anybox-rs 0.11.0

one API for the most popular passthrough boxes
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
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
use std::any::Any;
use std::collections::HashSet;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};

use crate::backend::{
    Backend, Command, InputKind, InputKinds, LOCKED, LockSlot, Sign, Sink, StreamFailure, Typing,
    UNLOCKED, Usage, WRITE_DEADLINE,
};
use crate::capability::{
    Action, Axis, Button, Capabilities, Capability, Family, Firmware, Info, Quirk, Snapshot,
    YscAction,
};
use crate::error::{Error, Result};
use crate::extension::{
    Extension, ExtensionReply, YscInterpolation, YscInterpolationSettings, YscProfile, YscSerial,
};
use crate::transport::link::{Link, Target};
use crate::transport::probe::Probe;
use crate::transport::{Candidate, Port, System, is_ysc};

mod frames;
use frames::YscFrames;

const BAUD: u32 = 115_200;
/// the vendor driver's own order for finding a V1's rate, read out of its auto detect
const V1_BAUDS: [u32; 9] = [
    4_000_000, 115_200, 3_000_000, 230_400, 2_000_000, 460_800, 1_500_000, 921_600, 1_000_000,
];
/// how long the vendor driver waits for a V1's answer at each rate
const V1_WAIT: Duration = Duration::from_millis(200);
const BOOTLOADER: &str = "the YSC box is in its bootloader, finish or leave the firmware update in the vendor tool and connect again";
const KEYBOARD: &str =
    "the YSC box says there's no keyboard behind it, so plug one in and connect again";
const MEDIA: &str = "YSC has no media keys";
/// how often cmd 48 asks whether the box is done typing, the vendor's own recipe polls at this rate
const TYPE_POLL: Duration = Duration::from_millis(20);
const BUTTONS: [Button; 5] = [
    Button::Left,
    Button::Right,
    Button::Middle,
    Button::Side1,
    Button::Side2,
];

fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(PoisonError::into_inner)
}

/// the single chip box behind a USB serial bridge, or the dual chip one on its own CDC ports
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Variant {
    V1,
    V2,
}

/// a V2 only gets anything on its left port. any other port is taken as a V1, the connect code only lets a YSC
/// probe there when the caller asked for a YSC
fn guard(candidate: &Candidate) -> Result<Variant> {
    let Some(usb) = candidate.usb.as_ref().filter(|usb| is_ysc(usb)) else {
        return Ok(Variant::V1);
    };
    match usb.serial.as_deref() {
        Some("TOWMCULEFT") => return Ok(Variant::V2),
        Some(role @ ("TOWMCURIGHT" | "TOWMCUIAP")) => {
            return Err(Error::Unsupported {
                action: Action::Connect,
                family: Family::Ysc,
                reason: format!("this is the {role} port, use the TOWMCULEFT port instead").into(),
            });
        }
        _ => {}
    }
    Err(Error::NotFound {
        tried: vec![candidate.path.display().to_string()],
    })
}

fn packet(payload: &str) -> Result<Vec<u8>> {
    frames::json(payload).ok_or(Error::InvalidArgument {
        action: Action::Connect,
        detail: "the YSC JSON payload must have 1 to 4096 bytes".into(),
    })
}

fn line(text: &str) -> Vec<u8> {
    format!("{text}\r\n").into_bytes()
}

fn version(variant: Variant, frame: &[u8]) -> Option<String> {
    match variant {
        Variant::V1 => frames::v1_version(frame),
        Variant::V2 => frames::version(frame),
    }
}

