x11-overlay 0.1.0

A library for creating overlay interfaces on X11 systems using Cairo for rendering
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
use crate::graphics::{Color, FontDesc, GraphicsContext, Rect, TextLayout};
use crate::ui::{Component, ComponentExt};
use anyhow::{Context, Result};
use x11rb::connection::Connection;
use x11rb::protocol::shape;
use x11rb::protocol::xproto::ConnectionExt as XprotoConnectionExt;
use x11rb::protocol::xproto::*;
use x11rb::protocol::Event;
use x11rb::wrapper::ConnectionExt;

pub struct Overlay {
    conn: x11rb::xcb_ffi::XCBConnection,
    window: Window,
    screen: Screen,
    graphics: Option<GraphicsContext>,
    visual: Option<Visualtype>,
    components: Vec<Box<dyn Component>>,
    needs_redraw: bool,
}

impl Overlay {
    pub fn new() -> Result<Self> {
        let (conn, screen_num) = x11rb::xcb_ffi::XCBConnection::connect(None)
            .context("Failed to connect to X11 server")?;

        let setup = conn.setup();
        let screen = setup.roots[screen_num].clone();

        let window = conn.generate_id()?;

        Ok(Self {
            conn,
            window,
            screen,
            graphics: None,
            visual: None,
            components: Vec::new(),
            needs_redraw: true,
        })
    }

    #[allow(dead_code)]
    pub fn add_component(&mut self, component: Box<dyn Component>) {
        self.components.push(component);
        self.needs_redraw = true;
    }

    #[allow(dead_code)]
    pub fn add_components(&mut self, components: impl IntoIterator<Item = Box<dyn Component>>) {
        self.components.extend(components);
        self.needs_redraw = true;
    }

    #[allow(dead_code)]
    pub fn remove_components_where<F>(&mut self, predicate: F)
    where
        F: Fn(&Box<dyn Component>) -> bool,
    {
        let original_len = self.components.len();
        self.components.retain(|component| !predicate(component));
        if self.components.len() != original_len {
            self.needs_redraw = true;
        }
    }

    #[allow(dead_code)]
    pub fn components_in_bounds(
        &self,
        bounds: crate::graphics::Rectangle,
    ) -> impl Iterator<Item = &Box<dyn Component>> {
        self.components
            .iter()
            .filter(move |component| component.bounds().intersects(&bounds))
    }

    pub fn screen_width(&self) -> u16 {
        self.screen.width_in_pixels
    }

    pub fn screen_height(&self) -> u16 {
        self.screen.height_in_pixels
    }

    pub fn run(&mut self) -> Result<()> {
        self.create_window()?;
        self.configure_window_properties()?;
        self.setup_click_through()?;
        self.setup_graphics()?;
        self.map_window()?;

        println!("Overlay window created and mapped");

        self.event_loop()
    }

    fn create_window(&mut self) -> Result<()> {
        let visual = self
            .find_argb_visual()
            .context("Failed to find suitable visual for overlay")?;

        self.visual = Some(visual);

        // Determine depth from visual
        let depth = self
            .screen
            .allowed_depths
            .iter()
            .find(|d| d.visuals.iter().any(|v| v.visual_id == visual.visual_id))
            .map(|d| d.depth)
            .unwrap_or(32);

        println!(
            "Using depth: {} for visual ID: 0x{:x}",
            depth, visual.visual_id
        );

        let colormap = self.conn.generate_id()?;
        self.conn
            .create_colormap(
                ColormapAlloc::NONE,
                colormap,
                self.screen.root,
                visual.visual_id,
            )
            .context("Failed to create colormap")?;

        let window_aux = CreateWindowAux::new()
            .background_pixel(0)
            .border_pixel(0)
            .colormap(colormap)
            .override_redirect(1) // Bypass window manager
            .event_mask(EventMask::EXPOSURE | EventMask::STRUCTURE_NOTIFY);

        self.conn
            .create_window(
                depth,
                self.window,
                self.screen.root,
                0,
                0, // x, y - position at top-left of screen
                self.screen.width_in_pixels,
                self.screen.height_in_pixels,
                0, // border_width
                WindowClass::INPUT_OUTPUT,
                visual.visual_id,
                &window_aux,
            )
            .context("Failed to create overlay window")?;

        Ok(())
    }

    fn setup_graphics(&mut self) -> Result<()> {
        if let Some(visual) = self.visual {
            let conn_ptr = &self.conn as *const _ as *mut x11rb::xcb_ffi::XCBConnection;
            let conn_static = unsafe { &*conn_ptr };

            self.graphics = Some(GraphicsContext::new(
                conn_static,
                self.window,
                &visual,
                self.screen.width_in_pixels as i32,
                self.screen.height_in_pixels as i32,
            )?);
        }
        Ok(())
    }

