From adb499dcc8403ff24afe75dae4efd64ed6aaba18 Mon Sep 17 00:00:00 2001 From: CatThingy Date: Wed, 7 Jan 2026 18:12:06 -0800 Subject: [PATCH] More cleanup --- src/bar.rs | 437 +++++++------------------------------------ src/bar/component.rs | 63 +++++-- src/bar/state.rs | 296 +++++++++++++++++++++++++++++ src/main.rs | 2 +- 4 files changed, 415 insertions(+), 383 deletions(-) create mode 100644 src/bar/state.rs diff --git a/src/bar.rs b/src/bar.rs index 81212c6..5fd03f5 100644 --- a/src/bar.rs +++ b/src/bar.rs @@ -1,222 +1,97 @@ -use std::{ptr::NonNull, sync::Arc}; +use crate::bar::state::BarState; +use std::{cell::RefCell, rc::Rc}; -use log::debug; -use parley::{Alignment, AlignmentOptions, FontStack, FontWeight, FontWidth, TextStyle}; -use raw_window_handle::{ - RawDisplayHandle, RawWindowHandle, WaylandDisplayHandle, WaylandWindowHandle, -}; -use screen_13::prelude::*; -use smithay_client_toolkit::{ - compositor::{CompositorHandler, CompositorState}, - delegate_compositor, delegate_layer, delegate_output, delegate_registry, delegate_seat, - output::{OutputHandler, OutputState}, - registry::{ProvidesRegistryState, RegistryState}, - registry_handlers, - seat::{Capability, SeatHandler, SeatState}, - shell::{ - WaylandSurface, - wlr_layer::{ - Anchor, KeyboardInteractivity, Layer, LayerShell, LayerShellHandler, LayerSurface, - LayerSurfaceConfigure, - }, - }, -}; -use smol::channel::{Receiver, Sender}; -use wayland_client::{ - Connection, EventQueue, Proxy, QueueHandle, - globals::registry_queue_init, - protocol::{wl_output, wl_seat, wl_surface}, -}; +use futures_util::FutureExt; +use parley::{Alignment, AlignmentOptions, FontStack, TextStyle}; +use smol::{LocalExecutor, channel::Receiver}; +use wayland_client::EventQueue; -use crate::{ - Window, - bar::{ - component::{Clock, Component, ComponentData}, - text::TextRenderer, - }, +use crate::bar::{ + component::{Clock, Component, ComponentMailbox}, + text::TextRenderer, }; mod component; +mod state; mod text; -pub struct BarState { - pub registry_state: RegistryState, - pub seat_state: SeatState, - pub output_state: OutputState, - - pub width: u32, - pub height: u32, - pub exit: bool, - pub layer: LayerSurface, - - pub display: Display, - pub pool: HashPool, - device: Arc, - update_sender: Sender<()>, -} - pub struct Bar { pub state: BarState, pub event_queue: EventQueue, - text_renderer: TextRenderer, + executor: LocalExecutor<'static>, + text_renderer: Rc>, - components: Vec, + mailboxes: Vec>, update_recv: Receiver<()>, } impl Bar { pub fn new() -> Self { - let conn = Connection::connect_to_env().unwrap(); - let (globals, mut event_queue) = registry_queue_init(&conn).unwrap(); - let qh: QueueHandle = event_queue.handle(); - - // Initialize xdg_shell handlers so we can select the correct adapter - let compositor_state = - CompositorState::bind(&globals, &qh).expect("wl_compositor not available"); - let layer_shell = LayerShell::bind(&globals, &qh).expect("layer shell not available"); - let surface = compositor_state.create_surface(&qh); - // Create the window for adapter selection - let layer = - layer_shell.create_layer_surface(&qh, surface, Layer::Bottom, Some("conduit"), None); - layer.set_anchor(Anchor::TOP); - layer.set_keyboard_interactivity(KeyboardInteractivity::None); - - // Create the raw window handle for the surface. - let raw_display_handle = RawDisplayHandle::Wayland(WaylandDisplayHandle::new( - NonNull::new(conn.backend().display_ptr() as *mut _).unwrap(), - )); - - let raw_window_handle = RawWindowHandle::Wayland(WaylandWindowHandle::new( - NonNull::new(layer.wl_surface().id().as_ptr() as *mut _).unwrap(), - )); - let window = Window { - display_handle: raw_display_handle, - window_handle: raw_window_handle, - }; - - let s13_device = Arc::new( - Device::create_display( - DeviceInfoBuilder::default() - .select_physical_device(Box::new(DeviceInfo::integrated_gpu)) - .debug(true), - &window, - ) - .unwrap(), - ); - - let s13_surface = Surface::create(&s13_device, &window).unwrap(); - let formats = Surface::formats(&s13_surface).unwrap(); - let format = Surface::srgb(&formats).unwrap(); - let s13_swapchain = Swapchain::new( - &s13_device, - s13_surface, - SwapchainInfoBuilder::default() - .width(0) - .height(20) - .surface(format), - ) - .unwrap(); - - let s13_display = - screen_13::Display::new(&s13_device, s13_swapchain, DisplayInfo::default()).unwrap(); - let mut s13_pool = HashPool::new(&s13_device); - let (tx, rx) = smol::channel::unbounded(); + let (mut state, mut event_queue) = BarState::new(20, tx.clone()); - let components = vec![Component { - data: ComponentData::Clock(component::Clock { - format: "%Y-%m-%d | %I:%M:%S %p".to_owned(), - style: TextStyle { - font_stack: FontStack::Source("Iosevka".into()), - font_size: 16.0, - brush: [255, 255, 255, 255], - ..TextStyle::default() - }, - }), - }]; - - for component in &components { - match component.data { - ComponentData::Clock(_) => { - smol::spawn(Clock::update(tx.clone())).detach(); + let components = vec![Component::Clock(Clock::new( + TextStyle { + font_stack: FontStack::Source("Iosevka".into()), + font_size: 16.0, + brush: [255, 255, 255, 255], + ..TextStyle::default() + }, + "%Y-%m-%d | %I:%M:%S %p".to_owned(), + ))]; + + let mut mailboxes = vec![]; + let executor = LocalExecutor::new(); + + let text_renderer = Rc::new(RefCell::new(TextRenderer::new( + &state.device, + &mut state.pool, + ))); + + for component in components { + let tx = tx.clone(); + match component { + Component::Clock(clock) => { + mailboxes.push(clock.run(&executor, Rc::clone(&text_renderer), tx)) } } } - let text_renderer = TextRenderer::new(&s13_device, &mut s13_pool); - let mut bar_state = BarState { - registry_state: RegistryState::new(&globals), - seat_state: SeatState::new(&globals, &qh), - output_state: OutputState::new(&globals, &qh), - - width: 0, - height: 20, - exit: false, - layer, - - display: s13_display, - pool: s13_pool, - device: s13_device, - update_sender: tx.clone(), - }; - - event_queue.blocking_dispatch(&mut bar_state).unwrap(); + event_queue.blocking_dispatch(&mut state).unwrap(); Bar { - state: bar_state, + state, event_queue, text_renderer, - components, + executor, + mailboxes, update_recv: rx, } } pub fn draw(&mut self) { if let Some(swapchain_image) = self.state.display.acquire_next_image().unwrap() { - let font_stack = FontStack::from("Noto Sans"); - - let text_style = TextStyle { - font_stack, - font_size: 16.0, - brush: [255, 255, 255, 255], - font_width: FontWidth::EXPANDED, - font_weight: FontWeight::BOLD, - ..TextStyle::default() - }; - - let mut layout_builder = self.text_renderer.layout_builder(1.0, false, &text_style); - layout_builder.push_text("Hello world!"); - let (mut layout, _) = layout_builder.build(); - layout.break_all_lines(None); - layout.align( - Some(self.state.width as f32), - Alignment::Start, - AlignmentOptions::default(), - ); - self.text_renderer.push_layout(&layout); - - for component in &self.components { - match &component.data { - ComponentData::Clock(clock) => { - let mut layout = clock.layout(&mut self.text_renderer); - layout.break_all_lines(None); - layout.align( - Some(self.state.width as f32), - Alignment::End, - AlignmentOptions::default(), - ); - self.text_renderer.push_layout(&layout); - } + let text_renderer = &mut self.text_renderer.borrow_mut(); + for component in &self.mailboxes { + if let Some(mut layout) = component.mailbox.take() { + layout.break_all_lines(None); + layout.align( + Some(self.state.width as f32), + Alignment::End, + AlignmentOptions::default(), + ); + text_renderer.push_layout(&layout); + component.mailbox.set(Some(layout)); } } let mut render_graph = screen_13::graph::RenderGraph::new(); let swapchain_node = render_graph.bind_node(swapchain_image); - self.text_renderer.draw( + text_renderer.draw( &mut self.state.pool, &mut render_graph, self.state.width, @@ -231,197 +106,29 @@ impl Bar { } } - pub async fn update( + pub async fn update_loop( &mut self, ) -> Result { loop { - match futures_util::future::select( - futures_util::future::poll_fn(|cx| { - self.event_queue.poll_dispatch_pending(cx, &mut self.state) - }), - std::pin::pin!(self.update_recv.recv()), - ) - .await + let draw; { - futures_util::future::Either::Left((_, _)) => {} - futures_util::future::Either::Right((a, _)) => match a { - Ok(_) => self.draw(), - Err(_) => todo!(), - }, - }; - } - } -} - -impl CompositorHandler for BarState { - fn scale_factor_changed( - &mut self, - _conn: &Connection, - _qh: &QueueHandle, - _surface: &wl_surface::WlSurface, - _new_factor: i32, - ) { - // Not needed for this example. - debug!("compositor: scale factor changed"); - } - - fn transform_changed( - &mut self, - _conn: &Connection, - _qh: &QueueHandle, - _surface: &wl_surface::WlSurface, - _new_transform: wl_output::Transform, - ) { - // Not needed for this example. - debug!("compositor: transform changed"); - } - - fn frame( - &mut self, - _conn: &Connection, - _qh: &QueueHandle, - _surface: &wl_surface::WlSurface, - _time: u32, - ) { - // Not needed for this example. - debug!("compositor: frame changed"); - } - - fn surface_enter( - &mut self, - _conn: &Connection, - _qh: &QueueHandle, - _surface: &wl_surface::WlSurface, - _output: &wl_output::WlOutput, - ) { - // Not needed for this example. - debug!("compositor: surface enter"); - } - - fn surface_leave( - &mut self, - _conn: &Connection, - _qh: &QueueHandle, - _surface: &wl_surface::WlSurface, - _output: &wl_output::WlOutput, - ) { - // Not needed for this example. - debug!("compositor: surface leave"); - } -} - -impl OutputHandler for BarState { - fn output_state(&mut self) -> &mut OutputState { - &mut self.output_state - } - - fn new_output( - &mut self, - _conn: &Connection, - _qh: &QueueHandle, - _output: wl_output::WlOutput, - ) { - debug!("output: new output"); - let size = self - .output_state - .info(&_output) - .and_then(|v| v.logical_size) - .unwrap(); - self.width = size.0 as u32; - self.layer.set_size(self.width, self.height); - self.layer.set_exclusive_zone(self.height as i32); - self.layer.commit(); - } - - fn update_output( - &mut self, - _conn: &Connection, - _qh: &QueueHandle, - _output: wl_output::WlOutput, - ) { - debug!("output: update output"); - } - - fn output_destroyed( - &mut self, - _conn: &Connection, - _qh: &QueueHandle, - _output: wl_output::WlOutput, - ) { - debug!("output: output destroyed"); - } -} - -impl SeatHandler for BarState { - fn seat_state(&mut self) -> &mut SeatState { - &mut self.seat_state - } - - fn new_seat(&mut self, _: &Connection, _: &QueueHandle, _: wl_seat::WlSeat) { - debug!("seat: new seat"); - } - - fn new_capability( - &mut self, - _conn: &Connection, - _qh: &QueueHandle, - _seat: wl_seat::WlSeat, - _capability: Capability, - ) { - debug!("seat: new capability"); - } - - fn remove_capability( - &mut self, - _conn: &Connection, - _: &QueueHandle, - _: wl_seat::WlSeat, - _capability: Capability, - ) { - debug!("seat: remove capability"); - } - - fn remove_seat(&mut self, _: &Connection, _: &QueueHandle, _: wl_seat::WlSeat) { - debug!("seat: remove seat"); - } -} - -impl LayerShellHandler for BarState { - fn closed(&mut self, _conn: &Connection, _qh: &QueueHandle, _layer: &LayerSurface) { - debug!("layer shell: closed"); - self.exit = true; - } - - fn configure( - &mut self, - _conn: &Connection, - _qh: &QueueHandle, - _layer: &LayerSurface, - _configure: LayerSurfaceConfigure, - _serial: u32, - ) { - debug!("layer shell: configure"); - self.display.set_swapchain_info( - self.display - .swapchain_info() - .to_builder() - .width(self.width) - .height(self.height), - ); - - smol::block_on(self.update_sender.send(())).unwrap(); - } -} - -delegate_compositor!(BarState); -delegate_output!(BarState); -delegate_seat!(BarState); -delegate_layer!(BarState); -delegate_registry!(BarState); + let mut tick_executor = std::pin::pin!(self.executor.tick().fuse()); + let mut poll_wayland = futures_util::future::poll_fn(|cx| { + self.event_queue.poll_dispatch_pending(cx, &mut self.state) + }) + .fuse(); + let mut redraw = std::pin::pin!(self.update_recv.recv().fuse()); + + draw = futures_util::select! { + _ = tick_executor => false, + _ = poll_wayland => false, + _ = redraw => true, + }; + } -impl ProvidesRegistryState for BarState { - fn registry(&mut self) -> &mut RegistryState { - &mut self.registry_state + if draw { + self.draw(); + } + } } - registry_handlers![OutputState]; } diff --git a/src/bar/component.rs b/src/bar/component.rs index d50c682..56a95d1 100644 --- a/src/bar/component.rs +++ b/src/bar/component.rs @@ -1,23 +1,39 @@ +use std::{ + cell::{Cell, RefCell}, + rc::Rc, +}; + use jiff::{Timestamp, TimestampRound, tz::TimeZone}; use parley::{Layout, TextStyle}; -use smol::channel::{SendError, Sender}; +use smol::{LocalExecutor, channel::Sender}; use crate::bar::text::TextRenderer; -pub struct Component { - pub data: ComponentData, +pub struct ComponentMailbox { + pub mailbox: Cell>>, } -pub enum ComponentData { +pub enum Component { Clock(Clock), } pub struct Clock { pub format: String, pub style: TextStyle<'static, [u8; 4]>, + mailbox: Rc, } impl Clock { + pub fn new(style: TextStyle<'static, [u8; 4]>, format: String) -> Self { + Clock { + format, + style, + mailbox: Rc::new(ComponentMailbox { + mailbox: Cell::new(None), + }), + } + } + pub fn layout(&self, text_renderer: &mut TextRenderer) -> Layout<[u8; 4]> { let time = Timestamp::now().to_zoned(TimeZone::system()); let timestamp = time.strftime(&self.format).to_string(); @@ -29,18 +45,31 @@ impl Clock { return layout; } - pub async fn update(tx: Sender<()>) -> Result> { - loop { - let next = Timestamp::now() - .round( - TimestampRound::new() - .mode(jiff::RoundMode::Ceil) - .smallest(jiff::Unit::Second), - ) - .unwrap(); - let waiting_time = Timestamp::now().duration_until(next).try_into().unwrap(); - smol::Timer::after(waiting_time).await; - tx.send(()).await?; - } + pub fn run( + self, + executor: &LocalExecutor<'static>, + text_renderer: Rc>, + tx: Sender<()>, + ) -> Rc { + let out_mailbox = Rc::clone(&self.mailbox); + let future = async move { + loop { + let layout = self.layout(&mut text_renderer.borrow_mut()); + self.mailbox.mailbox.set(Some(layout)); + tx.send(()).await.unwrap(); + let next = Timestamp::now() + .round( + TimestampRound::new() + .mode(jiff::RoundMode::Ceil) + .smallest(jiff::Unit::Second), + ) + .unwrap(); + let waiting_time = Timestamp::now().duration_until(next).try_into().unwrap(); + smol::Timer::after(waiting_time).await; + } + }; + executor.spawn(future).detach(); + + return out_mailbox; } } diff --git a/src/bar/state.rs b/src/bar/state.rs new file mode 100644 index 0000000..f61b864 --- /dev/null +++ b/src/bar/state.rs @@ -0,0 +1,296 @@ +use std::{ptr::NonNull, sync::Arc}; + +use raw_window_handle::{ + RawDisplayHandle, RawWindowHandle, WaylandDisplayHandle, WaylandWindowHandle, +}; + +use log::debug; +use screen_13::prelude::*; +use smithay_client_toolkit::{ + compositor::CompositorHandler, + compositor::CompositorState, + delegate_compositor, delegate_layer, delegate_output, delegate_registry, delegate_seat, + output::{OutputHandler, OutputState}, + registry::{ProvidesRegistryState, RegistryState}, + registry_handlers, + seat::{Capability, SeatHandler, SeatState}, + shell::wlr_layer::{Anchor, KeyboardInteractivity, Layer, LayerShell}, + shell::{ + WaylandSurface, + wlr_layer::{LayerShellHandler, LayerSurface, LayerSurfaceConfigure}, + }, +}; +use smol::channel::Sender; +use wayland_client::{ + Connection, EventQueue, Proxy, QueueHandle, + globals::registry_queue_init, + protocol::{wl_output, wl_seat, wl_surface}, +}; + +use crate::Window; +pub struct BarState { + pub registry_state: RegistryState, + pub seat_state: SeatState, + pub output_state: OutputState, + + pub width: u32, + pub height: u32, + pub exit: bool, + pub layer: LayerSurface, + + pub display: Display, + pub pool: HashPool, + pub device: Arc, + pub update_sender: Sender<()>, +} + +impl BarState { + pub fn new(height: u32, tx: Sender<()>) -> (Self, EventQueue) { + let conn = Connection::connect_to_env().unwrap(); + let (globals, event_queue) = registry_queue_init(&conn).unwrap(); + let qh: QueueHandle = event_queue.handle(); + + // Initialize xdg_shell handlers so we can select the correct adapter + let compositor_state = + CompositorState::bind(&globals, &qh).expect("wl_compositor not available"); + let layer_shell = LayerShell::bind(&globals, &qh).expect("layer shell not available"); + let surface = compositor_state.create_surface(&qh); + // Create the window for adapter selection + let layer = + layer_shell.create_layer_surface(&qh, surface, Layer::Bottom, Some("conduit"), None); + layer.set_anchor(Anchor::TOP); + layer.set_keyboard_interactivity(KeyboardInteractivity::None); + + // Create the raw window handle for the surface. + let raw_display_handle = RawDisplayHandle::Wayland(WaylandDisplayHandle::new( + NonNull::new(conn.backend().display_ptr() as *mut _).unwrap(), + )); + + let raw_window_handle = RawWindowHandle::Wayland(WaylandWindowHandle::new( + NonNull::new(layer.wl_surface().id().as_ptr() as *mut _).unwrap(), + )); + let window = Window { + display_handle: raw_display_handle, + window_handle: raw_window_handle, + }; + + let s13_device = Arc::new( + Device::create_display( + DeviceInfoBuilder::default() + .select_physical_device(Box::new(DeviceInfo::integrated_gpu)) + .debug(true), + &window, + ) + .unwrap(), + ); + + let s13_surface = Surface::create(&s13_device, &window).unwrap(); + let formats = Surface::formats(&s13_surface).unwrap(); + let format = Surface::srgb(&formats).unwrap(); + let s13_swapchain = Swapchain::new( + &s13_device, + s13_surface, + SwapchainInfoBuilder::default() + .width(0) + .height(20) + .surface(format), + ) + .unwrap(); + + let s13_display = + screen_13::Display::new(&s13_device, s13_swapchain, DisplayInfo::default()).unwrap(); + let s13_pool = HashPool::new(&s13_device); + + ( + BarState { + registry_state: RegistryState::new(&globals), + seat_state: SeatState::new(&globals, &qh), + output_state: OutputState::new(&globals, &qh), + + width: 0, + height, + exit: false, + layer, + + display: s13_display, + pool: s13_pool, + device: s13_device, + update_sender: tx, + }, + event_queue, + ) + } +} + +impl CompositorHandler for BarState { + fn scale_factor_changed( + &mut self, + _conn: &Connection, + _qh: &QueueHandle, + _surface: &wl_surface::WlSurface, + _new_factor: i32, + ) { + // Not needed for this example. + debug!("compositor: scale factor changed"); + } + + fn transform_changed( + &mut self, + _conn: &Connection, + _qh: &QueueHandle, + _surface: &wl_surface::WlSurface, + _new_transform: wl_output::Transform, + ) { + // Not needed for this example. + debug!("compositor: transform changed"); + } + + fn frame( + &mut self, + _conn: &Connection, + _qh: &QueueHandle, + _surface: &wl_surface::WlSurface, + _time: u32, + ) { + // Not needed for this example. + debug!("compositor: frame changed"); + } + + fn surface_enter( + &mut self, + _conn: &Connection, + _qh: &QueueHandle, + _surface: &wl_surface::WlSurface, + _output: &wl_output::WlOutput, + ) { + // Not needed for this example. + debug!("compositor: surface enter"); + } + + fn surface_leave( + &mut self, + _conn: &Connection, + _qh: &QueueHandle, + _surface: &wl_surface::WlSurface, + _output: &wl_output::WlOutput, + ) { + // Not needed for this example. + debug!("compositor: surface leave"); + } +} + +impl OutputHandler for BarState { + fn output_state(&mut self) -> &mut OutputState { + &mut self.output_state + } + + fn new_output( + &mut self, + _conn: &Connection, + _qh: &QueueHandle, + _output: wl_output::WlOutput, + ) { + debug!("output: new output"); + let size = self + .output_state + .info(&_output) + .and_then(|v| v.logical_size) + .unwrap(); + self.width = size.0 as u32; + self.layer.set_size(self.width, self.height); + self.layer.set_exclusive_zone(self.height as i32); + self.layer.commit(); + } + + fn update_output( + &mut self, + _conn: &Connection, + _qh: &QueueHandle, + _output: wl_output::WlOutput, + ) { + debug!("output: update output"); + } + + fn output_destroyed( + &mut self, + _conn: &Connection, + _qh: &QueueHandle, + _output: wl_output::WlOutput, + ) { + debug!("output: output destroyed"); + } +} + +impl SeatHandler for BarState { + fn seat_state(&mut self) -> &mut SeatState { + &mut self.seat_state + } + + fn new_seat(&mut self, _: &Connection, _: &QueueHandle, _: wl_seat::WlSeat) { + debug!("seat: new seat"); + } + + fn new_capability( + &mut self, + _conn: &Connection, + _qh: &QueueHandle, + _seat: wl_seat::WlSeat, + _capability: Capability, + ) { + debug!("seat: new capability"); + } + + fn remove_capability( + &mut self, + _conn: &Connection, + _: &QueueHandle, + _: wl_seat::WlSeat, + _capability: Capability, + ) { + debug!("seat: remove capability"); + } + + fn remove_seat(&mut self, _: &Connection, _: &QueueHandle, _: wl_seat::WlSeat) { + debug!("seat: remove seat"); + } +} + +impl LayerShellHandler for BarState { + fn closed(&mut self, _conn: &Connection, _qh: &QueueHandle, _layer: &LayerSurface) { + debug!("layer shell: closed"); + self.exit = true; + } + + fn configure( + &mut self, + _conn: &Connection, + _qh: &QueueHandle, + _layer: &LayerSurface, + _configure: LayerSurfaceConfigure, + _serial: u32, + ) { + debug!("layer shell: configure"); + self.display.set_swapchain_info( + self.display + .swapchain_info() + .to_builder() + .width(self.width) + .height(self.height), + ); + + smol::block_on(self.update_sender.send(())).unwrap(); + } +} + +delegate_compositor!(BarState); +delegate_output!(BarState); +delegate_seat!(BarState); +delegate_layer!(BarState); +delegate_registry!(BarState); + +impl ProvidesRegistryState for BarState { + fn registry(&mut self) -> &mut RegistryState { + &mut self.registry_state + } + registry_handlers![OutputState]; +} diff --git a/src/main.rs b/src/main.rs index fd03fa7..2074fda 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,7 +11,7 @@ fn main() { let mut bar = Bar::new(); bar.event_queue.blocking_dispatch(&mut bar.state).unwrap(); - match smol::block_on(bar.update()) { + match smol::block_on(bar.update_loop()) { Ok(_) => {} Err(e) => log::error!("{e}"), }; -- knotmirror 0.0.1