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-config/src/plugin/preloader.rs
yazi-config/src/plugin/preloader.rs
use serde::Deserialize; use yazi_fs::File; use yazi_shared::event::Cmd; use crate::{Pattern, Priority}; #[derive(Debug, Deserialize)] pub struct Preloader { #[serde(skip)] pub idx: u8, pub url: Option<Pattern>, pub mime: Option<Pattern>, pub run: Cmd, #[serde(default)] pub next: bool, #[serde(default)] pub prio: Priority, } impl Preloader { #[inline] pub fn matches(&self, file: &File, mime: &str) -> bool { self.mime.as_ref().is_some_and(|p| p.match_mime(mime)) || self.url.as_ref().is_some_and(|p| p.match_url(&file.url, file.is_dir())) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/plugin/spotter.rs
yazi-config/src/plugin/spotter.rs
use serde::Deserialize; use yazi_fs::File; use yazi_shared::event::Cmd; use crate::Pattern; #[derive(Debug, Deserialize)] pub struct Spotter { pub url: Option<Pattern>, pub mime: Option<Pattern>, pub run: Cmd, } impl Spotter { #[inline] pub fn matches(&self, file: &File, mime: &str) -> bool { self.mime.as_ref().is_some_and(|p| p.match_mime(mime)) || self.url.as_ref().is_some_and(|p| p.match_url(&file.url, file.is_dir())) } #[inline] pub fn any_file(&self) -> bool { self.url.as_ref().is_some_and(|p| p.any_file()) } #[inline] pub fn any_dir(&self) -> bool { self.url.as_ref().is_some_and(|p| p.any_dir()) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/plugin/plugin.rs
yazi-config/src/plugin/plugin.rs
use anyhow::Result; use hashbrown::HashSet; use serde::Deserialize; use tracing::warn; use yazi_codegen::DeserializeOver2; use yazi_fs::File; use super::{Fetcher, Preloader, Previewer, Spotter}; use crate::{Preset, plugin::MAX_PREWORKERS}; #[derive(Default, Deserialize, DeserializeOver2)] pub struct Plugin { pub fetchers: Vec<Fetcher>, #[serde(default)] prepend_fetchers: Vec<Fetcher>, #[serde(default)] append_fetchers: Vec<Fetcher>, pub spotters: Vec<Spotter>, #[serde(default)] prepend_spotters: Vec<Spotter>, #[serde(default)] append_spotters: Vec<Spotter>, pub preloaders: Vec<Preloader>, #[serde(default)] prepend_preloaders: Vec<Preloader>, #[serde(default)] append_preloaders: Vec<Preloader>, pub previewers: Vec<Previewer>, #[serde(default)] prepend_previewers: Vec<Previewer>, #[serde(default)] append_previewers: Vec<Previewer>, } impl Plugin { pub fn fetchers<'a, 'b: 'a>( &'b self, file: &'a File, mime: &'a str, ) -> impl Iterator<Item = &'b Fetcher> + 'a { let mut seen = HashSet::new(); self.fetchers.iter().filter(move |&f| { if seen.contains(&f.id) || !f.matches(file, mime) { return false; } seen.insert(&f.id); true }) } pub fn mime_fetchers(&self, files: Vec<File>) -> impl Iterator<Item = (&Fetcher, Vec<File>)> { let mut tasks: [Vec<_>; MAX_PREWORKERS as usize] = Default::default(); for f in files { let found = self.fetchers.iter().find(|&g| g.id == "mime" && g.matches(&f, "")); if let Some(g) = found { tasks[g.idx as usize].push(f); } else { warn!("No mime fetcher for {f:?}"); } } tasks.into_iter().enumerate().filter_map(|(i, tasks)| { if tasks.is_empty() { None } else { Some((&self.fetchers[i], tasks)) } }) } pub fn spotter(&self, file: &File, mime: &str) -> Option<&Spotter> { self.spotters.iter().find(|&p| p.matches(file, mime)) } pub fn preloaders<'a, 'b: 'a>( &'b self, file: &'a File, mime: &'a str, ) -> impl Iterator<Item = &'b Preloader> + 'a { let mut next = true; self.preloaders.iter().filter(move |&p| { if !next || !p.matches(file, mime) { return false; } next = p.next; true }) } pub fn previewer(&self, file: &File, mime: &str) -> Option<&Previewer> { self.previewers.iter().find(|&p| p.matches(file, mime)) } } impl Plugin { // TODO: remove .retain() and .collect() pub(crate) fn reshape(mut self) -> Result<Self> { if self.append_spotters.iter().any(|r| r.any_file()) { self.spotters.retain(|r| !r.any_file()); } if self.append_spotters.iter().any(|r| r.any_dir()) { self.spotters.retain(|r| !r.any_dir()); } if self.append_previewers.iter().any(|r| r.any_file()) { self.previewers.retain(|r| !r.any_file()); } if self.append_previewers.iter().any(|r| r.any_dir()) { self.previewers.retain(|r| !r.any_dir()); } self.fetchers = Preset::mix(self.prepend_fetchers, self.fetchers, self.append_fetchers).collect(); self.spotters = Preset::mix(self.prepend_spotters, self.spotters, self.append_spotters).collect(); self.preloaders = Preset::mix(self.prepend_preloaders, self.preloaders, self.append_preloaders).collect(); self.previewers = Preset::mix(self.prepend_previewers, self.previewers, self.append_previewers).collect(); if self.fetchers.len() + self.preloaders.len() > MAX_PREWORKERS as usize { panic!("Fetchers and preloaders exceed the limit of {MAX_PREWORKERS}"); } for (i, p) in self.fetchers.iter_mut().enumerate() { p.idx = i as u8; } for (i, p) in self.preloaders.iter_mut().enumerate() { p.idx = self.fetchers.len() as u8 + i as u8; } Ok(Self { fetchers: self.fetchers, spotters: self.spotters, preloaders: self.preloaders, previewers: self.previewers, ..Default::default() }) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/preview/mod.rs
yazi-config/src/preview/mod.rs
yazi_macro::mod_flat!(preview wrap);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/preview/wrap.rs
yazi-config/src/preview/wrap.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "kebab-case")] pub enum PreviewWrap { No, Yes, }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/preview/preview.rs
yazi-config/src/preview/preview.rs
use std::{borrow::Cow, path::PathBuf}; use anyhow::{Context, Result, bail}; use serde::{Deserialize, Serialize}; use yazi_codegen::DeserializeOver2; use yazi_fs::Xdg; use yazi_shared::{SStr, timestamp_us}; use super::PreviewWrap; use crate::normalize_path; #[rustfmt::skip] const TABS: &[&str] = &["", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "]; #[derive(Debug, Deserialize, DeserializeOver2, Serialize)] pub struct Preview { pub wrap: PreviewWrap, pub tab_size: u8, pub max_width: u16, pub max_height: u16, pub cache_dir: PathBuf, pub image_delay: u8, pub image_filter: String, pub image_quality: u8, pub ueberzug_scale: f32, pub ueberzug_offset: (f32, f32, f32, f32), } impl Preview { pub fn tmpfile(&self, prefix: &str) -> PathBuf { self.cache_dir.join(format!("{prefix}-{}", timestamp_us())) } pub fn indent(&self) -> SStr { Self::indent_with(self.tab_size as usize) } pub fn indent_with(n: usize) -> SStr { if let Some(s) = TABS.get(n) { Cow::Borrowed(s) } else { Cow::Owned(" ".repeat(n)) } } } impl Preview { pub(crate) fn reshape(mut self) -> Result<Self> { if self.image_delay > 100 { bail!("[preview].image_delay must be between 0 and 100."); } else if self.image_quality < 50 || self.image_quality > 90 { bail!("[preview].image_quality must be between 50 and 90."); } self.cache_dir = if self.cache_dir.as_os_str().is_empty() { Xdg::cache_dir().to_owned() } else if let Some(p) = normalize_path(self.cache_dir) { p } else { bail!("[preview].cache_dir must be either empty or an absolute path."); }; std::fs::create_dir_all(&self.cache_dir) .context(format!("Failed to create cache directory: {}", self.cache_dir.display()))?; Ok(self) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/mgr/mgr.rs
yazi-config/src/mgr/mgr.rs
use anyhow::{Result, bail}; use serde::Deserialize; use yazi_codegen::DeserializeOver2; use yazi_fs::{CWD, SortBy}; use yazi_shared::{SyncCell, url::UrlLike}; use super::{MgrRatio, MouseEvents}; #[derive(Debug, Deserialize, DeserializeOver2)] pub struct Mgr { pub ratio: SyncCell<MgrRatio>, // Sorting pub sort_by: SyncCell<SortBy>, pub sort_sensitive: SyncCell<bool>, pub sort_reverse: SyncCell<bool>, pub sort_dir_first: SyncCell<bool>, pub sort_translit: SyncCell<bool>, // Display pub linemode: String, pub show_hidden: SyncCell<bool>, pub show_symlink: SyncCell<bool>, pub scrolloff: SyncCell<u8>, pub mouse_events: SyncCell<MouseEvents>, pub title_format: String, } impl Mgr { pub fn title(&self) -> Option<String> { if self.title_format.is_empty() { return None; } let home = dirs::home_dir().unwrap_or_default(); let cwd = if let Ok(p) = CWD.load().try_strip_prefix(home) { format!("~{}{}", std::path::MAIN_SEPARATOR, p.display()) } else { format!("{}", CWD.load().display()) }; Some(self.title_format.replace("{cwd}", &cwd)) } pub(crate) fn reshape(self) -> Result<Self> { if self.linemode.is_empty() || self.linemode.len() > 20 { bail!("[mgr].linemode must be between 1 and 20 characters."); } Ok(self) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/mgr/mouse.rs
yazi-config/src/mgr/mouse.rs
use anyhow::{Result, bail}; use bitflags::bitflags; use crossterm::event::MouseEventKind; use serde::{Deserialize, Serialize}; bitflags! { #[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] #[serde(try_from = "Vec<String>", into = "Vec<String>")] pub struct MouseEvents: u8 { const CLICK = 0b00001; const SCROLL = 0b00010; const TOUCH = 0b00100; const MOVE = 0b01000; const DRAG = 0b10000; } } impl MouseEvents { pub const fn draggable(self) -> bool { self.contains(Self::DRAG) } } impl TryFrom<Vec<String>> for MouseEvents { type Error = anyhow::Error; fn try_from(value: Vec<String>) -> Result<Self, Self::Error> { value.into_iter().try_fold(Self::empty(), |aac, s| { Ok(match s.as_str() { "click" => aac | Self::CLICK, "scroll" => aac | Self::SCROLL, "touch" => aac | Self::TOUCH, "move" => aac | Self::MOVE, "drag" => aac | Self::DRAG, _ => bail!("Invalid mouse event: {s}"), }) }) } } impl From<MouseEvents> for Vec<String> { fn from(value: MouseEvents) -> Self { let events = [ (MouseEvents::CLICK, "click"), (MouseEvents::SCROLL, "scroll"), (MouseEvents::TOUCH, "touch"), (MouseEvents::MOVE, "move"), (MouseEvents::DRAG, "drag"), ]; events.into_iter().filter(|v| value.contains(v.0)).map(|v| v.1.to_owned()).collect() } } impl From<crossterm::event::MouseEventKind> for MouseEvents { fn from(value: crossterm::event::MouseEventKind) -> Self { match value { MouseEventKind::Down(_) | MouseEventKind::Up(_) => Self::CLICK, MouseEventKind::ScrollDown | MouseEventKind::ScrollUp => Self::SCROLL, MouseEventKind::ScrollLeft | MouseEventKind::ScrollRight => Self::TOUCH, MouseEventKind::Moved => Self::MOVE, MouseEventKind::Drag(_) => Self::DRAG, } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/mgr/mod.rs
yazi-config/src/mgr/mod.rs
yazi_macro::mod_flat!(mgr mouse ratio);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/mgr/ratio.rs
yazi-config/src/mgr/ratio.rs
use anyhow::bail; use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] #[serde(try_from = "[u16; 3]")] pub struct MgrRatio { pub parent: u16, pub current: u16, pub preview: u16, pub all: u16, } impl TryFrom<[u16; 3]> for MgrRatio { type Error = anyhow::Error; fn try_from(ratio: [u16; 3]) -> Result<Self, Self::Error> { if ratio.len() != 3 { bail!("invalid layout ratio: {:?}", ratio); } if ratio.iter().all(|&r| r == 0) { bail!("at least one layout ratio must be non-zero: {:?}", ratio); } Ok(Self { parent: ratio[0], current: ratio[1], preview: ratio[2], all: ratio[0] + ratio[1] + ratio[2], }) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/popup/offset.rs
yazi-config/src/popup/offset.rs
use anyhow::bail; use serde::Deserialize; #[derive(Clone, Copy, Debug, Default, Deserialize)] #[serde(try_from = "[i16; 4]")] pub struct Offset { pub x: i16, pub y: i16, pub width: u16, pub height: u16, } impl TryFrom<[i16; 4]> for Offset { type Error = anyhow::Error; fn try_from(values: [i16; 4]) -> Result<Self, Self::Error> { if values.len() != 4 { bail!("offset must have 4 values: {:?}", values); } if values[2] < 0 || values[3] < 0 { bail!("offset width and height must be positive: {:?}", values); } if values[3] < 3 { bail!("offset height must be at least 3: {:?}", values); } Ok(Self { x: values[0], y: values[1], width: values[2] as u16, height: values[3] as u16, }) } } impl Offset { #[inline] pub fn line() -> Self { Self { x: 0, y: 0, width: u16::MAX, height: 1 } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/popup/pick.rs
yazi-config/src/popup/pick.rs
use serde::Deserialize; use yazi_codegen::DeserializeOver2; use super::{Offset, Origin}; #[derive(Deserialize, DeserializeOver2)] pub struct Pick { // open pub open_title: String, pub open_origin: Origin, pub open_offset: Offset, } impl Pick { pub const fn border(&self) -> u16 { 2 } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/popup/options.rs
yazi-config/src/popup/options.rs
use ratatui::{text::{Line, Text}, widgets::{Paragraph, Wrap}}; use yazi_shared::{scheme::Encode as EncodeScheme, strand::ToStrand, url::{Url, UrlBuf}}; use super::{Offset, Position}; use crate::YAZI; #[derive(Debug, Default)] pub struct InputCfg { pub title: String, pub value: String, pub cursor: Option<usize>, pub obscure: bool, pub position: Position, pub realtime: bool, pub completion: bool, } #[derive(Debug, Default)] pub struct PickCfg { pub title: String, pub items: Vec<String>, pub position: Position, } #[derive(Debug, Default)] pub struct ConfirmCfg { pub position: Position, pub title: Line<'static>, pub body: Paragraph<'static>, pub list: Paragraph<'static>, } impl InputCfg { pub fn cd(cwd: Url) -> Self { Self { title: YAZI.input.cd_title.clone(), value: if cwd.kind().is_local() { String::new() } else { EncodeScheme(cwd).to_string() }, position: Position::new(YAZI.input.cd_origin, YAZI.input.cd_offset), completion: true, ..Default::default() } } pub fn create(dir: bool) -> Self { Self { title: YAZI.input.create_title[dir as usize].clone(), position: Position::new(YAZI.input.create_origin, YAZI.input.create_offset), ..Default::default() } } pub fn rename() -> Self { Self { title: YAZI.input.rename_title.clone(), position: Position::new(YAZI.input.rename_origin, YAZI.input.rename_offset), ..Default::default() } } pub fn filter() -> Self { Self { title: YAZI.input.filter_title.clone(), position: Position::new(YAZI.input.filter_origin, YAZI.input.filter_offset), realtime: true, ..Default::default() } } pub fn find(prev: bool) -> Self { Self { title: YAZI.input.find_title[prev as usize].clone(), position: Position::new(YAZI.input.find_origin, YAZI.input.find_offset), realtime: true, ..Default::default() } } pub fn search(name: &str) -> Self { Self { title: YAZI.input.search_title.replace("{n}", name), position: Position::new(YAZI.input.search_origin, YAZI.input.search_offset), ..Default::default() } } pub fn shell(block: bool) -> Self { Self { title: YAZI.input.shell_title[block as usize].clone(), position: Position::new(YAZI.input.shell_origin, YAZI.input.shell_offset), ..Default::default() } } #[inline] pub fn with_value(mut self, value: impl Into<String>) -> Self { self.value = value.into(); self } #[inline] pub fn with_cursor(mut self, cursor: Option<usize>) -> Self { self.cursor = cursor; self } } impl ConfirmCfg { fn new( title: String, position: Position, body: Option<Text<'static>>, list: Option<Text<'static>>, ) -> Self { Self { position, title: Line::raw(title), body: body.map(|b| Paragraph::new(b).wrap(Wrap { trim: false })).unwrap_or_default(), list: list.map(|l| Paragraph::new(l).wrap(Wrap { trim: false })).unwrap_or_default(), } } pub fn trash(urls: &[yazi_shared::url::UrlBuf]) -> Self { Self::new( Self::replace_number(&YAZI.confirm.trash_title, urls.len()), YAZI.confirm.trash_position(), None, Self::truncate_list(urls, urls.len(), 100), ) } pub fn delete(urls: &[yazi_shared::url::UrlBuf]) -> Self { Self::new( Self::replace_number(&YAZI.confirm.delete_title, urls.len()), YAZI.confirm.delete_position(), None, Self::truncate_list(urls, urls.len(), 100), ) } pub fn overwrite(url: &UrlBuf) -> Self { Self::new( YAZI.confirm.overwrite_title.clone(), YAZI.confirm.overwrite_position(), Some(Text::raw(&YAZI.confirm.overwrite_body)), Some(url.to_strand().into_string_lossy().into()), ) } pub fn quit(len: usize, names: Vec<String>) -> Self { Self::new( Self::replace_number(&YAZI.confirm.quit_title, len), YAZI.confirm.quit_position(), Some(Text::raw(&YAZI.confirm.quit_body)), Self::truncate_list(names, len, 10), ) } fn replace_number(tpl: &str, n: usize) -> String { tpl.replace("{n}", &n.to_string()).replace("{s}", if n > 1 { "s" } else { "" }) } fn truncate_list<I>(it: I, len: usize, max: usize) -> Option<Text<'static>> where I: IntoIterator, I::Item: ToStrand, { let mut lines = Vec::with_capacity(len.min(max + 1)); for (i, s) in it.into_iter().enumerate() { if i >= max { lines.push(format!("... and {} more", len - max)); break; } lines.push(s.to_strand().into_string_lossy()); } Some(Text::from_iter(lines)) } } impl PickCfg { fn max_height(len: usize) -> u16 { YAZI.pick.open_offset.height.min(YAZI.pick.border().saturating_add(len as u16)) } pub fn open(items: Vec<String>) -> Self { let max_height = Self::max_height(items.len()); Self { title: YAZI.pick.open_title.clone(), items, position: Position::new(YAZI.pick.open_origin, Offset { height: max_height, ..YAZI.pick.open_offset }), } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/popup/mod.rs
yazi-config/src/popup/mod.rs
yazi_macro::mod_flat!(confirm input offset options origin pick position);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/popup/origin.rs
yazi-config/src/popup/origin.rs
use std::{fmt::Display, str::FromStr}; use serde::Deserialize; #[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)] #[serde(rename_all = "kebab-case")] pub enum Origin { #[default] TopLeft, TopCenter, TopRight, BottomLeft, BottomCenter, BottomRight, Center, Hovered, } impl Display for Origin { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(match self { Self::TopLeft => "top-left", Self::TopCenter => "top-center", Self::TopRight => "top-right", Self::BottomLeft => "bottom-left", Self::BottomCenter => "bottom-center", Self::BottomRight => "bottom-right", Self::Center => "center", Self::Hovered => "hovered", }) } } impl FromStr for Origin { type Err = serde::de::value::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { Self::deserialize(serde::de::value::StrDeserializer::new(s)) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/popup/position.rs
yazi-config/src/popup/position.rs
use crossterm::terminal::WindowSize; use ratatui::layout::Rect; use super::{Offset, Origin}; #[derive(Clone, Copy, Debug, Default)] pub struct Position { pub origin: Origin, pub offset: Offset, } impl Position { pub const fn new(origin: Origin, offset: Offset) -> Self { Self { origin, offset } } pub fn rect(&self, WindowSize { columns, rows, .. }: WindowSize) -> Rect { use Origin::*; let Offset { x, y, width, height } = self.offset; let max_x = columns.saturating_sub(width); let new_x = match self.origin { TopLeft | BottomLeft => x.clamp(0, max_x as i16) as u16, TopCenter | BottomCenter | Center => { (columns / 2).saturating_sub(width / 2).saturating_add_signed(x).clamp(0, max_x) } TopRight | BottomRight => max_x.saturating_add_signed(x).clamp(0, max_x), Hovered => unreachable!(), }; let max_y = rows.saturating_sub(height); let new_y = match self.origin { TopLeft | TopCenter | TopRight => y.clamp(0, max_y as i16) as u16, Center => (rows / 2).saturating_sub(height / 2).saturating_add_signed(y).clamp(0, max_y), BottomLeft | BottomCenter | BottomRight => max_y.saturating_add_signed(y).clamp(0, max_y), Hovered => unreachable!(), }; Rect { x: new_x, y: new_y, width: width.min(columns.saturating_sub(new_x)), height: height.min(rows.saturating_sub(new_y)), } } pub fn sticky(WindowSize { columns, rows, .. }: WindowSize, base: Rect, offset: Offset) -> Rect { let Offset { x, y, width, height } = offset; let above = base.y.saturating_add(base.height).saturating_add(height).saturating_add_signed(y) > rows; let new_x = base.x.saturating_add_signed(x).clamp(0, columns.saturating_sub(width)); let new_y = if above { base.y.saturating_sub(height.saturating_sub(y.unsigned_abs())) } else { base.y.saturating_add(base.height).saturating_add_signed(y) }; Rect { x: new_x, y: new_y, width: width.min(columns.saturating_sub(new_x)), height: height.min(rows.saturating_sub(new_y)), } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/popup/confirm.rs
yazi-config/src/popup/confirm.rs
use serde::Deserialize; use yazi_codegen::DeserializeOver2; use super::{Offset, Origin}; use crate::popup::Position; #[derive(Deserialize, DeserializeOver2)] pub struct Confirm { // trash pub trash_title: String, pub trash_origin: Origin, pub trash_offset: Offset, // delete pub delete_title: String, pub delete_origin: Origin, pub delete_offset: Offset, // overwrite pub overwrite_title: String, pub overwrite_body: String, pub overwrite_origin: Origin, pub overwrite_offset: Offset, // quit pub quit_title: String, pub quit_body: String, pub quit_origin: Origin, pub quit_offset: Offset, } impl Confirm { pub const fn border(&self) -> u16 { 2 } pub const fn trash_position(&self) -> Position { Position::new(self.trash_origin, self.trash_offset) } pub const fn delete_position(&self) -> Position { Position::new(self.delete_origin, self.delete_offset) } pub const fn overwrite_position(&self) -> Position { Position::new(self.overwrite_origin, self.overwrite_offset) } pub const fn quit_position(&self) -> Position { Position::new(self.quit_origin, self.quit_offset) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/popup/input.rs
yazi-config/src/popup/input.rs
use serde::Deserialize; use yazi_codegen::DeserializeOver2; use super::{Offset, Origin}; #[derive(Deserialize, DeserializeOver2)] pub struct Input { pub cursor_blink: bool, // cd pub cd_title: String, pub cd_origin: Origin, pub cd_offset: Offset, // create pub create_title: [String; 2], pub create_origin: Origin, pub create_offset: Offset, // rename pub rename_title: String, pub rename_origin: Origin, pub rename_offset: Offset, // filter pub filter_title: String, pub filter_origin: Origin, pub filter_offset: Offset, // find pub find_title: [String; 2], pub find_origin: Origin, pub find_offset: Offset, // search pub search_title: String, pub search_origin: Origin, pub search_offset: Offset, // shell pub shell_title: [String; 2], pub shell_origin: Origin, pub shell_offset: Offset, } impl Input { pub const fn border(&self) -> u16 { 2 } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/keymap/key.rs
yazi-config/src/keymap/key.rs
use std::{fmt::{Display, Write}, str::FromStr}; use anyhow::bail; use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct Key { pub code: KeyCode, pub shift: bool, pub ctrl: bool, pub alt: bool, pub super_: bool, } impl Key { #[inline] pub fn plain(&self) -> Option<char> { match self.code { KeyCode::Char(c) if !self.ctrl && !self.alt && !self.super_ => Some(c), _ => None, } } } impl Default for Key { fn default() -> Self { Self { code: KeyCode::Null, shift: false, ctrl: false, alt: false, super_: false } } } impl From<KeyEvent> for Key { fn from(value: KeyEvent) -> Self { // For alphabet: // Unix : <S-a> => Char("A") + SHIFT // Windows : <S-a> => Char("A") + SHIFT // // For non-alphabet: // Unix : <S-`> => Char("~") + NULL // Windows : <S-`> => Char("~") + SHIFT // // So we detect `Char("~") + SHIFT`, and change it to `Char("~") + NULL` // for consistent behavior between OSs. let shift = match (value.code, value.modifiers) { (KeyCode::Char(c), _) => c.is_ascii_uppercase(), (KeyCode::BackTab, _) => false, (_, m) => m.contains(KeyModifiers::SHIFT), }; Self { code: value.code, shift, ctrl: value.modifiers.contains(KeyModifiers::CONTROL), alt: value.modifiers.contains(KeyModifiers::ALT), super_: value.modifiers.contains(KeyModifiers::SUPER), } } } impl FromStr for Key { type Err = anyhow::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { if s.is_empty() { bail!("empty key") } let mut key = Self::default(); if !s.starts_with('<') || !s.ends_with('>') { key.code = KeyCode::Char(s.chars().next().unwrap()); key.shift = matches!(key.code, KeyCode::Char(c) if c.is_ascii_uppercase()); return Ok(key); } let mut it = s[1..s.len() - 1].split_inclusive('-').peekable(); while let Some(next) = it.next() { match next.to_ascii_lowercase().as_str() { "s-" => key.shift = true, "c-" => key.ctrl = true, "a-" => key.alt = true, "d-" => key.super_ = true, "space" => key.code = KeyCode::Char(' '), "backspace" => key.code = KeyCode::Backspace, "enter" => key.code = KeyCode::Enter, "left" => key.code = KeyCode::Left, "right" => key.code = KeyCode::Right, "up" => key.code = KeyCode::Up, "down" => key.code = KeyCode::Down, "home" => key.code = KeyCode::Home, "end" => key.code = KeyCode::End, "pageup" => key.code = KeyCode::PageUp, "pagedown" => key.code = KeyCode::PageDown, "tab" => key.code = KeyCode::Tab, "backtab" => key.code = KeyCode::BackTab, "delete" => key.code = KeyCode::Delete, "insert" => key.code = KeyCode::Insert, "f1" => key.code = KeyCode::F(1), "f2" => key.code = KeyCode::F(2), "f3" => key.code = KeyCode::F(3), "f4" => key.code = KeyCode::F(4), "f5" => key.code = KeyCode::F(5), "f6" => key.code = KeyCode::F(6), "f7" => key.code = KeyCode::F(7), "f8" => key.code = KeyCode::F(8), "f9" => key.code = KeyCode::F(9), "f10" => key.code = KeyCode::F(10), "f11" => key.code = KeyCode::F(11), "f12" => key.code = KeyCode::F(12), "f13" => key.code = KeyCode::F(13), "f14" => key.code = KeyCode::F(14), "f15" => key.code = KeyCode::F(15), "f16" => key.code = KeyCode::F(16), "f17" => key.code = KeyCode::F(17), "f18" => key.code = KeyCode::F(18), "f19" => key.code = KeyCode::F(19), "esc" => key.code = KeyCode::Esc, _ => match next { s if it.peek().is_none() => { let c = s.chars().next().unwrap(); key.shift |= c.is_ascii_uppercase(); key.code = KeyCode::Char(if key.shift { c.to_ascii_uppercase() } else { c }); } s => bail!("unknown key: {s}"), }, } } if key.code == KeyCode::Null { bail!("empty key") } Ok(key) } } impl Display for Key { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if let Some(c) = self.plain() { return if c == ' ' { write!(f, "<Space>") } else { f.write_char(c) }; } write!(f, "<")?; if self.super_ { write!(f, "D-")?; } if self.ctrl { write!(f, "C-")?; } if self.alt { write!(f, "A-")?; } if self.shift && !matches!(self.code, KeyCode::Char(_)) { write!(f, "S-")?; } let code = match self.code { KeyCode::Backspace => "Backspace", KeyCode::Enter => "Enter", KeyCode::Left => "Left", KeyCode::Right => "Right", KeyCode::Up => "Up", KeyCode::Down => "Down", KeyCode::Home => "Home", KeyCode::End => "End", KeyCode::PageUp => "PageUp", KeyCode::PageDown => "PageDown", KeyCode::Tab => "Tab", KeyCode::BackTab => "BackTab", KeyCode::Delete => "Delete", KeyCode::Insert => "Insert", KeyCode::F(1) => "F1", KeyCode::F(2) => "F2", KeyCode::F(3) => "F3", KeyCode::F(4) => "F4", KeyCode::F(5) => "F5", KeyCode::F(6) => "F6", KeyCode::F(7) => "F7", KeyCode::F(8) => "F8", KeyCode::F(9) => "F9", KeyCode::F(10) => "F10", KeyCode::F(11) => "F11", KeyCode::F(12) => "F12", KeyCode::F(13) => "F13", KeyCode::F(14) => "F14", KeyCode::F(15) => "F15", KeyCode::F(16) => "F16", KeyCode::F(17) => "F17", KeyCode::F(18) => "F18", KeyCode::F(19) => "F19", KeyCode::Esc => "Esc", KeyCode::Char(' ') => "Space", KeyCode::Char(c) => { f.write_char(c)?; "" } _ => "Unknown", }; write!(f, "{code}>") } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/keymap/deserializers.rs
yazi-config/src/keymap/deserializers.rs
use std::{fmt, str::FromStr}; use anyhow::Result; use serde::{Deserializer, de::{self, Visitor}}; use yazi_shared::event::Cmd; use crate::keymap::Key; pub(super) fn deserialize_on<'de, D>(deserializer: D) -> Result<Vec<Key>, D::Error> where D: Deserializer<'de>, { struct OnVisitor; impl<'de> Visitor<'de> for OnVisitor { type Value = Vec<Key>; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a `on` string or array of strings within keymap.toml") } fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: de::SeqAccess<'de>, { let mut cmds = Vec::with_capacity(seq.size_hint().unwrap_or(0)); while let Some(value) = &seq.next_element::<String>()? { cmds.push(Key::from_str(value).map_err(de::Error::custom)?); } if cmds.is_empty() { return Err(de::Error::custom("`on` within keymap.toml cannot be empty")); } Ok(cmds) } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { Ok(vec![Key::from_str(value).map_err(de::Error::custom)?]) } } deserializer.deserialize_any(OnVisitor) } pub(super) fn deserialize_run<'de, D>(deserializer: D) -> Result<Vec<Cmd>, D::Error> where D: Deserializer<'de>, { struct RunVisitor; impl<'de> Visitor<'de> for RunVisitor { type Value = Vec<Cmd>; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a `run` string or array of strings within keymap.toml") } fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: de::SeqAccess<'de>, { let mut cmds = Vec::with_capacity(seq.size_hint().unwrap_or(0)); while let Some(value) = &seq.next_element::<String>()? { cmds.push(Cmd::from_str(value).map_err(de::Error::custom)?); } if cmds.is_empty() { return Err(de::Error::custom("`run` within keymap.toml cannot be empty")); } Ok(cmds) } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { Ok(vec![Cmd::from_str(value).map_err(de::Error::custom)?]) } } deserializer.deserialize_any(RunVisitor) }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/keymap/mod.rs
yazi-config/src/keymap/mod.rs
yazi_macro::mod_flat!(chord cow deserializers key keymap rules);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/keymap/chord.rs
yazi-config/src/keymap/chord.rs
use std::{borrow::Cow, hash::{Hash, Hasher}, sync::OnceLock}; use anyhow::Result; use regex::Regex; use serde::Deserialize; use yazi_shared::{Layer, Source, event::Cmd}; use super::Key; static RE: OnceLock<Regex> = OnceLock::new(); #[derive(Debug, Default, Deserialize)] pub struct Chord { #[serde(deserialize_with = "super::deserialize_on")] pub on: Vec<Key>, #[serde(deserialize_with = "super::deserialize_run")] pub run: Vec<Cmd>, pub desc: Option<String>, pub r#for: Option<String>, } impl PartialEq for Chord { fn eq(&self, other: &Self) -> bool { self.on == other.on } } impl Eq for Chord {} impl Hash for Chord { fn hash<H: Hasher>(&self, state: &mut H) { self.on.hash(state) } } impl Chord { pub fn on(&self) -> String { self.on.iter().map(ToString::to_string).collect() } pub fn run(&self) -> String { RE.get_or_init(|| Regex::new(r"\s+").unwrap()) .replace_all(&self.run.iter().map(|c| c.to_string()).collect::<Vec<_>>().join("; "), " ") .into_owned() } pub fn desc(&self) -> Option<Cow<'_, str>> { self.desc.as_ref().map(|s| RE.get_or_init(|| Regex::new(r"\s+").unwrap()).replace_all(s, " ")) } pub fn desc_or_run(&self) -> Cow<'_, str> { self.desc().unwrap_or_else(|| self.run().into()) } pub fn contains(&self, s: &str) -> bool { let s = s.to_lowercase(); self.desc().map(|d| d.to_lowercase().contains(&s)) == Some(true) || self.run().to_lowercase().contains(&s) || self.on().to_lowercase().contains(&s) } #[inline] pub(super) fn noop(&self) -> bool { self.run.len() == 1 && self.run[0].name == "noop" && self.run[0].args.is_empty() } } impl Chord { pub(super) fn reshape(mut self, layer: Layer) -> Result<Self> { for cmd in &mut self.run { cmd.source = Source::Key; if cmd.layer == Default::default() { cmd.layer = layer; } } Ok(self) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/keymap/keymap.rs
yazi-config/src/keymap/keymap.rs
use anyhow::{Context, Result}; use serde::Deserialize; use yazi_codegen::DeserializeOver1; use yazi_fs::{Xdg, ok_or_not_found}; use yazi_shared::Layer; use super::{Chord, KeymapRules}; #[derive(Deserialize, DeserializeOver1)] pub struct Keymap { pub mgr: KeymapRules, pub tasks: KeymapRules, pub spot: KeymapRules, pub pick: KeymapRules, pub input: KeymapRules, pub confirm: KeymapRules, pub help: KeymapRules, pub cmp: KeymapRules, } impl Keymap { pub fn get(&self, layer: Layer) -> &[Chord] { match layer { Layer::App => &[], Layer::Mgr => &self.mgr, Layer::Tasks => &self.tasks, Layer::Spot => &self.spot, Layer::Pick => &self.pick, Layer::Input => &self.input, Layer::Confirm => &self.confirm, Layer::Help => &self.help, Layer::Cmp => &self.cmp, Layer::Which => &[], } } } impl Keymap { pub(crate) fn read() -> Result<String> { let p = Xdg::config_dir().join("keymap.toml"); ok_or_not_found(std::fs::read_to_string(&p)) .with_context(|| format!("Failed to read keymap {p:?}")) } pub(crate) fn reshape(self) -> Result<Self> { Ok(Self { mgr: self.mgr.reshape(Layer::Mgr)?, tasks: self.tasks.reshape(Layer::Tasks)?, spot: self.spot.reshape(Layer::Spot)?, pick: self.pick.reshape(Layer::Pick)?, input: self.input.reshape(Layer::Input)?, confirm: self.confirm.reshape(Layer::Confirm)?, help: self.help.reshape(Layer::Help)?, cmp: self.cmp.reshape(Layer::Cmp)?, }) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/keymap/cow.rs
yazi-config/src/keymap/cow.rs
use std::ops::Deref; use yazi_shared::event::CmdCow; use super::Chord; #[derive(Debug)] pub enum ChordCow { Owned(Chord), Borrowed(&'static Chord), } impl From<Chord> for ChordCow { fn from(c: Chord) -> Self { Self::Owned(c) } } impl From<&'static Chord> for ChordCow { fn from(c: &'static Chord) -> Self { Self::Borrowed(c) } } impl Deref for ChordCow { type Target = Chord; fn deref(&self) -> &Self::Target { match self { Self::Owned(c) => c, Self::Borrowed(c) => c, } } } impl Default for ChordCow { fn default() -> Self { Self::Owned(Chord::default()) } } impl ChordCow { pub fn into_seq(self) -> Vec<CmdCow> { match self { Self::Owned(c) => c.run.into_iter().rev().map(|c| c.into()).collect(), Self::Borrowed(c) => c.run.iter().rev().map(|c| c.into()).collect(), } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/keymap/rules.rs
yazi-config/src/keymap/rules.rs
use std::ops::Deref; use anyhow::Result; use hashbrown::HashSet; use serde::Deserialize; use yazi_codegen::DeserializeOver2; use yazi_shared::Layer; use super::Chord; use crate::{Preset, check_for, keymap::Key}; #[derive(Default, Deserialize, DeserializeOver2)] pub struct KeymapRules { pub keymap: Vec<Chord>, #[serde(default)] prepend_keymap: Vec<Chord>, #[serde(default)] append_keymap: Vec<Chord>, } impl Deref for KeymapRules { type Target = Vec<Chord>; fn deref(&self) -> &Self::Target { &self.keymap } } impl KeymapRules { pub(crate) fn reshape(self, layer: Layer) -> Result<Self> { #[inline] fn on(Chord { on, .. }: &Chord) -> [Key; 2] { [on.first().copied().unwrap_or_default(), on.get(1).copied().unwrap_or_default()] } let a_seen: HashSet<_> = self.prepend_keymap.iter().map(on).collect(); let b_seen: HashSet<_> = self.keymap.iter().map(on).collect(); let keymap = Preset::mix( self.prepend_keymap, self.keymap.into_iter().filter(|v| !a_seen.contains(&on(v))), self.append_keymap.into_iter().filter(|v| !b_seen.contains(&on(v))), ) .map(|mut chord| (chord.r#for.take(), chord)) .filter(|(r#for, chord)| !chord.noop() && check_for(r#for.as_deref())) .map(|(_, chord)| chord.reshape(layer)) .collect::<Result<_>>()?; Ok(Self { keymap, ..Default::default() }) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/theme/icon.rs
yazi-config/src/theme/icon.rs
use std::ops::Deref; use anyhow::Result; use hashbrown::HashMap; use ratatui::style::Color; use serde::{Deserialize, Deserializer}; use yazi_codegen::DeserializeOver2; use yazi_fs::File; use yazi_shared::{Condition, url::UrlLike}; use crate::{Icon as I, Pattern, Style}; #[derive(Default, Deserialize, DeserializeOver2)] pub struct Icon { globs: PatIcons, #[serde(default)] prepend_globs: PatIcons, #[serde(default)] append_globs: PatIcons, dirs: StrIcons, #[serde(default)] prepend_dirs: StrIcons, #[serde(default)] append_dirs: StrIcons, files: StrIcons, #[serde(default)] prepend_files: StrIcons, #[serde(default)] append_files: StrIcons, exts: StrIcons, #[serde(default)] prepend_exts: StrIcons, #[serde(default)] append_exts: StrIcons, conds: CondIcons, #[serde(default)] prepend_conds: CondIcons, #[serde(default)] append_conds: CondIcons, } impl Icon { pub fn matches(&self, file: &File) -> Option<&I> { if let Some(i) = self.match_by_glob(file) { return Some(i); } if let Some(i) = self.match_by_name(file) { return Some(i); } let f = |s: &str| match s { "dir" => file.is_dir(), "hidden" => file.is_hidden(), "link" => file.is_link(), "orphan" => file.is_orphan(), "dummy" => file.is_dummy(), "block" => file.is_block(), "char" => file.is_char(), "fifo" => file.is_fifo(), "sock" => file.is_sock(), "exec" => file.is_exec(), "sticky" => file.is_sticky(), _ => false, }; self.conds.iter().find(|(c, _)| c.eval(f) == Some(true)).map(|(_, i)| i) } fn match_by_glob(&self, file: &File) -> Option<&I> { self.globs.iter().find(|(p, _)| p.match_url(&file.url, file.is_dir())).map(|(_, i)| i) } fn match_by_name(&self, file: &File) -> Option<&I> { let name = file.name()?.to_str().ok()?; if file.is_dir() { self.dirs.get(name).or_else(|| self.dirs.get(&name.to_ascii_lowercase())) } else { self .files .get(name) .or_else(|| self.files.get(&name.to_ascii_lowercase())) .or_else(|| self.match_by_ext(file)) } } fn match_by_ext(&self, file: &File) -> Option<&I> { let ext = file.url.ext()?.to_str().ok()?; self.exts.get(ext).or_else(|| self.exts.get(&ext.to_ascii_lowercase())) } } impl Icon { pub(crate) fn reshape(self) -> Result<Self> { Ok(Self { globs: PatIcons( self.prepend_globs.0.into_iter().chain(self.globs.0).chain(self.append_globs.0).collect(), ), dirs: StrIcons( self.append_dirs.0.into_iter().chain(self.dirs.0).chain(self.prepend_dirs.0).collect(), ), files: StrIcons( self.append_files.0.into_iter().chain(self.files.0).chain(self.prepend_files.0).collect(), ), exts: StrIcons( self.append_exts.0.into_iter().chain(self.exts.0).chain(self.prepend_exts.0).collect(), ), conds: CondIcons( self.prepend_conds.0.into_iter().chain(self.conds.0).chain(self.append_conds.0).collect(), ), ..Default::default() }) } } #[derive(Default)] pub struct PatIcons(Vec<(Pattern, I)>); impl Deref for PatIcons { type Target = Vec<(Pattern, I)>; fn deref(&self) -> &Self::Target { &self.0 } } impl<'de> Deserialize<'de> for PatIcons { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { #[derive(Deserialize)] struct Shadow { url: Pattern, text: String, fg: Option<Color>, } Ok(Self( <Vec<Shadow>>::deserialize(deserializer)? .into_iter() .map(|s| (s.url, I { text: s.text, style: Style { fg: s.fg, ..Default::default() } })) .collect(), )) } } #[derive(Default)] pub struct StrIcons(HashMap<String, I>); impl Deref for StrIcons { type Target = HashMap<String, I>; fn deref(&self) -> &Self::Target { &self.0 } } impl<'de> Deserialize<'de> for StrIcons { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { #[derive(Deserialize)] struct Shadow { name: String, text: String, fg: Option<Color>, } Ok(Self( <Vec<Shadow>>::deserialize(deserializer)? .into_iter() .map(|s| (s.name, I { text: s.text, style: Style { fg: s.fg, ..Default::default() } })) .collect(), )) } } #[derive(Default)] pub struct CondIcons(Vec<(Condition, I)>); impl Deref for CondIcons { type Target = Vec<(Condition, I)>; fn deref(&self) -> &Self::Target { &self.0 } } impl<'de> Deserialize<'de> for CondIcons { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { #[derive(Deserialize)] struct Shadow { r#if: Condition, text: String, fg: Option<Color>, } Ok(Self( <Vec<Shadow>>::deserialize(deserializer)? .into_iter() .map(|s| (s.r#if, I { text: s.text, style: Style { fg: s.fg, ..Default::default() } })) .collect(), )) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/theme/flavor.rs
yazi-config/src/theme/flavor.rs
use std::path::PathBuf; use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use toml::Value; use yazi_codegen::DeserializeOver2; use yazi_fs::Xdg; #[derive(Default, Deserialize, DeserializeOver2, Serialize)] pub struct Flavor { pub dark: String, pub light: String, } impl From<&Value> for Flavor { fn from(value: &Value) -> Self { let mut me = Self::default(); if let Value::Table(t) = value { if let Some(s) = t.get("dark").and_then(|v| v.as_str()) { me.dark = s.to_owned(); } if let Some(s) = t.get("light").and_then(|v| v.as_str()) { me.light = s.to_owned(); } } me } } impl Flavor { pub(crate) fn read(&self, light: bool) -> Result<String> { Ok(match if light { self.light.as_str() } else { self.dark.as_str() } { "" => String::new(), name => { let p = Xdg::config_dir().join(format!("flavors/{name}.yazi/flavor.toml")); std::fs::read_to_string(&p).with_context(|| format!("Failed to read flavor {p:?}"))? } }) } pub(crate) fn syntect_path(&self, light: bool) -> Option<PathBuf> { match if light { self.light.as_str() } else { self.dark.as_str() } { "" => None, name => Some(Xdg::config_dir().join(format!("flavors/{name}.yazi/tmtheme.xml"))), } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/theme/theme.rs
yazi-config/src/theme/theme.rs
use std::path::PathBuf; use anyhow::{Context, Result, anyhow, bail}; use serde::Deserialize; use yazi_codegen::{DeserializeOver1, DeserializeOver2}; use yazi_fs::{Xdg, ok_or_not_found}; use super::{Filetype, Flavor, Icon}; use crate::{Style, normalize_path}; #[derive(Deserialize, DeserializeOver1)] pub struct Theme { pub flavor: Flavor, pub app: App, pub mgr: Mgr, pub tabs: Tabs, pub mode: Mode, pub indicator: Indicator, pub status: Status, pub which: Which, pub confirm: Confirm, pub spot: Spot, pub notify: Notify, pub pick: Pick, pub input: Input, pub cmp: Cmp, pub tasks: Tasks, pub help: Help, // File-specific styles #[serde(skip_serializing)] pub filetype: Filetype, #[serde(skip_serializing)] pub icon: Icon, } #[derive(Deserialize, DeserializeOver2)] pub struct App { pub overall: Style, } #[derive(Deserialize, DeserializeOver2)] pub struct Mgr { pub cwd: Style, // Find pub find_keyword: Style, pub find_position: Style, // Symlink pub symlink_target: Style, // Marker pub marker_copied: Style, pub marker_cut: Style, pub marker_marked: Style, pub marker_selected: Style, // Count pub count_copied: Style, pub count_cut: Style, pub count_selected: Style, // Border pub border_symbol: String, pub border_style: Style, // Highlighting pub syntect_theme: PathBuf, } #[derive(Deserialize, DeserializeOver2)] pub struct Tabs { pub active: Style, pub inactive: Style, pub sep_inner: TabsSep, pub sep_outer: TabsSep, } #[derive(Deserialize, DeserializeOver2)] pub struct TabsSep { pub open: String, pub close: String, } #[derive(Deserialize, DeserializeOver2)] pub struct Mode { pub normal_main: Style, pub normal_alt: Style, pub select_main: Style, pub select_alt: Style, pub unset_main: Style, pub unset_alt: Style, } #[derive(Deserialize, DeserializeOver2)] pub struct Indicator { pub parent: Style, pub current: Style, pub preview: Style, pub padding: IndicatorPadding, } #[derive(Deserialize, DeserializeOver2)] pub struct IndicatorPadding { pub open: String, pub close: String, } #[derive(Deserialize, DeserializeOver2)] pub struct Status { pub overall: Style, pub sep_left: StatusSep, pub sep_right: StatusSep, // Permissions pub perm_sep: Style, pub perm_type: Style, pub perm_read: Style, pub perm_write: Style, pub perm_exec: Style, // Progress pub progress_label: Style, pub progress_normal: Style, pub progress_error: Style, } #[derive(Deserialize, DeserializeOver2)] pub struct StatusSep { pub open: String, pub close: String, } #[derive(Deserialize, DeserializeOver2)] pub struct Which { pub cols: u8, pub mask: Style, pub cand: Style, pub rest: Style, pub desc: Style, pub separator: String, pub separator_style: Style, } #[derive(Deserialize, DeserializeOver2)] pub struct Confirm { pub border: Style, pub title: Style, pub body: Style, pub list: Style, pub btn_yes: Style, pub btn_no: Style, pub btn_labels: [String; 2], } #[derive(Deserialize, DeserializeOver2)] pub struct Spot { pub border: Style, pub title: Style, pub tbl_col: Style, pub tbl_cell: Style, } #[derive(Deserialize, DeserializeOver2)] pub struct Notify { pub title_info: Style, pub title_warn: Style, pub title_error: Style, pub icon_info: String, pub icon_warn: String, pub icon_error: String, } #[derive(Deserialize, DeserializeOver2)] pub struct Pick { pub border: Style, pub active: Style, pub inactive: Style, } #[derive(Deserialize, DeserializeOver2)] pub struct Input { pub border: Style, pub title: Style, pub value: Style, pub selected: Style, } #[derive(Deserialize, DeserializeOver2)] pub struct Cmp { pub border: Style, pub active: Style, pub inactive: Style, pub icon_file: String, pub icon_folder: String, pub icon_command: String, } #[derive(Deserialize, DeserializeOver2)] pub struct Tasks { pub border: Style, pub title: Style, pub hovered: Style, } #[derive(Deserialize, DeserializeOver2)] pub struct Help { pub on: Style, pub run: Style, pub desc: Style, pub hovered: Style, pub footer: Style, } impl Theme { pub(crate) fn read() -> Result<String> { let p = Xdg::config_dir().join("theme.toml"); ok_or_not_found(std::fs::read_to_string(&p)) .with_context(|| format!("Failed to read theme {p:?}")) } pub(crate) fn reshape(mut self, light: bool) -> Result<Self> { if self.which.cols < 1 || self.which.cols > 3 { bail!("[which].cols must be between 1 and 3"); } self.icon = self.icon.reshape()?; self.mgr.syntect_theme = self .flavor .syntect_path(light) .or_else(|| normalize_path(self.mgr.syntect_theme)) .ok_or(anyhow!("[mgr].syntect_theme must be either empty or an absolute path."))?; Ok(self) } } impl App { pub fn bg_color(&self) -> String { self.overall.bg.map(|c| c.to_string()).unwrap_or_default() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/theme/filetype.rs
yazi-config/src/theme/filetype.rs
use std::ops::Deref; use serde::Deserialize; use yazi_codegen::DeserializeOver2; use yazi_fs::File; use super::Is; use crate::{Pattern, Style}; #[derive(Deserialize, DeserializeOver2)] pub struct Filetype { rules: Vec<FiletypeRule>, } impl Deref for Filetype { type Target = Vec<FiletypeRule>; fn deref(&self) -> &Self::Target { &self.rules } } #[derive(Deserialize)] pub struct FiletypeRule { #[serde(default)] is: Is, url: Option<Pattern>, mime: Option<Pattern>, #[serde(flatten)] pub style: Style, } impl FiletypeRule { pub fn matches(&self, file: &File, mime: &str) -> bool { if !self.is.check(&file.cha) { return false; } self.mime.as_ref().is_some_and(|p| p.match_mime(mime)) || self.url.as_ref().is_some_and(|n| n.match_url(&file.url, file.is_dir())) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/theme/mod.rs
yazi-config/src/theme/mod.rs
yazi_macro::mod_flat!(filetype flavor icon is theme);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/theme/is.rs
yazi-config/src/theme/is.rs
use serde::Deserialize; use yazi_fs::cha::Cha; #[derive(Default, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum Is { #[default] None, Hidden, Link, Orphan, Dummy, Block, Char, Fifo, Sock, Exec, Sticky, } impl Is { pub fn check(&self, cha: &Cha) -> bool { match self { Self::None => true, Self::Hidden => cha.is_hidden(), Self::Link => cha.is_link(), Self::Orphan => cha.is_orphan(), Self::Dummy => cha.is_dummy(), Self::Block => cha.is_block(), Self::Char => cha.is_char(), Self::Fifo => cha.is_fifo(), Self::Sock => cha.is_sock(), Self::Exec => cha.is_exec(), Self::Sticky => cha.is_sticky(), } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/which/sorting.rs
yazi-config/src/which/sorting.rs
use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "kebab-case")] pub enum SortBy { #[default] None, Key, Desc, }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/which/which.rs
yazi-config/src/which/which.rs
use serde::{Deserialize, Serialize}; use yazi_codegen::DeserializeOver2; use super::SortBy; #[derive(Debug, Deserialize, DeserializeOver2, Serialize)] pub struct Which { // Sorting pub sort_by: SortBy, pub sort_sensitive: bool, pub sort_reverse: bool, pub sort_translit: bool, }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/which/mod.rs
yazi-config/src/which/mod.rs
yazi_macro::mod_flat!(sorting which);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/vfs/services.rs
yazi-config/src/vfs/services.rs
use std::ops::Deref; use anyhow::{Result, bail}; use hashbrown::HashMap; use serde::{Deserialize, Serialize}; use crate::vfs::Service; #[derive(Deserialize, Serialize)] pub struct Services(HashMap<String, Service>); impl Deref for Services { type Target = HashMap<String, Service>; fn deref(&self) -> &Self::Target { &self.0 } } impl Services { pub(super) fn reshape(mut self) -> Result<Self> { for (name, service) in &mut self.0 { if name.is_empty() || name.len() > 20 { bail!("VFS name `{name}` must be between 1 and 20 characters"); } else if !name.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'z' | b'-')) { bail!("VFS name `{name}` must be in kebab-case"); } service.reshape()?; } Ok(self) } pub(super) fn deserialize_over<'de, D>(mut self, deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let map: HashMap<String, Service> = HashMap::deserialize(deserializer)?; self.0.extend(map); Ok(self) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/vfs/service.rs
yazi-config/src/vfs/service.rs
use std::{io, mem, path::PathBuf}; use serde::{Deserialize, Serialize}; use crate::normalize_path; #[derive(Deserialize, Serialize)] #[serde(tag = "type", rename_all = "kebab-case")] pub enum Service { Sftp(ServiceSftp), } impl TryFrom<&'static Service> for &'static ServiceSftp { type Error = &'static str; fn try_from(value: &'static Service) -> Result<Self, Self::Error> { match value { Service::Sftp(p) => Ok(p), } } } impl Service { pub(super) fn reshape(&mut self) -> io::Result<()> { match self { Self::Sftp(p) => p.reshape(), } } } // --- SFTP #[derive(Deserialize, Eq, Hash, PartialEq, Serialize)] pub struct ServiceSftp { pub host: String, pub user: String, pub port: u16, pub password: Option<String>, #[serde(default)] pub key_file: PathBuf, pub key_passphrase: Option<String>, #[serde(default)] pub identity_agent: PathBuf, } impl ServiceSftp { fn reshape(&mut self) -> io::Result<()> { if !self.key_file.as_os_str().is_empty() { self.key_file = normalize_path(mem::take(&mut self.key_file)) .ok_or_else(|| io::Error::other("key_file must be either empty or an absolute path"))?; } self.identity_agent = if self.identity_agent.as_os_str().is_empty() { std::env::var_os("SSH_AUTH_SOCK") .map(PathBuf::from) .filter(|p| p.is_absolute()) .unwrap_or_default() } else { normalize_path(mem::take(&mut self.identity_agent)).ok_or_else(|| { io::Error::other("identity_agent must be either empty or an absolute path") })? }; Ok(()) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/vfs/mod.rs
yazi-config/src/vfs/mod.rs
yazi_macro::mod_flat!(service services vfs);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/vfs/vfs.rs
yazi-config/src/vfs/vfs.rs
use std::io; use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use tokio::sync::OnceCell; use yazi_codegen::DeserializeOver1; use yazi_fs::{Xdg, ok_or_not_found}; use super::Service; use crate::{Preset, vfs::Services}; #[derive(Deserialize, Serialize, DeserializeOver1)] pub struct Vfs { pub services: Services, } impl Vfs { pub async fn load() -> io::Result<&'static Self> { pub static LOADED: OnceCell<Vfs> = OnceCell::const_new(); async fn init() -> io::Result<Vfs> { tokio::task::spawn_blocking(|| { Preset::vfs()?.deserialize_over(toml::Deserializer::parse(&Vfs::read()?)?)?.reshape() }) .await? .map_err(io::Error::other) } LOADED.get_or_try_init(init).await } pub async fn service<'a, P>(name: &str) -> io::Result<(&'a str, P)> where P: TryFrom<&'a Service, Error = &'static str>, { let Some((key, value)) = Self::load().await?.services.get_key_value(name) else { return Err(io::Error::other(format!("No such VFS service: {name}"))); }; match value.try_into() { Ok(p) => Ok((key.as_str(), p)), Err(e) => Err(io::Error::other(format!("VFS service `{key}` has wrong type: {e}"))), } } fn read() -> Result<String> { let p = Xdg::config_dir().join("vfs.toml"); ok_or_not_found(std::fs::read_to_string(&p)) .with_context(|| format!("Failed to read config {p:?}")) } fn reshape(self) -> Result<Self> { Ok(Self { services: self.services.reshape()? }) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/open/open.rs
yazi-config/src/open/open.rs
use std::ops::Deref; use anyhow::Result; use indexmap::IndexSet; use serde::Deserialize; use yazi_codegen::DeserializeOver2; use yazi_shared::url::AsUrl; use crate::{Preset, open::OpenRule}; #[derive(Default, Deserialize, DeserializeOver2)] pub struct Open { rules: Vec<OpenRule>, #[serde(default)] prepend_rules: Vec<OpenRule>, #[serde(default)] append_rules: Vec<OpenRule>, } impl Deref for Open { type Target = Vec<OpenRule>; fn deref(&self) -> &Self::Target { &self.rules } } impl Open { pub fn all<'a, 'b, U, M>(&'a self, url: U, mime: M) -> impl Iterator<Item = &'a str> + 'b where 'a: 'b, U: AsUrl + 'b, M: AsRef<str> + 'b, { let is_dir = mime.as_ref().starts_with("folder/"); self .rules .iter() .find(move |&r| { r.mime.as_ref().is_some_and(|p| p.match_mime(&mime)) || r.url.as_ref().is_some_and(|p| p.match_url(url.as_url(), is_dir)) }) .into_iter() .flat_map(|r| &r.r#use) .map(String::as_str) } pub fn common<'a, 'b, U, M>(&'a self, targets: &'b [(U, M)]) -> IndexSet<&'a str> where &'b U: AsUrl, M: AsRef<str>, { let each: Vec<IndexSet<&str>> = targets .iter() .map(|(u, m)| self.all(u, m).collect::<IndexSet<_>>()) .filter(|s| !s.is_empty()) .collect(); let mut flat: IndexSet<_> = each.iter().flatten().copied().collect(); flat.retain(|use_| each.iter().all(|e| e.contains(use_))); flat } } impl Open { pub(crate) fn reshape(self) -> Result<Self> { let any_file = self.append_rules.iter().any(|r| r.any_file()); let any_dir = self.append_rules.iter().any(|r| r.any_dir()); let it = self.rules.into_iter().filter(|r| !(any_file && r.any_file() || any_dir && r.any_dir())); Ok(Self { rules: Preset::mix(self.prepend_rules, it, self.append_rules).collect(), ..Default::default() }) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/open/mod.rs
yazi-config/src/open/mod.rs
yazi_macro::mod_flat!(open rule);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-config/src/open/rule.rs
yazi-config/src/open/rule.rs
use std::fmt; use serde::{Deserialize, Deserializer, de::{self, Visitor}}; use crate::pattern::Pattern; #[derive(Debug, Deserialize)] pub struct OpenRule { pub url: Option<Pattern>, pub mime: Option<Pattern>, #[serde(deserialize_with = "OpenRule::deserialize")] pub r#use: Vec<String>, } impl OpenRule { #[inline] pub fn any_file(&self) -> bool { self.url.as_ref().is_some_and(|p| p.any_file()) } #[inline] pub fn any_dir(&self) -> bool { self.url.as_ref().is_some_and(|p| p.any_dir()) } } impl OpenRule { fn deserialize<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error> where D: Deserializer<'de>, { struct UseVisitor; impl<'de> Visitor<'de> for UseVisitor { type Value = Vec<String>; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a string, or array of strings") } fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: de::SeqAccess<'de>, { let mut uses = Vec::with_capacity(seq.size_hint().unwrap_or(0)); while let Some(use_) = seq.next_element::<String>()? { uses.push(use_); } Ok(uses) } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { Ok(vec![value.to_owned()]) } fn visit_string<E>(self, v: String) -> Result<Self::Value, E> where E: de::Error, { Ok(vec![v]) } } deserializer.deserialize_any(UseVisitor) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-macro/src/event.rs
yazi-macro/src/event.rs
#[macro_export] macro_rules! emit { (Quit($opt:expr)) => { yazi_shared::event::Event::Quit($opt).emit(); }; (Call($cmd:expr)) => { yazi_shared::event::Event::Call(yazi_shared::event::CmdCow::from($cmd)).emit(); }; (Seq($cmds:expr)) => { yazi_shared::event::Event::Seq($cmds).emit(); }; ($event:ident) => { yazi_shared::event::Event::$event.emit(); }; } #[macro_export] macro_rules! relay { ($layer:ident : $name:ident) => { yazi_shared::event::Cmd::new_relay(concat!(stringify!($layer), ":", stringify!($name))) }; ($layer:ident : $name:ident, $args:expr) => { yazi_shared::event::Cmd::new_relay_args( concat!(stringify!($layer), ":", stringify!($name)), $args, ) }; } #[macro_export] macro_rules! succ { ($data:expr) => { return Ok(yazi_shared::data::Data::from($data)) }; () => { return Ok(yazi_shared::data::Data::Nil) }; }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-macro/src/lib.rs
yazi-macro/src/lib.rs
mod actor; mod asset; mod context; mod event; mod fmt; mod fs; mod log; mod module; mod platform; mod render; mod stdio;
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-macro/src/stdio.rs
yazi-macro/src/stdio.rs
#[macro_export] macro_rules! outln { ($($tt:tt)*) => {{ use std::io::Write; writeln!(std::io::stdout(), $($tt)*) }} } #[macro_export] macro_rules! errln { ($($tt:tt)*) => {{ use std::io::Write; writeln!(std::io::stderr(), $($tt)*) }} }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-macro/src/module.rs
yazi-macro/src/module.rs
#[macro_export] macro_rules! mod_pub { [ $( $name:ident $(,)? )+ ] => { $( pub mod $name; )+ }; } #[macro_export] macro_rules! mod_flat { [ $( $name:ident $(,)? )+ ] => { $( mod $name; pub use $name::*; )+ }; }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-macro/src/fs.rs
yazi-macro/src/fs.rs
#[macro_export] macro_rules! ok_or_not_found { ($result:expr, $not_found:expr) => { match $result { Ok(v) => v, Err(e) if e.kind() == std::io::ErrorKind::NotFound => $not_found, Err(e) => Err(e)?, } }; ($result:expr) => { ok_or_not_found!($result, Default::default()) }; }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-macro/src/actor.rs
yazi-macro/src/actor.rs
#[macro_export] macro_rules! act { (@pre $layer:ident : $name:ident, $cx:ident, $opt:ident) => { if let Some(hook) = <act!($layer:$name) as yazi_actor::Actor>::hook($cx, &$opt) { <act!(core:preflight)>::act($cx, (hook, yazi_dds::spark!($layer:$name, $opt))).map(|spark| spark.try_into().unwrap()) } else { Ok($opt) } }; (@impl $layer:ident : $name:ident, $cx:ident, $opt:ident) => {{ $cx.level += 1; #[cfg(debug_assertions)] $cx.backtrace.push(concat!(stringify!($layer), ":", stringify!($name))); let result = match act!(@pre $layer:$name, $cx, $opt) { Ok(opt) => <act!($layer:$name) as yazi_actor::Actor>::act($cx, opt), Err(e) => Err(e), }; $cx.level -= 1; #[cfg(debug_assertions)] $cx.backtrace.pop(); result }}; ($layer:ident : $name:ident, $cx:ident, $cmd:expr) => { <act!($layer:$name) as yazi_actor::Actor>::Options::try_from($cmd) .map_err(anyhow::Error::from) .and_then(|opt| act!(@impl $layer:$name, $cx, opt)) }; ($layer:ident : $name:ident, $cx:ident) => { act!($layer:$name, $cx, <<act!($layer:$name) as yazi_actor::Actor>::Options as Default>::default()) }; ($layer:ident : $name:ident) => { paste::paste! { yazi_actor::$layer::[<$name:camel>] } }; ($name:ident, $cx:expr, $cmd:expr) => { $cmd.try_into().map_err(anyhow::Error::from).and_then(|opt| $cx.$name(opt)) }; ($name:ident, $cx:expr) => { $cx.$name(Default::default()) }; }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-macro/src/platform.rs
yazi-macro/src/platform.rs
#[macro_export] macro_rules! unix_either { ($a:expr, $b:expr) => {{ #[cfg(unix)] { $a } #[cfg(not(unix))] { $b } }}; } #[macro_export] macro_rules! win_either { ($a:expr, $b:expr) => {{ #[cfg(windows)] { $a } #[cfg(not(windows))] { $b } }}; }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-macro/src/asset.rs
yazi-macro/src/asset.rs
#[macro_export] macro_rules! config_preset { ($name:literal) => {{ #[cfg(debug_assertions)] { std::borrow::Cow::from( std::fs::read_to_string(concat!( env!("CARGO_MANIFEST_DIR"), "/preset/", $name, "-default.toml" )) .expect(concat!("Failed to read 'yazi-config/preset/", $name, "-default.toml'")), ) } #[cfg(not(debug_assertions))] { std::borrow::Cow::from(include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/preset/", $name, "-default.toml" ))) } }}; } #[macro_export] macro_rules! plugin_preset { ($name:literal) => {{ #[cfg(debug_assertions)] { std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/preset/", $name, ".lua")).expect(concat!( "Failed to read 'yazi-plugin/preset/", $name, ".lua'" )) } #[cfg(not(debug_assertions))] { &include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/preset/", $name, ".lua"))[..] } }}; } #[macro_export] macro_rules! theme_preset { ($name:literal) => {{ #[cfg(debug_assertions)] { std::borrow::Cow::from( std::fs::read_to_string(concat!( env!("CARGO_MANIFEST_DIR"), "/preset/theme-", $name, ".toml" )) .expect(concat!("Failed to read 'yazi-config/preset/theme-", $name, ".toml'")), ) } #[cfg(not(debug_assertions))] { std::borrow::Cow::from(include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/preset/theme-", $name, ".toml" ))) } }}; }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-macro/src/log.rs
yazi-macro/src/log.rs
#[macro_export] macro_rules! time { ($expr:expr) => { $crate::time!(stringify!($expr), $expr) }; ($label:expr, $expr:expr) => { $crate::time!($expr, "{}", $label) }; ($expr:expr, $fmt:expr, $($args:tt)*) => {{ if tracing::enabled!(tracing::Level::DEBUG) { let start = std::time::Instant::now(); let result = $expr; tracing::debug!("{} took {:?}", format_args!($fmt, $($args)*), start.elapsed()); result } else { $expr } }}; } #[macro_export] macro_rules! err { ($expr:expr) => { $crate::err!(stringify!($expr), $expr) }; ($label:expr, $expr:expr) => { $crate::err!($expr, "{}", $label) }; ($expr:expr, $fmt:expr, $($args:tt)*) => {{ if let Err(e) = $expr { tracing::error!("{} failed: {e}", format_args!($fmt, $($args)*)); } }}; }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-macro/src/render.rs
yazi-macro/src/render.rs
#[macro_export] macro_rules! render { () => { yazi_shared::event::NEED_RENDER.store(true, std::sync::atomic::Ordering::Relaxed); }; ($cond:expr) => { if $cond { render!(); } }; ($left:expr, > $right:expr) => {{ let val = $left; if val > $right { render!(); } val }}; } #[macro_export] macro_rules! render_and { ($cond:expr) => { if $cond { yazi_macro::render!(); true } else { false } }; }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-macro/src/context.rs
yazi-macro/src/context.rs
#[macro_export] macro_rules! tab { ($cx:ident) => {{ let tab = $cx.tab; &mut $cx.core.mgr.tabs.items[tab] }}; }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-macro/src/fmt.rs
yazi-macro/src/fmt.rs
#[macro_export] macro_rules! try_format { ($($arg:tt)*) => {{ use std::fmt::Write; let mut output = String::new(); output.write_fmt(format_args!($($arg)*)).map(|_| output) }} }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-watcher/src/lib.rs
yazi-watcher/src/lib.rs
yazi_macro::mod_pub!(local remote); yazi_macro::mod_flat!(backend reporter watched watcher); pub static WATCHED: yazi_shared::RoCell<parking_lot::RwLock<Watched>> = yazi_shared::RoCell::new(); pub static WATCHER: yazi_shared::RoCell<tokio::sync::Semaphore> = yazi_shared::RoCell::new(); pub fn init() { WATCHED.with(<_>::default); WATCHER.init(tokio::sync::Semaphore::new(1)); local::init(); }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-watcher/src/watched.rs
yazi-watcher/src/watched.rs
use std::path::Path; use hashbrown::HashSet; use percent_encoding::percent_decode_str; use yazi_fs::{Xdg, path::PercentEncoding}; use yazi_shared::{path::{Component, PathBufDyn, PathDyn, PathLike}, pool::InternStr, scheme::SchemeKind, url::{AsUrl, UrlBuf, UrlLike}}; #[derive(Debug, Default)] pub struct Watched(HashSet<UrlBuf>); impl Watched { #[inline] pub(crate) fn contains(&self, url: impl AsUrl) -> bool { self.0.contains(&url.as_url()) } #[inline] pub(crate) fn diff(&self, new: &HashSet<UrlBuf>) -> (Vec<UrlBuf>, Vec<UrlBuf>) { (self.0.difference(new).cloned().collect(), new.difference(&self.0).cloned().collect()) } #[inline] pub(crate) fn insert(&mut self, url: impl Into<UrlBuf>) { self.0.insert(url.into()); } #[inline] pub(crate) fn paths(&self) -> impl Iterator<Item = &Path> { self.0.iter().filter_map(|u| u.as_local()) } #[inline] pub(crate) fn remove(&mut self, url: impl AsUrl) { self.0.remove(&url.as_url()); } pub(super) fn find_by_cache(&self, cache: PathDyn) -> Option<UrlBuf> { let mut it = cache.try_strip_prefix(Xdg::cache_dir()).ok()?.components(); // Parse domain let domain = it.next()?.as_normal()?.to_str().ok()?; let domain = percent_decode_str(domain.strip_prefix("sftp-")?).decode_utf8().ok()?.intern(); // Parse path let (path, abs) = if let Ok(p) = it.path().try_strip_prefix(".%2F") { (p, false) } else { (it.path(), true) }; let path = path.percent_decode(SchemeKind::Sftp).ok()?; let path = PathBufDyn::from_components( SchemeKind::Sftp, Some(Component::RootDir).filter(|_| abs).into_iter().chain(path.components()), ) .ok()?; let url = UrlBuf::Sftp { loc: path.into_unix().ok()?.into(), domain }; if self.contains(&url) { Some(url) } else { None } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-watcher/src/backend.rs
yazi-watcher/src/backend.rs
use anyhow::Result; use tokio::sync::mpsc; use yazi_shared::url::AsUrl; use crate::{Reporter, WATCHED, local::{self, LINKED, Linked}, remote}; pub(crate) struct Backend { local: local::Local, remote: remote::Remote, pub(super) reporter: Reporter, } impl Backend { pub(crate) fn serve() -> Self { #[cfg(any(target_os = "linux", target_os = "macos"))] yazi_fs::mounts::Partitions::monitor(&yazi_fs::mounts::PARTITIONS, || { yazi_macro::err!(yazi_dds::Pubsub::pub_after_mount()) }); let (local_tx, local_rx) = mpsc::unbounded_channel(); let (remote_tx, remote_rx) = mpsc::unbounded_channel(); let reporter = Reporter { local_tx, remote_tx }; Self { local: local::Local::serve(local_rx, reporter.clone()), remote: remote::Remote::serve(remote_rx, reporter.clone()), reporter, } } pub(super) fn watch(&mut self, url: impl AsUrl) -> Result<()> { let url = url.as_url(); if let Some(path) = url.as_local() { self.local.watch(path)?; } else { self.remote.watch(url)?; } Ok(()) } pub(super) fn unwatch(&mut self, url: impl AsUrl) -> Result<()> { let url = url.as_url(); if let Some(path) = url.as_local() { self.local.unwatch(path)?; } else { self.remote.unwatch(url)?; } Ok(()) } pub(super) async fn sync(self) -> Self { Linked::sync(&LINKED, &WATCHED).await; self } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-watcher/src/watcher.rs
yazi-watcher/src/watcher.rs
use hashbrown::HashSet; use tokio::sync::watch; use tracing::error; use yazi_fs::FsUrl; use yazi_shared::url::{UrlBuf, UrlCow, UrlLike}; use crate::{Reporter, WATCHED, backend::Backend}; pub struct Watcher { tx: watch::Sender<HashSet<UrlBuf>>, reporter: Reporter, } impl Watcher { pub fn serve() -> Self { let (tx, rx) = watch::channel(Default::default()); let backend = Backend::serve(); let reporter = backend.reporter.clone(); tokio::spawn(Self::watched(rx, backend)); Self { tx, reporter } } pub fn watch<'a, I>(&mut self, urls: I) where I: IntoIterator, I::Item: Into<UrlCow<'a>>, { let it = urls.into_iter(); let mut set = HashSet::with_capacity(it.size_hint().0); for url in it.map(Into::into) { if !url.is_absolute() { continue; } else if let Some(cache) = url.cache() { set.insert(cache.into()); } set.insert(url.into_owned()); } self.tx.send(set).ok(); } pub fn report<'a, I>(&self, urls: I) where I: IntoIterator, I::Item: Into<UrlCow<'a>>, { self.reporter.report(urls); } async fn watched(mut rx: watch::Receiver<HashSet<UrlBuf>>, mut backend: Backend) { loop { let (to_unwatch, to_watch) = WATCHED.read().diff(&rx.borrow_and_update()); if !to_unwatch.is_empty() || !to_watch.is_empty() { backend = Self::sync(backend, to_unwatch, to_watch).await; backend = backend.sync().await; } if rx.changed().await.is_err() { break; } } } async fn sync(mut backend: Backend, to_unwatch: Vec<UrlBuf>, to_watch: Vec<UrlBuf>) -> Backend { tokio::task::spawn_blocking(move || { for u in to_unwatch { match backend.unwatch(&u) { Ok(()) => WATCHED.write().remove(&u), Err(e) => error!("Unwatch failed: {e:?}"), } } for u in to_watch { match backend.watch(&u) { Ok(()) => WATCHED.write().insert(u), Err(e) => error!("Watch failed: {e:?}"), } } backend }) .await .unwrap() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-watcher/src/reporter.rs
yazi-watcher/src/reporter.rs
use std::borrow::Cow; use percent_encoding::percent_decode; use tokio::sync::mpsc; use yazi_shared::{scheme::SchemeKind, url::{AsUrl, Url, UrlBuf, UrlCow, UrlLike}}; use crate::{WATCHED, local::LINKED}; #[derive(Clone)] pub(crate) struct Reporter { pub(super) local_tx: mpsc::UnboundedSender<UrlBuf>, pub(super) remote_tx: mpsc::UnboundedSender<UrlBuf>, } impl Reporter { pub(crate) fn report<'a, I>(&self, urls: I) where I: IntoIterator, I::Item: Into<UrlCow<'a>>, { for url in urls.into_iter().map(Into::into) { match url.as_url().kind() { SchemeKind::Regular | SchemeKind::Search => self.report_local(url), SchemeKind::Archive => {} SchemeKind::Sftp => self.report_remote(url), } } } fn report_local(&self, url: UrlCow) { let Some((parent, urn)) = url.pair() else { return }; // FIXME: LINKED should return Url instead of Path let linked = LINKED.read(); let linked = linked.from_dir(parent).map(Url::regular); let watched = WATCHED.read(); for parent in [parent].into_iter().chain(linked) { if watched.contains(parent) { self.local_tx.send(url.to_owned()).ok(); self.local_tx.send(parent.to_owned()).ok(); } if urn.ext().is_some_and(|e| e == "%tmp") { continue; } // Virtual caches let Some(dir) = watched.find_by_cache(parent.loc()) else { continue }; let Some(name) = url.name() else { continue }; if let Ok(u) = dir.try_join(Cow::from(percent_decode(name.encoded_bytes()))) { self.remote_tx.send(u).ok(); } self.remote_tx.send(dir).ok(); } } fn report_remote(&self, url: UrlCow) { let Some(parent) = url.parent() else { return }; if !WATCHED.read().contains(parent) { return; } self.remote_tx.send(parent.to_owned()).ok(); self.remote_tx.send(url.into_owned()).ok(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-watcher/src/remote/remote.rs
yazi-watcher/src/remote/remote.rs
use std::time::{Duration, SystemTime}; use anyhow::Result; use hashbrown::HashSet; use tokio::{pin, sync::mpsc::UnboundedReceiver}; use tokio_stream::{StreamExt, wrappers::UnboundedReceiverStream}; use yazi_fs::{File, FilesOp}; use yazi_proxy::MgrProxy; use yazi_shared::url::{Url, UrlBuf, UrlLike}; use yazi_vfs::VfsFile; use crate::{Reporter, WATCHER}; pub(crate) struct Remote; impl Remote { pub(crate) fn serve(rx: UnboundedReceiver<UrlBuf>, _reporter: Reporter) -> Self { tokio::spawn(Self::changed(rx)); Self } pub(crate) fn watch(&mut self, _url: Url) -> Result<()> { Ok(()) } pub(crate) fn unwatch(&mut self, _url: Url) -> Result<()> { Ok(()) } async fn changed(rx: UnboundedReceiver<UrlBuf>) { let rx = UnboundedReceiverStream::new(rx).chunks_timeout(1000, Duration::from_millis(250)); pin!(rx); while let Some(chunk) = rx.next().await { let urls: HashSet<_> = chunk.into_iter().collect(); let _permit = WATCHER.acquire().await.unwrap(); let mut ops = Vec::with_capacity(urls.len()); let mut ups = Vec::with_capacity(urls.len()); for u in urls { let Some((parent, urn)) = u.pair() else { continue }; let Ok(mut file) = File::new(&u).await else { ops.push(FilesOp::Deleting(parent.into(), [urn.into()].into())); continue; }; let is_file = file.is_file(); file.cha.ctime = Some(SystemTime::now()); ops.push(FilesOp::Upserting(parent.into(), [(urn.into(), file)].into())); if is_file { ups.push(u); } } FilesOp::mutate(ops); MgrProxy::upload(ups); } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-watcher/src/remote/mod.rs
yazi-watcher/src/remote/mod.rs
yazi_macro::mod_flat!(remote);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-watcher/src/local/local.rs
yazi-watcher/src/local/local.rs
use std::{path::Path, time::Duration}; use anyhow::Result; use hashbrown::HashSet; use notify::{PollWatcher, RecommendedWatcher, RecursiveMode, Watcher}; use tokio::{pin, sync::mpsc::{self, UnboundedReceiver}}; use tokio_stream::{StreamExt, wrappers::UnboundedReceiverStream}; use tracing::error; use yazi_fs::{File, FilesOp, provider}; use yazi_shared::url::{UrlBuf, UrlLike}; use yazi_vfs::VfsFile; use crate::{Reporter, WATCHER}; pub(crate) struct Local(Box<dyn notify::Watcher + Send>); impl Local { pub(crate) fn serve(rx: mpsc::UnboundedReceiver<UrlBuf>, reporter: Reporter) -> Self { tokio::spawn(Self::changed(rx)); let config = notify::Config::default().with_poll_interval(Duration::from_millis(500)); let handler = move |res: Result<notify::Event, notify::Error>| { if let Ok(event) = res && !event.kind.is_access() { reporter.report(event.paths); } }; if cfg!(target_os = "netbsd") || yazi_adapter::WSL.get() { return Self(Box::new(PollWatcher::new(handler, config).unwrap())); } Self(match RecommendedWatcher::new(handler.clone(), config) { Ok(watcher) => Box::new(watcher), Err(e) => { error!("Falling back to PollWatcher due to RecommendedWatcher init failure: {e:?}"); Box::new(PollWatcher::new(handler, config).unwrap()) } }) } pub(crate) fn watch(&mut self, path: &Path) -> Result<()> { match self.0.watch(path, RecursiveMode::NonRecursive) { Ok(()) => Ok(()), Err(e) if matches!(e.kind, notify::ErrorKind::PathNotFound) => Ok(()), Err(e) => Err(e)?, } } pub(crate) fn unwatch(&mut self, path: &Path) -> Result<()> { match self.0.unwatch(path) { Ok(()) => Ok(()), Err(e) if matches!(e.kind, notify::ErrorKind::WatchNotFound) => Ok(()), Err(e) => Err(e)?, } } async fn changed(rx: UnboundedReceiver<UrlBuf>) { // TODO: revert this once a new notification is implemented let rx = UnboundedReceiverStream::new(rx).chunks_timeout(1000, Duration::from_millis(250)); pin!(rx); while let Some(chunk) = rx.next().await { let urls: HashSet<_> = chunk.into_iter().collect(); let _permit = WATCHER.acquire().await.unwrap(); let mut ops = Vec::with_capacity(urls.len()); for u in urls { let Some((parent, urn)) = u.pair() else { continue }; let Ok(file) = File::new(&u).await else { ops.push(FilesOp::Deleting(parent.into(), [urn.into()].into())); continue; }; if let Some(p) = file.url.as_local() && !provider::local::match_name_case(p).await { ops.push(FilesOp::Deleting(parent.into(), [urn.into()].into())); continue; } ops.push(FilesOp::Upserting(parent.into(), [(urn.into(), file)].into())); } FilesOp::mutate(ops); } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-watcher/src/local/linked.rs
yazi-watcher/src/local/linked.rs
use std::{iter, ops::{Deref, DerefMut}, path::{Path, PathBuf}}; use hashbrown::HashMap; use parking_lot::RwLock; use yazi_shared::url::Url; use crate::Watched; #[derive(Default)] pub struct Linked(HashMap<PathBuf, PathBuf> /* from ==> to */); impl Deref for Linked { type Target = HashMap<PathBuf, PathBuf>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for Linked { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl Linked { pub fn from_dir<'a, 'b, U>(&'a self, url: U) -> Box<dyn Iterator<Item = &'a Path> + 'b> where 'a: 'b, U: Into<Url<'b>>, { let url: Url = url.into(); let Some(path) = url.as_local() else { return Box::new(iter::empty()); }; if let Some(to) = self.get(path) { Box::new(self.iter().filter(move |(k, v)| *v == to && *k != path).map(|(k, _)| k.as_path())) } else { Box::new(self.iter().filter(move |(_, v)| *v == path).map(|(k, _)| k.as_path())) } } pub fn from_file(&self, url: Url) -> Vec<PathBuf> { let Some(path) = url.as_local() else { return vec![] }; if let Some((parent, name)) = path.parent().zip(path.file_name()) { self.from_dir(parent).map(|p| p.join(name)).collect() } else { vec![] } } pub(crate) async fn sync(linked: &'static RwLock<Self>, watched: &'static RwLock<Watched>) { tokio::task::spawn_blocking(move || { let watched = watched.read(); // Remove entries that are no longer watched linked.write().retain(|from, _| watched.contains(from)); // Update existing entries and remove broken links for from in watched.paths() { match std::fs::canonicalize(from) { Ok(to) if to != *from => _ = linked.write().entry_ref(from).insert(to), Ok(_) => _ = linked.write().remove(from), Err(e) if e.kind() == std::io::ErrorKind::NotFound => _ = linked.write().remove(from), Err(e) => tracing::error!("Failed to canonicalize watched path {from:?}: {e:?}"), } } }) .await .ok(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-watcher/src/local/mod.rs
yazi-watcher/src/local/mod.rs
yazi_macro::mod_flat!(linked local); pub static LINKED: yazi_shared::RoCell<parking_lot::RwLock<Linked>> = yazi_shared::RoCell::new(); pub(super) fn init() { LINKED.with(<_>::default); }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-boot/build.rs
yazi-boot/build.rs
#[path = "src/args.rs"] mod args; use std::{env, error::Error}; use clap::CommandFactory; use clap_complete::{Shell, generate_to}; use vergen_gitcl::{BuildBuilder, Emitter, GitclBuilder, RustcBuilder}; fn main() -> Result<(), Box<dyn Error>> { Emitter::default() .add_instructions(&BuildBuilder::default().build_date(true).build()?)? .add_instructions( &RustcBuilder::default() .commit_date(true) .commit_hash(true) .host_triple(true) .semver(true) .build()?, )? .add_instructions(&GitclBuilder::default().commit_date(true).sha(true).build()?)? .emit()?; if env::var_os("YAZI_GEN_COMPLETIONS").is_none() { return Ok(()); } let cmd = &mut args::Args::command(); let bin = "yazi"; let out = "completions"; std::fs::create_dir_all(out)?; for sh in [Shell::Bash, Shell::Fish, Shell::Zsh, Shell::Elvish, Shell::PowerShell] { generate_to(sh, cmd, bin, out)?; } generate_to(clap_complete_nushell::Nushell, cmd, bin, out)?; generate_to(clap_complete_fig::Fig, cmd, bin, out)?; Ok(()) }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-boot/src/lib.rs
yazi-boot/src/lib.rs
yazi_macro::mod_pub!(actions); yazi_macro::mod_flat!(args boot); use clap::Parser; use yazi_shared::RoCell; pub static ARGS: RoCell<Args> = RoCell::new(); pub static BOOT: RoCell<Boot> = RoCell::new(); pub fn init() { ARGS.with(<_>::parse); BOOT.init(<_>::from(&*ARGS)); actions::Actions::act(&ARGS); } pub fn init_default() { ARGS.with(<_>::default); BOOT.with(<_>::default); }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-boot/src/args.rs
yazi-boot/src/args.rs
use std::path::PathBuf; use clap::Parser; use yazi_shared::{Id, url::UrlBuf}; #[derive(Debug, Default, Parser)] #[command(name = "yazi")] pub struct Args { /// Set the current working entry #[arg(index = 1, num_args = 1..=9)] pub entries: Vec<UrlBuf>, /// Write the cwd on exit to this file #[arg(long)] pub cwd_file: Option<PathBuf>, /// Write the selected files to this file on open fired #[arg(long)] pub chooser_file: Option<PathBuf>, /// Clear the cache directory #[arg(long)] pub clear_cache: bool, /// Use the specified client ID, must be a globally unique number #[arg(long)] pub client_id: Option<Id>, /// Report the specified local events to stdout #[arg(long)] pub local_events: Option<String>, /// Report the specified remote events to stdout #[arg(long)] pub remote_events: Option<String>, /// Print debug information #[arg(long)] pub debug: bool, /// Print version #[arg(short = 'V', long)] pub version: bool, }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-boot/src/boot.rs
yazi-boot/src/boot.rs
use std::path::PathBuf; use futures::executor::block_on; use hashbrown::HashSet; use yazi_fs::{CWD, Xdg, path::clean_url}; use yazi_shared::{strand::StrandBuf, url::{UrlBuf, UrlLike}}; use yazi_vfs::provider; #[derive(Debug, Default)] pub struct Boot { pub cwds: Vec<UrlBuf>, pub files: Vec<StrandBuf>, pub local_events: HashSet<String>, pub remote_events: HashSet<String>, pub config_dir: PathBuf, pub flavor_dir: PathBuf, pub plugin_dir: PathBuf, pub state_dir: PathBuf, } impl Boot { async fn parse_entries(entries: &[UrlBuf]) -> (Vec<UrlBuf>, Vec<StrandBuf>) { if entries.is_empty() { return (vec![CWD.load().as_ref().clone()], vec![Default::default()]); } async fn go(entry: &UrlBuf) -> (UrlBuf, StrandBuf) { let mut entry = clean_url(entry); if let Ok(u) = provider::absolute(&entry).await && u.is_owned() { entry = u.into_owned(); } let Some((parent, child)) = entry.pair() else { return (entry, Default::default()); }; if provider::metadata(&entry).await.is_ok_and(|m| m.is_file()) { (parent.into(), child.into()) } else { (entry, Default::default()) } } futures::future::join_all(entries.iter().map(go)).await.into_iter().unzip() } } impl From<&crate::Args> for Boot { fn from(args: &crate::Args) -> Self { let config_dir = Xdg::config_dir(); let (cwds, files) = block_on(Self::parse_entries(&args.entries)); let local_events = args .local_events .as_ref() .map(|s| s.split(',').map(|s| s.to_owned()).collect()) .unwrap_or_default(); let remote_events = args .remote_events .as_ref() .map(|s| s.split(',').map(|s| s.to_owned()).collect()) .unwrap_or_default(); Self { cwds, files, local_events, remote_events, flavor_dir: config_dir.join("flavors"), plugin_dir: config_dir.join("plugins"), config_dir, state_dir: Xdg::state_dir(), } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-boot/src/actions/rustc.rs
yazi-boot/src/actions/rustc.rs
use super::Actions; impl Actions { pub(super) fn rustc() -> String { format!( "{} ({} {})", env!("VERGEN_RUSTC_SEMVER"), &env!("VERGEN_RUSTC_COMMIT_HASH")[..8], env!("VERGEN_RUSTC_COMMIT_DATE") ) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-boot/src/actions/triple.rs
yazi-boot/src/actions/triple.rs
use super::Actions; impl Actions { pub(super) fn triple() -> String { format!( "{} ({}-{})", env!("VERGEN_RUSTC_HOST_TRIPLE"), std::env::consts::OS, std::env::consts::ARCH ) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-boot/src/actions/version.rs
yazi-boot/src/actions/version.rs
use super::Actions; impl Actions { pub fn version() -> &'static str { concat!( env!("CARGO_PKG_VERSION"), " (", env!("VERGEN_GIT_SHA"), " ", env!("VERGEN_BUILD_DATE"), ")" ) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-boot/src/actions/clear_cache.rs
yazi-boot/src/actions/clear_cache.rs
use yazi_config::YAZI; use yazi_fs::Xdg; use super::Actions; impl Actions { pub(super) fn clear_cache() { if YAZI.preview.cache_dir == *Xdg::cache_dir() { println!("Clearing cache directory: \n{:?}", YAZI.preview.cache_dir); std::fs::remove_dir_all(&YAZI.preview.cache_dir).unwrap(); } else { println!( "You've changed the default cache directory, for your data's safety, please clear it manually: \n{:?}", YAZI.preview.cache_dir ); } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-boot/src/actions/debug.rs
yazi-boot/src/actions/debug.rs
use std::{env, ffi::OsStr, fmt::Write, path::Path}; use regex::Regex; use yazi_adapter::Mux; use yazi_config::{THEME, YAZI}; use yazi_fs::Xdg; use yazi_shared::timestamp_us; use super::Actions; impl Actions { pub(super) fn debug() -> Result<String, std::fmt::Error> { let mut s = String::new(); writeln!(s, "\nYazi")?; writeln!(s, " Version: {}", Self::version())?; writeln!(s, " Debug : {}", cfg!(debug_assertions))?; writeln!(s, " Triple : {}", Self::triple())?; writeln!(s, " Rustc : {}", Self::rustc())?; writeln!(s, "\nYa")?; writeln!(s, " Version: {}", Self::process_output("ya", "--version"))?; writeln!(s, "\nConfig")?; writeln!(s, " Yazi : {}", Self::config_state("yazi"))?; writeln!(s, " Keymap : {}", Self::config_state("keymap"))?; writeln!(s, " Theme : {}", Self::config_state("theme"))?; writeln!(s, " VFS : {}", Self::config_state("vfs"))?; writeln!(s, " Package : {}", Self::config_state("package"))?; writeln!(s, " Dark/light flavor: {:?} / {:?}", THEME.flavor.dark, THEME.flavor.light)?; writeln!(s, "\nEmulator")?; writeln!(s, " TERM : {:?}", env::var_os("TERM"))?; writeln!(s, " TERM_PROGRAM : {:?}", env::var_os("TERM_PROGRAM"))?; writeln!(s, " TERM_PROGRAM_VERSION: {:?}", env::var_os("TERM_PROGRAM_VERSION"))?; writeln!(s, " Brand.from_env : {:?}", yazi_adapter::Brand::from_env())?; writeln!(s, " Emulator.detect : {:?}", &*yazi_adapter::EMULATOR)?; writeln!(s, "\nAdapter")?; writeln!(s, " Adapter.matches : {:?}", yazi_adapter::ADAPTOR)?; writeln!(s, " Dimension.available: {:?}", yazi_adapter::Dimension::available())?; writeln!(s, "\nDesktop")?; writeln!(s, " XDG_SESSION_TYPE : {:?}", env::var_os("XDG_SESSION_TYPE"))?; writeln!(s, " WAYLAND_DISPLAY : {:?}", env::var_os("WAYLAND_DISPLAY"))?; writeln!(s, " DISPLAY : {:?}", env::var_os("DISPLAY"))?; writeln!(s, " SWAYSOCK : {:?}", env::var_os("SWAYSOCK"))?; #[rustfmt::skip] writeln!(s, " HYPRLAND_INSTANCE_SIGNATURE: {:?}", env::var_os("HYPRLAND_INSTANCE_SIGNATURE"))?; writeln!(s, " WAYFIRE_SOCKET : {:?}", env::var_os("WAYFIRE_SOCKET"))?; writeln!(s, "\nSSH")?; writeln!(s, " shared.in_ssh_connection: {}", yazi_shared::in_ssh_connection())?; writeln!(s, "\nWSL")?; writeln!(s, " WSL: {:?}", yazi_adapter::WSL)?; writeln!(s, "\nVariables")?; writeln!(s, " SHELL : {:?}", env::var_os("SHELL"))?; writeln!(s, " EDITOR : {:?}", env::var_os("EDITOR"))?; writeln!(s, " VISUAL : {:?}", env::var_os("VISUAL"))?; writeln!(s, " YAZI_FILE_ONE : {:?}", env::var_os("YAZI_FILE_ONE"))?; writeln!(s, " YAZI_CONFIG_HOME : {:?}", env::var_os("YAZI_CONFIG_HOME"))?; writeln!(s, " YAZI_ZOXIDE_OPTS : {:?}", env::var_os("YAZI_ZOXIDE_OPTS"))?; writeln!(s, " FZF_DEFAULT_OPTS : {:?}", env::var_os("FZF_DEFAULT_OPTS"))?; writeln!(s, " FZF_DEFAULT_COMMAND: {:?}", env::var_os("FZF_DEFAULT_COMMAND"))?; writeln!(s, "\nText Opener")?; writeln!( s, " default : {:?}", YAZI.opener.first(YAZI.open.all(Path::new("f75a.txt"), "text/plain")) )?; writeln!( s, " block-create: {:?}", YAZI.opener.block(YAZI.open.all(Path::new("bulk-create.txt"), "text/plain")) )?; writeln!( s, " block-rename: {:?}", YAZI.opener.block(YAZI.open.all(Path::new("bulk-rename.txt"), "text/plain")) )?; writeln!(s, "\nMultiplexers")?; writeln!(s, " TMUX : {}", yazi_adapter::TMUX)?; writeln!(s, " tmux version : {}", Self::process_output("tmux", "-V"))?; writeln!(s, " tmux build flags : enable-sixel={}", Mux::tmux_sixel_flag())?; writeln!(s, " ZELLIJ_SESSION_NAME: {:?}", env::var_os("ZELLIJ_SESSION_NAME"))?; writeln!(s, " Zellij version : {}", Self::process_output("zellij", "--version"))?; writeln!(s, "\nDependencies")?; #[rustfmt::skip] writeln!(s, " file : {}", Self::process_output(env::var_os("YAZI_FILE_ONE").unwrap_or("file".into()), "--version"))?; writeln!(s, " ueberzugpp : {}", Self::process_output("ueberzugpp", "--version"))?; #[rustfmt::skip] writeln!(s, " ffmpeg/ffprobe: {} / {}", Self::process_output("ffmpeg", "-version"), Self::process_output("ffprobe", "-version"))?; writeln!(s, " pdftoppm : {}", Self::process_output("pdftoppm", "--help"))?; writeln!(s, " magick : {}", Self::process_output("magick", "--version"))?; writeln!(s, " fzf : {}", Self::process_output("fzf", "--version"))?; #[rustfmt::skip] writeln!(s, " fd/fdfind : {} / {}", Self::process_output("fd", "--version"), Self::process_output("fdfind", "--version"))?; writeln!(s, " rg : {}", Self::process_output("rg", "--version"))?; writeln!(s, " chafa : {}", Self::process_output("chafa", "--version"))?; writeln!(s, " zoxide : {}", Self::process_output("zoxide", "--version"))?; #[rustfmt::skip] writeln!(s, " 7zz/7z : {} / {}", Self::process_output("7zz", "i"), Self::process_output("7z", "i"))?; writeln!(s, " resvg : {}", Self::process_output("resvg", "--version"))?; writeln!(s, " jq : {}", Self::process_output("jq", "--version"))?; writeln!(s, "\nClipboard")?; #[rustfmt::skip] writeln!(s, " wl-copy/paste: {} / {}", Self::process_output("wl-copy", "--version"), Self::process_output("wl-paste", "--version"))?; writeln!(s, " xclip : {}", Self::process_output("xclip", "-version"))?; writeln!(s, " xsel : {}", Self::process_output("xsel", "--version"))?; writeln!(s, "\nRoutine")?; writeln!(s, " `file -bL --mime-type`: {}", Self::file1_output())?; writeln!( s, "\n\nSee https://yazi-rs.github.io/docs/plugins/overview#debugging on how to enable logging or debug runtime errors." )?; Ok(s) } fn config_state(name: &str) -> String { let p = Xdg::config_dir().join(format!("{name}.toml")); match std::fs::read_to_string(&p) { Ok(s) if s.is_empty() => format!("{} (empty)", p.display()), Ok(s) if s.trim().is_empty() => format!("{} (whitespaces)", p.display()), Ok(s) => format!("{} ({} chars)", p.display(), s.chars().count()), Err(e) => format!("{} ({e})", p.display()), } } fn process_output(name: impl AsRef<OsStr>, arg: impl AsRef<OsStr>) -> String { match std::process::Command::new(&name).arg(arg).output() { Ok(out) if out.status.success() => { let line = String::from_utf8_lossy(&if out.stdout.is_empty() { out.stderr } else { out.stdout }) .trim() .lines() .next() .unwrap_or_default() .to_owned(); if name.as_ref() == "ya" { line.trim_start_matches("Ya ").to_owned() } else { Regex::new(r"\d+\.\d+(\.\d+-\d+|\.\d+|\b)") .unwrap() .find(&line) .map(|m| m.as_str().to_owned()) .unwrap_or(line) } } Ok(out) => format!("{:?}, {:?}", out.status, String::from_utf8_lossy(&out.stderr)), Err(e) => format!("{e}"), } } fn file1_output() -> String { use std::io::Write; let p = env::temp_dir().join(format!("yazi-debug-{}", timestamp_us())); std::fs::File::create_new(&p).map(|mut f| f.write_all(b"Hello, World!")).ok(); let cmd = env::var_os("YAZI_FILE_ONE").unwrap_or("file".into()); match std::process::Command::new(cmd).args(["-bL", "--mime-type"]).arg(&p).output() { Ok(out) => { String::from_utf8_lossy(&out.stdout).trim().lines().next().unwrap_or_default().to_owned() } Err(e) => format!("{e}"), } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-boot/src/actions/mod.rs
yazi-boot/src/actions/mod.rs
yazi_macro::mod_flat!(actions clear_cache debug rustc triple version);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-boot/src/actions/actions.rs
yazi-boot/src/actions/actions.rs
use std::process; pub struct Actions; impl Actions { pub(crate) fn act(args: &crate::Args) { if args.debug { println!("{}", Self::debug().unwrap()); process::exit(0); } if args.version { println!("Yazi {}", Self::version()); process::exit(0); } if args.clear_cache { Self::clear_cache(); process::exit(0); } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/build.rs
yazi-dds/build.rs
use std::error::Error; use vergen_gitcl::{Emitter, GitclBuilder}; fn main() -> Result<(), Box<dyn Error>> { Emitter::default() .add_instructions(&GitclBuilder::default().commit_date(true).sha(true).build()?)? .emit()?; Ok(()) }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/stream.rs
yazi-dds/src/stream.rs
use tokio::io::{BufReader, Lines, ReadHalf, WriteHalf}; pub(super) struct Stream; use tokio::io::AsyncBufReadExt; #[cfg(unix)] pub(super) type ClientReader = Lines<BufReader<ReadHalf<tokio::net::UnixStream>>>; #[cfg(not(unix))] pub(super) type ClientReader = Lines<BufReader<ReadHalf<tokio::net::TcpStream>>>; #[cfg(unix)] pub(super) type ClientWriter = WriteHalf<tokio::net::UnixStream>; #[cfg(not(unix))] pub(super) type ClientWriter = WriteHalf<tokio::net::TcpStream>; #[cfg(unix)] pub(super) type ServerListener = tokio::net::UnixListener; #[cfg(not(unix))] pub(super) type ServerListener = tokio::net::TcpListener; impl Stream { #[cfg(unix)] pub(super) async fn connect() -> std::io::Result<(ClientReader, ClientWriter)> { let stream = tokio::net::UnixStream::connect(Self::socket_file()).await?; let (reader, writer) = tokio::io::split(stream); Ok((BufReader::new(reader).lines(), writer)) } #[cfg(not(unix))] pub(super) async fn connect() -> std::io::Result<(ClientReader, ClientWriter)> { let stream = tokio::net::TcpStream::connect("127.0.0.1:33581").await?; let (reader, writer) = tokio::io::split(stream); Ok((BufReader::new(reader).lines(), writer)) } #[cfg(unix)] pub(super) async fn bind() -> std::io::Result<ServerListener> { use yazi_fs::provider::Provider; let p = Self::socket_file(); yazi_fs::provider::local::Local::regular(&p).remove_file().await.ok(); tokio::net::UnixListener::bind(p) } #[cfg(not(unix))] pub(super) async fn bind() -> std::io::Result<ServerListener> { tokio::net::TcpListener::bind("127.0.0.1:33581").await } #[cfg(unix)] fn socket_file() -> std::path::PathBuf { use std::env::temp_dir; use uzers::Users; use yazi_shared::USERS_CACHE; temp_dir().join(format!(".yazi_dds-{}.sock", USERS_CACHE.get_current_uid())) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/lib.rs
yazi-dds/src/lib.rs
mod macros; yazi_macro::mod_pub!(ember spark); yazi_macro::mod_flat!(client payload pubsub pump sendable server state stream); pub fn init() { let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); // Client ID.init(yazi_boot::ARGS.client_id.unwrap_or(yazi_shared::Id::unique())); PEERS.with(<_>::default); QUEUE_TX.init(tx); QUEUE_RX.init(rx); // Server CLIENTS.with(<_>::default); STATE.with(<_>::default); // Pubsub LOCAL.with(<_>::default); REMOTE.with(<_>::default); // Env unsafe { if let Some(s) = std::env::var("YAZI_ID").ok().filter(|s| !s.is_empty()) { std::env::set_var("YAZI_PID", s); } std::env::set_var("YAZI_ID", ID.to_string()); std::env::set_var( "YAZI_LEVEL", (std::env::var("YAZI_LEVEL").unwrap_or_default().parse().unwrap_or(0u16) + 1).to_string(), ); } } pub fn serve() { Pump::serve(); Client::serve(); } pub async fn shutdown() { Pump::shutdown().await; }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/state.rs
yazi-dds/src/state.rs
use std::{mem, ops::Deref, sync::atomic::{AtomicU64, Ordering}}; use anyhow::Result; use hashbrown::HashMap; use parking_lot::RwLock; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, BufWriter}; use yazi_boot::BOOT; use yazi_fs::provider::{FileBuilder, Provider, local::{Gate, Local}}; use yazi_shared::{RoCell, timestamp_us}; use crate::CLIENTS; pub static STATE: RoCell<State> = RoCell::new(); #[derive(Default)] pub struct State { inner: RwLock<Option<HashMap<String, String>>>, last: AtomicU64, } impl Deref for State { type Target = RwLock<Option<HashMap<String, String>>>; fn deref(&self) -> &Self::Target { &self.inner } } impl State { pub fn set(&self, kind: &str, sender: u64, body: &str) -> bool { let Some(inner) = &mut *self.inner.write() else { return false }; if body == "null" { return inner .remove(kind) .map(|_| self.last.store(timestamp_us(), Ordering::Relaxed)) .is_some(); } let value = format!("{kind},0,{sender},{body}\n"); if inner.get(kind).is_some_and(|s| *s == value) { return false; } inner.insert(kind.to_owned(), value); self.last.store(timestamp_us(), Ordering::Relaxed); true } pub async fn load_or_create(&self) { if self.load().await.is_err() { self.inner.write().replace(Default::default()); self.last.store(timestamp_us(), Ordering::Relaxed); } } pub async fn drain(&self) -> Result<()> { let Some(inner) = self.inner.write().take() else { return Ok(()) }; if self.skip().await.unwrap_or(false) { return Ok(()); } Local::regular(&BOOT.state_dir).create_dir_all().await?; let mut buf = BufWriter::new( Gate::default() .write(true) .create(true) .truncate(true) .open(BOOT.state_dir.join(".dds")) .await?, ); let mut state = inner.into_iter().collect::<Vec<_>>(); state.sort_unstable_by(|(a, _), (b, _)| a.cmp(b)); for (_, v) in state { buf.write_all(v.as_bytes()).await?; } buf.flush().await?; Ok(()) } async fn load(&self) -> Result<()> { let mut file = BufReader::new(Local::regular(&BOOT.state_dir.join(".dds")).open().await?); let mut buf = String::new(); let mut inner = HashMap::new(); while file.read_line(&mut buf).await? > 0 { let line = mem::take(&mut buf); let mut parts = line.splitn(4, ','); let Some(kind) = parts.next() else { continue }; let Some(_) = parts.next() else { continue }; inner.insert(kind.to_owned(), line); } let clients = CLIENTS.read(); for payload in inner.values() { clients.values().for_each(|c| _ = c.tx.send(payload.clone())); } self.inner.write().replace(inner); self.last.store(timestamp_us(), Ordering::Relaxed); Ok(()) } async fn skip(&self) -> Result<bool> { let cha = Local::regular(&BOOT.state_dir.join(".dds")).symlink_metadata().await?; let modified = cha.mtime_dur()?.as_micros(); Ok(modified >= self.last.load(Ordering::Relaxed) as u128) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/client.rs
yazi-dds/src/client.rs
use std::{iter, mem, str::FromStr}; use anyhow::{Context, Result, bail}; use hashbrown::{HashMap, HashSet}; use parking_lot::RwLock; use serde::{Deserialize, Serialize}; use tokio::{io::AsyncWriteExt, select, sync::mpsc, task::JoinHandle, time}; use tracing::error; use yazi_macro::try_format; use yazi_shared::{Id, RoCell}; use crate::{ClientReader, ClientWriter, Payload, Pubsub, Server, Stream, ember::{Ember, EmberBye, EmberHi}}; pub static ID: RoCell<Id> = RoCell::new(); pub(super) static PEERS: RoCell<RwLock<HashMap<Id, Peer>>> = RoCell::new(); pub(super) static QUEUE_TX: RoCell<mpsc::UnboundedSender<String>> = RoCell::new(); pub(super) static QUEUE_RX: RoCell<mpsc::UnboundedReceiver<String>> = RoCell::new(); #[derive(Debug)] pub struct Client { pub(super) id: Id, pub(super) tx: mpsc::UnboundedSender<String>, pub(super) abilities: HashSet<String>, } #[derive(Debug, Deserialize, Serialize)] pub struct Peer { pub(super) abilities: HashSet<String>, } impl Client { /// Connect to an existing server or start a new one. pub(super) fn serve() { let mut rx = QUEUE_RX.drop(); while rx.try_recv().is_ok() {} tokio::spawn(async move { let mut server = None; let (mut lines, mut writer) = Self::connect(&mut server).await; loop { select! { Some(payload) = rx.recv() => { if writer.write_all(payload.as_bytes()).await.is_err() { (lines, writer) = Self::reconnect(&mut server).await; writer.write_all(payload.as_bytes()).await.ok(); // Retry once } } Ok(next) = lines.next_line() => { let Some(line) = next else { (lines, writer) = Self::reconnect(&mut server).await; continue; }; if line.is_empty() { continue; } else if line.starts_with("hey,") { Self::handle_hey(&line); } else if let Err(e) = Payload::from_str(&line).and_then(|p| p.emit()) { error!("Could not parse payload:\n{line}\n\nError:\n{e}"); } } } } }); } /// Connect to an existing server to send a single message. pub async fn shot(kind: &str, receiver: Id, body: &str) -> Result<()> { Ember::validate(kind)?; let payload = try_format!( "{}\n{kind},{receiver},{ID},{body}\n{}\n", Payload::new(EmberHi::borrowed(iter::empty())), Payload::new(EmberBye::owned()) )?; let (mut lines, mut writer) = Stream::connect().await?; writer.write_all(payload.as_bytes()).await?; writer.flush().await?; drop(writer); let (mut peers, mut version) = Default::default(); while let Ok(Some(line)) = lines.next_line().await { match line.split(',').next() { Some("hey") => { if let Ok(Ember::Hey(hey)) = Payload::from_str(&line).map(|p| p.body) { (peers, version) = (hey.peers, Some(hey.version)); } } Some("bye") => break, _ => {} } } if version.as_deref() != Some(EmberHi::version()) { bail!( "Incompatible version (Ya {}, Yazi {}). Restart all `ya` and `yazi` processes if you upgrade either one.", EmberHi::version(), version.as_deref().unwrap_or("Unknown") ); } match (receiver, peers.get(&receiver).map(|p| p.able(kind))) { // Send to all receivers (Id(0), _) if peers.is_empty() => { bail!("No receiver found. Check if any receivers are running.") } (Id(0), _) if peers.values().all(|p| !p.able(kind)) => { bail!("No receiver has the ability to receive `{kind}` messages.") } (Id(0), _) => {} // Send to a specific receiver (_, Some(true)) => {} (_, Some(false)) => { bail!("Receiver `{receiver}` does not have the ability to receive `{kind}` messages.") } (_, None) => bail!("Receiver `{receiver}` not found. Check if the receiver is running."), } Ok(()) } /// Connect to an existing server and listen in on the messages that are being /// sent by other yazi instances: /// - If no server is running, fail right away; /// - If a server is closed, attempt to reconnect forever. pub async fn draw(kinds: HashSet<&str>) -> Result<()> { async fn make(kinds: &HashSet<&str>) -> Result<ClientReader> { let (lines, mut writer) = Stream::connect().await?; let hi = Payload::new(EmberHi::borrowed(kinds.iter().copied())); writer.write_all(try_format!("{hi}\n")?.as_bytes()).await?; writer.flush().await?; Ok(lines) } let mut lines = make(&kinds).await.context("No running Yazi instance found")?; loop { match lines.next_line().await? { Some(s) => { let kind = s.split(',').next(); if matches!(kind, Some(kind) if kinds.contains(kind)) { println!("{s}"); } } None => loop { time::sleep(time::Duration::from_secs(1)).await; if let Ok(new) = make(&kinds).await { lines = new; break; } }, } } } pub(super) fn push<'a>(payload: impl Into<Payload<'a>>) -> Result<()> { Ok(QUEUE_TX.send(try_format!("{}\n", payload.into())?)?) } pub(super) fn able(&self, ability: &str) -> bool { self.abilities.contains(ability) } async fn connect(server: &mut Option<JoinHandle<()>>) -> (ClientReader, ClientWriter) { let mut first = true; loop { if let Ok(conn) = Stream::connect().await { Pubsub::pub_inner_hi(); return conn; } server.take().map(|h| h.abort()); *server = Server::make().await.ok(); if server.is_some() { super::STATE.load_or_create().await; } if mem::replace(&mut first, false) && server.is_some() { continue; } time::sleep(time::Duration::from_secs(1)).await; } } async fn reconnect(server: &mut Option<JoinHandle<()>>) -> (ClientReader, ClientWriter) { PEERS.write().clear(); time::sleep(time::Duration::from_millis(500)).await; Self::connect(server).await } fn handle_hey(s: &str) { if let Ok(Ember::Hey(mut hey)) = Payload::from_str(s).map(|p| p.body) { hey.peers.retain(|&id, _| id != *ID); *PEERS.write() = hey.peers; } } } impl Peer { pub(super) fn new(abilities: &HashSet<String>) -> Self { Self { abilities: abilities.clone() } } pub(super) fn able(&self, ability: &str) -> bool { self.abilities.contains(ability) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/pubsub.rs
yazi-dds/src/pubsub.rs
use anyhow::Result; use hashbrown::{HashMap, HashSet}; use mlua::Function; use parking_lot::RwLock; use yazi_boot::BOOT; use yazi_fs::FolderStage; use yazi_shared::{Id, RoCell, url::{Url, UrlBuf, UrlBufCov}}; use crate::{Client, ID, PEERS, ember::{BodyDuplicateItem, BodyMoveItem, Ember, EmberBulk, EmberHi}}; pub static LOCAL: RoCell<RwLock<HashMap<String, HashMap<String, Function>>>> = RoCell::new(); pub static REMOTE: RoCell<RwLock<HashMap<String, HashMap<String, Function>>>> = RoCell::new(); macro_rules! sub { ($var:ident) => { |plugin: &str, kind: &str, f: Function| { let mut var = $var.write(); let Some(map) = var.get_mut(kind) else { var.insert(kind.to_owned(), HashMap::from_iter([(plugin.to_owned(), f)])); return true; }; if !map.contains_key(plugin) { map.insert(plugin.to_owned(), f); return true; } false } }; } macro_rules! unsub { ($var:ident) => { |plugin: &str, kind: &str| { let mut var = $var.write(); let Some(map) = var.get_mut(kind) else { return false }; if map.remove(plugin).is_none() { return false; } if map.is_empty() { var.remove(kind); } true } }; } macro_rules! pub_after { (&impl $name:ident ($($param:ident: $param_ty:ty),*), ($($borrowed:expr),*), ($($owned:expr),*), $static:literal) => { paste::paste! { pub fn [<pub_after_ $name>]($($param: $param_ty),*) -> Result<()> { use crate::ember::[<Ember $name:camel>] as B; let n = if $static { concat!("@", stringify!($name)) } else { stringify!($name) }; if BOOT.local_events.contains(n) { B::borrowed($($borrowed),*).with_receiver(*ID).flush()?; } if ($static && Self::any_remote_own(n)) || (!$static && PEERS.read().values().any(|p| p.able(n))) { Client::push(B::borrowed($($borrowed),*))?; } if LOCAL.read().contains_key(n) { Self::r#pub(B::owned($($owned),*))?; } Ok(()) } } }; ($name:ident ($($param:ident: $param_ty:ty),*), ($($borrowed:expr),*)) => { pub_after!(&impl $name($($param: $param_ty),*), ($($borrowed),*), ($($borrowed),*), false); }; ($name:ident ($($param:ident: $param_ty:ty),*), ($($borrowed:expr),*), ($($owned:expr),*)) => { pub_after!(&impl $name($($param: $param_ty),*), ($($borrowed),*), ($($owned),*), false); }; (@ $name:ident ($($param:ident: $param_ty:ty),*), ($($borrowed:expr),*)) => { pub_after!(&impl $name($($param: $param_ty),*), ($($borrowed),*), ($($borrowed),*), true); }; (@ $name:ident ($($param:ident: $param_ty:ty),*), ($($borrowed:expr),*), ($($owned:expr),*)) => { pub_after!(&impl $name($($param: $param_ty),*), ($($borrowed),*), ($($owned),*), true); }; } pub struct Pubsub; impl Pubsub { pub fn sub(plugin: &str, kind: &str, f: Function) -> bool { sub!(LOCAL)(plugin, kind, f) } pub fn sub_remote(plugin: &str, kind: &str, f: Function) -> bool { sub!(REMOTE)(plugin, kind, f) && Self::pub_inner_hi() } pub fn unsub(plugin: &str, kind: &str) -> bool { unsub!(LOCAL)(plugin, kind) } pub fn unsub_remote(plugin: &str, kind: &str) -> bool { unsub!(REMOTE)(plugin, kind) && Self::pub_inner_hi() } pub fn r#pub(body: Ember<'static>) -> Result<()> { body.with_receiver(*ID).emit() } pub fn pub_to(receiver: Id, body: Ember<'static>) -> Result<()> { if receiver == *ID { return Self::r#pub(body); } let kind = body.kind(); if receiver == 0 && Self::any_remote_own(kind) { Client::push(body)?; } else if PEERS.read().get(&receiver).is_some_and(|c| c.able(kind)) { Client::push(body.with_receiver(receiver))?; } Ok(()) } pub fn pub_inner_hi() -> bool { let abilities = REMOTE.read().keys().cloned().collect(); let abilities = BOOT.remote_events.union(&abilities).map(AsRef::as_ref); // FIXME: handle error Client::push(EmberHi::borrowed(abilities)).ok(); true } pub fn pub_after_bulk<'a, I>(changes: I) -> Result<()> where I: Iterator<Item = (Url<'a>, Url<'a>)> + Clone, { if BOOT.local_events.contains("bulk") { EmberBulk::borrowed(changes.clone()).with_receiver(*ID).flush()?; } if PEERS.read().values().any(|p| p.able("bulk")) { Client::push(EmberBulk::borrowed(changes.clone()))?; } if LOCAL.read().contains_key("bulk") { Self::r#pub(EmberBulk::owned(changes))?; } Ok(()) } fn any_remote_own(kind: &str) -> bool { REMOTE.read().contains_key(kind) // Own remote abilities || PEERS.read().values().any(|p| p.able(kind)) // Remote peers' abilities || BOOT.remote_events.contains(kind) // Own abilities from the command-line argument } } impl Pubsub { pub_after!(tab(idx: Id), (idx)); pub_after!(cd(tab: Id, url: &UrlBuf), (tab, url)); pub_after!(load(tab: Id, url: &UrlBuf, stage: &FolderStage), (tab, url, stage)); pub_after!(hover(tab: Id, url: Option<&UrlBuf>), (tab, url)); pub_after!(rename(tab: Id, from: &UrlBuf, to: &UrlBuf), (tab, from, to)); pub_after!(@yank(cut: bool, urls: &HashSet<UrlBufCov>), (cut, urls)); pub_after!(duplicate(items: Vec<BodyDuplicateItem>), (&items), (items)); pub_after!(move(items: Vec<BodyMoveItem>), (&items), (items)); pub_after!(trash(urls: Vec<UrlBuf>), (&urls), (urls)); pub_after!(delete(urls: Vec<UrlBuf>), (&urls), (urls)); pub_after!(mount(), ()); }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/macros.rs
yazi-dds/src/macros.rs
#[macro_export] macro_rules! spark { (mgr: $name:ident, $body:expr) => { paste::paste! { $crate::spark::Spark::[<$name:camel>]($body) } }; ($layer:ident : $name:ident, $body:expr) => { paste::paste! { $crate::spark::Spark::[<$layer:camel $name:camel>]($body.into()) } }; } #[macro_export] macro_rules! try_from_spark { ($opt:ty, $($($layer:ident)? : $name:ident),+) => { impl<'a> std::convert::TryFrom<$crate::spark::Spark<'a>> for paste::paste! { yazi_parser::$opt } { type Error = (); fn try_from(value: $crate::spark::Spark<'a>) -> Result<Self, Self::Error> { $( try_from_spark!(@if $($layer)? : $name, value); )+ Err(()) } } }; (@if mgr : $name:ident, $value:ident) => { try_from_spark!(@if : $name, $value); }; (@if $($layer:ident)? : $name:ident, $value:ident) => { if let paste::paste! { $crate::spark::Spark::[<$($layer:camel)* $name:camel>](opt) } = $value { return Ok(<_>::from(opt)) } }; }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/payload.rs
yazi-dds/src/payload.rs
use std::{fmt::Display, io::Write, str::FromStr}; use anyhow::{Result, anyhow}; use yazi_boot::BOOT; use yazi_macro::{emit, relay}; use yazi_shared::Id; use crate::{ID, ember::Ember}; #[derive(Debug)] pub struct Payload<'a> { pub receiver: Id, pub sender: Id, pub body: Ember<'a>, } impl<'a> Payload<'a> { pub(super) fn new(body: Ember<'a>) -> Self { Self { receiver: Id(0), sender: *ID, body } } pub(super) fn flush(&self) -> Result<()> { writeln!(std::io::stdout(), "{self}")?; Ok(()) } pub(super) fn try_flush(&self) -> Result<()> { let b = if self.receiver == 0 { BOOT.remote_events.contains(self.body.kind()) } else if let Ember::Custom(b) = &self.body { BOOT.local_events.contains(&b.kind) } else { false }; if b { self.flush() } else { Ok(()) } } pub(super) fn with_receiver(mut self, receiver: Id) -> Self { self.receiver = receiver; self } pub(super) fn with_sender(mut self, sender: Id) -> Self { self.sender = sender; self } } impl Payload<'static> { pub(super) fn emit(self) -> Result<()> { self.try_flush()?; emit!(Call(relay!(app:accept_payload).with_any("payload", self))); Ok(()) } } impl FromStr for Payload<'static> { type Err = anyhow::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let mut parts = s.splitn(4, ','); let kind = parts.next().ok_or_else(|| anyhow!("empty kind"))?; let receiver = parts.next().and_then(|s| s.parse().ok()).ok_or_else(|| anyhow!("invalid receiver"))?; let sender = parts.next().and_then(|s| s.parse().ok()).ok_or_else(|| anyhow!("invalid sender"))?; let body = parts.next().ok_or_else(|| anyhow!("empty body"))?; Ok(Self { receiver, sender, body: Ember::from_str(kind, body)? }) } } impl<'a> From<Ember<'a>> for Payload<'a> { fn from(value: Ember<'a>) -> Self { Self::new(value) } } impl Display for Payload<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let result = match &self.body { Ember::Hi(b) => serde_json::to_string(b), Ember::Hey(b) => serde_json::to_string(b), Ember::Bye(b) => serde_json::to_string(b), Ember::Cd(b) => serde_json::to_string(b), Ember::Load(b) => serde_json::to_string(b), Ember::Hover(b) => serde_json::to_string(b), Ember::Tab(b) => serde_json::to_string(b), Ember::Rename(b) => serde_json::to_string(b), Ember::Bulk(b) => serde_json::to_string(b), Ember::Yank(b) => serde_json::to_string(b), Ember::Duplicate(b) => serde_json::to_string(b), Ember::Move(b) => serde_json::to_string(b), Ember::Trash(b) => serde_json::to_string(b), Ember::Delete(b) => serde_json::to_string(b), Ember::Mount(b) => serde_json::to_string(b), Ember::Custom(b) => serde_json::to_string(b), }; if let Ok(s) = result { write!(f, "{},{},{},{s}", self.body.kind(), self.receiver, self.sender) } else { Err(std::fmt::Error) } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/pump.rs
yazi-dds/src/pump.rs
use std::time::Duration; use tokio::{pin, select, sync::mpsc}; use tokio_stream::{StreamExt, wrappers::UnboundedReceiverStream}; use yazi_macro::err; use yazi_shared::{RoCell, url::UrlBuf}; use crate::{Pubsub, ember::{BodyDuplicateItem, BodyMoveItem}}; static DUPLICATE_TX: RoCell<mpsc::UnboundedSender<BodyDuplicateItem>> = RoCell::new(); static MOVE_TX: RoCell<mpsc::UnboundedSender<BodyMoveItem>> = RoCell::new(); static TRASH_TX: RoCell<mpsc::UnboundedSender<UrlBuf>> = RoCell::new(); static DELETE_TX: RoCell<mpsc::UnboundedSender<UrlBuf>> = RoCell::new(); static SHUTDOWN_TX: RoCell<mpsc::UnboundedSender<()>> = RoCell::new(); pub struct Pump; impl Pump { pub fn push_duplicate<U>(from: U, to: U) where U: Into<UrlBuf>, { DUPLICATE_TX.send(BodyDuplicateItem { from: from.into(), to: to.into() }).ok(); } pub fn push_move<U>(from: U, to: U) where U: Into<UrlBuf>, { MOVE_TX.send(BodyMoveItem { from: from.into(), to: to.into() }).ok(); } pub fn push_trash<U>(target: U) where U: Into<UrlBuf>, { TRASH_TX.send(target.into()).ok(); } pub fn push_delete<U>(target: U) where U: Into<UrlBuf>, { DELETE_TX.send(target.into()).ok(); } pub(super) fn serve() { let (move_tx, move_rx) = mpsc::unbounded_channel(); let (duplicate_tx, duplicate_rx) = mpsc::unbounded_channel(); let (trash_tx, trash_rx) = mpsc::unbounded_channel(); let (delete_tx, delete_rx) = mpsc::unbounded_channel(); let (shutdown_tx, mut shutdown_rx) = mpsc::unbounded_channel(); DUPLICATE_TX.init(duplicate_tx); MOVE_TX.init(move_tx); TRASH_TX.init(trash_tx); DELETE_TX.init(delete_tx); SHUTDOWN_TX.init(shutdown_tx); tokio::spawn(async move { let duplicate_rx = UnboundedReceiverStream::new(duplicate_rx).chunks_timeout(1000, Duration::from_millis(500)); let move_rx = UnboundedReceiverStream::new(move_rx).chunks_timeout(1000, Duration::from_millis(500)); let trash_rx = UnboundedReceiverStream::new(trash_rx).chunks_timeout(1000, Duration::from_millis(500)); let delete_rx = UnboundedReceiverStream::new(delete_rx).chunks_timeout(1000, Duration::from_millis(500)); pin!(duplicate_rx); pin!(move_rx); pin!(trash_rx); pin!(delete_rx); loop { select! { Some(items) = duplicate_rx.next() => err!(Pubsub::pub_after_duplicate(items)), Some(items) = move_rx.next() => err!(Pubsub::pub_after_move(items)), Some(urls) = trash_rx.next() => err!(Pubsub::pub_after_trash(urls)), Some(urls) = delete_rx.next() => err!(Pubsub::pub_after_delete(urls)), _ = shutdown_rx.recv() => { shutdown_rx.close(); break; } } } }); } pub(super) async fn shutdown() { SHUTDOWN_TX.send(()).ok(); SHUTDOWN_TX.closed().await; } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/server.rs
yazi-dds/src/server.rs
use std::{str::FromStr, time::Duration}; use anyhow::Result; use hashbrown::HashMap; use parking_lot::RwLock; use tokio::{io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, select, sync::mpsc::{self, UnboundedReceiver}, task::JoinHandle, time}; use yazi_macro::try_format; use yazi_shared::{Id, RoCell}; use crate::{Client, ClientWriter, Payload, Peer, STATE, Stream, ember::{Ember, EmberBye, EmberHey}}; pub(super) static CLIENTS: RoCell<RwLock<HashMap<Id, Client>>> = RoCell::new(); pub(super) struct Server; impl Server { pub(super) async fn make() -> Result<JoinHandle<()>> { CLIENTS.write().clear(); let listener = Stream::bind().await?; Ok(tokio::spawn(async move { while let Ok((stream, _)) = listener.accept().await { let (tx, mut rx) = mpsc::unbounded_channel::<String>(); let (reader, mut writer) = tokio::io::split(stream); tokio::spawn(async move { let mut id = None; let mut lines = BufReader::new(reader).lines(); loop { select! { Some(payload) = rx.recv() => { if writer.write_all(payload.as_bytes()).await.is_err() { break; } } _ = time::sleep(Duration::from_secs(5)) => { if writer.write_u8(b'\n').await.is_err() { break; } } Ok(Some(mut line)) = lines.next_line() => { if line.starts_with("hi,") { Self::handle_hi(line, &mut id, tx.clone()); continue; } let Some(id) = id else { continue }; if line.starts_with("bye,") { Self::handle_bye(id, rx, writer).await; break; } let mut parts = line.splitn(4, ','); let Some(kind) = parts.next() else { continue }; let Some(receiver) = parts.next().and_then(|s| s.parse::<Id>().ok()) else { continue }; let Some(sender) = parts.next().and_then(|s| s.parse::<u64>().ok()) else { continue }; let clients = CLIENTS.read(); let clients: Vec<_> = if receiver == 0 { clients.values().filter(|c| c.able(kind)).collect() } else if let Some(c) = clients.get(&receiver).filter(|c| c.able(kind)) { vec![c] } else { vec![] }; if clients.is_empty() { continue; } if receiver == 0 && kind.starts_with('@') { let Some(body) = parts.next() else { continue }; if !STATE.set(kind, sender, body) { continue } } line.push('\n'); clients.into_iter().for_each(|c| _ = c.tx.send(line.clone())); } else => break } } let mut clients = CLIENTS.write(); if id.and_then(|id| clients.remove(&id)).is_some() { Self::handle_hey(&clients); } }); } })) } fn handle_hi(s: String, id: &mut Option<Id>, tx: mpsc::UnboundedSender<String>) { let Ok(payload) = Payload::from_str(&s) else { return }; let Ember::Hi(hi) = payload.body else { return }; if id.is_none() && let Some(ref state) = *STATE.read() { state.values().for_each(|s| _ = tx.send(s.clone())); } let mut clients = CLIENTS.write(); id.replace(payload.sender).and_then(|id| clients.remove(&id)); clients.insert(payload.sender, Client { id: payload.sender, tx, abilities: hi.abilities.into_iter().map(|s| s.into_owned()).collect(), }); Self::handle_hey(&clients); } fn handle_hey(clients: &HashMap<Id, Client>) { let payload = Payload::new(EmberHey::owned( clients.values().map(|c| (c.id, Peer::new(&c.abilities))).collect(), )); if let Ok(s) = try_format!("{payload}\n") { clients.values().for_each(|c| _ = c.tx.send(s.clone())); } } async fn handle_bye(id: Id, mut rx: UnboundedReceiver<String>, mut writer: ClientWriter) { while let Ok(payload) = rx.try_recv() { if writer.write_all(payload.as_bytes()).await.is_err() { break; } } let bye = EmberBye::owned().with_receiver(id).with_sender(Id(0)); if let Ok(s) = try_format!("{bye}") { writer.write_all(s.as_bytes()).await.ok(); writer.flush().await.ok(); } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/sendable.rs
yazi-dds/src/sendable.rs
use std::{any::TypeId, borrow::Cow}; use hashbrown::HashMap; use mlua::{ExternalError, IntoLua, Lua, MultiValue, Table, Value}; use ordered_float::OrderedFloat; use yazi_shared::{data::{Data, DataKey}, replace_cow}; pub struct Sendable; impl Sendable { pub fn value_to_data(lua: &Lua, value: Value) -> mlua::Result<Data> { Ok(match value { Value::Nil => Data::Nil, Value::Boolean(b) => Data::Boolean(b), Value::LightUserData(_) => Err("light userdata is not supported".into_lua_err())?, Value::Integer(i) => Data::Integer(i), Value::Number(n) => Data::Number(n), Value::String(b) => { if let Ok(s) = b.to_str() { Data::String(s.to_owned().into()) } else { Data::Bytes(b.as_bytes().to_owned()) } } Value::Table(t) => { let (mut i, mut map) = (1, HashMap::with_capacity(t.raw_len())); for result in t.pairs::<Value, Value>() { let (k, v) = result?; let k = Self::value_to_key(k)?; if k == DataKey::Integer(i) { i += 1; } map.insert(k, Self::value_to_data(lua, v)?); } if map.len() == i as usize - 1 { Data::List((1..i).map(|i| map.remove(&DataKey::Integer(i)).unwrap()).collect()) } else { Data::Dict(map) } } Value::Function(_) => Err("function is not supported".into_lua_err())?, Value::Thread(_) => Err("thread is not supported".into_lua_err())?, Value::UserData(ud) => match ud.type_id() { Some(t) if t == TypeId::of::<yazi_binding::Url>() => { Data::Url(ud.take::<yazi_binding::Url>()?.into()) } Some(t) if t == TypeId::of::<yazi_binding::Path>() => { Data::Path(ud.take::<yazi_binding::Path>()?.into()) } Some(t) if t == TypeId::of::<yazi_binding::Id>() => { Data::Id(**ud.borrow::<yazi_binding::Id>()?) } Some(t) if t == TypeId::of::<yazi_fs::FilesOp>() => { Data::Any(Box::new(ud.take::<yazi_fs::FilesOp>()?)) } Some(t) if t == TypeId::of::<yazi_parser::mgr::UpdateYankedIter>() => { Data::Any(Box::new(ud.take::<yazi_parser::mgr::UpdateYankedIter>()?.into_opt(lua)?)) } _ => Err(format!("unsupported userdata included: {ud:?}").into_lua_err())?, }, Value::Error(_) => Err("error is not supported".into_lua_err())?, Value::Other(..) => Err("unknown data is not supported".into_lua_err())?, }) } pub fn data_to_value(lua: &Lua, data: Data) -> mlua::Result<Value> { Ok(match data { Data::List(l) => { let mut vec = Vec::with_capacity(l.len()); for v in l.into_iter() { vec.push(Self::data_to_value(lua, v)?); } Value::Table(lua.create_sequence_from(vec)?) } Data::Dict(d) => { let seq_len = d.keys().filter(|&k| k.is_integer()).count(); let tbl = lua.create_table_with_capacity(seq_len, d.len() - seq_len)?; for (k, v) in d { tbl.raw_set(Self::key_to_value(lua, k)?, Self::data_to_value(lua, v)?)?; } Value::Table(tbl) } Data::Url(u) => yazi_binding::Url::new(u).into_lua(lua)?, Data::Path(u) => yazi_binding::Path::new(u).into_lua(lua)?, Data::Any(a) => { if a.is::<yazi_fs::FilesOp>() { lua.create_any_userdata(*a.downcast::<yazi_fs::FilesOp>().unwrap())?.into_lua(lua)? } else if a.is::<yazi_parser::mgr::UpdateYankedOpt>() { a.downcast::<yazi_parser::mgr::UpdateYankedOpt>().unwrap().into_lua(lua)? } else { Err("unsupported Data::Any included".into_lua_err())? } } data => Self::data_to_value_ref(lua, &data)?, }) } pub fn data_to_value_ref(lua: &Lua, data: &Data) -> mlua::Result<Value> { Ok(match data { Data::Nil => Value::Nil, Data::Boolean(b) => Value::Boolean(*b), Data::Integer(i) => Value::Integer(*i), Data::Number(n) => Value::Number(*n), Data::String(s) => Value::String(lua.create_string(&**s)?), Data::List(l) => { let mut vec = Vec::with_capacity(l.len()); for v in l { vec.push(Self::data_to_value_ref(lua, v)?); } Value::Table(lua.create_sequence_from(vec)?) } Data::Dict(d) => { let seq_len = d.keys().filter(|&k| k.is_integer()).count(); let tbl = lua.create_table_with_capacity(seq_len, d.len() - seq_len)?; for (k, v) in d { tbl.raw_set(Self::key_to_value_ref(lua, k)?, Self::data_to_value_ref(lua, v)?)?; } Value::Table(tbl) } Data::Id(i) => yazi_binding::Id(*i).into_lua(lua)?, Data::Url(u) => yazi_binding::Url::new(u).into_lua(lua)?, Data::Path(u) => yazi_binding::Path::new(u).into_lua(lua)?, Data::Bytes(b) => Value::String(lua.create_string(b)?), Data::Any(a) => { if let Some(t) = a.downcast_ref::<yazi_fs::FilesOp>() { lua.create_any_userdata(t.clone())?.into_lua(lua)? } else if let Some(t) = a.downcast_ref::<yazi_parser::mgr::UpdateYankedOpt>() { t.clone().into_lua(lua)? } else { Err("unsupported Data::Any included".into_lua_err())? } } }) } pub fn table_to_args(lua: &Lua, t: Table) -> mlua::Result<HashMap<DataKey, Data>> { let mut args = HashMap::with_capacity(t.raw_len()); for pair in t.pairs::<Value, Value>() { let (k, v) = pair?; match k { Value::Integer(i) if i > 0 => { args.insert(DataKey::Integer(i - 1), Self::value_to_data(lua, v)?); } Value::String(s) => { args.insert( DataKey::String(Cow::Owned(s.to_str()?.replace('_', "-"))), Self::value_to_data(lua, v)?, ); } _ => return Err("invalid key in Cmd".into_lua_err()), } } Ok(args) } pub fn args_to_table(lua: &Lua, args: HashMap<DataKey, Data>) -> mlua::Result<Table> { let seq_len = args.keys().filter(|&k| k.is_integer()).count(); let tbl = lua.create_table_with_capacity(seq_len, args.len() - seq_len)?; for (k, v) in args { match k { DataKey::Integer(i) => tbl.raw_set(i + 1, Self::data_to_value(lua, v)?), DataKey::String(s) => tbl.raw_set(replace_cow(s, "-", "_"), Self::data_to_value(lua, v)?), _ => Err("invalid key in Data".into_lua_err()), }?; } Ok(tbl) } pub fn args_to_table_ref(lua: &Lua, args: &HashMap<DataKey, Data>) -> mlua::Result<Table> { let seq_len = args.keys().filter(|&k| k.is_integer()).count(); let tbl = lua.create_table_with_capacity(seq_len, args.len() - seq_len)?; for (k, v) in args { match k { DataKey::Integer(i) => tbl.raw_set(i + 1, Self::data_to_value_ref(lua, v)?), DataKey::String(s) => { tbl.raw_set(replace_cow(&**s, "-", "_"), Self::data_to_value_ref(lua, v)?) } _ => Err("invalid key in Data".into_lua_err()), }?; } Ok(tbl) } pub fn list_to_values(lua: &Lua, data: Vec<Data>) -> mlua::Result<MultiValue> { data.into_iter().map(|d| Self::data_to_value(lua, d)).collect() } pub fn values_to_list(lua: &Lua, values: MultiValue) -> mlua::Result<Vec<Data>> { values.into_iter().map(|v| Self::value_to_data(lua, v)).collect() } } impl Sendable { fn value_to_key(value: Value) -> mlua::Result<DataKey> { Ok(match value { Value::Nil => DataKey::Nil, Value::Boolean(b) => DataKey::Boolean(b), Value::LightUserData(_) => Err("light userdata is not supported".into_lua_err())?, Value::Integer(i) => DataKey::Integer(i), Value::Number(n) => DataKey::Number(OrderedFloat(n)), Value::String(s) => { if let Ok(s) = s.to_str() { DataKey::String(s.to_owned().into()) } else { DataKey::Bytes(s.as_bytes().to_owned()) } } Value::Table(_) => Err("table is not supported".into_lua_err())?, Value::Function(_) => Err("function is not supported".into_lua_err())?, Value::Thread(_) => Err("thread is not supported".into_lua_err())?, Value::UserData(ud) => match ud.type_id() { Some(t) if t == TypeId::of::<yazi_binding::Url>() => { DataKey::Url(ud.take::<yazi_binding::Url>()?.into()) } Some(t) if t == TypeId::of::<yazi_binding::Path>() => { DataKey::Path(ud.take::<yazi_binding::Path>()?.into()) } Some(t) if t == TypeId::of::<yazi_binding::Id>() => { DataKey::Id(**ud.borrow::<yazi_binding::Id>()?) } _ => Err(format!("unsupported userdata included: {ud:?}").into_lua_err())?, }, Value::Error(_) => Err("error is not supported".into_lua_err())?, Value::Other(..) => Err("unknown data is not supported".into_lua_err())?, }) } fn key_to_value(lua: &Lua, key: DataKey) -> mlua::Result<Value> { match key { DataKey::Url(u) => yazi_binding::Url::new(u).into_lua(lua), DataKey::Path(u) => yazi_binding::Path::new(u).into_lua(lua), _ => Self::key_to_value_ref(lua, &key), } } fn key_to_value_ref(lua: &Lua, key: &DataKey) -> mlua::Result<Value> { Ok(match key { DataKey::Nil => Value::Nil, DataKey::Boolean(b) => Value::Boolean(*b), DataKey::Integer(i) => Value::Integer(*i), DataKey::Number(n) => Value::Number(n.0), DataKey::String(s) => Value::String(lua.create_string(&**s)?), DataKey::Id(i) => yazi_binding::Id(*i).into_lua(lua)?, DataKey::Url(u) => yazi_binding::Url::new(u).into_lua(lua)?, DataKey::Path(u) => yazi_binding::Path::new(u).into_lua(lua)?, DataKey::Bytes(b) => Value::String(lua.create_string(b)?), }) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/spark/spark.rs
yazi-dds/src/spark/spark.rs
use mlua::{FromLua, IntoLua, Lua, Value}; use crate::{spark::SparkKind, try_from_spark}; #[derive(Debug)] pub enum Spark<'a> { // Void Void(yazi_parser::VoidOpt), // Mgr Arrow(yazi_parser::ArrowOpt), Back(yazi_parser::VoidOpt), BulkRename(yazi_parser::VoidOpt), Cd(yazi_parser::mgr::CdOpt), Close(yazi_parser::mgr::CloseOpt), Copy(yazi_parser::mgr::CopyOpt), Create(yazi_parser::mgr::CreateOpt), Displace(yazi_parser::VoidOpt), DisplaceDo(yazi_parser::mgr::DisplaceDoOpt), Download(yazi_parser::mgr::DownloadOpt), Enter(yazi_parser::VoidOpt), Escape(yazi_parser::mgr::EscapeOpt), EscapeFilter(yazi_parser::VoidOpt), EscapeFind(yazi_parser::VoidOpt), EscapeSearch(yazi_parser::VoidOpt), EscapeSelect(yazi_parser::VoidOpt), EscapeVisual(yazi_parser::VoidOpt), Filter(yazi_parser::mgr::FilterOpt), FilterDo(yazi_parser::mgr::FilterOpt), Find(yazi_parser::mgr::FindOpt), FindArrow(yazi_parser::mgr::FindArrowOpt), FindDo(yazi_parser::mgr::FindDoOpt), Follow(yazi_parser::VoidOpt), Forward(yazi_parser::VoidOpt), Hardlink(yazi_parser::mgr::HardlinkOpt), Hidden(yazi_parser::mgr::HiddenOpt), Hover(yazi_parser::mgr::HoverOpt), Leave(yazi_parser::VoidOpt), Linemode(yazi_parser::mgr::LinemodeOpt), Link(yazi_parser::mgr::LinkOpt), Open(yazi_parser::mgr::OpenOpt), OpenDo(yazi_parser::mgr::OpenDoOpt), Paste(yazi_parser::mgr::PasteOpt), Peek(yazi_parser::mgr::PeekOpt), Quit(yazi_parser::mgr::QuitOpt), Refresh(yazi_parser::VoidOpt), Remove(yazi_parser::mgr::RemoveOpt), RemoveDo(yazi_parser::mgr::RemoveOpt), Rename(yazi_parser::mgr::RenameOpt), Reveal(yazi_parser::mgr::RevealOpt), Search(yazi_parser::mgr::SearchOpt), SearchDo(yazi_parser::mgr::SearchOpt), SearchStop(yazi_parser::VoidOpt), Seek(yazi_parser::mgr::SeekOpt), Shell(yazi_parser::mgr::ShellOpt), Sort(yazi_parser::mgr::SortOpt), Spot(yazi_parser::mgr::SpotOpt), Stash(yazi_parser::mgr::StashOpt), Suspend(yazi_parser::VoidOpt), TabClose(yazi_parser::mgr::TabCloseOpt), TabCreate(yazi_parser::mgr::TabCreateOpt), TabSwap(yazi_parser::ArrowOpt), TabSwitch(yazi_parser::mgr::TabSwitchOpt), Toggle(yazi_parser::mgr::ToggleOpt), ToggleAll(yazi_parser::mgr::ToggleAllOpt), Unyank(yazi_parser::VoidOpt), UpdateFiles(yazi_parser::mgr::UpdateFilesOpt), UpdateMimes(yazi_parser::mgr::UpdateMimesOpt), UpdatePaged(yazi_parser::mgr::UpdatePagedOpt), UpdatePeeked(yazi_parser::mgr::UpdatePeekedOpt), UpdateSpotted(yazi_parser::mgr::UpdateSpottedOpt), UpdateYanked(yazi_parser::mgr::UpdateYankedOpt<'a>), Upload(yazi_parser::mgr::UploadOpt), VisualMode(yazi_parser::mgr::VisualModeOpt), Watch(yazi_parser::VoidOpt), Yank(yazi_parser::mgr::YankOpt), // Cmp CmpArrow(yazi_parser::ArrowOpt), CmpClose(yazi_parser::cmp::CloseOpt), CmpShow(yazi_parser::cmp::ShowOpt), CmpTrigger(yazi_parser::cmp::TriggerOpt), // Confirm ConfirmArrow(yazi_parser::ArrowOpt), ConfirmClose(yazi_parser::confirm::CloseOpt), ConfirmShow(Box<yazi_parser::confirm::ShowOpt>), // Help HelpArrow(yazi_parser::ArrowOpt), HelpEscape(yazi_parser::VoidOpt), HelpFilter(yazi_parser::VoidOpt), HelpToggle(yazi_parser::help::ToggleOpt), // Input InputBackspace(yazi_parser::input::BackspaceOpt), InputBackward(yazi_parser::input::BackwardOpt), InputClose(yazi_parser::input::CloseOpt), InputComplete(yazi_parser::input::CompleteOpt), InputDelete(yazi_parser::input::DeleteOpt), InputEscape(yazi_parser::VoidOpt), InputForward(yazi_parser::input::ForwardOpt), InputInsert(yazi_parser::input::InsertOpt), InputKill(yazi_parser::input::KillOpt), InputMove(yazi_parser::input::MoveOpt), InputPaste(yazi_parser::input::PasteOpt), InputShow(yazi_parser::input::ShowOpt), // Notify NotifyTick(yazi_parser::notify::TickOpt), // Pick PickArrow(yazi_parser::ArrowOpt), PickClose(yazi_parser::pick::CloseOpt), PickShow(yazi_parser::pick::ShowOpt), // Spot SpotArrow(yazi_parser::ArrowOpt), SpotClose(yazi_parser::VoidOpt), SpotCopy(yazi_parser::spot::CopyOpt), SpotSwipe(yazi_parser::ArrowOpt), // Tasks TasksArrow(yazi_parser::ArrowOpt), TasksCancel(yazi_parser::VoidOpt), TasksClose(yazi_parser::VoidOpt), TasksInspect(yazi_parser::VoidOpt), TasksOpenShellCompat(yazi_parser::tasks::ProcessOpenOpt), TasksProcessOpen(yazi_parser::tasks::ProcessOpenOpt), TasksShow(yazi_parser::VoidOpt), TasksUpdateSucceed(yazi_parser::tasks::UpdateSucceedOpt), // Which WhichCallback(yazi_parser::which::CallbackOpt), WhichShow(yazi_parser::which::ShowOpt), } impl<'a> Spark<'a> { pub fn from_lua(lua: &Lua, kind: SparkKind, value: Value) -> mlua::Result<Self> { use SparkKind::*; Ok(match kind { // Sort KeySort => Self::Sort(<_>::from_lua(value, lua)?), IndSort => Self::Sort(<_>::from_lua(value, lua)?), // Stash IndStash => Self::Stash(<_>::from_lua(value, lua)?), RelayStash => Self::Stash(<_>::from_lua(value, lua)?), // Quit KeyQuit => Self::Quit(<_>::from_lua(value, lua)?), }) } } impl<'a> IntoLua for Spark<'a> { fn into_lua(self, lua: &Lua) -> mlua::Result<Value> { match self { // Void Self::Void(b) => b.into_lua(lua), // Mgr Self::Arrow(b) => b.into_lua(lua), Self::Back(b) => b.into_lua(lua), Self::BulkRename(b) => b.into_lua(lua), Self::Cd(b) => b.into_lua(lua), Self::Close(b) => b.into_lua(lua), Self::Copy(b) => b.into_lua(lua), Self::Create(b) => b.into_lua(lua), Self::Displace(b) => b.into_lua(lua), Self::DisplaceDo(b) => b.into_lua(lua), Self::Download(b) => b.into_lua(lua), Self::Enter(b) => b.into_lua(lua), Self::Escape(b) => b.into_lua(lua), Self::EscapeFilter(b) => b.into_lua(lua), Self::EscapeFind(b) => b.into_lua(lua), Self::EscapeSearch(b) => b.into_lua(lua), Self::EscapeSelect(b) => b.into_lua(lua), Self::EscapeVisual(b) => b.into_lua(lua), Self::Filter(b) => b.into_lua(lua), Self::FilterDo(b) => b.into_lua(lua), Self::Find(b) => b.into_lua(lua), Self::FindArrow(b) => b.into_lua(lua), Self::FindDo(b) => b.into_lua(lua), Self::Follow(b) => b.into_lua(lua), Self::Forward(b) => b.into_lua(lua), Self::Hardlink(b) => b.into_lua(lua), Self::Hidden(b) => b.into_lua(lua), Self::Hover(b) => b.into_lua(lua), Self::Leave(b) => b.into_lua(lua), Self::Linemode(b) => b.into_lua(lua), Self::Link(b) => b.into_lua(lua), Self::Open(b) => b.into_lua(lua), Self::OpenDo(b) => b.into_lua(lua), Self::Paste(b) => b.into_lua(lua), Self::Peek(b) => b.into_lua(lua), Self::Quit(b) => b.into_lua(lua), Self::Refresh(b) => b.into_lua(lua), Self::Remove(b) => b.into_lua(lua), Self::RemoveDo(b) => b.into_lua(lua), Self::Rename(b) => b.into_lua(lua), Self::Reveal(b) => b.into_lua(lua), Self::Search(b) => b.into_lua(lua), Self::SearchDo(b) => b.into_lua(lua), Self::SearchStop(b) => b.into_lua(lua), Self::Seek(b) => b.into_lua(lua), Self::Shell(b) => b.into_lua(lua), Self::Sort(b) => b.into_lua(lua), Self::Spot(b) => b.into_lua(lua), Self::Stash(b) => b.into_lua(lua), Self::Suspend(b) => b.into_lua(lua), Self::TabClose(b) => b.into_lua(lua), Self::TabCreate(b) => b.into_lua(lua), Self::TabSwap(b) => b.into_lua(lua), Self::TabSwitch(b) => b.into_lua(lua), Self::Toggle(b) => b.into_lua(lua), Self::ToggleAll(b) => b.into_lua(lua), Self::Unyank(b) => b.into_lua(lua), Self::UpdateFiles(b) => b.into_lua(lua), Self::UpdateMimes(b) => b.into_lua(lua), Self::UpdatePaged(b) => b.into_lua(lua), Self::UpdatePeeked(b) => b.into_lua(lua), Self::UpdateSpotted(b) => b.into_lua(lua), Self::UpdateYanked(b) => b.into_lua(lua), Self::Upload(b) => b.into_lua(lua), Self::VisualMode(b) => b.into_lua(lua), Self::Watch(b) => b.into_lua(lua), Self::Yank(b) => b.into_lua(lua), // Cmp Self::CmpArrow(b) => b.into_lua(lua), Self::CmpClose(b) => b.into_lua(lua), Self::CmpShow(b) => b.into_lua(lua), Self::CmpTrigger(b) => b.into_lua(lua), // Confirm Self::ConfirmArrow(b) => b.into_lua(lua), Self::ConfirmClose(b) => b.into_lua(lua), Self::ConfirmShow(b) => b.into_lua(lua), // Help Self::HelpArrow(b) => b.into_lua(lua), Self::HelpEscape(b) => b.into_lua(lua), Self::HelpFilter(b) => b.into_lua(lua), Self::HelpToggle(b) => b.into_lua(lua), // Input Self::InputBackspace(b) => b.into_lua(lua), Self::InputBackward(b) => b.into_lua(lua), Self::InputClose(b) => b.into_lua(lua), Self::InputComplete(b) => b.into_lua(lua), Self::InputDelete(b) => b.into_lua(lua), Self::InputEscape(b) => b.into_lua(lua), Self::InputForward(b) => b.into_lua(lua), Self::InputInsert(b) => b.into_lua(lua), Self::InputKill(b) => b.into_lua(lua), Self::InputMove(b) => b.into_lua(lua), Self::InputPaste(b) => b.into_lua(lua), Self::InputShow(b) => b.into_lua(lua), // Notify Self::NotifyTick(b) => b.into_lua(lua), // Pick Self::PickArrow(b) => b.into_lua(lua), Self::PickClose(b) => b.into_lua(lua), Self::PickShow(b) => b.into_lua(lua), // Spot Self::SpotArrow(b) => b.into_lua(lua), Self::SpotClose(b) => b.into_lua(lua), Self::SpotCopy(b) => b.into_lua(lua), Self::SpotSwipe(b) => b.into_lua(lua), // Tasks Self::TasksArrow(b) => b.into_lua(lua), Self::TasksCancel(b) => b.into_lua(lua), Self::TasksClose(b) => b.into_lua(lua), Self::TasksInspect(b) => b.into_lua(lua), Self::TasksOpenShellCompat(b) => b.into_lua(lua), Self::TasksProcessOpen(b) => b.into_lua(lua), Self::TasksShow(b) => b.into_lua(lua), Self::TasksUpdateSucceed(b) => b.into_lua(lua), // Which Self::WhichCallback(b) => b.into_lua(lua), Self::WhichShow(b) => b.into_lua(lua), } } } try_from_spark!( VoidOpt, mgr:back, mgr:bulk_rename, mgr:enter, mgr:escape_filter, mgr:escape_find, mgr:escape_search, mgr:escape_select, mgr:escape_visual, mgr:follow, mgr:forward, mgr:leave, mgr:refresh, mgr:search_stop, mgr:suspend, mgr:unyank, mgr:watch ); try_from_spark!(ArrowOpt, mgr:arrow, mgr:tab_swap); try_from_spark!(cmp::CloseOpt, cmp:close); try_from_spark!(cmp::ShowOpt, cmp:show); try_from_spark!(cmp::TriggerOpt, cmp:trigger); try_from_spark!(confirm::CloseOpt, confirm:close); try_from_spark!(confirm::ShowOpt, confirm:show); try_from_spark!(help::ToggleOpt, help:toggle); try_from_spark!(input::BackspaceOpt, input:backspace); try_from_spark!(input::BackwardOpt, input:backward); try_from_spark!(input::CloseOpt, input:close); try_from_spark!(input::CompleteOpt, input:complete); try_from_spark!(input::DeleteOpt, input:delete); try_from_spark!(input::ForwardOpt, input:forward); try_from_spark!(input::InsertOpt, input:insert); try_from_spark!(input::KillOpt, input:kill); try_from_spark!(input::MoveOpt, input:move); try_from_spark!(input::PasteOpt, input:paste); try_from_spark!(input::ShowOpt, input:show); try_from_spark!(mgr::CdOpt, mgr:cd); try_from_spark!(mgr::CloseOpt, mgr:close); try_from_spark!(mgr::CopyOpt, mgr:copy); try_from_spark!(mgr::CreateOpt, mgr:create); try_from_spark!(mgr::DisplaceDoOpt, mgr:displace_do); try_from_spark!(mgr::DownloadOpt, mgr:download); try_from_spark!(mgr::EscapeOpt, mgr:escape); try_from_spark!(mgr::FilterOpt, mgr:filter, mgr:filter_do); try_from_spark!(mgr::FindArrowOpt, mgr:find_arrow); try_from_spark!(mgr::FindDoOpt, mgr:find_do); try_from_spark!(mgr::FindOpt, mgr:find); try_from_spark!(mgr::HardlinkOpt, mgr:hardlink); try_from_spark!(mgr::HiddenOpt, mgr:hidden); try_from_spark!(mgr::HoverOpt, mgr:hover); try_from_spark!(mgr::LinemodeOpt, mgr:linemode); try_from_spark!(mgr::LinkOpt, mgr:link); try_from_spark!(mgr::OpenDoOpt, mgr:open_do); try_from_spark!(mgr::OpenOpt, mgr:open); try_from_spark!(mgr::PasteOpt, mgr:paste); try_from_spark!(mgr::PeekOpt, mgr:peek); try_from_spark!(mgr::QuitOpt, mgr:quit); try_from_spark!(mgr::RemoveOpt, mgr:remove, mgr:remove_do); try_from_spark!(mgr::RenameOpt, mgr:rename); try_from_spark!(mgr::RevealOpt, mgr:reveal); try_from_spark!(mgr::SearchOpt, mgr:search, mgr:search_do); try_from_spark!(mgr::SeekOpt, mgr:seek); try_from_spark!(mgr::ShellOpt, mgr:shell); try_from_spark!(mgr::SortOpt, mgr:sort); try_from_spark!(mgr::SpotOpt, mgr:spot); try_from_spark!(mgr::StashOpt, mgr:stash); try_from_spark!(mgr::TabCloseOpt, mgr:tab_close); try_from_spark!(mgr::TabCreateOpt, mgr:tab_create); try_from_spark!(mgr::TabSwitchOpt, mgr:tab_switch); try_from_spark!(mgr::ToggleAllOpt, mgr:toggle_all); try_from_spark!(mgr::ToggleOpt, mgr:toggle); try_from_spark!(mgr::UpdateFilesOpt, mgr:update_files); try_from_spark!(mgr::UpdateMimesOpt, mgr:update_mimes); try_from_spark!(mgr::UpdatePagedOpt, mgr:update_paged); try_from_spark!(mgr::UpdatePeekedOpt, mgr:update_peeked); try_from_spark!(mgr::UpdateSpottedOpt, mgr:update_spotted); try_from_spark!(mgr::UpdateYankedOpt<'a>, mgr:update_yanked); try_from_spark!(mgr::UploadOpt, mgr:upload); try_from_spark!(mgr::VisualModeOpt, mgr:visual_mode); try_from_spark!(mgr::YankOpt, mgr:yank); try_from_spark!(notify::TickOpt, notify:tick); try_from_spark!(pick::CloseOpt, pick:close); try_from_spark!(pick::ShowOpt, pick:show); try_from_spark!(spot::CopyOpt, spot:copy); try_from_spark!(tasks::ProcessOpenOpt, tasks:process_open); try_from_spark!(tasks::UpdateSucceedOpt, tasks:update_succeed); try_from_spark!(which::CallbackOpt, which:callback); try_from_spark!(which::ShowOpt, which:show);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/spark/kind.rs
yazi-dds/src/spark/kind.rs
use std::fmt::Display; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum SparkKind { // Sort KeySort, IndSort, // Stash IndStash, RelayStash, // Quit KeyQuit, } impl AsRef<str> for SparkKind { fn as_ref(&self) -> &str { match self { // Sort Self::KeySort => "key-sort", Self::IndSort => "ind-sort", // Stash Self::IndStash => "ind-stash", Self::RelayStash => "relay-stash", // Quit Self::KeyQuit => "key-quit", } } } impl Display for SparkKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.as_ref()) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/spark/mod.rs
yazi-dds/src/spark/mod.rs
yazi_macro::mod_flat!(kind spark);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/ember/bulk.rs
yazi-dds/src/ember/bulk.rs
use hashbrown::HashMap; use mlua::{IntoLua, Lua, Value}; use serde::{Deserialize, Serialize}; use yazi_shared::url::{Url, UrlCow}; use super::Ember; #[derive(Debug, Deserialize, Serialize)] pub struct EmberBulk<'a> { pub changes: HashMap<UrlCow<'a>, UrlCow<'a>>, } impl<'a> EmberBulk<'a> { pub fn borrowed<I>(changes: I) -> Ember<'a> where I: Iterator<Item = (Url<'a>, Url<'a>)>, { Self { changes: changes.map(|(from, to)| (from.into(), to.into())).collect() }.into() } } impl EmberBulk<'static> { pub fn owned<'a, I>(changes: I) -> Ember<'static> where I: Iterator<Item = (Url<'a>, Url<'a>)>, { Self { changes: changes.map(|(from, to)| (from.to_owned().into(), to.to_owned().into())).collect(), } .into() } } impl<'a> From<EmberBulk<'a>> for Ember<'a> { fn from(value: EmberBulk<'a>) -> Self { Self::Bulk(value) } } impl IntoLua for EmberBulk<'_> { fn into_lua(self, lua: &Lua) -> mlua::Result<Value> { lua .create_table_from( self .changes .into_iter() .map(|(from, to)| (yazi_binding::Url::new(from), yazi_binding::Url::new(to))), )? .into_lua(lua) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/ember/move.rs
yazi-dds/src/ember/move.rs
use std::borrow::Cow; use mlua::{IntoLua, Lua, Value}; use serde::{Deserialize, Serialize}; use yazi_shared::url::UrlBuf; use super::Ember; #[derive(Debug, Deserialize, Serialize)] pub struct EmberMove<'a> { pub items: Cow<'a, Vec<BodyMoveItem>>, } impl<'a> EmberMove<'a> { pub fn borrowed(items: &'a Vec<BodyMoveItem>) -> Ember<'a> { Self { items: Cow::Borrowed(items) }.into() } } impl EmberMove<'static> { pub fn owned(items: Vec<BodyMoveItem>) -> Ember<'static> { Self { items: Cow::Owned(items) }.into() } } impl<'a> From<EmberMove<'a>> for Ember<'a> { fn from(value: EmberMove<'a>) -> Self { Self::Move(value) } } impl IntoLua for EmberMove<'_> { fn into_lua(self, lua: &Lua) -> mlua::Result<Value> { lua.create_table_from([("items", self.items.into_owned())])?.into_lua(lua) } } // --- Item #[derive(Clone, Debug, Deserialize, Serialize)] pub struct BodyMoveItem { pub from: UrlBuf, pub to: UrlBuf, } impl IntoLua for BodyMoveItem { fn into_lua(self, lua: &Lua) -> mlua::Result<Value> { lua .create_table_from([ ("from", yazi_binding::Url::new(self.from)), ("to", yazi_binding::Url::new(self.to)), ])? .into_lua(lua) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/ember/ember.rs
yazi-dds/src/ember/ember.rs
use anyhow::{Result, bail}; use mlua::{ExternalResult, IntoLua, Lua, Value}; use yazi_shared::Id; use super::{EmberBulk, EmberBye, EmberCd, EmberCustom, EmberDelete, EmberDuplicate, EmberHey, EmberHi, EmberHover, EmberLoad, EmberMount, EmberMove, EmberRename, EmberTab, EmberTrash, EmberYank}; use crate::Payload; #[derive(Debug)] pub enum Ember<'a> { Hi(EmberHi<'a>), Hey(EmberHey), Bye(EmberBye), Tab(EmberTab), Cd(EmberCd<'a>), Load(EmberLoad<'a>), Hover(EmberHover<'a>), Rename(EmberRename<'a>), Bulk(EmberBulk<'a>), Yank(EmberYank<'a>), Duplicate(EmberDuplicate<'a>), Move(EmberMove<'a>), Trash(EmberTrash<'a>), Delete(EmberDelete<'a>), Mount(EmberMount), Custom(EmberCustom), } impl Ember<'static> { pub fn from_str(kind: &str, body: &str) -> Result<Self> { Ok(match kind { "hi" => Self::Hi(serde_json::from_str(body)?), "hey" => Self::Hey(serde_json::from_str(body)?), "bye" => Self::Bye(serde_json::from_str(body)?), "tab" => Self::Tab(serde_json::from_str(body)?), "cd" => Self::Cd(serde_json::from_str(body)?), "load" => Self::Load(serde_json::from_str(body)?), "hover" => Self::Hover(serde_json::from_str(body)?), "rename" => Self::Rename(serde_json::from_str(body)?), "bulk" => Self::Bulk(serde_json::from_str(body)?), "@yank" => Self::Yank(serde_json::from_str(body)?), "duplicate" => Self::Duplicate(serde_json::from_str(body)?), "move" => Self::Move(serde_json::from_str(body)?), "trash" => Self::Trash(serde_json::from_str(body)?), "delete" => Self::Delete(serde_json::from_str(body)?), "mount" => Self::Mount(serde_json::from_str(body)?), _ => EmberCustom::from_str(kind, body)?, }) } pub fn from_lua(lua: &Lua, kind: &str, value: Value) -> mlua::Result<Self> { Self::validate(kind).into_lua_err()?; EmberCustom::from_lua(lua, kind, value) } pub fn validate(kind: &str) -> Result<()> { if matches!( kind, "hi" | "hey" | "bye" | "tab" | "cd" | "load" | "hover" | "rename" | "bulk" | "@yank" | "duplicate" | "move" | "trash" | "delete" | "mount" ) || kind.starts_with("key-") || kind.starts_with("ind-") || kind.starts_with("emit-") || kind.starts_with("relay-") { bail!("Cannot construct system event"); } let mut it = kind.bytes().peekable(); if it.peek() == Some(&b'@') { it.next(); // Skip `@` as it's a prefix for static messages } if !it.all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'z' | b'-')) { bail!("Kind `{kind}` must be in kebab-case"); } Ok(()) } } impl<'a> Ember<'a> { pub fn kind(&self) -> &str { match self { Self::Hi(_) => "hi", Self::Hey(_) => "hey", Self::Bye(_) => "bye", Self::Tab(_) => "tab", Self::Cd(_) => "cd", Self::Load(_) => "load", Self::Hover(_) => "hover", Self::Rename(_) => "rename", Self::Bulk(_) => "bulk", Self::Yank(_) => "@yank", Self::Duplicate(_) => "duplicate", Self::Move(_) => "move", Self::Trash(_) => "trash", Self::Delete(_) => "delete", Self::Mount(_) => "mount", Self::Custom(b) => b.kind.as_str(), } } pub fn with_receiver(self, receiver: Id) -> Payload<'a> { Payload::new(self).with_receiver(receiver) } pub fn with_sender(self, sender: Id) -> Payload<'a> { Payload::new(self).with_sender(sender) } } impl<'a> IntoLua for Ember<'a> { fn into_lua(self, lua: &Lua) -> mlua::Result<Value> { match self { Self::Hi(b) => b.into_lua(lua), Self::Hey(b) => b.into_lua(lua), Self::Bye(b) => b.into_lua(lua), Self::Cd(b) => b.into_lua(lua), Self::Load(b) => b.into_lua(lua), Self::Hover(b) => b.into_lua(lua), Self::Tab(b) => b.into_lua(lua), Self::Rename(b) => b.into_lua(lua), Self::Bulk(b) => b.into_lua(lua), Self::Yank(b) => b.into_lua(lua), Self::Duplicate(b) => b.into_lua(lua), Self::Move(b) => b.into_lua(lua), Self::Trash(b) => b.into_lua(lua), Self::Delete(b) => b.into_lua(lua), Self::Mount(b) => b.into_lua(lua), Self::Custom(b) => b.into_lua(lua), } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/ember/yank.rs
yazi-dds/src/ember/yank.rs
use std::borrow::Cow; use hashbrown::HashSet; use mlua::{IntoLua, Lua, Value}; use serde::{Deserialize, Serialize}; use yazi_parser::mgr::UpdateYankedOpt; use yazi_shared::url::UrlBufCov; use super::Ember; #[derive(Debug, Deserialize, Serialize)] pub struct EmberYank<'a>(UpdateYankedOpt<'a>); impl<'a> EmberYank<'a> { pub fn borrowed(cut: bool, urls: &'a HashSet<UrlBufCov>) -> Ember<'a> { Self(UpdateYankedOpt { cut, urls: Cow::Borrowed(urls) }).into() } } impl EmberYank<'static> { pub fn owned(cut: bool, _: &HashSet<UrlBufCov>) -> Ember<'static> { Self(UpdateYankedOpt { cut, urls: Default::default() }).into() } } impl<'a> From<EmberYank<'a>> for Ember<'a> { fn from(value: EmberYank<'a>) -> Self { Self::Yank(value) } } impl IntoLua for EmberYank<'_> { fn into_lua(self, lua: &Lua) -> mlua::Result<Value> { self.0.into_lua(lua) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/ember/cd.rs
yazi-dds/src/ember/cd.rs
use std::borrow::Cow; use mlua::{IntoLua, Lua, Value}; use serde::{Deserialize, Serialize}; use yazi_shared::{Id, url::UrlBuf}; use super::Ember; #[derive(Debug, Deserialize, Serialize)] pub struct EmberCd<'a> { pub tab: Id, pub url: Cow<'a, UrlBuf>, #[serde(skip)] dummy: bool, } impl<'a> EmberCd<'a> { pub fn borrowed(tab: Id, url: &'a UrlBuf) -> Ember<'a> { Self { tab, url: url.into(), dummy: false }.into() } } impl EmberCd<'static> { pub fn owned(tab: Id, _: &UrlBuf) -> Ember<'static> { Self { tab, url: Default::default(), dummy: true }.into() } } impl<'a> From<EmberCd<'a>> for Ember<'a> { fn from(value: EmberCd<'a>) -> Self { Self::Cd(value) } } impl IntoLua for EmberCd<'_> { fn into_lua(self, lua: &Lua) -> mlua::Result<Value> { lua .create_table_from([ ("tab", self.tab.get().into_lua(lua)?), ("url", Some(self.url).filter(|_| !self.dummy).map(yazi_binding::Url::new).into_lua(lua)?), ])? .into_lua(lua) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/ember/rename.rs
yazi-dds/src/ember/rename.rs
use std::borrow::Cow; use mlua::{IntoLua, Lua, Value}; use serde::{Deserialize, Serialize}; use yazi_shared::{Id, url::UrlBuf}; use super::Ember; #[derive(Debug, Deserialize, Serialize)] pub struct EmberRename<'a> { pub tab: Id, pub from: Cow<'a, UrlBuf>, pub to: Cow<'a, UrlBuf>, } impl<'a> EmberRename<'a> { pub fn borrowed(tab: Id, from: &'a UrlBuf, to: &'a UrlBuf) -> Ember<'a> { Self { tab, from: from.into(), to: to.into() }.into() } } impl EmberRename<'static> { pub fn owned(tab: Id, from: &UrlBuf, to: &UrlBuf) -> Ember<'static> { Self { tab, from: from.clone().into(), to: to.clone().into() }.into() } } impl<'a> From<EmberRename<'a>> for Ember<'a> { fn from(value: EmberRename<'a>) -> Self { Self::Rename(value) } } impl IntoLua for EmberRename<'_> { fn into_lua(self, lua: &Lua) -> mlua::Result<Value> { lua .create_table_from([ ("tab", self.tab.get().into_lua(lua)?), ("from", yazi_binding::Url::new(self.from).into_lua(lua)?), ("to", yazi_binding::Url::new(self.to).into_lua(lua)?), ])? .into_lua(lua) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/ember/hi.rs
yazi-dds/src/ember/hi.rs
use std::borrow::Cow; use hashbrown::HashSet; use mlua::{ExternalResult, IntoLua, Lua, Value}; use serde::{Deserialize, Serialize}; use yazi_shared::SStr; use super::Ember; /// Client handshake #[derive(Debug, Deserialize, Serialize)] pub struct EmberHi<'a> { /// Kinds of events the client can handle pub abilities: HashSet<Cow<'a, str>>, pub version: SStr, } impl<'a> EmberHi<'a> { pub fn borrowed<I>(abilities: I) -> Ember<'a> where I: Iterator<Item = &'a str>, { Self { abilities: abilities.map(Into::into).collect(), version: Self::version().into() }.into() } pub fn version() -> &'static str { concat!(env!("CARGO_PKG_VERSION"), " ", env!("VERGEN_GIT_SHA")) } } impl<'a> From<EmberHi<'a>> for Ember<'a> { fn from(value: EmberHi<'a>) -> Self { Self::Hi(value) } } impl IntoLua for EmberHi<'_> { fn into_lua(self, _: &Lua) -> mlua::Result<Value> { Err("BodyHi cannot be converted to Lua").into_lua_err() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/ember/hover.rs
yazi-dds/src/ember/hover.rs
use std::borrow::Cow; use mlua::{IntoLua, Lua, Value}; use serde::{Deserialize, Serialize}; use yazi_shared::{Id, url::UrlBuf}; use super::Ember; #[derive(Debug, Deserialize, Serialize)] pub struct EmberHover<'a> { pub tab: Id, pub url: Option<Cow<'a, UrlBuf>>, } impl<'a> EmberHover<'a> { pub fn borrowed(tab: Id, url: Option<&'a UrlBuf>) -> Ember<'a> { Self { tab, url: url.map(Into::into) }.into() } } impl EmberHover<'static> { pub fn owned(tab: Id, _: Option<&UrlBuf>) -> Ember<'static> { Self { tab, url: None }.into() } } impl<'a> From<EmberHover<'a>> for Ember<'a> { fn from(value: EmberHover<'a>) -> Self { Self::Hover(value) } } impl IntoLua for EmberHover<'_> { fn into_lua(self, lua: &Lua) -> mlua::Result<Value> { lua .create_table_from([ ("tab", self.tab.get().into_lua(lua)?), ("url", self.url.map(yazi_binding::Url::new).into_lua(lua)?), ])? .into_lua(lua) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/ember/hey.rs
yazi-dds/src/ember/hey.rs
use hashbrown::HashMap; use mlua::{ExternalResult, IntoLua, Lua, Value}; use serde::{Deserialize, Serialize}; use yazi_shared::{Id, SStr}; use super::{Ember, EmberHi}; use crate::Peer; /// Server handshake #[derive(Debug, Deserialize, Serialize)] pub struct EmberHey { pub peers: HashMap<Id, Peer>, pub version: SStr, } impl EmberHey { pub fn owned(peers: HashMap<Id, Peer>) -> Ember<'static> { Self { peers, version: EmberHi::version().into() }.into() } } impl From<EmberHey> for Ember<'_> { fn from(value: EmberHey) -> Self { Self::Hey(value) } } impl IntoLua for EmberHey { fn into_lua(self, _: &Lua) -> mlua::Result<Value> { Err("BodyHey cannot be converted to Lua").into_lua_err() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/ember/mod.rs
yazi-dds/src/ember/mod.rs
yazi_macro::mod_flat!( bulk bye cd custom delete duplicate ember hey hi hover load mount r#move rename tab trash yank );
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/ember/trash.rs
yazi-dds/src/ember/trash.rs
use std::borrow::Cow; use mlua::{IntoLua, Lua, Value}; use serde::{Deserialize, Serialize}; use yazi_shared::url::UrlBuf; use super::Ember; #[derive(Debug, Deserialize, Serialize)] pub struct EmberTrash<'a> { pub urls: Cow<'a, Vec<UrlBuf>>, } impl<'a> EmberTrash<'a> { pub fn borrowed(urls: &'a Vec<UrlBuf>) -> Ember<'a> { Self { urls: Cow::Borrowed(urls) }.into() } } impl EmberTrash<'static> { pub fn owned(urls: Vec<UrlBuf>) -> Ember<'static> { Self { urls: Cow::Owned(urls) }.into() } } impl<'a> From<EmberTrash<'a>> for Ember<'a> { fn from(value: EmberTrash<'a>) -> Self { Self::Trash(value) } } impl IntoLua for EmberTrash<'_> { fn into_lua(self, lua: &Lua) -> mlua::Result<Value> { let urls = lua.create_sequence_from(self.urls.into_owned().into_iter().map(yazi_binding::Url::new))?; lua.create_table_from([("urls", urls)])?.into_lua(lua) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/ember/load.rs
yazi-dds/src/ember/load.rs
use std::borrow::Cow; use mlua::{IntoLua, Lua, Value}; use serde::{Deserialize, Serialize}; use yazi_fs::FolderStage; use yazi_shared::{Id, url::UrlBuf}; use super::Ember; #[derive(Debug, Deserialize, Serialize)] pub struct EmberLoad<'a> { pub tab: Id, pub url: Cow<'a, UrlBuf>, pub stage: Cow<'a, FolderStage>, } impl<'a> EmberLoad<'a> { pub fn borrowed(tab: Id, url: &'a UrlBuf, stage: &'a FolderStage) -> Ember<'a> { Self { tab, url: url.into(), stage: Cow::Borrowed(stage) }.into() } } impl EmberLoad<'static> { pub fn owned(tab: Id, url: &UrlBuf, stage: &FolderStage) -> Ember<'static> { Self { tab, url: url.clone().into(), stage: Cow::Owned(stage.clone()) }.into() } } impl<'a> From<EmberLoad<'a>> for Ember<'a> { fn from(value: EmberLoad<'a>) -> Self { Self::Load(value) } } impl IntoLua for EmberLoad<'_> { fn into_lua(self, lua: &Lua) -> mlua::Result<Value> { lua .create_table_from([ ("tab", self.tab.get().into_lua(lua)?), ("url", yazi_binding::Url::new(self.url).into_lua(lua)?), ("stage", yazi_binding::FolderStage::new(self.stage.into_owned()).into_lua(lua)?), ])? .into_lua(lua) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false