    fn find_argb_visual(&self) -> Option<Visualtype> {
        // Available visuals debug info (can be enabled for troubleshooting)
        // println!("Available visuals:");
        // for depth in &self.screen.allowed_depths {
        //     for visual in &depth.visuals {
        //         println!("  Depth: {}, Visual ID: 0x{:x}, Class: {:?}", depth.depth, visual.visual_id, visual.class);
        //     }
        // }

        // Use safe 32-bit visual approach
        if let Some(visual) = self
            .screen
            .allowed_depths
            .iter()
            .filter(|depth| depth.depth == 32)
            .flat_map(|depth| &depth.visuals)
            .filter(|visual| visual.class == VisualClass::TRUE_COLOR)
            .find(|visual| visual.visual_id >= 0x7a)
            .copied()
        {
            println!("Selected safe 32-bit visual: ID=0x{:x}", visual.visual_id);
            return Some(visual);
        }

        println!("No suitable visual found");
        None
    }

    fn configure_window_properties(&self) -> Result<()> {
        // Set window class for window manager recognition
        let class_name = b"x11-overlay\0x11-overlay\0";
        self.conn
            .change_property8(
                PropMode::REPLACE,
                self.window,
                AtomEnum::WM_CLASS,
                AtomEnum::STRING,
                class_name,
            )
            .context("Failed to set window class property")?;

        // Set window name
        let title = b"x11-overlay";
        self.conn
            .change_property8(
                PropMode::REPLACE,
                self.window,
                AtomEnum::WM_NAME,
                AtomEnum::STRING,
                title,
            )
            .context("Failed to set window title property")?;

        // Make window always on top and skip taskbar
        self.set_ewmh_properties()?;

        Ok(())
    }

    fn set_ewmh_properties(&self) -> Result<()> {
        // Get EWMH atoms
        let net_wm_state = self.conn.intern_atom(false, b"_NET_WM_STATE")?;
        let net_wm_state_above = self.conn.intern_atom(false, b"_NET_WM_STATE_ABOVE")?;
        let net_wm_state_sticky = self.conn.intern_atom(false, b"_NET_WM_STATE_STICKY")?;
        let net_wm_state_skip_taskbar = self
            .conn
            .intern_atom(false, b"_NET_WM_STATE_SKIP_TASKBAR")?;
        let net_wm_window_type = self.conn.intern_atom(false, b"_NET_WM_WINDOW_TYPE")?;
        let net_wm_window_type_desktop = self
            .conn
            .intern_atom(false, b"_NET_WM_WINDOW_TYPE_DESKTOP")?;

        let net_wm_state = net_wm_state.reply()?.atom;
        let net_wm_state_above = net_wm_state_above.reply()?.atom;
        let net_wm_state_sticky = net_wm_state_sticky.reply()?.atom;
        let net_wm_state_skip_taskbar = net_wm_state_skip_taskbar.reply()?.atom;
        let net_wm_window_type = net_wm_window_type.reply()?.atom;
        let net_wm_window_type_desktop = net_wm_window_type_desktop.reply()?.atom;

        // Set window states
        let states = [
            net_wm_state_above,
            net_wm_state_sticky,
            net_wm_state_skip_taskbar,
        ];
        self.conn
            .change_property32(
                PropMode::REPLACE,
                self.window,
                net_wm_state,
                AtomEnum::ATOM,
                &states,
            )
            .context("Failed to set EWMH window state properties")?;

        // Set window type to desktop for better click-through compatibility
        self.conn
            .change_property32(
                PropMode::REPLACE,
                self.window,
                net_wm_window_type,
                AtomEnum::ATOM,
                &[net_wm_window_type_desktop],
            )
            .context("Failed to set EWMH window type property")?;

        Ok(())
    }

    fn setup_click_through(&self) -> Result<()> {
        // Use XShape extension to make window click-through
        let shape_rectangles: &[Rectangle] = &[];

        shape::rectangles(
            &self.conn,
            shape::SO::SET,
            shape::SK::INPUT,
            ClipOrdering::UNSORTED,
            self.window,
            0,
            0, // x_offset, y_offset
            shape_rectangles,
        )
        .context("Failed to setup click-through with XShape extension")?;

        Ok(())
    }

    fn map_window(&self) -> Result<()> {
        self.conn
            .map_window(self.window)
            .context("Failed to map overlay window")?;
        self.conn.flush().context("Failed to flush X11 commands")?;
        Ok(())
    }

