x11-overlay 0.1.0

A library for creating overlay interfaces on X11 systems using Cairo for rendering
Documentation
use anyhow::Result;
use x11rb::protocol::xproto::*;

pub fn create_gc_with_color(
    conn: &impl x11rb::connection::Connection,
    drawable: Drawable,
    color: u32,
) -> Result<Gcontext> {
    let gc = conn.generate_id()?;
    let aux = CreateGCAux::new().foreground(color);
    conn.create_gc(gc, drawable, &aux)?;
    Ok(gc)
}

pub fn get_visual_depth(visual: &Visualtype) -> u8 {
    match visual.class {
        VisualClass::TRUE_COLOR => {
            let r_bits = visual.red_mask.count_ones();
            let g_bits = visual.green_mask.count_ones();
            let b_bits = visual.blue_mask.count_ones();
            (r_bits + g_bits + b_bits) as u8
        }
        _ => 24,
    }
}

pub fn rgb_to_pixel(r: u8, g: u8, b: u8, visual: &Visualtype) -> u32 {
    match visual.class {
        VisualClass::TRUE_COLOR => {
            let r_shift = visual.red_mask.trailing_zeros();
            let g_shift = visual.green_mask.trailing_zeros();
            let b_shift = visual.blue_mask.trailing_zeros();

            ((r as u32) << r_shift) | ((g as u32) << g_shift) | ((b as u32) << b_shift)
        }
        _ => 0,
    }
}

pub fn argb_to_pixel(a: u8, r: u8, g: u8, b: u8) -> u32 {
    ((a as u32) << 24) | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32)
}

#[derive(Debug, Clone, Copy)]
pub struct Point {
    pub x: i16,
    pub y: i16,
}

impl Point {
    pub fn new(x: i16, y: i16) -> Self {
        Self { x, y }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct Size {
    pub width: u16,
    pub height: u16,
}

impl Size {
    pub fn new(width: u16, height: u16) -> Self {
        Self { width, height }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct Bounds {
    pub x: i16,
    pub y: i16,
    pub width: u16,
    pub height: u16,
}

impl Bounds {
    pub fn new(x: i16, y: i16, width: u16, height: u16) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }

    pub fn from_point_size(point: Point, size: Size) -> Self {
        Self {
            x: point.x,
            y: point.y,
            width: size.width,
            height: size.height,
        }
    }

    pub fn contains_point(&self, point: Point) -> bool {
        point.x >= self.x
            && point.x < self.x + self.width as i16
            && point.y >= self.y
            && point.y < self.y + self.height as i16
    }

    pub fn intersects(&self, other: &Bounds) -> bool {
        self.x < other.x + other.width as i16
            && self.x + self.width as i16 > other.x
            && self.y < other.y + other.height as i16
            && self.y + self.height as i16 > other.y
    }
}