xremap 0.15.7

Dynamic key remap for X and Wayland
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
use crate::client::WMClient;
use crate::config::expmap_operator::ExpmapOperator;
use crate::config::Expmap;
use crate::emit_handler::{Emit, EmitHandler};
use crate::event::Event;
use crate::event_handler::PRESS;
use crate::operator_double_tap::DoubleTapOperator;
use crate::operator_sim::SimOperator;
use crate::operators::{ActiveOperator, OperatorAction, OperatorEntry, StaticOperator};
use crate::timeout_manager::TimeoutManager;
use evdev::KeyCode as Key;
use std::collections::HashMap;
use std::rc::Rc;
use std::usize;

pub struct OperatorHandler {
    active: Vec<Box<dyn ActiveOperator>>,
    candidates: Option<Candidates>,
    lookup_map: HashMap<Key, Vec<OperatorEntry>>,
    emit_handler: EmitHandler,
}

/// Operators start matching when their start_key is pressed.
/// Operators remain candidates until there is only one candidate left,
/// and that operator then becomes active, and is placed as the right-most operator.
/// Operators are given events from the left first, and can choose to emit to the next
/// operator or to the standard modmap.
/// The logic is:
///   1. Try all active operators in the order they ware activated.
///   2. Try all candidates. They have no order, and there's no active operators after
///      the candidates.
///   3. Lookup operators that have the keypress as start_key.
///   4. Let the event go to next level.
///
/// Candidates are needed to handle two operators like: Simultaneous(A,B) and Simultaneous(A,C). It's
/// not possible to determine which mapping to choose, when A is pressed. So the events
/// must be buffered until it's known which operator should handle the event.
///
/// Active operators are needed to handle Simultaneous(A,B) -> 1. The events 'ABaAbB' has an overlap
/// where the first operator handles the first part 'ABaAb' -> (1,A), and the second operator
/// handles the last part 'AB'. If operators were only static, then it would be more complicated
/// because they would have to keep track of the whether 'b' should be squashed or let through.
impl OperatorHandler {
    pub fn new(experimental_map: &Vec<Expmap>, timeout_manager: Rc<TimeoutManager>) -> OperatorHandler {
        let mut lookup_map: HashMap<Key, Vec<OperatorEntry>> = HashMap::new();

        for expmap in experimental_map {
            for chord in &expmap.chords {
                let operators = SimOperator {
                    keys: chord.keys.clone(),
                    actions: chord.actions.clone(),
                    timeout: chord.timeout,
                    timeout_manager: timeout_manager.clone(),
                }
                .get_operators();
                for (key, operator) in operators {
                    let entry = OperatorEntry {
                        operator,
                        application: expmap.application.clone(),
                        title: expmap.window.clone(),
                    };
                    match lookup_map.get_mut(&key) {
                        Some(current) => {
                            current.push(entry);
                        }
                        None => {
                            lookup_map.insert(key, vec![entry]);
                        }
                    };
                }
            }

            for (key, op) in &expmap.remap {
                let operators = match op {
                    ExpmapOperator::DoubleTap(dbltap) => DoubleTapOperator {
                        key: key.clone(),
                        actions: dbltap.actions.clone(),
                        timeout: dbltap.timeout,
                        timeout_manager: timeout_manager.clone(),
                    },
                }
                .get_operators();
                for (key, operator) in operators {
                    let entry = OperatorEntry {
                        operator,
                        application: expmap.application.clone(),
                        title: expmap.window.clone(),
                    };
                    match lookup_map.get_mut(&key) {
                        Some(current) => {
                            current.push(entry);
                        }
                        None => {
                            lookup_map.insert(key, vec![entry]);
                        }
                    };
                }
            }
        }

        OperatorHandler {
            active: vec![],
            candidates: None,
            lookup_map,
            emit_handler: EmitHandler::new(),
        }
    }

    #[cfg(test)]
    pub fn assert_base_state(&self) {
        assert!(self.active.is_empty());
        assert!(self.candidates.is_none());
    }

