Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
998 changes: 537 additions & 461 deletions Cargo.lock

Large diffs are not rendered by default.

17 changes: 9 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,31 +1,32 @@
[package]
name = "cosmic-bg"
version = "0.1.0"
version = "1.0.3"
edition = "2024"
rust-version = "1.85"
rust-version = "1.90"

[dependencies]
color-eyre = "0.6.5"
colorgrad = { workspace = true }
cosmic-bg-config = { path = "./config" }
eyre = "0.6.12"
fast_image_resize = { version = "5.1.4", features = ["image"] }
fast_image_resize = { version = "6.0.0", features = ["image"] }
image = { workspace = true, features = ["hdr", "jpeg", "png", "rayon", "webp"] }
jxl-oxide = { version = "0.12.4", features = ["image"] }
rayon = "1.11"
jxl-oxide = { version = "0.12.5", features = ["image"] }
notify = "8.2.0"
rand = "0.9.2"
sctk = { package = "smithay-client-toolkit", version = "0.20.0" }
tracing = { workspace = true }
tracing-subscriber = "0.3.20"
tracing-subscriber = "0.3.22"
walkdir = "2.5"

[workspace]
members = ["config"]

[workspace.dependencies]
colorgrad = "0.7.2"
image = { version = "0.25.6", default-features = false }
tracing = "0.1.41"
colorgrad = "0.8.0"
image = { version = "0.25.9", default-features = false }
tracing = "0.1.44"

