Skip to content

Commit

Permalink
wip: support desktop portal color-scheme, and accent variables
Browse files Browse the repository at this point in the history
  • Loading branch information
wash2 committed Mar 2, 2024
1 parent 604c3f0 commit 6b7b3b6
Show file tree
Hide file tree
Showing 6 changed files with 107 additions and 34 deletions.
3 changes: 2 additions & 1 deletion examples/application/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ edition = "2021"
[dependencies]
tracing = "0.1.37"
tracing-subscriber = "0.3.17"
tracing-log = "0.2.0"

[dependencies.libcosmic]
path = "../../"
default-features = false
features = ["debug", "winit", "tokio"]
features = ["debug", "winit", "tokio", "xdg-portal"]
6 changes: 4 additions & 2 deletions examples/application/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ impl Page {
/// Runs application with these settings
#[rustfmt::skip]
fn main() -> Result<(), Box<dyn std::error::Error>> {
tracing_subscriber::fmt::init();
let _ = tracing_log::LogTracer::init();

let input = vec![
(Page::Page1, "🖖 Hello from libcosmic.".into()),
(Page::Page2, "🌟 This is an example application.".into()),
Expand All @@ -44,8 +47,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
.default_icon_theme("Pop")
.default_text_size(16.0)
.scale_factor(1.0)
.size(Size::new(1024., 768.))
.theme(cosmic::Theme::dark());
.size(Size::new(1024., 768.));

cosmic::app::run::<App>(settings, input)?;

Expand Down
29 changes: 20 additions & 9 deletions src/app/cosmic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ use iced::event::PlatformSpecific;
use iced::multi_window::Application as IcedApplication;
#[cfg(feature = "wayland")]
use iced::wayland::Application as IcedApplication;
use iced::window;
#[cfg(not(any(feature = "multi-window", feature = "wayland")))]
use iced::Application as IcedApplication;
use iced::{window, Command};
use iced_futures::event::listen_with;
#[cfg(not(feature = "wayland"))]
use iced_runtime::command::Action;
Expand Down Expand Up @@ -54,9 +54,9 @@ pub enum Message {
/// Toggles the condensed status of the nav bar.
ToggleNavBarCondensed,
/// Notification of system theme changes.
SystemThemeChange(Theme),
SystemThemeChange(Vec<&'static str>, Theme),
/// Notification of system theme mode changes.
SystemThemeModeChange(ThemeMode),
SystemThemeModeChange(Vec<&'static str>, ThemeMode),
/// Updates the window maximized state
WindowMaximized(window::Id, bool),
/// Updates the tracked window geometry.
Expand Down Expand Up @@ -196,7 +196,10 @@ where
for e in update.errors {
tracing::error!("{e}");
}
Message::SystemThemeChange(crate::theme::Theme::system(Arc::new(update.config)))
Message::SystemThemeChange(
update.keys,
crate::theme::Theme::system(Arc::new(update.config)),
)
})
.map(super::Message::Cosmic),
self.app
Expand All @@ -206,7 +209,7 @@ where
for e in update.errors {
tracing::error!("{e}");
}
Message::SystemThemeModeChange(update.config)
Message::SystemThemeModeChange(update.keys, update.config)
})
.map(super::Message::Cosmic),
window_events.map(super::Message::Cosmic),
Expand All @@ -218,7 +221,7 @@ where
.unwrap_or_else(Subscription::none),
#[cfg(feature = "xdg-portal")]
crate::theme::portal::desktop_settings()
.map(|e| Message::DesktopSettings(e))
.map(Message::DesktopSettings)
.map(super::Message::Cosmic),
])
}
Expand Down Expand Up @@ -380,7 +383,8 @@ impl<T: Application> Cosmic<T> {
});
}

Message::SystemThemeChange(theme) => {
Message::SystemThemeChange(keys, theme) => {
let cmd = self.app.system_theme_update(&keys, theme.cosmic());
// Record the last-known system theme in event that the current theme is custom.
self.app.core_mut().system_theme = theme.clone();
let portal_accent = self.app.core().portal_accent;
Expand All @@ -402,6 +406,8 @@ impl<T: Application> Cosmic<T> {
cosmic_theme.set_theme(new_theme.theme_type);
}
});

return cmd;
}