    #[cfg(test)]
    pub fn assert_emitted_modifiers_are_synced(&self) {
        self.emit_handler.assert_emitted_modifiers_are_synced();
    }

    #[cfg(test)]
    pub fn map_evs(&mut self, events: Vec<Event>) -> Vec<Event> {
        let mut wmclient = WMClient::new("none", Box::new(crate::client::null_client::NullClient), false);
        self.map_events(events, &mut wmclient)
    }

    pub fn map_events(&mut self, events: Vec<Event>, wmclient: &mut WMClient) -> Vec<Event> {
        events
            .into_iter()
            .flat_map(|event| {
                self.emit_handler.on_event(&event);

                let events = process_event(event, &mut self.active, &mut self.candidates, &self.lookup_map, wmclient);

                self.emit_handler.map_output(events)
            })
            .collect()
    }
}

#[derive(Debug)]
enum CandidateState {
    Canceled,
    Done,
    Matching,
}

#[derive(Debug)]
struct Candidate {
    operator: Box<dyn ActiveOperator>,
    state: CandidateState,
    emitted: Vec<Emit>,
    unhandled: Vec<Event>,
}

#[derive(Debug)]
struct Candidates {
    // start_key and events are given to the candidates, and buffered here
    // in case all candidates cancel.
    start_event: Event,
    events: Vec<Event>,
    operators: Vec<Candidate>,
}

// Nodes that exist on the stack, that still needs to be processed.
enum Node {
    Event(Event),
    Operator(Box<dyn ActiveOperator>),
    CandidateChosen(usize),
    CandidatesCanceled,
}

// The point that is being processed is in the middle of the left-stack and the right-operators.
// Candidates only exist if there is no right-operators.
// The right-most event is always processed first. This is also true for the events emitted during
// processing.
fn process_event(
    event: Event,
    right: &mut Vec<Box<dyn ActiveOperator>>,
    candidates: &mut Option<Candidates>,
    lookup_map: &HashMap<Key, Vec<OperatorEntry>>,
    wmclient: &mut WMClient,
) -> Vec<Emit> {
    // The events that have passed fully through the operators.
    let mut emit: Vec<Emit> = vec![];
    // The stack, that still needs processing.
    let mut left: Vec<Node> = vec![Node::Event(event)];

    loop {
        match left.pop() {
            Some(Node::Event(event)) => {
                match right.pop() {
                    // Map the event with the operator to the right.
                    Some(mut operator) => match operator.on_event(&event) {
                        OperatorAction::Undecided => {
                            right.push(operator);
                        }
                        OperatorAction::Cancel => {
                            unreachable!()
                        }
                        OperatorAction::Unhandled => {
                            // Move operator one to the left
                            left.push(Node::Operator(operator));
                            left.push(Node::Event(event));
                        }
                        OperatorAction::Partial(emitted, unhandled) => {
                            // Leave operator where it is.
                            right.push(operator);
                            emit.extend(emitted);

                            unhandled_back_to_stack(unhandled, &mut left);
                        }
                        OperatorAction::Done(new_emit, unhandled) => {
                            // Implicitly drops operator
                            emit.extend(new_emit);
                            unhandled_back_to_stack(unhandled, &mut left);
                        }
                    },

                    // No more operators
                    None => {
                        match candidates {
                            Some(candidates) => try_candidates(event, &mut left, candidates),
                            None => static_lookup(event, candidates, &lookup_map, &mut emit, wmclient),
                        };
                    }
                };
            }

            Some(Node::Operator(operator)) => {
                right.push(operator);
            }

            Some(Node::CandidateChosen(chosen)) => {
                let candidate = candidates.take().unwrap().operators.into_iter().nth(chosen).unwrap();

                emit.extend(candidate.emitted);

                if !matches!(candidate.state, CandidateState::Done) {
                    right.push(candidate.operator);
                }

                unhandled_back_to_stack(candidate.unhandled, &mut left);
            }

            Some(Node::CandidatesCanceled) => {
                let taken = candidates.take().unwrap();

                // start_key didn't match anything, so emit.
                emit.push(Emit::Single(taken.start_event.clone()));
                // Start over with the next event.
                unhandled_back_to_stack(taken.events, &mut left);
            }

            None => {
                // No more nodes to process, so all events have gone through the pipeline.
                return emit;
            }
        };
    }
}