fn describe(probe: &Probe<'_>, reconnect: bool, variant: Variant) -> Result<Snapshot> {
    let budget = match (variant, reconnect) {
        (Variant::V1, _) => V1_WAIT,
        (Variant::V2, true) => WRITE_DEADLINE,
        (Variant::V2, false) => Duration::from_millis(1500),
    };
    let reply = probe.ask(
        &packet("{\"cmd\":132}")?,
        &mut YscFrames::probe(),
        |frame| {
            version(variant, frame).is_some()
                || (variant == Variant::V1 && frames::bootloader(frame))
        },
        budget,
    )?;
    if variant == Variant::V1 && reply.as_deref().is_some_and(frames::bootloader) {
        return Err(Error::Unsupported {
            action: Action::Connect,
            family: Family::Ysc,
            reason: BOOTLOADER.into(),
        });
    }
    let version = reply
        .as_deref()
        .and_then(|frame| version(variant, frame))
        .ok_or(Error::NotFound { tried: Vec::new() })?;
    let debug_budget = if reconnect {
        WRITE_DEADLINE
    } else {
        Duration::from_millis(1200)
    };
    let status = probe.ask(
        &packet("{\"cmd\":702}")?,
        &mut YscFrames::probe(),
        |frame| frames::debug(frame).is_some(),
        debug_budget,
    )?;
    if status.as_deref().and_then(frames::debug) == Some(true) {
        return Err(Error::Rejected { action: Action::Connect, detail: "the YSC box is in debug mode, leave debug mode in the vendor tool and connect again".into() });
    }
    probe.say(&packet("{\"cmd\":34,\"status\":0}")?)?;
    // no echo means every text command after it would time out. it's asked twice because the vendor tool can turn
    // echo off, and then only the second one comes back
    let mut echoed = false;
    for _ in 0..2 {
        echoed = probe
            .ask(
                &line("km.echo(1)"),
                &mut YscFrames::probe(),
                |frame| frame.starts_with(b"km.echo(1)\r\n"),
                WRITE_DEADLINE,
            )?
            .is_some();
        if echoed {
            break;
        }
    }
    if !echoed {
        return Err(Error::Rejected {
            action: Action::Connect,
            detail: "the YSC box answers but ignores its text commands, which it's been seen doing after a replug. turning debug mode on and off in the vendor tool fixed it once, so try that and connect again".into(),
        });
    }
    Ok(snapshot(version, variant))
}

pub(crate) fn open(candidate: &Candidate, sink: Sink) -> Result<(Box<dyn Backend>, Snapshot)> {
    let (backend, snapshot) = attach(Arc::new(crate::transport::os::OsSystem), candidate, sink)?;
    Ok((Box::new(backend), snapshot))
}

pub(crate) fn attach(
    system: Arc<dyn System>,
    candidate: &Candidate,
    sink: Sink,
) -> Result<(YscBackend, Snapshot)> {
    let stop = AtomicBool::new(false);
    if guard(candidate)? == Variant::V2 {
        let port = system.open(&candidate.path, BAUD)?;
        let snapshot = describe(&Probe::new(&*port, &stop), false, Variant::V2)?;
        return start(
            system,
            port,
            candidate,
            snapshot,
            Variant::V2,
            vec![BAUD],
            sink,
        );
    }
    // only when no rate opens at all, the driver's error says more than NotFound
    let mut opened = false;
    let mut refused = None;
    for &baud in &V1_BAUDS {
        let port = match system.open(&candidate.path, baud) {
            Ok(port) => {
                opened = true;
                port
            }
            // a bridge whose driver doesn't take this rate can still take the next one
            Err(error @ Error::Io(_)) => {
                refused.get_or_insert(error);
                continue;
            }
            Err(error) => return Err(error),
        };
        match describe(&Probe::new(&*port, &stop), false, Variant::V1) {
            Ok(snapshot) => {
                // a reconnect tries the rate that worked first, then the rest in the vendor's order
                let bauds = std::iter::once(baud)
                    .chain(V1_BAUDS.into_iter().filter(|&other| other != baud))
                    .collect();
                return start(system, port, candidate, snapshot, Variant::V1, bauds, sink);
            }
            Err(Error::NotFound { .. }) => {}
            Err(error) => return Err(error),
        }
    }
    if !opened && let Some(error) = refused {
        return Err(error);
    }
    Err(Error::NotFound {
        tried: vec![candidate.path.display().to_string()],
    })
}

fn start(
    system: Arc<dyn System>,
    port: Box<dyn Port>,
    candidate: &Candidate,
    snapshot: Snapshot,
    variant: Variant,
    bauds: Vec<u32>,
    sink: Sink,
) -> Result<(YscBackend, Snapshot)> {
    let shared = Arc::new(Shared::new(snapshot.clone()));
    let reprobe = {
        let shared = shared.clone();
        Box::new(move |probe: &Probe<'_>| {
            let snapshot = describe(probe, true, variant)?;
            // a key write that's half recorded would land in the old history and survive the reset
            let _requests = lock(&shared.requests);
            let mut state = lock(&shared.state);
            let held_keys = std::mem::take(&mut state.held_keys);
            *state = State::new(snapshot.clone());
            state.held_keys = held_keys;
            Ok(snapshot)
        })
    };
    let link = Arc::new(Link::start(
        system,
        port,
        Box::new(YscFrames::new(shared.clone(), Some(sink.clone()))),
        Target {
            family: Family::Ysc,
            path: candidate.path.clone(),
            usb: candidate.usb.clone(),
            id: None,
            bauds,
        },
        reprobe,
        sink,
    )?);
    Ok((YscBackend { shared, link }, snapshot))
}

fn snapshot(version: String, variant: Variant) -> Snapshot {
    let mut info = Info::new(Family::Ysc);
    info.model = Some(
        match variant {
            Variant::V1 => "YSC 8K V1",
            Variant::V2 => "YSC 8K V2",
        }
        .into(),
    );
    info.firmware = Some(Firmware::Text(version));
    let capabilities = Capabilities::new(BUTTONS.to_vec())
        .with_axes(vec![Axis::X, Axis::Y])
        .set(Action::Move, Capability::native())
        .set(Action::Press, Capability::native())
        .set(Action::Release, Capability::native())
        .set(
            Action::Wheel,
            Capability::native().with(Quirk::NotchesPerCommand(1)),
        )
        .set(Action::LockButton, Capability::native())
        .set(
            Action::LockAxis,
            Capability::native().with(Quirk::WholeAxisOnly),
        )
        .set(Action::ButtonEvents, Capability::native())
        .set(Action::MotionEvents, Capability::native())
        .set(Action::KeyPress, Capability::native())
        .set(Action::KeyRelease, Capability::native())
        .set(Action::KeyEvents, Capability::native())
        .set(
            Action::MoveNow,
            Capability::unsupported("YSC has no move that skips ahead of the others"),
        )
        .set(
            Action::DiscardPendingMoves,
            Capability::unsupported("YSC can't drop moves it already took"),
        )
        .set(
            Action::Pan,
            Capability::unsupported("YSC has no horizontal scroll command"),
        )
        .set(
            Action::ScaleAxis,
            Capability::unsupported("YSC can only block a whole axis, not scale it"),
        )
        .set(
            Action::LockKey,
            Capability::unsupported("YSC has no way to lock a key"),
        )
        .set(
            Action::ForceReleaseKey,
            Capability::unsupported("YSC has no way to mask a key"),
        )
        .set(Action::TypeText, Capability::native())
        // nothing documents what a firmware without them answers, so they stay on and a box that never answers
        // is a missed reply
        .set(Action::Ysc(YscAction::Interpolation), Capability::native())
        .set(Action::Ysc(YscAction::Serial), Capability::native())
        .set(
            Action::KeyChord,
            Capability::unsupported(
                "YSC presses keys one at a time, so it can't press several with one command",
            ),
        );
    let no_media = Capability::unsupported(MEDIA);
    let capabilities = [
        Action::MediaPress,
        Action::MediaRelease,
        Action::MediaTap,
        Action::MediaEvents,
    ]
    .into_iter()
    .fold(capabilities, |capabilities, action| {
        capabilities.set(action, no_media.clone())
    });
    Snapshot::new(info, capabilities)
}

struct State {
    snapshot: Snapshot,
    seen: frames::Seen,
    streams: InputKinds,
    keys: bool,
    held_keys: HashSet<crate::key::Key>,
    /// what kinds of key command went out on this connection, since a refusal doesn't say which one it's for
    pressed_keys: bool,
    released_keys: bool,
    refused: bool,
}

