easydrm 0.1.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
//! # 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(|gl, width, height| 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::os::fd::{AsFd, BorrowedFd, RawFd};
use std::os::unix::io::AsRawFd;

use drm::Device;
use drm::control::{Device as ControlDevice, Event, connector};
use gbm::Device as GbmDevice;
use nix::poll::{PollFd, PollFlags, PollTimeout, poll};
use thiserror::Error;

use crate::card::Card;
use crate::monitor::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"));
}

#[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 EasyDRM<T> {
    card: Card,
    gbm_device: GbmDevice<std::fs::File>,
    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 Fn(&crate::gl::Gles2, usize, usize) -> T + 'static>,
    uevent_socket: Option<hotplug::UEventSocket>,
}

impl<T> EasyDRM<T> {
    /// Initialize EasyDRM with a custom context constructor for each monitor
    ///
    /// The context_constructor is called for each monitor with access to its GL bindings,
    /// allowing you to initialize per-monitor resources (like Skia surfaces, Cairo contexts, etc.)
    ///
    /// # Example
    ///
    /// ```ignore
    /// struct MyContext {
    ///     skia_surface: skia::Surface,
    /// }
    ///
    /// let easydrm = EasyDRM::init(|gl| {
    ///     MyContext {
    ///         skia_surface: create_skia_surface(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: Fn(&crate::gl::Gles2, usize, usize) -> 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 mut easydrm = EasyDRM {
            card,
            gbm_device,
            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(),
        };
        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();

        // Setup monitors
        for connector_id in connector_handles {
            match Monitor::setup(
                &self.card,
                &self.gbm_device,
                connector_id,
                |gl, width, height| (self.context_constructor)(gl, width, height),
            ) {
                Ok(monitor) => {
                    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);
        }

        // Add newly connected monitors
        for connector_id in newly_connected {
            match Monitor::setup(
                &self.card,
                &self.gbm_device,
                connector_id,
                |gl, width, height| (self.context_constructor)(gl, width, height),
            ) {
                Ok(monitor) => {
                    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(())
    }
    /// 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.has_hotplug_event().unwrap_or(false) {
                println!("[INFO] Hotplug detected, refreshing monitors.");
                self.handle_hotplug()?;
            }
        }

        if drm_ready {
            self.handle_drm_events()?;
        }
        Ok(())
    }

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

    /// 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)
    }

    /// Swap buffers for all monitors that were drawn to.
    ///
    /// Each monitor that set `was_drawn = true` during this frame gets its own
    /// `Monitor::swap_buffers()` call, which issues the atomic commit and
    /// fence hand-off for that monitor.
    pub fn swap_buffers(&mut self) -> Result<(), EasyDRMError> {
        // Rebuild the set with swapped monitors
        let mut committed = Vec::new();
        for (&connector_id, monitor) in self.monitors.iter_mut() {
            if monitor.was_drawn() {
                monitor.swap_buffers(&self.card)?;
                monitor.reset_drawn_flag();
                committed.push(connector_id);
            }
        }
        for connector_id in committed {
            self.mark_fast_group_commit(connector_id);
        }

        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(&mut self) -> std::io::Result<()> {
        // Wait for events from DRM
        for event in self.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 self.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(|_gl| ())`.
    ///
    /// # 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(|_, _, _| ())
    }
}