    fn event_loop(&mut self) -> Result<()> {
        let mut last_update = std::time::Instant::now();

        // Force initial render
        self.needs_redraw = true;

        loop {
            // Check for X11 events (non-blocking)
            while let Ok(Some(event)) = self.conn.poll_for_event() {
                if let Event::Expose(_) = event {
                    self.needs_redraw = true;
                }
            }

            // Update components
            let now = std::time::Instant::now();
            let delta_time = (now - last_update).as_secs_f64();
            last_update = now;

            // Update components and remove expired ones
            if self.components.update_all(delta_time) {
                self.needs_redraw = true;
            }

            // Remove expired components
            let removed_count = self.components.remove_expired();
            if removed_count > 0 {
                self.needs_redraw = true;
            }

            // Render if needed
            if self.needs_redraw {
                self.render()?;
                self.needs_redraw = false;
            }

            // Sleep briefly to avoid busy waiting
            std::thread::sleep(std::time::Duration::from_millis(16)); // ~60 FPS
        }
    }

    fn render(&mut self) -> Result<()> {
        // Get screen dimensions before borrowing graphics mutably
        let _screen_width = self.screen_width();
        let _screen_height = self.screen_height();

        if let Some(ref mut graphics) = self.graphics {
            graphics.clear()?;

            // Check if Cairo is available for text rendering
            if graphics.has_cairo_surface() {
                match graphics.get_cairo_context() {
                    Ok(Some(cairo_context)) => {
                        // Clear the surface
                        cairo_context.save().unwrap();
                        cairo_context.set_operator(cairo::Operator::Clear);
                        cairo_context.paint().unwrap();
                        cairo_context.restore().unwrap();

                        // Render actual components
                        match self
                            .components
                            .iter()
                            .try_for_each(|component| component.render(graphics))
                        {
                            Ok(_) => {
                                // Components rendered successfully
                            }
                            Err(_) => {
                                Self::render_fallback_graphics(graphics)?;
                            }
                        }
                    }
                    Ok(None) | Err(_) => {
                        Self::render_fallback_graphics(graphics)?;
                    }
                }
            } else {
                Self::render_fallback_graphics(graphics)?;
            }

            graphics.flush()
        } else {
            self.render_transparent_background()
        }
    }

    fn render_transparent_background(&mut self) -> Result<()> {
        if let Some(ref mut graphics) = self.graphics {
            graphics.clear()?;

            let font = FontDesc::new("DejaVu Sans", 24.0);
            let layout = TextLayout::new()
                .text("Hello from X11 Overlay!")
                .font(font)
                .color(Color::rgba(1.0, 1.0, 1.0, 0.9))
                .bounds(Rect::new(50, 50, 400, 100))
                .alignment(crate::graphics::Alignment::Center);

            layout.render(graphics.text_renderer(), 50, 80)?;

            graphics.copy_text_to_window()?;
            graphics.flush()?;
        } else {
            self.conn
                .clear_area(
                    false, // exposures - don't generate expose events
                    self.window,
                    0,
                    0, // x, y
                    self.screen.width_in_pixels,
                    self.screen.height_in_pixels,
                )
                .context("Failed to clear window area for transparency")?;

            self.conn
                .flush()
                .context("Failed to flush rendering commands")?;
        }

        Ok(())
    }

    fn render_fallback_graphics(graphics: &mut GraphicsContext) -> Result<()> {
        // Render rectangles representing where text components would be
        // This demonstrates the overlay positioning system works even without Cairo

        // Component 1: Basic text (represented by red rectangle)
        graphics.fill_rectangle(Rect::new(50, 50, 400, 50), Color::rgba(1.0, 0.3, 0.3, 0.9))?;

        // Component 2: Title text (represented by blue rectangle)
        graphics.fill_rectangle(
            Rect::new(graphics.width() / 2 - 200, 150, 400, 80),
            Color::rgba(0.3, 0.3, 1.0, 0.9),
        )?;

        // Component 3: Colored text (represented by green rectangle)
        graphics.fill_rectangle(
            Rect::new(100, 300, 350, 60),
            Color::rgba(0.3, 1.0, 0.3, 0.9),
        )?;

        // Component 4: Multiline text (represented by yellow rectangle)
        graphics.fill_rectangle(
            Rect::new(200, 450, 500, 120),
            Color::rgba(1.0, 1.0, 0.3, 0.9),
        )?;

        // Component 5: Semi-transparent overlay (represented by purple rectangle)
        graphics.fill_rectangle(
            Rect::new(graphics.width() - 350, graphics.height() - 200, 300, 150),
            Color::rgba(1.0, 0.3, 1.0, 0.7),
        )?;

        // Status indicator showing Cairo is disabled
        graphics.fill_rectangle(
            Rect::new(10, 10, 20, 20),
            Color::rgba(1.0, 0.5, 0.0, 1.0), // Orange = warning
        )?;

        Ok(())
    }
}