impl State {
    fn new(snapshot: Snapshot) -> Self {
        Self {
            snapshot,
            seen: frames::Seen::default(),
            streams: InputKinds::default(),
            keys: true,
            held_keys: HashSet::new(),
            pressed_keys: false,
            released_keys: false,
            refused: false,
        }
    }
}

struct Shared {
    state: Mutex<State>,
    requests: Mutex<()>,
    stop: AtomicBool,
}

impl Shared {
    fn new(snapshot: Snapshot) -> Self {
        Self {
            state: Mutex::new(State::new(snapshot)),
            requests: Mutex::new(()),
            stop: AtomicBool::new(false),
        }
    }
}

pub(crate) struct YscBackend {
    shared: Arc<Shared>,
    link: Arc<Link>,
}

fn button_name(button: Button) -> Option<&'static str> {
    Some(match button {
        Button::Left => "left",
        Button::Right => "right",
        Button::Middle => "middle",
        Button::Side1 => "ms1",
        Button::Side2 => "ms2",
        _ => return None,
    })
}

fn lock_name(slot: LockSlot) -> Option<&'static str> {
    Some(match slot {
        LockSlot::Button(Button::Left) => "ml",
        LockSlot::Button(Button::Right) => "mr",
        LockSlot::Button(Button::Middle) => "mm",
        LockSlot::Button(Button::Side1) => "ms1",
        LockSlot::Button(Button::Side2) => "ms2",
        LockSlot::Axis(Axis::X, _) => "mx",
        LockSlot::Axis(Axis::Y, _) => "my",
        _ => return None,
    })
}

impl YscBackend {
    fn unsupported(&self, action: Action, reason: &'static str) -> Error {
        Error::Unsupported {
            action,
            family: Family::Ysc,
            reason: reason.into(),
        }
    }

    fn send_until(&self, command: Command, until: Instant) -> Result<()> {
        let _request = lock(&self.shared.requests);
        let action = command.action();
        if let Command::KeyPress(key) | Command::KeyRelease(key) = command {
            if !key.is_valid() {
                return Err(Error::InvalidArgument {
                    action,
                    detail: "YSC keys have to be HID usages from 0x04 to 0xE7".into(),
                });
            }
            let down = matches!(command, Command::KeyPress(_));
            {
                let mut state = lock(&self.shared.state);
                if !state.keys && (down || !state.held_keys.contains(&key)) {
                    return Err(self.unsupported(action, KEYBOARD));
                }
                // a refusal doesn't say which key it's for, so even a cleanup release could be what it's about
                if down {
                    state.pressed_keys = true;
                } else {
                    state.released_keys = true;
                }
                if down {
                    state.held_keys.insert(key);
                }
            }
            let sent = self
                .link
                .request_until(
                    packet(&format!(
                        "{{\"cmd\":45,\"kc\":{},\"down\":{}}}",
                        key.0,
                        u8::from(down)
                    ))?,
                    // the box chokes on writes that come right after one another, so each key waits for its answer
                    Some(frames::key_reply()),
                    until,
                )
                .and_then(|reply| match reply.as_deref().and_then(frames::object) {
                    Some(value)
                        if value.get("code").and_then(serde_json::Value::as_u64) == Some(400) =>
                    {
                        Err(Error::Rejected {
                            action,
                            detail: "the YSC box couldn't read the key command, try it again"
                                .into(),
                        })
                    }
                    _ => Ok(()),
                });
            if sent.is_ok() && !down {
                lock(&self.shared.state).held_keys.remove(&key);
            }
            return sent;
        }
        let text = match command {
            Command::Move(dx, dy) => format!("km.move({dx},{dy})"),
            Command::Press(button) | Command::Release(button) => {
                let name = button_name(button)
                    .ok_or_else(|| self.unsupported(action, "YSC has five mouse buttons"))?;
                format!(
                    "km.{name}({})",
                    u8::from(matches!(command, Command::Press(_)))
                )
            }
            Command::Wheel(0) => return Ok(()),
            Command::Wheel(notches) if (-1..=1).contains(&notches) => {
                format!("km.wheel({notches})")
            }
            Command::Lock { slot, keep } if keep == LOCKED || keep == UNLOCKED => {
                let name = lock_name(slot).ok_or_else(|| {
                    self.unsupported(action, "YSC only locks buttons and whole X or Y axes")
                })?;
                // the core pairs whole-axis slots, the positive slot carries the lock and either can clean it up
                if matches!(slot, LockSlot::Axis(_, Sign::Negative)) && keep == LOCKED {
                    return Ok(());
                }
                format!("km.lock_{name}({})", u8::from(keep == LOCKED))
            }
            _ => {
                return Err(
                    self.unsupported(action, "YSC has no common command for this operation")
                );
            }
        };
        self.link
            .request_until(line(&text), Some(frames::key(text.as_bytes())), until)
            .map(|_| ())
    }

