aboutsummaryrefslogtreecommitdiffstats
path: root/input-emulation/src/wlroots.rs
blob: 04ffa024843f36831b0c63a4effd3624dd0ad178 (plain) (blame)
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
use crate::error::EmulationError;

use super::{Emulation, error::WlrootsEmulationCreationError};
use async_trait::async_trait;
use bitflags::bitflags;
use std::collections::HashMap;
use std::io;
use std::os::fd::{AsFd, OwnedFd};
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
use wayland_client::WEnum;
use wayland_client::backend::WaylandError;

use wayland_client::protocol::wl_keyboard::{self, WlKeyboard};
use wayland_client::protocol::wl_output::WlOutput;
use wayland_client::protocol::wl_pointer::{Axis, AxisSource, ButtonState};
use wayland_client::protocol::wl_seat::WlSeat;
use wayland_protocols::xdg::xdg_output::zv1::client::{
    zxdg_output_manager_v1::ZxdgOutputManagerV1,
    zxdg_output_v1::{self, ZxdgOutputV1},
};
use wayland_protocols_wlr::virtual_pointer::v1::client::{
    zwlr_virtual_pointer_manager_v1::ZwlrVirtualPointerManagerV1 as VpManager,
    zwlr_virtual_pointer_v1::ZwlrVirtualPointerV1 as Vp,
};

use wayland_protocols_misc::zwp_virtual_keyboard_v1::client::{
    zwp_virtual_keyboard_manager_v1::ZwpVirtualKeyboardManagerV1 as VkManager,
    zwp_virtual_keyboard_v1::ZwpVirtualKeyboardV1 as Vk,
};

use wayland_client::{
    Connection, Dispatch, EventQueue, QueueHandle, delegate_noop,
    globals::{GlobalListContents, registry_queue_init},
    protocol::{wl_registry, wl_seat},
};

use input_event::{Event, KeyboardEvent, PointerEvent, scancode};

use super::error::WaylandBindError;
use super::{Edge, EmulationHandle};

/// logical output geometry, used to place the cursor on entry
#[derive(Default)]
struct OutputGeometry {
    global_name: u32,
    xdg_output: Option<ZxdgOutputV1>,
    pos: (i32, i32),
    size: (i32, i32),
}

struct State {
    keymap: Option<(u32, OwnedFd, u32)>,
    /// compositor sent a new keymap (layout change) not yet applied
    keymap_changed: bool,
    outputs: Vec<OutputGeometry>,
    xdg_output_manager: Option<ZxdgOutputManagerV1>,
    /// shared by all clients, so the keymap fd is sent once instead of once per client
    keyboard: Option<Vk>,
    input_for_client: HashMap<EmulationHandle, VirtualInput>,
    seat: wl_seat::WlSeat,
    qh: QueueHandle<Self>,
    vpm: VpManager,
    vkm: VkManager,
}

// App State, implements Dispatch event handlers
pub(crate) struct WlrootsEmulation {
    last_flush_failed: bool,
    /// events consumed since compositor events were last read
    since_dispatch: u32,
    state: State,
    queue: EventQueue<State>,
}

impl WlrootsEmulation {
    pub(crate) fn new() -> Result<Self, WlrootsEmulationCreationError> {
        let conn = Connection::connect_to_env()?;
        let (globals, queue) = registry_queue_init::<State>(&conn)?;
        let qh = queue.handle();

        let seat: wl_seat::WlSeat = globals
            .bind(&qh, 7..=8, ())
            .map_err(|e| WaylandBindError::new(e, "wl_seat 7..=8"))?;

        let vpm: VpManager = globals
            .bind(&qh, 1..=1, ())
            .map_err(|e| WaylandBindError::new(e, "wlr-virtual-pointer-unstable-v1"))?;
        let vkm: VkManager = globals
            .bind(&qh, 1..=1, ())
            .map_err(|e| WaylandBindError::new(e, "virtual-keyboard-unstable-v1"))?;

        let input_for_client: HashMap<EmulationHandle, VirtualInput> = HashMap::new();

        // optional: only needed to place the cursor where it entered
        let xdg_output_manager: Option<ZxdgOutputManagerV1> = globals.bind(&qh, 1..=3, ()).ok();
        let output_globals: Vec<u32> = globals.contents().with_list(|list| {
            list.iter()
                .filter(|g| g.interface == "wl_output")
                .map(|g| g.name)
                .collect()
        });

        let mut emulate = WlrootsEmulation {
            last_flush_failed: false,
            since_dispatch: 0,
            state: State {
                keymap: None,
                keymap_changed: false,
                outputs: Vec::new(),
                xdg_output_manager,
                keyboard: None,
                input_for_client,
                seat,
                vpm,
                vkm,
                qh,
            },
            queue,
        };
        for name in output_globals {
            emulate.state.add_output(globals.registry(), name);
        }
        while emulate.state.keymap.is_none() {
            emulate.queue.blocking_dispatch(&mut emulate.state)?;
        }
        // collect initial output geometry
        emulate.queue.roundtrip(&mut emulate.state)?;
        emulate.state.keymap_changed = false;
        // let fd = unsafe { &File::from_raw_fd(emulate.state.keymap.unwrap().1.as_raw_fd()) };
        // let mmap = unsafe { MmapOptions::new().map_copy(fd).unwrap() };
        // log::debug!("{:?}", &mmap[..100]);
        Ok(emulate)
    }
}