[dependencies.cosmic-config]
git = "https://github.com/pop-os/libcosmic"
Expand Down
4 changes: 2 additions & 2 deletions config/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
[package]
name = "cosmic-bg-config"
version = "0.1.0"
version = "1.0.3"
edition = "2024"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
derive_setters = "0.1.8"
derive_setters = "0.1.9"
image.workspace = true
serde = { version = "1.0", features = ["derive"] }
tracing.workspace = true
Expand Down
8 changes: 4 additions & 4 deletions config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,10 +303,10 @@ impl Config {

let new_value = self.outputs.iter().cloned().collect::<Vec<_>>();

if context.backgrounds() != new_value {
if let Err(why) = context.0.set::<Vec<String>>(BACKGROUNDS, new_value) {
tracing::error!(?why, "failed to update outputs");
}
if context.backgrounds() != new_value
&& let Err(why) = context.0.set::<Vec<String>>(BACKGROUNDS, new_value)
{
tracing::error!(?why, "failed to update outputs");
}

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[toolchain]
channel = "1.85"
channel = "1.90"
87 changes: 36 additions & 51 deletions src/colored.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,12 @@
use colorgrad::{Color, Gradient as ColorGradient};
use cosmic_bg_config::Gradient;
use image::Rgb32FImage;
use rayon::prelude::*;

/// Generate a background image from a color.
pub fn single(color: [f32; 3], width: u32, height: u32) -> Rgb32FImage {
let mut imgbuf = Rgb32FImage::new(width, height);

let pixel = image::Rgb(color);

for x in 0..width {
for y in 0..height {
imgbuf.put_pixel(x, y, pixel);
}
}

imgbuf
image::ImageBuffer::from_pixel(width, height, pixel)
}

/// Generate a background image from a gradient.
Expand All @@ -26,14 +18,8 @@ pub fn gradient(
height: u32,
) -> Result<Rgb32FImage, colorgrad::GradientBuilderError> {
let mut colors = Vec::with_capacity(gradient.colors.len());

for &[r, g, b] in &*gradient.colors {
colors.push(colorgrad::Color::from_linear_rgba(
f32::from(r),
f32::from(g),
f32::from(b),
1.0,
));
colors.push(colorgrad::Color::from_linear_rgba(r, g, b, 1.0));
}

let grad = colorgrad::GradientBuilder::new()
Expand All @@ -42,45 +28,44 @@ pub fn gradient(
.build::<colorgrad::LinearGradient>()?;

let mut imgbuf = image::ImageBuffer::new(width, height);

let width = f64::from(width);
let height = f64::from(height);
let width = width as f32;
let height = height as f32;
let orientation = gradient.radius as u16;

let (dmin, dmax) = grad.domain();
let angle = gradient.radius.to_radians();
let cos = f32::cos(angle);
let sin = f32::sin(angle);
const SCALE: f32 = 0.015;
let w_scale = width / SCALE;
let h_scale = height / SCALE;

// Map t which is in range [a, b] to range [c, d]
#[allow(clippy::items_after_statements)]
fn remap(t: f64, a: f64, b: f64, c: f64, d: f64) -> f64 {
fn remap(t: f32, a: f32, b: f32, c: f32, d: f32) -> f32 {
(t - a) * ((d - c) / (b - a)) + c
}

#[allow(clippy::items_after_statements)]
const SCALE: f64 = 0.015;

let positioner: Box<dyn Fn(u32, u32) -> f64> = match gradient.radius as u16 {
0 => Box::new(|_x, y| 1.0 - (y as f64 / height)),
90 => Box::new(|x, _y| x as f64 / width),
180 => Box::new(|_x, y| y as f64 / height),
270 => Box::new(|x, _y| 1.0 - (x as f64 / width)),
_ => Box::new(|x, y| {
let (dmin, dmax) = grad.domain();
let angle = f64::from(gradient.radius.to_radians());
let (x, y) = (f64::from(x) - width / SCALE, f64::from(y) - height / SCALE);

remap(
x * f64::cos(angle) - y * f64::sin(angle),
-width / SCALE,
width / SCALE,
f64::from(dmin),
f64::from(dmax),
)
}),
};

#[allow(clippy::cast_possible_truncation)]
for (x, y, pixel) in imgbuf.enumerate_pixels_mut() {
let Color { r, g, b, .. } = grad.at(positioner(x, y) as f32);

*pixel = image::Rgb([r as f32, g as f32, b as f32]);
}
imgbuf.par_enumerate_pixels_mut().for_each(|(x, y, pixel)| {
let x_f = x as f32;
let y_f = y as f32;

let pos = match orientation {
0 => 1.0 - (y_f / height),
90 => x_f / width,
180 => y_f / height,
270 => 1.0 - (x_f / width),
_ => remap(
(x_f - w_scale) * cos - (y_f - h_scale) * sin,
-w_scale,
w_scale,
dmin,
dmax,
),
};

let Color { r, g, b, .. } = grad.at(pos);
*pixel = image::Rgb([r, g, b]);
});

Ok(imgbuf)
}
15 changes: 8 additions & 7 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ fn main() -> color_eyre::Result<()> {
}
}

let _ = jxl_oxide::integration::register_image_decoding_hook();

init_logger();

let conn = Connection::connect_to_env().wrap_err("wayland client connection failed")?;
Expand Down Expand Up @@ -162,13 +164,12 @@ fn main() -> color_eyre::Result<()> {

_ => {
tracing::debug!(key, "key modified");
if let Some(output) = key.strip_prefix("output.") {
if let Ok(new_entry) = conf_context.entry(key) {
if let Some(existing) = state.config.entry_mut(output) {
*existing = new_entry;
changes_applied = true;
}
}
if let Some(output) = key.strip_prefix("output.")
&& let Ok(new_entry) = conf_context.entry(key)
&& let Some(existing) = state.config.entry_mut(output)
{
*existing = new_entry;
changes_applied = true;
}
}
}
Expand Down
75 changes: 23 additions & 52 deletions src/wallpaper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,14 @@ use crate::{CosmicBg, CosmicBgLayer};

use std::{
collections::VecDeque,
fs::{self, File},
fs,
path::PathBuf,
time::{Duration, Instant},
};

use cosmic_bg_config::{Color, Entry, SamplingMethod, ScalingMode, Source, state::State};
use cosmic_config::CosmicConfigEntry;
use eyre::eyre;
use image::{DynamicImage, ImageReader};
use jxl_oxide::integration::JxlDecoder;
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use rand::{rng, seq::SliceRandom};
use sctk::reexports::{
Expand Down Expand Up @@ -118,7 +116,7 @@ impl Wallpaper {

if cur_resized_img
.as_ref()
.map_or(true, |img| img.width() != width || img.height() != height)
.is_none_or(|img| img.width() != width || img.height() != height)
{
let Some(source) = self.current_source.as_ref() else {
tracing::info!("No source for wallpaper");
Expand All @@ -128,39 +126,23 @@ impl Wallpaper {
cur_resized_img = match source {
Source::Path(path) => {
if self.current_image.is_none() {
self.current_image = Some(match path.extension() {
Some(ext) if ext == "jxl" => match decode_jpegxl(&path) {
Ok(image) => image,
self.current_image = match ImageReader::open(path)
.ok()
.and_then(|f| f.with_guessed_format().ok())
{
Some(f) => match f.decode() {
Ok(img) => Some(img),
Err(why) => {
tracing::warn!(
?why,
"jpegl-xl image decode failed: {}",
"Failed to decode image: {}",
path.display()
);
continue;
}
},

_ => match ImageReader::open(&path) {
Ok(img) => {
match img
.with_guessed_format()
.ok()
.and_then(|f| f.decode().ok())
{
Some(img) => img,
None => {
tracing::warn!(
"could not decode image: {}",
path.display()
);
continue;
}
}
}
Err(_) => continue,
},
});
None => continue,
};
}
let img = self.current_image.as_ref().unwrap();

Expand Down Expand Up @@ -279,24 +261,24 @@ impl Wallpaper {
};

// If a wallpaper from this slideshow was previously set, resume with that wallpaper.
if let Some(Source::Path(last_path)) = current_image(&self.entry.output) {
if image_queue.contains(&last_path) {
while let Some(path) = image_queue.pop_front() {
if path == last_path {
image_queue.push_front(path);
break;
}

image_queue.push_back(path);
if let Some(Source::Path(last_path)) = current_image(&self.entry.output)
&& image_queue.contains(&last_path)
{
while let Some(path) = image_queue.pop_front() {
if path == last_path {
image_queue.push_front(path);
break;
}

image_queue.push_back(path);
}
}
}

image_queue.pop_front().map(|current_image_path| {
if let Some(current_image_path) = image_queue.pop_front() {
self.current_source = Some(Source::Path(current_image_path.clone()));
image_queue.push_back(current_image_path);
});
}
}

Source::Color(ref c) => {
Expand Down Expand Up @@ -359,7 +341,7 @@ impl Wallpaper {
return TimeoutAction::Drop; // Drop if no item found for this timer
};

while let Some(next) = item.image_queue.pop_front() {
if let Some(next) = item.image_queue.pop_front() {
item.current_source = Some(Source::Path(next.clone()));
if let Err(err) = item.save_state() {
error!("{err}");
Expand Down Expand Up @@ -402,14 +384,3 @@ fn current_image(output: &str) -> Option<Source> {

wallpaper.map(|(_name, path)| path)
}

/// Decodes JPEG XL image files into `image::DynamicImage` via `jxl-oxide`.
fn decode_jpegxl(path: &std::path::Path) -> eyre::Result<DynamicImage> {
let file = File::open(path).map_err(|why| eyre!("failed to open jxl image file: {why}"))?;

let decoder =
JxlDecoder::new(file).map_err(|why| eyre!("failed to read jxl image header: {why}"))?;

image::DynamicImage::from_decoder(decoder)
.map_err(|why| eyre!("failed to decode jxl image: {why}"))
}