    /// cmd 52, what the box reads back. a field it didn't send stays none
    fn interpolation(&self, until: Instant) -> Result<YscInterpolation> {
        let action = Action::Ysc(YscAction::Interpolation);
        let data = self.ask("{\"cmd\":52}", "interp", action, until)?;
        let number = |name: &str| {
            data.get(name)
                .and_then(|value| value.as_u64().or_else(|| value.as_bool().map(u64::from)))
        };
        // the measured interval can be a fraction of a ms, the vendor's own example has 0.5
        let ms = |name: &str| {
            data.get(name)
                .and_then(serde_json::Value::as_f64)
                .and_then(|ms| Duration::try_from_secs_f64(ms / 1000.0).ok())
        };
        let (Some(enabled), Some(profile)) = (number("enabled"), number("profile")) else {
            return Err(Error::Rejected {
                action,
                detail: "it answered without saying whether interpolation is on".into(),
            });
        };
        Ok(YscInterpolation {
            enabled: enabled != 0,
            profile: YscProfile::from_number(u32::try_from(profile).unwrap_or(u32::MAX)),
            window: ms("window"),
            max_window: ms("maxw"),
            measured_interval: ms("ema"),
        })
    }

    /// sends one JSON command and returns the data of its answer, which has to carry `message`. a 400 is the box
    /// failing to read it
    fn ask(
        &self,
        payload: &str,
        message: &str,
        action: Action,
        until: Instant,
    ) -> Result<serde_json::Value> {
        let reply = self
            .link
            .request_until(packet(payload)?, Some(frames::key_reply()), until)?;
        let value = reply
            .as_deref()
            .and_then(frames::object)
            .ok_or(Error::Disconnected)?;
        let code = value.get("code").and_then(serde_json::Value::as_u64);
        if code == Some(200)
            && value.get("message").and_then(serde_json::Value::as_str) == Some(message)
        {
            // read like every other data, as an object or as JSON inside a string
            return Ok(frames::data(&value).unwrap_or_default());
        }
        Err(Error::Rejected {
            action,
            detail: format!("it answered {value} instead"),
        })
    }

    /// a cmd 47 or 48 reply, anything but a 200 is an error
    fn typing_reply(&self, reply: Option<&[u8]>) -> Result<serde_json::Value> {
        let value = reply.and_then(frames::object).ok_or(Error::Disconnected)?;
        match value.get("code").and_then(serde_json::Value::as_u64) {
            Some(200) => Ok(value),
            Some(404) => Err(self.unsupported(Action::TypeText, KEYBOARD)),
            Some(409) => Err(Error::Rejected {
                action: Action::TypeText,
                detail: "the YSC box is already typing something else".into(),
            }),
            _ => Err(Error::Rejected {
                action: Action::TypeText,
                detail: "the YSC box couldn't read the text".into(),
            }),
        }
    }

    fn upload(&self, on: bool, until: Instant) -> Result<()> {
        self.link
            .request_until(
                packet(&format!("{{\"cmd\":34,\"status\":{}}}", u8::from(on)))?,
                None,
                until,
            )
            .map(|_| ())
    }
}

