Move Cosmic Applets into new Dir & remove old applets
This commit is contained in:
parent
813e6c0aff
commit
a682b8deb0
134 changed files with 0 additions and 1354 deletions
324
cosmic-applet-battery/src/app.rs
Normal file
324
cosmic-applet-battery/src/app.rs
Normal file
|
|
@ -0,0 +1,324 @@
|
|||
use crate::backlight::{
|
||||
screen_backlight_subscription, ScreenBacklightRequest, ScreenBacklightUpdate,
|
||||
};
|
||||
use crate::config;
|
||||
use crate::fl;
|
||||
use crate::upower_device::{device_subscription, DeviceDbusEvent};
|
||||
use crate::upower_kbdbacklight::{
|
||||
kbd_backlight_subscription, KeyboardBacklightRequest, KeyboardBacklightUpdate,
|
||||
};
|
||||
use cosmic::applet::CosmicAppletHelper;
|
||||
use cosmic::iced::alignment::Horizontal;
|
||||
use cosmic::iced::{
|
||||
executor,
|
||||
widget::{button, column, row, text, slider},
|
||||
window, Alignment, Application, Command, Length, Subscription,
|
||||
};
|
||||
use cosmic::iced_native::window::Settings;
|
||||
use cosmic::iced_style::application::{self, Appearance};
|
||||
use cosmic::iced_style::svg;
|
||||
use cosmic::theme::{self, Svg};
|
||||
use cosmic::widget::{icon, toggler, horizontal_rule};
|
||||
use cosmic::{iced_style, settings, Element, Theme};
|
||||
use cosmic_panel_config::{PanelAnchor, PanelSize};
|
||||
use iced_sctk::application::SurfaceIdWrapper;
|
||||
use iced_sctk::command::platform_specific::wayland::window::SctkWindowSettings;
|
||||
use iced_sctk::commands::popup::{destroy_popup, get_popup};
|
||||
use iced_sctk::settings::InitialSurface;
|
||||
use iced_sctk::Color;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
|
||||
// XXX improve
|
||||
// TODO: time to empty varies? needs averaging?
|
||||
fn format_duration(duration: Duration) -> String {
|
||||
let secs = duration.as_secs();
|
||||
if secs > 60 {
|
||||
let min = secs / 60;
|
||||
if min > 60 {
|
||||
format!("{}:{:02}", min / 60, min % 60)
|
||||
} else {
|
||||
format!("{}{}", min, fl!("minutes"))
|
||||
}
|
||||
} else {
|
||||
format!("{}{}", secs, fl!("seconds"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run() -> cosmic::iced::Result {
|
||||
let helper = CosmicAppletHelper::default();
|
||||
CosmicBatteryApplet::run(helper.window_settings())
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct CosmicBatteryApplet {
|
||||
icon_name: String,
|
||||
theme: Theme,
|
||||
charging_limit: bool,
|
||||
battery_percent: f64,
|
||||
time_remaining: Duration,
|
||||
kbd_brightness: f64,
|
||||
screen_brightness: f64,
|
||||
popup: Option<window::Id>,
|
||||
id_ctr: u32,
|
||||
screen_sender: Option<UnboundedSender<ScreenBacklightRequest>>,
|
||||
kbd_sender: Option<UnboundedSender<KeyboardBacklightRequest>>,
|
||||
applet_helper: CosmicAppletHelper,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum Message {
|
||||
TogglePopup,
|
||||
Update {
|
||||
icon_name: String,
|
||||
percent: f64,
|
||||
time_to_empty: i64,
|
||||
},
|
||||
SetKbdBrightness(i32),
|
||||
SetScreenBrightness(i32),
|
||||
SetChargingLimit(bool),
|
||||
UpdateKbdBrightness(f64),
|
||||
UpdateScreenBrightness(f64),
|
||||
OpenBatterySettings,
|
||||
InitKbdBacklight(UnboundedSender<KeyboardBacklightRequest>, f64),
|
||||
InitScreenBacklight(UnboundedSender<ScreenBacklightRequest>, f64),
|
||||
Errored(String),
|
||||
Ignore,
|
||||
}
|
||||
|
||||
impl Application for CosmicBatteryApplet {
|
||||
type Message = Message;
|
||||
type Theme = Theme;
|
||||
type Executor = executor::Default;
|
||||
type Flags = ();
|
||||
|
||||
fn new(_flags: ()) -> (Self, Command<Message>) {
|
||||
(
|
||||
CosmicBatteryApplet {
|
||||
icon_name: "battery-symbolic".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
Command::none(),
|
||||
)
|
||||
}
|
||||
|
||||
fn title(&self) -> String {
|
||||
config::APP_ID.to_string()
|
||||
}
|
||||
|
||||
fn update(&mut self, message: Message) -> Command<Message> {
|
||||
match message {
|
||||
Message::SetKbdBrightness(brightness) => {
|
||||
self.kbd_brightness = (brightness as f64 / 100.0).clamp(0., 1.);
|
||||
if let Some(tx) = &self.kbd_sender {
|
||||
let _ = tx.send(KeyboardBacklightRequest::Set(self.kbd_brightness));
|
||||
}
|
||||
}
|
||||
Message::SetScreenBrightness(brightness) => {
|
||||
self.screen_brightness = brightness as f64 / 100.0;
|
||||
if let Some(tx) = &self.screen_sender {
|
||||
let _ = tx.send(ScreenBacklightRequest::Set(self.screen_brightness));
|
||||
}
|
||||
}
|
||||
Message::SetChargingLimit(enable_charging_limit) => {
|
||||
self.charging_limit = enable_charging_limit;
|
||||
}
|
||||
Message::OpenBatterySettings => {
|
||||
// TODO Ashley
|
||||
}
|
||||
Message::Errored(_) => {
|
||||
// TODO log errors
|
||||
}
|
||||
Message::TogglePopup => {
|
||||
if let Some(p) = self.popup.take() {
|
||||
return destroy_popup(p);
|
||||
} else {
|
||||
if let Some(tx) = &self.kbd_sender {
|
||||
let _ = tx.send(KeyboardBacklightRequest::Get);
|
||||
}
|
||||
if let Some(tx) = &self.screen_sender {
|
||||
let _ = tx.send(ScreenBacklightRequest::Get);
|
||||
}
|
||||
|
||||
self.id_ctr += 1;
|
||||
let new_id = window::Id::new(self.id_ctr);
|
||||
self.popup.replace(new_id);
|
||||
|
||||
let popup_settings =
|
||||
self.applet_helper.get_popup_settings(window::Id::new(0), new_id, (400, 240), None, None);
|
||||
return get_popup(popup_settings);
|
||||
}
|
||||
}
|
||||
Message::Update {
|
||||
icon_name,
|
||||
percent,
|
||||
time_to_empty,
|
||||
} => {
|
||||
self.icon_name = icon_name;
|
||||
self.battery_percent = percent;
|
||||
self.time_remaining = Duration::from_secs(time_to_empty as u64);
|
||||
}
|
||||
Message::UpdateKbdBrightness(b) => {
|
||||
self.kbd_brightness = b;
|
||||
}
|
||||
Message::Ignore => {}
|
||||
Message::InitKbdBacklight(tx, brightness) => {
|
||||
let _ = tx.send(KeyboardBacklightRequest::Get);
|
||||
self.kbd_sender = Some(tx);
|
||||
self.kbd_brightness = brightness;
|
||||
}
|
||||
Message::InitScreenBacklight(tx, brightness) => {
|
||||
let _ = tx.send(ScreenBacklightRequest::Get);
|
||||
self.screen_sender = Some(tx);
|
||||
self.screen_brightness = brightness;
|
||||
}
|
||||
Message::UpdateScreenBrightness(b) => {
|
||||
self.screen_brightness = b;
|
||||
}
|
||||
}
|
||||
Command::none()
|
||||
}
|
||||
fn view(&self, id: SurfaceIdWrapper) -> Element<Message> {
|
||||
match id {
|
||||
SurfaceIdWrapper::LayerSurface(_) => unimplemented!(),
|
||||
SurfaceIdWrapper::Window(_) => self.applet_helper.icon_button(
|
||||
&self.icon_name,
|
||||
)
|
||||
.on_press(Message::TogglePopup)
|
||||
.into(),
|
||||
SurfaceIdWrapper::Popup(_) => {
|
||||
let name = text(fl!("battery")).size(18);
|
||||
let description = text(
|
||||
if "battery-full-charging-symbolic" == self.icon_name
|
||||
|| "battery-full-charged-symbolic" == self.icon_name
|
||||
{
|
||||
format!("{}%", self.battery_percent)
|
||||
} else {
|
||||
format!(
|
||||
"{} {} ({:.0}%)",
|
||||
format_duration(self.time_remaining),
|
||||
fl!("until-empty"),
|
||||
self.battery_percent
|
||||
)
|
||||
},
|
||||
)
|
||||
.size(12);
|
||||
self.applet_helper.popup_container(
|
||||
column![
|
||||
row![
|
||||
icon(&self.icon_name, 24)
|
||||
.style(Svg::Custom(|theme| {
|
||||
svg::Appearance {
|
||||
fill: Some(theme.palette().text),
|
||||
}
|
||||
}))
|
||||
.width(Length::Units(24))
|
||||
.height(Length::Units(24)),
|
||||
column![name, description]
|
||||
]
|
||||
.spacing(8)
|
||||
.align_items(Alignment::Center),
|
||||
horizontal_rule(1),
|
||||
// text{"Limit Battery Charging"},
|
||||
toggler(fl!("max-charge"), self.charging_limit, |_| {
|
||||
Message::SetChargingLimit(!self.charging_limit)
|
||||
}),
|
||||
horizontal_rule(1),
|
||||
row![
|
||||
icon("display-brightness-symbolic", 24)
|
||||
.style(Svg::Custom(|theme| {
|
||||
svg::Appearance {
|
||||
fill: Some(theme.palette().text),
|
||||
}
|
||||
}))
|
||||
.width(Length::Units(24))
|
||||
.height(Length::Units(24)),
|
||||
slider(
|
||||
0..=100,
|
||||
(self.screen_brightness * 100.0) as i32,
|
||||
Message::SetScreenBrightness
|
||||
),
|
||||
text(format!("{:.0}%", self.screen_brightness * 100.0))
|
||||
.width(Length::Units(40))
|
||||
.horizontal_alignment(Horizontal::Right)
|
||||
]
|
||||
.spacing(12),
|
||||
row![
|
||||
icon("keyboard-brightness-symbolic", 24)
|
||||
.style(Svg::Custom(|theme| {
|
||||
svg::Appearance {
|
||||
fill: Some(theme.palette().text),
|
||||
}
|
||||
}))
|
||||
.width(Length::Units(24))
|
||||
.height(Length::Units(24)),
|
||||
slider(
|
||||
0..=100,
|
||||
(self.kbd_brightness * 100.0) as i32,
|
||||
Message::SetKbdBrightness
|
||||
),
|
||||
text(format!("{:.0}%", self.kbd_brightness * 100.0))
|
||||
.width(Length::Units(40))
|
||||
.horizontal_alignment(Horizontal::Right)
|
||||
]
|
||||
.spacing(12),
|
||||
button(
|
||||
text(fl!("power-settings"))
|
||||
.horizontal_alignment(Horizontal::Center)
|
||||
.width(Length::Fill)
|
||||
.style(theme::Text::Custom(|theme| {
|
||||
let cosmic = theme.cosmic();
|
||||
iced_style::text::Appearance {
|
||||
color: Some(cosmic.accent.on.into()),
|
||||
}
|
||||
}))
|
||||
)
|
||||
.width(Length::Fill)
|
||||
]
|
||||
.spacing(4)
|
||||
.padding(8),
|
||||
)
|
||||
.into()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn subscription(&self) -> Subscription<Message> {
|
||||
Subscription::batch(vec![
|
||||
device_subscription(0).map(|(_, event)| match event {
|
||||
DeviceDbusEvent::Update {
|
||||
icon_name,
|
||||
percent,
|
||||
time_to_empty,
|
||||
} => Message::Update {
|
||||
icon_name,
|
||||
percent,
|
||||
time_to_empty,
|
||||
},
|
||||
}),
|
||||
kbd_backlight_subscription(0).map(|(_, event)| match event {
|
||||
KeyboardBacklightUpdate::Update(b) => Message::UpdateKbdBrightness(b),
|
||||
KeyboardBacklightUpdate::Init(tx, b) => Message::InitKbdBacklight(tx, b),
|
||||
}),
|
||||
screen_backlight_subscription(0).map(|(_, event)| match event {
|
||||
ScreenBacklightUpdate::Update(b) => Message::UpdateScreenBrightness(b),
|
||||
ScreenBacklightUpdate::Init(tx, b) => Message::InitScreenBacklight(tx, b),
|
||||
}),
|
||||
])
|
||||
}
|
||||
|
||||
fn theme(&self) -> Theme {
|
||||
self.theme
|
||||
}
|
||||
|
||||
fn close_requested(&self, _id: iced_sctk::application::SurfaceIdWrapper) -> Self::Message {
|
||||
Message::Ignore
|
||||
}
|
||||
|
||||
fn style(&self) -> <Self::Theme as application::StyleSheet>::Style {
|
||||
<Self::Theme as application::StyleSheet>::Style::Custom(|theme| Appearance {
|
||||
background_color: Color::from_rgba(0.0, 0.0, 0.0, 0.0),
|
||||
text_color: theme.cosmic().on_bg_color().into(),
|
||||
})
|
||||
}
|
||||
}
|
||||
180
cosmic-applet-battery/src/backlight.rs
Normal file
180
cosmic-applet-battery/src/backlight.rs
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
// TODO: use udev to monitor for brightness changes?
|
||||
// How should key bindings be handled? Need something like gnome-settings-daemon?
|
||||
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{self, Read},
|
||||
os::unix::ffi::OsStrExt,
|
||||
path::Path,
|
||||
str::{self, FromStr},
|
||||
hash::Hash,
|
||||
fmt::Debug
|
||||
};
|
||||
|
||||
use cosmic::iced;
|
||||
use iced_sctk::subscription;
|
||||
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
|
||||
|
||||
const BACKLIGHT_SYSDIR: &str = "/sys/class/backlight";
|
||||
|
||||
#[zbus::dbus_proxy(
|
||||
default_service = "org.freedesktop.login1",
|
||||
interface = "org.freedesktop.login1.Session",
|
||||
default_path = "/org/freedesktop/login1/session/auto"
|
||||
)]
|
||||
trait LogindSession {
|
||||
fn set_brightness(&self, subsystem: &str, name: &str, brightness: u32) -> zbus::Result<()>;
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Backlight(String);
|
||||
|
||||
impl Backlight {
|
||||
pub async fn brightness(&self) -> Option<u32> {
|
||||
self.prop("brightness").await
|
||||
}
|
||||
|
||||
// XXX cache value. Async?
|
||||
pub async fn max_brightness(&self) -> Option<u32> {
|
||||
self.prop("max_brightness").await
|
||||
}
|
||||
|
||||
pub async fn set_brightness(
|
||||
&self,
|
||||
session: &LogindSessionProxy<'_>,
|
||||
value: u32,
|
||||
) -> zbus::Result<()> {
|
||||
session.set_brightness("backlight", &self.0, value).await
|
||||
}
|
||||
|
||||
async fn prop<T: FromStr>(&self, name: &str) -> Option<T> {
|
||||
let path = Path::new(BACKLIGHT_SYSDIR).join(&self.0).join(name);
|
||||
let mut file = File::open(path).ok()?;
|
||||
let mut s = String::new();
|
||||
file.read_to_string(&mut s).ok()?;
|
||||
s.trim().parse().ok()
|
||||
}
|
||||
}
|
||||
|
||||
// Choose backlight with most "precision". This is what `light` does.
|
||||
pub async fn backlight() -> io::Result<Option<Backlight>> {
|
||||
let mut best_backlight = None;
|
||||
let mut best_max_brightness = 0;
|
||||
let mut dir_stream = tokio::fs::read_dir(BACKLIGHT_SYSDIR).await?;
|
||||
while let Ok(Some(entry)) = dir_stream.next_entry().await {
|
||||
if let Ok(filename) = str::from_utf8(entry.file_name().as_bytes()) {
|
||||
let backlight = Backlight(filename.to_string());
|
||||
if let Some(max_brightness) = backlight.max_brightness().await {
|
||||
if max_brightness > best_max_brightness {
|
||||
best_backlight = Some(backlight);
|
||||
best_max_brightness = max_brightness;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(best_backlight)
|
||||
}
|
||||
|
||||
|
||||
pub fn screen_backlight_subscription<I: 'static + Hash + Copy + Send + Sync + Debug>(
|
||||
id: I,
|
||||
) -> iced::Subscription<(I, ScreenBacklightUpdate)> {
|
||||
subscription::unfold(id, State::Ready, move |state| start_listening(id, state))
|
||||
}
|
||||
|
||||
pub enum State {
|
||||
Ready,
|
||||
Waiting(Backlight, LogindSessionProxy<'static>, UnboundedReceiver<ScreenBacklightRequest>),
|
||||
Finished,
|
||||
}
|
||||
|
||||
async fn start_listening<I: Copy>(id: I, state: State) -> (Option<(I, ScreenBacklightUpdate)>, State) {
|
||||
match state {
|
||||
State::Ready => {
|
||||
let conn = match zbus::Connection::system().await {
|
||||
Ok(conn) => conn,
|
||||
Err(_) => return (None, State::Finished),
|
||||
};
|
||||
let screen_proxy = match LogindSessionProxy::builder(&conn).build().await {
|
||||
Ok(p) => p,
|
||||
Err(_) => return (None, State::Finished),
|
||||
};
|
||||
let backlight = match backlight().await {
|
||||
Ok(Some(b)) => b,
|
||||
_ => return (None, State::Finished),
|
||||
};
|
||||
let (tx, rx) = unbounded_channel();
|
||||
|
||||
return (
|
||||
Some((
|
||||
id,
|
||||
ScreenBacklightUpdate::Init(tx, backlight.brightness().await.unwrap_or_default() as f64)
|
||||
)),
|
||||
State::Waiting(backlight, screen_proxy, rx),
|
||||
);
|
||||
|
||||
}
|
||||
State::Waiting(backlight, proxy, mut rx) => {
|
||||
match rx.recv().await {
|
||||
Some(req) => match req {
|
||||
ScreenBacklightRequest::Get => {
|
||||
let msg = if let Some(max_brightness) = backlight.max_brightness().await {
|
||||
let value = (backlight.brightness().await.unwrap_or_default() as f64 / max_brightness as f64).clamp(0., 1.);
|
||||
Some((
|
||||
id,
|
||||
ScreenBacklightUpdate::Update(value)
|
||||
))
|
||||
} else { None };
|
||||
(msg, State::Waiting(backlight, proxy, rx))
|
||||
}
|
||||
,
|
||||
ScreenBacklightRequest::Set(value) => {
|
||||
if let Some(max_brightness) = backlight.max_brightness().await {
|
||||
let value = value.clamp(0., 1.) * (max_brightness as f64);
|
||||
let value = value.round() as u32;
|
||||
let _ = backlight.set_brightness(&proxy, value).await;
|
||||
}
|
||||
(
|
||||
None,
|
||||
State::Waiting(backlight, proxy, rx),
|
||||
)
|
||||
},
|
||||
},
|
||||
None => (None, State::Finished),
|
||||
}
|
||||
}
|
||||
State::Finished => iced::futures::future::pending().await,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ScreenBacklightUpdate {
|
||||
Update(f64),
|
||||
Init(UnboundedSender<ScreenBacklightRequest>, f64)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ScreenBacklightRequest {
|
||||
Get,
|
||||
Set(f64),
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
// TODO: Cache device, max_brightness, etc.
|
||||
async fn set_display_brightness(brightness: f64) -> io::Result<()> {
|
||||
if let Some(backlight) = backlight()? {
|
||||
if let Some(max_brightness) = backlight.max_brightness() {
|
||||
let value = brightness.clamp(0., 1.) * (max_brightness as f64);
|
||||
let value = value.round() as u32;
|
||||
let connection = zbus::Connection::system().await?;
|
||||
if let Ok(session) = LogindSessionProxy::builder(&connection).build().await {
|
||||
backlight.set_brightness(&session, value).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
*/
|
||||
|
||||
// TODO: keyboard backlight
|
||||
3
cosmic-applet-battery/src/config.rs
Normal file
3
cosmic-applet-battery/src/config.rs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
pub const APP_ID: &str = "com.system76.CosmicAppletButton";
|
||||
pub const PROFILE: &str = "";
|
||||
pub const VERSION: &str = "0.1.0";
|
||||
47
cosmic-applet-battery/src/localize.rs
Normal file
47
cosmic-applet-battery/src/localize.rs
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
// SPDX-License-Identifier: MPL-2.0-only
|
||||
|
||||
use i18n_embed::{
|
||||
fluent::{fluent_language_loader, FluentLanguageLoader},
|
||||
DefaultLocalizer, LanguageLoader, Localizer,
|
||||
};
|
||||
use once_cell::sync::Lazy;
|
||||
use rust_embed::RustEmbed;
|
||||
|
||||
#[derive(RustEmbed)]
|
||||
#[folder = "i18n/"]
|
||||
struct Localizations;
|
||||
|
||||
pub static LANGUAGE_LOADER: Lazy<FluentLanguageLoader> = Lazy::new(|| {
|
||||
let loader: FluentLanguageLoader = fluent_language_loader!();
|
||||
|
||||
loader
|
||||
.load_fallback_language(&Localizations)
|
||||
.expect("Error while loading fallback language");
|
||||
|
||||
loader
|
||||
});
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! fl {
|
||||
($message_id:literal) => {{
|
||||
i18n_embed_fl::fl!($crate::localize::LANGUAGE_LOADER, $message_id)
|
||||
}};
|
||||
|
||||
($message_id:literal, $($args:expr),*) => {{
|
||||
i18n_embed_fl::fl!($crate::localize::LANGUAGE_LOADER, $message_id, $($args), *)
|
||||
}};
|
||||
}
|
||||
|
||||
// Get the `Localizer` to be used for localizing this library.
|
||||
pub fn localizer() -> Box<dyn Localizer> {
|
||||
Box::from(DefaultLocalizer::new(&*LANGUAGE_LOADER, &Localizations))
|
||||
}
|
||||
|
||||
pub fn localize() {
|
||||
let localizer = localizer();
|
||||
let requested_languages = i18n_embed::DesktopLanguageRequester::requested_languages();
|
||||
|
||||
if let Err(error) = localizer.select(&requested_languages) {
|
||||
eprintln!("Error while loading language for App List {}", error);
|
||||
}
|
||||
}
|
||||
28
cosmic-applet-battery/src/main.rs
Normal file
28
cosmic-applet-battery/src/main.rs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
#[rustfmt::skip]
|
||||
mod backlight;
|
||||
mod app;
|
||||
mod config;
|
||||
mod localize;
|
||||
mod power_daemon;
|
||||
mod upower;
|
||||
|
||||
mod upower_device;
|
||||
mod upower_kbdbacklight;
|
||||
use config::APP_ID;
|
||||
use log::info;
|
||||
|
||||
use localize::localize;
|
||||
|
||||
use crate::config::{PROFILE, VERSION};
|
||||
|
||||
fn main() -> cosmic::iced::Result {
|
||||
// Initialize logger
|
||||
pretty_env_logger::init();
|
||||
info!("Iced Workspaces Applet ({})", APP_ID);
|
||||
info!("Version: {} ({})", VERSION, PROFILE);
|
||||
|
||||
// Prepare i18n
|
||||
localize();
|
||||
|
||||
app::run()
|
||||
}
|
||||
67
cosmic-applet-battery/src/power_daemon.rs
Normal file
67
cosmic-applet-battery/src/power_daemon.rs
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
//! # DBus interface proxy for: `com.system76.PowerDaemon`
|
||||
//!
|
||||
//! This code was generated by `zbus-xmlgen` `2.0.1` from DBus introspection data.
|
||||
//! Source: `Interface '/com/system76/PowerDaemon' from service 'com.system76.PowerDaemon' on system bus`.
|
||||
|
||||
use zbus::dbus_proxy;
|
||||
|
||||
#[dbus_proxy(
|
||||
default_service = "com.system76.PowerDaemon",
|
||||
interface = "com.system76.PowerDaemon",
|
||||
default_path = "/com/system76/PowerDaemon"
|
||||
)]
|
||||
trait PowerDaemon {
|
||||
/// Balanced method
|
||||
fn balanced(&self) -> zbus::Result<()>;
|
||||
|
||||
/// Battery method
|
||||
fn battery(&self) -> zbus::Result<()>;
|
||||
|
||||
/// GetChargeProfiles method
|
||||
fn get_charge_profiles(
|
||||
&self,
|
||||
) -> zbus::Result<Vec<std::collections::HashMap<String, zbus::zvariant::OwnedValue>>>;
|
||||
|
||||
/// GetChargeThresholds method
|
||||
fn get_charge_thresholds(&self) -> zbus::Result<(u8, u8)>;
|
||||
|
||||
/// GetDefaultGraphics method
|
||||
fn get_default_graphics(&self) -> zbus::Result<String>;
|
||||
|
||||
/// GetExternalDisplaysRequireDGPU method
|
||||
fn get_external_displays_require_dgpu(&self) -> zbus::Result<bool>;
|
||||
|
||||
/// GetGraphics method
|
||||
fn get_graphics(&self) -> zbus::Result<String>;
|
||||
|
||||
/// GetGraphicsPower method
|
||||
fn get_graphics_power(&self) -> zbus::Result<bool>;
|
||||
|
||||
/// GetProfile method
|
||||
fn get_profile(&self) -> zbus::Result<String>;
|
||||
|
||||
/// GetSwitchable method
|
||||
fn get_switchable(&self) -> zbus::Result<bool>;
|
||||
|
||||
/// Performance method
|
||||
fn performance(&self) -> zbus::Result<()>;
|
||||
|
||||
/// SetChargeThresholds method
|
||||
fn set_charge_thresholds(&self, thresholds: &(u8, u8)) -> zbus::Result<()>;
|
||||
|
||||
/// SetGraphics method
|
||||
fn set_graphics(&self, vendor: &str) -> zbus::Result<()>;
|
||||
|
||||
/// SetGraphicsPower method
|
||||
fn set_graphics_power(&self, power: bool) -> zbus::Result<()>;
|
||||
|
||||
/// HotPlugDetect signal
|
||||
#[dbus_proxy(signal)]
|
||||
fn hot_plug_detect(&self, port: u64) -> zbus::Result<()>;
|
||||
|
||||
/// PowerProfileSwitch signal
|
||||
#[dbus_proxy(signal)]
|
||||
fn power_profile_switch(&self, profile: &str) -> zbus::Result<()>;
|
||||
}
|
||||
|
||||
// TODO power subscription
|
||||
45
cosmic-applet-battery/src/upower.rs
Normal file
45
cosmic-applet-battery/src/upower.rs
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
//! # DBus interface proxy for: `org.freedesktop.UPower`
|
||||
//!
|
||||
//! This code was generated by `zbus-xmlgen` `2.0.1` from DBus introspection data.
|
||||
//! Source: `Interface '/org/freedesktop/UPower' from service 'org.freedesktop.UPower' on system bus`.
|
||||
|
||||
use zbus::dbus_proxy;
|
||||
|
||||
#[dbus_proxy(
|
||||
default_service = "org.freedesktop.UPower",
|
||||
interface = "org.freedesktop.UPower"
|
||||
)]
|
||||
trait UPower {
|
||||
/// EnumerateDevices method
|
||||
fn enumerate_devices(&self) -> zbus::Result<Vec<zbus::zvariant::OwnedObjectPath>>;
|
||||
|
||||
/// GetCriticalAction method
|
||||
fn get_critical_action(&self) -> zbus::Result<String>;
|
||||
|
||||
/// GetDisplayDevice method
|
||||
fn get_display_device(&self) -> zbus::Result<zbus::zvariant::OwnedObjectPath>;
|
||||
|
||||
/// DeviceAdded signal
|
||||
#[dbus_proxy(signal)]
|
||||
fn device_added(&self, device: zbus::zvariant::ObjectPath<'_>) -> zbus::Result<()>;
|
||||
|
||||
/// DeviceRemoved signal
|
||||
#[dbus_proxy(signal)]
|
||||
fn device_removed(&self, device: zbus::zvariant::ObjectPath<'_>) -> zbus::Result<()>;
|
||||
|
||||
/// DaemonVersion property
|
||||
#[dbus_proxy(property)]
|
||||
fn daemon_version(&self) -> zbus::Result<String>;
|
||||
|
||||
/// LidIsClosed property
|
||||
#[dbus_proxy(property)]
|
||||
fn lid_is_closed(&self) -> zbus::Result<bool>;
|
||||
|
||||
/// LidIsPresent property
|
||||
#[dbus_proxy(property)]
|
||||
fn lid_is_present(&self) -> zbus::Result<bool>;
|
||||
|
||||
/// OnBattery property
|
||||
#[dbus_proxy(property)]
|
||||
fn on_battery(&self) -> zbus::Result<bool>;
|
||||
}
|
||||
245
cosmic-applet-battery/src/upower_device.rs
Normal file
245
cosmic-applet-battery/src/upower_device.rs
Normal file
|
|
@ -0,0 +1,245 @@
|
|||
//! # DBus interface proxy for: `org.freedesktop.UPower.Device`
|
||||
//!
|
||||
//! This code was generated by `zbus-xmlgen` `2.0.1` from DBus introspection data.
|
||||
//! Source: `Interface '/org/freedesktop/UPower/devices/DisplayDevice' from service 'org.freedesktop.UPower' on system bus`.
|
||||
|
||||
use cosmic::iced::{self, subscription};
|
||||
|
||||
use futures::StreamExt;
|
||||
use std::{fmt::Debug, hash::Hash};
|
||||
use zbus::dbus_proxy;
|
||||
|
||||
use crate::upower::UPowerProxy;
|
||||
#[dbus_proxy(
|
||||
default_service = "org.freedesktop.UPower",
|
||||
interface = "org.freedesktop.UPower.Device"
|
||||
)]
|
||||
trait Device {
|
||||
/// GetHistory method
|
||||
fn get_history(
|
||||
&self,
|
||||
type_: &str,
|
||||
timespan: u32,
|
||||
resolution: u32,
|
||||
) -> zbus::Result<Vec<(u32, f64, u32)>>;
|
||||
|
||||
/// GetStatistics method
|
||||
fn get_statistics(&self, type_: &str) -> zbus::Result<Vec<(f64, f64)>>;
|
||||
|
||||
/// Refresh method
|
||||
fn refresh(&self) -> zbus::Result<()>;
|
||||
|
||||
/// BatteryLevel property
|
||||
#[dbus_proxy(property)]
|
||||
fn battery_level(&self) -> zbus::Result<u32>;
|
||||
|
||||
/// Capacity property
|
||||
#[dbus_proxy(property)]
|
||||
fn capacity(&self) -> zbus::Result<f64>;
|
||||
|
||||
/// ChargeCycles property
|
||||
#[dbus_proxy(property)]
|
||||
fn charge_cycles(&self) -> zbus::Result<i32>;
|
||||
|
||||
/// Energy property
|
||||
#[dbus_proxy(property)]
|
||||
fn energy(&self) -> zbus::Result<f64>;
|
||||
|
||||
/// EnergyEmpty property
|
||||
#[dbus_proxy(property)]
|
||||
fn energy_empty(&self) -> zbus::Result<f64>;
|
||||
|
||||
/// EnergyFull property
|
||||
#[dbus_proxy(property)]
|
||||
fn energy_full(&self) -> zbus::Result<f64>;
|
||||
|
||||
/// EnergyFullDesign property
|
||||
#[dbus_proxy(property)]
|
||||
fn energy_full_design(&self) -> zbus::Result<f64>;
|
||||
|
||||
/// EnergyRate property
|
||||
#[dbus_proxy(property)]
|
||||
fn energy_rate(&self) -> zbus::Result<f64>;
|
||||
|
||||
/// HasHistory property
|
||||
#[dbus_proxy(property)]
|
||||
fn has_history(&self) -> zbus::Result<bool>;
|
||||
|
||||
/// HasStatistics property
|
||||
#[dbus_proxy(property)]
|
||||
fn has_statistics(&self) -> zbus::Result<bool>;
|
||||
|
||||
/// IconName property
|
||||
#[dbus_proxy(property)]
|
||||
fn icon_name(&self) -> zbus::Result<String>;
|
||||
|
||||
/// IsPresent property
|
||||
#[dbus_proxy(property)]
|
||||
fn is_present(&self) -> zbus::Result<bool>;
|
||||
|
||||
/// IsRechargeable property
|
||||
#[dbus_proxy(property)]
|
||||
fn is_rechargeable(&self) -> zbus::Result<bool>;
|
||||
|
||||
/// Luminosity property
|
||||
#[dbus_proxy(property)]
|
||||
fn luminosity(&self) -> zbus::Result<f64>;
|
||||
|
||||
/// Model property
|
||||
#[dbus_proxy(property)]
|
||||
fn model(&self) -> zbus::Result<String>;
|
||||
|
||||
/// NativePath property
|
||||
#[dbus_proxy(property)]
|
||||
fn native_path(&self) -> zbus::Result<String>;
|
||||
|
||||
/// Online property
|
||||
#[dbus_proxy(property)]
|
||||
fn online(&self) -> zbus::Result<bool>;
|
||||
|
||||
/// Percentage property
|
||||
#[dbus_proxy(property)]
|
||||
fn percentage(&self) -> zbus::Result<f64>;
|
||||
|
||||
/// PowerSupply property
|
||||
#[dbus_proxy(property)]
|
||||
fn power_supply(&self) -> zbus::Result<bool>;
|
||||
|
||||
/// Serial property
|
||||
#[dbus_proxy(property)]
|
||||
fn serial(&self) -> zbus::Result<String>;
|
||||
|
||||
/// State property
|
||||
#[dbus_proxy(property)]
|
||||
fn state(&self) -> zbus::Result<u32>;
|
||||
|
||||
/// Technology property
|
||||
#[dbus_proxy(property)]
|
||||
fn technology(&self) -> zbus::Result<u32>;
|
||||
|
||||
/// Temperature property
|
||||
#[dbus_proxy(property)]
|
||||
fn temperature(&self) -> zbus::Result<f64>;
|
||||
|
||||
/// TimeToEmpty property
|
||||
#[dbus_proxy(property)]
|
||||
fn time_to_empty(&self) -> zbus::Result<i64>;
|
||||
|
||||
/// TimeToFull property
|
||||
#[dbus_proxy(property)]
|
||||
fn time_to_full(&self) -> zbus::Result<i64>;
|
||||
|
||||
/// Type property
|
||||
#[dbus_proxy(property)]
|
||||
fn type_(&self) -> zbus::Result<u32>;
|
||||
|
||||
/// UpdateTime property
|
||||
#[dbus_proxy(property)]
|
||||
fn update_time(&self) -> zbus::Result<u64>;
|
||||
|
||||
/// Vendor property
|
||||
#[dbus_proxy(property)]
|
||||
fn vendor(&self) -> zbus::Result<String>;
|
||||
|
||||
/// Voltage property
|
||||
#[dbus_proxy(property)]
|
||||
fn voltage(&self) -> zbus::Result<f64>;
|
||||
|
||||
/// WarningLevel property
|
||||
#[dbus_proxy(property)]
|
||||
fn warning_level(&self) -> zbus::Result<u32>;
|
||||
}
|
||||
|
||||
pub fn device_subscription<I: 'static + Hash + Copy + Send + Sync + Debug>(
|
||||
id: I,
|
||||
) -> iced::Subscription<(I, DeviceDbusEvent)> {
|
||||
subscription::unfold(id, State::Ready, move |state| start_listening(id, state))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum State {
|
||||
Ready,
|
||||
Waiting(DeviceProxy<'static>),
|
||||
Finished,
|
||||
}
|
||||
|
||||
async fn display_device() -> zbus::Result<DeviceProxy<'static>> {
|
||||
let connection = zbus::Connection::system().await?;
|
||||
let upower = UPowerProxy::new(&connection).await?;
|
||||
let device_path = upower.get_display_device().await?;
|
||||
DeviceProxy::builder(&connection)
|
||||
.path(device_path)?
|
||||
.cache_properties(zbus::CacheProperties::Yes)
|
||||
.build()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn start_listening<I: Copy>(id: I, state: State) -> (Option<(I, DeviceDbusEvent)>, State) {
|
||||
match state {
|
||||
State::Ready => {
|
||||
if let Ok(device) = display_device().await {
|
||||
return (
|
||||
Some((
|
||||
id,
|
||||
DeviceDbusEvent::Update {
|
||||
icon_name: device
|
||||
.cached_icon_name()
|
||||
.unwrap_or_default()
|
||||
.unwrap_or_default(),
|
||||
percent: device
|
||||
.cached_percentage()
|
||||
.unwrap_or_default()
|
||||
.unwrap_or_default(),
|
||||
time_to_empty: device
|
||||
.cached_time_to_empty()
|
||||
.unwrap_or_default()
|
||||
.unwrap_or_default(),
|
||||
},
|
||||
)),
|
||||
State::Waiting(device),
|
||||
);
|
||||
}
|
||||
return (None, State::Finished);
|
||||
}
|
||||
State::Waiting(device) => {
|
||||
let mut stream = futures::stream_select!(
|
||||
device.receive_icon_name_changed().await.map(|_| ()),
|
||||
device.receive_percentage_changed().await.map(|_| ()),
|
||||
device.receive_time_to_empty_changed().await.map(|_| ()),
|
||||
);
|
||||
match stream.next().await {
|
||||
Some(_) => (
|
||||
Some((
|
||||
id,
|
||||
DeviceDbusEvent::Update {
|
||||
icon_name: device
|
||||
.cached_icon_name()
|
||||
.unwrap_or_default()
|
||||
.unwrap_or_default(),
|
||||
percent: device
|
||||
.cached_percentage()
|
||||
.unwrap_or_default()
|
||||
.unwrap_or_default(),
|
||||
time_to_empty: device
|
||||
.cached_time_to_empty()
|
||||
.unwrap_or_default()
|
||||
.unwrap_or_default(),
|
||||
},
|
||||
)),
|
||||
State::Waiting(device),
|
||||
),
|
||||
None => (None, State::Finished),
|
||||
}
|
||||
}
|
||||
State::Finished => iced::futures::future::pending().await,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum DeviceDbusEvent {
|
||||
Update {
|
||||
icon_name: String,
|
||||
percent: f64,
|
||||
time_to_empty: i64,
|
||||
},
|
||||
}
|
||||
115
cosmic-applet-battery/src/upower_kbdbacklight.rs
Normal file
115
cosmic-applet-battery/src/upower_kbdbacklight.rs
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
//! # DBus interface proxy for: `org.freedesktop.UPower.KbdBacklight`
|
||||
//!
|
||||
//! This code was generated by `zbus-xmlgen` `2.0.1` from DBus introspection data.
|
||||
//! Source: `Interface '/org/freedesktop/UPower/KbdBacklight' from service 'org.freedesktop.UPower' on system bus`.
|
||||
|
||||
use cosmic::iced;
|
||||
use iced::subscription;
|
||||
use std::{fmt::Debug, hash::Hash};
|
||||
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
|
||||
use zbus::dbus_proxy;
|
||||
#[dbus_proxy(
|
||||
default_service = "org.freedesktop.UPower",
|
||||
interface = "org.freedesktop.UPower.KbdBacklight",
|
||||
default_path = "/org/freedesktop/UPower/KbdBacklight"
|
||||
)]
|
||||
trait KbdBacklight {
|
||||
/// GetBrightness method
|
||||
fn get_brightness(&self) -> zbus::Result<i32>;
|
||||
|
||||
/// GetMaxBrightness method
|
||||
fn get_max_brightness(&self) -> zbus::Result<i32>;
|
||||
|
||||
/// SetBrightness method
|
||||
fn set_brightness(&self, value: i32) -> zbus::Result<()>;
|
||||
|
||||
/// BrightnessChanged signal
|
||||
#[dbus_proxy(signal)]
|
||||
fn brightness_changed(&self, value: i32) -> zbus::Result<()>;
|
||||
|
||||
/// BrightnessChangedWithSource signal
|
||||
#[dbus_proxy(signal)]
|
||||
fn brightness_changed_with_source(&self, value: i32, source: &str) -> zbus::Result<()>;
|
||||
}
|
||||
|
||||
pub fn kbd_backlight_subscription<I: 'static + Hash + Copy + Send + Sync + Debug>(
|
||||
id: I,
|
||||
) -> iced::Subscription<(I, KeyboardBacklightUpdate)> {
|
||||
subscription::unfold(id, State::Ready, move |state| start_listening(id, state))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum State {
|
||||
Ready,
|
||||
Waiting(
|
||||
KbdBacklightProxy<'static>,
|
||||
UnboundedReceiver<KeyboardBacklightRequest>,
|
||||
),
|
||||
Finished,
|
||||
}
|
||||
|
||||
async fn start_listening<I: Copy>(
|
||||
id: I,
|
||||
state: State,
|
||||
) -> (Option<(I, KeyboardBacklightUpdate)>, State) {
|
||||
match state {
|
||||
State::Ready => {
|
||||
let conn = match zbus::Connection::system().await {
|
||||
Ok(conn) => conn,
|
||||
Err(_) => return (None, State::Finished),
|
||||
};
|
||||
let kbd_proxy = match KbdBacklightProxy::builder(&conn).build().await {
|
||||
Ok(p) => p,
|
||||
Err(_) => return (None, State::Finished),
|
||||
};
|
||||
let (tx, rx) = unbounded_channel();
|
||||
|
||||
return (
|
||||
Some((
|
||||
id,
|
||||
KeyboardBacklightUpdate::Init(
|
||||
tx,
|
||||
kbd_proxy.get_brightness().await.unwrap_or_default() as f64,
|
||||
),
|
||||
)),
|
||||
State::Waiting(kbd_proxy, rx),
|
||||
);
|
||||
}
|
||||
State::Waiting(proxy, mut rx) => match rx.recv().await {
|
||||
Some(req) => match req {
|
||||
KeyboardBacklightRequest::Get => (
|
||||
Some((
|
||||
id,
|
||||
KeyboardBacklightUpdate::Update(
|
||||
proxy.get_brightness().await.unwrap_or_default() as f64,
|
||||
),
|
||||
)),
|
||||
State::Waiting(proxy, rx),
|
||||
),
|
||||
KeyboardBacklightRequest::Set(value) => {
|
||||
if let Ok(max_brightness) = proxy.get_max_brightness().await {
|
||||
let value = value.clamp(0., 1.) * (max_brightness as f64);
|
||||
let value = value.round() as i32;
|
||||
let _ = proxy.set_brightness(value).await;
|
||||
}
|
||||
|
||||
(None, State::Waiting(proxy, rx))
|
||||
}
|
||||
},
|
||||
None => (None, State::Finished),
|
||||
},
|
||||
State::Finished => iced::futures::future::pending().await,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum KeyboardBacklightUpdate {
|
||||
Update(f64),
|
||||
Init(UnboundedSender<KeyboardBacklightRequest>, f64),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum KeyboardBacklightRequest {
|
||||
Get,
|
||||
Set(f64),
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue