apeirogond 0.15.1

Daemon for Apeirogon, a cross-platform software KVM
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
// SPDX-License-Identifier: GPL-3.0-or-later

use std::collections::BTreeMap;
use std::future::pending;
use std::time::Instant;

use a7n_core::focus::edge::{EdgeResistance, HeldButtons};
use a7n_core::focus::{Action, Cursor, Focus, Take};
use a7n_core::hotkey::HotkeyMatcher;
use a7n_core::input::{MotionCounter, MotionScale, MotionTracker, edge_push};
use a7n_platform::input::{Bounds, Capture, CaptureControl, Captured, Inject, Injector};
use a7n_proto::v1::{Edge, Envelope, InputBatch, envelope::Body, input_event::Event};
use a7n_proto::{MachineId, Route};
use tokio::sync::oneshot;

use super::{Daemon, DaemonError};

mod hotkeys;
mod landing;

use landing::landing_point;

pub(super) struct Input {
    pub(super) focus: Focus,
    pub(super) capture: Option<Capture>,
    pub(super) injector: Option<Injector>,
    pub(super) unavailable: Option<String>,
    pub(super) paused: bool,
    trace_keys: bool,
    counter: MotionCounter,
    tracker: MotionTracker,
    pub(super) scale: MotionScale,
    pub(super) modifier_remap: BTreeMap<u32, u32>,
    pub(super) hotkeys: HotkeyMatcher,
    resistance: EdgeResistance,
    buttons: HeldButtons,
    pub(super) failed: bool,
    lost: Vec<MachineId>,
    /// Outcome of waiting for input permissions at startup or after revocation.
    pub(super) retried: Option<oneshot::Receiver<Retried>>,
}

pub(crate) type Handles = (Capture, Injector);
/// Started input, or why it still cannot start once nothing is missing.
pub(crate) type Retried = Result<Handles, String>;

impl Input {
    pub(super) fn new(own: MachineId) -> Self {
        Self {
            focus: Focus::new(own),
            capture: None,
            injector: None,
            unavailable: None,
            paused: false,
            trace_keys: false,
            counter: MotionCounter::default(),
            tracker: MotionTracker::default(),
            scale: MotionScale::new(1.0),
            modifier_remap: BTreeMap::new(),
            hotkeys: HotkeyMatcher::new(a7n_ipc::config::Config::default().bindings()),
            resistance: EdgeResistance::new(0),
            buttons: HeldButtons::default(),
            failed: false,
            lost: Vec::new(),
            retried: None,
        }
    }

    pub(super) fn keepalive(&mut self) {
        if let Some(capture) = &self.capture {
            if matches!(
                capture.control.try_send(CaptureControl::Keepalive),
                Err(tokio::sync::mpsc::error::TrySendError::Closed(_))
            ) {
                self.closed();
            }
        }
    }

    pub(super) fn closed(&mut self) {
        if !self.failed {
            crate::log::event!("kind=input_backend_closed");
        }
        self.failed = true;
        self.unavailable = Some("input backend closed".to_owned());
    }

    pub(super) async fn grab(&mut self, grabbed: bool) {
        if let Some(capture) = &self.capture {
            if capture
                .control
                .send(CaptureControl::Grab(grabbed))
                .await
                .is_err()
            {
                self.closed();
            }
        }
    }

    fn trace_key(&self, event: &a7n_proto::v1::InputEvent) {
        if !self.trace_keys {
            return;
        }
        if let Some(a7n_proto::v1::input_event::Event::Key(key)) = &event.event {
            crate::log::event!("kind=trace_key usage=0x{:x} down={}", key.usage, key.down);
        }
    }

    async fn inject(&mut self, command: Inject) {
        if let Inject::Event(event) = &command {
            self.trace_key(event);
            if let Some(Event::Button(button)) = &event.event {
                self.buttons.apply(button);
            }
        }
        if let Some(injector) = &self.injector {
            if injector.commands.send(command).await.is_err() {
                self.closed();
            }
        }
    }
}

pub(super) async fn captured(capture: &mut Option<Capture>) -> Option<Captured> {
    match capture {
        Some(capture) => capture.events.recv().await,
        None => pending().await,
    }
}