impl Backend for YscBackend {
    fn send(&self, command: Command) -> Result<()> {
        self.send_until(command, Instant::now() + WRITE_DEADLINE)
    }

    fn set_streams(&self, kinds: InputKinds) -> std::result::Result<(), StreamFailure> {
        let result = (|| {
            let _request = lock(&self.shared.requests);
            if kinds.media {
                return Err(self.unsupported(Action::MediaEvents, MEDIA));
            }
            // the box sends its keyboard report by itself, so only buttons and motion have a switch
            let current = lock(&self.shared.state).streams;
            if (current.buttons || current.motion) != (kinds.buttons || kinds.motion) {
                self.upload(
                    kinds.buttons || kinds.motion,
                    Instant::now() + WRITE_DEADLINE,
                )?;
                lock(&self.shared.state).seen.buttons = None;
            }
            lock(&self.shared.state).streams = kinds;
            Ok(())
        })();
        result.map_err(|error| StreamFailure {
            failed: kinds,
            error,
        })
    }

    fn restart_stream(&self, kind: InputKind) -> Result<()> {
        let _request = lock(&self.shared.requests);
        match kind {
            InputKind::Media => return Err(self.unsupported(Action::MediaEvents, MEDIA)),
            InputKind::Keys => return Ok(()),
            InputKind::Buttons | InputKind::Motion => {}
        }
        let streams = lock(&self.shared.state).streams;
        if streams.buttons || streams.motion {
            lock(&self.shared.state).seen.buttons = None;
            self.upload(true, Instant::now() + WRITE_DEADLINE)?;
        }
        Ok(())
    }

    /// cmd 47 with the piece, then cmd 48 until the box isn't busy any more, the vendor's own recipe for text
    /// in chunks. every request waits for its answer, so the requests lock keeps a key or another text out
    fn type_piece(&self, piece: &[u8], typing: &mut Typing) -> Result<()> {
        let until = Instant::now() + WRITE_DEADLINE;
        let _request = lock(&self.shared.requests);
        {
            let mut state = lock(&self.shared.state);
            if !state.keys {
                return Err(self.unsupported(Action::TypeText, KEYBOARD));
            }
            // a no_keyboard refusal after this can't be told apart from one for a key
            state.pressed_keys = true;
            state.released_keys = true;
        }
        let text = String::from_utf8_lossy(piece);
        let escaped = serde_json::Value::from(text.as_ref()).to_string();
        let (reply, generation) = self.link.request_on(
            packet(&format!("{{\"cmd\":47,\"s\":{escaped}}}"))?,
            Some(frames::key_reply()),
            typing.generation,
            until,
        )?;
        typing.generation.get_or_insert(generation);
        self.typing_reply(reply.as_deref())?;
        typing.sent = true;
        loop {
            std::thread::sleep(TYPE_POLL);
            if Instant::now() >= until {
                self.link.take_down(generation);
                return Err(Error::Disconnected);
            }
            let (reply, _) = self.link.request_on(
                packet("{\"cmd\":48}")?,
                Some(frames::key_reply()),
                Some(generation),
                until,
            )?;
            let value = self.typing_reply(reply.as_deref())?;
            let status = frames::data(&value).unwrap_or_default();
            let count = |name: &str| status.get(name).and_then(serde_json::Value::as_u64);
            // the vendor documents 0 or 1 and its own host only checks it's falsy, so false counts too
            let busy = status.get("busy").is_none_or(|busy| {
                busy.as_u64()
                    .map_or(busy.as_bool() != Some(false), |n| n != 0)
            });
            if busy {
                continue;
            }
            return match (count("typed"), count("total"), count("skipped")) {
                (Some(typed), Some(total), Some(0)) if typed == total => Ok(()),
                (typed, total, skipped) => Err(Error::Rejected {
                    action: Action::TypeText,
                    detail: format!(
                        "it says it typed {} of {} characters and skipped {}",
                        typed.unwrap_or(0),
                        total.unwrap_or(0),
                        skipped.unwrap_or(0)
                    ),
                }),
            };
        }
    }

