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-shared/src/scheme/scheme.rs
yazi-shared/src/scheme/scheme.rs
use std::hash::{Hash, Hasher}; use crate::{pool::Symbol, scheme::{AsScheme, SchemeRef}}; #[derive(Clone, Debug, Eq, PartialEq)] pub enum Scheme { Regular { uri: usize, urn: usize }, Search { domain: Symbol<str>, uri: usize, urn: usize }, Archive { domain: Symbol<str>, uri: usize, urn: usize }, Sftp { domain: Symbol<str>, uri: usize, urn: usize }, } impl Hash for Scheme { fn hash<H: Hasher>(&self, state: &mut H) { self.as_scheme().hash(state); } } impl PartialEq<SchemeRef<'_>> for Scheme { fn eq(&self, other: &SchemeRef<'_>) -> bool { self.as_scheme() == *other } } impl Scheme { #[inline] pub fn into_domain(self) -> Option<Symbol<str>> { match self { Self::Regular { .. } => None, Self::Search { domain, .. } | Self::Archive { domain, .. } | Self::Sftp { domain, .. } => { Some(domain) } } } #[inline] pub fn with_ports(self, uri: usize, urn: usize) -> Self { match self { Self::Regular { .. } => Self::Regular { uri, urn }, Self::Search { domain, .. } => Self::Search { domain, uri, urn }, Self::Archive { domain, .. } => Self::Archive { domain, uri, urn }, Self::Sftp { domain, .. } => Self::Sftp { domain, uri, urn }, } } #[inline] pub fn zeroed(self) -> Self { self.with_ports(0, 0) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/scheme/traits.rs
yazi-shared/src/scheme/traits.rs
use crate::scheme::{Scheme, SchemeCow, SchemeKind, SchemeRef}; pub trait AsScheme { fn as_scheme(&self) -> SchemeRef<'_>; } impl AsScheme for SchemeRef<'_> { #[inline] fn as_scheme(&self) -> SchemeRef<'_> { *self } } impl AsScheme for Scheme { #[inline] fn as_scheme(&self) -> SchemeRef<'_> { match *self { Self::Regular { uri, urn } => SchemeRef::Regular { uri, urn }, Self::Search { ref domain, uri, urn } => SchemeRef::Search { domain, uri, urn }, Self::Archive { ref domain, uri, urn } => SchemeRef::Archive { domain, uri, urn }, Self::Sftp { ref domain, uri, urn } => SchemeRef::Sftp { domain, uri, urn }, } } } impl AsScheme for &Scheme { #[inline] fn as_scheme(&self) -> SchemeRef<'_> { (**self).as_scheme() } } impl AsScheme for SchemeCow<'_> { #[inline] fn as_scheme(&self) -> SchemeRef<'_> { match self { SchemeCow::Borrowed(s) => *s, SchemeCow::Owned(s) => s.as_scheme(), } } } impl AsScheme for &SchemeCow<'_> { #[inline] fn as_scheme(&self) -> SchemeRef<'_> { (**self).as_scheme() } } // --- SchemeLike pub trait SchemeLike where Self: AsScheme + Sized, { fn kind(&self) -> SchemeKind { *self.as_scheme() } fn domain(&self) -> Option<&str> { self.as_scheme().domain() } fn covariant(&self, other: impl AsScheme) -> bool { self.as_scheme().covariant(other) } fn is_local(&self) -> bool { self.as_scheme().is_local() } fn is_remote(&self) -> bool { self.as_scheme().is_remote() } fn is_virtual(&self) -> bool { self.as_scheme().is_virtual() } } impl SchemeLike for Scheme {} impl SchemeLike for SchemeCow<'_> {}
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/event/event.rs
yazi-shared/src/event/event.rs
use crossterm::event::{KeyEvent, MouseEvent}; use tokio::sync::mpsc; use super::CmdCow; use crate::{RoCell, strand::StrandBuf}; static TX: RoCell<mpsc::UnboundedSender<Event>> = RoCell::new(); static RX: RoCell<mpsc::UnboundedReceiver<Event>> = RoCell::new(); #[derive(Debug)] pub enum Event { Call(CmdCow), Seq(Vec<CmdCow>), Render, Key(KeyEvent), Mouse(MouseEvent), Resize, Paste(String), Quit(EventQuit), } #[derive(Debug, Default)] pub struct EventQuit { pub code: i32, pub no_cwd_file: bool, pub selected: Option<StrandBuf>, } impl Event { #[inline] pub fn init() { let (tx, rx) = mpsc::unbounded_channel(); TX.init(tx); RX.init(rx); } #[inline] pub fn take() -> mpsc::UnboundedReceiver<Self> { RX.drop() } #[inline] pub fn emit(self) { TX.send(self).ok(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/event/mod.rs
yazi-shared/src/event/mod.rs
yazi_macro::mod_flat!(cmd cow event); pub static NEED_RENDER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/event/cow.rs
yazi-shared/src/event/cow.rs
use std::ops::Deref; use anyhow::Result; use super::Cmd; use crate::data::{Data, DataKey}; #[derive(Debug)] pub enum CmdCow { Owned(Cmd), Borrowed(&'static Cmd), } impl From<Cmd> for CmdCow { fn from(c: Cmd) -> Self { Self::Owned(c) } } impl From<&'static Cmd> for CmdCow { fn from(c: &'static Cmd) -> Self { Self::Borrowed(c) } } impl Deref for CmdCow { type Target = Cmd; fn deref(&self) -> &Self::Target { match self { Self::Owned(c) => c, Self::Borrowed(c) => c, } } } impl CmdCow { pub fn take<'a, T>(&mut self, name: impl Into<DataKey>) -> Result<T> where T: TryFrom<Data> + TryFrom<&'a Data>, <T as TryFrom<Data>>::Error: Into<anyhow::Error>, <T as TryFrom<&'a Data>>::Error: Into<anyhow::Error>, { match self { Self::Owned(c) => c.take(name), Self::Borrowed(c) => c.get(name), } } pub fn take_first<'a, T>(&mut self) -> Result<T> where T: TryFrom<Data> + TryFrom<&'a Data>, <T as TryFrom<Data>>::Error: Into<anyhow::Error>, <T as TryFrom<&'a Data>>::Error: Into<anyhow::Error>, { match self { Self::Owned(c) => c.take_first(), Self::Borrowed(c) => c.first(), } } pub fn take_second<'a, T>(&mut self) -> Result<T> where T: TryFrom<Data> + TryFrom<&'a Data>, <T as TryFrom<Data>>::Error: Into<anyhow::Error>, <T as TryFrom<&'a Data>>::Error: Into<anyhow::Error>, { match self { Self::Owned(c) => c.take_second(), Self::Borrowed(c) => c.second(), } } pub fn take_seq<'a, T>(&mut self) -> Vec<T> where T: TryFrom<Data> + TryFrom<&'a Data>, <T as TryFrom<Data>>::Error: Into<anyhow::Error>, <T as TryFrom<&'a Data>>::Error: Into<anyhow::Error>, { match self { Self::Owned(c) => c.take_seq(), Self::Borrowed(c) => c.seq(), } } pub fn take_any<T: 'static>(&mut self, name: impl Into<DataKey>) -> Option<T> { match self { Self::Owned(c) => c.take_any(name), Self::Borrowed(_) => None, } } pub fn take_any2<T: 'static>(&mut self, name: impl Into<DataKey>) -> Option<Result<T>> { match self { Self::Owned(c) => c.take_any2(name), Self::Borrowed(_) => None, } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/event/cmd.rs
yazi-shared/src/event/cmd.rs
use std::{any::Any, borrow::Cow, fmt::{self, Display}, mem, str::FromStr}; use anyhow::{Result, anyhow, bail}; use hashbrown::HashMap; use serde::{Deserialize, de}; use crate::{Layer, SStr, Source, data::{Data, DataKey}}; #[derive(Debug, Default)] pub struct Cmd { pub name: SStr, pub args: HashMap<DataKey, Data>, pub layer: Layer, pub source: Source, } impl Cmd { pub fn new<N>(name: N, source: Source, default: Option<Layer>) -> Result<Self> where N: Into<SStr>, { let cow: SStr = name.into(); let (layer, name) = match cow.find(':') { None => (default.ok_or_else(|| anyhow!("Cannot infer layer from command name: {cow}"))?, cow), Some(i) => (cow[..i].parse()?, match cow { Cow::Borrowed(s) => Cow::Borrowed(&s[i + 1..]), Cow::Owned(mut s) => { s.drain(..i + 1); Cow::Owned(s) } }), }; Ok(Self { name, args: Default::default(), layer, source }) } pub fn new_relay<N>(name: N) -> Self where N: Into<SStr>, { Self::new(name, Source::Relay, None).unwrap_or(Self::null()) } pub fn new_relay_args<N, D, I>(name: N, args: I) -> Self where N: Into<SStr>, D: Into<Data>, I: IntoIterator<Item = D>, { let mut cmd = Self::new(name, Source::Relay, None).unwrap_or(Self::null()); cmd.args = args.into_iter().enumerate().map(|(i, a)| (DataKey::Integer(i as i64), a.into())).collect(); cmd } fn null() -> Self { Self { name: Cow::Borrowed("null"), ..Default::default() } } pub fn len(&self) -> usize { self.args.len() } pub fn is_empty(&self) -> bool { self.args.is_empty() } // --- With pub fn with(mut self, name: impl Into<DataKey>, value: impl Into<Data>) -> Self { self.args.insert(name.into(), value.into()); self } pub fn with_seq<I>(mut self, values: I) -> Self where I: IntoIterator, I::Item: Into<Data>, { for (i, v) in values.into_iter().enumerate() { self.args.insert(DataKey::Integer(i as i64), v.into()); } self } pub fn with_any(mut self, name: impl Into<DataKey>, data: impl Any + Send + Sync) -> Self { self.args.insert(name.into(), Data::Any(Box::new(data))); self } // --- Get pub fn get<'a, T>(&'a self, name: impl Into<DataKey>) -> Result<T> where T: TryFrom<&'a Data>, T::Error: Into<anyhow::Error>, { let name = name.into(); match self.args.get(&name) { Some(data) => data.try_into().map_err(Into::into), None => bail!("argument not found: {:?}", name), } } pub fn str(&self, name: impl Into<DataKey>) -> &str { self.get(name).unwrap_or_default() } pub fn bool(&self, name: impl Into<DataKey>) -> bool { self.get(name).unwrap_or(false) } pub fn first<'a, T>(&'a self) -> Result<T> where T: TryFrom<&'a Data>, T::Error: Into<anyhow::Error>, { self.get(0) } pub fn second<'a, T>(&'a self) -> Result<T> where T: TryFrom<&'a Data>, T::Error: Into<anyhow::Error>, { self.get(1) } pub fn seq<'a, T>(&'a self) -> Vec<T> where T: TryFrom<&'a Data>, { let mut seq = Vec::with_capacity(self.len()); for i in 0..self.len() { if let Ok(data) = self.get::<&Data>(i) && let Ok(v) = data.try_into() { seq.push(v); } else { break; } } seq } // --- Take pub fn take<T>(&mut self, name: impl Into<DataKey>) -> Result<T> where T: TryFrom<Data>, T::Error: Into<anyhow::Error>, { let name = name.into(); match self.args.remove(&name) { Some(data) => data.try_into().map_err(Into::into), None => bail!("argument not found: {:?}", name), } } pub fn take_first<T>(&mut self) -> Result<T> where T: TryFrom<Data>, T::Error: Into<anyhow::Error>, { self.take(0) } pub fn take_second<T>(&mut self) -> Result<T> where T: TryFrom<Data>, T::Error: Into<anyhow::Error>, { self.take(1) } pub fn take_seq<T>(&mut self) -> Vec<T> where T: TryFrom<Data>, { let mut seq = Vec::with_capacity(self.len()); for i in 0..self.len() { if let Ok(data) = self.take::<Data>(i) && let Ok(v) = data.try_into() { seq.push(v); } else { break; } } seq } pub fn take_any<T: 'static>(&mut self, name: impl Into<DataKey>) -> Option<T> { self.args.remove(&name.into())?.into_any() } pub fn take_any2<T: 'static>(&mut self, name: impl Into<DataKey>) -> Option<Result<T>> { self.args.remove(&name.into()).map(Data::into_any2) } // Parse pub fn parse_args<I>(words: I, last: Option<String>) -> Result<HashMap<DataKey, Data>> where I: IntoIterator<Item = String>, { let mut i = 0i64; words .into_iter() .map(|s| (s, true)) .chain(last.into_iter().map(|s| (s, false))) .map(|(word, normal)| { let Some(arg) = word.strip_prefix("--").filter(|&s| normal && !s.is_empty()) else { i += 1; return Ok((DataKey::Integer(i - 1), word.into())); }; let mut parts = arg.splitn(2, '='); let key = parts.next().expect("at least one part"); let val = parts.next().map_or(Data::Boolean(true), Data::from); Ok((DataKey::from(key.to_owned()), val)) }) .collect() } } impl Display for Cmd { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.name)?; for i in 0..self.args.len() { let Ok(s) = self.get::<&str>(i) else { break }; write!(f, " {s}")?; } for (k, v) in &self.args { if let DataKey::String(k) = k { if v.try_into().is_ok_and(|b| b) { write!(f, " --{k}")?; } else if let Some(s) = v.as_str() { write!(f, " --{k}={s}")?; } } } Ok(()) } } impl FromStr for Cmd { type Err = anyhow::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let (mut words, last) = crate::shell::unix::split(s, true)?; if words.is_empty() || words[0].is_empty() { bail!("command name cannot be empty"); } let mut me = Self::new(mem::take(&mut words[0]), Default::default(), Some(Default::default()))?; me.args = Self::parse_args(words.into_iter().skip(1), last)?; Ok(me) } } impl<'de> Deserialize<'de> for Cmd { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { <_>::from_str(&String::deserialize(deserializer)?).map_err(de::Error::custom) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/loc/loc.rs
yazi-shared/src/loc/loc.rs
use std::{hash::{Hash, Hasher}, marker::PhantomData, ops::Deref}; use anyhow::{Result, bail}; use super::LocAbleImpl; use crate::{loc::{LocAble, LocBuf, LocBufAble, StrandAbleImpl}, path::{AsPath, AsPathView, PathDyn}, scheme::SchemeKind, strand::AsStrandView}; #[derive(Clone, Copy, Debug)] pub struct Loc<'p, P = &'p std::path::Path> { pub(super) inner: P, pub(super) uri: usize, pub(super) urn: usize, pub(super) _phantom: PhantomData<&'p ()>, } impl<'p, P> Default for Loc<'p, P> where P: LocAble<'p> + LocAbleImpl<'p>, { fn default() -> Self { Self { inner: P::empty(), uri: 0, urn: 0, _phantom: PhantomData } } } impl<'p, P> Deref for Loc<'p, P> where P: LocAble<'p>, { type Target = P; fn deref(&self) -> &Self::Target { &self.inner } } impl<'p, P> AsPath for Loc<'p, P> where P: LocAble<'p> + AsPath, { fn as_path(&self) -> PathDyn<'_> { self.inner.as_path() } } // FIXME: remove impl AsRef<std::path::Path> for Loc<'_, &std::path::Path> { fn as_ref(&self) -> &std::path::Path { self.inner } } // --- Hash impl<'p, P> Hash for Loc<'p, P> where P: LocAble<'p> + Hash, { fn hash<H: Hasher>(&self, state: &mut H) { self.inner.hash(state) } } impl<'p, P> From<Loc<'p, P>> for LocBuf<<P as LocAble<'p>>::Owned> where P: LocAble<'p> + LocAbleImpl<'p>, <P as LocAble<'p>>::Owned: LocBufAble, { fn from(value: Loc<'p, P>) -> Self { Self { inner: value.inner.to_path_buf(), uri: value.uri, urn: value.urn } } } // --- Eq impl<'p, P> PartialEq for Loc<'p, P> where P: LocAble<'p> + PartialEq, { fn eq(&self, other: &Self) -> bool { self.inner == other.inner } } impl<'p, P> Eq for Loc<'p, P> where P: LocAble<'p> + Eq {} impl<'p, P> Loc<'p, P> where P: LocAble<'p> + LocAbleImpl<'p>, { #[inline] pub fn as_inner(self) -> P { self.inner } #[inline] pub fn as_loc(self) -> Self { self } pub fn bare<T>(path: T) -> Self where T: AsPathView<'p, P>, { let path = path.as_path_view(); let Some(name) = path.file_name() else { let p = path.strip_prefix(P::empty()).unwrap(); return Self { inner: p, uri: 0, urn: 0, _phantom: PhantomData }; }; let name_len = name.len(); let prefix_len = unsafe { name.as_encoded_bytes().as_ptr().offset_from_unsigned(path.as_encoded_bytes().as_ptr()) }; let bytes = &path.as_encoded_bytes()[..prefix_len + name_len]; Self { inner: unsafe { P::from_encoded_bytes_unchecked(bytes) }, uri: name_len, urn: name_len, _phantom: PhantomData, } } #[inline] pub fn base(self) -> P { unsafe { P::from_encoded_bytes_unchecked( self.inner.as_encoded_bytes().get_unchecked(..self.inner.len() - self.uri), ) } } pub fn floated<'a, T, S>(path: T, base: S) -> Self where T: AsPathView<'p, P>, S: AsStrandView<'a, P::Strand<'a>>, { let mut loc = Self::bare(path); loc.uri = loc.inner.strip_prefix(base).expect("Loc must start with the given base").len(); loc } #[inline] pub fn has_base(self) -> bool { self.inner.len() != self.uri } #[inline] pub fn has_trail(self) -> bool { self.inner.len() != self.urn } #[inline] pub fn is_empty(self) -> bool { self.inner.len() == 0 } pub fn new<'a, T, S>(path: T, base: S, trail: S) -> Self where T: AsPathView<'p, P>, S: AsStrandView<'a, P::Strand<'a>>, { let mut loc = Self::bare(path); loc.uri = loc.inner.strip_prefix(base).expect("Loc must start with the given base").len(); loc.urn = loc.inner.strip_prefix(trail).expect("Loc must start with the given trail").len(); loc } #[inline] pub fn parent(self) -> Option<P> { self.inner.parent().filter(|p| !p.as_encoded_bytes().is_empty()) } pub fn saturated<'a, T>(path: T, kind: SchemeKind) -> Self where T: AsPathView<'p, P>, { match kind { SchemeKind::Regular => Self::bare(path), SchemeKind::Search => Self::zeroed(path), SchemeKind::Archive => Self::zeroed(path), SchemeKind::Sftp => Self::bare(path), } } #[inline] pub fn trail(self) -> P { unsafe { P::from_encoded_bytes_unchecked( self.inner.as_encoded_bytes().get_unchecked(..self.inner.len() - self.urn), ) } } #[inline] pub fn triple(self) -> (P, P, P) { let len = self.inner.len(); let base = ..len - self.uri; let rest = len - self.uri..len - self.urn; let urn = len - self.urn..; unsafe { ( P::from_encoded_bytes_unchecked(self.inner.as_encoded_bytes().get_unchecked(base)), P::from_encoded_bytes_unchecked(self.inner.as_encoded_bytes().get_unchecked(rest)), P::from_encoded_bytes_unchecked(self.inner.as_encoded_bytes().get_unchecked(urn)), ) } } #[inline] pub fn uri(self) -> P { unsafe { P::from_encoded_bytes_unchecked( self.inner.as_encoded_bytes().get_unchecked(self.inner.len() - self.uri..), ) } } #[inline] pub fn urn(self) -> P { unsafe { P::from_encoded_bytes_unchecked( self.inner.as_encoded_bytes().get_unchecked(self.inner.len() - self.urn..), ) } } pub fn with<T>(path: T, uri: usize, urn: usize) -> Result<Self> where T: AsPathView<'p, P>, { if urn > uri { bail!("URN cannot be longer than URI"); } let mut loc = Self::bare(path); if uri == 0 { (loc.uri, loc.urn) = (0, 0); return Ok(loc); } else if urn == 0 { loc.urn = 0; } let mut it = loc.inner.components(); for i in 1..=uri { if it.next_back().is_none() { bail!("URI exceeds the entire URL"); } if i == urn { loc.urn = loc.strip_prefix(it.clone()).unwrap().len(); } if i == uri { loc.uri = loc.strip_prefix(it).unwrap().len(); break; } } Ok(loc) } pub fn zeroed<T>(path: T) -> Self where T: AsPathView<'p, P>, { let mut loc = Self::bare(path); (loc.uri, loc.urn) = (0, 0); loc } } #[cfg(test)] mod tests { use super::*; #[test] fn test_with() -> Result<()> { let cases = [ // Relative paths ("tmp/test.zip/foo/bar", 3, 2, "test.zip/foo/bar", "foo/bar"), ("tmp/test.zip/foo/bar/", 3, 2, "test.zip/foo/bar", "foo/bar"), // Absolute paths ("/tmp/test.zip/foo/bar", 3, 2, "test.zip/foo/bar", "foo/bar"), ("/tmp/test.zip/foo/bar/", 3, 2, "test.zip/foo/bar", "foo/bar"), // Relative path with parent components ("tmp/test.zip/foo/bar/../..", 5, 4, "test.zip/foo/bar/../..", "foo/bar/../.."), ("tmp/test.zip/foo/bar/../../", 5, 4, "test.zip/foo/bar/../..", "foo/bar/../.."), // Absolute path with parent components ("/tmp/test.zip/foo/bar/../..", 5, 4, "test.zip/foo/bar/../..", "foo/bar/../.."), ("/tmp/test.zip/foo/bar/../../", 5, 4, "test.zip/foo/bar/../..", "foo/bar/../.."), ]; for (path, uri, urn, expect_uri, expect_urn) in cases { let loc = Loc::with(std::path::Path::new(path), uri, urn)?; assert_eq!(loc.uri().to_str().unwrap(), expect_uri); assert_eq!(loc.urn().to_str().unwrap(), expect_urn); let loc = Loc::with(typed_path::UnixPath::new(path), uri, urn)?; assert_eq!(loc.uri().to_str().unwrap(), expect_uri); assert_eq!(loc.urn().to_str().unwrap(), expect_urn); } Ok(()) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/loc/able.rs
yazi-shared/src/loc/able.rs
use std::{ffi::{OsStr, OsString}, fmt::Debug, hash::Hash}; use crate::{path::{AsPath, AsPathView}, strand::AsStrandView}; // --- LocAble pub trait LocAble<'p> where Self: Copy + AsStrandView<'p, Self::Strand<'p>>, { type Strand<'a>: StrandAble<'a> + StrandAbleImpl<'a>; type Owned: LocBufAble + LocBufAbleImpl + Into<Self::Owned>; type Components<'a>: Clone + DoubleEndedIterator + AsStrandView<'a, Self::Strand<'a>>; } impl<'p> LocAble<'p> for &'p std::path::Path { type Components<'a> = std::path::Components<'a>; type Owned = std::path::PathBuf; type Strand<'a> = &'a OsStr; } impl<'p> LocAble<'p> for &'p typed_path::UnixPath { type Components<'a> = typed_path::UnixComponents<'a>; type Owned = typed_path::UnixPathBuf; type Strand<'a> = &'a [u8]; } // --- LocBufAble pub trait LocBufAble where Self: 'static + AsPath + Default, { type Strand<'a>: StrandAble<'a>; type Borrowed<'a>: LocAble<'a> + LocAbleImpl<'a> + AsPathView<'a, Self::Borrowed<'a>> + Debug + Hash; } impl LocBufAble for std::path::PathBuf { type Borrowed<'a> = &'a std::path::Path; type Strand<'a> = &'a OsStr; } impl LocBufAble for typed_path::UnixPathBuf { type Borrowed<'a> = &'a typed_path::UnixPath; type Strand<'a> = &'a [u8]; } // --- StrandAble pub trait StrandAble<'a>: Copy {} impl<'a> StrandAble<'a> for &'a OsStr {} impl<'a> StrandAble<'a> for &'a [u8] {} // --- LocAbleImpl pub(super) trait LocAbleImpl<'p>: LocAble<'p> { fn as_encoded_bytes(self) -> &'p [u8]; fn components(self) -> Self::Components<'p>; fn empty() -> Self; fn file_name(self) -> Option<Self::Strand<'p>>; unsafe fn from_encoded_bytes_unchecked(bytes: &'p [u8]) -> Self; fn join<'a, T>(self, path: T) -> Self::Owned where T: AsStrandView<'a, Self::Strand<'a>>; fn len(self) -> usize { self.as_encoded_bytes().len() } fn parent(self) -> Option<Self>; fn strip_prefix<'a, T>(self, base: T) -> Option<Self> where T: AsStrandView<'a, Self::Strand<'a>>; fn to_path_buf(self) -> Self::Owned; } impl<'p> LocAbleImpl<'p> for &'p std::path::Path { fn as_encoded_bytes(self) -> &'p [u8] { self.as_os_str().as_encoded_bytes() } fn components(self) -> Self::Components<'p> { self.components() } fn empty() -> Self { std::path::Path::new("") } fn file_name(self) -> Option<Self::Strand<'p>> { self.file_name() } unsafe fn from_encoded_bytes_unchecked(bytes: &'p [u8]) -> Self { std::path::Path::new(unsafe { OsStr::from_encoded_bytes_unchecked(bytes) }) } fn join<'a, T>(self, path: T) -> Self::Owned where T: AsStrandView<'a, Self::Strand<'a>>, { self.join(path.as_strand_view()) } fn parent(self) -> Option<Self> { self.parent() } fn strip_prefix<'a, T>(self, base: T) -> Option<Self> where T: AsStrandView<'a, Self::Strand<'a>>, { use std::path::is_separator; let p = self.strip_prefix(base.as_strand_view()).ok()?; let mut b = p.as_encoded_bytes(); if b.last().is_none_or(|&c| !is_separator(c as char)) || p.parent().is_none() { return Some(p); } while let [head @ .., last] = b && is_separator(*last as char) { b = head; } Some(unsafe { Self::from_encoded_bytes_unchecked(b) }) } fn to_path_buf(self) -> Self::Owned { self.to_path_buf() } } impl<'p> LocAbleImpl<'p> for &'p typed_path::UnixPath { fn as_encoded_bytes(self) -> &'p [u8] { self.as_bytes() } fn components(self) -> Self::Components<'p> { self.components() } fn empty() -> Self { typed_path::UnixPath::new("") } fn file_name(self) -> Option<Self::Strand<'p>> { self.file_name() } unsafe fn from_encoded_bytes_unchecked(bytes: &'p [u8]) -> Self { typed_path::UnixPath::new(bytes) } fn join<'a, T>(self, path: T) -> Self::Owned where T: AsStrandView<'a, Self::Strand<'a>>, { self.join(path.as_strand_view()) } fn parent(self) -> Option<Self> { self.parent() } fn strip_prefix<'a, T>(self, base: T) -> Option<Self> where T: AsStrandView<'a, Self::Strand<'a>>, { let p = self.strip_prefix(base.as_strand_view()).ok()?; let mut b = p.as_bytes(); if b.last().is_none_or(|&c| c != b'/') || p.parent().is_none() { return Some(p); } while let [head @ .., b'/'] = b { b = head; } Some(typed_path::UnixPath::new(b)) } fn to_path_buf(self) -> Self::Owned { self.to_path_buf() } } // --- LocBufAbleImpl pub(super) trait LocBufAbleImpl: LocBufAble { fn as_encoded_bytes(&self) -> &[u8] { self.borrow().as_encoded_bytes() } fn borrow(&self) -> Self::Borrowed<'_>; unsafe fn from_encoded_bytes_unchecked(bytes: Vec<u8>) -> Self; fn into_encoded_bytes(self) -> Vec<u8>; fn len(&self) -> usize { self.borrow().len() } fn set_file_name<'a, T>(&mut self, name: T) where T: AsStrandView<'a, Self::Strand<'a>>; } impl LocBufAbleImpl for std::path::PathBuf { fn borrow(&self) -> Self::Borrowed<'_> { self.as_path() } unsafe fn from_encoded_bytes_unchecked(bytes: Vec<u8>) -> Self { Self::from(unsafe { OsString::from_encoded_bytes_unchecked(bytes) }) } fn into_encoded_bytes(self) -> Vec<u8> { self.into_os_string().into_encoded_bytes() } fn set_file_name<'a, T>(&mut self, name: T) where T: AsStrandView<'a, Self::Strand<'a>>, { self.set_file_name(name.as_strand_view()) } } impl LocBufAbleImpl for typed_path::UnixPathBuf { fn borrow(&self) -> Self::Borrowed<'_> { self.as_path() } unsafe fn from_encoded_bytes_unchecked(bytes: Vec<u8>) -> Self { bytes.into() } fn into_encoded_bytes(self) -> Vec<u8> { self.into_vec() } fn set_file_name<'a, T>(&mut self, name: T) where T: AsStrandView<'a, Self::Strand<'a>>, { self.set_file_name(name.as_strand_view()) } } // --- StrandAbleImpl pub(super) trait StrandAbleImpl<'a>: StrandAble<'a> { fn as_encoded_bytes(self) -> &'a [u8]; fn len(self) -> usize { self.as_encoded_bytes().len() } } impl<'a> StrandAbleImpl<'a> for &'a OsStr { fn as_encoded_bytes(self) -> &'a [u8] { self.as_encoded_bytes() } } impl<'a> StrandAbleImpl<'a> for &'a [u8] { fn as_encoded_bytes(self) -> &'a [u8] { self } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/loc/mod.rs
yazi-shared/src/loc/mod.rs
#![allow(private_bounds)] yazi_macro::mod_flat!(able buf loc);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/loc/buf.rs
yazi-shared/src/loc/buf.rs
use std::{cmp, ffi::OsStr, fmt::{self, Debug, Formatter}, hash::{Hash, Hasher}, marker::PhantomData, mem, ops::Deref}; use anyhow::Result; use crate::{loc::{Loc, LocAble, LocAbleImpl, LocBufAble, LocBufAbleImpl}, path::{AsPath, AsPathView, PathDyn, SetNameError}, scheme::SchemeKind, strand::AsStrandView}; #[derive(Clone, Default, Eq, PartialEq)] pub struct LocBuf<P = std::path::PathBuf> { pub(super) inner: P, pub(super) uri: usize, pub(super) urn: usize, } impl<P> Deref for LocBuf<P> where P: LocBufAble, { type Target = P; fn deref(&self) -> &Self::Target { &self.inner } } // FIXME: remove impl AsRef<std::path::Path> for LocBuf<std::path::PathBuf> { fn as_ref(&self) -> &std::path::Path { self.inner.as_ref() } } impl<T> AsPath for LocBuf<T> where T: LocBufAble + AsPath, { fn as_path(&self) -> PathDyn<'_> { self.inner.as_path() } } impl<T> AsPath for &LocBuf<T> where T: LocBufAble + AsPath, { fn as_path(&self) -> PathDyn<'_> { self.inner.as_path() } } impl<P> Ord for LocBuf<P> where P: LocBufAble + Ord, { fn cmp(&self, other: &Self) -> cmp::Ordering { self.inner.cmp(&other.inner) } } impl<P> PartialOrd for LocBuf<P> where P: LocBufAble + PartialOrd, { fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { self.inner.partial_cmp(&other.inner) } } // --- Hash impl<P> Hash for LocBuf<P> where P: LocBufAble + LocBufAbleImpl, for<'a> &'a P: AsPathView<'a, P::Borrowed<'a>>, { fn hash<H: Hasher>(&self, state: &mut H) { self.as_loc().hash(state) } } impl<P> Debug for LocBuf<P> where P: LocBufAble + LocBufAbleImpl + Debug, for<'a> &'a P: AsPathView<'a, P::Borrowed<'a>>, { fn fmt(&self, f: &mut Formatter) -> fmt::Result { f.debug_struct("LocBuf") .field("path", &self.inner) .field("uri", &self.uri()) .field("urn", &self.urn()) .finish() } } impl<P> From<P> for LocBuf<P> where P: LocBufAble + LocBufAbleImpl, for<'a> &'a P: AsPathView<'a, P::Borrowed<'a>>, { fn from(path: P) -> Self { let Loc { inner, uri, urn, _phantom } = Loc::bare(&path); let len = inner.len(); let mut bytes = path.into_encoded_bytes(); bytes.truncate(len); Self { inner: unsafe { P::from_encoded_bytes_unchecked(bytes) }, uri, urn } } } impl<T: ?Sized + AsRef<OsStr>> From<&T> for LocBuf<std::path::PathBuf> { fn from(value: &T) -> Self { Self::from(std::path::PathBuf::from(value)) } } impl<P> LocBuf<P> where P: LocBufAble + LocBufAbleImpl, for<'a> &'a P: AsPathView<'a, P::Borrowed<'a>>, { pub fn new<'a, S>(path: P, base: S, trail: S) -> Self where S: for<'b> AsStrandView<'a, <P::Borrowed<'b> as LocAble<'b>>::Strand<'a>>, { let loc = Self::from(path); let Loc { inner, uri, urn, _phantom } = Loc::new(&loc.inner, base, trail); debug_assert!(inner.as_encoded_bytes() == loc.inner.as_encoded_bytes()); Self { inner: loc.inner, uri, urn } } pub fn with(path: P, uri: usize, urn: usize) -> Result<Self> where for<'a> P::Borrowed<'a>: LocAble<'a>, { let loc = Self::from(path); let Loc { inner, uri, urn, _phantom } = Loc::with(&loc.inner, uri, urn)?; debug_assert!(inner.as_encoded_bytes() == loc.inner.as_encoded_bytes()); Ok(Self { inner: loc.inner, uri, urn }) } pub fn zeroed<T>(path: T) -> Self where T: Into<P>, { let loc = Self::from(path.into()); let Loc { inner, uri, urn, _phantom } = Loc::zeroed(&loc.inner); debug_assert!(inner.as_encoded_bytes() == loc.inner.as_encoded_bytes()); Self { inner: loc.inner, uri, urn } } pub fn floated<'a, S>(path: P, base: S) -> Self where S: for<'b> AsStrandView<'a, <P::Borrowed<'b> as LocAble<'b>>::Strand<'a>>, { let loc = Self::from(path); let Loc { inner, uri, urn, _phantom } = Loc::floated(&loc.inner, base); debug_assert!(inner.as_encoded_bytes() == loc.inner.as_encoded_bytes()); Self { inner: loc.inner, uri, urn } } pub fn saturated(path: P, kind: SchemeKind) -> Self { let loc = Self::from(path); let Loc { inner, uri, urn, _phantom } = Loc::saturated(&loc.inner, kind); debug_assert!(inner.as_encoded_bytes() == loc.inner.as_encoded_bytes()); Self { inner: loc.inner, uri, urn } } #[inline] pub fn as_loc<'a>(&'a self) -> Loc<'a, P::Borrowed<'a>> { Loc { inner: self.inner.as_path_view(), uri: self.uri, urn: self.urn, _phantom: PhantomData, } } #[inline] pub fn to_inner(&self) -> P where P: Clone, { self.inner.clone() } #[inline] pub fn into_inner(self) -> P { self.inner } pub fn try_set_name<'a, T>(&mut self, name: T) -> Result<(), SetNameError> where T: AsStrandView<'a, P::Strand<'a>>, { let old = self.inner.len(); self.mutate(|path| path.set_file_name(name)); let new = self.inner.len(); if new == old { return Ok(()); } if self.uri != 0 { if new > old { self.uri += new - old; } else { self.uri -= old - new; } } if self.urn != 0 { if new > old { self.urn += new - old; } else { self.urn -= old - new; } } Ok(()) } #[inline] pub fn rebase<'a, 'b>(&'a self, base: P::Borrowed<'b>) -> Self where 'a: 'b, for<'c> <P::Borrowed<'c> as LocAble<'c>>::Owned: Into<Self>, { let mut loc: Self = base.join(self.uri()).into(); (loc.uri, loc.urn) = (self.uri, self.urn); loc } #[inline] pub fn parent(&self) -> Option<P::Borrowed<'_>> { self.as_loc().parent() } #[inline] fn mutate<T, F: FnOnce(&mut P) -> T>(&mut self, f: F) -> T { let mut inner = mem::take(&mut self.inner); let result = f(&mut inner); self.inner = Self::from(inner).inner; result } } // FIXME: macro impl<P> LocBuf<P> where P: LocBufAble + LocBufAbleImpl, for<'a> &'a P: AsPathView<'a, P::Borrowed<'a>>, { #[inline] pub fn uri(&self) -> P::Borrowed<'_> { self.as_loc().uri() } #[inline] pub fn urn(&self) -> P::Borrowed<'_> { self.as_loc().urn() } #[inline] pub fn base(&self) -> P::Borrowed<'_> { self.as_loc().base() } #[inline] pub fn has_base(&self) -> bool { self.as_loc().has_base() } #[inline] pub fn trail(&self) -> P::Borrowed<'_> { self.as_loc().trail() } #[inline] pub fn has_trail(&self) -> bool { self.as_loc().has_trail() } } impl LocBuf<std::path::PathBuf> { pub const fn empty() -> Self { Self { inner: std::path::PathBuf::new(), uri: 0, urn: 0 } } } #[cfg(test)] mod tests { use std::path::{Path, PathBuf}; use super::*; use crate::url::{UrlBuf, UrlLike}; #[test] fn test_new() { let loc: LocBuf = Path::new("/").into(); assert_eq!(loc.uri().as_os_str(), OsStr::new("")); assert_eq!(loc.urn().as_os_str(), OsStr::new("")); assert_eq!(loc.file_name(), None); assert_eq!(loc.base().as_os_str(), OsStr::new("/")); assert_eq!(loc.trail().as_os_str(), OsStr::new("/")); let loc: LocBuf = Path::new("/root").into(); assert_eq!(loc.uri().as_os_str(), OsStr::new("root")); assert_eq!(loc.urn().as_os_str(), OsStr::new("root")); assert_eq!(loc.file_name().unwrap(), OsStr::new("root")); assert_eq!(loc.base().as_os_str(), OsStr::new("/")); assert_eq!(loc.trail().as_os_str(), OsStr::new("/")); let loc: LocBuf = Path::new("/root/code/foo/").into(); assert_eq!(loc.uri().as_os_str(), OsStr::new("foo")); assert_eq!(loc.urn().as_os_str(), OsStr::new("foo")); assert_eq!(loc.file_name().unwrap(), OsStr::new("foo")); assert_eq!(loc.base().as_os_str(), OsStr::new("/root/code/")); assert_eq!(loc.trail().as_os_str(), OsStr::new("/root/code/")); } #[test] fn test_with() -> Result<()> { let loc = LocBuf::<PathBuf>::with("/".into(), 0, 0)?; assert_eq!(loc.uri().as_os_str(), OsStr::new("")); assert_eq!(loc.urn().as_os_str(), OsStr::new("")); assert_eq!(loc.file_name(), None); assert_eq!(loc.base().as_os_str(), OsStr::new("/")); assert_eq!(loc.trail().as_os_str(), OsStr::new("/")); let loc = LocBuf::<PathBuf>::with("/root/code/".into(), 1, 1)?; assert_eq!(loc.uri().as_os_str(), OsStr::new("code")); assert_eq!(loc.urn().as_os_str(), OsStr::new("code")); assert_eq!(loc.file_name().unwrap(), OsStr::new("code")); assert_eq!(loc.base().as_os_str(), OsStr::new("/root/")); assert_eq!(loc.trail().as_os_str(), OsStr::new("/root/")); let loc = LocBuf::<PathBuf>::with("/root/code/foo//".into(), 2, 1)?; assert_eq!(loc.uri().as_os_str(), OsStr::new("code/foo")); assert_eq!(loc.urn().as_os_str(), OsStr::new("foo")); assert_eq!(loc.file_name().unwrap(), OsStr::new("foo")); assert_eq!(loc.base().as_os_str(), OsStr::new("/root/")); assert_eq!(loc.trail().as_os_str(), OsStr::new("/root/code/")); let loc = LocBuf::<PathBuf>::with("/root/code/foo//".into(), 2, 2)?; assert_eq!(loc.uri().as_os_str(), OsStr::new("code/foo")); assert_eq!(loc.urn().as_os_str(), OsStr::new("code/foo")); assert_eq!(loc.file_name().unwrap(), OsStr::new("foo")); assert_eq!(loc.base().as_os_str(), OsStr::new("/root/")); assert_eq!(loc.trail().as_os_str(), OsStr::new("/root/")); let loc = LocBuf::<PathBuf>::with("/root/code/foo//bar/".into(), 2, 2)?; assert_eq!(loc.uri().as_os_str(), OsStr::new("foo//bar")); assert_eq!(loc.urn().as_os_str(), OsStr::new("foo//bar")); assert_eq!(loc.file_name().unwrap(), OsStr::new("bar")); assert_eq!(loc.base().as_os_str(), OsStr::new("/root/code/")); assert_eq!(loc.trail().as_os_str(), OsStr::new("/root/code/")); let loc = LocBuf::<PathBuf>::with("/root/code/foo//bar/".into(), 3, 2)?; assert_eq!(loc.uri().as_os_str(), OsStr::new("code/foo//bar")); assert_eq!(loc.urn().as_os_str(), OsStr::new("foo//bar")); assert_eq!(loc.file_name().unwrap(), OsStr::new("bar")); assert_eq!(loc.base().as_os_str(), OsStr::new("/root/")); assert_eq!(loc.trail().as_os_str(), OsStr::new("/root/code/")); Ok(()) } #[test] fn test_set_name() -> Result<()> { crate::init_tests(); let cases = [ // Regular ("/", "a", "/a"), ("/a/b", "c", "/a/c"), // Archive ("archive:////", "a.zip", "archive:////a.zip"), ("archive:////a.zip/b", "c", "archive:////a.zip/c"), ("archive://:2//a.zip/b", "c", "archive://:2//a.zip/c"), ("archive://:2:1//a.zip/b", "c", "archive://:2:1//a.zip/c"), // Empty ("/a", "", "/"), ("archive:////a.zip", "", "archive:////"), ("archive:////a.zip/b", "", "archive:////a.zip"), ("archive://:1:1//a.zip", "", "archive:////"), ("archive://:2//a.zip/b", "", "archive://:1//a.zip"), ("archive://:2:2//a.zip/b", "", "archive://:1:1//a.zip"), ]; for (input, name, expected) in cases { let mut a: UrlBuf = input.parse()?; let b: UrlBuf = expected.parse()?; a.try_set_name(name).unwrap(); assert_eq!( (a.name(), format!("{a:?}").replace(r"\", "/")), (b.name(), expected.replace(r"\", "/")) ); } Ok(()) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/translit/table.rs
yazi-shared/src/translit/table.rs
const TABLE_0: [&str; 496] = [ "A", // À 192 "A", // Á 193 "A", //  194 "A", // à 195 "A", // Ä 196 "A", // Å 197 "AE", // Æ 198 "C", // Ç 199 "E", // È 200 "E", // É 201 "E", // Ê 202 "E", // Ë 203 "I", // Ì 204 "I", // Í 205 "I", // Î 206 "I", // Ï 207 "D", // Ð 208 "N", // Ñ 209 "O", // Ò 210 "O", // Ó 211 "O", // Ô 212 "O", // Õ 213 "O", // Ö 214 "×", // × 215 "O", // Ø 216 "U", // Ù 217 "U", // Ú 218 "U", // Û 219 "U", // Ü 220 "Y", // Ý 221 "T", // Þ 222 "ss", // ß 223 "a", // à 224 "a", // á 225 "a", // â 226 "a", // ã 227 "a", // ä 228 "a", // å 229 "ae", // æ 230 "c", // ç 231 "e", // è 232 "e", // é 233 "e", // ê 234 "e", // ë 235 "i", // ì 236 "i", // í 237 "i", // î 238 "i", // ï 239 "d", // ð 240 "n", // ñ 241 "o", // ò 242 "o", // ó 243 "o", // ô 244 "o", // õ 245 "o", // ö 246 "÷", // ÷ 247 "o", // ø 248 "u", // ù 249 "u", // ú 250 "u", // û 251 "u", // ü 252 "y", // ý 253 "t", // þ 254 "y", // ÿ 255 "A", // Ā 256 "a", // ā 257 "A", // Ă 258 "a", // ă 259 "A", // Ą 260 "a", // ą 261 "C", // Ć 262 "c", // ć 263 "C", // Ĉ 264 "c", // ĉ 265 "C", // Ċ 266 "c", // ċ 267 "C", // Č 268 "c", // č 269 "D", // Ď 270 "d", // ď 271 "D", // Đ 272 "d", // đ 273 "E", // Ē 274 "e", // ē 275 "E", // Ĕ 276 "e", // ĕ 277 "E", // Ė 278 "e", // ė 279 "E", // Ę 280 "e", // ę 281 "E", // Ě 282 "e", // ě 283 "G", // Ĝ 284 "g", // ĝ 285 "G", // Ğ 286 "g", // ğ 287 "G", // Ġ 288 "g", // ġ 289 "G", // Ģ 290 "g", // ģ 291 "H", // Ĥ 292 "h", // ĥ 293 "H", // Ħ 294 "h", // ħ 295 "I", // Ĩ 296 "i", // ĩ 297 "I", // Ī 298 "i", // ī 299 "I", // Ĭ 300 "i", // ĭ 301 "I", // Į 302 "i", // į 303 "I", // İ 304 "i", // ı 305 "IJ", // IJ 306 "ij", // ij 307 "J", // Ĵ 308 "j", // ĵ 309 "K", // Ķ 310 "k", // ķ 311 "k", // ĸ 312 "L", // Ĺ 313 "l", // ĺ 314 "L", // Ļ 315 "l", // ļ 316 "L", // Ľ 317 "l", // ľ 318 "L", // Ŀ 319 "l", // ŀ 320 "L", // Ł 321 "l", // ł 322 "N", // Ń 323 "n", // ń 324 "N", // Ņ 325 "n", // ņ 326 "N", // Ň 327 "n", // ň 328 "n", // ʼn 329 "N", // Ŋ 330 "n", // ŋ 331 "O", // Ō 332 "o", // ō 333 "O", // Ŏ 334 "o", // ŏ 335 "O", // Ő 336 "o", // ő 337 "OE", // Œ 338 "oe", // œ 339 "R", // Ŕ 340 "r", // ŕ 341 "R", // Ŗ 342 "r", // ŗ 343 "R", // Ř 344 "r", // ř 345 "S", // Ś 346 "s", // ś 347 "S", // Ŝ 348 "s", // ŝ 349 "S", // Ş 350 "s", // ş 351 "S", // Š 352 "s", // š 353 "T", // Ţ 354 "t", // ţ 355 "T", // Ť 356 "t", // ť 357 "T", // Ŧ 358 "t", // ŧ 359 "U", // Ũ 360 "u", // ũ 361 "U", // Ū 362 "u", // ū 363 "U", // Ŭ 364 "u", // ŭ 365 "U", // Ů 366 "u", // ů 367 "U", // Ű 368 "u", // ű 369 "U", // Ų 370 "u", // ų 371 "W", // Ŵ 372 "w", // ŵ 373 "Y", // Ŷ 374 "y", // ŷ 375 "Y", // Ÿ 376 "Z", // Ź 377 "z", // ź 378 "Z", // Ż 379 "z", // ż 380 "Z", // Ž 381 "z", // ž 382 "s", // ſ 383 "ƀ", // ƀ 384 "B", // Ɓ 385 "Ƃ", // Ƃ 386 "ƃ", // ƃ 387 "Ƅ", // Ƅ 388 "ƅ", // ƅ 389 "O", // Ɔ 390 "Ƈ", // Ƈ 391 "ƈ", // ƈ 392 "Ɖ", // Ɖ 393 "D", // Ɗ 394 "Ƌ", // Ƌ 395 "ƌ", // ƌ 396 "ƍ", // ƍ 397 "Ǝ", // Ǝ 398 "E", // Ə 399 "E", // Ɛ 400 "F", // Ƒ 401 "f", // ƒ 402 "Ɠ", // Ɠ 403 "Ɣ", // Ɣ 404 "ƕ", // ƕ 405 "Ɩ", // Ɩ 406 "Ɨ", // Ɨ 407 "K", // Ƙ 408 "k", // ƙ 409 "l", // ƚ 410 "l", // ƛ 411 "Ɯ", // Ɯ 412 "N", // Ɲ 413 "ƞ", // ƞ 414 "O", // Ɵ 415 "O", // Ơ 416 "o", // ơ 417 "Ƣ", // Ƣ 418 "ƣ", // ƣ 419 "Ƥ", // Ƥ 420 "ƥ", // ƥ 421 "Ʀ", // Ʀ 422 "Ƨ", // Ƨ 423 "ƨ", // ƨ 424 "Ʃ", // Ʃ 425 "ƪ", // ƪ 426 "ƫ", // ƫ 427 "Ƭ", // Ƭ 428 "ƭ", // ƭ 429 "Ʈ", // Ʈ 430 "U", // Ư 431 "u", // ư 432 "Ʊ", // Ʊ 433 "Ʋ", // Ʋ 434 "Y", // Ƴ 435 "y", // ƴ 436 "Z", // Ƶ 437 "z", // ƶ 438 "Ʒ", // Ʒ 439 "Ƹ", // Ƹ 440 "ƹ", // ƹ 441 "ƺ", // ƺ 442 "ƻ", // ƻ 443 "Ƽ", // Ƽ 444 "ƽ", // ƽ 445 "ƾ", // ƾ 446 "ƿ", // ƿ 447 "ǀ", // ǀ 448 "ǁ", // ǁ 449 "ǂ", // ǂ 450 "ǃ", // ǃ 451 "DZ", // DŽ 452 "Dz", // Dž 453 "dz", // dž 454 "LJ", // LJ 455 "Lj", // Lj 456 "lj", // lj 457 "NJ", // NJ 458 "Nj", // Nj 459 "nj", // nj 460 "A", // Ǎ 461 "a", // ǎ 462 "I", // Ǐ 463 "i", // ǐ 464 "O", // Ǒ 465 "o", // ǒ 466 "U", // Ǔ 467 "u", // ǔ 468 "U", // Ǖ 469 "u", // ǖ 470 "U", // Ǘ 471 "u", // ǘ 472 "U", // Ǚ 473 "u", // ǚ 474 "U", // Ǜ 475 "u", // ǜ 476 "ǝ", // ǝ 477 "Ǟ", // Ǟ 478 "ǟ", // ǟ 479 "Ǡ", // Ǡ 480 "ǡ", // ǡ 481 "Ǣ", // Ǣ 482 "ǣ", // ǣ 483 "Ǥ", // Ǥ 484 "ǥ", // ǥ 485 "G", // Ǧ 486 "g", // ǧ 487 "Ǩ", // Ǩ 488 "ǩ", // ǩ 489 "O", // Ǫ 490 "o", // ǫ 491 "Ǭ", // Ǭ 492 "ǭ", // ǭ 493 "Ǯ", // Ǯ 494 "e", // ǯ 495 "j", // ǰ 496 "DZ", // DZ 497 "Dz", // Dz 498 "dz", // dz 499 "G", // Ǵ 500 "g", // ǵ 501 "Ƕ", // Ƕ 502 "Ƿ", // Ƿ 503 "N", // Ǹ 504 "n", // ǹ 505 "A", // Ǻ 506 "a", // ǻ 507 "AE", // Ǽ 508 "ae", // ǽ 509 "O", // Ǿ 510 "o", // ǿ 511 "Ȁ", // Ȁ 512 "ȁ", // ȁ 513 "Ȃ", // Ȃ 514 "ȃ", // ȃ 515 "Ȅ", // Ȅ 516 "ȅ", // ȅ 517 "Ȇ", // Ȇ 518 "ȇ", // ȇ 519 "Ȉ", // Ȉ 520 "ȉ", // ȉ 521 "Ȋ", // Ȋ 522 "ȋ", // ȋ 523 "Ȍ", // Ȍ 524 "ȍ", // ȍ 525 "Ȏ", // Ȏ 526 "ȏ", // ȏ 527 "Ȑ", // Ȑ 528 "ȑ", // ȑ 529 "Ȓ", // Ȓ 530 "ȓ", // ȓ 531 "Ȕ", // Ȕ 532 "ȕ", // ȕ 533 "Ȗ", // Ȗ 534 "ȗ", // ȗ 535 "S", // Ș 536 "s", // ș 537 "T", // Ț 538 "t", // ț 539 "Ȝ", // Ȝ 540 "ȝ", // ȝ 541 "Ȟ", // Ȟ 542 "ȟ", // ȟ 543 "Ƞ", // Ƞ 544 "ȡ", // ȡ 545 "Ȣ", // Ȣ 546 "ȣ", // ȣ 547 "Ȥ", // Ȥ 548 "ȥ", // ȥ 549 "Ȧ", // Ȧ 550 "ȧ", // ȧ 551 "Ȩ", // Ȩ 552 "ȩ", // ȩ 553 "Ȫ", // Ȫ 554 "ȫ", // ȫ 555 "Ȭ", // Ȭ 556 "ȭ", // ȭ 557 "Ȯ", // Ȯ 558 "ȯ", // ȯ 559 "Ȱ", // Ȱ 560 "ȱ", // ȱ 561 "Y", // Ȳ 562 "y", // ȳ 563 "ȴ", // ȴ 564 "ȵ", // ȵ 565 "ȶ", // ȶ 566 "j", // ȷ 567 "ȸ", // ȸ 568 "ȹ", // ȹ 569 "Ⱥ", // Ⱥ 570 "Ȼ", // Ȼ 571 "ȼ", // ȼ 572 "L", // Ƚ 573 "Ⱦ", // Ⱦ 574 "ȿ", // ȿ 575 "ɀ", // ɀ 576 "Ɂ", // Ɂ 577 "ɂ", // ɂ 578 "Ƀ", // Ƀ 579 "Ʉ", // Ʉ 580 "Ʌ", // Ʌ 581 "Ɇ", // Ɇ 582 "ɇ", // ɇ 583 "Ɉ", // Ɉ 584 "ɉ", // ɉ 585 "Ɋ", // Ɋ 586 "ɋ", // ɋ 587 "Ɍ", // Ɍ 588 "ɍ", // ɍ 589 "Ɏ", // Ɏ 590 "ɏ", // ɏ 591 "a", // ɐ 592 "a", // ɑ 593 "a", // ɒ 594 "b", // ɓ 595 "o", // ɔ 596 "c", // ɕ 597 "d", // ɖ 598 "d", // ɗ 599 "e", // ɘ 600 "e", // ə 601 "e", // ɚ 602 "o", // ɛ 603 "e", // ɜ 604 "e", // ɝ 605 "e", // ɞ 606 "j", // ɟ 607 "g", // ɠ 608 "g", // ɡ 609 "ɢ", // ɢ 610 "g", // ɣ 611 "ɤ", // ɤ 612 "h", // ɥ 613 "h", // ɦ 614 "h", // ɧ 615 "i", // ɨ 616 "i", // ɩ 617 "ɪ", // ɪ 618 "l", // ɫ 619 "l", // ɬ 620 "l", // ɭ 621 "le", // ɮ 622 "m", // ɯ 623 "m", // ɰ 624 "m", // ɱ 625 "n", // ɲ 626 "n", // ɳ 627 "ɴ", // ɴ 628 "o", // ɵ 629 "OE", // ɶ 630 "ɷ", // ɷ 631 "p", // ɸ 632 "r", // ɹ 633 "r", // ɺ 634 "r", // ɻ 635 "r", // ɼ 636 "r", // ɽ 637 "r", // ɾ 638 "r", // ɿ 639 "ʀ", // ʀ 640 "R", // ʁ 641 "s", // ʂ 642 "s", // ʃ 643 "j", // ʄ 644 "s", // ʅ 645 "s", // ʆ 646 "t", // ʇ 647 "t", // ʈ 648 "u", // ʉ 649 "u", // ʊ 650 "v", // ʋ 651 "v", // ʌ 652 "w", // ʍ 653 "y", // ʎ 654 "ʏ", // ʏ 655 "z", // ʐ 656 "z", // ʑ 657 "e", // ʒ 658 "e", // ʓ 659 "ʔ", // ʔ 660 "ʕ", // ʕ 661 "ʖ", // ʖ 662 "C", // ʗ 663 "o", // ʘ 664 "ʙ", // ʙ 665 "e", // ʚ 666 "G", // ʛ 667 "ʜ", // ʜ 668 "j", // ʝ 669 "k", // ʞ 670 "ʟ", // ʟ 671 "q", // ʠ 672 "ʡ", // ʡ 673 "ʢ", // ʢ 674 "dz", // ʣ 675 "de", // ʤ 676 "dz", // ʥ 677 "ts", // ʦ 678 "ts", // ʧ 679 "tc", // ʨ 680 "fn", // ʩ 681 "ls", // ʪ 682 "lz", // ʫ 683 "W", // ʬ 684 "ʭ", // ʭ 685 "h", // ʮ 686 "h", // ʯ 687 ]; const TABLE_1: [&str; 246] = [ "B", // Ḅ 7684 "b", // ḅ 7685 "Ḇ", // Ḇ 7686 "ḇ", // ḇ 7687 "Ḉ", // Ḉ 7688 "ḉ", // ḉ 7689 "Ḋ", // Ḋ 7690 "ḋ", // ḋ 7691 "D", // Ḍ 7692 "d", // ḍ 7693 "D", // Ḏ 7694 "d", // ḏ 7695 "Ḑ", // Ḑ 7696 "ḑ", // ḑ 7697 "D", // Ḓ 7698 "d", // ḓ 7699 "Ḕ", // Ḕ 7700 "ḕ", // ḕ 7701 "Ḗ", // Ḗ 7702 "ḗ", // ḗ 7703 "Ḙ", // Ḙ 7704 "ḙ", // ḙ 7705 "Ḛ", // Ḛ 7706 "ḛ", // ḛ 7707 "Ḝ", // Ḝ 7708 "ḝ", // ḝ 7709 "Ḟ", // Ḟ 7710 "ḟ", // ḟ 7711 "G", // Ḡ 7712 "g", // ḡ 7713 "Ḣ", // Ḣ 7714 "ḣ", // ḣ 7715 "H", // Ḥ 7716 "h", // ḥ 7717 "Ḧ", // Ḧ 7718 "ḧ", // ḧ 7719 "Ḩ", // Ḩ 7720 "ḩ", // ḩ 7721 "H", // Ḫ 7722 "h", // ḫ 7723 "Ḭ", // Ḭ 7724 "ḭ", // ḭ 7725 "Ḯ", // Ḯ 7726 "ḯ", // ḯ 7727 "Ḱ", // Ḱ 7728 "ḱ", // ḱ 7729 "K", // Ḳ 7730 "k", // ḳ 7731 "K", // Ḵ 7732 "k", // ḵ 7733 "L", // Ḷ 7734 "l", // ḷ 7735 "L", // Ḹ 7736 "l", // ḹ 7737 "L", // Ḻ 7738 "l", // ḻ 7739 "L", // Ḽ 7740 "l", // ḽ 7741 "M", // Ḿ 7742 "m", // ḿ 7743 "M", // Ṁ 7744 "m", // ṁ 7745 "M", // Ṃ 7746 "m", // ṃ 7747 "N", // Ṅ 7748 "n", // ṅ 7749 "N", // Ṇ 7750 "n", // ṇ 7751 "N", // Ṉ 7752 "n", // ṉ 7753 "N", // Ṋ 7754 "n", // ṋ 7755 "Ṍ", // Ṍ 7756 "ṍ", // ṍ 7757 "Ṏ", // Ṏ 7758 "ṏ", // ṏ 7759 "Ṑ", // Ṑ 7760 "ṑ", // ṑ 7761 "Ṓ", // Ṓ 7762 "ṓ", // ṓ 7763 "Ṕ", // Ṕ 7764 "ṕ", // ṕ 7765 "Ṗ", // Ṗ 7766 "ṗ", // ṗ 7767 "R", // Ṙ 7768 "r", // ṙ 7769 "R", // Ṛ 7770 "r", // ṛ 7771 "R", // Ṝ 7772 "r", // ṝ 7773 "R", // Ṟ 7774 "r", // ṟ 7775 "S", // Ṡ 7776 "s", // ṡ 7777 "S", // Ṣ 7778 "s", // ṣ 7779 "Ṥ", // Ṥ 7780 "ṥ", // ṥ 7781 "Ṧ", // Ṧ 7782 "ṧ", // ṧ 7783 "Ṩ", // Ṩ 7784 "ṩ", // ṩ 7785 "Ṫ", // Ṫ 7786 "ṫ", // ṫ 7787 "T", // Ṭ 7788 "t", // ṭ 7789 "T", // Ṯ 7790 "t", // ṯ 7791 "T", // Ṱ 7792 "t", // ṱ 7793 "Ṳ", // Ṳ 7794 "ṳ", // ṳ 7795 "Ṵ", // Ṵ 7796 "ṵ", // ṵ 7797 "Ṷ", // Ṷ 7798 "ṷ", // ṷ 7799 "Ṹ", // Ṹ 7800 "ṹ", // ṹ 7801 "Ṻ", // Ṻ 7802 "ṻ", // ṻ 7803 "Ṽ", // Ṽ 7804 "ṽ", // ṽ 7805 "Ṿ", // Ṿ 7806 "ṿ", // ṿ 7807 "W", // Ẁ 7808 "w", // ẁ 7809 "W", // Ẃ 7810 "w", // ẃ 7811 "W", // Ẅ 7812 "w", // ẅ 7813 "Ẇ", // Ẇ 7814 "ẇ", // ẇ 7815 "Ẉ", // Ẉ 7816 "ẉ", // ẉ 7817 "Ẋ", // Ẋ 7818 "ẋ", // ẋ 7819 "Ẍ", // Ẍ 7820 "ẍ", // ẍ 7821 "Y", // Ẏ 7822 "y", // ẏ 7823 "Ẑ", // Ẑ 7824 "ẑ", // ẑ 7825 "Z", // Ẓ 7826 "z", // ẓ 7827 "Z", // Ẕ 7828 "z", // ẕ 7829 "h", // ẖ 7830 "t", // ẗ 7831 "ẘ", // ẘ 7832 "ẙ", // ẙ 7833 "ẚ", // ẚ 7834 "ẛ", // ẛ 7835 "ẜ", // ẜ 7836 "ẝ", // ẝ 7837 "SS", // ẞ 7838 "ẟ", // ẟ 7839 "A", // Ạ 7840 "a", // ạ 7841 "A", // Ả 7842 "a", // ả 7843 "A", // Ấ 7844 "a", // ấ 7845 "A", // Ầ 7846 "a", // ầ 7847 "A", // Ẩ 7848 "a", // ẩ 7849 "A", // Ẫ 7850 "a", // ẫ 7851 "A", // Ậ 7852 "a", // ậ 7853 "A", // Ắ 7854 "a", // ắ 7855 "A", // Ằ 7856 "a", // ằ 7857 "A", // Ẳ 7858 "a", // ẳ 7859 "A", // Ẵ 7860 "a", // ẵ 7861 "A", // Ặ 7862 "a", // ặ 7863 "E", // Ẹ 7864 "e", // ẹ 7865 "E", // Ẻ 7866 "e", // ẻ 7867 "E", // Ẽ 7868 "e", // ẽ 7869 "E", // Ế 7870 "e", // ế 7871 "E", // Ề 7872 "e", // ề 7873 "E", // Ể 7874 "e", // ể 7875 "E", // Ễ 7876 "e", // ễ 7877 "E", // Ệ 7878 "e", // ệ 7879 "I", // Ỉ 7880 "i", // ỉ 7881 "I", // Ị 7882 "i", // ị 7883 "O", // Ọ 7884 "o", // ọ 7885 "O", // Ỏ 7886 "o", // ỏ 7887 "O", // Ố 7888 "o", // ố 7889 "O", // Ồ 7890 "o", // ồ 7891 "O", // Ổ 7892 "o", // ổ 7893 "O", // Ỗ 7894 "o", // ỗ 7895 "O", // Ộ 7896 "o", // ộ 7897 "O", // Ớ 7898 "o", // ớ 7899 "O", // Ờ 7900 "o", // ờ 7901 "O", // Ở 7902 "o", // ở 7903 "O", // Ỡ 7904 "o", // ỡ 7905 "O", // Ợ 7906 "o", // ợ 7907 "U", // Ụ 7908 "u", // ụ 7909 "U", // Ủ 7910 "u", // ủ 7911 "U", // Ứ 7912 "u", // ứ 7913 "U", // Ừ 7914 "u", // ừ 7915 "U", // Ử 7916 "u", // ử 7917 "U", // Ữ 7918 "u", // ữ 7919 "U", // Ự 7920 "u", // ự 7921 "Y", // Ỳ 7922 "y", // ỳ 7923 "Y", // Ỵ 7924 "y", // ỵ 7925 "Y", // Ỷ 7926 "y", // ỷ 7927 "Y", // Ỹ 7928 "y", // ỹ 7929 ]; const TABLE_2: [&str; 2] = [ "fi", // fi 64257 "fl", // fl 64258 ]; #[inline(always)] pub(super) fn lookup(c: char) -> Option<&'static str> { match c as u16 { 192..=687 => unsafe { Some(TABLE_0.get_unchecked((c as u16 - 192) as usize)) }, 7684..=7929 => unsafe { Some(TABLE_1.get_unchecked((c as u16 - 7684) as usize)) }, 64257..=64258 => unsafe { Some(TABLE_2.get_unchecked((c as u16 - 64257) as usize)) }, _ => None, } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/translit/mod.rs
yazi-shared/src/translit/mod.rs
yazi_macro::mod_flat!(table traits);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/translit/traits.rs
yazi-shared/src/translit/traits.rs
use core::str; use std::borrow::Cow; pub trait Transliterator { fn transliterate(&self) -> Cow<'_, str>; } impl Transliterator for &[u8] { fn transliterate(&self) -> Cow<'_, str> { // Fast path to skip over ASCII chars at the beginning of the string let ascii_len = self.iter().take_while(|&&c| c < 0x7f).count(); if ascii_len >= self.len() { return Cow::Borrowed(unsafe { str::from_utf8_unchecked(self) }); } let (ascii, rest) = self.split_at(ascii_len); // Reserve a bit more space to avoid reallocations on longer transliterations // but instead of `+ 16` uses `| 15` to stay in the smallest allocation bucket // for short strings let mut out = String::new(); out.reserve_exact(self.len() | 15); out.push_str(unsafe { str::from_utf8_unchecked(ascii) }); for c in String::from_utf8_lossy(rest).chars() { if let Some(s) = super::lookup(c) { out.push_str(s); } else { out.push(c); } } Cow::Owned(out) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_transliterate() { assert_eq!("Æcœ".as_bytes().transliterate(), "AEcoe"); assert_eq!( "ěřůøĉĝĥĵŝŭèùÿėįųāēīūļķņģőűëïąćęłńśźżõșțčďĺľňŕšťýžéíñóúüåäöçîşûğăâđêôơưáàãảạ" .as_bytes() .transliterate(), "eruocghjsueuyeiuaeiulkngoueiacelnszzostcdllnrstyzeinouuaaocisugaadeoouaaaaa", ); assert_eq!( "áạàảãăắặằẳẵâấậầẩẫéẹèẻẽêếệềểễiíịìỉĩoóọòỏõôốộồổỗơớợờởỡúụùủũưứựừửữyýỵỳỷỹđ" .as_bytes() .transliterate(), "aaaaaaaaaaaaaaaaaeeeeeeeeeeeiiiiiioooooooooooooooooouuuuuuuuuuuyyyyyyd", ); assert_ne!( "ěřůøĉĝĥĵŝŭèùÿėįųāēīūļķņģőűëïąćęłńśźżõșțčďĺľňŕšťýžéíñóúüåäöçîşûğăâđêôơưáàãảạfifl" .as_bytes() .transliterate(), "ěřůøĉĝĥĵŝŭèùÿėįųāēīūļķņģőűëïąćęłńśźżõșțčďĺľňŕšťýžéíñóúüåäöçîşûğăâđêôơưáàãảạfifl" ); assert_eq!( "THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGthequickbrownfoxjumpedoverthelazydog" .as_bytes() .transliterate(), "THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGthequickbrownfoxjumpedoverthelazydog" ); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/data/key.rs
yazi-shared/src/data/key.rs
use std::borrow::Cow; use ordered_float::OrderedFloat; use serde::{Deserialize, Serialize, de}; use crate::{Id, SStr, path::PathBufDyn, url::{UrlBuf, UrlCow}}; #[derive(Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] #[serde(untagged)] pub enum DataKey { Nil, Boolean(bool), #[serde(deserialize_with = "Self::deserialize_integer")] Integer(i64), Number(OrderedFloat<f64>), String(SStr), Id(Id), #[serde(skip_deserializing)] Url(UrlBuf), #[serde(skip)] Path(PathBufDyn), #[serde(skip)] Bytes(Vec<u8>), } impl DataKey { pub fn is_integer(&self) -> bool { matches!(self, Self::Integer(_)) } pub fn as_str(&self) -> Option<&str> { match self { Self::String(s) => Some(s), _ => None, } } pub fn into_url(self) -> Option<UrlCow<'static>> { match self { Self::String(s) => s.try_into().ok(), Self::Url(u) => Some(u.into()), Self::Bytes(b) => b.try_into().ok(), _ => None, } } fn deserialize_integer<'de, D>(deserializer: D) -> Result<i64, D::Error> where D: de::Deserializer<'de>, { struct Visitor; impl de::Visitor<'_> for Visitor { type Value = i64; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { formatter.write_str("an integer or a string of an integer") } fn visit_i64<E>(self, value: i64) -> Result<i64, E> { Ok(value) } fn visit_str<E>(self, value: &str) -> Result<i64, E> where E: de::Error, { value.parse().map_err(de::Error::custom) } } deserializer.deserialize_any(Visitor) } } impl From<usize> for DataKey { fn from(value: usize) -> Self { Self::Integer(value as i64) } } impl From<&'static str> for DataKey { fn from(value: &'static str) -> Self { Self::String(Cow::Borrowed(value)) } } impl From<String> for DataKey { fn from(value: String) -> Self { Self::String(Cow::Owned(value)) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/data/mod.rs
yazi-shared/src/data/mod.rs
yazi_macro::mod_flat!(data key);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/data/data.rs
yazi-shared/src/data/data.rs
use std::{any::Any, borrow::Cow}; use anyhow::{Result, bail}; use hashbrown::HashMap; use serde::{Deserialize, Serialize}; use crate::{Id, SStr, data::DataKey, path::PathBufDyn, url::{UrlBuf, UrlCow}}; // --- Data #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum Data { Nil, Boolean(bool), Integer(i64), Number(f64), String(SStr), List(Vec<Self>), Dict(HashMap<DataKey, Self>), Id(Id), #[serde(skip_deserializing)] Url(UrlBuf), #[serde(skip)] Path(PathBufDyn), #[serde(skip)] Bytes(Vec<u8>), #[serde(skip)] Any(Box<dyn Any + Send + Sync>), } impl From<()> for Data { fn from(_: ()) -> Self { Self::Nil } } impl From<bool> for Data { fn from(value: bool) -> Self { Self::Boolean(value) } } impl From<i32> for Data { fn from(value: i32) -> Self { Self::Integer(value as i64) } } impl From<i64> for Data { fn from(value: i64) -> Self { Self::Integer(value) } } impl From<f64> for Data { fn from(value: f64) -> Self { Self::Number(value) } } impl From<usize> for Data { fn from(value: usize) -> Self { Self::Id(value.into()) } } impl From<String> for Data { fn from(value: String) -> Self { Self::String(Cow::Owned(value)) } } impl From<SStr> for Data { fn from(value: SStr) -> Self { Self::String(value) } } impl From<Id> for Data { fn from(value: Id) -> Self { Self::Id(value) } } impl From<UrlBuf> for Data { fn from(value: UrlBuf) -> Self { Self::Url(value) } } impl From<&UrlBuf> for Data { fn from(value: &UrlBuf) -> Self { Self::Url(value.clone()) } } impl From<&str> for Data { fn from(value: &str) -> Self { Self::String(Cow::Owned(value.to_owned())) } } impl TryFrom<&Data> for bool { type Error = anyhow::Error; fn try_from(value: &Data) -> Result<Self, Self::Error> { match value { Data::Boolean(b) => Ok(*b), Data::String(s) if s == "no" => Ok(false), Data::String(s) if s == "yes" => Ok(true), _ => bail!("not a boolean"), } } } impl<'a> TryFrom<&'a Data> for &'a str { type Error = anyhow::Error; fn try_from(value: &'a Data) -> Result<Self, Self::Error> { match value { Data::String(s) => Ok(s), _ => bail!("not a string"), } } } impl TryFrom<Data> for SStr { type Error = anyhow::Error; fn try_from(value: Data) -> Result<Self, Self::Error> { match value { Data::String(s) => Ok(s), _ => bail!("not a string"), } } } impl<'a> TryFrom<&'a Data> for Cow<'a, str> { type Error = anyhow::Error; fn try_from(value: &'a Data) -> Result<Self, Self::Error> { match value { Data::String(s) => Ok(Cow::Borrowed(s)), _ => bail!("not a string"), } } } impl TryFrom<Data> for HashMap<DataKey, Data> { type Error = anyhow::Error; fn try_from(value: Data) -> Result<Self, Self::Error> { match value { Data::Dict(d) => Ok(d), _ => bail!("not a dict"), } } } impl TryFrom<&Data> for HashMap<DataKey, Data> { type Error = anyhow::Error; fn try_from(_: &Data) -> Result<Self, Self::Error> { bail!("cannot take ownership of dict from &Data"); } } impl TryFrom<Data> for UrlCow<'static> { type Error = anyhow::Error; fn try_from(value: Data) -> Result<Self, Self::Error> { match value { Data::String(s) => s.try_into(), Data::Url(u) => Ok(u.into()), Data::Bytes(b) => b.try_into(), _ => bail!("not a URL"), } } } impl<'a> TryFrom<&'a Data> for UrlCow<'a> { type Error = anyhow::Error; fn try_from(value: &'a Data) -> Result<Self, Self::Error> { match value { Data::String(s) => Self::try_from(&**s), Data::Url(u) => Ok(u.into()), Data::Bytes(b) => b.as_slice().try_into(), _ => bail!("not a URL"), } } } impl<'a> TryFrom<&'a Data> for &'a [u8] { type Error = anyhow::Error; fn try_from(value: &'a Data) -> Result<Self, Self::Error> { match value { Data::Bytes(b) => Ok(b), _ => bail!("not bytes"), } } } impl PartialEq<bool> for Data { fn eq(&self, other: &bool) -> bool { self.try_into().is_ok_and(|b| *other == b) } } impl Data { pub fn as_str(&self) -> Option<&str> { match self { Self::String(s) => Some(s), _ => None, } } pub fn into_string(self) -> Option<SStr> { match self { Self::String(s) => Some(s), _ => None, } } pub fn into_any<T: 'static>(self) -> Option<T> { match self { Self::Any(b) => b.downcast::<T>().ok().map(|b| *b), _ => None, } } // FIXME: find a better name pub fn into_any2<T: 'static>(self) -> Result<T> { if let Self::Any(b) = self && let Ok(t) = b.downcast::<T>() { Ok(*t) } else { bail!("Failed to downcast Data into {}", std::any::type_name::<T>()) } } } impl<'de> serde::Deserializer<'de> for &Data { type Error = serde::de::value::Error; fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(serde::de::Error::custom("any not supported")) } fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_bool(self.try_into().map_err(serde::de::Error::custom)?) } fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_i8(self.try_into().map_err(serde::de::Error::custom)?) } fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_i16(self.try_into().map_err(serde::de::Error::custom)?) } fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_i32(self.try_into().map_err(serde::de::Error::custom)?) } fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_i64(self.try_into().map_err(serde::de::Error::custom)?) } fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_u8(self.try_into().map_err(serde::de::Error::custom)?) } fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_u16(self.try_into().map_err(serde::de::Error::custom)?) } fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_u32(self.try_into().map_err(serde::de::Error::custom)?) } fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_u64(self.try_into().map_err(serde::de::Error::custom)?) } fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_f32(self.try_into().map_err(serde::de::Error::custom)?) } fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_f64(self.try_into().map_err(serde::de::Error::custom)?) } fn deserialize_char<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(serde::de::Error::custom("not a char")) } fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_str(self.try_into().map_err(serde::de::Error::custom)?) } fn deserialize_string<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(serde::de::Error::custom("string not supported")) } fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_bytes(self.try_into().map_err(serde::de::Error::custom)?) } fn deserialize_byte_buf<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(serde::de::Error::custom("byte buf not supported")) } fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { match self { Data::Nil => visitor.visit_none(), _ => visitor.visit_some(self), } } fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_unit() } fn deserialize_unit_struct<V>( self, _name: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_unit() } fn deserialize_newtype_struct<V>( self, _name: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_newtype_struct(self) } fn deserialize_seq<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(serde::de::Error::custom("seq not supported")) } fn deserialize_tuple<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(serde::de::Error::custom("tuple not supported")) } fn deserialize_tuple_struct<V>( self, _name: &'static str, _len: usize, _visitor: V, ) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(serde::de::Error::custom("tuple struct not supported")) } fn deserialize_map<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(serde::de::Error::custom("map not supported")) } fn deserialize_struct<V>( self, _name: &'static str, _fields: &'static [&'static str], _visitor: V, ) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(serde::de::Error::custom("struct not supported")) } fn deserialize_enum<V>( self, _name: &'static str, _variants: &'static [&'static str], _visitor: V, ) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(serde::de::Error::custom("enum not supported")) } fn deserialize_identifier<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(serde::de::Error::custom("identifier not supported")) } fn deserialize_ignored_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(serde::de::Error::custom("ignored any not supported")) } } // --- Macros macro_rules! impl_into_integer { ($t:ty) => { impl TryFrom<&Data> for $t { type Error = anyhow::Error; fn try_from(value: &Data) -> Result<Self, Self::Error> { Ok(match value { Data::Integer(i) => <$t>::try_from(*i)?, Data::String(s) => s.parse()?, Data::Id(i) => <$t>::try_from(i.get())?, _ => bail!("not an integer"), }) } } }; } macro_rules! impl_into_number { ($t:ty) => { impl TryFrom<&Data> for $t { type Error = anyhow::Error; fn try_from(value: &Data) -> Result<Self, Self::Error> { Ok(match value { Data::Integer(i) if *i == (*i as $t as _) => *i as $t, Data::Number(n) if *n == (*n as $t as _) => *n as $t, Data::String(s) => s.parse()?, Data::Id(i) if i.0 == (i.0 as $t as _) => i.0 as $t, _ => bail!("not a number"), }) } } }; } impl_into_integer!(i8); impl_into_integer!(i16); impl_into_integer!(i32); impl_into_integer!(i64); impl_into_integer!(isize); impl_into_integer!(u8); impl_into_integer!(u16); impl_into_integer!(u32); impl_into_integer!(u64); impl_into_integer!(usize); impl_into_integer!(crate::Id); impl_into_number!(f32); impl_into_number!(f64);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/path/path.rs
yazi-shared/src/path/path.rs
use std::{borrow::Cow, ffi::OsStr}; use anyhow::Result; use hashbrown::Equivalent; use super::{RsplitOnceError, StartsWithError}; use crate::{BytesExt, Utf8BytePredictor, path::{AsPath, Components, Display, EndsWithError, JoinError, PathBufDyn, PathDynError, PathKind, StripPrefixError, StripSuffixError}, strand::{AsStrand, Strand, StrandError}}; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum PathDyn<'p> { Os(&'p std::path::Path), Unix(&'p typed_path::UnixPath), } impl<'a> From<&'a std::path::Path> for PathDyn<'a> { fn from(value: &'a std::path::Path) -> Self { Self::Os(value) } } impl<'a> From<&'a typed_path::UnixPath> for PathDyn<'a> { fn from(value: &'a typed_path::UnixPath) -> Self { Self::Unix(value) } } impl<'a> From<&'a PathBufDyn> for PathDyn<'a> { fn from(value: &'a PathBufDyn) -> Self { value.as_path() } } impl PartialEq<PathBufDyn> for PathDyn<'_> { fn eq(&self, other: &PathBufDyn) -> bool { *self == other.as_path() } } impl PartialEq<PathDyn<'_>> for &std::path::Path { fn eq(&self, other: &PathDyn<'_>) -> bool { matches!(*other, PathDyn::Os(p) if p == *self) } } impl PartialEq<&std::path::Path> for PathDyn<'_> { fn eq(&self, other: &&std::path::Path) -> bool { matches!(*self, PathDyn::Os(p) if p == *other) } } impl PartialEq<&str> for PathDyn<'_> { fn eq(&self, other: &&str) -> bool { match *self { PathDyn::Os(p) => p == *other, PathDyn::Unix(p) => p == typed_path::UnixPath::new(other), } } } impl Equivalent<PathBufDyn> for PathDyn<'_> { fn equivalent(&self, key: &PathBufDyn) -> bool { *self == key.as_path() } } impl<'p> PathDyn<'p> { #[inline] pub fn as_os(self) -> Result<&'p std::path::Path, PathDynError> { match self { Self::Os(p) => Ok(p), Self::Unix(_) => Err(PathDynError::AsOs), } } #[inline] pub fn as_unix(self) -> Result<&'p typed_path::UnixPath, PathDynError> { match self { Self::Os(_) => Err(PathDynError::AsUnix), Self::Unix(p) => Ok(p), } } pub fn components(self) -> Components<'p> { match self { Self::Os(p) => Components::Os(p.components()), Self::Unix(p) => Components::Unix(p.components()), } } pub fn display(self) -> Display<'p> { Display(self) } pub fn encoded_bytes(self) -> &'p [u8] { match self { Self::Os(p) => p.as_os_str().as_encoded_bytes(), Self::Unix(p) => p.as_bytes(), } } pub fn ext(self) -> Option<Strand<'p>> { Some(match self { Self::Os(p) => p.extension()?.into(), Self::Unix(p) => p.extension()?.into(), }) } #[inline] pub unsafe fn from_encoded_bytes<K>(kind: K, bytes: &'p [u8]) -> Self where K: Into<PathKind>, { match kind.into() { PathKind::Os => Self::Os(unsafe { OsStr::from_encoded_bytes_unchecked(bytes) }.as_ref()), PathKind::Unix => Self::Unix(typed_path::UnixPath::new(bytes)), } } pub fn has_root(self) -> bool { match self { Self::Os(p) => p.has_root(), Self::Unix(p) => p.has_root(), } } pub fn is_absolute(self) -> bool { match self { Self::Os(p) => p.is_absolute(), Self::Unix(p) => p.is_absolute(), } } pub fn is_empty(self) -> bool { self.encoded_bytes().is_empty() } #[cfg(unix)] pub fn is_hidden(self) -> bool { self.name().is_some_and(|n| n.encoded_bytes().first() == Some(&b'.')) } pub fn kind(self) -> PathKind { match self { Self::Os(_) => PathKind::Os, Self::Unix(_) => PathKind::Unix, } } pub fn len(self) -> usize { self.encoded_bytes().len() } pub fn name(self) -> Option<Strand<'p>> { Some(match self { Self::Os(p) => p.file_name()?.into(), Self::Unix(p) => p.file_name()?.into(), }) } pub fn parent(self) -> Option<Self> { Some(match self { Self::Os(p) => Self::Os(p.parent().filter(|p| !p.as_os_str().is_empty())?), Self::Unix(p) => Self::Unix(p.parent().filter(|p| !p.as_bytes().is_empty())?), }) } pub fn rsplit_pred<T>(self, pred: T) -> Option<(Self, Self)> where T: Utf8BytePredictor, { let (a, b) = self.encoded_bytes().rsplit_pred_once(pred)?; Some(unsafe { (Self::from_encoded_bytes(self.kind(), a), Self::from_encoded_bytes(self.kind(), b)) }) } pub fn stem(self) -> Option<Strand<'p>> { Some(match self { Self::Os(p) => p.file_stem()?.into(), Self::Unix(p) => p.file_stem()?.into(), }) } #[inline] pub fn to_os_owned(self) -> Result<std::path::PathBuf, PathDynError> { match self { Self::Os(p) => Ok(p.to_owned()), Self::Unix(_) => Err(PathDynError::AsOs), } } pub fn to_owned(self) -> PathBufDyn { match self { Self::Os(p) => PathBufDyn::Os(p.to_owned()), Self::Unix(p) => PathBufDyn::Unix(p.to_owned()), } } pub fn to_str(self) -> Result<&'p str, std::str::Utf8Error> { str::from_utf8(self.encoded_bytes()) } pub fn to_string_lossy(self) -> Cow<'p, str> { String::from_utf8_lossy(self.encoded_bytes()) } pub fn to_unix_owned(self) -> Result<typed_path::UnixPathBuf, PathDynError> { match self { Self::Os(_) => Err(PathDynError::AsUnix), Self::Unix(p) => Ok(p.to_owned()), } } pub fn try_ends_with<T>(self, child: T) -> Result<bool, EndsWithError> where T: AsStrand, { let s = child.as_strand(); Ok(match self { Self::Os(p) => p.ends_with(s.as_os()?), Self::Unix(p) => p.ends_with(s.encoded_bytes()), }) } pub fn try_join<T>(self, path: T) -> Result<PathBufDyn, JoinError> where T: AsStrand, { let s = path.as_strand(); Ok(match self { Self::Os(p) => PathBufDyn::Os(p.join(s.as_os()?)), Self::Unix(p) => PathBufDyn::Unix(p.join(s.encoded_bytes())), }) } pub fn try_rsplit_seq<T>(self, pat: T) -> Result<(Self, Self), RsplitOnceError> where T: AsStrand, { let pat = pat.as_strand(); let (a, b) = match self { PathDyn::Os(p) => { p.as_os_str().as_encoded_bytes().rsplit_seq_once(pat.as_os()?.as_encoded_bytes()) } PathDyn::Unix(p) => p.as_bytes().rsplit_seq_once(pat.encoded_bytes()), } .ok_or(RsplitOnceError::NotFound)?; Ok(unsafe { (Self::from_encoded_bytes(self.kind(), a), Self::from_encoded_bytes(self.kind(), b)) }) } pub fn try_starts_with<T>(self, base: T) -> Result<bool, StartsWithError> where T: AsStrand, { let s = base.as_strand(); Ok(match self { Self::Os(p) => p.starts_with(s.as_os()?), Self::Unix(p) => p.starts_with(s.encoded_bytes()), }) } pub fn try_strip_prefix<T>(self, base: T) -> Result<Self, StripPrefixError> where T: AsStrand, { let s = base.as_strand(); Ok(match self { Self::Os(p) => Self::Os(p.strip_prefix(s.as_os()?)?), Self::Unix(p) => Self::Unix(p.strip_prefix(s.encoded_bytes())?), }) } pub fn try_strip_suffix<T>(self, suffix: T) -> Result<Self, StripSuffixError> where T: AsStrand, { let s = suffix.as_strand(); let mut me_comps = self.components(); let mut suf_comps = match self.kind() { PathKind::Os => Components::Os(std::path::Path::new(s.as_os()?).components()), PathKind::Unix => Components::Unix(typed_path::UnixPath::new(s.encoded_bytes()).components()), }; while let Some(next) = suf_comps.next_back() { if me_comps.next_back() != Some(next) { return Err(StripSuffixError::NotSuffix); } } Ok(me_comps.path()) } pub fn with<K, S>(kind: K, strand: &'p S) -> Result<Self, StrandError> where K: Into<PathKind>, S: ?Sized + AsStrand, { let s = strand.as_strand(); Ok(match kind.into() { PathKind::Os => Self::Os(std::path::Path::new(s.as_os()?)), PathKind::Unix => Self::Unix(typed_path::UnixPath::new(s.encoded_bytes())), }) } pub fn with_str<K, S>(kind: K, s: &'p S) -> Self where K: Into<PathKind>, S: ?Sized + AsRef<str>, { let s = s.as_ref(); match kind.into() { PathKind::Os => Self::Os(s.as_ref()), PathKind::Unix => Self::Unix(s.as_ref()), } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/path/view.rs
yazi-shared/src/path/view.rs
// --- AsPathView pub trait AsPathView<'a, T> { fn as_path_view(self) -> T; } impl<'a> AsPathView<'a, &'a std::path::Path> for &'a std::path::Path { fn as_path_view(self) -> &'a std::path::Path { self } } impl<'a> AsPathView<'a, &'a std::path::Path> for &'a std::path::PathBuf { fn as_path_view(self) -> &'a std::path::Path { self } } impl<'a> AsPathView<'a, &'a typed_path::UnixPath> for &'a typed_path::UnixPath { fn as_path_view(self) -> &'a typed_path::UnixPath { self } } impl<'a> AsPathView<'a, &'a typed_path::UnixPath> for &'a typed_path::UnixPathBuf { fn as_path_view(self) -> &'a typed_path::UnixPath { self } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/path/like.rs
yazi-shared/src/path/like.rs
use std::borrow::Cow; use anyhow::Result; use crate::{Utf8BytePredictor, path::{AsPath, Components, Display, EndsWithError, JoinError, PathBufDyn, PathCow, PathDyn, PathDynError, PathKind, RsplitOnceError, StartsWithError, StripPrefixError, StripSuffixError}, strand::{AsStrand, Strand}}; pub trait PathLike: AsPath { fn as_os(&self) -> Result<&std::path::Path, PathDynError> { self.as_path().as_os() } fn as_unix(&self) -> Result<&typed_path::UnixPath, PathDynError> { self.as_path().as_unix() } fn components(&self) -> Components<'_> { self.as_path().components() } fn display(&self) -> Display<'_> { self.as_path().display() } fn encoded_bytes(&self) -> &[u8] { self.as_path().encoded_bytes() } fn ext(&self) -> Option<Strand<'_>> { self.as_path().ext() } fn has_root(&self) -> bool { self.as_path().has_root() } fn is_absolute(&self) -> bool { self.as_path().is_absolute() } fn is_empty(&self) -> bool { self.as_path().is_empty() } #[cfg(unix)] fn is_hidden(&self) -> bool { self.as_path().is_hidden() } fn kind(&self) -> PathKind { self.as_path().kind() } fn len(&self) -> usize { self.as_path().len() } fn name(&self) -> Option<Strand<'_>> { self.as_path().name() } fn parent(&self) -> Option<PathDyn<'_>> { self.as_path().parent() } fn rsplit_pred<T>(&self, pred: T) -> Option<(PathDyn<'_>, PathDyn<'_>)> where T: Utf8BytePredictor, { self.as_path().rsplit_pred(pred) } fn stem(&self) -> Option<Strand<'_>> { self.as_path().stem() } fn to_os_owned(&self) -> Result<std::path::PathBuf, PathDynError> { self.as_path().to_os_owned() } fn to_owned(&self) -> PathBufDyn { self.as_path().to_owned() } fn to_str(&self) -> Result<&str, std::str::Utf8Error> { self.as_path().to_str() } fn to_string_lossy(&self) -> Cow<'_, str> { self.as_path().to_string_lossy() } fn try_ends_with<T>(&self, child: T) -> Result<bool, EndsWithError> where T: AsStrand, { self.as_path().try_ends_with(child) } fn try_join<T>(&self, path: T) -> Result<PathBufDyn, JoinError> where T: AsStrand, { self.as_path().try_join(path) } fn try_rsplit_seq<T>(&self, pat: T) -> Result<(PathDyn<'_>, PathDyn<'_>), RsplitOnceError> where T: AsStrand, { self.as_path().try_rsplit_seq(pat) } fn try_starts_with<T>(&self, base: T) -> Result<bool, StartsWithError> where T: AsStrand, { self.as_path().try_starts_with(base) } fn try_strip_prefix<T>(&self, base: T) -> Result<PathDyn<'_>, StripPrefixError> where T: AsStrand, { self.as_path().try_strip_prefix(base) } fn try_strip_suffix<T>(&self, suffix: T) -> Result<PathDyn<'_>, StripSuffixError> where T: AsStrand, { self.as_path().try_strip_suffix(suffix) } } impl<P> From<&P> for PathBufDyn where P: PathLike, { fn from(value: &P) -> Self { value.to_owned() } } impl PathLike for PathBufDyn {} impl PathLike for PathCow<'_> {}
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/path/kind.rs
yazi-shared/src/path/kind.rs
use crate::scheme::SchemeKind; pub enum PathKind { Os, Unix, } impl From<SchemeKind> for PathKind { fn from(value: SchemeKind) -> Self { match value { SchemeKind::Regular => Self::Os, SchemeKind::Search => Self::Os, SchemeKind::Archive => Self::Os, SchemeKind::Sftp => Self::Unix, } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/path/error.rs
yazi-shared/src/path/error.rs
use thiserror::Error; use crate::strand::StrandError; // --- EndsWithError #[derive(Debug, Error)] #[error("calling ends_with on paths with different encodings")] pub enum EndsWithError { FromStrand(#[from] StrandError), } // --- JoinError #[derive(Debug, Error)] #[error("calling join on paths with different encodings")] pub enum JoinError { FromStrand(#[from] StrandError), FromPathDyn(#[from] PathDynError), } impl From<StartsWithError> for JoinError { fn from(err: StartsWithError) -> Self { match err { StartsWithError::FromStrand(e) => Self::FromStrand(e), } } } impl From<JoinError> for std::io::Error { fn from(err: JoinError) -> Self { Self::other(err) } } // --- PathDynError #[derive(Debug, Error)] pub enum PathDynError { #[error("conversion to OS path failed")] AsOs, #[error("conversion to Unix path failed")] AsUnix, #[error("conversion to UTF-8 path failed")] AsUtf8, } impl From<StrandError> for PathDynError { fn from(err: StrandError) -> Self { match err { StrandError::AsOs => Self::AsOs, StrandError::AsUtf8 => Self::AsUtf8, } } } impl From<PathDynError> for std::io::Error { fn from(err: PathDynError) -> Self { Self::other(err) } } // --- SetNameError #[derive(Debug, Error)] #[error("calling set_name on paths with different encodings")] pub enum SetNameError { FromStrand(#[from] StrandError), } impl From<SetNameError> for std::io::Error { fn from(err: SetNameError) -> Self { Self::other(err) } } // --- RsplitOnce #[derive(Error, Debug)] #[error("calling rsplit_once on paths with different encodings")] pub enum RsplitOnceError { #[error("conversion to OsStr failed")] AsOs, #[error("conversion to UTF-8 str failed")] AsUtf8, #[error("the pattern was not found")] NotFound, } impl From<StrandError> for RsplitOnceError { fn from(err: StrandError) -> Self { match err { StrandError::AsOs => Self::AsOs, StrandError::AsUtf8 => Self::AsUtf8, } } } // --- StartsWithError #[derive(Error, Debug)] #[error("calling starts_with on paths with different encodings")] pub enum StartsWithError { FromStrand(#[from] StrandError), } // --- StripPrefixError #[derive(Debug, Error)] pub enum StripPrefixError { #[error("calling strip_prefix on URLs with different schemes")] Exotic, #[error("the base is not a prefix of the path")] NotPrefix, #[error("calling strip_prefix on paths with different encodings")] WrongEncoding, } impl From<StrandError> for StripPrefixError { fn from(err: StrandError) -> Self { match err { StrandError::AsOs | StrandError::AsUtf8 => Self::WrongEncoding, } } } impl From<std::path::StripPrefixError> for StripPrefixError { fn from(_: std::path::StripPrefixError) -> Self { Self::NotPrefix } } impl From<typed_path::StripPrefixError> for StripPrefixError { fn from(_: typed_path::StripPrefixError) -> Self { Self::NotPrefix } } // --- StripSuffixError #[derive(Debug, Error)] pub enum StripSuffixError { #[error("calling strip_suffix on URLs with different schemes")] Exotic, #[error("the base is not a suffix of the path")] NotSuffix, #[error("calling strip_suffix on paths with different encodings")] WrongEncoding, } impl From<StrandError> for StripSuffixError { fn from(err: StrandError) -> Self { match err { StrandError::AsOs | StrandError::AsUtf8 => Self::WrongEncoding, } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/path/conversion.rs
yazi-shared/src/path/conversion.rs
use super::{PathBufDyn, PathDyn}; use crate::path::PathCow; // --- AsPath pub trait AsPath { fn as_path(&self) -> PathDyn<'_>; } impl AsPath for std::path::Path { fn as_path(&self) -> PathDyn<'_> { PathDyn::Os(self) } } impl AsPath for std::path::PathBuf { fn as_path(&self) -> PathDyn<'_> { PathDyn::Os(self) } } impl AsPath for typed_path::UnixPath { fn as_path(&self) -> PathDyn<'_> { PathDyn::Unix(self) } } impl AsPath for typed_path::UnixPathBuf { fn as_path(&self) -> PathDyn<'_> { PathDyn::Unix(self) } } impl AsPath for PathDyn<'_> { fn as_path(&self) -> PathDyn<'_> { *self } } impl AsPath for PathBufDyn { fn as_path(&self) -> PathDyn<'_> { match self { Self::Os(p) => PathDyn::Os(p), Self::Unix(p) => PathDyn::Unix(p), } } } impl AsPath for PathCow<'_> { fn as_path(&self) -> PathDyn<'_> { match self { PathCow::Borrowed(p) => *p, PathCow::Owned(p) => p.as_path(), } } } impl AsPath for super::Components<'_> { fn as_path(&self) -> PathDyn<'_> { self.path() } } // --- AsPathRef pub trait AsPathRef<'a> { fn as_path_ref(self) -> PathDyn<'a>; } impl<'a> AsPathRef<'a> for PathDyn<'a> { fn as_path_ref(self) -> Self { self } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/path/display.rs
yazi-shared/src/path/display.rs
use crate::path::PathDyn; pub struct Display<'a>(pub PathDyn<'a>); impl std::fmt::Display for Display<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self.0 { PathDyn::Os(p) => write!(f, "{}", p.display()), PathDyn::Unix(p) => write!(f, "{}", p.display()), } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/path/mod.rs
yazi-shared/src/path/mod.rs
yazi_macro::mod_flat!(buf component components conversion cow display error kind like path view);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/path/cow.rs
yazi-shared/src/path/cow.rs
use std::borrow::Cow; use anyhow::Result; use crate::path::{AsPath, PathBufDyn, PathDyn, PathDynError, PathKind}; // --- PathCow #[derive(Debug)] pub enum PathCow<'a> { Borrowed(PathDyn<'a>), Owned(PathBufDyn), } impl<'a> From<PathDyn<'a>> for PathCow<'a> { fn from(value: PathDyn<'a>) -> Self { Self::Borrowed(value) } } impl From<PathBufDyn> for PathCow<'_> { fn from(value: PathBufDyn) -> Self { Self::Owned(value) } } impl<'a> From<std::path::PathBuf> for PathCow<'a> { fn from(value: std::path::PathBuf) -> Self { Self::Owned(value.into()) } } impl<'a> From<&'a PathCow<'_>> for PathCow<'a> { fn from(value: &'a PathCow<'_>) -> Self { Self::Borrowed(value.as_path()) } } impl From<PathCow<'_>> for PathBufDyn { fn from(value: PathCow<'_>) -> Self { value.into_owned() } } impl PartialEq for PathCow<'_> { fn eq(&self, other: &Self) -> bool { self.as_path() == other.as_path() } } impl PartialEq<&str> for PathCow<'_> { fn eq(&self, other: &&str) -> bool { match self { Self::Borrowed(s) => s.as_path() == *other, Self::Owned(s) => s.as_path() == *other, } } } impl<'a> PathCow<'a> { pub fn into_owned(self) -> PathBufDyn { match self { Self::Borrowed(p) => p.to_owned(), Self::Owned(p) => p, } } pub fn into_os(self) -> Result<std::path::PathBuf, PathDynError> { match self { PathCow::Borrowed(p) => p.to_os_owned(), PathCow::Owned(p) => p.into_os(), } } pub fn is_borrowed(&self) -> bool { matches!(self, Self::Borrowed(_)) } pub fn with<K, T>(kind: K, bytes: T) -> Result<Self> where K: Into<PathKind>, T: Into<Cow<'a, [u8]>>, { Ok(match bytes.into() { Cow::Borrowed(b) => PathDyn::with(kind, b)?.into(), Cow::Owned(b) => PathBufDyn::with(kind, b)?.into(), }) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/path/components.rs
yazi-shared/src/path/components.rs
use std::iter::FusedIterator; use typed_path::Components as _; use crate::{path::{Component, PathDyn}, strand::Strand}; #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub enum Components<'a> { Os(std::path::Components<'a>), Unix(typed_path::UnixComponents<'a>), } impl<'a> Components<'a> { pub fn path(&self) -> PathDyn<'a> { match self { Self::Os(c) => PathDyn::Os(c.as_path()), Self::Unix(c) => PathDyn::Unix(c.as_path()), } } pub fn strand(&self) -> Strand<'a> { match self { Self::Os(c) => Strand::Os(c.as_path().as_os_str()), Self::Unix(c) => Strand::Bytes(c.as_bytes()), } } } impl<'a> Iterator for Components<'a> { type Item = Component<'a>; fn next(&mut self) -> Option<Component<'a>> { match self { Self::Os(c) => c.next().map(Into::into), Self::Unix(c) => c.next().map(Into::into), } } } impl<'a> DoubleEndedIterator for Components<'a> { fn next_back(&mut self) -> Option<Component<'a>> { match self { Self::Os(c) => c.next_back().map(Into::into), Self::Unix(c) => c.next_back().map(Into::into), } } } impl FusedIterator for Components<'_> {}
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/path/buf.rs
yazi-shared/src/path/buf.rs
use std::{borrow::Cow, ffi::OsString, hash::{Hash, Hasher}}; use hashbrown::Equivalent; use crate::{path::{AsPath, Component, PathDyn, PathDynError, PathKind, SetNameError}, strand::AsStrand, wtf8::FromWtf8Vec}; // --- PathBufDyn #[derive(Clone, Debug, Eq)] pub enum PathBufDyn { Os(std::path::PathBuf), Unix(typed_path::UnixPathBuf), } impl From<std::path::PathBuf> for PathBufDyn { fn from(value: std::path::PathBuf) -> Self { Self::Os(value) } } impl From<typed_path::UnixPathBuf> for PathBufDyn { fn from(value: typed_path::UnixPathBuf) -> Self { Self::Unix(value) } } impl From<PathDyn<'_>> for PathBufDyn { fn from(value: PathDyn<'_>) -> Self { value.to_owned() } } impl From<Cow<'_, std::path::Path>> for PathBufDyn { fn from(value: Cow<'_, std::path::Path>) -> Self { Self::Os(value.into_owned()) } } impl TryFrom<PathBufDyn> for std::path::PathBuf { type Error = PathDynError; fn try_from(value: PathBufDyn) -> Result<Self, Self::Error> { value.into_os() } } impl TryFrom<PathBufDyn> for typed_path::UnixPathBuf { type Error = PathDynError; fn try_from(value: PathBufDyn) -> Result<Self, Self::Error> { value.into_unix() } } // --- Hash impl Hash for PathBufDyn { fn hash<H: Hasher>(&self, state: &mut H) { self.as_path().hash(state) } } // --- PartialEq impl PartialEq for PathBufDyn { fn eq(&self, other: &Self) -> bool { self.as_path() == other.as_path() } } impl PartialEq<PathDyn<'_>> for PathBufDyn { fn eq(&self, other: &PathDyn<'_>) -> bool { self.as_path() == *other } } impl PartialEq<PathDyn<'_>> for &PathBufDyn { fn eq(&self, other: &PathDyn<'_>) -> bool { self.as_path() == *other } } impl Equivalent<PathDyn<'_>> for PathBufDyn { fn equivalent(&self, key: &PathDyn<'_>) -> bool { self.as_path() == *key } } impl PathBufDyn { #[inline] pub unsafe fn from_encoded_bytes<K>(kind: K, bytes: Vec<u8>) -> Self where K: Into<PathKind>, { match kind.into() { PathKind::Os => Self::Os(unsafe { OsString::from_encoded_bytes_unchecked(bytes) }.into()), PathKind::Unix => Self::Unix(bytes.into()), } } #[inline] pub fn from_components<'a, K, I>(kind: K, iter: I) -> Result<Self, PathDynError> where K: Into<PathKind>, I: IntoIterator<Item = Component<'a>>, { Ok(match kind.into() { PathKind::Os => Self::Os(iter.into_iter().collect::<Result<_, PathDynError>>()?), PathKind::Unix => Self::Unix(iter.into_iter().collect::<Result<_, PathDynError>>()?), }) } pub fn into_encoded_bytes(self) -> Vec<u8> { match self { Self::Os(p) => p.into_os_string().into_encoded_bytes(), Self::Unix(p) => p.into_vec(), } } #[inline] pub fn into_os(self) -> Result<std::path::PathBuf, PathDynError> { Ok(match self { Self::Os(p) => p, Self::Unix(_) => Err(PathDynError::AsOs)?, }) } #[inline] pub fn into_unix(self) -> Result<typed_path::UnixPathBuf, PathDynError> { Ok(match self { Self::Os(_) => Err(PathDynError::AsUnix)?, Self::Unix(p) => p, }) } #[inline] pub fn new(kind: PathKind) -> Self { match kind { PathKind::Os => Self::Os(std::path::PathBuf::new()), PathKind::Unix => Self::Unix(typed_path::UnixPathBuf::new()), } } pub fn try_extend<T>(&mut self, paths: T) -> Result<(), PathDynError> where T: IntoIterator, T::Item: AsPath, { for p in paths { self.try_push(p)?; } Ok(()) } pub fn try_push<T>(&mut self, path: T) -> Result<(), PathDynError> where T: AsPath, { let path = path.as_path(); Ok(match self { Self::Os(p) => p.push(path.as_os()?), Self::Unix(p) => p.push(path.encoded_bytes()), }) } pub fn try_set_name<T>(&mut self, name: T) -> Result<(), SetNameError> where T: AsStrand, { let s = name.as_strand(); Ok(match self { Self::Os(p) => p.set_file_name(s.as_os()?), Self::Unix(p) => p.set_file_name(s.encoded_bytes()), }) } pub fn with<K>(kind: K, bytes: Vec<u8>) -> Result<Self, PathDynError> where K: Into<PathKind>, { Ok(match kind.into() { PathKind::Os => { Self::Os(std::path::PathBuf::from_wtf8_vec(bytes).map_err(|_| PathDynError::AsOs)?) } PathKind::Unix => Self::Unix(bytes.into()), }) } pub fn with_capacity<K>(kind: K, capacity: usize) -> Self where K: Into<PathKind>, { match kind.into() { PathKind::Os => Self::Os(std::path::PathBuf::with_capacity(capacity)), PathKind::Unix => Self::Unix(typed_path::UnixPathBuf::with_capacity(capacity)), } } pub fn with_str<K, S>(kind: K, s: S) -> Self where K: Into<PathKind>, S: Into<String>, { let s = s.into(); match kind.into() { PathKind::Os => Self::Os(s.into()), PathKind::Unix => Self::Unix(s.into()), } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/path/component.rs
yazi-shared/src/path/component.rs
use std::path::PrefixComponent; use crate::{path::PathDynError, strand::Strand}; #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum Component<'a> { Prefix(PrefixComponent<'a>), RootDir, CurDir, ParentDir, Normal(Strand<'a>), } impl<'a> Component<'a> { pub fn as_normal(&self) -> Option<Strand<'a>> { match self { Self::Normal(s) => Some(*s), _ => None, } } } impl<'a> From<std::path::Component<'a>> for Component<'a> { fn from(value: std::path::Component<'a>) -> Self { match value { std::path::Component::Prefix(p) => Self::Prefix(p), std::path::Component::RootDir => Self::RootDir, std::path::Component::CurDir => Self::CurDir, std::path::Component::ParentDir => Self::ParentDir, std::path::Component::Normal(s) => Self::Normal(Strand::Os(s)), } } } impl<'a> From<typed_path::UnixComponent<'a>> for Component<'a> { fn from(value: typed_path::UnixComponent<'a>) -> Self { match value { typed_path::UnixComponent::RootDir => Self::RootDir, typed_path::UnixComponent::CurDir => Self::CurDir, typed_path::UnixComponent::ParentDir => Self::ParentDir, typed_path::UnixComponent::Normal(b) => Self::Normal(Strand::Bytes(b)), } } } impl<'a> TryFrom<Component<'a>> for std::path::Component<'a> { type Error = PathDynError; fn try_from(value: Component<'a>) -> Result<Self, Self::Error> { Ok(match value { Component::Prefix(p) => Self::Prefix(p), Component::RootDir => Self::RootDir, Component::CurDir => Self::CurDir, Component::ParentDir => Self::ParentDir, Component::Normal(s) => Self::Normal(s.as_os()?), }) } } impl<'a> TryFrom<Component<'a>> for typed_path::UnixComponent<'a> { type Error = PathDynError; fn try_from(value: Component<'a>) -> Result<Self, Self::Error> { Ok(match value { Component::Prefix(_) => Err(PathDynError::AsUnix)?, Component::RootDir => Self::RootDir, Component::CurDir => Self::CurDir, Component::ParentDir => Self::ParentDir, Component::Normal(s) => Self::Normal(s.encoded_bytes()), }) } } impl<'a> FromIterator<Component<'a>> for Result<std::path::PathBuf, PathDynError> { fn from_iter<I: IntoIterator<Item = Component<'a>>>(iter: I) -> Self { iter.into_iter().map(std::path::Component::try_from).collect() } } impl<'a> FromIterator<Component<'a>> for Result<typed_path::UnixPathBuf, PathDynError> { fn from_iter<I: IntoIterator<Item = Component<'a>>>(iter: I) -> Self { iter.into_iter().map(typed_path::UnixComponent::try_from).collect() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/shell/unix.rs
yazi-shared/src/shell/unix.rs
use std::{borrow::Cow, mem}; use crate::shell::SplitError; pub fn escape_os_bytes(b: &[u8]) -> Cow<'_, [u8]> { if !b.is_empty() && b.iter().copied().all(allowed) { return Cow::Borrowed(b); } let mut escaped = Vec::with_capacity(b.len() + 2); escaped.push(b'\''); for &c in b { match c { b'\'' | b'!' => { escaped.reserve(4); escaped.push(b'\''); escaped.push(b'\\'); escaped.push(c); escaped.push(b'\''); } _ => escaped.push(c), } } escaped.push(b'\''); escaped.into() } #[cfg(unix)] pub fn escape_os_str(s: &std::ffi::OsStr) -> Cow<'_, std::ffi::OsStr> { use std::os::unix::ffi::{OsStrExt, OsStringExt}; match escape_os_bytes(s.as_bytes()) { Cow::Borrowed(_) => Cow::Borrowed(s), Cow::Owned(v) => std::ffi::OsString::from_vec(v).into(), } } fn allowed(b: u8) -> bool { matches!(b, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'_' | b'=' | b'/' | b',' | b'.' | b'+') } pub fn split(s: &str, eoo: bool) -> Result<(Vec<String>, Option<String>), SplitError> { enum State { /// Within a delimiter. Delimiter, /// After backslash, but before starting word. Backslash, /// Within an unquoted word. Unquoted, /// After backslash in an unquoted word. UnquotedBackslash, /// Within a single quoted word. SingleQuoted, /// Within a double quoted word. DoubleQuoted, /// After backslash inside a double quoted word. DoubleQuotedBackslash, /// Inside a comment. Comment, } use State::*; let mut words = Vec::new(); let mut word = String::new(); let mut chars = s.chars(); let mut state = Delimiter; macro_rules! flush { () => { if word == "--" && eoo { return Ok((words, Some(chars.collect()))); } words.push(mem::take(&mut word)); }; } loop { let c = chars.next(); state = match state { Delimiter => match c { None => break, Some('\'') => SingleQuoted, Some('\"') => DoubleQuoted, Some('\\') => Backslash, Some('\t') | Some(' ') | Some('\n') => Delimiter, Some('#') => Comment, Some(c) => { word.push(c); Unquoted } }, Backslash => match c { None => { word.push('\\'); flush!(); break; } Some('\n') => Delimiter, Some(c) => { word.push(c); Unquoted } }, Unquoted => match c { None => { flush!(); break; } Some('\'') => SingleQuoted, Some('\"') => DoubleQuoted, Some('\\') => UnquotedBackslash, Some('\t') | Some(' ') | Some('\n') => { flush!(); Delimiter } Some(c) => { word.push(c); Unquoted } }, UnquotedBackslash => match c { None => { word.push('\\'); flush!(); break; } Some('\n') => Unquoted, Some(c) => { word.push(c); Unquoted } }, SingleQuoted => match c { None => return Err(SplitError::MissingSingleQuote), Some('\'') => Unquoted, Some(c) => { word.push(c); SingleQuoted } }, DoubleQuoted => match c { None => return Err(SplitError::MissingDoubleQuote), Some('\"') => Unquoted, Some('\\') => DoubleQuotedBackslash, Some(c) => { word.push(c); DoubleQuoted } }, DoubleQuotedBackslash => match c { None => return Err(SplitError::MissingQuoteAfterSlash), Some('\n') => DoubleQuoted, Some(c @ '$') | Some(c @ '`') | Some(c @ '"') | Some(c @ '\\') => { word.push(c); DoubleQuoted } Some(c) => { word.push('\\'); word.push(c); DoubleQuoted } }, Comment => match c { None => break, Some('\n') => Delimiter, Some(_) => Comment, }, } } Ok((words, None)) } #[cfg(test)] mod tests { use super::*; #[test] fn test_escape_os_bytes() { let cases: &[(&[u8], &[u8])] = &[ (b"", br#"''"#), (b" ", br#"' '"#), (b"*", br#"'*'"#), (b"--aaa=bbb-ccc", b"--aaa=bbb-ccc"), (br#"--features="default""#, br#"'--features="default"'"#), (b"linker=gcc -L/foo -Wl,bar", br#"'linker=gcc -L/foo -Wl,bar'"#), ( b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_=/,.+", b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_=/,.+", ), (br#"'!\$`\\\n "#, br#"''\'''\!'\$`\\\n '"#), (&[0x66, 0x6f, 0x80, 0x6f], &[b'\'', 0x66, 0x6f, 0x80, 0x6f, b'\'']), ]; for &(input, expected) in cases { let escaped = escape_os_bytes(input); assert_eq!(escaped, expected, "Failed to escape: {:?}", String::from_utf8_lossy(input)); } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/shell/error.rs
yazi-shared/src/shell/error.rs
use thiserror::Error; #[derive(Debug, Error)] pub enum SplitError { #[error("missing closing single quote")] MissingSingleQuote, #[error("missing closing double quote")] MissingDoubleQuote, #[error("missing quote after escape slash")] MissingQuoteAfterSlash, }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/shell/windows.rs
yazi-shared/src/shell/windows.rs
use std::borrow::Cow; pub fn escape_os_bytes(b: &[u8]) -> Cow<'_, [u8]> { let quote = needs_quotes(b); let mut buf = Vec::with_capacity(b.len() + quote as usize * 2); if quote { buf.push(b'"'); } // Loop through the string, escaping `\` only if followed by `"`. // And escaping `"` by doubling them. let mut backslashes: usize = 0; for &c in b { if c == b'\\' { backslashes += 1; } else { if c == b'"' { buf.extend((0..backslashes).map(|_| b'\\')); buf.push(b'"'); } else if c == b'%' { buf.extend_from_slice(b"%%cd:~,"); } else if c == b'\r' || c == b'\n' { buf.extend_from_slice(b"%=%"); backslashes = 0; continue; } backslashes = 0; } buf.push(c); } if quote { buf.extend((0..backslashes).map(|_| b'\\')); buf.push(b'"'); } buf.into() } #[cfg(windows)] pub fn escape_os_str(s: &std::ffi::OsStr) -> Cow<'_, std::ffi::OsStr> { use crate::wtf8::FromWtf8Vec; match escape_os_bytes(s.as_encoded_bytes()) { Cow::Borrowed(_) => Cow::Borrowed(s), Cow::Owned(v) => std::ffi::OsString::from_wtf8_vec(v).expect("valid WTF-8").into(), } } fn needs_quotes(arg: &[u8]) -> bool { static UNQUOTED: &[u8] = br"#$*+-./:?@\_"; if arg.is_empty() || arg.last() == Some(&b'\\') { return true; } for c in arg { if c.is_ascii_control() { return true; } else if c.is_ascii() && !(c.is_ascii_alphanumeric() || UNQUOTED.contains(c)) { return true; } } false } #[cfg(windows)] pub fn split(s: &str) -> std::io::Result<Vec<String>> { use std::os::windows::ffi::OsStrExt; let s: Vec<_> = std::ffi::OsStr::new(s).encode_wide().chain(std::iter::once(0)).collect(); split_wide(&s) } #[cfg(windows)] fn split_wide(s: &[u16]) -> std::io::Result<Vec<String>> { use std::mem::MaybeUninit; use windows_sys::{Win32::{Foundation::LocalFree, UI::Shell::CommandLineToArgvW}, core::PCWSTR}; unsafe extern "C" { fn wcslen(s: PCWSTR) -> usize; } let mut argc = MaybeUninit::<i32>::uninit(); let argv_p = unsafe { CommandLineToArgvW(s.as_ptr(), argc.as_mut_ptr()) }; if argv_p.is_null() { return Err(std::io::Error::last_os_error()); } let argv = unsafe { std::slice::from_raw_parts(argv_p, argc.assume_init() as usize) }; let mut res = vec![]; for &arg in argv { let len = unsafe { wcslen(arg) }; res.push(String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(arg, len) })); } unsafe { LocalFree(argv_p as _) }; Ok(res) } #[cfg(test)] mod tests { use super::*; #[test] fn test_escape_os_bytes() { let cases: &[(&[u8], &[u8])] = &[ // Empty string (b"", br#""""#), (br#""""#, br#""""""""#), // No escaping needed (b"--aaa=bbb-ccc", br#""--aaa=bbb-ccc""#), // Paths with spaces (br#"\path\to\my documents\"#, br#""\path\to\my documents\\""#), // Strings with quotes (br#"--features="default""#, br#""--features=""default""""#), // Nested quotes (br#""--features=\"default\"""#, br#""""--features=\\""default\\""""""#), // Complex command (b"linker=gcc -L/foo -Wl,bar", br#""linker=gcc -L/foo -Wl,bar""#), // Variable expansion (b"%APPDATA%.txt", br#""%%cd:~,%APPDATA%%cd:~,%.txt""#), // Unicode characters ("이것은 테스트".as_bytes(), r#""이것은 테스트""#.as_bytes()), ]; for &(input, expected) in cases { let escaped = escape_os_bytes(input); assert_eq!(escaped, expected, "Failed to escape: {:?}", String::from_utf8_lossy(input)); } } #[cfg(windows)] #[test] fn test_escape_os_str() { use std::{ffi::OsString, os::windows::ffi::OsStringExt}; #[rustfmt::skip] let cases: &[(OsString, OsString)] = &[ // Surrogate pairs and special characters ( OsString::from_wide(&[0x1055, 0x006e, 0x0069, 0x0063, 0x006f, 0x0064, 0x0065]), OsString::from_wide(&[0x1055, 0x006e, 0x0069, 0x0063, 0x006f, 0x0064, 0x0065]), ), // Surrogate pair with quotes ( OsString::from_wide(&[0xd801, 0x006e, 0x0069, 0x0063, 0x006f, 0x0064, 0x0065]), OsString::from_wide(&[0xd801, 0x006e, 0x0069, 0x0063, 0x006f, 0x0064, 0x0065]), ), ]; for (input, expected) in cases { let escaped = escape_os_str(&input); assert_eq!(&*escaped, expected, "Failed to escape: {:?}", input.to_string_lossy()); } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-shared/src/shell/mod.rs
yazi-shared/src/shell/mod.rs
//! Escape characters that may have special meaning in a shell, including //! spaces. This is a modified version of the [`shell-escape`], [`shell-words`], //! [Rust std] and [this PR]. //! //! [`shell-escape`]: https://crates.io/crates/shell-escape //! [`shell-words`]: https://crates.io/crates/shell-words //! [Rust std]: https://github.com/rust-lang/rust/blob/main/library/std/src/sys/args/windows.rs#L220 //! [this PR]: https://github.com/sfackler/shell-escape/pull/9 use std::{borrow::Cow, ffi::OsStr}; yazi_macro::mod_pub!(unix, windows); yazi_macro::mod_flat!(error); #[inline] pub fn escape_os_bytes(b: &[u8]) -> Cow<'_, [u8]> { #[cfg(unix)] { unix::escape_os_bytes(b) } #[cfg(windows)] { windows::escape_os_bytes(b) } } #[inline] pub fn escape_os_str(s: &OsStr) -> Cow<'_, OsStr> { #[cfg(unix)] { unix::escape_os_str(s) } #[cfg(windows)] { windows::escape_os_str(s) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/build.rs
yazi-fm/build.rs
use std::{env, error::Error}; fn main() -> Result<(), Box<dyn Error>> { let dir = env::var("OUT_DIR").unwrap(); // cargo build // C:\Users\Ika\Desktop\yazi\target\release\build\yazi-fm-cfc94820f71daa30\out // cargo install // C:\Users\Ika\AppData\Local\Temp\cargo-installTFU8cj\release\build\ // yazi-fm-45dffef2500eecd0\out if dir.contains(r"\release\build\yazi-fm-") { panic!( "Unwinding must be enabled for Windows. Please use `cargo build --profile release-windows --locked` instead to build Yazi." ); } let manifest = env::var_os("CARGO_MANIFEST_DIR").unwrap().to_string_lossy().replace(r"\", "/"); if env::var_os("YAZI_CRATE_BUILD").is_none() && (manifest.contains("/git/checkouts/yazi-") || manifest.contains("/registry/src/index.crates.io-")) { panic!( "Due to Cargo's limitations, the `yazi-fm` and `yazi-cli` crates on crates.io must be built with `cargo install --force yazi-build`" ); } Ok(()) }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/router.rs
yazi-fm/src/router.rs
use anyhow::Result; use yazi_config::{KEYMAP, keymap::{Chord, ChordCow, Key}}; use yazi_macro::emit; use yazi_shared::Layer; use crate::app::App; pub(super) struct Router<'a> { app: &'a mut App, } impl<'a> Router<'a> { pub(super) fn new(app: &'a mut App) -> Self { Self { app } } pub(super) fn route(&mut self, key: Key) -> Result<bool> { let core = &mut self.app.core; let layer = core.layer(); if core.help.visible && core.help.r#type(&key)? { return Ok(true); } if core.input.visible && core.input.r#type(&key)? { return Ok(true); } use Layer as L; Ok(match layer { L::App => unreachable!(), L::Mgr | L::Tasks | L::Spot | L::Pick | L::Input | L::Confirm | L::Help => { self.matches(layer, key) } L::Cmp => self.matches(L::Cmp, key) || self.matches(L::Input, key), L::Which => core.which.r#type(key), }) } fn matches(&mut self, layer: Layer, key: Key) -> bool { for chord @ Chord { on, .. } in KEYMAP.get(layer) { if on.is_empty() || on[0] != key { continue; } if on.len() > 1 { self.app.core.which.show_with(key, layer); } else { emit!(Seq(ChordCow::from(chord).into_seq())); } return true; } false } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/panic.rs
yazi-fm/src/panic.rs
use crate::Term; pub(super) struct Panic; impl Panic { pub(super) fn install() { better_panic::install(); let hook = std::panic::take_hook(); std::panic::set_hook(Box::new(move |info| { Term::goodbye(|| { hook(info); 1 }); })); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/root.rs
yazi-fm/src/root.rs
use mlua::{ObjectLike, Table}; use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget}; use tracing::error; use yazi_binding::elements::render_once; use yazi_core::Core; use yazi_plugin::LUA; use super::{cmp, confirm, help, input, mgr, pick, spot, tasks, which}; pub(super) struct Root<'a> { core: &'a Core, } impl<'a> Root<'a> { pub(super) fn new(core: &'a Core) -> Self { Self { core } } pub(super) fn reflow(area: Rect) -> mlua::Result<Table> { let area = yazi_binding::elements::Rect::from(area); let root = LUA.globals().raw_get::<Table>("Root")?.call_method::<Table>("new", area)?; root.call_method("reflow", ()) } } impl Widget for Root<'_> { fn render(self, area: Rect, buf: &mut Buffer) { let mut f = || { let area = yazi_binding::elements::Rect::from(area); let root = LUA.globals().raw_get::<Table>("Root")?.call_method::<Table>("new", area)?; render_once(root.call_method("redraw", ())?, buf, |p| self.core.mgr.area(p)); Ok::<_, mlua::Error>(()) }; if let Err(e) = f() { error!("Failed to redraw the `Root` component:\n{e}"); } mgr::Preview::new(self.core).render(area, buf); mgr::Modal::new(self.core).render(area, buf); if self.core.tasks.visible { tasks::Tasks::new(self.core).render(area, buf); } if self.core.active().spot.visible() { spot::Spot::new(self.core).render(area, buf); } if self.core.pick.visible { pick::Pick::new(self.core).render(area, buf); } if self.core.input.visible { input::Input::new(self.core).render(area, buf); } if self.core.confirm.visible { confirm::Confirm::new(self.core).render(area, buf); } if self.core.help.visible { help::Help::new(self.core).render(area, buf); } if self.core.cmp.visible { cmp::Cmp::new(self.core).render(area, buf); } if self.core.which.visible { which::Which::new(self.core).render(area, buf); } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/dispatcher.rs
yazi-fm/src/dispatcher.rs
use std::sync::atomic::Ordering; use anyhow::Result; use crossterm::event::KeyEvent; use tracing::warn; use yazi_config::keymap::Key; use yazi_macro::{act, emit, succ}; use yazi_shared::{data::Data, event::{CmdCow, Event, NEED_RENDER}}; use yazi_widgets::input::InputMode; use crate::{Executor, Router, app::App}; pub(super) struct Dispatcher<'a> { app: &'a mut App, } impl<'a> Dispatcher<'a> { #[inline] pub(super) fn new(app: &'a mut App) -> Self { Self { app } } #[inline] pub(super) fn dispatch(&mut self, event: Event) -> Result<()> { // FIXME: handle errors let result = match event { Event::Call(cmd) => self.dispatch_call(cmd), Event::Seq(cmds) => self.dispatch_seq(cmds), Event::Render => self.dispatch_render(), Event::Key(key) => self.dispatch_key(key), Event::Mouse(mouse) => act!(mouse, self.app, mouse), Event::Resize => act!(resize, self.app), Event::Paste(str) => self.dispatch_paste(str), Event::Quit(opt) => act!(quit, self.app, opt), }; if let Err(err) = result { warn!("Event dispatch error: {err:?}"); } Ok(()) } #[inline] fn dispatch_call(&mut self, cmd: CmdCow) -> Result<Data> { Executor::new(self.app).execute(cmd) } #[inline] fn dispatch_seq(&mut self, mut cmds: Vec<CmdCow>) -> Result<Data> { if let Some(last) = cmds.pop() { self.dispatch_call(last)?; } if !cmds.is_empty() { emit!(Seq(cmds)); } succ!(); } #[inline] fn dispatch_render(&mut self) -> Result<Data> { succ!(NEED_RENDER.store(true, Ordering::Relaxed)) } #[inline] fn dispatch_key(&mut self, key: KeyEvent) -> Result<Data> { Router::new(self.app).route(Key::from(key))?; succ!(); } #[inline] fn dispatch_paste(&mut self, str: String) -> Result<Data> { if self.app.core.input.visible { let input = &mut self.app.core.input; if input.mode() == InputMode::Insert { input.type_str(&str)?; } else if input.mode() == InputMode::Replace { input.replace_str(&str)?; } } succ!(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/executor.rs
yazi-fm/src/executor.rs
use anyhow::Result; use yazi_actor::Ctx; use yazi_macro::{act, succ}; use yazi_shared::{Layer, data::Data, event::CmdCow}; use yazi_widgets::input::InputMode; use crate::app::App; pub(super) struct Executor<'a> { app: &'a mut App, } impl<'a> Executor<'a> { #[inline] pub(super) fn new(app: &'a mut App) -> Self { Self { app } } #[inline] pub(super) fn execute(&mut self, cmd: CmdCow) -> Result<Data> { match cmd.layer { Layer::App => self.app(cmd), Layer::Mgr => self.mgr(cmd), Layer::Tasks => self.tasks(cmd), Layer::Spot => self.spot(cmd), Layer::Pick => self.pick(cmd), Layer::Input => self.input(cmd), Layer::Confirm => self.confirm(cmd), Layer::Help => self.help(cmd), Layer::Cmp => self.cmp(cmd), Layer::Which => self.which(cmd), } } fn app(&mut self, cmd: CmdCow) -> Result<Data> { macro_rules! on { ($name:ident) => { if cmd.name == stringify!($name) { return act!($name, self.app, cmd); } }; } on!(accept_payload); on!(notify); on!(plugin); on!(plugin_do); on!(update_notify); on!(update_progress); on!(resize); on!(stop); on!(resume); on!(deprecate); succ!(); } fn mgr(&mut self, cmd: CmdCow) -> Result<Data> { let cx = &mut Ctx::new(&mut self.app.core, &cmd)?; macro_rules! on { ($name:ident) => { if cmd.name == stringify!($name) { return act!(mgr:$name, cx, cmd) } }; } on!(cd); on!(update_yanked); on!(update_files); on!(update_mimes); on!(update_paged); on!(watch); on!(peek); on!(seek); on!(spot); on!(refresh); on!(quit); on!(close); on!(suspend); on!(escape); on!(update_peeked); on!(update_spotted); // Navigation on!(arrow); on!(leave); on!(enter); on!(back); on!(forward); on!(reveal); on!(follow); // Toggle on!(toggle); on!(toggle_all); on!(visual_mode); // Operation on!(open); on!(open_do); on!(yank); on!(unyank); on!(paste); on!(link); on!(hardlink); on!(remove); on!(remove_do); on!(create); on!(rename); on!(copy); on!(shell); on!(hidden); on!(linemode); on!(search); on!(search_do); on!(bulk_rename); // Filter on!(filter); on!(filter_do); // Find on!(find); on!(find_do); on!(find_arrow); // Sorting on!(sort); // Tabs on!(tab_create); on!(tab_close); on!(tab_switch); on!(tab_swap); // VFS on!(download); on!(upload); on!(displace_do); match cmd.name.as_ref() { // Help "help" => act!(help:toggle, cx, Layer::Mgr), // Plugin "plugin" => act!(plugin, self.app, cmd), _ => succ!(), } } fn tasks(&mut self, cmd: CmdCow) -> Result<Data> { let cx = &mut Ctx::new(&mut self.app.core, &cmd)?; macro_rules! on { ($name:ident) => { if cmd.name == stringify!($name) { return act!(tasks:$name, cx, cmd); } }; } on!(update_succeed); on!(show); on!(close); on!(arrow); on!(inspect); on!(cancel); on!(process_open); on!(open_shell_compat); match cmd.name.as_ref() { // Help "help" => act!(help:toggle, cx, Layer::Tasks), // Plugin "plugin" => act!(plugin, self.app, cmd), _ => succ!(), } } fn spot(&mut self, cmd: CmdCow) -> Result<Data> { let cx = &mut Ctx::new(&mut self.app.core, &cmd)?; macro_rules! on { ($name:ident) => { if cmd.name == stringify!($name) { return act!(spot:$name, cx, cmd); } }; } on!(arrow); on!(close); on!(swipe); on!(copy); match cmd.name.as_ref() { // Help "help" => act!(help:toggle, cx, Layer::Spot), // Plugin "plugin" => act!(plugin, self.app, cmd), _ => succ!(), } } fn pick(&mut self, cmd: CmdCow) -> Result<Data> { let cx = &mut Ctx::new(&mut self.app.core, &cmd)?; macro_rules! on { ($name:ident) => { if cmd.name == stringify!($name) { return act!(pick:$name, cx, cmd); } }; } on!(show); on!(close); on!(arrow); match cmd.name.as_ref() { // Help "help" => act!(help:toggle, cx, Layer::Pick), // Plugin "plugin" => act!(plugin, self.app, cmd), _ => succ!(), } } fn input(&mut self, cmd: CmdCow) -> Result<Data> { let mode = self.app.core.input.mode(); let cx = &mut Ctx::new(&mut self.app.core, &cmd)?; macro_rules! on { ($name:ident) => { if cmd.name == stringify!($name) { return act!(input:$name, cx, cmd); } }; } on!(escape); on!(show); on!(close); match mode { InputMode::Normal => { match cmd.name.as_ref() { // Help "help" => return act!(help:toggle, cx, Layer::Input), // Plugin "plugin" => return act!(plugin, self.app, cmd), _ => {} } } InputMode::Insert => { on!(complete); } InputMode::Replace => {} }; self.app.core.input.execute(cmd) } fn confirm(&mut self, cmd: CmdCow) -> Result<Data> { let cx = &mut Ctx::new(&mut self.app.core, &cmd)?; macro_rules! on { ($name:ident) => { if cmd.name == stringify!($name) { return act!(confirm:$name, cx, cmd); } }; } on!(arrow); on!(show); on!(close); succ!(); } fn help(&mut self, cmd: CmdCow) -> Result<Data> { let cx = &mut Ctx::new(&mut self.app.core, &cmd)?; macro_rules! on { ($name:ident) => { if cmd.name == stringify!($name) { return act!(help:$name, cx, cmd); } }; } on!(escape); on!(arrow); on!(filter); match cmd.name.as_ref() { // Help "close" => act!(help:toggle, cx, Layer::Help), // Plugin "plugin" => act!(plugin, self.app, cmd), _ => succ!(), } } fn cmp(&mut self, cmd: CmdCow) -> Result<Data> { let cx = &mut Ctx::new(&mut self.app.core, &cmd)?; macro_rules! on { ($name:ident) => { if cmd.name == stringify!($name) { return act!(cmp:$name, cx, cmd); } }; } on!(trigger); on!(show); on!(close); on!(arrow); match cmd.name.as_ref() { // Help "help" => act!(help:toggle, cx, Layer::Cmp), // Plugin "plugin" => act!(plugin, self.app, cmd), _ => succ!(), } } fn which(&mut self, cmd: CmdCow) -> Result<Data> { let cx = &mut Ctx::new(&mut self.app.core, &cmd)?; macro_rules! on { ($name:ident) => { if cmd.name == stringify!($name) { return act!(which:$name, cx, cmd); } }; } on!(show); on!(callback); succ!(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/main.rs
yazi-fm/src/main.rs
#[cfg(all(not(target_os = "macos"), not(target_os = "windows")))] #[global_allocator] static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc; yazi_macro::mod_pub!(app cmp confirm help input mgr notify pick spot tasks which); yazi_macro::mod_flat!(dispatcher executor logs panic root router signals term); #[tokio::main] async fn main() -> anyhow::Result<()> { Panic::install(); yazi_shared::init(); Logs::start()?; _ = fdlimit::raise_fd_limit(); yazi_term::init(); yazi_fs::init(); yazi_config::init()?; yazi_vfs::init(); yazi_adapter::init()?; yazi_boot::init(); yazi_proxy::init(); yazi_dds::init(); yazi_widgets::init(); yazi_watcher::init(); yazi_plugin::init()?; yazi_dds::serve(); yazi_shared::LOCAL_SET.run_until(app::App::serve()).await }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/logs.rs
yazi-fm/src/logs.rs
use std::fs::File; use anyhow::Context; use crossterm::style::{Color, Print, ResetColor, SetForegroundColor}; use tracing_appender::non_blocking::WorkerGuard; use tracing_subscriber::EnvFilter; use yazi_fs::Xdg; use yazi_shared::{LOG_LEVEL, RoCell}; static _GUARD: RoCell<WorkerGuard> = RoCell::new(); pub(super) struct Logs; impl Logs { pub(super) fn start() -> anyhow::Result<()> { let level = LOG_LEVEL.get(); if level.is_none() { return Ok(()); } let state_dir = Xdg::state_dir(); std::fs::create_dir_all(&state_dir) .with_context(|| format!("failed to create state directory: {state_dir:?}"))?; let log_path = state_dir.join("yazi.log"); let log_file = File::create(&log_path) .with_context(|| format!("failed to create log file: {log_path:?}"))?; let (non_blocking, guard) = tracing_appender::non_blocking(log_file); tracing_subscriber::fmt() .pretty() .with_env_filter(EnvFilter::new(level)) .with_writer(non_blocking) .with_ansi(cfg!(debug_assertions)) .init(); _GUARD.init(guard); Ok(crossterm::execute!( std::io::stderr(), SetForegroundColor(Color::Yellow), Print(format!("Running with log level `{level}`, logs are written to {log_path:?}\n")), ResetColor )?) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/term.rs
yazi-fm/src/term.rs
use std::{io, ops::{Deref, DerefMut}, sync::atomic::{AtomicBool, Ordering}}; use anyhow::Result; use crossterm::{event::{DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, EnableMouseCapture, KeyboardEnhancementFlags, PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags}, execute, queue, style::Print, terminal::{EnterAlternateScreen, LeaveAlternateScreen, SetTitle, disable_raw_mode, enable_raw_mode}}; use ratatui::{CompletedFrame, Frame, Terminal, backend::CrosstermBackend, buffer::Buffer, layout::Rect}; use yazi_adapter::{Emulator, Mux, TMUX}; use yazi_config::{THEME, YAZI}; use yazi_shared::SyncCell; use yazi_term::tty::{TTY, TtyWriter}; static CSI_U: AtomicBool = AtomicBool::new(false); pub(super) struct Term { inner: Terminal<CrosstermBackend<TtyWriter<'static>>>, last_area: Rect, last_buffer: Buffer, } impl Term { pub(super) fn start() -> Result<Self> { let mut term = Self { inner: Terminal::new(CrosstermBackend::new(TTY.writer()))?, last_area: Default::default(), last_buffer: Default::default(), }; enable_raw_mode()?; static FIRST: SyncCell<bool> = SyncCell::new(false); if FIRST.replace(true) && yazi_adapter::TMUX.get() { yazi_adapter::Mux::tmux_passthrough(); } execute!( TTY.writer(), yazi_term::If(!TMUX.get(), EnterAlternateScreen), Print("\x1bP$q q\x1b\\"), // Request cursor shape (DECRQSS query for DECSCUSR) Print("\x1b[?12$p"), // Request cursor blink status (DECRQM query for DECSET 12) Print("\x1b[?u"), // Request keyboard enhancement flags (CSI u) Print("\x1b[0c"), // Request device attributes yazi_term::If(TMUX.get(), EnterAlternateScreen), yazi_term::SetBackground(true, THEME.app.bg_color()), // Set app background EnableBracketedPaste, yazi_term::If(!YAZI.mgr.mouse_events.get().is_empty(), EnableMouseCapture), )?; let resp = Emulator::read_until_da1(); Mux::tmux_drain()?; yazi_term::RestoreCursor::store(&resp); CSI_U.store(resp.contains("\x1b[?0u"), Ordering::Relaxed); if CSI_U.load(Ordering::Relaxed) { _ = queue!( TTY.writer(), PushKeyboardEnhancementFlags( KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES | KeyboardEnhancementFlags::REPORT_ALTERNATE_KEYS, ) ); } if let Some(s) = YAZI.mgr.title() { queue!(TTY.writer(), SetTitle(s)).ok(); } term.hide_cursor()?; term.clear()?; term.flush()?; Ok(term) } fn stop(&mut self) -> Result<()> { if CSI_U.swap(false, Ordering::Relaxed) { queue!(TTY.writer(), PopKeyboardEnhancementFlags).ok(); } if !YAZI.mgr.title_format.is_empty() { queue!(TTY.writer(), SetTitle("")).ok(); } execute!( TTY.writer(), yazi_term::If(!YAZI.mgr.mouse_events.get().is_empty(), DisableMouseCapture), yazi_term::RestoreCursor, DisableBracketedPaste, LeaveAlternateScreen, )?; self.show_cursor()?; Ok(disable_raw_mode()?) } pub(super) fn goodbye(f: impl FnOnce() -> i32) -> ! { if CSI_U.swap(false, Ordering::Relaxed) { queue!(TTY.writer(), PopKeyboardEnhancementFlags).ok(); } if !YAZI.mgr.title_format.is_empty() { queue!(TTY.writer(), SetTitle("")).ok(); } execute!( TTY.writer(), yazi_term::If(!YAZI.mgr.mouse_events.get().is_empty(), DisableMouseCapture), yazi_term::SetBackground(false, THEME.app.bg_color()), yazi_term::RestoreCursor, DisableBracketedPaste, LeaveAlternateScreen, crossterm::cursor::Show ) .ok(); disable_raw_mode().ok(); std::process::exit(f()); } pub(super) fn draw(&mut self, f: impl FnOnce(&mut Frame)) -> io::Result<CompletedFrame<'_>> { let last = self.inner.draw(f)?; self.last_area = last.area; self.last_buffer = last.buffer.clone(); Ok(last) } pub(super) fn draw_partial( &mut self, f: impl FnOnce(&mut Frame), ) -> io::Result<CompletedFrame<'_>> { self.inner.draw(|frame| { let buffer = frame.buffer_mut(); for y in self.last_area.top()..self.last_area.bottom() { for x in self.last_area.left()..self.last_area.right() { let mut cell = self.last_buffer[(x, y)].clone(); cell.skip = false; buffer[(x, y)] = cell; } } f(frame); }) } pub(super) fn can_partial(&mut self) -> bool { self.inner.autoresize().is_ok() && self.last_area == self.inner.get_frame().area() } } impl Drop for Term { fn drop(&mut self) { self.stop().ok(); } } impl Deref for Term { type Target = Terminal<CrosstermBackend<TtyWriter<'static>>>; fn deref(&self) -> &Self::Target { &self.inner } } impl DerefMut for Term { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/signals.rs
yazi-fm/src/signals.rs
use anyhow::Result; use crossterm::event::{Event as CrosstermEvent, EventStream, KeyEvent, KeyEventKind}; use futures::StreamExt; use tokio::{select, sync::{mpsc, oneshot}}; use yazi_config::YAZI; use yazi_shared::event::Event; pub(super) struct Signals { tx: mpsc::UnboundedSender<(bool, Option<oneshot::Sender<()>>)>, } impl Signals { pub(super) fn start() -> Result<Self> { let (tx, rx) = mpsc::unbounded_channel(); Self::spawn(rx)?; Ok(Self { tx }) } pub(super) fn stop(&mut self, cb: Option<oneshot::Sender<()>>) { self.tx.send((false, cb)).ok(); } pub(super) fn resume(&mut self, cb: Option<oneshot::Sender<()>>) { self.tx.send((true, cb)).ok(); } #[cfg(unix)] fn handle_sys(n: libc::c_int) -> bool { use libc::{SIGCONT, SIGHUP, SIGINT, SIGQUIT, SIGSTOP, SIGTERM, SIGTSTP}; use tracing::error; use yazi_proxy::{AppProxy, HIDER}; match n { SIGINT => { /* ignored */ } SIGQUIT | SIGHUP | SIGTERM => { Event::Quit(Default::default()).emit(); return false; } SIGTSTP => { tokio::spawn(async move { AppProxy::stop().await; if unsafe { libc::kill(0, SIGSTOP) } != 0 { error!("Failed to stop the process:\n{}", std::io::Error::last_os_error()); Event::Quit(Default::default()).emit(); } }); } SIGCONT if HIDER.try_acquire().is_ok() => _ = tokio::spawn(AppProxy::resume()), _ => {} } true } #[cfg(windows)] #[inline] fn handle_sys(_: ()) -> bool { unreachable!() } fn handle_term(event: CrosstermEvent) { match event { CrosstermEvent::Key(key @ KeyEvent { kind: KeyEventKind::Press, .. }) => { Event::Key(key).emit() } CrosstermEvent::Mouse(mouse) => { if YAZI.mgr.mouse_events.get().contains(mouse.kind.into()) { Event::Mouse(mouse).emit(); } } CrosstermEvent::Paste(str) => Event::Paste(str).emit(), CrosstermEvent::Resize(..) => Event::Resize.emit(), _ => {} } } fn spawn(mut rx: mpsc::UnboundedReceiver<(bool, Option<oneshot::Sender<()>>)>) -> Result<()> { #[cfg(unix)] use libc::{SIGCONT, SIGHUP, SIGINT, SIGQUIT, SIGTERM, SIGTSTP}; #[cfg(unix)] let mut sys = signal_hook_tokio::Signals::new([ // Interrupt signals (Ctrl-C, Ctrl-\) SIGINT, SIGQUIT, // // Hangup signal (Terminal closed) SIGHUP, // // Termination signal (kill) SIGTERM, // // Job control signals (Ctrl-Z, fg/bg) SIGTSTP, SIGCONT, ])?; #[cfg(windows)] let mut sys = tokio_stream::empty(); let mut term = Some(EventStream::new()); tokio::spawn(async move { loop { if let Some(t) = &mut term { select! { biased; Some((state, mut callback)) = rx.recv() => { term = term.filter(|_| state); callback.take().map(|cb| cb.send(())); }, Some(n) = sys.next() => if !Self::handle_sys(n) { return }, Some(Ok(e)) = t.next() => Self::handle_term(e) } } else { select! { biased; Some((state, mut callback)) = rx.recv() => { term = state.then(EventStream::new); callback.take().map(|cb| cb.send(())); }, Some(n) = sys.next() => if !Self::handle_sys(n) { return }, } } } }); Ok(()) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/tasks/tasks.rs
yazi-fm/src/tasks/tasks.rs
use ratatui::{buffer::Buffer, layout::{self, Alignment, Constraint, Rect}, text::Line, widgets::{Block, BorderType, Widget}}; use yazi_config::THEME; use yazi_core::{Core, tasks::TASKS_PERCENT}; use crate::tasks::List; pub(crate) struct Tasks<'a> { core: &'a Core, } impl<'a> Tasks<'a> { pub(crate) fn new(core: &'a Core) -> Self { Self { core } } pub(super) fn area(area: Rect) -> Rect { let chunk = layout::Layout::vertical([ Constraint::Percentage((100 - TASKS_PERCENT) / 2), Constraint::Percentage(TASKS_PERCENT), Constraint::Percentage((100 - TASKS_PERCENT) / 2), ]) .split(area)[1]; layout::Layout::horizontal([ Constraint::Percentage((100 - TASKS_PERCENT) / 2), Constraint::Percentage(TASKS_PERCENT), Constraint::Percentage((100 - TASKS_PERCENT) / 2), ]) .split(chunk)[1] } } impl Widget for Tasks<'_> { fn render(self, area: Rect, buf: &mut Buffer) { let area = Self::area(area); yazi_binding::elements::Clear::default().render(area, buf); let block = Block::bordered() .title(Line::styled("Tasks", THEME.tasks.title)) .title_alignment(Alignment::Center) .border_type(BorderType::Rounded) .border_style(THEME.tasks.border); (&block).render(area, buf); List::new(self.core).render(block.inner(area), buf); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/tasks/list.rs
yazi-fm/src/tasks/list.rs
use mlua::{ObjectLike, Table}; use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget}; use tracing::error; use yazi_binding::elements::render_once; use yazi_core::Core; use yazi_plugin::LUA; pub(crate) struct List<'a> { core: &'a Core, } impl<'a> List<'a> { #[inline] pub(crate) fn new(core: &'a Core) -> Self { Self { core } } } impl Widget for List<'_> { fn render(self, area: Rect, buf: &mut Buffer) { let mut f = || { let area = yazi_binding::elements::Rect::from(area); let root = LUA.globals().raw_get::<Table>("Tasks")?.call_method::<Table>("new", area)?; render_once(root.call_method("redraw", ())?, buf, |p| self.core.mgr.area(p)); Ok::<_, mlua::Error>(()) }; if let Err(e) = f() { error!("Failed to redraw the `Tasks` component:\n{e}"); } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/tasks/progress.rs
yazi-fm/src/tasks/progress.rs
use mlua::{ObjectLike, Table}; use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget}; use tracing::error; use yazi_binding::elements::render_once; use yazi_config::LAYOUT; use yazi_core::Core; use yazi_plugin::LUA; pub(crate) struct Progress<'a> { core: &'a Core, } impl<'a> Progress<'a> { pub(crate) fn new(core: &'a Core) -> Self { Self { core } } } impl Widget for Progress<'_> { fn render(self, _: Rect, buf: &mut Buffer) { let mut f = || { let area = yazi_binding::elements::Rect::from(LAYOUT.get().progress); let progress = LUA.globals().raw_get::<Table>("Progress")?.call_method::<Table>("use", area)?; render_once(progress.call_method("redraw", ())?, buf, |p| self.core.mgr.area(p)); Ok::<_, mlua::Error>(()) }; if let Err(e) = f() { error!("Failed to redraw the `Progress` component:\n{e}"); } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/tasks/mod.rs
yazi-fm/src/tasks/mod.rs
yazi_macro::mod_flat!(list progress tasks);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/app/app.rs
yazi-fm/src/app/app.rs
use std::{sync::atomic::Ordering, time::{Duration, Instant}}; use anyhow::Result; use tokio::{select, time::sleep}; use yazi_core::Core; use yazi_macro::act; use yazi_shared::event::{Event, NEED_RENDER}; use crate::{Dispatcher, Signals, Term}; pub(crate) struct App { pub(crate) core: Core, pub(crate) term: Option<Term>, pub(crate) signals: Signals, } impl App { pub(crate) async fn serve() -> Result<()> { let term = Term::start()?; let (mut rx, signals) = (Event::take(), Signals::start()?); let mut app = Self { core: Core::make(), term: Some(term), signals }; act!(bootstrap, app)?; let mut events = Vec::with_capacity(50); let (mut timeout, mut last_render) = (None, Instant::now()); macro_rules! drain_events { () => { for event in events.drain(..) { Dispatcher::new(&mut app).dispatch(event)?; if !NEED_RENDER.load(Ordering::Relaxed) { continue; } timeout = Duration::from_millis(10).checked_sub(last_render.elapsed()); if timeout.is_none() { act!(render, app)?; last_render = Instant::now(); } } }; } loop { if let Some(t) = timeout.take() { select! { _ = sleep(t) => { act!(render, app)?; last_render = Instant::now(); } n = rx.recv_many(&mut events, 50) => { if n == 0 { break } drain_events!(); } } } else if rx.recv_many(&mut events, 50).await != 0 { drain_events!(); } else { break; } } Ok(()) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/app/mod.rs
yazi-fm/src/app/mod.rs
yazi_macro::mod_pub!(commands); yazi_macro::mod_flat!(app);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/app/commands/notify.rs
yazi-fm/src/app/commands/notify.rs
use anyhow::Result; use yazi_macro::succ; use yazi_parser::app::NotifyOpt; use yazi_shared::data::Data; use crate::app::App; impl App { pub(crate) fn notify(&mut self, opt: NotifyOpt) -> Result<Data> { succ!(self.core.notify.push(opt)); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/app/commands/update_progress.rs
yazi-fm/src/app/commands/update_progress.rs
use anyhow::Result; use yazi_actor::Ctx; use yazi_macro::{act, render, succ}; use yazi_parser::app::UpdateProgressOpt; use yazi_shared::data::Data; use crate::app::App; impl App { pub(crate) fn update_progress(&mut self, opt: UpdateProgressOpt) -> Result<Data> { // Update the progress of all tasks. let tasks = &mut self.core.tasks; let progressed = tasks.summary != opt.summary; tasks.summary = opt.summary; // If the task manager is visible, update the snaps with a full render. if tasks.visible { let new = tasks.paginate(); if tasks.snaps != new { tasks.snaps = new; let cx = &mut Ctx::active(&mut self.core); act!(tasks:arrow, cx)?; succ!(render!()); } } if !progressed { succ!() } else if tasks.summary.total == 0 { succ!(render!()) } else { act!(render_partially, self) } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/app/commands/mouse.rs
yazi-fm/src/app/commands/mouse.rs
use anyhow::Result; use crossterm::event::MouseEventKind; use mlua::{ObjectLike, Table}; use tracing::error; use yazi_actor::lives::Lives; use yazi_config::YAZI; use yazi_macro::succ; use yazi_parser::app::MouseOpt; use yazi_plugin::LUA; use yazi_shared::data::Data; use crate::app::App; impl App { pub fn mouse(&mut self, opt: MouseOpt) -> Result<Data> { let event = yazi_plugin::bindings::MouseEvent::from(opt.event); let Some(size) = self.term.as_ref().and_then(|t| t.size().ok()) else { succ!() }; let result = Lives::scope(&self.core, move || { let area = yazi_binding::elements::Rect::from(size); let root = LUA.globals().raw_get::<Table>("Root")?.call_method::<Table>("new", area)?; if matches!(event.kind, MouseEventKind::Down(_) if YAZI.mgr.mouse_events.get().draggable()) { root.raw_set("_drag_start", event)?; } match event.kind { MouseEventKind::Down(_) => root.call_method("click", (event, false))?, MouseEventKind::Up(_) => root.call_method("click", (event, true))?, MouseEventKind::ScrollDown => root.call_method("scroll", (event, 1))?, MouseEventKind::ScrollUp => root.call_method("scroll", (event, -1))?, MouseEventKind::ScrollRight => root.call_method("touch", (event, 1))?, MouseEventKind::ScrollLeft => root.call_method("touch", (event, -1))?, MouseEventKind::Moved => root.call_method("move", event)?, MouseEventKind::Drag(_) => root.call_method("drag", event)?, } Ok(()) }); if let Err(ref e) = result { error!("{e}"); } succ!(result?); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/app/commands/deprecate.rs
yazi-fm/src/app/commands/deprecate.rs
use anyhow::Result; use yazi_macro::succ; use yazi_parser::app::{DeprecateOpt, NotifyLevel, NotifyOpt}; use yazi_shared::data::Data; use crate::app::App; impl App { pub(crate) fn deprecate(&mut self, opt: DeprecateOpt) -> Result<Data> { succ!(self.core.notify.push(NotifyOpt { title: "Deprecated API".to_owned(), content: opt.content.into_owned(), level: NotifyLevel::Warn, timeout: std::time::Duration::from_secs(20), })); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/app/commands/reflow.rs
yazi-fm/src/app/commands/reflow.rs
use anyhow::Result; use mlua::Value; use ratatui::layout::Position; use tracing::error; use yazi_actor::lives::Lives; use yazi_config::LAYOUT; use yazi_macro::{render, succ}; use yazi_parser::VoidOpt; use yazi_shared::data::Data; use crate::{Root, app::App}; impl App { pub fn reflow(&mut self, _: VoidOpt) -> Result<Data> { let Some(size) = self.term.as_ref().and_then(|t| t.size().ok()) else { succ!() }; let mut layout = LAYOUT.get(); let result = Lives::scope(&self.core, || { let comps = Root::reflow((Position::ORIGIN, size).into())?; for v in comps.sequence_values::<Value>() { let Value::Table(t) = v? else { error!("`reflow()` must return a table of components"); continue; }; let id: mlua::String = t.get("_id")?; match &*id.as_bytes() { b"current" => layout.current = *t.raw_get::<yazi_binding::elements::Rect>("_area")?, b"preview" => layout.preview = *t.raw_get::<yazi_binding::elements::Rect>("_area")?, b"progress" => layout.progress = *t.raw_get::<yazi_binding::elements::Rect>("_area")?, _ => {} } } Ok(()) }); if layout != LAYOUT.get() { LAYOUT.set(layout); render!(); } if let Err(ref e) = result { error!("Failed to `reflow()` the `Root` component:\n{e}"); } succ!(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/app/commands/quit.rs
yazi-fm/src/app/commands/quit.rs
use yazi_boot::ARGS; use yazi_fs::provider::{Provider, local::Local}; use yazi_shared::{event::EventQuit, strand::{StrandBuf, StrandLike, ToStrand}}; use crate::{Term, app::App}; impl App { pub(crate) fn quit(&mut self, opt: EventQuit) -> ! { self.core.tasks.shutdown(); self.core.mgr.shutdown(); futures::executor::block_on(async { _ = futures::join!( yazi_dds::shutdown(), yazi_dds::STATE.drain(), self.cwd_to_file(opt.no_cwd_file), self.selected_to_file(opt.selected) ); }); Term::goodbye(|| opt.code); } async fn cwd_to_file(&self, no: bool) { if let Some(p) = ARGS.cwd_file.as_ref().filter(|_| !no) { let cwd = self.core.mgr.cwd().to_strand(); Local::regular(p).write(cwd.encoded_bytes()).await.ok(); } } async fn selected_to_file(&self, selected: Option<StrandBuf>) { if let (Some(s), Some(p)) = (selected, &ARGS.chooser_file) { Local::regular(p).write(s.encoded_bytes()).await.ok(); } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/app/commands/render.rs
yazi-fm/src/app/commands/render.rs
use std::sync::atomic::{AtomicU8, Ordering}; use anyhow::Result; use crossterm::{cursor::{MoveTo, SetCursorStyle, Show}, execute, queue, terminal::{BeginSynchronizedUpdate, EndSynchronizedUpdate}}; use ratatui::{CompletedFrame, backend::{Backend, CrosstermBackend}, buffer::Buffer, layout::Position}; use yazi_actor::{Ctx, lives::Lives}; use yazi_binding::elements::COLLISION; use yazi_macro::{act, succ}; use yazi_parser::VoidOpt; use yazi_shared::{data::Data, event::NEED_RENDER}; use yazi_term::tty::TTY; use crate::{app::App, root::Root}; impl App { pub(crate) fn render(&mut self, _: VoidOpt) -> Result<Data> { NEED_RENDER.store(false, Ordering::Relaxed); let Some(term) = &mut self.term else { succ!() }; Self::routine(true, None); let _guard = scopeguard::guard(self.core.cursor(), |c| Self::routine(false, c)); let collision = COLLISION.swap(false, Ordering::Relaxed); let frame = term .draw(|f| { _ = Lives::scope(&self.core, || Ok(f.render_widget(Root::new(&self.core), f.area()))); }) .unwrap(); if COLLISION.load(Ordering::Relaxed) { Self::patch(frame); } if !self.core.notify.messages.is_empty() { act!(render_partially, self)?; } // Reload preview if collision is resolved if collision && !COLLISION.load(Ordering::Relaxed) { let cx = &mut Ctx::active(&mut self.core); act!(mgr:peek, cx, true)?; } succ!(); } pub(crate) fn render_partially(&mut self, _: VoidOpt) -> Result<Data> { let Some(term) = &mut self.term else { succ!() }; if !term.can_partial() { return act!(render, self); } Self::routine(true, None); let _guard = scopeguard::guard(self.core.cursor(), |c| Self::routine(false, c)); let frame = term .draw_partial(|f| { _ = Lives::scope(&self.core, || { f.render_widget(crate::tasks::Progress::new(&self.core), f.area()); f.render_widget(crate::notify::Notify::new(&self.core), f.area()); Ok(()) }); }) .unwrap(); if COLLISION.load(Ordering::Relaxed) { Self::patch(frame); } succ!(); } #[inline] fn patch(frame: CompletedFrame) { let mut new = Buffer::empty(frame.area); for y in new.area.top()..new.area.bottom() { for x in new.area.left()..new.area.right() { let cell = &frame.buffer[(x, y)]; if cell.skip { new[(x, y)] = cell.clone(); } new[(x, y)].set_skip(!cell.skip); } } let patches = frame.buffer.diff(&new); CrosstermBackend::new(&mut *TTY.lockout()).draw(patches.into_iter()).ok(); } fn routine(push: bool, cursor: Option<(Position, SetCursorStyle)>) { static COUNT: AtomicU8 = AtomicU8::new(0); if push && COUNT.fetch_add(1, Ordering::Relaxed) != 0 { return; } else if !push && COUNT.fetch_sub(1, Ordering::Relaxed) != 1 { return; } _ = if push { queue!(TTY.writer(), BeginSynchronizedUpdate) } else if let Some((Position { x, y }, shape)) = cursor { execute!(TTY.writer(), shape, MoveTo(x, y), Show, EndSynchronizedUpdate) } else { execute!(TTY.writer(), EndSynchronizedUpdate) }; } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/app/commands/mod.rs
yazi-fm/src/app/commands/mod.rs
yazi_macro::mod_flat!( accept_payload bootstrap deprecate mouse notify plugin quit reflow render resize resume stop update_notify update_progress );
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/app/commands/accept_payload.rs
yazi-fm/src/app/commands/accept_payload.rs
use anyhow::{Result, bail}; use mlua::IntoLua; use tracing::error; use yazi_actor::lives::Lives; use yazi_binding::runtime_mut; use yazi_dds::{LOCAL, Payload, REMOTE}; use yazi_macro::succ; use yazi_plugin::LUA; use yazi_shared::{data::Data, event::CmdCow}; use crate::app::App; impl App { pub(crate) fn accept_payload(&self, mut c: CmdCow) -> Result<Data> { let Some(payload) = c.take_any2::<Payload>("payload").transpose()? else { bail!("'payload' is required for accept_payload"); }; let kind = payload.body.kind().to_owned(); let lock = if payload.receiver == 0 || payload.receiver != payload.sender { REMOTE.read() } else { LOCAL.read() }; let Some(handlers) = lock.get(&kind).filter(|&m| !m.is_empty()).cloned() else { succ!() }; drop(lock); succ!(Lives::scope(&self.core, || { let body = payload.body.into_lua(&LUA)?; for (id, cb) in handlers { runtime_mut!(LUA)?.push(&id); if let Err(e) = cb.call::<()>(body.clone()) { error!("Failed to run `{kind}` event handler in your `{id}` plugin: {e}"); } runtime_mut!(LUA)?.pop(); } Ok(()) })?); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/app/commands/update_notify.rs
yazi-fm/src/app/commands/update_notify.rs
use anyhow::Result; use ratatui::layout::Rect; use yazi_adapter::Dimension; use yazi_macro::act; use yazi_parser::notify::TickOpt; use yazi_shared::data::Data; use crate::{app::App, notify}; impl App { pub(crate) fn update_notify(&mut self, opt: TickOpt) -> Result<Data> { let Dimension { rows, columns, .. } = Dimension::available(); let area = notify::Notify::available(Rect { x: 0, y: 0, width: columns, height: rows }); self.core.notify.tick(opt, area); if self.core.notify.messages.is_empty() { act!(render, self) } else { act!(render_partially, self) } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/app/commands/bootstrap.rs
yazi-fm/src/app/commands/bootstrap.rs
use anyhow::Result; use yazi_actor::Ctx; use yazi_boot::BOOT; use yazi_macro::act; use yazi_parser::{VoidOpt, mgr::CdSource}; use yazi_shared::{data::Data, strand::StrandLike, url::UrlLike}; use crate::app::App; impl App { pub fn bootstrap(&mut self, _: VoidOpt) -> Result<Data> { for (i, file) in BOOT.files.iter().enumerate() { let tabs = &mut self.core.mgr.tabs; if tabs.len() <= i { tabs.push(Default::default()); } let cx = &mut Ctx::active(&mut self.core); cx.tab = i; if file.is_empty() { act!(mgr:cd, cx, (BOOT.cwds[i].clone(), CdSource::Tab))?; } else if let Ok(u) = BOOT.cwds[i].try_join(file) { act!(mgr:reveal, cx, (u, CdSource::Tab))?; } } act!(render, self) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/app/commands/resume.rs
yazi-fm/src/app/commands/resume.rs
use anyhow::Result; use yazi_macro::{act, render, succ}; use yazi_parser::VoidOpt; use yazi_shared::data::Data; use crate::{Term, app::App}; impl App { pub(crate) fn resume(&mut self, _: VoidOpt) -> Result<Data> { self.core.active_mut().preview.reset(); self.term = Some(Term::start().unwrap()); // While the app resumes, it's possible that the terminal size has changed. // We need to trigger a resize, and render the UI based on the resized area. act!(resize, self)?; self.signals.resume(None); succ!(render!()); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/app/commands/resize.rs
yazi-fm/src/app/commands/resize.rs
use anyhow::Result; use yazi_actor::Ctx; use yazi_macro::act; use yazi_parser::VoidOpt; use yazi_shared::data::Data; use crate::app::App; impl App { pub fn resize(&mut self, _: VoidOpt) -> Result<Data> { act!(reflow, self)?; self.core.current_mut().arrow(0); self.core.parent_mut().map(|f| f.arrow(0)); self.core.current_mut().sync_page(true); let cx = &mut Ctx::active(&mut self.core); act!(mgr:peek, cx) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/app/commands/stop.rs
yazi-fm/src/app/commands/stop.rs
use anyhow::Result; use yazi_macro::succ; use yazi_parser::app::StopOpt; use yazi_shared::data::Data; use crate::app::App; impl App { pub fn stop(&mut self, opt: StopOpt) -> Result<Data> { self.core.active_mut().preview.reset_image(); // We need to destroy the `term` first before stopping the `signals` // to prevent any signal from triggering the term to render again // while the app is being suspended. self.term = None; self.signals.stop(opt.tx); succ!(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/app/commands/plugin.rs
yazi-fm/src/app/commands/plugin.rs
use anyhow::Result; use mlua::ObjectLike; use scopeguard::defer; use tracing::{error, warn}; use yazi_actor::lives::Lives; use yazi_binding::runtime_mut; use yazi_dds::Sendable; use yazi_macro::succ; use yazi_parser::app::{PluginMode, PluginOpt}; use yazi_plugin::{LUA, loader::{LOADER, Loader}}; use yazi_proxy::AppProxy; use yazi_shared::data::Data; use crate::app::App; impl App { pub(crate) fn plugin(&mut self, mut opt: PluginOpt) -> Result<Data> { let mut hits = false; if let Some(chunk) = LOADER.read().get(&*opt.id) { hits = true; opt.mode = opt.mode.auto_then(chunk.sync_entry); } if opt.mode == PluginMode::Async { succ!(self.core.tasks.plugin_entry(opt)); } else if opt.mode == PluginMode::Sync && hits { return self.plugin_do(opt); } tokio::spawn(async move { match LOADER.ensure(&opt.id, |_| ()).await { Ok(()) => AppProxy::plugin_do(opt), Err(e) => AppProxy::notify_error("Plugin load failed", e), } }); succ!(); } pub(crate) fn plugin_do(&mut self, opt: PluginOpt) -> Result<Data> { let loader = LOADER.read(); let Some(chunk) = loader.get(&*opt.id) else { succ!(warn!("plugin `{}` not found", opt.id)); }; if let Err(e) = Loader::compatible_or_error(&opt.id, chunk) { succ!(AppProxy::notify_error("Incompatible plugin", e)); } if opt.mode.auto_then(chunk.sync_entry) != PluginMode::Sync { succ!(self.core.tasks.plugin_entry(opt)); } runtime_mut!(LUA)?.push(&opt.id); defer! { _ = runtime_mut!(LUA).map(|mut r| r.pop()) } let plugin = match LOADER.load_with(&LUA, &opt.id, chunk) { Ok(t) => t, Err(e) => succ!(warn!("{e}")), }; drop(loader); let result = Lives::scope(&self.core, || { if let Some(cb) = opt.cb { cb(&LUA, plugin) } else { let job = LUA.create_table_from([("args", Sendable::args_to_table(&LUA, opt.args)?)])?; plugin.call_method("entry", job) } }); if let Err(ref e) = result { error!("Sync plugin `{}` failed: {e}", opt.id); } succ!(result?); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/help/bindings.rs
yazi-fm/src/help/bindings.rs
use ratatui::{buffer::Buffer, layout::{self, Constraint, Rect}, widgets::{List, ListItem, Widget}}; use yazi_config::THEME; use yazi_core::Core; pub(super) struct Bindings<'a> { core: &'a Core, } impl<'a> Bindings<'a> { pub(super) fn new(core: &'a Core) -> Self { Self { core } } } impl Widget for Bindings<'_> { fn render(self, area: Rect, buf: &mut Buffer) { let bindings = &self.core.help.window(); if bindings.is_empty() { return; } // On let col1: Vec<_> = bindings.iter().map(|c| ListItem::new(c.on()).style(THEME.help.on)).collect(); // Run let col2: Vec<_> = bindings.iter().map(|c| ListItem::new(c.run()).style(THEME.help.run)).collect(); // Desc let col3: Vec<_> = bindings .iter() .map(|c| ListItem::new(c.desc().unwrap_or("-".into())).style(THEME.help.desc)) .collect(); let chunks = layout::Layout::horizontal([ Constraint::Ratio(2, 10), Constraint::Ratio(3, 10), Constraint::Ratio(5, 10), ]) .split(area); let cursor = self.core.help.rel_cursor() as u16; buf.set_style( Rect { x: area.x, y: area.y + cursor, width: area.width, height: 1 }, THEME.help.hovered, ); List::new(col1).render(chunks[0], buf); List::new(col2).render(chunks[1], buf); List::new(col3).render(chunks[2], buf); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/help/help.rs
yazi-fm/src/help/help.rs
use ratatui::{buffer::Buffer, layout::{self, Constraint, Rect}, text::Line, widgets::Widget}; use yazi_config::{KEYMAP, THEME}; use yazi_core::Core; use super::Bindings; pub(crate) struct Help<'a> { core: &'a Core, } impl<'a> Help<'a> { pub fn new(core: &'a Core) -> Self { Self { core } } fn tips() -> String { match KEYMAP.help.iter().find(|&c| c.run.iter().any(|c| c.name == "filter")) { Some(c) => format!(" (Press `{}` to filter)", c.on()), None => String::new(), } } } impl Widget for Help<'_> { fn render(self, area: Rect, buf: &mut Buffer) { let help = &self.core.help; yazi_binding::elements::Clear::default().render(area, buf); let chunks = layout::Layout::vertical([Constraint::Fill(1), Constraint::Length(1)]).split(area); Line::styled( help.keyword().unwrap_or_else(|| format!("{}.help{}", help.layer, Self::tips())), THEME.help.footer, ) .render(chunks[1], buf); Bindings::new(self.core).render(chunks[0], buf); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/help/mod.rs
yazi-fm/src/help/mod.rs
yazi_macro::mod_flat!(bindings help);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/mgr/mod.rs
yazi-fm/src/mgr/mod.rs
yazi_macro::mod_flat!(modal preview);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/mgr/modal.rs
yazi-fm/src/mgr/modal.rs
use mlua::{ObjectLike, Table}; use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget}; use tracing::error; use yazi_binding::elements::render_once; use yazi_core::Core; use yazi_plugin::LUA; pub(crate) struct Modal<'a> { core: &'a Core, } impl<'a> Modal<'a> { #[inline] pub(crate) fn new(core: &'a Core) -> Self { Self { core } } } impl Widget for Modal<'_> { fn render(self, area: Rect, buf: &mut Buffer) { let mut f = || { let area = yazi_binding::elements::Rect::from(area); let root = LUA.globals().raw_get::<Table>("Modal")?.call_method::<Table>("new", area)?; render_once(root.call_method("children_redraw", ())?, buf, |p| self.core.mgr.area(p)); Ok::<_, mlua::Error>(()) }; if let Err(e) = f() { error!("Failed to redraw the `Modal` component:\n{e}"); } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/mgr/preview.rs
yazi-fm/src/mgr/preview.rs
use ratatui::{buffer::Buffer, widgets::Widget}; use yazi_config::LAYOUT; use yazi_core::Core; pub(crate) struct Preview<'a> { core: &'a Core, } impl<'a> Preview<'a> { #[inline] pub(crate) fn new(core: &'a Core) -> Self { Self { core } } } impl Widget for Preview<'_> { fn render(self, win: ratatui::layout::Rect, buf: &mut Buffer) { let Some(lock) = &self.core.active().preview.lock else { return; }; if *lock.area != LAYOUT.get().preview { return; } for w in &lock.data { let rect = w.area().transform(|p| self.core.mgr.area(p)); if win.intersects(rect) { w.clone().render(rect, buf); } } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/spot/mod.rs
yazi-fm/src/spot/mod.rs
yazi_macro::mod_flat!(spot);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/spot/spot.rs
yazi-fm/src/spot/spot.rs
use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget}; use yazi_core::Core; pub(crate) struct Spot<'a> { core: &'a Core, } impl<'a> Spot<'a> { pub(crate) fn new(core: &'a Core) -> Self { Self { core } } } impl Widget for Spot<'_> { fn render(self, win: Rect, buf: &mut Buffer) { let Some(lock) = &self.core.active().spot.lock else { return; }; for w in &lock.data { let rect = w.area().transform(|p| self.core.mgr.area(p)); if win.intersects(rect) { w.clone().render(rect, buf); } } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/input/mod.rs
yazi-fm/src/input/mod.rs
yazi_macro::mod_flat!(input);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/input/input.rs
yazi-fm/src/input/input.rs
use ratatui::{buffer::Buffer, layout::{Margin, Rect}, text::Line, widgets::{Block, BorderType, Widget}}; use yazi_config::THEME; use yazi_core::Core; pub(crate) struct Input<'a> { core: &'a Core, } impl<'a> Input<'a> { pub(crate) fn new(core: &'a Core) -> Self { Self { core } } } impl Widget for Input<'_> { fn render(self, _: Rect, buf: &mut Buffer) { let input = &self.core.input; let area = self.core.mgr.area(input.position); yazi_binding::elements::Clear::default().render(area, buf); Block::bordered() .border_type(BorderType::Rounded) .border_style(THEME.input.border) .title(Line::styled(&input.title, THEME.input.title)) .render(area, buf); input.render(area.inner(Margin::new(1, 1)), buf); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/pick/list.rs
yazi-fm/src/pick/list.rs
use ratatui::{buffer::Buffer, layout::{Margin, Rect}, widgets::{ListItem, Scrollbar, ScrollbarOrientation, ScrollbarState, StatefulWidget, Widget}}; use yazi_config::THEME; use yazi_core::Core; use yazi_widgets::Scrollable; pub(crate) struct List<'a> { core: &'a Core, } impl<'a> List<'a> { pub(crate) fn new(core: &'a Core) -> Self { Self { core } } } impl Widget for List<'_> { fn render(self, area: Rect, buf: &mut Buffer) { let pick = &self.core.pick; // Vertical scrollbar if pick.total() > pick.limit() { Scrollbar::new(ScrollbarOrientation::VerticalRight).render( area, buf, &mut ScrollbarState::new(pick.total()).position(pick.cursor), ); } // List content let inner = area.inner(Margin::new(1, 0)); let items = pick.window().map(|(i, v)| { if i == pick.cursor { ListItem::new(format!(" {v}")).style(THEME.pick.active) } else { ListItem::new(format!(" {v}")).style(THEME.pick.inactive) } }); Widget::render(ratatui::widgets::List::new(items), inner, buf); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/pick/pick.rs
yazi-fm/src/pick/pick.rs
use ratatui::{buffer::Buffer, layout::{Margin, Rect}, widgets::{Block, BorderType, Widget}}; use yazi_config::THEME; use yazi_core::Core; use crate::pick::List; pub(crate) struct Pick<'a> { core: &'a Core, } impl<'a> Pick<'a> { pub(crate) fn new(core: &'a Core) -> Self { Self { core } } } impl Widget for Pick<'_> { fn render(self, _: Rect, buf: &mut Buffer) { let pick = &self.core.pick; let area = self.core.mgr.area(pick.position); yazi_binding::elements::Clear::default().render(area, buf); Block::bordered() .title(pick.title()) .border_type(BorderType::Rounded) .border_style(THEME.pick.border) .render(area, buf); List::new(self.core).render(area.inner(Margin::new(0, 1)), buf); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/pick/mod.rs
yazi-fm/src/pick/mod.rs
yazi_macro::mod_flat!(list pick);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/cmp/mod.rs
yazi-fm/src/cmp/mod.rs
yazi_macro::mod_flat!(cmp);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/cmp/cmp.rs
yazi-fm/src/cmp/cmp.rs
use std::path::MAIN_SEPARATOR_STR; use ratatui::{buffer::Buffer, layout::Rect, widgets::{Block, BorderType, List, ListItem, Widget}}; use yazi_adapter::Dimension; use yazi_config::{THEME, popup::{Offset, Position}}; use yazi_core::Core; use yazi_shared::strand::StrandLike; pub(crate) struct Cmp<'a> { core: &'a Core, } impl<'a> Cmp<'a> { pub(crate) fn new(core: &'a Core) -> Self { Self { core } } } impl Widget for Cmp<'_> { fn render(self, rect: Rect, buf: &mut Buffer) { let items: Vec<_> = self .core .cmp .window() .iter() .enumerate() .map(|(i, x)| { let icon = if x.is_dir { &THEME.cmp.icon_folder } else { &THEME.cmp.icon_file }; let slash = if x.is_dir { MAIN_SEPARATOR_STR } else { "" }; let mut item = ListItem::new(format!(" {icon} {}{slash}", x.name.display())); if i == self.core.cmp.rel_cursor() { item = item.style(THEME.cmp.active); } else { item = item.style(THEME.cmp.inactive); } item }) .collect(); let input_area = self.core.mgr.area(self.core.input.position); let mut area = Position::sticky(Dimension::available().into(), input_area, Offset { x: 1, y: 0, width: input_area.width.saturating_sub(2), height: items.len() as u16 + 2, }); if area.y > input_area.y { area.y = area.y.saturating_sub(1); } else { area.y = rect.height.min(area.y + 1); area.height = rect.height.saturating_sub(area.y).min(area.height); } yazi_binding::elements::Clear::default().render(area, buf); List::new(items) .block(Block::bordered().border_type(BorderType::Rounded).border_style(THEME.cmp.border)) .render(area, buf); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/confirm/list.rs
yazi-fm/src/confirm/list.rs
use ratatui::{buffer::Buffer, layout::{Margin, Rect}, widgets::{Block, Borders, Scrollbar, ScrollbarOrientation, ScrollbarState, StatefulWidget, Widget, Wrap}}; use yazi_config::THEME; use yazi_core::Core; pub(crate) struct List<'a> { core: &'a Core, } impl<'a> List<'a> { pub(crate) fn new(core: &'a Core) -> Self { Self { core } } } impl Widget for List<'_> { fn render(self, mut area: Rect, buf: &mut Buffer) { // List content area let inner = area.inner(Margin::new(2, 0)); // Bottom border let block = Block::new().borders(Borders::BOTTOM).border_style(THEME.confirm.border); block.clone().render(area.inner(Margin::new(1, 0)), buf); let list = self .core .confirm .list .clone() .scroll((self.core.confirm.offset as u16, 0)) .block(block) .style(THEME.confirm.list) .wrap(Wrap { trim: false }); // Vertical scrollbar let lines = list.line_count(inner.width); if lines >= inner.height as usize { area.height = area.height.saturating_sub(1); Scrollbar::new(ScrollbarOrientation::VerticalRight).render( area, buf, &mut ScrollbarState::new(lines).position(self.core.confirm.offset), ); } list.render(inner, buf); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/confirm/mod.rs
yazi-fm/src/confirm/mod.rs
yazi_macro::mod_flat!(buttons confirm body list);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/confirm/body.rs
yazi-fm/src/confirm/body.rs
use ratatui::{buffer::Buffer, layout::{Margin, Rect}, style::Styled, widgets::{Block, Borders, Widget}}; use yazi_config::THEME; use yazi_core::Core; pub(crate) struct Body<'a> { core: &'a Core, border: bool, } impl<'a> Body<'a> { pub(crate) fn new(core: &'a Core, border: bool) -> Self { Self { core, border } } } impl Widget for Body<'_> { fn render(self, area: Rect, buf: &mut Buffer) { let confirm = &self.core.confirm; // Inner area let inner = area.inner(Margin::new(1, 0)); // Border let block = if self.border { Block::new().borders(Borders::BOTTOM).border_style(THEME.confirm.border) } else { Block::new() }; confirm .body .clone() .alignment(ratatui::layout::Alignment::Center) .block(block) .style(THEME.confirm.body.derive(Styled::style(&confirm.body))) .render(inner, buf); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/confirm/buttons.rs
yazi-fm/src/confirm/buttons.rs
use ratatui::{buffer::Buffer, layout::{Constraint, Rect}, text::Span, widgets::{Paragraph, Widget}}; use yazi_config::THEME; pub(crate) struct Buttons; impl Widget for Buttons { fn render(self, area: Rect, buf: &mut Buffer) { let chunks = ratatui::layout::Layout::horizontal([Constraint::Fill(1), Constraint::Fill(1)]).split(area); Paragraph::new(Span::raw(&THEME.confirm.btn_labels[0]).style(THEME.confirm.btn_yes)) .centered() .render(chunks[0], buf); Paragraph::new(Span::raw(&THEME.confirm.btn_labels[1]).style(THEME.confirm.btn_no)) .centered() .render(chunks[1], buf); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/confirm/confirm.rs
yazi-fm/src/confirm/confirm.rs
use ratatui::{buffer::Buffer, layout::{Alignment, Constraint, Layout, Margin, Rect}, widgets::{Block, BorderType, Widget}}; use yazi_config::THEME; use yazi_core::Core; pub(crate) struct Confirm<'a> { core: &'a Core, } impl<'a> Confirm<'a> { pub(crate) fn new(core: &'a Core) -> Self { Self { core } } } impl Widget for Confirm<'_> { fn render(self, _: Rect, buf: &mut Buffer) { let confirm = &self.core.confirm; let area = self.core.mgr.area(confirm.position); yazi_binding::elements::Clear::default().render(area, buf); Block::bordered() .border_type(BorderType::Rounded) .border_style(THEME.confirm.border) .title(confirm.title.clone().style(THEME.confirm.title.derive(confirm.title.style))) .title_alignment(Alignment::Center) .render(area, buf); let body_border = confirm.list.line_count(area.width) != 0; let body_height = confirm.body.line_count(area.width) as u16; let chunks = Layout::vertical([ Constraint::Length(if body_height == 0 { 0 } else { body_height.saturating_add(body_border as u16) }), Constraint::Fill(1), Constraint::Length(1), ]) .split(area.inner(Margin::new(0, 1))); super::Body::new(self.core, body_border).render(chunks[0], buf); super::List::new(self.core).render(chunks[1], buf); super::Buttons.render(chunks[2], buf); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/notify/notify.rs
yazi-fm/src/notify/notify.rs
use ratatui::{buffer::Buffer, layout::{self, Constraint, Offset, Rect}, widgets::{Block, BorderType, Paragraph, Widget, Wrap}}; use yazi_core::{Core, notify::Message}; pub(crate) struct Notify<'a> { core: &'a Core, } impl<'a> Notify<'a> { pub(crate) fn new(core: &'a Core) -> Self { Self { core } } pub(crate) fn available(area: Rect) -> Rect { let chunks = layout::Layout::horizontal([Constraint::Fill(1), Constraint::Min(80)]).split(area); let chunks = layout::Layout::vertical([Constraint::Fill(1), Constraint::Max(1)]).split(chunks[1]); chunks[0] } fn tiles<'m>(area: Rect, messages: impl Iterator<Item = &'m Message> + Clone) -> Vec<Rect> { layout::Layout::vertical( [Constraint::Fill(1)] .into_iter() .chain(messages.clone().map(|m| Constraint::Length(m.height(area.width) as u16))), ) .spacing(1) .split(area) .iter() .skip(1) .zip(messages) .map(|(&(mut r), m)| { if r.width > m.max_width as u16 { r.x = r.x.saturating_add(r.width - m.max_width as u16); r.width = m.max_width as u16; } r }) .collect() } } impl Widget for Notify<'_> { fn render(self, area: Rect, buf: &mut Buffer) { let notify = &self.core.notify; let available = Self::available(area); let messages = notify.messages.iter().take(notify.limit(available)).rev(); let tiles = Self::tiles(available, messages.clone()); for (i, m) in messages.enumerate() { let mut rect = tiles[i].offset(Offset { x: (100 - m.percent) as i32 * tiles[i].width as i32 / 100, y: 0 }); rect.width -= rect.x - tiles[i].x; yazi_binding::elements::Clear::default().render(rect, buf); Paragraph::new(m.content.as_str()) .wrap(Wrap { trim: false }) .block( Block::bordered() .border_type(BorderType::Rounded) .title(format!("{} {}", m.level.icon(), m.title)) .title_style(m.level.style()) .border_style(m.level.style()), ) .render(rect, buf); } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/notify/mod.rs
yazi-fm/src/notify/mod.rs
yazi_macro::mod_flat!(notify);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/which/which.rs
yazi-fm/src/which/which.rs
use ratatui::{buffer::Buffer, layout, layout::{Constraint, Rect}, widgets::{Block, Widget}}; use yazi_config::THEME; use yazi_core::Core; use super::Cand; const PADDING_X: u16 = 1; const PADDING_Y: u16 = 1; pub(crate) struct Which<'a> { core: &'a Core, } impl<'a> Which<'a> { pub(crate) fn new(core: &'a Core) -> Self { Self { core } } } impl Widget for Which<'_> { fn render(self, area: Rect, buf: &mut Buffer) { let which = &self.core.which; if which.silent { return; } let cols = THEME.which.cols as usize; let height = area.height.min(which.cands.len().div_ceil(cols) as u16 + PADDING_Y * 2); let area = Rect { x: PADDING_X.min(area.width), y: area.height.saturating_sub(height + PADDING_Y * 2), width: area.width.saturating_sub(PADDING_X * 2), height, }; // Don't render if there's no space if area.height <= PADDING_Y * 2 { return; } let chunks = { use Constraint::*; layout::Layout::horizontal(match cols { 1 => &[Ratio(1, 1)][..], 2 => &[Ratio(1, 2), Ratio(1, 2)], _ => &[Ratio(1, 3), Ratio(1, 3), Ratio(1, 3)], }) .split(area) }; yazi_binding::elements::Clear::default().render(area, buf); Block::new().style(THEME.which.mask).render(area, buf); for y in 0..area.height { for (x, chunk) in chunks.iter().enumerate() { let Some(cand) = which.cands.get(y as usize * cols + x) else { break; }; Cand::new(cand, which.times).render(Rect { y: chunk.y + y + 1, height: 1, ..*chunk }, buf); } } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/which/mod.rs
yazi-fm/src/which/mod.rs
yazi_macro::mod_flat!(cand which);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-fm/src/which/cand.rs
yazi-fm/src/which/cand.rs
use ratatui::{buffer::Buffer, layout::Rect, text::{Line, Span}, widgets::Widget}; use yazi_config::{THEME, keymap::Chord}; pub(super) struct Cand<'a> { cand: &'a Chord, times: usize, } impl<'a> Cand<'a> { pub(super) fn new(cand: &'a Chord, times: usize) -> Self { Self { times, cand } } fn keys(&self) -> Vec<String> { self.cand.on[self.times..].iter().map(ToString::to_string).collect() } } impl Widget for Cand<'_> { fn render(self, area: Rect, buf: &mut Buffer) { let keys = self.keys(); let mut spans = Vec::with_capacity(10); // Padding spans.push(Span::raw(" ".repeat(10usize.saturating_sub(keys.join("").len())))); // First key spans.push(Span::styled(keys[0].clone(), THEME.which.cand)); // Rest keys spans.extend(keys.iter().skip(1).map(|k| Span::styled(k, THEME.which.rest))); // Separator spans.push(Span::styled(&THEME.which.separator, THEME.which.separator_style)); // Description spans.push(Span::styled(self.cand.desc_or_run(), THEME.which.desc)); Line::from(spans).render(area, buf); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-adapter/src/lib.rs
yazi-adapter/src/lib.rs
yazi_macro::mod_pub!(drivers); yazi_macro::mod_flat!(adapter brand dimension emulator icc image info mux unknown); use yazi_shared::{RoCell, SyncCell, in_wsl}; pub static EMULATOR: RoCell<Emulator> = RoCell::new(); pub static ADAPTOR: SyncCell<Adapter> = SyncCell::new(Adapter::Chafa); // Image state static SHOWN: SyncCell<Option<ratatui::layout::Rect>> = SyncCell::new(None); // WSL support pub static WSL: SyncCell<bool> = SyncCell::new(false); // Tmux support pub static TMUX: SyncCell<bool> = SyncCell::new(false); static ESCAPE: SyncCell<&'static str> = SyncCell::new("\x1b"); static START: SyncCell<&'static str> = SyncCell::new("\x1b"); static CLOSE: SyncCell<&'static str> = SyncCell::new(""); pub fn init() -> anyhow::Result<()> { // WSL support WSL.set(in_wsl()); // Emulator detection let mut emulator = Emulator::detect().unwrap_or_default(); TMUX.set(emulator.kind.is_left_and(|&b| b == Brand::Tmux)); // Tmux support if TMUX.get() { ESCAPE.set("\x1b\x1b"); START.set("\x1bPtmux;\x1b\x1b"); CLOSE.set("\x1b\\"); Mux::tmux_passthrough(); emulator = Emulator::detect().unwrap_or_default(); } EMULATOR.init(emulator); yazi_config::init_flavor(EMULATOR.light)?; ADAPTOR.set(Adapter::matches(&EMULATOR)); ADAPTOR.get().start(); Ok(()) }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-adapter/src/unknown.rs
yazi-adapter/src/unknown.rs
use crate::Adapter; #[derive(Clone, Copy, Debug, Default)] pub struct Unknown { pub kgp: bool, pub sixel: bool, } impl Unknown { pub(super) fn adapters(self) -> &'static [Adapter] { use Adapter as A; match (self.kgp, self.sixel) { (true, true) => &[A::Sixel, A::KgpOld], (true, false) => &[A::KgpOld], (false, true) => &[A::Sixel], (false, false) => &[], } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-adapter/src/image.rs
yazi-adapter/src/image.rs
use std::path::{Path, PathBuf}; use anyhow::Result; use image::{DynamicImage, ImageDecoder, ImageError, ImageReader, Limits, codecs::{jpeg::JpegEncoder, png::PngEncoder}, imageops::FilterType, metadata::Orientation}; use ratatui::layout::Rect; use yazi_config::YAZI; use yazi_fs::provider::{Provider, local::Local}; use crate::{Dimension, Icc}; pub struct Image; impl Image { pub async fn precache(src: PathBuf, cache: &Path) -> Result<()> { let (mut img, orientation) = Self::decode_from(src).await?; let (w, h) = Self::flip_size(orientation, (YAZI.preview.max_width, YAZI.preview.max_height)); let buf = tokio::task::spawn_blocking(move || { if img.width() > w || img.height() > h { img = img.resize(w, h, Self::filter()); } if orientation != Orientation::NoTransforms { img.apply_orientation(orientation); } let mut buf = Vec::new(); if img.color().has_alpha() { let encoder = PngEncoder::new(&mut buf); img.write_with_encoder(encoder)?; } else { let encoder = JpegEncoder::new_with_quality(&mut buf, YAZI.preview.image_quality); img.write_with_encoder(encoder)?; } Ok::<_, ImageError>(buf) }) .await??; Ok(Local::regular(&cache).write(buf).await?) } pub(super) async fn downscale(path: PathBuf, rect: Rect) -> Result<DynamicImage> { let (mut img, orientation) = Self::decode_from(path).await?; let (w, h) = Self::flip_size(orientation, Self::max_pixel(rect)); // Fast path. if img.width() <= w && img.height() <= h && orientation == Orientation::NoTransforms { return Ok(img); } let img = tokio::task::spawn_blocking(move || { if img.width() > w || img.height() > h { img = img.resize(w, h, Self::filter()) } if orientation != Orientation::NoTransforms { img.apply_orientation(orientation); } img }) .await?; Ok(img) } pub(super) fn max_pixel(rect: Rect) -> (u16, u16) { Dimension::cell_size() .map(|(cw, ch)| { let (w, h) = ((rect.width as f64 * cw) as u16, (rect.height as f64 * ch) as u16); (w.min(YAZI.preview.max_width), h.min(YAZI.preview.max_height)) }) .unwrap_or((YAZI.preview.max_width, YAZI.preview.max_height)) } pub(super) fn pixel_area(size: (u32, u32), rect: Rect) -> Rect { Dimension::cell_size() .map(|(cw, ch)| Rect { x: rect.x, y: rect.y, width: (size.0 as f64 / cw).ceil() as u16, height: (size.1 as f64 / ch).ceil() as u16, }) .unwrap_or(rect) } fn filter() -> FilterType { match YAZI.preview.image_filter.as_str() { "nearest" => FilterType::Nearest, "triangle" => FilterType::Triangle, "catmull-rom" => FilterType::CatmullRom, "gaussian" => FilterType::Gaussian, "lanczos3" => FilterType::Lanczos3, _ => FilterType::Triangle, } } async fn decode_from(path: PathBuf) -> Result<(DynamicImage, Orientation)> { let mut limits = Limits::no_limits(); if YAZI.tasks.image_alloc > 0 { limits.max_alloc = Some(YAZI.tasks.image_alloc as u64); } if YAZI.tasks.image_bound[0] > 0 { limits.max_image_width = Some(YAZI.tasks.image_bound[0] as u32); } if YAZI.tasks.image_bound[1] > 0 { limits.max_image_height = Some(YAZI.tasks.image_bound[1] as u32); } tokio::task::spawn_blocking(move || { let mut reader = ImageReader::open(path)?; reader.limits(limits); let mut decoder = reader.with_guessed_format()?.into_decoder()?; let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms); Ok((Icc::transform(decoder)?, orientation)) }) .await .map_err(|e| ImageError::IoError(e.into()))? } fn flip_size(orientation: Orientation, (w, h): (u16, u16)) -> (u32, u32) { use image::metadata::Orientation::{Rotate90, Rotate90FlipH, Rotate270, Rotate270FlipH}; match orientation { Rotate90 | Rotate270 | Rotate90FlipH | Rotate270FlipH => (h as u32, w as u32), _ => (w as u32, h as u32), } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-adapter/src/mux.rs
yazi-adapter/src/mux.rs
use std::borrow::Cow; use anyhow::Result; use tracing::error; use yazi_macro::time; use yazi_term::tty::TTY; use crate::{CLOSE, ESCAPE, Emulator, START, TMUX}; pub struct Mux; impl Mux { pub fn csi(s: &str) -> Cow<'_, str> { if TMUX.get() { Cow::Owned(format!( "{START}{}{CLOSE}", s.trim_start_matches('\x1b').replace('\x1b', ESCAPE.get()), )) } else { Cow::Borrowed(s) } } pub fn tmux_passthrough() { let output = time!( "Running `tmux set -p allow-passthrough on`", std::process::Command::new("tmux") .args(["set", "-p", "allow-passthrough", "on"]) .stdin(std::process::Stdio::null()) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::piped()) .spawn() .and_then(|c| c.wait_with_output()) ); match output { Ok(o) if o.status.success() => {} Ok(o) => { error!( "Running `tmux set -p allow-passthrough on` failed: {:?}, {}", o.status, String::from_utf8_lossy(&o.stderr) ); } Err(e) => { error!("Failed to spawn `tmux set -p allow-passthrough on`: {e}"); } } } pub fn tmux_drain() -> Result<()> { if TMUX.get() { crossterm::execute!(TTY.writer(), crossterm::style::Print(Self::csi("\x1b[5n")))?; _ = Emulator::read_until_dsr(); } Ok(()) } pub fn tmux_sixel_flag() -> &'static str { let stdout = std::process::Command::new("tmux") .args(["-LwU0dju1is5", "-f/dev/null", "start", ";", "display", "-p", "#{sixel_support}"]) .output() .ok() .and_then(|o| String::from_utf8(o.stdout).ok()) .unwrap_or_default(); match stdout.trim() { "1" => "Supported", "0" => "Unsupported", _ => "Unknown", } } pub(super) fn term_program() -> (Option<String>, Option<String>) { let (mut term, mut program) = (None, None); if !TMUX.get() { return (term, program); } let Ok(output) = time!( "Running `tmux show-environment`", std::process::Command::new("tmux").arg("show-environment").output() ) else { return (term, program); }; for line in String::from_utf8_lossy(&output.stdout).lines() { if let Some((k, v)) = line.trim().split_once('=') { match k { "TERM" => term = Some(v.to_owned()), "TERM_PROGRAM" => program = Some(v.to_owned()), _ => continue, } } if term.is_some() && program.is_some() { break; } } (term, program) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-adapter/src/info.rs
yazi-adapter/src/info.rs
use std::path::PathBuf; use image::{ImageDecoder, ImageError}; pub type ImageFormat = image::ImageFormat; pub type ImageColor = image::ColorType; pub type ImageOrientation = image::metadata::Orientation; #[derive(Clone, Copy)] pub struct ImageInfo { pub format: ImageFormat, pub width: u32, pub height: u32, pub color: ImageColor, pub orientation: Option<ImageOrientation>, } impl ImageInfo { pub async fn new(path: PathBuf) -> image::ImageResult<Self> { tokio::task::spawn_blocking(move || { let reader = image::ImageReader::open(path)?.with_guessed_format()?; let Some(format) = reader.format() else { return Err(ImageError::IoError(std::io::Error::new( std::io::ErrorKind::InvalidData, "unknown image format", ))); }; let mut decoder = reader.into_decoder()?; let (width, height) = decoder.dimensions(); Ok(Self { format, width, height, color: decoder.color_type(), orientation: decoder.orientation().ok(), }) }) .await .map_err(|e| ImageError::IoError(e.into()))? } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-adapter/src/adapter.rs
yazi-adapter/src/adapter.rs
use std::{env, fmt::Display, path::PathBuf}; use anyhow::Result; use ratatui::layout::Rect; use tracing::warn; use yazi_shared::env_exists; use crate::{Emulator, SHOWN, TMUX, drivers}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Adapter { Kgp, KgpOld, Iip, Sixel, // Supported by Überzug++ X11, Wayland, Chafa, } impl Display for Adapter { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Kgp => write!(f, "kgp"), Self::KgpOld => write!(f, "kgp-old"), Self::Iip => write!(f, "iip"), Self::Sixel => write!(f, "sixel"), Self::X11 => write!(f, "x11"), Self::Wayland => write!(f, "wayland"), Self::Chafa => write!(f, "chafa"), } } } impl Adapter { pub async fn image_show<P>(self, path: P, max: Rect) -> Result<Rect> where P: Into<PathBuf>, { if max.is_empty() { return Ok(Rect::default()); } let path = path.into(); match self { Self::Kgp => drivers::Kgp::image_show(path, max).await, Self::KgpOld => drivers::KgpOld::image_show(path, max).await, Self::Iip => drivers::Iip::image_show(path, max).await, Self::Sixel => drivers::Sixel::image_show(path, max).await, Self::X11 | Self::Wayland => drivers::Ueberzug::image_show(path, max).await, Self::Chafa => drivers::Chafa::image_show(path, max).await, } } pub fn image_hide(self) -> Result<()> { if let Some(area) = SHOWN.replace(None) { self.image_erase(area) } else { Ok(()) } } pub fn image_erase(self, area: Rect) -> Result<()> { match self { Self::Kgp => drivers::Kgp::image_erase(area), Self::KgpOld => drivers::KgpOld::image_erase(area), Self::Iip => drivers::Iip::image_erase(area), Self::Sixel => drivers::Sixel::image_erase(area), Self::X11 | Self::Wayland => drivers::Ueberzug::image_erase(area), Self::Chafa => drivers::Chafa::image_erase(area), } } #[inline] pub fn shown_load(self) -> Option<Rect> { SHOWN.get() } #[inline] pub(super) fn shown_store(area: Rect) { SHOWN.set(Some(area)); } pub(super) fn start(self) { drivers::Ueberzug::start(self); } #[inline] pub(super) fn needs_ueberzug(self) -> bool { !matches!(self, Self::Kgp | Self::KgpOld | Self::Iip | Self::Sixel) } } impl Adapter { pub fn matches(emulator: &Emulator) -> Self { let mut protocols = emulator.adapters().to_owned(); if env_exists("ZELLIJ_SESSION_NAME") { protocols.retain(|p| *p == Self::Sixel); } else if TMUX.get() { protocols.retain(|p| *p != Self::KgpOld); } if let Some(p) = protocols.first() { return *p; } let supported_compositor = drivers::Ueberzug::supported_compositor(); match env::var("XDG_SESSION_TYPE").unwrap_or_default().as_str() { "x11" => return Self::X11, "wayland" if supported_compositor => return Self::Wayland, "wayland" if !supported_compositor => return Self::Chafa, _ => warn!("[Adapter] Could not identify XDG_SESSION_TYPE"), } if env_exists("WAYLAND_DISPLAY") { return if supported_compositor { Self::Wayland } else { Self::Chafa }; } match env::var("DISPLAY").unwrap_or_default().as_str() { s if !s.is_empty() && !s.contains("/org.xquartz") => return Self::X11, _ => {} } warn!("[Adapter] Falling back to chafa"); Self::Chafa } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-adapter/src/brand.rs
yazi-adapter/src/brand.rs
use tracing::debug; use yazi_shared::env_exists; use crate::Mux; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Brand { Kitty, Konsole, Iterm2, WezTerm, Foot, Ghostty, Microsoft, Warp, Rio, BlackBox, VSCode, Tabby, Hyper, Mintty, Tmux, VTerm, Apple, Urxvt, Bobcat, } impl Brand { pub(super) fn from_csi(resp: &str) -> Option<Self> { let names = [ ("kitty", Self::Kitty), ("Konsole", Self::Konsole), ("iTerm2", Self::Iterm2), ("WezTerm", Self::WezTerm), ("foot", Self::Foot), ("ghostty", Self::Ghostty), ("Warp", Self::Warp), ("tmux ", Self::Tmux), ("libvterm", Self::VTerm), ("Bobcat", Self::Bobcat), ]; names.into_iter().find(|&(n, _)| resp.contains(n)).map(|(_, b)| b) } pub fn from_env() -> Option<Self> { let (term, program) = Self::env(); let vars = [ ("KITTY_WINDOW_ID", Self::Kitty), ("KONSOLE_VERSION", Self::Konsole), ("ITERM_SESSION_ID", Self::Iterm2), ("WEZTERM_EXECUTABLE", Self::WezTerm), ("GHOSTTY_RESOURCES_DIR", Self::Ghostty), ("WT_Session", Self::Microsoft), ("WARP_HONOR_PS1", Self::Warp), ("VSCODE_INJECTION", Self::VSCode), ("TABBY_CONFIG_DIRECTORY", Self::Tabby), ]; match term.as_str() { "xterm-kitty" => return Some(Self::Kitty), "foot" => return Some(Self::Foot), "foot-extra" => return Some(Self::Foot), "xterm-ghostty" => return Some(Self::Ghostty), "rio" => return Some(Self::Rio), "rxvt-unicode-256color" => return Some(Self::Urxvt), _ => {} } match program.as_str() { "iTerm.app" => return Some(Self::Iterm2), "WezTerm" => return Some(Self::WezTerm), "ghostty" => return Some(Self::Ghostty), "WarpTerminal" => return Some(Self::Warp), "rio" => return Some(Self::Rio), "BlackBox" => return Some(Self::BlackBox), "vscode" => return Some(Self::VSCode), "Tabby" => return Some(Self::Tabby), "Hyper" => return Some(Self::Hyper), "mintty" => return Some(Self::Mintty), "Apple_Terminal" => return Some(Self::Apple), _ => {} } if let Some((var, brand)) = vars.into_iter().find(|&(s, _)| env_exists(s)) { debug!("Detected special environment variable: {var}"); return Some(brand); } None } pub(super) fn adapters(self) -> &'static [crate::Adapter] { use crate::Adapter as A; match self { Self::Kitty => &[A::Kgp], Self::Konsole => &[A::KgpOld], Self::Iterm2 => &[A::Iip, A::Sixel], Self::WezTerm => &[A::Iip, A::Sixel], Self::Foot => &[A::Sixel], Self::Ghostty => &[A::Kgp], Self::Microsoft => &[A::Sixel], Self::Warp => &[A::Iip, A::KgpOld], Self::Rio => &[A::Iip, A::Sixel], Self::BlackBox => &[A::Sixel], Self::VSCode => &[A::Iip, A::Sixel], Self::Tabby => &[A::Iip, A::Sixel], Self::Hyper => &[A::Iip, A::Sixel], Self::Mintty => &[A::Iip], Self::Tmux => &[], Self::VTerm => &[], Self::Apple => &[], Self::Urxvt => &[], Self::Bobcat => &[A::Iip, A::Sixel], } } fn env() -> (String, String) { let (term, program) = Mux::term_program(); ( term.unwrap_or(std::env::var("TERM").unwrap_or_default()), program.unwrap_or(std::env::var("TERM_PROGRAM").unwrap_or_default()), ) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-adapter/src/emulator.rs
yazi-adapter/src/emulator.rs
use std::{io::BufWriter, time::Duration}; use anyhow::Result; use crossterm::{cursor::{RestorePosition, SavePosition}, execute, style::Print, terminal::{disable_raw_mode, enable_raw_mode}}; use scopeguard::defer; use tokio::time::sleep; use tracing::{debug, error, warn}; use yazi_shared::Either; use yazi_term::tty::{Handle, TTY}; use crate::{Adapter, Brand, Dimension, Mux, TMUX, Unknown}; #[derive(Clone, Debug)] pub struct Emulator { pub kind: Either<Brand, Unknown>, pub version: String, pub light: bool, pub csi_16t: (u16, u16), pub force_16t: bool, } impl Default for Emulator { fn default() -> Self { Self { kind: Either::Right(Unknown::default()), version: String::new(), light: false, csi_16t: (0, 0), force_16t: false, } } } impl Emulator { pub fn detect() -> Result<Self> { defer! { disable_raw_mode().ok(); } enable_raw_mode()?; let resort = Brand::from_env(); let kgp_seq = if resort.is_none() { Mux::csi("\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\") } else { "".into() }; execute!( TTY.writer(), SavePosition, Print(kgp_seq), // Detect KGP Print(Mux::csi("\x1b[>q")), // Request terminal version Print("\x1b[16t"), // Request cell size Print("\x1b]11;?\x07"), // Request background color Print(Mux::csi("\x1b[0c")), // Request device attributes RestorePosition )?; let resp = Self::read_until_da1(); Mux::tmux_drain()?; let kind = if let Some(b) = Brand::from_csi(&resp).or(resort) { Either::Left(b) } else { Either::Right(Unknown { kgp: resp.contains("\x1b_Gi=31;OK"), sixel: ["?4;", "?4c", ";4;", ";4c"].iter().any(|s| resp.contains(s)), }) }; let csi_16t = Self::csi_16t(&resp).unwrap_or_default(); Ok(Self { kind, version: Self::csi_gt_q(&resp).unwrap_or_default(), light: Self::light_bg(&resp).unwrap_or_default(), csi_16t, force_16t: Self::force_16t(csi_16t), }) } pub fn adapters(&self) -> &'static [Adapter] { match self.kind { Either::Left(brand) => brand.adapters(), Either::Right(unknown) => unknown.adapters(), } } pub fn move_lock<F, T>((x, y): (u16, u16), cb: F) -> Result<T> where F: FnOnce(&mut BufWriter<Handle>) -> Result<T>, { use std::{io::Write, thread, time::Duration}; use crossterm::{cursor::{Hide, MoveTo, Show}, queue}; let mut w = TTY.lockout(); // I really don't want to add this, // But tmux and ConPTY sometimes cause the cursor position to get out of sync. if TMUX.get() || cfg!(windows) { execute!(w, SavePosition, MoveTo(x, y), Show)?; execute!(w, MoveTo(x, y), Show)?; execute!(w, MoveTo(x, y), Show)?; thread::sleep(Duration::from_millis(1)); } else { queue!(w, SavePosition, MoveTo(x, y))?; } let result = cb(&mut w); if TMUX.get() || cfg!(windows) { queue!(w, Hide, RestorePosition)?; } else { queue!(w, RestorePosition)?; } w.flush()?; result } pub fn read_until_da1() -> String { let now = std::time::Instant::now(); let h = tokio::spawn(Self::error_to_user()); let (buf, result) = TTY.read_until(Duration::from_millis(1000), |b, buf| { b == b'c' && buf.contains(&0x1b) && buf.rsplitn(2, |&b| b == 0x1b).next().is_some_and(|s| s.starts_with(b"[?")) }); h.abort(); match result { Ok(()) => debug!("Terminal responded to DA1 in {:?}: {buf:?}", now.elapsed()), Err(e) => { error!("Terminal failed to respond to DA1 in {:?}: {buf:?}, error: {e:?}", now.elapsed()) } } String::from_utf8_lossy(&buf).into_owned() } pub fn read_until_dsr() -> String { let now = std::time::Instant::now(); let (buf, result) = TTY.read_until(Duration::from_millis(200), |b, buf| { b == b'n' && (buf.ends_with(b"\x1b[0n") || buf.ends_with(b"\x1b[3n")) }); match result { Ok(()) => debug!("Terminal responded to DSR in {:?}: {buf:?}", now.elapsed()), Err(e) => { error!("Terminal failed to respond to DSR in {:?}: {buf:?}, error: {e:?}", now.elapsed()) } } String::from_utf8_lossy(&buf).into_owned() } async fn error_to_user() { use crossterm::style::{Attribute, Color, Print, ResetColor, SetAttributes, SetForegroundColor}; sleep(Duration::from_millis(400)).await; _ = crossterm::execute!( std::io::stderr(), SetForegroundColor(Color::Red), SetAttributes(Attribute::Bold.into()), Print("\r\nTerminal response timeout: "), ResetColor, SetAttributes(Attribute::Reset.into()), // Print("The request sent by Yazi didn't receive a correct response.\r\n"), Print( "Please check your terminal environment as per: https://yazi-rs.github.io/docs/faq#trt\r\n" ), ); } fn csi_16t(resp: &str) -> Option<(u16, u16)> { let b = resp.split_once("\x1b[6;")?.1.as_bytes(); let h: Vec<_> = b.iter().copied().take_while(|&c| c.is_ascii_digit()).collect(); b.get(h.len()).filter(|&&c| c == b';')?; let w: Vec<_> = b[h.len() + 1..].iter().copied().take_while(|&c| c.is_ascii_digit()).collect(); b.get(h.len() + 1 + w.len()).filter(|&&c| c == b't')?; let (w, h) = unsafe { (String::from_utf8_unchecked(w), String::from_utf8_unchecked(h)) }; Some((w.parse().ok()?, h.parse().ok()?)) } fn csi_gt_q(resp: &str) -> Option<String> { let (_, s) = resp.split_once("\x1bP>|")?; Some(s[..s.find("\x1b\\")?].to_owned()) } fn light_bg(resp: &str) -> Result<bool> { match resp.split_once("]11;rgb:") { Some((_, s)) if s.len() >= 14 => { let r = u8::from_str_radix(&s[0..2], 16)? as f32; let g = u8::from_str_radix(&s[5..7], 16)? as f32; let b = u8::from_str_radix(&s[10..12], 16)? as f32; let luma = r * 0.2627 / 256.0 + g * 0.6780 / 256.0 + b * 0.0593 / 256.0; debug!("Detected background color: {} (luma = {luma:.2})", &s[..14]); Ok(luma > 0.6) } _ => { warn!("Failed to detect background color: {resp:?}"); Ok(false) } } } fn force_16t((w, h): (u16, u16)) -> bool { if w == 0 || h == 0 { return false; } Dimension::available() .ratio() .is_none_or(|(rw, rh)| rw.floor() as u16 != w || rh.floor() as u16 != h) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-adapter/src/dimension.rs
yazi-adapter/src/dimension.rs
use std::mem; use crossterm::terminal::WindowSize; use crate::EMULATOR; #[derive(Clone, Copy, Debug)] pub struct Dimension { pub rows: u16, pub columns: u16, pub width: u16, pub height: u16, } impl From<WindowSize> for Dimension { fn from(s: WindowSize) -> Self { Self { rows: s.rows, columns: s.columns, width: s.width, height: s.height } } } impl From<Dimension> for WindowSize { fn from(d: Dimension) -> Self { Self { rows: d.rows, columns: d.columns, width: d.width, height: d.height } } } impl Dimension { pub fn available() -> Self { let mut size = WindowSize { rows: 0, columns: 0, width: 0, height: 0 }; if let Ok(s) = crossterm::terminal::window_size() { _ = mem::replace(&mut size, s); } if (size.columns == 0 || size.rows == 0) && let Ok((cols, rows)) = crossterm::terminal::size() { size.columns = cols; size.rows = rows; } size.into() } pub fn ratio(self) -> Option<(f64, f64)> { if self.rows == 0 || self.columns == 0 || self.width == 0 || self.height == 0 { None } else { Some((self.width as f64 / self.columns as f64, self.height as f64 / self.rows as f64)) } } pub fn cell_size() -> Option<(f64, f64)> { let emu = &*EMULATOR; Some(if emu.force_16t { (emu.csi_16t.0 as f64, emu.csi_16t.1 as f64) } else if let Some(r) = Self::available().ratio() { r } else if emu.csi_16t.0 != 0 && emu.csi_16t.1 != 0 { (emu.csi_16t.0 as f64, emu.csi_16t.1 as f64) } else { None? }) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-adapter/src/icc.rs
yazi-adapter/src/icc.rs
use anyhow::Context; use image::{ColorType, DynamicImage, GrayAlphaImage, GrayImage, ImageDecoder, RgbImage, RgbaImage, metadata::Cicp}; use moxcms::{CicpColorPrimaries, ColorProfile, DataColorSpace, Layout, TransferCharacteristics, TransformOptions}; pub(super) struct Icc; impl Icc { pub(super) fn transform(mut decoder: impl ImageDecoder) -> anyhow::Result<DynamicImage> { if let Some(layout) = Self::color_type_to_layout(decoder.color_type()) && let Some(icc) = decoder.icc_profile().unwrap_or_default() && let Ok(profile) = ColorProfile::new_from_slice(&icc) && Self::requires_transform(&profile) { let mut buf = vec![0u8; decoder.total_bytes() as usize]; let (w, h) = decoder.dimensions(); decoder.read_image(&mut buf)?; let transformer = profile // TODO: Use `create_transform_in_place_nbit` in the next minor version of moxcms. .create_transform_8bit(layout, &ColorProfile::new_srgb(), layout, TransformOptions::default()) .context("cannot make a profile transformer")?; let mut converted = vec![0u8; buf.len()]; transformer.transform(&buf, &mut converted).context("cannot transform image")?; let mut image: DynamicImage = match layout { Layout::Gray => { GrayImage::from_raw(w, h, converted).context("cannot load transformed image")?.into() } Layout::GrayAlpha => { GrayAlphaImage::from_raw(w, h, converted).context("cannot load transformed image")?.into() } Layout::Rgb => { RgbImage::from_raw(w, h, converted).context("cannot load transformed image")?.into() } Layout::Rgba => { RgbaImage::from_raw(w, h, converted).context("cannot load transformed image")?.into() } _ => unreachable!(), }; image.set_rgb_primaries(Cicp::SRGB.primaries); image.set_transfer_function(Cicp::SRGB.transfer); Ok(image) } else { Ok(DynamicImage::from_decoder(decoder)?) } } fn color_type_to_layout(color_type: ColorType) -> Option<Layout> { match color_type { ColorType::L8 => Some(Layout::Gray), ColorType::La8 => Some(Layout::GrayAlpha), ColorType::Rgb8 => Some(Layout::Rgb), ColorType::Rgba8 => Some(Layout::Rgba), _ => None, } } fn requires_transform(profile: &ColorProfile) -> bool { if profile.color_space == DataColorSpace::Cmyk { return false; } profile.cicp.is_none_or(|c| { c.color_primaries != CicpColorPrimaries::Bt709 || c.transfer_characteristics != TransferCharacteristics::Srgb }) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-adapter/src/drivers/iip.rs
yazi-adapter/src/drivers/iip.rs
use std::{fmt::Write, io::Write as ioWrite, path::PathBuf}; use anyhow::Result; use base64::{Engine, engine::{Config, general_purpose::STANDARD}}; use crossterm::{cursor::MoveTo, queue}; use image::{DynamicImage, ExtendedColorType, ImageEncoder, codecs::{jpeg::JpegEncoder, png::PngEncoder}}; use ratatui::layout::Rect; use yazi_config::YAZI; use crate::{CLOSE, Emulator, Image, START, adapter::Adapter}; pub(crate) struct Iip; impl Iip { pub(crate) async fn image_show(path: PathBuf, max: Rect) -> Result<Rect> { let img = Image::downscale(path, max).await?; let area = Image::pixel_area((img.width(), img.height()), max); let b = Self::encode(img).await?; Adapter::Iip.image_hide()?; Adapter::shown_store(area); Emulator::move_lock((max.x, max.y), |w| { w.write_all(&b)?; Ok(area) }) } pub(crate) fn image_erase(area: Rect) -> Result<()> { let s = " ".repeat(area.width as usize); Emulator::move_lock((0, 0), |w| { for y in area.top()..area.bottom() { queue!(w, MoveTo(area.x, y))?; write!(w, "{s}")?; } Ok(()) }) } async fn encode(img: DynamicImage) -> Result<Vec<u8>> { tokio::task::spawn_blocking(move || { let (w, h) = (img.width(), img.height()); let mut b = vec![]; if img.color().has_alpha() { PngEncoder::new(&mut b).write_image(&img.into_rgba8(), w, h, ExtendedColorType::Rgba8)?; } else { JpegEncoder::new_with_quality(&mut b, YAZI.preview.image_quality).encode_image(&img)?; }; let mut buf = String::with_capacity( 200 + base64::encoded_len(b.len(), STANDARD.config().encode_padding()).unwrap_or(0), ); write!( buf, "{START}]1337;File=inline=1;size={};width={w}px;height={h}px;doNotMoveCursor=1:", b.len(), )?; STANDARD.encode_string(b, &mut buf); write!(buf, "\x07{CLOSE}")?; Ok(buf.into_bytes()) }) .await? } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-adapter/src/drivers/ueberzug.rs
yazi-adapter/src/drivers/ueberzug.rs
use std::{path::PathBuf, process::Stdio}; use anyhow::{Result, bail}; use image::ImageReader; use ratatui::layout::Rect; use tokio::{io::AsyncWriteExt, process::{Child, Command}, sync::mpsc::{self, UnboundedSender}}; use tracing::{debug, warn}; use yazi_config::YAZI; use yazi_shared::{LOG_LEVEL, RoCell, env_exists}; use crate::{Adapter, Dimension}; type Cmd = Option<(PathBuf, Rect)>; static DEMON: RoCell<Option<UnboundedSender<Cmd>>> = RoCell::new(); pub(crate) struct Ueberzug; impl Ueberzug { pub(crate) fn start(adapter: Adapter) { if !adapter.needs_ueberzug() { return DEMON.init(None); } let mut child = Self::create_demon(adapter).ok(); let (tx, mut rx) = mpsc::unbounded_channel(); tokio::spawn(async move { while let Some(cmd) = rx.recv().await { let exit = child.as_mut().and_then(|c| c.try_wait().ok()); if exit != Some(None) { child = None; } if child.is_none() { child = Self::create_demon(adapter).ok(); } if let Some(c) = &mut child { Self::send_command(adapter, c, cmd).await.ok(); } } }); DEMON.init(Some(tx)) } pub(crate) async fn image_show(path: PathBuf, max: Rect) -> Result<Rect> { let Some(tx) = &*DEMON else { bail!("uninitialized ueberzugpp"); }; let (w, h, path) = tokio::task::spawn_blocking(move || { ImageReader::open(&path)?.with_guessed_format()?.into_dimensions().map(|(w, h)| (w, h, path)) }) .await??; let area = Dimension::cell_size() .map(|(cw, ch)| Rect { x: max.x, y: max.y, width: max.width.min((w.min(YAZI.preview.max_width as _) as f64 / cw).ceil() as _), height: max.height.min((h.min(YAZI.preview.max_height as _) as f64 / ch).ceil() as _), }) .unwrap_or(max); tx.send(Some((path, area)))?; Adapter::shown_store(area); Ok(area) } pub(crate) fn image_erase(_: Rect) -> Result<()> { if let Some(tx) = &*DEMON { Ok(tx.send(None)?) } else { bail!("uninitialized ueberzugpp"); } } // Currently Überzug++'s Wayland output only supports Sway, Hyprland and Wayfire // as it requires information from specific compositor socket directly. // These environment variables are from ueberzugpp src/canvas/wayland/config.cpp pub(crate) fn supported_compositor() -> bool { env_exists("SWAYSOCK") || env_exists("HYPRLAND_INSTANCE_SIGNATURE") || env_exists("WAYFIRE_SOCKET") } fn create_demon(adapter: Adapter) -> Result<Child> { let result = Command::new("ueberzugpp") .args(["layer", "-so", &adapter.to_string()]) .env("SPDLOG_LEVEL", if LOG_LEVEL.get().is_none() { "" } else { "debug" }) .kill_on_drop(true) .stdin(Stdio::piped()) .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn(); if let Err(ref e) = result { warn!("Failed to start ueberzugpp: {e}"); } Ok(result?) } fn adjust_rect(mut rect: Rect) -> Rect { let scale = YAZI.preview.ueberzug_scale; let (x, y, w, h) = YAZI.preview.ueberzug_offset; rect.x = 0f32.max(rect.x as f32 * scale + x) as u16; rect.y = 0f32.max(rect.y as f32 * scale + y) as u16; rect.width = 0f32.max(rect.width as f32 * scale + w) as u16; rect.height = 0f32.max(rect.height as f32 * scale + h) as u16; rect } async fn send_command(adapter: Adapter, child: &mut Child, cmd: Cmd) -> Result<()> { let s = if let Some((path, rect)) = cmd { debug!("ueberzugpp rect before adjustment: {:?}", rect); let rect = Self::adjust_rect(rect); debug!("ueberzugpp rect after adjustment: {:?}", rect); format!( r#"{{"action":"add","identifier":"yazi","x":{},"y":{},"max_width":{},"max_height":{},"path":"{}"}}{}"#, rect.x, rect.y, rect.width, rect.height, path.to_string_lossy(), '\n' ) } else { format!(r#"{{"action":"remove","identifier":"yazi"}}{}"#, '\n') }; debug!("`ueberzugpp layer -so {adapter}` command: {s}"); child.stdin.as_mut().unwrap().write_all(s.as_bytes()).await?; Ok(()) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false