Skip to main content

cosmic_applet_avestruz/
button.rs

1// SPDX-License-Identifier: MIT
2
3//! The button in the panel, and the line between it and the window it
4//! opens.
5//!
6//! Avestruz runs as two processes of the one program. The panel starts the
7//! first, which is this: an applet that is a button and nothing else. It
8//! starts the second, the same program told to be the window
9//! ([`WINDOW_FLAG`]), which is the whole client (see [`crate::app`]).
10//!
11//! Two, because of who draws what. An applet's surfaces are the panel's:
12//! the panel is a compositor of its own, takes what its applets draw and
13//! hands it on, and takes no GPU buffers from them. An applet is therefore
14//! drawn by the CPU, which is plenty for a button and was the dearest
15//! thing about a list of pictures being scrolled. The window is no
16//! applet: it puts a surface of its own on the session's compositor, and
17//! the GPU draws it.
18//!
19//! ```mermaid
20//! flowchart LR
21//!     subgraph panel["The panel, a compositor of its own"]
22//!         button["The button: an applet, drawn by the CPU"]
23//!     end
24//!     window["The window: the client, drawn by the GPU"]
25//!     compositor["The session's compositor"]
26//!     button -->|"starts it, and says: toggle"| window
27//!     window -->|"says: unread 1, unread 0"| button
28//!     button -. "its surface is the panel's" .-> panel
29//!     panel --> compositor
30//!     window -->|"a surface of its own"| compositor
31//! ```
32//!
33//! They talk over the window's standard input and output, a line at a
34//! time. The button says [`TOGGLE`] when it is pressed. The window says
35//! [`UNREAD`] and `1` or `0`: whether the account has been told of
36//! something it has not looked at, which the button shows as a dot.
37//! Nothing else goes over the line: the window logs to its standard
38//! error, which is the button's, which the panel hands to the journal.
39//!
40//! The window lives as long as the button does: when its input ends, it
41//! leaves. If it goes first, the button starts another.
42//!
43//! The button is not the only one that can say [`TOGGLE`]. The window
44//! listens at a socket in the session's runtime directory as well
45//! ([`socket_path`]), and the program started with [`TOGGLE_FLAG`] says
46//! it there and leaves: which is what a keyboard shortcut of the
47//! desktop's runs, to open and close the popup without the mouse. One
48//! window listens there: this one, whenever no other does (see
49//! [`from_outside`]).
50//!
51//! ```mermaid
52//! flowchart LR
53//!     key["A key the desktop was told of"] -->|"runs"| said["The program, with --toggle"]
54//!     said -->|"toggle, at the socket"| window["The window"]
55//!     button["The button, pressed"] -->|"toggle, down the line"| window
56//!     window --> popup["The popup opens, or closes"]
57//! ```
58
59use 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
76/// What the program is started with to be the window rather than the
77/// button.
78pub const WINDOW_FLAG: &str = "--window";
79
80/// What the button says to the window when it is pressed.
81pub const TOGGLE: &str = "toggle";
82
83/// What the window says to the button, before `1` or `0`: whether there
84/// is something the account has not looked at.
85pub const UNREAD: &str = "unread";
86
87/// The variable by which iced is told what to draw with, and what the
88/// button is drawn with: the CPU renderer.
89const RENDERER: &str = "ICED_BACKEND";
90const CPU_RENDERER: &str = "tiny-skia";
91
92/// What [`RENDERER`] said when the program started, before the button
93/// took it for itself: the window's to go by.
94static RENDERER_ASKED_FOR: OnceLock<Option<String>> = OnceLock::new();
95
96/// How long after the window went the button starts another.
97const RESTART_AFTER: Duration = Duration::from_secs(2);
98
99/// How far in from the corner of the panel button the dot is that says
100/// there are new notifications.
101const DOT_INSET: u16 = 3;
102
103/// The button in the panel. See the [module docs](self).
104pub struct Button {
105    core: cosmic::Core,
106    /// The way to the window, once there is one.
107    window: Option<mpsc::Sender<()>>,
108    /// Whether the window said there is something not looked at.
109    unread: bool,
110}
111
112/// What happens to the button.
113#[derive(Debug, Clone)]
114pub enum Message {
115    /// It was pressed
116    Pressed,
117    /// A window was started: the way to it
118    Linked(mpsc::Sender<()>),
119    /// The window said whether there is something not looked at
120    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    /// The app icon, sized and padded as the panel asks, with a dot over
143    /// its corner while there is something not looked at. The dot takes no
144    /// room: the button is the same size with it and without.
145    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                // A press while no window is there, or while it is busy
158                // with the last one, is lost: the next one is not.
159                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
178/// Run the program as the button: an applet, drawn by the CPU whatever
179/// the program was built to draw with.
180pub fn run() -> cosmic::iced::Result {
181    let _ = RENDERER_ASKED_FOR.set(std::env::var(RENDERER).ok());
182    // SAFETY: `main` has started no thread yet when it comes here, so
183    // nothing reads the environment while it is written.
184    unsafe { std::env::set_var(RENDERER, CPU_RENDERER) };
185    cosmic::applet::run::<Button>(())
186}
187
188/// Start the program again as the window, on the session's compositor
189/// rather than the panel's: without the socket the panel gave the button,
190/// and drawn with what was asked for, which by default is the GPU.
191fn 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
201/// What `line`, said by the window, means: whether there is something not
202/// looked at, if that is what it says.
203fn 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
211/// The window, for as long as the button is there: started, told of each
212/// press, listened to, and started again if it goes.
213fn 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
258/// What the program is started with to say [`TOGGLE`] to the window that
259/// is running, and leave.
260pub const TOGGLE_FLAG: &str = "--toggle";
261
262/// What the socket the window listens at is called, in the session's
263/// runtime directory.
264const SOCKET_NAME: &str = "cosmic-applet-avestruz.sock";
265
266/// How long whoever connects to the socket gets to say something.
267const SAID_WITHIN: Duration = Duration::from_secs(1);
268
269/// How often the window looks whether the socket is still its own to
270/// listen at, and whether it has come to be nobody's.
271const LOOKED_AT_EVERY: Duration = Duration::from_secs(2);
272
273/// Where the window listens for what is said to it from outside: in the
274/// session's runtime directory, which is its user's alone. `None` if the
275/// session has none.
276pub fn socket_path() -> Option<PathBuf> {
277    dirs::runtime_dir().map(|directory| directory.join(SOCKET_NAME))
278}
279
280/// Say [`TOGGLE`] to the window that listens at `path`. An error if none
281/// does.
282pub 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
287/// Which file is at `path`, as the file system tells files apart. `None`
288/// if none is.
289fn 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
294/// A socket the window listens at, and which file it was when the window
295/// began to: the path may come to name another's socket, or nothing.
296struct Listening {
297    listener: tokio::net::UnixListener,
298    file: Option<(u64, u64)>,
299}
300
301impl Listening {
302    /// Listen at `path`, unless someone answers there: another window,
303    /// which is left to. What is there and answers to nobody is what a
304    /// window that is gone left behind, and is taken away first.
305    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    /// Whether `path` still names the socket listened at: not if the
315    /// file was taken away, or another put in its place.
316    fn is_still_at(&self, path: &Path) -> bool {
317        self.file.is_some() && self.file == file_at(path)
318    }
319}
320
321/// Whoever connects next to the socket listened at. Nobody, ever, while
322/// none is; `None` if they could not be let in.
323async 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
330/// What is said to the window from outside, at the socket `path`, as the
331/// window hears it: each `toggle`. Nothing, ever, if there is no path.
332///
333/// One window listens there, and it is this one whenever no other does.
334/// It looks every [`LOOKED_AT_EVERY`]: a window that finds another
335/// listening leaves the socket to it, and takes it once that one is gone;
336/// one whose socket file was taken away from under it, or replaced by
337/// one that answers to nobody, listens anew. So the socket is never left
338/// with a window running and none hearing, whatever else was started and
339/// stopped beside it, and whatever was deleted.
340///
341/// Nothing is taken away when the window leaves. A socket file with
342/// nobody behind it is in nobody's way: the next window replaces it. And
343/// taking it away is how a window that leaves late would take away the
344/// socket of the one started after it.
345pub 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
352/// [`from_outside`], looking at the socket every `looked_at_every`.
353fn 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        // Said once, not at every look.
363        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            // One line from each, and not waited for long: whoever says
393            // nothing does not keep the next from being heard.
394            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
406/// Say to the button, from the window, whether there is something not
407/// looked at. To nobody, if the window was started by hand.
408pub 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
414/// What the button says to the window, as the window hears it: each
415/// `toggle`, and that the button is gone when its end of the line closes.
416pub 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        // Said once: the stream stays open, so that it is not begun again.
429        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    /// A socket path of this test's own.
440    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    /// Say toggle at `path`, as soon as someone listens there.
445    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    /// A window that listens at `path` and looks at it every [`SOON`]:
455    /// what it hears, and the task it runs as, which ends when aborted.
456    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    /// How often the windows of these tests look at their socket.
471    const SOON: Duration = Duration::from_millis(20);
472
473    /// What `heard` hears next, if it comes soon enough.
474    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        // What a window that is gone left there is in nobody's way.
482        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            // Once the window listens: a toggle, something that is no
489            // toggle, and someone who says nothing at all.
490            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            // And once only.
499            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            // Another is started beside it, and has looked a few times:
515            // the first is the one that hears still.
516            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            // The first goes, and leaves its socket file behind with
523            // nobody at it: the second takes its place.
524            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            // Deleted from under it: what something run beside it did.
544            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            // And replaced by a file that answers to nobody.
550            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        // Anything else on the line is not for the button.
573        assert_eq!(unread_said(&format!("{UNREAD} many")), None);
574        assert_eq!(unread_said(TOGGLE), None);
575        assert_eq!(unread_said(""), None);
576    }
577}