Skip to content

Commit 1cf10ad

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 215762c commit 1cf10ad

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,6 +1,8 @@
11
// SPDX-License-Identifier: MPL-2.0
22
#![allow(deprecated)] // Derives on deprecated variants produce warnings...
33

4+
use std::str::FromStr;
5+
46
use serde::{Deserialize, Serialize};
57

68
/// An operation which may be bound to a keyboard shortcut.
@@ -199,7 +201,7 @@ pub enum System {
199201
}
200202

201203
/// Defines the direction of an operation
202-
#[derive(Copy, Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
204+
#[derive(Copy, Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize, Hash)]
203205
pub enum Direction {
204206
Left,
205207
Right,
@@ -219,6 +221,31 @@ impl std::ops::Not for Direction {
219221
}
220222
}
221223

224+
impl ToString for Direction {
225+
fn to_string(&self) -> String {
226+
match self {
227+
Direction::Left => "Left".to_string(),
228+
Direction::Right => "Right".to_string(),
229+
Direction::Up => "Up".to_string(),
230+
Direction::Down => "Down".to_string(),
231+
}
232+
}
233+
}
234+
235+
impl FromStr for Direction {
236+
type Err = String;
237+
238+
fn from_str(s: &str) -> Result<Self, Self::Err> {
239+
match s {
240+
"Down" => Ok(Self::Down),
241+
"Up" => Ok(Self::Up),
242+
"Left" => Ok(Self::Left),
243+
"Right" => Ok(Self::Right),
244+
_ => return Err(format!("String {} cannot be converted to direction.", s)),
245+
}
246+
}
247+
}
248+
222249
/// Defines the direction to focus towards
223250
#[derive(Copy, Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
224251
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
@@ -261,3 +303,49 @@ impl<'de> Deserialize<'de> for SystemActionsImpl {
261303
deserializer.deserialize_map(SystemActionsMapVisitor)
262304
}
263305
}
306+
307+
/// A map of defined [Gesture]s and their triggerable [Action]s
308+
#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
309+
#[serde(transparent)]
310+
pub struct Gestures(pub HashMap<Gesture, Action>);
311+
312+
impl Gestures {
313+
pub fn insert_default_gesture(
314+
&mut self,
315+
fingers: u32,
316+
direction: Direction,
317+
action: Action,
318+
) {
319+
if !self.0.values().any(|a| a == &action) {
320+
let pattern = Gesture {
321+
description: None,
322+
fingers,
323+
direction,
324+
};
325+
if !self.0.contains_key(&pattern) {
326+
self.0.insert(pattern, action.clone());
327+
}
328+
}
329+
}
330+
331+
pub fn iter(&self) -> impl Iterator<Item = (&Gesture, &Action)> {
332+
self.0.iter()
333+
}
334+
335+
pub fn iter_mut(&mut self) -> impl Iterator<Item = (&Gesture, &mut Action)> {
336+
self.0.iter_mut()
337+
}
338+
339+
pub fn gesture_for_action(&self, action: &Action) -> Option<String> {
340+
self.gestures(action)
341+
.next() // take the first one
342+
.map(|gesture| gesture.to_string())
343+
}
344+
345+
pub fn gestures<'a>(&'a self, action: &'a Action) -> impl Iterator<Item = &'a Gesture> {
346+
self.0
347+
.iter()
348+
.filter(move |(_, a)| *a == action)
349+
.map(|(b, _)| b)
350+
}
351+
}

0 commit comments

Comments
 (0)