cosmic-applets/cosmic-applet-battery/src/app.rs

442 lines
17 KiB
Rust
Raw Normal View History

2022-12-05 10:52:48 -05:00
use crate::backlight::{
screen_backlight_subscription, ScreenBacklightRequest, ScreenBacklightUpdate,
};
use crate::config;
use crate::fl;
2023-01-13 18:31:59 -05:00
use crate::power_daemon::{
power_profile_subscription, Power, PowerProfileRequest, PowerProfileUpdate,
};
2022-12-05 10:52:48 -05:00
use crate::upower_device::{device_subscription, DeviceDbusEvent};
use crate::upower_kbdbacklight::{
kbd_backlight_subscription, KeyboardBacklightRequest, KeyboardBacklightUpdate,
};
2022-12-02 20:24:52 -05:00
use cosmic::iced::alignment::Horizontal;
use cosmic::iced::wayland::popup::{destroy_popup, get_popup};
use cosmic::iced::Color;
2022-12-02 20:24:52 -05:00
use cosmic::iced::{
2023-01-13 18:31:59 -05:00
widget::{column, container, row, slider, text},
2022-12-02 20:24:52 -05:00
window, Alignment, Application, Command, Length, Subscription,
};
use cosmic::iced_runtime::core::layout::Limits;
2022-12-02 20:24:52 -05:00
use cosmic::iced_style::application::{self, Appearance};
2023-01-13 18:31:59 -05:00
use cosmic::theme::Svg;
use cosmic::widget::{button, divider, icon};
2023-01-13 18:31:59 -05:00
use cosmic::{Element, Theme};
use cosmic_applet::{applet_button_theme, CosmicAppletHelper};
2023-06-09 16:10:20 -04:00
use cosmic_time::{anim, chain, id, once_cell::sync::Lazy, Instant, Timeline};
2023-01-13 18:31:59 -05:00
use log::error;
2022-12-02 20:24:52 -05:00
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 {
2022-12-05 10:52:15 -05:00
format!("{}{}", min, fl!("minutes"))
2022-12-02 20:24:52 -05:00
}
} else {
2022-12-05 10:52:15 -05:00
format!("{}{}", secs, fl!("seconds"))
2022-12-02 20:24:52 -05:00
}
}
pub fn run() -> cosmic::iced::Result {
2022-12-07 12:46:54 -05:00
let helper = CosmicAppletHelper::default();
CosmicBatteryApplet::run(helper.window_settings())
2022-12-02 20:24:52 -05:00
}
static MAX_CHARGE: Lazy<id::Toggler> = Lazy::new(id::Toggler::unique);
2022-12-02 20:24:52 -05:00
#[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: u128,
2022-12-02 20:24:52 -05:00
screen_sender: Option<UnboundedSender<ScreenBacklightRequest>>,
kbd_sender: Option<UnboundedSender<KeyboardBacklightRequest>>,
applet_helper: CosmicAppletHelper,
2023-01-13 18:31:59 -05:00
power_profile: Power,
power_profile_sender: Option<UnboundedSender<PowerProfileRequest>>,
timeline: Timeline,
2022-12-02 20:24:52 -05:00
}
#[derive(Debug, Clone)]
enum Message {
TogglePopup,
Update {
icon_name: String,
percent: f64,
time_to_empty: i64,
},
SetKbdBrightness(i32),
SetScreenBrightness(i32),
SetChargingLimit(chain::Toggler, bool),
2022-12-02 20:24:52 -05:00
UpdateKbdBrightness(f64),
UpdateScreenBrightness(f64),
OpenBatterySettings,
InitKbdBacklight(UnboundedSender<KeyboardBacklightRequest>, f64),
InitScreenBacklight(UnboundedSender<ScreenBacklightRequest>, f64),
Errored(String),
Ignore,
2023-01-13 18:31:59 -05:00
InitProfile(UnboundedSender<PowerProfileRequest>, Power),
Profile(Power),
SelectProfile(Power),
Frame(Instant),
2023-06-09 16:10:20 -04:00
Theme(Theme),
2022-12-02 20:24:52 -05:00
}
impl Application for CosmicBatteryApplet {
type Message = Message;
type Theme = Theme;
type Executor = cosmic::SingleThreadExecutor;
2022-12-02 20:24:52 -05:00
type Flags = ();
fn new(_flags: ()) -> (Self, Command<Message>) {
2023-06-09 16:10:20 -04:00
let applet_helper = CosmicAppletHelper::default();
let theme = applet_helper.theme();
2022-12-02 20:24:52 -05:00
(
CosmicBatteryApplet {
icon_name: "battery-symbolic".to_string(),
2023-06-09 16:10:20 -04:00
applet_helper,
theme,
2022-12-02 20:24:52 -05:00
..Default::default()
},
Command::none(),
)
}
fn title(&self) -> String {
config::APP_ID.to_string()
}
fn update(&mut self, message: Message) -> Command<Message> {
match message {
Message::Frame(now) => self.timeline.now(now),
2022-12-02 20:24:52 -05:00
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) => {
2023-01-05 09:58:48 -08:00
self.screen_brightness = (brightness as f64 / 100.0).clamp(0.01, 1.0);
2022-12-02 20:24:52 -05:00
if let Some(tx) = &self.screen_sender {
let _ = tx.send(ScreenBacklightRequest::Set(self.screen_brightness));
}
}
Message::SetChargingLimit(chain, enable) => {
self.timeline.set_chain(chain).start();
self.charging_limit = enable;
2022-12-02 20:24:52 -05:00
}
Message::OpenBatterySettings => {
// TODO Ashley
}
2023-01-13 18:31:59 -05:00
Message::Errored(e) => {
error!("{}", e);
2022-12-02 20:24:52 -05:00
}
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(self.id_ctr);
2022-12-02 20:24:52 -05:00
self.popup.replace(new_id);
let mut popup_settings = self.applet_helper.get_popup_settings(
window::Id(0),
new_id,
None,
None,
None,
);
popup_settings.positioner.size_limits = Limits::NONE
.max_width(372.0)
.min_width(300.0)
.min_height(200.0)
.max_height(1080.0);
2023-01-13 18:31:59 -05:00
if let Some(tx) = self.power_profile_sender.as_ref() {
let _ = tx.send(PowerProfileRequest::Get);
}
2022-12-02 20:24:52 -05:00
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;
2022-12-05 10:52:48 -05:00
}
Message::Ignore => {}
2022-12-02 20:24:52 -05:00
Message::InitKbdBacklight(tx, brightness) => {
let _ = tx.send(KeyboardBacklightRequest::Get);
self.kbd_sender = Some(tx);
self.kbd_brightness = brightness;
2022-12-05 10:52:48 -05:00
}
2022-12-02 20:24:52 -05:00
Message::InitScreenBacklight(tx, brightness) => {
let _ = tx.send(ScreenBacklightRequest::Get);
self.screen_sender = Some(tx);
self.screen_brightness = brightness;
2022-12-05 10:52:48 -05:00
}
2022-12-02 20:24:52 -05:00
Message::UpdateScreenBrightness(b) => {
self.screen_brightness = b;
2022-12-05 10:52:48 -05:00
}
2023-01-13 18:31:59 -05:00
Message::InitProfile(tx, profile) => {
self.power_profile_sender.replace(tx);
self.power_profile = profile;
}
Message::Profile(profile) => {
self.power_profile = profile;
if let Some(tx) = &self.kbd_sender {
let _ = tx.send(KeyboardBacklightRequest::Get);
}
if let Some(tx) = &self.screen_sender {
let _ = tx.send(ScreenBacklightRequest::Get);
}
}
Message::SelectProfile(profile) => {
if let Some(tx) = self.power_profile_sender.as_ref() {
let _ = tx.send(PowerProfileRequest::Set(profile));
}
}
2023-06-09 16:10:20 -04:00
Message::Theme(t) => {
self.theme = t;
}
2022-12-02 20:24:52 -05:00
}
Command::none()
}
2023-04-05 20:40:22 -04:00
fn view(&self, id: window::Id) -> Element<Message> {
if id == window::Id(0) {
2023-04-05 20:40:22 -04:00
self.applet_helper
.icon_button(&self.icon_name)
.on_press(Message::TogglePopup)
2023-04-05 20:40:22 -04:00
.into()
} else {
let name = text(fl!("battery")).size(14);
2023-04-05 20:40:22 -04:00
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(10);
2023-04-05 20:40:22 -04:00
self.applet_helper
.popup_container(
column![
row![
icon(&*self.icon_name, 24).style(Svg::Symbolic),
2023-04-05 20:40:22 -04:00
column![name, description]
]
.padding([0, 24])
.spacing(8)
.align_items(Alignment::Center),
container(divider::horizontal::light())
.width(Length::Fill)
.padding([0, 12]),
button(applet_button_theme())
2023-04-05 20:40:22 -04:00
.custom(vec![row![
column![
text(fl!("battery")).size(14),
text(fl!("battery-desc")).size(10)
2023-01-13 18:31:59 -05:00
]
.width(Length::Fill),
2023-04-05 20:40:22 -04:00
icon("emblem-ok-symbolic", 12).size(12).style(
match self.power_profile {
Power::Battery => Svg::SymbolicActive,
_ => Svg::Default,
}
),
]
.align_items(Alignment::Center)
.into()])
.padding([8, 24])
.on_press(Message::SelectProfile(Power::Battery))
.width(Length::Fill),
button(applet_button_theme())
2023-04-05 20:40:22 -04:00
.custom(vec![row![
column![
text(fl!("balanced")).size(14),
text(fl!("balanced-desc")).size(10)
2023-01-13 18:31:59 -05:00
]
.width(Length::Fill),
2023-04-05 20:40:22 -04:00
icon("emblem-ok-symbolic", 12).size(12).style(
match self.power_profile {
Power::Balanced => Svg::SymbolicActive,
_ => Svg::Default,
}
),
]
2023-04-05 20:40:22 -04:00
.align_items(Alignment::Center)
.into()])
.padding([8, 24])
.on_press(Message::SelectProfile(Power::Balanced))
.width(Length::Fill),
button(applet_button_theme())
2023-04-05 20:40:22 -04:00
.custom(vec![row![
column![
text(fl!("performance")).size(14),
text(fl!("performance-desc")).size(10)
2023-04-05 20:40:22 -04:00
]
.width(Length::Fill),
icon("emblem-ok-symbolic", 12).size(12).style(
match self.power_profile {
Power::Performance => Svg::SymbolicActive,
_ => Svg::Default,
}
),
]
2023-04-05 20:40:22 -04:00
.align_items(Alignment::Center)
.into()])
.padding([8, 24])
.on_press(Message::SelectProfile(Power::Performance))
.width(Length::Fill),
container(divider::horizontal::light())
.width(Length::Fill)
.padding([0, 12]),
container(
2023-06-09 16:10:20 -04:00
anim!(
//toggler
MAX_CHARGE,
&self.timeline,
fl!("max-charge"),
self.charging_limit,
Message::SetChargingLimit,
)
.text_size(14)
.width(Length::Fill)
)
2023-04-05 20:40:22 -04:00
.padding([0, 24])
.width(Length::Fill),
container(divider::horizontal::light())
.width(Length::Fill)
.padding([0, 12]),
row![
icon("display-brightness-symbolic", 24).style(Svg::Symbolic),
2023-04-05 20:40:22 -04:00
slider(
1..=100,
(self.screen_brightness * 100.0) as i32,
Message::SetScreenBrightness
),
text(format!("{:.0}%", self.screen_brightness * 100.0))
.size(16)
.width(Length::Fixed(40.0))
2023-04-05 20:40:22 -04:00
.horizontal_alignment(Horizontal::Right)
2022-12-05 10:52:48 -05:00
]
2023-04-05 20:40:22 -04:00
.padding([0, 24])
.spacing(12),
row![
icon("keyboard-brightness-symbolic", 24).style(Svg::Symbolic),
2023-04-05 20:40:22 -04:00
slider(
0..=100,
(self.kbd_brightness * 100.0) as i32,
Message::SetKbdBrightness
),
text(format!("{:.0}%", self.kbd_brightness * 100.0))
.size(16)
.width(Length::Fixed(40.0))
2023-04-05 20:40:22 -04:00
.horizontal_alignment(Horizontal::Right)
]
.padding([0, 24])
.spacing(12),
container(divider::horizontal::light())
.width(Length::Fill)
.padding([0, 12]),
button(applet_button_theme())
.custom(vec![text(fl!("power-settings"))
.size(14)
.width(Length::Fill)
.into()])
2023-04-05 20:40:22 -04:00
.on_press(Message::OpenBatterySettings)
.width(Length::Fill)
.padding([8, 24])
]
.spacing(8)
.padding([8, 0]),
)
.into()
2022-12-02 20:24:52 -05:00
}
}
fn subscription(&self) -> Subscription<Message> {
Subscription::batch(vec![
2023-06-09 16:10:20 -04:00
self.applet_helper.theme_subscription(0).map(Message::Theme),
device_subscription(0).map(
|(
_,
DeviceDbusEvent::Update {
icon_name,
percent,
time_to_empty,
},
)| Message::Update {
2022-12-02 20:24:52 -05:00
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),
2022-12-02 20:24:52 -05:00
}),
screen_backlight_subscription(0).map(|e| match e {
(_, ScreenBacklightUpdate::Update(b)) => Message::UpdateScreenBrightness(b),
(_, ScreenBacklightUpdate::Init(tx, b)) => Message::InitScreenBacklight(tx, b),
2022-12-05 10:52:48 -05:00
}),
power_profile_subscription(0).map(|event| match event {
(_, PowerProfileUpdate::Update { profile }) => Message::Profile(profile),
(_, PowerProfileUpdate::Init(tx, p)) => Message::InitProfile(p, tx),
(_, PowerProfileUpdate::Error(e)) => Message::Errored(e), // TODO: handle error
2023-01-13 18:31:59 -05:00
}),
2023-06-15 15:03:06 -04:00
self.timeline
.as_subscription()
.map(|(_, now)| Message::Frame(now)),
2022-12-02 20:24:52 -05:00
])
}
fn theme(&self) -> Theme {
self.theme.clone()
2022-12-02 20:24:52 -05:00
}
2023-04-05 20:40:22 -04:00
fn close_requested(&self, _id: window::Id) -> Message {
2022-12-02 20:24:52 -05:00
Message::Ignore
}
fn style(&self) -> <Self::Theme as application::StyleSheet>::Style {
<Self::Theme as application::StyleSheet>::Style::Custom(Box::new(|theme| Appearance {
2022-12-02 20:24:52 -05:00
background_color: Color::from_rgba(0.0, 0.0, 0.0, 0.0),
text_color: theme.cosmic().on_bg_color().into(),
}))
2022-12-02 20:24:52 -05:00
}
}