This commit is contained in:
2026-09-07 11:41:59 +01:00
parent bc5a26b728
commit 3490af52e4
12 changed files with 274 additions and 170 deletions
+31 -13
View File
@@ -13,13 +13,9 @@ use iced_layershell::reexport::Anchor;
use iced_layershell::settings::{LayerShellSettings, Settings, StartMode};
use iced_layershell::to_layer_message;
use crate::module::{BarModule, ModuleMsg};
use crate::services::Service as ModuleService;
use crate::services::ServicePayloadKind;
use common::{BarModule, ModuleEffect, ModuleMsg, Service as ModuleService, ServicePayloadKind};
mod module;
mod popup;
mod services;
/// Height of the bar in logical pixels.
const BAR_HEIGHT: u32 = 36;
@@ -43,7 +39,7 @@ struct Bar {
impl Bar {
fn new() -> Self {
let mut modules: BTreeMap<&'static str, Box<dyn BarModule>> = BTreeMap::new();
modules.insert("clock", Box::new(crate::module::clock::Clock::new()));
modules.insert("clock", Box::new(module_clock::Clock::new()));
let routes = modules
.iter()
.map(|(id, module)| (*id, module.services()))
@@ -100,6 +96,26 @@ fn namespace() -> String {
String::from("barbar")
}
/// Maps a module-requested effect into an app message. Modules never name
/// app types; this is the only place the two meet.
fn module_effect_to_message(effect: ModuleEffect) -> Message {
match effect {
ModuleEffect::RequestPopup(module_id, element_id) => {
Message::Effect(Cmd::RequestPopup(module_id, element_id))
}
ModuleEffect::ClosePopup(id) => Message::Effect(Cmd::ClosePopup(id)),
}
}
/// One arm per service kind: turns a route key into its subscription.
/// Adding a service touches only this match (plus the leaf crate).
fn service_subscription(service: &ModuleService) -> Subscription<Message> {
match service {
ModuleService::Clock(_) => service_datatime::ClockTicker::run()
.map(|event| Message::Event(Msg::Subscription(event))),
}
}
fn main() -> Result<(), iced_layershell::Error> {
let start_mode = match std::env::args().nth(1) {
Some(output) => StartMode::TargetScreen(output),
@@ -127,7 +143,7 @@ fn gather_subscriptions(bar: &Bar) -> Subscription<Message> {
let route_sub = Subscription::batch(
bar.routes
.values()
.flat_map(|x| x.iter().map(ModuleService::subscription))
.flat_map(|x| x.iter().map(service_subscription))
.collect::<Vec<_>>(),
);
let close_events = window::close_events().map(|id| Message::Event(Msg::WindowClosed(id)));
@@ -151,8 +167,8 @@ fn update(bar: &mut Bar, msg: Message) -> Task<Message> {
fn handle_event(bar: &mut Bar, event: Msg) -> Task<Message> {
match event {
Msg::Module(m) => match bar.modules.get_mut(m.id) {
// Modules return their own app-level tasks (e.g. popups).
Some(module) => module.update(m),
// Modules return protocol tasks; map effects into `Cmd`s.
Some(module) => module.update(m).map(module_effect_to_message),
None => Task::none(),
},
@@ -169,10 +185,12 @@ fn handle_event(bar: &mut Bar, event: Msg) -> Task<Message> {
.is_some_and(|kinds| kinds.contains(&key))
})
.map(|(_, module)| {
module.update(ModuleMsg {
id: module.id(),
payload: payload.clone(),
})
module
.update(ModuleMsg {
id: module.id(),
payload: payload.clone(),
})
.map(module_effect_to_message)
})
.fold(Task::none(), |acc, t| acc.chain(t))
}
-98
View File
@@ -1,98 +0,0 @@
use iced::widget::{container, mouse_area, text};
use iced::{Element, Task};
use crate::module::{BarModule, ModuleMsg};
use crate::services::clock::{ClockKind, ClockPayload};
use crate::services::Service;
use crate::{Cmd, Message};
/// Clock module: subscribes to second ticks, renders the time in the bar.
/// Left-click toggles the seconds suffix; right-click opens a popup with
/// the current time in large text.
#[derive(Clone)]
pub enum ClockMsg {
/// Toggle the seconds suffix.
ToggleSeconds,
/// Open the big-time popup.
OpenPopup,
}
/// Big-text popup size (logical px).
const POPUP_W: u32 = 360;
const POPUP_H: u32 = 160;
pub struct Clock {
value: String,
show_seconds: bool,
}
impl Clock {
pub fn new() -> Self {
Self {
value: "--:--:--".to_string(),
show_seconds: true,
}
}
/// Display string: HH:MM:SS, or HH:MM when seconds are hidden.
fn shown(&self) -> String {
if self.show_seconds {
self.value.clone()
} else {
self.value
.split(':') // [hh, mm, ss]
.take(2)
.collect::<Vec<_>>()
.join(":")
}
}
}
impl BarModule for Clock {
fn id(&self) -> &'static str {
"clock"
}
fn view(&self, window_id: Option<iced::window::Id>) -> Element<'_, ModuleMsg> {
match window_id {
// Popup surface: current time in large text.
Some(_) => container(text(&self.value).size(56)).padding(20).into(),
// Bar surface: clickable time. Container carries the module id
// so the popup can anchor to these bounds.
None => container(
mouse_area(text(self.shown()).size(16))
.on_press(ModuleMsg::new(self.id(), ClockMsg::ToggleSeconds))
.on_right_press(ModuleMsg::new(self.id(), ClockMsg::OpenPopup)),
)
.id(iced::widget::Id::from(self.id()))
.into(),
}
}
fn update(&mut self, msg: ModuleMsg) -> Task<Message> {
// Subscription fan-out delivers a raw `ClockPayload`, not `ClockMsg`.
if let Some(payload) = msg.downcast::<ClockPayload>() {
self.value = payload.value.clone();
return Task::none();
}
match msg.downcast::<ClockMsg>() {
Some(ClockMsg::ToggleSeconds) => {
self.show_seconds = !self.show_seconds;
Task::none()
}
Some(ClockMsg::OpenPopup) => Task::done(Message::Effect(Cmd::RequestPopup(
self.id().to_string(),
self.id().to_string(),
))),
None => Task::none(),
}
}
fn services(&self) -> Vec<Service> {
vec![Service::Clock(ClockKind::Seconds)]
}
fn popup_size(&self) -> Option<(u32, u32)> {
Some((POPUP_W, POPUP_H))
}
}
-63
View File
@@ -1,63 +0,0 @@
use std::any::Any;
use std::fmt;
use std::sync::Arc;
use iced::{Element, Task};
use crate::services::Service;
use crate::Message;
pub mod clock;
/// A module-local message, boxed with its owner's `id`. The app routes by
/// `id` and never names a module's message type; the module downcasts.
#[derive(Clone)]
pub struct ModuleMsg {
pub id: &'static str,
pub payload: Arc<dyn Any + Send + Sync>,
}
impl ModuleMsg {
/// Wraps a module's own message; `id` must match its `BarModule::id`.
pub fn new<T: Any + Send + Sync>(id: &'static str, msg: T) -> Self {
Self {
id,
payload: Arc::new(msg),
}
}
/// Downcasts to the module's own message type.
pub fn downcast<T: Any + Send + Sync>(&self) -> Option<&T> {
self.payload.downcast_ref()
}
}
impl fmt::Debug for ModuleMsg {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ModuleMsg")
.field("id", &self.id)
.field("payload", &self.payload.type_id())
.finish()
}
}
/// A bar module. Object-safe; modules live in a `BTreeMap` keyed by id. The
/// `ModuleMsg` boundary keeps the app ignorant of each module's message enum.
pub trait BarModule: Send {
fn id(&self) -> &'static str;
/// Bar contents. When `window_id` is `Some`, this is the module's popup
/// surface and the module returns its popup contents instead.
fn view(&self, window_id: Option<iced::window::Id>) -> Element<'_, ModuleMsg>;
/// Handles a routed message; may return app-level tasks (e.g. popups).
fn update(&mut self, msg: ModuleMsg) -> Task<Message>;
/// What services this module wants.
fn services(&self) -> Vec<Service>;
/// Requested popup size when it's not the generic small menu.
fn popup_size(&self) -> Option<(u32, u32)> {
None
}
}
-82
View File
@@ -1,82 +0,0 @@
use std::collections::HashMap;
use iced::{futures::SinkExt, Subscription};
use crate::{services::ServicePayloadKind, Message, Msg};
/// What a clock subscription wants: the tick interval and payload selector.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum ClockKind {
Mins,
Seconds,
}
/// Clock tick payload: the value plus the kind that produced it.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct ClockPayload {
pub kind: ClockKind,
pub value: String,
}
/// Emits a payload only when a kind's displayed value changes (minute or
/// second rollover). Drive `tick` once per second.
#[derive(Default)]
pub struct ClockTicker {
last: HashMap<ClockKind, String>,
}
impl ClockTicker {
pub fn new() -> Self {
Self::default()
}
pub fn run() -> Subscription<Message> {
Subscription::run_with((), |_| {
iced::stream::channel(
0,
|mut sender: iced::futures::channel::mpsc::Sender<Message>| async move {
let mut clock = ClockTicker::new();
let mut interval = tokio::time::interval(std::time::Duration::from_secs(1));
loop {
interval.tick().await;
for payload in clock.tick() {
if sender
.send(Message::Event(Msg::Subscription(
ServicePayloadKind::Clock(payload),
)))
.await
.is_err()
{
return;
}
}
}
},
)
})
}
/// Returns a payload per kind whose value changed since the last tick.
/// The second that rolls into a new minute yields `[Seconds, Mins]`.
pub fn tick(&mut self) -> Vec<ClockPayload> {
let now = chrono::Local::now();
[ClockKind::Seconds, ClockKind::Mins]
.into_iter()
.filter_map(|kind| {
let value = now
.format(match kind {
ClockKind::Mins => "%H:%M",
ClockKind::Seconds => "%H:%M:%S",
})
.to_string();
match self.last.get(&kind) {
Some(prev) if *prev == value => None,
_ => {
self.last.insert(kind, value.clone());
Some(ClockPayload { kind, value })
}
}
})
.collect()
}
}
-47
View File
@@ -1,47 +0,0 @@
use std::any::Any;
use std::sync::Arc;
use crate::{
services::clock::{ClockKind, ClockPayload, ClockTicker},
Message,
};
pub mod clock;
/// Route key a module subscribes with; `Clock(kind)` selects the ticker.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Service {
Clock(ClockKind),
}
impl Service {
pub fn subscription(&self) -> iced::Subscription<Message> {
match self {
Self::Clock(_) => ClockTicker::run(),
}
}
}
/// A service event with a typed payload. The app only reads
/// `key()` for fan-out; the consuming module downcasts the payload.
#[derive(Clone, Debug)]
pub enum ServicePayloadKind {
Clock(ClockPayload),
}
impl ServicePayloadKind {
/// Route key for this event. One arm per kind — adding a service
/// touches only this match, never the routing code.
pub fn key(&self) -> Service {
match self {
Self::Clock(payload) => Service::Clock(payload.kind),
}
}
/// Erases the typed payload for the module to downcast.
pub fn into_payload(self) -> Arc<dyn Any + Send + Sync> {
match self {
Self::Clock(payload) => Arc::new(payload),
}
}
}