impl State {
    fn add_output(&mut self, registry: &wl_registry::WlRegistry, name: u32) {
        let Some(manager) = self.xdg_output_manager.as_ref() else {
            return;
        };
        let wl_output: WlOutput = registry.bind(name, 1, &self.qh, ());
        let xdg_output = manager.get_xdg_output(&wl_output, &self.qh, name);
        self.outputs.push(OutputGeometry {
            global_name: name,
            xdg_output: Some(xdg_output),
            ..Default::default()
        });
    }

    fn remove_output(&mut self, name: u32) {
        self.outputs.retain(|o| {
            if o.global_name != name {
                return true;
            }
            // wl_output is bound at v1, which has no release request
            if let Some(x) = &o.xdg_output {
                x.destroy();
            }
            false
        });
    }

    fn edge_point(&self, edge: Edge, offset: f64) -> Option<(u32, u32, u32, u32)> {
        edge_point(self.outputs.iter().map(|o| (o.pos, o.size)), edge, offset)
    }

    fn add_client(&mut self, client: EmulationHandle) {
        let pointer: Vp = self.vpm.create_virtual_pointer(None, &self.qh, ());

        let keyboard = match self.keyboard.as_ref() {
            Some(keyboard) => keyboard.clone(),
            None => {
                let keyboard: Vk = self.vkm.create_virtual_keyboard(&self.seat, &self.qh, ());
                // TODO: use server side keymap
                let Some((format, fd, size)) = self.keymap.as_ref() else {
                    panic!("no keymap");
                };
                keyboard.keymap(*format, fd.as_fd(), *size);
                self.keyboard = Some(keyboard.clone());
                keyboard
            }
        };

        let vinput = VirtualInput {
            pointer,
            keyboard,
            modifiers: Arc::new(Mutex::new(XMods::empty())),
        };

        self.input_for_client.insert(client, vinput);
    }

    fn destroy_client(&mut self, handle: EmulationHandle) {
        // the shared keyboard outlives every client; keys are released by InputEmulation::destroy
        if let Some(input) = self.input_for_client.remove(&handle) {
            input.pointer.destroy();
        }
    }
}

impl WlrootsEmulation {
    /// read and handle pending compositor events without blocking
    fn dispatch(&mut self) -> Result<(), WaylandError> {
        self.since_dispatch = 0;
        if let Some(guard) = self.queue.prepare_read() {
            match guard.read() {
                Ok(_) => {}
                Err(WaylandError::Io(e)) if e.kind() == io::ErrorKind::WouldBlock => {}
                Err(e) => return Err(e),
            }
        }
        if let Err(e) = self.queue.dispatch_pending(&mut self.state) {
            log::warn!("wayland dispatch failed: {e}");
        }
        if std::mem::take(&mut self.state.keymap_changed) {
            if let (Some(keyboard), Some((format, fd, size))) =
                (self.state.keyboard.as_ref(), self.state.keymap.as_ref())
            {
                log::info!("compositor keymap changed, updating virtual keyboard");
                keyboard.keymap(*format, fd.as_fd(), *size);
            }
        }
        Ok(())
    }
}

fn now_ms() -> u32 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u32
}

