Skip to content

Commit e138364

Browse files
authored
feat: platform-specific key binding (#2526)
1 parent 83f4dee commit e138364

File tree

10 files changed

+57
-43
lines changed

10 files changed

+57
-43
lines changed

yazi-cli/src/package/hash.rs

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use anyhow::{Context, Result};
1+
use anyhow::{Context, Result, bail};
22
use tokio::fs;
33
use twox_hash::XxHash3_128;
44
use yazi_fs::ok_or_not_found;
@@ -22,18 +22,21 @@ impl Dependency {
2222
&["LICENSE", "README.md", "main.lua"][..]
2323
};
2424

25-
let mut hasher = XxHash3_128::new();
26-
for file in files {
27-
hasher.write(file.as_bytes());
28-
hasher.write(b"VpvFw9Atb7cWGOdqhZCra634CcJJRlsRl72RbZeV0vpG1\0");
29-
hasher.write(&ok_or_not_found(fs::read(dir.join(file)).await)?);
25+
let mut h = XxHash3_128::new();
26+
for &file in files {
27+
h.write(file.as_bytes());
28+
h.write(b"VpvFw9Atb7cWGOdqhZCra634CcJJRlsRl72RbZeV0vpG1\0");
29+
h.write(&ok_or_not_found(fs::read(dir.join(file)).await)?);
3030
}
3131

3232
let mut assets = vec![];
3333
match fs::read_dir(dir.join("assets")).await {
3434
Ok(mut it) => {
3535
while let Some(entry) = it.next_entry().await? {
36-
assets.push((entry.file_name(), fs::read(entry.path()).await?));
36+
let Ok(name) = entry.file_name().into_string() else {
37+
bail!("asset path is not valid UTF-8: {}", entry.path().display());
38+
};
39+
assets.push((name, fs::read(entry.path()).await?));
3740
}
3841
}
3942
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
@@ -42,11 +45,11 @@ impl Dependency {
4245

4346
assets.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
4447
for (name, data) in assets {
45-
hasher.write(name.as_encoded_bytes());
46-
hasher.write(b"pQU2in0xcsu97Y77Nuq2LnT8mczMlFj22idcYRmMrglqU\0");
47-
hasher.write(&data);
48+
h.write(name.as_bytes());
49+
h.write(b"pQU2in0xcsu97Y77Nuq2LnT8mczMlFj22idcYRmMrglqU\0");
50+
h.write(&data);
4851
}
4952

50-
Ok(format!("{:x}", hasher.finish_128()))
53+
Ok(format!("{:x}", h.finish_128()))
5154
}
5255
}

yazi-config/src/keymap/chord.rs

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use std::{borrow::Cow, hash::{Hash, Hasher}, sync::OnceLock};
22

3+
use anyhow::Result;
34
use regex::Regex;
45
use serde::Deserialize;
56
use yazi_shared::{Layer, event::Cmd};
@@ -15,6 +16,8 @@ pub struct Chord {
1516
#[serde(deserialize_with = "super::deserialize_run")]
1617
pub run: Vec<Cmd>,
1718
pub desc: Option<String>,
19+
#[serde(rename = "for")]
20+
pub for_: Option<String>,
1821
}
1922

2023
impl PartialEq for Chord {
@@ -53,14 +56,15 @@ impl Chord {
5356
pub(super) fn noop(&self) -> bool {
5457
self.run.len() == 1 && self.run[0].name == "noop" && self.run[0].args.is_empty()
5558
}
59+
}
5660

57-
#[inline]
58-
pub(super) fn with_layer(mut self, layer: Layer) -> Self {
59-
for c in &mut self.run {
60-
if c.layer == Default::default() {
61-
c.layer = layer;
61+
impl Chord {
62+
pub(super) fn reshape(mut self, layer: Layer) -> Result<Self> {
63+
for cmd in &mut self.run {
64+
if cmd.layer == Default::default() {
65+
cmd.layer = layer;
6266
}
6367
}
64-
self
68+
Ok(self)
6569
}
6670
}

yazi-config/src/keymap/deserializers.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ where
2323
where
2424
A: de::SeqAccess<'de>,
2525
{
26-
let mut cmds = vec![];
26+
let mut cmds = Vec::with_capacity(seq.size_hint().unwrap_or(0));
2727
while let Some(value) = &seq.next_element::<String>()? {
2828
cmds.push(Key::from_str(value).map_err(de::Error::custom)?);
2929
}
@@ -61,7 +61,7 @@ where
6161
where
6262
A: de::SeqAccess<'de>,
6363
{
64-
let mut cmds = vec![];
64+
let mut cmds = Vec::with_capacity(seq.size_hint().unwrap_or(0));
6565
while let Some(value) = &seq.next_element::<String>()? {
6666
cmds.push(Cmd::from_str(value).map_err(de::Error::custom)?);
6767
}

yazi-config/src/keymap/keymap.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,19 @@ use serde::Deserialize;
33
use yazi_codegen::DeserializeOver1;
44
use yazi_shared::Layer;
55

6-
use super::{Chord, KeymapRule};
6+
use super::{Chord, KeymapRules};
77

88
#[derive(Deserialize, DeserializeOver1)]
99
pub struct Keymap {
1010
#[serde(rename = "manager")]
11-
pub mgr: KeymapRule,
12-
pub tasks: KeymapRule,
13-
pub spot: KeymapRule,
14-
pub pick: KeymapRule,
15-
pub input: KeymapRule,
16-
pub confirm: KeymapRule,
17-
pub help: KeymapRule,
18-
pub cmp: KeymapRule,
11+
pub mgr: KeymapRules,
12+
pub tasks: KeymapRules,
13+
pub spot: KeymapRules,
14+
pub pick: KeymapRules,
15+
pub input: KeymapRules,
16+
pub confirm: KeymapRules,
17+
pub help: KeymapRules,
18+
pub cmp: KeymapRules,
1919
}
2020

2121
impl Keymap {

yazi-config/src/keymap/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
yazi_macro::mod_flat!(chord cow deserializers key keymap rule);
1+
yazi_macro::mod_flat!(chord cow deserializers key keymap rules);

yazi-config/src/keymap/rule.rs renamed to yazi-config/src/keymap/rules.rs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,24 +6,24 @@ use yazi_codegen::DeserializeOver2;
66
use yazi_shared::Layer;
77

88
use super::Chord;
9-
use crate::{Preset, keymap::Key};
9+
use crate::{Preset, check_for, keymap::Key};
1010

1111
#[derive(Default, Deserialize, DeserializeOver2)]
12-
pub struct KeymapRule {
12+
pub struct KeymapRules {
1313
pub keymap: Vec<Chord>,
1414
#[serde(default)]
1515
prepend_keymap: Vec<Chord>,
1616
#[serde(default)]
1717
append_keymap: Vec<Chord>,
1818
}
1919

20-
impl Deref for KeymapRule {
20+
impl Deref for KeymapRules {
2121
type Target = Vec<Chord>;
2222

2323
fn deref(&self) -> &Self::Target { &self.keymap }
2424
}
2525

26-
impl KeymapRule {
26+
impl KeymapRules {
2727
pub(crate) fn reshape(self, layer: Layer) -> Result<Self> {
2828
#[inline]
2929
fn on(Chord { on, .. }: &Chord) -> [Key; 2] {
@@ -38,9 +38,10 @@ impl KeymapRule {
3838
self.keymap.into_iter().filter(|v| !a_seen.contains(&on(v))),
3939
self.append_keymap.into_iter().filter(|v| !b_seen.contains(&on(v))),
4040
)
41-
.filter(|chord| !chord.noop())
42-
.map(|chord| chord.with_layer(layer))
43-
.collect();
41+
.map(|mut chord| (chord.for_.take(), chord))
42+
.filter(|(for_, chord)| !chord.noop() && check_for(for_.as_deref()))
43+
.map(|(_, chord)| chord.reshape(layer))
44+
.collect::<Result<_>>()?;
4445

4546
Ok(Self { keymap, ..Default::default() })
4647
}

yazi-config/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
yazi_macro::mod_pub!(keymap mgr open opener plugin popup preview tasks theme which);
44

5-
yazi_macro::mod_flat!(layout pattern preset priority yazi);
5+
yazi_macro::mod_flat!(layout pattern platform preset priority yazi);
66

77
use std::io::{Read, Write};
88

yazi-config/src/opener/opener.rs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use indexmap::IndexSet;
55
use serde::Deserialize;
66

77
use super::OpenerRule;
8+
use crate::check_for;
89

910
#[derive(Debug, Deserialize)]
1011
pub struct Opener(HashMap<String, Vec<OpenerRule>>);
@@ -44,12 +45,7 @@ impl Opener {
4445
*rules = mem::take(rules)
4546
.into_iter()
4647
.map(|mut r| (r.for_.take(), r))
47-
.filter(|(for_, _)| match for_.as_ref().map(|s| s.as_str()) {
48-
Some("unix") if cfg!(unix) => true,
49-
Some(os) if os == std::env::consts::OS => true,
50-
Some(_) => false,
51-
None => true,
52-
})
48+
.filter(|(for_, _)| check_for(for_.as_deref()))
5349
.map(|(_, r)| r.reshape())
5450
.collect::<Result<IndexSet<_>>>()?
5551
.into_iter()

yazi-config/src/platform.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#[inline]
2+
pub(crate) fn check_for(for_: Option<&str>) -> bool {
3+
match for_.as_ref().map(|s| s.as_ref()) {
4+
Some("unix") if cfg!(unix) => true,
5+
Some(os) if os == std::env::consts::OS => true,
6+
Some(_) => false,
7+
None => true,
8+
}
9+
}

yazi-plugin/src/utils/layer.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ impl Utils {
2323
on: Self::parse_keys(cand.raw_get("on")?)?,
2424
run: vec![Cmd::args("which:callback", &[i]).with_any("tx", tx.clone())],
2525
desc: cand.raw_get("desc").ok(),
26+
for_: None,
2627
});
2728
}
2829

0 commit comments

Comments
 (0)