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-adapter/src/drivers/kgp_old.rs
yazi-adapter/src/drivers/kgp_old.rs
use core::str; use std::{io::Write, path::PathBuf}; use anyhow::Result; use base64::{Engine, engine::general_purpose}; use image::DynamicImage; use ratatui::layout::Rect; use yazi_term::tty::TTY; use crate::{CLOSE, ESCAPE, Emulator, Image, START, adapter::Adapter}; pub(crate) struct KgpOld; impl KgpOld { pub(crate) async fn image_show(path: PathBuf, max: Rect) -> Result<Rect> { let img = Image::downscale(path, max).await?; let area = Image::pixel_area((img.width(), img.height()), max); let b = Self::encode(img).await?; Adapter::KgpOld.image_hide()?; Adapter::shown_store(area); Emulator::move_lock((area.x, area.y), |w| { w.write_all(&b)?; Ok(area) }) } pub(crate) fn image_erase(_: Rect) -> Result<()> { let mut w = TTY.lockout(); write!(w, "{START}_Gq=2,a=d,d=A{ESCAPE}\\{CLOSE}")?; w.flush()?; Ok(()) } async fn encode(img: DynamicImage) -> Result<Vec<u8>> { fn output(raw: &[u8], format: u8, size: (u32, u32)) -> Result<Vec<u8>> { let b64 = general_purpose::STANDARD.encode(raw).into_bytes(); let mut it = b64.chunks(4096).peekable(); let mut buf = Vec::with_capacity(b64.len() + it.len() * 50); if let Some(first) = it.next() { write!( buf, "{START}_Gq=2,a=T,z=-1,C=1,f={format},s={},v={},m={};{}{ESCAPE}\\{CLOSE}", size.0, size.1, it.peek().is_some() as u8, unsafe { str::from_utf8_unchecked(first) }, )?; } while let Some(chunk) = it.next() { write!(buf, "{START}_Gm={};{}{ESCAPE}\\{CLOSE}", it.peek().is_some() as u8, unsafe { str::from_utf8_unchecked(chunk) })?; } write!(buf, "{CLOSE}")?; Ok(buf) } let size = (img.width(), img.height()); tokio::task::spawn_blocking(move || match img { DynamicImage::ImageRgb8(v) => output(v.as_raw(), 24, size), DynamicImage::ImageRgba8(v) => output(v.as_raw(), 32, size), v => output(v.into_rgb8().as_raw(), 24, size), }) .await? } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-adapter/src/drivers/sixel.rs
yazi-adapter/src/drivers/sixel.rs
use std::{io::Write, path::PathBuf}; use anyhow::{Result, bail}; use crossterm::{cursor::MoveTo, queue}; use image::{DynamicImage, GenericImageView, RgbImage}; use palette::{Srgb, cast::ComponentsAs}; use quantette::{PaletteSize, color_map::IndexedColorMap, wu::{BinnerU8x3, WuU8x3}}; use ratatui::layout::Rect; use crate::{CLOSE, ESCAPE, Emulator, Image, START, adapter::Adapter}; pub(crate) struct Sixel; struct QuantizeOutput<T> { indices: Vec<u8>, palette: Vec<T>, } impl Sixel { pub(crate) async fn image_show(path: PathBuf, max: Rect) -> Result<Rect> { let img = Image::downscale(path, max).await?; let area = Image::pixel_area((img.width(), img.height()), max); let b = Self::encode(img).await?; Adapter::Sixel.image_hide()?; Adapter::shown_store(area); Emulator::move_lock((area.x, area.y), |w| { w.write_all(&b)?; Ok(area) }) } pub(crate) fn image_erase(area: Rect) -> Result<()> { let s = " ".repeat(area.width as usize); Emulator::move_lock((0, 0), |w| { for y in area.top()..area.bottom() { queue!(w, MoveTo(area.x, y))?; write!(w, "{s}")?; } Ok(()) }) } async fn encode(img: DynamicImage) -> Result<Vec<u8>> { let alpha = img.color().has_alpha(); if img.width() == 0 || img.height() == 0 { bail!("image is empty"); } let (qo, img) = tokio::task::spawn_blocking(move || match &img { DynamicImage::ImageRgb8(rgb) => Self::quantify(rgb, false).map(|q| (q, img)), _ => Self::quantify(&img.to_rgb8(), alpha).map(|q| (q, img)), }) .await??; tokio::task::spawn_blocking(move || { let mut buf = vec![]; write!(buf, "{START}P9;1q\"1;1;{};{}", img.width(), img.height())?; // Palette for (i, c) in qo.palette.iter().enumerate() { write!( buf, "#{};2;{};{};{}", i + alpha as usize, c.red as u16 * 100 / 255, c.green as u16 * 100 / 255, c.blue as u16 * 100 / 255 )?; } for y in 0..img.height() { let c = (b'?' + (1 << (y % 6))) as char; let mut last = 0; let mut repeat = 0usize; for x in 0..img.width() { let idx = if img.get_pixel(x, y)[3] == 0 { 0 } else { qo.indices[y as usize * img.width() as usize + x as usize] + alpha as u8 }; if idx == last || repeat == 0 { (last, repeat) = (idx, repeat + 1); continue; } if repeat > 1 { write!(buf, "#{last}!{repeat}{c}")?; } else { write!(buf, "#{last}{c}")?; } (last, repeat) = (idx, 1); } if repeat > 1 { write!(buf, "#{last}!{repeat}{c}")?; } else { write!(buf, "#{last}{c}")?; } write!(buf, "$")?; if y % 6 == 5 { write!(buf, "-")?; } } write!(buf, "{ESCAPE}\\{CLOSE}")?; Ok(buf) }) .await? } fn quantify(rgb: &RgbImage, alpha: bool) -> Result<QuantizeOutput<Srgb<u8>>> { let buf = &rgb.as_raw()[..(rgb.pixels().len() * 3)]; let colors: &[Srgb<u8>] = buf.components_as(); let wu = WuU8x3::run_slice(colors, BinnerU8x3::rgb())?; let color_map = wu.color_map(PaletteSize::try_from(256u16 - alpha as u16)?); Ok(QuantizeOutput { indices: color_map.map_to_indices(colors), palette: color_map.into_palette().into_vec(), }) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-adapter/src/drivers/mod.rs
yazi-adapter/src/drivers/mod.rs
yazi_macro::mod_flat!(chafa iip kgp kgp_old sixel ueberzug);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-adapter/src/drivers/kgp.rs
yazi-adapter/src/drivers/kgp.rs
use core::str; use std::{io::Write, path::PathBuf}; use anyhow::Result; use base64::{Engine, engine::general_purpose}; use crossterm::{cursor::MoveTo, queue}; use image::DynamicImage; use ratatui::layout::Rect; use yazi_shared::SyncCell; use crate::{CLOSE, ESCAPE, Emulator, START, adapter::Adapter, image::Image}; static DIACRITICS: [char; 297] = [ '\u{0305}', '\u{030D}', '\u{030E}', '\u{0310}', '\u{0312}', '\u{033D}', '\u{033E}', '\u{033F}', '\u{0346}', '\u{034A}', '\u{034B}', '\u{034C}', '\u{0350}', '\u{0351}', '\u{0352}', '\u{0357}', '\u{035B}', '\u{0363}', '\u{0364}', '\u{0365}', '\u{0366}', '\u{0367}', '\u{0368}', '\u{0369}', '\u{036A}', '\u{036B}', '\u{036C}', '\u{036D}', '\u{036E}', '\u{036F}', '\u{0483}', '\u{0484}', '\u{0485}', '\u{0486}', '\u{0487}', '\u{0592}', '\u{0593}', '\u{0594}', '\u{0595}', '\u{0597}', '\u{0598}', '\u{0599}', '\u{059C}', '\u{059D}', '\u{059E}', '\u{059F}', '\u{05A0}', '\u{05A1}', '\u{05A8}', '\u{05A9}', '\u{05AB}', '\u{05AC}', '\u{05AF}', '\u{05C4}', '\u{0610}', '\u{0611}', '\u{0612}', '\u{0613}', '\u{0614}', '\u{0615}', '\u{0616}', '\u{0617}', '\u{0657}', '\u{0658}', '\u{0659}', '\u{065A}', '\u{065B}', '\u{065D}', '\u{065E}', '\u{06D6}', '\u{06D7}', '\u{06D8}', '\u{06D9}', '\u{06DA}', '\u{06DB}', '\u{06DC}', '\u{06DF}', '\u{06E0}', '\u{06E1}', '\u{06E2}', '\u{06E4}', '\u{06E7}', '\u{06E8}', '\u{06EB}', '\u{06EC}', '\u{0730}', '\u{0732}', '\u{0733}', '\u{0735}', '\u{0736}', '\u{073A}', '\u{073D}', '\u{073F}', '\u{0740}', '\u{0741}', '\u{0743}', '\u{0745}', '\u{0747}', '\u{0749}', '\u{074A}', '\u{07EB}', '\u{07EC}', '\u{07ED}', '\u{07EE}', '\u{07EF}', '\u{07F0}', '\u{07F1}', '\u{07F3}', '\u{0816}', '\u{0817}', '\u{0818}', '\u{0819}', '\u{081B}', '\u{081C}', '\u{081D}', '\u{081E}', '\u{081F}', '\u{0820}', '\u{0821}', '\u{0822}', '\u{0823}', '\u{0825}', '\u{0826}', '\u{0827}', '\u{0829}', '\u{082A}', '\u{082B}', '\u{082C}', '\u{082D}', '\u{0951}', '\u{0953}', '\u{0954}', '\u{0F82}', '\u{0F83}', '\u{0F86}', '\u{0F87}', '\u{135D}', '\u{135E}', '\u{135F}', '\u{17DD}', '\u{193A}', '\u{1A17}', '\u{1A75}', '\u{1A76}', '\u{1A77}', '\u{1A78}', '\u{1A79}', '\u{1A7A}', '\u{1A7B}', '\u{1A7C}', '\u{1B6B}', '\u{1B6D}', '\u{1B6E}', '\u{1B6F}', '\u{1B70}', '\u{1B71}', '\u{1B72}', '\u{1B73}', '\u{1CD0}', '\u{1CD1}', '\u{1CD2}', '\u{1CDA}', '\u{1CDB}', '\u{1CE0}', '\u{1DC0}', '\u{1DC1}', '\u{1DC3}', '\u{1DC4}', '\u{1DC5}', '\u{1DC6}', '\u{1DC7}', '\u{1DC8}', '\u{1DC9}', '\u{1DCB}', '\u{1DCC}', '\u{1DD1}', '\u{1DD2}', '\u{1DD3}', '\u{1DD4}', '\u{1DD5}', '\u{1DD6}', '\u{1DD7}', '\u{1DD8}', '\u{1DD9}', '\u{1DDA}', '\u{1DDB}', '\u{1DDC}', '\u{1DDD}', '\u{1DDE}', '\u{1DDF}', '\u{1DE0}', '\u{1DE1}', '\u{1DE2}', '\u{1DE3}', '\u{1DE4}', '\u{1DE5}', '\u{1DE6}', '\u{1DFE}', '\u{20D0}', '\u{20D1}', '\u{20D4}', '\u{20D5}', '\u{20D6}', '\u{20D7}', '\u{20DB}', '\u{20DC}', '\u{20E1}', '\u{20E7}', '\u{20E9}', '\u{20F0}', '\u{2CEF}', '\u{2CF0}', '\u{2CF1}', '\u{2DE0}', '\u{2DE1}', '\u{2DE2}', '\u{2DE3}', '\u{2DE4}', '\u{2DE5}', '\u{2DE6}', '\u{2DE7}', '\u{2DE8}', '\u{2DE9}', '\u{2DEA}', '\u{2DEB}', '\u{2DEC}', '\u{2DED}', '\u{2DEE}', '\u{2DEF}', '\u{2DF0}', '\u{2DF1}', '\u{2DF2}', '\u{2DF3}', '\u{2DF4}', '\u{2DF5}', '\u{2DF6}', '\u{2DF7}', '\u{2DF8}', '\u{2DF9}', '\u{2DFA}', '\u{2DFB}', '\u{2DFC}', '\u{2DFD}', '\u{2DFE}', '\u{2DFF}', '\u{A66F}', '\u{A67C}', '\u{A67D}', '\u{A6F0}', '\u{A6F1}', '\u{A8E0}', '\u{A8E1}', '\u{A8E2}', '\u{A8E3}', '\u{A8E4}', '\u{A8E5}', '\u{A8E6}', '\u{A8E7}', '\u{A8E8}', '\u{A8E9}', '\u{A8EA}', '\u{A8EB}', '\u{A8EC}', '\u{A8ED}', '\u{A8EE}', '\u{A8EF}', '\u{A8F0}', '\u{A8F1}', '\u{AAB0}', '\u{AAB2}', '\u{AAB3}', '\u{AAB7}', '\u{AAB8}', '\u{AABE}', '\u{AABF}', '\u{AAC1}', '\u{FE20}', '\u{FE21}', '\u{FE22}', '\u{FE23}', '\u{FE24}', '\u{FE25}', '\u{FE26}', '\u{10A0F}', '\u{10A38}', '\u{1D185}', '\u{1D186}', '\u{1D187}', '\u{1D188}', '\u{1D189}', '\u{1D1AA}', '\u{1D1AB}', '\u{1D1AC}', '\u{1D1AD}', '\u{1D242}', '\u{1D243}', '\u{1D244}', ]; pub(crate) struct Kgp; impl Kgp { pub(crate) async fn image_show(path: PathBuf, max: Rect) -> Result<Rect> { let img = Image::downscale(path, max).await?; let area = Image::pixel_area((img.width(), img.height()), max); let b1 = Self::encode(img).await?; let b2 = Self::place(&area)?; Adapter::Kgp.image_hide()?; Adapter::shown_store(area); Emulator::move_lock((area.x, area.y), |w| { w.write_all(&b1)?; w.write_all(&b2)?; Ok(area) }) } pub(crate) fn image_erase(area: Rect) -> Result<()> { let s = " ".repeat(area.width as usize); Emulator::move_lock((0, 0), |w| { for y in area.top()..area.bottom() { queue!(w, MoveTo(area.x, y))?; write!(w, "{s}")?; } write!(w, "{START}_Gq=2,a=d,d=A{ESCAPE}\\{CLOSE}")?; Ok(()) }) } async fn encode(img: DynamicImage) -> Result<Vec<u8>> { fn output(raw: &[u8], format: u8, size: (u32, u32)) -> Result<Vec<u8>> { let b64 = general_purpose::STANDARD.encode(raw).into_bytes(); let mut it = b64.chunks(4096).peekable(); let mut buf = Vec::with_capacity(b64.len() + it.len() * 50); if let Some(first) = it.next() { write!( buf, "{START}_Gq=2,a=T,C=1,U=1,f={format},s={},v={},i={},m={};{}{ESCAPE}\\{CLOSE}", size.0, size.1, Kgp::image_id(), it.peek().is_some() as u8, unsafe { str::from_utf8_unchecked(first) }, )?; } while let Some(chunk) = it.next() { write!(buf, "{START}_Gm={};{}{ESCAPE}\\{CLOSE}", it.peek().is_some() as u8, unsafe { str::from_utf8_unchecked(chunk) })?; } write!(buf, "{CLOSE}")?; Ok(buf) } let size = (img.width(), img.height()); tokio::task::spawn_blocking(move || match img { DynamicImage::ImageRgb8(v) => output(v.as_raw(), 24, size), DynamicImage::ImageRgba8(v) => output(v.as_raw(), 32, size), v => output(v.into_rgb8().as_raw(), 24, size), }) .await? } fn place(area: &Rect) -> Result<Vec<u8>> { let mut buf = Vec::with_capacity(area.width as usize * area.height as usize * 3 + 50); let id = Self::image_id(); let (r, g, b) = ((id >> 16) & 0xff, (id >> 8) & 0xff, id & 0xff); write!(buf, "\x1b[38;2;{r};{g};{b}m")?; for y in 0..area.height { write!(buf, "\x1b[{};{}H", area.y + y + 1, area.x + 1)?; for x in 0..area.width { write!(buf, "\u{10EEEE}")?; write!(buf, "{}", *DIACRITICS.get(y as usize).unwrap_or(&DIACRITICS[0]))?; write!(buf, "{}", *DIACRITICS.get(x as usize).unwrap_or(&DIACRITICS[0]))?; } } Ok(buf) } fn image_id() -> u32 { static CACHE: SyncCell<Option<u32>> = SyncCell::new(None); match CACHE.get() { Some(n) => n, None => { let n = std::process::id() % (0xffffff + 1); CACHE.set(Some(n)); n } } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-adapter/src/drivers/chafa.rs
yazi-adapter/src/drivers/chafa.rs
use std::{io::Write, path::PathBuf, process::Stdio}; use ansi_to_tui::IntoText; use anyhow::{Result, bail}; use crossterm::{cursor::MoveTo, queue}; use ratatui::layout::Rect; use tokio::process::Command; use crate::{Adapter, Emulator}; pub(crate) struct Chafa; impl Chafa { pub(crate) async fn image_show(path: PathBuf, max: Rect) -> Result<Rect> { let child = Command::new("chafa") .args([ "-f", "symbols", "--relative", "off", "--polite", "on", "--passthrough", "none", "--animate", "off", "--view-size", ]) .arg(format!("{}x{}", max.width, max.height)) .arg(path) .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::null()) .kill_on_drop(true) .spawn()?; let output = child.wait_with_output().await?; if !output.status.success() { bail!("chafa failed with status: {}", output.status); } else if output.stdout.is_empty() { bail!("chafa returned no output"); } let lines: Vec<_> = output.stdout.split(|&b| b == b'\n').collect(); let Ok(Some(first)) = lines[0].to_text().map(|mut t| t.lines.pop()) else { bail!("failed to parse chafa output"); }; let area = Rect { x: max.x, y: max.y, width: first.width() as u16, height: lines.len() as u16, }; Adapter::Chafa.image_hide()?; Adapter::shown_store(area); Emulator::move_lock((max.x, max.y), |w| { for (i, line) in lines.into_iter().enumerate() { w.write_all(line)?; queue!(w, MoveTo(max.x, max.y + i as u16 + 1))?; } Ok(area) }) } pub(crate) fn image_erase(area: Rect) -> Result<()> { let s = " ".repeat(area.width as usize); Emulator::move_lock((0, 0), |w| { for y in area.top()..area.bottom() { queue!(w, MoveTo(area.x, y))?; write!(w, "{s}")?; } Ok(()) }) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-codegen/src/lib.rs
yazi-codegen/src/lib.rs
use proc_macro::TokenStream; use quote::{format_ident, quote}; use syn::{Attribute, Data, DeriveInput, Fields, parse_macro_input}; #[proc_macro_derive(DeserializeOver1)] pub fn deserialize_over1(input: TokenStream) -> TokenStream { // Parse the input tokens into a syntax tree let input = parse_macro_input!(input as DeriveInput); // Get the name of the struct let name = &input.ident; let shadow_name = format_ident!("__{name}Shadow"); // Process the struct fields let (shadow_fields, field_calls) = match &input.data { Data::Struct(struct_) => match &struct_.fields { Fields::Named(fields) => { let mut shadow_fields = Vec::with_capacity(fields.named.len()); let mut field_calls = Vec::with_capacity(fields.named.len()); for field in &fields.named { let name = &field.ident; let attrs: Vec<&Attribute> = field.attrs.iter().filter(|&a| a.path().is_ident("serde")).collect(); shadow_fields.push(quote! { #(#attrs)* pub(crate) #name: Option<toml::Value> }); field_calls.push(quote! { if let Some(value) = shadow.#name { self.#name = self.#name.deserialize_over(value).map_err(serde::de::Error::custom)?; } }); } (shadow_fields, field_calls) } _ => panic!("DeserializeOver1 only supports structs with named fields"), }, _ => panic!("DeserializeOver1 only supports structs"), }; quote! { #[derive(serde::Deserialize)] pub(crate) struct #shadow_name { #(#shadow_fields),* } impl #name { #[inline] pub(crate) fn deserialize_over<'de, D>(self, deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { self.deserialize_over_with::<D>(Self::deserialize_shadow(deserializer)?) } #[inline] pub(crate) fn deserialize_shadow<'de, D>(deserializer: D) -> Result<#shadow_name, D::Error> where D: serde::Deserializer<'de>, { #shadow_name::deserialize(deserializer) } #[inline] pub(crate) fn deserialize_over_with<'de, D>(mut self, shadow: #shadow_name) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { #(#field_calls)* Ok(self) } } } .into() } #[proc_macro_derive(DeserializeOver2)] pub fn deserialize_over2(input: TokenStream) -> TokenStream { // Parse the input tokens into a syntax tree let input = parse_macro_input!(input as DeriveInput); // Get the name of the struct let name = &input.ident; let shadow_name = format_ident!("__{name}Shadow"); // Process the struct fields let (shadow_fields, field_assignments) = match &input.data { Data::Struct(struct_) => match &struct_.fields { Fields::Named(fields) => { let mut shadow_fields = Vec::with_capacity(fields.named.len()); let mut field_assignments = Vec::with_capacity(fields.named.len()); for field in &fields.named { let (ty, name) = (&field.ty, &field.ident); shadow_fields.push(quote! { pub(crate) #name: Option<#ty> }); field_assignments.push(quote! { if let Some(value) = shadow.#name { self.#name = value; } }); } (shadow_fields, field_assignments) } _ => panic!("DeserializeOver2 only supports structs with named fields"), }, _ => panic!("DeserializeOver2 only supports structs"), }; quote! { #[derive(serde::Deserialize)] pub(crate) struct #shadow_name { #(#shadow_fields),* } impl #name { #[inline] pub(crate) fn deserialize_over<'de, D>(mut self, deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { Ok(self.deserialize_over_with(Self::deserialize_shadow(deserializer)?)) } #[inline] pub(crate) fn deserialize_shadow<'de, D>(deserializer: D) -> Result<#shadow_name, D::Error> where D: serde::Deserializer<'de> { #shadow_name::deserialize(deserializer) } #[inline] pub(crate) fn deserialize_over_with(mut self, shadow: #shadow_name) -> Self { #(#field_assignments)* self } } } .into() }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/ser.rs
yazi-sftp/src/ser.rs
use serde::ser::{SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple, SerializeTupleStruct, SerializeTupleVariant}; use crate::Error; pub(super) struct Serializer { pub(super) output: Vec<u8>, } impl<'a> serde::Serializer for &'a mut Serializer { type Error = crate::Error; type Ok = (); type SerializeMap = &'a mut Serializer; type SerializeSeq = &'a mut Serializer; type SerializeStruct = &'a mut Serializer; type SerializeStructVariant = &'a mut Serializer; type SerializeTuple = &'a mut Serializer; type SerializeTupleStruct = &'a mut Serializer; type SerializeTupleVariant = &'a mut Serializer; fn serialize_bool(self, _v: bool) -> Result<Self::Ok, Self::Error> { Err(Error::serde("bool not supported")) } fn serialize_i8(self, _v: i8) -> Result<Self::Ok, Self::Error> { Err(Error::serde("i8 not supported")) } fn serialize_i16(self, _v: i16) -> Result<Self::Ok, Self::Error> { Err(Error::serde("i16 not supported")) } fn serialize_i32(self, _v: i32) -> Result<Self::Ok, Self::Error> { Err(Error::serde("i32 not supported")) } fn serialize_i64(self, _v: i64) -> Result<Self::Ok, Self::Error> { Err(Error::serde("i64 not supported")) } fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> { self.output.push(v); Ok(()) } fn serialize_u16(self, _v: u16) -> Result<Self::Ok, Self::Error> { Err(Error::serde("u16 not supported")) } fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> { self.output.extend_from_slice(&v.to_be_bytes()); Ok(()) } fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> { self.output.extend_from_slice(&v.to_be_bytes()); Ok(()) } fn serialize_f32(self, _v: f32) -> Result<Self::Ok, Self::Error> { Err(Error::serde("f32 not supported")) } fn serialize_f64(self, _v: f64) -> Result<Self::Ok, Self::Error> { Err(Error::serde("f64 not supported")) } fn serialize_char(self, _v: char) -> Result<Self::Ok, Self::Error> { Err(Error::serde("char not supported")) } fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> { self.serialize_bytes(v.as_bytes()) } fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> { let len = u32::try_from(v.len()).map_err(|_| Error::serde("bytes too long"))?; self.output.extend_from_slice(&len.to_be_bytes()); self.output.extend_from_slice(v); Ok(()) } fn serialize_none(self) -> Result<Self::Ok, Self::Error> { Ok(()) } fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error> where T: serde::Serialize + ?Sized, { value.serialize(self) } fn serialize_unit(self) -> Result<Self::Ok, Self::Error> { Err(Error::serde("unit not supported")) } fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> { Ok(()) } fn serialize_unit_variant( self, _name: &'static str, variant_index: u32, _variant: &'static str, ) -> Result<Self::Ok, Self::Error> { self.serialize_u32(variant_index) } fn serialize_newtype_struct<T>( self, _name: &'static str, value: &T, ) -> Result<Self::Ok, Self::Error> where T: serde::Serialize + ?Sized, { value.serialize(self) } fn serialize_newtype_variant<T>( self, _name: &'static str, _variant_index: u32, _variant: &'static str, value: &T, ) -> Result<Self::Ok, Self::Error> where T: serde::Serialize + ?Sized, { value.serialize(self) } fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> { if let Some(len) = len { self.serialize_u32(len.try_into().map_err(|_| Error::serde("sequence too long"))?)?; } Ok(self) } fn serialize_tuple_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, ) -> Result<Self::SerializeTupleVariant, Self::Error> { Ok(self) } fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> { Ok(self) } fn serialize_tuple_struct( self, _name: &'static str, _len: usize, ) -> Result<Self::SerializeTupleStruct, Self::Error> { Ok(self) } fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> { Ok(self) } fn serialize_struct( self, _name: &'static str, _len: usize, ) -> Result<Self::SerializeStruct, Self::Error> { Ok(self) } fn serialize_struct_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, ) -> Result<Self::SerializeStructVariant, Self::Error> { Err(Error::serde("struct variant not supported")) } fn is_human_readable(&self) -> bool { false } } impl SerializeMap for &mut Serializer { type Error = Error; type Ok = (); fn serialize_key<T>(&mut self, key: &T) -> Result<(), Self::Error> where T: serde::Serialize + ?Sized, { key.serialize(&mut **self) } fn serialize_value<T>(&mut self, value: &T) -> Result<(), Self::Error> where T: serde::Serialize + ?Sized, { value.serialize(&mut **self) } fn end(self) -> Result<Self::Ok, Self::Error> { Ok(()) } } impl SerializeSeq for &mut Serializer { type Error = Error; type Ok = (); fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error> where T: serde::Serialize + ?Sized, { value.serialize(&mut **self) } fn end(self) -> Result<Self::Ok, Self::Error> { Ok(()) } } impl SerializeStruct for &mut Serializer { type Error = Error; type Ok = (); fn serialize_field<T>(&mut self, _key: &'static str, value: &T) -> Result<(), Self::Error> where T: serde::Serialize + ?Sized, { value.serialize(&mut **self) } fn end(self) -> Result<Self::Ok, Self::Error> { Ok(()) } } impl SerializeStructVariant for &mut Serializer { type Error = Error; type Ok = (); fn serialize_field<T>(&mut self, _key: &'static str, value: &T) -> Result<(), Self::Error> where T: serde::Serialize + ?Sized, { value.serialize(&mut **self) } fn end(self) -> Result<Self::Ok, Self::Error> { Ok(()) } } impl SerializeTuple for &mut Serializer { type Error = Error; type Ok = (); fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error> where T: serde::Serialize + ?Sized, { value.serialize(&mut **self) } fn end(self) -> Result<Self::Ok, Self::Error> { Ok(()) } } impl SerializeTupleStruct for &mut Serializer { type Error = Error; type Ok = (); fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error> where T: serde::Serialize + ?Sized, { value.serialize(&mut **self) } fn end(self) -> Result<Self::Ok, Self::Error> { Ok(()) } } impl SerializeTupleVariant for &mut Serializer { type Error = Error; type Ok = (); fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error> where T: serde::Serialize + ?Sized, { value.serialize(&mut **self) } fn end(self) -> Result<Self::Ok, Self::Error> { Ok(()) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/path.rs
yazi-sftp/src/path.rs
use std::{borrow::Cow, ops::Deref}; use serde::{Deserialize, Serialize}; #[derive(Debug)] pub enum SftpPath<'a> { Borrowed(&'a typed_path::UnixPath), Owned(typed_path::UnixPathBuf), } impl Deref for SftpPath<'_> { type Target = typed_path::UnixPath; fn deref(&self) -> &Self::Target { match self { SftpPath::Borrowed(p) => p, SftpPath::Owned(p) => p.as_path(), } } } impl Default for SftpPath<'_> { fn default() -> Self { SftpPath::Borrowed(typed_path::UnixPath::new("")) } } impl<'a> From<&'a Self> for SftpPath<'a> { fn from(value: &'a SftpPath) -> Self { SftpPath::Borrowed(value) } } impl<'a> From<Cow<'a, [u8]>> for SftpPath<'a> { fn from(value: Cow<'a, [u8]>) -> Self { match value { Cow::Borrowed(b) => Self::Borrowed(typed_path::UnixPath::new(b)), Cow::Owned(b) => SftpPath::Owned(typed_path::UnixPathBuf::from(b)), } } } impl Serialize for SftpPath<'_> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serializer.serialize_bytes(self.as_bytes()) } } impl<'de> Deserialize<'de> for SftpPath<'_> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let cow = <Cow<'de, [u8]>>::deserialize(deserializer)?; Ok(Self::Owned(cow.into_owned().into())) } } impl<'a> SftpPath<'a> { pub fn len(&self) -> usize { self.as_bytes().len() } pub fn into_owned(self) -> typed_path::UnixPathBuf { match self { SftpPath::Borrowed(p) => p.to_owned(), SftpPath::Owned(p) => p, } } } // --- Traits pub trait AsSftpPath<'a> { fn as_sftp_path(self) -> SftpPath<'a>; } impl<'a, T> AsSftpPath<'a> for &'a T where T: ?Sized + AsRef<typed_path::UnixPath>, { fn as_sftp_path(self) -> SftpPath<'a> { SftpPath::Borrowed(self.as_ref()) } } impl<'a> AsSftpPath<'a> for &'a SftpPath<'a> { fn as_sftp_path(self) -> SftpPath<'a> { SftpPath::Borrowed(self) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/packet.rs
yazi-sftp/src/packet.rs
use serde::{Deserialize, Serialize}; use super::de::Deserializer; use crate::{Error, impl_from_packet, impl_try_from_packet, requests, responses}; #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum Packet<'a> { Init(requests::Init), Open(requests::Open<'a>), Close(requests::Close<'a>), Read(requests::Read<'a>), Write(requests::Write<'a>), Lstat(requests::Lstat<'a>), Fstat(requests::Fstat<'a>), SetStat(requests::SetStat<'a>), FSetStat(requests::FSetStat<'a>), OpenDir(requests::OpenDir<'a>), ReadDir(requests::ReadDir<'a>), Remove(requests::Remove<'a>), Mkdir(requests::Mkdir<'a>), Rmdir(requests::Rmdir<'a>), Realpath(requests::Realpath<'a>), Stat(requests::Stat<'a>), Rename(requests::Rename<'a>), Readlink(requests::Readlink<'a>), Symlink(requests::Symlink<'a>), ExtendedRename(requests::Extended<'a, requests::ExtendedRename<'a>>), ExtendedFsync(requests::Extended<'a, requests::ExtendedFsync<'a>>), ExtendedHardlink(requests::Extended<'a, requests::ExtendedHardlink<'a>>), ExtendedLimits(requests::Extended<'a, requests::ExtendedLimits>), // Responses Version(responses::Version), Status(responses::Status), Handle(responses::Handle), Data(responses::Data), Name(responses::Name<'a>), Attrs(responses::Attrs), ExtendedReply(responses::Extended<'a>), } impl_from_packet! { Init(requests::Init), Open(requests::Open<'a>), Close(requests::Close<'a>), Read(requests::Read<'a>), Write(requests::Write<'a>), Lstat(requests::Lstat<'a>), Fstat(requests::Fstat<'a>), SetStat(requests::SetStat<'a>), FSetStat(requests::FSetStat<'a>), OpenDir(requests::OpenDir<'a>), ReadDir(requests::ReadDir<'a>), Remove(requests::Remove<'a>), Mkdir(requests::Mkdir<'a>), Rmdir(requests::Rmdir<'a>), Realpath(requests::Realpath<'a>), Stat(requests::Stat<'a>), Rename(requests::Rename<'a>), Readlink(requests::Readlink<'a>), Symlink(requests::Symlink<'a>), ExtendedRename(requests::Extended<'a, requests::ExtendedRename<'a>>), ExtendedFsync(requests::Extended<'a, requests::ExtendedFsync<'a>>), ExtendedHardlink(requests::Extended<'a, requests::ExtendedHardlink<'a>>), ExtendedLimits(requests::Extended<'a, requests::ExtendedLimits>), // Responses Version(responses::Version), Status(responses::Status), Handle(responses::Handle), Data(responses::Data), Name(responses::Name<'a>), Attrs(responses::Attrs), ExtendedReply(responses::Extended<'a>), } impl_try_from_packet! { Version(responses::Version), Status(responses::Status), Handle(responses::Handle), Data(responses::Data), Name(responses::Name<'a>), Attrs(responses::Attrs), ExtendedReply(responses::Extended<'a>), } impl Packet<'_> { fn kind(&self) -> u8 { match self { Self::Init(_) => 1, Self::Open(_) => 3, Self::Close(_) => 4, Self::Read(_) => 5, Self::Write(_) => 6, Self::Lstat(_) => 7, Self::Fstat(_) => 8, Self::SetStat(_) => 9, Self::FSetStat(_) => 10, Self::OpenDir(_) => 11, Self::ReadDir(_) => 12, Self::Remove(_) => 13, Self::Mkdir(_) => 14, Self::Rmdir(_) => 15, Self::Realpath(_) => 16, Self::Stat(_) => 17, Self::Rename(_) => 18, Self::Readlink(_) => 19, Self::Symlink(_) => 20, Self::ExtendedRename(_) => 200, Self::ExtendedFsync(_) => 200, Self::ExtendedHardlink(_) => 200, Self::ExtendedLimits(_) => 200, // Responses Self::Version(_) => 2, Self::Status(_) => 101, Self::Handle(_) => 102, Self::Data(_) => 103, Self::Name(_) => 104, Self::Attrs(_) => 105, Self::ExtendedReply(_) => 201, } } pub fn id(&self) -> u32 { match self { Self::Init(_) => 0, Self::Open(v) => v.id, Self::Close(v) => v.id, Self::Read(v) => v.id, Self::Write(v) => v.id, Self::Lstat(v) => v.id, Self::Fstat(v) => v.id, Self::SetStat(v) => v.id, Self::FSetStat(v) => v.id, Self::OpenDir(v) => v.id, Self::ReadDir(v) => v.id, Self::Remove(v) => v.id, Self::Mkdir(v) => v.id, Self::Rmdir(v) => v.id, Self::Realpath(v) => v.id, Self::Stat(v) => v.id, Self::Rename(v) => v.id, Self::Readlink(v) => v.id, Self::Symlink(v) => v.id, Self::ExtendedRename(v) => v.id, Self::ExtendedFsync(v) => v.id, Self::ExtendedHardlink(v) => v.id, Self::ExtendedLimits(v) => v.id, // Responses Self::Version(_) => 0, Self::Status(v) => v.id, Self::Handle(v) => v.id, Self::Data(v) => v.id, Self::Name(v) => v.id, Self::Attrs(v) => v.id, Self::ExtendedReply(v) => v.id, } } pub fn with_id(mut self, id: u32) -> Self { match &mut self { Self::Init(_) => {} Self::Open(v) => v.id = id, Self::Close(v) => v.id = id, Self::Read(v) => v.id = id, Self::Write(v) => v.id = id, Self::Lstat(v) => v.id = id, Self::Fstat(v) => v.id = id, Self::SetStat(v) => v.id = id, Self::FSetStat(v) => v.id = id, Self::OpenDir(v) => v.id = id, Self::ReadDir(v) => v.id = id, Self::Remove(v) => v.id = id, Self::Mkdir(v) => v.id = id, Self::Rmdir(v) => v.id = id, Self::Realpath(v) => v.id = id, Self::Stat(v) => v.id = id, Self::Rename(v) => v.id = id, Self::Readlink(v) => v.id = id, Self::Symlink(v) => v.id = id, Self::ExtendedRename(v) => v.id = id, Self::ExtendedFsync(v) => v.id = id, Self::ExtendedHardlink(v) => v.id = id, Self::ExtendedLimits(v) => v.id = id, // Responses Self::Version(_) => {} Self::Status(v) => v.id = id, Self::Handle(v) => v.id = id, Self::Data(v) => v.id = id, Self::Name(v) => v.id = id, Self::Attrs(v) => v.id = id, Self::ExtendedReply(v) => v.id = id, } self } fn len(&self) -> usize { let type_len = 1; match self { Self::Init(v) => type_len + v.len(), Self::Open(v) => type_len + v.len(), Self::Close(v) => type_len + v.len(), Self::Read(v) => type_len + v.len(), Self::Write(v) => type_len + v.len(), Self::Lstat(v) => type_len + v.len(), Self::Fstat(v) => type_len + v.len(), Self::SetStat(v) => type_len + v.len(), Self::FSetStat(v) => type_len + v.len(), Self::OpenDir(v) => type_len + v.len(), Self::ReadDir(v) => type_len + v.len(), Self::Remove(v) => type_len + v.len(), Self::Mkdir(v) => type_len + v.len(), Self::Rmdir(v) => type_len + v.len(), Self::Realpath(v) => type_len + v.len(), Self::Stat(v) => type_len + v.len(), Self::Rename(v) => type_len + v.len(), Self::Readlink(v) => type_len + v.len(), Self::Symlink(v) => type_len + v.len(), Self::ExtendedRename(v) => type_len + v.len(), Self::ExtendedFsync(v) => type_len + v.len(), Self::ExtendedHardlink(v) => type_len + v.len(), Self::ExtendedLimits(v) => type_len + v.len(), // Responses Self::Version(v) => type_len + v.len(), Self::Status(v) => type_len + v.len(), Self::Handle(v) => type_len + v.len(), Self::Data(v) => type_len + v.len(), Self::Name(v) => type_len + v.len(), Self::Attrs(v) => type_len + v.len(), Self::ExtendedReply(v) => type_len + v.len(), } } } pub fn to_bytes<'a, T>(value: T) -> Result<Vec<u8>, Error> where T: Into<Packet<'a>> + Serialize, { let packet: Packet = value.into(); let len = u32::try_from(packet.len()).map_err(|_| Error::serde("packet too large"))?; let mut output = Vec::with_capacity(4 + len as usize); output.extend_from_slice(&len.to_be_bytes()); output.push(packet.kind()); let mut serializer = crate::Serializer { output }; packet.serialize(&mut serializer)?; Ok(serializer.output) } // TODO: use Vec<u8> pub fn from_bytes(mut bytes: &[u8]) -> Result<Packet<'static>, Error> { let kind = *bytes.first().ok_or(Error::serde("empty packet"))?; bytes = &bytes[1..]; Ok(match kind { 2 => Packet::Version(Deserializer::once(bytes)?), 101 => Packet::Status(Deserializer::once(bytes)?), 102 => Packet::Handle(Deserializer::once(bytes)?), 103 => Packet::Data(Deserializer::once(bytes)?), 104 => Packet::Name(Deserializer::once(bytes)?), 105 => Packet::Attrs(Deserializer::once(bytes)?), 201 => Packet::ExtendedReply(Deserializer::once(bytes)?), _ => return Err(Error::Packet("unknown packet kind")), }) }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/lib.rs
yazi-sftp/src/lib.rs
pub mod fs; pub mod requests; pub mod responses; mod de; mod error; mod id; mod macros; mod operator; mod packet; mod path; mod receiver; mod ser; mod session; pub(crate) use de::*; pub use error::*; pub(crate) use id::*; pub use operator::*; pub use packet::*; pub use path::*; pub use receiver::*; pub(crate) use ser::*; pub use session::*;
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/session.rs
yazi-sftp/src/session.rs
use std::{any::TypeId, collections::HashMap, io::{self, ErrorKind}, sync::Arc, time::Duration}; use parking_lot::Mutex; use russh::{ChannelStream, client::Msg}; use serde::Serialize; use tokio::{io::{AsyncReadExt, AsyncWriteExt, ReadHalf, WriteHalf}, select, sync::{mpsc, oneshot}}; use crate::{Error, Id, Packet, Receiver, responses}; pub struct Session { tx: mpsc::UnboundedSender<Vec<u8>>, id: Id, pub(super) callback: Mutex<HashMap<u32, oneshot::Sender<Packet<'static>>>>, pub(super) extensions: Mutex<HashMap<String, String>>, } impl Drop for Session { fn drop(&mut self) { self.tx.send(vec![]).ok(); } } impl Session { pub(super) fn make(stream: ChannelStream<Msg>) -> Arc<Self> { let (tx, mut rx) = mpsc::unbounded_channel(); let me = Arc::new(Self { tx, id: Id::default(), callback: Default::default(), extensions: Default::default(), }); async fn read(reader: &mut ReadHalf<ChannelStream<Msg>>) -> io::Result<Vec<u8>> { let len = reader.read_u32().await?; let mut buf = vec![0; len as usize]; reader.read_exact(&mut buf).await?; Ok(buf) } async fn write(writer: &mut WriteHalf<ChannelStream<Msg>>, buf: Vec<u8>) -> io::Result<()> { if buf.is_empty() { Err(io::Error::from(ErrorKind::BrokenPipe)) } else { writer.write_all(&buf).await } } let me_ = me.clone(); let (mut reader, mut writer) = tokio::io::split(stream); tokio::spawn(async move { while let Some(data) = rx.recv().await { if let Err(e) = write(&mut writer, data).await && e.kind() == ErrorKind::BrokenPipe { rx.close(); writer.shutdown().await.ok(); for (id, cb) in me_.callback.lock().drain() { cb.send(responses::Status::connection_lost(id).into()).ok(); } break; } } }); let me_ = me.clone(); tokio::spawn(async move { loop { select! { result = read(&mut reader) => { let buf = match result { Ok(b) => b, Err(e) if e.kind() == ErrorKind::UnexpectedEof => { me_.tx.send(vec![]).ok(); break; }, Err(_) => continue, }; if let Ok(packet) = crate::from_bytes(&buf) && let Some(cb) = me_.callback.lock().remove(&packet.id()) { cb.send(packet).ok(); } } _ = me_.tx.closed() => break, } } }); me } pub async fn send<'a, I, O>(self: &Arc<Self>, input: I) -> Result<O, Error> where I: Into<Packet<'a>> + Serialize, O: TryFrom<Packet<'static>, Error = Error> + 'static, { self.send_with_timeout(input, Duration::from_secs(45)).await } pub fn send_sync<'a, I>(self: &Arc<Self>, input: I) -> Result<Receiver, Error> where I: Into<Packet<'a>> + Serialize, { let mut request: Packet = input.into(); if request.id() == 0 { request = request.with_id(self.id.next()); } let id = request.id(); let (tx, rx) = oneshot::channel(); self.callback.lock().insert(id, tx); self.tx.send(crate::to_bytes(request)?)?; Ok(Receiver::new(self, id, rx)) } pub async fn send_with_timeout<'a, I, O>( self: &Arc<Self>, input: I, timeout: Duration, ) -> Result<O, Error> where I: Into<Packet<'a>> + Serialize, O: TryFrom<Packet<'static>, Error = Error> + 'static, { match tokio::time::timeout(timeout, self.send_sync(input)?).await?? { Packet::Status(status) if TypeId::of::<O>() != TypeId::of::<responses::Status>() => { Err(Error::Status(status)) } response => response.try_into(), } } pub fn is_closed(self: &Arc<Self>) -> bool { self.tx.is_closed() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/id.rs
yazi-sftp/src/id.rs
use std::sync::atomic::{AtomicU32, Ordering}; pub(super) struct Id(AtomicU32); impl Default for Id { fn default() -> Self { Self(AtomicU32::new(1)) } } impl Id { pub(super) fn next(&self) -> u32 { loop { let old = self.0.fetch_add(1, Ordering::Relaxed); if old != 0 { return old; } } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/error.rs
yazi-sftp/src/error.rs
use std::borrow::Cow; use crate::responses; #[derive(Debug)] pub enum Error { IO(std::io::Error), Serde(Cow<'static, str>), Status(responses::Status), Packet(&'static str), Timeout, Unsupported, Custom(Cow<'static, str>), } impl Error { pub(super) fn serde(s: impl Into<Cow<'static, str>>) -> Self { Self::Serde(s.into()) } pub(super) fn custom(s: impl Into<Cow<'static, str>>) -> Self { Self::Custom(s.into()) } } impl serde::ser::Error for Error { fn custom<T: std::fmt::Display>(msg: T) -> Self { Self::serde(msg.to_string()) } } impl serde::de::Error for Error { fn custom<T: std::fmt::Display>(msg: T) -> Self { Self::serde(msg.to_string()) } } impl From<Error> for std::io::Error { fn from(err: Error) -> Self { match err { Error::IO(e) => e, Error::Serde(e) => Self::new(std::io::ErrorKind::InvalidData, e), Error::Status(status) => match status.code { responses::StatusCode::Ok => Self::other("unexpected OK"), responses::StatusCode::Eof => Self::from(std::io::ErrorKind::UnexpectedEof), responses::StatusCode::NoSuchFile => Self::from(std::io::ErrorKind::NotFound), responses::StatusCode::PermissionDenied => Self::from(std::io::ErrorKind::PermissionDenied), responses::StatusCode::Failure => Self::from(std::io::ErrorKind::Other), responses::StatusCode::BadMessage => Self::from(std::io::ErrorKind::InvalidData), responses::StatusCode::NoConnection => Self::from(std::io::ErrorKind::NotConnected), responses::StatusCode::ConnectionLost => Self::from(std::io::ErrorKind::ConnectionReset), responses::StatusCode::OpUnsupported => Self::from(std::io::ErrorKind::Unsupported), responses::StatusCode::InvalidHandle => Self::from(std::io::ErrorKind::InvalidInput), responses::StatusCode::NoSuchPath => Self::from(std::io::ErrorKind::NotFound), responses::StatusCode::FileAlreadyExists => Self::from(std::io::ErrorKind::AlreadyExists), responses::StatusCode::WriteProtect => Self::from(std::io::ErrorKind::PermissionDenied), responses::StatusCode::NoMedia => Self::from(std::io::ErrorKind::Other), }, Error::Packet(e) => Self::new(std::io::ErrorKind::InvalidData, e), Error::Timeout => Self::from(std::io::ErrorKind::TimedOut), Error::Unsupported => Self::from(std::io::ErrorKind::Unsupported), Error::Custom(_) => Self::other(err), } } } impl<T> From<tokio::sync::mpsc::error::SendError<T>> for Error { fn from(_: tokio::sync::mpsc::error::SendError<T>) -> Self { Self::custom("channel closed") } } impl From<tokio::sync::oneshot::error::RecvError> for Error { fn from(_: tokio::sync::oneshot::error::RecvError) -> Self { Self::custom("channel closed") } } impl From<tokio::time::error::Elapsed> for Error { fn from(_: tokio::time::error::Elapsed) -> Self { Self::Timeout } } impl std::error::Error for Error {} impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::IO(e) => write!(f, "IO error: {e}"), Self::Serde(s) => write!(f, "Serde error: {s}"), Self::Status(s) => write!(f, "Status error: {s:?}"), Self::Packet(s) => write!(f, "Unexpected packet: {s}"), Self::Timeout => write!(f, "Operation timed out"), Self::Unsupported => write!(f, "Operation not supported"), Self::Custom(s) => write!(f, "{s}"), } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/operator.rs
yazi-sftp/src/operator.rs
use std::{ops::Deref, sync::Arc}; use russh::{ChannelStream, client::Msg}; use typed_path::UnixPathBuf; use crate::{AsSftpPath, Error, Receiver, Session, SftpPath, fs::{Attrs, File, Flags, ReadDir}, requests, responses}; pub struct Operator(Arc<Session>); impl Deref for Operator { type Target = Arc<Session>; fn deref(&self) -> &Self::Target { &self.0 } } impl From<&Arc<Session>> for Operator { fn from(session: &Arc<Session>) -> Self { Self(session.clone()) } } impl Operator { pub fn make(stream: ChannelStream<Msg>) -> Self { Self(Session::make(stream)) } pub async fn init(&mut self) -> Result<(), Error> { let version: responses::Version = self.send(requests::Init::default()).await?; *self.extensions.lock() = version.extensions; Ok(()) } pub async fn open<'a, P>(&self, path: P, flags: Flags, attrs: &'a Attrs) -> Result<File, Error> where P: AsSftpPath<'a>, { let handle: responses::Handle = self.send(requests::Open::new(path, flags, attrs)).await?; Ok(File::new(&self.0, handle.handle)) } pub fn close(&self, handle: &str) -> Result<Receiver, Error> { self.send_sync(requests::Close::new(handle)) } pub fn read(&self, handle: &str, offset: u64, len: u32) -> Result<Receiver, Error> { self.send_sync(requests::Read::new(handle, offset, len)) } pub fn write(&self, handle: &str, offset: u64, data: &[u8]) -> Result<Receiver, Error> { self.send_sync(requests::Write::new(handle, offset, data)) } pub async fn lstat<'a, P>(&self, path: P) -> Result<Attrs, Error> where P: AsSftpPath<'a>, { let attrs: responses::Attrs = self.send(requests::Lstat::new(path)).await?; Ok(attrs.attrs) } pub async fn fstat(&self, handle: &str) -> Result<Attrs, Error> { let attrs: responses::Attrs = self.send(requests::Fstat::new(handle)).await?; Ok(attrs.attrs) } pub async fn setstat<'a, P>(&self, path: P, attrs: Attrs) -> Result<(), Error> where P: AsSftpPath<'a>, { let status: responses::Status = self.send(requests::SetStat::new(path, attrs)).await?; status.into() } pub async fn fsetstat(&self, handle: &str, attrs: &Attrs) -> Result<(), Error> { let status: responses::Status = self.send(requests::FSetStat::new(handle, attrs)).await?; status.into() } pub async fn read_dir<'a, P>(&'a self, dir: P) -> Result<ReadDir, Error> where P: AsSftpPath<'a>, { let dir: SftpPath = dir.as_sftp_path(); let handle: responses::Handle = self.send(requests::OpenDir::new(&dir)).await?; Ok(ReadDir::new(&self.0, dir, handle.handle)) } pub async fn remove<'a, P>(&self, path: P) -> Result<(), Error> where P: AsSftpPath<'a>, { let status: responses::Status = self.send(requests::Remove::new(path)).await?; status.into() } pub async fn mkdir<'a, P>(&self, path: P, attrs: Attrs) -> Result<(), Error> where P: AsSftpPath<'a>, { let status: responses::Status = self.send(requests::Mkdir::new(path, attrs)).await?; status.into() } pub async fn rmdir<'a, P>(&self, path: P) -> Result<(), Error> where P: AsSftpPath<'a>, { let status: responses::Status = self.send(requests::Rmdir::new(path)).await?; status.into() } pub async fn realpath<'a, P>(&self, path: P) -> Result<UnixPathBuf, Error> where P: AsSftpPath<'a>, { let mut name: responses::Name = self.send(requests::Realpath::new(path)).await?; if name.items.is_empty() { Err(Error::custom("realpath returned no names")) } else { Ok(name.items.swap_remove(0).name.into_owned().into()) } } pub async fn stat<'a, P>(&self, path: P) -> Result<Attrs, Error> where P: AsSftpPath<'a>, { let attrs: responses::Attrs = self.send(requests::Stat::new(path)).await?; Ok(attrs.attrs) } pub async fn rename<'a, F, T>(&self, from: F, to: T) -> Result<(), Error> where F: AsSftpPath<'a>, T: AsSftpPath<'a>, { let status: responses::Status = self.send(requests::Rename::new(from, to)).await?; status.into() } pub async fn rename_posix<'a, F, T>(&self, from: F, to: T) -> Result<(), Error> where F: AsSftpPath<'a>, T: AsSftpPath<'a>, { if self.extensions.lock().get("posix-rename@openssh.com").is_none_or(|s| s != "1") { return Err(Error::Unsupported); } let data = requests::ExtendedRename::new(from, to); let status: responses::Status = self.send(requests::Extended::new("posix-rename@openssh.com", data)).await?; status.into() } pub async fn readlink<'a, P>(&self, path: P) -> Result<UnixPathBuf, Error> where P: AsSftpPath<'a>, { let mut name: responses::Name = self.send(requests::Readlink::new(path)).await?; if name.items.is_empty() { Err(Error::custom("readlink returned no names")) } else { Ok(name.items.swap_remove(0).name.into_owned().into()) } } pub async fn symlink<'a, L, O>(&self, original: O, link: L) -> Result<(), Error> where O: AsSftpPath<'a>, L: AsSftpPath<'a>, { let status: responses::Status = self.send(requests::Symlink::new(original, link)).await?; status.into() } pub fn fsync(&self, handle: &str) -> Result<Receiver, Error> { if self.extensions.lock().get("fsync@openssh.com").is_none_or(|s| s != "1") { return Err(Error::Unsupported); } let data = requests::ExtendedFsync::new(handle); self.send_sync(requests::Extended::new("fsync@openssh.com", data)) } pub async fn hardlink<'a, O, L>(&self, original: O, link: L) -> Result<(), Error> where O: AsSftpPath<'a>, L: AsSftpPath<'a>, { if self.extensions.lock().get("hardlink@openssh.com").is_none_or(|s| s != "1") { return Err(Error::Unsupported); } let data = requests::ExtendedHardlink::new(original, link); let status: responses::Status = self.send(requests::Extended::new("hardlink@openssh.com", data)).await?; status.into() } pub async fn limits(&self) -> Result<responses::ExtendedLimits, Error> { if self.extensions.lock().get("limits@openssh.com").is_none_or(|s| s != "1") { return Err(Error::Unsupported); } let extended: responses::Extended = self.send(requests::Extended::new("limits@openssh.com", requests::ExtendedLimits)).await?; extended.try_into() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/macros.rs
yazi-sftp/src/macros.rs
#[macro_export] macro_rules! impl_from_packet { ($($variant:ident($type:ty)),* $(,)?) => { $( impl<'a> From<$type> for $crate::Packet<'a> { fn from(value: $type) -> Self { Self::$variant(value) } } )* }; } #[macro_export] macro_rules! impl_try_from_packet { ($($variant:ident($type:ty)),* $(,)?) => { $( impl<'a> TryFrom<$crate::Packet<'a>> for $type { type Error = $crate::Error; fn try_from(value: $crate::Packet<'a>) -> Result<Self, Self::Error> { match value { $crate::Packet::$variant(v) => Ok(v), _ => Err($crate::Error::Packet(concat!("not a ", stringify!($variant)))), } } } )* }; }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/receiver.rs
yazi-sftp/src/receiver.rs
use std::{pin::Pin, sync::Arc, task::Poll}; use tokio::sync::oneshot; use crate::{Packet, Session}; pub struct Receiver { rx: oneshot::Receiver<Packet<'static>>, received: bool, session: Arc<Session>, id: u32, } impl Drop for Receiver { fn drop(&mut self) { if !self.received { self.session.callback.lock().remove(&self.id); } } } impl Receiver { pub(crate) fn new( session: &Arc<Session>, id: u32, rx: oneshot::Receiver<Packet<'static>>, ) -> Self { Self { rx, received: false, session: session.clone(), id } } } impl Future for Receiver { type Output = Result<Packet<'static>, oneshot::error::RecvError>; fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { let me = self.get_mut(); match Pin::new(&mut me.rx).poll(cx) { Poll::Ready(Ok(packet)) => { me.received = true; Poll::Ready(Ok(packet)) } Poll::Ready(Err(e)) => Poll::Ready(Err(e)), Poll::Pending => Poll::Pending, } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/de.rs
yazi-sftp/src/de.rs
use serde::{Deserializer as _, de::{EnumAccess, MapAccess, SeqAccess, VariantAccess, value::U32Deserializer}}; use crate::Error; pub(super) struct Deserializer<'a> { input: &'a [u8], } impl<'a> Deserializer<'a> { pub(super) fn once<'de, T>(input: &'de [u8]) -> Result<T, Error> where T: serde::Deserialize<'de>, { let mut de = Deserializer { input }; let t = T::deserialize(&mut de)?; if !de.input.is_empty() { return Err(Error::serde("trailing bytes")); } Ok(t) } } impl<'de> serde::Deserializer<'de> for &mut Deserializer<'de> { type Error = Error; fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { let len = self.input.len(); visitor.visit_seq(SeqDeserializer { de: self, remaining: len }) } fn deserialize_bool<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(Error::serde("bool not supported")) } fn deserialize_i8<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(Error::serde("i8 not supported")) } fn deserialize_i16<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(Error::serde("i16 not supported")) } fn deserialize_i32<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(Error::serde("i32 not supported")) } fn deserialize_i64<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(Error::serde("i64 not supported")) } fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { let b = *self.input.first().ok_or(Error::serde("u8 not enough"))?; self.input = &self.input[1..]; visitor.visit_u8(b) } fn deserialize_u16<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(Error::serde("u16 not supported")) } fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { let b: [u8; 4] = self.input.get(..4).ok_or(Error::serde("u32 not enough"))?.try_into().unwrap(); self.input = &self.input[4..]; visitor.visit_u32(u32::from_be_bytes(b)) } fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { let b: [u8; 8] = self.input.get(..8).ok_or(Error::serde("u64 not enough"))?.try_into().unwrap(); self.input = &self.input[8..]; visitor.visit_u64(u64::from_be_bytes(b)) } fn deserialize_f32<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(Error::serde("f32 not supported")) } fn deserialize_f64<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(Error::serde("f64 not supported")) } fn deserialize_char<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(Error::serde("char not supported")) } fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { let len: [u8; 4] = self.input.get(..4).ok_or(Error::serde("invalid string length"))?.try_into().unwrap(); let len = u32::from_be_bytes(len) as usize; self.input = &self.input[4..]; let b = self.input.get(..len).ok_or(Error::serde("string not enough"))?; self.input = &self.input[len..]; visitor.visit_str(str::from_utf8(b).map_err(|e| Error::serde(e.to_string()))?) } fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { self.deserialize_str(visitor) } fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { let len: [u8; 4] = self.input.get(..4).ok_or(Error::serde("invalid bytes length"))?.try_into().unwrap(); let len = u32::from_be_bytes(len) as usize; let b = self.input.get(4..4 + len).ok_or(Error::serde("bytes not enough"))?; self.input = &self.input[4 + len..]; visitor.visit_bytes(b) } fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { self.deserialize_bytes(visitor) } fn deserialize_option<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(Error::serde("option not supported")) } fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_unit() } fn deserialize_unit_struct<V>( self, _name: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_unit() } fn deserialize_newtype_struct<V>( self, _name: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_newtype_struct(self) } fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { let len: [u8; 4] = self.input.get(..4).ok_or(Error::serde("invalid seq length"))?.try_into().unwrap(); self.input = &self.input[4..]; visitor.visit_seq(SeqDeserializer { de: self, remaining: u32::from_be_bytes(len) as _ }) } fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_seq(SeqDeserializer { de: self, remaining: len }) } fn deserialize_tuple_struct<V>( self, _name: &'static str, len: usize, visitor: V, ) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { self.deserialize_tuple(len, visitor) } fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_map(MapDeserializer { de: self }) } fn deserialize_struct<V>( self, _name: &'static str, fields: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { self.deserialize_tuple(fields.len(), visitor) } fn deserialize_enum<V>( self, _name: &'static str, _variants: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { visitor.visit_enum(self) } fn deserialize_identifier<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(Error::serde("identifier not supported")) } fn deserialize_ignored_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { Err(Error::serde("ignored any not supported")) } fn is_human_readable(&self) -> bool { false } } struct SeqDeserializer<'a, 'de: 'a> { de: &'a mut Deserializer<'de>, remaining: usize, } impl<'de> SeqAccess<'de> for SeqDeserializer<'_, 'de> { type Error = Error; fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> where T: serde::de::DeserializeSeed<'de>, { if self.remaining == 0 { Ok(None) } else { self.remaining -= 1; seed.deserialize(&mut *self.de).map(Some) } } fn size_hint(&self) -> Option<usize> { Some(self.remaining) } } struct MapDeserializer<'a, 'de: 'a> { de: &'a mut Deserializer<'de>, } impl<'de> MapAccess<'de> for MapDeserializer<'_, 'de> { type Error = Error; fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error> where K: serde::de::DeserializeSeed<'de>, { if self.de.input.is_empty() { Ok(None) } else { seed.deserialize(&mut *self.de).map(Some) } } fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error> where V: serde::de::DeserializeSeed<'de>, { seed.deserialize(&mut *self.de) } } impl<'de> VariantAccess<'de> for &mut Deserializer<'de> { type Error = Error; fn unit_variant(self) -> Result<(), Self::Error> { Ok(()) } fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error> where T: serde::de::DeserializeSeed<'de>, { seed.deserialize(self) } fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { use serde::Deserializer; self.deserialize_tuple(len, visitor) } fn struct_variant<V>( self, fields: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de>, { self.deserialize_tuple(fields.len(), visitor) } } impl<'de> EnumAccess<'de> for &mut Deserializer<'de> { type Error = Error; type Variant = Self; fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> where V: serde::de::DeserializeSeed<'de>, { let b: [u8; 4] = self.input.get(..4).ok_or(Error::serde("enum not enough"))?.try_into().unwrap(); self.input = &self.input[4..]; let de = U32Deserializer::<Self::Error>::new(u32::from_be_bytes(b)); Ok((seed.deserialize(de)?, self)) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/requests/open.rs
yazi-sftp/src/requests/open.rs
use std::borrow::Cow; use serde::{Deserialize, Serialize}; use crate::{AsSftpPath, SftpPath, fs::{Attrs, Flags}}; #[derive(Debug, Deserialize, Serialize)] pub struct Open<'a> { pub id: u32, pub path: SftpPath<'a>, pub flags: Flags, pub attrs: Cow<'a, Attrs>, } impl<'a> Open<'a> { pub fn new<P>(path: P, flags: Flags, attrs: &'a Attrs) -> Self where P: AsSftpPath<'a>, { Self { id: 0, path: path.as_sftp_path(), flags, attrs: Cow::Borrowed(attrs) } } pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.path.len() + size_of_val(&self.flags) + self.attrs.len() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/requests/rmdir.rs
yazi-sftp/src/requests/rmdir.rs
use serde::{Deserialize, Serialize}; use crate::{AsSftpPath, SftpPath}; #[derive(Debug, Deserialize, Serialize)] pub struct Rmdir<'a> { pub id: u32, pub path: SftpPath<'a>, } impl<'a> Rmdir<'a> { pub fn new<P>(path: P) -> Self where P: AsSftpPath<'a>, { Self { id: 0, path: path.as_sftp_path() } } pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.path.len() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/requests/mkdir.rs
yazi-sftp/src/requests/mkdir.rs
use serde::{Deserialize, Serialize}; use crate::{AsSftpPath, SftpPath, fs::Attrs}; #[derive(Debug, Deserialize, Serialize)] pub struct Mkdir<'a> { pub id: u32, pub path: SftpPath<'a>, pub attrs: Attrs, } impl<'a> Mkdir<'a> { pub fn new<P>(path: P, attrs: Attrs) -> Self where P: AsSftpPath<'a>, { Self { id: 0, path: path.as_sftp_path(), attrs } } pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.path.len() + self.attrs.len() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/requests/write.rs
yazi-sftp/src/requests/write.rs
use std::borrow::Cow; use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] pub struct Write<'a> { pub id: u32, pub handle: Cow<'a, str>, pub offset: u64, pub data: Cow<'a, [u8]>, } impl Write<'_> { pub fn new<'a, H, D>(handle: H, offset: u64, data: D) -> Write<'a> where H: Into<Cow<'a, str>>, D: Into<Cow<'a, [u8]>>, { Write { id: 0, handle: handle.into(), offset, data: data.into() } } pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.handle.len() + size_of_val(&self.offset) + 4 + self.data.len() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/requests/symlink.rs
yazi-sftp/src/requests/symlink.rs
use serde::{Deserialize, Serialize}; use crate::{AsSftpPath, SftpPath}; #[derive(Debug, Deserialize, Serialize)] pub struct Symlink<'a> { pub id: u32, pub link: SftpPath<'a>, pub original: SftpPath<'a>, } impl<'a> Symlink<'a> { pub fn new<L, O>(link: L, original: O) -> Self where L: AsSftpPath<'a>, O: AsSftpPath<'a>, { Self { id: 0, link: link.as_sftp_path(), original: original.as_sftp_path() } } pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.link.len() + 4 + self.original.len() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/requests/stat.rs
yazi-sftp/src/requests/stat.rs
use serde::{Deserialize, Serialize}; use crate::{AsSftpPath, SftpPath}; #[derive(Debug, Deserialize, Serialize)] pub struct Stat<'a> { pub id: u32, pub path: SftpPath<'a>, } impl<'a> Stat<'a> { pub fn new<P>(path: P) -> Self where P: AsSftpPath<'a>, { Self { id: 0, path: path.as_sftp_path() } } pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.path.len() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/requests/rename.rs
yazi-sftp/src/requests/rename.rs
use serde::{Deserialize, Serialize}; use crate::{AsSftpPath, SftpPath}; #[derive(Debug, Deserialize, Serialize)] pub struct Rename<'a> { pub id: u32, pub from: SftpPath<'a>, pub to: SftpPath<'a>, } impl<'a> Rename<'a> { pub fn new<F, T>(from: F, to: T) -> Self where F: AsSftpPath<'a>, T: AsSftpPath<'a>, { Self { id: 0, from: from.as_sftp_path(), to: to.as_sftp_path() } } pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.from.len() + 4 + self.to.len() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/requests/realpath.rs
yazi-sftp/src/requests/realpath.rs
use serde::{Deserialize, Serialize}; use crate::{AsSftpPath, SftpPath}; #[derive(Debug, Deserialize, Serialize)] pub struct Realpath<'a> { pub id: u32, pub path: SftpPath<'a>, } impl<'a> Realpath<'a> { pub fn new<P>(path: P) -> Self where P: AsSftpPath<'a>, { Self { id: 0, path: path.as_sftp_path() } } pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.path.len() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/requests/set_stat.rs
yazi-sftp/src/requests/set_stat.rs
use std::borrow::Cow; use serde::{Deserialize, Serialize}; use crate::{AsSftpPath, SftpPath, fs::Attrs}; #[derive(Debug, Deserialize, Serialize)] pub struct SetStat<'a> { pub id: u32, pub path: SftpPath<'a>, pub attrs: Attrs, } impl<'a> SetStat<'a> { pub fn new<P>(path: P, attrs: Attrs) -> Self where P: AsSftpPath<'a>, { Self { id: 0, path: path.as_sftp_path(), attrs } } pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.path.len() + self.attrs.len() } } #[derive(Debug, Deserialize, Serialize)] pub struct FSetStat<'a> { pub id: u32, pub handle: Cow<'a, str>, pub attrs: Cow<'a, Attrs>, } impl<'a> FSetStat<'a> { pub fn new(handle: impl Into<Cow<'a, str>>, attrs: &'a Attrs) -> Self { Self { id: 0, handle: handle.into(), attrs: Cow::Borrowed(attrs) } } pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.handle.len() + self.attrs.len() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/requests/mod.rs
yazi-sftp/src/requests/mod.rs
mod close; mod extended; mod fstat; mod init; mod lstat; mod mkdir; mod open; mod open_dir; mod read; mod read_dir; mod readlink; mod realpath; mod remove; mod rename; mod rmdir; mod set_stat; mod stat; mod symlink; mod write; pub use close::*; pub use extended::*; pub use fstat::*; pub use init::*; pub use lstat::*; pub use mkdir::*; pub use open::*; pub use open_dir::*; pub use read::*; pub use read_dir::*; pub use readlink::*; pub use realpath::*; pub use remove::*; pub use rename::*; pub use rmdir::*; pub use set_stat::*; pub use stat::*; pub use symlink::*; pub use write::*;
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/requests/fstat.rs
yazi-sftp/src/requests/fstat.rs
use std::borrow::Cow; use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] pub struct Fstat<'a> { pub id: u32, pub handle: Cow<'a, str>, } impl<'a> Fstat<'a> { pub fn new(handle: impl Into<Cow<'a, str>>) -> Self { Self { id: 0, handle: handle.into() } } pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.handle.len() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/requests/init.rs
yazi-sftp/src/requests/init.rs
use std::collections::HashMap; use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] pub struct Init { pub version: u32, pub extensions: HashMap<String, String>, } impl Init { pub fn new(extensions: HashMap<String, String>) -> Self { Self { version: 3, extensions } } pub fn len(&self) -> usize { size_of_val(&self.version) + self.extensions.iter().map(|(k, v)| 4 + k.len() + 4 + v.len()).sum::<usize>() } } impl Default for Init { fn default() -> Self { Self::new(HashMap::new()) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/requests/readlink.rs
yazi-sftp/src/requests/readlink.rs
use serde::{Deserialize, Serialize}; use crate::{AsSftpPath, SftpPath}; #[derive(Debug, Deserialize, Serialize)] pub struct Readlink<'a> { pub id: u32, pub path: SftpPath<'a>, } impl<'a> Readlink<'a> { pub fn new<P>(path: P) -> Self where P: AsSftpPath<'a>, { Self { id: 0, path: path.as_sftp_path() } } pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.path.len() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/requests/read.rs
yazi-sftp/src/requests/read.rs
use std::borrow::Cow; use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] pub struct Read<'a> { pub id: u32, pub handle: Cow<'a, str>, pub offset: u64, pub len: u32, } impl<'a> Read<'a> { pub fn new<H>(handle: H, offset: u64, len: u32) -> Self where H: Into<Cow<'a, str>>, { Self { id: 0, handle: handle.into(), offset, len } } pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.handle.len() + size_of_val(&self.offset) + size_of_val(&self.len) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/requests/open_dir.rs
yazi-sftp/src/requests/open_dir.rs
use serde::{Deserialize, Serialize}; use crate::{AsSftpPath, SftpPath}; #[derive(Debug, Deserialize, Serialize)] pub struct OpenDir<'a> { pub id: u32, pub path: SftpPath<'a>, } impl<'a> OpenDir<'a> { pub fn new<P>(path: P) -> Self where P: AsSftpPath<'a>, { Self { id: 0, path: path.as_sftp_path() } } pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.path.len() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/requests/read_dir.rs
yazi-sftp/src/requests/read_dir.rs
use std::borrow::Cow; use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] pub struct ReadDir<'a> { pub id: u32, pub handle: Cow<'a, str>, } impl<'a> ReadDir<'a> { pub fn new(handle: &'a str) -> Self { Self { id: 0, handle: handle.into() } } pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.handle.len() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/requests/remove.rs
yazi-sftp/src/requests/remove.rs
use serde::{Deserialize, Serialize}; use crate::{AsSftpPath, SftpPath}; #[derive(Debug, Deserialize, Serialize)] pub struct Remove<'a> { pub id: u32, pub path: SftpPath<'a>, } impl<'a> Remove<'a> { pub fn new<P>(path: P) -> Self where P: AsSftpPath<'a>, { Self { id: 0, path: path.as_sftp_path() } } pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.path.len() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/requests/extended.rs
yazi-sftp/src/requests/extended.rs
use std::{borrow::Cow, fmt::Debug}; use serde::{Deserialize, Serialize}; use crate::{AsSftpPath, SftpPath}; #[derive(Debug, Deserialize, Serialize)] pub struct Extended<'a, D> { pub id: u32, pub request: Cow<'a, str>, pub data: D, } impl<D: ExtendedData> Extended<'_, D> { pub fn new<'a, R>(request: R, data: D) -> Extended<'a, D> where R: Into<Cow<'a, str>>, { Extended { id: 0, request: request.into(), data } } pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.request.len() + self.data.len() } } // --- Data pub trait ExtendedData: Debug + Serialize + for<'de> Deserialize<'de> { fn len(&self) -> usize; } // --- POSIX Rename #[derive(Debug, Deserialize, Serialize)] pub struct ExtendedRename<'a> { pub from: SftpPath<'a>, pub to: SftpPath<'a>, } impl<'a> ExtendedRename<'a> { pub fn new<F, T>(from: F, to: T) -> Self where F: AsSftpPath<'a>, T: AsSftpPath<'a>, { Self { from: from.as_sftp_path(), to: to.as_sftp_path() } } } impl ExtendedData for ExtendedRename<'_> { fn len(&self) -> usize { 4 + self.from.len() + 4 + self.to.len() } } // --- Fsync #[derive(Debug, Deserialize, Serialize)] pub struct ExtendedFsync<'a> { pub handle: Cow<'a, str>, } impl<'a> ExtendedFsync<'a> { pub fn new(handle: impl Into<Cow<'a, str>>) -> Self { Self { handle: handle.into() } } } impl ExtendedData for ExtendedFsync<'_> { fn len(&self) -> usize { 4 + self.handle.len() } } // --- Hardlink #[derive(Debug, Deserialize, Serialize)] pub struct ExtendedHardlink<'a> { pub original: SftpPath<'a>, pub link: SftpPath<'a>, } impl<'a> ExtendedHardlink<'a> { pub fn new<O, L>(original: O, link: L) -> Self where O: AsSftpPath<'a>, L: AsSftpPath<'a>, { Self { original: original.as_sftp_path(), link: link.as_sftp_path() } } } impl ExtendedData for ExtendedHardlink<'_> { fn len(&self) -> usize { 4 + self.original.len() + 4 + self.link.len() } } // --- Limits #[derive(Debug, Deserialize, Serialize)] pub struct ExtendedLimits; impl ExtendedData for ExtendedLimits { fn len(&self) -> usize { 0 } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/requests/close.rs
yazi-sftp/src/requests/close.rs
use std::borrow::Cow; use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] pub struct Close<'a> { pub id: u32, pub handle: Cow<'a, str>, } impl<'a> Close<'a> { pub fn new(handle: impl Into<Cow<'a, str>>) -> Self { Self { id: 0, handle: handle.into() } } pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.handle.len() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/requests/lstat.rs
yazi-sftp/src/requests/lstat.rs
use serde::{Deserialize, Serialize}; use crate::{AsSftpPath, SftpPath}; #[derive(Debug, Deserialize, Serialize)] pub struct Lstat<'a> { pub id: u32, pub path: SftpPath<'a>, } impl Lstat<'_> { pub fn new<'a, P>(path: P) -> Lstat<'a> where P: AsSftpPath<'a>, { Lstat { id: 0, path: path.as_sftp_path() } } pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.path.len() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/fs/attrs.rs
yazi-sftp/src/fs/attrs.rs
use std::{collections::HashMap, fmt}; use serde::{Deserialize, Deserializer, Serialize, de::Visitor, ser::SerializeStruct}; #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct Attrs { pub size: Option<u64>, pub uid: Option<u32>, pub gid: Option<u32>, pub perm: Option<u32>, pub atime: Option<u32>, pub mtime: Option<u32>, pub extended: HashMap<String, String>, } impl Attrs { pub fn is_empty(&self) -> bool { *self == Self::default() } pub fn len(&self) -> usize { let mut len = 4; if let Some(size) = self.size { len += size_of_val(&size); } if self.uid.is_some() || self.gid.is_some() { len += 4 + 4; } if let Some(perm) = self.perm { len += size_of_val(&perm); } if self.atime.is_some() || self.mtime.is_some() { len += 4 + 4; } if !self.extended.is_empty() { len += 4 + self.extended.iter().map(|(k, v)| 4 + k.len() + 4 + v.len()).sum::<usize>(); } len } } impl Serialize for Attrs { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { let mut flags: u32 = 0; let mut len = 1; if self.size.is_some() { flags |= 0x1; len += 1; } if self.uid.is_some() || self.gid.is_some() { flags |= 0x2; len += 2; } if self.perm.is_some() { flags |= 0x4; len += 1; } if self.atime.is_some() || self.mtime.is_some() { flags |= 0x8; len += 2; } if !self.extended.is_empty() { flags |= 0x80000000; len += 1 + self.extended.len() * 2; } let mut seq = serializer.serialize_struct("Attrs", len)?; seq.serialize_field("flags", &flags)?; if let Some(size) = self.size { seq.serialize_field("size", &size)?; } if self.uid.is_some() || self.gid.is_some() { seq.serialize_field("uid", &self.uid.unwrap_or(0))?; seq.serialize_field("gid", &self.gid.unwrap_or(0))?; } if let Some(perm) = self.perm { seq.serialize_field("perm", &perm)?; } if self.atime.is_some() || self.mtime.is_some() { seq.serialize_field("atime", &self.atime.unwrap_or(0))?; seq.serialize_field("mtime", &self.mtime.unwrap_or(0))?; } if !self.extended.is_empty() { let count = self.extended.len() as u32; seq.serialize_field("extended_count", &count)?; for (k, v) in self.extended.iter().take(count as usize) { seq.serialize_field("extended_key", k)?; seq.serialize_field("extended_value", v)?; } } seq.end() } } impl<'de> Deserialize<'de> for Attrs { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct AttrsVisitor; impl<'de> Visitor<'de> for AttrsVisitor { type Value = Attrs; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("attributes") } fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: serde::de::SeqAccess<'de>, { let b = seq.next_element::<u32>()?.unwrap_or(0); let mut attrs = Attrs::default(); if b & 0x1 != 0 { attrs.size = seq.next_element()?; } if b & 0x2 != 0 { attrs.uid = seq.next_element()?; attrs.gid = seq.next_element()?; } if b & 0x4 != 0 { attrs.perm = seq.next_element()?; } if b & 0x8 != 0 { attrs.atime = seq.next_element()?; attrs.mtime = seq.next_element()?; } if b & 0x80000000 != 0 { let count: u32 = seq.next_element()?.unwrap_or(0); for _ in 0..count { attrs.extended.insert( seq.next_element()?.unwrap_or_default(), seq.next_element()?.unwrap_or_default(), ); } } Ok(attrs) } } deserializer.deserialize_any(AttrsVisitor) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/fs/flags.rs
yazi-sftp/src/fs/flags.rs
use bitflags::bitflags; use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)] pub struct Flags(u32); bitflags! { impl Flags: u32 { const READ = 0b000001; const WRITE = 0b000010; const APPEND = 0b000100; const CREATE = 0b001000; const TRUNCATE = 0b010000; const EXCLUDE = 0b100000; } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/fs/file.rs
yazi-sftp/src/fs/file.rs
use std::{io::{self, SeekFrom}, pin::Pin, sync::Arc, task::{Context, Poll, ready}, time::Duration}; use tokio::{io::{AsyncRead, AsyncSeek, AsyncWrite, ReadBuf}, time::{Timeout, timeout}}; use crate::{Error, Operator, Packet, Receiver, Session, fs::Attrs, requests}; pub struct File { session: Arc<Session>, handle: String, cursor: u64, closed: bool, close_rx: Option<Timeout<Receiver>>, read_rx: Option<Receiver>, seek_rx: Option<SeekState>, write_rx: Option<(Receiver, usize)>, flush_rx: Option<Timeout<Receiver>>, } enum SeekState { NonBlocking(u64), Blocking(i64, Timeout<Receiver>), } impl Unpin for File {} impl Drop for File { fn drop(&mut self) { if !self.closed { Operator::from(&self.session).close(&self.handle).ok(); } } } impl File { pub(crate) fn new(session: &Arc<Session>, handle: impl Into<String>) -> Self { Self { session: session.clone(), handle: handle.into(), closed: false, cursor: 0, close_rx: None, read_rx: None, seek_rx: None, write_rx: None, flush_rx: None, } } pub async fn fstat(&self) -> Result<Attrs, Error> { Operator::from(&self.session).fstat(&self.handle).await } pub async fn fsetstat(&self, attrs: &Attrs) -> Result<(), Error> { Operator::from(&self.session).fsetstat(&self.handle, attrs).await } } impl AsyncRead for File { fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>> { let me = unsafe { self.get_unchecked_mut() }; if me.read_rx.is_none() { let max = buf.remaining().min(261120) as u32; me.read_rx = Some(Operator::from(&me.session).read(&me.handle, me.cursor, max)?); } let result = ready!(Pin::new(me.read_rx.as_mut().unwrap()).poll(cx)); me.read_rx = None; Poll::Ready(match result { Ok(Packet::Data(data)) => { let len = buf.remaining().min(data.data.len()); me.cursor += len as u64; buf.put_slice(&data.data[..len]); Ok(()) } Ok(Packet::Status(status)) if status.is_eof() => Ok(()), Ok(Packet::Status(status)) => Err(Error::Status(status).into()), Ok(_) => Err(Error::Packet("not a Data or Status").into()), Err(e) => Err(Error::from(e).into()), }) } } impl AsyncSeek for File { fn start_seek(mut self: Pin<&mut Self>, position: io::SeekFrom) -> io::Result<()> { if self.seek_rx.is_some() { return Err(io::Error::other( "other file operation is pending, call poll_complete before start_seek", )); } self.seek_rx = Some(match position { SeekFrom::Start(n) => SeekState::NonBlocking(n), SeekFrom::Current(n) => self .cursor .checked_add_signed(n) .map(SeekState::NonBlocking) .ok_or_else(|| io::Error::other("seeking to a negative or overflowed position"))?, SeekFrom::End(n) => SeekState::Blocking( n, timeout( Duration::from_secs(45), self.session.send_sync(requests::Fstat::new(&self.handle))?, ), ), }); Ok(()) } fn poll_complete(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<u64>> { let me = unsafe { self.get_unchecked_mut() }; let Some(state) = &mut me.seek_rx else { return Poll::Ready(Ok(me.cursor)); }; fn imp(cx: &mut Context<'_>, state: &mut SeekState) -> Poll<io::Result<u64>> { use Poll::Ready; let (n, rx) = match state { SeekState::NonBlocking(n) => return Ready(Ok(*n)), SeekState::Blocking(n, rx) => (n, rx), }; let Ok(result) = ready!(unsafe { Pin::new_unchecked(rx) }.poll(cx)) else { return Ready(Err(Error::Timeout.into())); }; let packet = match result { Ok(Packet::Attrs(packet)) => packet, Ok(_) => return Ready(Err(Error::Packet("not an Attrs").into())), Err(e) => return Ready(Err(Error::from(e).into())), }; let Some(size) = packet.attrs.size else { return Ready(Err(io::Error::other("could not get file size for seeking from end"))); }; Ready( size .checked_add_signed(*n) .ok_or_else(|| io::Error::other("seeking to a negative or overflowed position")), ) } let result = ready!(imp(cx, state)); if let Ok(n) = result { me.cursor = n; } me.seek_rx = None; Poll::Ready(result) } } impl AsyncWrite for File { fn poll_write( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<Result<usize, io::Error>> { let me = unsafe { self.get_unchecked_mut() }; let (rx, len) = match &mut me.write_rx { Some((rx, len)) => (rx, *len), None => { let max = buf.len().min(261120); let rx = Operator::from(&me.session).write(&me.handle, me.cursor, &buf[..max])?; (&mut me.write_rx.get_or_insert((rx, max)).0, max) } }; let result = ready!(Pin::new(rx).poll(cx)); me.write_rx = None; Poll::Ready(match result { Ok(Packet::Status(status)) if status.is_ok() => { me.cursor += len as u64; Ok(len) } Ok(Packet::Status(status)) => Err(Error::Status(status).into()), Ok(_) => Err(Error::Packet("not a Status").into()), Err(e) => Err(Error::from(e).into()), }) } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> { let me = unsafe { self.get_unchecked_mut() }; if me.flush_rx.is_none() { match Operator::from(&me.session).fsync(&me.handle) { Ok(rx) => me.flush_rx = Some(timeout(Duration::from_secs(45), rx)), Err(Error::Unsupported) => return Poll::Ready(Ok(())), Err(e) => Err(e)?, } } let rx = unsafe { Pin::new_unchecked(me.flush_rx.as_mut().unwrap()) }; let result = ready!(rx.poll(cx)); me.flush_rx = None; let Ok(result) = result else { return Poll::Ready(Err(Error::Timeout.into())); }; Poll::Ready(match result { Ok(Packet::Status(status)) if status.is_ok() => Ok(()), Ok(Packet::Status(status)) => Err(Error::Status(status).into()), Ok(_) => Err(Error::Packet("not a Status").into()), Err(e) => Err(Error::from(e).into()), }) } fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> { let me = unsafe { self.get_unchecked_mut() }; if me.close_rx.is_none() { me.close_rx = Some(timeout(Duration::from_secs(10), Operator::from(&me.session).close(&me.handle)?)); } let rx = unsafe { Pin::new_unchecked(me.close_rx.as_mut().unwrap()) }; let result = ready!(rx.poll(cx)); me.close_rx = None; let Ok(result) = result else { return Poll::Ready(Err(Error::Timeout.into())); }; Poll::Ready(match result { Ok(Packet::Status(status)) if status.is_ok() => { me.closed = true; Ok(()) } Ok(Packet::Status(status)) => Err(Error::Status(status).into()), Ok(_) => Err(Error::Packet("not a Status").into()), Err(e) => Err(Error::from(e).into()), }) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/fs/dir_entry.rs
yazi-sftp/src/fs/dir_entry.rs
use std::sync::Arc; use typed_path::UnixPathBuf; use crate::fs::Attrs; pub struct DirEntry { pub(super) dir: Arc<typed_path::UnixPathBuf>, pub(super) name: Vec<u8>, pub(super) long_name: Vec<u8>, pub(super) attrs: Attrs, } impl DirEntry { #[must_use] pub fn path(&self) -> UnixPathBuf { self.dir.join(&self.name) } pub fn name(&self) -> &[u8] { &self.name } pub fn long_name(&self) -> &[u8] { &self.long_name } pub fn attrs(&self) -> &Attrs { &self.attrs } pub fn nlink(&self) -> Option<u64> { str::from_utf8(self.long_name_field(1)?).ok()?.parse().ok() } pub fn user(&self) -> Option<&[u8]> { self.long_name_field(2) } pub fn group(&self) -> Option<&[u8]> { self.long_name_field(3) } fn long_name_field(&self, n: usize) -> Option<&[u8]> { self.long_name.split(|b| b.is_ascii_whitespace()).filter(|s| !s.is_empty()).nth(n) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/fs/mod.rs
yazi-sftp/src/fs/mod.rs
mod attrs; mod dir_entry; mod file; mod flags; mod read_dir; pub use attrs::*; pub use dir_entry::*; pub use file::*; pub use flags::*; pub use read_dir::*;
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/fs/read_dir.rs
yazi-sftp/src/fs/read_dir.rs
use std::{mem, sync::Arc, time::Duration}; use crate::{Error, Operator, Session, SftpPath, fs::DirEntry, requests, responses}; pub struct ReadDir { session: Arc<Session>, dir: Arc<typed_path::UnixPathBuf>, handle: String, name: responses::Name<'static>, cursor: usize, done: bool, } impl Drop for ReadDir { fn drop(&mut self) { Operator::from(&self.session).close(&self.handle).ok(); } } impl ReadDir { pub(crate) fn new(session: &Arc<Session>, dir: SftpPath, handle: String) -> Self { Self { session: session.clone(), dir: Arc::new(dir.into_owned()), handle, name: Default::default(), cursor: 0, done: false, } } pub async fn next(&mut self) -> Result<Option<DirEntry>, Error> { loop { self.fetch().await?; let Some(item) = self.name.items.get_mut(self.cursor).map(mem::take) else { return Ok(None); }; self.cursor += 1; if &*item.name != b"." && &*item.name != b".." { return Ok(Some(DirEntry { dir: self.dir.clone(), name: item.name.into_owned(), long_name: item.long_name.into_owned(), attrs: item.attrs, })); } } } async fn fetch(&mut self) -> Result<(), Error> { if self.cursor < self.name.items.len() || self.done { return Ok(()); } let result = self .session .send_with_timeout(requests::ReadDir::new(&self.handle), Duration::from_mins(45)) .await; self.name = match result { Ok(resp) => resp, Err(Error::Status(status)) if status.is_eof() => { self.done = true; return Ok(()); } Err(e) => return Err(e), }; self.cursor = 0; Ok(()) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/responses/attrs.rs
yazi-sftp/src/responses/attrs.rs
use serde::{Deserialize, Serialize}; use crate::fs; #[derive(Debug, Deserialize, Serialize)] pub struct Attrs { pub id: u32, pub attrs: fs::Attrs, } impl Attrs { pub fn len(&self) -> usize { size_of_val(&self.id) + self.attrs.len() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/responses/version.rs
yazi-sftp/src/responses/version.rs
use std::collections::HashMap; use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] pub struct Version { pub version: u32, pub extensions: HashMap<String, String>, } impl Version { pub fn len(&self) -> usize { size_of_val(&self.version) + self.extensions.iter().map(|(k, v)| 4 + k.len() + 4 + v.len()).sum::<usize>() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/responses/status.rs
yazi-sftp/src/responses/status.rs
use serde::{Deserialize, Serialize}; use crate::Error; #[derive(Debug, Deserialize, Serialize)] pub struct Status { pub id: u32, pub code: StatusCode, pub message: String, pub language: String, } impl From<Status> for Result<(), Error> { fn from(status: Status) -> Self { if status.is_ok() { Ok(()) } else { Err(Error::Status(status)) } } } impl Status { pub fn len(&self) -> usize { size_of_val(&self.id) + size_of_val(&(self.code as u32)) + 4 + self.message.len() + 4 + self.language.len() } pub fn is_ok(&self) -> bool { self.code == StatusCode::Ok } pub fn is_eof(&self) -> bool { self.code == StatusCode::Eof } pub fn is_failure(&self) -> bool { self.code == StatusCode::Failure } pub(crate) fn connection_lost(id: u32) -> Self { Self { id, code: StatusCode::ConnectionLost, message: "connection lost".to_owned(), language: "en".to_owned(), } } } #[derive(Debug, Clone, Copy, PartialEq, Deserialize, Serialize)] pub enum StatusCode { Ok = 0, Eof = 1, NoSuchFile = 2, PermissionDenied = 3, Failure = 4, BadMessage = 5, NoConnection = 6, ConnectionLost = 7, OpUnsupported = 8, InvalidHandle = 9, NoSuchPath = 10, FileAlreadyExists = 11, WriteProtect = 12, NoMedia = 13, }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/responses/mod.rs
yazi-sftp/src/responses/mod.rs
mod attrs; mod data; mod extended; mod handle; mod name; mod status; mod version; pub use attrs::*; pub use data::*; pub use extended::*; pub use handle::*; pub use name::*; pub use status::*; pub use version::*;
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/responses/name.rs
yazi-sftp/src/responses/name.rs
use std::borrow::Cow; use serde::{Deserialize, Serialize}; use crate::fs::Attrs; #[derive(Debug, Default, Deserialize, Serialize)] pub struct Name<'a> { pub id: u32, pub items: Vec<NameItem<'a>>, } #[derive(Debug, Default, Deserialize, Serialize)] pub struct NameItem<'a> { pub name: Cow<'a, [u8]>, pub long_name: Cow<'a, [u8]>, pub attrs: Attrs, } impl Name<'_> { pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.items.iter().map(|v| v.len()).sum::<usize>() } } impl NameItem<'_> { pub fn len(&self) -> usize { 4 + self.name.len() + 4 + self.long_name.len() + self.attrs.len() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/responses/data.rs
yazi-sftp/src/responses/data.rs
use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] pub struct Data { pub id: u32, pub data: Vec<u8>, } impl Data { pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.data.len() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/responses/extended.rs
yazi-sftp/src/responses/extended.rs
use std::{borrow::Cow, fmt, ops::Deref}; use serde::{Deserialize, Serialize, de::Visitor, ser::SerializeSeq}; use crate::Error; #[derive(Debug, Deserialize, Serialize)] pub struct Extended<'a> { pub id: u32, pub data: ExtendedData<'a>, } impl<'a> Extended<'a> { pub fn len(&self) -> usize { size_of_val(&self.id) + self.data.len() } } // --- Data #[derive(Debug)] pub struct ExtendedData<'a>(Cow<'a, [u8]>); impl Deref for ExtendedData<'_> { type Target = [u8]; fn deref(&self) -> &Self::Target { &self.0 } } impl Serialize for ExtendedData<'_> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { let mut seq = serializer.serialize_seq(None)?; for b in &*self.0 { seq.serialize_element(b)?; } seq.end() } } impl<'de> Deserialize<'de> for ExtendedData<'_> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { struct ExtendedDataVisitor; impl<'de> Visitor<'de> for ExtendedDataVisitor { type Value = Vec<u8>; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("extended data") } fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: serde::de::SeqAccess<'de>, { let mut bytes = Vec::with_capacity(seq.size_hint().unwrap_or(0)); while let Some(b) = seq.next_element()? { bytes.push(b); } Ok(bytes) } } deserializer.deserialize_any(ExtendedDataVisitor).map(Cow::Owned).map(ExtendedData) } } // --- Limits #[derive(Debug, Deserialize, Serialize)] pub struct ExtendedLimits { pub packet_len: u64, pub read_len: u64, pub write_len: u64, pub open_handles: u64, } impl TryFrom<Extended<'_>> for ExtendedLimits { type Error = Error; fn try_from(value: Extended<'_>) -> Result<Self, Self::Error> { crate::Deserializer::once(&value.data) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-sftp/src/responses/handle.rs
yazi-sftp/src/responses/handle.rs
use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] pub struct Handle { pub id: u32, pub handle: String, } impl Handle { pub fn len(&self) -> usize { size_of_val(&self.id) + 4 + self.handle.len() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-term/src/if.rs
yazi-term/src/if.rs
pub struct If<T: crossterm::Command>(pub bool, pub T); impl<T: crossterm::Command> crossterm::Command for If<T> { fn write_ansi(&self, f: &mut impl std::fmt::Write) -> std::fmt::Result { if self.0 { self.1.write_ansi(f) } else { Ok(()) } } #[cfg(windows)] fn execute_winapi(&self) -> std::io::Result<()> { if self.0 { self.1.execute_winapi() } else { Ok(()) } } #[cfg(windows)] fn is_ansi_code_supported(&self) -> bool { self.1.is_ansi_code_supported() } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-term/src/cursor.rs
yazi-term/src/cursor.rs
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; use crossterm::cursor::SetCursorStyle; static SHAPE: AtomicU8 = AtomicU8::new(0); static BLINK: AtomicBool = AtomicBool::new(false); pub struct RestoreCursor; impl RestoreCursor { pub fn store(resp: &str) { SHAPE.store( resp .split_once("\x1bP1$r") .and_then(|(_, s)| s.bytes().next()) .filter(|&b| matches!(b, b'0'..=b'6')) .map_or(u8::MAX, |b| b - b'0'), Ordering::Relaxed, ); BLINK.store(resp.contains("\x1b[?12;1$y"), Ordering::Relaxed); } } impl crossterm::Command for RestoreCursor { fn write_ansi(&self, f: &mut impl std::fmt::Write) -> std::fmt::Result { let (shape, shape_blink) = match SHAPE.load(Ordering::Relaxed) { u8::MAX => (0, None), n => (n.max(1).div_ceil(2), Some(n.max(1) & 1 == 1)), }; let blink = shape_blink.unwrap_or(BLINK.load(Ordering::Relaxed)); Ok(match shape { 2 if blink => SetCursorStyle::BlinkingUnderScore.write_ansi(f)?, 2 if !blink => SetCursorStyle::SteadyUnderScore.write_ansi(f)?, 3 if blink => SetCursorStyle::BlinkingBar.write_ansi(f)?, 3 if !blink => SetCursorStyle::SteadyBar.write_ansi(f)?, _ if blink => SetCursorStyle::DefaultUserShape.write_ansi(f)?, _ if !blink => SetCursorStyle::SteadyBlock.write_ansi(f)?, _ => unreachable!(), }) } #[cfg(windows)] fn execute_winapi(&self) -> std::io::Result<()> { Ok(()) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-term/src/lib.rs
yazi-term/src/lib.rs
yazi_macro::mod_pub!(tty); yazi_macro::mod_flat!(background cursor r#if); pub fn init() { tty::init(); }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-term/src/background.rs
yazi-term/src/background.rs
pub struct SetBackground(pub bool, pub String); impl crossterm::Command for SetBackground { fn write_ansi(&self, f: &mut impl std::fmt::Write) -> std::fmt::Result { if self.1.is_empty() { Ok(()) } else if self.0 { write!(f, "\x1b]11;{}\x1b\\", self.1) } else { write!(f, "\x1b]111\x1b\\") } } #[cfg(windows)] fn execute_winapi(&self) -> std::io::Result<()> { Ok(()) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-term/src/tty/tty.rs
yazi-term/src/tty/tty.rs
use std::{io::{BufWriter, Error, ErrorKind, Read, Write}, time::{Duration, Instant}}; use parking_lot::{Mutex, MutexGuard}; use super::Handle; pub struct Tty { stdin: Mutex<Handle>, stdout: Mutex<BufWriter<Handle>>, } impl Default for Tty { fn default() -> Self { Self { stdin: Mutex::new(Handle::new(false)), stdout: Mutex::new(BufWriter::new(Handle::new(true))), } } } impl Tty { pub const fn reader(&self) -> TtyReader<'_> { TtyReader(&self.stdin) } pub const fn writer(&self) -> TtyWriter<'_> { TtyWriter(&self.stdout) } pub fn lockin(&self) -> MutexGuard<'_, Handle> { self.stdin.lock() } pub fn lockout(&self) -> MutexGuard<'_, BufWriter<Handle>> { self.stdout.lock() } pub fn read_until<P>(&self, timeout: Duration, predicate: P) -> (Vec<u8>, std::io::Result<()>) where P: Fn(u8, &[u8]) -> bool, { let mut buf: Vec<u8> = Vec::with_capacity(200); let now = Instant::now(); let mut read = || { let mut stdin = self.stdin.lock(); loop { if now.elapsed() > timeout { return Err(Error::from(ErrorKind::TimedOut)); } else if !stdin.poll(Duration::from_millis(30))? { continue; } let b = stdin.read_u8()?; buf.push(b); if predicate(b, &buf) { break; } } Ok(()) }; let result = read(); (buf, result) } } // --- Reader pub struct TtyReader<'a>(&'a Mutex<Handle>); impl Read for TtyReader<'_> { fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { self.0.lock().read(buf) } } // --- Writer pub struct TtyWriter<'a>(&'a Mutex<BufWriter<Handle>>); impl std::io::Write for TtyWriter<'_> { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { self.0.lock().write(buf) } fn flush(&mut self) -> std::io::Result<()> { self.0.lock().flush() } } impl std::fmt::Write for TtyWriter<'_> { fn write_str(&mut self, s: &str) -> std::fmt::Result { self.0.lock().write_all(s.as_bytes()).map_err(|_| std::fmt::Error) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-term/src/tty/windows.rs
yazi-term/src/tty/windows.rs
// Copied from https://github.com/rust-lang/rust/blob/master/library/std/src/sys/pal/windows/stdio.rs use std::{mem::MaybeUninit, os::windows::io::RawHandle, str}; use windows_sys::Win32::{Globalization::{CP_UTF8, MB_ERR_INVALID_CHARS, MultiByteToWideChar}, System::Console::WriteConsoleW}; use yazi_shared::{floor_char_boundary, utf8_char_width}; // Apparently Windows doesn't handle large reads on stdin or writes to // stdout/stderr well (see #13304 for details). // // From MSDN (2011): "The storage for this buffer is allocated from a shared // heap for the process that is 64 KB in size. The maximum size of the buffer // will depend on heap usage." // // We choose the cap at 8 KiB because libuv does the same, and it seems to be // acceptable so far. const MAX_BUFFER_SIZE: usize = 8192; #[derive(Default)] pub(super) struct IncompleteUtf8 { bytes: [u8; 4], len: u8, } pub(super) fn write_console_utf16( data: &[u8], incomplete_utf8: &mut IncompleteUtf8, handle: RawHandle, ) -> std::io::Result<usize> { if incomplete_utf8.len > 0 { assert!(incomplete_utf8.len < 4, "Unexpected number of bytes for incomplete UTF-8 codepoint."); if data[0] >> 6 != 0b10 { // not a continuation byte - reject incomplete_utf8.len = 0; return Err(std::io::Error::new( std::io::ErrorKind::InvalidData, "Windows stdio in console mode does not support writing non-UTF-8 byte sequences", )); } incomplete_utf8.bytes[incomplete_utf8.len as usize] = data[0]; incomplete_utf8.len += 1; let char_width = utf8_char_width(incomplete_utf8.bytes[0]); if (incomplete_utf8.len as usize) < char_width { // more bytes needed return Ok(1); } let s = str::from_utf8(&incomplete_utf8.bytes[0..incomplete_utf8.len as usize]); incomplete_utf8.len = 0; match s { Ok(s) => { assert_eq!(char_width, s.len()); let written = write_valid_utf8_to_console(handle, s)?; assert_eq!(written, s.len()); // guaranteed by write_valid_utf8_to_console() for single codepoint writes return Ok(1); } Err(_) => { return Err(std::io::Error::new( std::io::ErrorKind::InvalidData, "Windows stdio in console mode does not support writing non-UTF-8 byte sequences", )); } } } // As the console is meant for presenting text, we assume bytes of `data` are // encoded as UTF-8, which needs to be encoded as UTF-16. // // If the data is not valid UTF-8 we write out as many bytes as are valid. // If the first byte is invalid it is either first byte of a multi-byte sequence // but the provided byte slice is too short or it is the first byte of an // invalid multi-byte sequence. let len = std::cmp::min(data.len(), MAX_BUFFER_SIZE / 2); let utf8 = match str::from_utf8(&data[..len]) { Ok(s) => s, Err(ref e) if e.valid_up_to() == 0 => { let first_byte_char_width = utf8_char_width(data[0]); if first_byte_char_width > 1 && data.len() < first_byte_char_width { incomplete_utf8.bytes[0] = data[0]; incomplete_utf8.len = 1; return Ok(1); } else { return Err(std::io::Error::new( std::io::ErrorKind::InvalidData, "Windows stdio in console mode does not support writing non-UTF-8 byte sequences", )); } } Err(e) => str::from_utf8(&data[..e.valid_up_to()]).unwrap(), }; write_valid_utf8_to_console(handle, utf8) } fn write_valid_utf8_to_console(handle: RawHandle, utf8: &str) -> std::io::Result<usize> { debug_assert!(!utf8.is_empty()); let mut utf16 = [MaybeUninit::<u16>::uninit(); MAX_BUFFER_SIZE / 2]; let utf8 = &utf8[..floor_char_boundary(utf8, utf16.len())]; let utf16: &[u16] = unsafe { // Note that this theoretically checks validity twice in the (most common) case // where the underlying byte sequence is valid utf-8 (given the check in // `write()`). let result = MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, utf8.as_ptr(), utf8.len() as i32, utf16.as_mut_ptr() as *mut _, utf16.len() as i32, ); assert!(result != 0, "Unexpected error in MultiByteToWideChar"); // Safety: MultiByteToWideChar initializes `result` values. &*(&utf16[..result as usize] as *const [MaybeUninit<u16>] as *const [u16]) }; let mut written = write_u16s(handle, utf16)?; // Figure out how many bytes of as UTF-8 were written away as UTF-16. if written == utf16.len() { Ok(utf8.len()) } else { // Make sure we didn't end up writing only half of a surrogate pair (even though // the chance is tiny). Because it is not possible for user code to re-slice // `data` in such a way that a missing surrogate can be produced (and also // because of the UTF-8 validation above), write the missing surrogate out // now. Buffering it would mean we have to lie about the number of bytes // written. let first_code_unit_remaining = utf16[written]; if matches!(first_code_unit_remaining, 0xdcee..=0xdfff) { // low surrogate // We just hope this works, and give up otherwise let _ = write_u16s(handle, &utf16[written..written + 1]); written += 1; } // Calculate the number of bytes of `utf8` that were actually written. let mut count = 0; for ch in utf16[..written].iter() { count += match ch { 0x0000..=0x007f => 1, 0x0080..=0x07ff => 2, 0xdcee..=0xdfff => 1, // Low surrogate. We already counted 3 bytes for the other. _ => 3, }; } debug_assert!(String::from_utf16(&utf16[..written]).unwrap() == utf8[..count]); Ok(count) } } fn write_u16s(handle: RawHandle, data: &[u16]) -> std::io::Result<usize> { debug_assert!(data.len() < u32::MAX as usize); let mut written = 0; let result = unsafe { WriteConsoleW(handle, data.as_ptr(), data.len() as u32, &mut written, std::ptr::null_mut()) }; if result == 0 { Err(std::io::Error::last_os_error()) } else { Ok(written as usize) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-term/src/tty/mod.rs
yazi-term/src/tty/mod.rs
yazi_macro::mod_flat!(handle tty); #[cfg(windows)] yazi_macro::mod_flat!(windows); pub static TTY: yazi_shared::RoCell<Tty> = yazi_shared::RoCell::new(); pub(super) fn init() { TTY.with(<_>::default); }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-term/src/tty/handle.rs
yazi-term/src/tty/handle.rs
use std::{io::{Error, ErrorKind, Read, Write}, time::Duration}; use tracing::error; pub struct Handle { #[cfg(unix)] inner: std::os::fd::RawFd, #[cfg(windows)] inner: std::os::windows::io::RawHandle, close: bool, #[cfg(windows)] out_utf8: bool, #[cfg(windows)] incomplete_utf8: super::IncompleteUtf8, } impl Drop for Handle { fn drop(&mut self) { #[cfg(unix)] if self.close { unsafe { libc::close(self.inner) }; } #[cfg(windows)] if self.close { unsafe { windows_sys::Win32::Foundation::CloseHandle(self.inner) }; } } } impl Read for Handle { fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { #[cfg(unix)] { use std::os::{fd::IntoRawFd, unix::io::FromRawFd}; let mut f = unsafe { std::fs::File::from_raw_fd(self.inner) }; let result = f.read(buf); _ = f.into_raw_fd(); result } #[cfg(windows)] { use std::os::windows::io::{FromRawHandle, IntoRawHandle}; let mut f = unsafe { std::fs::File::from_raw_handle(self.inner) }; let result = f.read(buf); _ = f.into_raw_handle(); result } } } impl Write for Handle { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { #[cfg(unix)] { use std::os::{fd::IntoRawFd, unix::io::FromRawFd}; let mut f = unsafe { std::fs::File::from_raw_fd(self.inner) }; let result = f.write(buf); _ = f.into_raw_fd(); result } #[cfg(windows)] { use std::os::windows::io::{FromRawHandle, IntoRawHandle}; if self.out_utf8 { let mut f = unsafe { std::fs::File::from_raw_handle(self.inner) }; let result = f.write(buf); _ = f.into_raw_handle(); result } else { super::write_console_utf16(buf, &mut self.incomplete_utf8, self.inner) } } } fn flush(&mut self) -> std::io::Result<()> { Ok(()) } } #[cfg(unix)] impl Handle { pub(super) fn new(out: bool) -> Self { use std::{fs::OpenOptions, os::fd::IntoRawFd}; use libc::{STDIN_FILENO, STDOUT_FILENO}; let resort = Self { inner: if out { STDOUT_FILENO } else { STDIN_FILENO }, close: false }; if unsafe { libc::isatty(resort.inner) } == 1 { return resort; } match OpenOptions::new().read(!out).write(out).open("/dev/tty") { Ok(f) => Self { inner: f.into_raw_fd(), close: true }, Err(err) => { error!("Failed to open /dev/tty, falling back to stdin/stdout: {err}"); resort } } } pub(super) fn poll(&mut self, timeout: Duration) -> std::io::Result<bool> { let mut tv = libc::timeval { tv_sec: timeout.as_secs() as libc::time_t, tv_usec: timeout.subsec_micros() as libc::suseconds_t, }; let result = unsafe { let mut set: libc::fd_set = std::mem::zeroed(); libc::FD_ZERO(&mut set); libc::FD_SET(self.inner, &mut set); libc::select(self.inner + 1, &mut set, std::ptr::null_mut(), std::ptr::null_mut(), &mut tv) }; match result { -1 => Err(Error::last_os_error()), 0 => Ok(false), _ => Ok(true), } } pub(super) fn read_u8(&mut self) -> std::io::Result<u8> { let mut b = 0; match unsafe { libc::read(self.inner, &mut b as *mut _ as *mut _, 1) } { -1 => Err(Error::last_os_error()), 0 => Err(Error::from(ErrorKind::UnexpectedEof)), _ => Ok(b), } } } #[cfg(windows)] impl Handle { pub(super) fn new(out: bool) -> Self { use std::{io::{Error, stdin, stdout}, os::windows::io::AsRawHandle}; use windows_sys::Win32::{Foundation::{GENERIC_READ, GENERIC_WRITE, INVALID_HANDLE_VALUE}, Globalization::CP_UTF8, Storage::FileSystem::{CreateFileW, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING}, System::Console::GetConsoleOutputCP}; let name: Vec<u16> = if out { "CONOUT$\0" } else { "CONIN$\0" }.encode_utf16().collect(); let result = unsafe { CreateFileW( name.as_ptr(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, std::ptr::null_mut(), OPEN_EXISTING, 0, std::ptr::null_mut(), ) }; if result != INVALID_HANDLE_VALUE { return Self { inner: result, close: true, out_utf8: unsafe { GetConsoleOutputCP() } == CP_UTF8, incomplete_utf8: Default::default(), }; } error!( "Failed to open {}, falling back to stdin/stdout: {}", if out { "CONOUT$" } else { "CONIN$" }, Error::last_os_error() ); Self { inner: if out { stdout().as_raw_handle() } else { stdin().as_raw_handle() }, close: false, out_utf8: unsafe { GetConsoleOutputCP() } == CP_UTF8, incomplete_utf8: Default::default(), } } pub(super) fn poll(&mut self, timeout: Duration) -> std::io::Result<bool> { use windows_sys::Win32::{Foundation::{WAIT_FAILED, WAIT_OBJECT_0}, System::Threading::WaitForSingleObject}; let millis = timeout.as_millis(); match unsafe { WaitForSingleObject(self.inner, millis as u32) } { WAIT_FAILED => Err(Error::last_os_error()), WAIT_OBJECT_0 => Ok(true), _ => Ok(false), } } pub(super) fn read_u8(&mut self) -> std::io::Result<u8> { use windows_sys::Win32::Storage::FileSystem::ReadFile; let mut buf = 0; let mut bytes = 0; let success = unsafe { ReadFile(self.inner, &mut buf, 1, &mut bytes, std::ptr::null_mut()) }; if success == 0 { return Err(Error::last_os_error()); } else if bytes == 0 { return Err(Error::from(ErrorKind::UnexpectedEof)); } Ok(buf) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-packing/src/lib.rs
yazi-packing/src/lib.rs
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/lib.rs
yazi-actor/src/lib.rs
extern crate self as yazi_actor; yazi_macro::mod_pub!(cmp confirm core help input lives mgr pick spot tasks which); yazi_macro::mod_flat!(actor context);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/actor.rs
yazi-actor/src/actor.rs
use anyhow::Result; use yazi_dds::spark::SparkKind; use yazi_shared::data::Data; use crate::Ctx; pub trait Actor { type Options; const NAME: &str; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data>; fn hook(_cx: &Ctx, _opt: &Self::Options) -> Option<SparkKind> { None } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/context.rs
yazi-actor/src/context.rs
use std::ops::{Deref, DerefMut}; use anyhow::{Result, anyhow}; use yazi_core::{Core, mgr::Tabs, tab::{Folder, Tab}, tasks::Tasks}; use yazi_fs::File; use yazi_shared::{Id, Source, event::Cmd, url::UrlBuf}; pub struct Ctx<'a> { pub core: &'a mut Core, pub tab: usize, pub level: usize, pub source: Source, #[cfg(debug_assertions)] pub backtrace: Vec<&'static str>, } impl Deref for Ctx<'_> { type Target = Core; fn deref(&self) -> &Self::Target { self.core } } impl DerefMut for Ctx<'_> { fn deref_mut(&mut self) -> &mut Self::Target { self.core } } impl<'a> Ctx<'a> { #[inline] pub fn new(core: &'a mut Core, cmd: &Cmd) -> Result<Self> { let tab = if let Ok(id) = cmd.get::<Id>("tab") { core .mgr .tabs .iter() .position(|t| t.id == id) .ok_or_else(|| anyhow!("Tab with id {id} not found"))? } else { core.mgr.tabs.cursor }; Ok(Self { core, tab, level: 0, source: cmd.source, #[cfg(debug_assertions)] backtrace: vec![], }) } #[inline] pub fn renew<'b>(cx: &'a mut Ctx<'b>) -> Self { let tab = cx.core.mgr.tabs.cursor; Self { core: cx.core, tab, level: cx.level, source: cx.source, #[cfg(debug_assertions)] backtrace: vec![], } } #[inline] pub fn active(core: &'a mut Core) -> Self { let tab = core.mgr.tabs.cursor; Self { core, tab, level: 0, source: Source::Unknown, #[cfg(debug_assertions)] backtrace: vec![], } } } impl<'a> Ctx<'a> { #[inline] pub fn tabs(&self) -> &Tabs { &self.mgr.tabs } #[inline] pub fn tabs_mut(&mut self) -> &mut Tabs { &mut self.mgr.tabs } #[inline] pub fn tab(&self) -> &Tab { &self.tabs()[self.tab] } #[inline] pub fn tab_mut(&mut self) -> &mut Tab { &mut self.core.mgr.tabs[self.tab] } #[inline] pub fn cwd(&self) -> &UrlBuf { self.tab().cwd() } #[inline] pub fn parent(&self) -> Option<&Folder> { self.tab().parent.as_ref() } #[inline] pub fn parent_mut(&mut self) -> Option<&mut Folder> { self.tab_mut().parent.as_mut() } #[inline] pub fn current(&self) -> &Folder { &self.tab().current } #[inline] pub fn current_mut(&mut self) -> &mut Folder { &mut self.tab_mut().current } #[inline] pub fn hovered(&self) -> Option<&File> { self.tab().hovered() } #[inline] pub fn hovered_folder(&self) -> Option<&Folder> { self.tab().hovered_folder() } #[inline] pub fn hovered_folder_mut(&mut self) -> Option<&mut Folder> { self.tab_mut().hovered_folder_mut() } #[inline] pub fn tasks(&self) -> &Tasks { &self.tasks } #[inline] pub fn source(&self) -> Source { if self.level != 1 { Source::Ind } else { self.source } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/tasks/arrow.rs
yazi-actor/src/tasks/arrow.rs
use anyhow::Result; use yazi_core::tasks::Tasks; use yazi_macro::{render, succ}; use yazi_parser::ArrowOpt; use yazi_shared::data::Data; use crate::{Actor, Ctx}; pub struct Arrow; impl Actor for Arrow { type Options = ArrowOpt; const NAME: &str = "arrow"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { let tasks = &mut cx.tasks; let old = tasks.cursor; tasks.cursor = opt.step.add(tasks.cursor, tasks.snaps.len(), Tasks::limit()); succ!(render!(tasks.cursor != old)); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/tasks/open_shell_compat.rs
yazi-actor/src/tasks/open_shell_compat.rs
use anyhow::Result; use yazi_macro::succ; use yazi_parser::tasks::ProcessOpenOpt; use yazi_shared::data::Data; use crate::{Actor, Ctx}; pub struct OpenShellCompat; // TODO: remove impl Actor for OpenShellCompat { type Options = ProcessOpenOpt; const NAME: &str = "open_shell_compat"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { succ!(cx.tasks.open_shell_compat(opt)); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/tasks/cancel.rs
yazi-actor/src/tasks/cancel.rs
use anyhow::Result; use yazi_macro::{act, render, succ}; use yazi_parser::VoidOpt; use yazi_shared::data::Data; use crate::{Actor, Ctx}; pub struct Cancel; impl Actor for Cancel { type Options = VoidOpt; const NAME: &str = "cancel"; fn act(cx: &mut Ctx, _: Self::Options) -> Result<Data> { let tasks = &mut cx.tasks; let id = tasks.ongoing().lock().get_id(tasks.cursor); if id.map(|id| tasks.scheduler.cancel(id)) != Some(true) { succ!(); } tasks.snaps = tasks.paginate(); act!(tasks:arrow, cx)?; succ!(render!()); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/tasks/update_succeed.rs
yazi-actor/src/tasks/update_succeed.rs
use anyhow::Result; use yazi_macro::succ; use yazi_parser::tasks::UpdateSucceedOpt; use yazi_shared::data::Data; use crate::{Actor, Ctx}; pub struct UpdateSucceed; impl Actor for UpdateSucceed { type Options = UpdateSucceedOpt; const NAME: &str = "update_succeed"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { cx.mgr.watcher.report(opt.urls); succ!(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/tasks/process_open.rs
yazi-actor/src/tasks/process_open.rs
use anyhow::Result; use yazi_macro::succ; use yazi_parser::tasks::ProcessOpenOpt; use yazi_shared::data::Data; use crate::{Actor, Ctx}; pub struct ProcessOpen; impl Actor for ProcessOpen { type Options = ProcessOpenOpt; const NAME: &str = "process_open"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { succ!(cx.tasks.scheduler.process_open(opt)); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/tasks/mod.rs
yazi-actor/src/tasks/mod.rs
yazi_macro::mod_flat!(arrow cancel close open_shell_compat inspect process_open show update_succeed);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/tasks/show.rs
yazi-actor/src/tasks/show.rs
use anyhow::Result; use yazi_macro::{act, render, succ}; use yazi_parser::VoidOpt; use yazi_shared::data::Data; use crate::{Actor, Ctx}; pub struct Show; impl Actor for Show { type Options = VoidOpt; const NAME: &str = "show"; fn act(cx: &mut Ctx, _: Self::Options) -> Result<Data> { let tasks = &mut cx.tasks; if tasks.visible { succ!(); } tasks.visible = true; tasks.snaps = tasks.paginate(); act!(tasks:arrow, cx)?; succ!(render!()); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/tasks/close.rs
yazi-actor/src/tasks/close.rs
use anyhow::Result; use yazi_macro::{act, render, succ}; use yazi_parser::VoidOpt; use yazi_shared::data::Data; use crate::{Actor, Ctx}; pub struct Close; impl Actor for Close { type Options = VoidOpt; const NAME: &str = "close"; fn act(cx: &mut Ctx, _: Self::Options) -> Result<Data> { let tasks = &mut cx.tasks; if !tasks.visible { succ!(); } tasks.visible = false; tasks.snaps = Vec::new(); act!(tasks:arrow, cx)?; succ!(render!()); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/tasks/inspect.rs
yazi-actor/src/tasks/inspect.rs
use std::io::Write; use anyhow::Result; use crossterm::{execute, terminal::{disable_raw_mode, enable_raw_mode}}; use scopeguard::defer; use tokio::{io::{AsyncReadExt, stdin}, select, sync::mpsc, time}; use yazi_binding::Permit; use yazi_macro::succ; use yazi_parser::VoidOpt; use yazi_proxy::{AppProxy, HIDER}; use yazi_shared::{data::Data, terminal_clear}; use yazi_term::tty::TTY; use crate::{Actor, Ctx}; pub struct Inspect; impl Actor for Inspect { type Options = VoidOpt; const NAME: &str = "inspect"; fn act(cx: &mut Ctx, _: Self::Options) -> Result<Data> { let ongoing = cx.tasks.ongoing().clone(); let Some(id) = ongoing.lock().get_id(cx.tasks.cursor) else { succ!(); }; tokio::spawn(async move { let _permit = Permit::new(HIDER.acquire().await.unwrap(), AppProxy::resume()); let (tx, mut rx) = mpsc::unbounded_channel(); let buffered = { let mut ongoing = ongoing.lock(); let Some(task) = ongoing.get_mut(id) else { return }; task.logger = Some(tx); task.logs.clone() }; AppProxy::stop().await; terminal_clear(TTY.writer()).ok(); TTY.writer().write_all(buffered.as_bytes()).ok(); TTY.writer().flush().ok(); defer! { disable_raw_mode().ok(); } enable_raw_mode().ok(); let mut stdin = stdin(); // TODO: stdin let mut answer = 0; loop { select! { Some(line) = rx.recv() => { execute!(TTY.writer(), crossterm::style::Print(line), crossterm::style::Print("\r\n")).ok(); } _ = time::sleep(time::Duration::from_millis(500)) => { if !ongoing.lock().exists(id) { execute!(TTY.writer(), crossterm::style::Print("Task finished, press `q` to quit\r\n")).ok(); break; } }, result = stdin.read_u8() => { answer = result.unwrap_or(b'q'); if answer == b'q' { break; } } } } if let Some(task) = ongoing.lock().get_mut(id) { task.logger = None; } while answer != b'q' { answer = stdin.read_u8().await.unwrap_or(b'q'); } }); succ!(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/help/filter.rs
yazi-actor/src/help/filter.rs
use anyhow::Result; use yazi_macro::{render, succ}; use yazi_parser::VoidOpt; use yazi_shared::data::Data; use crate::{Actor, Ctx}; pub struct Filter; impl Actor for Filter { type Options = VoidOpt; const NAME: &str = "filter"; fn act(cx: &mut Ctx, _: Self::Options) -> Result<Data> { let help = &mut cx.help; help.in_filter = Some(Default::default()); help.filter_apply(); succ!(render!()); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/help/arrow.rs
yazi-actor/src/help/arrow.rs
use anyhow::Result; use yazi_macro::{render, succ}; use yazi_parser::ArrowOpt; use yazi_shared::data::Data; use yazi_widgets::Scrollable; use crate::{Actor, Ctx}; pub struct Arrow; impl Actor for Arrow { type Options = ArrowOpt; const NAME: &str = "arrow"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { succ!(render!(cx.help.scroll(opt.step))); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/help/toggle.rs
yazi-actor/src/help/toggle.rs
use anyhow::Result; use yazi_macro::{render, succ}; use yazi_parser::help::ToggleOpt; use yazi_shared::data::Data; use crate::{Actor, Ctx}; pub struct Toggle; impl Actor for Toggle { type Options = ToggleOpt; const NAME: &str = "toggle"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { let help = &mut cx.help; help.visible = !help.visible; help.layer = opt.layer; help.keyword = String::new(); help.in_filter = None; help.filter_apply(); help.offset = 0; help.cursor = 0; succ!(render!()); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/help/mod.rs
yazi-actor/src/help/mod.rs
yazi_macro::mod_flat!(arrow escape filter toggle);
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/help/escape.rs
yazi-actor/src/help/escape.rs
use anyhow::Result; use yazi_macro::{act, render, succ}; use yazi_parser::VoidOpt; use yazi_shared::data::Data; use crate::{Actor, Ctx}; pub struct Escape; impl Actor for Escape { type Options = VoidOpt; const NAME: &str = "escape"; fn act(cx: &mut Ctx, _: Self::Options) -> Result<Data> { if cx.help.keyword().is_none() { return act!(help:toggle, cx, cx.help.layer); } let help = &mut cx.help; help.keyword = String::new(); help.in_filter = None; help.filter_apply(); succ!(render!()); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/open.rs
yazi-actor/src/mgr/open.rs
use anyhow::Result; use yazi_boot::ARGS; use yazi_fs::File; use yazi_macro::{act, succ}; use yazi_parser::mgr::{OpenDoOpt, OpenOpt}; use yazi_proxy::MgrProxy; use yazi_shared::data::Data; use yazi_vfs::VfsFile; use crate::{Actor, Ctx, mgr::Quit}; pub struct Open; impl Actor for Open { type Options = OpenOpt; const NAME: &str = "open"; fn act(cx: &mut Ctx, mut opt: Self::Options) -> Result<Data> { if !opt.interactive && ARGS.chooser_file.is_some() { succ!(if !opt.targets.is_empty() { Quit::with_selected(opt.targets) } else if opt.hovered { Quit::with_selected(cx.hovered().map(|h| &h.url)) } else { act!(mgr:escape_visual, cx)?; Quit::with_selected(cx.tab().selected_or_hovered()) }); } if opt.targets.is_empty() { opt.targets = if opt.hovered { cx.hovered().map(|h| vec![h.url.clone().into()]).unwrap_or_default() } else { act!(mgr:escape_visual, cx)?; cx.tab().selected_or_hovered().cloned().map(Into::into).collect() }; } if opt.targets.is_empty() { succ!(); } let todo: Vec<_> = opt .targets .iter() .enumerate() .filter(|&(_, u)| !cx.mgr.mimetype.contains(u)) .map(|(i, _)| i) .collect(); let cwd = opt.cwd.unwrap_or_else(|| cx.cwd().clone().into()); if todo.is_empty() { return act!(mgr:open_do, cx, OpenDoOpt { cwd, targets: opt.targets, interactive: opt.interactive }); } let scheduler = cx.tasks.scheduler.clone(); tokio::spawn(async move { let mut files = Vec::with_capacity(todo.len()); for i in todo { if let Ok(f) = File::new(&opt.targets[i]).await { files.push(f); } } if scheduler.fetch_mimetype(files).await { MgrProxy::open_do(OpenDoOpt { cwd, targets: opt.targets, interactive: opt.interactive }); } }); succ!(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/stash.rs
yazi-actor/src/mgr/stash.rs
use anyhow::Result; use yazi_dds::spark::SparkKind; use yazi_macro::succ; use yazi_parser::mgr::StashOpt; use yazi_shared::{Source, data::Data, url::{AsUrl, UrlLike}}; use crate::{Actor, Ctx}; pub struct Stash; impl Actor for Stash { type Options = StashOpt; const NAME: &str = "stash"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { if opt.target.is_absolute() && opt.target.is_internal() { cx.tab_mut().backstack.push(opt.target.as_url()); } succ!() } fn hook(cx: &Ctx, _opt: &Self::Options) -> Option<SparkKind> { match cx.source() { Source::Ind => Some(SparkKind::IndStash), Source::Relay => Some(SparkKind::RelayStash), _ => None, } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/update_mimes.rs
yazi-actor/src/mgr/update_mimes.rs
use anyhow::Result; use hashbrown::HashMap; use yazi_macro::{act, render, succ}; use yazi_parser::mgr::UpdateMimesOpt; use yazi_shared::{data::Data, pool::InternStr, url::{AsUrl, UrlCov}}; use yazi_watcher::local::LINKED; use crate::{Actor, Ctx}; pub struct UpdateMimes; impl Actor for UpdateMimes { type Options = UpdateMimesOpt; const NAME: &str = "update_mimes"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { let linked = LINKED.read(); let updates = opt .updates .into_iter() .flat_map(|(key, value)| key.into_url().zip(value.into_string())) .filter(|(url, mime)| cx.mgr.mimetype.get(url) != Some(mime)) .fold(HashMap::new(), |mut map, (u, m)| { for u in linked.from_file(u.as_url()) { map.insert(u.into(), m.intern()); } map.insert(u.into(), m.intern()); map }); drop(linked); if updates.is_empty() { succ!(); } let affected: Vec<_> = cx .current() .paginate(cx.current().page) .iter() .filter(|&f| updates.contains_key(&UrlCov::new(&f.url))) .cloned() .collect(); let repeek = cx.hovered().is_some_and(|f| updates.contains_key(&UrlCov::new(&f.url))); cx.mgr.mimetype.extend(updates); if repeek { act!(mgr:peek, cx)?; } cx.tasks.fetch_paged(&affected, &cx.mgr.mimetype); cx.tasks.preload_paged(&affected, &cx.mgr.mimetype); succ!(render!()); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/link.rs
yazi-actor/src/mgr/link.rs
use anyhow::Result; use yazi_macro::succ; use yazi_parser::mgr::LinkOpt; use yazi_shared::data::Data; use crate::{Actor, Ctx}; pub struct Link; impl Actor for Link { type Options = LinkOpt; const NAME: &str = "link"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { let mgr = &mut cx.core.mgr; let tab = &mgr.tabs[cx.tab]; if !mgr.yanked.cut { cx.core.tasks.file_link(&mgr.yanked, tab.cwd(), opt.relative, opt.force); } succ!(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/download.rs
yazi-actor/src/mgr/download.rs
use std::{mem, time::{Duration, Instant}}; use anyhow::Result; use futures::{StreamExt, stream::FuturesUnordered}; use hashbrown::HashSet; use yazi_fs::{File, FsScheme, provider::{Provider, local::Local}}; use yazi_macro::succ; use yazi_parser::mgr::{DownloadOpt, OpenOpt}; use yazi_proxy::MgrProxy; use yazi_shared::{data::Data, url::{UrlCow, UrlLike}}; use yazi_vfs::VfsFile; use crate::{Actor, Ctx}; pub struct Download; impl Actor for Download { type Options = DownloadOpt; const NAME: &str = "download"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { let cwd = cx.cwd().clone(); let scheduler = cx.tasks.scheduler.clone(); tokio::spawn(async move { Self::prepare(&opt.urls).await; let mut wg1 = FuturesUnordered::new(); for url in opt.urls { let done = scheduler.file_download(url.to_owned()); wg1.push(async move { (done.future().await, url) }); } let mut wg2 = vec![]; let mut urls = Vec::with_capacity(wg1.len()); let mut files = Vec::with_capacity(wg1.len()); let mut instant = Instant::now(); while let Some((success, url)) = wg1.next().await { if !success { continue; } let Ok(f) = File::new(&url).await else { continue }; urls.push(url); files.push(f); if instant.elapsed() >= Duration::from_secs(1) { wg2.push(scheduler.fetch_mimetype(mem::take(&mut files))); instant = Instant::now(); } } if !files.is_empty() { wg2.push(scheduler.fetch_mimetype(files)); } if futures::future::join_all(wg2).await.into_iter().any(|b| !b) { return; } if opt.open && !urls.is_empty() { MgrProxy::open(OpenOpt { cwd: Some(cwd.into()), targets: urls, interactive: false, hovered: false, }); } }); succ!(); } } impl Download { async fn prepare(urls: &[UrlCow<'_>]) { let roots: HashSet<_> = urls.iter().filter_map(|u| u.scheme().cache()).collect(); for mut root in roots { root.push("%lock"); Local::regular(&root).create_dir_all().await.ok(); } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/suspend.rs
yazi-actor/src/mgr/suspend.rs
use anyhow::Result; use yazi_macro::succ; use yazi_parser::VoidOpt; use yazi_shared::data::Data; use crate::{Actor, Ctx}; pub struct Suspend; impl Actor for Suspend { type Options = VoidOpt; const NAME: &str = "suspend"; fn act(_: &mut Ctx, _: Self::Options) -> Result<Data> { #[cfg(unix)] if !yazi_shared::session_leader() { unsafe { libc::raise(libc::SIGTSTP); } } succ!(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/yank.rs
yazi-actor/src/mgr/yank.rs
use anyhow::Result; use yazi_core::mgr::Yanked; use yazi_macro::{act, render}; use yazi_parser::mgr::YankOpt; use yazi_shared::{data::Data, url::UrlBufCov}; use crate::{Actor, Ctx}; pub struct Yank; impl Actor for Yank { type Options = YankOpt; const NAME: &str = "yank"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { act!(mgr:escape_visual, cx)?; cx.mgr.yanked = Yanked::new(opt.cut, cx.tab().selected_or_hovered().cloned().map(UrlBufCov).collect()); render!(cx.mgr.yanked.catchup_revision(true)); act!(mgr:escape_select, cx) } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/hardlink.rs
yazi-actor/src/mgr/hardlink.rs
use anyhow::Result; use yazi_macro::succ; use yazi_parser::mgr::HardlinkOpt; use yazi_shared::data::Data; use crate::{Actor, Ctx}; pub struct Hardlink; impl Actor for Hardlink { type Options = HardlinkOpt; const NAME: &str = "hardlink"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { let mgr = &mut cx.core.mgr; let tab = &mgr.tabs[cx.tab]; if !mgr.yanked.cut { cx.core.tasks.file_hardlink(&mgr.yanked, tab.cwd(), opt.force, opt.follow); } succ!(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/cd.rs
yazi-actor/src/mgr/cd.rs
use std::{mem, time::Duration}; use anyhow::Result; use tokio::pin; use tokio_stream::{StreamExt, wrappers::UnboundedReceiverStream}; use yazi_config::popup::InputCfg; use yazi_dds::Pubsub; use yazi_fs::{File, FilesOp, path::{clean_url, expand_url}}; use yazi_macro::{act, err, render, succ}; use yazi_parser::mgr::CdOpt; use yazi_proxy::{CmpProxy, InputProxy, MgrProxy}; use yazi_shared::{Debounce, data::Data, errors::InputError, url::{AsUrl, UrlBuf, UrlLike}}; use yazi_vfs::{VfsFile, provider}; use crate::{Actor, Ctx}; pub struct Cd; impl Actor for Cd { type Options = CdOpt; const NAME: &str = "cd"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { act!(mgr:escape_visual, cx)?; if opt.interactive { return Self::cd_interactive(cx); } let tab = cx.tab_mut(); if opt.target == *tab.cwd() { succ!(); } // Take parent to history if let Some(t) = tab.parent.take() { tab.history.insert(t.url.clone(), t); } // Current let rep = tab.history.remove_or(&opt.target); let rep = mem::replace(&mut tab.current, rep); tab.history.insert(rep.url.clone(), rep); // Parent if let Some(parent) = opt.target.parent() { tab.parent = Some(tab.history.remove_or(parent)); } err!(Pubsub::pub_after_cd(tab.id, tab.cwd())); act!(mgr:displace, cx)?; act!(mgr:hidden, cx)?; act!(mgr:sort, cx).ok(); act!(mgr:hover, cx)?; act!(mgr:refresh, cx)?; act!(mgr:stash, cx, opt).ok(); succ!(render!()); } } impl Cd { fn cd_interactive(cx: &Ctx) -> Result<Data> { let input = InputProxy::show(InputCfg::cd(cx.cwd().as_url())); tokio::spawn(async move { let rx = Debounce::new(UnboundedReceiverStream::new(input), Duration::from_millis(50)); pin!(rx); while let Some(result) = rx.next().await { match result { Ok(s) => { let Ok(url) = UrlBuf::try_from(s).map(expand_url) else { return }; let Ok(url) = provider::absolute(&url).await else { return }; let url = clean_url(url); let Ok(file) = File::new(&url).await else { return }; if file.is_dir() { return MgrProxy::cd(&url); } if let Some(p) = url.parent() { FilesOp::Upserting(p.into(), [(url.urn().into(), file)].into()).emit(); } MgrProxy::reveal(url); } Err(InputError::Completed(before, ticket)) => { CmpProxy::trigger(before, ticket); } _ => break, } } }); succ!(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/filter.rs
yazi-actor/src/mgr/filter.rs
use std::time::Duration; use anyhow::Result; use tokio::pin; use tokio_stream::{StreamExt, wrappers::UnboundedReceiverStream}; use yazi_config::popup::InputCfg; use yazi_macro::succ; use yazi_parser::mgr::FilterOpt; use yazi_proxy::{InputProxy, MgrProxy}; use yazi_shared::{Debounce, data::Data, errors::InputError}; use crate::{Actor, Ctx}; pub struct Filter; impl Actor for Filter { type Options = FilterOpt; const NAME: &str = "filter"; fn act(_: &mut Ctx, opt: Self::Options) -> Result<Data> { let input = InputProxy::show(InputCfg::filter()); tokio::spawn(async move { let rx = Debounce::new(UnboundedReceiverStream::new(input), Duration::from_millis(50)); pin!(rx); while let Some(result) = rx.next().await { let done = result.is_ok(); let (Ok(s) | Err(InputError::Typed(s))) = result else { continue }; MgrProxy::filter_do(FilterOpt { query: s.into(), case: opt.case, done }); } }); succ!(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/update_spotted.rs
yazi-actor/src/mgr/update_spotted.rs
use anyhow::Result; use yazi_macro::{render, succ}; use yazi_parser::mgr::UpdateSpottedOpt; use yazi_shared::data::Data; use crate::{Actor, Ctx}; pub struct UpdateSpotted; impl Actor for UpdateSpotted { type Options = UpdateSpottedOpt; const NAME: &str = "update_spotted"; fn act(cx: &mut Ctx, mut opt: Self::Options) -> Result<Data> { let tab = cx.tab_mut(); let Some(hovered) = tab.hovered().map(|h| &h.url) else { succ!(tab.spot.reset()); }; if opt.lock.url != *hovered { succ!(); } if tab.spot.lock.as_ref().is_none_or(|l| l.id != opt.lock.id) { tab.spot.skip = opt.lock.selected().unwrap_or_default(); } else if let Some(s) = opt.lock.selected() { tab.spot.skip = s; } else { opt.lock.select(Some(tab.spot.skip)); } tab.spot.lock = Some(opt.lock); succ!(render!()); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/sort.rs
yazi-actor/src/mgr/sort.rs
use anyhow::Result; use yazi_core::tab::Folder; use yazi_dds::spark::SparkKind; use yazi_fs::{FilesSorter, FolderStage}; use yazi_macro::{act, render, render_and, succ}; use yazi_parser::mgr::SortOpt; use yazi_shared::{Source, data::Data}; use crate::{Actor, Ctx}; pub struct Sort; impl Actor for Sort { type Options = SortOpt; const NAME: &str = "sort"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { let pref = &mut cx.tab_mut().pref; pref.sort_by = opt.by.unwrap_or(pref.sort_by); pref.sort_reverse = opt.reverse.unwrap_or(pref.sort_reverse); pref.sort_dir_first = opt.dir_first.unwrap_or(pref.sort_dir_first); pref.sort_sensitive = opt.sensitive.unwrap_or(pref.sort_sensitive); pref.sort_translit = opt.translit.unwrap_or(pref.sort_translit); let sorter = FilesSorter::from(&*pref); let hovered = cx.hovered().map(|f| f.urn().to_owned()); let apply = |f: &mut Folder| { if f.stage == FolderStage::Loading { render!(); false } else { f.files.set_sorter(sorter); render_and!(f.files.catchup_revision()) } }; // Apply to CWD and parent if let (a, Some(b)) = (apply(cx.current_mut()), cx.parent_mut().map(apply)) && (a | b) { act!(mgr:hover, cx)?; act!(mgr:update_paged, cx)?; cx.tasks.prework_sorted(&cx.mgr.tabs[cx.tab].current.files); } // Apply to hovered if let Some(h) = cx.hovered_folder_mut() && apply(h) { render!(h.repos(None)); act!(mgr:peek, cx, true)?; } else if cx.hovered().map(|f| f.urn()) != hovered.as_ref().map(Into::into) { act!(mgr:peek, cx)?; act!(mgr:watch, cx)?; } succ!(); } fn hook(cx: &Ctx, _: &Self::Options) -> Option<SparkKind> { match cx.source() { Source::Ind => Some(SparkKind::IndSort), Source::Key => Some(SparkKind::KeySort), _ => None, } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/rename.rs
yazi-actor/src/mgr/rename.rs
use anyhow::Result; use yazi_config::popup::{ConfirmCfg, InputCfg}; use yazi_dds::Pubsub; use yazi_fs::{File, FilesOp}; use yazi_macro::{act, err, ok_or_not_found, succ}; use yazi_parser::mgr::RenameOpt; use yazi_proxy::{ConfirmProxy, InputProxy, MgrProxy}; use yazi_shared::{Id, data::Data, url::{UrlBuf, UrlLike}}; use yazi_vfs::{VfsFile, maybe_exists, provider}; use yazi_watcher::WATCHER; use crate::{Actor, Ctx}; pub struct Rename; impl Actor for Rename { type Options = RenameOpt; const NAME: &str = "rename"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { act!(mgr:escape_visual, cx)?; if !opt.hovered && !cx.tab().selected.is_empty() { return act!(mgr:bulk_rename, cx); } let Some(hovered) = cx.hovered() else { succ!() }; let name = Self::empty_url_part(&hovered.url, &opt.empty); let cursor = match opt.cursor.as_ref() { "start" => Some(0), "before_ext" => name .chars() .rev() .position(|c| c == '.') .filter(|_| hovered.is_file()) .map(|i| name.chars().count() - i - 1) .filter(|&i| i != 0), _ => None, }; let (tab, old) = (cx.tab().id, hovered.url_owned()); let mut input = InputProxy::show(InputCfg::rename().with_value(name).with_cursor(cursor)); tokio::spawn(async move { let Some(Ok(name)) = input.recv().await else { return }; if name.is_empty() { return; } let Some(Ok(new)) = old.parent().map(|u| u.try_join(name)) else { return; }; if opt.force || !maybe_exists(&new).await || provider::must_identical(&old, &new).await { Self::r#do(tab, old, new).await.ok(); } else if ConfirmProxy::show(ConfirmCfg::overwrite(&new)).await { Self::r#do(tab, old, new).await.ok(); } }); succ!(); } } impl Rename { async fn r#do(tab: Id, old: UrlBuf, new: UrlBuf) -> Result<()> { let Some((old_p, old_n)) = old.pair() else { return Ok(()) }; let Some(_) = new.pair() else { return Ok(()) }; let _permit = WATCHER.acquire().await.unwrap(); let overwritten = provider::casefold(&new).await; provider::rename(&old, &new).await?; if let Ok(u) = overwritten && u != new && let Some((parent, urn)) = u.pair() { ok_or_not_found!(provider::rename(&u, &new).await); FilesOp::Deleting(parent.to_owned(), [urn.into()].into()).emit(); } let new = provider::casefold(&new).await?; let Some((new_p, new_n)) = new.pair() else { return Ok(()) }; let file = File::new(&new).await?; if new_p == old_p { FilesOp::Upserting(old_p.into(), [(old_n.into(), file)].into()).emit(); } else { FilesOp::Deleting(old_p.into(), [old_n.into()].into()).emit(); FilesOp::Upserting(new_p.into(), [(new_n.into(), file)].into()).emit(); } MgrProxy::reveal(&new); err!(Pubsub::pub_after_rename(tab, &old, &new)); Ok(()) } fn empty_url_part(url: &UrlBuf, by: &str) -> String { if by == "all" { return String::new(); } let ext = url.ext(); match by { "stem" => ext.map_or_else(String::new, |s| format!(".{}", s.to_string_lossy())), "ext" if ext.is_some() => format!("{}.", url.stem().unwrap().to_string_lossy()), "dot_ext" if ext.is_some() => url.stem().unwrap().to_string_lossy().into_owned(), _ => url.name().unwrap_or_default().to_string_lossy().into_owned(), } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/toggle_all.rs
yazi-actor/src/mgr/toggle_all.rs
use anyhow::Result; use yazi_macro::{render, succ}; use yazi_parser::mgr::ToggleAllOpt; use yazi_proxy::AppProxy; use yazi_shared::data::Data; use crate::{Actor, Ctx}; pub struct ToggleAll; impl Actor for ToggleAll { type Options = ToggleAllOpt; const NAME: &str = "toggle_all"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { use yazi_shared::Either::*; let tab = cx.tab_mut(); let it = tab.current.files.iter().map(|f| &f.url); let either = match opt.state { Some(true) if opt.urls.is_empty() => Left((vec![], it.collect())), Some(true) => Right((vec![], opt.urls)), Some(false) if opt.urls.is_empty() => Left((it.collect(), vec![])), Some(false) => Right((opt.urls, vec![])), None if opt.urls.is_empty() => Left(it.partition(|&u| tab.selected.contains(u))), None => Right(opt.urls.into_iter().partition(|u| tab.selected.contains(u))), }; let warn = match either { Left((removal, addition)) => { render!(tab.selected.remove_many(removal) > 0); addition.len() != render!(tab.selected.add_many(addition), > 0) } Right((removal, addition)) => { render!(tab.selected.remove_many(&removal) > 0); render!(tab.selected.add_many(&addition), > 0) != addition.len() } }; if warn { AppProxy::notify_warn( "Toggle all", "Some files cannot be selected, due to path nesting conflict.", ); } succ!(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/tab_close.rs
yazi-actor/src/mgr/tab_close.rs
use anyhow::Result; use yazi_macro::{act, render, succ}; use yazi_parser::mgr::TabCloseOpt; use yazi_shared::data::Data; use crate::{Actor, Ctx}; pub struct TabClose; impl Actor for TabClose { type Options = TabCloseOpt; const NAME: &str = "tab_close"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { let len = cx.tabs().len(); if len < 2 || opt.idx >= len { succ!(); } let tabs = cx.tabs_mut(); tabs.remove(opt.idx).shutdown(); if opt.idx > tabs.cursor { tabs.set_idx(tabs.cursor); } else { tabs.set_idx(usize::min(tabs.cursor + 1, tabs.len() - 1)); } let cx = &mut Ctx::renew(cx); act!(mgr:refresh, cx)?; act!(mgr:peek, cx, true)?; succ!(render!()); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/arrow.rs
yazi-actor/src/mgr/arrow.rs
use anyhow::Result; use yazi_macro::{act, render, succ}; use yazi_parser::ArrowOpt; use yazi_shared::data::Data; use crate::{Actor, Ctx}; pub struct Arrow; impl Actor for Arrow { type Options = ArrowOpt; const NAME: &str = "arrow"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { let tab = cx.tab_mut(); if !tab.current.arrow(opt.step) { succ!(); } // Visual selection if let Some((start, items)) = tab.mode.visual_mut() { let end = tab.current.cursor; *items = (start.min(end)..=end.max(start)).collect(); } act!(mgr:hover, cx)?; act!(mgr:peek, cx)?; act!(mgr:watch, cx)?; succ!(render!()); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/peek.rs
yazi-actor/src/mgr/peek.rs
use anyhow::Result; use yazi_macro::succ; use yazi_parser::mgr::PeekOpt; use yazi_proxy::HIDER; use yazi_shared::data::Data; use crate::{Actor, Ctx}; pub struct Peek; impl Actor for Peek { type Options = PeekOpt; const NAME: &str = "peek"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { let Some(hovered) = cx.hovered().cloned() else { succ!(cx.tab_mut().preview.reset()); }; if HIDER.try_acquire().is_err() { succ!(cx.tab_mut().preview.reset_image()); } let mime = cx.mgr.mimetype.owned(&hovered.url).unwrap_or_default(); let folder = cx.tab().hovered_folder().map(|f| (f.offset, f.cha)); if !cx.tab().preview.same_url(&hovered.url) { cx.tab_mut().preview.skip = folder.map(|f| f.0).unwrap_or_default(); } if !cx.tab().preview.same_file(&hovered, &mime) { cx.tab_mut().preview.reset(); } if !cx.tab().preview.same_folder(&hovered.url) { cx.tab_mut().preview.folder_lock = None; } if matches!(opt.only_if, Some(u) if u != hovered.url) { succ!(); } if let Some(skip) = opt.skip { let preview = &mut cx.tab_mut().preview; if opt.upper_bound { preview.skip = preview.skip.min(skip); } else { preview.skip = skip; } } if hovered.is_dir() { cx.tab_mut().preview.go_folder(hovered, folder.map(|(_, cha)| cha), mime, opt.force); } else { cx.tab_mut().preview.go(hovered, mime, opt.force); } succ!(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/open_do.rs
yazi-actor/src/mgr/open_do.rs
use anyhow::Result; use hashbrown::HashMap; use yazi_config::{YAZI, popup::PickCfg}; use yazi_fs::Splatter; use yazi_macro::succ; use yazi_parser::{mgr::OpenDoOpt, tasks::ProcessOpenOpt}; use yazi_proxy::{PickProxy, TasksProxy}; use yazi_shared::{data::Data, url::UrlCow}; use crate::{Actor, Ctx}; pub struct OpenDo; impl Actor for OpenDo { type Options = OpenDoOpt; const NAME: &str = "open_do"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { let targets: Vec<_> = opt .targets .into_iter() .map(|u| { let m = cx.mgr.mimetype.get(&u).unwrap_or_default(); (u, m) }) .filter(|(_, m)| !m.is_empty()) .collect(); if targets.is_empty() { succ!(); } else if !opt.interactive { succ!(Self::match_and_open(cx, opt.cwd, targets)); } let openers: Vec<_> = YAZI.opener.all(YAZI.open.common(&targets).into_iter()).collect(); if openers.is_empty() { succ!(); } let pick = PickProxy::show(PickCfg::open(openers.iter().map(|o| o.desc()).collect())); let urls: Vec<_> = [UrlCow::default()].into_iter().chain(targets.into_iter().map(|(u, _)| u)).collect(); tokio::spawn(async move { if let Ok(choice) = pick.await { TasksProxy::open_shell_compat(ProcessOpenOpt { cwd: opt.cwd, cmd: Splatter::new(&urls).splat(&openers[choice].run), args: urls, block: openers[choice].block, orphan: openers[choice].orphan, done: None, spread: openers[choice].spread, }); } }); succ!(); } } impl OpenDo { // TODO: remove fn match_and_open(cx: &Ctx, cwd: UrlCow<'static>, targets: Vec<(UrlCow<'static>, &str)>) { let mut openers = HashMap::new(); for (url, mime) in targets { if let Some(opener) = YAZI.opener.first(YAZI.open.all(&url, mime)) { openers.entry(opener).or_insert_with(|| vec![UrlCow::default()]).push(url); } } for (opener, args) in openers { cx.tasks.open_shell_compat(ProcessOpenOpt { cwd: cwd.clone(), cmd: Splatter::new(&args).splat(&opener.run), args, block: opener.block, orphan: opener.orphan, done: None, spread: opener.spread, }); } } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/update_files.rs
yazi-actor/src/mgr/update_files.rs
use anyhow::Result; use yazi_core::tab::Folder; use yazi_fs::FilesOp; use yazi_macro::{act, render, succ}; use yazi_parser::mgr::UpdateFilesOpt; use yazi_shared::{data::Data, url::UrlLike}; use yazi_watcher::local::LINKED; use crate::{Actor, Ctx}; pub struct UpdateFiles; impl Actor for UpdateFiles { type Options = UpdateFilesOpt; const NAME: &str = "update_files"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { let revision = cx.current().files.revision; let linked: Vec<_> = LINKED.read().from_dir(opt.op.cwd()).map(|u| opt.op.chdir(u)).collect(); for op in [opt.op].into_iter().chain(linked) { cx.mgr.yanked.apply_op(&op); Self::update_tab(cx, op).ok(); } render!(cx.mgr.yanked.catchup_revision(false)); act!(mgr:hidden, cx)?; act!(mgr:sort, cx).ok(); if revision != cx.current().files.revision { act!(mgr:hover, cx)?; act!(mgr:peek, cx)?; act!(mgr:watch, cx)?; act!(mgr:update_paged, cx)?; } succ!(); } } impl UpdateFiles { fn update_tab(cx: &mut Ctx, op: FilesOp) -> Result<Data> { let url = op.cwd(); cx.tab_mut().selected.apply_op(&op); if url == cx.cwd() { Self::update_current(cx, op) } else if matches!(cx.parent(), Some(p) if *url == p.url) { Self::update_parent(cx, op) } else if matches!(cx.hovered(), Some(h) if *url == h.url) { Self::update_hovered(cx, op) } else { Self::update_history(cx, op) } } fn update_parent(cx: &mut Ctx, op: FilesOp) -> Result<Data> { let tab = cx.tab_mut(); let urn = tab.current.url.urn(); let leave = matches!(op, FilesOp::Deleting(_, ref urns) if urns.contains(&urn)); if let Some(f) = tab.parent.as_mut() { render!(f.update_pub(tab.id, op)); render!(f.hover(urn)); } if leave { act!(mgr:leave, cx)?; } succ!(); } fn update_current(cx: &mut Ctx, op: FilesOp) -> Result<Data> { let calc = !matches!(op, FilesOp::Size(..) | FilesOp::Deleting(..)); let id = cx.tab().id; if !cx.current_mut().update_pub(id, op) { succ!(); } if calc { cx.tasks.prework_sorted(&cx.current().files); } succ!(); } fn update_hovered(cx: &mut Ctx, op: FilesOp) -> Result<Data> { let (id, url) = (cx.tab().id, op.cwd()); let (_, folder) = cx .tab_mut() .history .raw_entry_mut() .from_key(url) .or_insert_with(|| (url.clone(), Folder::from(url))); if folder.update_pub(id, op) { act!(mgr:peek, cx, true)?; } succ!(); } fn update_history(cx: &mut Ctx, op: FilesOp) -> Result<Data> { let tab = &mut cx.tab_mut(); let leave = tab.parent.as_ref().and_then(|f| f.url.parent().map(|p| (p, f.url.urn()))).is_some_and( |(p, n)| matches!(op, FilesOp::Deleting(ref parent, ref urns) if *parent == p && urns.contains(&n)), ); tab .history .raw_entry_mut() .from_key(op.cwd()) .or_insert_with(|| (op.cwd().clone(), Folder::from(op.cwd()))) .1 .update_pub(tab.id, op); if leave { act!(mgr:leave, cx)?; } succ!(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/filter_do.rs
yazi-actor/src/mgr/filter_do.rs
use anyhow::Result; use yazi_fs::Filter; use yazi_macro::{act, render, succ}; use yazi_parser::mgr::FilterOpt; use yazi_shared::data::Data; use crate::{Actor, Ctx}; pub struct FilterDo; impl Actor for FilterDo { type Options = FilterOpt; const NAME: &str = "filter_do"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { let filter = if opt.query.is_empty() { None } else { Some(Filter::new(&opt.query, opt.case)?) }; let hovered = cx.hovered().map(|f| f.urn().into()); cx.current_mut().files.set_filter(filter); if cx.hovered().map(|f| f.urn()) != hovered.as_ref().map(Into::into) { act!(mgr:hover, cx, hovered)?; act!(mgr:peek, cx)?; act!(mgr:watch, cx)?; } if opt.done { act!(mgr:update_paged, cx)?; } succ!(render!()); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/toggle.rs
yazi-actor/src/mgr/toggle.rs
use anyhow::Result; use yazi_macro::{render_and, succ}; use yazi_parser::mgr::ToggleOpt; use yazi_proxy::AppProxy; use yazi_shared::{data::Data, url::UrlCow}; use crate::{Actor, Ctx}; pub struct Toggle; impl Actor for Toggle { type Options = ToggleOpt; const NAME: &str = "toggle"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { let tab = cx.tab_mut(); let Some(url) = opt.url.or(tab.current.hovered().map(|h| UrlCow::from(&h.url))) else { succ!(); }; let b = match opt.state { Some(true) => render_and!(tab.selected.add(&url)), Some(false) => render_and!(tab.selected.remove(&url)) | true, None => render_and!(tab.selected.remove(&url) || tab.selected.add(&url)), }; if !b { AppProxy::notify_warn( "Toggle", "This file cannot be selected, due to path nesting conflict.", ); } succ!(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/shell.rs
yazi-actor/src/mgr/shell.rs
use std::borrow::Cow; use anyhow::Result; use yazi_config::popup::InputCfg; use yazi_fs::Splatter; use yazi_macro::{act, succ}; use yazi_parser::{mgr::ShellOpt, tasks::ProcessOpenOpt}; use yazi_proxy::{InputProxy, TasksProxy}; use yazi_shared::data::Data; use crate::{Actor, Ctx}; pub struct Shell; impl Actor for Shell { type Options = ShellOpt; const NAME: &str = "shell"; fn act(cx: &mut Ctx, mut opt: Self::Options) -> Result<Data> { act!(mgr:escape_visual, cx)?; let cwd = opt.cwd.take().unwrap_or(cx.cwd().into()).into_owned(); let selected: Vec<_> = cx.tab().hovered_and_selected().cloned().map(Into::into).collect(); let input = opt.interactive.then(|| { InputProxy::show(InputCfg::shell(opt.block).with_value(&*opt.run).with_cursor(opt.cursor)) }); tokio::spawn(async move { if let Some(mut rx) = input { match rx.recv().await { Some(Ok(e)) => opt.run = Cow::Owned(e), _ => return, } } if opt.run.is_empty() { return; } TasksProxy::open_shell_compat(ProcessOpenOpt { cwd: cwd.into(), cmd: Splatter::new(&selected).splat(&*opt.run), args: selected, block: opt.block, orphan: opt.orphan, done: None, spread: true, }); }); succ!(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false
sxyazi/yazi
https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-actor/src/mgr/hover.rs
yazi-actor/src/mgr/hover.rs
use anyhow::Result; use yazi_dds::Pubsub; use yazi_macro::{err, render, succ, tab}; use yazi_parser::mgr::HoverOpt; use yazi_shared::{data::Data, url::UrlLike}; use crate::{Actor, Ctx}; pub struct Hover; impl Actor for Hover { type Options = HoverOpt; const NAME: &str = "hover"; fn act(cx: &mut Ctx, opt: Self::Options) -> Result<Data> { let tab = tab!(cx); // Parent should always track CWD if let Some(p) = &mut tab.parent { render!(p.repos(tab.current.url.try_strip_prefix(&p.url).ok())); } // Repos CWD tab.current.repos(opt.urn.as_ref().map(Into::into)); // Turn on tracing if let (Some(h), Some(u)) = (tab.hovered(), opt.urn) && h.urn() == u { // `hover(Some)` occurs after user actions, such as create, rename, reveal, etc. // At this point, it's intuitive to track the location of the file regardless. tab.current.trace = Some(u.clone()); } // Publish through DDS err!(Pubsub::pub_after_hover(tab.id, tab.hovered().map(|h| &h.url))); succ!(); } }
rust
MIT
3c39a326abaacb37d9ff15af7668756d60624dfa
2026-01-04T15:33:17.426354Z
false