/// Point on `edge` of the output layout at `offset` (fraction) along it, as
/// `(x, y, width, height)` relative to the layout's bounding box.
/// `outputs` are `(position, size)` in logical coordinates.
fn edge_point(
    outputs: impl Iterator<Item = ((i32, i32), (i32, i32))>,
    edge: Edge,
    offset: f64,
) -> Option<(u32, u32, u32, u32)> {
    // stay this many logical pixels inside the edge, so the cursor does not
    // land on our own 1px capture surface there and bounce straight back
    const INSET: i32 = 2;
    let outputs: Vec<_> = outputs.filter(|(_, s)| s.0 > 0 && s.1 > 0).collect();
    let min_x = outputs.iter().map(|(p, _)| p.0).min()?;
    let min_y = outputs.iter().map(|(p, _)| p.1).min()?;
    let max_x = outputs.iter().map(|(p, s)| p.0 + s.0).max()?;
    let max_y = outputs.iter().map(|(p, s)| p.1 + s.1).max()?;
    // span (start, end) along the edge of every output touching it
    let spans = outputs.iter().filter_map(|&(p, s)| match edge {
        Edge::Left => (p.0 == min_x).then_some((p.1, p.1 + s.1)),
        Edge::Right => (p.0 + s.0 == max_x).then_some((p.1, p.1 + s.1)),
        Edge::Top => (p.1 == min_y).then_some((p.0, p.0 + s.0)),
        Edge::Bottom => (p.1 + s.1 == max_y).then_some((p.0, p.0 + s.0)),
    });
    let (lo, hi) = spans.fold((i32::MAX, i32::MIN), |(lo, hi), (a, b)| {
        (lo.min(a), hi.max(b))
    });
    if hi <= lo {
        return None;
    }
    let along = (lo as f64 + offset.clamp(0.0, 1.0) * (hi - lo) as f64)
        .clamp(lo as f64, (hi - 1) as f64) as i32;
    let (x, y) = match edge {
        Edge::Left => (min_x + INSET, along),
        Edge::Right => (max_x - 1 - INSET, along),
        Edge::Top => (along, min_y + INSET),
        Edge::Bottom => (along, max_y - 1 - INSET),
    };
    let (w, h) = (max_x - min_x, max_y - min_y);
    Some((
        (x - min_x).clamp(0, w - 1) as u32,
        (y - min_y).clamp(0, h - 1) as u32,
        w as u32,
        h as u32,
    ))
}

#[async_trait]
impl Emulation for WlrootsEmulation {
    async fn consume(
        &mut self,
        event: Event,
        handle: EmulationHandle,
    ) -> Result<(), EmulationError> {
        // read compositor events now and then; nothing else drains the
        // socket, and keymap updates (layout switches) arrive there
        self.since_dispatch += 1;
        if self.since_dispatch >= 64 {
            self.dispatch()?;
        }
        if let Some(virtual_input) = self.state.input_for_client.get(&handle) {
            if self.last_flush_failed {
                match self.queue.flush() {
                    Err(WaylandError::Io(e)) if e.kind() == io::ErrorKind::WouldBlock => {
                        /*
                         * outgoing buffer is full - sending more events
                         * will overwhelm the output buffer and leave the
                         * wayland connection in a broken state
                         */
                        log::warn!("can't keep up, discarding event: ({handle}) - {event:?}");
                        return Ok(());
                    }
                    _ => {}
                }
            }
            virtual_input
                .consume_event(event)
                .unwrap_or_else(|_| panic!("failed to convert event: {event:?}"));
            match self.queue.flush() {
                Err(WaylandError::Io(e)) if e.kind() == io::ErrorKind::WouldBlock => {
                    self.last_flush_failed = true;
                    log::warn!("can't keep up, discarding event: ({handle}) - {event:?}");
                }
                Err(WaylandError::Protocol(e)) => panic!("wayland protocol violation: {e}"),
                Ok(()) => self.last_flush_failed = false,
                Err(e) => Err(e)?,
            }
        }
        Ok(())
    }

    async fn warp(&mut self, handle: EmulationHandle, edge: Edge, offset: Option<f64>) {
        // without an offset (old peer) keep the cursor where it is
        let Some(offset) = offset else { return };
        if let Err(e) = self.dispatch() {
            log::warn!("{e}");
        }
        let Some(input) = self.state.input_for_client.get(&handle) else {
            return;
        };
        let Some((x, y, w, h)) = self.state.edge_point(edge, offset) else {
            log::debug!("no output geometry, not placing cursor");
            return;
        };
        log::debug!("placing cursor at {edge:?} edge ({x}, {y}) of {w}x{h}");
        input.pointer.motion_absolute(now_ms(), x, y, w, h);
        input.pointer.frame();
        if let Err(e) = self.queue.flush() {
            log::warn!("{e}");
        }
    }

    async fn create(&mut self, handle: EmulationHandle) {
        if let Err(e) = self.dispatch() {
            log::warn!("{e}");
        }
        self.state.add_client(handle);
        if let Err(e) = self.queue.flush() {
            log::error!("{e}");
        }
    }
    async fn destroy(&mut self, handle: EmulationHandle) {
        self.state.destroy_client(handle);
        if let Err(e) = self.queue.flush() {
            log::error!("{e}");
        }
    }
    async fn terminate(&mut self) {
        /* nothing to do */
    }
}