fn unhandled_back_to_stack(events: Vec<Event>, nodes: &mut Vec<Node>) {
    nodes.extend(
        events
            .iter()
            .rev()
            .map(|event| Node::Event(event.clone()))
            .collect::<Vec<_>>(),
    );
}

fn try_candidates(event: Event, left: &mut Vec<Node>, candidates: &mut Candidates) {
    candidates.events.push(event.clone());

    let mut first = true;

    for (usize, candidate) in candidates.operators.iter_mut().enumerate() {
        match candidate.state {
            CandidateState::Canceled => {
                continue;
            }
            CandidateState::Done => {
                if first {
                    if !matches!(event, Event::Tick) {
                        todo!()
                    }
                    candidate.unhandled.push(event.clone());

                    left.push(Node::CandidateChosen(usize));
                    return;
                } else {
                    candidate.unhandled.push(event.clone());
                }
            }
            CandidateState::Matching => {
                match candidate.operator.on_event(&event) {
                    OperatorAction::Undecided => {
                        first = false;
                    }
                    OperatorAction::Cancel => {
                        candidate.state = CandidateState::Canceled;
                    }
                    OperatorAction::Unhandled => {
                        candidate.unhandled.push(event.clone());

                        if first {
                            left.push(Node::CandidateChosen(usize));
                            return;
                        }
                    }
                    OperatorAction::Partial(new_emit, unhandled) => {
                        candidate.emitted.extend(new_emit);
                        candidate.unhandled.extend(unhandled);

                        if first {
                            left.push(Node::CandidateChosen(usize));
                            return;
                        }
                    }
                    OperatorAction::Done(new_emit, unhandled) => {
                        candidate.emitted.extend(new_emit);
                        candidate.unhandled.extend(unhandled);
                        candidate.state = CandidateState::Done;

                        if first {
                            left.push(Node::CandidateChosen(usize));
                            return;
                        }
                    }
                };
            }
        };
    }

    if first {
        // all canceled
        left.push(Node::CandidatesCanceled);
    }
}

fn static_lookup(
    event: Event,
    candidates: &mut Option<Candidates>,
    lookup_map: &HashMap<Key, Vec<OperatorEntry>>,
    emit: &mut Vec<Emit>,
    wmclient: &mut WMClient,
) {
    let (device, key_event) = match &event {
        Event::KeyEvent(device, key_event) => (device, key_event),
        Event::Tick => {
            // Ignore, because static operators can't be triggered by timeout.
            return;
        }
        _ => {
            emit.push(Emit::Single(event));
            return;
        }
    };

    if key_event.value() != PRESS {
        emit.push(Emit::key_event(device.clone(), key_event.clone()));
        return;
    }

    // Static operators
    match lookup_map.get(&key_event.key) {
        Some(entries) => {
            debug_assert!(!entries.is_empty());
            debug_assert!(candidates.is_none());

            let new_candidates: Vec<_> = entries
                .iter()
                .filter(|entry| {
                    if let Some(window_matcher) = &entry.title {
                        if !wmclient.match_window(window_matcher) {
                            return false;
                        }
                    }

                    if let Some(application_matcher) = &entry.application {
                        if !wmclient.match_application(application_matcher) {
                            return false;
                        }
                    }

                    true
                })
                .map(|entry| Candidate {
                    operator: entry.operator.get_active_operator(&event),
                    state: CandidateState::Matching,
                    emitted: vec![],
                    unhandled: vec![],
                })
                .collect();

            candidates.replace(Candidates {
                start_event: event,
                events: vec![],
                operators: new_candidates,
            });
        }
        None => {
            emit.push(Emit::key_event(device.clone(), key_event.clone()));
        }
    };
}