/// Resolves once, when the retry task finishes or is dropped.
pub(super) async fn retried(retried: &mut Option<oneshot::Receiver<Retried>>) -> Option<Retried> {
    match retried {
        Some(receiver) => receiver.await.ok(),
        None => pending().await,
    }
}

pub(super) async fn feedback(injector: &mut Option<Injector>) -> Option<Captured> {
    match injector {
        Some(injector) => injector.pointer.recv().await,
        None => pending().await,
    }
}

pub(super) async fn deadline(deadline: Option<Instant>) {
    match deadline {
        Some(deadline) => tokio::time::sleep_until(deadline.into()).await,
        None => pending().await,
    }
}

impl Daemon {
    pub(crate) fn with_input_error(mut self, error: Option<String>) -> Self {
        self.input.unavailable = error;
        self
    }

    pub(crate) fn with_trace_input(mut self, enabled: bool) -> Self {
        self.input.trace_keys = enabled;
        self
    }

    pub(crate) fn with_input(mut self, handles: Option<Handles>) -> Self {
        if let Some(handles) = handles {
            self.attach_input(handles);
        }
        self
    }

    /// Input that could not start yet arrives here once its permissions are granted.
    pub(crate) fn with_input_retry(mut self, retried: oneshot::Receiver<Retried>) -> Self {
        self.input.retried = Some(retried);
        self
    }

    /// Takes the retry outcome; `None` means the task ended without one.
    pub(super) fn finish_input_retry(&mut self, retried: Option<Retried>) {
        self.input.retried = None;
        match retried {
            Some(Ok(handles)) => self.attach_input(handles),
            // The old reason named a permission that is granted by now.
            Some(Err(reason)) => self.input.unavailable = Some(reason),
            None => {}
        }
    }

    fn attach_input(&mut self, (capture, injector): Handles) {
        self.input.capture = Some(capture);
        self.input.injector = Some(injector);
        self.input.unavailable = None;
        self.input.failed = false;
    }

    pub(super) async fn retry_input_after_permission_loss(&mut self) {
        crate::log::event!("kind=input_permission_lost");
        let actions = self.input.focus.go_home();
        self.input_actions(actions).await;
        let peers: Vec<_> = self.links.by_peer.keys().copied().collect();
        for peer in peers {
            let actions = self.input.focus.deny_drive(peer);
            self.input_actions(actions).await;
        }
        self.input.grab(false).await;
        self.input.capture = None;
        self.input.injector = None;
        self.input.failed = false;
        self.input.unavailable = Some("input permissions missing".to_owned());
        let (handles, retried) = oneshot::channel();
        self.input.retried = Some(retried);
        crate::input_retry::spawn(handles);
    }

    pub(super) async fn shutdown_input(&mut self) {
        let peers: Vec<_> = self.links.by_peer.keys().copied().collect();
        for peer in peers {
            self.input_link_lost(peer);
        }
        self.flush_link_losses().await;
        self.input.grab(false).await;
    }

    pub(super) async fn poll_focus(&mut self) {
        let actions = self.input.focus.poll(now());
        self.input_actions(actions).await;
    }

    pub(super) fn input_link_lost(&mut self, peer: MachineId) {
        self.clipboard_link_down(peer);
        self.files_link_down(peer);
        self.input.lost.push(peer);
    }

    pub(super) async fn flush_link_losses(&mut self) {
        while let Some(peer) = self.input.lost.pop() {
            let actions = self.input.focus.on_link_lost(peer);
            self.input_actions(actions).await;
            self.sync_grab().await;
        }
    }

    pub(super) async fn sync_grab(&mut self) {
        self.input
            .grab(
                self.input.focus.is_driven()
                    || matches!(self.input.focus.cursor(), Cursor::Driving(_)),
            )
            .await;
    }

