#![allow(linker_messages)] use crate::error::*; use crate::facility::*; use crate::geometry::*; use crate::module::*; use crate::x::*; use std::num::NonZero; use std::process::ExitCode; use std::sync::Arc; use std::sync::Mutex; use std::time::Duration; use async_channel::{ Sender, Receiver }; use async_executor::StaticExecutor; use futures_lite::future; use xcb::{ Xid }; use xcb::x::{ ClearArea, ClientMessageData, Gc, ChangeGc, Cw, CreateWindow, Drawable, EventMask, PolyFillArc, PolyFillRectangle, Screen, Visibility, WindowClass }; mod error; mod facility; mod geometry; mod module; mod x; static EXECUTOR: StaticExecutor = StaticExecutor::new(); struct DockConfiguration { thickness: u16, baseline_offset: i8, edge_inset: i8, side: Side, background: Color, foreground: Color, use_rounded_inside_corners: bool, use_rounded_outside_corners: bool, } struct Dock { configuration: DockConfiguration, window: Window, is_visible: bool, bounds: Arc>, font: Arc, baseline_position: i16, facilities: FacilityMap, time_module: Arc>, } unsafe impl Send for Dock { } impl HasWindow for Dock { fn window(&self) -> &Window { &self.window } } fn main() -> ExitCode { let (shutdown_sender, shutdown_receiver) = async_channel::unbounded(); let n_extra_threads = std::thread::available_parallelism() .map(|i| i.into()).unwrap_or(1); for _ in 0 .. n_extra_threads { let child_receiver = Receiver::clone(&shutdown_receiver); let _ = std::thread::spawn(move || { log_and_ignore_errors(future::block_on( EXECUTOR.run(child_receiver.recv()))); }); } future::block_on(async { if let Err(error) = async_main(shutdown_sender).await { error.log(); println!("That means... we are released from our task. Fare well."); ExitCode::FAILURE } else { ExitCode::SUCCESS } }) } async fn async_main(_shutdown_sender: Sender<()>) -> Result<()> { let display = Arc::new(Display::new()?); let configuration = DockConfiguration::new(&display)?; let dock = Dock::new(Arc::clone(&display), configuration)?; let (redraw_sender, redraw_receiver) = async_channel::unbounded(); let event_task = EXECUTOR.spawn( event_loop(display, Arc::clone(&dock), Sender::clone(&redraw_sender))); let (sleep_sender, sleep_receiver) = async_channel::unbounded(); let sleep_task = EXECUTOR.spawn(sleep_loop(sleep_receiver, redraw_sender)); /* Since we declared Dock as Send, we could do this on another * thread, but it's easier to do it on the primary one. */ redraw_loop(dock, redraw_receiver, sleep_sender).await?; event_task.cancel().await; sleep_task.cancel().await; Ok(()) } impl DockConfiguration { fn new(display: &Arc) -> Result { // #d4ffcc let background = display.allocate_color(54484, 65535, 52428)?; // #5c01be let foreground = display.allocate_color(23644, 257, 48830)?; Ok(DockConfiguration { thickness: 34, baseline_offset: 2, edge_inset: 12, side: Side::Bottom, background, foreground, use_rounded_inside_corners: false, use_rounded_outside_corners: true, }) } } impl Dock { fn new(display: Arc, configuration: DockConfiguration) -> Result>> { let screen = display.screen(); let dock_bounds = Dock::compute_bounds(&screen, &configuration); let window = Window::new(Arc::clone(&display), &mut CreateWindow { depth: xcb::x::COPY_FROM_PARENT as u8, wid: xcb::x::Window::none(), parent: screen.root(), x: dock_bounds.left as i16, y: dock_bounds.top as i16, width: dock_bounds.width, height: dock_bounds.height, border_width: 0, class: WindowClass::InputOutput, visual: screen.root_visual(), value_list: &[ Cw::BackPixel(configuration.background.as_pixel()), Cw::EventMask(EventMask::EXPOSURE | EventMask::VISIBILITY_CHANGE | EventMask::BUTTON_PRESS), ], })?; let font = Font::new(Arc::clone(&display), "FantasqueSansM Nerd Font Mono:style=Regular:size=18")?; let font_height = font.ascent() + font.descent(); let vertical_padding = (dock_bounds.height - font_height) / 2; let baseline_position = font.ascent() as i16 + vertical_padding as i16 + configuration.baseline_offset as i16; let facilities = FacilityMap::new(); let time_module = TimeModule::new()?; /* We start is_visible at false. Since redraw events set it to true, this * won't make us miss any drawing. */ let dock = Dock { window, configuration, is_visible: false, bounds: Arc::new(dock_bounds), font, baseline_position, facilities, time_module, }; dock.set_string_property(&xcb::x::ATOM_WM_NAME, b"sandbar")?; dock.set_atom_property(&dock.atoms().wm_protocols, &[dock.atoms().wm_delete_window])?; dock.set_atom_property(&dock.atoms().wm_type, &[dock.atoms().wm_type_dock])?; dock.set_strut_properties(&screen)?; dock.map_window()?; Ok(Arc::new(Mutex::new(dock))) } fn set_strut_properties(&self, screen: &Screen) -> Result<()> { let atoms = self.atoms(); let thickness = self.configuration.thickness as u32; let strut_values = match self.configuration.side { Side::Left => &[thickness, 0 as u32, 0 as u32, 0 as u32], Side::Right => &[0 as u32, thickness, 0 as u32, 0 as u32], Side::Top => &[0 as u32, 0 as u32, thickness, 0 as u32], Side::Bottom => &[0 as u32, 0 as u32, 0 as u32, thickness], }; self.set_cardinal_property(&atoms.wm_strut, strut_values)?; let strut_partial_values = &[ strut_values[0], strut_values[1], strut_values[2], strut_values[3], 0 as u32, if self.configuration.side == Side::Left { screen.height_in_pixels() as u32 } else { 0 as u32 }, 0 as u32, if self.configuration.side == Side::Right { screen.height_in_pixels() as u32 } else { 0 as u32 }, 0 as u32, if self.configuration.side == Side::Top { screen.width_in_pixels() as u32 } else { 0 as u32 }, 0 as u32, if self.configuration.side == Side::Bottom { screen.width_in_pixels() as u32 } else { 0 as u32 }, ]; self.set_cardinal_property(&atoms.wm_strut_partial, strut_partial_values)?; Ok(()) } fn compute_bounds(screen: &Screen, configuration: &DockConfiguration) -> Rectangle { if configuration.side == Side::Top || configuration.side == Side::Bottom { let left = 0; let width = screen.width_in_pixels(); let height = configuration.thickness; let top = if configuration.side == Side::Bottom { screen.height_in_pixels() - height } else { 0 }; Rectangle { left, top, width, height } } else { let top = 0; let height = screen.height_in_pixels(); let width = configuration.thickness; let left = if configuration.side == Side::Right { screen.width_in_pixels() - width } else { 0 }; Rectangle { left, top, width, height } } } async fn redraw(&self) -> Result> { let drawable = Drawable::Window(self.window_id()); let context = GraphicContext::new( Arc::clone(self.display()), drawable)?; self.erase_all()?; if self.configuration.use_rounded_inside_corners || self.configuration.use_rounded_outside_corners { self.draw_corners(drawable, &context)?; } self.draw_text("playful cool fic tech nonfic", Alignment::Left)?; let time = self.time_module.lock()?.format(); self.draw_text(&time, Alignment::Right)?; let mut shortest_duration = None; let next_duration = self.time_module.lock()?.sleep_duration(); shortest_duration = shorter_duration(shortest_duration, next_duration); Ok(shortest_duration) } fn erase_all(&self) -> Result<()> { let cookie = self.send_request_checked(&ClearArea { exposures: false, window: self.window().window_id(), x: 0, y: 0, width: self.bounds.width, height: self.bounds.height, }); self.check_request(cookie)?; Ok(()) } fn draw_corners(&self, drawable: Drawable, context: &GraphicContext) -> Result<()> { let black_pixel = self.screen().black_pixel(); let mut corner_squares = Vec::new(); let mut corner_arcs = Vec::new(); if self.configuration.use_rounded_outside_corners { for corner in self.configuration.side.corners_on_side() { let (corner_square, corner_arc) = self.compute_corner_regions(*corner); corner_squares.push(corner_square); corner_arcs.push(corner_arc); } } if self.configuration.use_rounded_inside_corners { for corner in self.configuration.side.opposite().corners_on_side() { let (corner_square, corner_arc) = self.compute_corner_regions(*corner); corner_squares.push(corner_square); corner_arcs.push(corner_arc); } } let cookie = self.send_request_checked(&ChangeGc { gc: context.graphic_context_id(), value_list: &[ Gc::Foreground(black_pixel), ], }); self.check_request(cookie)?; let cookie = self.send_request_checked(&PolyFillRectangle { drawable: drawable, gc: context.graphic_context_id(), rectangles: &corner_squares, }); self.check_request(cookie)?; let cookie = self.send_request_checked(&ChangeGc { gc: context.graphic_context_id(), value_list: &[ Gc::Foreground(self.configuration.background.as_pixel()), ], }); self.check_request(cookie)?; let cookie = self.send_request_checked(&PolyFillArc { drawable: drawable, gc: context.graphic_context_id(), arcs: &corner_arcs, }); self.check_request(cookie)?; Ok(()) } fn compute_corner_regions(&self, corner: Corner) -> (xcb::x::Rectangle, xcb::x::Arc) { let radius = self.configuration.thickness / 2; let diameter = self.configuration.thickness; let bounds = &self.bounds; let corner_square = bounds.corner_square(corner, radius) .to_x_rectangle(); let angle1 = corner.first_clockwise_side().to_x_angle(); let corner_arc = bounds.corner_square(corner, diameter) .to_x_arc(angle1, X_CLOCKWISE_RIGHT_ANGLE); (corner_square, corner_arc) } fn draw_text(&self, text: &str, alignment: Alignment) -> Result<()> { let context = FontGraphicContext::new(self.window())?; let color = &self.configuration.foreground; let text = self.font.text_span(text)?; let mut location = Point::::zero(); location.x += text.draw_offset().x as i32; location.y += self.baseline_position as i32; match alignment { Alignment::Left => { location.x += self.configuration.edge_inset as i32; } Alignment::Right => { location.x += self.bounds.width as i32 - text.draw_size().width as i32; location.x -= self.configuration.edge_inset as i32; } } text.draw(&context, color, location)?; Ok(()) } } impl HasDisplay for Dock { fn display(&self) -> &Arc { self.window.display() } } impl HasConnection for Dock { fn connection(&self) -> &Connection { self.window.connection() } } async fn event_loop(display: Arc, dock: Arc>, redraw_sender: Sender<()>) { loop { match display.wait_for_event() { result@Err(_) => log_and_ignore_errors(result), Ok(xcb::Event::X(xcb::x::Event::Expose(_event))) => { if let Ok(mut dock) = dock.lock() { dock.is_visible = true; } log_and_ignore_errors(redraw_sender.send(()).await); } Ok(xcb::Event::X(xcb::x::Event::VisibilityNotify(event))) => { if let Ok(mut dock) = dock.lock() { if event.window() == dock.window.window_id() { dock.is_visible = event.state() != Visibility::FullyObscured; /* We don't initiate a redraw here, instead waiting for the * redraw event. */ } } } Ok(xcb::Event::X(xcb::x::Event::ButtonPress(event))) => { println!("click {:?}", event); } Ok(xcb::Event::X(xcb::x::Event::ClientMessage(event))) => { if let ClientMessageData::Data32([atom, ..]) = event.data() { if atom == display.atoms().wm_delete_window.resource_id() { break; } } } Ok(event) => { println!("unknown event {:?}", event); } } } } async fn sleep_loop(sleep_receiver: Receiver, redraw_sender: Sender<()>) { loop { if let Ok(duration) = sleep_receiver.recv().await { std::thread::sleep(duration); /* If it's not visible, the redraw loop will skip the actual redraw, so * we don't need to worry at this end. */ log_and_ignore_errors(redraw_sender.send(()).await); } else { break } } } async fn redraw_loop(dock: Arc>, redraw_receiver: Receiver<()>, sleep_sender: Sender) -> Result<()> { loop { if let Ok(()) = redraw_receiver.recv().await { let duration = match dock.lock() { Ok(dock) => { if !dock.is_visible { continue } match dock.redraw().await { Ok(Some(duration)) => { if let Err(error) = dock.connection().flush() { Into::::into(error).log(); } Some(duration) } Ok(None) => None, result@Err(_) => { log_and_ignore_errors(result); None } } } result@Err(_) => { log_and_ignore_errors(result); None } }; if let Some(duration) = duration { log_and_ignore_errors(sleep_sender.send(duration).await); } } else { break } } Ok(()) } fn shorter_duration(a: Option, b: Option) -> Option { if let Some(a_value) = a { if let Some(b_value) = b && b_value < a_value { b } else { a } } else { b } }