repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/in.rs
yazi-scheduler/src/in.rs
use yazi_shared::Id; use crate::{file::{FileInCopy, FileInCut, FileInDelete, FileInDownload, FileInHardlink, FileInLink, FileInTrash, FileInUpload}, hook::{HookInOutCopy, HookInOutCut, HookInOutDelete, HookInOutDownload, HookInOutTrash}, impl_from_in, plugin::PluginInEntry, prework::{PreworkInFetch, PreworkInLoad, PreworkInSize}, process::{ProcessInBg, ProcessInBlock, ProcessInOrphan}}; #[derive(Debug)] pub(crate) enum TaskIn { // File FileCopy(FileInCopy), FileCut(FileInCut), FileLink(FileInLink), FileHardlink(FileInHardlink), FileDelete(FileInDelete), FileTrash(FileInTrash), FileDownload(FileInDownload), FileUpload(FileInUpload), // Plugin PluginEntry(PluginInEntry), // Prework PreworkFetch(PreworkInFetch), PreworkLoad(PreworkInLoad), PreworkSize(PreworkInSize), // Process ProcessBlock(ProcessInBlock), ProcessOrphan(ProcessInOrphan), ProcessBg(ProcessInBg), // Hook HookCopy(HookInOutCopy), HookCut(HookInOutCut), HookDelete(HookInOutDelete), HookTrash(HookInOutTrash), HookDownload(HookInOutDownload), } impl_from_in! { // File FileCopy(FileInCopy), FileCut(FileInCut), FileLink(FileInLink), FileHardlink(FileInHardlink), FileDelete(FileInDelete), FileTrash(FileInTrash), FileDownload(FileInDownload), FileUpload(FileInUpload), // Plugin PluginEntry(PluginInEntry), // Prework PreworkFetch(PreworkInFetch), PreworkLoad(PreworkInLoad), PreworkSize(PreworkInSize), // Process ProcessBlock(ProcessInBlock), ProcessOrphan(ProcessInOrphan), ProcessBg(ProcessInBg), // Hook HookCopy(HookInOutCopy), HookCut(HookInOutCut), HookDelete(HookInOutDelete), HookTrash(HookInOutTrash), HookDownload(HookInOutDownload), } impl TaskIn { pub fn id(&self) -> Id { match self { // File Self::FileCopy(r#in) => r#in.id, Self::FileCut(r#in) => r#in.id, Self::FileLink(r#in) => r#in.id, Self::FileHardlink(r#in) => r#in.id, Self::FileDelete(r#in) => r#in.id, Self::FileTrash(r#in) => r#in.id, Self::FileDownload(r#in) => r#in.id, Self::FileUpload(r#in) => r#in.id, // Plugin Self::PluginEntry(r#in) => r#in.id, // Prework Self::PreworkFetch(r#in) => r#in.id, Self::PreworkLoad(r#in) => r#in.id, Self::PreworkSize(r#in) => r#in.id, // Process Self::ProcessBlock(r#in) => r#in.id, Self::ProcessOrphan(r#in) => r#in.id, Self::ProcessBg(r#in) => r#in.id, // Hook Self::HookCopy(r#in) => r#in.id, Self::HookCut(r#in) => r#in.id, Self::HookDelete(r#in) => r#in.id, Self::HookTrash(r#in) => r#in.id, Self::HookDownload(r#in) => r#in.id, } } pub fn is_hook(&self) -> bool { match self { // File Self::FileCopy(_) => false, Self::FileCut(_) => false, Self::FileLink(_) => false, Self::FileHardlink(_) => false, Self::FileDelete(_) => false, Self::FileTrash(_) => false, Self::FileDownload(_) => false, Self::FileUpload(_) => false, // Plugin Self::PluginEntry(_) => false, // Prework Self::PreworkFetch(_) => false, Self::PreworkLoad(_) => false, Self::PreworkSize(_) => false, // Process Self::ProcessBlock(_) => false, Self::ProcessOrphan(_) => false, Self::ProcessBg(_) => false, // Hook Self::HookCopy(_) => true, Self::HookCut(_) => true, Self::HookDelete(_) => true, Self::HookTrash(_) => true, Self::HookDownload(_) => true, } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/progress.rs
yazi-scheduler/src/progress.rs
use serde::Serialize; use yazi_parser::app::TaskSummary; use crate::{file::{FileProgCopy, FileProgCut, FileProgDelete, FileProgDownload, FileProgHardlink, FileProgLink, FileProgTrash, FileProgUpload}, impl_from_prog, plugin::PluginProgEntry, prework::{PreworkProgFetch, PreworkProgLoad, PreworkProgSize}, process::{ProcessProgBg, ProcessProgBlock, ProcessProgOrphan}}; #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] #[serde(tag = "kind")] pub enum TaskProg { // File FileCopy(FileProgCopy), FileCut(FileProgCut), FileLink(FileProgLink), FileHardlink(FileProgHardlink), FileDelete(FileProgDelete), FileTrash(FileProgTrash), FileDownload(FileProgDownload), FileUpload(FileProgUpload), // Plugin PluginEntry(PluginProgEntry), // Prework PreworkFetch(PreworkProgFetch), PreworkLoad(PreworkProgLoad), PreworkSize(PreworkProgSize), // Process ProcessBlock(ProcessProgBlock), ProcessOrphan(ProcessProgOrphan), ProcessBg(ProcessProgBg), } impl_from_prog! { // File FileCopy(FileProgCopy), FileCut(FileProgCut), FileLink(FileProgLink), FileHardlink(FileProgHardlink), FileDelete(FileProgDelete), FileTrash(FileProgTrash), FileDownload(FileProgDownload), FileUpload(FileProgUpload), // Plugin PluginEntry(PluginProgEntry), // Prework PreworkFetch(PreworkProgFetch), PreworkLoad(PreworkProgLoad), PreworkSize(PreworkProgSize), // Process ProcessBlock(ProcessProgBlock), ProcessOrphan(ProcessProgOrphan), ProcessBg(ProcessProgBg), } impl From<TaskProg> for TaskSummary { fn from(value: TaskProg) -> Self { match value { // File TaskProg::FileCopy(p) => p.into(), TaskProg::FileCut(p) => p.into(), TaskProg::FileLink(p) => p.into(), TaskProg::FileHardlink(p) => p.into(), TaskProg::FileDelete(p) => p.into(), TaskProg::FileTrash(p) => p.into(), TaskProg::FileDownload(p) => p.into(), TaskProg::FileUpload(p) => p.into(), // Plugin TaskProg::PluginEntry(p) => p.into(), // Prework TaskProg::PreworkFetch(p) => p.into(), TaskProg::PreworkLoad(p) => p.into(), TaskProg::PreworkSize(p) => p.into(), // Process TaskProg::ProcessBlock(p) => p.into(), TaskProg::ProcessOrphan(p) => p.into(), TaskProg::ProcessBg(p) => p.into(), } } } impl TaskProg { pub fn cooked(self) -> bool { match self { // File Self::FileCopy(p) => p.cooked(), Self::FileCut(p) => p.cooked(), Self::FileLink(p) => p.cooked(), Self::FileHardlink(p) => p.cooked(), Self::FileDelete(p) => p.cooked(), Self::FileTrash(p) => p.cooked(), Self::FileDownload(p) => p.cooked(), Self::FileUpload(p) => p.cooked(), // Plugin Self::PluginEntry(p) => p.cooked(), // Prework Self::PreworkFetch(p) => p.cooked(), Self::PreworkLoad(p) => p.cooked(), Self::PreworkSize(p) => p.cooked(), // Process Self::ProcessBlock(p) => p.cooked(), Self::ProcessOrphan(p) => p.cooked(), Self::ProcessBg(p) => p.cooked(), } } pub fn running(self) -> bool { match self { // File Self::FileCopy(p) => p.running(), Self::FileCut(p) => p.running(), Self::FileLink(p) => p.running(), Self::FileHardlink(p) => p.running(), Self::FileDelete(p) => p.running(), Self::FileTrash(p) => p.running(), Self::FileDownload(p) => p.running(), Self::FileUpload(p) => p.running(), // Plugin Self::PluginEntry(p) => p.running(), // Prework Self::PreworkFetch(p) => p.running(), Self::PreworkLoad(p) => p.running(), Self::PreworkSize(p) => p.running(), // Process Self::ProcessBlock(p) => p.running(), Self::ProcessOrphan(p) => p.running(), Self::ProcessBg(p) => p.running(), } } pub fn success(self) -> bool { match self { // File Self::FileCopy(p) => p.success(), Self::FileCut(p) => p.success(), Self::FileLink(p) => p.success(), Self::FileHardlink(p) => p.success(), Self::FileDelete(p) => p.success(), Self::FileTrash(p) => p.success(), Self::FileDownload(p) => p.success(), Self::FileUpload(p) => p.success(), // Plugin Self::PluginEntry(p) => p.success(), // Prework Self::PreworkFetch(p) => p.success(), Self::PreworkLoad(p) => p.success(), Self::PreworkSize(p) => p.success(), // Process Self::ProcessBlock(p) => p.success(), Self::ProcessOrphan(p) => p.success(), Self::ProcessBg(p) => p.success(), } } pub fn failed(self) -> bool { match self { // File Self::FileCopy(p) => p.failed(), Self::FileCut(p) => p.failed(), Self::FileLink(p) => p.failed(), Self::FileHardlink(p) => p.failed(), Self::FileDelete(p) => p.failed(), Self::FileTrash(p) => p.failed(), Self::FileDownload(p) => p.failed(), Self::FileUpload(p) => p.failed(), // Plugin Self::PluginEntry(p) => p.failed(), // Prework Self::PreworkFetch(p) => p.failed(), Self::PreworkLoad(p) => p.failed(), Self::PreworkSize(p) => p.failed(), // Process Self::ProcessBlock(p) => p.failed(), Self::ProcessOrphan(p) => p.failed(), Self::ProcessBg(p) => p.failed(), } } pub fn cleaned(self) -> Option<bool> { match self { // File Self::FileCopy(p) => p.cleaned(), Self::FileCut(p) => p.cleaned(), Self::FileLink(p) => p.cleaned(), Self::FileHardlink(p) => p.cleaned(), Self::FileDelete(p) => p.cleaned(), Self::FileTrash(p) => p.cleaned(), Self::FileDownload(p) => p.cleaned(), Self::FileUpload(p) => p.cleaned(), // Plugin Self::PluginEntry(p) => p.cleaned(), // Prework Self::PreworkFetch(p) => p.cleaned(), Self::PreworkLoad(p) => p.cleaned(), Self::PreworkSize(p) => p.cleaned(), // Process Self::ProcessBlock(p) => p.cleaned(), Self::ProcessOrphan(p) => p.cleaned(), Self::ProcessBg(p) => p.cleaned(), } } pub fn percent(self) -> Option<f32> { match self { // File Self::FileCopy(p) => p.percent(), Self::FileCut(p) => p.percent(), Self::FileLink(p) => p.percent(), Self::FileHardlink(p) => p.percent(), Self::FileDelete(p) => p.percent(), Self::FileTrash(p) => p.percent(), Self::FileDownload(p) => p.percent(), Self::FileUpload(p) => p.percent(), // Plugin Self::PluginEntry(p) => p.percent(), // Prework Self::PreworkFetch(p) => p.percent(), Self::PreworkLoad(p) => p.percent(), Self::PreworkSize(p) => p.percent(), // Process Self::ProcessBlock(p) => p.percent(), Self::ProcessOrphan(p) => p.percent(), Self::ProcessBg(p) => p.percent(), } } pub(crate) fn is_user(self) -> bool { match self { // File Self::FileCopy(_) => true, Self::FileCut(_) => true, Self::FileLink(_) => true, Self::FileHardlink(_) => true, Self::FileDelete(_) => true, Self::FileTrash(_) => true, Self::FileDownload(_) => true, Self::FileUpload(_) => true, // Plugin Self::PluginEntry(_) => true, // Prework Self::PreworkFetch(_) => false, Self::PreworkLoad(_) => false, Self::PreworkSize(_) => false, // Process Self::ProcessBlock(_) => true, Self::ProcessOrphan(_) => true, Self::ProcessBg(_) => true, } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/out.rs
yazi-scheduler/src/out.rs
use crate::{Task, file::{FileOutCopy, FileOutCopyDo, FileOutCut, FileOutCutDo, FileOutDelete, FileOutDeleteDo, FileOutDownload, FileOutDownloadDo, FileOutHardlink, FileOutHardlinkDo, FileOutLink, FileOutTrash, FileOutUpload, FileOutUploadDo}, hook::{HookInOutCopy, HookInOutCut, HookInOutDelete, HookInOutDownload, HookInOutTrash}, impl_from_out, plugin::PluginOutEntry, prework::{PreworkOutFetch, PreworkOutLoad, PreworkOutSize}, process::{ProcessOutBg, ProcessOutBlock, ProcessOutOrphan}}; #[derive(Debug)] pub(super) enum TaskOut { // File FileCopy(FileOutCopy), FileCopyDo(FileOutCopyDo), FileCut(FileOutCut), FileCutDo(FileOutCutDo), FileLink(FileOutLink), FileHardlink(FileOutHardlink), FileHardlinkDo(FileOutHardlinkDo), FileDelete(FileOutDelete), FileDeleteDo(FileOutDeleteDo), FileTrash(FileOutTrash), FileDownload(FileOutDownload), FileDownloadDo(FileOutDownloadDo), FileUpload(FileOutUpload), FileUploadDo(FileOutUploadDo), // Plugin PluginEntry(PluginOutEntry), // Prework PreworkFetch(PreworkOutFetch), PreworkLoad(PreworkOutLoad), PreworkSize(PreworkOutSize), // Process ProcessBlock(ProcessOutBlock), ProcessOrphan(ProcessOutOrphan), ProcessBg(ProcessOutBg), // Hook HookCopy(HookInOutCopy), HookCut(HookInOutCut), HookDelete(HookInOutDelete), HookTrash(HookInOutTrash), HookDownload(HookInOutDownload), } impl_from_out! { // File FileCopy(FileOutCopy), FileCopyDo(FileOutCopyDo), FileCut(FileOutCut), FileCutDo(FileOutCutDo), FileLink(FileOutLink), FileHardlink(FileOutHardlink), FileHardlinkDo(FileOutHardlinkDo), FileDelete(FileOutDelete), FileDeleteDo(FileOutDeleteDo), FileTrash(FileOutTrash), FileDownload(FileOutDownload), FileDownloadDo(FileOutDownloadDo), FileUpload(FileOutUpload), FileUploadDo(FileOutUploadDo), // Plugin PluginEntry(PluginOutEntry), // Prework PreworkFetch(PreworkOutFetch), PreworkLoad(PreworkOutLoad), PreworkSize(PreworkOutSize), // Process ProcessBlock(ProcessOutBlock), ProcessOrphan(ProcessOutOrphan), ProcessBg(ProcessOutBg), // Hook HookCopy(HookInOutCopy), HookCut(HookInOutCut), HookDelete(HookInOutDelete), HookTrash(HookInOutTrash), HookDownload(HookInOutDownload), } impl TaskOut { pub(crate) fn reduce(self, task: &mut Task) { match self { // File Self::FileCopy(out) => out.reduce(task), Self::FileCopyDo(out) => out.reduce(task), Self::FileCut(out) => out.reduce(task), Self::FileCutDo(out) => out.reduce(task), Self::FileLink(out) => out.reduce(task), Self::FileHardlink(out) => out.reduce(task), Self::FileHardlinkDo(out) => out.reduce(task), Self::FileDelete(out) => out.reduce(task), Self::FileDeleteDo(out) => out.reduce(task), Self::FileTrash(out) => out.reduce(task), Self::FileDownload(out) => out.reduce(task), Self::FileDownloadDo(out) => out.reduce(task), Self::FileUpload(out) => out.reduce(task), Self::FileUploadDo(out) => out.reduce(task), // Plugin Self::PluginEntry(out) => out.reduce(task), // Prework Self::PreworkFetch(out) => out.reduce(task), Self::PreworkLoad(out) => out.reduce(task), Self::PreworkSize(out) => out.reduce(task), // Process Self::ProcessBlock(out) => out.reduce(task), Self::ProcessOrphan(out) => out.reduce(task), Self::ProcessBg(out) => out.reduce(task), // Hook Self::HookCopy(out) => out.reduce(task), Self::HookCut(out) => out.reduce(task), Self::HookDelete(out) => out.reduce(task), Self::HookTrash(out) => out.reduce(task), Self::HookDownload(out) => out.reduce(task), } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/macros.rs
yazi-scheduler/src/macros.rs
#[macro_export] macro_rules! ctx { ($task:ident, $result:expr) => {{ use anyhow::Context; $result.with_context(|| format!("Failed to work on {:?}", $task)) }}; ($task:ident, $result:expr, $($args:tt)*) => {{ use anyhow::Context; $result.with_context(|| format!("Failed to work on {:?}: {}", $task, format_args!($($args)*))) }}; } #[macro_export] macro_rules! ok_or_not_found { ($task:ident, $result:expr, $not_found:expr) => { match $result { Ok(v) => v, Err(e) if e.kind() == std::io::ErrorKind::NotFound => $not_found, Err(e) => $crate::ctx!($task, Err(e))?, } }; ($task:ident, $result:expr) => { ok_or_not_found!($task, $result, Default::default()) }; } #[macro_export] macro_rules! progress_or_break { ($rx:ident, $done:expr) => { tokio::select! { r = $rx.recv() => { match r { Some(prog) => prog, None => break, } }, false = $done.future() => break, } }; } #[macro_export] macro_rules! impl_from_in { ($($variant:ident($type:ty)),* $(,)?) => { $( impl From<$type> for $crate::TaskIn { fn from(value: $type) -> Self { Self::$variant(value) } } )* }; } #[macro_export] macro_rules! impl_from_out { ($($variant:ident($type:ty)),* $(,)?) => { $( impl From<$type> for $crate::TaskOut { fn from(value: $type) -> Self { Self::$variant(value) } } )* }; } #[macro_export] macro_rules! impl_from_prog { ($($variant:ident($type:ty)),* $(,)?) => { $( impl From<$type> for $crate::TaskProg { fn from(value: $type) -> Self { Self::$variant(value) } } )* }; }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/task.rs
yazi-scheduler/src/task.rs
use tokio::sync::mpsc; use yazi_shared::{CompletionToken, Id}; use crate::{TaskIn, TaskProg}; #[derive(Debug)] pub struct Task { pub id: Id, pub name: String, pub(crate) prog: TaskProg, pub(crate) hook: Option<TaskIn>, pub done: CompletionToken, pub logs: String, pub logger: Option<mpsc::UnboundedSender<String>>, } impl Task { pub(super) fn new<T>(id: Id, name: String) -> Self where T: Into<TaskProg> + Default, { Self { id, name, prog: T::default().into(), hook: None, done: Default::default(), logs: Default::default(), logger: Default::default(), } } pub(crate) fn log(&mut self, line: String) { self.logs.push_str(&line); self.logs.push('\n'); if let Some(logger) = &self.logger { logger.send(line).ok(); } } pub(super) fn set_hook(&mut self, hook: impl Into<TaskIn>) { self.hook = Some(hook.into()); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/snap.rs
yazi-scheduler/src/snap.rs
use serde::Serialize; use crate::{Task, TaskProg}; #[derive(Debug, PartialEq, Eq, Serialize)] pub struct TaskSnap { pub name: String, pub prog: TaskProg, } impl From<&Task> for TaskSnap { fn from(task: &Task) -> Self { Self { name: task.name.clone(), prog: task.prog } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/scheduler.rs
yazi-scheduler/src/scheduler.rs
use std::{sync::Arc, time::Duration}; use parking_lot::Mutex; use tokio::{select, sync::mpsc::{self, UnboundedReceiver}, task::JoinHandle}; use yazi_config::{YAZI, plugin::{Fetcher, Preloader}}; use yazi_parser::{app::PluginOpt, tasks::ProcessOpenOpt}; use yazi_shared::{CompletionToken, Id, Throttle, url::{UrlBuf, UrlLike}}; use super::{Ongoing, TaskOp}; use crate::{HIGH, LOW, NORMAL, Runner, TaskIn, TaskOps, file::{File, FileInCopy, FileInCut, FileInDelete, FileInDownload, FileInHardlink, FileInLink, FileInTrash, FileInUpload, FileOutCopy, FileOutCut, FileOutDownload, FileOutHardlink, FileOutUpload, FileProgCopy, FileProgCut, FileProgDelete, FileProgDownload, FileProgHardlink, FileProgLink, FileProgTrash, FileProgUpload}, hook::{Hook, HookInOutDelete, HookInOutDownload, HookInOutTrash}, plugin::{Plugin, PluginInEntry, PluginProgEntry}, prework::{Prework, PreworkInFetch, PreworkInLoad, PreworkInSize, PreworkProgFetch, PreworkProgLoad, PreworkProgSize}, process::{Process, ProcessInBg, ProcessInBlock, ProcessInOrphan, ProcessProgBg, ProcessProgBlock, ProcessProgOrphan}}; pub struct Scheduler { ops: TaskOps, pub runner: Runner, micro: async_priority_channel::Sender<TaskIn, u8>, handles: Vec<JoinHandle<()>>, pub ongoing: Arc<Mutex<Ongoing>>, } impl Scheduler { pub fn serve() -> Self { let (op_tx, op_rx) = mpsc::unbounded_channel(); let (micro_tx, micro_rx) = async_priority_channel::unbounded(); let (macro_tx, macro_rx) = async_priority_channel::unbounded(); let ongoing = Arc::new(Mutex::new(Ongoing::default())); let runner = Runner { file: Arc::new(File::new(&op_tx, &macro_tx)), plugin: Arc::new(Plugin::new(&op_tx, &macro_tx)), prework: Arc::new(Prework::new(&op_tx, &macro_tx)), process: Arc::new(Process::new(&op_tx)), hook: Arc::new(Hook::new(&op_tx, &ongoing)), }; let mut scheduler = Self { ops: TaskOps(op_tx), runner, micro: micro_tx, handles: Vec::with_capacity( YAZI.tasks.micro_workers as usize + YAZI.tasks.macro_workers as usize + 1, ), ongoing, }; for _ in 0..YAZI.tasks.micro_workers { scheduler.handles.push(scheduler.schedule_micro(micro_rx.clone())); } for _ in 0..YAZI.tasks.macro_workers { scheduler.handles.push(scheduler.schedule_macro(micro_rx.clone(), macro_rx.clone())); } scheduler.handle_ops(op_rx); scheduler } pub fn cancel(&self, id: Id) -> bool { if let Some(hook) = self.ongoing.lock().cancel(id) { self.micro.try_send(hook, HIGH).ok(); return false; } true } pub fn shutdown(&self) { for handle in &self.handles { handle.abort(); } } pub fn file_cut(&self, from: UrlBuf, to: UrlBuf, force: bool) { let mut ongoing = self.ongoing.lock(); let task = ongoing.add::<FileProgCut>(format!("Cut {} to {}", from.display(), to.display())); if to.try_starts_with(&from).unwrap_or(false) && !to.covariant(&from) { return self .ops .out(task.id, FileOutCut::Fail("Cannot cut directory into itself".to_owned())); } let follow = !from.scheme().covariant(to.scheme()); self.queue( FileInCut { id: task.id, from, to, force, cha: None, follow, retry: 0, drop: None, done: task.done.clone(), }, LOW, ); } pub fn file_copy(&self, from: UrlBuf, to: UrlBuf, force: bool, follow: bool) { let mut ongoing = self.ongoing.lock(); let task = ongoing.add::<FileProgCopy>(format!("Copy {} to {}", from.display(), to.display())); if to.try_starts_with(&from).unwrap_or(false) && !to.covariant(&from) { return self .ops .out(task.id, FileOutCopy::Fail("Cannot copy directory into itself".to_owned())); } let follow = follow || !from.scheme().covariant(to.scheme()); self.queue( FileInCopy { id: task.id, from, to, force, cha: None, follow, retry: 0, done: task.done.clone(), }, LOW, ); } pub fn file_link(&self, from: UrlBuf, to: UrlBuf, relative: bool, force: bool) { let mut ongoing = self.ongoing.lock(); let task = ongoing.add::<FileProgLink>(format!("Link {} to {}", from.display(), to.display())); self.queue( FileInLink { id: task.id, from, to, force, cha: None, resolve: false, relative, delete: false, }, LOW, ); } pub fn file_hardlink(&self, from: UrlBuf, to: UrlBuf, force: bool, follow: bool) { let mut ongoing = self.ongoing.lock(); let task = ongoing.add::<FileProgHardlink>(format!("Hardlink {} to {}", from.display(), to.display())); if !from.scheme().covariant(to.scheme()) { return self .ops .out(task.id, FileOutHardlink::Fail("Cannot hardlink cross filesystem".to_owned())); } if to.try_starts_with(&from).unwrap_or(false) && !to.covariant(&from) { return self .ops .out(task.id, FileOutHardlink::Fail("Cannot hardlink directory into itself".to_owned())); } self.queue(FileInHardlink { id: task.id, from, to, force, cha: None, follow }, LOW); } pub fn file_delete(&self, target: UrlBuf) { let mut ongoing = self.ongoing.lock(); let task = ongoing.add::<FileProgDelete>(format!("Delete {}", target.display())); task.set_hook(HookInOutDelete { id: task.id, target: target.clone() }); self.queue(FileInDelete { id: task.id, target, cha: None }, LOW); } pub fn file_trash(&self, target: UrlBuf) { let mut ongoing = self.ongoing.lock(); let task = ongoing.add::<FileProgTrash>(format!("Trash {}", target.display())); task.set_hook(HookInOutTrash { id: task.id, target: target.clone() }); self.queue(FileInTrash { id: task.id, target }, LOW); } pub fn file_download(&self, url: UrlBuf) -> CompletionToken { let mut ongoing = self.ongoing.lock(); let task = ongoing.add::<FileProgDownload>(format!("Download {}", url.display())); task.set_hook(HookInOutDownload { id: task.id }); if url.kind().is_remote() { self.queue( FileInDownload { id: task.id, url, cha: None, retry: 0, done: task.done.clone() }, LOW, ); } else { self.ops.out(task.id, FileOutDownload::Fail("Cannot download non-remote file".to_owned())); } task.done.clone() } pub fn file_upload(&self, url: UrlBuf) { let mut ongoing = self.ongoing.lock(); let task = ongoing.add::<FileProgUpload>(format!("Upload {}", url.display())); if !url.kind().is_remote() { return self .ops .out(task.id, FileOutUpload::Fail("Cannot upload non-remote file".to_owned())); }; self.queue( FileInUpload { id: task.id, url, cha: None, cache: None, done: task.done.clone() }, LOW, ); } pub fn plugin_entry(&self, opt: PluginOpt) { let mut ongoing = self.ongoing.lock(); let task = ongoing.add::<PluginProgEntry>(format!("Run micro plugin `{}`", opt.id)); self.queue(PluginInEntry { id: task.id, opt }, NORMAL); } pub fn fetch_paged( &self, fetcher: &'static Fetcher, targets: Vec<yazi_fs::File>, ) -> CompletionToken { let mut ongoing = self.ongoing.lock(); let task = ongoing.add::<PreworkProgFetch>(format!( "Run fetcher `{}` with {} target(s)", fetcher.run.name, targets.len() )); self.queue(PreworkInFetch { id: task.id, plugin: fetcher, targets }, NORMAL); task.done.clone() } pub async fn fetch_mimetype(&self, targets: Vec<yazi_fs::File>) -> bool { let mut wg = vec![]; for (fetcher, targets) in YAZI.plugin.mime_fetchers(targets) { wg.push(self.fetch_paged(fetcher, targets)); } for done in wg { if !done.future().await { return false; // Canceled } } true } pub fn preload_paged(&self, preloader: &'static Preloader, target: &yazi_fs::File) { let mut ongoing = self.ongoing.lock(); let task = ongoing.add::<PreworkProgLoad>(format!("Run preloader `{}`", preloader.run.name)); let target = target.clone(); self.queue(PreworkInLoad { id: task.id, plugin: preloader, target }, NORMAL); } pub fn prework_size(&self, targets: Vec<&UrlBuf>) { let throttle = Arc::new(Throttle::new(targets.len(), Duration::from_millis(300))); let mut ongoing = self.ongoing.lock(); for target in targets { let task = ongoing.add::<PreworkProgSize>(format!("Calculate the size of {}", target.display())); let target = target.clone(); let throttle = throttle.clone(); self.queue(PreworkInSize { id: task.id, target, throttle }, NORMAL); } } pub fn process_open(&self, opt: ProcessOpenOpt) { let name = { let args = opt.args.iter().map(|a| a.display().to_string()).collect::<Vec<_>>().join(" "); if args.is_empty() { format!("Run {:?}", opt.cmd) } else { format!("Run {:?} with `{args}`", opt.cmd) } }; let mut ongoing = self.ongoing.lock(); let task = if opt.block { ongoing.add::<ProcessProgBlock>(name) } else if opt.orphan { ongoing.add::<ProcessProgOrphan>(name) } else { ongoing.add::<ProcessProgBg>(name) }; if let Some(done) = opt.done { task.done = done; } if opt.block { self .queue(ProcessInBlock { id: task.id, cwd: opt.cwd, cmd: opt.cmd, args: opt.args }, NORMAL); } else if opt.orphan { self .queue(ProcessInOrphan { id: task.id, cwd: opt.cwd, cmd: opt.cmd, args: opt.args }, NORMAL); } else { self.queue( ProcessInBg { id: task.id, cwd: opt.cwd, cmd: opt.cmd, args: opt.args, done: task.done.clone(), }, NORMAL, ); }; } fn schedule_micro(&self, rx: async_priority_channel::Receiver<TaskIn, u8>) -> JoinHandle<()> { let ops = self.ops.clone(); let runner = self.runner.clone(); let ongoing = self.ongoing.clone(); tokio::spawn(async move { loop { if let Ok((r#in, _)) = rx.recv().await { let id = r#in.id(); let Some(token) = ongoing.lock().get_token(id) else { continue; }; let result = if r#in.is_hook() { runner.micro(r#in).await } else { select! { r = runner.micro(r#in) => r, false = token.future() => Ok(()) } }; if let Err(out) = result { ops.out(id, out); } } } }) } fn schedule_macro( &self, micro: async_priority_channel::Receiver<TaskIn, u8>, r#macro: async_priority_channel::Receiver<TaskIn, u8>, ) -> JoinHandle<()> { let ops = self.ops.clone(); let runner = self.runner.clone(); let ongoing = self.ongoing.clone(); tokio::spawn(async move { loop { let (r#in, micro) = select! { Ok((r#in, _)) = micro.recv() => (r#in, true), Ok((r#in, _)) = r#macro.recv() => (r#in, false), }; let id = r#in.id(); let Some(token) = ongoing.lock().get_token(id) else { continue; }; let result = if r#in.is_hook() { if micro { runner.micro(r#in).await } else { runner.r#macro(r#in).await } } else if micro { select! { r = runner.micro(r#in) => r, false = token.future() => Ok(()), } } else { select! { r = runner.r#macro(r#in) => r, false = token.future() => Ok(()), } }; if let Err(out) = result { ops.out(id, out); } } }) } fn handle_ops(&self, mut rx: UnboundedReceiver<TaskOp>) -> JoinHandle<()> { let micro = self.micro.clone(); let ongoing = self.ongoing.clone(); tokio::spawn(async move { while let Some(op) = rx.recv().await { let mut ongoing = ongoing.lock(); let Some(task) = ongoing.get_mut(op.id) else { continue }; op.out.reduce(task); if !task.prog.cooked() && task.done.completed() != Some(false) { continue; // Not cooked yet, also not canceled } else if task.prog.cleaned() == Some(false) { continue; // Failed to clean up } else if let Some(hook) = task.hook.take() { micro.try_send(hook, LOW).ok(); } else { ongoing.fulfill(op.id); } } }) } #[inline] fn queue(&self, r#in: impl Into<TaskIn>, priority: u8) { _ = self.micro.try_send(r#in.into(), priority); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/process/process.rs
yazi-scheduler/src/process/process.rs
use anyhow::{Result, anyhow}; use tokio::{io::{AsyncBufReadExt, BufReader}, select, sync::mpsc}; use yazi_binding::Permit; use yazi_proxy::{AppProxy, HIDER}; use super::{ProcessInBg, ProcessInBlock, ProcessInOrphan, ShellOpt}; use crate::{TaskOp, TaskOps, process::{ProcessOutBg, ProcessOutBlock, ProcessOutOrphan}}; pub(crate) struct Process { ops: TaskOps, } impl Process { pub(crate) fn new(ops: &mpsc::UnboundedSender<TaskOp>) -> Self { Self { ops: ops.into() } } pub(crate) async fn block(&self, task: ProcessInBlock) -> Result<(), ProcessOutBlock> { let _permit = Permit::new(HIDER.acquire().await.unwrap(), AppProxy::resume()); AppProxy::stop().await; let (id, cmd) = (task.id, task.cmd.clone()); let result = super::shell(task.into()).await; if let Err(e) = result { AppProxy::notify_warn(cmd.to_string_lossy(), format!("Failed to start process: {e}")); return Ok(self.ops.out(id, ProcessOutBlock::Succ)); } let status = result.unwrap().wait().await?; if !status.success() { let content = match status.code() { Some(130) => return Ok(self.ops.out(id, ProcessOutBlock::Succ)), // Ctrl-C pressed by user Some(code) => format!("Process exited with status code: {code}"), None => "Process terminated by signal".to_string(), }; AppProxy::notify_warn(cmd.to_string_lossy(), content); } Ok(self.ops.out(id, ProcessOutBlock::Succ)) } pub(crate) async fn orphan(&self, task: ProcessInOrphan) -> Result<(), ProcessOutOrphan> { let id = task.id; super::shell(task.into()).await?; Ok(self.ops.out(id, ProcessOutOrphan::Succ)) } pub(crate) async fn bg(&self, task: ProcessInBg) -> Result<(), ProcessOutBg> { let mut child = super::shell(ShellOpt { cwd: task.cwd, cmd: task.cmd, args: task.args, piped: true, orphan: false, }) .await?; let done = task.done; let mut stdout = BufReader::new(child.stdout.take().unwrap()).lines(); let mut stderr = BufReader::new(child.stderr.take().unwrap()).lines(); loop { select! { false = done.future() => { child.start_kill().ok(); break; } Ok(Some(line)) = stdout.next_line() => { self.ops.out(task.id, ProcessOutBg::Log(line)); } Ok(Some(line)) = stderr.next_line() => { self.ops.out(task.id, ProcessOutBg::Log(line)); } Ok(status) = child.wait() => { self.ops.out(task.id, ProcessOutBg::Log(match status.code() { Some(code) => format!("Exited with status code: {code}"), None => "Process terminated by signal".to_string(), })); if !status.success() { Err(anyhow!("Process failed"))?; } break; } } } Ok(self.ops.out(task.id, ProcessOutBg::Succ)) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/process/in.rs
yazi-scheduler/src/process/in.rs
use std::ffi::OsString; use yazi_shared::{CompletionToken, Id, url::UrlCow}; use super::ShellOpt; // --- Block #[derive(Debug)] pub(crate) struct ProcessInBlock { pub(crate) id: Id, pub(crate) cwd: UrlCow<'static>, pub(crate) cmd: OsString, pub(crate) args: Vec<UrlCow<'static>>, } 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(crate) struct ProcessInOrphan { pub(crate) id: Id, pub(crate) cwd: UrlCow<'static>, pub(crate) cmd: OsString, pub(crate) args: Vec<UrlCow<'static>>, } 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(crate) struct ProcessInBg { pub(crate) id: Id, pub(crate) cwd: UrlCow<'static>, pub(crate) cmd: OsString, pub(crate) args: Vec<UrlCow<'static>>, pub(crate) done: CompletionToken, } 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 } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/process/shell.rs
yazi-scheduler/src/process/shell.rs
use std::{ffi::OsString, process::Stdio}; use anyhow::Result; use tokio::process::{Child, Command}; use yazi_fs::Cwd; use yazi_shared::url::{AsUrl, UrlCow}; pub(crate) struct ShellOpt { pub(crate) cwd: UrlCow<'static>, pub(crate) cmd: OsString, pub(crate) args: Vec<UrlCow<'static>>, pub(crate) piped: bool, pub(crate) orphan: bool, } impl ShellOpt { #[inline] fn stdio(&self) -> Stdio { if self.orphan { Stdio::null() } else if self.piped { Stdio::piped() } else { Stdio::inherit() } } } pub(crate) async fn shell(opt: ShellOpt) -> Result<Child> { tokio::task::spawn_blocking(move || { let cwd = Cwd::ensure(opt.cwd.as_url()); #[cfg(unix)] return Ok(unsafe { use yazi_fs::FsUrl; use yazi_shared::url::AsUrl; Command::new("sh") .stdin(opt.stdio()) .stdout(opt.stdio()) .stderr(opt.stdio()) .arg("-c") .arg(opt.cmd) // TODO: remove .args(opt.args.iter().map(|u| u.as_url().unified_path_str())) .current_dir(cwd) .kill_on_drop(!opt.orphan) .pre_exec(move || { if (opt.piped || opt.orphan) && libc::setsid() < 0 { return Err(std::io::Error::last_os_error()); } Ok(()) }) .spawn()? }); #[cfg(windows)] return Ok( Command::new("cmd.exe") .stdin(opt.stdio()) .stdout(opt.stdio()) .stderr(opt.stdio()) .env("=", r#""^\n\n""#) .raw_arg(r#"/Q /S /D /V:OFF /E:ON /C ""#) .raw_arg(opt.cmd) .raw_arg(r#"""#) .current_dir(cwd) .kill_on_drop(!opt.orphan) .spawn()?, ); }) .await? }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/process/progress.rs
yazi-scheduler/src/process/progress.rs
use serde::Serialize; use yazi_parser::app::TaskSummary; // --- Block #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)] pub struct ProcessProgBlock { pub state: Option<bool>, } impl From<ProcessProgBlock> for TaskSummary { fn from(value: ProcessProgBlock) -> Self { Self { total: (value.state == Some(false)) as u32, success: 0, failed: (value.state == Some(false)) as u32, percent: value.percent().map(Into::into), } } } impl ProcessProgBlock { pub fn cooked(self) -> bool { self.state == Some(true) } pub fn running(self) -> bool { self.state.is_none() } pub fn success(self) -> bool { self.cooked() } pub fn failed(self) -> bool { self.state == Some(false) } pub fn cleaned(self) -> Option<bool> { None } pub fn percent(self) -> Option<f32> { None } } // --- Orphan #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)] pub struct ProcessProgOrphan { pub state: Option<bool>, } impl From<ProcessProgOrphan> for TaskSummary { fn from(value: ProcessProgOrphan) -> Self { Self { total: (value.state == Some(false)) as u32, success: 0, failed: (value.state == Some(false)) as u32, percent: value.percent().map(Into::into), } } } impl ProcessProgOrphan { pub fn cooked(self) -> bool { self.state == Some(true) } pub fn running(self) -> bool { self.state.is_none() } pub fn success(self) -> bool { self.cooked() } pub fn failed(self) -> bool { self.state == Some(false) } pub fn cleaned(self) -> Option<bool> { None } pub fn percent(self) -> Option<f32> { None } } // --- Bg #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)] pub struct ProcessProgBg { pub state: Option<bool>, } impl From<ProcessProgBg> for TaskSummary { fn from(value: ProcessProgBg) -> Self { Self { total: 1, success: (value.state == Some(true)) as u32, failed: (value.state == Some(false)) as u32, percent: value.percent().map(Into::into), } } } impl ProcessProgBg { pub fn cooked(self) -> bool { self.state == Some(true) } pub fn running(self) -> bool { self.state.is_none() } pub fn success(self) -> bool { self.cooked() } pub fn failed(self) -> bool { self.state == Some(false) } pub fn cleaned(self) -> Option<bool> { None } pub fn percent(self) -> Option<f32> { None } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/process/out.rs
yazi-scheduler/src/process/out.rs
use crate::{Task, TaskProg}; #[derive(Debug)] pub(crate) enum ProcessOutBlock { Succ, Fail(String), } impl From<std::io::Error> for ProcessOutBlock { fn from(value: std::io::Error) -> Self { Self::Fail(value.to_string()) } } impl ProcessOutBlock { pub(crate) fn reduce(self, task: &mut Task) { let TaskProg::ProcessBlock(prog) = &mut task.prog else { return }; match self { Self::Succ => { prog.state = Some(true); } Self::Fail(reason) => { prog.state = Some(false); task.log(reason); } } } } // --- Orphan #[derive(Debug)] pub(crate) enum ProcessOutOrphan { Succ, Fail(String), } impl From<anyhow::Error> for ProcessOutOrphan { fn from(value: anyhow::Error) -> Self { Self::Fail(value.to_string()) } } impl ProcessOutOrphan { pub(crate) fn reduce(self, task: &mut Task) { let TaskProg::ProcessOrphan(prog) = &mut task.prog else { return }; match self { Self::Succ => { prog.state = Some(true); } Self::Fail(reason) => { prog.state = Some(false); task.log(reason); } } } } // --- Bg #[derive(Debug)] pub(crate) enum ProcessOutBg { Log(String), Succ, Fail(String), } impl From<anyhow::Error> for ProcessOutBg { fn from(value: anyhow::Error) -> Self { Self::Fail(value.to_string()) } } impl ProcessOutBg { pub(crate) fn reduce(self, task: &mut Task) { let TaskProg::ProcessBg(prog) = &mut task.prog else { return }; match self { Self::Log(line) => { task.log(line); } Self::Succ => { prog.state = Some(true); } Self::Fail(reason) => { prog.state = Some(false); task.log(reason); } } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/process/mod.rs
yazi-scheduler/src/process/mod.rs
yazi_macro::mod_flat!(out process progress r#in shell);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/plugin/in.rs
yazi-scheduler/src/plugin/in.rs
use yazi_parser::app::PluginOpt; use yazi_shared::Id; #[derive(Debug)] pub(crate) struct PluginInEntry { pub(crate) id: Id, pub(crate) opt: PluginOpt, }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/plugin/progress.rs
yazi-scheduler/src/plugin/progress.rs
use serde::Serialize; use yazi_parser::app::TaskSummary; // --- Entry #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)] pub struct PluginProgEntry { pub state: Option<bool>, } impl From<PluginProgEntry> for TaskSummary { fn from(value: PluginProgEntry) -> Self { Self { total: 1, success: (value.state == Some(true)) as u32, failed: (value.state == Some(false)) as u32, percent: value.percent().map(Into::into), } } } impl PluginProgEntry { pub fn cooked(self) -> bool { self.state == Some(true) } pub fn running(self) -> bool { self.state.is_none() } pub fn success(self) -> bool { self.cooked() } pub fn failed(self) -> bool { self.state == Some(false) } pub fn cleaned(self) -> Option<bool> { None } pub fn percent(self) -> Option<f32> { None } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/plugin/out.rs
yazi-scheduler/src/plugin/out.rs
use crate::{Task, TaskProg}; // --- Entry #[derive(Debug)] pub(crate) enum PluginOutEntry { Succ, Fail(String), } impl From<mlua::Error> for PluginOutEntry { fn from(value: mlua::Error) -> Self { Self::Fail(value.to_string()) } } impl PluginOutEntry { pub(crate) fn reduce(self, task: &mut Task) { let TaskProg::PluginEntry(prog) = &mut task.prog else { return }; match self { Self::Succ => { prog.state = Some(true); } Self::Fail(reason) => { prog.state = Some(false); task.log(reason); } } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/plugin/mod.rs
yazi-scheduler/src/plugin/mod.rs
yazi_macro::mod_flat!(out plugin progress r#in);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/plugin/plugin.rs
yazi-scheduler/src/plugin/plugin.rs
use anyhow::Result; use tokio::sync::mpsc; use yazi_plugin::isolate; use super::PluginInEntry; use crate::{HIGH, TaskIn, TaskOp, TaskOps, plugin::PluginOutEntry}; pub(crate) struct Plugin { ops: TaskOps, r#macro: async_priority_channel::Sender<TaskIn, u8>, } impl Plugin { pub(crate) fn new( ops: &mpsc::UnboundedSender<TaskOp>, r#macro: &async_priority_channel::Sender<TaskIn, u8>, ) -> Self { Self { ops: ops.into(), r#macro: r#macro.clone() } } pub(crate) async fn entry(&self, task: PluginInEntry) -> Result<(), PluginOutEntry> { Ok(self.queue(task, HIGH)) } pub(crate) async fn entry_do(&self, task: PluginInEntry) -> Result<(), PluginOutEntry> { isolate::entry(task.opt).await?; Ok(self.ops.out(task.id, PluginOutEntry::Succ)) } } impl Plugin { #[inline] fn queue(&self, r#in: impl Into<TaskIn>, priority: u8) { _ = self.r#macro.try_send(r#in.into(), priority); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/prework/in.rs
yazi-scheduler/src/prework/in.rs
use std::sync::Arc; use yazi_config::plugin::{Fetcher, Preloader}; use yazi_shared::{Id, Throttle, url::UrlBuf}; #[derive(Debug)] pub(crate) struct PreworkInFetch { pub(crate) id: Id, pub(crate) plugin: &'static Fetcher, pub(crate) targets: Vec<yazi_fs::File>, } #[derive(Clone, Debug)] pub(crate) struct PreworkInLoad { pub(crate) id: Id, pub(crate) plugin: &'static Preloader, pub(crate) target: yazi_fs::File, } #[derive(Debug)] pub(crate) struct PreworkInSize { pub(crate) id: Id, pub(crate) target: UrlBuf, pub(crate) throttle: Arc<Throttle<(UrlBuf, u64)>>, }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/prework/prework.rs
yazi-scheduler/src/prework/prework.rs
use std::num::NonZeroUsize; use anyhow::Result; use hashbrown::{HashMap, HashSet}; use lru::LruCache; use parking_lot::{Mutex, RwLock}; use tokio::sync::mpsc; use tokio_util::sync::CancellationToken; use tracing::error; use yazi_config::Priority; use yazi_fs::{FilesOp, FsHash64}; use yazi_plugin::isolate; use yazi_shared::{event::CmdCow, url::{UrlBuf, UrlLike}}; use yazi_vfs::provider; use super::{PreworkInFetch, PreworkInLoad, PreworkInSize}; use crate::{HIGH, NORMAL, TaskIn, TaskOp, TaskOps, prework::{PreworkOutFetch, PreworkOutLoad, PreworkOutSize}}; pub struct Prework { ops: TaskOps, r#macro: async_priority_channel::Sender<TaskIn, u8>, pub loaded: Mutex<LruCache<u64, u32>>, pub loading: Mutex<LruCache<u64, CancellationToken>>, pub sizing: RwLock<HashSet<UrlBuf>>, } impl Prework { pub(crate) fn new( ops: &mpsc::UnboundedSender<TaskOp>, r#macro: &async_priority_channel::Sender<TaskIn, u8>, ) -> Self { Self { ops: ops.into(), r#macro: r#macro.clone(), loaded: Mutex::new(LruCache::new(NonZeroUsize::new(4096).unwrap())), loading: Mutex::new(LruCache::new(NonZeroUsize::new(256).unwrap())), sizing: Default::default(), } } pub(crate) async fn fetch(&self, task: PreworkInFetch) -> Result<(), PreworkOutFetch> { match task.plugin.prio { Priority::Low => Ok(self.queue(task, NORMAL)), Priority::Normal => Ok(self.queue(task, HIGH)), Priority::High => self.fetch_do(task).await, } } pub(crate) async fn fetch_do(&self, task: PreworkInFetch) -> Result<(), PreworkOutFetch> { let hashes: Vec<_> = task.targets.iter().map(|f| f.hash_u64()).collect(); let (state, err) = isolate::fetch(CmdCow::from(&task.plugin.run), task.targets).await?; let mut loaded = self.loaded.lock(); for (_, h) in hashes.into_iter().enumerate().filter(|&(i, _)| !state.get(i)) { loaded.get_mut(&h).map(|x| *x &= !(1 << task.plugin.idx)); } if let Some(e) = err { error!("Error when running fetcher `{}`:\n{e}", task.plugin.run.name); } Ok(self.ops.out(task.id, PreworkOutFetch::Succ)) } pub(crate) async fn load(&self, task: PreworkInLoad) -> Result<(), PreworkOutLoad> { match task.plugin.prio { Priority::Low => Ok(self.queue(task, NORMAL)), Priority::Normal => Ok(self.queue(task, HIGH)), Priority::High => self.load_do(task).await, } } pub(crate) async fn load_do(&self, task: PreworkInLoad) -> Result<(), PreworkOutLoad> { let ct = CancellationToken::new(); if let Some(ct) = self.loading.lock().put(task.target.url.hash_u64(), ct.clone()) { ct.cancel(); } let hash = task.target.hash_u64(); let (ok, err) = isolate::preload(&task.plugin.run, task.target, ct).await?; if !ok { self.loaded.lock().get_mut(&hash).map(|x| *x &= !(1 << task.plugin.idx)); } if let Some(e) = err { error!("Error when running preloader `{}`:\n{e}", task.plugin.run.name); } Ok(self.ops.out(task.id, PreworkOutLoad::Succ)) } pub(crate) async fn size(&self, task: PreworkInSize) -> Result<(), PreworkOutSize> { self.size_do(task).await } pub(crate) async fn size_do(&self, task: PreworkInSize) -> Result<(), PreworkOutSize> { let length = provider::calculate(&task.target).await.unwrap_or(0); task.throttle.done((task.target, length), |buf| { { let mut loading = self.sizing.write(); for (path, _) in &buf { loading.remove(path); } } let parent = buf[0].0.parent().unwrap(); FilesOp::Size( parent.into(), HashMap::from_iter(buf.into_iter().map(|(u, s)| (u.urn().into(), s))), ) .emit(); }); Ok(self.ops.out(task.id, PreworkOutSize::Done)) } } impl Prework { #[inline] fn queue(&self, r#in: impl Into<TaskIn>, priority: u8) { _ = self.r#macro.try_send(r#in.into(), priority); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/prework/progress.rs
yazi-scheduler/src/prework/progress.rs
use serde::Serialize; use yazi_parser::app::TaskSummary; // --- Fetch #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)] pub struct PreworkProgFetch { pub state: Option<bool>, } impl From<PreworkProgFetch> for TaskSummary { fn from(value: PreworkProgFetch) -> Self { Self { total: 1, success: (value.state == Some(true)) as u32, failed: (value.state == Some(false)) as u32, percent: value.percent().map(Into::into), } } } impl PreworkProgFetch { pub fn cooked(self) -> bool { self.state == Some(true) } pub fn running(self) -> bool { self.state.is_none() } pub fn success(self) -> bool { self.cooked() } pub fn failed(self) -> bool { self.state == Some(false) } pub fn cleaned(self) -> Option<bool> { None } pub fn percent(self) -> Option<f32> { None } } // --- Load #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)] pub struct PreworkProgLoad { pub state: Option<bool>, } impl From<PreworkProgLoad> for TaskSummary { fn from(value: PreworkProgLoad) -> Self { Self { total: 1, success: (value.state == Some(true)) as u32, failed: (value.state == Some(false)) as u32, percent: value.percent().map(Into::into), } } } impl PreworkProgLoad { pub fn cooked(self) -> bool { self.state == Some(true) } pub fn running(self) -> bool { self.state.is_none() } pub fn success(self) -> bool { self.cooked() } pub fn failed(self) -> bool { self.state == Some(false) } pub fn cleaned(self) -> Option<bool> { None } pub fn percent(self) -> Option<f32> { None } } // --- Size #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)] pub struct PreworkProgSize { pub done: bool, } impl From<PreworkProgSize> for TaskSummary { fn from(value: PreworkProgSize) -> Self { Self { total: 1, success: value.done as u32, failed: 0, percent: value.percent().map(Into::into), } } } impl PreworkProgSize { pub fn cooked(self) -> bool { self.done } pub fn running(self) -> bool { !self.done } pub fn success(self) -> bool { self.cooked() } pub fn failed(self) -> bool { false } pub fn cleaned(self) -> Option<bool> { None } pub fn percent(self) -> Option<f32> { None } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/prework/out.rs
yazi-scheduler/src/prework/out.rs
use crate::{Task, TaskProg}; // --- Fetch #[derive(Debug)] pub(crate) enum PreworkOutFetch { Succ, Fail(String), } impl From<mlua::Error> for PreworkOutFetch { fn from(value: mlua::Error) -> Self { Self::Fail(value.to_string()) } } impl PreworkOutFetch { pub(crate) fn reduce(self, task: &mut Task) { let TaskProg::PreworkFetch(prog) = &mut task.prog else { return }; match self { Self::Succ => { prog.state = Some(true); } Self::Fail(reason) => { prog.state = Some(false); task.log(reason); } } } } // --- Load #[derive(Debug)] pub(crate) enum PreworkOutLoad { Succ, Fail(String), } impl From<mlua::Error> for PreworkOutLoad { fn from(value: mlua::Error) -> Self { Self::Fail(value.to_string()) } } impl PreworkOutLoad { pub(crate) fn reduce(self, task: &mut Task) { let TaskProg::PreworkLoad(prog) = &mut task.prog else { return }; match self { Self::Succ => { prog.state = Some(true); } Self::Fail(reason) => { prog.state = Some(false); task.log(reason); } } } } // --- Size #[derive(Debug)] pub(crate) enum PreworkOutSize { Done, } impl PreworkOutSize { pub(crate) fn reduce(self, task: &mut Task) { let TaskProg::PreworkSize(prog) = &mut task.prog else { return }; match self { Self::Done => { prog.done = true; } } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/prework/mod.rs
yazi-scheduler/src/prework/mod.rs
yazi_macro::mod_flat!(out prework progress r#in);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/file/in.rs
yazi-scheduler/src/file/in.rs
use std::{mem, path::PathBuf}; use tokio::sync::mpsc; use yazi_fs::cha::Cha; use yazi_shared::{CompletionToken, Id, url::UrlBuf}; // --- Copy #[derive(Clone, Debug)] pub(crate) struct FileInCopy { pub(crate) id: Id, pub(crate) from: UrlBuf, pub(crate) to: UrlBuf, pub(crate) force: bool, pub(crate) cha: Option<Cha>, pub(crate) follow: bool, pub(crate) retry: u8, pub(crate) done: CompletionToken, } impl FileInCopy { pub(super) fn into_link(self) -> FileInLink { FileInLink { id: self.id, from: self.from, to: self.to, force: true, cha: self.cha, resolve: true, relative: false, delete: false, } } } // --- Cut #[derive(Clone, Debug)] pub(crate) struct FileInCut { pub(crate) id: Id, pub(crate) from: UrlBuf, pub(crate) to: UrlBuf, pub(crate) force: bool, pub(crate) cha: Option<Cha>, pub(crate) follow: bool, pub(crate) retry: u8, pub(crate) done: CompletionToken, pub(crate) drop: Option<mpsc::Sender<()>>, } impl Drop for FileInCut { fn drop(&mut self) { _ = self.drop.take(); } } impl FileInCut { pub(super) fn into_link(mut self) -> FileInLink { FileInLink { id: self.id, from: mem::take(&mut self.from), to: mem::take(&mut self.to), force: true, cha: self.cha, resolve: true, relative: false, delete: true, } } pub(super) fn with_drop(mut self, drop: &mpsc::Sender<()>) -> Self { self.drop = Some(drop.clone()); self } } // --- Link #[derive(Clone, Debug)] pub(crate) struct FileInLink { pub(crate) id: Id, pub(crate) from: UrlBuf, pub(crate) to: UrlBuf, pub(crate) force: bool, pub(crate) cha: Option<Cha>, pub(crate) resolve: bool, pub(crate) relative: bool, pub(crate) delete: bool, } // --- Hardlink #[derive(Clone, Debug)] pub(crate) struct FileInHardlink { pub(crate) id: Id, pub(crate) from: UrlBuf, pub(crate) to: UrlBuf, pub(crate) force: bool, pub(crate) cha: Option<Cha>, pub(crate) follow: bool, } // --- Delete #[derive(Clone, Debug)] pub(crate) struct FileInDelete { pub(crate) id: Id, pub(crate) target: UrlBuf, pub(crate) cha: Option<Cha>, } // --- Trash #[derive(Clone, Debug)] pub(crate) struct FileInTrash { pub(crate) id: Id, pub(crate) target: UrlBuf, } // --- Download #[derive(Clone, Debug)] pub(crate) struct FileInDownload { pub(crate) id: Id, pub(crate) url: UrlBuf, pub(crate) cha: Option<Cha>, pub(crate) retry: u8, pub(crate) done: CompletionToken, } // --- Upload #[derive(Clone, Debug)] pub(crate) struct FileInUpload { pub(crate) id: Id, pub(crate) url: UrlBuf, pub(crate) cha: Option<Cha>, pub(crate) cache: Option<PathBuf>, pub(crate) done: CompletionToken, }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/file/file.rs
yazi-scheduler/src/file/file.rs
use std::mem; use anyhow::{Context, Result, anyhow}; use tokio::{io::{self, ErrorKind::NotFound}, sync::mpsc}; use tracing::warn; use yazi_config::YAZI; use yazi_fs::{Cwd, FsHash128, FsUrl, cha::Cha, ok_or_not_found, path::path_relative_to, provider::{Attrs, FileHolder, Provider, local::Local}}; use yazi_shared::{path::PathCow, url::{AsUrl, UrlCow, UrlLike}}; use yazi_vfs::{VfsCha, maybe_exists, provider::{self, DirEntry}, unique_file}; use super::{FileInCopy, FileInDelete, FileInHardlink, FileInLink, FileInTrash}; use crate::{LOW, NORMAL, TaskIn, TaskOp, TaskOps, ctx, file::{FileInCut, FileInDownload, FileInUpload, FileOutCopy, FileOutCopyDo, FileOutCut, FileOutCutDo, FileOutDelete, FileOutDeleteDo, FileOutDownload, FileOutDownloadDo, FileOutHardlink, FileOutHardlinkDo, FileOutLink, FileOutTrash, FileOutUpload, FileOutUploadDo, Transaction, Traverse}, hook::{HookInOutCopy, HookInOutCut}, ok_or_not_found, progress_or_break}; pub(crate) struct File { ops: TaskOps, r#macro: async_priority_channel::Sender<TaskIn, u8>, } impl File { pub(crate) fn new( ops: &mpsc::UnboundedSender<TaskOp>, r#macro: &async_priority_channel::Sender<TaskIn, u8>, ) -> Self { Self { ops: ops.into(), r#macro: r#macro.clone() } } pub(crate) async fn copy(&self, mut task: FileInCopy) -> Result<(), FileOutCopy> { let id = task.id; if !task.force { task.to = unique_file(mem::take(&mut task.to), task.init().await?.is_dir()) .await .context("Cannot determine unique destination name")?; } self.ops.out(id, HookInOutCopy::from(&task)); super::traverse::<FileOutCopy, _, _, _, _, _>( task, async |dir| match provider::create_dir(dir).await { Err(e) if e.kind() != io::ErrorKind::AlreadyExists => Err(e)?, _ => Ok(()), }, async |task, cha| { Ok(if cha.is_orphan() || (cha.is_link() && !task.follow) { self.ops.out(id, FileOutCopy::New(0)); self.queue(task.into_link(), NORMAL); } else { self.ops.out(id, FileOutCopy::New(cha.len)); self.queue(task, LOW); }) }, |err| { self.ops.out(id, FileOutCopy::Deform(err)); }, ) .await?; Ok(self.ops.out(id, FileOutCopy::Succ)) } pub(crate) async fn copy_do(&self, mut task: FileInCopy) -> Result<(), FileOutCopyDo> { ok_or_not_found!(task, Transaction::unlink(&task.to).await); let mut it = ctx!(task, provider::copy_with_progress(&task.from, &task.to, task.cha.unwrap()).await)?; loop { match progress_or_break!(it, task.done) { Ok(0) => break, Ok(n) => self.ops.out(task.id, FileOutCopyDo::Adv(n)), Err(e) if e.kind() == NotFound => { warn!("Copy task partially done: {task:?}"); break; } // Operation not permitted (os error 1) // Attribute not found (os error 93) Err(e) if task.retry < YAZI.tasks.bizarre_retry && matches!(e.raw_os_error(), Some(1) | Some(93)) => { task.retry += 1; self.ops.out(task.id, FileOutCopyDo::Log(format!("Retrying due to error: {e}"))); return Ok(self.queue(task, LOW)); } Err(e) => ctx!(task, Err(e))?, } } Ok(self.ops.out(task.id, FileOutCopyDo::Succ)) } pub(crate) async fn cut(&self, mut task: FileInCut) -> Result<(), FileOutCut> { let id = task.id; if !task.force { task.to = unique_file(mem::take(&mut task.to), task.init().await?.is_dir()) .await .context("Cannot determine unique destination name")?; } self.ops.out(id, HookInOutCut::from(&task)); if !task.follow && ok_or_not_found(provider::rename(&task.from, &task.to).await).is_ok() { return Ok(self.ops.out(id, FileOutCut::Succ)); } let (mut links, mut files) = (vec![], vec![]); let reorder = task.follow && ctx!(task, provider::capabilities(&task.from).await)?.symlink; super::traverse::<FileOutCut, _, _, _, _, _>( task, async |dir| match provider::create_dir(dir).await { Err(e) if e.kind() != io::ErrorKind::AlreadyExists => Err(e)?, _ => Ok(()), }, |task, cha| { let nofollow = cha.is_orphan() || (cha.is_link() && !task.follow); self.ops.out(id, FileOutCut::New(if nofollow { 0 } else { cha.len })); if nofollow { self.queue(task.into_link(), NORMAL); } else { match (cha.is_link(), reorder) { (_, false) => self.queue(task, LOW), (true, true) => links.push(task), (false, true) => files.push(task), } }; async { Ok(()) } }, |err| { self.ops.out(id, FileOutCut::Deform(err)); }, ) .await?; if !links.is_empty() { let (tx, mut rx) = mpsc::channel(1); for task in links { self.queue(task.with_drop(&tx), LOW); } drop(tx); while rx.recv().await.is_some() {} } for task in files { self.queue(task, LOW); } Ok(self.ops.out(id, FileOutCut::Succ)) } pub(crate) async fn cut_do(&self, mut task: FileInCut) -> Result<(), FileOutCutDo> { ok_or_not_found!(task, Transaction::unlink(&task.to).await); let mut it = ctx!(task, provider::copy_with_progress(&task.from, &task.to, task.cha.unwrap()).await)?; loop { match progress_or_break!(it, task.done) { Ok(0) => { provider::remove_file(&task.from).await.ok(); break; } Ok(n) => self.ops.out(task.id, FileOutCutDo::Adv(n)), Err(e) if e.kind() == NotFound => { warn!("Cut task partially done: {task:?}"); break; } // Operation not permitted (os error 1) // Attribute not found (os error 93) Err(e) if task.retry < YAZI.tasks.bizarre_retry && matches!(e.raw_os_error(), Some(1) | Some(93)) => { task.retry += 1; self.ops.out(task.id, FileOutCutDo::Log(format!("Retrying due to error: {e}"))); return Ok(self.queue(task, LOW)); } Err(e) => ctx!(task, Err(e))?, } } Ok(self.ops.out(task.id, FileOutCutDo::Succ)) } pub(crate) async fn link(&self, mut task: FileInLink) -> Result<(), FileOutLink> { if !task.force { task.to = unique_file(task.to, false).await.context("Cannot determine unique destination name")?; } Ok(self.queue(task, NORMAL)) } pub(crate) async fn link_do(&self, task: FileInLink) -> Result<(), FileOutLink> { let mut src: PathCow = if task.resolve { ok_or_not_found!( task, provider::read_link(&task.from).await, return Ok(self.ops.out(task.id, FileOutLink::Succ)) ) .into() } else { task.from.loc().into() }; if task.relative { let canon = ctx!(task, provider::canonicalize(task.to.parent().unwrap()).await)?; src = ctx!(task, path_relative_to(canon.loc(), src))?; } ok_or_not_found!(task, provider::remove_file(&task.to).await); ctx!( task, provider::symlink(&task.to, src, async || { Ok(match task.cha { Some(cha) => cha.is_dir(), None => Self::cha(&task.from, task.resolve, None).await?.is_dir(), }) }) .await )?; if task.delete { provider::remove_file(&task.from).await.ok(); } Ok(self.ops.out(task.id, FileOutLink::Succ)) } pub(crate) async fn hardlink(&self, mut task: FileInHardlink) -> Result<(), FileOutHardlink> { let id = task.id; if !task.force { task.to = unique_file(task.to, false).await.context("Cannot determine unique destination name")?; } super::traverse::<FileOutHardlink, _, _, _, _, _>( task, async |dir| match provider::create_dir(dir).await { Err(e) if e.kind() != io::ErrorKind::AlreadyExists => Err(e)?, _ => Ok(()), }, async |task, _cha| { self.ops.out(id, FileOutHardlink::New); Ok(self.queue(task, NORMAL)) }, |err| { self.ops.out(id, FileOutHardlink::Deform(err)); }, ) .await?; Ok(self.ops.out(id, FileOutHardlink::Succ)) } pub(crate) async fn hardlink_do(&self, task: FileInHardlink) -> Result<(), FileOutHardlinkDo> { let src = if !task.follow { UrlCow::from(&task.from) } else if let Ok(p) = provider::canonicalize(&task.from).await { UrlCow::from(p) } else { UrlCow::from(&task.from) }; ok_or_not_found!(task, provider::remove_file(&task.to).await); ok_or_not_found!(task, provider::hard_link(&src, &task.to).await); Ok(self.ops.out(task.id, FileOutHardlinkDo::Succ)) } pub(crate) async fn delete(&self, task: FileInDelete) -> Result<(), FileOutDelete> { let id = task.id; super::traverse::<FileOutDelete, _, _, _, _, _>( task, async |_dir| Ok(()), async |task, cha| { self.ops.out(id, FileOutDelete::New(cha.len)); Ok(self.queue(task, NORMAL)) }, |_err| {}, ) .await?; Ok(self.ops.out(id, FileOutDelete::Succ)) } pub(crate) async fn delete_do(&self, task: FileInDelete) -> Result<(), FileOutDeleteDo> { match provider::remove_file(&task.target).await { Ok(()) => {} Err(e) if e.kind() == NotFound => {} Err(_) if !maybe_exists(&task.target).await => {} Err(e) => ctx!(task, Err(e))?, } Ok(self.ops.out(task.id, FileOutDeleteDo::Succ(task.cha.unwrap().len))) } pub(crate) async fn trash(&self, task: FileInTrash) -> Result<(), FileOutTrash> { Ok(self.queue(task, LOW)) } pub(crate) async fn trash_do(&self, task: FileInTrash) -> Result<(), FileOutTrash> { ctx!(task, provider::trash(&task.target).await)?; Ok(self.ops.out(task.id, FileOutTrash::Succ)) } pub(crate) async fn download(&self, task: FileInDownload) -> Result<(), FileOutDownload> { let id = task.id; super::traverse::<FileOutDownload, _, _, _, _, _>( task, async |dir| { let dir = dir.to_owned(); tokio::task::spawn_blocking(move || _ = Cwd::ensure(dir.as_url())).await.ok(); Ok(()) }, async |task, cha| { Ok(if cha.is_orphan() { Err(anyhow!("Failed to work on {task:?}: source of symlink doesn't exist"))? } else { self.ops.out(id, FileOutDownload::New(cha.len)); self.queue(task, LOW); }) }, |err| { self.ops.out(id, FileOutDownload::Deform(err)); }, ) .await?; Ok(self.ops.out(id, FileOutDownload::Succ)) } pub(crate) async fn download_do( &self, mut task: FileInDownload, ) -> Result<(), FileOutDownloadDo> { let cha = task.cha.unwrap(); let cache = ctx!(task, task.url.cache(), "Cannot determine cache path")?; let cache_tmp = ctx!(task, Transaction::tmp(&cache).await, "Cannot determine download cache")?; let mut it = ctx!(task, provider::copy_with_progress(&task.url, &cache_tmp, cha).await)?; loop { match progress_or_break!(it, task.done) { Ok(0) => { Local::regular(&cache).remove_dir_all().await.ok(); ctx!(task, provider::rename(cache_tmp, cache).await, "Cannot persist downloaded file")?; let lock = ctx!(task, task.url.cache_lock(), "Cannot determine cache lock")?; let hash = format!("{:x}", cha.hash_u128()); ctx!(task, Local::regular(&lock).write(hash).await, "Cannot lock cache")?; break; } Ok(n) => self.ops.out(task.id, FileOutDownloadDo::Adv(n)), Err(e) if e.kind() == NotFound => { warn!("Download task partially done: {task:?}"); break; } // Operation not permitted (os error 1) // Attribute not found (os error 93) Err(e) if task.retry < YAZI.tasks.bizarre_retry && matches!(e.raw_os_error(), Some(1) | Some(93)) => { task.retry += 1; self.ops.out(task.id, FileOutDownloadDo::Log(format!("Retrying due to error: {e}"))); return Ok(self.queue(task, LOW)); } Err(e) => ctx!(task, Err(e))?, } } Ok(self.ops.out(task.id, FileOutDownloadDo::Succ)) } pub(crate) async fn upload(&self, task: FileInUpload) -> Result<(), FileOutUpload> { let id = task.id; super::traverse::<FileOutUpload, _, _, _, _, _>( task, async |_dir| Ok(()), async |task, cha| { let cache = ctx!(task, task.cache.as_ref(), "Cannot determine cache path")?; Ok(match Self::cha(cache, true, None).await { Ok(c) if c.mtime == cha.mtime => {} Ok(c) => { self.ops.out(id, FileOutUpload::New(c.len)); self.queue(task, LOW); } Err(e) if e.kind() == NotFound => {} Err(e) => ctx!(task, Err(e))?, }) }, |err| { self.ops.out(id, FileOutUpload::Deform(err)); }, ) .await?; Ok(self.ops.out(id, FileOutUpload::Succ)) } pub(crate) async fn upload_do(&self, task: FileInUpload) -> Result<(), FileOutUploadDo> { let cha = task.cha.unwrap(); let cache = ctx!(task, task.cache.as_ref(), "Cannot determine cache path")?; let lock = ctx!(task, task.url.cache_lock(), "Cannot determine cache lock")?; let hash = ctx!(task, Local::regular(&lock).read_to_string().await, "Cannot read cache lock")?; let hash = ctx!(task, u128::from_str_radix(&hash, 16), "Cannot parse hash from lock")?; if hash != cha.hash_u128() { Err(anyhow!("Failed to work on: {task:?}: remote file has changed since last download"))?; } let tmp = ctx!(task, Transaction::tmp(&task.url).await, "Cannot determine temporary upload path")?; let mut it = ctx!( task, provider::copy_with_progress(cache, &tmp, Attrs { mode: Some(cha.mode), atime: None, btime: None, mtime: None, }) .await )?; loop { match progress_or_break!(it, task.done) { Ok(0) => { let cha = ctx!(task, Self::cha(&task.url, true, None).await, "Cannot stat original file")?; if hash != cha.hash_u128() { Err(anyhow!("Failed to work on: {task:?}: remote file has changed during upload"))?; } ctx!(task, provider::rename(&tmp, &task.url).await, "Cannot persist uploaded file")?; let cha = ctx!(task, Self::cha(&task.url, true, None).await, "Cannot stat uploaded file")?; let hash = format!("{:x}", cha.hash_u128()); ctx!(task, Local::regular(&lock).write(hash).await, "Cannot lock cache")?; break; } Ok(n) => self.ops.out(task.id, FileOutUploadDo::Adv(n)), Err(e) => ctx!(task, Err(e))?, } } Ok(self.ops.out(task.id, FileOutUploadDo::Succ)) } pub(super) async fn cha<U>(url: U, follow: bool, entry: Option<DirEntry>) -> io::Result<Cha> where U: AsUrl, { let cha = if let Some(entry) = entry { entry.metadata().await? } else { provider::symlink_metadata(url.as_url()).await? }; Ok(if follow { Cha::from_follow(url, cha).await } else { cha }) } } impl File { #[inline] fn queue(&self, r#in: impl Into<TaskIn>, priority: u8) { _ = self.r#macro.try_send(r#in.into(), priority); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/file/progress.rs
yazi-scheduler/src/file/progress.rs
use serde::Serialize; use yazi_parser::app::TaskSummary; // --- Copy #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)] pub struct FileProgCopy { pub total_files: u32, pub success_files: u32, pub failed_files: u32, pub total_bytes: u64, pub processed_bytes: u64, pub collected: Option<bool>, pub cleaned: Option<bool>, } impl From<FileProgCopy> for TaskSummary { fn from(value: FileProgCopy) -> Self { Self { total: value.total_files, success: value.success_files, failed: value.failed_files, percent: value.percent().map(Into::into), } } } impl FileProgCopy { pub fn cooked(self) -> bool { self.collected == Some(true) && self.success_files == self.total_files } pub fn running(self) -> bool { self.collected.is_none() || self.success_files + self.failed_files != self.total_files || (self.cleaned.is_none() && self.cooked()) } pub fn success(self) -> bool { self.cleaned == Some(true) && self.cooked() } pub fn failed(self) -> bool { self.cleaned == Some(false) || self.collected == Some(false) } pub fn cleaned(self) -> Option<bool> { self.cleaned } pub fn percent(self) -> Option<f32> { Some(if self.success() { 100.0 } else if self.failed() { 0.0 } else if self.total_bytes != 0 { 99.99f32.min(self.processed_bytes as f32 / self.total_bytes as f32 * 100.0) } else { 99.99 }) } } // --- Cut #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)] pub struct FileProgCut { pub total_files: u32, pub success_files: u32, pub failed_files: u32, pub total_bytes: u64, pub processed_bytes: u64, pub collected: Option<bool>, pub cleaned: Option<bool>, } impl From<FileProgCut> for TaskSummary { fn from(value: FileProgCut) -> Self { Self { total: value.total_files, success: value.success_files, failed: value.failed_files, percent: value.percent().map(Into::into), } } } impl FileProgCut { pub fn cooked(self) -> bool { self.collected == Some(true) && self.success_files == self.total_files } pub fn running(self) -> bool { self.collected.is_none() || self.success_files + self.failed_files != self.total_files || (self.cleaned.is_none() && self.cooked()) } pub fn success(self) -> bool { self.cleaned == Some(true) && self.cooked() } pub fn failed(self) -> bool { self.cleaned == Some(false) || self.collected == Some(false) } pub fn cleaned(self) -> Option<bool> { self.cleaned } pub fn percent(self) -> Option<f32> { Some(if self.success() { 100.0 } else if self.failed() { 0.0 } else if self.total_bytes != 0 { 99.99f32.min(self.processed_bytes as f32 / self.total_bytes as f32 * 100.0) } else { 99.99 }) } } // --- Link #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)] pub struct FileProgLink { pub state: Option<bool>, } impl From<FileProgLink> for TaskSummary { fn from(value: FileProgLink) -> Self { Self { total: 1, success: (value.state == Some(true)) as u32, failed: (value.state == Some(false)) as u32, percent: value.percent().map(Into::into), } } } impl FileProgLink { pub fn cooked(self) -> bool { self.state == Some(true) } pub fn running(self) -> bool { self.state.is_none() } pub fn success(self) -> bool { self.cooked() } pub fn failed(self) -> bool { self.state == Some(false) } pub fn cleaned(self) -> Option<bool> { None } pub fn percent(self) -> Option<f32> { None } } // --- Hardlink #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)] pub struct FileProgHardlink { pub total: u32, pub success: u32, pub failed: u32, pub collected: Option<bool>, } impl From<FileProgHardlink> for TaskSummary { fn from(value: FileProgHardlink) -> Self { Self { total: value.total, success: value.success, failed: value.failed, percent: value.percent().map(Into::into), } } } impl FileProgHardlink { pub fn cooked(self) -> bool { self.collected == Some(true) && self.success == self.total } pub fn running(self) -> bool { self.collected.is_none() || self.success + self.failed != self.total } pub fn success(self) -> bool { self.cooked() } pub fn failed(self) -> bool { self.collected == Some(false) } pub fn cleaned(self) -> Option<bool> { None } pub fn percent(self) -> Option<f32> { None } } // --- Delete #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)] pub struct FileProgDelete { pub total_files: u32, pub success_files: u32, pub failed_files: u32, pub total_bytes: u64, pub processed_bytes: u64, pub collected: Option<bool>, pub cleaned: Option<bool>, } impl From<FileProgDelete> for TaskSummary { fn from(value: FileProgDelete) -> Self { Self { total: value.total_files, success: value.success_files, failed: value.failed_files, percent: value.percent().map(Into::into), } } } impl FileProgDelete { pub fn cooked(self) -> bool { self.collected == Some(true) && self.success_files == self.total_files } pub fn running(self) -> bool { self.collected.is_none() || self.success_files + self.failed_files != self.total_files || (self.cleaned.is_none() && self.cooked()) } pub fn success(self) -> bool { self.cleaned == Some(true) && self.cooked() } pub fn failed(self) -> bool { self.cleaned == Some(false) || self.collected == Some(false) } pub fn cleaned(self) -> Option<bool> { self.cleaned } pub fn percent(self) -> Option<f32> { Some(if self.success() { 100.0 } else if self.failed() { 0.0 } else if self.total_bytes != 0 { 99.99f32.min(self.processed_bytes as f32 / self.total_bytes as f32 * 100.0) } else { 99.99 }) } } // --- Trash #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)] pub struct FileProgTrash { pub state: Option<bool>, pub cleaned: Option<bool>, } impl From<FileProgTrash> for TaskSummary { fn from(value: FileProgTrash) -> Self { Self { total: 1, success: (value.state == Some(true)) as u32, failed: (value.state == Some(false)) as u32, percent: value.percent().map(Into::into), } } } impl FileProgTrash { pub fn cooked(self) -> bool { self.state == Some(true) } pub fn running(self) -> bool { self.state.is_none() || (self.cleaned.is_none() && self.cooked()) } pub fn success(self) -> bool { self.cleaned == Some(true) && self.cooked() } pub fn failed(self) -> bool { self.cleaned == Some(false) || self.state == Some(false) } pub fn cleaned(self) -> Option<bool> { self.cleaned } pub fn percent(self) -> Option<f32> { None } } // --- Download #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)] pub struct FileProgDownload { pub total_files: u32, pub success_files: u32, pub failed_files: u32, pub total_bytes: u64, pub processed_bytes: u64, pub collected: Option<bool>, pub cleaned: Option<bool>, } impl From<FileProgDownload> for TaskSummary { fn from(value: FileProgDownload) -> Self { Self { total: value.total_files, success: value.success_files, failed: value.failed_files, percent: value.percent().map(Into::into), } } } impl FileProgDownload { pub fn cooked(self) -> bool { self.collected == Some(true) && self.success_files == self.total_files } pub fn running(self) -> bool { self.collected.is_none() || self.success_files + self.failed_files != self.total_files || (self.cleaned.is_none() && self.cooked()) } pub fn success(self) -> bool { self.cleaned == Some(true) && self.cooked() } pub fn failed(self) -> bool { self.cleaned == Some(false) || self.collected == Some(false) } pub fn cleaned(self) -> Option<bool> { self.cleaned } pub fn percent(self) -> Option<f32> { Some(if self.success() { 100.0 } else if self.failed() { 0.0 } else if self.total_bytes != 0 { 99.99f32.min(self.processed_bytes as f32 / self.total_bytes as f32 * 100.0) } else { 99.99 }) } } // --- Upload #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)] pub struct FileProgUpload { pub total_files: u32, pub success_files: u32, pub failed_files: u32, pub total_bytes: u64, pub processed_bytes: u64, pub collected: Option<bool>, } impl From<FileProgUpload> for TaskSummary { fn from(value: FileProgUpload) -> Self { Self { total: value.total_files, success: value.success_files, failed: value.failed_files, percent: value.percent().map(Into::into), } } } impl FileProgUpload { pub fn cooked(self) -> bool { self.collected == Some(true) && self.success_files == self.total_files } pub fn running(self) -> bool { self.collected.is_none() || self.success_files + self.failed_files != self.total_files } pub fn success(self) -> bool { self.cooked() } pub fn failed(self) -> bool { self.collected == Some(false) } pub fn cleaned(self) -> Option<bool> { None } pub fn percent(self) -> Option<f32> { Some(if self.success() { 100.0 } else if self.failed() { 0.0 } else if self.total_bytes != 0 { 99.99f32.min(self.processed_bytes as f32 / self.total_bytes as f32 * 100.0) } else { 99.99 }) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/file/out.rs
yazi-scheduler/src/file/out.rs
use std::io; use crate::{Task, TaskProg}; // --- Copy #[derive(Debug)] pub(crate) enum FileOutCopy { New(u64), Deform(String), Succ, Fail(String), Clean, } impl From<anyhow::Error> for FileOutCopy { fn from(value: anyhow::Error) -> Self { Self::Fail(format!("{value:?}")) } } impl From<std::io::Error> for FileOutCopy { fn from(value: std::io::Error) -> Self { Self::Fail(format!("{value:?}")) } } impl FileOutCopy { pub(crate) fn reduce(self, task: &mut Task) { let TaskProg::FileCopy(prog) = &mut task.prog else { return }; match self { Self::New(bytes) => { prog.total_files += 1; prog.total_bytes += bytes; } Self::Deform(reason) => { prog.total_files += 1; prog.failed_files += 1; task.log(reason); } Self::Succ => { prog.collected = Some(true); } Self::Fail(reason) => { prog.collected = Some(false); task.log(reason); } Self::Clean => { prog.cleaned = Some(true); } } } } // --- CopyDo #[derive(Debug)] pub(crate) enum FileOutCopyDo { Adv(u64), Log(String), Succ, Fail(String), } impl From<anyhow::Error> for FileOutCopyDo { fn from(value: anyhow::Error) -> Self { Self::Fail(format!("{value:?}")) } } impl FileOutCopyDo { pub(crate) fn reduce(self, task: &mut Task) { let TaskProg::FileCopy(prog) = &mut task.prog else { return }; match self { Self::Adv(size) => { prog.processed_bytes += size; } Self::Log(line) => { task.log(line); } Self::Succ => { prog.success_files += 1; } Self::Fail(reason) => { prog.failed_files += 1; task.log(reason); } } } } // --- Cut #[derive(Debug)] pub(crate) enum FileOutCut { New(u64), Deform(String), Succ, Fail(String), Clean(io::Result<()>), } impl From<anyhow::Error> for FileOutCut { fn from(value: anyhow::Error) -> Self { Self::Fail(format!("{value:?}")) } } impl From<std::io::Error> for FileOutCut { fn from(value: std::io::Error) -> Self { Self::Fail(format!("{value:?}")) } } impl FileOutCut { pub(crate) fn reduce(self, task: &mut Task) { let TaskProg::FileCut(prog) = &mut task.prog else { return }; match self { Self::New(bytes) => { prog.total_files += 1; prog.total_bytes += bytes; } Self::Deform(reason) => { prog.total_files += 1; prog.failed_files += 1; task.log(reason); } Self::Succ => { prog.collected = Some(true); } Self::Fail(reason) => { prog.collected = Some(false); task.log(reason); } Self::Clean(Ok(())) => { prog.cleaned = Some(true); } Self::Clean(Err(reason)) => { prog.cleaned = Some(false); task.log(format!("Failed cleaning up cut file: {reason:?}")); } } } } // --- CutDo #[derive(Debug)] pub(crate) enum FileOutCutDo { Adv(u64), Log(String), Succ, Fail(String), } impl From<anyhow::Error> for FileOutCutDo { fn from(value: anyhow::Error) -> Self { Self::Fail(format!("{value:?}")) } } impl FileOutCutDo { pub(crate) fn reduce(self, task: &mut Task) { let TaskProg::FileCut(prog) = &mut task.prog else { return }; match self { Self::Adv(size) => { prog.processed_bytes += size; } Self::Log(line) => { task.log(line); } Self::Succ => { prog.success_files += 1; } Self::Fail(reason) => { prog.failed_files += 1; task.log(reason); } } } } // --- Link #[derive(Debug)] pub(crate) enum FileOutLink { Succ, Fail(String), } impl From<anyhow::Error> for FileOutLink { fn from(value: anyhow::Error) -> Self { Self::Fail(format!("{value:?}")) } } impl FileOutLink { pub(crate) fn reduce(self, task: &mut Task) { if let TaskProg::FileLink(prog) = &mut task.prog { match self { Self::Succ => { prog.state = Some(true); } Self::Fail(reason) => { prog.state = Some(false); task.log(reason); } } } else if let TaskProg::FileCopy(prog) = &mut task.prog { match self { Self::Succ => { prog.success_files += 1; } Self::Fail(reason) => { prog.failed_files += 1; task.log(reason); } } } else if let TaskProg::FileCut(prog) = &mut task.prog { match self { Self::Succ => { prog.success_files += 1; } Self::Fail(reason) => { prog.failed_files += 1; task.log(reason); } } } } } // --- Hardlink #[derive(Debug)] pub(crate) enum FileOutHardlink { New, Deform(String), Succ, Fail(String), } impl From<anyhow::Error> for FileOutHardlink { fn from(value: anyhow::Error) -> Self { Self::Fail(format!("{value:?}")) } } impl From<std::io::Error> for FileOutHardlink { fn from(value: std::io::Error) -> Self { Self::Fail(format!("{value:?}")) } } impl FileOutHardlink { pub(crate) fn reduce(self, task: &mut Task) { let TaskProg::FileHardlink(prog) = &mut task.prog else { return }; match self { Self::New => { prog.total += 1; } Self::Deform(reason) => { prog.total += 1; prog.failed += 1; task.log(reason); } Self::Succ => { prog.collected = Some(true); } Self::Fail(reason) => { prog.collected = Some(false); task.log(reason); } } } } // --- HardlinkDo #[derive(Debug)] pub(crate) enum FileOutHardlinkDo { Succ, Fail(String), } impl From<anyhow::Error> for FileOutHardlinkDo { fn from(value: anyhow::Error) -> Self { Self::Fail(format!("{value:?}")) } } impl FileOutHardlinkDo { pub(crate) fn reduce(self, task: &mut Task) { let TaskProg::FileHardlink(prog) = &mut task.prog else { return }; match self { Self::Succ => { prog.success += 1; } Self::Fail(reason) => { prog.failed += 1; task.log(reason); } } } } // --- Delete #[derive(Debug)] pub(crate) enum FileOutDelete { New(u64), Succ, Fail(String), Clean(io::Result<()>), } impl From<anyhow::Error> for FileOutDelete { fn from(value: anyhow::Error) -> Self { Self::Fail(format!("{value:?}")) } } impl FileOutDelete { pub(crate) fn reduce(self, task: &mut Task) { let TaskProg::FileDelete(prog) = &mut task.prog else { return }; match self { Self::New(size) => { prog.total_files += 1; prog.total_bytes += size; } Self::Succ => { prog.collected = Some(true); } Self::Fail(reason) => { prog.collected = Some(false); task.log(reason); } Self::Clean(Ok(())) => { prog.cleaned = Some(true); } Self::Clean(Err(reason)) => { prog.cleaned = Some(false); task.log(format!("Failed cleaning up deleted file: {reason:?}")); } } } } // --- DeleteDo #[derive(Debug)] pub(crate) enum FileOutDeleteDo { Succ(u64), Fail(String), } impl From<anyhow::Error> for FileOutDeleteDo { fn from(value: anyhow::Error) -> Self { Self::Fail(format!("{value:?}")) } } impl FileOutDeleteDo { pub(crate) fn reduce(self, task: &mut Task) { let TaskProg::FileDelete(prog) = &mut task.prog else { return }; match self { Self::Succ(size) => { prog.success_files += 1; prog.processed_bytes += size; } Self::Fail(reason) => { prog.failed_files += 1; task.log(reason); } } } } // --- Trash #[derive(Debug)] pub(crate) enum FileOutTrash { Succ, Fail(String), Clean, } impl From<anyhow::Error> for FileOutTrash { fn from(value: anyhow::Error) -> Self { Self::Fail(format!("{value:?}")) } } impl FileOutTrash { pub(crate) fn reduce(self, task: &mut Task) { let TaskProg::FileTrash(prog) = &mut task.prog else { return }; match self { Self::Succ => { prog.state = Some(true); } Self::Fail(reason) => { prog.state = Some(false); task.log(reason); } Self::Clean => { prog.cleaned = Some(true); } } } } // --- Download #[derive(Debug)] pub(crate) enum FileOutDownload { New(u64), Deform(String), Succ, Fail(String), Clean, } impl From<anyhow::Error> for FileOutDownload { fn from(value: anyhow::Error) -> Self { Self::Fail(format!("{value:?}")) } } impl FileOutDownload { pub(crate) fn reduce(self, task: &mut Task) { let TaskProg::FileDownload(prog) = &mut task.prog else { return }; match self { Self::New(bytes) => { prog.total_files += 1; prog.total_bytes += bytes; } Self::Deform(reason) => { prog.total_files += 1; prog.failed_files += 1; task.log(reason); } Self::Succ => { prog.collected = Some(true); } Self::Fail(reason) => { prog.collected = Some(false); task.log(reason); } Self::Clean => { prog.cleaned = Some(true); } } } } // --- DownloadDo #[derive(Debug)] pub(crate) enum FileOutDownloadDo { Adv(u64), Log(String), Succ, Fail(String), } impl From<anyhow::Error> for FileOutDownloadDo { fn from(value: anyhow::Error) -> Self { Self::Fail(format!("{value:?}")) } } impl FileOutDownloadDo { pub(crate) fn reduce(self, task: &mut Task) { let TaskProg::FileDownload(prog) = &mut task.prog else { return }; match self { Self::Adv(size) => { prog.processed_bytes += size; } Self::Log(line) => { task.log(line); } Self::Succ => { prog.success_files += 1; } Self::Fail(reason) => { prog.failed_files += 1; task.log(reason); } } } } // --- Upload #[derive(Debug)] pub(crate) enum FileOutUpload { New(u64), Deform(String), Succ, Fail(String), } impl From<anyhow::Error> for FileOutUpload { fn from(value: anyhow::Error) -> Self { Self::Fail(format!("{value:?}")) } } impl FileOutUpload { pub(crate) fn reduce(self, task: &mut Task) { let TaskProg::FileUpload(prog) = &mut task.prog else { return }; match self { Self::New(bytes) => { prog.total_files += 1; prog.total_bytes += bytes; } Self::Deform(reason) => { prog.total_files += 1; prog.failed_files += 1; task.log(reason); } Self::Succ => { prog.collected = Some(true); } Self::Fail(reason) => { prog.collected = Some(false); task.log(reason); } } } } // --- UploadDo #[derive(Debug)] pub(crate) enum FileOutUploadDo { Adv(u64), Succ, Fail(String), } impl From<anyhow::Error> for FileOutUploadDo { fn from(value: anyhow::Error) -> Self { Self::Fail(format!("{value:?}")) } } impl FileOutUploadDo { pub(crate) fn reduce(self, task: &mut Task) { let TaskProg::FileUpload(prog) = &mut task.prog else { return }; match self { Self::Adv(size) => { prog.processed_bytes += size; } Self::Succ => { prog.success_files += 1; } Self::Fail(reason) => { prog.failed_files += 1; task.log(reason); } } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/file/mod.rs
yazi-scheduler/src/file/mod.rs
yazi_macro::mod_flat!(file out progress r#in transaction traverse);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/file/traverse.rs
yazi-scheduler/src/file/traverse.rs
use std::{collections::VecDeque, fmt::Debug}; use yazi_fs::{FsUrl, cha::Cha, path::skip_url, provider::{DirReader, FileHolder}}; use yazi_shared::{strand::StrandLike, url::{AsUrl, Url, UrlBuf, UrlLike}}; use yazi_vfs::provider::{self}; use crate::{ctx, file::{FileInCopy, FileInCut, FileInDelete, FileInDownload, FileInHardlink, FileInUpload}}; pub(super) trait Traverse { fn cha(&mut self) -> &mut Option<Cha>; fn follow(&self) -> bool; fn from(&self) -> Url<'_>; async fn init(&mut self) -> anyhow::Result<Cha> { if self.cha().is_none() { *self.cha() = Some(super::File::cha(self.from(), self.follow(), None).await?) } Ok(self.cha().unwrap()) } fn spawn(&self, from: UrlBuf, to: Option<UrlBuf>, cha: Cha) -> Self; fn to(&self) -> Option<Url<'_>>; } impl Traverse for FileInCopy { fn cha(&mut self) -> &mut Option<Cha> { &mut self.cha } fn follow(&self) -> bool { self.follow } fn from(&self) -> Url<'_> { self.from.as_url() } fn spawn(&self, from: UrlBuf, to: Option<UrlBuf>, cha: Cha) -> Self { Self { id: self.id, from, to: to.unwrap(), force: self.force, cha: Some(cha), follow: self.follow, retry: self.retry, done: self.done.clone(), } } fn to(&self) -> Option<Url<'_>> { Some(self.to.as_url()) } } impl Traverse for FileInCut { fn cha(&mut self) -> &mut Option<Cha> { &mut self.cha } fn follow(&self) -> bool { self.follow } fn from(&self) -> Url<'_> { self.from.as_url() } fn spawn(&self, from: UrlBuf, to: Option<UrlBuf>, cha: Cha) -> Self { Self { id: self.id, from, to: to.unwrap(), force: self.force, cha: Some(cha), follow: self.follow, retry: self.retry, done: self.done.clone(), drop: self.drop.clone(), } } fn to(&self) -> Option<Url<'_>> { Some(self.to.as_url()) } } impl Traverse for FileInHardlink { fn cha(&mut self) -> &mut Option<Cha> { &mut self.cha } fn follow(&self) -> bool { self.follow } fn from(&self) -> Url<'_> { self.from.as_url() } fn spawn(&self, from: UrlBuf, to: Option<UrlBuf>, cha: Cha) -> Self { Self { id: self.id, from, to: to.unwrap(), force: self.force, cha: Some(cha), follow: self.follow, } } fn to(&self) -> Option<Url<'_>> { Some(self.to.as_url()) } } impl Traverse for FileInDelete { fn cha(&mut self) -> &mut Option<Cha> { &mut self.cha } fn follow(&self) -> bool { false } fn from(&self) -> Url<'_> { self.target.as_url() } fn spawn(&self, from: UrlBuf, _to: Option<UrlBuf>, cha: Cha) -> Self { Self { id: self.id, target: from, cha: Some(cha) } } fn to(&self) -> Option<Url<'_>> { None } } impl Traverse for FileInDownload { fn cha(&mut self) -> &mut Option<Cha> { &mut self.cha } fn follow(&self) -> bool { true } fn from(&self) -> Url<'_> { self.url.as_url() } fn spawn(&self, from: UrlBuf, _to: Option<UrlBuf>, cha: Cha) -> Self { Self { id: self.id, url: from, cha: Some(cha), retry: self.retry, done: self.done.clone(), } } fn to(&self) -> Option<Url<'_>> { None } } impl Traverse for FileInUpload { fn cha(&mut self) -> &mut Option<Cha> { &mut self.cha } fn follow(&self) -> bool { true } fn from(&self) -> Url<'_> { self.url.as_url() } async fn init(&mut self) -> anyhow::Result<Cha> { if self.cha.is_none() { self.cha = Some(super::File::cha(self.from(), self.follow(), None).await?) } if self.cache.is_none() { self.cache = self.url.cache(); } Ok(self.cha.unwrap()) } fn spawn(&self, from: UrlBuf, _to: Option<UrlBuf>, cha: Cha) -> Self { Self { id: self.id, cha: Some(cha), cache: from.cache(), url: from, done: self.done.clone(), } } fn to(&self) -> Option<Url<'_>> { None } } #[allow(private_bounds)] pub(super) async fn traverse<O, I, D, FC, FR, E>( mut task: I, on_dir: D, mut on_file: FC, on_error: E, ) -> Result<(), O> where O: Debug + From<anyhow::Error>, I: Debug + Traverse, D: AsyncFn(Url) -> Result<(), O>, FC: FnMut(I, Cha) -> FR, FR: Future<Output = Result<(), O>>, E: Fn(String), { let cha = ctx!(task, task.init().await)?; if !cha.is_dir() { return on_file(task, cha).await; } let root = task.to(); let skip = task.from().components().count(); let mut dirs = VecDeque::from([task.from().to_owned()]); macro_rules! err { ($result:expr, $($args:tt)*) => { match $result { Ok(v) => v, Err(e) => { on_error(format!("{}: {e:?}", format_args!($($args)*))); continue; } } }; } while let Some(src) = dirs.pop_front() { let mut it = err!(provider::read_dir(&src).await, "Cannot read directory {src:?}"); let dest = if let Some(root) = root { let s = skip_url(&src, skip); err!(root.try_join(&s), "Cannot join {root:?} with {}", s.display()) } else { src }; () = err!(on_dir(dest.as_url()).await, "Cannot process directory {dest:?}"); while let Ok(Some(entry)) = it.next().await { let from = entry.url(); let cha = err!( super::File::cha(&from, task.follow(), Some(entry)).await, "Cannot get metadata for {from:?}" ); if cha.is_dir() { dirs.push_back(from); continue; } let to = if root.is_some() { let name = from.name().unwrap(); Some(err!(dest.try_join(name), "Cannot join {dest:?} with {}", name.display())) } else { None }; err!(on_file(task.spawn(from, to, cha), cha).await, "Cannot process file"); } } Ok(()) }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/file/transaction.rs
yazi-scheduler/src/file/transaction.rs
use std::{hash::{BuildHasher, Hash, Hasher}, io}; use yazi_macro::ok_or_not_found; use yazi_shared::{timestamp_us, url::{AsUrl, Url, UrlBuf}}; use yazi_vfs::{provider, unique_file}; pub(super) struct Transaction; impl Transaction { pub(super) async fn tmp<U>(url: U) -> io::Result<UrlBuf> where U: AsUrl, { Self::tmp_impl(url.as_url()).await } async fn tmp_impl(url: Url<'_>) -> io::Result<UrlBuf> { let Some(parent) = url.parent() else { Err(io::Error::new(io::ErrorKind::InvalidInput, "Url has no parent"))? }; let mut h = foldhash::fast::FixedState::default().build_hasher(); url.hash(&mut h); timestamp_us().hash(&mut h); unique_file(parent.try_join(format!(".{:x}.%tmp", h.finish()))?, false).await } pub(super) async fn unlink<U>(url: U) -> io::Result<()> where U: AsUrl, { let url = url.as_url(); if ok_or_not_found!(provider::symlink_metadata(url).await, return Ok(())).is_link() { provider::rename(Self::tmp(url).await?, url).await?; } Ok(()) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/hook/hook.rs
yazi-scheduler/src/hook/hook.rs
use std::sync::Arc; use parking_lot::Mutex; use tokio::sync::mpsc; use yazi_dds::Pump; use yazi_fs::ok_or_not_found; use yazi_proxy::TasksProxy; use yazi_vfs::provider; use crate::{Ongoing, TaskOp, TaskOps, file::{FileOutCopy, FileOutCut, FileOutDelete, FileOutDownload, FileOutTrash}, hook::{HookInOutCopy, HookInOutCut, HookInOutDelete, HookInOutDownload, HookInOutTrash}}; pub(crate) struct Hook { ops: TaskOps, ongoing: Arc<Mutex<Ongoing>>, } impl Hook { pub(crate) fn new(ops: &mpsc::UnboundedSender<TaskOp>, ongoing: &Arc<Mutex<Ongoing>>) -> Self { Self { ops: ops.into(), ongoing: ongoing.clone() } } // --- File pub(crate) async fn cut(&self, task: HookInOutCut) { if !self.ongoing.lock().intact(task.id) { return self.ops.out(task.id, FileOutCut::Clean(Ok(()))); } let result = ok_or_not_found(provider::remove_dir_clean(&task.from).await); TasksProxy::update_succeed([&task.to, &task.from]); Pump::push_move(task.from, task.to); self.ops.out(task.id, FileOutCut::Clean(result)); } pub(crate) async fn copy(&self, task: HookInOutCopy) { if self.ongoing.lock().intact(task.id) { TasksProxy::update_succeed([&task.to]); Pump::push_duplicate(task.from, task.to); } self.ops.out(task.id, FileOutCopy::Clean); } pub(crate) async fn delete(&self, task: HookInOutDelete) { if !self.ongoing.lock().intact(task.id) { return self.ops.out(task.id, FileOutDelete::Clean(Ok(()))); } let result = ok_or_not_found(provider::remove_dir_all(&task.target).await); TasksProxy::update_succeed([&task.target]); Pump::push_delete(task.target); self.ops.out(task.id, FileOutDelete::Clean(result)); } pub(crate) async fn trash(&self, task: HookInOutTrash) { let intact = self.ongoing.lock().intact(task.id); if intact { TasksProxy::update_succeed([&task.target]); Pump::push_trash(task.target); } self.ops.out(task.id, FileOutTrash::Clean); } pub(crate) async fn download(&self, task: HookInOutDownload) { self.ops.out(task.id, FileOutDownload::Clean); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/hook/in.rs
yazi-scheduler/src/hook/in.rs
use yazi_shared::{Id, url::UrlBuf}; use crate::{Task, TaskProg, file::{FileInCopy, FileInCut}}; // --- Copy #[derive(Debug)] pub(crate) struct HookInOutCopy { pub(crate) id: Id, pub(crate) from: UrlBuf, pub(crate) to: UrlBuf, } impl From<&FileInCopy> for HookInOutCopy { fn from(value: &FileInCopy) -> Self { Self { id: value.id, from: value.from.clone(), to: value.to.clone() } } } impl HookInOutCopy { pub(crate) fn reduce(self, task: &mut Task) { if let TaskProg::FileCopy(_) = &task.prog { task.hook = Some(self.into()); } } } // --- Cut #[derive(Debug)] pub(crate) struct HookInOutCut { pub(crate) id: Id, pub(crate) from: UrlBuf, pub(crate) to: UrlBuf, } impl From<&FileInCut> for HookInOutCut { fn from(value: &FileInCut) -> Self { Self { id: value.id, from: value.from.clone(), to: value.to.clone() } } } impl HookInOutCut { pub(crate) fn reduce(self, task: &mut Task) { if let TaskProg::FileCut(_) = &task.prog { task.hook = Some(self.into()); } } } // --- Delete #[derive(Debug)] pub(crate) struct HookInOutDelete { pub(crate) id: Id, pub(crate) target: UrlBuf, } impl HookInOutDelete { pub(crate) fn reduce(self, task: &mut Task) { if let TaskProg::FileDelete(_) = &task.prog { task.hook = Some(self.into()); } } } // --- Trash #[derive(Debug)] pub(crate) struct HookInOutTrash { pub(crate) id: Id, pub(crate) target: UrlBuf, } impl HookInOutTrash { pub(crate) fn reduce(self, task: &mut Task) { if let TaskProg::FileTrash(_) = &task.prog { task.hook = Some(self.into()); } } } // --- Download #[derive(Debug)] pub(crate) struct HookInOutDownload { pub(crate) id: Id, } impl HookInOutDownload { pub(crate) fn reduce(self, task: &mut Task) { if let TaskProg::FileDownload(_) = &task.prog { task.hook = Some(self.into()); } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-scheduler/src/hook/mod.rs
yazi-scheduler/src/hook/mod.rs
yazi_macro::mod_flat!(hook r#in);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-ffi/src/disk_arbitration.rs
yazi-ffi/src/disk_arbitration.rs
use std::ffi::{c_char, c_void}; use core_foundation_sys::{array::CFArrayRef, base::CFAllocatorRef, dictionary::CFDictionaryRef, runloop::CFRunLoopRef, string::CFStringRef}; #[link(name = "DiskArbitration", kind = "framework")] unsafe extern "C" { pub fn DASessionCreate(allocator: CFAllocatorRef) -> *const c_void; pub fn DADiskCreateFromBSDName( allocator: CFAllocatorRef, session: *const c_void, path: *const c_char, ) -> *const c_void; pub fn DADiskCopyDescription(disk: *const c_void) -> CFDictionaryRef; pub fn DARegisterDiskAppearedCallback( session: *const c_void, 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, r#match: CFDictionaryRef, watch: CFArrayRef, callback: extern "C" fn(disk: *const c_void, keys: CFArrayRef, context: *mut c_void), context: *mut c_void, ); pub fn DARegisterDiskDisappearedCallback( session: *const c_void, r#match: CFDictionaryRef, callback: extern "C" fn(disk: *const c_void, context: *mut c_void), context: *mut c_void, ); pub fn DASessionScheduleWithRunLoop( session: *const c_void, runLoop: CFRunLoopRef, runLoopMode: CFStringRef, ); }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-ffi/src/cf_dict.rs
yazi-ffi/src/cf_dict.rs
use std::{ffi::{CStr, OsStr, OsString, c_char, c_void}, mem::ManuallyDrop, os::unix::ffi::OsStrExt, path::PathBuf}; use anyhow::{Result, bail}; use core_foundation_sys::{base::{CFRelease, TCFTypeRef}, dictionary::{CFDictionaryGetValueIfPresent, CFDictionaryRef}, string::CFStringRef}; use objc2::{msg_send, runtime::AnyObject}; use super::cf_string::CFString; pub struct CFDict(CFDictionaryRef); impl CFDict { pub fn take(dict: CFDictionaryRef) -> Result<Self> { if dict.is_null() { bail!("Cannot take a null pointer"); } Ok(Self(dict)) } pub fn value(&self, key: &str) -> Result<*const c_void> { let key_ = CFString::new(key)?; let mut value = std::ptr::null(); if unsafe { CFDictionaryGetValueIfPresent(self.0, key_.as_void_ptr(), &mut value) } == 0 || value.is_null() { bail!("Cannot get the value for the key `{key}`"); } Ok(value) } pub fn bool(&self, key: &str) -> Result<bool> { let value = self.value(key)?; #[allow(unexpected_cfgs)] Ok(unsafe { msg_send![value as *const AnyObject, boolValue] }) } pub fn integer(&self, key: &str) -> Result<i64> { let value = self.value(key)?; #[allow(unexpected_cfgs)] Ok(unsafe { msg_send![value as *const AnyObject, longLongValue] }) } pub fn os_string(&self, key: &str) -> Result<OsString> { ManuallyDrop::new(CFString(self.value(key)? as CFStringRef)).os_string() } pub fn path_buf(&self, key: &str) -> Result<PathBuf> { let url = self.value(key)? as *const AnyObject; #[allow(unexpected_cfgs)] let cstr: *const c_char = unsafe { let nss: *const AnyObject = msg_send![url, path]; msg_send![nss, UTF8String] }; Ok(OsStr::from_bytes(unsafe { CStr::from_ptr(cstr) }.to_bytes()).into()) } } impl Drop for CFDict { fn drop(&mut self) { unsafe { CFRelease(self.0 as _) } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-ffi/src/lib.rs
yazi-ffi/src/lib.rs
#[cfg(target_os = "macos")] yazi_macro::mod_flat!(cf_dict cf_string disk_arbitration io_kit);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-ffi/src/cf_string.rs
yazi-ffi/src/cf_string.rs
use std::{ffi::OsString, ops::Deref, os::unix::ffi::OsStringExt}; use anyhow::{Result, bail}; use core_foundation_sys::{base::{CFRelease, kCFAllocatorDefault, kCFAllocatorNull}, string::{CFStringCreateWithBytesNoCopy, CFStringGetCString, CFStringGetLength, CFStringGetMaximumSizeForEncoding, CFStringRef, kCFStringEncodingUTF8}}; use libc::strlen; pub struct CFString(pub(super) CFStringRef); impl CFString { pub fn new(s: &str) -> Result<Self> { let key = unsafe { CFStringCreateWithBytesNoCopy( kCFAllocatorDefault, s.as_ptr(), s.len() as _, kCFStringEncodingUTF8, false as _, kCFAllocatorNull, ) }; if key.is_null() { bail!("Allocation failed while creating CFString"); } Ok(Self(key)) } pub fn len(&self) -> usize { unsafe { CFStringGetLength(self.0) as _ } } pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn os_string(&self) -> Result<OsString> { let len = self.len(); let capacity = unsafe { CFStringGetMaximumSizeForEncoding(len as _, kCFStringEncodingUTF8) } + 1; let mut out: Vec<u8> = Vec::with_capacity(capacity as usize); let result = unsafe { CFStringGetCString(self.0, out.as_mut_ptr().cast(), capacity, kCFStringEncodingUTF8) }; if result == 0 { bail!("Failed to get the C string from CFString"); } unsafe { out.set_len(strlen(out.as_ptr().cast())) }; out.shrink_to_fit(); Ok(OsString::from_vec(out)) } } impl Deref for CFString { type Target = CFStringRef; fn deref(&self) -> &Self::Target { &self.0 } } impl Drop for CFString { fn drop(&mut self) { unsafe { CFRelease(self.0 as _) }; } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-ffi/src/io_kit.rs
yazi-ffi/src/io_kit.rs
use std::ffi::c_char; use core_foundation_sys::{base::{CFAllocatorRef, CFTypeRef, mach_port_t}, dictionary::CFMutableDictionaryRef, string::CFStringRef}; use libc::kern_return_t; #[link(name = "IOKit", kind = "framework")] unsafe extern "C" { pub fn IOServiceGetMatchingServices( mainPort: mach_port_t, matching: CFMutableDictionaryRef, existing: *mut mach_port_t, ) -> kern_return_t; pub fn IOServiceMatching(a: *const c_char) -> CFMutableDictionaryRef; pub fn IOIteratorNext(iterator: mach_port_t) -> mach_port_t; pub fn IORegistryEntryCreateCFProperty( entry: mach_port_t, key: CFStringRef, allocator: CFAllocatorRef, options: u32, ) -> CFTypeRef; pub fn IOObjectRelease(obj: mach_port_t) -> kern_return_t; }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-proxy/src/app.rs
yazi-proxy/src/app.rs
use std::time::Duration; use tokio::sync::oneshot; use yazi_macro::{emit, relay}; use yazi_parser::app::{NotifyLevel, NotifyOpt, PluginOpt, TaskSummary}; pub struct AppProxy; impl AppProxy { pub async fn stop() { let (tx, rx) = oneshot::channel::<()>(); emit!(Call(relay!(app:stop).with_any("tx", tx))); rx.await.ok(); } pub async fn resume() { let (tx, rx) = oneshot::channel::<()>(); emit!(Call(relay!(app:resume).with_any("tx", tx))); rx.await.ok(); } pub fn notify(opt: NotifyOpt) { emit!(Call(relay!(app:notify).with_any("opt", opt))); } pub fn update_notify(dur: Duration) { emit!(Call(relay!(app:update_notify, [dur.as_secs_f64()]))); } pub fn notify_warn(title: impl Into<String>, content: impl Into<String>) { Self::notify(NotifyOpt { title: title.into(), content: content.into(), level: NotifyLevel::Warn, timeout: Duration::from_secs(5), }); } pub fn notify_error(title: &str, content: impl ToString) { Self::notify(NotifyOpt { title: title.to_owned(), content: content.to_string(), level: NotifyLevel::Error, timeout: Duration::from_secs(10), }); } pub fn plugin(opt: PluginOpt) { emit!(Call(relay!(app:plugin).with_any("opt", opt))); } pub fn plugin_do(opt: PluginOpt) { emit!(Call(relay!(app:plugin_do).with_any("opt", opt))); } pub fn update_progress(summary: TaskSummary) { emit!(Call(relay!(app:update_progress).with_any("summary", summary))); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-proxy/src/tasks.rs
yazi-proxy/src/tasks.rs
use std::ffi::OsString; use yazi_macro::{emit, relay}; use yazi_parser::tasks::ProcessOpenOpt; use yazi_shared::{CompletionToken, url::{UrlBuf, UrlCow}}; pub struct TasksProxy; impl TasksProxy { // TODO: remove pub fn open_shell_compat(opt: ProcessOpenOpt) { emit!(Call(relay!(tasks:open_shell_compat).with_any("opt", opt))); } pub async fn process_exec( cwd: UrlCow<'static>, cmd: OsString, args: Vec<UrlCow<'static>>, block: bool, orphan: bool, ) { let done = CompletionToken::default(); emit!(Call(relay!(tasks:process_open).with_any("opt", ProcessOpenOpt { cwd, cmd, args, block, orphan, done: Some(done.clone()), spread: false }))); done.future().await; } pub fn update_succeed<I>(url: I) where I: IntoIterator, I::Item: Into<UrlBuf>, { let urls: Vec<_> = url.into_iter().map(Into::into).collect(); emit!(Call(relay!(tasks:update_succeed).with_any("urls", urls))); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-proxy/src/mgr.rs
yazi-proxy/src/mgr.rs
use std::borrow::Cow; use yazi_macro::{emit, relay}; use yazi_parser::mgr::{DisplaceDoOpt, FilterOpt, FindDoOpt, OpenDoOpt, OpenOpt, SearchOpt, UpdatePeekedOpt, UpdateSpottedOpt}; use yazi_shared::{Id, SStr, url::UrlBuf}; pub struct MgrProxy; impl MgrProxy { pub fn arrow(step: impl Into<SStr>) { emit!(Call(relay!(mgr:arrow, [step.into()]))); } pub fn cd(target: impl Into<UrlBuf>) { emit!(Call(relay!(mgr:cd, [target.into()]).with("raw", true))); } pub fn displace_do(tab: Id, opt: DisplaceDoOpt) { emit!(Call(relay!(mgr:displace_do).with("tab", tab).with_any("opt", opt))); } pub fn filter_do(opt: FilterOpt) { emit!(Call(relay!(mgr:filter_do).with_any("opt", opt))); } pub fn find_do(opt: FindDoOpt) { emit!(Call(relay!(mgr:find_do).with_any("opt", opt))); } pub fn open(opt: OpenOpt) { emit!(Call(relay!(mgr:open).with_any("opt", opt))); } pub fn open_do(opt: OpenDoOpt) { emit!(Call(relay!(mgr:open_do).with_any("opt", opt))); } pub fn remove_do(targets: Vec<UrlBuf>, permanently: bool) { emit!(Call( relay!(mgr:remove_do).with("permanently", permanently).with_any("targets", targets) )); } pub fn reveal(target: impl Into<UrlBuf>) { emit!(Call(relay!(mgr:reveal, [target.into()]).with("raw", true).with("no-dummy", true))); } pub fn search_do(opt: SearchOpt) { emit!(Call( // TODO: use second positional argument instead of `args` parameter relay!(mgr:search_do, [opt.subject]) .with("via", Cow::Borrowed(opt.via.into_str())) .with("args", opt.args_raw.into_owned()) )); } pub fn update_paged_by(page: usize, only_if: &UrlBuf) { emit!(Call(relay!(mgr:update_paged, [page]).with("only-if", only_if))); } pub fn update_peeked(opt: UpdatePeekedOpt) { emit!(Call(relay!(mgr:update_peeked).with_any("opt", opt))); } pub fn update_spotted(opt: UpdateSpottedOpt) { emit!(Call(relay!(mgr:update_spotted).with_any("opt", opt))); } pub fn upload<I>(urls: I) where I: IntoIterator<Item = UrlBuf>, { emit!(Call(relay!(mgr:upload).with_seq(urls))); } pub fn watch() { emit!(Call(relay!(mgr:watch))); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-proxy/src/lib.rs
yazi-proxy/src/lib.rs
mod macros; yazi_macro::mod_flat!(app cmp confirm input mgr pick semaphore tasks which); pub fn init() { crate::init_semaphore(); }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-proxy/src/which.rs
yazi-proxy/src/which.rs
use yazi_macro::{emit, relay}; use yazi_parser::which::ShowOpt; pub struct WhichProxy; impl WhichProxy { pub fn show(opt: ShowOpt) { emit!(Call(relay!(which:show).with_any("opt", opt))); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-proxy/src/pick.rs
yazi-proxy/src/pick.rs
use tokio::sync::oneshot; use yazi_config::popup::PickCfg; use yazi_macro::{emit, relay}; pub struct PickProxy; impl PickProxy { pub async fn show(cfg: PickCfg) -> anyhow::Result<usize> { let (tx, rx) = oneshot::channel(); emit!(Call(relay!(pick:show).with_any("tx", tx).with_any("cfg", cfg))); rx.await? } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-proxy/src/macros.rs
yazi-proxy/src/macros.rs
#[macro_export] macro_rules! deprecate { ($content:expr) => {{ static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) { $crate::emit!(Call( yazi_shared::event::Cmd::new("app:deprecate").with("content", format!($tt, id)) )); } }}; }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-proxy/src/cmp.rs
yazi-proxy/src/cmp.rs
use yazi_macro::{emit, relay}; use yazi_parser::cmp::ShowOpt; use yazi_shared::Id; pub struct CmpProxy; impl CmpProxy { pub fn show(opt: ShowOpt) { emit!(Call(relay!(cmp:show).with_any("opt", opt))); } pub fn trigger(word: impl Into<String>, ticket: Id) { emit!(Call(relay!(cmp:trigger, [word.into()]).with("ticket", ticket))); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-proxy/src/semaphore.rs
yazi-proxy/src/semaphore.rs
use tokio::sync::Semaphore; use yazi_shared::RoCell; pub static HIDER: RoCell<Semaphore> = RoCell::new(); pub(super) fn init_semaphore() { HIDER.init(Semaphore::new(1)); }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-proxy/src/confirm.rs
yazi-proxy/src/confirm.rs
use tokio::sync::oneshot; use yazi_config::popup::ConfirmCfg; use yazi_macro::{emit, relay}; pub struct ConfirmProxy; impl ConfirmProxy { pub async fn show(cfg: ConfirmCfg) -> bool { Self::show_rx(cfg).await.unwrap_or(false) } pub fn show_rx(cfg: ConfirmCfg) -> oneshot::Receiver<bool> { let (tx, rx) = oneshot::channel(); emit!(Call(relay!(confirm:show).with_any("tx", tx).with_any("cfg", cfg))); rx } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-proxy/src/input.rs
yazi-proxy/src/input.rs
use tokio::sync::mpsc; use yazi_config::popup::InputCfg; use yazi_macro::{emit, relay}; use yazi_shared::errors::InputError; pub struct InputProxy; impl InputProxy { pub fn show(cfg: InputCfg) -> mpsc::UnboundedReceiver<Result<String, InputError>> { let (tx, rx) = mpsc::unbounded_channel(); emit!(Call(relay!(input:show).with_any("tx", tx).with_any("cfg", cfg))); rx } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/icon.rs
yazi-binding/src/icon.rs
use std::ops::Deref; use mlua::{UserData, UserDataFields, Value}; use crate::{Style, cached_field}; pub struct Icon { inner: &'static yazi_config::Icon, v_text: Option<Value>, v_style: Option<Value>, } impl Deref for Icon { type Target = yazi_config::Icon; fn deref(&self) -> &Self::Target { self.inner } } impl From<&'static yazi_config::Icon> for Icon { fn from(icon: &'static yazi_config::Icon) -> Self { Self { inner: icon, v_text: None, v_style: None } } } impl UserData for Icon { fn add_fields<F: UserDataFields<Self>>(fields: &mut F) { cached_field!(fields, text, |lua, me| lua.create_string(&me.text)); cached_field!(fields, style, |_, me| Ok(Style::from(me.style))); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/stage.rs
yazi-binding/src/stage.rs
use mlua::{IntoLuaMulti, MetaMethod, UserData, UserDataMethods}; pub struct FolderStage(yazi_fs::FolderStage); impl FolderStage { pub fn new(inner: yazi_fs::FolderStage) -> Self { Self(inner) } } impl UserData for FolderStage { fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { methods.add_meta_method(MetaMethod::Call, |lua, me, ()| { use yazi_fs::FolderStage::*; match &me.0 { Loading => false.into_lua_multi(lua), Loaded => true.into_lua_multi(lua), Failed(e) => (true, crate::Error::Fs(e.clone())).into_lua_multi(lua), } }); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/path.rs
yazi-binding/src/path.rs
use std::ops::Deref; use mlua::{ExternalError, ExternalResult, FromLua, Lua, MetaMethod, UserData, UserDataFields, UserDataMethods, UserDataRef, Value}; use yazi_shared::{path::{PathBufDyn, PathLike, StripPrefixError}, strand::{AsStrand, Strand, StrandCow}}; use crate::cached_field; pub type PathRef = UserDataRef<Path>; pub struct Path { inner: PathBufDyn, v_ext: Option<Value>, v_name: Option<Value>, v_parent: Option<Value>, v_stem: Option<Value>, } impl Deref for Path { type Target = PathBufDyn; fn deref(&self) -> &Self::Target { &self.inner } } impl From<Path> for PathBufDyn { fn from(value: Path) -> Self { value.inner } } impl AsStrand for Path { fn as_strand(&self) -> Strand<'_> { self.inner.as_strand() } } impl AsStrand for &Path { fn as_strand(&self) -> Strand<'_> { self.inner.as_strand() } } impl Path { pub fn new(path: impl Into<PathBufDyn>) -> Self { Self { inner: path.into(), v_ext: None, v_name: None, v_parent: None, v_stem: None, } } fn ends_with(&self, child: Value) -> mlua::Result<bool> { match child { Value::String(s) => { self.try_ends_with(StrandCow::with(self.kind(), &*s.as_bytes())?).into_lua_err() } Value::UserData(ud) => self.try_ends_with(&*ud.borrow::<Self>()?).into_lua_err(), _ => Err("must be a string or Path".into_lua_err())?, } } fn join(&self, other: Value) -> mlua::Result<Self> { Ok(Self::new(match other { Value::String(s) => { self.try_join(StrandCow::with(self.kind(), &*s.as_bytes())?).into_lua_err()? } Value::UserData(ref ud) => { let path = ud.borrow::<Self>()?; self.try_join(&*path).into_lua_err()? } _ => Err("must be a string or Path".into_lua_err())?, })) } fn starts_with(&self, base: Value) -> mlua::Result<bool> { match base { Value::String(s) => { self.try_starts_with(StrandCow::with(self.kind(), &*s.as_bytes())?).into_lua_err() } Value::UserData(ud) => self.try_starts_with(&*ud.borrow::<Self>()?).into_lua_err(), _ => Err("must be a string or Path".into_lua_err())?, } } fn strip_prefix(&self, base: Value) -> mlua::Result<Option<Self>> { let strip = match base { Value::String(s) => self.try_strip_prefix(StrandCow::with(self.kind(), &*s.as_bytes())?), Value::UserData(ud) => self.try_strip_prefix(&*ud.borrow::<Self>()?), _ => Err("must be a string or Path".into_lua_err())?, }; Ok(match strip { Ok(p) => Some(Self::new(p)), Err(StripPrefixError::Exotic | StripPrefixError::NotPrefix) => None, Err(e @ StripPrefixError::WrongEncoding) => Err(e.into_lua_err())?, }) } } impl FromLua for Path { fn from_lua(value: Value, _: &Lua) -> mlua::Result<Self> { Ok(match value { Value::UserData(ud) => ud.take()?, _ => Err("Expected a Path".into_lua_err())?, }) } } impl UserData for Path { fn add_fields<F: UserDataFields<Self>>(fields: &mut F) { cached_field!(fields, ext, |lua, me| { me.ext().map(|s| lua.create_string(s.encoded_bytes())).transpose() }); cached_field!(fields, name, |lua, me| { me.name().map(|s| lua.create_string(s.encoded_bytes())).transpose() }); cached_field!(fields, parent, |_, me| Ok(me.parent().map(Self::new))); cached_field!(fields, stem, |lua, me| { me.stem().map(|s| lua.create_string(s.encoded_bytes())).transpose() }); fields.add_field_method_get("is_absolute", |_, me| Ok(me.is_absolute())); fields.add_field_method_get("has_root", |_, me| Ok(me.has_root())); } fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { methods.add_method("ends_with", |_, me, child: Value| me.ends_with(child)); methods.add_method("join", |_, me, other: Value| me.join(other)); methods.add_method("starts_with", |_, me, base: Value| me.starts_with(base)); methods.add_method("strip_prefix", |_, me, base: Value| me.strip_prefix(base)); methods.add_meta_method(MetaMethod::Concat, |lua, lhs, rhs: mlua::String| { lua.create_string([lhs.encoded_bytes(), &rhs.as_bytes()].concat()) }); methods.add_meta_method(MetaMethod::Eq, |_, me, other: PathRef| Ok(me.inner == other.inner)); methods .add_meta_method(MetaMethod::ToString, |lua, me, ()| lua.create_string(me.encoded_bytes())); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/lib.rs
yazi-binding/src/lib.rs
mod macros; yazi_macro::mod_pub!(elements); yazi_macro::mod_flat!(cha color composer error file handle icon id iter path permit runtime scheme stage style url utils);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/permit.rs
yazi-binding/src/permit.rs
use std::{mem, ops::Deref}; use futures::{FutureExt, future::BoxFuture}; use mlua::{UserData, prelude::LuaUserDataMethods}; use tokio::sync::SemaphorePermit; pub type PermitRef = mlua::UserDataRef<Permit>; pub struct Permit { inner: Option<SemaphorePermit<'static>>, destruct: Option<BoxFuture<'static, ()>>, } impl Deref for Permit { type Target = Option<SemaphorePermit<'static>>; fn deref(&self) -> &Self::Target { &self.inner } } impl Permit { pub fn new<F>(inner: SemaphorePermit<'static>, f: F) -> Self where F: Future<Output = ()> + 'static + Send, { Self { inner: Some(inner), destruct: Some(f.boxed()) } } fn dropping(&mut self) -> impl Future<Output = ()> + 'static { let inner = self.inner.take(); let destruct = self.destruct.take(); async move { if let Some(f) = destruct { f.await; } if let Some(p) = inner { mem::drop(p); } } } } impl Drop for Permit { fn drop(&mut self) { tokio::spawn(self.dropping()); } } impl UserData for Permit { fn add_methods<M: LuaUserDataMethods<Self>>(methods: &mut M) { methods.add_async_method_mut("drop", |_, mut me, ()| async move { Ok(me.dropping().await) }); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/id.rs
yazi-binding/src/id.rs
use std::ops::Deref; use mlua::{ExternalError, ExternalResult, FromLua, Lua, UserData, Value}; #[derive(Clone, Copy)] pub struct Id(pub yazi_shared::Id); impl Deref for Id { type Target = yazi_shared::Id; fn deref(&self) -> &Self::Target { &self.0 } } impl FromLua for Id { fn from_lua(value: Value, _: &Lua) -> mlua::Result<Self> { Ok(match value { Value::Integer(i) => Self(i.try_into().into_lua_err()?), Value::UserData(ud) => *ud.borrow::<Self>()?, _ => Err("expected integer or userdata".into_lua_err())?, }) } } impl UserData for Id { fn add_fields<F: mlua::UserDataFields<Self>>(fields: &mut F) { fields.add_field_method_get("value", |_, me| Ok(me.0.get())); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/url.rs
yazi-binding/src/url.rs
use std::ops::Deref; use mlua::{AnyUserData, ExternalError, ExternalResult, FromLua, IntoLua, Lua, MetaMethod, UserData, UserDataFields, UserDataMethods, UserDataRef, Value}; use yazi_fs::{FsHash64, FsHash128, FsUrl}; use yazi_shared::{path::{PathLike, StripPrefixError}, scheme::SchemeCow, strand::{StrandLike, ToStrand}, url::{AsUrl, UrlCow, UrlLike}}; use crate::{Path, Scheme, cached_field, deprecate}; pub type UrlRef = UserDataRef<Url>; const EXPECTED: &str = "expected a string, Url, or Path"; pub struct Url { inner: yazi_shared::url::UrlBuf, v_path: Option<Value>, v_name: Option<Value>, v_stem: Option<Value>, v_ext: Option<Value>, v_urn: Option<Value>, v_base: Option<Value>, v_parent: Option<Value>, v_scheme: Option<Value>, v_domain: Option<Value>, v_cache: Option<Value>, } impl Deref for Url { type Target = yazi_shared::url::UrlBuf; fn deref(&self) -> &Self::Target { &self.inner } } impl AsUrl for Url { fn as_url(&self) -> yazi_shared::url::Url<'_> { self.inner.as_url() } } impl AsUrl for &Url { fn as_url(&self) -> yazi_shared::url::Url<'_> { self.inner.as_url() } } impl From<Url> for yazi_shared::url::UrlBuf { fn from(value: Url) -> Self { value.inner } } impl From<Url> for yazi_shared::url::UrlBufCov { fn from(value: Url) -> Self { Self(value.inner) } } impl From<Url> for yazi_shared::url::UrlCow<'_> { fn from(value: Url) -> Self { value.inner.into() } } impl TryFrom<&[u8]> for Url { type Error = mlua::Error; fn try_from(value: &[u8]) -> mlua::Result<Self> { Ok(Self::new(UrlCow::try_from(value)?)) } } impl Url { pub fn new(url: impl Into<yazi_shared::url::UrlBuf>) -> Self { Self { inner: url.into(), v_path: None, v_name: None, v_stem: None, v_ext: None, v_urn: None, v_base: None, v_parent: None, v_scheme: None, v_domain: None, v_cache: None, } } pub fn install(lua: &Lua) -> mlua::Result<()> { lua.globals().raw_set( "Url", lua.create_function(|_, value: Value| { Ok(match value { Value::String(s) => Self::try_from(&*s.as_bytes())?, Value::UserData(ud) => { if let Ok(url) = ud.borrow::<Self>() { Self::new(&url.inner) } else if let Ok(path) = ud.borrow::<Path>() { Self::new(path.as_os().into_lua_err()?) } else { Err(EXPECTED.into_lua_err())? } } _ => Err(EXPECTED.into_lua_err())?, }) })?, ) } fn ends_with(&self, child: Value) -> mlua::Result<bool> { match child { Value::String(s) => self.try_ends_with(UrlCow::try_from(&*s.as_bytes())?).into_lua_err(), Value::UserData(ud) => self.try_ends_with(&*ud.borrow::<Self>()?).into_lua_err(), _ => Err("must be a string or Url".into_lua_err())?, } } fn hash(&self, long: Option<bool>) -> mlua::Result<String> { Ok(if long.unwrap_or(false) { format!("{:x}", self.hash_u128()) } else { format!("{:x}", self.hash_u64()) }) } fn join(&self, lua: &Lua, other: Value) -> mlua::Result<Value> { match other { Value::String(s) => { let b = s.as_bytes(); let (scheme, path) = SchemeCow::parse(&b)?; if scheme == self.scheme() { Self::new(self.try_join(path).into_lua_err()?).into_lua(lua) } else { Self::new(UrlCow::try_from((scheme, path))?).into_lua(lua) } } Value::UserData(ref ud) => { let url = ud.borrow::<Self>()?; if url.scheme() == self.scheme() { Self::new(self.try_join(url.loc()).into_lua_err()?).into_lua(lua) } else { Ok(other) } } _ => Err("must be a string or Url".into_lua_err())?, } } fn starts_with(&self, base: Value) -> mlua::Result<bool> { match base { Value::String(s) => self.try_starts_with(UrlCow::try_from(&*s.as_bytes())?).into_lua_err(), Value::UserData(ud) => self.try_starts_with(&*ud.borrow::<Self>()?).into_lua_err(), _ => Err("must be a string or Url".into_lua_err())?, } } fn strip_prefix(&self, base: Value) -> mlua::Result<Option<Path>> { let strip = match base { Value::String(s) => self.try_strip_prefix(UrlCow::try_from(&*s.as_bytes())?), Value::UserData(ud) => self.try_strip_prefix(&*ud.borrow::<Self>()?), _ => Err("must be a string or Url".into_lua_err())?, }; Ok(match strip { Ok(p) => Some(Path::new(p)), Err(StripPrefixError::Exotic | StripPrefixError::NotPrefix) => None, Err(e @ StripPrefixError::WrongEncoding) => Err(e.into_lua_err())?, }) } } impl FromLua for Url { fn from_lua(value: Value, _: &Lua) -> mlua::Result<Self> { Ok(match value { Value::UserData(ud) => ud.take()?, _ => Err("Expected a Url".into_lua_err())?, }) } } impl UserData for Url { fn add_fields<F: UserDataFields<Self>>(fields: &mut F) { cached_field!(fields, path, |_, me| Ok(Path::new(me.loc()))); cached_field!(fields, name, |lua, me| { me.name().map(|s| lua.create_string(s.encoded_bytes())).transpose() }); cached_field!(fields, stem, |lua, me| { me.stem().map(|s| lua.create_string(s.encoded_bytes())).transpose() }); cached_field!(fields, ext, |lua, me| { me.ext().map(|s| lua.create_string(s.encoded_bytes())).transpose() }); cached_field!(fields, urn, |_, me| Ok(Path::new(me.urn()))); cached_field!(fields, base, |_, me| { Ok(Some(me.base()).filter(|u| !u.loc().is_empty()).map(Self::new)) }); cached_field!(fields, parent, |_, me| Ok(me.parent().map(Self::new))); cached_field!(fields, scheme, |_, me| Ok(Scheme::new(me.scheme()))); cached_field!(fields, domain, |lua, me| { me.scheme().domain().map(|s| lua.create_string(s)).transpose() }); cached_field!(fields, cache, |_, me| Ok(me.cache().map(Path::new))); fields.add_field_method_get("frag", |lua, me| { deprecate!(lua, "`frag` property of Url is deprecated and renamed to `domain`, please use the new name instead, in your {}"); me.scheme().domain().map(|s| lua.create_string(s)).transpose() }); fields.add_field_method_get("is_regular", |_, me| Ok(me.is_regular())); fields.add_field_method_get("is_search", |_, me| Ok(me.is_search())); fields.add_field_method_get("is_archive", |_, me| Ok(me.is_archive())); fields.add_field_method_get("is_absolute", |_, me| Ok(me.is_absolute())); fields.add_field_method_get("has_root", |_, me| Ok(me.has_root())); } fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { methods.add_method("ends_with", |_, me, child: Value| me.ends_with(child)); methods.add_method("hash", |_, me, long: Option<bool>| me.hash(long)); methods.add_method("join", |lua, me, other: Value| me.join(lua, other)); methods.add_method("starts_with", |_, me, base: Value| me.starts_with(base)); methods.add_method("strip_prefix", |_, me, base: Value| me.strip_prefix(base)); methods.add_function_mut("into_search", |_, (ud, domain): (AnyUserData, mlua::String)| { let url = ud.take::<Self>()?.inner.into_search(domain.to_str()?).into_lua_err()?; Ok(Self::new(url)) }); methods.add_meta_method(MetaMethod::Eq, |_, me, other: UrlRef| Ok(me.inner == other.inner)); methods.add_meta_method(MetaMethod::ToString, |lua, me, ()| { lua.create_string(me.to_strand().encoded_bytes()) }); methods.add_meta_method(MetaMethod::Concat, |lua, lhs, rhs: mlua::String| { lua.create_string([lhs.to_strand().encoded_bytes(), &rhs.as_bytes()].concat()) }); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/error.rs
yazi-binding/src/error.rs
use std::{borrow::Cow, fmt::Display}; use mlua::{ExternalError, FromLua, Lua, MetaMethod, UserData, UserDataFields, UserDataMethods, Value}; use yazi_shared::SStr; const EXPECTED: &str = "expected a Error"; pub enum Error { Io(std::io::Error), Fs(yazi_fs::error::Error), Serde(serde_json::Error), Custom(SStr), } impl Error { pub fn install(lua: &Lua) -> mlua::Result<()> { let custom = lua.create_function(|_, msg: String| Ok(Self::custom(msg)))?; let fs = lua.create_function(|_, value: Value| { Ok(Self::Fs(match value { Value::Table(t) => yazi_fs::error::Error::custom( &t.raw_get::<mlua::String>("kind")?.to_str()?, t.raw_get("code")?, &t.raw_get::<mlua::String>("message")?.to_str()?, )?, _ => Err("expected a table".into_lua_err())?, })) })?; lua.globals().raw_set("Error", lua.create_table_from([("custom", custom), ("fs", fs)])?) } pub fn custom(msg: impl Into<SStr>) -> Self { Self::Custom(msg.into()) } pub fn into_string(self) -> SStr { match self { Self::Io(e) => Cow::Owned(e.to_string()), Self::Fs(e) => Cow::Owned(e.to_string()), Self::Serde(e) => Cow::Owned(e.to_string()), Self::Custom(s) => s, } } } impl Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Io(e) => write!(f, "{e}"), Self::Fs(e) => write!(f, "{e}"), Self::Serde(e) => write!(f, "{e}"), Self::Custom(s) => write!(f, "{s}"), } } } impl FromLua for Error { fn from_lua(value: Value, _: &Lua) -> mlua::Result<Self> { match value { Value::UserData(ud) => ud.take(), _ => Err(EXPECTED.into_lua_err()), } } } impl UserData for Error { fn add_fields<F: UserDataFields<Self>>(fields: &mut F) { fields.add_field_method_get("code", |_, me| { Ok(match me { Self::Io(e) => e.raw_os_error(), Self::Fs(e) => e.raw_os_error(), _ => None, }) }); fields.add_field_method_get("kind", |_, me| { Ok(match me { Self::Io(e) => Some(yazi_fs::error::Error::from(e.kind()).kind_str()), Self::Fs(e) => Some(e.kind_str()), _ => None, }) }); } fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { methods.add_meta_method(MetaMethod::ToString, |lua, me, ()| { Ok(match me { Self::Io(_) | Self::Fs(_) | Self::Serde(_) => lua.create_string(me.to_string()), Self::Custom(s) => lua.create_string(&**s), }) }); methods.add_meta_function(MetaMethod::Concat, |lua, (lhs, rhs): (Value, Value)| { match (lhs, rhs) { (Value::String(l), Value::UserData(r)) => { let r = r.borrow::<Self>()?; lua.create_string([&l.as_bytes(), r.to_string().as_bytes()].concat()) } (Value::UserData(l), Value::String(r)) => { let l = l.borrow::<Self>()?; lua.create_string([l.to_string().as_bytes(), &r.as_bytes()].concat()) } _ => Err("only string can be concatenated with Error".into_lua_err()), } }); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/file.rs
yazi-binding/src/file.rs
use std::ops::Deref; use mlua::{AnyUserData, ExternalError, FromLua, Lua, ObjectLike, Table, UserData, UserDataFields, UserDataMethods, UserDataRef, Value}; use crate::{Cha, Url, impl_file_fields, impl_file_methods}; pub type FileRef = UserDataRef<File>; const EXPECTED: &str = "expected a table, File, or fs::File"; #[derive(Clone)] pub struct File { inner: yazi_fs::File, v_cha: Option<Value>, v_url: Option<Value>, v_link_to: Option<Value>, v_name: Option<Value>, v_path: Option<Value>, v_cache: Option<Value>, } impl Deref for File { type Target = yazi_fs::File; fn deref(&self) -> &Self::Target { &self.inner } } impl From<File> for yazi_fs::File { fn from(value: File) -> Self { value.inner } } impl File { pub fn new(inner: impl Into<yazi_fs::File>) -> Self { Self { inner: inner.into(), v_cha: None, v_url: None, v_link_to: None, v_name: None, v_path: None, v_cache: None, } } pub fn install(lua: &Lua) -> mlua::Result<()> { lua.globals().raw_set("File", lua.create_function(|_, value: Value| Self::try_from(value))?) } } impl TryFrom<Value> for File { type Error = mlua::Error; fn try_from(value: Value) -> Result<Self, Self::Error> { match value { Value::Table(tbl) => Self::try_from(tbl), Value::UserData(ud) => Self::try_from(ud), _ => Err(EXPECTED.into_lua_err())?, } } } impl TryFrom<Table> for File { type Error = mlua::Error; fn try_from(value: Table) -> Result<Self, Self::Error> { Ok(Self::new(yazi_fs::File { url: value.raw_get::<Url>("url")?.into(), cha: *value.raw_get::<Cha>("cha")?, ..Default::default() })) } } impl TryFrom<AnyUserData> for File { type Error = mlua::Error; fn try_from(value: AnyUserData) -> Result<Self, Self::Error> { Ok(if let Ok(me) = value.borrow::<Self>() { me.clone() } else { value.get("bare")? }) } } impl FromLua for File { fn from_lua(value: Value, _: &Lua) -> mlua::Result<Self> { Ok(match value { Value::UserData(ud) => Self::new(ud.take::<Self>()?.inner), _ => Err("expected a File".into_lua_err())?, }) } } impl UserData for File { fn add_fields<F: UserDataFields<Self>>(fields: &mut F) { impl_file_fields!(fields); } fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { impl_file_methods!(methods); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/utils.rs
yazi-binding/src/utils.rs
use mlua::{IntoLua, Lua, SerializeOptions, Table, Value}; pub const SER_OPT: SerializeOptions = SerializeOptions::new().serialize_none_to_null(false).serialize_unit_to_null(false); pub fn get_metatable(lua: &Lua, value: impl IntoLua) -> mlua::Result<Table> { let (_, mt): (Value, Table) = unsafe { lua.exec_raw(value.into_lua(lua)?, |state| { mlua::ffi::lua_getmetatable(state, -1); }) }?; Ok(mt) }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/runtime.rs
yazi-binding/src/runtime.rs
use std::collections::VecDeque; use hashbrown::HashMap; use mlua::Function; #[derive(Debug)] pub struct Runtime { frames: VecDeque<RuntimeFrame>, blocks: HashMap<String, Vec<Function>>, pub initing: bool, } #[derive(Debug)] struct RuntimeFrame { id: String, calls: usize, } impl Runtime { pub fn new() -> Self { Self { frames: <_>::default(), blocks: <_>::default(), initing: true } } pub fn new_isolate(id: &str) -> Self { Self { frames: VecDeque::from([RuntimeFrame { id: id.to_owned(), calls: 0 }]), blocks: <_>::default(), initing: false, } } pub fn push(&mut self, id: &str) { self.frames.push_back(RuntimeFrame { id: id.to_owned(), calls: 0 }); } pub fn pop(&mut self) { self.frames.pop_back(); } pub fn current(&self) -> Option<&str> { self.frames.back().map(|f| f.id.as_str()) } pub fn current_owned(&self) -> Option<String> { self.current().map(ToOwned::to_owned) } pub fn next_block(&mut self) -> Option<usize> { self.frames.back_mut().map(|f| { f.calls += 1; f.calls - 1 }) } pub fn get_block(&self, id: &str, calls: usize) -> Option<Function> { self.blocks.get(id).and_then(|v| v.get(calls)).cloned() } pub fn put_block(&mut self, f: Function) -> bool { let Some(cur) = self.frames.back() else { return false }; if let Some(v) = self.blocks.get_mut(&cur.id) { v.push(f); } else { self.blocks.insert(cur.id.clone(), vec![f]); } true } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/macros.rs
yazi-binding/src/macros.rs
#[macro_export] macro_rules! runtime { ($lua:ident) => {{ use mlua::ExternalError; $lua.app_data_ref::<$crate::Runtime>().ok_or_else(|| "Runtime not found".into_lua_err()) }}; } #[macro_export] macro_rules! runtime_mut { ($lua:ident) => {{ use mlua::ExternalError; $lua.app_data_mut::<$crate::Runtime>().ok_or_else(|| "Runtime not found".into_lua_err()) }}; } #[macro_export] macro_rules! deprecate { ($lua:ident, $tt:tt) => {{ static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) { let id = match $crate::runtime!($lua)?.current() { Some(id) => &format!("`{id}.yazi` plugin"), None => "`init.lua` config", }; yazi_macro::emit!(Call( yazi_macro::relay!(app:deprecate).with("content", format!($tt, id)) )); } }}; } #[macro_export] macro_rules! cached_field { ($fields:ident, $key:ident, $value:expr) => { $fields.add_field_function_get(stringify!($key), |lua, ud| { use mlua::{Error::UserDataDestructed, IntoLua, Lua, Result, Value, Value::UserData}; ud.borrow_mut_scoped::<Self, Result<Value>>(|me| match paste::paste! { &me.[<v_ $key>] } { Some(v) if !v.is_userdata() => Ok(v.clone()), Some(v @ UserData(ud)) if !matches!(ud.borrow::<()>(), Err(UserDataDestructed)) => { Ok(v.clone()) } _ => { let v = ($value as fn(&Lua, &Self) -> Result<_>)(lua, me)?.into_lua(lua)?; paste::paste! { me.[<v_ $key>] = Some(v.clone()) }; Ok(v) } })? }); }; } #[macro_export] macro_rules! impl_area_method { ($methods:ident) => { $methods.add_function_mut( "area", |lua, (ud, area): (mlua::AnyUserData, Option<mlua::AnyUserData>)| { use mlua::IntoLua; if let Some(v) = area { ud.borrow_mut::<Self>()?.area = $crate::elements::Area::try_from(v)?; ud.into_lua(lua) } else { ud.borrow::<Self>()?.area.into_lua(lua) } }, ); }; } #[macro_export] macro_rules! impl_style_method { ($methods:ident, $($field:tt).+) => { $methods.add_function_mut("style", |_, (ud, value): (mlua::AnyUserData, mlua::Value)| { ud.borrow_mut::<Self>()?.$($field).+ = $crate::Style::try_from(value)?.0; Ok(ud) }); }; } #[macro_export] macro_rules! impl_style_shorthands { ($methods:ident, $($field:tt).+) => { $methods.add_function_mut("fg", |lua, (ud, value): (mlua::AnyUserData, mlua::Value)| { use ratatui::style::Modifier; let me = &mut ud.borrow_mut::<Self>()?.$($field).+; match value { mlua::Value::Boolean(true) if me.add_modifier.contains(Modifier::REVERSED) && !me.sub_modifier.contains(Modifier::REVERSED) => { me.bg.map($crate::Color).into_lua(lua) } mlua::Value::Nil | mlua::Value::Boolean(_) => { me.fg.map($crate::Color).into_lua(lua) } _ => { me.fg = Some($crate::Color::try_from(value)?.0); ud.into_lua(lua) } } }); $methods.add_function_mut("bg", |lua, (ud, value): (mlua::AnyUserData, mlua::Value)| { use ratatui::style::Modifier; let me = &mut ud.borrow_mut::<Self>()?.$($field).+; match value { mlua::Value::Boolean(true) if me.add_modifier.contains(Modifier::REVERSED) && !me.sub_modifier.contains(Modifier::REVERSED) => { me.fg.map($crate::Color).into_lua(lua) } mlua::Value::Nil | mlua::Value::Boolean(_) => { me.bg.map($crate::Color).into_lua(lua) } _ => { me.bg = Some($crate::Color::try_from(value)?.0); ud.into_lua(lua) } } }); $methods.add_function_mut("bold", |_, (ud, remove): (mlua::AnyUserData, bool)| { let me = &mut ud.borrow_mut::<Self>()?.$($field).+; if remove { *me = me.remove_modifier(ratatui::style::Modifier::BOLD); } else { *me = me.add_modifier(ratatui::style::Modifier::BOLD); } Ok(ud) }); $methods.add_function_mut("dim", |_, (ud, remove): (mlua::AnyUserData, bool)| { let me = &mut ud.borrow_mut::<Self>()?.$($field).+; if remove { *me = me.remove_modifier(ratatui::style::Modifier::DIM); } else { *me = me.add_modifier(ratatui::style::Modifier::DIM); } Ok(ud) }); $methods.add_function_mut("italic", |_, (ud, remove): (mlua::AnyUserData, bool)| { let me = &mut ud.borrow_mut::<Self>()?.$($field).+; if remove { *me = me.remove_modifier(ratatui::style::Modifier::ITALIC); } else { *me = me.add_modifier(ratatui::style::Modifier::ITALIC); } Ok(ud) }); $methods.add_function_mut("underline", |_, (ud, remove): (mlua::AnyUserData, bool)| { let me = &mut ud.borrow_mut::<Self>()?.$($field).+; if remove { *me = me.remove_modifier(ratatui::style::Modifier::UNDERLINED); } else { *me = me.add_modifier(ratatui::style::Modifier::UNDERLINED); } Ok(ud) }); $methods.add_function_mut("blink", |_, (ud, remove): (mlua::AnyUserData, bool)| { let me = &mut ud.borrow_mut::<Self>()?.$($field).+; if remove { *me = me.remove_modifier(ratatui::style::Modifier::SLOW_BLINK); } else { *me = me.add_modifier(ratatui::style::Modifier::SLOW_BLINK); } Ok(ud) }); $methods.add_function_mut("blink_rapid", |_, (ud, remove): (mlua::AnyUserData, bool)| { let me = &mut ud.borrow_mut::<Self>()?.$($field).+; if remove { *me = me.remove_modifier(ratatui::style::Modifier::RAPID_BLINK); } else { *me = me.add_modifier(ratatui::style::Modifier::RAPID_BLINK); } Ok(ud) }); $methods.add_function_mut("reverse", |_, (ud, remove): (mlua::AnyUserData, bool)| { let me = &mut ud.borrow_mut::<Self>()?.$($field).+; if remove { *me = me.remove_modifier(ratatui::style::Modifier::REVERSED); } else { *me = me.add_modifier(ratatui::style::Modifier::REVERSED); } Ok(ud) }); $methods.add_function_mut("hidden", |_, (ud, remove): (mlua::AnyUserData, bool)| { let me = &mut ud.borrow_mut::<Self>()?.$($field).+; if remove { *me = me.remove_modifier(ratatui::style::Modifier::HIDDEN); } else { *me = me.add_modifier(ratatui::style::Modifier::HIDDEN); } Ok(ud) }); $methods.add_function_mut("crossed", |_, (ud, remove): (mlua::AnyUserData, bool)| { let me = &mut ud.borrow_mut::<Self>()?.$($field).+; if remove { *me = me.remove_modifier(ratatui::style::Modifier::CROSSED_OUT); } else { *me = me.add_modifier(ratatui::style::Modifier::CROSSED_OUT); } Ok(ud) }); $methods.add_function_mut("reset", |_, ud: mlua::AnyUserData| { ud.borrow_mut::<Self>()?.$($field).+ = ratatui::style::Style::reset(); Ok(ud) }); }; } #[macro_export] macro_rules! impl_file_fields { ($fields:ident) => { $crate::cached_field!($fields, cha, |_, me| Ok($crate::Cha(me.cha))); $crate::cached_field!($fields, url, |_, me| Ok($crate::Url::new(me.url_owned()))); $crate::cached_field!($fields, link_to, |_, me| Ok(me.link_to.as_ref().map($crate::Path::new))); $crate::cached_field!($fields, name, |lua, me| { me.name().map(|s| lua.create_string(s.encoded_bytes())).transpose() }); $crate::cached_field!($fields, path, |_, me| { use yazi_fs::FsUrl; use yazi_shared::url::AsUrl; Ok($crate::Path::new(me.url.as_url().unified_path())) }); $crate::cached_field!($fields, cache, |_, me| { use yazi_fs::FsUrl; Ok(me.url.cache().map($crate::Path::new)) }); }; } #[macro_export] macro_rules! impl_file_methods { ($methods:ident) => { $methods.add_method("hash", |_, me, ()| { use yazi_fs::FsHash64; Ok(me.hash_u64()) }); $methods.add_method("icon", |_, me, ()| { use $crate::Icon; // TODO: use a cache Ok(yazi_config::THEME.icon.matches(me).map(Icon::from)) }); }; }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/style.rs
yazi-binding/src/style.rs
use mlua::{AnyUserData, ExternalError, IntoLua, Lua, LuaSerdeExt, MetaMethod, Table, UserData, UserDataMethods, Value}; use crate::SER_OPT; #[derive(Clone, Copy, Default)] pub struct Style(pub ratatui::style::Style); impl Style { pub fn compose(lua: &Lua) -> mlua::Result<Value> { let new = lua.create_function(|_, (_, value): (Table, Value)| Self::try_from(value))?; let style = lua.create_table()?; style.set_metatable(Some(lua.create_table_from([(MetaMethod::Call.name(), new)])?))?; style.into_lua(lua) } } impl TryFrom<Value> for Style { type Error = mlua::Error; fn try_from(value: Value) -> Result<Self, Self::Error> { Ok(Self(match value { Value::Nil => Default::default(), Value::UserData(ud) => ud.borrow::<Self>()?.0, _ => Err("expected a Style or nil".into_lua_err())?, })) } } impl From<yazi_config::Style> for Style { fn from(value: yazi_config::Style) -> Self { Self(value.into()) } } impl UserData for Style { fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { crate::impl_style_shorthands!(methods, 0); methods .add_method("raw", |lua, me, ()| lua.to_value_with(&yazi_config::Style::from(me.0), SER_OPT)); methods.add_function_mut("patch", |_, (ud, value): (AnyUserData, Value)| { { let mut me = ud.borrow_mut::<Self>()?; me.0 = me.0.patch(Self::try_from(value)?.0); } Ok(ud) }) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/composer.rs
yazi-binding/src/composer.rs
use hashbrown::HashMap; use mlua::{Lua, MetaMethod, UserData, UserDataMethods, Value}; pub type ComposerGet = fn(&Lua, &[u8]) -> mlua::Result<Value>; pub type ComposerSet = fn(&Lua, &[u8], Value) -> mlua::Result<Value>; pub struct Composer<G, S> { get: G, set: S, parent: Option<(G, S)>, cache: HashMap<Vec<u8>, Value>, } impl<G, S> Composer<G, S> where G: Fn(&Lua, &[u8]) -> mlua::Result<Value> + 'static, S: Fn(&Lua, &[u8], Value) -> mlua::Result<Value> + 'static, { #[inline] pub fn new(get: G, set: S) -> Self { Self { get, set, parent: None, cache: Default::default() } } #[inline] pub fn with_parent(get: G, set: S, p_get: G, p_set: S) -> Self { Self { get, set, parent: Some((p_get, p_set)), cache: Default::default() } } } impl<G, S> UserData for Composer<G, S> where G: Fn(&Lua, &[u8]) -> mlua::Result<Value> + 'static, S: Fn(&Lua, &[u8], Value) -> mlua::Result<Value> + 'static, { fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { methods.add_meta_method_mut(MetaMethod::Index, |lua, me, key: mlua::String| { let key = key.as_bytes(); if let Some(v) = me.cache.get(key.as_ref()) { return Ok(v.clone()); } let mut value = (me.get)(lua, &key)?; if value.is_nil() && let Some((p_get, _)) = &me.parent { value = p_get(lua, &key)?; } me.cache.insert(key.to_owned(), value.clone()); Ok(value) }); methods.add_meta_method_mut( MetaMethod::NewIndex, |lua, me, (key, value): (mlua::String, Value)| { let key = key.as_bytes(); let value = (me.set)(lua, key.as_ref(), value)?; if value.is_nil() { me.cache.remove(key.as_ref()); } else if let Some((_, p_set)) = &me.parent { match p_set(lua, key.as_ref(), value)? { Value::Nil => me.cache.remove(key.as_ref()), v => me.cache.insert(key.to_owned(), v), }; } else { me.cache.insert(key.to_owned(), value); } Ok(()) }, ); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/scheme.rs
yazi-binding/src/scheme.rs
use std::ops::Deref; use mlua::{UserData, UserDataFields, Value}; use yazi_fs::FsScheme; use yazi_shared::scheme::SchemeLike; use crate::{Path, cached_field}; pub struct Scheme { inner: yazi_shared::scheme::Scheme, v_kind: Option<Value>, v_cache: Option<Value>, } impl Deref for Scheme { type Target = yazi_shared::scheme::Scheme; fn deref(&self) -> &Self::Target { &self.inner } } impl Scheme { pub fn new(scheme: impl Into<yazi_shared::scheme::Scheme>) -> Self { Self { inner: scheme.into(), v_kind: None, v_cache: None } } } impl UserData for Scheme { fn add_fields<F: UserDataFields<Self>>(fields: &mut F) { cached_field!(fields, kind, |_, me| Ok(me.kind().as_str())); cached_field!(fields, cache, |_, me| Ok(me.cache().map(Path::new))); fields.add_field_method_get("is_virtual", |_, me| Ok(me.is_virtual())); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/cha.rs
yazi-binding/src/cha.rs
use std::{ops::Deref, time::{Duration, SystemTime}}; use mlua::{ExternalError, FromLua, IntoLua, Lua, Table, UserData, UserDataFields, UserDataMethods}; use yazi_fs::{FsHash128, cha::{ChaKind, ChaMode}}; #[derive(Clone, Copy, FromLua)] pub struct Cha(pub yazi_fs::cha::Cha); impl Deref for Cha { type Target = yazi_fs::cha::Cha; fn deref(&self) -> &Self::Target { &self.0 } } impl Cha { pub fn install(lua: &Lua) -> mlua::Result<()> { fn parse_time(f: Option<f64>) -> mlua::Result<Option<SystemTime>> { Ok(match f { Some(n) if n >= 0.0 => Some(SystemTime::UNIX_EPOCH + Duration::from_secs_f64(n)), Some(n) => Err(format!("Invalid timestamp: {n}").into_lua_err())?, None => None, }) } lua.globals().raw_set( "Cha", lua.create_function(|lua, t: Table| { let kind = ChaKind::from_bits(t.raw_get("kind").unwrap_or_default()) .ok_or_else(|| "Invalid kind".into_lua_err())?; let mode = ChaMode::try_from(t.raw_get::<u16>("mode")?)?; Self(yazi_fs::cha::Cha { kind, mode, len: t.raw_get("len").unwrap_or_default(), atime: parse_time(t.raw_get("atime").ok())?, btime: parse_time(t.raw_get("btime").ok())?, ctime: parse_time(t.raw_get("ctime").ok())?, mtime: parse_time(t.raw_get("mtime").ok())?, dev: t.raw_get("dev").unwrap_or_default(), uid: t.raw_get("uid").unwrap_or_default(), gid: t.raw_get("gid").unwrap_or_default(), nlink: t.raw_get("nlink").unwrap_or_default(), }) .into_lua(lua) })?, ) } } impl UserData for Cha { fn add_fields<F: UserDataFields<Self>>(fields: &mut F) { fields.add_field_method_get("mode", |_, me| Ok(me.mode.bits())); fields.add_field_method_get("is_dir", |_, me| Ok(me.is_dir())); fields.add_field_method_get("is_hidden", |_, me| Ok(me.is_hidden())); fields.add_field_method_get("is_link", |_, me| Ok(me.is_link())); fields.add_field_method_get("is_orphan", |_, me| Ok(me.is_orphan())); fields.add_field_method_get("is_dummy", |_, me| Ok(me.is_dummy())); fields.add_field_method_get("is_block", |_, me| Ok(me.is_block())); fields.add_field_method_get("is_char", |_, me| Ok(me.is_char())); fields.add_field_method_get("is_fifo", |_, me| Ok(me.is_fifo())); fields.add_field_method_get("is_sock", |_, me| Ok(me.is_sock())); fields.add_field_method_get("is_exec", |_, me| Ok(me.is_exec())); fields.add_field_method_get("is_sticky", |_, me| Ok(me.is_sticky())); fields.add_field_method_get("len", |_, me| Ok(me.len)); fields.add_field_method_get("atime", |_, me| Ok(me.atime_dur().ok().map(|d| d.as_secs_f64()))); fields.add_field_method_get("btime", |_, me| Ok(me.btime_dur().ok().map(|d| d.as_secs_f64()))); fields.add_field_method_get("ctime", |_, me| Ok(me.ctime_dur().ok().map(|d| d.as_secs_f64()))); fields.add_field_method_get("mtime", |_, me| Ok(me.mtime_dur().ok().map(|d| d.as_secs_f64()))); fields.add_field_method_get("dev", |_, me| Ok(me.dev)); fields.add_field_method_get("uid", |_, me| Ok(me.uid)); fields.add_field_method_get("gid", |_, me| Ok(me.gid)); fields.add_field_method_get("nlink", |_, me| Ok(me.nlink)); } fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { methods.add_method("hash", |_, me, long: Option<bool>| { Ok(if long.unwrap_or(false) { format!("{:x}", me.hash_u128()) } else { Err("Short hash not supported".into_lua_err())? }) }); methods.add_method("perm", |lua, _me, ()| { Ok( #[cfg(unix)] lua.create_string(_me.mode.permissions(_me.is_dummy())), #[cfg(windows)] Ok::<_, mlua::Error>(mlua::Value::Nil), ) }); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/color.rs
yazi-binding/src/color.rs
use std::str::FromStr; use mlua::{ExternalError, ExternalResult, UserData, Value}; #[derive(Clone, Copy, Default)] pub struct Color(pub ratatui::style::Color); impl TryFrom<Value> for Color { type Error = mlua::Error; fn try_from(value: Value) -> Result<Self, Self::Error> { Ok(Self(match value { Value::String(s) => ratatui::style::Color::from_str(&s.to_str()?).into_lua_err()?, Value::UserData(ud) => ud.borrow::<Self>()?.0, _ => Err("expected a Color".into_lua_err())?, })) } } impl UserData for Color {}
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/iter.rs
yazi-binding/src/iter.rs
use mlua::{AnyUserData, ExternalError, FromLua, IntoLua, IntoLuaMulti, Lua, MetaMethod, UserData, UserDataMethods, UserDataRefMut, Value}; pub struct Iter<I: Iterator<Item = T>, T> { iter: I, len: Option<usize>, count: usize, cache: Vec<Value>, } impl<I, T> Iter<I, T> where I: Iterator<Item = T> + 'static, T: IntoLua + 'static, { pub fn new(iter: I, len: Option<usize>) -> Self { Self { iter, len, count: 0, cache: vec![] } } } impl<I, T> Iter<I, T> where I: Iterator<Item = T> + 'static, T: FromLua + 'static, { pub fn into_iter(self, lua: &Lua) -> impl Iterator<Item = mlua::Result<T>> { self .cache .into_iter() .map(|cached| T::from_lua(cached, lua)) .chain(self.iter.map(|rest| Ok(rest))) } } impl<I, T> UserData for Iter<I, T> where I: Iterator<Item = T> + 'static, T: IntoLua + 'static, { fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { methods.add_meta_method(MetaMethod::Len, |_, me, ()| { if let Some(len) = me.len { Ok(len) } else { Err(format!("Length is unknown for {}", std::any::type_name::<Self>()).into_lua_err()) } }); methods.add_meta_function(MetaMethod::Pairs, |lua, ud: AnyUserData| { let iter = lua.create_function(|lua, mut me: UserDataRefMut<Self>| { if let Some(next) = me.cache.get(me.count).cloned() { me.count += 1; (me.count, next).into_lua_multi(lua) } else if let Some(next) = me.iter.next() { let value = next.into_lua(lua)?; me.cache.push(value.clone()); me.count += 1; (me.count, value).into_lua_multi(lua) } else { ().into_lua_multi(lua) } })?; ud.borrow_mut::<Self>()?.count = 0; Ok((iter, ud)) }); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/handle.rs
yazi-binding/src/handle.rs
use mlua::{MultiValue, UserData, UserDataMethods}; use tokio::task::JoinHandle; pub enum Handle { AsyncFn(JoinHandle<mlua::Result<MultiValue>>), } impl UserData for Handle { fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { methods.add_method("abort", |_, me, ()| { Ok(match me { Self::AsyncFn(h) => h.abort(), }) }); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/gauge.rs
yazi-binding/src/elements/gauge.rs
use mlua::{AnyUserData, ExternalError, IntoLua, Lua, MetaMethod, Table, UserData, UserDataMethods, Value}; use ratatui::widgets::Widget; use super::{Area, Span}; use crate::Style; #[derive(Clone, Debug, Default)] pub struct Gauge { pub(super) area: Area, ratio: f64, label: Option<ratatui::text::Span<'static>>, style: ratatui::style::Style, gauge_style: ratatui::style::Style, } impl Gauge { pub fn compose(lua: &Lua) -> mlua::Result<Value> { let new = lua.create_function(|_, _: Table| Ok(Self::default()))?; let gauge = lua.create_table()?; gauge.set_metatable(Some(lua.create_table_from([(MetaMethod::Call.name(), new)])?))?; gauge.into_lua(lua) } pub(super) fn render(self, rect: ratatui::layout::Rect, buf: &mut ratatui::buffer::Buffer) { let mut gauge = ratatui::widgets::Gauge::default() .ratio(self.ratio) .style(self.style) .gauge_style(self.gauge_style); if let Some(s) = self.label { gauge = gauge.label(s) } gauge.render(rect, buf); } } impl UserData for Gauge { fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { crate::impl_area_method!(methods); crate::impl_style_method!(methods, style); methods.add_function_mut("percent", |_, (ud, percent): (AnyUserData, u8)| { if percent > 100 { return Err("percent must be between 0 and 100".into_lua_err()); } ud.borrow_mut::<Self>()?.ratio = percent as f64 / 100.0; Ok(ud) }); methods.add_function_mut("ratio", |_, (ud, ratio): (AnyUserData, f64)| { if !(0.0..1.0).contains(&ratio) { return Err("ratio must be between 0 and 1".into_lua_err()); } ud.borrow_mut::<Self>()?.ratio = ratio; Ok(ud) }); methods.add_function_mut("label", |_, (ud, label): (AnyUserData, Value)| { ud.borrow_mut::<Self>()?.label = Some(Span::try_from(label)?.0); Ok(ud) }); methods.add_function_mut("gauge_style", |_, (ud, value): (AnyUserData, Value)| { ud.borrow_mut::<Self>()?.gauge_style = Style::try_from(value)?.0; Ok(ud) }); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/edge.rs
yazi-binding/src/elements/edge.rs
use std::ops::Deref; use mlua::{FromLua, IntoLua, Lua, Value}; use ratatui::widgets::Borders; #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub struct Edge(pub Borders); impl Deref for Edge { type Target = Borders; fn deref(&self) -> &Self::Target { &self.0 } } impl Edge { pub fn compose(lua: &Lua) -> mlua::Result<Value> { lua .create_table_from([ ("NONE", Borders::NONE.bits()), ("TOP", Borders::TOP.bits()), ("RIGHT", Borders::RIGHT.bits()), ("BOTTOM", Borders::BOTTOM.bits()), ("LEFT", Borders::LEFT.bits()), ("ALL", Borders::ALL.bits()), ])? .into_lua(lua) } } impl FromLua for Edge { fn from_lua(value: Value, _: &Lua) -> mlua::Result<Self> { let Value::Integer(n) = value else { return Err(mlua::Error::FromLuaConversionError { from: value.type_name(), to: "Edge".to_string(), message: Some("expected an integer representation of an Edge".to_string()), }); }; let Ok(Some(b)) = u8::try_from(n).map(Borders::from_bits) else { return Err(mlua::Error::FromLuaConversionError { from: value.type_name(), to: "Edge".to_string(), message: Some("invalid bits for Edge".to_string()), }); }; Ok(Self(b)) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/pad.rs
yazi-binding/src/elements/pad.rs
use std::ops::{Add, AddAssign, Deref}; use mlua::{FromLua, IntoLua, Lua, MetaMethod, Table, UserData, Value}; #[derive(Clone, Copy, Default, FromLua)] pub struct Pad(ratatui::widgets::Padding); impl Deref for Pad { type Target = ratatui::widgets::Padding; fn deref(&self) -> &Self::Target { &self.0 } } impl From<ratatui::widgets::Padding> for Pad { fn from(pad: ratatui::widgets::Padding) -> Self { Self(pad) } } impl Pad { pub fn compose(lua: &Lua) -> mlua::Result<Value> { let new = lua.create_function(|_, (_, top, right, bottom, left): (Table, u16, u16, u16, u16)| { Ok(Self(ratatui::widgets::Padding::new(left, right, top, bottom))) })?; let pad = lua.create_table_from([ ( "left", lua.create_function(|_, left: u16| Ok(Self(ratatui::widgets::Padding::left(left))))?, ), ( "right", lua.create_function(|_, right: u16| Ok(Self(ratatui::widgets::Padding::right(right))))?, ), ("top", lua.create_function(|_, top: u16| Ok(Self(ratatui::widgets::Padding::top(top))))?), ( "bottom", lua .create_function(|_, bottom: u16| Ok(Self(ratatui::widgets::Padding::bottom(bottom))))?, ), ("x", lua.create_function(|_, x: u16| Ok(Self(ratatui::widgets::Padding::new(x, x, 0, 0))))?), ("y", lua.create_function(|_, y: u16| Ok(Self(ratatui::widgets::Padding::new(0, 0, y, y))))?), ( "xy", lua .create_function(|_, xy: u16| Ok(Self(ratatui::widgets::Padding::new(xy, xy, xy, xy))))?, ), ])?; pad.set_metatable(Some(lua.create_table_from([(MetaMethod::Call.name(), new)])?))?; pad.into_lua(lua) } } impl UserData for Pad { fn add_fields<F: mlua::UserDataFields<Self>>(fields: &mut F) { fields.add_field_method_get("left", |_, me| Ok(me.left)); fields.add_field_method_get("right", |_, me| Ok(me.right)); fields.add_field_method_get("top", |_, me| Ok(me.top)); fields.add_field_method_get("bottom", |_, me| Ok(me.bottom)); } } impl Add<ratatui::widgets::Padding> for Pad { type Output = Self; fn add(self, rhs: ratatui::widgets::Padding) -> Self::Output { Self(ratatui::widgets::Padding::new( self.left.saturating_add(rhs.left), self.right.saturating_add(rhs.right), self.top.saturating_add(rhs.top), self.bottom.saturating_add(rhs.bottom), )) } } impl AddAssign<ratatui::widgets::Padding> for Pad { fn add_assign(&mut self, rhs: ratatui::widgets::Padding) { *self = *self + rhs; } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/list.rs
yazi-binding/src/elements/list.rs
use mlua::{ExternalError, IntoLua, Lua, MetaMethod, Table, UserData, Value}; use ratatui::widgets::Widget; use super::{Area, Text}; const EXPECTED: &str = "expected a table of strings, Texts, Lines or Spans"; // --- List #[derive(Clone, Debug, Default)] pub struct List { pub(super) area: Area, inner: ratatui::widgets::List<'static>, } impl List { pub fn compose(lua: &Lua) -> mlua::Result<Value> { let new = lua.create_function(|_, (_, seq): (Table, Table)| { let mut items = Vec::with_capacity(seq.raw_len()); for v in seq.sequence_values::<Value>() { items.push(Text::try_from(v?).map_err(|_| EXPECTED.into_lua_err())?); } Ok(Self { inner: ratatui::widgets::List::new(items), ..Default::default() }) })?; let list = lua.create_table()?; list.set_metatable(Some(lua.create_table_from([(MetaMethod::Call.name(), new)])?))?; list.into_lua(lua) } pub(super) fn render(self, rect: ratatui::layout::Rect, buf: &mut ratatui::buffer::Buffer) { self.inner.render(rect, buf); } } impl UserData for List { fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) { crate::impl_area_method!(methods); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/row.rs
yazi-binding/src/elements/row.rs
use mlua::{AnyUserData, ExternalError, IntoLua, Lua, MetaMethod, Table, UserData, Value}; use super::Cell; const EXPECTED: &str = "expected a Row"; #[derive(Clone, Debug, Default)] pub struct Row { pub(super) cells: Vec<Cell>, height: u16, top_margin: u16, bottom_margin: u16, style: ratatui::style::Style, } impl Row { pub fn compose(lua: &Lua) -> mlua::Result<Value> { let new = lua.create_function(|_, (_, cells): (Table, Vec<Cell>)| { Ok(Self { cells, ..Default::default() }) })?; let row = lua.create_table()?; row.set_metatable(Some(lua.create_table_from([(MetaMethod::Call.name(), new)])?))?; row.into_lua(lua) } } impl From<Row> for ratatui::widgets::Row<'static> { fn from(value: Row) -> Self { Self::new(value.cells) .height(value.height.max(1)) .top_margin(value.top_margin) .bottom_margin(value.bottom_margin) .style(value.style) } } impl TryFrom<Value> for Row { type Error = mlua::Error; fn try_from(value: Value) -> Result<Self, Self::Error> { Ok(match value { Value::UserData(ud) => { if let Ok(row) = ud.take() { row } else { Err(EXPECTED.into_lua_err())? } } _ => Err(EXPECTED.into_lua_err())?, }) } } impl UserData for Row { fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) { crate::impl_style_method!(methods, style); methods.add_function_mut("height", |_, (ud, value): (AnyUserData, u16)| { ud.borrow_mut::<Self>()?.height = value; Ok(ud) }); methods.add_function_mut("margin_t", |_, (ud, value): (AnyUserData, u16)| { ud.borrow_mut::<Self>()?.top_margin = value; Ok(ud) }); methods.add_function_mut("margin_b", |_, (ud, value): (AnyUserData, u16)| { ud.borrow_mut::<Self>()?.bottom_margin = value; Ok(ud) }); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/table.rs
yazi-binding/src/elements/table.rs
use mlua::{AnyUserData, ExternalError, IntoLua, Lua, MetaMethod, UserData, Value}; use ratatui::widgets::StatefulWidget; use super::{Area, Row}; use crate::{Style, elements::Constraint}; const EXPECTED: &str = "expected a table of Rows"; // --- Table #[derive(Clone, Debug, Default)] pub struct Table { pub area: Area, rows: Vec<Row>, header: Option<ratatui::widgets::Row<'static>>, footer: Option<ratatui::widgets::Row<'static>>, widths: Vec<ratatui::layout::Constraint>, column_spacing: u16, block: Option<ratatui::widgets::Block<'static>>, // TODO style: ratatui::style::Style, row_highlight_style: ratatui::style::Style, column_highlight_style: ratatui::style::Style, cell_highlight_style: ratatui::style::Style, highlight_symbol: ratatui::text::Text<'static>, // TODO highlight_spacing: ratatui::widgets::HighlightSpacing, // TODO flex: ratatui::layout::Flex, state: ratatui::widgets::TableState, } impl Table { pub fn compose(lua: &Lua) -> mlua::Result<Value> { let new = lua.create_function(|_, (_, seq): (mlua::Table, mlua::Table)| { let mut rows = Vec::with_capacity(seq.raw_len()); for v in seq.sequence_values::<Value>() { rows.push(Row::try_from(v?).map_err(|_| EXPECTED.into_lua_err())?); } Ok(Self { rows, ..Default::default() }) })?; let table = lua.create_table()?; table.set_metatable(Some(lua.create_table_from([(MetaMethod::Call.name(), new)])?))?; table.into_lua(lua) } pub fn selected_cell(&self) -> Option<&ratatui::text::Text<'_>> { let row = &self.rows[self.selected()?]; let col = self.state.selected_column()?; if row.cells.is_empty() { None } else { Some(&row.cells[col.min(row.cells.len() - 1)].text) } } pub(super) fn render(mut self, rect: ratatui::layout::Rect, buf: &mut ratatui::buffer::Buffer) { let mut table = ratatui::widgets::Table::new(self.rows, self.widths) .column_spacing(self.column_spacing) .style(self.style) .row_highlight_style(self.row_highlight_style) .column_highlight_style(self.column_highlight_style) .cell_highlight_style(self.cell_highlight_style) .highlight_symbol(self.highlight_symbol) .highlight_spacing(self.highlight_spacing) .flex(self.flex); if let Some(header) = self.header { table = table.header(header); } if let Some(footer) = self.footer { table = table.footer(footer); } if let Some(block) = self.block { table = table.block(block); } table.render(rect, buf, &mut self.state); } pub fn len(&self) -> usize { self.rows.len() } pub fn select(&mut self, idx: Option<usize>) { self .state .select(idx.map(|i| if self.rows.is_empty() { 0 } else { i.min(self.rows.len() - 1) })); } pub fn selected(&self) -> Option<usize> { if self.rows.is_empty() { None } else { Some(self.state.selected()?.min(self.rows.len() - 1)) } } } impl TryFrom<AnyUserData> for Table { type Error = mlua::Error; fn try_from(value: AnyUserData) -> Result<Self, Self::Error> { value.take() } } impl UserData for Table { fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) { crate::impl_area_method!(methods); methods.add_function_mut("header", |_, (ud, value): (AnyUserData, Value)| { ud.borrow_mut::<Self>()?.header = Some(Row::try_from(value)?.into()); Ok(ud) }); methods.add_function_mut("footer", |_, (ud, value): (AnyUserData, Value)| { ud.borrow_mut::<Self>()?.footer = Some(Row::try_from(value)?.into()); Ok(ud) }); methods.add_function_mut("widths", |_, (ud, widths): (AnyUserData, Vec<Constraint>)| { ud.borrow_mut::<Self>()?.widths = widths.into_iter().map(Into::into).collect(); Ok(ud) }); methods.add_function_mut("spacing", |_, (ud, spacing): (AnyUserData, u16)| { ud.borrow_mut::<Self>()?.column_spacing = spacing; Ok(ud) }); methods.add_function_mut("row", |_, (ud, idx): (AnyUserData, Option<usize>)| { ud.borrow_mut::<Self>()?.state.select(idx); Ok(ud) }); methods.add_function_mut("col", |_, (ud, idx): (AnyUserData, Option<usize>)| { ud.borrow_mut::<Self>()?.state.select_column(idx); Ok(ud) }); methods.add_function_mut("style", |_, (ud, value): (AnyUserData, Value)| { ud.borrow_mut::<Self>()?.style = Style::try_from(value)?.0; Ok(ud) }); methods.add_function_mut("row_style", |_, (ud, value): (AnyUserData, Value)| { ud.borrow_mut::<Self>()?.row_highlight_style = Style::try_from(value)?.0; Ok(ud) }); methods.add_function_mut("col_style", |_, (ud, value): (AnyUserData, Value)| { ud.borrow_mut::<Self>()?.column_highlight_style = Style::try_from(value)?.0; Ok(ud) }); methods.add_function_mut("cell_style", |_, (ud, value): (AnyUserData, Value)| { ud.borrow_mut::<Self>()?.cell_highlight_style = Style::try_from(value)?.0; Ok(ud) }); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/clear.rs
yazi-binding/src/elements/clear.rs
use std::sync::atomic::{AtomicBool, Ordering}; use mlua::{IntoLua, Lua, MetaMethod, Table, UserData, Value}; use yazi_adapter::ADAPTOR; use super::Area; pub static COLLISION: AtomicBool = AtomicBool::new(false); #[derive(Clone, Copy, Debug, Default)] pub struct Clear { pub area: Area, } impl Clear { pub fn compose(lua: &Lua) -> mlua::Result<Value> { let new = lua.create_function(|_, (_, area): (Table, Area)| Ok(Self { area }))?; let clear = lua.create_table()?; clear.set_metatable(Some(lua.create_table_from([(MetaMethod::Call.name(), new)])?))?; clear.into_lua(lua) } pub(super) fn render(self, rect: ratatui::layout::Rect, buf: &mut ratatui::buffer::Buffer) { <Self as ratatui::widgets::Widget>::render(Default::default(), rect, buf); } } impl ratatui::widgets::Widget for Clear { fn render(self, area: ratatui::layout::Rect, buf: &mut ratatui::prelude::Buffer) where Self: Sized, { ratatui::widgets::Clear.render(area, buf); let Some(r) = ADAPTOR.get().shown_load().and_then(|r| overlap(area, r)) else { return; }; ADAPTOR.get().image_erase(r).ok(); COLLISION.store(true, Ordering::Relaxed); for y in r.top()..r.bottom() { for x in r.left()..r.right() { buf[(x, y)].set_skip(true); } } } } impl UserData for Clear { fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) { crate::impl_area_method!(methods); } } const fn is_overlapping(a: ratatui::layout::Rect, b: ratatui::layout::Rect) -> bool { a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y } fn overlap(a: ratatui::layout::Rect, b: ratatui::layout::Rect) -> Option<ratatui::layout::Rect> { if !is_overlapping(a, b) { return None; } let x = a.x.max(b.x); let y = a.y.max(b.y); let width = (a.x + a.width).min(b.x + b.width) - x; let height = (a.y + a.height).min(b.y + b.height) - y; Some(ratatui::layout::Rect { x, y, width, height }) }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/rect.rs
yazi-binding/src/elements/rect.rs
use std::ops::Deref; use mlua::{FromLua, IntoLua, Lua, MetaMethod, Table, UserData, Value}; use super::Pad; use crate::deprecate; #[derive(Clone, Copy, Debug, Default, FromLua)] pub struct Rect(pub ratatui::layout::Rect); impl Deref for Rect { type Target = ratatui::layout::Rect; fn deref(&self) -> &Self::Target { &self.0 } } impl From<ratatui::layout::Rect> for Rect { fn from(rect: ratatui::layout::Rect) -> Self { Self(rect) } } impl From<ratatui::layout::Size> for Rect { fn from(size: ratatui::layout::Size) -> Self { Self(ratatui::layout::Rect { x: 0, y: 0, width: size.width, height: size.height }) } } impl Rect { pub fn compose(lua: &Lua) -> mlua::Result<Value> { let new = lua.create_function(|_, (_, args): (Table, Table)| { Ok(Self(ratatui::layout::Rect { x: args.raw_get("x").unwrap_or_default(), y: args.raw_get("y").unwrap_or_default(), width: args.raw_get("w").unwrap_or_default(), height: args.raw_get("h").unwrap_or_default(), })) })?; let index = lua.create_function(move |lua, (_, key): (Table, mlua::String)| { Ok(match &*key.as_bytes() { b"default" => { deprecate!(lua, "`ui.Rect.default` is deprecated, use `ui.Rect{{}}` instead, in your {}\nSee #2927 for more details: https://github.com/sxyazi/yazi/pull/2927"); Some(Self(Default::default())) } _ => None, }) })?; let rect = lua.create_table()?; rect.set_metatable(Some( lua.create_table_from([(MetaMethod::Call.name(), new), (MetaMethod::Index.name(), index)])?, ))?; rect.into_lua(lua) } pub(super) fn pad(self, pad: Pad) -> Self { let mut r = *self; r.x = r.x.saturating_add(pad.left); r.y = r.y.saturating_add(pad.top); r.width = r.width.saturating_sub(pad.left + pad.right); r.height = r.height.saturating_sub(pad.top + pad.bottom); Self(r) } } impl UserData for Rect { fn add_fields<F: mlua::UserDataFields<Self>>(fields: &mut F) { fields.add_field_method_get("x", |_, me| Ok(me.x)); fields.add_field_method_get("y", |_, me| Ok(me.y)); fields.add_field_method_get("w", |_, me| Ok(me.width)); fields.add_field_method_get("h", |_, me| Ok(me.height)); fields.add_field_method_set("x", |_, me, x| Ok(me.0.x = x)); fields.add_field_method_set("y", |_, me, y| Ok(me.0.y = y)); fields.add_field_method_set("w", |_, me, w| Ok(me.0.width = w)); fields.add_field_method_set("h", |_, me, h| Ok(me.0.height = h)); fields.add_field_method_get("left", |_, me| Ok(me.left())); fields.add_field_method_get("right", |_, me| Ok(me.right())); fields.add_field_method_get("top", |_, me| Ok(me.top())); fields.add_field_method_get("bottom", |_, me| Ok(me.bottom())); } fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) { methods.add_method("pad", |_, me, pad: Pad| Ok(me.pad(pad))); methods.add_method("contains", |_, me, Self(rect)| Ok(me.contains(rect.into()))); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/text.rs
yazi-binding/src/elements/text.rs
use std::{any::TypeId, mem}; use ansi_to_tui::IntoText; use mlua::{AnyUserData, ExternalError, ExternalResult, IntoLua, Lua, MetaMethod, Table, UserData, Value}; use ratatui::widgets::Widget; use super::{Area, Line, Span, Wrap}; use crate::{Error, elements::Align}; const EXPECTED: &str = "expected a string, Line, Span, or a table of them"; #[derive(Clone, Debug, Default)] pub struct Text { pub area: Area, // TODO: block pub inner: ratatui::text::Text<'static>, pub wrap: Wrap, pub scroll: ratatui::layout::Position, } impl Text { pub fn compose(lua: &Lua) -> mlua::Result<Value> { let new = lua.create_function(|_, (_, value): (Table, Value)| Self::try_from(value))?; let parse = lua.create_function(|_, code: mlua::String| { Ok(Self { inner: code.as_bytes().into_text().into_lua_err()?, ..Default::default() }) })?; let text = lua.create_table_from([("parse", parse)])?; text.set_metatable(Some(lua.create_table_from([(MetaMethod::Call.name(), new)])?))?; text.into_lua(lua) } pub(super) fn render(self, rect: ratatui::layout::Rect, buf: &mut ratatui::buffer::Buffer) { if self.wrap.is_none() && self.scroll == Default::default() { self.inner.render(rect, buf); } else { ratatui::widgets::Paragraph::from(self).render(rect, buf); } } } impl TryFrom<Value> for Text { type Error = mlua::Error; fn try_from(value: Value) -> mlua::Result<Self> { let inner = match value { Value::Table(tb) => return Self::try_from(tb), Value::String(s) => s.to_string_lossy().into(), Value::UserData(ud) => match ud.type_id() { Some(t) if t == TypeId::of::<Line>() => ud.take::<Line>()?.inner.into(), Some(t) if t == TypeId::of::<Span>() => ud.take::<Span>()?.0.into(), Some(t) if t == TypeId::of::<Self>() => return ud.take(), Some(t) if t == TypeId::of::<Error>() => ud.take::<Error>()?.into_string().into(), _ => Err(EXPECTED.into_lua_err())?, }, _ => Err(EXPECTED.into_lua_err())?, }; Ok(Self { inner, ..Default::default() }) } } impl TryFrom<Table> for Text { type Error = mlua::Error; fn try_from(tb: Table) -> Result<Self, Self::Error> { let mut lines = Vec::with_capacity(tb.raw_len()); for v in tb.sequence_values() { lines.push(match v? { Value::String(s) => s.to_string_lossy().into(), Value::UserData(ud) => match ud.type_id() { Some(t) if t == TypeId::of::<Span>() => ud.take::<Span>()?.0.into(), Some(t) if t == TypeId::of::<Line>() => ud.take::<Line>()?.inner, Some(t) if t == TypeId::of::<Error>() => ud.take::<Error>()?.into_string().into(), _ => Err(EXPECTED.into_lua_err())?, }, _ => Err(EXPECTED.into_lua_err())?, }) } Ok(Self { inner: lines.into(), ..Default::default() }) } } impl From<Text> for ratatui::text::Text<'static> { fn from(value: Text) -> Self { value.inner } } impl From<Text> for ratatui::widgets::Paragraph<'static> { fn from(mut value: Text) -> Self { let align = value.inner.alignment.take(); let style = mem::take(&mut value.inner.style); let mut p = ratatui::widgets::Paragraph::new(value.inner).style(style); if let Some(align) = align { p = p.alignment(align); } if let Some(wrap) = value.wrap.0 { p = p.wrap(wrap); } p.scroll((value.scroll.y, value.scroll.x)) } } impl UserData for Text { fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) { crate::impl_area_method!(methods); crate::impl_style_method!(methods, inner.style); crate::impl_style_shorthands!(methods, inner.style); methods.add_function_mut("align", |_, (ud, align): (AnyUserData, Align)| { ud.borrow_mut::<Self>()?.inner.alignment = Some(align.0); Ok(ud) }); methods.add_function_mut("wrap", |_, (ud, wrap): (AnyUserData, Wrap)| { ud.borrow_mut::<Self>()?.wrap = wrap; Ok(ud) }); methods.add_function_mut("scroll", |_, (ud, x, y): (AnyUserData, u16, u16)| { ud.borrow_mut::<Self>()?.scroll = ratatui::layout::Position { x, y }; Ok(ud) }); methods.add_method("max_width", |_, me, ()| { Ok(me.inner.lines.iter().take(me.area.size().height as usize).map(|l| l.width()).max()) }); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/renderable.rs
yazi-binding/src/elements/renderable.rs
use std::any::TypeId; use mlua::{AnyUserData, ExternalError}; use super::{Bar, Border, Clear, Gauge, Line, List, Table, Text}; use crate::{Error, elements::Area}; #[derive(Clone, Debug)] pub enum Renderable { Line(Line), Text(Text), List(Box<List>), Bar(Bar), Clear(Clear), Border(Border), Gauge(Box<Gauge>), Table(Box<Table>), } impl Renderable { pub fn area(&self) -> Area { match self { Self::Line(line) => line.area, Self::Text(text) => text.area, Self::List(list) => list.area, Self::Bar(bar) => bar.area, Self::Clear(clear) => clear.area, Self::Border(border) => border.area, Self::Gauge(gauge) => gauge.area, Self::Table(table) => table.area, } } pub fn with_area(mut self, area: impl Into<Area>) -> Self { let area = area.into(); match &mut self { Self::Line(line) => line.area = area, Self::Text(text) => text.area = area, Self::List(list) => list.area = area, Self::Bar(bar) => bar.area = area, Self::Clear(clear) => clear.area = area, Self::Border(border) => border.area = area, Self::Gauge(gauge) => gauge.area = area, Self::Table(table) => table.area = area, } self } pub fn render(self, rect: ratatui::layout::Rect, buf: &mut ratatui::buffer::Buffer) { match self { Self::Line(line) => line.render(rect, buf), Self::Text(text) => text.render(rect, buf), Self::List(list) => list.render(rect, buf), Self::Bar(bar) => bar.render(rect, buf), Self::Clear(clear) => clear.render(rect, buf), Self::Border(border) => border.render(rect, buf), Self::Gauge(gauge) => gauge.render(rect, buf), Self::Table(table) => table.render(rect, buf), } } pub fn render_with<T>(self, buf: &mut ratatui::buffer::Buffer, trans: T) where T: FnOnce(yazi_config::popup::Position) -> ratatui::layout::Rect, { let rect = self.area().transform(trans); self.render(rect, buf); } } impl TryFrom<&AnyUserData> for Renderable { type Error = mlua::Error; fn try_from(ud: &AnyUserData) -> Result<Self, Self::Error> { Ok(match ud.type_id() { Some(t) if t == TypeId::of::<Line>() => Self::Line(ud.take()?), Some(t) if t == TypeId::of::<Text>() => Self::Text(ud.take()?), Some(t) if t == TypeId::of::<List>() => Self::List(Box::new(ud.take()?)), Some(t) if t == TypeId::of::<Bar>() => Self::Bar(ud.take()?), Some(t) if t == TypeId::of::<Clear>() => Self::Clear(ud.take()?), Some(t) if t == TypeId::of::<Border>() => Self::Border(ud.take()?), Some(t) if t == TypeId::of::<Gauge>() => Self::Gauge(Box::new(ud.take()?)), Some(t) if t == TypeId::of::<Table>() => Self::Table(Box::new(ud.take()?)), _ => Err(format!("expected a UserData of renderable element, not: {ud:#?}").into_lua_err())?, }) } } impl TryFrom<AnyUserData> for Renderable { type Error = mlua::Error; fn try_from(ud: AnyUserData) -> Result<Self, Self::Error> { Self::try_from(&ud) } } impl From<Error> for Renderable { fn from(error: Error) -> Self { Self::Text(Text { inner: error.into_string().into(), wrap: ratatui::widgets::Wrap { trim: false }.into(), ..Default::default() }) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/span.rs
yazi-binding/src/elements/span.rs
use std::{borrow::Cow, ops::{Deref, DerefMut}}; use mlua::{AnyUserData, ExternalError, IntoLua, Lua, MetaMethod, Table, UserData, UserDataMethods, Value}; use unicode_width::UnicodeWidthChar; const EXPECTED: &str = "expected a string or Span"; pub struct Span(pub(super) ratatui::text::Span<'static>); impl Deref for Span { type Target = ratatui::text::Span<'static>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for Span { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl Span { pub fn compose(lua: &Lua) -> mlua::Result<Value> { let new = lua.create_function(|_, (_, value): (Table, Value)| Self::try_from(value))?; let span = lua.create_table()?; span.set_metatable(Some(lua.create_table_from([(MetaMethod::Call.name(), new)])?))?; span.into_lua(lua) } pub(super) fn truncate(&mut self, max: usize) -> usize { if max < 1 { match &mut self.0.content { Cow::Borrowed(_) => self.0.content = Cow::Borrowed(""), Cow::Owned(s) => s.clear(), } return 0; } let mut adv = 0; let mut last; for (i, c) in self.0.content.char_indices() { (last, adv) = (adv, adv + c.width().unwrap_or(0)); if adv < max { continue; } else if adv == max && self.0.content[i..].chars().nth(1).is_none() { return max; } match &mut self.0.content { Cow::Borrowed(s) => self.0.content = format!("{}…", &s[..i]).into(), Cow::Owned(s) => { s.truncate(i); s.push('…'); } } return last + 1; } adv } } impl TryFrom<Value> for Span { type Error = mlua::Error; fn try_from(value: Value) -> Result<Self, Self::Error> { Ok(Self(match value { Value::String(s) => s.to_string_lossy().into(), Value::UserData(ud) => { if let Ok(Self(span)) = ud.take() { span } else { Err(EXPECTED.into_lua_err())? } } _ => Err(EXPECTED.into_lua_err())?, })) } } impl UserData for Span { fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { crate::impl_style_method!(methods, 0.style); crate::impl_style_shorthands!(methods, 0.style); methods.add_method("visible", |_, Self(me), ()| { Ok(me.content.chars().any(|c| c.width().unwrap_or(0) > 0)) }); methods.add_function_mut("truncate", |_, (ud, t): (AnyUserData, Table)| { ud.borrow_mut::<Self>()?.truncate(t.raw_get("max")?); Ok(ud) }); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/align.rs
yazi-binding/src/elements/align.rs
use std::ops::Deref; use mlua::{FromLua, IntoLua, Lua, Value}; #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub struct Align(pub(super) ratatui::layout::Alignment); impl Deref for Align { type Target = ratatui::layout::Alignment; fn deref(&self) -> &Self::Target { &self.0 } } impl Align { pub fn compose(lua: &Lua) -> mlua::Result<Value> { lua.create_table_from([("LEFT", 0), ("CENTER", 1), ("RIGHT", 2)])?.into_lua(lua) } } impl FromLua for Align { fn from_lua(value: Value, _: &Lua) -> mlua::Result<Self> { let Value::Integer(n) = value else { return Err(mlua::Error::FromLuaConversionError { from: value.type_name(), to: "Align".to_string(), message: Some("expected an integer representation of Align".to_string()), }); }; Ok(Self(match n { 0 => ratatui::layout::Alignment::Left, 1 => ratatui::layout::Alignment::Center, 2 => ratatui::layout::Alignment::Right, _ => Err(mlua::Error::FromLuaConversionError { from: value.type_name(), to: "Align".to_string(), message: Some("invalid value for Align".to_string()), })?, })) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/bar.rs
yazi-binding/src/elements/bar.rs
use mlua::{AnyUserData, IntoLua, Lua, MetaMethod, Table, UserData, Value}; use ratatui::widgets::Borders; use super::{Area, Edge}; #[derive(Clone, Debug, Default)] pub struct Bar { pub(super) area: Area, edge: Edge, symbol: String, style: ratatui::style::Style, } impl Bar { pub fn compose(lua: &Lua) -> mlua::Result<Value> { let new = lua.create_function(|_, (_, edge): (Table, Edge)| Ok(Self { edge, ..Default::default() }))?; let bar = lua.create_table()?; bar.set_metatable(Some(lua.create_table_from([(MetaMethod::Call.name(), new)])?))?; bar.into_lua(lua) } pub(super) fn render(self, rect: ratatui::layout::Rect, buf: &mut ratatui::buffer::Buffer) { if rect.area() == 0 { return; } let symbol = if !self.symbol.is_empty() { &self.symbol } else if self.edge.intersects(Borders::TOP | Borders::BOTTOM) { "─" } else if self.edge.intersects(Borders::LEFT | Borders::RIGHT) { "│" } else { " " }; if self.edge.contains(Borders::LEFT) { for y in rect.top()..rect.bottom() { buf[(rect.left(), y)].set_style(self.style).set_symbol(symbol); } } if self.edge.contains(Borders::TOP) { for x in rect.left()..rect.right() { buf[(x, rect.top())].set_style(self.style).set_symbol(symbol); } } if self.edge.contains(Borders::RIGHT) { let x = rect.right() - 1; for y in rect.top()..rect.bottom() { buf[(x, y)].set_style(self.style).set_symbol(symbol); } } if self.edge.contains(Borders::BOTTOM) { let y = rect.bottom() - 1; for x in rect.left()..rect.right() { buf[(x, y)].set_style(self.style).set_symbol(symbol); } } } } impl UserData for Bar { fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) { crate::impl_area_method!(methods); crate::impl_style_method!(methods, style); methods.add_function_mut("edge", |_, (ud, edge): (AnyUserData, Edge)| { ud.borrow_mut::<Self>()?.edge = edge; Ok(ud) }); methods.add_function_mut("symbol", |_, (ud, symbol): (AnyUserData, String)| { ud.borrow_mut::<Self>()?.symbol = symbol; Ok(ud) }); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/mod.rs
yazi-binding/src/elements/mod.rs
yazi_macro::mod_flat!(align area bar border cell clear constraint edge elements gauge layout line list pad pos rect renderable row span table text wrap);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/layout.rs
yazi-binding/src/elements/layout.rs
use mlua::{AnyUserData, IntoLua, Lua, MetaMethod, Table, UserData, UserDataMethods, Value}; use super::{Constraint, Rect}; const HORIZONTAL: bool = true; const VERTICAL: bool = false; #[derive(Clone, Default)] pub struct Layout { direction: bool, margin: Option<ratatui::layout::Margin>, constraints: Vec<ratatui::layout::Constraint>, } impl Layout { pub fn compose(lua: &Lua) -> mlua::Result<Value> { let new = lua.create_function(|_, _: Table| Ok(Self::default()))?; let layout = lua.create_table_from([("HORIZONTAL", HORIZONTAL), ("VERTICAL", VERTICAL)])?; layout.set_metatable(Some(lua.create_table_from([(MetaMethod::Call.name(), new)])?))?; layout.into_lua(lua) } } impl UserData for Layout { fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { methods.add_function_mut("direction", |_, (ud, value): (AnyUserData, bool)| { ud.borrow_mut::<Self>()?.direction = value; Ok(ud) }); methods.add_function_mut("margin", |_, (ud, value): (AnyUserData, u16)| { ud.borrow_mut::<Self>()?.margin = Some(ratatui::layout::Margin::new(value, value)); Ok(ud) }); methods.add_function_mut("margin_h", |_, (ud, value): (AnyUserData, u16)| { { let mut me = ud.borrow_mut::<Self>()?; if let Some(margin) = &mut me.margin { margin.horizontal = value; } else { me.margin = Some(ratatui::layout::Margin::new(value, 0)); } } Ok(ud) }); methods.add_function_mut("margin_v", |_, (ud, value): (AnyUserData, u16)| { { let mut me = ud.borrow_mut::<Self>()?; if let Some(margin) = &mut me.margin { margin.vertical = value; } else { me.margin = Some(ratatui::layout::Margin::new(0, value)); } } Ok(ud) }); methods.add_function_mut("constraints", |_, (ud, value): (AnyUserData, Vec<Constraint>)| { ud.borrow_mut::<Self>()?.constraints = value.into_iter().map(Into::into).collect(); Ok(ud) }); methods.add_method("split", |lua, me, value: Rect| { let mut layout = ratatui::layout::Layout::new( if me.direction == VERTICAL { ratatui::layout::Direction::Vertical } else { ratatui::layout::Direction::Horizontal }, &me.constraints, ); if let Some(margin) = me.margin { layout = layout.horizontal_margin(margin.horizontal); layout = layout.vertical_margin(margin.vertical); } lua.create_sequence_from(layout.split(*value).iter().map(|chunk| Rect::from(*chunk))) }); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/area.rs
yazi-binding/src/elements/area.rs
use std::fmt::Debug; use mlua::{AnyUserData, ExternalError, FromLua, IntoLua, Value}; use super::{Pos, Rect}; const EXPECTED: &str = "expected a Pos or Rect"; #[derive(Clone, Copy)] pub enum Area { Pos(Pos), Rect(Rect), } impl Default for Area { fn default() -> Self { Self::Rect(Default::default()) } } impl Area { pub fn size(self) -> ratatui::layout::Size { match self { Self::Pos(pos) => { ratatui::layout::Size { width: pos.offset.width, height: pos.offset.height } } Self::Rect(rect) => (*rect).into(), } } pub fn inner(self, padding: ratatui::widgets::Padding) -> Self { match self { Self::Pos(mut pos) => { pos.pad += padding; Self::Pos(pos) } Self::Rect(rect) => Self::Rect(rect.pad(padding.into())), } } pub fn transform( self, f: impl FnOnce(yazi_config::popup::Position) -> ratatui::layout::Rect, ) -> ratatui::layout::Rect { match self { Self::Pos(pos) => *Rect(f(*pos)).pad(pos.pad), Self::Rect(rect) => *rect, } } } impl From<Rect> for Area { fn from(rect: Rect) -> Self { Self::Rect(rect) } } impl From<ratatui::layout::Rect> for Area { fn from(rect: ratatui::layout::Rect) -> Self { Self::Rect(rect.into()) } } impl TryFrom<AnyUserData> for Area { type Error = mlua::Error; fn try_from(value: AnyUserData) -> Result<Self, Self::Error> { Ok(if let Ok(rect) = value.borrow::<Rect>() { Self::Rect(*rect) } else if let Ok(pos) = value.borrow::<Pos>() { Self::Pos(*pos) } else { return Err(EXPECTED.into_lua_err()); }) } } impl FromLua for Area { fn from_lua(value: Value, _: &mlua::Lua) -> mlua::Result<Self> { match value { Value::UserData(ud) => Self::try_from(ud), _ => Err(EXPECTED.into_lua_err()), } } } impl IntoLua for Area { fn into_lua(self, lua: &mlua::Lua) -> mlua::Result<mlua::Value> { match self { Self::Pos(pos) => pos.into_lua(lua), Self::Rect(rect) => rect.into_lua(lua), } } } impl Debug for Area { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Pos(pos) => write!(f, "{:?}", **pos), Self::Rect(rect) => write!(f, "{:?}", **rect), } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/elements.rs
yazi-binding/src/elements/elements.rs
use mlua::{AnyUserData, IntoLua, Lua, Value}; use tracing::error; use super::Renderable; use crate::{Composer, ComposerGet, ComposerSet}; pub fn compose(p_get: ComposerGet, p_set: ComposerSet) -> Composer<ComposerGet, ComposerSet> { fn get(lua: &Lua, key: &[u8]) -> mlua::Result<Value> { match key { b"Align" => super::Align::compose(lua)?, b"Bar" => super::Bar::compose(lua)?, b"Border" => super::Border::compose(lua)?, b"Clear" => super::Clear::compose(lua)?, b"Constraint" => super::Constraint::compose(lua)?, b"Edge" => super::Edge::compose(lua)?, b"Gauge" => super::Gauge::compose(lua)?, b"Layout" => super::Layout::compose(lua)?, b"Line" => super::Line::compose(lua)?, b"List" => super::List::compose(lua)?, b"Pad" => super::Pad::compose(lua)?, b"Pos" => super::Pos::compose(lua)?, b"Rect" => super::Rect::compose(lua)?, b"Row" => super::Row::compose(lua)?, b"Span" => super::Span::compose(lua)?, b"Style" => crate::Style::compose(lua)?, b"Table" => super::Table::compose(lua)?, b"Text" => super::Text::compose(lua)?, b"Wrap" => super::Wrap::compose(lua)?, _ => return Ok(Value::Nil), } .into_lua(lua) } fn set(_: &Lua, _: &[u8], value: Value) -> mlua::Result<Value> { Ok(value) } Composer::with_parent(get, set, p_get, p_set) } pub fn render_once<F>(value: Value, buf: &mut ratatui::buffer::Buffer, trans: F) where F: FnOnce(yazi_config::popup::Position) -> ratatui::layout::Rect + Copy, { match value { Value::Table(tbl) => { for widget in tbl.sequence_values::<AnyUserData>() { let Ok(widget) = widget else { error!("Failed to convert to renderable UserData: {}", widget.unwrap_err()); continue; }; match Renderable::try_from(widget) { Ok(w) => w.render_with(buf, trans), Err(e) => error!("{e}"), } } } Value::UserData(ud) => match Renderable::try_from(ud) { Ok(w) => w.render_with(buf, trans), Err(e) => error!("{e}"), }, _ => error!("Expected a renderable UserData, or a table of them, got: {value:?}"), } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/line.rs
yazi-binding/src/elements/line.rs
use std::{borrow::Cow, mem, ops::{Deref, DerefMut}}; use ansi_to_tui::IntoText; use mlua::{AnyUserData, ExternalError, ExternalResult, IntoLua, Lua, MetaMethod, Table, UserData, UserDataMethods, Value}; use ratatui::widgets::Widget; use unicode_width::UnicodeWidthChar; use super::{Area, Span}; use crate::elements::Align; const EXPECTED: &str = "expected a string, Span, Line, or a table of them"; #[derive(Clone, Debug, Default)] pub struct Line { pub(super) area: Area, pub(super) inner: ratatui::text::Line<'static>, } impl Deref for Line { type Target = ratatui::text::Line<'static>; fn deref(&self) -> &Self::Target { &self.inner } } impl DerefMut for Line { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } } impl Line { pub fn compose(lua: &Lua) -> mlua::Result<Value> { let new = lua.create_function(|_, (_, value): (Table, Value)| Self::try_from(value))?; let parse = lua.create_function(|_, code: mlua::String| { let code = code.as_bytes(); let Some(line) = code.split_inclusive(|&b| b == b'\n').next() else { return Ok(Self::default()); }; let mut lines = line.into_text().into_lua_err()?.lines; if lines.is_empty() { return Ok(Self::default()); } Ok(Self { inner: mem::take(&mut lines[0]), ..Default::default() }) })?; let line = lua.create_table_from([("parse", parse)])?; line.set_metatable(Some(lua.create_table_from([(MetaMethod::Call.name(), new)])?))?; line.into_lua(lua) } pub(super) fn render(self, rect: ratatui::layout::Rect, buf: &mut ratatui::buffer::Buffer) { self.inner.render(rect, buf); } } impl TryFrom<Value> for Line { type Error = mlua::Error; fn try_from(value: Value) -> Result<Self, Self::Error> { Ok(Self { inner: match value { Value::Table(tb) => return Self::try_from(tb), Value::String(s) => s.to_string_lossy().into(), Value::UserData(ud) => { if let Ok(Span(span)) = ud.take() { span.into() } else if let Ok(line) = ud.take() { return Ok(line); } else { Err(EXPECTED.into_lua_err())? } } _ => Err(EXPECTED.into_lua_err())?, }, ..Default::default() }) } } impl TryFrom<Table> for Line { type Error = mlua::Error; fn try_from(tb: Table) -> Result<Self, Self::Error> { let mut spans = Vec::with_capacity(tb.raw_len()); for v in tb.sequence_values() { match v? { Value::String(s) => spans.push(s.to_string_lossy().into()), Value::UserData(ud) => { if let Ok(Span(span)) = ud.take() { spans.push(span); } else if let Ok(Self { inner: mut line, .. }) = ud.take() { line.spans.iter_mut().for_each(|s| s.style = line.style.patch(s.style)); spans.extend(line.spans); } else { return Err(EXPECTED.into_lua_err()); } } _ => Err(EXPECTED.into_lua_err())?, } } Ok(Self { inner: spans.into(), ..Default::default() }) } } impl From<Line> for ratatui::text::Line<'static> { fn from(value: Line) -> Self { value.inner } } impl UserData for Line { fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { crate::impl_area_method!(methods); crate::impl_style_method!(methods, style); crate::impl_style_shorthands!(methods, style); methods.add_method("width", |_, me, ()| Ok(me.width())); methods.add_function_mut("align", |_, (ud, align): (AnyUserData, Align)| { ud.borrow_mut::<Self>()?.alignment = Some(align.0); Ok(ud) }); methods.add_method("visible", |_, me, ()| { Ok(me.iter().flat_map(|s| s.content.chars()).any(|c| c.width().unwrap_or(0) > 0)) }); methods.add_function_mut("truncate", |_, (ud, t): (AnyUserData, Table)| { let mut me = ud.borrow_mut::<Self>()?; let max = t.raw_get("max")?; if max < 1 { me.spans.clear(); return Ok(ud); } let ellipsis = match t.raw_get::<Value>("ellipsis")? { Value::Nil => (1, ratatui::text::Span::raw("…")), v => { let mut span = Span::try_from(v)?; (span.truncate(max), span.0) } }; fn traverse( max: usize, threshold: usize, it: impl Iterator<Item = (usize, usize, char)>, ) -> (Option<(usize, usize, usize)>, bool) { let (mut adv, mut cut) = (0, None); for (x, y, c) in it { adv += c.width().unwrap_or(0); if adv <= threshold { cut = Some((x, y, adv)); } else if adv > max { break; } } (cut, adv > max) } let rtl = t.raw_get("rtl")?; let (cut, remain) = if rtl { traverse( max, max - ellipsis.0, me.iter() .enumerate() .rev() .flat_map(|(x, s)| s.content.char_indices().rev().map(move |(y, c)| (x, y, c))), ) } else { traverse( max, max - ellipsis.0, me.iter() .enumerate() .flat_map(|(x, s)| s.content.char_indices().map(move |(y, c)| (x, y, c))), ) }; let Some((x, y, width)) = cut else { me.spans.clear(); me.spans.push(ellipsis.1); return Ok(ud); }; if !remain { return Ok(ud); } let spans = &mut me.spans; let len = match (rtl, width == max) { (a, b) if a == b => spans[x].content[y..].chars().next().map_or(0, |c| c.len_utf8()), _ => 0, }; if rtl { match &mut spans[x].content { Cow::Borrowed(s) => spans[x].content = Cow::Borrowed(&s[y + len..]), Cow::Owned(s) => _ = s.drain(..y + len), } spans.splice(..x, [ellipsis.1]); } else { match &mut spans[x].content { Cow::Borrowed(s) => spans[x].content = Cow::Borrowed(&s[..y + len]), Cow::Owned(s) => s.truncate(y + len), } spans.truncate(x + 1); spans.push(ellipsis.1); } Ok(ud) }); } } #[cfg(test)] mod tests { use mlua::{UserDataRef, chunk}; use super::*; fn truncate(s: &str, max: usize, rtl: bool) -> String { let lua = Lua::new(); let comp = Line::compose(&lua).unwrap(); let line: UserDataRef<Line> = lua .load(chunk! { return $comp($s):truncate { max = $max, rtl = $rtl } }) .call(()) .unwrap(); line.spans.iter().map(|s| &*s.content).collect() } #[test] fn test_truncate() { assert_eq!(truncate("你好,world", 0, false), ""); assert_eq!(truncate("你好,world", 1, false), "…"); assert_eq!(truncate("你好,world", 2, false), "…"); assert_eq!(truncate("你好,世界", 3, false), "你…"); assert_eq!(truncate("你好,世界", 4, false), "你…"); assert_eq!(truncate("你好,世界", 5, false), "你好…"); assert_eq!(truncate("Hello, world", 5, false), "Hell…"); assert_eq!(truncate("Ni好,世界", 3, false), "Ni…"); } #[test] fn test_truncate_rtl() { assert_eq!(truncate("world,你好", 0, true), ""); assert_eq!(truncate("world,你好", 1, true), "…"); assert_eq!(truncate("world,你好", 2, true), "…"); assert_eq!(truncate("你好,世界", 3, true), "…界"); assert_eq!(truncate("你好,世界", 4, true), "…界"); assert_eq!(truncate("你好,世界", 5, true), "…世界"); assert_eq!(truncate("Hello, world", 5, true), "…orld"); assert_eq!(truncate("你好,Shi界", 3, true), "…界"); } #[test] fn test_truncate_oboe() { assert_eq!(truncate("Hello, world", 11, false), "Hello, wor…"); assert_eq!(truncate("你好,世界", 9, false), "你好,世…"); assert_eq!(truncate("你好,世Jie", 9, false), "你好,世…"); assert_eq!(truncate("Hello, world", 11, true), "…llo, world"); assert_eq!(truncate("你好,世界", 9, true), "…好,世界"); assert_eq!(truncate("Ni好,世界", 9, true), "…好,世界"); } #[test] fn test_truncate_exact() { assert_eq!(truncate("Hello, world", 12, false), "Hello, world"); assert_eq!(truncate("你好,世界", 10, false), "你好,世界"); assert_eq!(truncate("Hello, world", 12, true), "Hello, world"); assert_eq!(truncate("你好,世界", 10, true), "你好,世界"); } #[test] fn test_truncate_overflow() { assert_eq!(truncate("Hello, world", 13, false), "Hello, world"); assert_eq!(truncate("你好,世界", 11, false), "你好,世界"); assert_eq!(truncate("Hello, world", 13, true), "Hello, world"); assert_eq!(truncate("你好,世界", 11, true), "你好,世界"); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/border.rs
yazi-binding/src/elements/border.rs
use mlua::{AnyUserData, IntoLua, Lua, MetaMethod, Table, UserData, Value}; use ratatui::widgets::{Borders, Widget}; use super::{Area, Edge}; use crate::elements::Line; // Type const PLAIN: u8 = 0; const ROUNDED: u8 = 1; const DOUBLE: u8 = 2; const THICK: u8 = 3; const QUADRANT_INSIDE: u8 = 4; const QUADRANT_OUTSIDE: u8 = 5; #[derive(Clone, Debug, Default)] pub struct Border { pub area: Area, pub edge: Edge, pub r#type: ratatui::widgets::BorderType, pub style: ratatui::style::Style, pub titles: Vec<(ratatui::widgets::TitlePosition, ratatui::text::Line<'static>)>, } impl Border { pub fn compose(lua: &Lua) -> mlua::Result<Value> { let new = lua.create_function(|_, (_, edge): (Table, Edge)| { Ok(Self { edge, r#type: ratatui::widgets::BorderType::Rounded, ..Default::default() }) })?; let border = lua.create_table_from([ // Type ("PLAIN", PLAIN), ("ROUNDED", ROUNDED), ("DOUBLE", DOUBLE), ("THICK", THICK), ("QUADRANT_INSIDE", QUADRANT_INSIDE), ("QUADRANT_OUTSIDE", QUADRANT_OUTSIDE), ])?; border.set_metatable(Some(lua.create_table_from([(MetaMethod::Call.name(), new)])?))?; border.into_lua(lua) } pub(super) fn render(self, rect: ratatui::layout::Rect, buf: &mut ratatui::buffer::Buffer) { let mut block = ratatui::widgets::Block::default() .borders(self.edge.0) .border_type(self.r#type) .border_style(self.style); for title in self.titles { block = match title { (ratatui::widgets::TitlePosition::Top, line) => block.title(line), (ratatui::widgets::TitlePosition::Bottom, line) => block.title(line), }; } block.render(rect, buf); } } impl UserData for Border { fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) { crate::impl_area_method!(methods); crate::impl_style_method!(methods, style); methods.add_function_mut("type", |_, (ud, value): (AnyUserData, u8)| { ud.borrow_mut::<Self>()?.r#type = match value { ROUNDED => ratatui::widgets::BorderType::Rounded, DOUBLE => ratatui::widgets::BorderType::Double, THICK => ratatui::widgets::BorderType::Thick, QUADRANT_INSIDE => ratatui::widgets::BorderType::QuadrantInside, QUADRANT_OUTSIDE => ratatui::widgets::BorderType::QuadrantOutside, _ => ratatui::widgets::BorderType::Plain, }; Ok(ud) }); methods.add_function_mut( "title", |_, (ud, line, position): (AnyUserData, Value, Option<u8>)| { let position = if position == Some(Borders::BOTTOM.bits()) { ratatui::widgets::TitlePosition::Bottom } else { ratatui::widgets::TitlePosition::Top }; ud.borrow_mut::<Self>()?.titles.push((position, Line::try_from(line)?.inner)); Ok(ud) }, ); methods.add_function_mut("edge", |_, (ud, edge): (AnyUserData, Edge)| { ud.borrow_mut::<Self>()?.edge = edge; Ok(ud) }); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/constraint.rs
yazi-binding/src/elements/constraint.rs
use mlua::{FromLua, IntoLua, Lua, UserData, Value}; #[derive(Clone, Copy, Default, FromLua)] pub struct Constraint(pub(super) ratatui::layout::Constraint); impl Constraint { pub fn compose(lua: &Lua) -> mlua::Result<Value> { use ratatui::layout::Constraint as C; lua .create_table_from([ ("Min", lua.create_function(|_, n: u16| Ok(Self(C::Min(n))))?), ("Max", lua.create_function(|_, n: u16| Ok(Self(C::Max(n))))?), ("Length", lua.create_function(|_, n: u16| Ok(Self(C::Length(n))))?), ("Percentage", lua.create_function(|_, n: u16| Ok(Self(C::Percentage(n))))?), ("Ratio", lua.create_function(|_, (a, b): (u32, u32)| Ok(Self(C::Ratio(a, b))))?), ("Fill", lua.create_function(|_, n: u16| Ok(Self(C::Fill(n))))?), ])? .into_lua(lua) } } impl From<Constraint> for ratatui::layout::Constraint { fn from(value: Constraint) -> Self { value.0 } } impl UserData for Constraint {}
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/cell.rs
yazi-binding/src/elements/cell.rs
use mlua::{ExternalError, FromLua}; use super::Text; const EXPECTED: &str = "expected a table of strings, Texts, Lines or Spans"; #[derive(Clone, Debug)] pub struct Cell { pub(super) text: ratatui::text::Text<'static>, } impl From<Cell> for ratatui::widgets::Cell<'static> { fn from(value: Cell) -> Self { Self::new(value.text) } } impl FromLua for Cell { fn from_lua(value: mlua::Value, _: &mlua::Lua) -> mlua::Result<Self> { Ok(Self { text: Text::try_from(value).map_err(|_| EXPECTED.into_lua_err())?.inner }) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/pos.rs
yazi-binding/src/elements/pos.rs
use std::{ops::Deref, str::FromStr}; use mlua::{AnyUserData, ExternalError, ExternalResult, IntoLua, Lua, MetaMethod, Table, UserData, Value}; use super::Pad; const EXPECTED: &str = "expected a Pos"; #[derive(Clone, Copy, Default)] pub struct Pos { inner: yazi_config::popup::Position, pub(super) pad: Pad, } impl Deref for Pos { type Target = yazi_config::popup::Position; fn deref(&self) -> &Self::Target { &self.inner } } impl From<yazi_config::popup::Position> for Pos { fn from(value: yazi_config::popup::Position) -> Self { Self { inner: value, ..Default::default() } } } impl From<Pos> for yazi_config::popup::Position { fn from(value: Pos) -> Self { value.inner } } impl TryFrom<mlua::Table> for Pos { type Error = mlua::Error; fn try_from(t: mlua::Table) -> Result<Self, Self::Error> { use yazi_config::popup::{Offset, Origin, Position}; Ok(Self::from(Position { origin: Origin::from_str(&t.raw_get::<mlua::String>(1)?.to_str()?).into_lua_err()?, offset: Offset { x: t.raw_get("x").unwrap_or_default(), y: t.raw_get("y").unwrap_or_default(), width: t.raw_get("w").unwrap_or_default(), height: t.raw_get("h").unwrap_or_default(), }, })) } } impl TryFrom<Value> for Pos { type Error = mlua::Error; fn try_from(value: Value) -> Result<Self, Self::Error> { Ok(match value { Value::Table(tbl) => Self::try_from(tbl)?, Value::UserData(ud) => { if let Ok(pos) = ud.borrow() { *pos } else { Err(EXPECTED.into_lua_err())? } } _ => Err(EXPECTED.into_lua_err())?, }) } } impl Pos { pub fn compose(lua: &Lua) -> mlua::Result<Value> { let new = lua.create_function(|_, (_, t): (Table, Table)| Self::try_from(t))?; let position = lua.create_table()?; position.set_metatable(Some(lua.create_table_from([(MetaMethod::Call.name(), new)])?))?; position.into_lua(lua) } pub fn new_input(v: Value) -> mlua::Result<Self> { let mut p = Self::try_from(v)?; p.inner.offset.height = 3; Ok(p) } } impl UserData for Pos { fn add_fields<F: mlua::UserDataFields<Self>>(fields: &mut F) { // TODO: cache fields.add_field_method_get("1", |_, me| Ok(me.origin.to_string())); fields.add_field_method_get("x", |_, me| Ok(me.offset.x)); fields.add_field_method_get("y", |_, me| Ok(me.offset.y)); fields.add_field_method_get("w", |_, me| Ok(me.offset.width)); fields.add_field_method_get("h", |_, me| Ok(me.offset.height)); } fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) { methods.add_function_mut("pad", |_, (ud, pad): (AnyUserData, Pad)| { ud.borrow_mut::<Self>()?.pad = pad; Ok(ud) }); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-binding/src/elements/wrap.rs
yazi-binding/src/elements/wrap.rs
use std::ops::Deref; use mlua::{FromLua, IntoLua, Lua, Value}; use yazi_config::preview::PreviewWrap; #[derive(Clone, Copy, Debug, Default)] pub struct Wrap(pub(super) Option<ratatui::widgets::Wrap>); impl Deref for Wrap { type Target = Option<ratatui::widgets::Wrap>; fn deref(&self) -> &Self::Target { &self.0 } } impl Wrap { pub fn compose(lua: &Lua) -> mlua::Result<Value> { lua.create_table_from([("NO", 0), ("YES", 1), ("TRIM", 2)])?.into_lua(lua) } } impl From<ratatui::widgets::Wrap> for Wrap { fn from(value: ratatui::widgets::Wrap) -> Self { Self(Some(value)) } } impl From<PreviewWrap> for Wrap { fn from(value: PreviewWrap) -> Self { Self(match value { PreviewWrap::No => None, PreviewWrap::Yes => Some(ratatui::widgets::Wrap { trim: false }), }) } } impl FromLua for Wrap { fn from_lua(value: Value, _: &Lua) -> mlua::Result<Self> { let Value::Integer(n) = value else { return Err(mlua::Error::FromLuaConversionError { from: value.type_name(), to: "Wrap".to_string(), message: Some("expected an integer representation of a Wrap".to_string()), }); }; Ok(Self(match n { 0 => None, 1 => Some(ratatui::widgets::Wrap { trim: false }), 2 => Some(ratatui::widgets::Wrap { trim: true }), _ => Err(mlua::Error::FromLuaConversionError { from: value.type_name(), to: "Wrap".to_string(), message: Some("invalid value for Wrap".to_string()), })?, })) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/op.rs
yazi-fs/src/op.rs
use std::path::Path; use hashbrown::{HashMap, HashSet}; use yazi_macro::relay; use yazi_shared::{Id, Ids, path::PathBufDyn, url::{UrlBuf, UrlLike}}; use super::File; use crate::{cha::Cha, error::Error}; pub static FILES_TICKET: Ids = Ids::new(); #[derive(Clone, Debug)] pub enum FilesOp { Full(UrlBuf, Vec<File>, Cha), Part(UrlBuf, Vec<File>, Id), Done(UrlBuf, Cha, Id), Size(UrlBuf, HashMap<PathBufDyn, u64>), IOErr(UrlBuf, Error), Creating(UrlBuf, Vec<File>), Deleting(UrlBuf, HashSet<PathBufDyn>), Updating(UrlBuf, HashMap<PathBufDyn, File>), Upserting(UrlBuf, HashMap<PathBufDyn, File>), } impl FilesOp { #[inline] pub fn cwd(&self) -> &UrlBuf { match self { Self::Full(u, ..) => u, Self::Part(u, ..) => u, Self::Done(u, ..) => u, Self::Size(u, _) => u, Self::IOErr(u, _) => u, Self::Creating(u, _) => u, Self::Deleting(u, _) => u, Self::Updating(u, _) => u, Self::Upserting(u, _) => u, } } #[inline] pub fn emit(self) { yazi_shared::event::Event::Call(relay!(mgr:update_files).with_any("op", self).into()).emit(); } pub fn prepare(cwd: &UrlBuf) -> Id { let ticket = FILES_TICKET.next(); Self::Part(cwd.clone(), vec![], ticket).emit(); ticket } pub fn rename(map: HashMap<UrlBuf, File>) { let mut parents: HashMap<_, (HashSet<_>, HashMap<_, _>)> = Default::default(); for (o, n) in map { let Some(o_p) = o.parent() else { continue }; let Some(n_p) = n.url.parent() else { continue }; if o_p == n_p { parents.entry_ref(&o_p).or_default().1.insert(o.urn().into(), n); } else { parents.entry_ref(&o_p).or_default().0.insert(o.urn().into()); parents.entry_ref(&n_p).or_default().1.insert(n.urn().into(), n); } } for (p, (o, n)) in parents { match (o.is_empty(), n.is_empty()) { (true, true) => unreachable!(), (true, false) => Self::Upserting(p, n).emit(), (false, true) => Self::Deleting(p, o).emit(), (false, false) => { Self::Deleting(p.clone(), o).emit(); Self::Upserting(p, n).emit(); } } } } pub fn mutate(ops: Vec<Self>) { let mut parents: HashMap<_, (HashMap<_, _>, HashSet<_>)> = Default::default(); for op in ops { match op { Self::Upserting(p, map) => parents.entry(p).or_default().0.extend(map), Self::Deleting(p, urns) => parents.entry(p).or_default().1.extend(urns), _ => unreachable!(), } } for (p, (u, d)) in parents { match (u.is_empty(), d.is_empty()) { (true, true) => unreachable!(), (true, false) => Self::Deleting(p, d).emit(), (false, true) => Self::Upserting(p, u).emit(), (false, false) => { Self::Deleting(p.clone(), d).emit(); Self::Upserting(p, u).emit(); } } } } pub fn chdir(&self, wd: &Path) -> Self { macro_rules! files { ($files:expr) => {{ $files.iter().map(|file| file.chdir(wd)).collect() }}; } macro_rules! map { ($map:expr) => {{ $map.iter().map(|(urn, file)| (urn.clone(), file.chdir(wd))).collect() }}; } let w = UrlBuf::from(wd); match self { Self::Full(_, files, cha) => Self::Full(w, files!(files), *cha), Self::Part(_, files, ticket) => Self::Part(w, files!(files), *ticket), Self::Done(_, cha, ticket) => Self::Done(w, *cha, *ticket), Self::Size(_, map) => Self::Size(w, map.iter().map(|(urn, &s)| (urn.clone(), s)).collect()), Self::IOErr(_, err) => Self::IOErr(w, err.clone()), Self::Creating(_, files) => Self::Creating(w, files!(files)), Self::Deleting(_, urns) => Self::Deleting(w, urns.clone()), Self::Updating(_, map) => Self::Updating(w, map!(map)), Self::Upserting(_, map) => Self::Upserting(w, map!(map)), } } pub fn diff_recoverable(&self, contains: impl Fn(&UrlBuf) -> bool) -> (Vec<UrlBuf>, Vec<UrlBuf>) { match self { Self::Deleting(cwd, urns) => { (urns.iter().filter_map(|u| cwd.try_join(u).ok()).collect(), vec![]) } Self::Updating(cwd, urns) | Self::Upserting(cwd, urns) => urns .iter() .filter(|&(u, f)| u != f.urn()) .filter_map(|(u, f)| cwd.try_join(u).ok().map(|u| (u, f))) .filter(|(u, _)| contains(u)) .map(|(u, f)| (u, f.url_owned())) .unzip(), _ => (vec![], vec![]), } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/xdg.rs
yazi-fs/src/xdg.rs
use std::{env, path::PathBuf, sync::OnceLock}; pub struct Xdg; impl Xdg { pub fn config_dir() -> PathBuf { if let Some(p) = env::var_os("YAZI_CONFIG_HOME").map(PathBuf::from) && p.is_absolute() { return p; } #[cfg(windows)] { dirs::config_dir() .map(|p| p.join("yazi").join("config")) .expect("Failed to get config directory") } #[cfg(unix)] { env::var_os("XDG_CONFIG_HOME") .map(PathBuf::from) .filter(|p| p.is_absolute()) .or_else(|| dirs::home_dir().map(|h| h.join(".config"))) .map(|p| p.join("yazi")) .expect("Failed to get config directory") } } pub fn state_dir() -> PathBuf { #[cfg(windows)] { dirs::data_dir().map(|p| p.join("yazi").join("state")).expect("Failed to get state directory") } #[cfg(unix)] { env::var_os("XDG_STATE_HOME") .map(PathBuf::from) .filter(|p| p.is_absolute()) .or_else(|| dirs::home_dir().map(|h| h.join(".local/state"))) .map(|p| p.join("yazi")) .expect("Failed to get state directory") } } pub fn cache_dir() -> &'static PathBuf { static CACHE: OnceLock<PathBuf> = OnceLock::new(); CACHE.get_or_init(|| { let mut p = env::temp_dir(); assert!(p.is_absolute(), "Temp dir is not absolute"); #[cfg(unix)] { use uzers::Users; p.push(format!("yazi-{}", yazi_shared::USERS_CACHE.get_current_uid())) } #[cfg(not(unix))] p.push("yazi"); p }) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/stage.rs
yazi-fs/src/stage.rs
use serde::{Deserialize, Serialize}; use crate::error::Error; #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] pub enum FolderStage { #[default] Loading, Loaded, Failed(Error), } impl FolderStage { pub fn is_loading(&self) -> bool { *self == Self::Loading } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/lib.rs
yazi-fs/src/lib.rs
yazi_macro::mod_pub!(cha error mounts path provider); yazi_macro::mod_flat!(cwd file files filter fns hash op scheme sorter sorting splatter stage url xdg); pub fn init() { CWD.init(<_>::default()); mounts::init(); }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/filter.rs
yazi-fs/src/filter.rs
use std::{fmt::Display, ops::Range}; use anyhow::Result; use regex::bytes::{Regex, RegexBuilder}; use yazi_shared::{event::Cmd, strand::AsStrand}; pub struct Filter { raw: String, regex: Regex, } impl Filter { pub fn new(s: &str, case: FilterCase) -> Result<Self> { let regex = match case { FilterCase::Smart => { let uppercase = s.chars().any(|c| c.is_uppercase()); RegexBuilder::new(s).case_insensitive(!uppercase).build()? } FilterCase::Sensitive => Regex::new(s)?, FilterCase::Insensitive => RegexBuilder::new(s).case_insensitive(true).build()?, }; Ok(Self { raw: s.to_owned(), regex }) } #[inline] #[allow(private_bounds)] pub fn matches<T>(&self, name: T) -> bool where T: AsStrand, { self.regex.is_match(name.as_strand().encoded_bytes()) } #[inline] pub fn highlighted(&self, name: impl AsStrand) -> Option<Vec<Range<usize>>> { self.regex.find(name.as_strand().encoded_bytes()).map(|m| vec![m.range()]) } } impl PartialEq for Filter { fn eq(&self, other: &Self) -> bool { self.raw == other.raw } } impl Display for Filter { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.raw) } } #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub enum FilterCase { Smart, #[default] Sensitive, Insensitive, } impl From<&Cmd> for FilterCase { fn from(c: &Cmd) -> Self { match (c.bool("smart"), c.bool("insensitive")) { (true, _) => Self::Smart, (_, false) => Self::Sensitive, (_, true) => Self::Insensitive, } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/sorting.rs
yazi-fs/src/sorting.rs
use std::{fmt::Display, str::FromStr}; use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)] #[serde(rename_all = "kebab-case")] pub enum SortBy { #[default] None, Mtime, Btime, Extension, Alphabetical, Natural, Size, Random, } impl FromStr for SortBy { type Err = serde::de::value::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { Self::deserialize(serde::de::value::StrDeserializer::new(s)) } } impl Display for SortBy { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(match self { Self::None => "none", Self::Mtime => "mtime", Self::Btime => "btime", Self::Extension => "extension", Self::Alphabetical => "alphabetical", Self::Natural => "natural", Self::Size => "size", Self::Random => "random", }) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/url.rs
yazi-fs/src/url.rs
use std::{borrow::Cow, ffi::OsStr, path::{Path, PathBuf}}; use yazi_shared::{path::{AsPath, PathDyn}, url::{AsUrl, Url, UrlBuf, UrlCow}}; use crate::{FsHash128, FsScheme, path::PercentEncoding}; pub trait FsUrl<'a> { fn cache(&self) -> Option<PathBuf>; fn cache_lock(&self) -> Option<PathBuf>; fn unified_path(self) -> Cow<'a, Path>; fn unified_path_str(self) -> Cow<'a, OsStr> where Self: Sized, { match self.unified_path() { Cow::Borrowed(p) => p.as_os_str().into(), Cow::Owned(p) => p.into_os_string().into(), } } } impl<'a> FsUrl<'a> for Url<'a> { fn cache(&self) -> Option<PathBuf> { fn with_loc(loc: PathDyn, mut root: PathBuf) -> PathBuf { let mut it = loc.components(); if it.next() == Some(yazi_shared::path::Component::RootDir) { root.push(it.as_path().percent_encode()); } else { root.push(".%2F"); root.push(loc.percent_encode()); } root } self.scheme().cache().map(|root| with_loc(self.loc(), root)) } fn cache_lock(&self) -> Option<PathBuf> { self.scheme().cache().map(|mut root| { root.push("%lock"); root.push(format!("{:x}", self.hash_u128())); root }) } fn unified_path(self) -> Cow<'a, Path> { match self { Self::Regular(loc) | Self::Search { loc, .. } => loc.as_inner().into(), Self::Archive { .. } | Self::Sftp { .. } => { self.cache().expect("non-local URL should have a cache path").into() } } } } impl FsUrl<'_> for UrlBuf { fn cache(&self) -> Option<PathBuf> { self.as_url().cache() } fn cache_lock(&self) -> Option<PathBuf> { self.as_url().cache_lock() } fn unified_path(self) -> Cow<'static, Path> { match self { Self::Regular(loc) | Self::Search { loc, .. } => loc.into_inner().into(), Self::Archive { .. } | Self::Sftp { .. } => { self.cache().expect("non-local URL should have a cache path").into() } } } } impl<'a> FsUrl<'a> for UrlCow<'a> { fn cache(&self) -> Option<PathBuf> { self.as_url().cache() } fn cache_lock(&self) -> Option<PathBuf> { self.as_url().cache_lock() } fn unified_path(self) -> Cow<'a, Path> { match self { Self::Regular(loc) | Self::Search { loc, .. } => loc.into_inner().into(), Self::RegularRef(loc) | Self::SearchRef { loc, .. } => loc.as_inner().into(), Self::Archive { .. } | Self::ArchiveRef { .. } | Self::Sftp { .. } | Self::SftpRef { .. } => { self.cache().expect("non-local URL should have a cache path").into() } } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/file.rs
yazi-fs/src/file.rs
use std::{hash::{Hash, Hasher}, ops::Deref, path::Path}; use yazi_shared::{path::{PathBufDyn, PathDyn}, strand::Strand, url::{UrlBuf, UrlLike}}; use crate::cha::{Cha, ChaType}; #[derive(Clone, Debug, Default)] pub struct File { pub url: UrlBuf, pub cha: Cha, pub link_to: Option<PathBufDyn>, } impl Deref for File { type Target = Cha; fn deref(&self) -> &Self::Target { &self.cha } } impl From<&Self> for File { fn from(value: &Self) -> Self { value.clone() } } impl File { #[inline] pub fn from_dummy(url: impl Into<UrlBuf>, r#type: Option<ChaType>) -> Self { let url = url.into(); let cha = Cha::from_dummy(&url, r#type); Self { url, cha, link_to: None } } #[inline] pub fn chdir(&self, wd: &Path) -> Self { Self { url: self.url.rebase(wd), cha: self.cha, link_to: self.link_to.clone() } } } impl File { // --- Url #[inline] pub fn url_owned(&self) -> UrlBuf { self.url.clone() } #[inline] pub fn uri(&self) -> PathDyn<'_> { self.url.uri() } #[inline] pub fn urn(&self) -> PathDyn<'_> { self.url.urn() } #[inline] pub fn name(&self) -> Option<Strand<'_>> { self.url.name() } #[inline] pub fn stem(&self) -> Option<Strand<'_>> { self.url.stem() } } impl Hash for File { fn hash<H: Hasher>(&self, state: &mut H) { self.url.hash(state); self.cha.len.hash(state); self.cha.btime.hash(state); self.cha.ctime.hash(state); self.cha.mtime.hash(state); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fs/src/splatter.rs
yazi-fs/src/splatter.rs
#[cfg(unix)] use std::os::unix::ffi::{OsStrExt, OsStringExt}; #[cfg(windows)] use std::os::windows::ffi::{OsStrExt, OsStringExt}; use std::{cell::Cell, ffi::{OsStr, OsString}, iter::{self, Peekable}, mem}; use yazi_shared::url::{AsUrl, Url, UrlCow}; use crate::FsUrl; #[cfg(unix)] type Iter<'a> = Peekable<std::iter::Copied<std::slice::Iter<'a, u8>>>; #[cfg(windows)] type Iter<'a> = Peekable<std::os::windows::ffi::EncodeWide<'a>>; #[cfg(unix)] type Buf = Vec<u8>; #[cfg(windows)] type Buf = Vec<u16>; #[derive(Clone, Copy)] pub struct Splatter<T> { src: T, tab: usize, } pub trait Splatable { fn tab(&self) -> usize; fn selected(&self, tab: usize, idx: Option<usize>) -> impl Iterator<Item = Url<'_>>; fn hovered(&self, tab: usize) -> Option<Url<'_>>; fn yanked(&self) -> impl Iterator<Item = Url<'_>>; } #[cfg(unix)] fn b2c(b: u8) -> Option<char> { Some(b as char) } #[cfg(windows)] fn b2c(b: u16) -> Option<char> { char::from_u32(b as u32) } fn cue(buf: &mut Buf, s: impl AsRef<OsStr>) { #[cfg(unix)] buf.extend(yazi_shared::shell::escape_os_str(s.as_ref()).as_bytes()); #[cfg(windows)] buf.extend(yazi_shared::shell::escape_os_str(s.as_ref()).encode_wide()); } impl<T> Splatter<T> where T: Splatable, { pub fn new(src: T) -> Self { Self { tab: src.tab() + 1, src } } pub fn splat(mut self, cmd: impl AsRef<OsStr>) -> OsString { #[cfg(unix)] let mut it = cmd.as_ref().as_bytes().iter().copied().peekable(); #[cfg(windows)] let mut it = cmd.as_ref().encode_wide().peekable(); let mut buf = vec![]; while let Some(cur) = it.next() { if b2c(cur) == Some('%') && it.peek().is_some() { self.visit(&mut it, &mut buf); } else { buf.push(cur); } } #[cfg(unix)] return OsString::from_vec(buf); #[cfg(windows)] return OsString::from_wide(&buf); } fn visit(&mut self, it: &mut Iter, buf: &mut Buf) { let c = it.peek().copied().and_then(b2c); match c { Some('s') | Some('S') => self.visit_selected(it, buf), Some('h') | Some('H') => self.visit_hovered(it, buf), Some('d') | Some('D') => self.visit_dirname(it, buf), Some('t') | Some('T') => self.visit_tab(it, buf), Some('y') | Some('Y') => self.visit_yanked(it, buf), Some('%') => self.visit_escape(it, buf), Some('*') => self.visit_selected(it, buf), // TODO: remove this Some(c) if c.is_ascii_digit() => self.visit_digit(it, buf), _ => self.visit_unknown(it, buf), } } fn visit_selected(&mut self, it: &mut Iter, buf: &mut Buf) { let c = it.next().and_then(b2c); let idx = self.consume_digit(it); let mut first = true; for url in self.src.selected(self.tab, idx) { if !mem::replace(&mut first, false) { buf.push(b' ' as _); } if c == Some('S') { cue(buf, url.os_str()); } else { cue(buf, url.unified_path_str()); } } if first && idx.is_some() { cue(buf, ""); } } fn visit_hovered(&mut self, it: &mut Iter, buf: &mut Buf) { match it.next().and_then(b2c) { Some('h') => { cue(buf, self.src.hovered(self.tab).map(|u| u.unified_path_str()).unwrap_or_default()); } Some('H') => { cue(buf, self.src.hovered(self.tab).map(|u| u.os_str()).unwrap_or_default()); } _ => unreachable!(), } } fn visit_dirname(&mut self, it: &mut Iter, buf: &mut Buf) { let c = it.next().and_then(b2c); let idx = self.consume_digit(it); let mut first = true; for url in self.src.selected(self.tab, idx) { if !mem::replace(&mut first, false) { buf.push(b' ' as _); } if c == Some('D') { cue(buf, url.parent().map(|p| p.os_str()).unwrap_or_default()); } else { cue(buf, url.parent().map(|p| p.unified_path_str()).unwrap_or_default()); } } if first && idx.is_some() { cue(buf, ""); } } fn visit_tab(&mut self, it: &mut Iter, buf: &mut Buf) { let old = self.tab; match it.next().and_then(b2c) { Some('t') => self.tab = self.tab.saturating_add(1), Some('T') => self.tab = self.tab.saturating_sub(1), _ => unreachable!(), } self.visit(it, buf); self.tab = old; } fn visit_digit(&mut self, it: &mut Iter, buf: &mut Buf) { // TODO: remove match self.consume_digit(it) { Some(0) => { cue(buf, self.src.hovered(self.tab).map(|u| u.unified_path_str()).unwrap_or_default()); } Some(n) => { cue( buf, self .src .selected(self.tab, Some(n)) .next() .map(|u| u.unified_path_str()) .unwrap_or_default(), ); } None => unreachable!(), } } fn visit_yanked(&mut self, it: &mut Iter, buf: &mut Buf) { let c = it.next().and_then(b2c); let mut first = true; for url in self.src.yanked() { if !mem::replace(&mut first, false) { buf.push(b' ' as _); } if c == Some('Y') { cue(buf, url.os_str()); } else { cue(buf, url.unified_path_str()); } } } fn visit_escape(&mut self, it: &mut Iter, buf: &mut Buf) { buf.push(it.next().unwrap()); } fn visit_unknown(&mut self, it: &mut Iter, buf: &mut Buf) { buf.push(b'%' as _); if let Some(b) = it.next() { buf.push(b); } } fn consume_digit(&mut self, it: &mut Iter) -> Option<usize> { fn next(it: &mut Iter) -> Option<usize> { let n = b2c(*it.peek()?)?.to_digit(10)? as usize; it.next(); Some(n) } let mut sum = next(it)?; while let Some(n) = next(it) { sum = sum.checked_mul(10)?.checked_add(n)?; } Some(sum) } } impl<T> Splatter<T> { pub fn spread(cmd: impl AsRef<OsStr>) -> bool { struct Source(Cell<bool>); impl Splatable for &Source { fn tab(&self) -> usize { 0 } fn selected(&self, _tab: usize, idx: Option<usize>) -> impl Iterator<Item = Url<'_>> { if idx.is_none() { self.0.set(true); } iter::empty() } fn hovered(&self, _tab: usize) -> Option<Url<'_>> { None } fn yanked(&self) -> impl Iterator<Item = Url<'_>> { self.0.set(true); iter::empty() } } let src = Source(Cell::new(false)); Splatter { src: &src, tab: 1 }.splat(cmd.as_ref()); src.0.get() } } // TODO: remove impl<'a, T> Splatable for &'a T where T: AsRef<[UrlCow<'a>]>, { fn tab(&self) -> usize { 0 } fn selected(&self, tab: usize, idx: Option<usize>) -> impl Iterator<Item = Url<'_>> { self .as_ref() .iter() .filter(move |_| tab == 1) .map(|u| u.as_url()) .skip(idx.unwrap_or(1)) .take(if idx.is_some() { 1 } else { usize::MAX }) } fn hovered(&self, tab: usize) -> Option<Url<'_>> { self.as_ref().first().filter(|_| tab == 1).map(|u| u.as_url()) } fn yanked(&self) -> impl Iterator<Item = Url<'_>> { iter::empty() } } #[cfg(test)] mod tests { use super::*; struct Source(usize); impl Splatable for Source { fn tab(&self) -> usize { self.0 } fn selected(&self, tab: usize, mut idx: Option<usize>) -> impl Iterator<Item = Url<'_>> { let urls = if tab == 1 { vec![Url::regular("t1/s1"), Url::regular("t1/s2")] } else if tab == 2 { vec![Url::regular("t 2/s 1"), Url::regular("t 2/s 2")] } else { vec![] }; idx = idx.and_then(|i| i.checked_sub(1)); urls.into_iter().skip(idx.unwrap_or(0)).take(if idx.is_some() { 1 } else { usize::MAX }) } fn hovered(&self, tab: usize) -> Option<Url<'_>> { if tab == 1 { Some(Url::regular("hovered")) } else if tab == 2 { Some(Url::regular("hover ed")) } else { None } } fn yanked(&self) -> impl Iterator<Item = Url<'_>> { [Url::regular("y1"), Url::regular("y 2"), Url::regular("y3")].into_iter() } } #[test] #[cfg(unix)] fn test_unix() { let cases = [ // Selected (Source(0), r#"ls %s"#, r#"ls t1/s1 t1/s2"#), (Source(0), r#"ls %s1 %s2 %s3"#, r#"ls t1/s1 t1/s2 ''"#), (Source(0), r#"ls %s %s2 %s"#, r#"ls t1/s1 t1/s2 t1/s2 t1/s1 t1/s2"#), (Source(1), r#"ls %s"#, r#"ls 't 2/s 1' 't 2/s 2'"#), (Source(1), r#"ls %s1 %s3 %s2"#, r#"ls 't 2/s 1' '' 't 2/s 2'"#), (Source(2), r#"ls %s"#, r#"ls "#), (Source(2), r#"ls %s1 %s %s2"#, r#"ls '' ''"#), // Hovered (Source(0), r#"ls %h"#, r#"ls hovered"#), (Source(1), r#"ls %h"#, r#"ls 'hover ed'"#), (Source(2), r#"ls %h"#, r#"ls ''"#), // Dirname (Source(0), r#"cd %d"#, r#"cd t1 t1"#), (Source(1), r#"cd %d"#, r#"cd 't 2' 't 2'"#), (Source(1), r#"cd %d1 %d3 %d2"#, r#"cd 't 2' '' 't 2'"#), (Source(2), r#"cd %d %d1"#, r#"cd ''"#), // Yanked (Source(0), r#"cd %y"#, r#"cd y1 'y 2' y3"#), (Source(1), r#"cd %y"#, r#"cd y1 'y 2' y3"#), (Source(2), r#"cd %y"#, r#"cd y1 'y 2' y3"#), // Tab (Source(0), r#"ls %s %ts %s"#, r#"ls t1/s1 t1/s2 't 2/s 1' 't 2/s 2' t1/s1 t1/s2"#), (Source(1), r#"ls %s1 %ts %s2"#, r#"ls 't 2/s 1' 't 2/s 2'"#), (Source(1), r#"ls %s1 %Ts1 %s2 %Ts2"#, r#"ls 't 2/s 1' t1/s1 't 2/s 2' t1/s2"#), (Source(0), r#"ls %s1 %Ts1 %s2 %Ts2"#, r#"ls t1/s1 '' t1/s2 ''"#), (Source(0), r#"ls %ty"#, r#"ls y1 'y 2' y3"#), (Source(0), r#"ls %Ty"#, r#"ls y1 'y 2' y3"#), // Escape ( Source(0), r#"echo % %% %s2 %%h %d %%%y %%%%ts %%%%%ts1"#, r#"echo % % t1/s2 %h t1 t1 %y1 'y 2' y3 %%ts %%'t 2/s 1'"#, ), // TODO: remove (Source(0), r#"ls %1 %* %2 %0 %3"#, r#"ls t1/s1 t1/s1 t1/s2 t1/s2 hovered ''"#), ]; for (src, cmd, expected) in cases { let s = Splatter::new(src).splat(OsStr::new(cmd)); assert_eq!(s, OsStr::new(expected), "{cmd}"); } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false