    pub(super) async fn input_actions(&mut self, actions: Vec<Action>) {
        for action in actions {
            match action {
                Action::Send { peer, body } => self.send_input(peer, body),
                Action::Release(events) => {
                    self.input.buttons.reset();
                    for event in events {
                        self.input.inject(Inject::Event(event)).await;
                    }
                }
                Action::Cursor(cursor) => {
                    self.input.buttons.reset();
                    if let Cursor::Driving(peer) = cursor {
                        self.input.counter.reset();
                        self.snapshot_remap(peer);
                    }
                    self.input.resistance = EdgeResistance::new(0);
                    self.sync_grab().await;
                }
                Action::Driven {
                    landing,
                    resistance_px,
                    ..
                } => {
                    self.input.buttons.reset();
                    self.input.tracker.reset();
                    self.input.scale = MotionScale::new(self.config.input.speed);
                    self.input.resistance = EdgeResistance::new(resistance_px);
                    self.sync_grab().await;
                    if let (Some(landing), Some(injector)) = (landing, &self.input.injector) {
                        let (x, y) = landing_point(injector.bounds, &landing);
                        self.input.inject(Inject::Warp { x, y }).await;
                    }
                }
            }
        }
    }

    pub(super) fn send_input(&mut self, peer: MachineId, body: Body) {
        let Some(handle) = self.links.by_peer.get(&peer) else {
            return;
        };
        if handle
            .sender
            .try_send(Envelope { body: Some(body) })
            .is_err()
        {
            handle.connection.close(0u32.into(), b"");
            self.links.by_peer.remove(&peer);
            self.input_link_lost(peer);
        }
    }

    pub(super) async fn receive_from(
        &mut self,
        peer: MachineId,
        envelope: Envelope,
    ) -> Result<(), DaemonError> {
        self.poll_focus().await;
        let actions = match &envelope.body {
            Some(Body::TransferRequest(request)) => {
                if !self.files_request(peer, request) {
                    self.clipboard_request(peer, request);
                }
                return Ok(());
            }
            Some(Body::ClipboardAnnounce(wire)) => {
                if wire.send {
                    self.receive_file_offer(peer, wire);
                } else {
                    self.receive_clipboard(peer, wire);
                }
                return Ok(());
            }
            Some(Body::TransferCancel(cancel)) => {
                self.files_cancel_from(peer, cancel.transfer_id);
                return Ok(());
            }
            Some(Body::Settings(settings)) => {
                if self.links.by_peer.get(&peer).is_some_and(|handle| {
                    handle
                        .capabilities
                        .contains(&a7n_proto::v1::Capability::SettingsSync)
                }) {
                    self.receive_settings(settings).await?;
                }
                return Ok(());
            }
            Some(Body::Focus(focus)) => {
                // Without an injector there is no backend that can honour a take.
                let allow_drive = self.allow_drive(peer);
                self.input.focus.on_focus(peer, focus, allow_drive, now())
            }
            Some(Body::Accept(accept)) => self.input.focus.on_accept(peer, accept),
            Some(Body::Accepts(accepts)) => self.input.focus.on_accepts(peer, accepts.accepts),
            Some(Body::Refuse(refuse)) => self.input.focus.on_refuse(peer, refuse),
            Some(Body::Handover(handover)) if !self.input.paused => {
                self.input.focus.on_handover(peer, handover, now())
            }
            Some(Body::Ack(ack)) => self.input.focus.on_ack(peer, ack),
            Some(Body::Motion(motion)) => {
                if self
                    .input
                    .focus
                    .on_remote_input(peer, Route(motion.route), now())
                {
                    let delta = self
                        .input
                        .tracker
                        .apply(motion.motion_seq, motion.x, motion.y);
                    self.inject_motion(delta).await;
                }
                return Ok(());
            }
            Some(Body::Input(batch)) => {
                self.receive_input(peer, batch).await;
                return Ok(());
            }
            _ => return self.receive(envelope),
        };
        self.input_actions(actions).await;
        self.sync_grab().await;
        Ok(())
    }

    async fn receive_input(&mut self, peer: MachineId, batch: &InputBatch) {
        let route = Route(batch.route);
        if !self.input.focus.on_remote_input(peer, route, now()) {
            return;
        }
        let delta = self
            .input
            .tracker
            .resync(batch.motion_seq, batch.motion_x, batch.motion_y);
        self.inject_motion(delta).await;
        for event in &batch.events {
            if self.input.focus.on_input_event(peer, route, event, now()) {
                self.input.inject(Inject::Event(event.clone())).await;
            }
        }
    }

    async fn inject_motion(&mut self, delta: Option<(i32, i32)>) {
        if let Some((dx, dy)) = delta {
            let (dx, dy) = self.input.scale.apply(dx, dy);
            self.input.inject(Inject::Motion { dx, dy }).await;
        }
    }