struct VirtualInput {
    pointer: Vp,
    keyboard: Vk,
    modifiers: Arc<Mutex<XMods>>,
}

impl VirtualInput {
    fn consume_event(&self, event: Event) -> Result<(), ()> {
        // the peer's timestamps use its own clock and unit (libei sends microseconds,
        // windows and macos send 0); clients compare them to detect double clicks
        let now = now_ms();

        match event {
            Event::Pointer(e) => {
                match e {
                    PointerEvent::Motion { dx, dy, .. } => self.pointer.motion(now, dx, dy),
                    PointerEvent::Button { button, state, .. } => {
                        let state: ButtonState = state.try_into()?;
                        self.pointer.button(now, button, state);
                    }
                    // axis_source belongs before the axis events of a frame;
                    // the single frame below closes it
                    PointerEvent::Axis { axis, value, .. } => {
                        let axis: Axis = (axis as u32).try_into()?;
                        self.pointer.axis_source(AxisSource::Continuous);
                        self.pointer.axis(now, axis, value);
                    }
                    PointerEvent::AxisDiscrete120 { axis, value } => {
                        let axis: Axis = (axis as u32).try_into()?;
                        self.pointer.axis_source(AxisSource::Wheel);
                        self.pointer
                            .axis_discrete(now, axis, value as f64 / 8., value / 120);
                    }
                }
                self.pointer.frame();
            }
            Event::Keyboard(e) => match e {
                KeyboardEvent::Key { key, state, .. } => {
                    self.keyboard.key(now, key, state as u32);
                    if let Ok(mut mods) = self.modifiers.lock() {
                        if mods.update_by_key_event(key, state) {
                            log::trace!("Key triggers modifier change: {mods:?}");
                            self.keyboard.modifiers(
                                mods.mask_pressed().bits(),
                                0,
                                mods.mask_locks().bits(),
                                0,
                            );
                        }
                    }
                }
                KeyboardEvent::Modifiers {
                    depressed: mods_depressed,
                    latched: mods_latched,
                    locked: mods_locked,
                    group,
                } => {
                    // Synchronize internal modifier state, assuming server is authoritative
                    if let Ok(mut mods) = self.modifiers.lock() {
                        mods.update_by_mods_event(e);
                    }
                    self.keyboard
                        .modifiers(mods_depressed, mods_latched, mods_locked, group);
                }
            },
        }
        Ok(())
    }
}

delegate_noop!(State: Vp);
delegate_noop!(State: Vk);
delegate_noop!(State: VpManager);
delegate_noop!(State: VkManager);

impl Dispatch<wl_registry::WlRegistry, GlobalListContents> for State {
    fn event(
        state: &mut State,
        registry: &wl_registry::WlRegistry,
        event: wl_registry::Event,
        _: &GlobalListContents,
        _: &Connection,
        _: &QueueHandle<State>,
    ) {
        match event {
            wl_registry::Event::Global {
                name, interface, ..
            } if interface == "wl_output" => state.add_output(registry, name),
            wl_registry::Event::GlobalRemove { name } => state.remove_output(name),
            _ => {}
        }
    }
}

impl Dispatch<ZxdgOutputV1, u32> for State {
    fn event(
        state: &mut Self,
        _: &ZxdgOutputV1,
        event: zxdg_output_v1::Event,
        name: &u32,
        _: &Connection,
        _: &QueueHandle<Self>,
    ) {
        let Some(output) = state.outputs.iter_mut().find(|o| o.global_name == *name) else {
            return;
        };
        match event {
            zxdg_output_v1::Event::LogicalPosition { x, y } => output.pos = (x, y),
            zxdg_output_v1::Event::LogicalSize { width, height } => output.size = (width, height),
            _ => {}
        }
    }
}

delegate_noop!(State: ignore WlOutput);
delegate_noop!(State: ZxdgOutputManagerV1);

impl Dispatch<WlKeyboard, ()> for State {
    fn event(
        state: &mut Self,
        _: &WlKeyboard,
        event: <WlKeyboard as wayland_client::Proxy>::Event,
        _: &(),
        _: &Connection,
        _: &QueueHandle<Self>,
    ) {
        if let wl_keyboard::Event::Keymap { format, fd, size } = event {
            state.keymap = Some((u32::from(format), fd, size));
            state.keymap_changed = true;
        }
    }
}

