easydrm 0.4.0

GLFW-inspired abstraction over DRM/KMS, GBM, and EGL/OpenGL that lets you build fullscreen Linux applications without a compositor (no X11, no 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
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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
//! # EasyDRM - Minimal DRM/KMS Framework
//!
//! EasyDRM provides a simple, GLFW-like API for direct rendering on Linux without
//! a compositor (no X11, no Wayland). It's designed for fullscreen applications,
//! kiosks, embedded systems, or custom compositors.
//!
//! ## Features
//!
//! - **Multi-monitor support** with independent OpenGL ES contexts per monitor
//! - **Hot-plug detection** - monitors can be added/removed at runtime
//! - **Zero-monitor graceful handling** - doesn't crash without monitors
//! - **Per-monitor user context** - attach custom data (Skia, Cairo, etc.)
//! - **Refresh-rate grouping metadata** for diagnostics or custom scheduling strategies
//! - **Atomic commits** with proper fence synchronization
//! - **3-state mode management** for efficient mode setting
//!
//! ## Basic Usage
//!
//! ```no_run
//! use easydrm::EasyDRM;
//!
//! // Initialize without custom context
//! let mut easydrm = EasyDRM::init_empty().unwrap();
//!
//! loop {
//!     // Wait for events (page flip, hotplug, etc.)
//!     easydrm.poll_events().unwrap();
//!
//!     // Render to each monitor that's ready
//!     for monitor in easydrm.monitors() {
//!         if monitor.can_render() {
//!             monitor.make_current().unwrap();
//!             let gl = monitor.gl();
//!             unsafe {
//!                 gl.Clear(gl::COLOR_BUFFER_BIT);
//!             }
//!         }
//!     }
//!
//!     // Commit all drawn monitors
//!     easydrm.swap_buffers().unwrap();
//! }
//! ```
//!
//! ## With Custom Context
//!
//! ```no_run
//! use easydrm::EasyDRM;
//!
//! struct MyContext {
//!     frame_count: u32,
//! }
//!
//! let mut easydrm = EasyDRM::init(|req| {
//!     println!(
//!         "Monitor init: {}x{}, get symbol ptr example: {:?}",
//!         req.width,
//!         req.height,
//!         (req.get_proc_address)("glCreateShader")
//!     );
//!     MyContext { frame_count: 0 }
//! })
//! .unwrap();
//!
//! for monitor in easydrm.monitors() {
//!     let ctx = monitor.context_mut();
//!     ctx.frame_count += 1;
//! }
//! ```

use std::collections::{HashMap, HashSet};
use std::future::pending;
use std::ops::Deref;
use std::os::fd::{AsFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
use std::os::unix::io::AsRawFd;
use std::sync::{Arc, Mutex};

use drm::Device;
use drm::control::atomic::AtomicModeReq;
use drm::control::{
    AtomicCommitFlags, Device as ControlDevice, Event, PlaneType, connector, crtc, plane,
};
use gbm::Device as GbmDevice;
use libc::{F_GETFL, F_SETFL, O_NONBLOCK, fcntl};
use nix::poll::{PollFd, PollFlags, PollTimeout, poll};
use thiserror::Error;
use tokio::io::Interest;
use tokio::io::unix::AsyncFd;

use crate::card::Card;
pub use crate::gles_context::{GlesContext, GlesContextError};
use crate::monitor::{MonitorResourceAllocation, MonitorSetupError};

mod card;
mod gles_context;
mod hotplug;
mod monitor;

// Public API exports
pub use monitor::Monitor;

/// OpenGL ES bindings generated at build time
#[allow(clippy::all, warnings)]
pub mod gl {
    include!(concat!(env!("OUT_DIR"), "/gl_bindings.rs"));
}

/// Data provided to the user callback when creating a per-monitor context.
pub struct MonitorContextCreationRequest<'a> {
    /// OpenGL ES bindings for this monitor.
    pub gl: &'a crate::gl::Gles2,
    /// Width of the monitor surface in pixels.
    pub width: usize,
    /// Height of the monitor surface in pixels.
    pub height: usize,
    /// Helper to load extra GL symbols (useful for third-party loaders).
    pub get_proc_address: &'a dyn Fn(&str) -> *const std::ffi::c_void,
}

#[derive(Debug, Error)]
pub enum EasyDRMError {
    #[error("IO Error: {0}")]
    IOError(#[from] std::io::Error),
    #[error("Monitor setup error: {0}")]
    MonitorSetup(#[from] MonitorSetupError),
}

pub struct SwapResult {
    pub committed_connectors: Vec<connector::Handle>,
    pub render_fence: i32,
}

pub struct EasyDRM<T> {
    card: Card,
    gbm_device: GbmDevice<std::fs::File>,
    shared_gles_context: Arc<Mutex<GlesContext>>,
    monitors: HashMap<connector::Handle, Monitor<T>>,
    refresh_rate_groups: HashMap<u32, Vec<connector::Handle>>, // refresh_rate -> connector handles
    fastest_group_refresh: Option<u32>,
    fastest_group_pending: HashSet<connector::Handle>,
    should_update_flag: bool,
    context_constructor: Box<dyn for<'a> Fn(&MonitorContextCreationRequest<'a>) -> T + 'static>,
    uevent_socket: Option<hotplug::UEventSocket>,
    last_fence_fd: Option<OwnedFd>
}


const EGL_SYNC_FENCE_KHR: u32 = 0x3144;

impl<T> EasyDRM<T> {
    /// Initialize EasyDRM with a custom context constructor for each monitor
    ///
    /// The context_constructor receives a [`MonitorContextCreationRequest`] with access to GL
    /// bindings, framebuffer size, and a `get_proc_address` helper so you can load extra
    /// OpenGL functions during initialization. Use this to set up per-monitor resources
    /// (Skia surfaces, Cairo contexts, etc.)
    ///
    /// # Example
    ///
    /// ```ignore
    /// struct MyContext {
    ///     skia_surface: skia::Surface,
    /// }
    ///
    /// let easydrm = EasyDRM::init(|req| {
    ///     MyContext {
    ///         skia_surface: create_skia_surface(req.gl),
    ///     }
    /// })?;
    /// ```
    ///
    /// Note: EasyDRM will successfully initialize even with zero monitors connected as long as you have a GPU.
    /// Monitors can be hot-plugged later and will be automatically discovered via `poll_events()`.
    pub fn init<F>(context_constructor: F) -> Result<Self, EasyDRMError>
    where
        F: for<'a> Fn(&MonitorContextCreationRequest<'a>) -> T + 'static,
    {
        // Open DRM card
        let card = Card::open_default_card();

        // Enable required capabilities
        card.set_client_capability(drm::ClientCapability::UniversalPlanes, true)
            .expect("Unable to request UniversalPlanes capability");
        card.set_client_capability(drm::ClientCapability::Atomic, true)
            .expect("Unable to request Atomic capability");

        // Create GBM device (needs ownership, so we clone the file descriptor)
        let fd = card.as_raw_fd();
        let gbm_device = unsafe {
            use std::os::unix::io::FromRawFd;
            GbmDevice::new(std::fs::File::from_raw_fd(libc::dup(fd)))
                .expect("Failed to create GBM device")
        };
        let shared_gles_context = Arc::new(Mutex::new(
            GlesContext::new(&gbm_device).map_err(MonitorSetupError::GlesContextError)?,
        ));

        let mut easydrm = EasyDRM {
            card,
            gbm_device,
            shared_gles_context,
            monitors: HashMap::new(),
            refresh_rate_groups: HashMap::new(),
            fastest_group_refresh: None,
            fastest_group_pending: HashSet::new(),
            should_update_flag: false,
            context_constructor: Box::new(context_constructor),
            uevent_socket: hotplug::UEventSocket::open().ok(),
            last_fence_fd: None
        };
        if easydrm.uevent_socket.is_none() {
            eprintln!(
                "[WARNING] Failed to open uevent socket, monitors plugged in afterwards won't be able to be detected"
            );
        }
        // Discover and initialize all connected monitors
        easydrm.discover_monitors()?;

        // It's OK to have zero monitors - they might be connected later via hotplug

        Ok(easydrm)
    }

    /// Discover all connected monitors and initialize them
    fn discover_monitors(&mut self) -> Result<(), EasyDRMError> {
        let res = self.card.resource_handles()?;

        // Get all connector handles
        let connector_handles: Vec<connector::Handle> = res.connectors().to_vec();
        let (mut used_crtcs, mut used_primary_planes, mut used_cursor_planes) =
            self.current_resource_usage();

        // Setup monitors
        for connector_id in connector_handles {
            if self.monitors.contains_key(&connector_id) {
                continue;
            }

            let allocation = match self.allocate_monitor_resources(
                connector_id,
                &used_crtcs,
                &used_primary_planes,
                &used_cursor_planes,
            ) {
                Ok(allocation) => allocation,
                Err(e) => {
                    eprintln!(
                        "Warning: Failed to allocate resources for monitor {:?}: {}",
                        connector_id, e
                    );
                    continue;
                }
            };

            match Monitor::setup(
                &self.card,
                &self.gbm_device,
                Arc::clone(&self.shared_gles_context),
                connector_id,
                allocation,
                |request| (self.context_constructor)(request),
            ) {
                Ok(monitor) => {
                    used_crtcs.insert(monitor.crtc().handle());
                    used_primary_planes.insert(monitor.primary_plane());
                    if let Some(cursor) = monitor.cursor_plane() {
                        used_cursor_planes.insert(cursor);
                    }
                    self.monitors.insert(connector_id, monitor);
                }
                Err(e) => {
                    eprintln!("Warning: Failed to setup monitor {:?}: {}", connector_id, e);
                }
            }
        }

        self.update_refresh_rate_groups();

        Ok(())
    }

    /// Update refresh rate groups based on current monitors
    fn update_refresh_rate_groups(&mut self) {
        self.refresh_rate_groups.clear();

        for (&connector_id, monitor) in self.monitors.iter() {
            let refresh_rate = monitor.active_mode().vrefresh();
            self.refresh_rate_groups
                .entry(refresh_rate)
                .or_default()
                .push(connector_id);
        }

        self.fastest_group_refresh = self.refresh_rate_groups.keys().max().copied();
        self.reset_fastest_group_pending();
    }

    fn reset_fastest_group_pending(&mut self) {
        self.fastest_group_pending.clear();
        if let Some(refresh) = self.fastest_group_refresh {
            if let Some(connectors) = self.refresh_rate_groups.get(&refresh) {
                self.fastest_group_pending
                    .extend(connectors.iter().copied());
            }
        }
        // If there is no fastest group (i.e., no monitors), keep the flag false.
        self.should_update_flag =
            self.fastest_group_pending.is_empty() && self.fastest_group_refresh.is_some();
    }

    fn mark_fast_group_commit(&mut self, connector_id: connector::Handle) {
        if self.fastest_group_pending.remove(&connector_id) && self.fastest_group_pending.is_empty()
        {
            self.should_update_flag = true;
        }
    }

    /// Handle hotplug events - add/remove monitors as needed
    fn handle_hotplug(&mut self) -> Result<(), EasyDRMError> {
        let res = self.card.resource_handles()?;

        // Get current connected monitors from DRM
        let drm_connected = res
            .connectors()
            .into_iter()
            .copied()
            .collect::<HashSet<_>>();

        // Get current monitor connector IDs
        let current_monitors: HashSet<connector::Handle> = self.monitors.keys().copied().collect();

        // Find monitors that were disconnected
        let disconnected: Vec<connector::Handle> = current_monitors
            .difference(&drm_connected)
            .copied()
            .collect();

        // Find monitors that were newly connected
        let newly_connected: Vec<connector::Handle> = drm_connected
            .difference(&current_monitors)
            .copied()
            .collect();

        // Check if we need to update groups before consuming the vectors
        let needs_update = !disconnected.is_empty() || !newly_connected.is_empty();

        // Remove disconnected monitors
        for connector_id in disconnected {
            self.monitors.retain(|&c, _| c != connector_id);
        }

        let (mut used_crtcs, mut used_primary_planes, mut used_cursor_planes) =
            self.current_resource_usage();

        // Add newly connected monitors
        for connector_id in newly_connected {
            let allocation = match self.allocate_monitor_resources(
                connector_id,
                &used_crtcs,
                &used_primary_planes,
                &used_cursor_planes,
            ) {
                Ok(allocation) => allocation,
                Err(e) => {
                    eprintln!(
                        "Warning: Failed to allocate resources for monitor {:?}: {}",
                        connector_id, e
                    );
                    continue;
                }
            };

            match Monitor::setup(
                &self.card,
                &self.gbm_device,
                Arc::clone(&self.shared_gles_context),
                connector_id,
                allocation,
                |request| (self.context_constructor)(request),
            ) {
                Ok(monitor) => {
                    used_crtcs.insert(monitor.crtc().handle());
                    used_primary_planes.insert(monitor.primary_plane());
                    if let Some(cursor) = monitor.cursor_plane() {
                        used_cursor_planes.insert(cursor);
                    }
                    self.monitors.insert(connector_id, monitor);
                }
                Err(e) => {
                    eprintln!("Warning: Failed to setup monitor {:?}: {}", connector_id, e);
                }
            }
        }

        // Update refresh rate groups if monitors changed
        if needs_update {
            self.update_refresh_rate_groups();
        }

        Ok(())
    }

    fn current_resource_usage(
        &self,
    ) -> (
        HashSet<crtc::Handle>,
        HashSet<plane::Handle>,
        HashSet<plane::Handle>,
    ) {
        let mut used_crtcs = HashSet::new();
        let mut used_primary_planes = HashSet::new();
        let mut used_cursor_planes = HashSet::new();

        for monitor in self.monitors.values() {
            used_crtcs.insert(monitor.crtc().handle());
            used_primary_planes.insert(monitor.primary_plane());
            if let Some(cursor) = monitor.cursor_plane() {
                used_cursor_planes.insert(cursor);
            }
        }

        (used_crtcs, used_primary_planes, used_cursor_planes)
    }

    fn allocate_monitor_resources(
        &self,
        connector_id: connector::Handle,
        used_crtcs: &HashSet<crtc::Handle>,
        used_primary_planes: &HashSet<plane::Handle>,
        used_cursor_planes: &HashSet<plane::Handle>,
    ) -> Result<MonitorResourceAllocation, MonitorSetupError> {
        let connector = self.card.get_connector(connector_id, true)?;
        if connector.state() != connector::State::Connected {
            return Err(MonitorSetupError::NotConnected);
        }

        let res = self.card.resource_handles()?;
        let crtc_candidates = self.crtc_candidates_for_connector(&connector, &res, used_crtcs)?;
        let planes = self.card.plane_handles()?;
        let plane_handles: Vec<plane::Handle> = planes.iter().copied().collect();

        let mut crtc_info = None;
        for handle in crtc_candidates {
            if let Ok(info) = self.card.get_crtc(handle) {
                crtc_info = Some(info);
                break;
            }
        }
        let crtc_info = crtc_info.ok_or(MonitorSetupError::NoCRTCFound)?;

        let primary_plane = self
            .find_plane_for_crtc(
                &plane_handles,
                &res,
                crtc_info.handle(),
                PlaneType::Primary,
                used_primary_planes,
            )?
            .ok_or(MonitorSetupError::NoPrimaryPlaneFound)?;

        let cursor_plane = self.find_plane_for_crtc(
            &plane_handles,
            &res,
            crtc_info.handle(),
            PlaneType::Cursor,
            used_cursor_planes,
        )?;

        Ok(MonitorResourceAllocation {
            crtc_info,
            primary_plane,
            cursor_plane,
        })
    }

    fn crtc_candidates_for_connector(
        &self,
        connector: &connector::Info,
        res: &drm::control::ResourceHandles,
        used_crtcs: &HashSet<crtc::Handle>,
    ) -> Result<Vec<crtc::Handle>, MonitorSetupError> {
        let mut seen = HashSet::new();
        let mut candidates = Vec::new();

        for encoder_handle in connector.encoders() {
            let Ok(encoder) = self.card.get_encoder(*encoder_handle) else {
                continue;
            };

            for crtc_handle in res.filter_crtcs(encoder.possible_crtcs()) {
                if used_crtcs.contains(&crtc_handle) {
                    continue;
                }
                if seen.insert(crtc_handle) {
                    candidates.push(crtc_handle);
                }
            }
        }

        Ok(candidates)
    }

    fn find_plane_for_crtc(
        &self,
        plane_handles: &[plane::Handle],
        res: &drm::control::ResourceHandles,
        crtc_handle: crtc::Handle,
        plane_type: PlaneType,
        used_planes: &HashSet<plane::Handle>,
    ) -> Result<Option<plane::Handle>, MonitorSetupError> {
        for plane_handle in plane_handles {
            if used_planes.contains(plane_handle) {
                continue;
            }

            let Ok(plane_info) = self.card.get_plane(*plane_handle) else {
                continue;
            };
            let compatible_crtcs = res.filter_crtcs(plane_info.possible_crtcs());
            if !compatible_crtcs.contains(&crtc_handle) {
                continue;
            }

            if self.plane_is_type(*plane_handle, plane_type)? {
                return Ok(Some(*plane_handle));
            }
        }

        Ok(None)
    }

    fn plane_is_type(
        &self,
        plane_handle: plane::Handle,
        plane_type: PlaneType,
    ) -> Result<bool, MonitorSetupError> {
        let properties = self.card.get_properties(plane_handle)?;
        for (&id, &value) in properties.iter() {
            let Ok(info) = self.card.get_property(id) else {
                continue;
            };

            if info
                .name()
                .to_str()
                .map(|name| name == "type")
                .unwrap_or(false)
            {
                return Ok(value == (plane_type as u32).into());
            }
        }

        Ok(false)
    }
    /// Poll for events (page flip, hotplug, etc.)
    /// This blocks until an event is received
    pub fn poll_events(&mut self) -> Result<(), EasyDRMError> {
        self.poll_events_ex([])
    }
    /// Extended version of [[poll_events]] that allows waiting for additional fds
    pub fn poll_events_ex(
        &mut self,
        extra_fds: impl IntoIterator<Item = RawFd>,
    ) -> Result<(), EasyDRMError> {
        let drm_fd = self.card.as_fd();
        let uevents_socket = self.uevent_socket.as_ref();

        // preparar descritores para poll
        let mut fds = vec![PollFd::new(drm_fd, PollFlags::POLLIN)];
        fds.extend(
            extra_fds
                .into_iter()
                .map(|f| PollFd::new(unsafe { BorrowedFd::borrow_raw(f) }, PollFlags::POLLIN)),
        );
        if let Some(uevents_socket) = uevents_socket {
            fds.push(PollFd::new(uevents_socket.fd.as_fd(), PollFlags::POLLIN));
        }

        // bloquear até haver evento
        poll(&mut fds, PollTimeout::NONE).ok();

        let drm_ready = fds[0]
            .revents()
            .unwrap_or(PollFlags::empty())
            .contains(PollFlags::POLLIN);

        if let Some(uevents_socket) = uevents_socket {
            let hotplug_ready = fds
                .iter()
                .find(|p| p.as_fd().as_raw_fd() == uevents_socket.fd.as_raw_fd())
                .and_then(|p| p.revents())
                .unwrap_or(PollFlags::empty())
                .contains(PollFlags::POLLIN);

            if hotplug_ready && uevents_socket.drain_hotplug_events().unwrap_or(false) {
                println!("[INFO] Hotplug detected, refreshing monitors.");
                self.handle_hotplug()?;
            }
        }

        if drm_ready {
            Self::handle_drm_events(&mut self.card, &mut self.monitors)?;
        }
        Ok(())
    }
    /// Non-blocking version of [[poll_events]]
    pub async fn poll_events_async(&mut self) -> Result<(), EasyDRMError> {
        let drm_sync_fd = self.card.as_raw_fd();
        let drm_async_fd = AsyncFd::with_interest(drm_sync_fd, Interest::READABLE)?;
        let uevents_raw_fd = self.uevent_socket.as_ref().map(|s| s.fd.as_raw_fd());
        unsafe {
            fcntl(
                drm_sync_fd,
                F_SETFL,
                fcntl(drm_sync_fd, F_GETFL) | O_NONBLOCK,
            );
            if let Some(fd) = uevents_raw_fd {
                fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
            }
        }
        let uevents_async_fd = self
            .uevent_socket
            .as_ref()
            .map(|s| AsyncFd::with_interest(s.fd.as_raw_fd(), Interest::READABLE))
            .transpose()?;
        tokio::select! {
            guard = drm_async_fd.readable() => {
                let mut guard = guard?;
                if let Ok(r) = guard.try_io(|_fd| {
                    Self::handle_drm_events(&mut self.card, &mut self.monitors)
                }) { r? }
            }

            _ = async {
                if let Some(ref uevents_async_fd) = uevents_async_fd {
                    uevents_async_fd.readable().await
                } else {
                    pending().await
                }
            } => {
                if let Some(ue) = self.uevent_socket.as_ref()
                && ue.drain_hotplug_events().unwrap_or(false) {
                    self.handle_hotplug()?;
                }
            }
        }
        Ok(())
    }

    /// Get an iterator over all monitors
    pub fn monitors(&self) -> impl Iterator<Item = &Monitor<T>> {
        self.monitors.values()
    }

    /// Returns a clone of the shared OpenGL ES bindings for the global EGL context.
    pub fn gl(&self) -> Result<crate::gl::Gles2, GlesContextError> {
        let ctx = self
            .shared_gles_context
            .lock()
            .map_err(|_| GlesContextError::MakeCurrentFailed)?;
        Ok(ctx.gl().clone())
    }

    /// Makes the shared EGL context current on the calling thread.
    pub fn make_current(&self) -> Result<(), GlesContextError> {
        let ctx = self
            .shared_gles_context
            .lock()
            .map_err(|_| GlesContextError::MakeCurrentFailed)?;
        ctx.make_current_surfaceless()
    }

    /// Resolves an EGL/GL symbol from the shared EGL display.
    pub fn get_proc_address(&self, symbol: &str) -> *const std::ffi::c_void {
        self.shared_gles_context
            .lock()
            .map(|ctx| ctx.get_proc_address(symbol))
            .unwrap_or(std::ptr::null())
    }

    /// Returns a clone of the shared EGL context handle.
    pub fn egl_context(&self) -> Arc<Mutex<GlesContext>> {
        Arc::clone(&self.shared_gles_context)
    }

    /// Get an iterator over all monitors
    pub fn monitors_mut(&mut self) -> impl Iterator<Item = &mut Monitor<T>> {
        self.monitors.values_mut()
    }

    /// Get a specific monitor by connector handle
    pub fn get_monitor_mut(&mut self, connector_id: connector::Handle) -> Option<&mut Monitor<T>> {
        self.monitors.get_mut(&connector_id)
    }

    /// Get a specific monitor by connector handle
    pub fn get_monitor(&self, connector_id: connector::Handle) -> Option<&Monitor<T>> {
        self.monitors.get(&connector_id)
    }

    fn create_egl_fence_fd(ctx: &GlesContext) -> Result<OwnedFd, String> {
        ctx.make_current_surfaceless()
            .map_err(|e| format!("failed to make current context for fence creation: {e}"))?;
        let egl = ctx.display().egl();
        let (fence_fd, sync) = unsafe {
            let sync = egl.CreateSyncKHR(
                egl.GetCurrentDisplay(),
                EGL_SYNC_FENCE_KHR,
                std::ptr::null(),
            );

            if sync.is_null() {
                return Err("Failed to create EGL sync".to_string());
            }


            let fence_fd = egl.DupNativeFenceFDANDROID(egl.GetCurrentDisplay(), sync);
            if fence_fd < 0 {
                egl.DestroySyncKHR(egl.GetCurrentDisplay(), sync);
                return Err(format!("Failed to duplicate fence FD: fence_fd={fence_fd}"));
            }

            (fence_fd, sync as *mut std::ffi::c_void)
        };
        if !sync.is_null() {
            unsafe{egl.DestroySyncKHR(egl.GetCurrentDisplay(), sync);}
        }
        if fence_fd < 0 {
            return Err(format!("invalid fence fd: {fence_fd}"));
        }
        Ok(unsafe { OwnedFd::from_raw_fd(fence_fd) })
    }

    /// Swap buffers for all monitors that were drawn to.
    ///
    /// Each monitor that set `was_drawn = true` during this frame contributes
    /// to a single atomic commit, avoiding EBUSY races with NONBLOCK commits.
    pub fn swap_buffers_with_result(&mut self) -> Result<SwapResult, EasyDRMError> {
        let mut atomic_req = AtomicModeReq::new();
        let mut flags = AtomicCommitFlags::PAGE_FLIP_EVENT | AtomicCommitFlags::NONBLOCK;
        let committed_connectors = self
            .monitors
            .iter()
            .filter_map(|(&connector_id, monitor)| {
                if monitor.can_render() && monitor.was_drawn() {
                    Some(connector_id)
                } else {
                    None
                }
            })
            .collect::<Vec<_>>();

        if committed_connectors.is_empty() {
            return Ok(SwapResult {
                committed_connectors,
                render_fence: -1,
            });
        }

        self.last_fence_fd = Some({
            let ctx = self
                .shared_gles_context
                .lock()
                .map_err(|_| MonitorSetupError::DrmError("Shared GLES context poisoned".into()))?;
            Self::create_egl_fence_fd(ctx.deref()).map_err(MonitorSetupError::DrmError)?
        });
        let fence_fd = self.last_fence_fd.as_ref().map(|f| f.as_raw_fd()).unwrap_or(-1);
        for connector_id in committed_connectors.iter().copied() {
            let Some(monitor) = self.monitors.get_mut(&connector_id) else {
                continue;
            };
            if monitor.needs_mode_set() {
                flags |= AtomicCommitFlags::ALLOW_MODESET;
            }

            monitor.populate_commit(&self.card, &mut atomic_req, self.last_fence_fd.as_ref().map(|f| f.as_raw_fd()))?;
            monitor.reset_drawn_flag();
        }

        if !committed_connectors.is_empty() {
            self
                .card
                .atomic_commit(flags, atomic_req)
                .map_err(|e| MonitorSetupError::DrmError(format!("Failed to commit: {}", e)))?
        }

        for connector_id in committed_connectors.iter().copied() {
            self.mark_fast_group_commit(connector_id);
        }

        Ok(SwapResult {
            committed_connectors,
            render_fence: fence_fd,
        })
    }

    pub fn swap_buffers(&mut self) -> Result<(), EasyDRMError> {
        let _ = self.swap_buffers_with_result()?;
        Ok(())
    }

    /// Get the number of connected monitors
    pub fn monitor_count(&self) -> usize {
        self.monitors.len()
    }

    /// Check if there are any monitors connected
    pub fn has_monitors(&self) -> bool {
        !self.monitors.is_empty()
    }

    /// Check if any monitor can render
    pub fn any_can_render(&self) -> bool {
        self.monitors.values().any(|m| m.can_render())
    }

    /// Get monitors grouped by refresh rate.
    ///
    /// This is currently informational for callers that want to drive custom
    /// scheduling policies; EasyDRM itself does not yet alter timing based on
    /// these groups.
    pub fn refresh_rate_groups(&self) -> &HashMap<u32, Vec<connector::Handle>> {
        &self.refresh_rate_groups
    }

    /// Returns true once after every cycle where all monitors in the fastest refresh
    /// rate group have swapped their buffers.
    ///
    /// Call this from your main loop to synchronize global logic (simulation, input
    /// processing, etc.) to the fastest monitor's cadence.
    pub fn should_update(&mut self) -> bool {
        if self.should_update_flag {
            self.should_update_flag = false;
            self.reset_fastest_group_pending();
            true
        } else {
            false
        }
    }

    fn handle_drm_events(
        card: &mut Card,
        monitors: &mut HashMap<connector::Handle, Monitor<T>>,
    ) -> std::io::Result<()> {
        // Wait for events from DRM
        for event in card.receive_events()? {
            match event {
                Event::PageFlip(page_flip_event) => {
                    // Find the monitor that completed the page flip
                    // Set can_render = true for that monitor
                    let crtc_handle = page_flip_event.crtc;

                    for monitor in monitors.values_mut() {
                        if monitor.crtc().handle() == crtc_handle {
                            monitor.set_can_render(true);
                        }
                    }
                }
                _ => {}
            }
        }
        Ok(())
    }
}

// Special implementation for unit type - no user context
impl EasyDRM<()> {
    /// Initialize EasyDRM without any custom context
    ///
    /// This is a convenience method for when you don't need per-monitor data.
    /// Equivalent to `EasyDRM::init(|_| ())`.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let easydrm = EasyDRM::init_empty()?;
    ///
    /// for monitor in easydrm.monitors() {
    ///     // No custom context, just use GL directly
    ///     let gl = monitor.gl();
    ///     // ...
    /// }
    /// ```
    pub fn init_empty() -> Result<Self, EasyDRMError> {
        Self::init(|_| ())
    }
}