repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/util/src/color.rs | crates/util/src/color.rs | // NOTE: GENERATED BY AI
use cosmic_text::Color;
use regex_lite::Regex;
use std::num::{ParseFloatError, ParseIntError};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ParseColorError {
#[error("invalid color name")]
InvalidName,
#[error("invalid hex format")]
InvalidHex,
#[error("invalid color format")]
InvalidFormat,
#[error("value out of range")]
OutOfRange,
#[error("parse int error: {0}")]
ParseInt(#[from] ParseIntError),
#[error("parse float error")]
ParseFloat(#[from] ParseFloatError),
}
lazy_static::lazy_static! {
// static ref CSS_COLORS: HashMap<&'static str, [u8; 4]> = {
// let mut m = HashMap::new();
// m.insert("black", [0, 0, 0, 255]);
// m.insert("white", [255, 255, 255, 255]);
// m.insert("red", [255, 0, 0, 255]);
// m.insert("lime", [0, 255, 0, 255]);
// m.insert("blue", [0, 0, 255, 255]);
// m.insert("transparent", [0, 0, 0, 0]);
// // ...
// m
// };
static ref RGB_REGEX: Regex = Regex::new(
r"(?i)^rgba?\(\s*(\d+%?)\s*,\s*(\d+%?)\s*,\s*(\d+%?)\s*(?:,\s*([\d.]+%?)\s*)?\)$"
).unwrap();
static ref HSL_REGEX: Regex = Regex::new(
r"(?i)^hsla?\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*(?:,\s*([\d.]+%?)\s*)?\)$"
).unwrap();
}
pub const COLOR_BLACK: Color = Color::rgb(0, 0, 0);
pub const COLOR_RED: Color = Color::rgb(255, 0, 0);
pub const COLOR_GREEN: Color = Color::rgb(0, 255, 0);
pub const COLOR_BLUE: Color = Color::rgb(0, 0, 255);
pub const COLOR_WHITE: Color = Color::rgb(255, 255, 255);
pub const COLOR_TRANSPARENT: Color = Color::rgba(0, 0, 0, 0);
pub fn parse_color(s: &str) -> Result<Color, ParseColorError> {
parse_color_inner(s).map(|v| Color::rgba(v[0], v[1], v[2], v[3]))
}
pub fn cairo_set_color(ctx: &cairo::Context, color: Color) {
ctx.set_source_rgba(
color.r() as f64 / 255.,
color.g() as f64 / 255.,
color.b() as f64 / 255.,
color.a() as f64 / 255.,
);
}
pub fn color_transition(start: Color, end: Color, t: f32) -> Color {
if t <= 0.0 {
return start;
}
if t >= 1.0 {
return end;
}
#[inline]
fn interpolate_channel(start: u8, end: u8, n: u16) -> u8 {
let start = start as u32;
let end = end as u32;
let n = n as u32;
((start * (256 - n) + end * n + 128) >> 8) as u8
}
let n = (t * 256.0).round() as u16;
Color::rgba(
interpolate_channel(start.r(), end.r(), n),
interpolate_channel(start.g(), end.g(), n),
interpolate_channel(start.b(), end.b(), n),
interpolate_channel(start.a(), end.a(), n),
)
}
pub fn color_mix(one: Color, two: Color) -> Color {
let a1 = one.a() as f64 / 255.;
let r1 = one.r() as f64 / 255.;
let g1 = one.g() as f64 / 255.;
let b1 = one.b() as f64 / 255.;
let a2 = two.a() as f64 / 255.;
let r2 = two.r() as f64 / 255.;
let g2 = two.g() as f64 / 255.;
let b2 = two.b() as f64 / 255.;
let a = 1. - (1. - a1) * (1. - a2);
let r = (r1 * a1 + r2 * a2 * (1. - a1)) / a;
let g = (g1 * a1 + g2 * a2 * (1. - a1)) / a;
let b = (b1 * a1 + b2 * a2 * (1. - a1)) / a;
Color::rgba(
(r * 255.0).round() as u8,
(g * 255.0).round() as u8,
(b * 255.0).round() as u8,
(a * 255.0).round() as u8,
)
}
fn parse_color_inner(s: &str) -> Result<[u8; 4], ParseColorError> {
let s = s.trim().to_lowercase();
// if let Some(&color) = CSS_COLORS.get(s.as_str()) {
// return Ok(color);
// }
// hex
if let Some(hex) = s.strip_prefix('#') {
return parse_hex(hex);
}
// rgb/rgba
if s.starts_with("rgb") {
return parse_rgb(&s);
}
// HSL/HSLA
if s.starts_with("hsl") {
return parse_hsl(&s);
}
Err(ParseColorError::InvalidFormat)
}
fn parse_hex(hex: &str) -> Result<[u8; 4], ParseColorError> {
let len = hex.len();
let mut chars = hex.chars();
let (r_len, g_len, b_len, a_len) = match len {
3 | 4 => (1, 1, 1, if len == 4 { 1 } else { 0 }),
6 | 8 => (2, 2, 2, if len == 8 { 2 } else { 0 }),
9 | 12 => (3, 3, 3, if len == 12 { 3 } else { 0 }),
16 => (4, 4, 4, 4),
_ => return Err(ParseColorError::InvalidHex),
};
let r = parse_hex_component(&chars.by_ref().take(r_len).collect::<String>(), r_len)?;
let g = parse_hex_component(&chars.by_ref().take(g_len).collect::<String>(), g_len)?;
let b = parse_hex_component(&chars.by_ref().take(b_len).collect::<String>(), b_len)?;
let a = if a_len > 0 {
parse_hex_component(&chars.take(a_len).collect::<String>(), a_len)?
} else {
255
};
Ok([r, g, b, a])
}
fn parse_hex_component(s: &str, digits: usize) -> Result<u8, ParseColorError> {
let max_val = (1u32 << (digits * 4)) - 1;
let value = u32::from_str_radix(s, 16)?;
let scaled = ((value as f32 * 255.0) / max_val as f32).round() as u8;
Ok(scaled)
}
fn parse_rgb(s: &str) -> Result<[u8; 4], ParseColorError> {
let caps = RGB_REGEX
.captures(s)
.ok_or(ParseColorError::InvalidFormat)?;
let r = parse_percent_or_byte(caps.get(1).unwrap().as_str())?;
let g = parse_percent_or_byte(caps.get(2).unwrap().as_str())?;
let b = parse_percent_or_byte(caps.get(3).unwrap().as_str())?;
let a = if let Some(a_match) = caps.get(4) {
parse_alpha(a_match.as_str())?
} else {
255
};
Ok([r, g, b, a])
}
fn parse_percent_or_byte(s: &str) -> Result<u8, ParseColorError> {
if let Some(percent) = s.strip_suffix('%') {
let value = percent.parse::<f32>()?;
Ok((value.clamp(0.0, 100.0) * 2.55).round() as u8)
} else {
let value = s.parse::<u8>()?;
Ok(value.clamp(0, 255))
}
}
fn parse_alpha(s: &str) -> Result<u8, ParseColorError> {
if let Some(percent) = s.strip_suffix('%') {
let value = percent.parse::<f32>()?;
Ok((value.clamp(0.0, 100.0) * 2.55).round() as u8)
} else {
let value = s.parse::<f32>()?;
Ok((value.clamp(0.0, 1.0) * 255.0).round() as u8)
}
}
fn parse_hsl(s: &str) -> Result<[u8; 4], ParseColorError> {
let caps = HSL_REGEX
.captures(s)
.ok_or(ParseColorError::InvalidFormat)?;
let h = caps[1].parse::<f32>()? % 360.0;
let s = caps[2].parse::<f32>()?.clamp(0.0, 100.0) / 100.0;
let l = caps[3].parse::<f32>()?.clamp(0.0, 100.0) / 100.0;
let alpha = if let Some(a_match) = caps.get(4) {
parse_alpha(a_match.as_str())?
} else {
255
};
let rgb = hsl_to_rgb(h, s, l);
Ok([rgb[0], rgb[1], rgb[2], alpha])
}
fn hsl_to_rgb(h: f32, s: f32, l: f32) -> [u8; 3] {
let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
let x = c * (1.0 - ((h / 60.0) % 2.0 - 1.0).abs());
let m = l - c / 2.0;
let (r, g, b) = match h {
h if (0.0..60.0).contains(&h) => (c, x, 0.0),
h if (60.0..120.0).contains(&h) => (x, c, 0.0),
h if (120.0..180.0).contains(&h) => (0.0, c, x),
h if (180.0..240.0).contains(&h) => (0.0, x, c),
h if (240.0..300.0).contains(&h) => (x, 0.0, c),
_ => (c, 0.0, x),
};
[
((r + m) * 255.0).round() as u8,
((g + m) * 255.0).round() as u8,
((b + m) * 255.0).round() as u8,
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_hex() {
assert_eq!(parse_color_inner("#f00").unwrap(), [255, 0, 0, 255]);
assert_eq!(parse_color_inner("#ff0000").unwrap(), [255, 0, 0, 255]);
assert_eq!(parse_color_inner("#ff000080").unwrap(), [255, 0, 0, 128]);
assert_eq!(parse_color_inner("#fff000000").unwrap(), [255, 0, 0, 255]); // 3 digits per channel
}
#[test]
fn test_parse_rgb() {
assert_eq!(
parse_color_inner("rgb(255, 0, 0)").unwrap(),
[255, 0, 0, 255]
);
assert_eq!(
parse_color_inner("rgba(255, 0, 0, 0.5)").unwrap(),
[255, 0, 0, 128]
);
assert_eq!(
parse_color_inner("rgb(100%, 50%, 0%)").unwrap(),
[255, 128, 0, 255]
);
}
#[test]
fn test_parse_hsl() {
assert_eq!(
parse_color_inner("hsl(0, 100%, 50%)").unwrap(),
[255, 0, 0, 255]
);
assert_eq!(
parse_color_inner("hsla(120, 100%, 50%, 0.5)").unwrap(),
[0, 255, 0, 128]
);
}
// #[test]
// fn test_named_color() {
// assert_eq!(parse_color("red").unwrap(), [255, 0, 0, 255]);
// assert_eq!(parse_color("transparent").unwrap(), [0, 0, 0, 0]);
// }
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/util/src/template/base.rs | crates/util/src/template/base.rs | use std::{borrow::Cow, collections::HashMap, fmt::Debug, rc::Rc};
use downcast_rs::Downcast;
pub trait TemplateArgParser: Debug + Downcast {
fn name(&self) -> &str;
}
downcast_rs::impl_downcast!(TemplateArgParser);
pub trait TemplateArgProcesser: Debug {
fn process(&self, param: &str) -> Result<Box<dyn TemplateArgParser>, String>;
fn name(&self) -> &str;
}
pub struct TemplateProcesser(HashMap<String, Box<dyn TemplateArgProcesser>>);
impl TemplateProcesser {
pub fn new() -> Self {
Self(HashMap::new())
}
pub fn add_processer(mut self, p: impl TemplateArgProcesser + 'static) -> Self {
self.0.insert(p.name().to_string(), Box::new(p));
self
}
fn get(&self, name: &str) -> Option<&dyn TemplateArgProcesser> {
self.0.get(name).map(|f| f.as_ref())
}
}
impl Default for TemplateProcesser {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone)]
pub enum TemplateContent {
String(String),
Template(Rc<dyn TemplateArgParser>),
}
#[derive(Debug, Clone)]
pub struct Template {
pub contents: Vec<TemplateContent>,
}
impl Template {
pub fn create_from_str(raw: &str, processers: TemplateProcesser) -> Result<Self, String> {
let mut contents = vec![];
let mut record_index = 0;
let matches = extract_braces(raw)?;
for m in matches {
// push string before
let end = m.start;
if end > record_index {
contents.push(TemplateContent::String(
raw[record_index..end].replace(r"\", ""),
))
}
record_index = m.end;
// push template
let template = m.get_content();
let (name, arg) = match template.split_once(":") {
Some((n, a)) => (n.trim(), a.trim()),
None => (template.trim(), ""),
};
let Some(processer) = processers.get(name) else {
let msg = format!("Unknown template: {name}");
log::error!("{msg}");
continue;
};
let processed = processer.process(arg);
let Ok(parser) = processed else {
let msg = format!("Faild to parse template: {name}: {processed:?}");
log::error!("{msg}");
continue;
};
// NOTE: INTO RC
contents.push(TemplateContent::Template(parser.into()));
}
if record_index < raw.len() {
contents.push(TemplateContent::String(
raw[record_index..].replace(r"\", ""),
));
};
Ok(Self { contents })
}
pub fn parse(&self, mut cb: impl FnMut(&dyn TemplateArgParser) -> String) -> String {
self.contents
.iter()
.map(|content| match content {
TemplateContent::String(s) => Cow::Borrowed(s.as_str()),
TemplateContent::Template(parser) => Cow::Owned(cb(parser.as_ref())),
})
.collect::<Vec<Cow<str>>>()
.join("")
.to_string()
}
}
struct BraceMatch<'a> {
start: usize,
end: usize,
s: &'a str,
}
impl<'a> BraceMatch<'a> {
fn from_total(start: usize, end: usize, total: &'a str) -> Self {
let s = &total[start..end];
Self { start, end, s }
}
fn get_content(&self) -> &str {
&self.s[1..self.s.len() - 1]
}
}
fn extract_braces(input: &str) -> Result<Vec<BraceMatch<'_>>, String> {
let chars = input.chars().enumerate();
struct BraceState<'a> {
start: i32,
indexes: Vec<BraceMatch<'a>>,
str: &'a str,
}
impl<'a> BraceState<'a> {
fn new(s: &'a str) -> Self {
Self {
start: -1,
indexes: vec![],
str: s,
}
}
fn enter(&mut self, index: i32) {
self.start = index;
}
fn leave(&mut self, index: i32) {
if self.start != -1 {
self.indexes.push(BraceMatch::from_total(
self.start as usize,
(index + 1) as usize,
self.str,
));
}
self.start = -1
}
}
let mut state = BraceState::new(input);
let mut escaped = false;
for (index, c) in chars {
match c {
'\\' => {
escaped = !escaped;
}
'{' if !escaped => {
state.enter(index as i32);
}
'}' if !escaped => {
state.leave(index as i32);
}
_ => {}
}
}
let BraceState {
start: _,
indexes,
str: _,
} = state;
Ok(indexes)
}
#[macro_export]
macro_rules! template_parser {
($visibility:vis, $name:ident, $s:expr) => {
use paste::paste;
paste! {
$visibility const [<TEMPLATE_ARG_ $name:upper>]: &str = $s;
impl TemplateArgParser for [<$name Parser>] {
fn name(&self) -> &str {
$s
}
}
#[derive(Debug)]
$visibility struct [<$name Processer>];
impl TemplateArgProcesser for [<$name Processer>] {
fn process(&self, p: &str) -> Result<Box<dyn TemplateArgParser>, String> {
let parser = [<$name Parser>]::from_str(p)?;
Ok(Box::new(parser))
}
fn name(&self) -> &str {
$s
}
}
}
};
}
mod test {
#![allow(unused_imports, dead_code, unused_macros)]
use super::*;
use crate::template::arg::{
TemplateArgFloatParser, TemplateArgFloatProcesser, TEMPLATE_ARG_FLOAT,
};
use std::str::FromStr;
template_parser!(, Preset, "preset");
#[derive(Debug, Clone)]
pub struct PresetParser;
impl FromStr for PresetParser {
type Err = String;
fn from_str(_: &str) -> Result<Self, Self::Err> {
Ok(PresetParser)
}
}
macro_rules! make_template {
($name:ident, $i:expr, $($pat:tt)*) => {
let $($pat)* $name = Template::create_from_str(
$i,
TemplateProcesser::new()
.add_processer(TemplateArgFloatProcesser)
.add_processer(PresetProcesser),
)
.unwrap();
};
}
#[test]
fn test_ring_template() {
macro_rules! test {
($i:expr, $s:expr) => {
make_template!(temp, $i,);
let len = temp.contents.len();
assert_eq!(len, $s);
};
}
// test!("{}", 0);
test!(r"\{\}", 1);
test!(r"\{}", 1);
test!(r"{\}", 1);
test!("{preset:}{float:}", 2);
test!("{preset}{float}", 2);
test!(" {preset}{float}", 3);
test!("{preset} {float}", 3);
test!("{preset}{float} ", 3);
test!(" {preset} {float} ", 5);
test!(" { preset } { float } ", 5);
test!("{{preset}}{float}", 4);
test!(r"\{preset\} \{float\}", 1);
test!(r"\{preset\} {float\}", 1);
test!("{{preset}}{{float}", 4);
}
#[test]
fn test_parse_content() {
macro_rules! test {
($i:expr, $preset_str:expr, $float:expr, $s:expr) => {
make_template!(temp, $i,);
let res = temp.parse(|parser| {
let a = match parser.name() {
TEMPLATE_ARG_PRESET => $preset_str.to_string(),
TEMPLATE_ARG_FLOAT => {
let a = parser.downcast_ref::<TemplateArgFloatParser>().unwrap();
a.parse($float).clone()
}
_ => unreachable!(),
};
a
});
assert_eq!(res, $s);
};
}
test!("", "hh", 2., "");
test!("a", "hh", 2., "a");
test!("{}{}", "hh", 2., "");
test!("{float}", "hh", 2., "2.00");
test!(" { preset}a{ float }", "hh", 2., " hha2.00");
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/util/src/template/mod.rs | crates/util/src/template/mod.rs | pub mod arg;
pub mod base;
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/util/src/template/arg/ring_preset.rs | crates/util/src/template/arg/ring_preset.rs | use crate::template::base::{TemplateArgParser, TemplateArgProcesser};
pub const TEMPLATE_ARG_RING_PRESET: &str = "preset";
#[derive(Debug, Default, Clone)]
pub struct TemplateArgRingPresetParser;
impl TemplateArgRingPresetParser {
pub fn parse(&self, arg: String) -> String {
arg
}
}
impl TemplateArgParser for TemplateArgRingPresetParser {
fn name(&self) -> &str {
TEMPLATE_ARG_RING_PRESET
}
}
#[derive(Debug)]
pub struct TemplateArgRingPresetProcesser;
impl TemplateArgProcesser for TemplateArgRingPresetProcesser {
fn process(&self, _: &str) -> Result<Box<dyn TemplateArgParser>, String> {
Ok(Box::new(TemplateArgRingPresetParser))
}
fn name(&self) -> &str {
TEMPLATE_ARG_RING_PRESET
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/util/src/template/arg/mod.rs | crates/util/src/template/arg/mod.rs | mod float;
mod ring_preset;
pub use float::*;
pub use ring_preset::*;
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/util/src/template/arg/float.rs | crates/util/src/template/arg/float.rs | use std::str::FromStr;
use crate::template::base::{TemplateArgParser, TemplateArgProcesser};
pub const TEMPLATE_ARG_FLOAT: &str = "float";
#[derive(Debug, Clone)]
pub struct TemplateArgFloatParser {
precision: usize,
multiply: Option<f64>,
}
impl Default for TemplateArgFloatParser {
fn default() -> Self {
Self {
precision: 2,
multiply: None,
}
}
}
impl TemplateArgFloatParser {
pub fn parse(&self, mut progress: f64) -> String {
if let Some(multiply) = self.multiply {
progress *= multiply
}
format!("{:.precision$}", progress, precision = self.precision)
}
}
impl FromStr for TemplateArgFloatParser {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut template = Self::default();
let s = s.trim();
if s.is_empty() {
return Ok(template);
}
let mut precision = s;
let mut multiply = None;
if let Some((p, m)) = s.split_once(',') {
let p = p.trim();
let m = m.trim();
precision = p;
if !m.is_empty() {
multiply = Some(m);
}
}
if !precision.is_empty() {
template.precision = precision.parse::<usize>().map_err(|e| e.to_string())?;
}
if let Some(multiply) = multiply {
template.multiply = Some(multiply.parse::<f64>().map_err(|e| e.to_string())?);
}
Ok(template)
}
}
impl TemplateArgParser for TemplateArgFloatParser {
fn name(&self) -> &str {
TEMPLATE_ARG_FLOAT
}
}
#[derive(Debug)]
pub struct TemplateArgFloatProcesser;
impl TemplateArgProcesser for TemplateArgFloatProcesser {
fn process(&self, param: &str) -> Result<Box<dyn TemplateArgParser>, String> {
let a = TemplateArgFloatParser::from_str(param)?;
Ok(Box::new(a))
}
fn name(&self) -> &str {
TEMPLATE_ARG_FLOAT
}
}
mod test {
#[allow(unused_imports)]
use super::*;
#[test]
fn test_float_template() {
macro_rules! test {
($i:expr) => {
let res = TemplateArgFloatParser::from_str($i).unwrap().parse(0.5125);
assert_eq!(res, "0.51");
};
}
test!(",");
test!("");
test!("2,");
test!("2");
test!(" 2,");
test!(" 2");
test!("2,1");
test!("2, 1");
test!(" 2, 1 ");
test!(" , 1 ");
}
#[test]
fn test_float_template_parse() {
macro_rules! test {
($i:expr, $s:expr) => {
let res = TemplateArgFloatParser::from_str($i).unwrap().parse(0.5125);
assert_eq!(res, $s);
};
}
test!("0", "1");
test!("1", "0.5");
test!("2", "0.51");
test!("4", "0.5125");
test!("10", "0.5125000000");
test!(",0", "0.00");
test!("3,2", "1.025");
test!(",10", "5.12");
test!(",100", "51.25");
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/util/src/text/draw.rs | crates/util/src/text/draw.rs | use cairo::ImageSurface;
use cosmic_text::{
Attrs, Buffer, Color, Family, FontSystem, LayoutRunIter, Metrics, Shaping, SwashCache, Weight,
};
use crate::pre_multiply_and_to_little_endian_argb;
use super::slide_font::include_slide_font;
extern crate alloc;
static FONT_SYSTEM: std::sync::LazyLock<std::sync::Mutex<FontSystem>> =
std::sync::LazyLock::new(|| {
let mut f = FontSystem::new();
f.db_mut().load_font_data(include_slide_font!().to_vec());
std::sync::Mutex::new(f)
});
static SWASH_CACHE: std::sync::LazyLock<std::sync::Mutex<SwashCache>> =
std::sync::LazyLock::new(|| std::sync::Mutex::new(SwashCache::new()));
pub struct Canvas {
pub canvas_buffer: Box<[u8]>,
pub height: i32,
pub width: i32,
pub stride: i32,
}
impl Canvas {
fn new(width: i32, height: i32) -> Self {
let canvas_buffer = vec![0; width as usize * height as usize * 4].into_boxed_slice();
Self {
canvas_buffer,
height,
width,
stride: width * 4,
}
}
fn set_pixel_color(&mut self, color: Color, x: i32, y: i32) {
let stride = self.stride;
let line = stride * y;
let chunk_start = (x * 4) + line;
if chunk_start as usize > self.canvas_buffer.len() - 4 {
return;
}
let color = pre_multiply_and_to_little_endian_argb(color.as_rgba());
self.canvas_buffer[chunk_start as usize..(chunk_start + 4) as usize]
.copy_from_slice(&color);
}
pub fn to_image_surface(self) -> ImageSurface {
let Self {
canvas_buffer,
height,
width,
stride,
} = self;
ImageSurface::create_for_data(canvas_buffer, cairo::Format::ARgb32, width, height, stride)
.unwrap()
}
}
fn measure_text_size(
buffer: &Buffer,
swash_cache: &mut SwashCache,
font_system: &mut FontSystem,
) -> (i32, i32) {
// Get the layout runs
let layout_runs: LayoutRunIter = buffer.layout_runs();
let mut run_width: f32 = 0.;
let mut run_height_high: f32 = f32::MIN;
let mut last_run = None;
for run in layout_runs {
run_width = run_width.max(run.line_w);
run_height_high = run_height_high.max(run.line_y);
last_run = Some(run);
}
if let Some(run) = last_run {
let mut m = 0;
for g in run.glyphs {
let img = swash_cache
.get_image(font_system, g.physical((0., 0.), 1.).cache_key)
.as_ref()
.unwrap();
m = m.max(img.placement.height as i32 - img.placement.top);
}
run_height_high += m as f32;
}
(run_width.ceil() as i32, run_height_high.ceil() as i32)
}
#[derive(Debug, Clone, Copy)]
pub struct TextConfig<'a> {
pub family: Family<'a>,
pub weight: Option<Weight>,
pub color: Color,
pub size: i32,
}
impl<'a> TextConfig<'a> {
pub fn new(family: Family<'a>, weight: Option<u16>, color: Color, size: i32) -> Self {
Self {
family,
weight: weight.map(Weight),
color,
size,
}
}
}
fn draw_text_inner(
text: &str,
config: TextConfig,
swash_cache: &mut SwashCache,
font_system: &mut FontSystem,
) -> Canvas {
let height = config.size as f32;
let metrics = Metrics::new(height, height);
let mut buffer = Buffer::new_empty(metrics);
let mut attrs = Attrs::new();
if let Some(weight) = config.weight {
attrs = attrs.weight(weight);
}
attrs = attrs.family(config.family);
buffer.set_text(font_system, text, &attrs, Shaping::Advanced);
buffer.shape_until_scroll(font_system, true);
let (width, height) = measure_text_size(&buffer, swash_cache, font_system);
let mut canvas = Canvas::new(width, height);
buffer.draw(
font_system,
swash_cache,
config.color,
|x, y, w, h, color| {
if color.a() == 0 || x < 0 || x >= width || y < 0 || y >= height || w != 1 || h != 1 {
return;
}
canvas.set_pixel_color(color, x, y)
},
);
canvas
}
pub fn draw_text(text: &str, config: TextConfig) -> Canvas {
let mut swash_cache = SWASH_CACHE.lock().unwrap();
let mut font_system = FONT_SYSTEM.lock().unwrap();
draw_text_inner(text, config, &mut swash_cache, &mut font_system)
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/util/src/text/slide_font.rs | crates/util/src/text/slide_font.rs | pub const FAMILY_NAME: &str = "WayEdges-Slide";
macro_rules! include_slide_font {
() => {
[
0x4f, 0x54, 0x54, 0x4f, 0x00, 0x09, 0x00, 0x80, 0x00, 0x03, 0x00, 0x10, 0x43, 0x46,
0x46, 0x20, 0xa7, 0x4f, 0xdb, 0x3b, 0x00, 0x00, 0x08, 0x5c, 0x00, 0x00, 0x14, 0x99,
0x4f, 0x53, 0x2f, 0x32, 0x72, 0xd2, 0x6b, 0x0b, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x60, 0x63, 0x6d, 0x61, 0x70, 0x01, 0xde, 0x01, 0xe1, 0x00, 0x00, 0x07, 0xa8,
0x00, 0x00, 0x00, 0x94, 0x68, 0x65, 0x61, 0x64, 0x2d, 0xa7, 0x75, 0x02, 0x00, 0x00,
0x00, 0x9c, 0x00, 0x00, 0x00, 0x36, 0x68, 0x68, 0x65, 0x61, 0x08, 0xbb, 0x05, 0x9e,
0x00, 0x00, 0x00, 0xd4, 0x00, 0x00, 0x00, 0x24, 0x68, 0x6d, 0x74, 0x78, 0x36, 0x3e,
0x00, 0x00, 0x00, 0x00, 0x1c, 0xf8, 0x00, 0x00, 0x00, 0x38, 0x6d, 0x61, 0x78, 0x70,
0x00, 0x0e, 0x50, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x00, 0x00, 0x06, 0x6e, 0x61,
0x6d, 0x65, 0x19, 0x69, 0xb1, 0xe3, 0x00, 0x00, 0x01, 0x60, 0x00, 0x00, 0x06, 0x45,
0x70, 0x6f, 0x73, 0x74, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x08, 0x3c, 0x00, 0x00,
0x00, 0x20, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0xa2, 0xa4, 0x0f, 0xb5,
0x5f, 0x0f, 0x3c, 0xf5, 0x00, 0x03, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe3, 0x91,
0x94, 0xc9, 0x00, 0x00, 0x00, 0x00, 0xe3, 0x91, 0x94, 0xc9, 0x00, 0x00, 0xff, 0xea,
0x07, 0x6d, 0x06, 0x8e, 0x00, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x08, 0xb9, 0xfd, 0xdc, 0x00, 0x00, 0x07, 0xb3,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x50, 0x00,
0x00, 0x0e, 0x00, 0x00, 0x00, 0x03, 0x04, 0x09, 0x01, 0xf4, 0x00, 0x05, 0x00, 0x00,
0x02, 0x8a, 0x02, 0xbb, 0x00, 0x00, 0x00, 0x8c, 0x02, 0x8a, 0x02, 0xbb, 0x00, 0x00,
0x01, 0xdf, 0x00, 0x31, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0x58, 0x58, 0x58, 0x00, 0x40, 0x00, 0x20,
0x00, 0x39, 0x08, 0xb9, 0xfd, 0xdc, 0x00, 0x00, 0x06, 0x8e, 0x00, 0x16, 0x00, 0x00,
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x06, 0x8e, 0x00, 0x20, 0x00, 0x20,
0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0x01, 0x9e, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x25, 0x03, 0x63, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x00, 0x0e, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x06,
0x00, 0x2a, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x22, 0x04, 0x41,
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x15, 0x00, 0x3c, 0x00, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x02, 0x03, 0x5d, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x06, 0x00, 0x14, 0x00, 0x7b, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x07, 0x00, 0x25, 0x03, 0xd2, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08,
0x00, 0x0c, 0x00, 0xb7, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x0c,
0x00, 0xb7, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x25, 0x03, 0x63,
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x18, 0x00, 0xdb, 0x00, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x18, 0x00, 0xdb, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0d, 0x00, 0xa4, 0x01, 0x23, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0e, 0x00, 0x1a, 0x03, 0x0f, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
0x00, 0x0e, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x06,
0x00, 0x2a, 0x00, 0x03, 0x00, 0x01, 0x04, 0x09, 0x00, 0x00, 0x00, 0x4a, 0x03, 0x88,
0x00, 0x03, 0x00, 0x01, 0x04, 0x09, 0x00, 0x01, 0x00, 0x1c, 0x00, 0x0e, 0x00, 0x03,
0x00, 0x01, 0x04, 0x09, 0x00, 0x02, 0x00, 0x0c, 0x00, 0x30, 0x00, 0x03, 0x00, 0x01,
0x04, 0x09, 0x00, 0x03, 0x00, 0x44, 0x04, 0x63, 0x00, 0x03, 0x00, 0x01, 0x04, 0x09,
0x00, 0x04, 0x00, 0x2a, 0x00, 0x51, 0x00, 0x03, 0x00, 0x01, 0x04, 0x09, 0x00, 0x05,
0x00, 0x04, 0x03, 0x5f, 0x00, 0x03, 0x00, 0x01, 0x04, 0x09, 0x00, 0x06, 0x00, 0x28,
0x00, 0x8f, 0x00, 0x03, 0x00, 0x01, 0x04, 0x09, 0x00, 0x07, 0x00, 0x4a, 0x03, 0xf7,
0x00, 0x03, 0x00, 0x01, 0x04, 0x09, 0x00, 0x08, 0x00, 0x18, 0x00, 0xc3, 0x00, 0x03,
0x00, 0x01, 0x04, 0x09, 0x00, 0x09, 0x00, 0x18, 0x00, 0xc3, 0x00, 0x03, 0x00, 0x01,
0x04, 0x09, 0x00, 0x0a, 0x00, 0x4a, 0x03, 0x88, 0x00, 0x03, 0x00, 0x01, 0x04, 0x09,
0x00, 0x0b, 0x00, 0x30, 0x00, 0xf3, 0x00, 0x03, 0x00, 0x01, 0x04, 0x09, 0x00, 0x0c,
0x00, 0x30, 0x00, 0xf3, 0x00, 0x03, 0x00, 0x01, 0x04, 0x09, 0x00, 0x0d, 0x01, 0x48,
0x01, 0xc7, 0x00, 0x03, 0x00, 0x01, 0x04, 0x09, 0x00, 0x0e, 0x00, 0x34, 0x03, 0x29,
0x00, 0x03, 0x00, 0x01, 0x04, 0x09, 0x00, 0x10, 0x00, 0x1c, 0x00, 0x0e, 0x00, 0x03,
0x00, 0x01, 0x04, 0x09, 0x00, 0x11, 0x00, 0x0c, 0x00, 0x30, 0x57, 0x61, 0x79, 0x45,
0x64, 0x67, 0x65, 0x73, 0x2d, 0x53, 0x6c, 0x69, 0x64, 0x65, 0x00, 0x57, 0x00, 0x61,
0x00, 0x79, 0x00, 0x45, 0x00, 0x64, 0x00, 0x67, 0x00, 0x65, 0x00, 0x73, 0x00, 0x2d,
0x00, 0x53, 0x00, 0x6c, 0x00, 0x69, 0x00, 0x64, 0x00, 0x65, 0x49, 0x74, 0x61, 0x6c,
0x69, 0x63, 0x00, 0x49, 0x00, 0x74, 0x00, 0x61, 0x00, 0x6c, 0x00, 0x69, 0x00, 0x63,
0x57, 0x61, 0x79, 0x45, 0x64, 0x67, 0x65, 0x73, 0x2d, 0x53, 0x6c, 0x69, 0x64, 0x65,
0x20, 0x49, 0x74, 0x61, 0x6c, 0x69, 0x63, 0x00, 0x57, 0x00, 0x61, 0x00, 0x79, 0x00,
0x45, 0x00, 0x64, 0x00, 0x67, 0x00, 0x65, 0x00, 0x73, 0x00, 0x2d, 0x00, 0x53, 0x00,
0x6c, 0x00, 0x69, 0x00, 0x64, 0x00, 0x65, 0x00, 0x20, 0x00, 0x49, 0x00, 0x74, 0x00,
0x61, 0x00, 0x6c, 0x00, 0x69, 0x00, 0x63, 0x57, 0x61, 0x79, 0x45, 0x64, 0x67, 0x65,
0x73, 0x2d, 0x53, 0x6c, 0x69, 0x64, 0x65, 0x49, 0x74, 0x61, 0x6c, 0x69, 0x63, 0x00,
0x57, 0x00, 0x61, 0x00, 0x79, 0x00, 0x45, 0x00, 0x64, 0x00, 0x67, 0x00, 0x65, 0x00,
0x73, 0x00, 0x2d, 0x00, 0x53, 0x00, 0x6c, 0x00, 0x69, 0x00, 0x64, 0x00, 0x65, 0x00,
0x49, 0x00, 0x74, 0x00, 0x61, 0x00, 0x6c, 0x00, 0x69, 0x00, 0x63, 0x56, 0x65, 0x72,
0x6e, 0x6f, 0x6e, 0x20, 0x41, 0x64, 0x61, 0x6d, 0x73, 0x00, 0x56, 0x00, 0x65, 0x00,
0x72, 0x00, 0x6e, 0x00, 0x6f, 0x00, 0x6e, 0x00, 0x20, 0x00, 0x41, 0x00, 0x64, 0x00,
0x61, 0x00, 0x6d, 0x00, 0x73, 0x63, 0x6f, 0x64, 0x65, 0x2e, 0x6e, 0x65, 0x77, 0x74,
0x79, 0x70, 0x6f, 0x67, 0x72, 0x61, 0x70, 0x68, 0x79, 0x2e, 0x63, 0x6f, 0x2e, 0x75,
0x6b, 0x00, 0x63, 0x00, 0x6f, 0x00, 0x64, 0x00, 0x65, 0x00, 0x2e, 0x00, 0x6e, 0x00,
0x65, 0x00, 0x77, 0x00, 0x74, 0x00, 0x79, 0x00, 0x70, 0x00, 0x6f, 0x00, 0x67, 0x00,
0x72, 0x00, 0x61, 0x00, 0x70, 0x00, 0x68, 0x00, 0x79, 0x00, 0x2e, 0x00, 0x63, 0x00,
0x6f, 0x00, 0x2e, 0x00, 0x75, 0x00, 0x6b, 0x43, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67,
0x68, 0x74, 0x20, 0x28, 0x63, 0x29, 0x20, 0x32, 0x30, 0x31, 0x33, 0x2c, 0x20, 0x76,
0x65, 0x72, 0x6e, 0x6f, 0x6e, 0x20, 0x61, 0x64, 0x61, 0x6d, 0x73, 0x20, 0x28, 0x76,
0x65, 0x72, 0x6e, 0x6e, 0x6f, 0x62, 0x69, 0x6c, 0x65, 0x40, 0x67, 0x6d, 0x61, 0x69,
0x6c, 0x2e, 0x63, 0x6f, 0x6d, 0x29, 0x2c, 0x77, 0x69, 0x74, 0x68, 0x20, 0x52, 0x65,
0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x20, 0x46, 0x6f, 0x6e, 0x74, 0x20, 0x4e, 0x61,
0x6d, 0x65, 0x20, 0x4f, 0x73, 0x77, 0x61, 0x6c, 0x64, 0x2e, 0x20, 0x54, 0x68, 0x69,
0x73, 0x20, 0x46, 0x6f, 0x6e, 0x74, 0x20, 0x53, 0x6f, 0x66, 0x74, 0x77, 0x61, 0x72,
0x65, 0x20, 0x69, 0x73, 0x20, 0x6c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x64, 0x20,
0x75, 0x6e, 0x64, 0x65, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x53, 0x49, 0x4c, 0x20,
0x4f, 0x70, 0x65, 0x6e, 0x20, 0x46, 0x6f, 0x6e, 0x74, 0x20, 0x4c, 0x69, 0x63, 0x65,
0x6e, 0x73, 0x65, 0x2c, 0x20, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x31,
0x2e, 0x31, 0x2e, 0x00, 0x43, 0x00, 0x6f, 0x00, 0x70, 0x00, 0x79, 0x00, 0x72, 0x00,
0x69, 0x00, 0x67, 0x00, 0x68, 0x00, 0x74, 0x00, 0x20, 0x00, 0x28, 0x00, 0x63, 0x00,
0x29, 0x00, 0x20, 0x00, 0x32, 0x00, 0x30, 0x00, 0x31, 0x00, 0x33, 0x00, 0x2c, 0x00,
0x20, 0x00, 0x76, 0x00, 0x65, 0x00, 0x72, 0x00, 0x6e, 0x00, 0x6f, 0x00, 0x6e, 0x00,
0x20, 0x00, 0x61, 0x00, 0x64, 0x00, 0x61, 0x00, 0x6d, 0x00, 0x73, 0x00, 0x20, 0x00,
0x28, 0x00, 0x76, 0x00, 0x65, 0x00, 0x72, 0x00, 0x6e, 0x00, 0x6e, 0x00, 0x6f, 0x00,
0x62, 0x00, 0x69, 0x00, 0x6c, 0x00, 0x65, 0x00, 0x40, 0x00, 0x67, 0x00, 0x6d, 0x00,
0x61, 0x00, 0x69, 0x00, 0x6c, 0x00, 0x2e, 0x00, 0x63, 0x00, 0x6f, 0x00, 0x6d, 0x00,
0x29, 0x00, 0x2c, 0x00, 0x77, 0x00, 0x69, 0x00, 0x74, 0x00, 0x68, 0x00, 0x20, 0x00,
0x52, 0x00, 0x65, 0x00, 0x73, 0x00, 0x65, 0x00, 0x72, 0x00, 0x76, 0x00, 0x65, 0x00,
0x64, 0x00, 0x20, 0x00, 0x46, 0x00, 0x6f, 0x00, 0x6e, 0x00, 0x74, 0x00, 0x20, 0x00,
0x4e, 0x00, 0x61, 0x00, 0x6d, 0x00, 0x65, 0x00, 0x20, 0x00, 0x4f, 0x00, 0x73, 0x00,
0x77, 0x00, 0x61, 0x00, 0x6c, 0x00, 0x64, 0x00, 0x2e, 0x00, 0x20, 0x00, 0x54, 0x00,
0x68, 0x00, 0x69, 0x00, 0x73, 0x00, 0x20, 0x00, 0x46, 0x00, 0x6f, 0x00, 0x6e, 0x00,
0x74, 0x00, 0x20, 0x00, 0x53, 0x00, 0x6f, 0x00, 0x66, 0x00, 0x74, 0x00, 0x77, 0x00,
0x61, 0x00, 0x72, 0x00, 0x65, 0x00, 0x20, 0x00, 0x69, 0x00, 0x73, 0x00, 0x20, 0x00,
0x6c, 0x00, 0x69, 0x00, 0x63, 0x00, 0x65, 0x00, 0x6e, 0x00, 0x73, 0x00, 0x65, 0x00,
0x64, 0x00, 0x20, 0x00, 0x75, 0x00, 0x6e, 0x00, 0x64, 0x00, 0x65, 0x00, 0x72, 0x00,
0x20, 0x00, 0x74, 0x00, 0x68, 0x00, 0x65, 0x00, 0x20, 0x00, 0x53, 0x00, 0x49, 0x00,
0x4c, 0x00, 0x20, 0x00, 0x4f, 0x00, 0x70, 0x00, 0x65, 0x00, 0x6e, 0x00, 0x20, 0x00,
0x46, 0x00, 0x6f, 0x00, 0x6e, 0x00, 0x74, 0x00, 0x20, 0x00, 0x4c, 0x00, 0x69, 0x00,
0x63, 0x00, 0x65, 0x00, 0x6e, 0x00, 0x73, 0x00, 0x65, 0x00, 0x2c, 0x00, 0x20, 0x00,
0x56, 0x00, 0x65, 0x00, 0x72, 0x00, 0x73, 0x00, 0x69, 0x00, 0x6f, 0x00, 0x6e, 0x00,
0x20, 0x00, 0x31, 0x00, 0x2e, 0x00, 0x31, 0x00, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x3a,
0x2f, 0x2f, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x73, 0x2e, 0x73, 0x69, 0x6c, 0x2e,
0x6f, 0x72, 0x67, 0x2f, 0x4f, 0x46, 0x4c, 0x00, 0x68, 0x00, 0x74, 0x00, 0x74, 0x00,
0x70, 0x00, 0x3a, 0x00, 0x2f, 0x00, 0x2f, 0x00, 0x73, 0x00, 0x63, 0x00, 0x72, 0x00,
0x69, 0x00, 0x70, 0x00, 0x74, 0x00, 0x73, 0x00, 0x2e, 0x00, 0x73, 0x00, 0x69, 0x00,
0x6c, 0x00, 0x2e, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x67, 0x00, 0x2f, 0x00, 0x4f, 0x00,
0x46, 0x00, 0x4c, 0x22, 0x22, 0x00, 0x22, 0x00, 0x22, 0x43, 0x6f, 0x70, 0x79, 0x72,
0x69, 0x67, 0x68, 0x74, 0x20, 0x28, 0x63, 0x29, 0x20, 0x32, 0x30, 0x31, 0x30, 0x2d,
0x31, 0x33, 0x20, 0x62, 0x79, 0x20, 0x56, 0x65, 0x72, 0x6e, 0x6f, 0x6e, 0x20, 0x41,
0x64, 0x61, 0x6d, 0x73, 0x00, 0x43, 0x00, 0x6f, 0x00, 0x70, 0x00, 0x79, 0x00, 0x72,
0x00, 0x69, 0x00, 0x67, 0x00, 0x68, 0x00, 0x74, 0x00, 0x20, 0x00, 0x28, 0x00, 0x63,
0x00, 0x29, 0x00, 0x20, 0x00, 0x32, 0x00, 0x30, 0x00, 0x31, 0x00, 0x30, 0x00, 0x2d,
0x00, 0x31, 0x00, 0x33, 0x00, 0x20, 0x00, 0x62, 0x00, 0x79, 0x00, 0x20, 0x00, 0x56,
0x00, 0x65, 0x00, 0x72, 0x00, 0x6e, 0x00, 0x6f, 0x00, 0x6e, 0x00, 0x20, 0x00, 0x41,
0x00, 0x64, 0x00, 0x61, 0x00, 0x6d, 0x00, 0x73, 0x4f, 0x73, 0x77, 0x61, 0x6c, 0x64,
0x20, 0x69, 0x73, 0x20, 0x61, 0x20, 0x74, 0x72, 0x61, 0x64, 0x65, 0x6d, 0x61, 0x72,
0x6b, 0x20, 0x6f, 0x66, 0x20, 0x56, 0x65, 0x72, 0x6e, 0x6f, 0x6e, 0x20, 0x41, 0x64,
0x61, 0x6d, 0x73, 0x00, 0x4f, 0x00, 0x73, 0x00, 0x77, 0x00, 0x61, 0x00, 0x6c, 0x00,
0x64, 0x00, 0x20, 0x00, 0x69, 0x00, 0x73, 0x00, 0x20, 0x00, 0x61, 0x00, 0x20, 0x00,
0x74, 0x00, 0x72, 0x00, 0x61, 0x00, 0x64, 0x00, 0x65, 0x00, 0x6d, 0x00, 0x61, 0x00,
0x72, 0x00, 0x6b, 0x00, 0x20, 0x00, 0x6f, 0x00, 0x66, 0x00, 0x20, 0x00, 0x56, 0x00,
0x65, 0x00, 0x72, 0x00, 0x6e, 0x00, 0x6f, 0x00, 0x6e, 0x00, 0x20, 0x00, 0x41, 0x00,
0x64, 0x00, 0x61, 0x00, 0x6d, 0x00, 0x73, 0x56, 0x65, 0x72, 0x6e, 0x6f, 0x6e, 0x20,
0x41, 0x64, 0x61, 0x6d, 0x73, 0x3a, 0x57, 0x61, 0x79, 0x45, 0x64, 0x67, 0x65, 0x73,
0x2d, 0x53, 0x6c, 0x69, 0x64, 0x65, 0x20, 0x49, 0x74, 0x61, 0x6c, 0x69, 0x63, 0x00,
0x56, 0x00, 0x65, 0x00, 0x72, 0x00, 0x6e, 0x00, 0x6f, 0x00, 0x6e, 0x00, 0x20, 0x00,
0x41, 0x00, 0x64, 0x00, 0x61, 0x00, 0x6d, 0x00, 0x73, 0x00, 0x3a, 0x00, 0x57, 0x00,
0x61, 0x00, 0x79, 0x00, 0x45, 0x00, 0x64, 0x00, 0x67, 0x00, 0x65, 0x00, 0x73, 0x00,
0x2d, 0x00, 0x53, 0x00, 0x6c, 0x00, 0x69, 0x00, 0x64, 0x00, 0x65, 0x00, 0x20, 0x00,
0x49, 0x00, 0x74, 0x00, 0x61, 0x00, 0x6c, 0x00, 0x69, 0x00, 0x63, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x04,
0x00, 0x88, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x10, 0x00, 0x03, 0x00, 0x0e, 0x00, 0x00,
0x00, 0x20, 0x00, 0x25, 0x00, 0x2e, 0x00, 0x30, 0x00, 0x31, 0x00, 0x32, 0x00, 0x33,
0x00, 0x34, 0x00, 0x35, 0x00, 0x36, 0x00, 0x37, 0x00, 0x38, 0x00, 0x39, 0xff, 0xff,
0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x25, 0x00, 0x2e, 0x00, 0x30, 0x00, 0x31,
0x00, 0x32, 0x00, 0x33, 0x00, 0x34, 0x00, 0x35, 0x00, 0x36, 0x00, 0x37, 0x00, 0x38,
0x00, 0x39, 0xff, 0xff, 0x00, 0x00, 0xff, 0xe1, 0xff, 0xdd, 0xff, 0xd5, 0xff, 0xd4,
0xff, 0xd4, 0xff, 0xd4, 0xff, 0xd4, 0xff, 0xd4, 0xff, 0xd4, 0xff, 0xd4, 0xff, 0xd4,
0xff, 0xd4, 0xff, 0xd4, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
0x04, 0x01, 0x00, 0x01, 0x01, 0x01, 0x15, 0x57, 0x61, 0x79, 0x45, 0x64, 0x67, 0x65,
0x73, 0x2d, 0x53, 0x6c, 0x69, 0x64, 0x65, 0x49, 0x74, 0x61, 0x6c, 0x69, 0x63, 0x00,
0x01, 0x01, 0x01, 0x43, 0xf8, 0x1b, 0x00, 0xf8, 0x1c, 0x02, 0xf8, 0x1d, 0x03, 0xf8,
0x1e, 0x04, 0x8b, 0x75, 0x1c, 0x08, 0xb9, 0x1c, 0x07, 0xb3, 0x05, 0x1d, 0x00, 0x00,
0x00, 0xe0, 0x0f, 0x1d, 0x00, 0x00, 0x00, 0xfb, 0x11, 0x8b, 0x1d, 0x00, 0x00, 0x14,
0x99, 0x12, 0x1e, 0x0a, 0x00, 0x04, 0x88, 0x28, 0x12, 0x5f, 0x1e, 0x0f, 0x1e, 0x0f,
0x1e, 0x0a, 0x00, 0x04, 0x88, 0x28, 0x12, 0x5f, 0x1e, 0x0f, 0x1e, 0x0f, 0x0c, 0x07,
0x00, 0x11, 0x01, 0x01, 0x03, 0x18, 0x26, 0x2c, 0x31, 0x38, 0x3e, 0x42, 0x45, 0x48,
0x4d, 0x51, 0x55, 0x58, 0x5d, 0x62, 0x66, 0x22, 0x22, 0x57, 0x61, 0x79, 0x45, 0x64,
0x67, 0x65, 0x73, 0x2d, 0x53, 0x6c, 0x69, 0x64, 0x65, 0x20, 0x49, 0x74, 0x61, 0x6c,
0x69, 0x63, 0x57, 0x61, 0x79, 0x45, 0x64, 0x67, 0x65, 0x73, 0x2d, 0x53, 0x6c, 0x69,
0x64, 0x65, 0x49, 0x74, 0x61, 0x6c, 0x69, 0x63, 0x73, 0x70, 0x61, 0x63, 0x65, 0x70,
0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x70, 0x65, 0x72, 0x69, 0x6f, 0x64, 0x7a, 0x65,
0x72, 0x6f, 0x6f, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x74, 0x68, 0x72, 0x65, 0x65, 0x66,
0x6f, 0x75, 0x72, 0x66, 0x69, 0x76, 0x65, 0x73, 0x69, 0x78, 0x73, 0x65, 0x76, 0x65,
0x6e, 0x65, 0x69, 0x67, 0x68, 0x74, 0x6e, 0x69, 0x6e, 0x65, 0x00, 0x00, 0x00, 0x01,
0x8b, 0x01, 0x8c, 0x01, 0x8d, 0x01, 0x8e, 0x01, 0x8f, 0x01, 0x90, 0x01, 0x91, 0x01,
0x92, 0x01, 0x93, 0x01, 0x94, 0x01, 0x95, 0x01, 0x96, 0x01, 0x97, 0x00, 0x0e, 0x02,
0x00, 0x01, 0x00, 0x4c, 0x00, 0x4f, 0x03, 0xa2, 0x03, 0xc9, 0x05, 0x1b, 0x05, 0x66,
0x07, 0x3c, 0x09, 0x7c, 0x09, 0xfb, 0x0b, 0xfc, 0x0e, 0xb4, 0x0e, 0xf7, 0x11, 0x13,
0x13, 0x7e, 0xf8, 0x5d, 0x9f, 0xf9, 0x37, 0x15, 0x8b, 0x8b, 0x8b, 0xfd, 0x37, 0x8b,
0x8b, 0x08, 0x8b, 0x8b, 0xf8, 0x35, 0x8b, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0xf9,
0x37, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0xfc, 0x35, 0x8b, 0x8b, 0x8b, 0x08, 0xbb, 0xfd,
0x07, 0x15, 0x8b, 0x8b, 0x8b, 0xf8, 0xd7, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0xf7, 0xd4,
0x8b, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0xfc, 0xd7, 0x8b, 0x8b, 0x08, 0x8b, 0x8b,
0xfb, 0xd4, 0x8b, 0x8b, 0x8b, 0x08, 0x0e, 0xf8, 0x72, 0x0e, 0x1c, 0x07, 0xb3, 0xf8,
0x7b, 0xfa, 0x3f, 0x15, 0x6a, 0x8b, 0x72, 0x95, 0x7a, 0x9f, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0x7b, 0x9e, 0x82, 0xa6, 0x8a, 0xad, 0x08, 0x8b, 0x8b, 0x8b,
0x9a, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8b, 0xa4, 0x8d,
0xac, 0x8e, 0xb4, 0x08, 0x8b, 0x8b, 0x95, 0xe9, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0x8e, 0xa8, 0x8e, 0xa3, 0x8e, 0x9e, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0x8e, 0x9b, 0x8f, 0x9e, 0x92, 0xa2, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0x91, 0xa0, 0x93, 0x9a, 0x95, 0x96, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0x94, 0x96, 0x98, 0x93, 0x9b, 0x92, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0x9c, 0x92, 0x9d, 0x8f, 0xa0, 0x8b, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0xae, 0x8b, 0xa5, 0x82, 0x9c, 0x79, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0x9b, 0x7a, 0x94, 0x72, 0x8c, 0x6c, 0x08, 0x8b, 0x8b, 0x8b,
0x7d, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8b, 0x73, 0x89,
0x6a, 0x88, 0x61, 0x08, 0x8b, 0x8b, 0x81, 0x2d, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0x86, 0x64, 0x87, 0x6d, 0x87, 0x77, 0x08, 0x87, 0x77, 0x83,
0x74, 0x7f, 0x71, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x81, 0x74, 0x7d,
0x7b, 0x79, 0x80, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x78, 0x80, 0x76,
0x85, 0x72, 0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x77, 0xfb, 0x54,
0x15, 0xf7, 0x12, 0x8b, 0xea, 0xad, 0xcb, 0xd0, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b,
0x8b, 0x08, 0xca, 0xd0, 0xb3, 0xf2, 0x9a, 0xf7, 0x1d, 0x08, 0x8b, 0x8b, 0x96, 0xf3,
0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8e, 0xae, 0x8d, 0xa8,
0x8b, 0xa2, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8a, 0xea, 0x78, 0xd3,
0x65, 0xbe, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x5a, 0xcd, 0x32, 0xab,
0xfb, 0x13, 0x8a, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0xfb, 0x15, 0x8b,
0x2c, 0x69, 0x4d, 0x48, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x4e, 0x48,
0x64, 0x24, 0x7c, 0xfb, 0x20, 0x08, 0x8b, 0x8b, 0x81, 0x31, 0x8b, 0x8b, 0x08, 0x8b,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x88, 0x68, 0x89, 0x6e, 0x8b, 0x72, 0x08, 0x8b,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8a, 0x2c, 0x9e, 0x41, 0xb2, 0x55, 0x08, 0x8b,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0xbc, 0x44, 0xe3, 0x68, 0xf7, 0x12, 0x8c, 0x08,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0xfa, 0x9f, 0xfc, 0xc6, 0x15, 0x6a, 0x8b,
0x72, 0x95, 0x7b, 0x9f, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x7a, 0xa0,
0x83, 0xa5, 0x8a, 0xac, 0x08, 0x8b, 0x8b, 0x8b, 0x9c, 0x8b, 0x8b, 0x08, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8b, 0xac, 0x8c, 0xac, 0x8e, 0xaa, 0x08, 0x8b, 0x8b,
0x95, 0xe9, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8e, 0xa8,
0x8e, 0xa3, 0x8e, 0x9e, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8d, 0x96,
0x90, 0x9f, 0x93, 0xa6, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x91, 0xa0,
0x93, 0x9a, 0x95, 0x96, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x94, 0x96,
0x98, 0x93, 0x9b, 0x92, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x9c, 0x92,
0x9d, 0x8f, 0xa0, 0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0xaf, 0x8b,
0xa5, 0x82, 0x9b, 0x79, 0x08, 0x9b, 0x79, 0x93, 0x73, 0x8b, 0x6c, 0x08, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8b, 0x88, 0x8b, 0x89, 0x8c, 0x89, 0x08, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8b, 0x6e, 0x89, 0x67, 0x87, 0x62, 0x08, 0x8b, 0x8b,
0x81, 0x2d, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x86, 0x64,
0x87, 0x6d, 0x87, 0x76, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x86, 0x76,
0x84, 0x74, 0x80, 0x73, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x80, 0x74,
0x7e, 0x7a, 0x7a, 0x81, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x78, 0x80,
0x75, 0x85, 0x72, 0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x76, 0xfb,
0x54, 0x15, 0xf7, 0x12, 0x8b, 0xea, 0xad, 0xcb, 0xd0, 0x08, 0x8b, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x08, 0xca, 0xd0, 0xb3, 0xf2, 0x9a, 0xf7, 0x1d, 0x08, 0x8b, 0x8b, 0x96,
0xf3, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8e, 0xae, 0x8d,
0xa9, 0x8b, 0xa4, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8c, 0xe8, 0x78,
0xd2, 0x65, 0xbe, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x5a, 0xcc, 0x32,
0xac, 0xfb, 0x14, 0x8a, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0xfb, 0x15,
0x8b, 0x2c, 0x69, 0x4d, 0x48, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x4c,
0x48, 0x65, 0x23, 0x7c, 0xfb, 0x1f, 0x08, 0x8b, 0x8b, 0x81, 0x31, 0x8b, 0x8b, 0x08,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x88, 0x68, 0x89, 0x6f, 0x8b, 0x74, 0x08,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8c, 0x2a, 0x9f, 0x40, 0xb1, 0x55, 0x08,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0xbc, 0x44, 0xe2, 0x68, 0xf7, 0x11, 0x8c,
0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0xfd, 0x3a, 0x92, 0x15, 0x8b, 0x8b,
0xf9, 0x12, 0x1c, 0x06, 0x7a, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0xfb, 0x5a, 0x8b, 0x8b,
0x8b, 0x08, 0x8b, 0x8b, 0xfd, 0x12, 0x1c, 0xf9, 0x86, 0x8b, 0x8b, 0x08, 0x8b, 0x8b,
0xf7, 0x5a, 0x8b, 0x8b, 0x8b, 0x08, 0x0e, 0xf8, 0x44, 0xf7, 0xcb, 0x8b, 0x15, 0x8b,
0x8b, 0xa8, 0xf7, 0xa6, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0xfb, 0x9f, 0x8b, 0x8b, 0x8b,
0x08, 0x8b, 0x8b, 0x6e, 0xfb, 0xa6, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0xf7, 0x9f, 0x8b,
0x8b, 0x8b, 0x08, 0x0e, 0xfa, 0xb2, 0xf8, 0x88, 0xf7, 0x6c, 0x15, 0x38, 0x8b, 0x61,
0xc7, 0x8b, 0xf7, 0x0b, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8b, 0xa3,
0x8c, 0xa3, 0x8e, 0xa2, 0x08, 0x8b, 0x8b, 0xd6, 0xf9, 0x63, 0x8b, 0x8b, 0x08, 0x8b,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8f, 0xaf, 0x90, 0xa9, 0x91, 0xa4, 0x08, 0x8b,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x92, 0xa6, 0x94, 0xa5, 0x96, 0xa5, 0x08, 0x8b,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x97, 0xa6, 0x9c, 0xa0, 0xa2, 0x9a, 0x08, 0xa2,
0x9a, 0xa6, 0x92, 0xaa, 0x8b, 0x08, 0xaa, 0x8b, 0xa5, 0x83, 0x9e, 0x7c, 0x08, 0x9e,
0x7c, 0x98, 0x77, 0x91, 0x72, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x92,
0x70, 0x8e, 0x70, 0x8c, 0x6e, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8b,
0x7e, 0x8b, 0x84, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8b,
0x76, 0x89, 0x74, 0x88, 0x72, 0x08, 0x8b, 0x8b, 0x40, 0xfd, 0x63, 0x8b, 0x8b, 0x08,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x7a, 0xfb, 0x3b, 0x51, 0x38, 0x28, 0x8b,
0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x72, 0xfb, 0x82, 0x15, 0xf7, 0x1f,
0x8b, 0xf7, 0x03, 0xb7, 0xde, 0xe3, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08,
0xde, 0xe3, 0xbc, 0xf7, 0x09, 0x9a, 0xf7, 0x27, 0x08, 0x8b, 0x8b, 0xd7, 0xf9, 0x6b,
0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8e, 0xae, 0x8d, 0xa8,
0x8b, 0xa3, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8b, 0xf7, 0x03, 0x72,
0xe4, 0x59, 0xd0, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x4c, 0xe2, 0x24,
0xb7, 0xfb, 0x21, 0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0xfb, 0x23,
0x8b, 0xfb, 0x04, 0x60, 0x3a, 0x34, 0x08, 0x3a, 0x34, 0x5b, 0xfb, 0x0b, 0x7b, 0xfb,
0x2c, 0x08, 0x8b, 0x8b, 0x3f, 0xfd, 0x6b, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x08, 0x88, 0x72, 0x8a, 0x70, 0x8b, 0x6e, 0x08, 0x8b, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x08, 0x8a, 0xfb, 0x01, 0xa4, 0x30, 0xc0, 0x44, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0xcb, 0x33, 0xf1, 0x5f, 0xf7, 0x1f, 0x8b, 0x08, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x0e, 0xfa, 0xb3, 0xf9, 0x3d, 0x8b, 0x15, 0x8b, 0x8b,
0xf7, 0x42, 0x1c, 0x06, 0x7a, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0xfb, 0x69, 0x8b, 0x8b,
0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x4e, 0x49, 0xfb, 0x0b, 0x4f,
0xfb, 0x43, 0x56, 0x08, 0x8b, 0x8b, 0x75, 0xfb, 0x65, 0x8b, 0x8b, 0x08, 0x8b, 0x8b,
0xf7, 0xaa, 0xd0, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0xfb, 0x20, 0x1c, 0xfa, 0xc5, 0x8b,
0x8b, 0x08, 0x8b, 0x8b, 0xf7, 0xaa, 0x8b, 0x8b, 0x8b, 0x08, 0x0e, 0xfa, 0xb3, 0xf9,
0xf8, 0x8b, 0x15, 0x8b, 0x8b, 0xa3, 0xf7, 0x75, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0xfc,
0x87, 0x8b, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0xf8, 0x25, 0xf8, 0xa2, 0x8b, 0x8b, 0x08,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8c, 0x8c, 0x8d, 0x8e, 0x8e, 0x8f, 0x08,
0x8e, 0x8e, 0x8f, 0x91, 0x90, 0x92, 0x08, 0x90, 0x92, 0x91, 0x91, 0x90, 0x92, 0x08,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x9d, 0xa3, 0x96, 0x9a, 0x90, 0x92, 0x08,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8c, 0x8c, 0x8e, 0x8e, 0x8e, 0x8f, 0x08,
0x8e, 0x8f, 0x8e, 0x90, 0x90, 0x92, 0x08, 0x90, 0x92, 0x8f, 0x91, 0x90, 0x91, 0x08,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x9a, 0xa0, 0x96, 0x9b, 0x91, 0x94, 0x08,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8c, 0x8d, 0x8f, 0x91, 0x91, 0x95, 0x08,
0x90, 0x94, 0x90, 0x94, 0x90, 0x93, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08,
0x99, 0xa2, 0x94, 0x9b, 0x8f, 0x94, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08,
0x90, 0x97, 0x92, 0x9b, 0x94, 0x9f, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08,
0x92, 0x9c, 0x92, 0x9d, 0x90, 0xa0, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08,
0x92, 0xa7, 0x90, 0x9d, 0x8c, 0x94, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08,
0x8f, 0xa0, 0x8e, 0xa0, 0x8d, 0x9f, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08,
0x8e, 0xa2, 0x8c, 0xa4, 0x8b, 0xa6, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08,
0x8b, 0xf2, 0x71, 0xdd, 0x58, 0xc8, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08,
0x4c, 0xd7, 0x26, 0xb1, 0xfb, 0x1f, 0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b,
0x08, 0xfb, 0x28, 0x8b, 0xfb, 0x05, 0x5f, 0x3d, 0x33, 0x08, 0x8b, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x08, 0x3e, 0x34, 0x5c, 0xfb, 0x0e, 0x7a, 0xfb, 0x33, 0x08, 0x8b, 0x8b,
0x83, 0x45, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0xf7, 0xa6, 0x8b, 0x8b, 0x8b, 0x08, 0x8b,
0x8b, 0x92, 0xcf, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x9e,
0xf7, 0x43, 0xc8, 0xe5, 0xf4, 0x90, 0x08, 0x8b, 0x8b, 0x93, 0x8b, 0x8b, 0x8b, 0x08,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0xb8, 0x8b, 0xab, 0x7b, 0x9d, 0x6a, 0x08,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x99, 0x72, 0x92, 0x6a, 0x8b, 0x60, 0x08,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8b, 0x7c, 0x8a, 0x7a, 0x89, 0x78, 0x08,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x88, 0x6e, 0x85, 0x70, 0x84, 0x72, 0x08,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x84, 0x71, 0x82, 0x73, 0x81, 0x76, 0x08,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x82, 0x77, 0x7e, 0x74, 0x7a, 0x71, 0x08,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x78, 0x6e, 0x7d, 0x76, 0x82, 0x7f, 0x08,
0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x85, 0x83, 0x7b, 0x75, 0x70, 0x68, 0x08,
0x70, 0x68, 0x7b, 0x75, 0x85, 0x83, 0x08, 0x8b, 0x8b, 0xfc, 0x6d, 0xfd, 0x10, 0x8b,
0x8b, 0x08, 0x8b, 0x8b, 0x76, 0xfb, 0x58, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0xf9, 0xc7,
0x8b, 0x8b, 0x8b, 0x08, 0x0e, 0xfa, 0xb3, 0xf8, 0x6e, 0x75, 0x15, 0xd8, 0x8b, 0xce,
0x97, 0xc5, 0xa3, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0xc6, 0xa4, 0xbb,
0xad, 0xb0, 0xb6, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0xb3, 0xba, 0xaa,
0xc0, 0xa0, 0xc5, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0xa1, 0xc7, 0x9a,
0xcf, 0x93, 0xd8, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8e, 0xa5, 0x8c,
0xa6, 0x8b, 0xa8, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8b, 0xd2, 0x7f,
0xc8, 0x74, 0xbd, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x6a, 0xcf, 0x59,
0xb9, 0x47, 0xa4, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0xd1, 0x9f, 0xc6,
0xb4, 0xba, 0xca, 0x08, 0xba, 0xca, 0xa8, 0xd8, 0x95, 0xe8, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0x8e, 0xa1, 0x8c, 0xa3, 0x8b, 0xa6, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0x8b, 0xf5, 0x70, 0xdf, 0x55, 0xc9, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0x48, 0xd7, 0x24, 0xb1, 0xfb, 0x1f, 0x8b, 0x08, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0xfb, 0x1e, 0x8b, 0xfb, 0x02, 0x64, 0x39, 0x3e, 0x08,
0x39, 0x3e, 0x5a, 0xfb, 0x02, 0x7c, 0xfb, 0x21, 0x08, 0x8b, 0x8b, 0x83, 0x40, 0x8b,
0x8b, 0x08, 0x8b, 0x8b, 0xf7, 0xaa, 0x8b, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0x91, 0xc1,
0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x95, 0xd8, 0x9d, 0xc7,
0xa4, 0xb5, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0xa4, 0xb4, 0xb4, 0x9f,
0xc6, 0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0xc4, 0x8c, 0xb1, 0x78,
0x9e, 0x66, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x98, 0x6f, 0x92, 0x67,
0x8b, 0x5e, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x8b, 0x79, 0x8a, 0x78,
0x89, 0x76, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x82, 0x36, 0x75, 0x4f,
0x6a, 0x68, 0x08, 0x6a, 0x68, 0x55, 0x77, 0x41, 0x88, 0x08, 0x8b, 0x8b, 0x67, 0x8b,
0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0x71, 0xfb, 0x82, 0x8b, 0x8b, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0xa4, 0x8b, 0x98, 0x8b, 0x8e, 0x8a, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0xbc, 0x88, 0xb0, 0x7e, 0xa6, 0x73, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0xa6, 0x73, 0x9c, 0x6c, 0x92, 0x64, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0x8f, 0x76, 0x8d, 0x73, 0x8b, 0x70, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0x8b, 0x72, 0x8a, 0x73, 0x88, 0x73, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0x87, 0x67, 0x87, 0x6d, 0x87, 0x74, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0x88, 0x7b, 0x85, 0x73, 0x80, 0x6b, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0x83, 0x73, 0x81, 0x78, 0x7f, 0x7d, 0x08, 0x7f, 0x7d, 0x7b,
0x7f, 0x77, 0x82, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x79, 0x82, 0x74,
0x87, 0x6f, 0x8b, 0x08, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x8b, 0x08, 0x63, 0x8b, 0x6c,
0x95, 0x75, 0xa0, 0x08, 0x75, 0xa0, 0x7f, 0xa7, 0x88, 0xaf, 0x08, 0x8b, 0x8b, 0x8b,
0x8b, 0x8b, 0x8b, 0x08, 0x8a, 0xa2, 0x8a, 0x9d, 0x8b, 0x99, 0x08, 0x8b, 0x8b, 0x8b,
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | true |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/util/src/text/mod.rs | crates/util/src/text/mod.rs | mod draw;
pub mod slide_font;
pub use draw::*;
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/lib.rs | crates/backend/src/lib.rs | pub mod backlight;
pub mod config_file_watch;
pub mod ipc;
pub mod pulseaudio;
pub mod runtime;
pub mod system;
pub mod tray;
pub mod workspace;
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/system.rs | crates/backend/src/system.rs | use std::sync::{Arc, LazyLock, Mutex, MutexGuard};
use starship_battery::{Battery, State};
use sysinfo::{Disks, MemoryRefreshKind, System};
static SYSTEM: LazyLock<Arc<Mutex<System>>> = LazyLock::new(|| Arc::new(Mutex::new(System::new())));
fn get_system() -> MutexGuard<'static, System> {
Mutex::lock(&SYSTEM).unwrap()
}
pub struct MemoryInfo {
pub used: u64,
pub total: u64,
}
pub fn get_ram_info() -> MemoryInfo {
let mut sys = get_system();
sys.refresh_memory_specifics(MemoryRefreshKind::nothing().with_ram());
MemoryInfo {
used: sys.used_memory(),
total: sys.total_memory(),
}
}
pub fn get_swap_info() -> MemoryInfo {
let mut sys = get_system();
sys.refresh_memory_specifics(MemoryRefreshKind::nothing().with_swap());
let total = sys.total_swap();
let used = total - sys.free_swap();
MemoryInfo { used, total }
}
pub fn get_cpu_info(core: Option<usize>) -> f64 {
let mut sys = get_system();
sys.refresh_cpu_usage();
let usage = if let Some(core_id) = core {
let Some(cpu) = sys.cpus().get(core_id) else {
return 0.;
};
cpu.cpu_usage()
} else {
sys.global_cpu_usage()
} as f64;
usage / 100.
}
static BATTERY: LazyLock<Arc<Mutex<Battery>>> = LazyLock::new(|| {
let manager = starship_battery::Manager::new().unwrap();
let battery = manager.batteries().unwrap().next().unwrap().unwrap();
Arc::new(Mutex::new(battery))
});
fn get_battery() -> MutexGuard<'static, Battery> {
Mutex::lock(&BATTERY).unwrap()
}
pub fn get_battery_info() -> (f64, State) {
let mut battery = get_battery();
battery.refresh().unwrap();
use starship_battery::units::ratio::ratio;
(
battery.state_of_charge().get::<ratio>() as f64,
battery.state(),
)
}
static DISK: LazyLock<Arc<Mutex<Disks>>> = LazyLock::new(|| Arc::new(Mutex::new(Disks::new())));
fn get_disk() -> MutexGuard<'static, Disks> {
Mutex::lock(&DISK).unwrap()
}
pub struct DiskInfo {
pub used: u64,
pub total: u64,
}
pub fn get_disk_info(partition: &str) -> DiskInfo {
let mut disk = get_disk();
disk.refresh_specifics(true, sysinfo::DiskRefreshKind::nothing().with_storage());
let partition = disk
.iter()
.find(|d| d.mount_point().to_str().unwrap() == partition)
.unwrap();
let total = partition.total_space();
let used = total - partition.available_space();
DiskInfo { used, total }
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/runtime.rs | crates/backend/src/runtime.rs | use std::sync::atomic::AtomicPtr;
use tokio::runtime::{Handle, LocalRuntime};
static LOCAL_RUNTIME: AtomicPtr<LocalRuntime> = AtomicPtr::new(std::ptr::null_mut());
static TASK_HANDLER: AtomicPtr<Handle> = AtomicPtr::new(std::ptr::null_mut());
pub fn get_backend_runtime() -> &'static LocalRuntime {
unsafe {
LOCAL_RUNTIME
.load(std::sync::atomic::Ordering::Relaxed)
.as_ref()
.unwrap()
}
}
pub fn get_backend_runtime_handle() -> &'static Handle {
unsafe {
TASK_HANDLER
.load(std::sync::atomic::Ordering::Relaxed)
.as_ref()
.unwrap()
}
}
pub fn init_backend_runtime_handle() {
let (created, is_created) = tokio::sync::oneshot::channel();
std::thread::spawn(|| {
// let rt = tokio::runtime::Builder::new_current_thread()
// .enable_all()
// .build()
// .unwrap();
let rt = tokio::runtime::LocalRuntime::new().unwrap();
TASK_HANDLER.store(
Box::into_raw(Box::new(rt.handle().clone())),
std::sync::atomic::Ordering::Relaxed,
);
LOCAL_RUNTIME.store(
Box::into_raw(Box::new(rt)),
std::sync::atomic::Ordering::Relaxed,
);
created.send(()).unwrap();
get_backend_runtime().block_on(std::future::pending::<()>());
});
is_created.blocking_recv().unwrap();
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/config_file_watch.rs | crates/backend/src/config_file_watch.rs | use std::{sync::Arc, time::Duration};
use calloop::channel::Sender;
use config::get_config_path;
use futures_util::StreamExt;
use inotify::{EventMask, Inotify, WatchMask};
use log::info;
use crate::runtime::get_backend_runtime_handle;
pub fn start_configuration_file_watcher(sender: Sender<()>) {
get_backend_runtime_handle().spawn(async move {
let mut debouncer = None;
loop {
let inotify = Inotify::init().unwrap();
let file_path = get_config_path();
inotify
.watches()
.add(
file_path,
WatchMask::CREATE
| WatchMask::MODIFY
| WatchMask::DELETE
| WatchMask::DELETE_SELF
| WatchMask::MOVE
| WatchMask::MOVE_SELF
| WatchMask::ATTRIB,
)
.unwrap();
let mut buffer = [0; 1024];
let mut stream = inotify.into_event_stream(&mut buffer).unwrap();
while let Some(event_or_error) = stream.next().await {
let event = event_or_error.unwrap();
info!("Received inotify event: {event:?}");
let new_d = Arc::new(());
let weak_d = Arc::downgrade(&new_d);
debouncer.replace(new_d);
let sender = sender.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(700)).await;
if weak_d.upgrade().is_none() {
return;
}
sender.send(()).unwrap();
});
if event.mask == EventMask::IGNORED {
break;
}
}
}
});
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/tray/event.rs | crates/backend/src/tray/event.rs | use std::sync::Arc;
use system_tray::client::ActivateRequest;
use crate::runtime::get_backend_runtime_handle;
use super::{
context::{get_tray_context, TrayMap},
item::{Icon, RootMenu, Tray},
};
#[derive(Debug, Clone)]
pub enum TrayEventSignal {
Add(Arc<String>),
Rm(Arc<String>),
Update(Arc<String>),
}
impl TrayMap {
pub(super) fn handle_event(
&mut self,
e: system_tray::client::Event,
) -> Option<TrayEventSignal> {
match e {
system_tray::client::Event::Add(dest, status_notifier_item) => {
let item = Tray::new(*status_notifier_item);
let dest = Arc::new(dest);
self.inner.insert(dest.clone(), item);
Some(TrayEventSignal::Add(dest))
}
system_tray::client::Event::Remove(id) => {
self.inner.remove(&id);
Some(TrayEventSignal::Rm(Arc::new(id)))
}
system_tray::client::Event::Update(id, update_event) => {
let need_update = match update_event {
system_tray::client::UpdateEvent::Menu(tray_menu) => {
if let Some(tray) = self.inner.get_mut(&id) {
tray.update_menu(RootMenu::from_tray_menu(tray_menu))
}
true
}
system_tray::client::UpdateEvent::Title(title) => self
.inner
.get_mut(&id)
.map(|tray| tray.update_title(title))
.unwrap_or_default(),
system_tray::client::UpdateEvent::Icon {
icon_name,
icon_pixmap,
} => {
let icon = icon_name
.filter(|name| !name.is_empty())
.map(Icon::Named)
.or_else(|| {
icon_pixmap
.filter(|pixmap| !pixmap.is_empty())
.map(Icon::Pixmap)
});
self.inner
.get_mut(&id)
.map(|tray| tray.update_icon(icon))
.unwrap_or_default()
}
// not implemented
system_tray::client::UpdateEvent::AttentionIcon(_) => {
log::warn!("NOT IMPLEMENTED ATTENTION ICON");
false
}
system_tray::client::UpdateEvent::OverlayIcon(_) => {
log::warn!("NOT IMPLEMENTED OVERLAY ICON");
false
}
system_tray::client::UpdateEvent::Status(_) => {
// no need
log::warn!("NOT IMPLEMENTED STATUS");
false
}
system_tray::client::UpdateEvent::Tooltip(_) => {
// maybe some other time
log::warn!("NOT IMPLEMENTED TOOLTIP");
false
}
system_tray::client::UpdateEvent::MenuDiff(diffs) => {
if let Some(tray) = self.inner.get_mut(&id) {
diffs
.into_iter()
.for_each(|diff| tray.update_menu_item(diff));
}
true
}
system_tray::client::UpdateEvent::MenuConnect(_) => {
// no need i think?
log::warn!("NOT IMPLEMENTED MENU CONNECT");
false
}
};
if need_update {
Some(TrayEventSignal::Update(Arc::new(id)))
} else {
None
}
}
}
}
}
pub fn tray_active_request(req: ActivateRequest) {
get_backend_runtime_handle().spawn(async move {
if let Err(e) = get_tray_context().client.activate(req).await {
let msg = format!("error requesting tray activation: {e:?}");
log::error!("{msg}");
}
});
}
pub fn tray_about_to_show_menuitem(address: String, path: String, id: i32) {
get_backend_runtime_handle().spawn(async move {
if let Err(e) = get_tray_context()
.client
.about_to_show_menuitem(address, path, id)
.await
{
let msg = format!("error requesting tray about to show: {e:?}");
log::error!("{msg}");
}
});
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/tray/mod.rs | crates/backend/src/tray/mod.rs | mod context;
mod event;
pub mod icon;
pub mod item;
pub use context::{
init_tray_client, register_tray, unregister_tray, TrayBackendHandle, TrayMap, TrayMsg,
};
pub use event::{tray_about_to_show_menuitem, tray_active_request, TrayEventSignal};
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/tray/item.rs | crates/backend/src/tray/item.rs | use std::{collections::HashMap, sync::Mutex};
use cairo::ImageSurface;
use log::{error, warn};
use system_tray::{
item::{IconPixmap, StatusNotifierItem},
menu::MenuDiff,
};
use super::icon::{
fallback_icon, parse_icon_given_data, parse_icon_given_name, parse_icon_given_pixmaps,
IconThemeNameOrPath,
};
#[derive(Debug, Hash, PartialEq, Eq)]
struct IconCacheKey {
size: i32,
t: IconCacheType,
}
#[derive(Debug, Hash, PartialEq, Eq)]
enum IconCacheType {
Name {
name: String,
theme: Option<String>,
theme_path: Option<String>,
},
PngData,
Pixmap,
}
#[derive(Debug)]
// Using Mutex instead of RefCell for thread safety to be consistent with Arc<Mutex<TrayMap>>
// sharing pattern and to satisfy clippy::arc_with_non_send_sync. While this application
// uses single-threaded async runtime, Wayland API constraints require Send+Sync types.
pub struct IconHandle {
cache: Mutex<HashMap<IconCacheKey, ImageSurface>>,
icon: Option<Icon>,
}
impl IconHandle {
fn new(icon: Option<Icon>) -> Self {
Self {
cache: Mutex::new(HashMap::new()),
icon,
}
}
pub fn draw_icon(
&self,
size: i32,
theme: Option<&str>,
theme_path: Option<&str>,
) -> ImageSurface {
let Some(icon) = self.icon.as_ref() else {
return ImageSurface::create(cairo::Format::ARgb32, size, size).unwrap();
};
// cache
let cache_key = IconCacheKey {
size,
t: match icon {
Icon::Named(name) => IconCacheType::Name {
name: name.clone(),
theme: theme.map(ToString::to_string),
theme_path: theme_path.map(ToString::to_string),
},
Icon::PngData(_) => IconCacheType::PngData,
Icon::Pixmap(_) => IconCacheType::Pixmap,
},
};
if let Some(cache) = self.cache.lock().unwrap().get(&cache_key).cloned() {
return cache;
}
if let Some(content) = icon.draw_icon(size, theme, theme_path) {
self.cache
.lock()
.unwrap()
.insert(cache_key, content.clone());
return content;
}
fallback_icon(size, theme)
.unwrap_or(ImageSurface::create(cairo::Format::ARgb32, size, size).unwrap())
}
}
#[derive(Debug)]
pub enum Icon {
Named(String),
PngData(Vec<u8>),
Pixmap(Vec<IconPixmap>),
}
impl Icon {
pub fn draw_icon(
&self,
size: i32,
theme: Option<&str>,
theme_path: Option<&str>,
) -> Option<ImageSurface> {
match self {
Icon::Named(name) => {
let theme_or_path = theme_path
.filter(|path| !path.is_empty())
.map(IconThemeNameOrPath::Path)
.unwrap_or_else(|| IconThemeNameOrPath::Name(theme));
parse_icon_given_name(name, size, theme_or_path)
}
Icon::PngData(items) => parse_icon_given_data(items, size),
Icon::Pixmap(icon_pixmap) => parse_icon_given_pixmaps(icon_pixmap, size),
}
}
}
impl PartialEq for Icon {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Named(l0), Self::Named(r0)) => l0 == r0,
// THIS OPERATION IS HEAVY
(Self::PngData(_), Self::PngData(_)) | (Self::Pixmap(_), Self::Pixmap(_)) => false,
_ => core::mem::discriminant(self) == core::mem::discriminant(other),
}
}
}
#[derive(Debug)]
pub struct RootMenu {
#[allow(dead_code)]
pub id: i32,
pub submenus: Vec<MenuItem>,
}
impl RootMenu {
pub(super) fn from_tray_menu(tray_menu: system_tray::menu::TrayMenu) -> Self {
Self {
id: tray_menu.id as i32,
submenus: tray_menu
.submenus
.into_iter()
.map(MenuItem::from_menu_item)
.collect(),
}
}
}
#[derive(Debug)]
pub struct MenuItem {
pub id: i32,
pub enabled: bool,
pub label: Option<String>,
pub icon: Option<IconHandle>,
pub menu_type: MenuType,
pub submenu: Option<Vec<MenuItem>>,
}
impl MenuItem {
fn from_menu_item(value: system_tray::menu::MenuItem) -> Self {
let system_tray::menu::MenuItem {
id,
menu_type,
label,
enabled,
icon_name,
icon_data,
toggle_type,
toggle_state,
children_display,
submenu,
..
// shortcut,
// visible,
// disposition,
} = value;
let icon = icon_data
.map(Icon::PngData)
.or_else(|| icon_name.map(Icon::Named))
.map(Some)
.map(IconHandle::new);
let menu_type = match menu_type {
system_tray::menu::MenuType::Separator => MenuType::Separator,
system_tray::menu::MenuType::Standard => {
match toggle_type {
system_tray::menu::ToggleType::Checkmark => {
MenuType::Check(match toggle_state {
system_tray::menu::ToggleState::On => true,
system_tray::menu::ToggleState::Off => false,
system_tray::menu::ToggleState::Indeterminate => {
log::error!("THIS SHOULD NOT HAPPEN. menu item has toggle but not toggle state");
// ???
false
}
})
}
system_tray::menu::ToggleType::Radio => {
MenuType::Radio(match toggle_state {
system_tray::menu::ToggleState::On => true,
system_tray::menu::ToggleState::Off => false,
system_tray::menu::ToggleState::Indeterminate => {
log::error!("THIS SHOULD NOT HAPPEN. menu item has toggle but not toggle state");
// ???
false
}
})
}
system_tray::menu::ToggleType::CannotBeToggled => MenuType::Normal,
}
}
};
let submenu = if let Some("submenu") = children_display.as_deref() {
Some(submenu.into_iter().map(MenuItem::from_menu_item).collect())
} else {
None
};
Self {
id,
label,
enabled,
icon,
menu_type,
submenu,
}
}
}
#[derive(Debug)]
pub enum MenuType {
Radio(bool),
Check(bool),
// should the menu wtih submenus have toggle states?
Separator,
Normal,
}
#[derive(Debug)]
pub struct Tray {
pub id: String,
pub title: Option<String>,
pub icon: IconHandle,
pub icon_theme_path: Option<String>,
pub menu_path: Option<String>,
pub menu: Option<RootMenu>,
}
impl Tray {
pub(super) fn new(value: StatusNotifierItem) -> Self {
let StatusNotifierItem {
id,
title,
icon_theme_path,
icon_name,
icon_pixmap,
menu,
..
// category,
// status,
// window_id,
// overlay_icon_name,
// overlay_icon_pixmap,
// attention_icon_name,
// attention_icon_pixmap,
// attention_movie_name,
// tool_tip,
// item_is_menu,
} = value;
let icon = icon_name
.filter(|icon_name| !icon_name.is_empty())
.map(Icon::Named)
.or_else(|| icon_pixmap.map(Icon::Pixmap));
let icon = IconHandle::new(icon);
let menu_path = menu;
Tray {
id,
title,
icon,
menu_path,
menu: None,
icon_theme_path,
}
}
pub(super) fn update_title(&mut self, title: Option<String>) -> bool {
if self.title != title {
self.title = title;
true
} else {
false
}
}
pub(super) fn update_icon(&mut self, icon: Option<Icon>) -> bool {
if self.icon.icon != icon {
self.icon = IconHandle::new(icon);
true
} else {
false
}
}
pub(super) fn update_menu(&mut self, new: RootMenu) {
self.menu.replace(new);
}
pub(super) fn update_menu_item(&mut self, diff: MenuDiff) {
if let Some(root) = &mut self.menu {
fn find_menu_by_id(v: &mut [MenuItem], id: i32) -> Option<&mut MenuItem> {
v.iter_mut().find_map(|item| {
if item.id == id {
Some(item)
} else {
if let Some(submenu) = &mut item.submenu {
return find_menu_by_id(submenu, id);
}
None
}
})
}
if let Some(item) = find_menu_by_id(&mut root.submenus, diff.id) {
// update
if let Some(label) = diff.update.label {
item.label = label
}
if let Some(enabled) = diff.update.enabled {
item.enabled = enabled;
}
if let Some(icon_name) = diff.update.icon_name {
item.icon = Some(IconHandle::new(icon_name.map(Icon::Named)));
}
if let Some(icon_data) = diff.update.icon_data {
item.icon = Some(IconHandle::new(icon_data.map(Icon::PngData)));
}
if let Some(toggle_state) = diff.update.toggle_state {
use system_tray::menu::ToggleState::*;
match toggle_state {
On | Off => match &mut item.menu_type {
MenuType::Radio(v) | MenuType::Check(v) => *v = toggle_state == On,
_ => error!("Menu item with toggle state but not toggle type"),
},
Indeterminate => {
warn!(
"Menu item with toggle state Indeterminate, this should not happen"
);
item.menu_type = MenuType::Normal;
}
}
}
// remove
for i in diff.remove {
#[allow(clippy::single_match)]
match i.as_str() {
"enabled" => {
item.enabled = true;
}
_ => {}
}
}
}
}
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/tray/context.rs | crates/backend/src/tray/context.rs | use std::{
borrow::Borrow,
collections::HashMap,
hash::Hash,
sync::{
atomic::{AtomicBool, AtomicPtr},
Arc, Mutex,
},
};
use calloop::channel::Sender;
use system_tray::client::{Client, Event};
use crate::runtime::get_backend_runtime_handle;
use super::{event::TrayEventSignal, item::Tray};
/// destination
pub type TrayMsg = TrayEventSignal;
#[derive(Debug)]
pub struct TrayBackendHandle {
tray_map: Arc<Mutex<TrayMap>>,
id: i32,
}
impl TrayBackendHandle {
pub fn get_tray_map(&self) -> Arc<Mutex<TrayMap>> {
self.tray_map.clone()
}
}
impl Drop for TrayBackendHandle {
fn drop(&mut self) {
unregister_tray(self.id);
}
}
#[derive(Debug)]
pub struct TrayMap {
pub(super) inner: HashMap<Arc<String>, Tray>,
}
impl TrayMap {
// Allow Arc<Mutex<TrayMap>> despite TrayMap not being Send+Sync due to cairo::ImageSurface.
// This is acceptable because:
// 1. Application uses single-threaded async runtime (LocalRuntime)
// 2. Arc<Mutex<...>> pattern required by Wayland API constraints (WlSurface::data needs Send+Sync)
// 3. Cairo surfaces are inherently not thread-safe and shouldn't cross thread boundaries
#[allow(clippy::arc_with_non_send_sync)]
fn new() -> Arc<Mutex<Self>> {
Arc::new(Mutex::new(Self {
inner: HashMap::new(),
}))
}
pub fn list_tray(&self) -> Vec<(Arc<String>, &Tray)> {
self.inner.iter().map(|(k, v)| (k.clone(), v)).collect()
}
pub fn get_tray<Q: Hash + Eq>(&self, destination: &Q) -> Option<&Tray>
where
Arc<String>: Borrow<Q>,
{
self.inner.get(destination)
}
}
pub(super) struct TrayContext {
pub client: Client,
tray_map: Arc<Mutex<TrayMap>>,
cbs: HashMap<i32, Sender<TrayMsg>>,
count: i32,
}
impl TrayContext {
fn new(client: Client) -> Self {
Self {
client,
cbs: HashMap::new(),
count: 0,
tray_map: TrayMap::new(),
}
}
pub fn call(&mut self, e: Event) {
let mut map = self.tray_map.lock().unwrap();
if let Some(dest) = map.handle_event(e) {
drop(map);
self.cbs.iter().for_each(|(_, cb)| {
cb.send(dest.clone()).unwrap();
});
}
}
fn add_cb(&mut self, cb: Sender<TrayMsg>) -> TrayBackendHandle {
let key = self.count;
self.count += 1;
self.cbs.insert(key, cb);
TrayBackendHandle {
tray_map: self.tray_map.clone(),
id: key,
}
}
fn remove_cb(&mut self, key: i32) {
self.cbs.remove_entry(&key);
}
}
static TRAY_CONTEXT: AtomicPtr<TrayContext> = AtomicPtr::new(std::ptr::null_mut());
pub(super) fn get_tray_context() -> &'static mut TrayContext {
unsafe {
TRAY_CONTEXT
.load(std::sync::atomic::Ordering::Acquire)
.as_mut()
.unwrap()
}
}
pub fn init_tray_client() {
static CONTEXT_INITED: AtomicBool = AtomicBool::new(false);
if CONTEXT_INITED.load(std::sync::atomic::Ordering::Acquire) {
return;
}
let client = get_backend_runtime_handle().block_on(async { Client::new().await.unwrap() });
let mut tray_rx = client.subscribe();
TRAY_CONTEXT.store(
Box::into_raw(Box::new(TrayContext::new(client))),
std::sync::atomic::Ordering::Release,
);
CONTEXT_INITED.store(true, std::sync::atomic::Ordering::Release);
get_backend_runtime_handle().spawn(async move {
while let Ok(ev) = tray_rx.recv().await {
// log::debug!("tray event: {ev:?}");
get_tray_context().call(ev);
}
});
}
pub fn register_tray(cb: Sender<TrayMsg>) -> TrayBackendHandle {
get_tray_context().add_cb(cb)
}
pub fn unregister_tray(id: i32) {
get_tray_context().remove_cb(id);
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/tray/icon/freedesktop.rs | crates/backend/src/tray/icon/freedesktop.rs | use std::{path::PathBuf, sync::LazyLock};
static DEFAULT_ICON_THEME: LazyLock<Option<String>> = LazyLock::new(linicon_theme::get_icon_theme);
pub fn fallback_icon(size: i32, theme: Option<&str>) -> Option<PathBuf> {
let mut builder = freedesktop_icons::lookup("image-missing")
.with_size(size as u16)
.with_size_scheme(freedesktop_icons::SizeScheme::LargerClosest)
.with_cache();
if let Some(t) = theme.or(DEFAULT_ICON_THEME.as_deref()) {
builder = builder.with_theme(t);
}
builder.find()
}
pub fn find_icon(name: &str, size: i32, theme: Option<&str>) -> Option<PathBuf> {
let mut builder = freedesktop_icons::lookup(name)
.with_size(size as u16)
.with_size_scheme(freedesktop_icons::SizeScheme::LargerClosest);
if let Some(t) = theme.or(DEFAULT_ICON_THEME.as_deref()) {
builder = builder.with_theme(t);
}
builder.find()
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/tray/icon/mod.rs | crates/backend/src/tray/icon/mod.rs | mod custom;
mod freedesktop;
use std::{io::Cursor, path::PathBuf};
use cairo::ImageSurface;
use resvg::{tiny_skia, usvg};
use system_tray::item::IconPixmap;
use util::{pre_multiply_and_to_little_endian_argb, Z};
pub fn parse_icon_given_data(vec: &Vec<u8>, size: i32) -> Option<ImageSurface> {
ImageSurface::create_from_png(&mut Cursor::new(vec))
.ok()
.and_then(|img| scale_image_to_size(img, size))
}
pub fn parse_icon_given_pixmaps(vec: &[IconPixmap], size: i32) -> Option<ImageSurface> {
if vec.is_empty() {
None
} else {
let pixmap = vec.last().unwrap();
// ARGB
let mut pixels = pixmap.pixels.clone();
// pre multiply
for i in (0..pixels.len()).step_by(4) {
// little endian (BGRA)
let res = pre_multiply_and_to_little_endian_argb([
pixels[i + 1],
pixels[i + 2],
pixels[i + 3],
pixels[i],
]);
pixels[i] = res[0];
pixels[i + 1] = res[1];
pixels[i + 2] = res[2];
pixels[i + 3] = res[3];
}
let img = ImageSurface::create_for_data(
pixels,
cairo::Format::ARgb32,
pixmap.width,
pixmap.height,
pixmap.width * 4,
)
.unwrap();
scale_image_to_size(img, size)
}
}
pub enum IconThemeNameOrPath<'a> {
Name(Option<&'a str>),
Path(&'a str),
}
pub fn parse_icon_given_name(
name: &str,
size: i32,
theme: IconThemeNameOrPath,
) -> Option<ImageSurface> {
let f = match theme {
IconThemeNameOrPath::Name(n) => freedesktop::find_icon(name, size, n),
IconThemeNameOrPath::Path(p) => custom::find_icon(p, name),
}?;
draw_icon_file(f, size)
}
pub fn fallback_icon(size: i32, theme: Option<&str>) -> Option<ImageSurface> {
let f = freedesktop::fallback_icon(size, theme)?;
draw_icon_file(f, size)
}
fn scale_image_to_size(img: ImageSurface, size: i32) -> Option<ImageSurface> {
if img.height() == 0 || img.width() == 0 {
log::error!(
"scale_image_to_size error: image has zero width or height: width={}, height={}",
img.width(),
img.height()
);
return None;
}
let scale = size as f64 / img.height() as f64;
let width = (img.width() as f64 * scale).ceil() as i32;
let height = (img.height() as f64 * scale).ceil() as i32;
let surf = ImageSurface::create(cairo::Format::ARgb32, width, height).unwrap();
let context = cairo::Context::new(&surf).unwrap();
context.scale(scale, scale);
context.set_source_surface(&img, Z, Z).unwrap();
context.paint().unwrap();
Some(surf)
}
fn draw_icon_file(file_path: PathBuf, size: i32) -> Option<ImageSurface> {
let ext = file_path.extension().unwrap().to_str().unwrap();
let img = match ext {
"png" => load_png(&file_path),
"svg" => load_svg(&file_path),
_ => {
log::error!("draw_icon_file error: unsupported file extension: {ext}");
return None;
}
}?;
scale_image_to_size(img, size)
}
fn load_png(p: &PathBuf) -> Option<ImageSurface> {
let contents = std::fs::read(p)
.inspect_err(|e| log::error!("load_png error: {e}"))
.ok()?;
ImageSurface::create_from_png(&mut Cursor::new(contents))
.inspect_err(|f| log::error!("load_png to surface error: {f}"))
.ok()
}
fn load_svg(p: &PathBuf) -> Option<ImageSurface> {
let tree = {
let opt = usvg::Options {
resources_dir: std::fs::canonicalize(p)
.ok()
.and_then(|p| p.parent().map(|p| p.to_path_buf())),
..usvg::Options::default()
};
// NOTE: WE DO NOT EXPECT TEXT TO APPEAR INSIDE
// opt.fontdb.load_system_fonts();
let svg_data = std::fs::read(p)
.inspect_err(|f| log::error!("load_svg error: {f}"))
.ok()?;
usvg::Tree::from_data(&svg_data, &opt)
.inspect_err(|f| log::error!("parse svg data error: {f}"))
.ok()?
};
let pixmap_size = tree.size().to_int_size();
let mut pixmap = tiny_skia::Pixmap::new(pixmap_size.width(), pixmap_size.height()).unwrap();
resvg::render(&tree, tiny_skia::Transform::default(), &mut pixmap.as_mut());
// RGBA
let mut pixels = pixmap.take();
// TO BGRA(little endian of ARGB)
for i in (0..pixels.len()).step_by(4) {
let bgra = [pixels[i + 2], pixels[i + 1], pixels[i], pixels[i + 3]];
pixels[i] = bgra[0];
pixels[i + 1] = bgra[1];
pixels[i + 2] = bgra[2];
pixels[i + 3] = bgra[3];
}
ImageSurface::create_for_data(
pixels,
cairo::Format::ARgb32,
pixmap_size.width() as i32,
pixmap_size.height() as i32,
pixmap_size.width() as i32 * 4,
)
.inspect_err(|f| log::error!("load_svg to surface error: {f}"))
.ok()
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/tray/icon/custom.rs | crates/backend/src/tray/icon/custom.rs | use std::{
collections::BTreeMap,
ffi::OsStr,
path::PathBuf,
sync::{LazyLock, Mutex},
};
pub fn find_icon(icon_theme_path: &str, icon_name: &str) -> Option<PathBuf> {
if let Some(path) = try_cached(icon_theme_path, icon_name) {
return Some(path);
}
walkdir::WalkDir::new(icon_theme_path)
.max_depth(1)
.contents_first(true)
.into_iter()
.find_map(|r| {
let r = match r {
Ok(r) => r,
Err(e) => {
log::error!("Error walking dir: {e}");
return None;
}
};
let (Some(before), Some(after)) = rsplit_file_at_dot(r.file_name()) else {
return None;
};
match after.as_encoded_bytes() {
b"png" | b"svg" => {
if before.as_encoded_bytes() == icon_name.as_bytes() {
Some(r.into_path())
} else {
None
}
}
_ => None,
}
})
.inspect(|f| {
insert_to_cache(icon_theme_path, icon_name, f.clone());
})
}
fn rsplit_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
if file.as_encoded_bytes() == b".." {
return (Some(file), None);
}
// The unsafety here stems from converting between &OsStr and &[u8]
// and back. This is safe to do because (1) we only look at ASCII
// contents of the encoding and (2) new &OsStr values are produced
// only from ASCII-bounded slices of existing &OsStr values.
let mut iter = file.as_encoded_bytes().rsplitn(2, |b| *b == b'.');
let after = iter.next();
let before = iter.next();
if before == Some(b"") {
(Some(file), None)
} else {
unsafe {
(
before.map(|s| OsStr::from_encoded_bytes_unchecked(s)),
after.map(|s| OsStr::from_encoded_bytes_unchecked(s)),
)
}
}
}
type NameCache = BTreeMap<String, PathBuf>;
type ThemePathCache = BTreeMap<String, NameCache>;
#[derive(Default)]
struct Cache(Mutex<ThemePathCache>);
static CACHE: LazyLock<Cache> = LazyLock::new(Cache::default);
fn try_cached(icon_theme_path: &str, icon_name: &str) -> Option<PathBuf> {
CACHE
.0
.lock()
.unwrap()
.get(icon_theme_path)?
.get(icon_name)
.cloned()
}
fn insert_to_cache(icon_theme_path: &str, icon_name: &str, path: PathBuf) {
let mut theme_map = CACHE.0.lock().unwrap();
match theme_map.get_mut(icon_theme_path) {
Some(icon_map) => {
icon_map.insert(icon_name.to_string(), path);
}
None => {
let mut icon_map = BTreeMap::new();
icon_map.insert(icon_name.to_string(), path);
theme_map.insert(icon_theme_path.to_string(), icon_map);
}
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/backlight/dbus.rs | crates/backend/src/backlight/dbus.rs | use zbus::proxy;
use zbus::Connection;
use crate::backlight::match_device;
use crate::runtime::get_backend_runtime_handle;
// NOTE: this dbus proxy takes 2 threads
// it'll create 1 thread which always on after first connection
#[proxy(interface = "org.freedesktop.login1.Session")]
trait BackLight {
fn SetBrightness(&self, subsystem: &str, name: &str, brightness: u32) -> zbus::Result<()>;
}
async fn get_proxy() -> zbus::Result<BackLightProxy<'static>> {
let connection = Connection::system().await?;
BackLightProxy::new(
&connection,
"org.freedesktop.login1",
"/org/freedesktop/login1/session/auto",
)
.await
}
pub async fn set_brightness(device_name: &str, v: u32) -> zbus::Result<()> {
let proxy = get_proxy().await?;
proxy.SetBrightness("backlight", device_name, v).await?;
Ok(())
}
pub fn set_backlight(device_name: Option<&String>, p: f64) {
let device = match_device(device_name).unwrap();
let device_name = device.name().to_string();
let v = (device.max() as f64) * p;
get_backend_runtime_handle().spawn(async move {
if let Err(e) = set_brightness(&device_name, v as u32).await {
log::error!("Error setting brightness: {e}");
}
});
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/backlight/mod.rs | crates/backend/src/backlight/mod.rs | pub mod dbus;
use std::{
borrow::Cow,
collections::{HashMap, HashSet},
rc::Rc,
sync::atomic::{AtomicBool, AtomicPtr, Ordering},
};
use blight::Device;
use calloop::channel::Sender;
use futures_util::StreamExt;
use inotify::{Inotify, WatchDescriptor, WatchMask, Watches};
use crate::runtime::get_backend_runtime_handle;
type ID = i32;
type DeviceName = Rc<String>;
struct BackLight {
count: i32,
cbs: HashMap<ID, (DeviceName, Sender<f64>)>,
device_map: HashMap<DeviceName, (WatchDescriptor, Device, HashSet<ID>)>,
watcher: Watches,
path_to_device_name: HashMap<WatchDescriptor, DeviceName>,
}
impl BackLight {
fn new(watcher: Watches) -> Self {
Self {
count: 0,
cbs: HashMap::new(),
device_map: HashMap::new(),
watcher,
path_to_device_name: HashMap::new(),
}
}
fn call(&mut self, fd: WatchDescriptor) {
#[allow(clippy::option_map_unit_fn)]
self.path_to_device_name
.get(&fd)
.and_then(|name| self.device_map.get_mut(name))
.map(|(_, device, ids)| {
device.reload();
let v = device.current_percent() / 100.;
ids.iter().for_each(|i| {
if let Some((_, s)) = self.cbs.get(i) {
s.send(v).unwrap();
}
});
});
}
fn add_cb(&mut self, cb: Sender<f64>, mut device: Device) -> Result<i32, String> {
device.reload();
let id = self.count;
let name = Rc::new(device.name().to_string());
cb.send(device.current_percent() / 100.).unwrap();
self.cbs.insert(id, (name.clone(), cb));
if let Some((_, _, id_set)) = self.device_map.get_mut(&name) {
id_set.insert(self.count);
} else {
let fd = self
.watcher
.add(
device.device_path().as_path(),
WatchMask::CREATE | WatchMask::MODIFY | WatchMask::DELETE,
)
.unwrap();
self.device_map
.insert(name.clone(), (fd.clone(), device, HashSet::from([id])));
self.path_to_device_name.insert(fd, name);
}
self.count += 1;
Ok(id)
}
fn remove_cb(&mut self, key: i32) {
if let Some((name, _)) = self.cbs.remove(&key) {
let (_, _, id_set) = self.device_map.get_mut(&name).unwrap();
id_set.remove(&key);
if id_set.is_empty() {
let (fd, _, _) = self.device_map.remove(&name).unwrap();
self.watcher.remove(fd).unwrap();
}
}
}
}
static IS_BL_INITED: AtomicBool = AtomicBool::new(false);
static BL_CTX: AtomicPtr<BackLight> = AtomicPtr::new(std::ptr::null_mut());
fn get_ctx() -> &'static mut BackLight {
unsafe { BL_CTX.load(Ordering::Acquire).as_mut().unwrap() }
}
fn is_bl_inited() -> bool {
IS_BL_INITED.load(Ordering::Acquire)
}
pub fn try_init_backlight() {
if !is_bl_inited() {
IS_BL_INITED.store(true, Ordering::Release);
let watcher = init_watcher();
BL_CTX.store(
Box::into_raw(Box::new(BackLight::new(watcher))),
Ordering::Release,
);
}
}
fn init_watcher() -> Watches {
let inotify = Inotify::init().unwrap();
let watches = inotify.watches();
get_backend_runtime_handle().spawn(async move {
let mut buffer = [0; 1024];
let mut stream = inotify.into_event_stream(&mut buffer).unwrap();
while let Some(event_or_error) = stream.next().await {
let event = event_or_error.unwrap();
get_ctx().call(event.wd);
}
});
watches
}
fn match_device(device_name: Option<&String>) -> Result<Device, String> {
match device_name {
Some(s) => Device::new(Some(Cow::from(s))),
None => Device::new(None),
}
.map_err(|e| format!("Failed to get device({device_name:?}): {e}"))
}
pub fn register_callback(cb: Sender<f64>, device_name: Option<String>) -> Result<i32, String> {
get_backend_runtime_handle().block_on(async {
try_init_backlight();
let device = match_device(device_name.as_ref())?;
get_ctx().add_cb(cb, device)
})
}
pub fn unregister_callback(key: i32) {
get_backend_runtime_handle().block_on(async {
log::info!("unregister backlight callback for key({key})");
if is_bl_inited() {
get_ctx().remove_cb(key);
}
})
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/workspace/hypr.rs | crates/backend/src/workspace/hypr.rs | use std::{
collections::HashMap,
num::ParseIntError,
process,
str::FromStr,
sync::atomic::{AtomicBool, AtomicPtr},
};
use hyprland::{
data::{Monitor, Workspace},
event_listener::{self},
prelude::async_closure,
shared::{HyprData, HyprDataActive, WorkspaceType},
};
use crate::{runtime::get_backend_runtime_handle, workspace::WorkspaceData};
use super::{WorkspaceCB, WorkspaceCtx, WorkspaceHandler, ID};
fn sort_workspaces(v: Vec<Workspace>, m: Vec<Monitor>) -> HashMap<String, (Vec<Workspace>, i32)> {
let mut map = HashMap::new();
v.into_iter().for_each(|f| {
map.entry(f.monitor.clone())
.or_insert((vec![], 0))
.0
.push(f);
});
map.iter_mut().for_each(|(k, (v, active))| {
v.retain(|w| w.id > 0); // common workspaces id start from 1
v.sort_by_key(|w| w.id);
*active = m
.iter()
.find(|m| &m.name == k)
.map(|monitor| monitor.active_workspace.id)
.unwrap_or(-1);
});
map
}
fn workspace_vec_to_data(v: &[Workspace], focus_id: i32, active: i32) -> WorkspaceData {
// Count actual workspaces on this monitor, not assuming contiguous IDs
let min_id = v.first().map(|w| w.id).unwrap();
let max_id = v.last().map(|w| w.id).unwrap();
let workspace_count = max_id - min_id + 1;
let active = active - min_id;
let focus = if focus_id < min_id || focus_id > max_id {
-1
} else {
active
};
WorkspaceData {
workspace_count,
focus,
active,
}
}
fn get_workspace() -> Vec<Workspace> {
hyprland::data::Workspaces::get()
.unwrap()
.into_iter()
.collect()
}
fn get_monitors() -> Vec<Monitor> {
hyprland::data::Monitors::get()
.unwrap()
.into_iter()
.collect()
}
fn get_focus() -> i32 {
hyprland::data::Workspace::get_active().unwrap().id
}
fn get_focused_monitor() -> Option<String> {
hyprland::data::Monitors::get()
.ok()?
.into_iter()
.find(|m| m.focused)
.map(|m| m.name)
}
fn on_signal() {
let ctx = get_hypr_ctx();
let is_initial_sync = ctx.data.is_default();
ctx.data.map = sort_workspaces(get_workspace(), get_monitors());
ctx.data.focus = get_focus();
// Always try to update focused_monitor after fetching new data
ctx.data.focused_monitor = get_focused_monitor();
if is_initial_sync {
// Perform the unconditional sync only on the first population
ctx.workspace_ctx
.sync_all_widgets_unconditionally(|output, _conf_data| {
ctx.data.get_workspace_data(output)
});
}
// Regular call that respects focused_only
ctx.call();
}
fn on_monitor_focus_change(monitor_name: &str) {
let ctx = get_hypr_ctx();
ctx.data.focused_monitor = Some(monitor_name.to_string());
log::debug!("Monitor focus changed to: {}", monitor_name);
ctx.call();
}
static CTX_INITED: AtomicBool = AtomicBool::new(false);
static GLOBAL_HYPR_LISTENER_CTX: AtomicPtr<HyprCtx> = AtomicPtr::new(std::ptr::null_mut());
fn is_ctx_inited() -> bool {
CTX_INITED.load(std::sync::atomic::Ordering::Relaxed)
}
fn get_hypr_ctx() -> &'static mut HyprCtx {
unsafe {
GLOBAL_HYPR_LISTENER_CTX
.load(std::sync::atomic::Ordering::Relaxed)
.as_mut()
.unwrap()
}
}
#[derive(Debug)]
struct CacheData {
// workspace and active id
map: HashMap<String, (Vec<Workspace>, i32)>,
focus: i32,
// Track the currently focused monitor for focused_only feature
focused_monitor: Option<String>,
}
impl CacheData {
fn new() -> Self {
Self {
map: HashMap::new(),
focus: -1,
focused_monitor: None,
}
}
fn is_default(&self) -> bool {
self.map.is_empty() && self.focus == -1 && self.focused_monitor.is_none()
}
fn get_workspace_data(&self, output: &str) -> WorkspaceData {
let Some((wps, active)) = self.map.get(output) else {
return WorkspaceData::default();
};
workspace_vec_to_data(wps, self.focus, *active)
}
}
// TODO: Hyprland specific config
pub struct HyprConf;
struct HyprCtx {
workspace_ctx: WorkspaceCtx<HyprConf>,
data: CacheData,
}
impl HyprCtx {
fn new() -> Self {
Self {
workspace_ctx: WorkspaceCtx::new(),
data: CacheData::new(),
}
}
fn call(&mut self) {
self.workspace_ctx.call(|output, _, focused_only| {
if focused_only {
// Only send updates to the currently focused monitor
if let Some(ref focused_monitor) = self.data.focused_monitor {
if output != focused_monitor {
return None; // Skip non-focused monitors
}
} else {
return None; // No focused monitor known yet
}
}
Some(self.data.get_workspace_data(output))
});
}
fn add_cb(&mut self, cb: WorkspaceCB<HyprConf>) -> ID {
if !self.data.is_default() {
cb.sender
.send(self.data.get_workspace_data(&cb.output))
.unwrap_or_else(|e| log::error!("Error sending initial data in add_cb: {}", e));
}
self.workspace_ctx.add_cb(cb)
}
fn remove_cb(&mut self, id: ID) {
self.workspace_ctx.remove_cb(id);
}
}
trait WorkspaceIDToInt {
fn regular_to_i32(&self) -> Option<Result<i32, ParseIntError>>;
}
impl WorkspaceIDToInt for WorkspaceType {
fn regular_to_i32(&self) -> Option<Result<i32, ParseIntError>> {
match self {
WorkspaceType::Regular(id) => Some(i32::from_str(id)),
WorkspaceType::Special(_) => None,
}
}
}
fn init_hyprland_listener() {
if is_ctx_inited() {
return;
}
GLOBAL_HYPR_LISTENER_CTX.store(
Box::into_raw(Box::new(HyprCtx::new())),
std::sync::atomic::Ordering::Relaxed,
);
CTX_INITED.store(true, std::sync::atomic::Ordering::Relaxed);
let mut listener = event_listener::AsyncEventListener::new();
#[allow(deprecated)]
listener.add_workspace_changed_handler(async_closure!(move |data| {
let workspace_type = data.name;
log::debug!("received workspace change: {workspace_type}");
if let Some(id) = workspace_type.regular_to_i32() {
match id {
Ok(_) => {
on_signal();
}
Err(e) => {
log::error!("Fail to parse workspace id: {e}");
}
}
}
}));
#[allow(deprecated)]
listener.add_workspace_added_handler(async_closure!(move |data| {
let workspace_type = data.name;
log::debug!("received workspace add: {workspace_type}");
if let WorkspaceType::Regular(_) = workspace_type {
on_signal();
}
}));
#[allow(deprecated)]
listener.add_workspace_deleted_handler(async_closure!(move |e| {
log::debug!("received workspace destroy: {e:?}");
on_signal();
}));
#[allow(deprecated)]
listener.add_active_monitor_changed_handler(async_closure!(|e| {
log::debug!("received monitor change: {e:?}");
// Update focused monitor for focused_only feature
on_monitor_focus_change(&e.monitor_name);
if let Some(workspace_name) = e.workspace_name {
if let Some(id) = workspace_name.regular_to_i32() {
match id {
Ok(_) => {
on_signal();
}
Err(e) => log::error!("Fail to parse workspace id: {e}"),
}
}
}
}));
get_backend_runtime_handle().spawn(async move {
log::info!("hyprland workspace listener is running");
if let Err(e) = listener.start_listener_async().await {
log::error!("{e}");
process::exit(-1)
}
log::info!("hyprland workspace listener stopped");
});
get_backend_runtime_handle().spawn(async {
on_signal();
});
}
pub fn register_hypr_event_callback(cb: WorkspaceCB<HyprConf>) -> WorkspaceHandler {
init_hyprland_listener();
let cb_id = get_hypr_ctx().add_cb(cb);
WorkspaceHandler::Hyprland(HyprWorkspaceHandler { cb_id })
}
pub fn unregister_hypr_event_callback(id: ID) {
get_hypr_ctx().remove_cb(id)
}
#[derive(Debug)]
pub struct HyprWorkspaceHandler {
cb_id: ID,
}
impl Drop for HyprWorkspaceHandler {
fn drop(&mut self) {
unregister_hypr_event_callback(self.cb_id);
}
}
impl HyprWorkspaceHandler {
pub fn change_to_workspace(&mut self, index: usize) {
use hyprland::dispatch::*;
let ctx = get_hypr_ctx();
let Some(output) = ctx
.workspace_ctx
.cb
.get(&self.cb_id)
.map(|w| w.output.as_str())
else {
return;
};
log::debug!("change to workspace: {output} - {index}");
let Some(id) = ctx.data.map.get(output).and_then(|(v, _)| {
// Use the actual workspace ID at the given index
v.first().map(|w| w.id + index as i32)
}) else {
return;
};
// ignore
let _ = Dispatch::call(DispatchType::Workspace(WorkspaceIdentifierWithSpecial::Id(
id,
)));
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/workspace/mod.rs | crates/backend/src/workspace/mod.rs | use std::collections::HashMap;
use calloop::channel::Sender;
use hypr::HyprWorkspaceHandler;
use niri::NiriWorkspaceHandler;
pub mod hypr;
pub mod niri;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WorkspaceData {
/// workspace len, start from 1
pub workspace_count: i32,
/// index, start from 0
pub focus: i32,
/// index, start from 0
pub active: i32,
}
impl Default for WorkspaceData {
fn default() -> Self {
WorkspaceData {
workspace_count: 1,
focus: 0,
active: 0,
}
}
}
pub struct WorkspaceCB<T> {
pub sender: Sender<WorkspaceData>,
pub output: String,
pub data: T,
pub focused_only: bool,
}
type ID = u32;
struct WorkspaceCtx<T> {
id_cache: ID,
cb: HashMap<ID, WorkspaceCB<T>>,
}
impl<T> WorkspaceCtx<T> {
fn new() -> Self {
Self {
cb: HashMap::new(),
id_cache: 0,
}
}
fn add_cb(&mut self, cb: WorkspaceCB<T>) -> ID {
let id = self.id_cache;
self.cb.insert(id, cb);
self.id_cache += 1;
id
}
fn remove_cb(&mut self, id: ID) {
self.cb.remove(&id);
}
fn call(&mut self, mut data_func: impl FnMut(&str, &T, bool) -> Option<WorkspaceData>) {
self.cb.values().for_each(|f| {
if let Some(data) = data_func(&f.output, &f.data, f.focused_only) {
// one output should always have a active workspace
assert!(data.active >= -1);
// the focus and active workspace should always be the same
assert!(data.focus < 0 || (data.focus == data.active));
f.sender
.send(data)
.unwrap_or_else(|e| log::error!("Failed to send workspace data: {}", e));
}
})
}
fn sync_all_widgets_unconditionally(
&self,
mut data_func: impl FnMut(&str, &T) -> WorkspaceData,
) {
self.cb.values().for_each(|f| {
let data = data_func(&f.output, &f.data);
f.sender.send(data).unwrap_or_else(|e| {
log::error!("Error sending unconditional sync data: {}", e);
});
});
}
}
#[derive(Debug)]
pub enum WorkspaceHandler {
Hyprland(HyprWorkspaceHandler),
Niri(NiriWorkspaceHandler),
}
impl WorkspaceHandler {
pub fn change_to_workspace(&mut self, index: usize) {
match self {
WorkspaceHandler::Hyprland(h) => {
h.change_to_workspace(index);
}
WorkspaceHandler::Niri(h) => {
h.change_to_workspace(index);
}
}
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/workspace/niri/connection.rs | crates/backend/src/workspace/niri/connection.rs | use niri_ipc::{socket::SOCKET_PATH_ENV, Reply, Workspace};
use serde::Deserialize;
use tokio::{
io::{self, AsyncBufReadExt, AsyncWriteExt, BufReader},
net::UnixStream,
};
/// A compositor event.
#[derive(Deserialize, Debug, Clone)]
pub enum Event {
/// The workspace configuration has changed.
WorkspacesChanged {
/// The new workspace configuration.
///
/// This configuration completely replaces the previous configuration. I.e. if any
/// workspaces are missing from here, then they were deleted.
workspaces: Vec<Workspace>,
},
/// A workspace was activated on an output.
///
/// This doesn't always mean the workspace became focused, just that it's now the active
/// workspace on its output. All other workspaces on the same output become inactive.
WorkspaceActivated {
/// Id of the newly active workspace.
#[allow(dead_code)]
id: u64,
/// Whether this workspace also became focused.
///
/// If `true`, this is now the single focused workspace. All other workspaces are no longer
/// focused, but they may remain active on their respective outputs.
#[allow(dead_code)]
focused: bool,
},
}
pub struct Connection(UnixStream);
impl Connection {
pub async fn make_connection() -> io::Result<Connection> {
let socket_path = std::env::var_os(SOCKET_PATH_ENV).ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("{SOCKET_PATH_ENV} is not set, are you running this within niri?"),
)
})?;
let s = UnixStream::connect(socket_path).await?;
Ok(Self(s))
}
#[allow(clippy::wrong_self_convention)]
pub async fn to_listener(mut self) -> io::Result<Listener> {
self.push_request(niri_ipc::Request::EventStream)
.await?
.expect("Failed to open event stream");
let reader = BufReader::new(self.0);
Ok(Listener(reader))
}
pub async fn push_request(&mut self, req: niri_ipc::Request) -> io::Result<Reply> {
let mut buf = serde_jsonrc::to_string(&req).unwrap();
self.0.write_all(buf.as_bytes()).await?;
self.0.shutdown().await?;
buf.clear();
BufReader::new(&mut self.0).read_line(&mut buf).await?;
Ok(serde_jsonrc::from_str(buf.as_str()).unwrap())
}
}
pub struct Listener(BufReader<UnixStream>);
impl Listener {
pub async fn next_event(&mut self, buf: &mut String) -> io::Result<Option<Event>> {
self.0.read_line(buf).await.map(|_| {
log::debug!("Received niri event: {buf}");
serde_jsonrc::from_str(buf).ok()
})
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/workspace/niri/mod.rs | crates/backend/src/workspace/niri/mod.rs | mod connection;
use std::{
collections::HashMap,
sync::atomic::{AtomicBool, AtomicPtr},
};
use config::widgets::workspace::NiriConf;
use connection::{Connection, Event};
use tokio::io;
use crate::runtime::get_backend_runtime_handle;
use super::{WorkspaceCB, WorkspaceCtx, WorkspaceData, WorkspaceHandler, ID};
fn filter_empty_workspace(v: &[niri_ipc::Workspace]) -> Vec<&niri_ipc::Workspace> {
v.iter()
.filter(|w| w.is_focused || w.active_window_id.is_some())
.collect()
}
#[derive(Default)]
struct DataCache {
inner: HashMap<String, Vec<niri_ipc::Workspace>>,
focused_output: Option<String>,
}
impl DataCache {
fn new(map: HashMap<String, Vec<niri_ipc::Workspace>>) -> Self {
// Determine which output is focused by looking for the focused workspace
let focused_output = map.iter().find_map(|(output_name, workspaces)| {
if workspaces.iter().any(|w| w.is_focused) {
Some(output_name.clone())
} else {
None
}
});
Self {
inner: map,
focused_output,
}
}
fn is_default(&self) -> bool {
self.inner.is_empty() && self.focused_output.is_none()
}
fn get_workspace_data(&self, output: &str, filter_empty: bool) -> WorkspaceData {
let Some(wps) = self.inner.get(output) else {
return WorkspaceData::default();
};
let v = if filter_empty {
filter_empty_workspace(wps)
} else {
wps.iter().collect()
};
let focus = v
.iter()
.position(|w| w.is_focused)
.map(|i| i as i32)
.unwrap_or(-1);
let active = v
.iter()
.position(|w| w.is_active)
.map(|i| i as i32)
.unwrap_or(-1);
let workspace_count = v.len() as i32;
WorkspaceData {
workspace_count,
focus,
active,
}
}
fn get_workspace(
&self,
output: &str,
filter_empty: bool,
index: usize,
) -> Option<&niri_ipc::Workspace> {
let wps = self.inner.get(output)?;
let v = if filter_empty {
filter_empty_workspace(wps)
} else {
wps.iter().collect()
};
if v.len() > index {
Some(v[index])
} else {
None
}
}
}
fn sort_workspaces(v: Vec<niri_ipc::Workspace>) -> HashMap<String, Vec<niri_ipc::Workspace>> {
let mut a = HashMap::new();
v.into_iter().for_each(|mut f| {
let Some(o) = f.output.take() else {
return;
};
a.entry(o).or_insert(vec![]).push(f);
});
a.values_mut().for_each(|v| v.sort_by_key(|w| w.idx));
a
}
async fn process_event(e: Event) {
log::debug!("niri event: {e:?}");
let ctx = get_niri_ctx();
// NOTE: id start from 1
ctx.data = match e {
Event::WorkspaceActivated { id: _, focused: _ } => {
let data = get_workspaces().await.expect("Failed to get workspaces");
DataCache::new(sort_workspaces(data))
}
Event::WorkspacesChanged { workspaces } => DataCache::new(sort_workspaces(workspaces)),
};
ctx.call();
}
async fn get_workspaces() -> io::Result<Vec<niri_ipc::Workspace>> {
let mut l = Connection::make_connection()
.await
.expect("Failed to connect to niri socket");
let r = l
.push_request(niri_ipc::Request::Workspaces)
.await?
.expect("Failed to request workspaces");
match r {
niri_ipc::Response::Workspaces(vec) => Ok(vec),
_ => unreachable!(),
}
}
static CTX_INITED: AtomicBool = AtomicBool::new(false);
static GLOBAL_NIRI_LISTENER_CTX: AtomicPtr<NiriCtx> = AtomicPtr::new(std::ptr::null_mut());
fn is_ctx_inited() -> bool {
CTX_INITED.load(std::sync::atomic::Ordering::Relaxed)
}
fn get_niri_ctx() -> &'static mut NiriCtx {
unsafe {
GLOBAL_NIRI_LISTENER_CTX
.load(std::sync::atomic::Ordering::Relaxed)
.as_mut()
.unwrap()
}
}
struct NiriCtx {
workspace_ctx: WorkspaceCtx<NiriConf>,
data: DataCache,
}
impl NiriCtx {
fn new() -> Self {
Self {
workspace_ctx: WorkspaceCtx::new(),
data: DataCache::default(),
}
}
fn call(&mut self) {
self.workspace_ctx.call(|output, conf, focused_only| {
// If focused_only is enabled, only send updates to the focused monitor
if focused_only {
if let Some(ref focused_output) = self.data.focused_output {
if output != focused_output {
return None; // Skip this monitor
}
} else {
return None; // No focused monitor found, skip all
}
}
Some(self.data.get_workspace_data(output, conf.filter_empty))
});
}
fn add_cb(&mut self, cb: WorkspaceCB<NiriConf>) -> ID {
if !self.data.is_default() {
cb.sender
.send(
self.data
.get_workspace_data(&cb.output, cb.data.filter_empty),
)
.unwrap_or_else(|e| log::error!("Error sending initial data in add_cb: {e}"));
}
self.workspace_ctx.add_cb(cb)
}
fn remove_cb(&mut self, id: ID) {
self.workspace_ctx.remove_cb(id);
}
}
fn start_listener() {
if is_ctx_inited() {
return;
}
GLOBAL_NIRI_LISTENER_CTX.store(
Box::into_raw(Box::new(NiriCtx::new())),
std::sync::atomic::Ordering::Relaxed,
);
CTX_INITED.store(true, std::sync::atomic::Ordering::Relaxed);
get_backend_runtime_handle().spawn(async {
let wp = get_workspaces().await.expect("Failed to get workspaces");
let ctx = get_niri_ctx();
ctx.data = DataCache::new(sort_workspaces(wp));
// Perform the unconditional sync
ctx.workspace_ctx
.sync_all_widgets_unconditionally(|output, conf_data| {
ctx.data.get_workspace_data(output, conf_data.filter_empty)
});
// It's good practice to call the main update logic afterwards,
// which will respect focused_only for any subsequent updates.
ctx.call();
});
get_backend_runtime_handle().spawn(async {
let mut l = Connection::make_connection()
.await
.expect("Failed to connect to niri socket")
.to_listener()
.await
.expect("Failed to send EventStream request");
let mut buf = String::new();
loop {
match l.next_event(&mut buf).await {
Ok(Some(e)) => process_event(e).await,
Ok(None) => {}
Err(err) => {
log::error!("error reading from event stream: {err}");
break;
}
}
buf.clear();
}
log::error!("niri event stream closed")
});
}
pub fn register_niri_event_callback(cb: WorkspaceCB<NiriConf>) -> WorkspaceHandler {
start_listener();
let cb_id = get_niri_ctx().add_cb(cb);
WorkspaceHandler::Niri(NiriWorkspaceHandler { cb_id })
}
pub fn unregister_niri_event_callback(id: ID) {
get_niri_ctx().remove_cb(id)
}
#[derive(Debug)]
pub struct NiriWorkspaceHandler {
cb_id: ID,
}
impl Drop for NiriWorkspaceHandler {
fn drop(&mut self) {
unregister_niri_event_callback(self.cb_id);
}
}
impl NiriWorkspaceHandler {
pub fn change_to_workspace(&mut self, index: usize) {
let cb_id = self.cb_id;
get_backend_runtime_handle().spawn(async move {
let ctx = get_niri_ctx();
let Some((output, filter_empty)) = ctx
.workspace_ctx
.cb
.get(&cb_id)
.map(|w| (w.output.as_str(), w.data.filter_empty))
else {
return;
};
let Some(id) = ctx
.data
.get_workspace(output, filter_empty, index)
.map(|w| w.id)
else {
return;
};
connection::Connection::make_connection()
.await
.expect("Failed to connect to niri socket")
.push_request(niri_ipc::Request::Action(
niri_ipc::Action::FocusWorkspace {
reference: niri_ipc::WorkspaceReferenceArg::Id(id),
},
))
.await
.expect("Failed to request workspace change")
.expect("request error");
});
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/ipc/mod.rs | crates/backend/src/ipc/mod.rs | mod listen;
use std::{
io::Write,
os::unix::net::UnixStream,
path::{Path, PathBuf},
sync::OnceLock,
};
pub use listen::start_ipc;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
pub struct CommandBody {
#[serde(default)]
pub command: String,
#[serde(default)]
pub args: Vec<String>,
}
pub const IPC_COMMAND_RELOAD: &str = "reload";
pub const IPC_COMMAND_QUIT: &str = "q";
pub const IPC_COMMAND_TOGGLE_PIN: &str = "togglepin";
static SOCK_FILE: OnceLock<PathBuf> = OnceLock::new();
pub fn set_ipc_namespace(namespace: Option<&str>) {
SOCK_FILE
.set(
xdg::BaseDirectories::new()
.place_runtime_file(format!("way-edges{}.sock", namespace.unwrap_or_default()))
.unwrap(),
)
.unwrap();
}
fn get_ipc_sock() -> &'static Path {
SOCK_FILE.get().expect("IPC socket file not set")
}
pub fn send_command(cmd: CommandBody) {
let data = serde_jsonrc::to_string(&cmd).unwrap();
let mut socket = UnixStream::connect(get_ipc_sock()).unwrap();
socket.write_all(data.as_bytes()).unwrap();
}
#[derive(Debug)]
pub enum IPCCommand {
TogglePin(String),
Reload,
Exit,
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/ipc/listen.rs | crates/backend/src/ipc/listen.rs | use crate::ipc::{get_ipc_sock, IPC_COMMAND_RELOAD};
use crate::runtime::get_backend_runtime_handle;
use super::{CommandBody, IPCCommand};
use super::{IPC_COMMAND_QUIT, IPC_COMMAND_TOGGLE_PIN};
use std::path::Path;
use calloop::channel::Sender;
use tokio::net::UnixStream;
pub fn start_ipc(sender: Sender<IPCCommand>) {
get_backend_runtime_handle().spawn(async {
let listener = {
let path = Path::new(get_ipc_sock());
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let _ = std::fs::remove_file(path);
tokio::net::UnixListener::bind(path).unwrap()
};
tokio::spawn(async move {
loop {
match listener.accept().await {
Ok((stream, _)) => {
deal_stream_in_background(stream, sender.clone());
}
Err(e) => {
log::error!("Fail to connect socket: {e}");
break;
}
}
}
});
});
}
fn deal_stream_in_background(stream: UnixStream, sender: Sender<IPCCommand>) {
tokio::spawn(async move {
let raw = stream_read_all(&stream).await?;
log::debug!("recv ipc msg: {raw}");
let command_body =
serde_jsonrc::from_str::<CommandBody>(&raw).map_err(|e| e.to_string())?;
let ipc = match command_body.command.as_str() {
IPC_COMMAND_TOGGLE_PIN => {
IPCCommand::TogglePin(command_body.args.first().ok_or("No widget name")?.clone())
}
IPC_COMMAND_QUIT => IPCCommand::Exit,
IPC_COMMAND_RELOAD => IPCCommand::Reload,
_ => return Err("unknown command".to_string()),
};
log::info!("Receive ipc message: {ipc:?}");
sender
.send(ipc)
.map_err(|_| "ipc channel closed".to_string())?;
Ok(())
});
}
async fn stream_read_all(stream: &UnixStream) -> Result<String, String> {
let mut buf_array = vec![];
let a = loop {
// Wait for the socket to be readable
if stream.readable().await.is_err() {
return Err("stream not readable".to_string());
}
// Creating the buffer **after** the `await` prevents it from
// being stored in the async task.
let mut buf = [0; 4096];
// Try to read data, this may still fail with `WouldBlock`
// if the readiness event is a false positive.
match stream.try_read(&mut buf) {
Ok(0) => break String::from_utf8_lossy(&buf_array),
Ok(n) => {
buf_array.extend_from_slice(&buf[..n]);
}
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
continue;
}
Err(e) => {
return Err(format!("Can not read command: {e}"));
}
}
};
Ok(a.to_string())
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/pulseaudio/change.rs | crates/backend/src/pulseaudio/change.rs | use libpulse_binding::{
context::Context,
volume::{ChannelVolumes, Volume},
};
use crate::runtime::get_backend_runtime_handle;
use super::{
get_pa,
pa::{self, with_context},
PulseAudioDevice,
};
pub fn get_default_sink() -> Option<&'static String> {
get_pa().default_sink.as_ref()
}
pub fn get_default_source() -> Option<&'static String> {
get_pa().default_source.as_ref()
}
fn calculate_volumn(channel_volumns: &mut ChannelVolumes, vol_percentage: f64) {
let cv_len = channel_volumns.len();
let v = Volume((vol_percentage * (Volume::NORMAL.0 as f64)) as u32);
channel_volumns.set(cv_len, v);
}
fn change_sink_vol(ctx: &Context, name: &str, vol_percentage: f64) {
ctx.introspect().get_sink_info_by_name(name, move |list| {
if let Some(sink_info) = pa::drain_list(list) {
let index = sink_info.index;
let mut channel_volumns = sink_info.volume;
calculate_volumn(&mut channel_volumns, vol_percentage);
with_context(move |ctx| {
ctx.introspect()
.set_sink_volume_by_index(index, &channel_volumns, None)
});
};
});
}
fn change_source_vol(ctx: &Context, name: &str, vol_percentage: f64) {
ctx.introspect().get_source_info_by_name(name, move |list| {
if let Some(source_info) = pa::drain_list(list) {
let index = source_info.index;
let mut channel_volumns = source_info.volume;
calculate_volumn(&mut channel_volumns, vol_percentage);
with_context(move |ctx| {
ctx.introspect()
.set_source_volume_by_index(index, &channel_volumns, None)
});
};
});
}
pub fn set_vol(os: PulseAudioDevice, v: f64, debounce_ctx: std::sync::Weak<()>) {
get_backend_runtime_handle().spawn(async move {
// debounce 1ms
tokio::time::sleep(std::time::Duration::from_millis(1)).await;
if debounce_ctx.upgrade().is_none() {
return;
}
pa::with_context(|ctx| match os {
PulseAudioDevice::DefaultSink => {
if let Some(name) = get_default_sink() {
change_sink_vol(ctx, name, v);
};
}
PulseAudioDevice::DefaultSource => {
if let Some(name) = get_default_source() {
change_source_vol(ctx, name, v);
};
}
PulseAudioDevice::NamedSink(name) => {
change_sink_vol(ctx, &name, v);
}
PulseAudioDevice::NamedSource(name) => {
change_source_vol(ctx, &name, v);
}
})
});
}
pub fn set_mute(os: PulseAudioDevice, mute: bool) {
get_backend_runtime_handle().spawn_blocking(move || {
pa::with_context(move |ctx| {
let mut ins = ctx.introspect();
match os {
PulseAudioDevice::DefaultSink => {
if let Some(name) = get_default_sink() {
ins.set_sink_mute_by_name(name, mute, None);
};
}
PulseAudioDevice::DefaultSource => {
if let Some(name) = get_default_source() {
ins.set_source_mute_by_name(name, mute, None);
};
}
PulseAudioDevice::NamedSink(name) => {
ins.set_sink_mute_by_name(&name, mute, None);
}
PulseAudioDevice::NamedSource(name) => {
ins.set_source_mute_by_name(&name, mute, None);
}
}
})
});
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/pulseaudio/mod.rs | crates/backend/src/pulseaudio/mod.rs | pub mod change;
mod pa;
use std::{
collections::{HashMap, HashSet},
sync::atomic::{AtomicBool, AtomicPtr, Ordering},
};
use calloop::channel::Sender;
pub use pa::PulseAudioDevice;
pub use pa::VInfo;
use crate::runtime::get_backend_runtime_handle;
#[derive(Default)]
struct VInfoMap(HashMap<String, VInfo>);
impl VInfoMap {
fn get_by_name(&self, n: &str) -> Option<VInfo> {
let a = self.0.get(n).cloned();
a
}
fn set_by_name(&mut self, n: String, v: VInfo) {
self.0.insert(n, v);
}
}
type CallbackID = i32;
struct PA {
count: i32,
cbs: HashMap<CallbackID, Sender<VInfo>>,
device_map: HashMap<PulseAudioDevice, HashSet<CallbackID>>,
sink_vinfo_map: VInfoMap,
source_vinfo_map: VInfoMap,
default_sink: Option<String>,
default_source: Option<String>,
}
impl PA {
fn new() -> Self {
PA {
count: 0,
cbs: HashMap::new(),
device_map: HashMap::new(),
sink_vinfo_map: VInfoMap::default(),
source_vinfo_map: VInfoMap::default(),
default_sink: None,
default_source: None,
}
}
fn call_device(&mut self, device: &PulseAudioDevice, vinfo: VInfo) {
if let Some(ids) = self.device_map.get(device) {
ids.iter().for_each(|id| {
let cb = self.cbs.get(id).unwrap();
cb.send(vinfo).unwrap();
})
}
}
fn call(&mut self, device: PulseAudioDevice, vinfo: VInfo) {
match &device {
PulseAudioDevice::NamedSink(name) => {
if self.default_sink.as_ref().is_some_and(|dt| dt == name) {
self.call_device(&PulseAudioDevice::DefaultSink, vinfo);
}
self.sink_vinfo_map.set_by_name(name.clone(), vinfo);
}
PulseAudioDevice::NamedSource(name) => {
if self.default_source.as_ref().is_some_and(|dt| dt == name) {
self.call_device(&PulseAudioDevice::DefaultSource, vinfo);
}
self.source_vinfo_map.set_by_name(name.clone(), vinfo);
}
_ => unreachable!(),
}
self.call_device(&device, vinfo);
}
fn add_cb(&mut self, cb: Sender<VInfo>, device: PulseAudioDevice) -> i32 {
let key = self.count;
self.count += 1;
match &device {
PulseAudioDevice::DefaultSink => self
.default_sink
.as_ref()
.and_then(|name| self.sink_vinfo_map.get_by_name(name)),
PulseAudioDevice::DefaultSource => self
.default_source
.as_ref()
.and_then(|name| self.source_vinfo_map.get_by_name(name)),
PulseAudioDevice::NamedSink(name) => self.sink_vinfo_map.get_by_name(name),
PulseAudioDevice::NamedSource(name) => self.source_vinfo_map.get_by_name(name),
}
.map(|vinfo| cb.send(vinfo));
self.cbs.insert(key, cb);
self.device_map.entry(device).or_default().insert(key);
key
}
fn remove_cb(&mut self, key: i32) {
self.cbs.remove_entry(&key);
}
}
static IS_PA_INITIALIZED: AtomicBool = AtomicBool::new(false);
static GLOBAL_PA: AtomicPtr<PA> = AtomicPtr::new(std::ptr::null_mut());
fn init_pa() {
IS_PA_INITIALIZED.store(true, Ordering::Release);
GLOBAL_PA.store(Box::into_raw(Box::new(PA::new())), Ordering::Release);
}
fn is_pa_inited() -> bool {
IS_PA_INITIALIZED.load(Ordering::Acquire)
}
fn get_pa() -> &'static mut PA {
unsafe { GLOBAL_PA.load(Ordering::Acquire).as_mut().unwrap() }
}
pub fn try_init_pulseaudio() -> Result<(), String> {
if !is_pa_inited() {
init_pa();
pa::init_pulseaudio_subscriber();
}
Ok(())
}
pub fn register_callback(cb: Sender<VInfo>, device: PulseAudioDevice) -> Result<i32, String> {
get_backend_runtime_handle().block_on(async move {
try_init_pulseaudio()?;
Ok(get_pa().add_cb(cb, device))
})
}
pub fn unregister_callback(key: i32) {
get_backend_runtime_handle().block_on(async move {
if is_pa_inited() {
get_pa().remove_cb(key);
}
})
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/backend/src/pulseaudio/pa.rs | crates/backend/src/pulseaudio/pa.rs | use std::sync::atomic::{AtomicPtr, Ordering};
use libpulse_binding::{
self as pulse,
callbacks::ListResult,
context::{
introspect::{ServerInfo, SinkInfo, SourceInfo},
subscribe::{Facility, InterestMaskSet, Operation},
Context, FlagSet,
},
volume::{ChannelVolumes, Volume},
};
fn get_avg_volume(cv: ChannelVolumes) -> f64 {
cv.avg().0 as f64 / Volume::NORMAL.0 as f64
}
fn set_default_sink(s: String) {
get_pa().default_sink.replace(s);
}
fn set_default_source(s: String) {
get_pa().default_source.replace(s);
}
#[derive(Debug, Hash, PartialEq, Eq, Clone)]
pub enum PulseAudioDevice {
DefaultSink,
DefaultSource,
NamedSink(String),
NamedSource(String),
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct VInfo {
pub vol: f64,
pub is_muted: bool,
}
static CONTEXT: AtomicPtr<Context> = AtomicPtr::new(std::ptr::null_mut());
pub fn with_context<T>(f: impl FnOnce(&mut Context) -> T) -> T {
let a = unsafe { CONTEXT.load(Ordering::Acquire).as_mut().unwrap() };
f(a)
}
pub fn drain_list<'a, T: 'a>(ls: ListResult<&'a T>) -> Option<&'a T> {
match ls {
pulse::callbacks::ListResult::Item(res) => {
return Some(res);
}
pulse::callbacks::ListResult::End => {}
pulse::callbacks::ListResult::Error => {
log::error!("Error getting list result info");
}
};
None
}
use libpulse_tokio::TokioMain;
use crate::runtime::get_backend_runtime;
use super::get_pa;
fn signal_callback_group(msg: PulseAudioDevice, vinfo: VInfo) {
// NOTE: WE USE LIBPULSE WITH GLIB BINDING
// SO NO NEED TO WORRY ABOUT SEND OR SYNC
get_pa().call(msg, vinfo);
}
pub fn sink_cb(list_result: ListResult<&SinkInfo>) {
if let Some(sink_info) = drain_list(list_result) {
let avg = get_avg_volume(sink_info.volume);
let desc = sink_info.name.clone().unwrap().to_string();
signal_callback_group(
PulseAudioDevice::NamedSink(desc),
VInfo {
vol: avg,
is_muted: sink_info.mute,
},
)
};
}
pub fn source_cb(list_result: ListResult<&SourceInfo>) {
if let Some(source_info) = drain_list(list_result) {
let avg = get_avg_volume(source_info.volume);
let desc = source_info.name.clone().unwrap().to_string();
signal_callback_group(
PulseAudioDevice::NamedSource(desc),
VInfo {
vol: avg,
is_muted: source_info.mute,
},
);
};
}
fn server_cb(server_info: &ServerInfo) {
if let Some(name) = &server_info.default_sink_name {
set_default_sink(name.to_string());
with_context(|ctx| {
ctx.introspect().get_sink_info_by_name(name, sink_cb);
});
}
if let Some(name) = &server_info.default_source_name {
set_default_source(name.to_string());
with_context(|ctx| {
ctx.introspect().get_source_info_by_name(name, source_cb);
});
};
}
pub fn subscribe_cb(facility: Option<Facility>, _: Option<Operation>, index: u32) {
let facility = if let Some(facility) = facility {
facility
} else {
return;
};
with_context(|ctx| {
let ins = ctx.introspect();
match facility {
Facility::Sink => {
ins.get_sink_info_by_index(index, sink_cb);
}
Facility::Source => {
ins.get_source_info_by_index(index, source_cb);
}
Facility::Server => {
ins.get_server_info(server_cb);
}
_ => {}
};
});
}
fn setup_subscribe(ctx: &mut Context) {
ctx.subscribe(
InterestMaskSet::SINK | InterestMaskSet::SOURCE | InterestMaskSet::SERVER,
move |s| {
if !s {
log::warn!("Fail to subscribe pulseaudio");
}
},
);
ctx.set_subscribe_callback(Some(Box::new(subscribe_cb)));
}
fn get_initial_data(ctx: &mut Context) {
let ins = ctx.introspect();
ins.get_server_info(server_cb);
ins.get_sink_info_list(sink_cb);
ins.get_source_info_list(source_cb);
}
fn with_pulse_audio_connected(ctx: &mut Context) {
log::debug!("start subscribe pulseaudio sink and source");
setup_subscribe(ctx);
get_initial_data(ctx);
}
fn init_mainloop_and_context() -> (TokioMain, &'static mut Context) {
let m = libpulse_tokio::TokioMain::new();
let c = Context::new(&m, "Volume Monitor").expect("Failed to create context");
CONTEXT.store(Box::into_raw(Box::new(c)), Ordering::Release);
(m, unsafe {
CONTEXT.load(Ordering::Acquire).as_mut().unwrap()
})
}
pub fn init_pulseaudio_subscriber() {
get_backend_runtime().spawn_local(async {
let (mut m, ctx) = init_mainloop_and_context();
ctx.connect(None, FlagSet::NOFAIL, None)
.map_err(|e| format!("Failed to connect context: {e}"))
.unwrap();
match m.wait_for_ready(ctx).await {
Ok(pulse::context::State::Ready) => {}
Ok(c) => {
log::error!("Pulse context {:?}, not continuing", c);
}
Err(_) => {
log::error!("Pulse mainloop exited while waiting on context, not continuing");
}
}
with_pulse_audio_connected(ctx);
let res = m.run().await;
log::error!("Pulse mainloop exited with retval: {res:?}");
});
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/way-edges-derive/src/lib.rs | crates/way-edges-derive/src/lib.rs | use proc_macro::{self, TokenStream};
use quote::{format_ident, quote};
use syn::{
parse_macro_input, punctuated::Punctuated, DeriveInput, LitStr, Meta, MetaNameValue, Token,
};
#[proc_macro_derive(GetSize)]
pub fn derive_size(input: TokenStream) -> TokenStream {
let a: DeriveInput = syn::parse(input).unwrap();
let struct_name = a.ident;
quote! {
impl #struct_name {
pub fn size(&self) -> Result<(f64, f64), String> {
Ok((self.size.thickness.get_num()?, self.size.length.get_num()?))
}
}
}
.into()
}
#[proc_macro_attribute]
pub fn wrap_rc(attr: TokenStream, item: TokenStream) -> TokenStream {
let args = parse_macro_input!(attr with Punctuated<Meta, Token![,]>::parse_terminated);
let a: DeriveInput = syn::parse(item.clone()).unwrap();
let normal_name = a.ident;
fn str_from_meta_name_value(nv: MetaNameValue) -> Option<proc_macro2::TokenStream> {
if let syn::Expr::Lit(expr_lit) = nv.value {
if let syn::Lit::Str(str) = &expr_lit.lit {
return Some(str.value().parse().unwrap());
}
}
None
}
let mut rc = None;
let mut normal = None;
for m in args.into_iter() {
if let Meta::NameValue(meta_name_value) = m {
let is = |s| meta_name_value.path.is_ident(s);
if is("rc") {
rc = str_from_meta_name_value(meta_name_value);
} else if is("normal") {
normal = str_from_meta_name_value(meta_name_value);
};
}
}
let pub_rc = rc;
let pub_normal = normal;
let rc_name = syn::Ident::new(&format!("{}Rc", normal_name), normal_name.span());
let rc_weak_name = syn::Ident::new(&format!("{}RcWeak", normal_name), normal_name.span());
let item = proc_macro2::TokenStream::from(item);
quote! {
#item
impl #normal_name {
#pub_normal fn make_rc(self) -> #rc_name {
#rc_name::new(self)
}
}
#[derive(Debug, Clone)]
#pub_rc struct #rc_name(std::rc::Rc<std::cell::RefCell<#normal_name>>);
impl #rc_name {
#pub_rc fn new(normal: #normal_name) -> Self {
use std::cell::RefCell;
use std::rc::Rc;
Self(Rc::new(RefCell::new(normal)))
}
}
impl std::ops::Deref for #rc_name {
type Target = std::cell::RefCell<#normal_name>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Debug, Clone)]
#pub_rc struct #rc_weak_name(std::rc::Weak<std::cell::RefCell<#normal_name>>);
impl #rc_weak_name {
#pub_rc fn upgrade(&self) -> Option<#rc_name> {
std::rc::Weak::upgrade(&self.0).map(#rc_name)
}
}
impl #rc_name {
#pub_rc fn downgrade(&self) -> #rc_weak_name {
#rc_weak_name(std::rc::Rc::downgrade(&self.0))
}
}
}
.into()
}
use syn::{
parse::{Parse, ParseStream},
Attribute,
};
struct PropertyPair {
name: LitStr,
value: LitStr,
}
impl Parse for PropertyPair {
fn parse(input: ParseStream) -> syn::Result<Self> {
let name: LitStr = input.parse()?;
input.parse::<Token![,]>()?;
let value: LitStr = input.parse()?;
Ok(PropertyPair { name, value })
}
}
/// Parse the attributes to find the const_property attributes
fn extract_const_properties(attrs: &[Attribute]) -> Vec<PropertyPair> {
let mut properties = Vec::new();
for attr in attrs {
if attr.path().is_ident("const_property") {
if let Ok(meta) = attr.parse_args::<PropertyPair>() {
properties.push(meta);
}
}
}
properties
}
#[proc_macro_attribute]
pub fn const_property(args: TokenStream, input: TokenStream) -> TokenStream {
let args = parse_macro_input!(args as PropertyPair);
let mut input_ast = parse_macro_input!(input as DeriveInput);
let struct_name = &input_ast.ident;
let property_name = &args.name;
let property_value = &args.value;
// Generate the function name for the schema transformation
let function_name = format_ident!("{}_generate_defs", struct_name);
// Add the schemars transform attribute to the struct
let schemars_path: syn::Path = syn::parse_str("schemars").unwrap();
let transform_meta = syn::parse_quote! {
#schemars_path(transform = #function_name)
};
// Add the schemars attribute
input_ast.attrs.insert(
0,
syn::Attribute {
pound_token: syn::token::Pound::default(),
style: syn::AttrStyle::Outer,
bracket_token: syn::token::Bracket::default(),
meta: transform_meta,
},
);
// Create the output with the transformed struct and the schema function
let output = quote! {
#input_ast
#[allow(non_snake_case)]
fn #function_name(schema: &mut Schema) {
let root = schema.ensure_object();
match root.get_mut("properties") {
Some(Value::Object(map)) => map,
_ => return,
}
.insert(
#property_name.to_string(),
Value::Object(serde_json::Map::from_iter(
vec![("const".to_string(), Value::String(#property_value.to_string()))].into_iter(),
)),
);
}
};
output.into()
}
#[proc_macro_derive(ConstProperties, attributes(const_property))]
pub fn derive_const_properties(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let struct_name = &input.ident;
let properties = extract_const_properties(&input.attrs);
if properties.is_empty() {
return quote! {
#input
}
.into();
}
// Generate the function name for the schema transformation
let function_name = format_ident!("{}_generate_defs", struct_name);
// Generate property insertions
let property_insertions = properties.iter().map(|prop| {
let name = &prop.name;
let value = &prop.value;
quote! {
.insert(
#name.to_string(),
Value::Object(serde_json::Map::from_iter(
vec![("const".to_string(), Value::String(#value.to_string()))].into_iter(),
)),
)
}
});
// Create the output with the transformed struct and the schema function
let output = quote! {
#[schemars(transform = #function_name)]
#input
#[allow(non_snake_case)]
fn #function_name(schema: &mut Schema) {
let root = schema.ensure_object();
let props = match root.get_mut("properties") {
Some(Value::Object(map)) => map,
_ => return,
};
#(props #property_insertions;)*
}
};
output.into()
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/mouse_state.rs | crates/frontend/src/mouse_state.rs | use smithay_client_toolkit::seat::pointer::{AxisScroll, PointerEvent, PointerEventKind};
#[derive(Debug, Clone)]
pub enum MouseEvent {
Press((f64, f64), u32),
Release((f64, f64), u32),
Enter((f64, f64)),
Leave,
Motion((f64, f64)),
Scroll(AxisScroll, AxisScroll), // horizontal, vertical
}
#[derive(Debug)]
pub struct MouseStateData {
pub hovering: bool,
pub pressing: Option<u32>,
}
impl MouseStateData {
pub fn new() -> Self {
Self {
hovering: false,
pressing: None,
}
}
}
impl Default for MouseStateData {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug)]
pub struct MouseState {
pub data: MouseStateData,
mouse_debug: bool,
}
impl MouseState {
pub fn is_hovering(&self) -> bool {
self.data.hovering
}
}
impl MouseState {
pub fn new() -> Self {
Self {
data: MouseStateData::new(),
mouse_debug: false,
}
}
#[allow(clippy::wrong_self_convention)]
pub fn from_wl_pointer(&mut self, event: &PointerEvent) -> Option<MouseEvent> {
use PointerEventKind::*;
match event.kind {
Enter { .. } => self.hover_enter(event.position),
Leave { .. } => self.hover_leave(),
Motion { .. } => self.hover_motion(event.position),
Press { button, .. } => self.press(button, event.position),
Release { button, .. } => self.unpress(button, event.position),
Axis {
horizontal,
vertical,
..
} => Some(MouseEvent::Scroll(horizontal, vertical)),
}
}
// triggers
fn press(&mut self, p: u32, pos: (f64, f64)) -> Option<MouseEvent> {
if self.mouse_debug {
log::debug!("Mouse Debug info: key pressed: {p}");
};
if self.data.pressing.is_none() {
self.data.pressing = Some(p);
Some(MouseEvent::Press(pos, p))
} else {
None
}
}
fn unpress(&mut self, p: u32, pos: (f64, f64)) -> Option<MouseEvent> {
if self.mouse_debug {
log::debug!("Mouse Debug info: key released: {p}");
};
if self.data.pressing.eq(&Some(p)) {
self.data.pressing = None;
Some(MouseEvent::Release(pos, p))
} else {
None
}
}
fn hover_enter(&mut self, pos: (f64, f64)) -> Option<MouseEvent> {
self.data.hovering = true;
Some(MouseEvent::Enter(pos))
}
fn hover_motion(&mut self, pos: (f64, f64)) -> Option<MouseEvent> {
Some(MouseEvent::Motion(pos))
}
fn hover_leave(&mut self) -> Option<MouseEvent> {
self.data.hovering = false;
Some(MouseEvent::Leave)
}
}
impl Default for MouseState {
fn default() -> Self {
Self::new()
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/lib.rs | crates/frontend/src/lib.rs | mod animation;
mod buffer;
// mod frame;
mod mouse_state;
pub mod widgets;
// pub mod window;
mod wayland;
pub use wayland::mainloop::run_app;
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/buffer.rs | crates/frontend/src/buffer.rs | use cairo::ImageSurface;
use util::draw::new_surface;
#[derive(Clone, Debug, Default)]
pub struct Buffer(Option<ImageSurface>);
impl Buffer {
pub fn update_buffer(&mut self, new: ImageSurface) {
self.0.replace(new);
}
pub fn get_buffer(&self) -> ImageSurface {
self.0.clone().unwrap_or(new_surface((0, 0)))
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/mod.rs | crates/frontend/src/widgets/mod.rs | use cairo::ImageSurface;
use crate::{
mouse_state::{MouseEvent, MouseStateData},
wayland::app::WidgetBuilder,
};
mod button;
mod slide;
mod workspace;
mod wrapbox;
pub trait WidgetContext: std::fmt::Debug {
fn redraw(&mut self) -> ImageSurface;
fn on_mouse_event(&mut self, data: &MouseStateData, event: MouseEvent) -> bool;
}
pub fn init_widget(
conf: config::WidgetConfig,
builder: &mut WidgetBuilder,
) -> Box<dyn WidgetContext> {
let monitor = builder.app.output_state.info(&builder.output).unwrap();
let size = monitor.modes[0].dimensions;
match conf {
config::widgets::WidgetConfig::Btn(btn_config) => {
log::debug!("initializing button");
let w = button::init_widget(builder, size, btn_config);
log::info!("initialized button");
Box::new(w)
}
config::widgets::WidgetConfig::Slider(slide_config) => {
log::debug!("initializing slider");
let w = slide::init_widget(builder, size, slide_config);
log::info!("initialized slider");
w
}
config::widgets::WidgetConfig::Workspace(workspace_config) => {
log::debug!("initializing workspace");
let w = workspace::init_widget(builder, size, workspace_config, &monitor);
log::info!("initialized workspace");
Box::new(w)
}
config::widgets::WidgetConfig::WrapBox(box_config) => {
log::debug!("initializing box");
let w = wrapbox::init_widget(builder, box_config);
log::info!("initialized box");
Box::new(w)
}
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/workspace/event.rs | crates/frontend/src/widgets/workspace/event.rs | use smithay_client_toolkit::shell::wlr_layer::Anchor;
use util::binary_search_within_range;
use way_edges_derive::wrap_rc;
type ItemLocation = Vec<[f64; 2]>;
type MatchItemFunc = fn(&ItemLocation, (f64, f64)) -> isize;
fn make_hover_match_func(edge: Anchor) -> MatchItemFunc {
macro_rules! create_func {
($name:ident, $i:tt) => {
fn $name(item_location: &ItemLocation, mouse_pos: (f64, f64)) -> isize {
binary_search_within_range(item_location, mouse_pos.$i)
}
};
}
create_func!(h, 0);
create_func!(v, 1);
match edge {
Anchor::TOP | Anchor::BOTTOM => h,
Anchor::LEFT | Anchor::RIGHT => v,
_ => unreachable!(),
}
}
#[wrap_rc(rc = "pub(super)", normal = "pub(super)")]
#[derive(Debug)]
pub struct HoverData {
// [[0, 2], [4, 9]]
// 2 5
item_location: Vec<[f64; 2]>,
match_item_func: MatchItemFunc,
invert_direction: bool,
pub hover_id: isize,
}
impl HoverData {
pub fn new(edge: Anchor, invert_direction: bool) -> Self {
Self {
item_location: vec![],
match_item_func: make_hover_match_func(edge),
hover_id: -1,
invert_direction,
}
}
pub fn update_hover_data(&mut self, item_location: Vec<[f64; 2]>) {
self.item_location = item_location;
}
pub fn match_hover_id(&self, mouse_pos: (f64, f64)) -> isize {
let id = (self.match_item_func)(&self.item_location, mouse_pos);
if id < 0 {
id
} else {
// to match workspace id
if self.invert_direction {
self.item_location.len() as isize - 1 - id
} else {
id
}
}
}
pub fn update_hover_id_with_mouse_position(&mut self, mouse_pos: (f64, f64)) -> isize {
self.hover_id = self.match_hover_id(mouse_pos);
self.hover_id
}
pub fn force_update_hover_id(&mut self, id: isize) {
self.hover_id = id
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/workspace/draw.rs | crates/frontend/src/widgets/workspace/draw.rs | use cairo::{Context, ImageSurface};
use backend::workspace::WorkspaceData;
use config::widgets::workspace::WorkspaceConfig;
use cosmic_text::Color;
use smithay_client_toolkit::shell::wlr_layer::Anchor;
use util::{
color::{cairo_set_color, color_mix, color_transition},
draw::{draw_rect_path, new_surface},
Z,
};
use crate::animation::ToggleAnimationRc;
use super::event::HoverData;
#[derive(Debug)]
pub struct DrawConf {
thickness: i32,
length: i32,
gap: i32,
active_increase: f64,
border_width: f64,
border_radius: f64,
pub default_color: Color,
pub focus_color: Color,
pub active_color: Color,
pub hover_color: Option<Color>,
workspace_transition: ToggleAnimationRc,
invert_direction: bool,
func: fn(&DrawConf, WorkspaceData, WorkspaceData, &mut HoverData) -> ImageSurface,
}
impl DrawConf {
pub fn new(
w_conf: &WorkspaceConfig,
workspace_transition: ToggleAnimationRc,
edge: Anchor,
) -> Self {
let (thickness, length) = w_conf.size().unwrap();
let func = match edge {
Anchor::LEFT | Anchor::RIGHT => draw_vertical,
Anchor::TOP | Anchor::BOTTOM => draw_horizontal,
_ => unreachable!(),
};
Self {
thickness: thickness.ceil() as i32,
length: length.ceil() as i32,
gap: w_conf.gap,
active_increase: w_conf.active_increase,
default_color: w_conf.default_color,
focus_color: w_conf.focus_color,
active_color: w_conf.active_color,
hover_color: w_conf.hover_color,
invert_direction: w_conf.invert_direction,
workspace_transition,
func,
border_width: w_conf
.border_width
.map(|w| w as f64)
.unwrap_or(thickness.ceil() / 10.),
border_radius: w_conf.border_radius as f64,
}
}
pub fn draw(
&self,
data: WorkspaceData,
prev_data: WorkspaceData,
hover_data: &mut HoverData,
) -> ImageSurface {
(self.func)(self, data, prev_data, hover_data)
}
}
fn draw_common_horizontal(
conf: &DrawConf,
data: WorkspaceData,
prev_data: WorkspaceData,
hover_data: &mut HoverData,
) -> ImageSurface {
let item_base_length = {
let up = (conf.length - conf.gap * (data.workspace_count - 1)) as f64;
up / data.workspace_count as f64
};
let item_changable_length = item_base_length * conf.active_increase;
let item_max_length = item_base_length + item_changable_length;
let item_min_length =
item_base_length - item_changable_length / (data.workspace_count - 1).max(1) as f64;
let surf = new_surface((conf.length, conf.thickness));
let ctx = Context::new(&surf).unwrap();
let y = conf.workspace_transition.borrow().progress_abs();
let mut item_location = vec![];
let mut draw_start_pos = 0.;
let hover_id = hover_data.hover_id;
macro_rules! get_target {
($d:expr, $c:expr) => {
if $d.focus > -1 {
($d.focus, $c.focus_color)
} else {
($d.active, $c.active_color)
}
};
}
let (target, target_color) = get_target!(data, conf);
let (prev_target, _) = get_target!(prev_data, conf);
let default_color = conf.default_color;
let sorting: Box<dyn std::iter::Iterator<Item = _>> = if conf.invert_direction {
Box::new((0..data.workspace_count).rev())
} else {
Box::new(0..data.workspace_count)
};
sorting.enumerate().for_each(|(index, workspace_index)| {
// size and color
let (length, mut color) = if workspace_index == target {
(
item_min_length + (item_max_length - item_min_length) * y,
color_transition(default_color, target_color, y as f32),
)
} else if workspace_index == prev_target {
(
item_min_length + (item_max_length - item_min_length) * (1. - y),
color_transition(target_color, default_color, y as f32),
)
} else {
(item_min_length, default_color)
};
// mouse hover color
if let Some(hover_color) = conf.hover_color {
if workspace_index as isize == hover_id {
color = color_mix(hover_color, color);
}
}
// draw
ctx.save().unwrap();
if workspace_index == target {
cairo_set_color(&ctx, color);
ctx.append_path(
&draw_rect_path(
conf.border_radius,
(length, conf.thickness as f64),
[true, true, true, true],
)
.unwrap(),
);
ctx.fill().unwrap();
} else {
cairo_set_color(&ctx, target_color);
ctx.append_path(
&draw_rect_path(
conf.border_radius,
(length, conf.thickness as f64),
[true, true, true, true],
)
.unwrap(),
);
ctx.fill().unwrap();
cairo_set_color(&ctx, color);
ctx.translate(conf.border_width, conf.border_width);
ctx.append_path(
&draw_rect_path(
conf.border_radius,
(
length - 2. * conf.border_width,
conf.thickness as f64 - 2. * conf.border_width,
),
[true, true, true, true],
)
.unwrap(),
);
ctx.fill().unwrap();
}
ctx.restore().unwrap();
if (index + 1) as i32 != data.workspace_count {
ctx.translate(length + conf.gap as f64, Z);
};
// record calculated size for mouse locate
let end = draw_start_pos + length;
item_location.push([draw_start_pos, draw_start_pos + length]);
draw_start_pos = end + conf.gap as f64;
});
hover_data.update_hover_data(item_location);
surf
}
fn draw_horizontal(
conf: &DrawConf,
data: WorkspaceData,
prev_data: WorkspaceData,
hover_data: &mut HoverData,
) -> ImageSurface {
draw_common_horizontal(conf, data, prev_data, hover_data)
}
fn draw_vertical(
conf: &DrawConf,
data: WorkspaceData,
prev_data: WorkspaceData,
hover_data: &mut HoverData,
) -> ImageSurface {
let common = draw_common_horizontal(conf, data, prev_data, hover_data);
let surf = new_surface((common.height(), common.width()));
let ctx = Context::new(&surf).unwrap();
ctx.rotate(90.0_f64.to_radians());
ctx.translate(0., -conf.thickness as f64);
ctx.set_source_surface(&common, Z, Z).unwrap();
ctx.paint().unwrap();
surf
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/workspace/mod.rs | crates/frontend/src/widgets/workspace/mod.rs | mod draw;
mod event;
use std::{cell::Cell, rc::Rc};
use crate::{
mouse_state::{MouseEvent, MouseStateData},
wayland::app::WidgetBuilder,
};
use backend::workspace::{
hypr::{register_hypr_event_callback, HyprConf},
niri::register_niri_event_callback,
WorkspaceCB, WorkspaceData, WorkspaceHandler,
};
use config::widgets::workspace::{WorkspaceConfig, WorkspacePreset};
use draw::DrawConf;
use event::HoverData;
use smithay_client_toolkit::{output::OutputInfo, seat::pointer::BTN_LEFT};
use super::WidgetContext;
pub fn init_widget(
builder: &mut WidgetBuilder,
size: (i32, i32),
mut w_conf: WorkspaceConfig,
output: &OutputInfo,
) -> impl WidgetContext {
let edge = builder.common_config.edge;
w_conf.size.calculate_relative(size, edge);
if w_conf.output_name.is_none() {
w_conf.output_name = output.name.clone();
}
let workspace_transition = builder.new_animation(
w_conf.workspace_transition_duration,
w_conf.workspace_animation_curve,
);
let draw_conf = DrawConf::new(&w_conf, workspace_transition.clone(), edge);
let workspace_data = Rc::new(Cell::new((
WorkspaceData::default(),
WorkspaceData::default(),
)));
let hover_data = HoverData::new(edge, w_conf.invert_direction);
let workspace_data_weak = Rc::downgrade(&workspace_data);
let workspace_transition_weak = workspace_transition.downgrade();
let pop_signal_sender = builder.make_pop_channel(w_conf.pop_duration, move |_, msg| {
let Some(workspace_data) = workspace_data_weak.upgrade() else {
return;
};
let Some(workspace_transition) = workspace_transition_weak.upgrade() else {
return;
};
let mut old = workspace_data.get();
if old.0 != msg {
old.1 = old.0;
old.0 = msg;
workspace_data.set(old);
workspace_transition.borrow_mut().flip();
}
});
macro_rules! wp_cb {
($s:expr, $c:expr, $d:expr) => {
WorkspaceCB {
sender: $s,
output: $c.output_name.take().unwrap(),
data: $d,
focused_only: $c.focused_only,
}
};
}
let workspace_handler = match w_conf.preset.clone() {
WorkspacePreset::Hyprland => {
register_hypr_event_callback(wp_cb!(pop_signal_sender, w_conf, HyprConf))
}
WorkspacePreset::Niri(niri_conf) => {
register_niri_event_callback(wp_cb!(pop_signal_sender, w_conf, niri_conf))
}
};
WorkspaceCtx {
workspace_handler,
draw_conf,
workspace_data,
hover_data,
}
}
#[derive(Debug)]
pub struct WorkspaceCtx {
workspace_handler: WorkspaceHandler,
draw_conf: DrawConf,
workspace_data: Rc<Cell<(WorkspaceData, WorkspaceData)>>,
hover_data: HoverData,
}
impl WidgetContext for WorkspaceCtx {
fn redraw(&mut self) -> cairo::ImageSurface {
let d = self.workspace_data.get();
self.draw_conf.draw(d.0, d.1, &mut self.hover_data)
}
fn on_mouse_event(&mut self, _: &MouseStateData, event: MouseEvent) -> bool {
let mut should_redraw = false;
macro_rules! hhh {
($h:expr, $pos:expr) => {{
let old = $h.hover_id;
$h.update_hover_id_with_mouse_position($pos) != old
}};
}
match event {
MouseEvent::Release(pos, key) => {
if key == BTN_LEFT {
should_redraw = hhh!(self.hover_data, pos);
let id = self.hover_data.hover_id;
if id >= 0 {
self.workspace_handler.change_to_workspace(id as usize);
}
};
}
MouseEvent::Enter(pos) => {
should_redraw = hhh!(self.hover_data, pos);
}
MouseEvent::Motion(pos) => {
should_redraw = hhh!(self.hover_data, pos);
}
MouseEvent::Leave => {
let old = self.hover_data.hover_id;
if old != -1 {
self.hover_data.force_update_hover_id(-1);
should_redraw = true;
}
}
MouseEvent::Scroll(_, v) => {
let (d, _) = self.workspace_data.get();
let id = d.active;
let new_id = id + v.discrete;
if new_id == new_id.clamp(0, d.workspace_count - 1) {
self.workspace_handler.change_to_workspace(new_id as usize);
should_redraw = true;
}
}
_ => {}
};
should_redraw
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/slide/mod.rs | crates/frontend/src/widgets/slide/mod.rs | mod backlight;
mod base;
mod custom;
mod pulseaudio;
use crate::wayland::app::WidgetBuilder;
use config::widgets::slide::base::SlideConfig;
use super::WidgetContext;
pub fn init_widget(
builder: &mut WidgetBuilder,
size: (i32, i32),
mut w_conf: SlideConfig,
) -> Box<dyn WidgetContext> {
w_conf
.size
.calculate_relative(size, builder.common_config.edge);
use config::widgets::slide::preset::Preset;
match std::mem::take(&mut w_conf.preset) {
Preset::Backlight(backlight_config) => {
Box::new(backlight::preset(builder, w_conf, backlight_config))
}
Preset::Speaker(pulse_audio_config) => {
Box::new(pulseaudio::speaker(builder, w_conf, pulse_audio_config))
}
Preset::Microphone(pulse_audio_config) => {
Box::new(pulseaudio::microphone(builder, w_conf, pulse_audio_config))
}
Preset::Custom(custom_config) => {
Box::new(custom::custom_preset(builder, w_conf, custom_config))
}
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/slide/custom/mod.rs | crates/frontend/src/widgets/slide/custom/mod.rs | use cairo::ImageSurface;
use interval_task::runner::Runner;
use std::{cell::Cell, rc::Rc, time::Duration};
use config::{
shared::KeyEventMap,
widgets::slide::{base::SlideConfig, preset::CustomConfig},
};
use util::{
shell::{shell_cmd, shell_cmd_non_block},
template::base::Template,
};
use super::base::{
draw::DrawConfig,
event::{setup_event, ProgressState},
};
use crate::{
mouse_state::{MouseEvent, MouseStateData},
wayland::app::WidgetBuilder,
widgets::{
slide::base::event::{ProgressData, ProgressDataf},
WidgetContext,
},
};
#[derive(Debug)]
pub struct CustomContext {
#[allow(dead_code)]
runner: Option<Runner<()>>,
event_map: KeyEventMap,
on_change: Option<Template>,
draw_conf: DrawConfig,
progress_state: ProgressState<ProgressDataf>,
only_redraw_on_internal_update: bool,
}
impl WidgetContext for CustomContext {
fn redraw(&mut self) -> ImageSurface {
let p = self.progress_state.p();
self.draw_conf.draw(p)
}
fn on_mouse_event(&mut self, _: &MouseStateData, event: MouseEvent) -> bool {
if let MouseEvent::Release(_, key) = event.clone() {
self.event_map.call(key);
}
if let Some(p) = self
.progress_state
.if_change_progress(event, !self.only_redraw_on_internal_update)
{
self.run_on_change_command(p);
!self.only_redraw_on_internal_update
} else {
false
}
}
}
impl CustomContext {
fn run_on_change_command(&mut self, progress: f64) {
if let Some(template) = self.on_change.as_mut() {
use util::template::arg;
let cmd = template.parse(|parser| {
let res = match parser.name() {
arg::TEMPLATE_ARG_FLOAT => {
let float_parser = parser
.downcast_ref::<util::template::arg::TemplateArgFloatParser>()
.unwrap();
float_parser.parse(progress).clone()
}
_ => unreachable!(),
};
res
});
shell_cmd_non_block(cmd);
}
}
}
pub fn custom_preset(
builder: &mut WidgetBuilder,
w_conf: SlideConfig,
mut preset_conf: CustomConfig,
) -> impl WidgetContext {
let progress_data = Rc::new(Cell::new(0.));
// interval
let runner = interval_update(builder, &preset_conf, &progress_data);
// key event map
let event_map = std::mem::take(&mut preset_conf.event_map);
// on change
let on_change = preset_conf.on_change_command.take();
let edge = builder.common_config.edge;
CustomContext {
runner,
event_map,
on_change,
draw_conf: DrawConfig::new(edge, &w_conf),
progress_state: setup_event(edge, &w_conf, progress_data),
only_redraw_on_internal_update: w_conf.redraw_only_on_internal_update,
}
}
fn interval_update(
window: &mut WidgetBuilder,
preset_conf: &CustomConfig,
progress_cache: &Rc<Cell<f64>>,
) -> Option<Runner<()>> {
if preset_conf.update_interval == 0 || preset_conf.update_command.is_empty() {
return None;
}
let progress_cache_weak = Rc::downgrade(progress_cache);
let redraw_signal = window.make_redraw_channel(move |_, p| {
let Some(mut progress_cache) = progress_cache_weak.upgrade() else {
return;
};
progress_cache.set(p);
});
let cmd = preset_conf.update_command.clone();
let mut runner = interval_task::runner::new_runner(
Duration::from_millis(preset_conf.update_interval),
|| (),
move |_| {
if let Err(err) = shell_cmd(&cmd)
.and_then(|res| {
use std::str::FromStr;
f64::from_str(res.trim()).map_err(|_| "Invalid number".to_string())
})
.and_then(|progress| {
redraw_signal
.send(progress)
.map_err(|e| format!("Redraw signal error: {e}"))
})
{
log::error!("slide custom updata error: {err}")
}
false
},
);
runner.start().unwrap();
Some(runner)
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/slide/base/event.rs | crates/frontend/src/widgets/slide/base/event.rs | use std::cell::Cell;
use std::rc::Rc;
use crate::mouse_state::MouseEvent;
use config::widgets::slide::base::SlideConfig;
use smithay_client_toolkit::seat::pointer::BTN_LEFT;
use smithay_client_toolkit::shell::wlr_layer::Anchor;
fn make_translate_func(edge: Anchor) -> fn(i32, i32, (f64, f64)) -> f64 {
macro_rules! hhh {
($len:expr, $border_width:expr, $pos:expr, VERTICAL) => {
(($len as f64 - ($pos.1 - $border_width as f64)) / $len as f64)
.min(1.)
.max(0.)
};
($len:expr, $border_width:expr, $pos:expr, HORIZONTAL) => {
(($pos.0 - $border_width as f64) / $len as f64)
.min(1.)
.max(0.)
};
}
macro_rules! create_func {
($name:ident, $i:tt) => {
fn $name(length: i32, border_width: i32, pos: (f64, f64)) -> f64 {
hhh!(length, border_width, pos, $i)
}
};
}
create_func!(lor, VERTICAL);
create_func!(tob, HORIZONTAL);
match edge {
Anchor::LEFT | Anchor::RIGHT => lor,
Anchor::TOP | Anchor::BOTTOM => tob,
_ => unreachable!(),
}
}
pub trait ProgressData {
fn get(&self) -> f64;
fn set(&mut self, value: f64);
}
pub fn setup_event<T: ProgressData>(
edge: Anchor,
w_conf: &SlideConfig,
data: T,
) -> ProgressState<T> {
let func = make_translate_func(edge);
let left_pressing = false;
ProgressState {
left_pressing,
scroll_unit: w_conf.scroll_unit,
length: w_conf.size().unwrap().1 as i32 - 2 * w_conf.border_width,
border_width: w_conf.border_width,
func,
progress: data,
}
}
pub type ProgressDataf = Rc<Cell<f64>>;
impl ProgressData for ProgressDataf {
fn get(&self) -> f64 {
Cell::get(self)
}
fn set(&mut self, value: f64) {
Cell::set(self, value);
}
}
#[derive(Debug)]
pub struct ProgressState<T: ProgressData> {
left_pressing: bool,
length: i32,
border_width: i32,
func: fn(i32, i32, (f64, f64)) -> f64,
scroll_unit: f64,
progress: T,
}
impl<T: ProgressData> ProgressState<T> {
fn calculate(&self, pos: (f64, f64)) -> f64 {
(self.func)(self.length, self.border_width, pos)
}
pub fn p(&self) -> f64 {
self.progress.get()
}
pub fn data(&mut self) -> &mut T {
&mut self.progress
}
pub fn if_change_progress(
&mut self,
event: MouseEvent,
update_progress_immediate: bool,
) -> Option<f64> {
let mut p = None;
match event {
MouseEvent::Press(pos, key) => {
if key == BTN_LEFT {
self.left_pressing = true;
p = Some(self.calculate(pos));
}
}
MouseEvent::Release(pos, key) => {
if key == BTN_LEFT {
self.left_pressing = false;
p = Some(self.calculate(pos));
}
}
MouseEvent::Motion(pos) => {
if self.left_pressing {
p = Some(self.calculate(pos));
}
}
MouseEvent::Scroll(_, v) => {
p = Some((self.progress.get() + (self.scroll_unit * v.absolute)).clamp(0.0, 1.0));
}
_ => {}
}
#[allow(clippy::unnecessary_unwrap)]
if update_progress_immediate && p.is_some() {
self.progress.set(p.unwrap());
}
p
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/slide/base/draw.rs | crates/frontend/src/widgets/slide/base/draw.rs | use config::widgets::slide::base::SlideConfig;
use cosmic_text::Color;
use smithay_client_toolkit::shell::wlr_layer::Anchor;
use util::color::{cairo_set_color, COLOR_BLACK};
use util::text::TextConfig;
use std::f64::consts::PI;
use cairo::{self, Context, ImageSurface, Path};
use util::draw::new_surface;
use util::Z;
#[derive(Debug)]
pub struct DrawConfig {
length: i32,
thickness: i32,
border_width: i32,
obtuse_angle: f64,
radius: f64,
bg_color: Color,
pub fg_color: Color,
// if None we want to use half fg and bg and split at the seam
pub fg_text_color: Option<Color>,
pub bg_text_color: Option<Color>,
border_color: Color,
func: fn(&DrawConfig, f64) -> ImageSurface,
}
impl DrawConfig {
pub fn new(edge: Anchor, slide_conf: &SlideConfig) -> Self {
let content_size = slide_conf.size().unwrap();
let func = match edge {
Anchor::LEFT => draw_left,
Anchor::RIGHT => draw_right,
Anchor::TOP => draw_top,
Anchor::BOTTOM => draw_bottom,
_ => unreachable!(),
};
Self {
length: content_size.1.ceil() as i32,
thickness: content_size.0.ceil() as i32,
border_width: slide_conf.border_width,
obtuse_angle: slide_conf.obtuse_angle,
radius: slide_conf.radius,
bg_color: slide_conf.bg_color,
fg_color: slide_conf.fg_color,
border_color: slide_conf.border_color,
fg_text_color: slide_conf.fg_text_color,
bg_text_color: slide_conf.bg_text_color,
func,
}
}
fn new_horizontal_surf(&self) -> (ImageSurface, Context) {
let surf = new_surface((self.length, self.thickness));
let ctx = cairo::Context::new(&surf).unwrap();
(surf, ctx)
}
fn new_vertical_surf(&self) -> (ImageSurface, Context) {
let surf = new_surface((self.thickness, self.length));
let ctx = cairo::Context::new(&surf).unwrap();
(surf, ctx)
}
pub fn draw(&self, p: f64) -> ImageSurface {
(self.func)(self, p)
}
}
fn draw_text(progress: f64, progress_thickness: i32) -> ImageSurface {
let height = (progress_thickness as f64 * 0.8).ceil() as i32;
let text = format!("{:.2}%", progress * 100.);
util::text::draw_text(
&text,
TextConfig::new(
cosmic_text::Family::Name(util::text::slide_font::FAMILY_NAME),
Some(500),
COLOR_BLACK,
height,
),
)
.to_image_surface()
}
fn draw_slide_path(
obtuse_angle: f64,
radius: f64,
size: (f64, f64),
close_path: bool,
) -> Result<Path, String> {
let ctx =
cairo::Context::new(new_surface((size.0.ceil() as i32, size.1.ceil() as i32))).unwrap();
#[allow(dead_code)]
struct BigTrangle {
height: f64,
width: f64,
left_angle: f64,
top_angle: f64,
}
#[allow(dead_code)]
struct TrangleForRotation {
rotate_angle: f64,
height: f64,
width: f64,
max_line: f64,
}
fn from_angle(a: f64) -> f64 {
a / 180. * PI
}
// get trangle for rotation
let rotate_angle = 180. - obtuse_angle;
let height = size.1;
let width = size.1 / from_angle(rotate_angle).tan();
let max_line = height / from_angle(rotate_angle).sin();
let trangle_for_rotation = TrangleForRotation {
rotate_angle,
height,
width,
max_line,
};
// get big angle data
let height = radius;
let left_angle = obtuse_angle / 2.;
let top_angle = 90. - left_angle;
let width = radius / from_angle(left_angle).tan();
let big_trangle = BigTrangle {
height,
width,
left_angle,
top_angle,
};
// move
let percentage =
(trangle_for_rotation.max_line - big_trangle.width) / trangle_for_rotation.max_line;
ctx.move_to(Z, Z);
ctx.rel_line_to(
trangle_for_rotation.width * percentage,
trangle_for_rotation.height * percentage,
);
// rounded corner left
let origin = (
trangle_for_rotation.width + big_trangle.width,
size.1 - big_trangle.height,
);
let angle_from_to = (
from_angle(90. + 2. * big_trangle.top_angle),
from_angle(90.),
);
ctx.arc_negative(origin.0, origin.1, radius, angle_from_to.0, angle_from_to.1);
// next straight line
let origin_x = origin.0;
let line_length = size.0 - 2. * origin_x;
ctx.rel_line_to(line_length, Z);
// rounded corner right
let origin = (size.0 - origin.0, origin.1);
let angle_from_to = (
from_angle(90.),
from_angle(90. - 2. * big_trangle.top_angle),
);
ctx.arc_negative(origin.0, origin.1, radius, angle_from_to.0, angle_from_to.1);
// final rotate line
ctx.line_to(size.0, Z);
if close_path {
ctx.line_to(Z, Z);
ctx.close_path();
}
let path = ctx.copy_path().unwrap();
Ok(path)
}
struct DrawData {
bar: ImageSurface,
fg_surf: ImageSurface,
bg_size: (f64, f64),
normal_text_surf: ImageSurface,
}
impl DrawData {
fn new_surface_bar(&self) -> (cairo::ImageSurface, cairo::Context) {
let surf = new_surface((self.bar.width(), self.bar.height()));
let ctx = cairo::Context::new(&surf).unwrap();
(surf, ctx)
}
fn make_text(&self, conf: &DrawConfig) -> (ImageSurface, ImageSurface) {
let normal_text_surf = &self.normal_text_surf;
let text_start_pos = (
((self.bar.width() - normal_text_surf.width()) as f64 / 2.).floor(),
((self.bg_size.1 - normal_text_surf.height() as f64) / 2.).floor(),
);
let fg_text_surf = {
let (fg_text_surf, ctx) = self.new_surface_bar();
ctx.mask_surface(normal_text_surf, text_start_pos.0, text_start_pos.1)
.unwrap();
let (mask_surf, ctx) = self.new_surface_bar();
if let Some(fg_text_color) = conf.fg_text_color {
cairo_set_color(&ctx, fg_text_color);
} else {
cairo_set_color(&ctx, conf.bg_color);
}
ctx.mask_surface(&self.fg_surf, Z, Z).unwrap();
let (final_surf, ctx) = self.new_surface_bar();
ctx.set_source_surface(mask_surf, Z, Z).unwrap();
ctx.mask_surface(&fg_text_surf, Z, Z).unwrap();
final_surf
};
let bg_text_surf = {
let (bg_text_surf, ctx) = self.new_surface_bar();
if let Some(bg_text_color) = conf.bg_text_color {
cairo_set_color(&ctx, bg_text_color);
} else {
cairo_set_color(&ctx, conf.fg_color);
}
ctx.mask_surface(normal_text_surf, text_start_pos.0, text_start_pos.1)
.unwrap();
// ctx.translate(conf.border_width as f64 + self.text_translate_x, Z);
// ctx.append_path(&self.bg_path);
// ctx.set_operator(cairo::Operator::Clear);
// ctx.fill().unwrap();
bg_text_surf
};
(fg_text_surf, bg_text_surf)
}
fn draw_text_on_ctx(&self, ctx: &cairo::Context, conf: &DrawConfig) {
let (bg_text, fg_text) = self.make_text(conf);
ctx.set_source_surface(&fg_text, Z, Z).unwrap();
ctx.paint().unwrap();
ctx.set_source_surface(&bg_text, Z, Z).unwrap();
ctx.paint().unwrap();
}
}
fn make_draw_data(conf: &DrawConfig, progress: f64, is_forward: bool) -> DrawData {
let (surf, ctx) = conf.new_horizontal_surf();
// bg
let bg_size = (
(conf.length - conf.border_width * 2) as f64,
(conf.thickness - conf.border_width) as f64,
);
let radius = conf.radius;
let bg_path = draw_slide_path(conf.obtuse_angle, radius, bg_size, true).unwrap();
ctx.save().unwrap();
ctx.translate(conf.border_width as f64, Z);
ctx.append_path(&bg_path);
cairo_set_color(&ctx, conf.bg_color);
ctx.fill().unwrap();
ctx.restore().unwrap();
// fg
let fg_size = ((bg_size.0 * progress).ceil(), bg_size.1);
let translate_x = match is_forward {
true => -(bg_size.0 - fg_size.0),
false => bg_size.0 - fg_size.0,
};
let fg_surf = new_surface((surf.width(), surf.height()));
let fg_ctx = Context::new(&fg_surf).unwrap();
fg_ctx.translate(conf.border_width as f64 + translate_x, Z);
fg_ctx.append_path(&bg_path);
cairo_set_color(&fg_ctx, conf.fg_color);
fg_ctx.fill().unwrap();
ctx.save().unwrap();
ctx.translate(conf.border_width as f64, Z);
ctx.append_path(&bg_path);
ctx.restore().unwrap();
ctx.set_source_surface(&fg_surf, Z, Z).unwrap();
ctx.fill().unwrap();
// border
let border_size = (
(conf.length - conf.border_width) as f64,
(conf.thickness as f64 - conf.border_width as f64 / 2.),
);
let radius = conf.radius + conf.border_width as f64 / 2.;
let path = draw_slide_path(conf.obtuse_angle, radius, border_size, false).unwrap();
ctx.save().unwrap();
ctx.translate(conf.border_width as f64 / 2., Z);
ctx.append_path(&path);
cairo_set_color(&ctx, conf.border_color);
ctx.set_line_width(conf.border_width as f64);
ctx.stroke().unwrap();
ctx.restore().unwrap();
// text
let normal_text_surf = draw_text(progress, fg_size.1 as i32);
DrawData {
bar: surf,
fg_surf,
bg_size,
normal_text_surf,
}
}
fn draw_top(conf: &DrawConfig, progress: f64) -> ImageSurface {
let (surf, ctx) = conf.new_horizontal_surf();
let draw_data = make_draw_data(conf, progress, true);
ctx.set_source_surface(&draw_data.bar, Z, Z).unwrap();
ctx.paint().unwrap();
draw_data.draw_text_on_ctx(&ctx, conf);
surf
}
fn draw_left(conf: &DrawConfig, progress: f64) -> ImageSurface {
let top = draw_top(conf, progress);
let (surf, ctx) = conf.new_vertical_surf();
ctx.rotate(-90.0_f64.to_radians());
ctx.translate(-surf.height() as f64, Z);
ctx.set_source_surface(top, Z, Z).unwrap();
ctx.paint().unwrap();
surf
}
fn draw_right(conf: &DrawConfig, progress: f64) -> ImageSurface {
let (surf, ctx) = conf.new_vertical_surf();
let draw_data = make_draw_data(conf, progress, false);
ctx.rotate(90.0_f64.to_radians());
ctx.translate(Z, -conf.thickness as f64);
ctx.set_source_surface(&draw_data.bar, Z, Z).unwrap();
ctx.paint().unwrap();
draw_data.draw_text_on_ctx(&ctx, conf);
surf
}
fn draw_bottom(conf: &DrawConfig, progress: f64) -> ImageSurface {
let (surf, ctx) = conf.new_horizontal_surf();
let mut draw_data = make_draw_data(conf, progress, false);
ctx.save().unwrap();
ctx.rotate(180.0_f64.to_radians());
ctx.translate(-surf.width() as f64, -surf.height() as f64);
ctx.set_source_surface(&draw_data.bar, Z, Z).unwrap();
ctx.paint().unwrap();
ctx.restore().unwrap();
{
let (surf, ctx) = draw_data.new_surface_bar();
ctx.rotate(180.0_f64.to_radians());
ctx.translate(-surf.width() as f64, -surf.height() as f64);
ctx.translate(Z, conf.border_width as f64);
// let translate_y =
// ((draw_data.bg_size.1 - draw_data.normal_text_surf.height() as f64) / 2.).floor();
ctx.set_source_surface(&draw_data.fg_surf, Z, Z).unwrap();
ctx.paint().unwrap();
draw_data.fg_surf = surf;
};
ctx.translate(Z, conf.border_width as f64);
draw_data.draw_text_on_ctx(&ctx, conf);
surf
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/slide/base/mod.rs | crates/frontend/src/widgets/slide/base/mod.rs | pub mod draw;
pub mod event;
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/slide/backlight/mod.rs | crates/frontend/src/widgets/slide/backlight/mod.rs | use cairo::ImageSurface;
use std::{cell::Cell, rc::Rc};
use super::base::{
draw::DrawConfig,
event::{setup_event, ProgressState},
};
use crate::{
mouse_state::{MouseEvent, MouseStateData},
wayland::app::WidgetBuilder,
widgets::{slide::base::event::ProgressDataf, WidgetContext},
};
use config::widgets::slide::{base::SlideConfig, preset::BacklightConfig};
#[derive(Debug)]
pub struct BacklightContext {
#[allow(dead_code)]
backend_id: i32,
device: Option<String>,
draw_conf: DrawConfig,
progress_state: ProgressState<ProgressDataf>,
only_redraw_on_internal_update: bool,
}
impl WidgetContext for BacklightContext {
fn redraw(&mut self) -> ImageSurface {
let p = self.progress_state.p();
self.draw_conf.draw(p)
}
fn on_mouse_event(&mut self, _: &MouseStateData, event: MouseEvent) -> bool {
if let Some(p) = self
.progress_state
.if_change_progress(event.clone(), !self.only_redraw_on_internal_update)
{
backend::backlight::dbus::set_backlight(self.device.as_ref(), p);
!self.only_redraw_on_internal_update
} else {
false
}
}
}
pub fn preset(
builder: &mut WidgetBuilder,
w_conf: SlideConfig,
mut preset_conf: BacklightConfig,
) -> impl WidgetContext {
let device = preset_conf.device.take();
let progress = Rc::new(Cell::new(0.));
let progress_weak = Rc::downgrade(&progress);
let redraw_signal = builder.make_redraw_channel(move |_, p| {
let Some(progress) = progress_weak.upgrade() else {
return;
};
progress.set(p);
});
let backend_id = backend::backlight::register_callback(redraw_signal, device.clone()).unwrap();
let edge = builder.common_config.edge;
BacklightContext {
backend_id,
device,
draw_conf: DrawConfig::new(edge, &w_conf),
progress_state: setup_event(edge, &w_conf, progress),
only_redraw_on_internal_update: w_conf.redraw_only_on_internal_update,
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/slide/pulseaudio/mod.rs | crates/frontend/src/widgets/slide/pulseaudio/mod.rs | use cairo::ImageSurface;
use cosmic_text::Color;
use smithay_client_toolkit::seat::pointer::BTN_RIGHT;
use std::sync::Arc;
use std::{cell::Cell, rc::Rc};
use util::color::color_transition;
use super::base::{
draw::DrawConfig,
event::{setup_event, ProgressState},
};
use crate::widgets::slide::base::event::ProgressData;
use crate::{
animation::ToggleAnimationRc,
mouse_state::{MouseEvent, MouseStateData},
wayland::app::WidgetBuilder,
widgets::WidgetContext,
};
use backend::pulseaudio::{
change::{set_mute, set_vol},
PulseAudioDevice, VInfo,
};
use config::widgets::slide::{base::SlideConfig, preset::PulseAudioConfig};
#[derive(Debug)]
struct Progress(Rc<Cell<VInfo>>);
impl ProgressData for Progress {
fn get(&self) -> f64 {
Cell::get(&self.0).vol
}
fn set(&mut self, value: f64) {
let mut v = Cell::get(&self.0);
v.vol = value;
Cell::set(&self.0, v);
}
}
impl From<Rc<Cell<VInfo>>> for Progress {
fn from(vinfo: Rc<Cell<VInfo>>) -> Self {
Progress(vinfo)
}
}
impl Progress {
fn is_muted(&self) -> bool {
Cell::get(&self.0).is_muted
}
}
#[derive(Debug)]
pub struct PulseAudioContext {
#[allow(dead_code)]
backend_id: i32,
device: PulseAudioDevice,
debounce_ctx: Option<Arc<()>>,
non_mute_color: Color,
mute_color: Color,
non_mute_text_color: Color,
mute_text_color: Option<Color>,
mute_animation: ToggleAnimationRc,
draw_conf: DrawConfig,
progress_state: ProgressState<Progress>,
only_redraw_on_internal_update: bool,
}
impl WidgetContext for PulseAudioContext {
fn redraw(&mut self) -> ImageSurface {
let mute_y = self.mute_animation.borrow_mut().progress();
let fg_color = color_transition(self.non_mute_color, self.mute_color, mute_y as f32);
self.draw_conf.fg_color = fg_color;
if let Some(mute_text_color) = self.mute_text_color {
let bg_text_color =
color_transition(self.non_mute_text_color, mute_text_color, mute_y as f32);
self.draw_conf.bg_text_color = Some(bg_text_color);
}
let p = self.progress_state.p();
self.draw_conf.draw(p)
}
fn on_mouse_event(&mut self, _: &MouseStateData, event: MouseEvent) -> bool {
if let MouseEvent::Release(_, BTN_RIGHT) = event {
set_mute(self.device.clone(), !self.progress_state.data().is_muted());
}
if let Some(p) = self
.progress_state
.if_change_progress(event.clone(), !self.only_redraw_on_internal_update)
{
// debounce
let ctx = Arc::new(());
set_vol(self.device.clone(), p, std::sync::Arc::downgrade(&ctx));
self.debounce_ctx = Some(ctx);
!self.only_redraw_on_internal_update
} else {
false
}
}
}
fn common(
builder: &mut WidgetBuilder,
w_conf: SlideConfig,
preset_conf: PulseAudioConfig,
device: PulseAudioDevice,
) -> impl WidgetContext {
// TODO: PUT TIME COST INTO CONFIG?
let mute_animation = builder.new_animation(200, preset_conf.animation_curve);
let non_mute_color = w_conf.fg_color;
let mute_color = preset_conf.mute_color;
let non_mute_text_color = w_conf.bg_text_color.unwrap_or(w_conf.fg_color);
let mute_text_color = preset_conf.mute_text_color;
let vinfo = Rc::new(Cell::new(VInfo::default()));
let vinfo_weak = Rc::downgrade(&vinfo);
let mute_animation_weak = mute_animation.downgrade();
let redraw_signal = builder.make_redraw_channel(move |_, vinfo: VInfo| {
let Some(vinfo_old) = vinfo_weak.upgrade() else {
return;
};
let Some(mute_animation) = mute_animation_weak.upgrade() else {
return;
};
if vinfo_old.get().is_muted != vinfo.is_muted {
mute_animation
.borrow_mut()
.set_direction(vinfo.is_muted.into());
}
vinfo_old.set(vinfo);
});
let backend_id = backend::pulseaudio::register_callback(redraw_signal, device.clone()).unwrap();
let edge = builder.common_config.edge;
PulseAudioContext {
backend_id,
device,
non_mute_color,
mute_color,
non_mute_text_color,
mute_text_color,
mute_animation,
draw_conf: DrawConfig::new(edge, &w_conf),
progress_state: setup_event(edge, &w_conf, vinfo.into()),
only_redraw_on_internal_update: w_conf.redraw_only_on_internal_update,
debounce_ctx: None,
}
}
pub fn speaker(
builder: &mut WidgetBuilder,
w_conf: SlideConfig,
mut preset_conf: PulseAudioConfig,
) -> impl WidgetContext {
let device = preset_conf
.device
.take()
.map_or(PulseAudioDevice::DefaultSink, |name| {
PulseAudioDevice::NamedSink(name)
});
common(builder, w_conf, preset_conf, device)
}
pub fn microphone(
builder: &mut WidgetBuilder,
w_conf: SlideConfig,
mut preset_conf: PulseAudioConfig,
) -> impl WidgetContext {
let device = preset_conf
.device
.take()
.map_or(PulseAudioDevice::DefaultSource, |name| {
PulseAudioDevice::NamedSource(name)
});
common(builder, w_conf, preset_conf, device)
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/button/draw.rs | crates/frontend/src/widgets/button/draw.rs | use super::BtnConfig;
use cosmic_text::Color;
use smithay_client_toolkit::shell::wlr_layer::Anchor;
use util::color::cairo_set_color;
use std::f64::consts::PI;
use cairo::{self, Context, ImageSurface, LinearGradient};
use util::draw::new_surface;
use util::Z;
// for top only
#[derive(Debug)]
pub struct DrawConfig {
length: i32,
thickness: i32,
color: Color,
border_width: i32,
border_color: Color,
func: fn(&DrawConfig, bool) -> ImageSurface,
}
impl DrawConfig {
pub fn new(btn_conf: &BtnConfig, edge: Anchor) -> Self {
let content_size = btn_conf.size().unwrap();
let border_width = btn_conf.border_width;
let func = match edge {
Anchor::LEFT => draw_left,
Anchor::RIGHT => draw_right,
Anchor::TOP => draw_top,
Anchor::BOTTOM => draw_bottom,
_ => unreachable!(),
};
Self {
length: content_size.1.ceil() as i32,
thickness: content_size.0.ceil() as i32,
border_width,
color: btn_conf.color,
border_color: btn_conf.border_color,
func,
}
}
pub fn draw(&self, pressing: bool) -> ImageSurface {
(self.func)(self, pressing)
}
fn new_horizontal_surf(&self) -> (ImageSurface, Context) {
let surf = new_surface((self.length, self.thickness));
let ctx = cairo::Context::new(&surf).unwrap();
(surf, ctx)
}
fn new_vertical_surf(&self) -> (ImageSurface, Context) {
let surf = new_surface((self.thickness, self.length));
let ctx = cairo::Context::new(&surf).unwrap();
(surf, ctx)
}
}
fn draw_top(conf: &DrawConfig, pressing: bool) -> ImageSurface {
let (surf, ctx) = conf.new_horizontal_surf();
let size = (conf.length as f64, conf.thickness as f64);
let border_width = conf.border_width as f64;
// path
let radius = size.1 - border_width;
ctx.arc(size.1, Z, radius, 0.5 * PI, 1. * PI);
ctx.rel_line_to(size.0 - 2. * size.1, Z);
ctx.arc(size.0 - size.1, Z, radius, 0. * PI, 0.5 * PI);
ctx.rel_line_to(size.0 - 2. * border_width, Z);
ctx.close_path();
// content
cairo_set_color(&ctx, conf.color);
ctx.fill_preserve().unwrap();
// mask
let lg = if pressing {
let lg = LinearGradient::new(size.0 / 2., Z, size.0 / 2., size.1);
lg.add_color_stop_rgba(0., 0., 0., 0., 0.7);
lg.add_color_stop_rgba(0.3, 0., 0., 0., 0.);
lg.add_color_stop_rgba(1., 0., 0., 0., 0.7);
lg
} else {
let lg = LinearGradient::new(size.0 / 2., Z, size.0 / 2., size.1);
lg.add_color_stop_rgba(0., 0., 0., 0., 0.);
lg.add_color_stop_rgba(0.4, 0., 0., 0., 0.);
lg.add_color_stop_rgba(1., 0., 0., 0., 0.7);
lg
};
ctx.set_source(&lg).unwrap();
ctx.fill_preserve().unwrap();
ctx.new_path();
// border
let radius = size.1 - (border_width / 2.);
ctx.arc(size.1, Z, radius, 0.5 * PI, 1. * PI);
ctx.rel_line_to(size.0 - 2. * size.1, Z);
ctx.arc(size.0 - size.1, Z, radius, 0. * PI, 0.5 * PI);
ctx.close_path();
cairo_set_color(&ctx, conf.border_color);
ctx.set_line_width(border_width);
ctx.stroke_preserve().unwrap();
surf
}
fn draw_right(conf: &DrawConfig, pressing: bool) -> ImageSurface {
let (surf, ctx) = conf.new_vertical_surf();
let base = draw_top(conf, pressing);
ctx.rotate(90.0_f64.to_radians());
ctx.translate(Z, -conf.thickness as f64);
ctx.set_source_surface(&base, 0., 0.).unwrap();
ctx.paint().unwrap();
surf
}
fn draw_bottom(conf: &DrawConfig, pressing: bool) -> ImageSurface {
let (surf, ctx) = conf.new_horizontal_surf();
let base = draw_top(conf, pressing);
ctx.rotate(180.0_f64.to_radians());
ctx.translate(-conf.length as f64, -conf.thickness as f64);
ctx.set_source_surface(&base, 0., 0.).unwrap();
ctx.paint().unwrap();
surf
}
fn draw_left(conf: &DrawConfig, pressing: bool) -> ImageSurface {
let (surf, ctx) = conf.new_vertical_surf();
let base = draw_top(conf, pressing);
ctx.rotate(-90.0_f64.to_radians());
ctx.translate(-conf.length as f64, Z);
ctx.set_source_surface(&base, 0., 0.).unwrap();
ctx.paint().unwrap();
surf
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/button/mod.rs | crates/frontend/src/widgets/button/mod.rs | mod draw;
use crate::{
mouse_state::{MouseEvent, MouseStateData},
wayland::app::WidgetBuilder,
};
use config::{shared::KeyEventMap, widgets::button::BtnConfig};
use draw::DrawConfig;
use super::WidgetContext;
pub fn init_widget(
builder: &mut WidgetBuilder,
size: (i32, i32),
mut btn_config: BtnConfig,
) -> impl WidgetContext {
let edge = builder.common_config.edge;
btn_config.size.calculate_relative(size, edge);
BtnContext {
draw_conf: DrawConfig::new(&btn_config, edge),
pressing: false,
event_map: btn_config.event_map,
}
}
#[derive(Debug)]
pub struct BtnContext {
draw_conf: DrawConfig,
pressing: bool,
event_map: KeyEventMap,
}
impl WidgetContext for BtnContext {
fn redraw(&mut self) -> cairo::ImageSurface {
self.draw_conf.draw(self.pressing)
}
fn on_mouse_event(&mut self, data: &MouseStateData, event: MouseEvent) -> bool {
if let MouseEvent::Release(_, k) = event {
self.event_map.call(k);
}
let new_pressing_state = data.pressing.is_some();
if new_pressing_state != self.pressing {
self.pressing = new_pressing_state;
true
} else {
false
}
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/wrapbox/box_traits.rs | crates/frontend/src/widgets/wrapbox/box_traits.rs | use std::{cell::Cell, fmt::Debug, rc::Rc};
use cairo::ImageSurface;
use way_edges_derive::wrap_rc;
use crate::{animation::AnimationList, buffer::Buffer, mouse_state::MouseEvent};
use super::grid::GridBox;
pub type BoxedWidgetGrid = GridBox<BoxedWidgetCtxRc>;
pub trait BoxedWidget: Debug {
fn content(&mut self) -> ImageSurface;
fn on_mouse_event(&mut self, _: MouseEvent) -> bool {
false
}
}
#[wrap_rc(rc = "pub", normal = "pub")]
#[derive(Debug)]
pub struct BoxedWidgetCtx {
pub ctx: Box<dyn BoxedWidget>,
pub has_update: Rc<Cell<bool>>,
pub animation_list: AnimationList,
pub did_last_frame: bool,
pub buffer: Buffer,
}
impl BoxedWidgetCtx {
pub fn new(
ctx: impl BoxedWidget + 'static,
animation_list: AnimationList,
has_update: Rc<Cell<bool>>,
) -> Self {
Self {
ctx: Box::new(ctx),
animation_list,
did_last_frame: true,
buffer: Buffer::default(),
has_update,
}
}
fn update_buffer(&mut self, img: ImageSurface) {
self.buffer.update_buffer(img);
}
fn get_buffer(&self) -> ImageSurface {
self.buffer.get_buffer()
}
pub fn draw(&mut self) -> ImageSurface {
let mut call_redraw = false;
if self.animation_list.has_in_progress() {
if self.did_last_frame {
self.did_last_frame = false
}
call_redraw = true
} else if !self.did_last_frame {
self.did_last_frame = true;
call_redraw = true
} else if self.has_update.get() {
self.has_update.set(false);
call_redraw = true
}
if call_redraw {
let content = self.ctx.content();
self.update_buffer(content);
}
self.get_buffer()
}
pub fn on_mouse_event(&mut self, event: MouseEvent) -> bool {
let should_update = self.ctx.on_mouse_event(event);
if should_update {
self.has_update.set(true);
}
should_update
}
}
impl PartialEq for BoxedWidgetCtxRc {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
impl PartialEq for BoxedWidgetCtxRcWeak {
fn eq(&self, other: &Self) -> bool {
std::rc::Weak::ptr_eq(&self.0, &other.0)
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/wrapbox/event.rs | crates/frontend/src/widgets/wrapbox/event.rs | use util::Or;
use super::{
box_traits::{BoxedWidgetCtxRc, BoxedWidgetCtxRcWeak, BoxedWidgetGrid},
outlook::OutlookDraw,
BoxContext,
};
use crate::mouse_state::MouseEvent;
/// last hover widget, for trigger mouse leave option for that widget.
#[derive(Debug)]
pub struct LastWidget {
press_lock: bool,
current_widget: Option<BoxedWidgetCtxRcWeak>,
}
impl LastWidget {
pub fn new() -> Self {
Self {
press_lock: false,
current_widget: None,
}
}
fn set_current(&mut self, w: BoxedWidgetCtxRc, pos: (f64, f64)) -> bool {
if self.press_lock {
return false;
}
let mut redraw = Or(false);
if let Some(last) = self.current_widget.take() {
let last = last.upgrade().unwrap();
if last == w {
// if same widget
redraw.or(w.borrow_mut().on_mouse_event(MouseEvent::Motion(pos)));
} else {
// not same widget
redraw.or(last.borrow_mut().on_mouse_event(MouseEvent::Leave));
redraw.or(w.borrow_mut().on_mouse_event(MouseEvent::Enter(pos)));
}
} else {
// if no last widget
redraw.or(w.borrow_mut().on_mouse_event(MouseEvent::Enter(pos)));
}
self.current_widget = Some(w.downgrade());
redraw.res()
}
fn dispose_current(&mut self) -> bool {
// here we trust that press_lock from MouseState works fine:
// won't trigger `leave` while pressing
if self.press_lock {
return false;
}
if let Some(last) = self.current_widget.take() {
last.upgrade()
.unwrap()
.borrow_mut()
.on_mouse_event(MouseEvent::Leave)
} else {
false
}
}
fn lock_press(&mut self) {
self.press_lock = true
}
fn release_press(&mut self) {
self.press_lock = false
}
fn take_current(&mut self) -> Option<BoxedWidgetCtxRc> {
self.current_widget.take().map(|w| w.upgrade().unwrap())
}
}
fn match_item(
grid_box: &BoxedWidgetGrid,
outlook_mouse_pos: &dyn OutlookDraw,
pos: (f64, f64),
) -> Option<(BoxedWidgetCtxRc, (f64, f64))> {
let pos = outlook_mouse_pos.translate_mouse_position(pos);
grid_box
.match_item(pos)
.map(|(widget, pos)| (widget.clone(), pos))
}
pub fn on_mouse_event(event: MouseEvent, ctx: &mut BoxContext) -> bool {
let mut redraw = Or(false);
match event {
MouseEvent::Enter(pos) | MouseEvent::Motion(pos) => {
let matched = match_item(&ctx.grid_box, ctx.outlook_draw_conf.as_ref(), pos);
if let Some((widget, pos)) = matched {
redraw.or(ctx.last_widget.set_current(widget, pos));
} else {
redraw.or(ctx.last_widget.dispose_current());
}
ctx.leave_box_state = false;
}
MouseEvent::Leave => {
redraw.or(ctx.last_widget.dispose_current());
ctx.leave_box_state = true;
}
MouseEvent::Press(pos, k) => {
let matched = match_item(&ctx.grid_box, ctx.outlook_draw_conf.as_ref(), pos);
if let Some((widget, pos)) = matched {
ctx.last_widget.lock_press();
redraw.or(widget
.borrow_mut()
.on_mouse_event(MouseEvent::Press(pos, k)));
}
}
MouseEvent::Release(pos, k) => {
ctx.last_widget.release_press();
let matched = match_item(&ctx.grid_box, ctx.outlook_draw_conf.as_ref(), pos);
if let Some((widget, pos)) = matched {
redraw.or(widget
.borrow_mut()
.on_mouse_event(MouseEvent::Release(pos, k)));
} else if ctx.leave_box_state {
ctx.leave_box_state = false;
if let Some(last) = ctx.last_widget.take_current() {
let mut last = last.borrow_mut();
redraw.or(last.on_mouse_event(MouseEvent::Leave));
redraw.or(last.on_mouse_event(MouseEvent::Release(pos, k)));
}
}
}
common_event => {
if let Some(last) = ctx.last_widget.take_current() {
redraw.or(last.borrow_mut().on_mouse_event(common_event));
}
}
};
redraw.res()
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/wrapbox/mod.rs | crates/frontend/src/widgets/wrapbox/mod.rs | mod box_traits;
mod event;
mod grid;
mod outlook;
mod widgets;
use std::{cell::Cell, rc::Rc};
use crate::{
animation::{AnimationList, ToggleAnimationRc},
wayland::app::{App, WidgetBuilder},
};
use box_traits::{BoxedWidgetCtx, BoxedWidgetCtxRc, BoxedWidgetGrid};
use config::{shared::Curve, widgets::wrapbox::BoxConfig};
use event::LastWidget;
use grid::{builder::GrideBoxBuilder, GridBox};
use outlook::{init_outlook, OutlookDraw};
use super::WidgetContext;
#[derive(Debug)]
pub struct BoxContext {
grid_box: GridBox<BoxedWidgetCtxRc>,
outlook_draw_conf: Box<dyn OutlookDraw>,
last_widget: LastWidget,
leave_box_state: bool,
}
impl WidgetContext for BoxContext {
fn redraw(&mut self) -> cairo::ImageSurface {
let content = self.grid_box.draw(|ctx| ctx.borrow_mut().draw());
self.outlook_draw_conf.draw(content)
}
fn on_mouse_event(
&mut self,
_: &crate::mouse_state::MouseStateData,
event: crate::mouse_state::MouseEvent,
) -> bool {
event::on_mouse_event(event, self)
}
}
pub fn init_widget(builder: &mut WidgetBuilder, w_conf: BoxConfig) -> impl WidgetContext {
let outlook_draw_conf = init_outlook(
&w_conf.outlook,
builder.common_config.edge,
builder.common_config.offset,
);
let grid_box = init_boxed_widgets(builder, w_conf);
BoxContext {
grid_box,
outlook_draw_conf,
// last hover widget, for trigger mouse leave option for that widget.
last_widget: LastWidget::new(),
// because mouse leave event is before release,
// we need to check if unpress is right behind leave
leave_box_state: false,
}
}
fn init_boxed_widgets(window: &mut WidgetBuilder, mut box_conf: BoxConfig) -> BoxedWidgetGrid {
let mut builder = GrideBoxBuilder::<BoxedWidgetCtxRc>::new();
let ws = std::mem::take(&mut box_conf.items);
use config::widgets::wrapbox::BoxedWidget;
ws.into_iter().for_each(|w| {
let mut box_temporary_ctx = BoxTemporaryCtx::new(window);
macro_rules! boxed {
($ctx:expr, $w:expr) => {{
let w = $w;
$ctx.to_boxed_widget_ctx(w)
}};
}
let boxed_widget_context = match w.widget {
BoxedWidget::Text(text_config) => {
boxed!(
box_temporary_ctx,
widgets::text::init_text(&mut box_temporary_ctx, text_config)
)
}
BoxedWidget::Ring(ring_config) => {
boxed!(
box_temporary_ctx,
widgets::ring::init_widget(&mut box_temporary_ctx, ring_config)
)
}
BoxedWidget::Tray(tray_config) => {
boxed!(
box_temporary_ctx,
widgets::tray::init_widget(&mut box_temporary_ctx, tray_config)
)
}
};
builder.add(boxed_widget_context.make_rc(), (w.index[0], w.index[1]));
});
builder.build(box_conf.gap, box_conf.align)
}
struct BoxTemporaryCtx<'a, 'b> {
builder: &'a mut WidgetBuilder<'b>,
animation_list: AnimationList,
has_update: Rc<Cell<bool>>,
}
impl<'a, 'b> BoxTemporaryCtx<'a, 'b> {
fn new(builder: &'a mut WidgetBuilder<'b>) -> Self {
Self {
builder,
animation_list: AnimationList::new(),
has_update: Rc::new(Cell::new(true)),
}
}
fn new_animation(&mut self, time_cost: u64, curve: Curve) -> ToggleAnimationRc {
self.animation_list.new_transition(time_cost, curve)
}
fn redraw_essential(&self) -> impl Fn() + 'static {
let has_update = Rc::downgrade(&self.has_update);
move || {
let Some(has_update) = has_update.upgrade() else {
return;
};
has_update.set(true);
}
}
fn make_redraw_channel<T: 'static>(
&mut self,
mut func: impl FnMut(&mut App, T) + 'static,
) -> calloop::channel::Sender<T> {
let update = self.redraw_essential();
self.builder.make_redraw_channel(move |app, msg| {
func(app, msg);
update();
})
}
#[allow(dead_code)]
fn make_redraw_ping_with_func(
&mut self,
mut func: impl FnMut(&mut App) + 'static,
) -> calloop::ping::Ping {
let update = self.redraw_essential();
self.builder.make_redraw_ping_with_func(move |app| {
func(app);
update();
})
}
#[allow(dead_code)]
fn make_redraw_ping(&mut self) -> calloop::ping::Ping {
let update = self.redraw_essential();
self.builder.make_redraw_ping_with_func(move |_| {
update();
})
}
#[allow(clippy::wrong_self_convention)]
fn to_boxed_widget_ctx(self, ctx: impl box_traits::BoxedWidget + 'static) -> BoxedWidgetCtx {
self.builder.extend_animation_list(&self.animation_list);
BoxedWidgetCtx::new(ctx, self.animation_list, self.has_update)
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/wrapbox/widgets/mod.rs | crates/frontend/src/widgets/wrapbox/widgets/mod.rs | pub mod ring;
pub mod text;
pub mod tray;
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/wrapbox/widgets/tray/draw.rs | crates/frontend/src/widgets/wrapbox/widgets/tray/draw.rs | use std::f64::consts::PI;
use backend::tray::item::{MenuItem, MenuType, Tray};
use cairo::{Context, ImageSurface};
use config::widgets::wrapbox::tray::{MenuDrawConfig, TrayConfig};
use util::{
color::cairo_set_color,
draw::new_surface,
text::{draw_text, TextConfig},
Z,
};
use super::item::{MenuState, TrayState};
pub struct HeaderDrawArg<'a> {
text_conf: TextConfig<'a>,
}
impl<'a> HeaderDrawArg<'a> {
pub fn create_from_config(conf: &'a TrayConfig) -> Self {
let draw_config = &conf.header_draw_config;
let text_conf = TextConfig::new(
conf.font_family.as_family(),
None,
draw_config.text_color,
draw_config.font_pixel_height,
);
Self { text_conf }
}
pub fn draw_header(
&self,
tray_state: &TrayState,
tray: &Tray,
conf: &TrayConfig,
) -> ImageSurface {
let draw_icon = || {
tray.icon.draw_icon(
conf.icon_size,
conf.icon_theme.as_deref(),
tray.icon_theme_path.as_deref(),
)
};
if !tray_state.is_open {
return draw_icon();
}
let Some(title) = tray.title.as_ref().filter(|title| !title.is_empty()) else {
return draw_icon();
};
let text_surf = self.draw_text(title);
static ICON_TEXT_GAP: i32 = 4;
combine_horizonal_center(&[draw_icon(), text_surf], Some(ICON_TEXT_GAP))
}
fn draw_text(&self, text: &str) -> ImageSurface {
draw_text(text, self.text_conf).to_image_surface()
}
}
enum MenuItemDrawResult {
Item(ImageSurface),
Separator(i32),
}
impl MenuItemDrawResult {
fn get_size(&self) -> (i32, i32) {
match self {
MenuItemDrawResult::Item(surf) => (surf.width(), surf.height()),
MenuItemDrawResult::Separator(height) => (0, *height),
}
}
}
static GAP_BETWEEN_MARKER_AND_TEXT: i32 = 5;
// TODO: ICON FOR MENU ITEM
pub struct MenuDrawArg<'a> {
draw_config: &'a MenuDrawConfig,
text_conf: TextConfig<'a>,
}
impl<'a> MenuDrawArg<'a> {
pub fn create_from_config(conf: &'a TrayConfig) -> Self {
let draw_config = &conf.menu_draw_config;
let text_conf = TextConfig::new(
conf.font_family.as_family(),
None,
draw_config.text_color,
draw_config.font_pixel_height,
);
Self {
draw_config,
text_conf,
}
}
pub fn draw_menu(
&self,
menu: &[MenuItem],
menu_state: &MenuState,
conf: &TrayConfig,
) -> (ImageSurface, Vec<f64>) {
// this should be in config, or?
static MENU_ITEM_BORDER_WIDTH: i32 = 4;
let last_menu_index = menu.len() - 1;
let mut max_width = 0;
let mut total_height = 0;
let menu_draw_res: Vec<MenuItemDrawResult> = menu
.iter()
.enumerate()
.map(|(index, item)| {
// current_item
let menu_res = self.draw_menu_item(item, conf);
// count size
let size = menu_res.get_size();
max_width = max_width.max(size.0);
total_height += size.1;
// count in menu border
if index != last_menu_index {
total_height += MENU_ITEM_BORDER_WIDTH;
}
menu_res
})
.collect();
// context and surface
let size = (
max_width + MENU_ITEM_BORDER_WIDTH * 2,
total_height + MENU_ITEM_BORDER_WIDTH * 2,
);
let surf = new_surface(size);
let ctx = Context::new(&surf).unwrap();
cairo_set_color(&ctx, self.draw_config.border_color);
ctx.set_line_width(MENU_ITEM_BORDER_WIDTH as f64);
// outline of the menu
let half_line = MENU_ITEM_BORDER_WIDTH as f64 / 2.;
ctx.rectangle(
half_line,
half_line,
half_line + max_width as f64,
half_line + total_height as f64,
);
ctx.stroke().unwrap();
ctx.translate(half_line, half_line);
// menu item draw func
let draw_menu_border = || {
// draw a bottom border line
cairo_set_color(&ctx, self.draw_config.border_color);
ctx.move_to(Z, half_line);
ctx.rel_line_to(max_width as f64, Z);
ctx.stroke().unwrap();
// translate
ctx.translate(Z, MENU_ITEM_BORDER_WIDTH as f64);
};
let draw_menu_img = |index: usize, img: ImageSurface| {
let height = img.height() as f64;
ctx.set_source_surface(&img, Z, Z).unwrap();
ctx.paint().unwrap();
// menu state
let menu_item = &menu[index];
if !menu_item.enabled {
// not enable
ctx.save().unwrap();
ctx.set_source_rgba(0., 0., 0., 0.2);
ctx.rectangle(Z, Z, max_width as f64, height);
ctx.fill().unwrap();
ctx.restore().unwrap();
} else if menu_state.is_hover(menu_item.id) {
// hover
ctx.save().unwrap();
ctx.set_source_rgba(1., 1., 1., 0.2);
ctx.rectangle(Z, Z, max_width as f64, height);
ctx.fill().unwrap();
ctx.restore().unwrap();
}
if index < last_menu_index {
ctx.translate(Z, height);
draw_menu_border();
}
};
let draw_menu_sep = |index: usize, height: i32| {
cairo_set_color(&ctx, self.draw_config.border_color);
ctx.rectangle(Z, Z, max_width as f64, height as f64);
ctx.fill().unwrap();
ctx.translate(Z, height as f64);
if index < last_menu_index {
draw_menu_border();
}
};
// y map for layout
let mut y_map = vec![];
let mut y_count = 0.;
let mut count_y_map = |index, height: i32| {
let item_height = if index == 0 {
half_line + MENU_ITEM_BORDER_WIDTH as f64 + height as f64
} else if index == last_menu_index {
size.1 as f64
} else {
MENU_ITEM_BORDER_WIDTH as f64 + height as f64
};
y_count += item_height;
y_map.push(y_count);
};
// iter menu item and draw
menu_draw_res
.into_iter()
.enumerate()
.for_each(|(index, res)| match res {
MenuItemDrawResult::Item(img) => {
let height = img.height();
draw_menu_img(index, img);
count_y_map(index, height);
}
MenuItemDrawResult::Separator(height) => {
draw_menu_sep(index, height);
count_y_map(index, height);
}
});
(surf, y_map)
}
fn draw_menu_item(&self, item: &MenuItem, conf: &TrayConfig) -> MenuItemDrawResult {
let mut imgs = Vec::with_capacity(4);
// marker
match item.menu_type {
MenuType::Radio(state) => imgs.push(self.draw_marker_radio(state)),
MenuType::Check(state) => imgs.push(self.draw_marker_check(state)),
// empty marker
MenuType::Normal => imgs.push(new_surface((
self.draw_config.marker_size,
self.draw_config.marker_size,
))),
// do not draw anything
MenuType::Separator => {
return MenuItemDrawResult::Separator(self.draw_config.separator_height)
}
}
// icon
if let Some(icon) = item.icon.as_ref() {
// NOTE: SHOULD THEME PATH BE USED?
imgs.push(icon.draw_icon(
conf.menu_draw_config.icon_size,
conf.icon_theme.as_deref(),
None,
));
}
// text
if let Some(label) = item.label.as_ref() {
imgs.push(self.draw_text(label))
}
// submenu marker
if item.submenu.is_some() {
imgs.push(self.draw_marker_parent());
}
// combined
let combined = combine_horizonal_center(&imgs, Some(GAP_BETWEEN_MARKER_AND_TEXT));
// margin
let surf = new_surface((
combined.width() + 2 * self.draw_config.margin[0],
combined.height() + 2 * self.draw_config.margin[1],
));
let ctx = Context::new(&surf).unwrap();
ctx.set_source_surface(
&combined,
self.draw_config.margin[0] as f64,
self.draw_config.margin[1] as f64,
)
.unwrap();
ctx.paint().unwrap();
MenuItemDrawResult::Item(surf)
}
}
// supports: markers, text
impl MenuDrawArg<'_> {
fn draw_text(&self, text: &str) -> ImageSurface {
draw_text(text, self.text_conf).to_image_surface()
}
fn get_marker_surf_context(&self) -> (ImageSurface, Context) {
let size = self.draw_config.marker_size;
let color = self
.draw_config
.marker_color
.unwrap_or(self.draw_config.text_color);
let surf = new_surface((size, size));
let ctx = Context::new(&surf).unwrap();
cairo_set_color(&ctx, color);
(surf, ctx)
}
fn draw_marker_radio(&self, state: bool) -> ImageSurface {
let (surf, ctx) = self.get_marker_surf_context();
let size = self.draw_config.marker_size;
let center = size as f64 / 2.;
let line_width = (size as f64 / 10.).ceil();
let radius = center - line_width / 2.;
ctx.set_line_width(line_width);
ctx.arc(center, center, radius, Z, 2. * PI);
ctx.stroke().unwrap();
if state {
let radius = size as f64 / 5.;
ctx.arc(center, center, radius, Z, 2. * PI);
ctx.fill().unwrap();
}
surf
}
fn draw_marker_check(&self, state: bool) -> ImageSurface {
let (surf, ctx) = self.get_marker_surf_context();
let size = self.draw_config.marker_size;
ctx.rectangle(Z, Z, size as f64, size as f64);
ctx.set_line_width((size as f64 / 5.).ceil());
ctx.stroke().unwrap();
if state {
let inner_size = (size as f64 * 0.5).ceil();
let start = (size as f64 - inner_size) / 2.;
ctx.rectangle(start, start, inner_size, inner_size);
ctx.fill().unwrap();
}
surf
}
fn draw_marker_parent(&self) -> ImageSurface {
let (surf, ctx) = self.get_marker_surf_context();
let size = self.draw_config.marker_size;
ctx.move_to(Z, Z);
ctx.line_to(size as f64, size as f64 / 2.);
ctx.line_to(Z, size as f64);
ctx.close_path();
ctx.fill().unwrap();
surf
}
}
pub fn combine_horizonal_center(imgs: &[ImageSurface], gap: Option<i32>) -> ImageSurface {
let last_index = imgs.len() - 1;
let mut max_height = 0;
let mut total_width = 0;
imgs.iter().enumerate().for_each(|(index, img)| {
max_height = max_height.max(img.height());
total_width += img.width();
// count in gap
if index != last_index {
if let Some(gap) = gap {
total_width += gap;
}
}
});
let surf = new_surface((total_width, max_height));
let ctx = Context::new(&surf).unwrap();
imgs.iter().enumerate().for_each(|(index, img)| {
let height = img.height();
let y = (max_height - height) / 2;
ctx.set_source_surface(img, Z, y as f64).unwrap();
ctx.paint().unwrap();
ctx.translate(img.width() as f64, Z);
// translate for gap
if index != last_index {
if let Some(gap) = gap {
ctx.translate(gap as f64, Z);
}
}
});
surf
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/wrapbox/widgets/tray/module.rs | crates/frontend/src/widgets/wrapbox/widgets/tray/module.rs | use std::{collections::HashMap, sync::Arc};
use backend::tray::{item::Tray, TrayMap};
use cairo::ImageSurface;
use config::widgets::wrapbox::tray::TrayConfig;
use crate::{mouse_state::MouseEvent, widgets::wrapbox::grid::GridBox};
use super::item::TrayState;
#[derive(Debug)]
pub struct ModuleState {
current_mouse_in: Option<Destination>,
}
impl ModuleState {
fn new() -> Self {
Self {
current_mouse_in: None,
}
}
pub fn set_current_tary(&mut self, dest: Destination) -> Option<Destination> {
self.current_mouse_in
.as_mut()
.filter(|old| *old != &dest)
.map(|old| {
let ret = old.clone();
*old = dest;
ret
})
}
}
type Destination = Arc<String>;
#[derive(Debug)]
pub struct TrayModule {
// id
pub grid: GridBox<Destination>,
pub id_tray_map: HashMap<Destination, TrayState>,
pub module_state: ModuleState,
pub config: TrayConfig,
}
impl TrayModule {
pub fn draw_content(&mut self, tray_map: &TrayMap) -> ImageSurface {
self.grid.draw(|dest| {
let tray_state = self.id_tray_map.get_mut(dest).unwrap();
let tray = tray_map.get_tray(dest).unwrap();
tray_state.draw(tray, &self.config)
})
}
pub fn add_tray(&mut self, dest: Arc<String>, tray: &Tray) {
if self.id_tray_map.contains_key(&dest) {
return;
}
let state = TrayState::new(dest.clone(), tray);
self.grid.add(dest.clone());
self.id_tray_map.insert(dest, state);
}
pub fn remove_tray(&mut self, id: &String) {
self.grid.rm(id);
self.id_tray_map.remove(id);
}
pub fn update_tray(&mut self, dest: &String, tray: &Tray) {
if let Some(state) = self.find_tray(dest) {
state.update_tray(tray)
}
}
pub fn find_tray(&mut self, id: &String) -> Option<&mut TrayState> {
self.id_tray_map.get_mut(id)
}
pub fn match_tray_id_from_pos(
&mut self,
pos: (f64, f64),
) -> Option<(Arc<String>, &mut TrayState, (f64, f64))> {
let (dest, pos) = self
.grid
.position_map
.as_ref()
.unwrap()
.match_item(pos, &self.grid.item_map)?;
let dest = dest.clone();
self.find_tray(&dest).map(|state| (dest, state, pos))
}
pub fn leave_last_tray(&mut self) -> bool {
if let Some(f) = self.module_state.current_mouse_in.take() {
self.find_tray(&f)
.map(|state| state.on_mouse_event(MouseEvent::Leave))
.unwrap_or_default()
} else {
false
}
}
pub fn replace_current_tray(&mut self, dest: Destination) -> bool {
if let Some(f) = self.module_state.set_current_tary(dest) {
self.find_tray(&f)
.map(|state| state.on_mouse_event(MouseEvent::Leave))
.unwrap_or_default()
} else {
false
}
}
}
pub fn new_tray_module(config: TrayConfig) -> TrayModule {
let grid = GridBox::new(config.tray_gap as f64, config.grid_align);
TrayModule {
grid,
config,
id_tray_map: HashMap::new(),
module_state: ModuleState::new(),
}
}
impl GridBox<Destination> {
fn arrangement(num_icons: usize) -> (usize, usize) {
let num_icons = num_icons as f64;
let mut best_cols = 1.;
let mut min_rows = f64::INFINITY;
let max_col = num_icons.sqrt().ceil();
let mut cols = 1.;
while cols <= max_col {
let rows = (num_icons / cols).ceil();
if rows < min_rows {
min_rows = rows;
best_cols = cols;
}
cols += 1.;
}
(min_rows as usize, best_cols as usize)
}
fn rearrange(&mut self) {
let len = self.item_map.items.len();
if len == 0 {
self.row_col_num = (0, 0);
self.item_map.row_index.clear();
return;
}
let arrangement = Self::arrangement(len);
self.row_col_num = arrangement;
self.item_map.row_index.clear();
for raw_num in 0..arrangement.0 {
self.item_map.row_index.push(raw_num * arrangement.1);
}
}
fn add(&mut self, v: Arc<String>) {
self.item_map.items.push(v);
self.rearrange();
}
fn rm(&mut self, v: &str) {
if let Some(index) = self
.item_map
.items
.iter()
.position(|tray| tray.as_str() == v)
{
self.item_map.items.remove(index);
self.rearrange();
}
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/wrapbox/widgets/tray/mod.rs | crates/frontend/src/widgets/wrapbox/widgets/tray/mod.rs | mod draw;
mod item;
mod layout;
mod module;
use std::{
cell::RefCell,
rc::{Rc, Weak},
};
use backend::tray::{init_tray_client, register_tray, TrayBackendHandle, TrayMsg};
use config::widgets::wrapbox::tray::TrayConfig;
use module::{new_tray_module, TrayModule};
use util::Or;
use crate::{
mouse_state::MouseEvent,
widgets::wrapbox::{box_traits::BoxedWidget, BoxTemporaryCtx},
};
#[derive(Debug)]
pub struct TrayCtx {
module: TrayModule,
backend_handle: TrayBackendHandle,
}
impl TrayCtx {
fn content(&mut self) -> cairo::ImageSurface {
self.module
.draw_content(&self.backend_handle.get_tray_map().lock().unwrap())
}
fn on_mouse_event(&mut self, e: MouseEvent) -> bool {
let mut redraw = Or(false);
match e {
MouseEvent::Release(pos, key) => {
if let Some((dest, tray, pos)) = self.module.match_tray_id_from_pos(pos) {
redraw.or(tray.on_mouse_event(MouseEvent::Release(pos, key)));
redraw.or(self.module.replace_current_tray(dest));
}
}
MouseEvent::Enter(pos) | MouseEvent::Motion(pos) => {
if let Some((dest, tray, pos)) = self.module.match_tray_id_from_pos(pos) {
redraw.or(tray.on_mouse_event(MouseEvent::Motion(pos)));
redraw.or(self.module.replace_current_tray(dest));
}
}
MouseEvent::Leave => {
redraw.or(self.module.leave_last_tray());
}
_ => {}
}
redraw.res()
}
}
#[derive(Debug)]
pub struct TrayCtxRc(Rc<RefCell<TrayCtx>>);
impl BoxedWidget for TrayCtxRc {
fn content(&mut self) -> cairo::ImageSurface {
self.0.borrow_mut().content()
}
fn on_mouse_event(&mut self, e: MouseEvent) -> bool {
self.0.borrow_mut().on_mouse_event(e)
}
}
pub fn init_widget(box_temp_ctx: &mut BoxTemporaryCtx, config: TrayConfig) -> TrayCtxRc {
init_tray_client();
let rc = Rc::new_cyclic(|weak: &Weak<RefCell<TrayCtx>>| {
let weak = weak.clone();
let mut module = new_tray_module(config);
let s = box_temp_ctx.make_redraw_channel(move |_, dest: TrayMsg| {
let Some(module) = weak.upgrade() else {
return;
};
let mut m = module.borrow_mut();
use backend::tray::TrayEventSignal::*;
match dest {
Add(dest) => {
let tray_map_ptr = m.backend_handle.get_tray_map();
let tray_map = tray_map_ptr.lock().unwrap();
let tray = tray_map.get_tray(&dest).unwrap();
m.module.add_tray(dest, tray);
}
Rm(dest) => {
m.module.remove_tray(&dest);
}
Update(dest) => {
let tray_map_ptr = m.backend_handle.get_tray_map();
let tray_map = tray_map_ptr.lock().unwrap();
let tray = tray_map.get_tray(&dest).unwrap();
m.module.update_tray(&dest, tray)
}
};
});
let backend_handle = register_tray(s);
let map_ptr = backend_handle.get_tray_map();
map_ptr
.lock()
.unwrap()
.list_tray()
.into_iter()
.for_each(|(k, v)| {
module.add_tray(k, v);
});
RefCell::new(TrayCtx {
module,
backend_handle,
})
});
TrayCtxRc(rc)
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/wrapbox/widgets/tray/layout.rs | crates/frontend/src/widgets/wrapbox/widgets/tray/layout.rs | use backend::tray::item::{MenuItem, RootMenu, Tray};
use cairo::{Context, ImageSurface};
use config::widgets::wrapbox::tray::{HeaderMenuAlign, HeaderMenuStack, TrayConfig};
use util::{binary_search_end, draw::new_surface, Z};
use super::{
draw::{HeaderDrawArg, MenuDrawArg},
item::{MenuState, TrayState},
};
#[derive(Debug)]
pub enum HoveringItem {
TrayIcon,
MenuItem(i32),
}
#[derive(Default, Debug)]
struct TrayHeadLayout {
// icon should always be at 0,0
header_height: i32,
}
impl TrayHeadLayout {
fn draw_and_create(state: &TrayState, tray: &Tray, conf: &TrayConfig) -> (ImageSurface, Self) {
let draw_arg = HeaderDrawArg::create_from_config(conf);
let img = draw_arg.draw_header(state, tray, conf);
// let content_size = (img.width(), img.height());
let header_height = img.height();
(img, Self { header_height })
}
}
#[derive(Debug)]
struct MenuCol {
height_range: Vec<f64>,
id_vec: Vec<i32>,
}
impl MenuCol {
fn draw_and_create_from_root_menu(
menu_items: &[MenuItem],
state: &MenuState,
conf: &TrayConfig,
menu_arg: &mut MenuDrawArg,
) -> Vec<(ImageSurface, Self)> {
let (surf, height_range) = menu_arg.draw_menu(menu_items, state, conf);
let mut next_col = None;
let id_vec: Vec<i32> = menu_items
.iter()
.map(|item| {
// check next col
if let Some(submenu) = &item.submenu {
if state.is_open(item.id) {
next_col = Some(submenu);
}
}
item.id
})
.collect();
let mut res = vec![(
surf,
Self {
height_range,
id_vec,
},
)];
if let Some(next_col) = next_col {
let next_col = Self::draw_and_create_from_root_menu(next_col, state, conf, menu_arg);
res.extend(next_col);
}
res
}
fn get_hovering(&self, pos: (f64, f64)) -> Option<i32> {
let row_index = binary_search_end(&self.height_range, pos.1);
if row_index == -1 {
None
} else {
Some(self.id_vec[row_index as usize])
}
}
}
#[derive(Debug)]
struct MenuLayout {
menu_size: (i32, i32),
// end pixel index of each col
menu_each_col_x_end: Vec<i32>,
// same index of `menu_each_col_x_end`
menu_cols: Vec<MenuCol>,
}
impl MenuLayout {
fn draw_and_create(
root_menu: &RootMenu,
state: &MenuState,
conf: &TrayConfig,
) -> (ImageSurface, Self) {
let mut menu_arg = MenuDrawArg::create_from_config(conf);
let cols = MenuCol::draw_and_create_from_root_menu(
&root_menu.submenus,
state,
conf,
&mut menu_arg,
);
// TODO: WHY DO I PUT THIS HERE AT THE FIRST PLACE?
#[allow(clippy::drop_non_drop)]
drop(menu_arg);
let mut max_height = 0;
let mut menu_each_col_x_end = vec![];
let mut width_count = 0;
cols.iter().for_each(|(img, _)| {
max_height = max_height.max(img.height());
width_count += img.width();
menu_each_col_x_end.push(width_count);
});
let surf = new_surface((width_count, max_height));
let ctx = Context::new(&surf).unwrap();
let menu_cols = cols
.into_iter()
.map(|(img, col)| {
let width = img.width();
ctx.set_source_surface(img, Z, Z).unwrap();
ctx.paint().unwrap();
ctx.translate(width as f64, Z);
col
})
.collect();
let menu_size = (surf.width(), surf.height());
(
surf,
Self {
menu_each_col_x_end,
menu_cols,
menu_size,
},
)
}
fn get_hovering(&self, pos: (f64, f64)) -> Option<i32> {
let col_index = binary_search_end(&self.menu_each_col_x_end, pos.0 as i32);
if col_index == -1 {
None
} else {
let col_index = col_index as usize;
let new_pos_width = if col_index == 0 {
0.
} else {
pos.0 - self.menu_each_col_x_end[col_index - 1] as f64
};
self.menu_cols[col_index].get_hovering((new_pos_width, pos.1))
}
}
}
static GAP_HEADER_MENU: i32 = 6;
#[derive(Default, Debug)]
pub struct TrayLayout {
total_size: (i32, i32),
header_menu_stack: HeaderMenuStack,
header_menu_align: HeaderMenuAlign,
tray_head_layout: TrayHeadLayout,
menu_layout: Option<MenuLayout>,
}
impl TrayLayout {
pub fn draw_and_create(
tray_state: &TrayState,
tray: &Tray,
conf: &TrayConfig,
) -> (ImageSurface, TrayLayout) {
let (header_img, header_layout) = TrayHeadLayout::draw_and_create(tray_state, tray, conf);
macro_rules! done_with_only_header {
($tray:expr, $tray_config:expr, $header_img:expr, $header_layout:expr) => {{
let header_menu_stack = $tray_config.header_menu_stack.clone();
let header_menu_align = $tray_config.header_menu_align.clone();
let total_size = ($header_img.width(), $header_img.height());
let content = $header_img;
let layout = TrayLayout {
tray_head_layout: $header_layout,
menu_layout: None,
total_size,
header_menu_stack,
header_menu_align,
};
(content, layout)
}};
}
if !tray_state.is_open {
return done_with_only_header!(tray, conf, header_img, header_layout);
}
let Some((menu_img, menu_layout)) = tray
.menu
.as_ref()
.map(|root_menu| MenuLayout::draw_and_create(root_menu, &tray_state.menu_state, conf))
else {
return done_with_only_header!(tray, conf, header_img, header_layout);
};
// combine header and menu
let imgs = match conf.header_menu_stack {
HeaderMenuStack::HeaderTop => [header_img, menu_img],
HeaderMenuStack::MenuTop => [menu_img, header_img],
};
let combined = combine_vertcal(
&imgs,
Some(GAP_HEADER_MENU),
conf.header_menu_align.is_left(),
);
let total_size = (combined.width(), combined.height());
let header_menu_stack = conf.header_menu_stack.clone();
let header_menu_align = conf.header_menu_align.clone();
let content = combined;
let layout = TrayLayout {
tray_head_layout: header_layout,
menu_layout: Some(menu_layout),
total_size,
header_menu_stack,
header_menu_align,
};
(content, layout)
}
pub fn get_hovering(&self, pos: (f64, f64)) -> Option<HoveringItem> {
if pos.0 < Z
&& pos.0 > self.total_size.0 as f64
&& pos.1 < Z
&& pos.1 > self.total_size.1 as f64
{
return None;
}
let get_menu_x_when_at_left = || pos.0;
let get_menu_x_when_at_right =
|| pos.0 - (self.total_size.0 - self.menu_layout.as_ref().unwrap().menu_size.0) as f64;
let get_menu_y_when_at_top = || pos.1;
let get_menu_y_when_at_bottom =
|| pos.1 - self.tray_head_layout.header_height as f64 - GAP_HEADER_MENU as f64;
macro_rules! stack {
(header $self:expr, $pos:expr, $menu_x:expr, $menu_y:expr) => {{
let header_height = self.tray_head_layout.header_height as f64;
if $pos.1 < header_height {
Some(HoveringItem::TrayIcon)
} else if let Some(layout) = &self.menu_layout {
layout
.get_hovering(($menu_x, $menu_y))
.map(HoveringItem::MenuItem)
} else {
None
}
}};
(bottom $self:expr, $pos:expr, $menu_x:expr, $menu_y:expr) => {{
if let Some(layout) = &$self
.menu_layout
.as_ref()
.filter(|layout| $pos.1 < layout.menu_size.1 as f64)
{
layout
.get_hovering(($menu_x, $menu_y))
.map(HoveringItem::MenuItem)
} else {
Some(HoveringItem::TrayIcon)
}
}};
}
match (&self.header_menu_stack, &self.header_menu_align) {
(HeaderMenuStack::HeaderTop, HeaderMenuAlign::Left) => {
stack!(header self, pos, get_menu_x_when_at_left(), get_menu_y_when_at_bottom())
}
(HeaderMenuStack::HeaderTop, HeaderMenuAlign::Right) => {
stack!(header self, pos, get_menu_x_when_at_right(), get_menu_y_when_at_bottom())
}
(HeaderMenuStack::MenuTop, HeaderMenuAlign::Left) => {
stack!(bottom self, pos, get_menu_x_when_at_left(), get_menu_y_when_at_top())
}
(HeaderMenuStack::MenuTop, HeaderMenuAlign::Right) => {
stack!(bottom self, pos, get_menu_x_when_at_right(), get_menu_y_when_at_top())
}
}
}
}
pub fn combine_vertcal(imgs: &[ImageSurface], gap: Option<i32>, align_left: bool) -> ImageSurface {
let last_index = imgs.len() - 1;
let mut max_width = 0;
let mut total_height = 0;
imgs.iter().enumerate().for_each(|(index, img)| {
max_width = max_width.max(img.width());
total_height += img.height();
// count in gap
if index != last_index {
if let Some(gap) = gap {
total_height += gap;
}
}
});
let surf = new_surface((max_width, total_height));
let ctx = Context::new(&surf).unwrap();
imgs.iter().enumerate().for_each(|(index, img)| {
if align_left {
ctx.set_source_surface(img, Z, Z).unwrap();
} else {
ctx.set_source_surface(img, (surf.width() - img.width()) as f64, Z)
.unwrap();
}
ctx.paint().unwrap();
ctx.translate(Z, img.height() as f64);
// translate for gap
if index != last_index {
if let Some(gap) = gap {
ctx.translate(Z, gap as f64);
}
}
});
surf
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/wrapbox/widgets/tray/item.rs | crates/frontend/src/widgets/wrapbox/widgets/tray/item.rs | use std::sync::Arc;
use cairo::ImageSurface;
use smithay_client_toolkit::seat::pointer::{BTN_LEFT, BTN_RIGHT};
use system_tray::client::ActivateRequest;
use backend::tray::{
item::{MenuItem, RootMenu, Tray},
tray_about_to_show_menuitem, tray_active_request,
};
use config::widgets::wrapbox::tray::TrayConfig;
use crate::{buffer::Buffer, mouse_state::MouseEvent};
use super::layout::TrayLayout;
#[derive(Default, Debug)]
pub struct MenuState {
// pub open_state: HashSet<i32>,
pub open_state: Box<[i32]>,
pub hover_state: i32,
}
impl MenuState {
pub fn is_open(&self, id: i32) -> bool {
self.open_state.contains(&id)
}
pub fn is_hover(&self, id: i32) -> bool {
self.hover_state == id
}
fn set_hovering(&mut self, id: i32) -> bool {
if self.hover_state != id {
self.hover_state = id;
true
} else {
false
}
}
fn set_open_id(&mut self, mut id_chain: Vec<i32>) {
let clicked_one = id_chain.last().unwrap();
if self.open_state.contains(clicked_one) {
id_chain.pop();
}
self.open_state = id_chain.into_boxed_slice();
}
fn filter_state_with_new_menu(&mut self, menu: &RootMenu) {
Checker::run(self, menu);
struct Checker<'a> {
state: &'a mut MenuState,
new_open_state: Option<Vec<i32>>,
found_hover: Option<bool>,
}
impl<'a> Checker<'a> {
fn run(state: &'a mut MenuState, menu: &RootMenu) {
let need_check_open_state = !state.open_state.is_empty();
let need_check_hover = state.hover_state != -1;
let mut checker = Checker {
state,
new_open_state: if need_check_open_state {
Some(vec![])
} else {
None
},
found_hover: if need_check_hover { Some(false) } else { None },
};
checker.iter_menus(&menu.submenus, 0);
checker.post_check_open_state();
checker.post_check_hover_state();
}
fn check_open_state(&mut self, menu: &MenuItem, level: usize) {
if let Some(new_open_state) = self.new_open_state.as_mut() {
if level < self.state.open_state.len()
&& self.state.open_state[level] == menu.id
&& menu.submenu.is_some()
{
new_open_state.push(menu.id);
}
}
}
fn post_check_open_state(&mut self) {
if let Some(new_open_state) = self.new_open_state.take() {
self.state.open_state = new_open_state.into_boxed_slice();
}
}
fn check_hover_state(&mut self, menu: &MenuItem, _: usize) {
if let Some(found_hover) = self.found_hover.as_mut() {
if menu.id == self.state.hover_state {
*found_hover = true;
}
}
}
fn post_check_hover_state(&mut self) {
if let Some(found_hover) = self.found_hover.take() {
if !found_hover {
self.state.hover_state = -1;
}
}
}
fn iter_menus(&mut self, vec: &[MenuItem], level: usize) {
vec.iter().for_each(|menu| {
self.check_open_state(menu, level);
self.check_hover_state(menu, level);
if let Some(submenu) = &menu.submenu {
self.iter_menus(submenu, level + 1);
}
});
}
}
}
}
#[derive(Debug)]
struct MenuIDTreeNode {
id: i32,
sub: Option<Vec<MenuIDTreeNode>>,
}
impl MenuIDTreeNode {
fn from_root_menu(root: &RootMenu) -> Self {
Self {
id: root.id,
sub: Some(Self::from_menu(&root.submenus)),
}
}
fn from_menu(menu: &[MenuItem]) -> Vec<Self> {
menu.iter()
.map(|m| Self {
id: m.id,
sub: m.submenu.as_deref().map(Self::from_menu),
})
.collect()
}
}
#[derive(Debug)]
struct TrayCacheData {
dest: Arc<String>,
menu_path: Option<String>,
menu_id_tree: Option<MenuIDTreeNode>,
}
#[derive(Debug)]
pub struct TrayState {
tray_cache_data: TrayCacheData,
pub menu_state: MenuState,
pub is_open: bool,
pub updated: bool,
layout: TrayLayout,
buffer: Buffer,
}
// update
impl TrayState {
pub fn new(dest: Arc<String>, tray: &Tray) -> Self {
Self {
tray_cache_data: TrayCacheData {
dest,
menu_path: tray.menu_path.clone(),
menu_id_tree: tray.menu.as_ref().map(MenuIDTreeNode::from_root_menu),
},
menu_state: MenuState::default(),
is_open: false,
updated: true,
layout: TrayLayout::default(),
buffer: Buffer::default(),
}
}
pub fn update_tray(&mut self, tray: &Tray) {
self.updated = true;
tray.menu.as_ref().inspect(|f| {
self.tray_cache_data.menu_id_tree = Some(MenuIDTreeNode::from_root_menu(f));
self.menu_state.filter_state_with_new_menu(f);
});
}
}
// proxy request
impl TrayState {
fn send_active_request(req: ActivateRequest) {
tray_active_request(req)
}
fn tray_clicked_req(&self) {
let address = String::clone(&self.tray_cache_data.dest);
Self::send_active_request(ActivateRequest::Default {
address,
x: 0,
y: 0,
});
}
fn menu_item_clicked_req(&self, submenu_id: i32) {
if let Some(menu_path) = self.tray_cache_data.menu_path.as_ref() {
let address = String::clone(&self.tray_cache_data.dest);
let menu_path = menu_path.clone();
Self::send_active_request(ActivateRequest::MenuItem {
address,
menu_path,
submenu_id,
});
}
}
fn menuitem_about_to_show(&self, menuitem_id: i32) {
if let Some(path) = self.tray_cache_data.menu_path.as_ref() {
tray_about_to_show_menuitem(
self.tray_cache_data.dest.to_string(),
path.to_string(),
menuitem_id,
);
}
}
}
// content
impl TrayState {
// recalculate id chain
// for menu:
// a:
// - b
// - c:
// - e
// - d
//
// pressing e will produce id chain: a,c,e
// but the result is e,c,a so we need to reverse it after this
fn recalculate_open_id_chain(&mut self, id: i32) -> bool {
fn calculate_id_chain(menu: &[MenuIDTreeNode], id: i32, chain: &mut Vec<i32>) -> bool {
for i in menu.iter() {
// only happens for a parent menu
if let Some(submenu) = &i.sub {
if i.id == id || calculate_id_chain(submenu, id, chain) {
chain.push(i.id);
return true;
}
}
}
false
}
let mut id_chain = vec![];
calculate_id_chain(
self.tray_cache_data
.menu_id_tree
.as_ref()
.unwrap()
.sub
.as_ref()
.unwrap(),
id,
&mut id_chain,
);
id_chain.reverse();
if !id_chain.is_empty() {
id_chain.reverse();
self.menu_state.set_open_id(id_chain);
true
} else {
false
}
}
fn set_updated(&mut self) {
self.updated = true;
}
fn redraw_if_updated(&mut self, tray: &Tray, conf: &TrayConfig) {
if self.updated {
self.updated = false;
let (buf, ly) = TrayLayout::draw_and_create(self, tray, conf);
self.buffer.update_buffer(buf);
self.layout = ly;
}
}
pub fn draw(&mut self, tray: &Tray, conf: &TrayConfig) -> ImageSurface {
self.redraw_if_updated(tray, conf);
self.buffer.get_buffer()
}
}
impl TrayState {
pub fn on_mouse_event(&mut self, e: MouseEvent) -> bool {
use super::layout::HoveringItem;
let mut redraw = false;
match e {
MouseEvent::Release(pos, key) => {
let Some(hovering) = self.layout.get_hovering(pos) else {
return false;
};
if key == BTN_RIGHT {
// toggle state
let menuitem_id = match hovering {
HoveringItem::TrayIcon => {
self.is_open = !self.is_open;
Some(0)
}
HoveringItem::MenuItem(id) => {
if self.recalculate_open_id_chain(id) {
Some(id)
} else {
None
}
}
};
// send about to show request or else some menu won't appear
if let Some(id) = menuitem_id {
self.set_updated();
redraw = true;
self.menuitem_about_to_show(id);
}
} else if key == BTN_LEFT {
match hovering {
HoveringItem::TrayIcon => self.tray_clicked_req(),
HoveringItem::MenuItem(id) => self.menu_item_clicked_req(id),
}
}
}
MouseEvent::Enter(pos) | MouseEvent::Motion(pos) => {
let mut hover_id = -1;
if let Some(HoveringItem::MenuItem(id)) = self.layout.get_hovering(pos) {
hover_id = id;
}
if self.menu_state.set_hovering(hover_id) {
self.set_updated();
redraw = true
}
}
MouseEvent::Leave => {
if self.menu_state.set_hovering(-1) {
self.set_updated();
redraw = true
}
}
// ignore press
_ => {}
}
redraw
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/wrapbox/widgets/ring/draw.rs | crates/frontend/src/widgets/wrapbox/widgets/ring/draw.rs | use cairo::{Format, ImageSurface};
use config::widgets::wrapbox::ring::RingConfig;
use cosmic_text::{Color, FamilyOwned};
use util::color::cairo_set_color;
use util::draw::{draw_fan, new_surface};
use util::template::arg::{TemplateArgFloatParser, TEMPLATE_ARG_FLOAT};
use util::template::base::Template;
use util::text::{draw_text, TextConfig};
use util::Z;
use crate::animation::{calculate_transition, ToggleAnimationRc};
use crate::widgets::wrapbox::BoxTemporaryCtx;
use super::preset::RunnerResult;
#[derive(Debug)]
pub struct RingDrawer {
radius: i32,
ring_width: i32,
bg_color: Color,
fg_color: Color,
prefix: Option<Template>,
prefix_hide: bool,
suffix: Option<Template>,
suffix_hide: bool,
font_family: FamilyOwned,
font_size: i32,
pub animation: ToggleAnimationRc,
}
impl RingDrawer {
fn draw_ring(&self, progress: f64) -> ImageSurface {
let big_radius = self.radius as f64;
let small_radius = big_radius - self.ring_width as f64;
let size = self.radius * 2;
let surf = ImageSurface::create(Format::ARgb32, size, size).unwrap();
let ctx = cairo::Context::new(&surf).unwrap();
cairo_set_color(&ctx, self.bg_color);
draw_fan(&ctx, (big_radius, big_radius), big_radius, 0., 2.);
ctx.fill().unwrap();
cairo_set_color(&ctx, self.fg_color);
draw_fan(
&ctx,
(big_radius, big_radius),
big_radius,
-0.5,
progress * 2. - 0.5,
);
ctx.fill().unwrap();
ctx.set_operator(cairo::Operator::Clear);
draw_fan(&ctx, (big_radius, big_radius), small_radius, 0., 2.);
ctx.fill().unwrap();
surf
}
fn draw_text(
&self,
progress: f64,
preset_text: &str,
) -> (Option<ImageSurface>, Option<ImageSurface>) {
// let layout = self.make_layout();
let text_conf = TextConfig::new(
self.font_family.as_family(),
None,
self.fg_color,
self.font_size,
);
let template_func = |template: &Template| {
let text = template.parse(|parser| {
let text = match parser.name() {
TEMPLATE_ARG_FLOAT => {
let parser = parser.downcast_ref::<TemplateArgFloatParser>().unwrap();
parser.parse(progress)
}
util::template::arg::TEMPLATE_ARG_RING_PRESET => preset_text.to_string(),
_ => unreachable!(),
};
text
});
draw_text(&text, text_conf).to_image_surface()
};
let prefix = self.prefix.as_ref().map(template_func);
let suffix = self.suffix.as_ref().map(template_func);
(prefix, suffix)
}
pub fn merge(
&self,
ring: ImageSurface,
prefix: Option<ImageSurface>,
suffix: Option<ImageSurface>,
) -> ImageSurface {
let y = self.animation.borrow_mut().progress();
let mut size = (self.radius * 2, self.radius * 2);
let mut v = [None, None];
if let Some(img) = prefix {
let img_size = (img.width(), img.height());
if self.prefix_hide {
let visible_text_width =
calculate_transition(y, (0., img_size.0 as f64)).ceil() as i32;
v[0] = Some((img, visible_text_width, img_size.1));
size.0 += visible_text_width;
size.1 = size.1.max(img_size.1);
} else {
v[0] = Some((img, img_size.0, img_size.1));
size.0 += img_size.0;
size.1 = size.1.max(img_size.1);
}
}
if let Some(img) = suffix {
let img_size = (img.width(), img.height());
if self.suffix_hide {
let visible_text_width =
calculate_transition(y, (0., img_size.0 as f64)).ceil() as i32;
v[1] = Some((img, visible_text_width, img_size.1));
size.0 += visible_text_width;
size.1 = size.1.max(img_size.1);
} else {
v[1] = Some((img, img_size.0, img_size.1));
size.0 += img_size.1;
size.1 = size.1.max(img_size.1);
}
}
let surf = new_surface(size);
let ctx = cairo::Context::new(&surf).unwrap();
if let Some((img, width, height)) = &v[0] {
let h = ((size.1 as f64 - *height as f64) / 2.).floor();
ctx.set_source_surface(img, Z, h).unwrap();
ctx.rectangle(Z, h, *width as f64, *height as f64);
ctx.fill().unwrap();
ctx.translate(*width as f64, Z);
}
let h = (size.1 - self.radius * 2) as f64 / 2.;
ctx.set_source_surface(ring, Z, h).unwrap();
ctx.paint().unwrap();
ctx.translate((self.radius * 2) as f64, Z);
if let Some((img, _, height)) = &v[1] {
let h = (size.1 as f64 - *height as f64) / 2.;
ctx.set_source_surface(img, Z, h.floor()).unwrap();
ctx.paint().unwrap();
}
surf
}
pub fn draw(&self, data: &RunnerResult) -> ImageSurface {
let ring = self.draw_ring(data.progress);
let (prefix, suffix) = self.draw_text(data.progress, &data.preset_text);
self.merge(ring, prefix, suffix)
}
pub fn new(box_temp_ctx: &mut BoxTemporaryCtx, config: &mut RingConfig) -> Self {
let radius = config.radius;
let ring_width = config.ring_width;
let bg_color = config.bg_color;
let fg_color = config.fg_color;
let font_family = config.font_family.clone();
let font_size = config.font_size;
let prefix = config.prefix.take();
let suffix = config.suffix.take();
let prefix_hide = config.prefix_hide;
let suffix_hide = config.suffix_hide;
let animation =
box_temp_ctx.new_animation(config.text_transition_ms, config.animation_curve);
Self {
radius,
fg_color,
font_size,
prefix,
suffix,
ring_width,
bg_color,
prefix_hide,
suffix_hide,
font_family,
animation,
}
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/wrapbox/widgets/ring/preset.rs | crates/frontend/src/widgets/wrapbox/widgets/ring/preset.rs | use calloop::channel::Sender;
use interval_task::runner::Runner;
use std::time::Duration;
use backend::system::{get_battery_info, get_cpu_info, get_disk_info, get_ram_info, get_swap_info};
use config::widgets::wrapbox::ring::RingPreset;
use util::shell::shell_cmd;
#[allow(dead_code)]
fn from_kb(total: u64, avaibale: u64) -> (f64, f64, &'static str) {
let mut c = 0;
let mut total = total as f64;
let mut avaibale = avaibale as f64;
while total > 1000. && c < 4 {
total /= 1000.;
avaibale /= 1000.;
c += 1;
}
let surfix = match c {
0 => "bytes",
1 => "KB",
2 => "MB",
3 => "GB",
4 => "TB",
_ => unreachable!(),
};
(total, avaibale, surfix)
}
fn from_kib(total: u64, avaibale: u64) -> (f64, f64, &'static str) {
let mut c = 0;
let mut total = total as f64;
let mut avaibale = avaibale as f64;
while total > 1024. && c < 4 {
total /= 1024.;
avaibale /= 1024.;
c += 1;
}
let surfix = match c {
0 => "bytes",
1 => "KiB",
2 => "MiB",
3 => "GiB",
4 => "TiB",
_ => unreachable!(),
};
(total, avaibale, surfix)
}
macro_rules! new_runner {
($time:expr, $s:expr, $f:expr) => {
interval_task::runner::new_runner(
Duration::from_millis($time),
|| (),
move |_| {
$s.send($f()).unwrap();
false
},
)
};
}
fn ram(s: Sender<RunnerResult>, update_interval: u64) -> Runner<()> {
let f = || {
let info = get_ram_info();
let (total, used, surfix) = from_kib(info.total, info.used);
let progress = used / total;
let preset_text = format!(
"{:.2}{surfix} / {:.2}{surfix} [{:.2}%]",
used,
total,
progress * 100.
);
RunnerResult {
progress,
preset_text,
}
};
new_runner!(update_interval, s, f)
}
fn swap(s: Sender<RunnerResult>, update_interval: u64) -> Runner<()> {
let f = || {
let info = get_swap_info();
let (total, used, surfix) = from_kib(info.total, info.used);
let progress = used / total;
let preset_text = format!(
"{:.2}{surfix} / {:.2}{surfix} [{:.2}%]",
used,
total,
progress * 100.
);
RunnerResult {
progress,
preset_text,
}
};
new_runner!(update_interval, s, f)
}
fn cpu(s: Sender<RunnerResult>, update_interval: u64, core: Option<usize>) -> Runner<()> {
let f = move || {
let progress = get_cpu_info(core);
let text = format!("{:.2}%", progress * 100.);
RunnerResult {
progress,
preset_text: text,
}
};
new_runner!(update_interval, s, f)
}
fn battery(s: Sender<RunnerResult>, update_interval: u64) -> Runner<()> {
let f = || {
let (progress, state) = get_battery_info();
let preset_text = format!("{:.2}% {state:?}", progress * 100.);
RunnerResult {
progress,
preset_text,
}
};
new_runner!(update_interval, s, f)
}
fn disk(s: Sender<RunnerResult>, update_interval: u64, partition: String) -> Runner<()> {
let f = move || {
let info = get_disk_info(&partition);
let (total, used, surfix) = from_kib(info.total, info.used);
let progress = used / total;
let preset_text = format!(
"[Partition: {}] {:.2}{surfix} / {:.2}{surfix} [{:.2}%]",
partition,
used,
total,
progress * 100.
);
RunnerResult {
progress,
preset_text,
}
};
new_runner!(update_interval, s, f)
}
fn custom(s: Sender<RunnerResult>, update_interval: u64, cmd: String) -> Runner<()> {
let f = move || {
let Ok(progress) = shell_cmd(&cmd) else {
return RunnerResult::default();
};
let progress = progress.trim().parse().unwrap_or(0.);
RunnerResult {
progress,
preset_text: String::default(),
}
};
new_runner!(update_interval, s, f)
}
#[derive(Default, Debug)]
pub struct RunnerResult {
pub progress: f64,
pub preset_text: String,
}
pub fn parse_preset(preset: RingPreset, s: Sender<RunnerResult>) -> Runner<()> {
match preset {
RingPreset::Ram { update_interval } => ram(s, update_interval),
RingPreset::Swap { update_interval } => swap(s, update_interval),
RingPreset::Cpu {
update_interval,
core,
} => cpu(s, update_interval, core),
RingPreset::Battery { update_interval } => battery(s, update_interval),
RingPreset::Disk {
update_interval,
partition,
} => disk(s, update_interval, partition),
RingPreset::Custom {
update_interval,
cmd,
} => custom(s, update_interval, cmd),
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/wrapbox/widgets/ring/mod.rs | crates/frontend/src/widgets/wrapbox/widgets/ring/mod.rs | mod draw;
mod preset;
use std::cell::UnsafeCell;
use std::rc::Rc;
use cairo::ImageSurface;
use config::shared::KeyEventMap;
use draw::RingDrawer;
use interval_task::runner::Runner;
use config::widgets::wrapbox::ring::RingConfig;
use preset::RunnerResult;
use crate::mouse_state::MouseEvent;
use crate::widgets::wrapbox::box_traits::BoxedWidget;
use crate::widgets::wrapbox::BoxTemporaryCtx;
#[derive(Debug)]
pub struct RingCtx {
#[allow(dead_code)]
runner: Runner<()>,
current: Rc<UnsafeCell<RunnerResult>>,
drawer: RingDrawer,
event_map: KeyEventMap,
}
impl BoxedWidget for RingCtx {
fn content(&mut self) -> ImageSurface {
let current = unsafe { self.current.get().as_ref().unwrap() };
self.drawer.draw(current)
}
fn on_mouse_event(&mut self, event: MouseEvent) -> bool {
match event {
MouseEvent::Enter(_) => {
self.drawer
.animation
.borrow_mut()
.set_direction(crate::animation::ToggleDirection::Forward);
true
}
MouseEvent::Leave => {
self.drawer
.animation
.borrow_mut()
.set_direction(crate::animation::ToggleDirection::Backward);
true
}
MouseEvent::Release(_, key) => {
self.event_map.call(key);
false
}
_ => false,
}
}
}
pub fn init_widget(box_temp_ctx: &mut BoxTemporaryCtx, mut conf: RingConfig) -> impl BoxedWidget {
let drawer = RingDrawer::new(box_temp_ctx, &mut conf);
// runner
let current = Rc::new(UnsafeCell::new(RunnerResult::default()));
let current_weak = Rc::downgrade(¤t);
let redraw_signal = box_temp_ctx.make_redraw_channel(move |_, msg| {
let Some(current) = current_weak.upgrade() else {
return;
};
unsafe { *current.get().as_mut().unwrap() = msg };
});
let mut runner = preset::parse_preset(conf.preset, redraw_signal);
runner.start().unwrap();
RingCtx {
runner,
current,
drawer,
event_map: conf.event_map,
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/wrapbox/widgets/text/draw.rs | crates/frontend/src/widgets/wrapbox/widgets/text/draw.rs | use cairo::ImageSurface;
use config::widgets::wrapbox::text::TextConfig;
use cosmic_text::{Color, FamilyOwned};
use util::text::draw_text;
#[derive(Debug)]
pub struct TextDrawer {
pub fg_color: Color,
pub font_family: FamilyOwned,
pub font_pixel_size: i32,
}
impl TextDrawer {
pub fn new(conf: &TextConfig) -> Self {
Self {
fg_color: conf.fg_color,
font_family: conf.font_family.clone(),
font_pixel_size: conf.font_size,
}
}
pub fn draw_text(&self, text: &str) -> ImageSurface {
let text_conf = util::text::TextConfig::new(
self.font_family.as_family(),
None,
self.fg_color,
self.font_pixel_size,
);
draw_text(text, text_conf).to_image_surface()
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/wrapbox/widgets/text/mod.rs | crates/frontend/src/widgets/wrapbox/widgets/text/mod.rs | mod draw;
use std::cell::UnsafeCell;
use std::{rc::Rc, time::Duration};
use cairo::ImageSurface;
use calloop::channel::Sender;
use chrono::{Local, Utc};
use config::shared::KeyEventMap;
use draw::TextDrawer;
use interval_task::runner::Runner;
use config::widgets::wrapbox::text::{TextConfig, TextPreset};
use util::shell::shell_cmd;
use super::super::box_traits::BoxedWidget;
use crate::widgets::wrapbox::BoxTemporaryCtx;
fn time_preset(
s: Sender<String>,
format: String,
time_zone: Option<String>,
update_interval: u64,
) -> Runner<()> {
let f = move || {
let time = time_zone
.as_ref()
.map_or(Local::now().naive_local(), |time_zone| {
use chrono::TimeZone;
let dt = Utc::now();
let tz = time_zone.parse::<chrono_tz::Tz>().unwrap();
tz.from_utc_datetime(&dt.naive_utc()).naive_local()
});
time.format(format.as_str()).to_string()
};
interval_task::runner::new_runner(
Duration::from_millis(update_interval),
|| (),
move |_| {
s.send(f()).unwrap();
false
},
)
}
fn custom_preset(s: Sender<String>, time: u64, cmd: String) -> Runner<()> {
// ignore fail
let f = move || shell_cmd(&cmd).unwrap_or_default();
interval_task::runner::new_runner(
Duration::from_millis(time),
|| (),
move |_| {
s.send(f()).unwrap();
false
},
)
}
fn match_preset(preset: TextPreset, s: Sender<String>) -> Runner<()> {
match preset {
TextPreset::Time {
format,
time_zone,
update_interval,
} => time_preset(s, format, time_zone, update_interval),
TextPreset::Custom {
update_interval,
cmd,
} => custom_preset(s, update_interval, cmd),
}
}
#[derive(Debug)]
pub struct TextCtx {
#[allow(dead_code)]
runner: Runner<()>,
text: Rc<UnsafeCell<String>>,
drawer: TextDrawer,
event_map: KeyEventMap,
}
impl BoxedWidget for TextCtx {
fn content(&mut self) -> ImageSurface {
let text = unsafe { self.text.get().as_ref().unwrap().as_str() };
self.drawer.draw_text(text)
}
fn on_mouse_event(&mut self, e: crate::mouse_state::MouseEvent) -> bool {
if let crate::mouse_state::MouseEvent::Release(_, k) = e {
self.event_map.call(k);
};
false
}
}
pub fn init_text(box_temp_ctx: &mut BoxTemporaryCtx, conf: TextConfig) -> impl BoxedWidget {
let drawer = TextDrawer::new(&conf);
let text = Rc::new(UnsafeCell::new(String::default()));
let text_weak = Rc::downgrade(&text);
let redraw_signal = box_temp_ctx.make_redraw_channel(move |_, msg| {
let Some(text) = text_weak.upgrade() else {
return;
};
unsafe { *text.get().as_mut().unwrap() = msg };
});
let mut runner = match_preset(conf.preset, redraw_signal);
runner.start().unwrap();
TextCtx {
runner,
text,
drawer,
event_map: conf.event_map,
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/wrapbox/outlook/board.rs | crates/frontend/src/widgets/wrapbox/outlook/board.rs | use cairo::ImageSurface;
use config::{
shared::NumOrRelative,
widgets::wrapbox::{OutlookBoardConfig, OutlookMargins},
};
use cosmic_text::Color;
use smithay_client_toolkit::shell::wlr_layer::Anchor;
use util::{
color::{cairo_set_color, color_mix},
draw::{draw_rect_path, new_surface},
};
use super::OutlookDraw;
#[derive(Debug)]
pub struct DrawConf {
margins: OutlookMargins,
color: Color,
border_radius: i32,
corners: [bool; 4],
}
impl DrawConf {
pub fn new(outlook: &OutlookBoardConfig, edge: Anchor, offset: NumOrRelative) -> Self {
let corners = match offset.is_zero() {
false => [true; 4],
true => match edge {
Anchor::LEFT => [false, true, true, false],
Anchor::RIGHT => [true, false, false, true],
Anchor::TOP => [false, false, true, true],
Anchor::BOTTOM => [true, true, false, false],
_ => unreachable!(),
},
};
Self {
margins: outlook.margins.clone(),
color: outlook.color,
border_radius: outlook.border_radius,
corners,
}
}
}
impl OutlookDraw for DrawConf {
fn translate_mouse_position(&self, pos: (f64, f64)) -> (f64, f64) {
// pos - border - margin
(
pos.0 - self.margins.left as f64,
pos.1 - self.margins.top as f64,
)
}
fn draw(&mut self, content: ImageSurface) -> ImageSurface {
let content_size = (content.width(), content.height());
let border_radius = self.border_radius as f64;
let corners = self.corners;
// calculate_info for later use
let total_size = (
self.margins.left + self.margins.right + content_size.0,
self.margins.top + self.margins.bottom + content_size.1,
);
// mix color of border color and shadow(black)
let box_color = color_mix(Color::rgba(0, 0, 0, 0x22), self.color);
// bg
let path = draw_rect_path(
border_radius,
(total_size.0 as f64, total_size.1 as f64),
corners,
)
.unwrap();
let surf = new_surface(total_size);
let ctx = cairo::Context::new(&surf).unwrap();
cairo_set_color(&ctx, box_color);
ctx.append_path(&path);
ctx.fill().unwrap();
ctx.set_source_surface(content, self.margins.left as f64, self.margins.top as f64)
.unwrap();
ctx.append_path(&path);
ctx.fill().unwrap();
surf
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/wrapbox/outlook/mod.rs | crates/frontend/src/widgets/wrapbox/outlook/mod.rs | use std::fmt::Debug;
use cairo::ImageSurface;
use config::{shared::NumOrRelative, widgets::wrapbox::Outlook};
use smithay_client_toolkit::shell::wlr_layer::Anchor;
mod board;
mod window;
pub fn init_outlook(outlook: &Outlook, edge: Anchor, offset: NumOrRelative) -> Box<dyn OutlookDraw> {
match outlook {
Outlook::Window(outlook_window_config) => {
Box::new(window::DrawConf::new(outlook_window_config, edge, offset))
}
Outlook::Board(outlook_board_config) => {
Box::new(board::DrawConf::new(outlook_board_config, edge, offset))
}
}
}
pub trait OutlookDraw: Debug {
fn draw(&mut self, content: ImageSurface) -> ImageSurface;
fn translate_mouse_position(&self, pos: (f64, f64)) -> (f64, f64);
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/wrapbox/outlook/window.rs | crates/frontend/src/widgets/wrapbox/outlook/window.rs | use cairo::ImageSurface;
use config::{shared::NumOrRelative, widgets::wrapbox::{OutlookMargins, OutlookWindowConfig}};
use cosmic_text::Color;
use smithay_client_toolkit::shell::wlr_layer::Anchor;
use util::{
color::{cairo_set_color, color_mix},
draw::{draw_rect_path, new_surface},
Z,
};
use super::OutlookDraw;
#[derive(Debug)]
pub struct DrawConf {
margins: OutlookMargins,
color: Color,
border_radius: i32,
border_width: i32,
corners: [bool; 4],
}
impl DrawConf {
pub fn new(outlook: &OutlookWindowConfig, edge: Anchor, offset: NumOrRelative) -> Self {
let corners = match offset.is_zero() {
false => [true; 4],
true => match edge {
Anchor::LEFT => [false, true, true, false],
Anchor::RIGHT => [true, false, false, true],
Anchor::TOP => [false, false, true, true],
Anchor::BOTTOM => [true, true, false, false],
_ => unreachable!(),
},
};
Self {
margins: outlook.margins.clone(),
color: outlook.color,
border_radius: outlook.border_radius,
border_width: outlook.border_width,
corners,
}
}
}
impl OutlookDraw for DrawConf {
fn draw(&mut self, content: ImageSurface) -> ImageSurface {
let base = draw_base(self, (content.width(), content.height()));
let surf = new_surface((base.bg.width(), base.bg.height()));
let ctx = cairo::Context::new(&surf).unwrap();
ctx.set_source_surface(base.bg, Z, Z).unwrap();
ctx.paint().unwrap();
ctx.save().unwrap();
ctx.translate(
(self.border_width + self.margins.left) as f64,
(self.border_width + self.margins.top) as f64,
);
ctx.set_source_surface(&content, Z, Z).unwrap();
ctx.paint().unwrap();
ctx.restore().unwrap();
ctx.set_source_surface(base.border_with_shadow, Z, Z)
.unwrap();
ctx.paint().unwrap();
surf
}
fn translate_mouse_position(&self, pos: (f64, f64)) -> (f64, f64) {
// pos - border - margin
(
pos.0 - self.border_width as f64 - self.margins.left as f64,
pos.1 - self.border_width as f64 - self.margins.top as f64,
)
}
}
struct DrawBase {
bg: ImageSurface,
border_with_shadow: ImageSurface,
}
fn draw_base(conf: &DrawConf, content_size: (i32, i32)) -> DrawBase {
let border_radius = conf.border_radius as f64;
let corners = conf.corners;
// calculate_info for later use
let content_box_size = (
conf.margins.left + conf.margins.right + content_size.0,
conf.margins.top + conf.margins.bottom + content_size.1,
);
let total_size = (
content_box_size.0 + conf.border_width * 2,
content_box_size.1 + conf.border_width * 2,
);
// make float var for later use
let f_content_box_size = (content_box_size.0 as f64, content_box_size.1 as f64);
let f_total_size = (total_size.0 as f64, total_size.1 as f64);
// mix color of border color and shadow(black)
let box_color = color_mix(Color::rgba(0, 0, 0, 0x22), conf.color);
// bg
let (bg_path, bg) = {
let path = draw_rect_path(border_radius, f_total_size, corners).unwrap();
let surf = new_surface(total_size);
let ctx = cairo::Context::new(&surf).unwrap();
cairo_set_color(&ctx, box_color);
ctx.append_path(&path);
ctx.fill().unwrap();
(path, surf)
};
// shadow
let shadow_surf = {
fn inside_grandient(p: [f64; 4], color: [f64; 3]) -> cairo::LinearGradient {
let [r, g, b] = color;
let t = cairo::LinearGradient::new(p[0], p[1], p[2], p[3]);
t.add_color_stop_rgba(0., r, g, b, 0.4);
t.add_color_stop_rgba(0.3, r, g, b, 0.1);
t.add_color_stop_rgba(1., r, g, b, 0.);
t
}
let surf = new_surface(content_box_size);
let ctx = cairo::Context::new(&surf).unwrap();
let g = |p: [f64; 4], c: [f64; 3]| {
let t = inside_grandient(p, c);
ctx.set_source(t).unwrap();
ctx.paint().unwrap();
};
let shadow_size = 10.0_f64.min(f_content_box_size.0 * 0.3);
let color = [Z, Z, Z];
// left, top, right, bottom
g([Z, Z, shadow_size, Z], color);
g([Z, Z, Z, shadow_size], color);
g(
[
f_content_box_size.0,
Z,
f_content_box_size.0 - shadow_size,
Z,
],
color,
);
g(
[
Z,
f_content_box_size.1,
Z,
f_content_box_size.1 - shadow_size,
],
color,
);
surf
};
// border
let border_surf = {
let surf = new_surface(total_size);
let ctx = cairo::Context::new(&surf).unwrap();
cairo_set_color(&ctx, conf.color);
ctx.append_path(&bg_path);
ctx.fill().unwrap();
ctx.set_operator(cairo::Operator::Clear);
let path =
draw_rect_path(border_radius, f_content_box_size, [true, true, true, true]).unwrap();
ctx.translate(conf.border_width as f64, conf.border_width as f64);
ctx.append_path(&path);
ctx.fill().unwrap();
surf
};
// combine border and shadow
let border_with_shadow = {
let surf = new_surface(total_size);
let ctx = cairo::Context::new(&surf).unwrap();
ctx.save().unwrap();
ctx.translate(conf.border_width as f64, conf.border_width as f64);
ctx.set_source_surface(shadow_surf, Z, Z).unwrap();
ctx.paint().unwrap();
ctx.restore().unwrap();
ctx.set_source_surface(border_surf, Z, Z).unwrap();
ctx.paint().unwrap();
surf
};
DrawBase {
bg,
border_with_shadow,
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/wrapbox/grid/builder.rs | crates/frontend/src/widgets/wrapbox/grid/builder.rs | use config::widgets::wrapbox::{Align, AlignFunc};
use super::{item::GridItemMap, GridBox};
pub struct GrideBoxBuilder<T> {
ws: Vec<Vec<Option<T>>>,
row_col_num: (usize, usize),
}
impl<T> GrideBoxBuilder<T> {
pub fn new() -> Self {
Self {
ws: vec![],
row_col_num: (0, 0),
}
}
pub fn add(&mut self, w: T, position: (isize, isize)) -> (usize, usize) {
let mut pos = (0, 0);
// row index
pos.0 = if position.0 == -1 {
self.row_col_num.0
} else if position.0 >= 0 {
position.0 as usize
} else {
panic!("position must be positive or -1");
};
// col index
pos.1 = if position.1 == -1 {
self.row_col_num.1
} else if position.1 >= 0 {
position.1 as usize
} else {
panic!("position must be positive or -1");
};
// self.size_change_map.insert(pos, w.get_size());
macro_rules! ensure_vec {
($vec:expr, $need_size:expr, $update_len:expr, $val:expr) => {
if $need_size > $vec.len() {
$vec.resize_with($need_size, || $val);
$update_len = $vec.len()
}
};
}
// create row if not enough
let vec = &mut self.ws;
ensure_vec!(vec, pos.0 + 1, self.row_col_num.0, vec![]);
// create col if not enough
let vec = &mut self.ws[pos.0];
ensure_vec!(vec, pos.1 + 1, self.row_col_num.1, None);
vec[pos.1] = Some(w);
pos
}
pub fn build(self, gap: f64, align: Align) -> GridBox<T> {
let align_func: AlignFunc = align.to_func();
let mut items = vec![];
let mut row_index = vec![];
let mut index = 0;
let mut max_col = 0;
// filter the emptys
for row in self.ws.into_iter() {
let mut col_index = 0;
for widget in row.into_iter().flatten() {
col_index += 1;
items.push(widget);
}
if col_index > 0 {
row_index.push(index);
max_col = max_col.max(col_index);
index += col_index;
}
}
let row_col_num = (row_index.len(), max_col);
let grid_item_map = GridItemMap { items, row_index };
GridBox {
item_map: grid_item_map,
row_col_num,
gap,
align_func,
position_map: None,
}
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/wrapbox/grid/mod.rs | crates/frontend/src/widgets/wrapbox/grid/mod.rs | pub mod builder;
pub mod item;
use cairo::{self, Format, ImageSurface};
use config::widgets::wrapbox::{Align, AlignFunc};
use item::GridItemMap;
use util::binary_search_within_range;
#[derive(Debug)]
pub struct GridPositionMap {
// use i32 to save memory
total_size: (i32, i32),
grid_cell_position_map: [Vec<[i32; 2]>; 2],
widget_start_point_list: Vec<(f64, f64)>,
}
impl GridPositionMap {
pub fn match_item<'a, T>(
&self,
pos: (f64, f64),
item_map: &'a item::GridItemMap<T>,
) -> Option<(&'a T, (f64, f64))> {
if pos.0 < 0.
|| pos.1 < 0.
|| pos.0 > self.total_size.0 as f64
|| pos.1 > self.total_size.1 as f64
{
return None;
}
let which_row = binary_search_within_range(&self.grid_cell_position_map[0], pos.1 as i32);
let which_col = binary_search_within_range(&self.grid_cell_position_map[1], pos.0 as i32);
if which_row == -1 || which_col == -1 {
return None;
}
let widget_index = item_map.row_index[which_row as usize] + which_col as usize;
let start_point = self.widget_start_point_list.get(widget_index)?;
let new_position = (pos.0 - start_point.0, pos.1 - start_point.1);
let widget = &item_map.items[widget_index];
Some((widget, new_position))
}
}
#[derive(Debug)]
pub struct GridBox<T> {
pub position_map: Option<GridPositionMap>,
pub item_map: GridItemMap<T>,
pub row_col_num: (usize, usize),
pub gap: f64,
pub align_func: AlignFunc,
}
impl<T> GridBox<T> {
pub fn new(gap: f64, align: Align) -> Self {
Self {
item_map: GridItemMap::default(),
row_col_num: (0, 0),
gap,
align_func: align.to_func(),
position_map: None,
}
}
pub fn match_item(&self, pos: (f64, f64)) -> Option<(&T, (f64, f64))> {
self.position_map
.as_ref()
.and_then(|position_map| position_map.match_item(pos, &self.item_map))
}
pub fn draw<F: FnMut(&mut T) -> ImageSurface>(&mut self, draw_func: F) -> ImageSurface {
if self.item_map.row_index.is_empty() {
return ImageSurface::create(Format::ARgb32, 0, 0).unwrap();
}
let contents: Vec<ImageSurface> = self.item_map.items.iter_mut().map(draw_func).collect();
let (grid_block_size_map, widget_render_map) = {
let mut grid_block_size_map = [
// height of each row
vec![0.; self.row_col_num.0],
// width of each col
vec![0.; self.row_col_num.1],
];
let mut widget_render_map =
vec![Vec::with_capacity(self.row_col_num.1); self.row_col_num.0];
let mut which_row = 0;
let mut next_row = which_row + 1;
let max_row = self.item_map.row_index.len() - 1;
contents
.into_iter()
.enumerate()
.for_each(|(widget_index, content)| {
// ensure in the correct row
if which_row != max_row {
// if reaches next row
if widget_index == self.item_map.row_index[next_row] {
which_row = next_row;
next_row += 1;
}
}
// calculate col index
let current_row_start_index = self.item_map.row_index[which_row];
let which_col = widget_index - current_row_start_index;
// calculate size
let widget_content_size = (content.width() as f64, content.height() as f64);
// max height for each row
let height: &mut f64 = &mut grid_block_size_map[0][which_row];
*height = height.max(widget_content_size.1);
// max width for each col
let width: &mut f64 = &mut grid_block_size_map[1][which_col];
*width = width.max(widget_content_size.0);
// put into render map
widget_render_map[which_row].push(content);
});
(grid_block_size_map, widget_render_map)
};
let total_size = {
#[inline]
fn join_size(v: &[f64], gap: f64) -> f64 {
let mut m = 0.;
for (i, s) in v.iter().enumerate() {
if i == 0 {
m += *s;
} else {
m += gap + *s;
}
}
m
}
(
join_size(&grid_block_size_map[1].clone(), self.gap).ceil() as i32,
join_size(&grid_block_size_map[0].clone(), self.gap).ceil() as i32,
)
};
let surf = ImageSurface::create(Format::ARgb32, total_size.0, total_size.1).unwrap();
let ctx = cairo::Context::new(&surf).unwrap();
let mut widget_start_point_list: Vec<(f64, f64)> = vec![];
let mut position_y = 0.;
for (which_row, row) in widget_render_map.into_iter().enumerate() {
let mut position_x = 0.;
let max_col = row.len() - 1;
for (which_col, surf) in row.into_iter().enumerate() {
let content_size = (surf.width() as f64, surf.height() as f64);
// calculate start position considering align
let mut pos = (self.align_func)(
(position_x, position_y),
// grid cell size
(
grid_block_size_map[1][which_col],
grid_block_size_map[0][which_row],
),
content_size,
);
pos.0 = pos.0.floor();
pos.1 = pos.1.floor();
// push widget's start point
widget_start_point_list.push(pos);
// draw
ctx.set_source_surface(surf, pos.0, pos.1).unwrap();
ctx.paint().unwrap();
// add position x
if which_col < max_col {
position_x += grid_block_size_map[1][which_col] + self.gap;
}
}
position_y += grid_block_size_map[0][which_row] + self.gap;
}
let grid_cell_position_map = {
let mut grid_cell_position_map: [Vec<[i32; 2]>; 2] = [
// y position range(height) of each row
vec![[0, 0]; self.row_col_num.0],
// x position range(width) of each col
vec![[0, 0]; self.row_col_num.1],
];
macro_rules! calculate_grid_cell_position_map {
($size_map:expr, $position_map:expr, $gap:expr) => {
let mut pos = 0;
$size_map.iter().enumerate().for_each(|(i, size)| {
let end = pos + *size as i32;
$position_map[i] = [pos, end];
pos = end + $gap as i32;
});
};
}
calculate_grid_cell_position_map!(
grid_block_size_map[0],
grid_cell_position_map[0],
self.gap
);
calculate_grid_cell_position_map!(
grid_block_size_map[1],
grid_cell_position_map[1],
self.gap
);
grid_cell_position_map
};
self.position_map = Some(GridPositionMap {
total_size,
grid_cell_position_map,
widget_start_point_list,
});
surf
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/widgets/wrapbox/grid/item.rs | crates/frontend/src/widgets/wrapbox/grid/item.rs | use core::fmt::Debug;
#[derive(Debug)]
pub struct GridItemMap<T> {
pub items: Vec<T>,
// record each row start index in `items`
pub row_index: Vec<usize>,
}
impl<T> Default for GridItemMap<T> {
fn default() -> Self {
Self {
items: Vec::default(),
row_index: Vec::default(),
}
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/wayland/app.rs | crates/frontend/src/wayland/app.rs | use std::{
collections::HashMap,
mem,
rc::Rc,
sync::{atomic::AtomicPtr, Arc, Mutex, Weak},
time::Duration,
};
use backend::ipc::IPCCommand;
use calloop::{
channel::Sender,
ping::{make_ping, Ping},
Idle, LoopHandle, LoopSignal,
};
use config::{common::MonitorSpecifier, shared::Curve};
use smithay_client_toolkit::{
compositor::{CompositorState, SurfaceData as SctkSurfaceData, SurfaceDataExt},
output::OutputState,
reexports::protocols::wp::{
fractional_scale::v1::client::{
wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1,
wp_fractional_scale_v1::WpFractionalScaleV1,
},
viewporter::client::{wp_viewport::WpViewport, wp_viewporter::WpViewporter},
},
registry::{GlobalProxy, RegistryState},
seat::{pointer::PointerEvent, SeatState},
shell::{
wlr_layer::{LayerShell, LayerSurface},
WaylandSurface,
},
shm::{slot::SlotPool, Shm},
};
use wayland_client::{
protocol::{wl_output::WlOutput, wl_pointer, wl_surface::WlSurface},
Proxy, QueueHandle,
};
use crate::{
animation::{AnimationList, ToggleAnimation, ToggleAnimationRc},
buffer::Buffer,
mouse_state::{MouseEvent, MouseState},
widgets::{init_widget, WidgetContext},
};
use super::{draw::DrawCore, window_pop_state::WindowPopState};
pub struct App {
pub exit: bool,
pub show_mouse_key: bool,
pub widget_map: WidgetMap,
pub queue_handle: QueueHandle<App>,
pub event_loop_handle: LoopHandle<'static, App>,
pub signal: LoopSignal,
pub compositor_state: CompositorState,
pub registry_state: RegistryState,
pub output_state: OutputState,
pub seat_state: SeatState,
pub fractional_manager: GlobalProxy<WpFractionalScaleManagerV1>,
pub viewporter_manager: GlobalProxy<WpViewporter>,
pub pointer: Option<wl_pointer::WlPointer>,
pub shell: LayerShell,
pub shm: Shm,
pub pool: SlotPool,
// if the the outputs get updated before we first initialize widgets, do not call reload
pub(crate) first_time_initialized: bool,
pub(crate) reload_guard: Option<Idle<'static>>,
}
impl App {
pub fn handle_ipc(&mut self, cmd: IPCCommand) {
match cmd {
IPCCommand::TogglePin(wn) => self.toggle_pin(&wn),
IPCCommand::Exit => self.exit = true,
IPCCommand::Reload => self.reload(),
};
}
fn toggle_pin(&mut self, name: &str) {
for w in self.widget_map.get_widgets(name) {
w.lock().unwrap().toggle_pin(self)
}
}
fn reload_widgets(&mut self) {
// clear contents of old widgets
let ws = mem::take(&mut self.widget_map.0)
.into_values()
.flatten()
.collect::<Vec<_>>();
ws.into_iter().for_each(|arc| {
// we make sure that no other references exist
// tipically this should be Some() since this function is called in idle
// and the backend or any other threads shall not hold references to widgets
let mtx = Arc::into_inner(arc).unwrap();
// and tipically this should be Ok() since no other references should exist
match mtx.into_inner() {
Ok(mut w) => w.clear_contents(self),
Err(e) => {
log::error!(
"Failed to clear widget contents during reload, mutex of this widget is poisoned: {e}"
);
}
}
});
// create new
self.widget_map = config::get_config_root()
.and_then(|c| WidgetMap::new(c.widgets.clone(), self))
.unwrap_or_else(|e| {
log::error!("Failed to load widgets: {e}");
WidgetMap(HashMap::new())
});
}
pub fn reload(&mut self) {
log::info!("Reloading widgets...");
self.first_time_initialized = true;
let idle = self.event_loop_handle.insert_idle(App::reload_widgets);
if let Some(old) = self.reload_guard.replace(idle) {
old.cancel()
}
}
}
// the states from `App` that are needed when building widgets
pub struct WidgetBuildingStates<'a> {
pub event_loop_handle: &'a LoopHandle<'static, App>,
pub output_state: &'a OutputState,
}
#[derive(Debug, Default)]
pub struct WidgetMap(HashMap<String, Vec<Arc<Mutex<Widget>>>>);
impl WidgetMap {
fn new(widgets_config: Vec<config::Widget>, app: &App) -> Result<Self, String> {
let mut map: HashMap<String, Vec<Arc<Mutex<Widget>>>> = HashMap::new();
for conf in widgets_config.iter().cloned() {
let name = conf.common.namespace.clone();
let confs: Vec<(config::Widget, WlOutput)> = match conf.common.monitor.clone() {
MonitorSpecifier::ID(index) => app
.output_state
.outputs()
.nth(index)
.map(|output| vec![(conf, output)])
.unwrap_or(vec![]),
MonitorSpecifier::Names(items) => app
.output_state
.outputs()
.filter_map(|out| {
app.output_state
.info(&out)
.and_then(|info| info.name)
.filter(|output_name| items.contains(output_name))
.is_some()
.then(|| (conf.clone(), out))
})
.collect(),
MonitorSpecifier::All => app
.output_state
.outputs()
.map(|out| (conf.clone(), out))
.collect(),
_ => unreachable!(),
};
for (conf, output) in confs.into_iter() {
let ctx = Widget::init_widget(conf, output, app)?;
// TODO: CLONE
map.entry(name.clone()).or_default().push(ctx.clone());
}
}
Ok(Self(map))
}
fn get_widgets(&self, name: &str) -> Vec<Arc<Mutex<Widget>>> {
self.0.get(name).cloned().unwrap_or_default()
}
}
#[derive(Debug)]
pub struct Widget {
pub monitor: MonitorSpecifier,
pub configured: bool,
pub output: WlOutput,
pub layer: LayerSurface,
pub scale: Scale,
pub mouse_state: MouseState,
pub window_pop_state: WindowPopState,
pub start_pos: (i32, i32),
pub w: Box<dyn WidgetContext>,
pub buffer: Buffer,
pub content_width: i32,
pub content_height: i32,
pub draw_core: DrawCore,
pub pop_animation: ToggleAnimationRc,
pub animation_list: AnimationList,
pop_animation_finished: bool,
widget_animation_finished: bool,
widget_has_update: bool,
next_frame: bool,
frame_available: bool,
offset: i32,
margins: [i32; 4],
// for damage
output_size: (i32, i32),
}
impl Widget {
fn call_frame(&mut self, qh: &QueueHandle<App>) {
self.frame_available = false;
self.layer
.wl_surface()
.frame(qh, self.layer.wl_surface().clone());
}
pub fn on_frame_callback(&mut self, app: &mut App) {
if self.has_animation_update() || self.next_frame {
self.draw(app);
} else {
self.frame_available = true;
}
}
fn on_widget_update(&mut self, app: &mut App) {
self.widget_has_update = true;
self.try_redraw(app);
}
fn try_redraw(&mut self, app: &mut App) {
if !self.configured {
return;
}
if self.frame_available {
self.draw(app)
} else {
self.next_frame = true;
}
}
fn has_animation_update(&mut self) -> bool {
let widget_has_animation_update = self.animation_list.has_in_progress();
let pop_animation_update = self.pop_animation.borrow().is_in_progress();
widget_has_animation_update
|| !self.widget_animation_finished
|| pop_animation_update
|| !self.pop_animation_finished
}
fn prepare_content(&mut self) {
self.animation_list.refresh();
self.pop_animation.borrow_mut().refresh();
if self.pop_animation.borrow().is_in_progress() {
if self.pop_animation_finished {
self.pop_animation_finished = false
}
} else if !self.pop_animation_finished {
self.pop_animation_finished = true;
}
let widget_has_animation_update = if self.animation_list.has_in_progress() {
if self.widget_animation_finished {
self.widget_animation_finished = false
}
true
} else if !self.widget_animation_finished {
self.widget_animation_finished = true;
true
} else {
false
};
// update content
if self.widget_has_update || widget_has_animation_update {
self.widget_has_update = false;
let img = self.w.redraw();
self.content_width = img.width();
self.content_height = img.height();
self.buffer.update_buffer(img);
}
}
pub fn draw(&mut self, app: &mut App) {
if self.next_frame {
self.next_frame = false
}
self.prepare_content();
let progress = self.pop_animation.borrow_mut().progress();
let coordinate = self.draw_core.calc_coordinate(
(self.content_width, self.content_height),
self.offset,
progress,
);
self.start_pos = (coordinate[0], coordinate[1]);
let width = coordinate[2];
let height = coordinate[3];
// create and draw content
let (buffer, canvas) = app
.pool
.create_buffer(
width,
height,
width * 4,
wayland_client::protocol::wl_shm::Format::Argb8888,
)
.unwrap();
buffer
.attach_to(self.layer.wl_surface())
.expect("buffer attach");
// clear old buffer*
canvas.fill(0);
// copy with transition
let buffer = self.buffer.get_buffer();
buffer
.with_data(|data| {
util::draw::copy_pixmap(
data,
buffer.width() as usize,
buffer.height() as usize,
canvas,
width as usize,
height as usize,
coordinate[0] as isize,
coordinate[1] as isize,
);
})
.unwrap();
// attach content
self.layer
.wl_surface()
.damage_buffer(0, 0, self.output_size.0, self.output_size.1);
// set size
let (w, h) = self.scale.calculate_size(width as u32, height as u32);
self.layer.set_size(w, h);
self.call_frame(&app.queue_handle);
self.layer.commit();
}
fn toggle_pin(&mut self, app: &mut App) {
self.window_pop_state
.toggle_pin(self.mouse_state.is_hovering());
self.try_redraw(app);
}
pub fn update_normal(&mut self, normal: u32, app: &mut App) {
// IGNORING NORMAL SCALE IF FRACTIONAL SCALE IS AVAILABLE
if self.scale.is_fractional() {
return;
}
if self.scale.update_normal(normal) {
self.try_redraw(app);
}
let margins = self.scale.calculate_margin(self.margins);
self.layer
.set_margin(margins[0], margins[1], margins[2], margins[3]);
}
pub fn update_fraction(&mut self, fraction: u32, app: &mut App) {
if self.scale.update_fraction(fraction) {
self.try_redraw(app);
}
let margins = self.scale.calculate_margin(self.margins);
self.layer
.set_margin(margins[0], margins[1], margins[2], margins[3]);
}
pub fn on_mouse_event(&mut self, app: &mut App, event: &PointerEvent) {
let Some(mut event) = self.mouse_state.from_wl_pointer(event) else {
return;
};
let data = &mut self.mouse_state.data;
let mut trigger_redraw = false;
let mut do_redraw = || {
if !trigger_redraw {
trigger_redraw = true;
}
};
match &mut event {
MouseEvent::Release(pos, _)
| MouseEvent::Press(pos, _)
| MouseEvent::Enter(pos)
| MouseEvent::Motion(pos) => {
self.scale.calculate_pos(pos);
pos.0 -= self.start_pos.0 as f64;
pos.1 -= self.start_pos.1 as f64;
}
_ => {}
}
match event {
MouseEvent::Release(_, key) => {
if self
.window_pop_state
.toggle_pin_with_key(key, data.hovering)
{
do_redraw()
}
}
MouseEvent::Enter(_) => {
self.window_pop_state.enter();
do_redraw()
}
MouseEvent::Leave => {
self.window_pop_state.leave();
do_redraw()
}
MouseEvent::Motion(_) => self.window_pop_state.invalidate_pop(),
_ => {}
}
let widget_trigger_redraw = self.w.on_mouse_event(data, event);
if widget_trigger_redraw {
self.on_widget_update(app);
} else if trigger_redraw {
self.try_redraw(app);
}
}
fn init_widget(
conf: config::Widget,
wl_output: WlOutput,
app: &App,
) -> Result<Arc<Mutex<Self>>, String> {
let config::Widget { common, widget } = conf;
let mut builder = WidgetBuilder::new(common, wl_output, app)?;
let w = init_widget(widget, &mut builder);
let s = builder.build(w);
Ok(Arc::new_cyclic(|weak| {
SurfaceData::from_wl(s.layer.wl_surface()).store_widget(weak.clone());
Mutex::new(s)
}))
}
fn clear_contents(&mut self, app: &mut App) {
let (buffer, canvas) = app
.pool
.create_buffer(
1,
1,
1 * 4,
wayland_client::protocol::wl_shm::Format::Argb8888,
)
.unwrap();
buffer
.attach_to(self.layer.wl_surface())
.expect("buffer attach");
canvas.fill(0);
self.layer
.wl_surface()
.damage_buffer(0, 0, self.output_size.0, self.output_size.1);
self.call_frame(&app.queue_handle);
self.layer.commit();
}
}
#[derive(Debug)]
pub struct Scale {
normal: u32,
fractional: Option<(u32, WpFractionalScaleV1, WpViewport)>,
}
impl Scale {
fn new_fractional(fractional_client: WpFractionalScaleV1, viewprot: WpViewport) -> Self {
Self {
normal: 1,
fractional: Some((0, fractional_client, viewprot)),
}
}
fn new_normal() -> Self {
Self {
normal: 1,
fractional: None,
}
}
fn is_fractional(&self) -> bool {
self.fractional.is_some()
}
fn update_normal(&mut self, normal: u32) -> bool {
let changed = self.normal != normal;
self.normal = normal;
changed
}
fn update_fraction(&mut self, fraction: u32) -> bool {
if let Some(fractional) = self.fractional.as_mut() {
let changed = fractional.0 != fraction;
fractional.0 = fraction;
changed
} else {
false
}
}
fn calculate_size(&self, width: u32, height: u32) -> (u32, u32) {
if let Some(fractional) = self.fractional.as_ref() {
let mut scale = fractional.0;
if scale == 0 {
scale = 120
}
let size = (
((width * 120 + 60) / scale).max(1),
((height * 120 + 60) / scale).max(1),
);
// viewport
fractional.2.set_destination(size.0 as i32, size.1 as i32);
size
} else {
(width / self.normal, height / self.normal)
}
}
fn calculate_pos(&self, pos: &mut (f64, f64)) {
if let Some(fractional) = self.fractional.as_ref() {
let mut scale = fractional.0;
if scale == 0 {
scale = 120
}
let scale_f64 = scale as f64 / 120.;
pos.0 *= scale_f64;
pos.1 *= scale_f64;
} else {
pos.0 *= self.normal as f64;
pos.1 *= self.normal as f64;
}
}
fn calculate_margin(&self, margins: [i32; 4]) -> [i32; 4] {
let c = |m: i32| {
(if let Some(fractional) = self.fractional.as_ref() {
let mut scale = fractional.0;
if scale == 0 {
scale = 120
}
(m as u32 * 120 + 60) / scale
} else {
m as u32 / self.normal
}) as i32
};
[c(margins[0]), c(margins[1]), c(margins[2]), c(margins[3])]
}
}
impl Drop for Scale {
fn drop(&mut self) {
#[allow(clippy::option_map_unit_fn)]
self.fractional.as_ref().map(|(_, f, v)| {
f.destroy();
v.destroy();
});
}
}
macro_rules! widget_from_layer {
($w:ident, $layer:expr) => {
let Some($w) = SurfaceData::from_wl($layer.wl_surface()).get_widget() else {
return;
};
};
($w:ident, $layer:expr, $ret:expr) => {
let Some($w) = SurfaceData::from_wl($layer.wl_surface()).get_widget() else {
return $ret;
};
};
}
struct PopEssential {
pop_duration: Duration,
layer: LayerSurface,
}
impl PopEssential {
fn pop(&self, app: &mut App) {
// pop up
let guard_weak = {
widget_from_layer!(w, self.layer);
let mut wg = w.lock().unwrap();
let state = &mut wg.window_pop_state;
state.enter();
let guard = Rc::new(());
let guard_weak = Rc::downgrade(&guard);
state.pop_state.replace(guard);
wg.try_redraw(app);
guard_weak
};
// hide
let layer = self.layer.clone();
app.event_loop_handle
.insert_source(
calloop::timer::Timer::from_duration(self.pop_duration),
move |_, _, app| {
if guard_weak.upgrade().is_none() {
return calloop::timer::TimeoutAction::Drop;
}
widget_from_layer!(w, layer, calloop::timer::TimeoutAction::Drop);
let mut wg = w.lock().unwrap();
if !wg.mouse_state.data.hovering {
wg.window_pop_state.leave();
wg.try_redraw(app);
}
calloop::timer::TimeoutAction::Drop
},
)
.unwrap();
}
}
struct RedrawEssentail {
layer: LayerSurface,
}
impl RedrawEssentail {
fn redraw(&self, app: &mut App) {
let Some(w) = SurfaceData::from_wl(self.layer.wl_surface()).get_widget() else {
return;
};
w.lock().unwrap().on_widget_update(app);
}
}
pub struct WidgetBuilder<'a> {
pub common_config: config::CommonConfig,
pub offset: i32,
pub margins: [i32; 4],
pub output_size: (i32, i32),
pub monitor: MonitorSpecifier,
pub output: WlOutput,
pub app: WidgetBuildingStates<'a>,
pub layer: LayerSurface,
pub scale: Scale,
pub animation_list: AnimationList,
pub window_pop_state: WindowPopState,
}
impl WidgetBuilder<'_> {
pub fn new_animation(&mut self, time_cost: u64, curve: Curve) -> ToggleAnimationRc {
self.animation_list.new_transition(time_cost, curve)
}
pub fn extend_animation_list(&mut self, list: &AnimationList) {
self.animation_list.extend_list(list);
}
fn make_pop_essential(&self, pop_duration: u64) -> PopEssential {
let layer = self.layer.clone();
let pop_duration = Duration::from_millis(pop_duration);
PopEssential {
pop_duration,
layer,
}
}
pub fn make_pop_channel<T: 'static>(
&mut self,
pop_duration: u64,
mut func: impl FnMut(&mut App, T) + 'static,
) -> Sender<T> {
let (sender, source) = calloop::channel::channel();
let pop_essential = self.make_pop_essential(pop_duration);
self.app
.event_loop_handle
.insert_source(source, move |event, _, app| {
if let calloop::channel::Event::Msg(msg) = event {
func(app, msg);
pop_essential.pop(app);
}
})
.unwrap();
sender
}
pub fn make_pop_ping_with_func(
&mut self,
pop_duration: u64,
mut func: impl FnMut(&mut App) + 'static,
) -> Ping {
let (ping, source) = make_ping().unwrap();
let pop_essential = self.make_pop_essential(pop_duration);
self.app
.event_loop_handle
.insert_source(source, move |_, _, app| {
func(app);
pop_essential.pop(app);
})
.unwrap();
ping
}
pub fn make_pop_ping(&mut self, pop_duration: u64) -> Ping {
let (ping, source) = make_ping().unwrap();
let pop_essential = self.make_pop_essential(pop_duration);
self.app
.event_loop_handle
.insert_source(source, move |_, _, app| {
pop_essential.pop(app);
})
.unwrap();
ping
}
fn make_redraw_essentail(&self) -> RedrawEssentail {
let layer = self.layer.clone();
RedrawEssentail { layer }
}
pub fn make_redraw_channel<T: 'static>(
&self,
mut func: impl FnMut(&mut App, T) + 'static,
) -> Sender<T> {
let (sender, source) = calloop::channel::channel();
let redraw_essential = self.make_redraw_essentail();
self.app
.event_loop_handle
.insert_source(source, move |event, _, app| {
if let calloop::channel::Event::Msg(msg) = event {
func(app, msg);
redraw_essential.redraw(app);
}
})
.unwrap();
sender
}
pub fn make_redraw_ping_with_func(&self, mut func: impl FnMut(&mut App) + 'static) -> Ping {
let (ping, source) = make_ping().unwrap();
let redraw_essential = self.make_redraw_essentail();
self.app
.event_loop_handle
.insert_source(source, move |_, _, app| {
func(app);
redraw_essential.redraw(app);
})
.unwrap();
ping
}
pub fn make_redraw_ping(&self) -> Ping {
let (ping, source) = make_ping().unwrap();
let redraw_essential = self.make_redraw_essentail();
self.app
.event_loop_handle
.insert_source(source, move |_, _, app| {
redraw_essential.redraw(app);
})
.unwrap();
ping
}
}
impl<'a> WidgetBuilder<'a> {
fn new(
mut common: config::CommonConfig,
output: WlOutput,
app: &'a App,
) -> Result<WidgetBuilder<'a>, String> {
let monitor = app
.output_state
.info(&output)
.ok_or("Failed to get output info")?;
let output_size = monitor.modes[0].dimensions;
common.resolve_relative(output_size);
let surface = app.compositor_state.create_surface_with_data(
&app.queue_handle,
SurfaceData {
sctk: SctkSurfaceData::new(None, 1),
widget: AtomicPtr::new(std::ptr::null_mut()),
},
);
let fractional = app
.fractional_manager
.get()
.inspect_err(|e| log::error!("Fatal on Fractional scale: {e}"))
.ok()
.map(|manager| {
manager.get_fractional_scale(&surface, &app.queue_handle, surface.clone())
})
.and_then(|fractional| {
app.viewporter_manager
.get()
.inspect_err(|e| {
// NOTE: DESTROY FRACTIONAL IF WE FAILED TO GET VIEWPORT
fractional.destroy();
log::error!("Fatal on Viewporter: {e}");
})
.ok()
.map(|manager| {
(
fractional,
manager.get_viewport(&surface, &app.queue_handle, ()),
)
})
});
let scale = match fractional {
Some((f, v)) => Scale::new_fractional(f, v),
None => Scale::new_normal(),
};
let layer = app.shell.create_layer_surface(
&app.queue_handle,
surface,
common.layer,
Some(format!("way-edges-widget{}", common.namespace)),
Some(&output),
);
layer.set_anchor(common.edge | common.position);
if common.ignore_exclusive {
layer.set_exclusive_zone(-1);
};
let offset = common.offset.get_num().unwrap() as i32;
let margins = [
common.margins.top.get_num().unwrap() as i32,
common.margins.right.get_num().unwrap() as i32,
common.margins.bottom.get_num().unwrap() as i32,
common.margins.left.get_num().unwrap() as i32,
];
layer.set_margin(margins[0], margins[1], margins[2], margins[3]);
layer.set_size(1, 1);
layer.commit();
let pop_animation = ToggleAnimation::new(
Duration::from_millis(common.transition_duration),
common.animation_curve,
)
.make_rc();
let animation_list = AnimationList::new();
let mut window_pop_state = WindowPopState::new(
pop_animation,
common.pinnable,
common.pin_with_key,
common.pin_key,
);
if common.pin_on_startup {
window_pop_state.toggle_pin(false);
}
let widget_builder_states = WidgetBuildingStates {
event_loop_handle: &app.event_loop_handle,
output_state: &app.output_state,
};
Ok(Self {
monitor: common.monitor.clone(),
output,
app: widget_builder_states,
layer,
animation_list,
scale,
offset,
margins,
output_size,
window_pop_state,
common_config: common,
})
}
pub fn build(self, w: Box<dyn WidgetContext>) -> Widget {
let Self {
monitor,
output,
app: _,
layer,
scale,
animation_list,
offset,
margins,
output_size,
window_pop_state,
common_config,
} = self;
let start_pos = (0, 0);
let mouse_state = MouseState::new();
let buffer = Buffer::default();
let draw_core = DrawCore::new(&common_config);
Widget {
monitor,
configured: false,
output,
layer,
scale,
pop_animation: window_pop_state.pop_animation.clone(),
animation_list,
mouse_state,
window_pop_state,
start_pos,
w,
buffer,
draw_core,
pop_animation_finished: true,
widget_animation_finished: true,
content_width: 1,
content_height: 1,
widget_has_update: true,
next_frame: false,
frame_available: true,
offset,
margins,
output_size,
}
}
}
// TODO: we are not really access this in multithreaded situation, so we don't need
// Arc&Mutex, but since WlSurface::data needs Send&Sync, we might as well use it then.
// We can test for using Rc&RefCell, but it's not really a significant overhead when comparing to
// refresh rate(even 240hz still needs 4.9ms, but the overhead from lock is only nanoseconds)
// pub struct WidgetPtr(Rc<RefCell<Widget>>);
pub struct SurfaceData {
pub sctk: SctkSurfaceData,
pub widget: AtomicPtr<std::sync::Weak<Mutex<Widget>>>,
}
impl SurfaceDataExt for SurfaceData {
fn surface_data(&self) -> &SctkSurfaceData {
&self.sctk
}
}
impl SurfaceData {
pub fn from_wl(wl: &WlSurface) -> &Self {
wl.data::<SurfaceData>().unwrap()
}
fn store_widget(&self, widget: Weak<Mutex<Widget>>) {
self.widget.store(
Box::into_raw(Box::new(widget)),
std::sync::atomic::Ordering::SeqCst,
);
}
pub fn get_widget(&self) -> Option<Arc<Mutex<Widget>>> {
unsafe {
self.widget
.load(std::sync::atomic::Ordering::SeqCst)
.as_ref()
.unwrap()
}
.upgrade()
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/wayland/window_pop_state.rs | crates/frontend/src/wayland/window_pop_state.rs | use std::rc::Rc;
use crate::animation::{ToggleAnimationRc, ToggleDirection};
#[derive(Debug)]
pub struct WindowPopState {
pinnale: bool,
pin_with_key: bool,
pin_key: u32,
pub pin_state: bool,
pub pop_state: Option<Rc<()>>,
pub pop_animation: ToggleAnimationRc,
}
impl WindowPopState {
pub fn new(ani: ToggleAnimationRc, pinnale: bool, pin_with_key: bool, pin_key: u32) -> Self {
Self {
pin_state: false,
pop_state: None,
pop_animation: ani,
pin_key,
pinnale,
pin_with_key,
}
}
pub fn invalidate_pop(&mut self) {
drop(self.pop_state.take());
}
pub fn toggle_pin(&mut self, is_hovering: bool) {
if !self.pinnale {
return;
}
self.invalidate_pop();
let state = !self.pin_state;
self.pin_state = state;
if is_hovering {
return;
}
self.pop_animation.borrow_mut().set_direction(state.into());
}
pub fn toggle_pin_with_key(&mut self, key: u32, is_hovering: bool) -> bool {
if !self.pin_with_key || key != self.pin_key {
return false;
}
self.toggle_pin(is_hovering);
true
}
pub fn enter(&mut self) {
self.invalidate_pop();
if self.pin_state {
return;
}
self.pop_animation
.borrow_mut()
.set_direction(ToggleDirection::Forward);
}
pub fn leave(&mut self) {
self.invalidate_pop();
if self.pin_state {
return;
}
self.pop_animation
.borrow_mut()
.set_direction(ToggleDirection::Backward);
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/wayland/draw.rs | crates/frontend/src/wayland/draw.rs | use config::{common::CommonConfig, shared::NumOrRelative};
use smithay_client_toolkit::shell::wlr_layer::Anchor;
#[derive(Debug)]
pub struct DrawCore {
extra_trigger_size: i32,
preview_size: NumOrRelative,
visible_y_func: VisibleYFunc,
pop_coordinate_func: PopCoordinateFunc,
}
impl DrawCore {
pub fn new(conf: &CommonConfig) -> Self {
let visible_y_func = make_visible_y_func(conf.edge);
let pop_coordinate_func = make_pop_coordiante_pose_func(conf.edge);
Self {
extra_trigger_size: conf.extra_trigger_size.get_num().unwrap() as i32,
preview_size: conf.preview_size,
visible_y_func,
pop_coordinate_func,
}
}
pub fn calc_coordinate(&self, content_size: (i32, i32), offset: i32, progress: f64) -> [i32; 4] {
let visible = (self.visible_y_func)(content_size, offset, progress, self.preview_size);
(self.pop_coordinate_func)(content_size, visible, self.extra_trigger_size)
}
}
/// in: content_size, offset, visible_y, preview_size
/// out: coordinate to translate, is will be <=0, size revealed
type VisibleYFunc = fn((i32, i32), i32, f64, NumOrRelative) -> i32;
fn make_visible_y_func(edge: Anchor) -> VisibleYFunc {
macro_rules! cal_pre {
($s:expr, $p:expr) => {
match $p {
NumOrRelative::Num(n) => n.ceil(),
NumOrRelative::Relative(r) => ($s as f64 * r).ceil(),
} as i32
};
}
macro_rules! a {
($n:ident, $t:tt) => {
fn $n(size: (i32, i32), offset: i32, progress: f64, preview: NumOrRelative) -> i32 {
let preview = cal_pre!(size.$t, preview);
let total = size.$t + offset;
let visable = (total as f64 * progress).ceil() as i32;
visable.max(preview)
}
};
}
a!(h, 0);
a!(v, 1);
match edge {
Anchor::LEFT | Anchor::RIGHT => h,
Anchor::TOP | Anchor::BOTTOM => v,
_ => unreachable!(),
}
}
/// in: content_size, visible_y, extra
/// out: coordinate to translate, is will be <=0, size revealed
type PopCoordinateFunc = fn((i32, i32), i32, i32) -> [i32; 4];
fn make_pop_coordiante_pose_func(edge: Anchor) -> PopCoordinateFunc {
fn top(size: (i32, i32), visible_y: i32, extra: i32) -> [i32; 4] {
let x = 0;
let y = visible_y - size.1;
let w = size.0;
let h = visible_y + extra;
[x, y, w, h]
}
fn bottom(size: (i32, i32), visible_y: i32, extra: i32) -> [i32; 4] {
let x = 0;
let y = extra;
let w = size.0;
let h = visible_y + extra;
[x, y, w, h]
}
fn left(size: (i32, i32), visible_y: i32, extra: i32) -> [i32; 4] {
let x = visible_y - size.0;
let y = 0;
let w = visible_y + extra;
let h = size.1;
[x, y, w, h]
}
fn right(size: (i32, i32), visible_y: i32, extra: i32) -> [i32; 4] {
let x = extra;
let y = 0;
let w = visible_y + extra;
let h = size.1;
[x, y, w, h]
}
match edge {
Anchor::LEFT => left,
Anchor::TOP => top,
Anchor::RIGHT => right,
Anchor::BOTTOM => bottom,
_ => unreachable!(),
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/wayland/mainloop.rs | crates/frontend/src/wayland/mainloop.rs | use std::time::Duration;
use backend::{
config_file_watch::start_configuration_file_watcher, ipc::start_ipc,
runtime::init_backend_runtime_handle,
};
use calloop::EventLoop;
use smithay_client_toolkit::{
compositor::CompositorState,
output::OutputState,
reexports::calloop_wayland_source::WaylandSource,
registry::RegistryState,
seat::SeatState,
shell::wlr_layer::LayerShell,
shm::{slot::SlotPool, Shm},
};
use wayland_client::{globals::registry_queue_init, Connection};
use crate::wayland::app::WidgetMap;
use super::app::App;
pub fn run_app(show_mouse_key: bool) {
let conn = Connection::connect_to_env().unwrap();
let (globals, event_queue) = registry_queue_init(&conn).unwrap();
let qh = event_queue.handle();
let mut event_loop: EventLoop<App> =
EventLoop::try_new().expect("Failed to initialize the event loop!");
let signal = event_loop.get_signal();
let loop_handle = event_loop.handle();
WaylandSource::new(conn.clone(), event_queue)
.insert(loop_handle)
.unwrap();
let compositor_state =
CompositorState::bind(&globals, &qh).expect("wl_compositor is not available");
let layer_shell = LayerShell::bind(&globals, &qh).expect("layer shell is not available");
let shm = Shm::bind(&globals, &qh).expect("wl_shm is not available");
let pool = SlotPool::new(256 * 256 * 4, &shm).expect("Failed to create pool");
let output_state = OutputState::new(&globals, &qh);
let registry_state = RegistryState::new(&globals);
let seat_state = SeatState::new(&globals, &qh);
let fractional_manager = globals.bind(&qh, 0..=1, ()).into();
let viewporter_manager = globals.bind(&qh, 0..=1, ()).into();
let mut app = App {
reload_guard: None,
first_time_initialized: false,
exit: false,
show_mouse_key,
queue_handle: qh,
event_loop_handle: event_loop.handle(),
signal,
compositor_state,
registry_state,
seat_state,
output_state,
fractional_manager,
viewporter_manager,
shm,
pool,
pointer: None,
shell: layer_shell,
widget_map: WidgetMap::default(),
};
init_backend_runtime_handle();
let (sender, r) = calloop::channel::channel();
start_ipc(sender);
event_loop
.handle()
.insert_source(r, |event, _, app| {
let calloop::channel::Event::Msg(cmd) = event else {
log::error!("IPC server shutdown, exiting...");
app.exit = true;
return;
};
app.handle_ipc(cmd);
})
.unwrap();
let (sender, r) = calloop::channel::channel();
start_configuration_file_watcher(sender);
event_loop
.handle()
.insert_source(r, |event, _, app| {
if let calloop::channel::Event::Closed = event {
log::error!("IPC server shutdown, exiting...");
app.exit = true;
return;
};
app.reload();
})
.unwrap();
event_loop.handle().insert_idle(|app| {
app.reload();
});
while !app.exit {
event_loop
.dispatch(Some(Duration::from_millis(16)), &mut app)
.unwrap();
}
log::info!("EXITED");
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/wayland/implement.rs | crates/frontend/src/wayland/implement.rs | use smithay_client_toolkit::{
compositor::{CompositorHandler, SurfaceData as SctkSurfaceData},
delegate_compositor, delegate_layer, delegate_output, delegate_pointer, delegate_registry,
delegate_seat, delegate_shm, delegate_simple,
output::{OutputHandler, OutputState},
reexports::protocols::wp::{
fractional_scale::v1::client::{
wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1,
wp_fractional_scale_v1::{self, WpFractionalScaleV1},
},
viewporter::client::{wp_viewport::WpViewport, wp_viewporter::WpViewporter},
},
registry::{ProvidesRegistryState, RegistryState},
registry_handlers,
seat::{
pointer::{PointerEvent, PointerHandler},
Capability, SeatHandler, SeatState,
},
shell::{
wlr_layer::{LayerShellHandler, LayerSurface, LayerSurfaceConfigure},
WaylandSurface,
},
shm::{Shm, ShmHandler},
};
use wayland_client::{
delegate_noop,
protocol::{
wl_output, wl_pointer, wl_seat,
wl_surface::{self, WlSurface},
},
Connection, QueueHandle,
};
use super::app::{App, SurfaceData};
impl CompositorHandler for App {
fn scale_factor_changed(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
surface: &wl_surface::WlSurface,
new_factor: i32,
) {
log::debug!("scale factor changes");
let data = SurfaceData::from_wl(surface);
if let Some(w) = data.get_widget() {
let mut w = w.lock().unwrap();
w.update_normal(new_factor as u32, self);
}
}
fn transform_changed(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_surface: &wl_surface::WlSurface,
_new_transform: wl_output::Transform,
) {
// Not needed for this example.
}
fn frame(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_surface: &wl_surface::WlSurface,
_time: u32,
) {
let Some(widget) = SurfaceData::from_wl(_surface).get_widget() else {
return;
};
widget.lock().unwrap().on_frame_callback(self);
}
fn surface_enter(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_surface: &wl_surface::WlSurface,
_output: &wl_output::WlOutput,
) {
// Not needed for this example.
}
fn surface_leave(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_surface: &wl_surface::WlSurface,
_output: &wl_output::WlOutput,
) {
// Not needed for this example.
}
}
impl OutputHandler for App {
fn output_state(&mut self) -> &mut OutputState {
&mut self.output_state
}
fn new_output(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_output: wl_output::WlOutput,
) {
if !self.first_time_initialized {
return;
}
log::info!("new output detected");
self.reload();
}
fn update_output(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_output: wl_output::WlOutput,
) {
if !self.first_time_initialized {
return;
}
log::info!("output updated");
self.reload();
}
fn output_destroyed(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_output: wl_output::WlOutput,
) {
if !self.first_time_initialized {
return;
}
log::info!("output destroyed");
self.reload();
}
}
impl LayerShellHandler for App {
fn closed(&mut self, _conn: &Connection, _qh: &QueueHandle<Self>, _layer: &LayerSurface) {
log::debug!("Close event from layer surface: {_layer:?}");
}
fn configure(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
layer: &LayerSurface,
_configure: LayerSurfaceConfigure,
_serial: u32,
) {
log::debug!("configure layer");
let Some(layer) = SurfaceData::from_wl(layer.wl_surface()).get_widget() else {
return;
};
// Initiate the first draw.
let mut layer = layer.lock().unwrap();
if !layer.configured {
layer.configured = true;
layer.draw(self);
}
}
}
impl SeatHandler for App {
fn seat_state(&mut self) -> &mut SeatState {
&mut self.seat_state
}
fn new_seat(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_seat::WlSeat) {}
fn new_capability(
&mut self,
_conn: &Connection,
qh: &QueueHandle<Self>,
seat: wl_seat::WlSeat,
capability: Capability,
) {
// mouse
if capability == Capability::Pointer && self.pointer.is_none() {
log::info!("got pointer capability");
let pointer = self
.seat_state
.get_pointer(qh, &seat)
.expect("Failed to create pointer");
self.pointer = Some(pointer);
}
}
fn remove_capability(
&mut self,
_conn: &Connection,
_: &QueueHandle<Self>,
_: wl_seat::WlSeat,
capability: Capability,
) {
// mouse
if capability == Capability::Pointer && self.pointer.is_some() {
log::warn!("remove pointer capability");
self.pointer.take().unwrap().release();
}
}
fn remove_seat(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_seat::WlSeat) {}
}
impl PointerHandler for App {
fn pointer_frame(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_pointer: &wl_pointer::WlPointer,
events: &[PointerEvent],
) {
// as for keys: [https://github.com/torvalds/linux/blob/fda5e3f284002ea55dac1c98c1498d6dd684046e/include/uapi/linux/input-event-codes.h#L355]
for event in events {
if self.show_mouse_key {
use smithay_client_toolkit::seat::pointer::PointerEventKind::*;
match event.kind {
Press {
time: _,
button,
serial: _,
}
| Release {
time: _,
button,
serial: _,
} => {
println!("MOUSE DEBUG KEY PRESSED OR RELEASED: {button}");
}
_ => {}
}
}
let Some(w) = SurfaceData::from_wl(&event.surface).get_widget() else {
continue;
};
w.lock().unwrap().on_mouse_event(self, event);
}
}
}
impl wayland_client::Dispatch<WpFractionalScaleV1, WlSurface> for App {
fn event(
app: &mut App,
_: &WpFractionalScaleV1,
event: wp_fractional_scale_v1::Event,
surface: &WlSurface,
_: &wayland_client::Connection,
_qh: &QueueHandle<App>,
) {
if let wp_fractional_scale_v1::Event::PreferredScale { scale } = event {
let Some(w) = SurfaceData::from_wl(surface).get_widget() else {
return;
};
w.lock().unwrap().update_fraction(scale, app);
}
}
}
impl ShmHandler for App {
fn shm_state(&mut self) -> &mut Shm {
&mut self.shm
}
}
impl ProvidesRegistryState for App {
fn registry(&mut self) -> &mut RegistryState {
&mut self.registry_state
}
registry_handlers![OutputState, SeatState];
}
delegate_compositor!(App, surface: [SctkSurfaceData, SurfaceData]);
delegate_output!(App);
delegate_shm!(App);
delegate_layer!(App);
delegate_registry!(App);
delegate_simple!(App, WpFractionalScaleManagerV1, 1);
delegate_simple!(App, WpViewporter, 1);
delegate_noop!(App: WpViewport);
delegate_seat!(App);
delegate_pointer!(App);
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/wayland/mod.rs | crates/frontend/src/wayland/mod.rs | pub mod app;
mod draw;
mod implement;
pub mod mainloop;
mod window_pop_state;
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/animation/base.rs | crates/frontend/src/animation/base.rs | use std::time::{Duration, Instant};
use config::shared::Curve;
#[derive(Debug)]
pub(super) struct Animation {
pub start_time: Instant,
pub animation_costs: Duration,
get_y: fn(f64) -> f64,
get_x: fn(f64) -> f64,
cache_y: f64,
}
impl Animation {
pub(super) fn new(time_cost: Duration, curve: Curve) -> Self {
fn linear(x: f64) -> f64 {
x
}
fn quad_y(x: f64) -> f64 {
x * (2.0 - x)
}
fn quad_x(y: f64) -> f64 {
1.0 - (1.0 - y).sqrt()
}
fn cubic_y(x: f64) -> f64 {
let x_minus_one = x - 1.0;
1.0 + x_minus_one * x_minus_one * x_minus_one
}
fn cubic_x(y: f64) -> f64 {
1.0 + (y - 1.0).cbrt()
}
fn expo_x(x: f64) -> f64 {
1. - 2f64.powf(-10. * x)
}
fn expo_y(y: f64) -> f64 {
-(1.0 - y).ln() / (10.0 * 2.0f64.ln())
}
#[allow(clippy::type_complexity)]
let (get_y, get_x): (fn(f64) -> f64, fn(f64) -> f64) = match curve {
Curve::Linear => (linear, linear),
Curve::EaseQuad => (quad_y, quad_x),
Curve::EaseCubic => (cubic_y, cubic_x),
Curve::EaseExpo => (expo_y, expo_x),
};
Self {
start_time: Instant::now(),
animation_costs: time_cost,
get_y,
get_x,
cache_y: 0.,
}
}
pub(super) fn refresh(&mut self) {
let max_time = self.animation_costs.as_secs_f64();
let x = self.start_time.elapsed().as_secs_f64() / max_time;
self.cache_y = if x >= 1. {
1.
} else if x <= 0. {
0.
} else {
(self.get_y)(x)
};
}
pub(super) fn flip(&mut self) {
let passed = self.start_time.elapsed();
if passed < self.animation_costs {
self.start_time = Instant::now()
.checked_sub(
self.animation_costs
.mul_f64((self.get_x)(1.0 - self.progress())),
)
.unwrap();
} else {
self.start_time = Instant::now();
}
self.refresh();
}
pub(super) fn progress(&self) -> f64 {
self.cache_y
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/animation/list.rs | crates/frontend/src/animation/list.rs | use std::{collections::HashSet, time::Duration};
use config::shared::Curve;
use super::{ToggleAnimation, ToggleAnimationRc};
// use way_edges_derive::wrap_rc;
// #[wrap_rc(rc = "pub", normal = "pub")]
#[derive(Debug)]
pub struct AnimationList {
inner: HashSet<ToggleAnimationRc>,
}
impl AnimationList {
pub fn new() -> Self {
Self {
inner: HashSet::new(),
}
}
// this is mainly for
pub fn has_in_progress(&self) -> bool {
self.inner.iter().any(|f| f.borrow().is_in_progress())
}
pub fn new_transition(&mut self, time_cost: u64, curve: Curve) -> ToggleAnimationRc {
let item = ToggleAnimationRc::new(ToggleAnimation::new(
Duration::from_millis(time_cost),
curve,
));
self.inner.insert(item.clone());
item
}
pub fn refresh(&mut self) {
self.inner.iter().for_each(|f| f.borrow_mut().refresh());
}
pub fn extend_list(&mut self, l: &Self) {
self.inner.extend(l.inner.iter().cloned());
}
pub fn remove_item(&mut self, item: &ToggleAnimationRc) {
self.inner.remove(item);
}
}
impl Default for AnimationList {
fn default() -> Self {
Self::new()
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/frontend/src/animation/mod.rs | crates/frontend/src/animation/mod.rs | mod base;
mod list;
use std::{hash::Hash, ops::Not, rc::Rc, time::Duration};
use config::shared::Curve;
use way_edges_derive::wrap_rc;
use base::Animation;
pub use list::AnimationList;
// pub use list::{AnimationList, AnimationListRc};
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ToggleDirection {
Forward,
Backward,
}
impl Not for ToggleDirection {
type Output = ToggleDirection;
fn not(self) -> Self::Output {
match self {
ToggleDirection::Forward => Self::Backward,
ToggleDirection::Backward => Self::Forward,
}
}
}
impl From<bool> for ToggleDirection {
fn from(x: bool) -> Self {
if x {
Self::Forward
} else {
Self::Backward
}
}
}
#[wrap_rc(rc = "pub", normal = "pub")]
#[derive(Debug)]
pub struct ToggleAnimation {
pub direction: ToggleDirection,
base_animation: Animation,
}
impl ToggleAnimation {
pub fn new(time_cost: Duration, curve: Curve) -> ToggleAnimation {
Self {
direction: ToggleDirection::Backward,
base_animation: Animation::new(time_cost, curve),
}
}
pub fn refresh(&mut self) {
self.base_animation.refresh();
}
pub fn progress(&self) -> f64 {
let p = self.base_animation.progress();
match self.direction {
ToggleDirection::Forward => p,
ToggleDirection::Backward => 1. - p,
}
}
pub fn set_direction(&mut self, to_direction: ToggleDirection) {
if self.direction == to_direction {
return;
}
self.base_animation.flip();
self.direction = to_direction;
}
pub fn flip(&mut self) {
self.set_direction(self.direction.not());
}
pub fn progress_abs(&self) -> f64 {
self.base_animation.progress()
}
pub fn is_in_progress(&self) -> bool {
let p = self.progress();
p > 0. && p < 1.
}
}
impl Hash for ToggleAnimationRc {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::ptr::hash(&*self.0, state)
}
}
impl Eq for ToggleAnimationRc {}
impl PartialEq for ToggleAnimationRc {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
pub fn calculate_transition(y: f64, range: (f64, f64)) -> f64 {
range.0 + (range.1 - range.0) * y
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/config/src/lib.rs | crates/config/src/lib.rs | pub mod common;
pub mod shared;
pub mod widgets;
use schemars::{schema_for, JsonSchema};
use serde::Deserialize;
use std::{
fs::OpenOptions,
io::Read,
path::{Path, PathBuf},
sync::OnceLock,
};
pub use crate::common::CommonConfig;
pub use crate::widgets::WidgetConfig;
static CONFIG_PATH: OnceLock<PathBuf> = OnceLock::new();
pub fn set_config_path(path: Option<&str>) {
CONFIG_PATH
.set(path.map(PathBuf::from).unwrap_or_else(|| {
let bd = xdg::BaseDirectories::new();
match bd.place_config_file("way-edges/config.jsonc") {
Ok(p) => p,
Err(e) => panic!("failed to create config file: {e}"),
}
}))
.unwrap();
}
pub fn get_config_path() -> &'static Path {
if CONFIG_PATH.get().is_none() {
// If the config path is not set, we will use the default path.
set_config_path(None);
}
CONFIG_PATH.get().unwrap().as_path()
}
fn get_config_file_content() -> Result<String, String> {
let p = get_config_path();
OpenOptions::new()
.read(true)
.open(p)
.and_then(|mut f| {
let mut s = String::new();
f.read_to_string(&mut s).map(|_| s)
})
.map_err(|e| format!("failed to open config file: {e}"))
}
pub fn get_config_root() -> Result<Root, String> {
let s = get_config_file_content()?;
serde_jsonrc::from_str(&s).map_err(|e| format!("JSON parse error: {e}"))
}
pub fn output_json_schema() {
let schema = schema_for!(Root);
println!("{}", serde_jsonrc::to_string_pretty(&schema).unwrap());
}
#[derive(Deserialize, Debug, JsonSchema)]
#[schemars(extend("allowTrailingCommas" = true))]
#[serde(rename_all = "kebab-case")]
pub struct Root {
#[serde(default)]
pub widgets: Vec<Widget>,
}
#[derive(Deserialize, Debug, JsonSchema, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct Widget {
#[serde(flatten)]
pub common: CommonConfig,
#[serde(flatten)]
pub widget: WidgetConfig,
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/config/src/common.rs | crates/config/src/common.rs | use schemars::json_schema;
use serde::Deserializer;
use smithay_client_toolkit::shell::wlr_layer::{Anchor, Layer};
use schemars::JsonSchema;
use std::collections::HashSet;
use serde::Deserialize;
use crate::shared::{Curve, NumOrRelative};
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum MonitorSpecifier {
ID(usize),
Names(HashSet<String>),
All,
// this shall not be used for deserialization
Name(String),
}
impl JsonSchema for MonitorSpecifier {
fn schema_name() -> std::borrow::Cow<'static, str> {
"MonitorSpecifier".into()
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
json_schema!({
"oneOf": [
{
"type": "string",
},
{
"enum": ["*"],
},
{
"type": "number",
"minimum": 0,
},
{
"type": "array",
"items": {
"type": "string",
},
}
],
})
}
}
impl Default for MonitorSpecifier {
fn default() -> Self {
Self::ID(0)
}
}
impl<'de> Deserialize<'de> for MonitorSpecifier {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct MonitorSpecifierVisitor;
impl<'ae> serde::de::Visitor<'ae> for MonitorSpecifierVisitor {
type Value = MonitorSpecifier;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a monitor ID or a list of monitor names")
}
fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(MonitorSpecifier::ID(value as usize))
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
if value == "*" {
Ok(MonitorSpecifier::All)
} else {
let mut hashset = HashSet::new();
hashset.insert(value.to_string());
Ok(MonitorSpecifier::Names(hashset))
}
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'ae>,
{
let mut names = HashSet::new();
while let Some(value) = seq.next_element::<String>()? {
names.insert(value);
}
Ok(MonitorSpecifier::Names(names))
}
}
deserializer.deserialize_any(MonitorSpecifierVisitor)
}
}
mod tests {
#[test]
fn test_monitor_specifier() {
use super::*;
use serde_jsonrc::json;
#[derive(Debug, Deserialize)]
struct TestConfig {
monitor: MonitorSpecifier,
}
let json_data = json!({
"monitor": 1,
});
let config: TestConfig = serde_jsonrc::from_value(json_data).unwrap();
assert_eq!(config.monitor, MonitorSpecifier::ID(1));
let json_data = json!({
"monitor": "*",
});
let config: TestConfig = serde_jsonrc::from_value(json_data).unwrap();
assert_eq!(config.monitor, MonitorSpecifier::All);
let json_data = json!({
"monitor": ["Monitor1", "Monitor2"],
});
let config: TestConfig = serde_jsonrc::from_value(json_data).unwrap();
assert_eq!(
config.monitor,
MonitorSpecifier::Names(HashSet::from_iter(vec![
"Monitor1".to_string(),
"Monitor2".to_string()
]))
);
}
}
#[derive(Debug, Deserialize, Clone, Default, JsonSchema)]
#[schemars(deny_unknown_fields)]
#[serde(rename_all = "kebab-case")]
pub struct Margins {
#[serde(default)]
pub left: NumOrRelative,
#[serde(default)]
pub top: NumOrRelative,
#[serde(default)]
pub right: NumOrRelative,
#[serde(default)]
pub bottom: NumOrRelative,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct ConfigShadow {
#[serde(default = "dt_edge")]
#[serde(deserialize_with = "deserialize_edge")]
pub edge: Anchor,
#[serde(default)]
#[serde(deserialize_with = "deserialize_optional_edge")]
pub position: Option<Anchor>,
#[serde(default = "dt_layer")]
#[serde(deserialize_with = "deserialize_layer")]
pub layer: Layer,
#[serde(default)]
pub offset: NumOrRelative,
#[serde(default)]
pub margins: Margins,
#[serde(default)]
pub monitor: MonitorSpecifier,
#[serde(default)]
pub namespace: String,
#[serde(default)]
pub ignore_exclusive: bool,
#[serde(default = "dt_transition_duration")]
pub transition_duration: u64,
#[serde(default)]
pub animation_curve: Curve,
#[serde(default = "dt_extra_trigger_size")]
pub extra_trigger_size: NumOrRelative,
#[serde(default = "dt_preview_size")]
pub preview_size: NumOrRelative,
#[serde(default = "dt_pinnable")]
pub pinnable: bool,
#[serde(default = "dt_pin_with_key")]
pub pin_with_key: bool,
#[serde(default = "dt_pin_key")]
pub pin_key: u32,
#[serde(default)]
pub pin_on_startup: bool,
}
impl From<ConfigShadow> for CommonConfig {
fn from(value: ConfigShadow) -> Self {
let position;
if let Some(pos) = value.position {
position = pos
} else {
position = value.edge
}
Self {
edge: value.edge,
position,
layer: value.layer,
offset: value.offset,
margins: value.margins,
monitor: value.monitor,
namespace: value.namespace,
ignore_exclusive: value.ignore_exclusive,
transition_duration: value.transition_duration,
extra_trigger_size: value.extra_trigger_size,
preview_size: value.preview_size,
animation_curve: value.animation_curve,
pinnable: value.pinnable,
pin_with_key: value.pin_with_key,
pin_key: value.pin_key,
pin_on_startup: value.pin_on_startup,
}
}
}
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[serde(from = "ConfigShadow")]
#[schemars(deny_unknown_fields, !from)]
#[serde(rename_all = "kebab-case")]
pub struct CommonConfig {
#[schemars(schema_with = "schema_edge")]
pub edge: Anchor,
#[schemars(schema_with = "schema_optional_edge")]
pub position: Anchor,
#[schemars(schema_with = "schema_layer")]
pub layer: Layer,
pub offset: NumOrRelative,
pub margins: Margins,
pub monitor: MonitorSpecifier,
pub namespace: String,
pub ignore_exclusive: bool,
pub transition_duration: u64,
pub animation_curve: Curve,
pub extra_trigger_size: NumOrRelative,
pub preview_size: NumOrRelative,
pub pin_with_key: bool,
pub pin_key: u32,
pub pinnable: bool,
pub pin_on_startup: bool,
}
impl CommonConfig {
pub fn resolve_relative(&mut self, size: (i32, i32)) {
// margins
macro_rules! calculate_margins {
($m:expr, $s:expr) => {
if $m.is_relative() {
$m.calculate_relative($s as f64);
}
};
}
calculate_margins!(self.margins.left, size.0);
calculate_margins!(self.margins.right, size.0);
calculate_margins!(self.margins.top, size.1);
calculate_margins!(self.margins.bottom, size.1);
// offset & extra
let max = match self.edge {
Anchor::LEFT | Anchor::RIGHT => size.0,
Anchor::TOP | Anchor::BOTTOM => size.1,
_ => unreachable!(),
};
if self.offset.is_relative() {
self.offset.calculate_relative(max as f64);
}
if self.extra_trigger_size.is_relative() {
self.extra_trigger_size.calculate_relative(max as f64);
}
}
}
fn dt_edge() -> Anchor {
Anchor::LEFT
}
fn dt_layer() -> Layer {
Layer::Top
}
fn dt_transition_duration() -> u64 {
300
}
fn dt_extra_trigger_size() -> NumOrRelative {
NumOrRelative::Num(1.0)
}
fn dt_preview_size() -> NumOrRelative {
NumOrRelative::Num(0.0)
}
fn dt_pinnable() -> bool {
true
}
fn dt_pin_with_key() -> bool {
true
}
fn dt_pin_key() -> u32 {
smithay_client_toolkit::seat::pointer::BTN_MIDDLE
}
fn match_edge(edge: &str) -> Option<Anchor> {
Some(match edge {
"top" => Anchor::TOP,
"left" => Anchor::LEFT,
"bottom" => Anchor::BOTTOM,
"right" => Anchor::RIGHT,
_ => return None,
})
}
pub fn deserialize_optional_edge<'de, D>(d: D) -> Result<Option<Anchor>, D::Error>
where
D: Deserializer<'de>,
{
struct EventMapVisitor;
impl serde::de::Visitor<'_> for EventMapVisitor {
type Value = Option<Anchor>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("edge only support: left, right, top, bottom")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
if let Some(edge) = match_edge(v) {
Ok(Some(edge))
} else {
Err(serde::de::Error::invalid_value(
serde::de::Unexpected::Str(v),
&self,
))
}
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_str(v.as_str())
}
}
d.deserialize_any(EventMapVisitor)
}
pub fn deserialize_edge<'de, D>(d: D) -> Result<Anchor, D::Error>
where
D: Deserializer<'de>,
{
if let Some(edge) = deserialize_optional_edge(d)? {
Ok(edge)
} else {
Err(serde::de::Error::missing_field("edge is not optional"))
}
}
pub fn deserialize_layer<'de, D>(d: D) -> Result<Layer, D::Error>
where
D: Deserializer<'de>,
{
struct EventMapVisitor;
impl serde::de::Visitor<'_> for EventMapVisitor {
type Value = Layer;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("layer only support: background, bottom, top, overlay")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
let edge = match v {
"background" => Layer::Background,
"bottom" => Layer::Bottom,
"top" => Layer::Top,
"overlay" => Layer::Overlay,
_ => {
return Err(serde::de::Error::invalid_value(
serde::de::Unexpected::Str(v),
&self,
));
}
};
Ok(edge)
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_str(v.as_str())
}
}
d.deserialize_any(EventMapVisitor)
}
pub fn schema_edge(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
json_schema!({
"type": "string",
"enum": ["top", "bottom", "left", "right"]
})
}
pub fn schema_optional_edge(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
json_schema!({
"type": ["string", "null"],
"enum": ["top", "bottom", "left", "right"]
})
}
pub fn schema_layer(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
json_schema!({
"type": "string",
"enum": ["top", "bottom", "background", "overlay"]
})
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/config/src/shared.rs | crates/config/src/shared.rs | use cosmic_text::{Color, FamilyOwned};
use regex_lite::Regex;
use schemars::{json_schema, JsonSchema};
use serde::{self, Deserialize, Deserializer, Serialize};
use serde_jsonrc::Value;
use smithay_client_toolkit::shell::wlr_layer::Anchor;
use std::collections::HashMap;
use std::str::FromStr;
use util::{color::parse_color, shell::shell_cmd_non_block};
#[rustfmt::skip]
static ACTION_CODE_PAIRS: &[(&'static str, u32)] = &[
("mouse-left", 0x110),
("mouse-right", 0x111),
("mouse-middle", 0x112),
("mouse-side", 0x113),
("mouse-extra", 0x114),
("mouse-forward", 0x115),
("mouse-back", 0x116),
];
#[derive(Debug, Clone, Copy, Deserialize, Default, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum Curve {
Linear,
EaseQuad,
#[default]
EaseCubic,
EaseExpo,
}
#[derive(Debug, Clone, Copy)]
pub enum NumOrRelative {
Num(f64),
Relative(f64),
}
impl JsonSchema for NumOrRelative {
fn schema_id() -> std::borrow::Cow<'static, str> {
Self::schema_name()
}
fn schema_name() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed("NumOrRelative")
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
json_schema!({
"type": ["number", "string"],
"anyOf": [
{
"type": "number",
"description": "absolute number"
},
{
"type": "string",
"pattern": r"^(\d+(\.\d+)?)%\s*(.*)$",
"description": "relative number"
}
]
})
}
}
impl Default for NumOrRelative {
fn default() -> Self {
Self::Num(f64::default())
}
}
#[allow(dead_code)]
impl NumOrRelative {
pub fn is_relative(&self) -> bool {
match self {
NumOrRelative::Num(_) => false,
NumOrRelative::Relative(_) => true,
}
}
pub fn is_zero(&self) -> bool {
match self {
NumOrRelative::Num(r) => *r == 0.,
NumOrRelative::Relative(r) => *r == 0.,
}
}
pub fn get_num(&self) -> Result<f64, &str> {
if let Self::Num(r) = self {
Ok(*r)
} else {
Err("relative, not num")
}
}
pub fn get_num_into(self) -> Result<f64, &'static str> {
if let Self::Num(r) = self {
Ok(r)
} else {
Err("relative, not num")
}
}
pub fn is_valid_length(&self) -> bool {
match self {
NumOrRelative::Num(r) => *r > f64::default(),
NumOrRelative::Relative(r) => *r > 0.,
}
}
pub fn get_rel(&self) -> Result<f64, &'static str> {
if let Self::Relative(r) = self {
Ok(*r)
} else {
Err("num, not relative")
}
}
pub fn get_rel_into(self) -> Result<f64, &'static str> {
if let Self::Relative(r) = self {
Ok(r)
} else {
Err("num, not relative")
}
}
pub fn calculate_relative_into(self, max: f64) -> Self {
if let Self::Relative(r) = self {
Self::Num(r * max)
} else {
self
}
}
pub fn calculate_relative(&mut self, max: f64) {
if let Self::Relative(r) = self {
*self = Self::Num(*r * max)
}
}
}
impl<'de> Deserialize<'de> for NumOrRelative {
fn deserialize<D>(d: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct F64OrRelativeVisitor;
impl serde::de::Visitor<'_> for F64OrRelativeVisitor {
type Value = NumOrRelative;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a number or a string")
}
fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(NumOrRelative::Num(v as f64))
}
fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(NumOrRelative::Num(v as f64))
}
fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(NumOrRelative::Num(v))
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
// just `unwrap`, it's ok
lazy_static::lazy_static! {
static ref re: Regex = Regex::new(r"^(\d+(\.\d+)?)%\s*(.*)$").unwrap();
}
if let Some(captures) = re.captures(v) {
let percentage_str = captures.get(1).map_or("", |m| m.as_str());
let percentage = f64::from_str(percentage_str).map_err(E::custom)?;
Ok(NumOrRelative::Relative(percentage * 0.01))
} else {
Err(E::custom(
"Input does not match the expected format.".to_string(),
))
}
}
}
d.deserialize_any(F64OrRelativeVisitor)
}
}
#[derive(Debug, Deserialize, JsonSchema, Clone)]
pub struct CommonSize {
pub thickness: NumOrRelative,
pub length: NumOrRelative,
}
impl CommonSize {
pub fn calculate_relative(&mut self, monitor_size: (i32, i32), edge: Anchor) {
let max_size = match edge {
Anchor::LEFT | Anchor::RIGHT => (monitor_size.0, monitor_size.1),
Anchor::TOP | Anchor::BOTTOM => (monitor_size.1, monitor_size.0),
_ => unreachable!(),
};
self.thickness.calculate_relative(max_size.0 as f64);
self.length.calculate_relative(max_size.1 as f64);
}
}
#[derive(Debug, Default, Clone)]
pub struct KeyEventMap(HashMap<u32, String>);
impl KeyEventMap {
pub fn call(&self, k: u32) {
if let Some(cmd) = self.0.get(&k) {
// PERF: SHOULE THIS BE USE OF CLONING???
shell_cmd_non_block(cmd.clone());
}
}
}
impl<'de> Deserialize<'de> for KeyEventMap {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct EventMapVisitor;
impl<'a> serde::de::Visitor<'a> for EventMapVisitor {
type Value = KeyEventMap;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("vec of tuples: (key: number, command: string)")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: serde::de::MapAccess<'a>,
{
let mut event_map = HashMap::new();
while let Some((key, value)) = map.next_entry::<String, String>()? {
let action_code = if let Ok(code) = key.parse::<u32>() {
code
} else {
ACTION_CODE_PAIRS
.iter()
.find_map(|&(k, code)| (k == key).then_some(code))
.ok_or_else(|| {
serde::de::Error::custom(format!("Unknown action key: '{}'.", key))
})?
};
event_map.insert(action_code, value);
}
Ok(KeyEventMap(event_map))
}
}
deserializer.deserialize_any(EventMapVisitor)
}
}
impl JsonSchema for KeyEventMap {
fn schema_id() -> std::borrow::Cow<'static, str> {
Self::schema_name()
}
fn schema_name() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed("KeyEventMap")
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
let allowed_str_keys: Vec<_> = ACTION_CODE_PAIRS.iter().map(|&(k, _)| k).collect();
let str_keys_pattern = format!("^({})$", allowed_str_keys.join("|"));
json_schema!({
"type": "object",
"patternProperties": {
r"^\d+$": {"type": "string"},
str_keys_pattern: {"type": "string"}
},
"additionalProperties": false
})
}
}
pub fn option_color_translate<'de, D>(d: D) -> Result<Option<Color>, D::Error>
where
D: Deserializer<'de>,
{
struct ColorVisitor;
impl serde::de::Visitor<'_> for ColorVisitor {
type Value = Option<Color>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("A string")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(Some(parse_color(v).map_err(serde::de::Error::custom)?))
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_str(v.as_str())
}
}
d.deserialize_any(ColorVisitor)
}
pub fn color_translate<'de, D>(d: D) -> Result<Color, D::Error>
where
D: Deserializer<'de>,
{
if let Some(c) = option_color_translate(d)? {
Ok(c)
} else {
Err(serde::de::Error::missing_field("color is not optional"))
}
}
pub fn from_value<T>(v: Value) -> Result<T, String>
where
T: serde::de::DeserializeOwned,
{
serde_jsonrc::from_value::<T>(v).map_err(|e| format!("Fail to parse config: {e}"))
}
pub fn schema_color(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"type": "string",
"default": "#00000000",
})
}
pub fn schema_optional_color(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"type": ["string", "null"],
"default": "#00000000",
})
}
pub fn schema_template(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"type": "string",
"default": "{float:2,100}",
})
}
pub fn schema_optional_template(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"type": ["string", "null"],
"default": "{float:2,100}",
})
}
#[derive(Serialize, Deserialize)]
#[serde(remote = "FamilyOwned")]
#[serde(rename_all = "kebab-case")]
pub enum FamilyOwnedRef {
Serif,
SansSerif,
Cursive,
Fantasy,
Monospace,
#[serde(untagged)]
Name(
#[serde(deserialize_with = "deserialize_smol_str")]
#[serde(serialize_with = "serialize_smol_str")]
smol_str::SmolStr,
),
}
impl JsonSchema for FamilyOwnedRef {
fn schema_name() -> std::borrow::Cow<'static, str> {
"FamilyOwned".into()
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"oneOf": [
{
"enum": [
"serif",
"sans-serif",
"cursive",
"fantasy",
"monospace",
],
},
{
"type": "string",
}
],
})
}
}
pub fn dt_family_owned() -> FamilyOwned {
FamilyOwned::Monospace
}
// deserialize SmolStr
fn deserialize_smol_str<'de, D>(d: D) -> Result<smol_str::SmolStr, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(d)?;
Ok(s.into())
}
fn serialize_smol_str<S>(s: &smol_str::SmolStr, d: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
String::serialize(&s.to_string(), d)
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/config/src/widgets/button.rs | crates/config/src/widgets/button.rs | use crate::shared::{color_translate, schema_color, CommonSize, KeyEventMap};
use cosmic_text::Color;
use educe::Educe;
use schemars::JsonSchema;
use serde::Deserialize;
use util::color::{parse_color, COLOR_BLACK};
use way_edges_derive::{const_property, GetSize};
use schemars::Schema;
use serde_json::Value;
#[derive(Educe, Deserialize, GetSize, JsonSchema, Clone)]
#[educe(Debug)]
#[schemars(transform = BtnConfig_generate_defs)]
#[schemars(deny_unknown_fields)]
// FIXME: THIS DOES NOT WORK IDK WHY. so i have to add `transform` manually
#[const_property("type", "btn")]
#[serde(rename_all = "kebab-case")]
pub struct BtnConfig {
#[serde(flatten)]
pub size: CommonSize,
#[serde(default = "dt_color")]
#[serde(deserialize_with = "color_translate")]
#[schemars(schema_with = "schema_color")]
pub color: Color,
#[serde(default = "dt_border_width")]
pub border_width: i32,
#[serde(default = "dt_border_color")]
#[serde(deserialize_with = "color_translate")]
#[schemars(schema_with = "schema_color")]
pub border_color: Color,
#[serde(default)]
pub event_map: KeyEventMap,
}
fn dt_color() -> Color {
parse_color("#7B98FF").unwrap()
}
fn dt_border_width() -> i32 {
3
}
fn dt_border_color() -> Color {
COLOR_BLACK
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/config/src/widgets/workspace.rs | crates/config/src/widgets/workspace.rs | use crate::shared::{
color_translate, option_color_translate, schema_color, schema_optional_color, CommonSize, Curve,
};
use cosmic_text::Color;
use schemars::Schema;
use schemars::{json_schema, JsonSchema};
use serde::{Deserialize, Deserializer};
use serde_json::Value;
use util::color::parse_color;
use way_edges_derive::{const_property, GetSize};
#[derive(Debug, Deserialize, GetSize, JsonSchema, Clone)]
#[schemars(deny_unknown_fields)]
#[schemars(transform = WorkspaceConfig_generate_defs)]
#[const_property("type", "workspace")]
#[serde(rename_all = "kebab-case")]
pub struct WorkspaceConfig {
#[serde(flatten)]
// flatten does not support `default` yet.
// issue: https://github.com/serde-rs/serde/issues/1626
// PR: https://github.com/serde-rs/serde/pull/2687
// #[serde(default = "dt_size")]
pub size: CommonSize,
#[serde(default = "dt_gap")]
pub gap: i32,
#[serde(default = "dt_active_increase")]
pub active_increase: f64,
#[serde(default = "dt_workspace_transition_duration")]
pub workspace_transition_duration: u64,
#[serde(default)]
pub workspace_animation_curve: Curve,
#[serde(default = "dt_pop_duration")]
pub pop_duration: u64,
#[serde(default = "dt_default_color")]
#[serde(deserialize_with = "color_translate")]
#[schemars(schema_with = "schema_color")]
pub default_color: Color,
#[serde(default = "dt_focus_color")]
#[serde(deserialize_with = "color_translate")]
#[schemars(schema_with = "schema_color")]
pub focus_color: Color,
#[serde(default = "dt_active_color")]
#[serde(deserialize_with = "color_translate")]
#[schemars(schema_with = "schema_color")]
pub active_color: Color,
#[serde(default)]
#[serde(deserialize_with = "option_color_translate")]
#[schemars(schema_with = "schema_optional_color")]
pub hover_color: Option<Color>,
#[serde(default)]
pub invert_direction: bool,
#[serde(default)]
pub output_name: Option<String>,
#[serde(default)]
pub focused_only: bool,
#[serde(default)]
pub border_width: Option<i32>,
#[serde(default = "dt_border_radius")]
pub border_radius: i32,
pub preset: WorkspacePreset,
}
fn dt_border_radius() -> i32 {
5
}
fn dt_gap() -> i32 {
5
}
fn dt_active_increase() -> f64 {
0.5
}
fn dt_workspace_transition_duration() -> u64 {
300
}
fn dt_pop_duration() -> u64 {
1000
}
fn dt_default_color() -> Color {
parse_color("#003049").unwrap()
}
fn dt_focus_color() -> Color {
parse_color("#669bbc").unwrap()
}
fn dt_active_color() -> Color {
parse_color("#aaa").unwrap()
}
#[derive(Debug, JsonSchema, Clone)]
#[schemars(transform = WorkspacePreset_generate_defs)]
#[serde(rename_all = "kebab-case")]
pub enum WorkspacePreset {
Hyprland,
Niri(NiriConf),
}
impl<'de> Deserialize<'de> for WorkspacePreset {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = Value::deserialize(deserializer)?;
if let Some(preset_str) = value.as_str() {
match preset_str {
"hyprland" => Ok(WorkspacePreset::Hyprland),
"niri" => Ok(WorkspacePreset::Niri(NiriConf::default())),
_ => Err(serde::de::Error::unknown_variant(
preset_str,
&["hyprland", "niri"],
)),
}
} else {
#[derive(Deserialize)]
#[serde(rename_all = "kebab-case", tag = "type")]
enum Helper {
Hyprland,
Niri(NiriConf),
}
let helper: Helper = Helper::deserialize(value).map_err(|err| {
serde::de::Error::custom(format!("Failed to deserialize as object: {}", err))
})?;
match helper {
Helper::Hyprland => Ok(WorkspacePreset::Hyprland),
Helper::Niri(conf) => Ok(WorkspacePreset::Niri(conf)),
}
}
}
}
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[schemars(deny_unknown_fields)]
#[schemars(transform = NiriConf_generate_defs)]
#[const_property("type", "niri")]
#[serde(rename_all = "kebab-case")]
pub struct NiriConf {
#[serde(default = "dt_filter_empty")]
pub filter_empty: bool,
}
impl Default for NiriConf {
fn default() -> Self {
Self {
filter_empty: dt_filter_empty(),
}
}
}
fn dt_filter_empty() -> bool {
true
}
#[allow(non_snake_case)]
fn WorkspacePreset_generate_defs(s: &mut Schema) {
*s = json_schema!({
"oneOf": [
{
"type": "string",
"enum": ["hyprland", "niri"]
},
{
"type": "object",
"$ref": "#/$defs/NiriConf",
}
]
})
}
#[cfg(test)]
mod tests {
use super::*;
use serde_jsonrc;
use std::fmt;
// for test
impl fmt::Display for WorkspacePreset {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
WorkspacePreset::Hyprland => write!(f, "Hyprland"),
WorkspacePreset::Niri(conf) => {
write!(f, "Niri(filter_empty: {})", conf.filter_empty)
}
}
}
}
#[test]
fn test_deserialize_string_niri() {
let yaml_str = r#"{ "preset": "niri" }"#;
let config: serde_jsonrc::Value = serde_jsonrc::from_str(yaml_str).unwrap();
let preset: WorkspacePreset = serde_jsonrc::from_value(config["preset"].clone()).unwrap();
assert_eq!(preset.to_string(), "Niri(filter_empty: true)");
}
#[test]
fn test_deserialize_object_niri() {
let yaml_str = r#"{ "preset": { "type": "niri" } }"#;
let config: serde_jsonrc::Value = serde_jsonrc::from_str(yaml_str).unwrap();
let preset: WorkspacePreset = serde_jsonrc::from_value(config["preset"].clone()).unwrap();
assert_eq!(preset.to_string(), "Niri(filter_empty: true)");
}
#[test]
fn test_deserialize_object_niri_with_config() {
let yaml_str = r#"{ "preset": { "type": "niri", "filter-empty": false } }"#;
let config: serde_jsonrc::Value = serde_jsonrc::from_str(yaml_str).unwrap();
let preset: WorkspacePreset = serde_jsonrc::from_value(config["preset"].clone()).unwrap();
assert_eq!(preset.to_string(), "Niri(filter_empty: false)");
}
#[test]
fn test_deserialize_string_hyprland() {
let yaml_str = r#"{ "preset": "hyprland" }"#;
let config: serde_jsonrc::Value = serde_jsonrc::from_str(yaml_str).unwrap();
let preset: WorkspacePreset = serde_jsonrc::from_value(config["preset"].clone()).unwrap();
assert_eq!(preset.to_string(), "Hyprland");
}
#[test]
fn test_deserialize_object_hyprland() {
let yaml_str = r#"{ "preset": { "type": "hyprland" } }"#;
let config: serde_jsonrc::Value = serde_jsonrc::from_str(yaml_str).unwrap();
let preset: WorkspacePreset = serde_jsonrc::from_value(config["preset"].clone()).unwrap();
assert_eq!(preset.to_string(), "Hyprland");
}
#[test]
fn test_deserialize_invalid_string() {
let yaml_str = r#"{ "preset": "invalid_preset" }"#;
let config: serde_jsonrc::Value = serde_jsonrc::from_str(yaml_str).unwrap();
let result = serde_jsonrc::from_value::<WorkspacePreset>(config["preset"].clone());
assert!(result.is_err());
println!("Expected error: {}", result.unwrap_err());
}
#[test]
fn test_deserialize_invalid_object_type() {
let yaml_str = r#"{ "preset": { "type": "invalid_preset" } }"#;
let config: serde_jsonrc::Value = serde_jsonrc::from_str(yaml_str).unwrap();
let result = serde_jsonrc::from_value::<WorkspacePreset>(config["preset"].clone());
assert!(result.is_err());
println!("Expected error: {}", result.unwrap_err());
}
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/config/src/widgets/mod.rs | crates/config/src/widgets/mod.rs | use button::BtnConfig;
use schemars::JsonSchema;
use serde::Deserialize;
use slide::base::SlideConfig;
use workspace::WorkspaceConfig;
use wrapbox::BoxConfig;
pub mod button;
pub mod slide;
pub mod workspace;
pub mod wrapbox;
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[serde(rename_all = "kebab-case", tag = "type")]
pub enum WidgetConfig {
Btn(BtnConfig),
Slider(SlideConfig),
WrapBox(BoxConfig),
Workspace(WorkspaceConfig),
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/config/src/widgets/slide/base.rs | crates/config/src/widgets/slide/base.rs | use cosmic_text::Color;
use educe::Educe;
use schemars::JsonSchema;
use serde::Deserialize;
use util::color::parse_color;
use way_edges_derive::{const_property, GetSize};
use crate::shared::{
color_translate, option_color_translate, schema_color, schema_optional_color, CommonSize,
};
use super::preset::Preset;
use schemars::Schema;
use serde_json::Value;
// TODO: serde_valid
#[derive(Educe, Deserialize, GetSize, JsonSchema, Clone)]
#[educe(Debug)]
#[schemars(deny_unknown_fields)]
#[schemars(transform = SlideConfig_generate_defs)]
#[const_property("type", "slide")]
#[serde(rename_all = "kebab-case")]
pub struct SlideConfig {
// draw related
#[serde(flatten)]
pub size: CommonSize,
#[serde(default = "dt_border_width")]
pub border_width: i32,
#[serde(default = "dt_obtuse_angle")]
pub obtuse_angle: f64,
#[serde(default = "dt_radius")]
pub radius: f64,
#[serde(default = "dt_bg_color")]
#[serde(deserialize_with = "color_translate")]
#[schemars(schema_with = "schema_color")]
pub bg_color: Color,
#[serde(default = "dt_fg_color")]
#[serde(deserialize_with = "color_translate")]
#[schemars(schema_with = "schema_color")]
pub fg_color: Color,
#[serde(default = "dt_border_color")]
#[serde(deserialize_with = "color_translate")]
#[schemars(schema_with = "schema_color")]
pub border_color: Color,
#[serde(default)]
#[serde(deserialize_with = "option_color_translate")]
#[schemars(schema_with = "schema_optional_color")]
pub fg_text_color: Option<Color>,
#[serde(default)]
#[serde(deserialize_with = "option_color_translate")]
#[schemars(schema_with = "schema_optional_color")]
pub bg_text_color: Option<Color>,
#[serde(default)]
pub redraw_only_on_internal_update: bool,
#[serde(default = "default_scroll_unit")]
pub scroll_unit: f64,
#[serde(default)]
pub preset: Preset,
}
fn default_scroll_unit() -> f64 {
0.005
}
fn dt_border_width() -> i32 {
3
}
fn dt_bg_color() -> Color {
parse_color("#808080").unwrap()
}
fn dt_fg_color() -> Color {
parse_color("#FFB847").unwrap()
}
fn dt_border_color() -> Color {
parse_color("#646464").unwrap()
}
fn dt_obtuse_angle() -> f64 {
120.
}
fn dt_radius() -> f64 {
20.
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/config/src/widgets/slide/preset.rs | crates/config/src/widgets/slide/preset.rs | use cosmic_text::Color;
use schemars::JsonSchema;
use serde::{Deserialize, Deserializer};
use util::{
color::COLOR_BLACK,
template::{
arg::TemplateArgFloatProcesser,
base::{Template, TemplateProcesser},
},
};
use crate::shared::{
color_translate, option_color_translate, schema_color, schema_optional_color,
schema_optional_template, Curve, KeyEventMap,
};
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[serde(rename_all = "kebab-case", tag = "type")]
pub enum Preset {
Speaker(PulseAudioConfig),
Microphone(PulseAudioConfig),
Backlight(BacklightConfig),
Custom(CustomConfig),
}
impl Default for Preset {
fn default() -> Self {
Self::Custom(CustomConfig::default())
}
}
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[schemars(deny_unknown_fields)]
#[serde(rename_all = "kebab-case")]
pub struct PulseAudioConfig {
#[serde(default = "default_mute_color")]
#[serde(deserialize_with = "color_translate")]
#[schemars(schema_with = "schema_color")]
pub mute_color: Color,
#[serde(default)]
#[serde(deserialize_with = "option_color_translate")]
#[schemars(schema_with = "schema_optional_color")]
pub mute_text_color: Option<Color>,
#[serde(default)]
pub animation_curve: Curve,
pub device: Option<String>,
}
fn default_mute_color() -> Color {
COLOR_BLACK
}
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[schemars(deny_unknown_fields)]
#[serde(rename_all = "kebab-case")]
pub struct BacklightConfig {
#[serde(default)]
pub device: Option<String>,
}
#[derive(Debug, Deserialize, Default, JsonSchema, Clone)]
#[schemars(deny_unknown_fields)]
#[serde(rename_all = "kebab-case")]
pub struct CustomConfig {
#[serde(default)]
pub update_command: String,
#[serde(default)]
pub update_interval: u64,
#[serde(default)]
#[serde(deserialize_with = "slide_change_template")]
#[schemars(schema_with = "schema_optional_template")]
pub on_change_command: Option<Template>,
#[serde(default)]
pub event_map: KeyEventMap,
}
pub fn slide_change_template<'de, D>(d: D) -> Result<Option<Template>, D::Error>
where
D: Deserializer<'de>,
{
struct EventMapVisitor;
impl serde::de::Visitor<'_> for EventMapVisitor {
type Value = Option<Template>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("vec of tuples: (key: number, command: string)")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_string(v.to_string())
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(Some(
Template::create_from_str(
&v,
TemplateProcesser::new().add_processer(TemplateArgFloatProcesser),
)
.map_err(serde::de::Error::custom)?,
))
}
}
d.deserialize_any(EventMapVisitor)
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/config/src/widgets/slide/mod.rs | crates/config/src/widgets/slide/mod.rs | pub mod base;
pub mod preset;
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/config/src/widgets/wrapbox/tray.rs | crates/config/src/widgets/wrapbox/tray.rs | use cosmic_text::{Color, FamilyOwned};
use educe::Educe;
use schemars::JsonSchema;
use serde::Deserialize;
use util::color::COLOR_WHITE;
use super::Align;
use crate::shared::{
color_translate, dt_family_owned, option_color_translate, schema_color, schema_optional_color,
FamilyOwnedRef,
};
#[derive(Debug, Deserialize, Default, Clone, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum HeaderMenuStack {
#[default]
HeaderTop,
MenuTop,
}
#[derive(Debug, Deserialize, Default, Clone, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum HeaderMenuAlign {
#[default]
Left,
Right,
}
impl HeaderMenuAlign {
pub fn is_left(&self) -> bool {
match self {
HeaderMenuAlign::Left => true,
HeaderMenuAlign::Right => false,
}
}
}
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[schemars(deny_unknown_fields)]
#[serde(rename_all = "kebab-case")]
pub struct HeaderDrawConfig {
#[serde(default = "dt_header_font_pixel_height")]
pub font_pixel_height: i32,
#[serde(default = "dt_header_text_color")]
#[serde(deserialize_with = "color_translate")]
#[schemars(schema_with = "schema_color")]
pub text_color: Color,
}
impl Default for HeaderDrawConfig {
fn default() -> Self {
Self {
font_pixel_height: dt_header_font_pixel_height(),
text_color: dt_header_text_color(),
}
}
}
fn dt_header_font_pixel_height() -> i32 {
20
}
fn dt_header_text_color() -> Color {
COLOR_WHITE
}
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[schemars(deny_unknown_fields)]
#[serde(rename_all = "kebab-case")]
pub struct MenuDrawConfig {
#[serde(default = "dt_menu_margin")]
pub margin: [i32; 2],
#[serde(default = "dt_font_pixel_height")]
pub font_pixel_height: i32,
#[serde(default = "dt_menu_icon_size")]
pub icon_size: i32,
#[serde(default = "dt_menu_marker_size")]
pub marker_size: i32,
#[serde(default = "dt_menu_separator_height")]
pub separator_height: i32,
#[serde(default = "dt_menu_border_color")]
#[serde(deserialize_with = "color_translate")]
#[schemars(schema_with = "schema_color")]
pub border_color: Color,
#[serde(default = "dt_menu_text_color")]
#[serde(deserialize_with = "color_translate")]
#[schemars(schema_with = "schema_color")]
pub text_color: Color,
#[serde(default)]
#[serde(deserialize_with = "option_color_translate")]
#[schemars(schema_with = "schema_optional_color")]
pub marker_color: Option<Color>,
}
impl Default for MenuDrawConfig {
fn default() -> Self {
Self {
margin: dt_menu_margin(),
marker_size: dt_menu_marker_size(),
font_pixel_height: dt_font_pixel_height(),
separator_height: dt_menu_separator_height(),
border_color: dt_menu_border_color(),
text_color: dt_menu_text_color(),
icon_size: dt_menu_icon_size(),
marker_color: None,
}
}
}
fn dt_menu_margin() -> [i32; 2] {
[12, 12]
}
fn dt_font_pixel_height() -> i32 {
22
}
fn dt_menu_icon_size() -> i32 {
20
}
fn dt_menu_marker_size() -> i32 {
20
}
fn dt_menu_separator_height() -> i32 {
5
}
fn dt_menu_border_color() -> Color {
COLOR_WHITE
}
fn dt_menu_text_color() -> Color {
COLOR_WHITE
}
#[derive(Educe, Deserialize, JsonSchema, Clone)]
#[educe(Debug)]
#[schemars(deny_unknown_fields)]
#[serde(rename_all = "kebab-case")]
pub struct TrayConfig {
#[serde(default = "dt_family_owned")]
#[serde(with = "FamilyOwnedRef")]
pub font_family: FamilyOwned,
#[serde(default)]
pub icon_theme: Option<String>,
#[serde(default = "dt_icon_size")]
pub icon_size: i32,
#[serde(default = "dt_tray_gap")]
pub tray_gap: i32,
#[serde(default)]
pub grid_align: Align,
#[serde(default)]
pub header_menu_stack: HeaderMenuStack,
#[serde(default)]
pub header_menu_align: HeaderMenuAlign,
#[serde(default)]
pub header_draw_config: HeaderDrawConfig,
#[serde(default)]
pub menu_draw_config: MenuDrawConfig,
}
fn dt_icon_size() -> i32 {
20
}
fn dt_tray_gap() -> i32 {
2
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/config/src/widgets/wrapbox/text.rs | crates/config/src/widgets/wrapbox/text.rs | use cosmic_text::{Color, FamilyOwned};
use educe::Educe;
use schemars::JsonSchema;
use serde::Deserialize;
use util::color::COLOR_BLACK;
use crate::shared::{color_translate, dt_family_owned, schema_color, FamilyOwnedRef, KeyEventMap};
#[derive(Educe, Deserialize, JsonSchema, Clone)]
#[educe(Debug)]
#[serde(
rename_all = "kebab-case",
rename_all_fields = "kebab-case",
tag = "type"
)]
#[schemars(deny_unknown_fields)]
pub enum TextPreset {
Time {
#[serde(default = "dt_time_format")]
format: String,
#[serde(default)]
time_zone: Option<String>,
#[serde(default = "dt_update_interval")]
update_interval: u64,
},
Custom {
#[serde(default = "dt_update_interval")]
update_interval: u64,
cmd: String,
},
}
fn dt_time_format() -> String {
"%Y-%m-%d %H:%M:%S".to_string()
}
fn dt_update_interval() -> u64 {
1000
}
#[derive(Educe, Deserialize, JsonSchema, Clone)]
#[educe(Debug)]
#[schemars(deny_unknown_fields)]
#[serde(rename_all = "kebab-case")]
pub struct TextConfig {
#[serde(default = "dt_fg_color")]
#[serde(deserialize_with = "color_translate")]
#[schemars(schema_with = "schema_color")]
pub fg_color: Color,
#[serde(default = "dt_font_size")]
pub font_size: i32,
#[serde(default = "dt_family_owned")]
#[serde(with = "FamilyOwnedRef")]
pub font_family: FamilyOwned,
#[serde(default)]
pub event_map: KeyEventMap,
pub preset: TextPreset,
}
fn dt_fg_color() -> Color {
COLOR_BLACK
}
fn dt_font_size() -> i32 {
24
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/config/src/widgets/wrapbox/ring.rs | crates/config/src/widgets/wrapbox/ring.rs | use crate::shared::{
color_translate, dt_family_owned, schema_color, schema_optional_template, Curve,
FamilyOwnedRef, KeyEventMap,
};
use cosmic_text::{Color, FamilyOwned};
use schemars::JsonSchema;
use serde::{Deserialize, Deserializer};
use util::color::parse_color;
use util::template::{
arg::{TemplateArgFloatProcesser, TemplateArgRingPresetProcesser},
base::{Template, TemplateProcesser},
};
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[serde(
rename_all = "kebab-case",
rename_all_fields = "kebab-case",
tag = "type"
)]
#[schemars(deny_unknown_fields)]
pub enum RingPreset {
Ram {
#[serde(default = "dt_update_interval")]
update_interval: u64,
},
Swap {
#[serde(default = "dt_update_interval")]
update_interval: u64,
},
Cpu {
#[serde(default = "dt_update_interval")]
update_interval: u64,
#[serde(default)]
core: Option<usize>,
},
Battery {
#[serde(default = "dt_update_interval")]
update_interval: u64,
},
Disk {
#[serde(default = "dt_update_interval")]
update_interval: u64,
#[serde(default = "dt_partition")]
partition: String,
},
Custom {
#[serde(default = "dt_update_interval")]
update_interval: u64,
cmd: String,
},
}
impl Default for RingPreset {
fn default() -> Self {
Self::Custom {
update_interval: dt_update_interval(),
cmd: String::default(),
}
}
}
fn dt_partition() -> String {
"/".to_string()
}
fn dt_update_interval() -> u64 {
1000
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct RingConfigShadow {
#[serde(default = "dt_r")]
pub radius: i32,
#[serde(default = "dt_rw")]
pub ring_width: i32,
#[serde(default = "dt_bg")]
#[serde(deserialize_with = "color_translate")]
pub bg_color: Color,
#[serde(default = "dt_fg")]
#[serde(deserialize_with = "color_translate")]
pub fg_color: Color,
#[serde(default = "dt_tt")]
pub text_transition_ms: u64,
#[serde(default)]
pub animation_curve: Curve,
#[serde(default)]
#[serde(deserialize_with = "ring_text_template")]
pub prefix: Option<Template>,
#[serde(default)]
pub prefix_hide: bool,
#[serde(default)]
#[serde(deserialize_with = "ring_text_template")]
pub suffix: Option<Template>,
#[serde(default)]
pub suffix_hide: bool,
#[serde(default = "dt_family_owned")]
#[serde(with = "FamilyOwnedRef")]
pub font_family: FamilyOwned,
#[serde(default)]
pub font_size: Option<i32>,
#[serde(default)]
pub event_map: KeyEventMap,
pub preset: RingPreset,
}
fn dt_r() -> i32 {
13
}
fn dt_rw() -> i32 {
5
}
fn dt_bg() -> Color {
parse_color("#9F9F9F").unwrap()
}
fn dt_fg() -> Color {
parse_color("#F1FA8C").unwrap()
}
fn dt_tt() -> u64 {
300
}
impl From<RingConfigShadow> for RingConfig {
fn from(value: RingConfigShadow) -> Self {
let font_size = value.font_size.unwrap_or(value.radius * 2);
Self {
radius: value.radius,
ring_width: value.ring_width,
bg_color: value.bg_color,
fg_color: value.fg_color,
text_transition_ms: value.text_transition_ms,
prefix: value.prefix,
prefix_hide: value.prefix_hide,
suffix: value.suffix,
suffix_hide: value.suffix_hide,
font_family: value.font_family,
font_size,
preset: value.preset,
animation_curve: value.animation_curve,
event_map: value.event_map,
}
}
}
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[serde(from = "RingConfigShadow")]
#[serde(rename_all = "kebab-case")]
#[schemars(deny_unknown_fields, !from)]
pub struct RingConfig {
pub radius: i32,
pub ring_width: i32,
#[schemars(schema_with = "schema_color")]
pub bg_color: Color,
#[schemars(schema_with = "schema_color")]
pub fg_color: Color,
pub text_transition_ms: u64,
pub animation_curve: Curve,
#[schemars(schema_with = "schema_optional_template")]
pub prefix: Option<Template>,
pub prefix_hide: bool,
#[schemars(schema_with = "schema_optional_template")]
pub suffix: Option<Template>,
pub suffix_hide: bool,
#[serde(default = "dt_family_owned")]
#[serde(with = "FamilyOwnedRef")]
pub font_family: FamilyOwned,
pub font_size: i32,
pub event_map: KeyEventMap,
pub preset: RingPreset,
}
pub fn ring_text_template<'de, D>(d: D) -> Result<Option<Template>, D::Error>
where
D: Deserializer<'de>,
{
struct EventMapVisitor;
impl serde::de::Visitor<'_> for EventMapVisitor {
type Value = Option<Template>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("vec of tuples: (key: number, command: string)")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
self.visit_string(v.to_string())
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(Some(
Template::create_from_str(
&v,
TemplateProcesser::new()
.add_processer(TemplateArgFloatProcesser)
.add_processer(TemplateArgRingPresetProcesser),
)
.map_err(serde::de::Error::custom)?,
))
}
}
d.deserialize_any(EventMapVisitor)
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
way-edges/way-edges | https://github.com/way-edges/way-edges/blob/03a9091642ad39345115223890000481eeac8333/crates/config/src/widgets/wrapbox/mod.rs | crates/config/src/widgets/wrapbox/mod.rs | pub mod ring;
pub mod text;
pub mod tray;
use cosmic_text::Color;
use ring::RingConfig;
use schemars::JsonSchema;
use serde::Deserialize;
use text::TextConfig;
use tray::TrayConfig;
use util::color::parse_color;
use way_edges_derive::const_property;
use crate::shared::{color_translate, schema_color};
// =================================== OUTLOOK
#[derive(Debug, Deserialize, Clone, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub struct OutlookMargins {
#[serde(default = "dt_margin")]
pub left: i32,
#[serde(default = "dt_margin")]
pub top: i32,
#[serde(default = "dt_margin")]
pub right: i32,
#[serde(default = "dt_margin")]
pub bottom: i32,
}
fn dt_margin() -> i32 {
5
}
impl Default for OutlookMargins {
fn default() -> Self {
Self {
left: dt_margin(),
top: dt_margin(),
right: dt_margin(),
bottom: dt_margin(),
}
}
}
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[schemars(deny_unknown_fields)]
#[serde(rename_all = "kebab-case")]
pub struct OutlookWindowConfig {
#[serde(default)]
pub margins: OutlookMargins,
#[serde(default = "dt_color")]
#[serde(deserialize_with = "color_translate")]
#[schemars(schema_with = "schema_color")]
pub color: Color,
#[serde(default = "dt_radius")]
pub border_radius: i32,
#[serde(default = "dt_border_width")]
pub border_width: i32,
}
impl Default for OutlookWindowConfig {
fn default() -> Self {
Self {
margins: Default::default(),
color: dt_color(),
border_radius: dt_radius(),
border_width: dt_border_width(),
}
}
}
fn dt_color() -> Color {
parse_color("#4d8080").unwrap()
}
fn dt_radius() -> i32 {
5
}
fn dt_border_width() -> i32 {
15
}
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct OutlookBoardConfig {
#[serde(default)]
pub margins: OutlookMargins,
#[serde(default = "dt_color")]
#[serde(deserialize_with = "color_translate")]
#[schemars(schema_with = "schema_color")]
pub color: Color,
#[serde(default = "dt_radius")]
pub border_radius: i32,
}
#[derive(Debug, Deserialize, Clone, JsonSchema)]
#[serde(rename_all = "kebab-case", tag = "type")]
pub enum Outlook {
Window(OutlookWindowConfig),
Board(OutlookBoardConfig),
}
impl Default for Outlook {
fn default() -> Self {
Self::Window(OutlookWindowConfig::default())
}
}
// =================================== GRID
#[derive(Deserialize, Debug, Default, Clone, Copy, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum Align {
#[default]
TopLeft,
TopCenter,
TopRight,
CenterLeft,
CenterCenter,
CenterRight,
BottomLeft,
BottomCenter,
BottomRight,
}
pub type AlignFuncPos = (f64, f64);
pub type AlignFuncGridBlockSize = (f64, f64);
pub type AlignFuncContentSize = (f64, f64);
pub type AlignFunc =
Box<fn(AlignFuncPos, AlignFuncGridBlockSize, AlignFuncContentSize) -> AlignFuncPos>;
impl Align {
pub fn to_func(&self) -> AlignFunc {
macro_rules! align_y {
(T, $pos:expr, $size:expr, $content_size:expr) => {
$pos.1
};
(C, $pos:expr, $size:expr, $content_size:expr) => {
$pos.1 + ($size.1 - $content_size.1) / 2.
};
(B, $pos:expr, $size:expr, $content_size:expr) => {
$pos.1 + ($size.1 - $content_size.1)
};
}
macro_rules! align_x {
(L, $pos:expr, $size:expr, $content_size:expr) => {
$pos.0
};
(C, $pos:expr, $size:expr, $content_size:expr) => {
$pos.0 + ($size.0 - $content_size.0) / 2.
};
(R, $pos:expr, $size:expr, $content_size:expr) => {
$pos.0 + ($size.0 - $content_size.0)
};
}
macro_rules! a {
($x:tt $y:tt) => {
|pos, size, content_size| {
(
align_x!($x, pos, size, content_size),
align_y!($y, pos, size, content_size),
)
}
};
}
Box::new(match self {
#[allow(unused)]
Align::TopLeft => a!(L T),
Align::TopCenter => a!(C T),
Align::TopRight => a!(R T),
Align::CenterLeft => a!(L C),
Align::CenterCenter => a!(C C),
Align::CenterRight => a!(R C),
Align::BottomLeft => a!(L B),
Align::BottomCenter => a!(C B),
Align::BottomRight => a!(R B),
})
}
}
// =================================== WIDGETS
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[serde(rename_all = "kebab-case", tag = "type")]
pub enum BoxedWidget {
Ring(RingConfig),
Text(TextConfig),
Tray(TrayConfig),
}
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[schemars(deny_unknown_fields)]
#[serde(rename_all = "kebab-case")]
pub struct BoxedWidgetConfig {
#[serde(default = "dt_index")]
pub index: [isize; 2],
#[serde(flatten)]
pub widget: BoxedWidget,
}
fn dt_index() -> [isize; 2] {
[-1, -1]
}
use schemars::Schema;
use serde_json::Value;
// =================================== FINAL
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[schemars(deny_unknown_fields)]
#[schemars(transform = BoxConfig_generate_defs)]
#[const_property("type", "wrap-box")]
#[serde(rename_all = "kebab-case")]
pub struct BoxConfig {
#[serde(default)]
pub outlook: Outlook,
#[serde(default)]
pub items: Vec<BoxedWidgetConfig>,
#[serde(default = "dt_gap")]
pub gap: f64,
#[serde(default)]
pub align: Align,
}
fn dt_gap() -> f64 {
10.
}
| rust | MIT | 03a9091642ad39345115223890000481eeac8333 | 2026-01-04T20:25:15.177432Z | false |
alexpasmantier/grip-grab | https://github.com/alexpasmantier/grip-grab/blob/831a5646dd030785b6ea32c1c3ceb0f33b989779/src/fs.rs | src/fs.rs | use ignore::{types::TypesBuilder, Error, WalkBuilder};
use std::path::{Path, PathBuf};
pub fn walk_builder(
paths: Vec<&Path>,
ignored_paths: &[PathBuf],
n_threads: usize,
respect_gitignore: bool,
filter_filetypes: &[String],
) -> WalkBuilder {
let mut builder = WalkBuilder::new(paths[0]);
// add all paths to the builder
paths.iter().skip(1).for_each(|path| {
builder.add(*path);
});
// ft-based filtering
let mut types_builder = TypesBuilder::new();
types_builder.add_defaults();
add_custom_filetypes(&mut types_builder).unwrap();
for ft in filter_filetypes {
types_builder.select(ft);
}
builder.types(types_builder.build().unwrap());
// path-based filtering
let ignored_paths = ignored_paths.to_vec();
builder.filter_entry(move |entry| {
for ignore in &ignored_paths {
if entry.path() == ignore {
return false;
}
}
true
});
// .gitignore filtering
builder.git_ignore(respect_gitignore);
builder.threads(n_threads);
builder
}
fn add_custom_filetypes(types_builder: &mut TypesBuilder) -> Result<(), Error> {
types_builder.add("pystrict", "*.py")
}
// Original code from https://github.com/BurntSushi/ripgrep/blob/e0f1000df67f82ab0e735bad40e9b45b2d774ef0/crates/cli/src/lib.rs#L249
pub fn is_readable_stdin() -> bool {
use std::io::IsTerminal;
#[cfg(unix)]
fn imp() -> bool {
use std::{
fs::File,
os::{fd::AsFd, unix::fs::FileTypeExt},
};
let stdin = std::io::stdin();
let Ok(fd) = stdin.as_fd().try_clone_to_owned() else {
return false;
};
let file = File::from(fd);
let Ok(md) = file.metadata() else {
return false;
};
let ft = md.file_type();
let is_file = ft.is_file();
let is_fifo = ft.is_fifo();
let is_socket = ft.is_socket();
is_file || is_fifo || is_socket
}
#[cfg(windows)]
fn imp() -> bool {
let stdin = winapi_util::HandleRef::stdin();
let typ = match winapi_util::file::typ(stdin) {
Ok(typ) => typ,
Err(err) => {
log::debug!(
"for heuristic stdin detection on Windows, \
could not get file type of stdin \
(thus assuming stdin is not readable): {err}",
);
return false;
}
};
let is_disk = typ.is_disk();
let is_pipe = typ.is_pipe();
let is_readable = is_disk || is_pipe;
log::debug!(
"for heuristic stdin detection on Windows, \
found that is_disk={is_disk} and is_pipe={is_pipe}, \
and thus concluded that is_stdin_readable={is_readable}",
);
is_readable
}
#[cfg(not(any(unix, windows)))]
fn imp() -> bool {
log::debug!("on non-{{Unix,Windows}}, assuming stdin is not readable");
false
}
!std::io::stdin().is_terminal() && imp()
}
| rust | Apache-2.0 | 831a5646dd030785b6ea32c1c3ceb0f33b989779 | 2026-01-04T20:25:24.435580Z | false |
alexpasmantier/grip-grab | https://github.com/alexpasmantier/grip-grab/blob/831a5646dd030785b6ea32c1c3ceb0f33b989779/src/cli.rs | src/cli.rs | use std::path::PathBuf;
use crate::{printer::PrintMode, utils};
use clap::{ArgAction, Parser, Subcommand};
#[derive(Parser, Debug)]
#[command(name = "grip-grab")]
#[command(bin_name = "gg")]
#[command(version, about = "A faster, more lightweight ripgrep alternative for day to day usecases.", long_about = None, arg_required_else_help=true)]
pub struct Cli {
/// a regex pattern to search for
#[arg(num_args = 1)]
pub pattern: Option<String>,
/// you can specify multiple patterns using -e "pattern1" -e "pattern2" etc.
#[arg(
short = 'e',
long,
action = ArgAction::Append
)]
patterns: Vec<String>,
/// path in which to search recursively
#[arg(num_args = 0..)]
pub paths: Vec<PathBuf>,
/// paths to ignore when recursively walking target directory
#[clap(short = 'I', long)]
pub ignore_paths: Vec<PathBuf>,
/// disregard .gitignore rules when recursively walking directory (defaults to false)
#[clap(short = 'G', long, default_value_t = false)]
pub disregard_gitignore: bool,
/// number of threads to use
#[clap(short = 'T', long, default_value_t = 4)]
pub n_threads: usize,
/// enable multiline matching
#[clap(short = 'U', long, default_value_t = false)]
pub multiline: bool,
/// output in JSON format
#[clap(long, default_value_t = false)]
pub json: bool,
/// output file paths only
#[clap(short = 'f', long, default_value_t = false)]
pub file_paths_only: bool,
/// output absolute paths (defaults to relative)
#[clap(short = 'A', long, default_value_t = false)]
pub absolute_paths: bool,
/// disable colored output (colored by default)
#[clap(short = 'C', long, default_value_t = false)]
pub disable_colored_output: bool,
/// filter on filetype (defaults to all filetypes)
#[clap(short = 't', long)]
pub filter_filetypes: Vec<String>,
/// disable hyperlinks in output (defaults to false)
#[clap(short = 'H', long, default_value_t = false)]
pub disable_hyperlinks: bool,
/// enable devicons in output (defaults to false)
#[clap(short = 'D', long, default_value_t = false)]
pub enable_devicons: bool,
/// Subcommands
#[clap(subcommand)]
pub sub_command: Option<Commands>,
}
#[derive(Subcommand, Debug)]
pub enum Commands {
/// Upgrade the crate to its latest version
Upgrade {
/// Optional flag for force upgrade
#[arg(short, long, default_value_t = false)]
force: bool,
},
}
const DEFAULT_PATH: &str = ".";
impl Cli {
pub fn validate(&mut self) {
if self.sub_command.is_some() {
return;
}
if self.patterns.is_empty() {
// If no patterns are provided using -e, the positional argument should be treated as a
// pattern
if self.pattern.is_none() {
eprintln!("error: the following required arguments were not provided: <PATTERN>");
std::process::exit(1);
}
} else if self.pattern.is_some() {
// If patterns are provided using -e and we have what seems to be an additional positional pattern,
// it should be interpreted as a path.
self.paths
.push(PathBuf::from(self.pattern.clone().unwrap()));
self.pattern = None;
} else {
// If patterns are provided using -e and no positional arguments are provided, use
// default path
self.paths = vec![PathBuf::from(DEFAULT_PATH)];
}
}
}
#[derive(Debug)]
pub struct PostProcessedCli {
pub patterns: Vec<String>,
pub paths: Vec<PathBuf>,
pub ignored_paths: Vec<PathBuf>,
pub n_threads: usize,
pub disregard_gitignore: bool,
pub multiline: bool,
pub print_mode: PrintMode,
pub absolute_paths: bool,
pub colored_output: bool,
pub filter_filetypes: Vec<String>,
pub disable_hyperlinks: bool,
pub enable_devicons: bool,
pub sub_command: Option<Commands>,
}
impl Default for PostProcessedCli {
fn default() -> Self {
PostProcessedCli {
patterns: Vec::new(),
paths: Vec::new(),
ignored_paths: Vec::new(),
n_threads: 1,
disregard_gitignore: false,
multiline: false,
print_mode: PrintMode::Text,
absolute_paths: false,
colored_output: true,
filter_filetypes: Vec::new(),
disable_hyperlinks: false,
enable_devicons: false,
sub_command: None,
}
}
}
pub fn process_cli_args(mut cli: Cli) -> PostProcessedCli {
cli.validate();
if cli.paths.is_empty() {
cli.paths.push(PathBuf::from(DEFAULT_PATH));
}
if let Some(Commands::Upgrade { force }) = cli.sub_command {
return PostProcessedCli {
sub_command: Some(Commands::Upgrade { force }),
..Default::default()
};
}
PostProcessedCli {
patterns: if cli.patterns.is_empty() {
vec![cli.pattern.unwrap()]
} else {
cli.patterns
},
paths: utils::resolve_paths(cli.paths),
ignored_paths: utils::resolve_paths(cli.ignore_paths),
n_threads: cli.n_threads,
disregard_gitignore: cli.disregard_gitignore,
multiline: cli.multiline,
print_mode: if cli.json {
PrintMode::Json
} else if cli.file_paths_only {
PrintMode::Files
} else {
PrintMode::Text
},
absolute_paths: cli.absolute_paths,
colored_output: !cli.disable_colored_output,
filter_filetypes: cli.filter_filetypes,
disable_hyperlinks: cli.disable_hyperlinks,
enable_devicons: cli.enable_devicons,
sub_command: cli.sub_command,
}
}
| rust | Apache-2.0 | 831a5646dd030785b6ea32c1c3ceb0f33b989779 | 2026-01-04T20:25:24.435580Z | false |
alexpasmantier/grip-grab | https://github.com/alexpasmantier/grip-grab/blob/831a5646dd030785b6ea32c1c3ceb0f33b989779/src/search.rs | src/search.rs | #![allow(clippy::module_name_repetitions)]
use std::{fmt, io};
use std::{path::PathBuf, slice::Iter};
use grep::{
matcher::{Match, Matcher},
regex::{self, RegexMatcher, RegexMatcherBuilder},
searcher::{sinks::UTF8, Searcher, SearcherBuilder},
};
use serde::Serialize;
#[derive(Debug, Serialize, Clone)]
pub struct SearchResult {
pub line_number: u64,
pub line: String,
pub line_start: u64,
pub line_end: u64,
pub matches: Vec<MatchRange>,
}
#[derive(Serialize, Debug, Clone)]
pub struct MatchRange {
pub start: usize,
pub end: usize,
}
impl MatchRange {
/// Create a new match.
///
/// # Panics
///
/// This function panics if `start > end`.
#[inline]
pub fn new(start: usize, end: usize) -> MatchRange {
assert!(start <= end);
MatchRange { start, end }
}
#[inline]
pub fn from_match(m: Match) -> MatchRange {
MatchRange::new(m.start(), m.end())
}
/// Creates a zero width match at the given offset.
#[inline]
pub fn zero(offset: usize) -> MatchRange {
MatchRange {
start: offset,
end: offset,
}
}
/// Return the start offset of this match.
#[inline]
pub fn start(&self) -> usize {
self.start
}
/// Return the end offset of this match.
#[inline]
pub fn end(&self) -> usize {
self.end
}
/// Return a new match with the start offset replaced with the given
/// value.
///
/// # Panics
///
/// This method panics if `start > self.end`.
#[inline]
pub fn with_start(&self, start: usize) -> MatchRange {
assert!(start <= self.end, "{} is not <= {}", start, self.end);
MatchRange { start, ..*self }
}
/// Return a new match with the end offset replaced with the given
/// value.
///
/// # Panics
///
/// This method panics if `self.start > end`.
#[inline]
pub fn with_end(&self, end: usize) -> MatchRange {
assert!(self.start <= end, "{} is not <= {}", self.start, end);
MatchRange { end, ..*self }
}
/// Offset this match by the given amount and return a new match.
///
/// This adds the given offset to the start and end of this match, and
/// returns the resulting match.
///
/// # Panics
///
/// This panics if adding the given amount to either the start or end
/// offset would result in an overflow.
#[inline]
pub fn offset(&self, amount: usize) -> MatchRange {
MatchRange {
start: self.start.checked_add(amount).unwrap(),
end: self.end.checked_add(amount).unwrap(),
}
}
/// Returns the number of bytes in this match.
#[inline]
pub fn len(&self) -> usize {
self.end - self.start
}
/// Returns true if and only if this match is empty.
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl std::ops::Index<MatchRange> for [u8] {
type Output = [u8];
#[inline]
fn index(&self, index: MatchRange) -> &[u8] {
&self[index.start..index.end]
}
}
impl std::ops::IndexMut<MatchRange> for [u8] {
#[inline]
fn index_mut(&mut self, index: MatchRange) -> &mut [u8] {
&mut self[index.start..index.end]
}
}
impl std::ops::Index<MatchRange> for str {
type Output = str;
#[inline]
fn index(&self, index: MatchRange) -> &str {
&self[index.start..index.end]
}
}
#[derive(Debug, Serialize, Clone)]
pub struct FileResults {
pub path: PathBuf,
pub results: Vec<SearchResult>,
}
impl fmt::Display for FileResults {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "{}\n", self.path.to_string_lossy()).and_then(|()| {
self.results
.iter()
.try_for_each(|r| write!(f, "{}: {}", r.line_number, r.line))
})
}
}
impl FileResults {
pub fn is_empty(&self) -> bool {
self.results.is_empty()
}
pub fn len(&self) -> usize {
self.results.len()
}
}
impl<'a> IntoIterator for &'a FileResults {
type Item = &'a SearchResult;
type IntoIter = Iter<'a, SearchResult>;
fn into_iter(self) -> Self::IntoIter {
self.results.iter()
}
}
struct PartialSearchResult {
pub line_number: u64,
pub line: String,
pub m: MatchRange,
}
pub fn search_file(
path: PathBuf,
matcher: &RegexMatcher,
searcher: &mut Searcher,
) -> Result<FileResults, io::Error> {
let mut partial_results: Vec<PartialSearchResult> = Vec::new();
searcher.search_path(
matcher,
&path,
UTF8(|lnum, line| {
matcher.find_iter(line.as_bytes(), |m| {
partial_results.push(PartialSearchResult {
line_number: lnum,
line: line.to_string(),
m: MatchRange::from_match(m),
});
true
})?;
Ok(true)
}),
)?;
if partial_results.is_empty() {
return Ok(FileResults {
path,
results: Vec::new(),
});
}
let mut results = vec![SearchResult {
line_number: partial_results[0].line_number,
line: partial_results[0].line.clone(),
line_start: partial_results[0].line_number,
line_end: partial_results[0].line_number,
matches: vec![partial_results[0].m.clone()],
}];
for partial_result in &partial_results[1..] {
let last_result = results.last_mut().unwrap();
if last_result.line_number == partial_result.line_number {
last_result.matches.push(partial_result.m.clone());
last_result.line_end = partial_result.line_number;
} else {
results.push(SearchResult {
line_number: partial_result.line_number,
line: partial_result.line.clone(),
line_start: partial_result.line_number,
line_end: partial_result.line_number,
matches: vec![partial_result.m.clone()],
});
}
}
Ok(FileResults { path, results })
}
#[allow(clippy::similar_names)]
pub fn search_reader(
reader: impl std::io::BufRead,
matcher: &RegexMatcher,
searcher: &mut Searcher,
) -> Result<Vec<SearchResult>, io::Error> {
let mut results = Vec::new();
let mut line_number = 0;
searcher.search_reader(
matcher,
reader,
UTF8(|lnum, line| {
line_number = lnum;
let mut matches = Vec::new();
matcher.find_iter(line.as_bytes(), |m| {
matches.push(MatchRange::from_match(m));
true
})?;
results.push(SearchResult {
line_number: lnum,
line: line.to_string(),
line_start: lnum,
line_end: lnum,
matches,
});
Ok(true)
}),
)?;
Ok(results)
}
pub fn build_matcher(patterns: &[String]) -> Result<RegexMatcher, regex::Error> {
let builder = RegexMatcherBuilder::new();
// matcher Error
builder.build_many(patterns)
}
pub fn build_searcher(multiline: bool) -> Searcher {
let mut builder = SearcherBuilder::new();
builder.multi_line(multiline);
builder.build()
}
| rust | Apache-2.0 | 831a5646dd030785b6ea32c1c3ceb0f33b989779 | 2026-01-04T20:25:24.435580Z | false |
alexpasmantier/grip-grab | https://github.com/alexpasmantier/grip-grab/blob/831a5646dd030785b6ea32c1c3ceb0f33b989779/src/printer.rs | src/printer.rs | use devicons::FileIcon;
use std::{
env::current_dir,
fmt,
io::{IsTerminal, Result, Write},
path::{Path, PathBuf},
};
use termcolor::{Buffer, BufferWriter, Color, ColorChoice, ColorSpec, WriteColor};
use crate::search::{FileResults, SearchResult};
use std::io::stdout;
#[derive(Debug, Eq, PartialEq)]
pub enum PrintMode {
Text,
Json,
Files,
}
pub struct ResultsPrinter {
writer: BufferWriter,
buffer: Buffer,
config: PrinterConfig,
cwd: PathBuf,
}
pub struct PrinterConfig {
pub mode: PrintMode,
pub colored_output: bool,
pub color_specs: ColorSpecs,
pub absolute_paths: bool,
pub disable_hyperlinks: bool,
pub disable_devicons: bool,
}
impl Default for PrinterConfig {
fn default() -> PrinterConfig {
PrinterConfig {
mode: PrintMode::Text,
colored_output: true,
color_specs: ColorSpecs::default(),
absolute_paths: false,
disable_hyperlinks: false,
disable_devicons: false,
}
}
}
pub struct ColorSpecs {
paths: ColorSpec,
line_numbers: ColorSpec,
lines: ColorSpec,
matched: ColorSpec,
}
impl Default for ColorSpecs {
fn default() -> ColorSpecs {
let mut paths: ColorSpec = ColorSpec::new();
paths
.set_fg(Some(Color::Green))
.set_italic(true)
.set_bold(true)
.set_underline(true);
let mut line_numbers: ColorSpec = ColorSpec::new();
line_numbers.set_fg(Some(Color::Yellow)).set_bold(true);
let mut lines: ColorSpec = ColorSpec::new();
lines.set_fg(Some(Color::White));
let mut matched: ColorSpec = ColorSpec::new();
matched.set_fg(Some(Color::Red)).set_bold(true);
ColorSpecs {
paths,
line_numbers,
lines,
matched,
}
}
}
impl ResultsPrinter {
pub fn new(mut config: PrinterConfig) -> ResultsPrinter {
let stdout = stdout();
if !stdout.is_terminal() {
config.disable_hyperlinks = true;
config.colored_output = false;
}
let color_choice = if !config.colored_output || config.mode == PrintMode::Json {
ColorChoice::Never
} else {
ColorChoice::Always
};
let bufwriter = BufferWriter::stdout(color_choice);
let buffer = bufwriter.buffer();
ResultsPrinter {
writer: bufwriter,
buffer,
config,
cwd: current_dir().unwrap(),
}
}
const MAX_BUFFER_SIZE: usize = 1024;
pub fn write(&mut self, results: FileResults) -> Result<()> {
if self.buffer.len() > Self::MAX_BUFFER_SIZE {
self.buffer.flush()?;
}
match self.config.mode {
PrintMode::Text => self.write_colored_text_results(&results.path, &results.results),
PrintMode::Json => self.writeln_to_buffer(&serde_json::to_string(&FileResults {
path: results.path.clone(),
results: results.results,
})?),
PrintMode::Files => self.write_colored_path(&results.path),
}
}
fn write_colored_text_results(
&mut self,
path: &Path,
search_results: &[SearchResult],
) -> Result<()> {
self.write_colored_path(path)?;
self.write_colored_search_results(search_results)?;
self.write_newline_to_buffer()
}
fn write_colored_path(&mut self, path: &Path) -> Result<()> {
if !self.config.disable_devicons {
let icon = FileIcon::from(path);
self.buffer.set_color(ColorSpec::new().set_fg(Some(
devicons_to_termcolor_color(icon.color).unwrap_or(Color::White),
)))?;
write!(&mut self.buffer, "{} ", icon.icon)?;
}
self.buffer.set_color(&self.config.color_specs.paths)?;
let display_path = if self.config.absolute_paths {
path.to_string_lossy()
} else if path.starts_with(&self.cwd) {
path.strip_prefix(&self.cwd).unwrap().to_string_lossy()
} else {
path.to_string_lossy()
};
if self.config.disable_hyperlinks {
return writeln!(&mut self.buffer, "{display_path}");
}
let path_str = path.to_string_lossy();
let link = Hyperlink {
uri: &format!("file://{path_str}"),
id: None,
};
writeln!(&mut self.buffer, "{link}{display_path}{link:#}",)
}
fn write_colored_search_results(&mut self, results: &[SearchResult]) -> Result<()> {
results.iter().try_for_each(|result| {
self.write_colored_line(result)?;
Ok(())
})
}
fn write_colored_line(&mut self, result: &SearchResult) -> Result<()> {
self.buffer
.set_color(&self.config.color_specs.line_numbers)?;
write!(&mut self.buffer, "{}:\t", result.line_number)?;
self.write_colored_matches(result)
}
fn write_colored_matches(&mut self, result: &SearchResult) -> Result<()> {
self.buffer.set_color(&self.config.color_specs.lines)?;
let mut last_end_offset = 0;
result
.matches
.iter()
.try_for_each(|match_range| -> Result<()> {
write!(
&mut self.buffer,
"{}",
&result.line[last_end_offset..match_range.start]
)?;
self.buffer.set_color(&self.config.color_specs.matched)?;
write!(
&mut self.buffer,
"{}",
&result.line[match_range.start..match_range.end]
)?;
self.buffer.set_color(&self.config.color_specs.lines)?;
last_end_offset = match_range.end;
Ok(())
})?;
write!(&mut self.buffer, "{}", &result.line[last_end_offset..])
}
fn writeln_to_buffer(&mut self, text: &str) -> Result<()> {
writeln!(self.buffer, "{text}")
}
const EMPTY_STRING: &str = "";
fn write_newline_to_buffer(&mut self) -> Result<()> {
writeln!(self.buffer, "{}", Self::EMPTY_STRING)
}
pub fn wipeout(&mut self) -> Result<()> {
self.buffer.flush()?;
self.reset_ansi_formatting()
}
fn reset_ansi_formatting(&mut self) -> Result<()> {
self.buffer.reset()?;
write!(&mut self.buffer, "")?;
self.writer.print(&self.buffer)
}
}
fn devicons_to_termcolor_color(d_color: &str) -> Option<Color> {
d_color.strip_prefix("#").and_then(|hex| {
if hex.len() != 6 {
return None;
}
let red = u8::from_str_radix(&hex[0..2], 16).ok()?;
let green = u8::from_str_radix(&hex[2..4], 16).ok()?;
let blue = u8::from_str_radix(&hex[4..6], 16).ok()?;
Some(Color::Rgb(red, green, blue))
})
}
#[derive(Default, Debug, PartialEq, Clone)]
pub struct Hyperlink<'a> {
// maybe this should use u8 to support non-utf encodings?
uri: &'a str,
id: Option<&'a str>,
}
const OSC8: &str = "\x1b]8";
/// string terminator
const ST: &str = "\x1b\\";
impl fmt::Display for Hyperlink<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let url = self.uri;
if f.alternate() {
// based off of the cargo internal hyperlink behavior.
// if the alternate flag is specified, end the hyperlink.
write!(f, "{OSC8};;{ST}")
} else if let Some(id) = self.id {
write!(f, "{OSC8};id={id};{url}{ST}")
} else {
write!(f, "{OSC8};;{url}{ST}")
}
}
}
| rust | Apache-2.0 | 831a5646dd030785b6ea32c1c3ceb0f33b989779 | 2026-01-04T20:25:24.435580Z | false |
alexpasmantier/grip-grab | https://github.com/alexpasmantier/grip-grab/blob/831a5646dd030785b6ea32c1c3ceb0f33b989779/src/upgrade.rs | src/upgrade.rs | use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
#[cfg(not(feature = "upgrade"))]
pub fn upgrade_gg(_force: bool) {
let mut colored_stdout = StandardStream::stdout(ColorChoice::Always);
colored_stdout
.set_color(ColorSpec::new().set_fg(Some(Color::Red)).set_italic(true))
.expect("Failed to set color");
println!("\nββββββββββββββββββββββββββββββββββββββββββββββ");
println!("β Upgrade feature is not enabled. β");
println!("β Please recompile with `upgrade` feature β");
println!("β enabled to use this feature: β");
println!("β β");
println!("β cargo install grip-grab --features=upgrade β");
println!("ββββββββββββββββββββββββββββββββββββββββββββββ\n");
colored_stdout.reset().expect("Failed to reset color");
}
#[cfg(feature = "upgrade")]
pub fn upgrade_gg(force: bool) {
use std::{
io::{BufRead, BufReader},
process::Command,
thread::{self},
};
let mut colored_stdout = StandardStream::stdout(ColorChoice::Always);
colored_stdout
.set_color(ColorSpec::new().set_fg(Some(Color::Green)).set_italic(true))
.expect("Failed to set color");
println!("\nβββββββββββββββββββββββββββββββββββββββββββ");
println!("β Upgrading `gg` to its latest version... β");
println!("βββββββββββββββββββββββββββββββββββββββββββ\n");
let mut command = Command::new("cargo");
command.arg("install").arg("grip-grab");
if force {
command.arg("--force");
}
let mut output = command
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("Failed to spawn cargo install command");
colored_stdout
.set_color(
ColorSpec::new()
.set_fg(Some(Color::Rgb(128, 128, 128)))
.set_dimmed(true)
.set_italic(true),
)
.expect("Failed to set color");
println!("This may take a few moments..");
let stdout = output.stdout.take().expect("Failed to capture stdout");
let stderr = output.stderr.take().expect("Failed to capture stderr");
let stdout_thread = thread::spawn(move || {
let reader = BufReader::new(stdout);
for line in reader.lines() {
match line {
Ok(line) => println!("{line}"),
Err(e) => eprintln!("Error reading stdout: {e}"),
}
}
});
let stderr_thread = thread::spawn(move || {
let reader = BufReader::new(stderr);
for line in reader.lines() {
match line {
Ok(line) => eprintln!("{line}"),
Err(e) => eprintln!("Error reading stderr: {e}"),
}
}
});
stdout_thread.join().expect("Failed to join stdout thread");
stderr_thread.join().expect("Failed to join stderr thread");
let status = output.wait().expect("Failed to wait on output");
if status.success() {
colored_stdout
.set_color(
ColorSpec::new()
.set_fg(Some(Color::Green))
.set_italic(true)
.set_dimmed(false),
)
.expect("Failed to set color");
println!("\nYou're all set!");
} else {
colored_stdout
.set_color(
ColorSpec::new()
.set_fg(Some(Color::Red))
.set_italic(true)
.set_dimmed(false),
)
.expect("Failed to set color");
eprintln!("\nFailed to upgrade crate. See errors above.");
}
colored_stdout.reset().expect("Failed to reset color");
}
| rust | Apache-2.0 | 831a5646dd030785b6ea32c1c3ceb0f33b989779 | 2026-01-04T20:25:24.435580Z | false |
alexpasmantier/grip-grab | https://github.com/alexpasmantier/grip-grab/blob/831a5646dd030785b6ea32c1c3ceb0f33b989779/src/utils.rs | src/utils.rs | use std::path::{Path, PathBuf};
pub fn resolve_paths(paths: Vec<PathBuf>) -> Vec<PathBuf> {
paths.into_iter().map(|pb| resolve_path(&pb)).collect()
}
pub fn resolve_path(path: &Path) -> PathBuf {
path.canonicalize().unwrap()
}
| rust | Apache-2.0 | 831a5646dd030785b6ea32c1c3ceb0f33b989779 | 2026-01-04T20:25:24.435580Z | false |
alexpasmantier/grip-grab | https://github.com/alexpasmantier/grip-grab/blob/831a5646dd030785b6ea32c1c3ceb0f33b989779/src/main.rs | src/main.rs | use std::io::{self, stdin, Read};
use std::path::PathBuf;
use std::sync::{mpsc, Arc};
use clap::Parser;
use cli::Commands;
use fs::is_readable_stdin;
use grep::regex::{self, RegexMatcher};
use ignore::DirEntry;
use printer::PrinterConfig;
use search::{build_searcher, search_reader};
use thiserror::Error;
use upgrade::upgrade_gg;
use crate::cli::{process_cli_args, Cli};
use crate::fs::walk_builder;
use crate::printer::ResultsPrinter;
use crate::search::{build_matcher, search_file, FileResults};
mod cli;
mod fs;
mod printer;
mod search;
mod upgrade;
mod utils;
#[derive(Error, Debug)]
pub enum GGError {
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
Regex(#[from] regex::Error),
}
pub fn main() -> Result<(), GGError> {
let cli_args = process_cli_args(Cli::parse());
if let Some(subcommand) = cli_args.sub_command {
match subcommand {
Commands::Upgrade { force } => {
upgrade_gg(force);
return Ok(());
}
}
}
if is_readable_stdin() {
let stdin = stdin();
let mut buf = Vec::new();
if stdin.lock().read_to_end(&mut buf)? != 0 {
let matcher = build_matcher(&cli_args.patterns)?;
let mut searcher = build_searcher(cli_args.multiline);
match search_reader(buf.as_slice(), &matcher, &mut searcher) {
Ok(search_results) => {
let printer_config = PrinterConfig {
mode: cli_args.print_mode,
absolute_paths: cli_args.absolute_paths,
colored_output: cli_args.colored_output,
disable_hyperlinks: cli_args.disable_hyperlinks,
..Default::default()
};
let mut printer = ResultsPrinter::new(printer_config);
printer.write(FileResults {
path: PathBuf::from("stdin"),
results: search_results,
})?;
printer.wipeout()?;
}
Err(err) => {
eprintln!("Error: {err}");
}
}
return Ok(());
}
}
let haystack_builder = walk_builder(
cli_args.paths.iter().map(PathBuf::as_path).collect(),
&cli_args.ignored_paths,
cli_args.n_threads,
!cli_args.disregard_gitignore,
&cli_args.filter_filetypes,
);
let matcher: Arc<RegexMatcher> = Arc::new(build_matcher(&cli_args.patterns)?);
let (tx, printer_queue) = mpsc::channel();
std::thread::spawn(move || {
haystack_builder.build_parallel().run(|| {
let matcher = Arc::clone(&matcher);
let mut searcher = build_searcher(cli_args.multiline);
let tx = tx.clone();
Box::new(move |entry: Result<DirEntry, ignore::Error>| match entry {
Ok(entry) => {
if !entry.path().is_dir() {
let path = entry.path().to_path_buf();
match search_file(path, &matcher, &mut searcher) {
Ok(file_results) => {
if !file_results.is_empty() {
tx.send(file_results).unwrap_or(());
}
}
Err(_err) => (),
}
}
ignore::WalkState::Continue
}
Err(err) => {
eprintln!("Error: {err}");
ignore::WalkState::Continue
}
})
});
});
let printer_config = PrinterConfig {
mode: cli_args.print_mode,
absolute_paths: cli_args.absolute_paths,
colored_output: cli_args.colored_output,
disable_hyperlinks: cli_args.disable_hyperlinks,
disable_devicons: !cli_args.enable_devicons,
..Default::default()
};
let mut printer = ResultsPrinter::new(printer_config);
while let Ok(result) = printer_queue.recv() {
printer.write(result)?;
}
printer.wipeout()?;
Ok(())
}
| rust | Apache-2.0 | 831a5646dd030785b6ea32c1c3ceb0f33b989779 | 2026-01-04T20:25:24.435580Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_release/src/lib.rs | rust_icu_release/src/lib.rs | // Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! See LICENSE for licensing information.
//!
//! This library provides Cargo _features_ indicating the target ICU4C library version,
//! enabling some conditionally compiled Rust code in this crate that depends on the particular
//! ICU4C version.
//!
//! Please refer to README.md for instructions on how to build the library for your use.
use anyhow::{Result, Context, anyhow};
use std::process;
/// A `Command` that also knows its name.
pub struct Command {
name: String,
rep: process::Command,
}
impl Command {
/// Creates a new command to run, with the executable `name`.
pub fn new(name: &'static str) -> Self {
let rep = process::Command::new(&name);
let name = String::from(name);
Command { name, rep }
}
/// Runs this command with `args` as arguments.
pub fn run(&mut self, args: &[&str]) -> Result<String> {
self.rep.args(args);
let stdout = self.stdout().context("while getting stdout")?;
Ok(String::from(&stdout).trim().to_string())
}
// Captures the stdout of the command.
fn stdout(&mut self) -> Result<String> {
let output = self
.rep
.output()
.with_context(|| format!("could not execute command: {}", self.name))?;
let result = String::from_utf8(output.stdout)
.with_context(|| "could not convert output to UTF8")?;
Ok(result.trim().to_string())
}
}
/// A command representing an auto-configuration detector. Use `ICUConfig::new()` to create.
pub struct ICUConfig {
rep: Command,
}
impl ICUConfig {
/// Creates a new ICUConfig.
pub fn new() -> Self {
ICUConfig {
rep: Command::new("pkg-config"),
}
}
/// Obtains the major-minor version number for the library. Returns a string like `64.2`.
pub fn version(&mut self) -> Result<String> {
self.rep
.run(&["--modversion", "icu-i18n"])
.context("while getting ICU version; is pkg-config in $PATH?")
}
/// Returns the config major number. For example, will return "64" for
/// version "64.2"
pub fn version_major() -> Result<String> {
let version = ICUConfig::new().version().context("while getting ICU version")?;
let components = version.split('.');
let last = components
.take(1)
.last()
.with_context(|| format!("could not parse version number: {version}"))?;
Ok(last.to_string())
}
pub fn version_major_int() -> Result<i32> {
let version_str = ICUConfig::version_major().context("while getting ICU version")?;
version_str.parse().map_err(|err| anyhow!("could not parse version from string: '{version_str}': {err:?}"))
}
/// Obtains the prefix directory, e.g. `$HOME/local`
pub fn prefix(&mut self) -> Result<String> {
self.rep
.run(&["--variable=prefix", "icu-i18n"])
.with_context(|| "could not get config prefix")
}
/// Obtains the default library path for the libraries.
pub fn libdir(&mut self) -> Result<String> {
self.rep
.run(&["--variable=libdir", "icu-i18n"])
.context("could not get library directory")
}
/// Obtains the needed flags for the linker.
pub fn ldflags(&mut self) -> Result<String> {
self.rep
.run(&["--libs", "icu-i18n"])
.context("could not get the ld flags")
}
/// Obtains the needed flags for the C++ compiler.
pub fn cppflags(&mut self) -> Result<String> {
self.rep
.run(&["--cflags", "icu-i18n"])
.context("while getting the cpp flags")
}
/// Obtains the major-minor version number for the library. Returns a string like `64.2`.
pub fn install_dir(&mut self) -> Result<String> {
self.prefix()
}
}
pub fn run() -> Result<()> {
unsafe {
std::env::set_var("RUST_BACKTRACE", "full")
};
let icu_major_version = ICUConfig::version_major_int().context("while getting version")?;
println!("icu-major-version: {}", icu_major_version);
if icu_major_version >= 64 {
println!("cargo:rustc-cfg=feature=\"icu_version_64_plus\"");
}
if icu_major_version >= 67 {
println!("cargo:rustc-cfg=feature=\"icu_version_67_plus\"");
}
if icu_major_version >= 68 {
println!("cargo:rustc-cfg=feature=\"icu_version_68_plus\"");
}
// Starting from version 69, the feature flags depending on the version
// number work for up to a certain version, so that they can be retired
// over time.
if icu_major_version <= 69 {
println!("cargo:rustc-cfg=feature=\"icu_version_69_max\"");
}
println!("done");
Ok(())
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_udat/build.rs | rust_icu_udat/build.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! This build.rs script provides Cargo _features_ indicating the target ICU4C library version,
//! enabling some conditionally compiled Rust code in this crate that depends on the particular
//! ICU4C version.
//!
//! Please refer to README.md for instructions on how to build the library for your use.
#[cfg(feature = "icu_config")]
fn main() -> anyhow::Result<()> {
use rust_icu_release::run;
run()
}
/// No-op if icu_config is disabled.
#[cfg(not(feature = "icu_config"))]
fn main() {}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_udat/src/lib.rs | rust_icu_udat/src/lib.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Contains implementations of functions from ICU's `udat.h`.
//!
//! All functions that take `ustring::UChar` instead of a rust string reference do so for
//! efficiency. The encoding of `ustring::UChar` is uniform (in contrast to say UTF-8), so
//! repeated manipulation of that string does not waste CPU cycles.
//!
//! For detailed instructions for date and time formatting please refer to the [original Unicode
//! project documentation for date and time formatting](http://userguide.icu-project.org/formatparse/datetime)
use {
rust_icu_common as common, rust_icu_sys as sys, rust_icu_sys::versioned_function,
rust_icu_ucal as ucal, rust_icu_uloc as uloc, rust_icu_ustring as ustring,
};
use std::convert::{TryFrom, TryInto};
/// Implements `UDateTimePatternGenerator`. Since 0.5.1.
#[derive(Debug)]
pub struct UDatePatternGenerator {
rep: std::ptr::NonNull<sys::UDateTimePatternGenerator>,
}
impl std::clone::Clone for UDatePatternGenerator {
/// Implements `udatpg_clone`. Since 0.5.1.
fn clone(&self) -> Self {
let mut status = common::Error::OK_CODE;
let rep = unsafe {
let cloned = versioned_function!(udatpg_clone)(self.rep.as_ptr(), &mut status);
std::ptr::NonNull::new_unchecked(cloned)
};
UDatePatternGenerator{ rep }
}
}
// Implements `udatpg_close`.
common::simple_drop_impl!(UDatePatternGenerator, udatpg_close);
impl UDatePatternGenerator {
/// Implements `udatpg_open`. Since 0.5.1.
pub fn new(loc: &uloc::ULoc) -> Result<Self, common::Error> {
let mut status = common::Error::OK_CODE;
let asciiz = loc.as_c_str();
let rep = unsafe {
assert!(common::Error::is_ok(status));
let ptr = versioned_function!(udatpg_open)(
asciiz.as_ptr(),
&mut status,
);
std::ptr::NonNull::new_unchecked(ptr)
};
common::Error::ok_or_warning(status)?;
Ok(UDatePatternGenerator{ rep })
}
/// Implements `udatpg_getBestPattern`. Since 0.5.1.
pub fn get_best_pattern(&self, skeleton: &str) -> Result<String, common::Error> {
let skeleton = ustring::UChar::try_from(skeleton)?;
let result = self.get_best_pattern_ustring(&skeleton)?;
String::try_from(&result)
}
/// Implements `udatpg_getBestPattern`. Since 0.5.1.
pub fn get_best_pattern_ustring(&self, skeleton: &ustring::UChar) -> Result<ustring::UChar, common::Error> {
const BUFFER_CAPACITY: usize = 180;
ustring::buffered_uchar_method_with_retry!(
get_best_pattern_impl,
BUFFER_CAPACITY,
[f: *mut sys::UDateTimePatternGenerator, skel: *const sys::UChar, skel_len: i32,],
[]
);
get_best_pattern_impl(
versioned_function!(udatpg_getBestPattern),
self.rep.as_ptr(),
skeleton.as_c_ptr(), skeleton.len() as i32,
)
}
}
/// Implements `UDateFormat`
#[derive(Debug)]
pub struct UDateFormat {
// Internal C representation of UDateFormat. It is owned by this type and
// must be dropped by calling `udat_close`.
rep: *mut sys::UDateFormat,
}
impl Drop for UDateFormat {
/// Implements `udat_close`
fn drop(&mut self) {
unsafe {
versioned_function!(udat_close)(self.rep);
}
}
}
/// Parsed contains output of the call to `UDateFormat::parse_from_position`.
pub struct Parsed {
/// The point in time parsed out of the date-time string.
date: sys::UDate,
/// The position in the input string at which the parsing ended.
end_position: usize,
}
impl Parsed {
/// Returns the date resulting from a call to `UDateFormat::parse_from_position`.
pub fn date(&self) -> sys::UDate {
self.date
}
/// Returns the end position resulting from a call to `UDateFormat::parse_from_position`.
pub fn end_position(&self) -> usize {
self.end_position
}
}
impl UDateFormat {
/// Creates a new `UDateFormat` based on the provided styles.
///
/// Neither time_style nor date_style may be `UDAT_PATTERN`. If you need
/// formatting with a pattern, use instead `new_with_pattern`.
/// Implements `udat_open`
pub fn new_with_styles(
time_style: sys::UDateFormatStyle,
date_style: sys::UDateFormatStyle,
loc: &uloc::ULoc,
tz_id: &ustring::UChar,
) -> Result<Self, common::Error> {
assert_ne!(
time_style,
sys::UDateFormatStyle::UDAT_PATTERN,
"programmer error: time_style may not be UDAT_PATTERN"
);
assert_ne!(
date_style,
sys::UDateFormatStyle::UDAT_PATTERN,
"programmer error: date_style may not be UDAT_PATTERN"
);
// pattern is ignored if time_style or date_style aren't equal to pattern.
let pattern = ustring::UChar::try_from("").expect("pattern created");
Self::new_internal(time_style, date_style, loc, tz_id, &pattern)
}
/// Creates a new `UDateFormat` based on the provided pattern.
///
/// One example pattern is: "yyyy-MM-dd'T'HH:mm:ssXX".
///
/// Implements `udat_open`
pub fn new_with_pattern(
loc: &uloc::ULoc,
tz_id: &ustring::UChar,
pattern: &ustring::UChar,
) -> Result<Self, common::Error> {
Self::new_internal(
/*timestyle=*/ sys::UDateFormatStyle::UDAT_PATTERN,
/*datestyle=*/ sys::UDateFormatStyle::UDAT_PATTERN,
loc,
tz_id,
pattern,
)
}
// Generalized constructor based on `udat_open`. It is hidden from public eye because its
// input parameters are not orthogonal.
//
// Implements `udat_open`
fn new_internal(
time_style: sys::UDateFormatStyle,
date_style: sys::UDateFormatStyle,
loc: &uloc::ULoc,
tz_id: &ustring::UChar,
pattern: &ustring::UChar,
) -> Result<Self, common::Error> {
let mut status = common::Error::OK_CODE;
let asciiz = loc.as_c_str();
// If the timezone is empty, short-circuit it to default.
let (tz_id_ptr, tz_id_len): (*const rust_icu_sys::UChar, i32) = if tz_id.len() == 0 {
(std::ptr::null(), 0i32)
} else {
(tz_id.as_c_ptr(), tz_id.len() as i32)
};
// Requires that all pointers be valid. Should be guaranteed by all
// objects passed into this function.
let date_format = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(udat_open)(
time_style,
date_style,
asciiz.as_ptr(),
tz_id_ptr,
tz_id_len,
pattern.as_c_ptr(),
pattern.len() as i32,
&mut status,
)
};
common::Error::ok_or_warning(status)?;
Ok(UDateFormat { rep: date_format })
}
/// Implements `udat_setCalendar`
pub fn set_calendar(&mut self, calendar: &ucal::UCalendar) {
unsafe {
versioned_function!(udat_setCalendar)(self.rep, calendar.as_c_calendar());
};
}
/// Parses a date-time given as a string into a `sys::UDate` timestamp.
///
/// This version of date parsing does not allow reuse of the input parameters so it is less
/// useful for purposes that are not one-shot. See somewhat more detailed `parse_from_position`
/// instead.
///
/// Implements `udat_parse`
pub fn parse(&self, datetime: &str) -> Result<sys::UDate, common::Error> {
let datetime_uc = ustring::UChar::try_from(datetime)?;
self.parse_from_position(&datetime_uc, 0).map(|r| r.date)
}
/// Parses a date-time given as a string into a `sys::UDate` timestamp and a position
/// indicating the first index into `datetime` that was not consumed in parsing. The
/// `position` parameter indicates the index into `datetime` that parsing should start from.
///
/// Implements `udat_parse`
pub fn parse_from_position(
&self,
datetime: &ustring::UChar,
position: usize,
) -> Result<Parsed, common::Error> {
let mut status = common::Error::OK_CODE;
let mut _unused_pos: i32 = 0;
// We do not expect positions that exceed the range of i32.
let mut end_position: i32 = position as i32;
// Requires that self.rep, and datetime are valid values. Ensured by
// the guaranteses of UDateFormat and ustring::UChar.
let date = unsafe {
versioned_function!(udat_parse)(
self.rep,
datetime.as_c_ptr(),
datetime.len() as i32,
&mut end_position,
&mut status,
)
};
common::Error::ok_or_warning(status)?;
Ok(Parsed {
date,
end_position: end_position as usize,
})
}
/// Formats a date using this formatter.
///
/// Implements `udat_format`
pub fn format(&self, date_to_format: sys::UDate) -> Result<String, common::Error> {
// This approach follows the recommended practice for unicode conversions: adopt a
// resonably-sized buffer, then repeat the conversion if it fails the first time around.
const CAP: usize = 1024;
let mut status = common::Error::OK_CODE;
let mut result = ustring::UChar::new_with_capacity(CAP);
let mut field_position_unused = sys::UFieldPosition {
field: 0,
beginIndex: 0,
endIndex: 0,
};
// Requires that result is a buffer at least as long as CAP and that
// self.rep is a valid pointer to a `sys::UDateFormat` structure.
let total_size = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(udat_format)(
self.rep,
date_to_format,
result.as_mut_c_ptr(),
CAP as i32,
&mut field_position_unused,
&mut status,
)
} as usize;
common::Error::ok_or_warning(status)?;
result.resize(total_size as usize);
if total_size > CAP {
// Requires that result is a buffer that has length and capacity of
// exactly total_size, and that self.rep is a valid pointer to
// a `UDateFormat`.
unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(udat_format)(
self.rep,
date_to_format,
result.as_mut_c_ptr(),
total_size as i32,
&mut field_position_unused,
&mut status,
);
};
common::Error::ok_or_warning(status)?;
}
String::try_from(&result)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Restores the timezone once its scope ends.
struct RestoreTimezone {
timezone_to_restore: String,
}
impl Drop for RestoreTimezone {
fn drop(&mut self) {
RestoreTimezone::set_default_time_zone(&self.timezone_to_restore).unwrap();
}
}
impl RestoreTimezone {
/// Set the timezone to the requested one, and restores to whatever the timezone
/// was before the set once the struct goes out of scope.
fn new(set_timezone: &str) -> Self {
let timezone_to_restore =
RestoreTimezone::get_default_time_zone().expect("could get old time zone");
RestoreTimezone::set_default_time_zone(set_timezone).expect("set timezone");
RestoreTimezone {
timezone_to_restore,
}
}
// The two methods below are lifted from `rust_icu_ucal` to not introduce
// a circular dependency.
fn set_default_time_zone(zone_id: &str) -> Result<(), common::Error> {
let mut status = common::Error::OK_CODE;
let mut zone_id_uchar = ustring::UChar::try_from(zone_id)?;
zone_id_uchar.make_z();
// Requires zone_id_uchar to be a valid pointer until the function returns.
unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ucal_setDefaultTimeZone)(zone_id_uchar.as_c_ptr(), &mut status);
};
common::Error::ok_or_warning(status)
}
fn get_default_time_zone() -> Result<String, common::Error> {
let mut status = common::Error::OK_CODE;
// Preflight the time zone first.
let time_zone_length = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ucal_getDefaultTimeZone)(std::ptr::null_mut(), 0, &mut status)
} as usize;
common::Error::ok_preflight(status)?;
// Should this capacity include the terminating \u{0}?
let mut status = common::Error::OK_CODE;
let mut uchar = ustring::UChar::new_with_capacity(time_zone_length);
// Requires that uchar is a valid buffer. Should be guaranteed by the constructor above.
unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ucal_getDefaultTimeZone)(
uchar.as_mut_c_ptr(),
time_zone_length as i32,
&mut status,
)
};
common::Error::ok_or_warning(status)?;
String::try_from(&uchar)
}
}
#[test]
fn test_format_default_calendar() -> Result<(), common::Error> {
#[derive(Debug)]
struct Test {
_name: &'static str,
locale: &'static str,
timezone: &'static str,
date: sys::UDate,
expected: &'static str,
calendar: Option<ucal::UCalendar>,
}
let tests = vec![
Test {
_name: "French default",
locale: "fr-FR",
timezone: "America/Los_Angeles",
date: 100.0,
expected:
"mercredi 31 dΓ©cembre 1969 Γ 16:00:00 heure normale du Pacifique nord-amΓ©ricain",
calendar: None,
},
Test {
_name: "French default, a few hours later",
locale: "fr-FR",
timezone: "America/Los_Angeles",
date: 100000.0,
expected:
"mercredi 31 dΓ©cembre 1969 Γ 16:01:40 heure normale du Pacifique nord-amΓ©ricain",
calendar: None,
},
Test {
_name: "Serbian default",
locale: "sr-RS",
timezone: "America/Los_Angeles",
date: 100000.0,
expected:
"ΡΡΠ΅Π΄Π°, 31. Π΄Π΅ΡΠ΅ΠΌΠ±Π°Ρ 1969. 16:01:40 Π‘Π΅Π²Π΅ΡΠ½ΠΎΠ°ΠΌΠ΅ΡΠΈΡΠΊΠΎ ΠΏΠ°ΡΠΈΡΠΈΡΠΊΠΎ ΡΡΠ°Π½Π΄Π°ΡΠ΄Π½ΠΎ Π²ΡΠ΅ΠΌΠ΅",
calendar: None,
},
// TODO: The Dutch time zones regressed: https://unicode-org.atlassian.net/browse/CLDR-17389
//Test {
//_name: "Dutch default",
//locale: "nl-NL",
//timezone: "America/Los_Angeles",
//date: 100000.0,
//expected: "woensdag 31 december 1969 om 16:01:40 Pacific-standaardtijd",
//calendar: None,
//},
//Test {
//_name: "Dutch islamic overrides locale calendar and timezone",
//locale: "nl-NL-u-ca-gregorian",
//timezone: "America/Los_Angeles",
//date: 100000.0,
//expected: "woensdag 22 Sjawal 1389 om 16:01:40 Pacific-standaardtijd",
//calendar: Some(
//ucal::UCalendar::new(
//"America/Los_Angeles",
//"und-u-ca-islamic",
//sys::UCalendarType::UCAL_DEFAULT,
//)
//.expect("created calendar"),
//),
//},
//Test {
//_name: "Dutch islamic take from locale",
//locale: "nl-NL-u-ca-islamic",
//timezone: "America/Los_Angeles",
//date: 200000.0,
//expected: "woensdag 22 Sjawal 1389 AH om 16:03:20 Pacific-standaardtijd",
//calendar: None,
//},
//Test {
//_name: "Dutch islamic take from locale",
//locale: "nl-NL-u-ca-islamic",
//timezone: "America/Los_Angeles",
//date: 200000.0,
//expected: "woensdag 22 Sjawal 1389 AH om 16:03:20 Pacific-standaardtijd",
//calendar: None,
//},
];
let _restore_timezone = RestoreTimezone::new("UTC");
for t in tests {
let loc = uloc::ULoc::try_from(t.locale)?;
let tz_id = ustring::UChar::try_from(t.timezone)?;
let mut fmt = super::UDateFormat::new_with_styles(
sys::UDateFormatStyle::UDAT_FULL,
sys::UDateFormatStyle::UDAT_FULL,
&loc,
&tz_id,
)?;
if let Some(ref cal) = t.calendar {
fmt.set_calendar(&cal);
}
let fmt = fmt;
let actual = fmt.format(t.date)?;
assert_eq!(
actual, t.expected,
"(left==actual; right==expected)\n\ttest: {:?}",
t
);
}
Ok(())
}
#[test]
fn test_format_pattern() -> Result<(), common::Error> {
#[derive(Debug)]
struct Test {
date: sys::UDate,
pattern: &'static str,
expected: &'static str,
}
let tests = vec![
Test {
date: 100.0,
pattern: "yyyy-MM-dd'T'HH:mm:ssXX",
expected: "1969-12-31T19:00:00-0500",
},
Test {
date: 100000.0,
pattern: "yyyy-MM-dd'T'HH",
expected: "1969-12-31T19",
},
Test {
date: 100000.0,
pattern: "V",
expected: "usnyc",
},
];
let loc = uloc::ULoc::try_from("en-US")?;
let tz_id = ustring::UChar::try_from("America/New_York")?;
for t in tests {
let pattern = ustring::UChar::try_from(t.pattern)?;
let fmt = super::UDateFormat::new_with_pattern(&loc, &tz_id, &pattern)?;
let actual = fmt.format(t.date)?;
assert_eq!(
actual, t.expected,
"want: {:?}, got: {:?}",
t.expected, actual
);
}
Ok(())
}
#[test]
fn parse_utf8() -> Result<(), common::Error> {
#[derive(Debug)]
struct Test {
input: &'static str,
pattern: &'static str,
expected: sys::UDate,
}
let tests: Vec<Test> = vec![
Test {
input: "2018-10-30T15:30:00-07:00",
pattern: "yyyy-MM-dd'T'HH:mm:ssXX",
expected: 1540938600000.0 as sys::UDate,
},
Test {
input: "2018-10-30T15:30:00-07:00",
// The entire "time" portion of this string is not used.
pattern: "yyyy-MM-dd",
expected: 1540872000000.0 as sys::UDate,
},
];
let loc = uloc::ULoc::try_from("en-US")?;
let tz_id = ustring::UChar::try_from("America/New_York")?;
for test in tests {
let pattern = ustring::UChar::try_from(test.pattern)?;
let format = super::UDateFormat::new_with_pattern(&loc, &tz_id, &pattern)?;
let actual = format.parse(test.input)?;
assert_eq!(
actual, test.expected,
"want: {:?}, got: {:?}",
test.expected, actual
)
}
Ok(())
}
#[test]
fn best_pattern() -> Result<(), common::Error> {
#[derive(Debug)]
struct Test {
locale: &'static str,
skeleton: &'static str,
expected: &'static str,
}
let tests: Vec<Test> = vec![
Test {
locale: "sr-RS",
skeleton: "MMMMj",
expected: "LLLL HH",
},
Test {
locale: "en-US",
skeleton: "EEEE yyy LLL d H m s",
expected: "EEEE, MMM d, yyy, HH:mm:ss",
},
];
for test in tests {
let locale = uloc::ULoc::try_from(test.locale)?;
let gen = UDatePatternGenerator::new(&locale)?.clone();
let actual = gen.get_best_pattern(&test.skeleton)?;
assert_eq!(actual, test.expected, "for test: {:?}", &test);
}
Ok(())
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.