1use std::io::Write;
60use std::path::{Path, PathBuf};
61use std::process::Stdio;
62use std::sync::OnceLock;
63use std::time::Duration;
64
65use cosmic::iced::widget::Stack;
66use cosmic::iced::{Length, Subscription};
67use cosmic::prelude::*;
68use cosmic::widget::container;
69use futures_util::{SinkExt, Stream};
70use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
71use tokio::process::{Child, Command};
72use tokio::sync::mpsc;
73
74use crate::views::components::{app_icon, dot_badge};
75
76pub const WINDOW_FLAG: &str = "--window";
79
80pub const TOGGLE: &str = "toggle";
82
83pub const UNREAD: &str = "unread";
86
87const RENDERER: &str = "ICED_BACKEND";
90const CPU_RENDERER: &str = "tiny-skia";
91
92static RENDERER_ASKED_FOR: OnceLock<Option<String>> = OnceLock::new();
95
96const RESTART_AFTER: Duration = Duration::from_secs(2);
98
99const DOT_INSET: u16 = 3;
102
103pub struct Button {
105 core: cosmic::Core,
106 window: Option<mpsc::Sender<()>>,
108 unread: bool,
110}
111
112#[derive(Debug, Clone)]
114pub enum Message {
115 Pressed,
117 Linked(mpsc::Sender<()>),
119 Unread(bool),
121}
122
123impl cosmic::Application for Button {
124 type Executor = cosmic::executor::Default;
125 type Flags = ();
126 type Message = Message;
127
128 const APP_ID: &'static str = crate::app::APP_ID;
129
130 fn core(&self) -> &cosmic::Core {
131 &self.core
132 }
133
134 fn core_mut(&mut self) -> &mut cosmic::Core {
135 &mut self.core
136 }
137
138 fn init(core: cosmic::Core, _flags: Self::Flags) -> (Self, Task<cosmic::Action<Self::Message>>) {
139 (Self { core, window: None, unread: false }, Task::none())
140 }
141
142 fn view(&self) -> Element<'_, Self::Message> {
146 let button = self.core.applet.icon_button_from_handle(app_icon()).on_press_down(Message::Pressed);
147 if !self.unread {
148 return button.into();
149 }
150 let dot = container(dot_badge()).align_right(Length::Fill).padding(DOT_INSET);
151 Stack::new().push(button).push(dot).into()
152 }
153
154 fn update(&mut self, message: Self::Message) -> Task<cosmic::Action<Self::Message>> {
155 match message {
156 Message::Pressed => {
157 if let Some(window) = &self.window {
160 let _ = window.try_send(());
161 }
162 }
163 Message::Linked(window) => self.window = Some(window),
164 Message::Unread(unread) => self.unread = unread,
165 }
166 Task::none()
167 }
168
169 fn subscription(&self) -> Subscription<Self::Message> {
170 Subscription::run(window)
171 }
172
173 fn style(&self) -> Option<cosmic::iced::theme::Style> {
174 Some(cosmic::applet::style())
175 }
176}
177
178pub fn run() -> cosmic::iced::Result {
181 let _ = RENDERER_ASKED_FOR.set(std::env::var(RENDERER).ok());
182 unsafe { std::env::set_var(RENDERER, CPU_RENDERER) };
185 cosmic::applet::run::<Button>(())
186}
187
188fn start_window() -> std::io::Result<Child> {
192 let mut window = Command::new(std::env::current_exe()?);
193 window.arg(WINDOW_FLAG).env_remove("WAYLAND_SOCKET").env_remove("X_PRIVILEGED_WAYLAND_SOCKET");
194 match RENDERER_ASKED_FOR.get().cloned().flatten() {
195 Some(renderer) => window.env(RENDERER, renderer),
196 None => window.env_remove(RENDERER),
197 };
198 window.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::inherit()).kill_on_drop(true).spawn()
199}
200
201fn unread_said(line: &str) -> Option<bool> {
204 match line.trim().strip_prefix(UNREAD)?.trim() {
205 "1" => Some(true),
206 "0" => Some(false),
207 _ => None,
208 }
209}
210
211fn window() -> impl Stream<Item = Message> {
214 cosmic::iced::stream::channel(8, async |mut output| {
215 loop {
216 let (presses, mut pressed) = mpsc::channel(1);
217 if output.send(Message::Linked(presses)).await.is_err() {
218 return;
219 }
220 match start_window() {
221 Ok(mut window) => {
222 let (Some(mut said_to), Some(said_by)) = (window.stdin.take(), window.stdout.take()) else {
223 return;
224 };
225 let mut said_by = BufReader::new(said_by).lines();
226 loop {
227 tokio::select! {
228 press = pressed.recv() => {
229 if press.is_none() {
230 return;
231 }
232 let told = said_to.write_all(format!("{TOGGLE}\n").as_bytes()).await;
233 if told.is_err() || said_to.flush().await.is_err() {
234 break;
235 }
236 }
237 line = said_by.next_line() => match line {
238 Ok(Some(line)) => {
239 if let Some(unread) = unread_said(&line) {
240 let _ = output.send(Message::Unread(unread)).await;
241 }
242 }
243 _ => break,
244 },
245 }
246 }
247 tracing::warn!("the window went: another is started");
248 let _ = window.kill().await;
249 }
250 Err(e) => tracing::error!("the window could not be started: {e}"),
251 }
252 let _ = output.send(Message::Unread(false)).await;
253 tokio::time::sleep(RESTART_AFTER).await;
254 }
255 })
256}
257
258pub const TOGGLE_FLAG: &str = "--toggle";
261
262const SOCKET_NAME: &str = "cosmic-applet-avestruz.sock";
265
266const SAID_WITHIN: Duration = Duration::from_secs(1);
268
269const LOOKED_AT_EVERY: Duration = Duration::from_secs(2);
272
273pub fn socket_path() -> Option<PathBuf> {
277 dirs::runtime_dir().map(|directory| directory.join(SOCKET_NAME))
278}
279
280pub fn say_toggle(path: &Path) -> std::io::Result<()> {
283 let mut window = std::os::unix::net::UnixStream::connect(path)?;
284 writeln!(window, "{TOGGLE}")
285}
286
287fn file_at(path: &Path) -> Option<(u64, u64)> {
290 use std::os::unix::fs::MetadataExt;
291 std::fs::symlink_metadata(path).ok().map(|file| (file.dev(), file.ino()))
292}
293
294struct Listening {
297 listener: tokio::net::UnixListener,
298 file: Option<(u64, u64)>,
299}
300
301impl Listening {
302 fn at(path: &Path) -> std::io::Result<Option<Self>> {
306 if std::os::unix::net::UnixStream::connect(path).is_ok() {
307 return Ok(None);
308 }
309 let _ = std::fs::remove_file(path);
310 let listener = tokio::net::UnixListener::bind(path)?;
311 Ok(Some(Self { listener, file: file_at(path) }))
312 }
313
314 fn is_still_at(&self, path: &Path) -> bool {
317 self.file.is_some() && self.file == file_at(path)
318 }
319}
320
321async fn next_at(listening: Option<&Listening>) -> Option<tokio::net::UnixStream> {
324 match listening {
325 Some(listening) => listening.listener.accept().await.ok().map(|(said_by, _)| said_by),
326 None => std::future::pending().await,
327 }
328}
329
330pub fn from_outside<Message>(path: Option<PathBuf>, toggle: Message) -> impl Stream<Item = Message>
346where
347 Message: Clone + Send + 'static,
348{
349 heard_at(path, toggle, LOOKED_AT_EVERY)
350}
351
352fn heard_at<Message>(path: Option<PathBuf>, toggle: Message, looked_at_every: Duration) -> impl Stream<Item = Message>
354where
355 Message: Clone + Send + 'static,
356{
357 cosmic::iced::stream::channel(4, async move |mut output| {
358 let Some(path) = path else {
359 return std::future::pending::<()>().await;
360 };
361 let mut listening: Option<Listening> = None;
362 let mut refused = false;
364 let mut look = tokio::time::interval(looked_at_every);
365 look.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
366 loop {
367 let said_by = tokio::select! {
368 _ = look.tick() => {
369 if !listening.as_ref().is_some_and(|listening| listening.is_still_at(&path)) {
370 listening = match Listening::at(&path) {
371 Ok(listening) => {
372 refused = false;
373 listening
374 }
375 Err(e) => {
376 if !refused {
377 tracing::warn!("nothing can be said to the window at {}: {e}", path.display());
378 }
379 refused = true;
380 None
381 }
382 };
383 }
384 continue;
385 }
386 said_by = next_at(listening.as_ref()) => said_by,
387 };
388 let Some(said_by) = said_by else {
389 tokio::time::sleep(SAID_WITHIN).await;
390 continue;
391 };
392 let mut said = BufReader::new(said_by).lines();
395 let line = tokio::time::timeout(SAID_WITHIN, said.next_line()).await;
396 if let Ok(Ok(Some(line))) = line
397 && line.trim() == TOGGLE
398 && output.send(toggle.clone()).await.is_err()
399 {
400 return;
401 }
402 }
403 })
404}
405
406pub fn tell_unread(unread: bool) {
409 let mut out = std::io::stdout().lock();
410 let _ = writeln!(out, "{UNREAD} {}", u8::from(unread));
411 let _ = out.flush();
412}
413
414pub fn from_button<Message>(toggle: Message, gone: Message) -> impl Stream<Item = Message>
417where
418 Message: Clone + Send + 'static,
419{
420 cosmic::iced::stream::channel(4, async move |mut output| {
421 let mut said = BufReader::new(tokio::io::stdin()).lines();
422 while let Ok(Some(line)) = said.next_line().await {
423 if line.trim() == TOGGLE && output.send(toggle.clone()).await.is_err() {
424 return;
425 }
426 }
427 let _ = output.send(gone).await;
428 std::future::pending::<()>().await;
430 })
431}
432
433#[cfg(test)]
434mod tests {
435 use super::{TOGGLE, UNREAD, from_outside, heard_at, say_toggle, unread_said};
436 use futures_util::StreamExt;
437 use std::time::Duration;
438
439 fn socket_for(test: &str) -> std::path::PathBuf {
441 std::env::temp_dir().join(format!("avestruz-test-{test}-{}.sock", std::process::id()))
442 }
443
444 async fn say_toggle_once_heard(path: &std::path::Path) {
446 let said = async {
447 while say_toggle(path).is_err() {
448 tokio::time::sleep(Duration::from_millis(5)).await;
449 }
450 };
451 tokio::time::timeout(Duration::from_secs(10), said).await.expect("nobody came to listen");
452 }
453
454 fn window(
457 path: &std::path::Path,
458 name: &'static str,
459 ) -> (tokio::sync::mpsc::UnboundedReceiver<&'static str>, tokio::task::JoinHandle<()>) {
460 let (hears, heard) = tokio::sync::mpsc::unbounded_channel();
461 let mut stream = Box::pin(heard_at(Some(path.to_path_buf()), name, SOON));
462 let task = tokio::spawn(async move {
463 while let Some(said) = stream.next().await {
464 let _ = hears.send(said);
465 }
466 });
467 (heard, task)
468 }
469
470 const SOON: Duration = Duration::from_millis(20);
472
473 async fn next(heard: &mut tokio::sync::mpsc::UnboundedReceiver<&'static str>) -> Option<&'static str> {
475 tokio::time::timeout(Duration::from_secs(10), heard.recv()).await.ok().flatten()
476 }
477
478 #[test]
479 fn toggle_said_at_the_socket_is_heard_by_the_window_and_nothing_else_is() {
480 let path = socket_for("heard");
481 std::fs::write(&path, "left behind").unwrap();
483 assert!(say_toggle(&path).is_err(), "nobody listens there yet");
484
485 let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
486 runtime.block_on(async {
487 let (mut heard, task) = window(&path, "toggle heard");
488 say_toggle_once_heard(&path).await;
491 {
492 use std::io::Write;
493 let mut other = std::os::unix::net::UnixStream::connect(&path).unwrap();
494 writeln!(other, "something else").unwrap();
495 drop(std::os::unix::net::UnixStream::connect(&path).unwrap());
496 }
497 assert_eq!(next(&mut heard).await, Some("toggle heard"));
498 assert!(tokio::time::timeout(Duration::from_millis(200), heard.recv()).await.is_err());
500 task.abort();
501 });
502 let _ = std::fs::remove_file(&path);
503 }
504
505 #[test]
506 fn a_window_leaves_the_socket_to_the_one_that_listens_and_takes_it_when_that_one_is_gone() {
507 let path = socket_for("two");
508 let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
509 runtime.block_on(async {
510 let (mut first_heard, first) = window(&path, "first");
511 say_toggle_once_heard(&path).await;
512 assert_eq!(next(&mut first_heard).await, Some("first"));
513
514 let (mut second_heard, second) = window(&path, "second");
517 tokio::time::sleep(SOON * 5).await;
518 say_toggle(&path).unwrap();
519 assert_eq!(next(&mut first_heard).await, Some("first"));
520 assert!(second_heard.try_recv().is_err());
521
522 first.abort();
525 let _ = first.await;
526 assert!(path.exists());
527 say_toggle_once_heard(&path).await;
528 assert_eq!(next(&mut second_heard).await, Some("second"));
529 second.abort();
530 });
531 let _ = std::fs::remove_file(&path);
532 }
533
534 #[test]
535 fn a_window_whose_socket_file_was_taken_away_listens_anew() {
536 let path = socket_for("taken");
537 let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
538 runtime.block_on(async {
539 let (mut heard, task) = window(&path, "heard");
540 say_toggle_once_heard(&path).await;
541 assert_eq!(next(&mut heard).await, Some("heard"));
542
543 std::fs::remove_file(&path).unwrap();
545 assert!(say_toggle(&path).is_err());
546 say_toggle_once_heard(&path).await;
547 assert_eq!(next(&mut heard).await, Some("heard"));
548
549 std::fs::remove_file(&path).unwrap();
551 std::fs::write(&path, "another's, and nobody at it").unwrap();
552 say_toggle_once_heard(&path).await;
553 assert_eq!(next(&mut heard).await, Some("heard"));
554 task.abort();
555 });
556 let _ = std::fs::remove_file(&path);
557 }
558
559 #[test]
560 fn with_no_socket_to_listen_at_nothing_is_heard() {
561 let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
562 runtime.block_on(async {
563 let mut heard = Box::pin(from_outside(None, "toggle heard"));
564 assert!(tokio::time::timeout(Duration::from_millis(100), heard.next()).await.is_err());
565 });
566 }
567
568 #[test]
569 fn the_window_says_whether_there_is_something_not_looked_at() {
570 assert_eq!(unread_said(&format!("{UNREAD} 1")), Some(true));
571 assert_eq!(unread_said(&format!("{UNREAD} 0\n")), Some(false));
572 assert_eq!(unread_said(&format!("{UNREAD} many")), None);
574 assert_eq!(unread_said(TOGGLE), None);
575 assert_eq!(unread_said(""), None);
576 }
577}