impl Dispatch<WlSeat, ()> for State {
    fn event(
        _: &mut Self,
        seat: &WlSeat,
        event: <WlSeat as wayland_client::Proxy>::Event,
        _: &(),
        _: &Connection,
        qhandle: &QueueHandle<Self>,
    ) {
        if let wl_seat::Event::Capabilities {
            capabilities: WEnum::Value(capabilities),
        } = event
        {
            if capabilities.contains(wl_seat::Capability::Keyboard) {
                seat.get_keyboard(qhandle, ());
            }
        }
    }
}

// From X11/X.h
bitflags! {
    #[repr(C)]
    #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
    struct XMods: u32 {
        const ShiftMask = (1<<0);
        const LockMask = (1<<1);
        const ControlMask = (1<<2);
        const Mod1Mask = (1<<3);
        const Mod2Mask = (1<<4);
        const Mod3Mask = (1<<5);
        const Mod4Mask = (1<<6);
        const Mod5Mask = (1<<7);
    }
}

impl XMods {
    fn update_by_mods_event(&mut self, evt: KeyboardEvent) {
        if let KeyboardEvent::Modifiers {
            depressed, locked, ..
        } = evt
        {
            *self = XMods::from_bits_truncate(depressed) | XMods::from_bits_truncate(locked);
        }
    }

    fn update_by_key_event(&mut self, key: u32, state: u8) -> bool {
        if let Ok(key) = scancode::Linux::try_from(key) {
            log::trace!("Attempting to process modifier from: {key:#?}");
            let pressed_mask = match key {
                scancode::Linux::KeyLeftShift | scancode::Linux::KeyRightShift => XMods::ShiftMask,
                scancode::Linux::KeyLeftCtrl | scancode::Linux::KeyRightCtrl => XMods::ControlMask,
                scancode::Linux::KeyLeftAlt | scancode::Linux::KeyRightalt => XMods::Mod1Mask,
                scancode::Linux::KeyLeftMeta | scancode::Linux::KeyRightmeta => XMods::Mod4Mask,
                _ => XMods::empty(),
            };

            let locked_mask = match key {
                scancode::Linux::KeyCapsLock => XMods::LockMask,
                scancode::Linux::KeyNumlock => XMods::Mod2Mask,
                scancode::Linux::KeyScrollLock => XMods::Mod3Mask,
                _ => XMods::empty(),
            };

            // unchanged
            if pressed_mask.is_empty() && locked_mask.is_empty() {
                log::trace!("{key:#?} is not a modifier key");
                return false;
            }
            match state {
                1 => self.insert(pressed_mask),
                _ => {
                    self.remove(pressed_mask);
                    self.toggle(locked_mask);
                }
            }
            true
        } else {
            false
        }
    }

    fn mask_locks(&self) -> XMods {
        *self & (XMods::LockMask | XMods::Mod2Mask | XMods::Mod3Mask)
    }

    fn mask_pressed(&self) -> XMods {
        *self & (XMods::ShiftMask | XMods::ControlMask | XMods::Mod1Mask | XMods::Mod4Mask)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // como: eDP-1 1920x1080 at (0,0), DP-1 1920x1080 at (1920,0)
    const TWO: [((i32, i32), (i32, i32)); 2] = [((0, 0), (1920, 1080)), ((1920, 0), (1920, 1080))];

    #[test]
    fn right_edge_uses_rightmost_output() {
        let p = edge_point(TWO.into_iter(), Edge::Right, 0.5).unwrap();
        assert_eq!(p, (3840 - 3, 540, 3840, 1080));
    }

    #[test]
    fn left_edge_extremes_stay_on_screen() {
        assert_eq!(
            edge_point(TWO.into_iter(), Edge::Left, 0.0).unwrap(),
            (2, 0, 3840, 1080)
        );
        assert_eq!(
            edge_point(TWO.into_iter(), Edge::Left, 1.0).unwrap(),
            (2, 1079, 3840, 1080)
        );
    }

    #[test]
    fn top_edge_spans_both_outputs() {
        assert_eq!(
            edge_point(TWO.into_iter(), Edge::Top, 0.75).unwrap(),
            (2880, 2, 3840, 1080)
        );
    }

    #[test]
    fn offset_outputs_and_no_outputs() {
        // second output lower and to the right: right edge is only DP
        let o = [((0, 0), (1920, 1080)), ((1920, 300), (1280, 1024))];
        assert_eq!(
            edge_point(o.into_iter(), Edge::Right, 0.0).unwrap(),
            (3197, 300, 3200, 1324)
        );
        assert!(edge_point(std::iter::empty(), Edge::Right, 0.5).is_none());
    }
}