Skip to content

Commit 93f7fb1

Browse files
committed
feat: Gesture configuration in shortcuts config
This commit adds a Gesture abstraction, which can define gestures by the number of fingers used, and the direction the gesture is performed in. The abstraction is modeled after the Binding type, and the resulting Gestures type is similar to the Shortcuts type. This is the first step in implementing configurable touchpad gestures (pop-os/cosmic-comp#396) Signed-off-by: Ryan Brue <[email protected]>
1 parent 9d9ad8e commit 93f7fb1

File tree

3 files changed

+243
-1
lines changed

3 files changed

+243
-1
lines changed

config/src/shortcuts/action.rs

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
// SPDX-License-Identifier: MPL-2.0
22

3+
use std::str::FromStr;
4+
35
use serde::{Deserialize, Serialize};
46

57
/// An operation which may be bound to a keyboard shortcut.
@@ -180,7 +182,7 @@ pub enum System {
180182
}
181183

182184
/// Defines the direction of an operation
183-
#[derive(Copy, Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
185+
#[derive(Copy, Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize, Hash)]
184186
pub enum Direction {
185187
Left,
186188
Right,
@@ -200,6 +202,31 @@ impl std::ops::Not for Direction {
200202
}
201203
}
202204

205+
impl ToString for Direction {
206+
fn to_string(&self) -> String {
207+
match self {
208+
Direction::Left => "Left".to_string(),
209+
Direction::Right => "Right".to_string(),
210+
Direction::Up => "Up".to_string(),
211+
Direction::Down => "Down".to_string(),
212+
}
213+
}
214+
}
215+
216+
impl FromStr for Direction {
217+
type Err = String;
218+
219+
fn from_str(s: &str) -> Result<Self, Self::Err> {
220+
match s {
221+
"Down" => Ok(Self::Down),
222+
"Up" => Ok(Self::Up),
223+
"Left" => Ok(Self::Left),
224+
"Right" => Ok(Self::Right),
225+
_ => return Err(format!("String {} cannot be converted to direction.", s)),
226+
}
227+
}
228+
}
229+
203230
/// Defines the direction to focus towards
204231
#[derive(Copy, Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
205232
pub enum FocusDirection {

config/src/shortcuts/gesture.rs

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
// SPDX-License-Identifier: MPL-2.0
2+
use std::str::FromStr;
3+
4+
use serde::{Deserialize, Serialize};
5+
6+
use super::action::Direction;
7+
8+
/// Description of a gesture that can be handled by the compositor
9+
#[serde_with::serde_as]
10+
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, Hash)]
11+
#[serde(deny_unknown_fields)]
12+
pub struct Gesture {
13+
/// How many fingers are held down
14+
pub fingers: u32,
15+
pub direction: Direction,
16+
// A custom description for a custom binding
17+
#[serde(default, skip_serializing_if = "Option::is_none")]
18+
pub description: Option<String>,
19+
}
20+
21+
impl Gesture {
22+
/// Creates a new gesture from a number of fingers and a direction
23+
pub fn new(fingers: impl Into<u32>, direction: impl Into<Direction>) -> Gesture {
24+
Gesture {
25+
fingers: fingers.into(),
26+
direction: direction.into(),
27+
description: None,
28+
}
29+
}
30+
31+
/// Append the binding to an existing string
32+
pub fn to_string_in_place(&self, string: &mut String) {
33+
string.push_str(&format!(
34+
"{} Finger {}",
35+
self.fingers,
36+
self.direction.to_string()
37+
));
38+
}
39+
}
40+
41+
impl ToString for Gesture {
42+
fn to_string(&self) -> String {
43+
let mut string = String::new();
44+
self.to_string_in_place(&mut string);
45+
string
46+
}
47+
}
48+
49+
impl FromStr for Gesture {
50+
type Err = String;
51+
52+
fn from_str(value: &str) -> Result<Self, Self::Err> {
53+
let mut value_iter = value.split("+");
54+
let n = match value_iter.next() {
55+
Some(val) => val,
56+
None => {
57+
return Err(format!("no value for the number of fingers"));
58+
}
59+
};
60+
let fingers = match u32::from_str(n) {
61+
Ok(a) => a,
62+
Err(_) => {
63+
return Err(format!("could not parse number of fingers"));
64+
}
65+
};
66+
67+
let n2 = match value_iter.next() {
68+
Some(val) => val,
69+
None => {
70+
return Err(format!("could not parse direction"));
71+
}
72+
};
73+
74+
let direction = match Direction::from_str(n2) {
75+
Ok(dir) => dir,
76+
Err(e) => {
77+
return Err(e);
78+
}
79+
};
80+
81+
if let Some(n3) = value_iter.next() {
82+
return Err(format!("Extra data {} not expected", n3));
83+
}
84+
85+
return Ok(Self {
86+
fingers,
87+
direction,
88+
description: None,
89+
});
90+
}
91+
}
92+
93+
#[cfg(test)]
94+
mod tests {
95+
96+
use crate::shortcuts::action::Direction;
97+
98+
use super::Gesture;
99+
use std::str::FromStr;
100+
101+
#[test]
102+
fn binding_from_str() {
103+
assert_eq!(
104+
Gesture::from_str("3+Left"),
105+
Ok(Gesture::new(
106+
3 as u32,
107+
Direction::Left
108+
))
109+
);
110+
111+
assert_eq!(
112+
Gesture::from_str("5+Up"),
113+
Ok(Gesture::new(
114+
5 as u32,
115+
Direction::Up
116+
))
117+
);
118+
119+
assert_ne!(
120+
Gesture::from_str("4+Left+More+Info"),
121+
Ok(Gesture::new(
122+
4 as u32,
123+
Direction::Left
124+
))
125+
);
126+
}
127+
}