    pub(super) async fn captured(&mut self, event: Option<Captured>) {
        let Some(event) = event else {
            self.input.closed();
            return;
        };
        if let Captured::Input(input) = &event {
            self.input.trace_key(input);
        }
        self.poll_focus().await;
        if self.match_hotkey(&event).await {
            return;
        }
        if let Cursor::Driving(peer) = self.input.focus.cursor() {
            self.forward_capture(peer, event);
            return;
        }
        let was_driven = self.input.focus.is_driven();
        let (allowed, actions) = self.input.focus.on_local_input(now());
        self.input_actions(actions).await;
        if !allowed {
            return;
        }
        if let Captured::Input(input) = &event {
            if let Some(Event::Button(button)) = &input.event {
                self.input.buttons.apply(button);
            }
        }
        if was_driven {
            self.sync_grab().await;
            match event {
                Captured::Input(event) => self.input.inject(Inject::Event(event)).await,
                Captured::Pointer { dx, dy, .. } => {
                    self.input.inject(Inject::Motion { dx, dy }).await;
                }
            }
            return;
        }
        if let (Captured::Pointer { x, y, dx, dy }, Some(capture)) = (event, &self.input.capture) {
            self.cross_edge(capture.bounds, x, y, dx, dy, false).await;
        }
    }

    fn forward_capture(&mut self, peer: MachineId, event: Captured) {
        let Some(route) = self.input.focus.driving_route() else {
            return;
        };
        let body = match event {
            Captured::Pointer { dx, dy, .. } => {
                let mut motion = self.input.counter.push(dx, dy);
                motion.route = route.0;
                Body::Motion(motion)
            }
            Captured::Input(mut event) => {
                self.transform_input(&mut event);
                let motion = self.input.counter.current();
                // ponytail: one event per batch; coalesce when capture throughput needs it.
                Body::Input(InputBatch {
                    route: route.0,
                    seq: 0,
                    motion_seq: motion.motion_seq,
                    motion_x: motion.x,
                    motion_y: motion.y,
                    events: vec![event],
                })
            }
        };
        self.send_input(peer, body);
    }

    pub(super) async fn pointer_feedback(&mut self, event: Option<Captured>) {
        let Some(event) = event else {
            self.input.closed();
            return;
        };
        if !self.input.focus.is_driven() {
            return;
        }
        if let (Captured::Pointer { x, y, dx, dy }, Some(injector)) = (event, &self.input.injector)
        {
            self.cross_edge(injector.bounds, x, y, dx, dy, true).await;
        }
    }

    async fn cross_edge(&mut self, bounds: Bounds, x: i32, y: i32, dx: i32, dy: i32, driven: bool) {
        if self.input.buttons.any_held() {
            self.input.resistance.push(Edge::Unspecified, 0);
            return;
        }
        if self.input.paused || (!driven && self.input.focus.is_locked()) {
            return;
        }
        let Some((edge, overshoot, along)) = edge_push(
            (bounds.x, bounds.y, bounds.width, bounds.height),
            x,
            y,
            dx,
            dy,
        ) else {
            self.input.resistance.push(Edge::Unspecified, 0);
            return;
        };
        if !self.input.resistance.push(edge, overshoot) {
            return;
        }
        let Some((target, landing)) = self
            .layout
            .state
            .exit(self.identity.machine_id, edge, along)
        else {
            return;
        };
        let actions = if driven {
            self.wol.pending = None;
            self.input.focus.handover(target, Some(landing))
        } else {
            if !self.is_linked(target) {
                let _ = self.auto_wake(target, super::wol::WakeAction::Edge(landing), now());
                return;
            }
            self.wol.pending = None;
            self.input.focus.take(
                Take {
                    target,
                    landing: Some(landing),
                    resistance_px: 0,
                    reach: self.links.by_peer.keys().copied().collect(),
                },
                now(),
            )
        };
        self.input_actions(actions).await;
    }
}

// Tokio time also supports deterministic paused-time tests of the core's deadlines.
fn now() -> Instant {
    tokio::time::Instant::now().into_std()
}

#[cfg(test)]
mod tests;