Message::ScaleFactor(factor) => {
Expand All @@ -412,7 +418,9 @@ impl<T: Application> Cosmic<T> {
self.app.on_app_exit();
return self.close();
}
Message::SystemThemeModeChange(mode) => {
Message::SystemThemeModeChange(keys, mode) => {
let mut cmds = vec![self.app.system_theme_mode_update(&keys, &mode)];

let core = self.app.core_mut();
let prev_is_dark = core.system_is_dark();
core.system_theme_mode = mode;
Expand All @@ -425,7 +433,9 @@ impl<T: Application> Cosmic<T> {
} else {
crate::theme::system_light()
};
cmds.push(self.app.system_theme_update(&[], new_theme.cosmic()));

let core = self.app.core_mut();
new_theme = if let Some(a) = core.portal_accent {
let t_inner = new_theme.cosmic();
if a.distance_squared(*t_inner.accent_color()) > 0.00001 {
Expand All @@ -447,6 +457,7 @@ impl<T: Application> Cosmic<T> {
}
});
}
return Command::batch(cmds);
}
Message::Activate(_token) => {
#[cfg(feature = "wayland")]
Expand Down Expand Up @@ -498,7 +509,7 @@ impl<T: Application> Cosmic<T> {
}
#[cfg(feature = "xdg-portal")]
Message::DesktopSettings(crate::theme::portal::Desktop::Accent(c)) => {
use palette::{IntoColor, Oklch, Oklcha, Srgb, Srgba};
use palette::Srgba;

let c = Srgba::new(c.red() as f32, c.green() as f32, c.blue() as f32, 1.0);
let core = self.app.core_mut();
Expand Down
18 changes: 18 additions & 0 deletions src/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,24 @@ where
iced::Command::none()
}

/// Respond to a system theme change
fn system_theme_update(
&mut self,
keys: &[&'static str],
new_theme: &cosmic_theme::Theme,
) -> iced::Command<Message<Self::Message>> {
iced::Command::none()
}

/// Respond to a system theme mode change
fn system_theme_mode_update(
&mut self,
keys: &[&'static str],
new_theme: &cosmic_theme::ThemeMode,
) -> iced::Command<Message<Self::Message>> {
iced::Command::none()
}

/// Constructs the view for the main window.
fn view(&self) -> Element<Self::Message>;

Expand Down
4 changes: 2 additions & 2 deletions src/theme/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,8 @@ pub fn system_dark() -> Theme {
}

pub fn system_light() -> Theme {
let Ok(helper) = crate::cosmic_theme::Theme::dark_config() else {
return Theme::dark();
let Ok(helper) = crate::cosmic_theme::Theme::light_config() else {
return Theme::light();
};

let t = crate::cosmic_theme::Theme::get_entry(&helper).unwrap_or_else(|(errors, theme)| {
Expand Down
81 changes: 61 additions & 20 deletions src/theme/portal.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use ashpd::desktop::settings::{ColorScheme, Contrast};
use ashpd::desktop::Color;
use iced::futures::{self, select, FutureExt, SinkExt, StreamExt};
use iced::Subscription;
use iced_futures::subscription;
use tracing::error;

#[derive(Debug, Clone)]
pub enum Desktop {
Expand All @@ -15,12 +17,56 @@ pub fn desktop_settings() -> iced_futures::Subscription<Desktop> {
async move {
let Ok(settings) = ashpd::desktop::settings::Settings::new().await else {
// wait forever
error!("Failed to create the settings proxy");
futures::future::pending::<()>().await;
unreachable!()
};

match settings.color_scheme().await {
Ok(color_scheme) => {
dbg!(color_scheme);
let _ = tx.send(Desktop::ColorScheme(color_scheme)).await;
}
Err(err) => error!("Failed to get the color scheme {err:?}"),
};
// match settings
// .read::<ashpd::zvariant::OwnedValue>("org.freedesktop.appearance", "accent-color")
// .await
// {
// Ok(accent_color) => {
// dbg!(&accent_color);
// // let _ = tx.send(Desktop::Accent(accent_color)).await;
// }
// Err(err) => error!("Failed to get the accent color {err:?}"),
// };
match settings.contrast().await {
Ok(contrast) => {
dbg!(contrast);
let _ = tx.send(Desktop::Contrast(contrast)).await;
}
Err(err) => error!("Failed to get the contrast {err:?}"),
};

let mut color_scheme_stream = settings.receive_color_scheme_changed().await.ok();
let mut accent_stream = settings.receive_accent_color_changed().await.ok();
if color_scheme_stream.is_none() {
error!("Failed to receive color scheme changes");
}
// Item type is wrong in this version
// updating requires updating to zbus 4
let mut accent_stream = settings
.receive_setting_changed_with_args::<Color>(
"org.freedesktop.appearance",
"accent-color",
)
.await
.ok();
if accent_stream.is_none() {
error!("Failed to receive accent color changes");
}
let mut contrast_stream = settings.receive_contrast_changed().await.ok();
if contrast_stream.is_none() {
error!("Failed to receive contrast changes");
}

loop {
let next_color_scheme = async {
Expand All @@ -29,18 +75,12 @@ pub fn desktop_settings() -> iced_futures::Subscription<Desktop> {
}
futures::future::pending().await
};
let next_accent = async {
if let Some(s) = accent_stream.as_mut() {
// Item type is wrong in this version
// updating requires updating to zbus 4
return if s.next().await.is_some() {
settings.accent_color().await.ok()
} else {
None
};
}
futures::future::pending().await
};
// let next_accent = async {
// if let Some(s) = accent_stream.as_mut() {
// return s.next().await.and_then(std::result::Result::ok);
// }
// futures::future::pending().await
// };
let next_contrast = async {
if let Some(s) = contrast_stream.as_mut() {
return s.next().await;
Expand All @@ -56,13 +96,14 @@ pub fn desktop_settings() -> iced_futures::Subscription<Desktop> {
color_scheme_stream = None;
}
},
a = next_accent.fuse() => {
if let Some(a) = a {
_ = tx.send(Desktop::Accent(a)).await;
} else {
accent_stream = None;
}
},
// a = next_accent.fuse() => {
// dbg!(a);
// if let Some(a) = a {
// _ = tx.send(Desktop::Accent(a)).await;
// } else {
// accent_stream = None;
// }
// },
c = next_contrast.fuse() => {
if let Some(c) = c {
_ = tx.send(Desktop::Contrast(c)).await;
Expand Down

0 comments on commit 6b7b3b6

Please sign in to comment.