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
//! This is a lightweight, event-driven status bar for EWMH-compliant window
//! managers on X11.
//!
//! It uses [`tokio`] in combination with existing event APIs to poll as rarely
//! as possible. For example, the [`Inotify`][panels::Inotify] panel uses
//! Linux's inotify to monitor the contents of a file.
//!
//! You're welcome to use this crate as a library if you want to expand on the
//! functionality included herein, but its intentended use case is as a binary.
//! It reads a configuration file located at
//! `$XDG_CONFIG_HOME/lazybar/config.toml`, and this documentation will focus on
//! accepted syntax for that file. See [`panels`] for panel-specific
//! information.
//!
//! The general structure of the file is as follows:
//!
//! Top-level tables:
//! - `bars`: each subtable defines a bar, and the name is used as a command
//! line argument to run that bar.
//! - `ramps`: each subtable defines a ramp with the same name, and those names
//! are referenced by panel tables (see below).
//! - `panels`: each subtable defines a panel with the same name, and those
//! names are referenced by bar tables.
//! - `attrs`: each subtable defines a set of attributes that can be referenced
//! by panels.
//! - `bgs`: each subtable defines a background configuration (shape, color)
//! that can be referenced by attrs.
//!
//! None of these tables need to be declared explicitly, as they hold no values
//! of their own. `[bars.example]` is sufficient to define a bar named
//! `example`. Any values in these top level tables will be ignored, along with
//! any top level table with a different name. See <https://toml.io/> for more
//! information.
//!
//! Note: types are pretty flexible, and [`config`] will try its best to
//! figure out what you mean, but if you have issues, make sure that your types
//! are correct.
//!
//! # Example Config
//! ```toml
#![doc = include_str!("../examples/config.toml")]
//! ```
#![deny(missing_docs)]
/// Configuration options for colors and fonts.
pub mod attrs;
/// Background configuration options.
pub mod background;
/// The bar itself and bar-related utility structs and functions.
pub mod bar;
mod cleanup;
mod highlight;
/// Support for inter-process communication, like that provided by the
/// `lazybar-msg` crate.
pub mod ipc;
/// Panels that can be added to the bar. A new panel must implement
/// [`PanelConfig`].
pub mod panels;
/// The parser for the `config.toml` file.
pub mod parser;
mod ramp;
mod utils;
mod x;
use std::{
collections::HashMap,
fmt::Display,
pin::Pin,
rc::Rc,
sync::{Arc, Mutex},
};
use anyhow::Result;
use attrs::Attrs;
use bar::{Bar, Event, EventResponse, Panel, PanelDrawInfo};
pub use builders::BarConfig;
use config::{Config, Value};
pub use csscolorparser::Color;
pub use glib::markup_escape_text;
pub use highlight::Highlight;
use ipc::ChannelEndpoint;
pub use ramp::Ramp;
use tokio_stream::Stream;
pub use utils::*;
use x::{create_surface, create_window, map_window, set_wm_properties};
/// A function that can be called repeatedly to draw the panel.
pub type PanelDrawFn = Box<dyn Fn(&cairo::Context) -> Result<()>>;
/// A stream that produces panel changes when the underlying data source
/// changes.
pub type PanelStream = Pin<Box<dyn Stream<Item = Result<PanelDrawInfo>>>>;
/// The channel endpoint associated with a panel
pub type PanelEndpoint = Arc<Mutex<ChannelEndpoint<Event, EventResponse>>>;
/// The trait implemented by all panels. Provides support for parsing a panel
/// and turning it into a [`PanelStream`].
pub trait PanelConfig {
/// Parses an instance of this type from a subset of the global [`Config`].
fn parse(
name: &'static str,
table: &mut HashMap<String, Value>,
global: &Config,
) -> Result<Self>
where
Self: Sized;
/// Returns the name of the panel. If the panel supports events, each
/// instance must return a unique name.
fn props(&self) -> (&'static str, bool);
/// Performs any necessary setup, then returns a [`PanelStream`]
/// representing the provided [`PanelConfig`].
///
/// # Errors
///
/// If the process of creating a [`PanelStream`] fails.
fn run(
self: Box<Self>,
cr: Rc<cairo::Context>,
global_attrs: Attrs,
height: i32,
) -> Result<(
PanelStream,
Option<ipc::ChannelEndpoint<Event, EventResponse>>,
)>;
}
/// Describes where on the screen the bar should appear.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Position {
/// The top of the screen
Top,
/// The bottom of the screen
Bottom,
}
/// Describes where on the bar a panel should appear.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Alignment {
/// The left of the bar
Left,
/// The center of the bar
Center,
/// The right of the bar
Right,
}
impl Display for Alignment {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
Self::Left => f.write_str("left"),
Self::Center => f.write_str("center"),
Self::Right => f.write_str("right"),
}
}
}
/// Describes the minimum width of gaps around panel groups.
#[derive(Clone, Debug)]
pub struct Margins {
/// The distance in pixels from the left side of the screen to the start
/// of the leftmost panel.
pub left: f64,
/// The minimum distance in pixels between the last panel with
/// [`Alignment::Left`] and the first with [`Alignment::Center`] and
/// between the last with [`Alignment::Center`] and the first with
/// [`Alignment::Right`].
pub internal: f64,
/// The distance in pixels between the rightmost panel and the right side
/// of the screen. Can be overriden if the panels overflow.
pub right: f64,
}
impl Margins {
/// Create a new set of margins.
#[must_use]
pub const fn new(left: f64, internal: f64, right: f64) -> Self {
Self {
left,
internal,
right,
}
}
}
/// Builder structs for non-panel items, courtesy of [`derive_builder`]. See
/// [`panels::builders`] for panel builders.
pub mod builders {
use std::{pin::Pin, thread};
use anyhow::Result;
use derive_builder::Builder;
use signal_hook::{consts::TERM_SIGNALS, iterator::Signals};
use tokio::{
net::UnixStream,
runtime::Runtime,
sync::mpsc::unbounded_channel,
task::{self, JoinSet},
};
use tokio_stream::{Stream, StreamExt, StreamMap};
use crate::{
cleanup,
ipc::{self, ChannelEndpoint},
x::XStream,
Alignment, Attrs, Bar, Color, Margins, Panel, PanelConfig, Position,
UnixStreamWrapper,
};
pub use crate::{PanelCommonBuilder, PanelCommonBuilderError};
/// A set of options for a bar.
///
/// See [`parser::parse`][crate::parser::parse] for configuration details.
#[derive(Builder)]
#[builder_struct_attr(allow(missing_docs))]
#[builder_impl_attr(allow(missing_docs))]
#[builder(pattern = "owned")]
pub struct BarConfig {
/// The bar name to look for in the config file
pub name: String,
left: Vec<Box<dyn PanelConfig>>,
center: Vec<Box<dyn PanelConfig>>,
right: Vec<Box<dyn PanelConfig>>,
/// Whether the bar should be rendered at the top or bottom of the
/// screen
pub position: Position,
/// In pixels
pub height: u16,
/// Whether the bar can be transparent. The background color still
/// applies!
pub transparent: bool,
/// The background color. Supports transparency if `transparent` is
/// true.
pub bg: Color,
/// The minimum gaps between the edges of the screen and panel
/// sections. See [`Margins`] for details.
pub margins: Margins,
/// The default attributes of panels on the bar. See [`Attrs`] for
/// details.
pub attrs: Attrs,
/// Whether to reverse the scrolling direction for panel events.
pub reverse_scroll: bool,
/// Whether inter-process communication (via Unix socket) is enabled.
/// See [`crate::ipc`] for details.
pub ipc: bool,
}
impl BarConfig {
/// Add a panel to the bar with a given [`Alignment`]. It will appear to
/// the right of all other panels with the same alignment.
pub fn add_panel(
&mut self,
panel: Box<dyn PanelConfig>,
alignment: Alignment,
) {
match alignment {
Alignment::Left => self.left.push(panel),
Alignment::Center => self.center.push(panel),
Alignment::Right => self.right.push(panel),
};
}
/// Turn the provided [`BarConfig`] into a [`Bar`] and start the main
/// event loop.
///
/// # Errors
///
/// In the case of unrecoverable runtime errors.
pub fn run(self) -> Result<()> {
log::info!("Starting bar {}", self.name);
let rt = Runtime::new()?;
let local = task::LocalSet::new();
local.block_on(&rt, self.run_inner())?;
Ok(())
}
#[allow(clippy::future_not_send)]
async fn run_inner(self) -> Result<()> {
let mut bar = Bar::new(
self.name,
self.position,
self.height,
self.transparent,
self.bg,
self.margins,
self.reverse_scroll,
self.ipc,
)?;
log::debug!("bar created");
let mut left_panels = StreamMap::with_capacity(self.left.len());
for (idx, panel) in self.left.into_iter().enumerate() {
let (name, visible) = panel.props();
let (stream, sender) = panel.run(
bar.cr.clone(),
self.attrs.clone(),
i32::from(self.height),
)?;
bar.left.push(Panel::new(None, name, sender, visible));
left_panels.insert(idx, stream);
}
bar.streams.insert(Alignment::Left, left_panels);
log::debug!("left panels running");
let mut center_panels = StreamMap::with_capacity(self.center.len());
for (idx, panel) in self.center.into_iter().enumerate() {
let (name, visible) = panel.props();
let (stream, sender) = panel.run(
bar.cr.clone(),
self.attrs.clone(),
i32::from(self.height),
)?;
bar.center.push(Panel::new(None, name, sender, visible));
center_panels.insert(idx, stream);
}
bar.streams.insert(Alignment::Center, center_panels);
log::debug!("center panels running");
let mut right_panels = StreamMap::with_capacity(self.right.len());
for (idx, panel) in self.right.into_iter().enumerate() {
let (name, visible) = panel.props();
let (stream, sender) = panel.run(
bar.cr.clone(),
self.attrs.clone(),
i32::from(self.height),
)?;
bar.right.push(Panel::new(None, name, sender, visible));
right_panels.insert(idx, stream);
}
bar.streams.insert(Alignment::Right, right_panels);
log::debug!("right panels running");
let mut x_stream = XStream::new(bar.conn.clone());
let mut signals = Signals::new(TERM_SIGNALS)?;
let name = bar.name.clone();
thread::spawn(move || loop {
if let Some(signal) = signals.wait().next() {
log::info!("Received signal {signal} - shutting down");
cleanup::exit(Some((name.as_str(), self.ipc)), 0);
}
});
log::debug!("Set up signal listener");
let result = ipc::init(bar.ipc, bar.name.as_str());
let mut ipc_stream: Pin<
Box<
dyn Stream<
Item = std::result::Result<UnixStream, std::io::Error>,
>,
>,
> = match result {
Ok(stream) => {
log::info!("IPC initialized");
stream
}
Err(e) => {
log::info!("IPC disabled due to an error: {e}");
Box::pin(tokio_stream::pending())
}
};
let mut ipc_set = JoinSet::<Result<()>>::new();
task::spawn_local(async move { loop {
tokio::select! {
Some(Ok(event)) = x_stream.next() => {
log::trace!("X event: {event:?}");
if let Err(e) = bar.process_event(&event).await {
if let Some(e) = e.downcast_ref::<xcb::Error>() {
log::warn!("X event caused an error: {e}");
// close when X server does
// this could cause problems, maybe only exit under certain circumstances?
cleanup::exit(Some((bar.name.as_str(), self.ipc)), 0);
} else {
log::warn!("Error produced as a side effect of an X event (expect cryptic error messages): {e}");
}
}
},
Some((alignment, result)) = bar.streams.next() => {
log::debug!("Received event from {alignment} panel at index {}", result.0);
match result {
(idx, Ok(draw_info)) => if let Err(e) = bar.update_panel(alignment, idx, draw_info) {
log::warn!("Error updating {alignment} panel at index {idx}: {e}");
}
(idx, Err(e)) =>
log::warn!("Error produced by {alignment} panel at index {idx:?}: {e}"),
}
},
Some(Ok(stream)) = ipc_stream.next(), if bar.ipc => {
log::debug!("Received new ipc connection");
let (local_send, mut local_recv) = unbounded_channel();
let (ipc_send, ipc_recv) = unbounded_channel();
let wrapper = UnixStreamWrapper::new(stream, ChannelEndpoint::new(local_send, ipc_recv));
let _handle = task::spawn(wrapper.run());
log::trace!("wrapper running");
let message = local_recv.recv().await;
log::trace!("message received");
if let Some(message) = message {
if let Err(e) = bar.send_message(message.as_str(), &mut ipc_set, ipc_send) {
log::warn!("Sending message {message} generated an error: {e}");
}
}
}
// maybe not strictly necessary, but ensures that the ipc futures get polled
Some(_) = ipc_set.join_next() => {
log::debug!("ipc future completed");
}
}
} }).await?;
Ok(())
}
}
}