    fn release_all(&self, held: &[Usage]) -> Result<()> {
        let mut first = Ok(());
        for &usage in held {
            let result = self.send(usage.release());
            if first.is_ok() {
                first = result;
            }
        }
        first
    }

    fn unlock_all(&self, slots: &[LockSlot]) -> Result<()> {
        let mut first = Ok(());
        for &slot in slots {
            let result = self.send(Command::Lock {
                slot,
                keep: UNLOCKED,
            });
            if matches!(result, Err(Error::Disconnected)) {
                return result;
            }
            if first.is_ok() {
                first = result;
            }
        }
        first
    }

    fn shutdown(&self, deadline: Duration) {
        let _ = self.close(deadline);
    }

    fn close(&self, deadline: Duration) -> Result<()> {
        if self.shared.stop.swap(true, Ordering::AcqRel) {
            return Ok(());
        }
        let until = Instant::now() + deadline;
        let streams = lock(&self.shared.state).streams;
        // the box keeps uploading to whoever opens the port next, so a failed off is worth reporting, but only
        // when anybox turned it on
        let stopped = if streams.buttons || streams.motion {
            self.upload(false, until)
        } else {
            Ok(())
        };
        self.link
            .shutdown(until.saturating_duration_since(Instant::now()));
        stopped
    }

    fn extension(&self, request: Extension) -> Result<ExtensionReply> {
        let until = Instant::now() + WRITE_DEADLINE * 2;
        // one request at a time, the JSON answers share a key and don't name their command
        let _request = lock(&self.shared.requests);
        match request {
            Extension::YscInterpolation => self
                .interpolation(until)
                .map(ExtensionReply::YscInterpolation),
            Extension::YscSetInterpolation(settings) => {
                self.link
                    .request_until(packet(&interpolation_json(settings))?, None, until)?;
                let now = self.interpolation(until)?;
                if !matches(&now, &settings) {
                    return Err(Error::Rejected {
                        action: request.action(),
                        detail: format!("it didn't take the interpolation, it reads back {now:?}"),
                    });
                }
                Ok(ExtensionReply::Done)
            }
            Extension::YscResetInterpolation => {
                self.link
                    .request_until(packet("{\"cmd\":53}")?, None, until)?;
                self.interpolation(until)
                    .map(ExtensionReply::YscInterpolation)
            }
            Extension::YscSerial => {
                let data = self.ask("{\"cmd\":54}", "sn", request.action(), until)?;
                let text = |name: &str| {
                    data.get(name)
                        .and_then(serde_json::Value::as_str)
                        .map(String::from)
                };
                Ok(ExtensionReply::YscSerial(YscSerial {
                    custom: text("custom"),
                    physical: text("physical"),
                    active: text("active"),
                }))
            }
            _ => Err(Error::Unsupported {
                action: request.action(),
                family: Family::Ysc,
                reason: "a YSC doesn't have this".into(),
            }),
        }
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl Drop for YscBackend {
    fn drop(&mut self) {
        self.shutdown(WRITE_DEADLINE);
    }
}

#[cfg(any(test, feature = "mock"))]
pub(crate) mod mock;
#[cfg(test)]
mod tests;

fn interpolation_json(settings: YscInterpolationSettings) -> String {
    format!(
        "{{\"cmd\":51,\"e\":{},\"p\":{},\"w\":{},\"mx\":{}}}",
        u8::from(settings.enabled),
        settings.profile.number(),
        settings.window.as_millis(),
        settings.max_window.as_millis()
    )
}

/// what the box read back against what was set, the windows only when it sent them
fn matches(now: &YscInterpolation, settings: &YscInterpolationSettings) -> bool {
    now.enabled == settings.enabled
        && now.profile == settings.profile
        && now.window.is_none_or(|window| window == settings.window)
        && now.max_window.is_none_or(|max| max == settings.max_window)
}