feat: support and hide Windows system files by default (#2149)

This commit is contained in:
三咲雅 · Misaki Masa 2025-01-03 08:18:34 +08:00 committed by GitHub
parent 40fea8521e
commit 7d993c1517
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
32 changed files with 62 additions and 390 deletions

View file

@ -63,7 +63,7 @@ body:
label: Checklist
description: Before submitting the issue, please make sure you have completed the following
options:
- label: I tried the [latest nightly build](https://yazi-rs.github.io/docs/installation#official-binaries), and the issue is still reproducible
- label: I tried the [latest nightly build](https://yazi-rs.github.io/docs/installation#binaries), and the issue is still reproducible
required: true
- label: I updated the debug information (`yazi --debug`) input box to the nightly that I tried
required: true

View file

@ -45,5 +45,5 @@ body:
options:
- label: I have searched the existing issues/discussions
required: true
- label: The [latest nightly build](https://yazi-rs.github.io/docs/installation/#official-binaries) doesn't already have this feature
- label: The [latest nightly build](https://yazi-rs.github.io/docs/installation/#binaries) doesn't already have this feature
required: true

16
Cargo.lock generated
View file

@ -272,9 +272,9 @@ dependencies = [
[[package]]
name = "bstr"
version = "1.11.1"
version = "1.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "786a307d683a5bf92e6fd5fd69a7eb613751668d1d8d67d802846dfe367c62c8"
checksum = "531a9155a481e2ee699d4f98f43c0ca4ff8ee1bfd55c31e9e98fb29d2b176fe0"
dependencies = [
"memchr",
"serde",
@ -413,9 +413,9 @@ dependencies = [
[[package]]
name = "clap_complete_nushell"
version = "4.5.4"
version = "4.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "315902e790cc6e5ddd20cbd313c1d0d49db77f191e149f96397230fb82a17677"
checksum = "c6a8b1593457dfc2fe539002b795710d022dc62a65bf15023f039f9760c7b18a"
dependencies = [
"clap",
"clap_complete",
@ -2456,9 +2456,9 @@ dependencies = [
[[package]]
name = "syn"
version = "2.0.93"
version = "2.0.94"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c786062daee0d6db1132800e623df74274a0a87322d8e183338e01b3d98d058"
checksum = "987bc0be1cdea8b10216bd06e2ca407d40b9543468fafd3ddfb02f36e77f71f3"
dependencies = [
"proc-macro2",
"quote",
@ -3309,9 +3309,9 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winnow"
version = "0.6.20"
version = "0.6.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36c1fec1a2bb5866f07c25f68c26e565c4c200aebb96d7e55710c19d3e8ac49b"
checksum = "e6f5bb5257f2407a5425c6e749bfd9692192a73e70a6060516ac04f889087d68"
dependencies = [
"memchr",
]

View file

@ -24,5 +24,5 @@ serde = { workspace = true }
clap = { workspace = true }
clap_complete = "4.5.40"
clap_complete_fig = "4.5.2"
clap_complete_nushell = "4.5.4"
clap_complete_nushell = "4.5.5"
vergen-gitcl = { version = "1.0.2", features = [ "build", "rustc" ] }

View file

@ -32,7 +32,7 @@ anyhow = { workspace = true }
clap = { workspace = true }
clap_complete = "4.5.40"
clap_complete_fig = "4.5.2"
clap_complete_nushell = "4.5.4"
clap_complete_nushell = "4.5.5"
serde_json = { workspace = true }
vergen-gitcl = { version = "1.0.2", features = [ "build" ] }

View file

@ -13,5 +13,5 @@ proc-macro = true
[dependencies]
# External dependencies
syn = { version = "2.0.93", features = [ "full" ] }
syn = { version = "2.0.94", features = [ "full" ] }
quote = "1.0.38"

View file

@ -39,11 +39,13 @@ open = [
{ run = 'xdg-open "$1"', desc = "Open", for = "linux" },
{ run = 'open "$@"', desc = "Open", for = "macos" },
{ run = 'start "" "%1"', orphan = true, desc = "Open", for = "windows" },
{ run = 'termux-open "$1"', desc = "Open", for = "android" },
]
reveal = [
{ run = 'xdg-open "$(dirname "$1")"', desc = "Reveal", for = "linux" },
{ run = 'open -R "$1"', desc = "Reveal", for = "macos" },
{ run = 'explorer /select,"%1"', orphan = true, desc = "Reveal", for = "windows" },
{ run = 'termux-open "$(dirname "$1")"', desc = "Reveal", for = "android" },
{ run = '''exiftool "$1"; echo "Press enter to exit"; read _''', block = true, desc = "Show EXIF", for = "unix" },
]
extract = [

View file

@ -28,16 +28,6 @@ pub fn init() -> anyhow::Result<()> {
try_init(false)?;
}
// TODO: Remove in v0.3.6
if matches!(INPUT.create_title, popup::InputCreateTitle::One(_)) {
eprintln!(
r#"WARNING: The `create_title` under `[input]` now accepts an array instead of a string to support different titles for `create` and `create --dir` command.
Please change `create_title = "Create:"` to `create_title = ["Create:", "Create (dir):"]` in your yazi.toml.
"#
);
}
Ok(())
}

View file

@ -26,10 +26,6 @@ pub struct Manager {
pub scrolloff: u8,
pub mouse_events: MouseEvents,
pub title_format: String,
// TODO: remove this in Yazi 0.4.2
#[serde(default)]
pub _v4_suppress_deprecation_warnings: bool,
}
impl FromStr for Manager {

View file

@ -15,7 +15,7 @@ pub struct Input {
pub cd_offset: Offset,
// create
pub create_title: InputCreateTitle,
pub create_title: [String; 2],
pub create_origin: Origin,
pub create_offset: Offset,
@ -64,20 +64,3 @@ impl FromStr for Input {
Ok(outer.input)
}
}
// TODO: Remove in v0.3.6
#[derive(Deserialize)]
#[serde(untagged)]
pub enum InputCreateTitle {
One(String),
Two([String; 2]),
}
impl InputCreateTitle {
pub fn as_array(&self) -> [&str; 2] {
match self {
Self::One(s) => [s, "Create (dir):"],
Self::Two(a) => [&a[0], &a[1]],
}
}
}

View file

@ -42,7 +42,7 @@ impl InputCfg {
pub fn create(dir: bool) -> Self {
Self {
title: INPUT.create_title.as_array()[dir as usize].to_owned(),
title: INPUT.create_title[dir as usize].to_owned(),
position: Position::new(INPUT.create_origin, INPUT.create_offset),
..Default::default()
}

View file

@ -16,8 +16,6 @@ yazi_macro::mod_flat!(
linemode
reveal
search
select
select_all
shell
sort
toggle

View file

@ -1,30 +0,0 @@
use std::time::Duration;
use yazi_shared::event::CmdCow;
use crate::tab::Tab;
struct Opt;
impl From<CmdCow> for Opt {
fn from(_: CmdCow) -> Self { Self }
}
impl From<()> for Opt {
fn from(_: ()) -> Self { Self }
}
impl Tab {
// TODO: remove this in Yazi 0.4.1
#[yazi_codegen::command]
pub fn select(&mut self, _: Opt) {
yazi_proxy::AppProxy::notify(yazi_proxy::options::NotifyOpt {
title: "Deprecated command".to_owned(),
content: "`select` and `select_all` command has been renamed to `toggle` and `toggle_all` in Yazi v0.4
Please change it in your keymap.toml, see #1772 for details: https://github.com/sxyazi/yazi/issues/1772".to_owned(),
level: yazi_proxy::options::NotifyLevel::Error,
timeout: Duration::from_secs(20),
});
}
}

View file

@ -1,15 +0,0 @@
use yazi_shared::event::CmdCow;
use crate::tab::Tab;
struct Opt;
impl From<CmdCow> for Opt {
fn from(_: CmdCow) -> Self { Self }
}
impl Tab {
// TODO: remove this in Yazi 0.4.1
#[yazi_codegen::command]
pub fn select_all(&mut self, _: Opt) { self.select(()); }
}

View file

@ -68,9 +68,6 @@ impl App {
} else {
let job = LUA.create_table_from([("args", Sendable::args_to_table(&LUA, opt.args)?)])?;
// TODO: remove this
yazi_plugin::isolate::install_entry_warn(&LUA, &job, opt._old_args).ok();
plugin.call_method("entry", job)
}
});

View file

@ -102,8 +102,6 @@ impl<'a> Executor<'a> {
on!(ACTIVE, toggle);
on!(ACTIVE, toggle_all);
on!(ACTIVE, visual_mode);
on!(ACTIVE, select);
on!(ACTIVE, select_all);
// Operation
on!(MANAGER, open, &self.app.cx.tasks);

View file

@ -26,28 +26,6 @@ impl UserData for Tab {
fn add_fields<F: UserDataFields<Self>>(fields: &mut F) {
fields.add_field_method_get("id", |_, me| Ok(me.id.get()));
fields.add_field_method_get("mode", |_, me| Mode::make(&me.mode));
// TODO: remove `conf` once v0.4 is released
fields.add_field_method_get("conf", |lua, me| {
static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) {
let id = match lua.named_registry_value::<yazi_plugin::RtRef>("rt")?.current() {
Some(id) => format!("`{id}.yazi` plugin"),
None => "`init.lua` config".to_owned(),
};
let s = "The `conf` property of `tab::Tab` has been deprecated in Yazi v0.4.
Please use `pref` instead, e.g. `cx.active.conf` => `cx.active.pref`, in your {id}.";
yazi_proxy::AppProxy::notify(yazi_proxy::options::NotifyOpt {
title: "Deprecated API".to_owned(),
content: s.replace("{id}", &id),
level: yazi_proxy::options::NotifyLevel::Warn,
timeout: std::time::Duration::from_secs(20),
});
}
Preference::make(&me.pref)
});
fields.add_field_method_get("pref", |_, me| Preference::make(&me.pref));
fields.add_field_method_get("current", |_, me| Folder::make(None, &me.current, me));
fields.add_field_method_get("parent", |_, me| {

View file

@ -1,7 +1,7 @@
use std::{fs::{FileType, Metadata}, path::Path, time::SystemTime};
use bitflags::bitflags;
use yazi_macro::unix_either;
use yazi_macro::{unix_either, win_either};
bitflags! {
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@ -13,6 +13,8 @@ bitflags! {
const ORPHAN = 0b00001000;
const DUMMY = 0b00010000;
#[cfg(windows)]
const SYSTEM = 0b00100000;
}
}
@ -153,9 +155,14 @@ impl Cha {
#[cfg(windows)]
{
use std::os::windows::fs::MetadataExt;
if meta.file_attributes() & 2 != 0 {
use windows_sys::Win32::Storage::FileSystem::{FILE_ATTRIBUTE_HIDDEN, FILE_ATTRIBUTE_SYSTEM};
if meta.file_attributes() & FILE_ATTRIBUTE_HIDDEN != 0 {
attached |= ChaKind::HIDDEN;
}
if meta.file_attributes() & FILE_ATTRIBUTE_SYSTEM != 0 {
attached |= ChaKind::SYSTEM;
}
}
let mut cha = Self::from(meta);
@ -182,7 +189,9 @@ impl Cha {
pub const fn is_dir(&self) -> bool { self.kind.contains(ChaKind::DIR) }
#[inline]
pub const fn is_hidden(&self) -> bool { self.kind.contains(ChaKind::HIDDEN) }
pub const fn is_hidden(&self) -> bool {
self.kind.contains(ChaKind::HIDDEN) || win_either!(self.kind.contains(ChaKind::SYSTEM), false)
}
#[inline]
pub const fn is_link(&self) -> bool { self.kind.contains(ChaKind::LINK) }

View file

@ -11,3 +11,17 @@ macro_rules! unix_either {
}
}};
}
#[macro_export]
macro_rules! win_either {
($a:expr, $b:expr) => {{
#[cfg(windows)]
{
$a
}
#[cfg(not(windows))]
{
$b
}
}};
}

View file

@ -22,9 +22,9 @@ end
function Tab:build()
self._children = {
Parent:new(self._chunks[1]:padding(ui.Padding.x(1)), self._tab),
Parent:new(self._chunks[1]:pad(ui.Pad.x(1)), self._tab),
Current:new(self._chunks[2], self._tab),
Preview:new(self._chunks[3]:padding(ui.Padding.x(1)), self._tab),
Preview:new(self._chunks[3]:pad(ui.Pad.x(1)), self._tab),
Rail:new(self._chunks, self._tab),
}
end

View file

@ -1,21 +1,6 @@
local M = {}
function M:setup()
-- TODO: remove this
local b = false
ps.sub_remote("dds-cd", function(url)
if not b then
b = true
ya.notify {
title = "Deprecated DDS Event",
content = "The `dds-cd` event is deprecated, please use `ya emit cd /your/path` instead of `ya pub dds-cd --str /your/path`\n\nSee #1979 for details: https://github.com/sxyazi/yazi/pull/1979",
timeout = 20,
level = "warn",
}
end
ya.manager_emit("cd", { url })
end)
ps.sub_remote("dds-emit", function(cmd) ya.manager_emit(cmd[1], cmd[2]) end)
end

View file

@ -3,8 +3,6 @@ use std::{ops::Deref, time::{Duration, SystemTime, UNIX_EPOCH}};
use mlua::{ExternalError, FromLua, IntoLua, Lua, Table, UserData, UserDataFields, UserDataMethods};
use yazi_fs::ChaKind;
use crate::RtRef;
#[derive(Clone, Copy, FromLua)]
pub struct Cha(yazi_fs::Cha);
@ -18,26 +16,6 @@ impl<T: Into<yazi_fs::Cha>> From<T> for Cha {
fn from(cha: T) -> Self { Self(cha.into()) }
}
#[inline]
fn warn_deprecated(id: Option<&str>) {
static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) {
let id = match id {
Some(id) => format!("`{id}.yazi` plugin"),
None => "`init.lua` config".to_owned(),
};
let s = "The `created`, `modified`, `accessed`, `length`, and `permissions` properties of `Cha` have been renamed in Yazi v0.4.
Please use the new `btime`, `mtime`, `atime`, `len`, and `perm` instead, in your {id}. See #1772 for details: https://github.com/sxyazi/yazi/issues/1772";
yazi_proxy::AppProxy::notify(yazi_proxy::options::NotifyOpt {
title: "Deprecated API".to_owned(),
content: s.replace("{id}", &id),
level: yazi_proxy::options::NotifyLevel::Warn,
timeout: Duration::from_secs(20),
});
}
}
impl Cha {
pub fn install(lua: &Lua) -> mlua::Result<()> {
#[inline]
@ -113,26 +91,6 @@ impl UserData for Cha {
fields.add_field_method_get("mtime", |_, me| {
Ok(me.mtime.and_then(|t| t.duration_since(UNIX_EPOCH).map(|d| d.as_secs_f64()).ok()))
});
// TODO: remove these deprecated properties in the future
{
fields.add_field_method_get("length", |lua, me| {
warn_deprecated(lua.named_registry_value::<RtRef>("rt")?.current());
Ok(me.len)
});
fields.add_field_method_get("created", |lua, me| {
warn_deprecated(lua.named_registry_value::<RtRef>("rt")?.current());
Ok(me.btime.and_then(|t| t.duration_since(UNIX_EPOCH).map(|d| d.as_secs_f64()).ok()))
});
fields.add_field_method_get("modified", |lua, me| {
warn_deprecated(lua.named_registry_value::<RtRef>("rt")?.current());
Ok(me.mtime.and_then(|t| t.duration_since(UNIX_EPOCH).map(|d| d.as_secs_f64()).ok()))
});
fields.add_field_method_get("accessed", |lua, me| {
warn_deprecated(lua.named_registry_value::<RtRef>("rt")?.current());
Ok(me.atime.and_then(|t| t.duration_since(UNIX_EPOCH).map(|d| d.as_secs_f64()).ok()))
});
}
}
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
@ -144,16 +102,5 @@ impl UserData for Cha {
None::<String>,
)
});
// TODO: remove these deprecated properties in the future
methods.add_method("permissions", |lua, _me, ()| {
warn_deprecated(lua.named_registry_value::<RtRef>("rt")?.current());
Ok(
#[cfg(unix)]
Some(yazi_fs::permissions(_me.mode, _me.is_dummy())),
#[cfg(windows)]
None::<String>,
)
});
}
}

View file

@ -24,6 +24,7 @@ impl Clipboard {
let all = [
("pbpaste", &[][..]),
("termux-clipboard-get", &[]),
("wl-paste", &[]),
("xclip", &["-o", "-selection", "clipboard"]),
("xsel", &["-ob"]),
@ -64,6 +65,7 @@ impl Clipboard {
let all = [
("pbcopy", &[][..]),
("termux-clipboard-set", &[]),
("wl-copy", &[]),
("xclip", &["-selection", "clipboard"]),
("xsel", &["-ib"]),

View file

@ -17,7 +17,6 @@ pub fn compose(lua: &Lua) -> mlua::Result<Table> {
b"Pad" => super::Pad::compose(lua, true)?,
// TODO: deprecate this
b"Padding" => super::Pad::compose(lua, false)?,
b"Paragraph" => super::Paragraph::compose(lua)?,
b"Pos" => super::Pos::compose(lua)?,
b"Rect" => super::Rect::compose(lua)?,
b"Row" => super::Row::compose(lua)?,

View file

@ -1,3 +1,3 @@
#![allow(clippy::module_inception)]
yazi_macro::mod_flat!(area bar border cell clear constraint elements gauge layout line list pad paragraph pos rect renderable row span style table text);
yazi_macro::mod_flat!(area bar border cell clear constraint elements gauge layout line list pad pos rect renderable row span style table text);

View file

@ -1,64 +0,0 @@
use std::time::Duration;
use mlua::{FromLua, Lua, MetaMethod, MultiValue, Table, Value};
use super::Rect;
use crate::RtRef;
#[inline]
fn warn_deprecated(id: Option<&str>) {
static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) {
let id = match id {
Some(id) => format!("`{id}.yazi` plugin"),
None => "`init.lua` config".to_owned(),
};
let s = "The `ui.Paragraph` and `ui.ListItem` elements have been deprecated in Yazi v0.4.
Please use the new `ui.Text` instead, in your {id}. See #1772 for details: https://github.com/sxyazi/yazi/issues/1772";
yazi_proxy::AppProxy::notify(yazi_proxy::options::NotifyOpt {
title: "Deprecated API".to_owned(),
content: s.replace("{id}", &id),
level: yazi_proxy::options::NotifyLevel::Warn,
timeout: Duration::from_secs(20),
});
}
}
// TODO: remove this after v0.4 release
#[derive(Clone, Default, FromLua)]
pub struct Paragraph;
impl Paragraph {
pub fn compose(lua: &Lua) -> mlua::Result<Table> {
let mt = lua.create_table_from([
(
MetaMethod::Call.name(),
lua.create_function(|lua, (_, area, lines): (Table, Rect, Value)| {
warn_deprecated(lua.named_registry_value::<RtRef>("rt")?.current());
lua
.load(mlua::chunk! {
return ui.Text($lines):area($area)
})
.call::<MultiValue>(())
})?,
),
(
MetaMethod::Index.name(),
lua.create_function(|lua, (_, key): (Table, mlua::String)| {
warn_deprecated(lua.named_registry_value::<RtRef>("rt")?.current());
lua
.load(mlua::chunk! {
return ui.Text[$key]
})
.call::<MultiValue>(())
})?,
),
])?;
let paragraph = lua.create_table()?;
paragraph.set_metatable(Some(mt));
Ok(paragraph)
}
}

View file

@ -1,13 +1,10 @@
use std::time::Duration;
use mlua::{ExternalError, ExternalResult, Lua, MetaMethod, ObjectLike, Table, Value};
use mlua::{ExternalError, ExternalResult, ObjectLike, Table};
use tokio::runtime::Handle;
use yazi_dds::Sendable;
use yazi_proxy::options::PluginOpt;
use yazi_shared::event::Data;
use super::slim_lua;
use crate::{RtRef, loader::LOADER};
use crate::loader::LOADER;
pub async fn entry(opt: PluginOpt) -> mlua::Result<()> {
LOADER.ensure(&opt.id).await.into_lua_err()?;
@ -22,54 +19,8 @@ pub async fn entry(opt: PluginOpt) -> mlua::Result<()> {
let job = lua.create_table_from([("args", Sendable::args_to_table(&lua, opt.args)?)])?;
// TODO: remove this
install_entry_warn(&lua, &job, opt._old_args).ok();
Handle::current().block_on(plugin.call_async_method("entry", job))
})
.await
.into_lua_err()?
}
#[inline]
fn warn_deprecated(id: Option<&str>) {
static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) {
let id = match id {
Some(id) => format!("`{id}.yazi` plugin"),
None => "`init.lua` config".to_owned(),
};
let s = "The first parameter of `entry()` has been replaced by the new `job` instead of the previous `args`.
Please use `job.args` instead `args` to access the arguments in your {id}.
See #1966 for details: https://github.com/sxyazi/yazi/pull/1966";
yazi_proxy::AppProxy::notify(yazi_proxy::options::NotifyOpt {
title: "Deprecated API".to_owned(),
content: s.replace("{id}", &id),
level: yazi_proxy::options::NotifyLevel::Warn,
timeout: Duration::from_secs(20),
});
}
}
pub fn install_entry_warn(lua: &Lua, job: &Table, old_args: Vec<Data>) -> mlua::Result<()> {
let mt = lua.create_table_from([(
MetaMethod::Index.name(),
lua.create_function(|lua, (ts, key): (Table, mlua::String)| {
if key.as_bytes().first().is_some_and(|&b| b.is_ascii_digit()) {
warn_deprecated(lua.named_registry_value::<RtRef>("rt")?.current());
lua
.load(mlua::chunk! {
return rawget($ts, "__unsafe_args")[tonumber($key)]
})
.call::<Value>(())
} else {
ts.raw_get::<Value>(key)
}
})?,
)])?;
job.set_metatable(Some(mt));
job.raw_set("__unsafe_args", Sendable::data_to_value(lua, Data::List(old_args))?)?;
Ok(())
}

View file

@ -1,6 +1,6 @@
use std::{borrow::Cow, time::Duration};
use std::borrow::Cow;
use mlua::{ExternalError, ExternalResult, HookTriggers, IntoLua, Lua, MetaMethod, MultiValue, ObjectLike, Table, VmState};
use mlua::{ExternalError, ExternalResult, HookTriggers, IntoLua, ObjectLike, Table, VmState};
use tokio::{runtime::Handle, select};
use tokio_util::sync::CancellationToken;
use tracing::error;
@ -10,7 +10,7 @@ use yazi_proxy::{AppProxy, options::{PluginCallback, PluginOpt}};
use yazi_shared::event::Cmd;
use super::slim_lua;
use crate::{RtRef, bindings::Cast, elements::Rect, file::File, loader::LOADER};
use crate::{bindings::Cast, elements::Rect, file::File, loader::LOADER};
pub fn peek(
cmd: &'static Cmd,
@ -51,9 +51,6 @@ pub fn peek(
("skip", skip.into_lua(&lua)?),
])?;
// TODO: remove this
install_warn_mt(&lua, &plugin, job.clone()).ok();
if ct2.is_cancelled() { Ok(()) } else { plugin.call_async_method("peek", job).await }
};
@ -84,58 +81,8 @@ pub fn peek_sync(cmd: &'static Cmd, file: yazi_fs::File, mime: Cow<'static, str>
("skip", skip.into_lua(lua)?),
])?;
// TODO: remove this
install_warn_mt(lua, &plugin, job.clone()).ok();
plugin.call_method("peek", job)
});
AppProxy::plugin(PluginOpt::new_callback(&cmd.name, cb));
}
pub(super) fn install_warn_mt(lua: &Lua, plugin: &Table, job: Table) -> mlua::Result<()> {
let mt = lua.create_table_from([(
MetaMethod::Index.name(),
lua.create_function(|lua, (ts, key): (Table, mlua::String)| {
let b = key.as_bytes() == b"file"
|| key.as_bytes() == b"mime"
|| key.as_bytes() == b"skip"
|| key.as_bytes() == b"area";
if b {
warn_deprecated(lua.named_registry_value::<RtRef>("rt")?.current());
}
lua
.load(mlua::chunk! {
if $b then
return rawget($ts, "__unsafe_job")[$key]
else
return rawget($ts, $key)
end
})
.call::<MultiValue>(())
})?,
)])?;
plugin.set_metatable(Some(mt));
plugin.raw_set("__unsafe_job", job.clone())?;
Ok(())
}
#[inline]
fn warn_deprecated(id: Option<&str>) {
static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) {
let id = match id {
Some(id) => format!("`{id}.yazi` plugin"),
None => "`init.lua` config".to_owned(),
};
let s = "The file list for peek() and preload() method has been moved from `self` to the first parameter `job` of the method to avoid conflicts with the plugin's own attributes.
Please use the new `job` parameter in your {id} instead of `self`. See #1966 for details: https://github.com/sxyazi/yazi/pull/1966";
yazi_proxy::AppProxy::notify(yazi_proxy::options::NotifyOpt {
title: "Deprecated API".to_owned(),
content: s.replace("{id}", &id),
level: yazi_proxy::options::NotifyLevel::Warn,
timeout: Duration::from_secs(20),
});
}
}

View file

@ -25,9 +25,6 @@ pub async fn preload(cmd: &'static Cmd, file: yazi_fs::File) -> mlua::Result<u8>
("skip", 0.into_lua(&lua)?),
])?;
// TODO: remove this
super::install_warn_mt(&lua, &plugin, job.clone()).ok();
Handle::current().block_on(plugin.call_async_method("preload", job))
})
.await

View file

@ -21,15 +21,14 @@ impl TryFrom<Table> for PreviewLock {
type Error = mlua::Error;
fn try_from(t: Table) -> Result<Self, Self::Error> {
// TODO: use `raw_get` instead of `get`
let file: FileRef = t.get("file")?;
let file: FileRef = t.raw_get("file")?;
Ok(Self {
url: file.url_owned(),
cha: file.cha,
mime: t.get("mime")?,
mime: t.raw_get("mime")?,
skip: t.get("skip")?,
area: t.get("area")?,
skip: t.raw_get("skip")?,
area: t.raw_get("area")?,
data: Default::default(),
})
}
@ -38,7 +37,7 @@ impl TryFrom<Table> for PreviewLock {
impl Utils {
pub(super) fn preview_code(lua: &Lua) -> mlua::Result<Function> {
lua.create_async_function(|lua, t: Table| async move {
let area: Area = t.get("area")?; // TODO: use `raw_get` instead of `get`
let area: Area = t.raw_get("area")?;
let mut lock = PreviewLock::try_from(t)?;
let inner = match Highlighter::new(&lock.url).highlight(lock.skip, area.size()).await {

View file

@ -1,7 +1,6 @@
use std::time::Duration;
use tokio::sync::oneshot;
use yazi_config::MANAGER;
use yazi_macro::emit;
use yazi_shared::{Layer, event::Cmd};
@ -24,10 +23,6 @@ impl AppProxy {
#[inline]
pub fn notify(opt: NotifyOpt) {
if MANAGER._v4_suppress_deprecation_warnings && opt.title.contains("Deprecated") {
return;
}
emit!(Call(Cmd::new("notify").with_any("option", opt), Layer::App));
}

View file

@ -12,9 +12,6 @@ pub struct PluginOpt {
pub args: HashMap<DataKey, Data>,
pub mode: PluginMode,
pub cb: Option<PluginCallback>,
// TODO: remove this
pub _old_args: Vec<Data>,
}
impl TryFrom<CmdCow> for PluginOpt {
@ -29,13 +26,10 @@ impl TryFrom<CmdCow> for PluginOpt {
bail!("plugin id cannot be empty");
};
let (args, _old_args) = if let Some(s) = c.str("args") {
(
Cmd::parse_args(shell_words::split(s)?.into_iter(), true)?,
shell_words::split(s)?.into_iter().map(Data::String).collect(),
)
let args = if let Some(s) = c.str("args") {
Cmd::parse_args(shell_words::split(s)?.into_iter(), true)?
} else {
(Default::default(), Default::default())
Default::default()
};
let mut mode = c.str("mode").map(Into::into).unwrap_or_default();
@ -52,7 +46,7 @@ Please add `--- @sync entry` metadata at the head of your `{id}` plugin instead.
});
}
Ok(Self { id, args, mode, cb: c.take_any("callback"), _old_args })
Ok(Self { id, args, mode, cb: c.take_any("callback") })
}
}