config/src/shortcuts/mod.rs

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,13 @@ pub use action::Action;
55

66
pub mod modifier;
77

8+
use action::Direction;
89
pub use modifier::{Modifier, Modifiers, ModifiersDef};
910

1011
mod binding;
12+
mod gesture;
1113
pub use binding::Binding;
14+
pub use gesture::Gesture;
1215

1316
pub mod sym;
1417

@@ -49,6 +52,31 @@ pub fn shortcuts(context: &cosmic_config::Config) -> Shortcuts {
4952
shortcuts
5053
}
5154

55+
/// Get the current system gesture configuration
56+
///
57+
/// Merges user-defined custom gestures to the system default config
58+
pub fn gestures(context: &cosmic_config::Config) -> Gestures {
59+
// Load gestures defined by the system.
60+
let mut gestures = context
61+
.get::<Gestures>("default_gestures")
62+
.unwrap_or_else(|why| {
63+
tracing::error!("shortcuts defaults config error: {why:?}");
64+
Gestures::default()
65+
});
66+
67+
// Load custom gestures defined by the user.
68+
let custom_gestures = context
69+
.get::<Gestures>("custom_gestures")
70+
.unwrap_or_else(|why| {
71+
tracing::error!("shortcuts custom config error: {why:?}");
72+
Gestures::default()
73+
});
74+
75+
// Combine while overriding system gestures.
76+
gestures.0.extend(custom_gestures.0);
77+
gestures
78+
}
79+
5280
/// Get a map of system actions and their configured commands
5381
pub fn system_actions(context: &cosmic_config::Config) -> SystemActions {
5482
let mut config = SystemActions::default();
@@ -80,6 +108,8 @@ pub fn system_actions(context: &cosmic_config::Config) -> SystemActions {
80108
pub struct Config {
81109
pub defaults: Shortcuts,
82110
pub custom: Shortcuts,
111+
pub default_gestures: Gestures,
112+
pub custom_gestures: Gestures,
83113
pub system_actions: SystemActions,
84114
}
85115

@@ -97,6 +127,18 @@ impl Config {
97127
.shortcut_for_action(action)
98128
.or_else(|| self.defaults.shortcut_for_action(action))
99129
}
130+
131+
pub fn gestures(&self) -> impl Iterator<Item = (&Gesture, &Action)> {
132+
self.custom_gestures
133+
.iter()
134+
.chain(self.default_gestures.iter())
135+
}
136+
137+
pub fn gesture_for_action(&self, action: &Action) -> Option<String> {
138+
self.custom_gestures
139+
.gesture_for_action(action)
140+
.or_else(|| self.default_gestures.gesture_for_action(action))
141+
}
100142
}
101143

102144
/// A map of defined key [Binding]s and their triggerable [Action]s
@@ -172,3 +214,49 @@ pub enum State {
172214
Pressed,
173215
Released,
174216
}
217+
218+
/// A map of defined [Gesture]s and their triggerable [Action]s
219+
#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
220+
#[serde(transparent)]
221+
pub struct Gestures(pub HashMap<Gesture, Action>);
222+
223+
impl Gestures {
224+
pub fn insert_default_gesture(
225+
&mut self,
226+
fingers: u32,
227+
direction: Direction,
228+
action: Action,
229+
) {
230+
if !self.0.values().any(|a| a == &action) {
231+
let pattern = Gesture {
232+
description: None,
233+
fingers,
234+
direction,
235+
};
236+
if !self.0.contains_key(&pattern) {
237+
self.0.insert(pattern, action.clone());
238+
}
239+
}
240+
}
241+
242+
pub fn iter(&self) -> impl Iterator<Item = (&Gesture, &Action)> {
243+
self.0.iter()
244+
}
245+
246+
pub fn iter_mut(&mut self) -> impl Iterator<Item = (&Gesture, &mut Action)> {
247+
self.0.iter_mut()
248+
}
249+
250+
pub fn gesture_for_action(&self, action: &Action) -> Option<String> {
251+
self.gestures(action)
252+
.next() // take the first one
253+
.map(|gesture| gesture.to_string())
254+
}
255+
256+
pub fn gestures<'a>(&'a self, action: &'a Action) -> impl Iterator<Item = &'a Gesture> {
257+
self.0
258+
.iter()
259+
.filter(move |(_, a)| *a == action)
260+
.map(|(b, _)| b)
261+
}
262+
}

0 commit comments

Comments
 (0)