Skip to main content

cosmic_applet_avestruz/
app.rs

1// SPDX-License-Identifier: MIT
2
3//! COSMIC application implementation for Avestruz.
4//!
5//! This module wires up the [`cosmic::Application`] trait — defining the
6//! init, update, view, and subscription lifecycle — and re-exports the
7//! core types ([`AppModel`], [`Message`], [`ViewState`]) that the rest
8//! of the crate depends on.
9//!
10//! ```mermaid
11//! flowchart TD
12//!     init["init: the config is read, and four things start at once"] --> running
13//!     subgraph running["For as long as the session"]
14//!         direction LR
15//!         subscription["subscription: two timers, the config watch, pictures and previews asked for"]
16//!         update["update: one match over every Message, each arm a handler"]
17//!         button["the button in the panel: another process"]
18//!         window["view_window: the popup, when it is open"]
19//!         subscription -->|"messages"| update
20//!         window -->|"messages"| update
21//!         button -->|"TogglePopup"| subscription
22//!         update -->|"the model changed"| window
23//!     end
24//! ```
25//!
26//! What starts at `init`, and in which order the answers matter, is in
27//! [`crate::guide::architecture`].
28
29use std::collections::{HashMap, HashSet};
30use std::sync::Arc;
31use std::time::Duration;
32
33use cosmic::cosmic_config::{self, CosmicConfigEntry};
34use cosmic::iced::Subscription;
35use cosmic::iced::event::Status;
36use cosmic::iced::keyboard::key::Named;
37use cosmic::iced::keyboard::{self, Key};
38use cosmic::iced::runtime::core::event::wayland::LayerEvent;
39use cosmic::iced::runtime::core::event::{PlatformSpecific, wayland};
40use cosmic::iced::window::Id;
41use cosmic::prelude::*;
42use cosmic::widget::segmented_button;
43use tokio::sync::Mutex;
44
45use crate::button;
46use crate::config::Config;
47use crate::drafts::{self, Drafts};
48use crate::emoji;
49use crate::fl;
50use crate::fonts;
51use crate::http;
52use crate::images::{self, ImageStore};
53use crate::logging;
54use crate::nostr::account::{self, Signer};
55use crate::nostr::client::{self, NostrService};
56use crate::nostr::engagement::Mark;
57use crate::nostr::feed::FeedMode;
58use crate::previews::PreviewStore;
59use crate::requests;
60use crate::video::Videos;
61
62// Re-export types from state and messages modules
63pub use crate::messages::Message;
64use crate::nostr::notifications::Tab;
65pub use crate::state::{AppModel, BookmarkState, FeedState, LoginProgress, MediaState, RelaysState, ViewState};
66use crate::state::{NotificationsState, REACTIONS_OFFERED, Step};
67
68/// The name the panel, the settings and the keyring know Avestruz by.
69pub const APP_ID: &str = "io.github.cosmic-applet-avestruz";
70
71/// Run the program as the window: the whole client, with no window of its
72/// own until the button in the panel asks for the popup (see
73/// [`crate::button`]). It stays when the popup closes, and leaves when
74/// the button does.
75pub fn run() -> cosmic::iced::Result {
76    let settings =
77        cosmic::app::Settings::default().no_main_window(true).exit_on_close(false).default_text_size(14.0).transparent(true);
78    cosmic::app::run::<AppModel>(settings, ())
79}
80
81/// How often the feed is looked at for new notes: while the popup is open,
82/// and while it is closed.
83const NEW_NOTES_EVERY_OPEN: Duration = Duration::from_secs(60);
84
85/// How often the composer says anew how far the files on their way to a
86/// media server have got.
87const UPLOADS_SHOWN_EVERY: Duration = Duration::from_millis(250);
88const NEW_NOTES_EVERY_CLOSED: Duration = Duration::from_secs(5 * 60);
89
90/// How often it is seen whether the event store is to let go of what is
91/// old: it does so once a day, and the day may begin at any time.
92const SWEEP_LOOK_EVERY: Duration = Duration::from_secs(60 * 60);
93
94impl cosmic::Application for AppModel {
95    type Executor = cosmic::executor::Default;
96
97    type Flags = ();
98
99    type Message = Message;
100
101    /// Unique identifier in RDNN (reverse domain name notation) format.
102    const APP_ID: &'static str = APP_ID;
103
104    fn core(&self) -> &cosmic::Core {
105        &self.core
106    }
107
108    fn core_mut(&mut self) -> &mut cosmic::Core {
109        &mut self.core
110    }
111
112    /// Initializes the application with any given flags and startup commands.
113    fn init(core: cosmic::Core, _flags: Self::Flags) -> (Self, Task<cosmic::Action<Self::Message>>) {
114        let config = cosmic_config::Config::new(Self::APP_ID, Config::VERSION)
115            .map(|context| match Config::get_entry(&context) {
116                Ok(config) => config,
117                Err((_errors, config)) => config,
118            })
119            .unwrap_or_default();
120
121        // Log as much as the settings say, unless `RUST_LOG` does, which
122        // keeps precedence as it had in `main`.
123        if !logging::level_set_by_environment() {
124            logging::set_console_level(config.log_level);
125        }
126
127        // Before anything is drawn: emoji would come out blank, or from
128        // a text font, otherwise.
129        fonts::prepare();
130
131        // Open the event store and start connecting to relays, off the main
132        // thread.
133        let open_task = Task::perform(NostrService::open(client::default_store_path(), config.relays.clone()), |result| {
134            cosmic::Action::App(Message::NostrReady(result))
135        });
136
137        // Someone signed in before: straight to their feed, and ask the
138        // keyring whether their secret key is there.
139        let (view_state, restore_task) = match &config.account {
140            Some(npub) => (
141                ViewState::Feed,
142                Task::perform(account::restore(npub.clone()), |result| cosmic::Action::App(Message::AccountRestored(result))),
143            ),
144            None => (ViewState::Login, Task::none()),
145        };
146
147        let draft_path = drafts::default_draft_path();
148
149        // The two ways a list of notes is read, for the control that
150        // chooses between them, with the one kept from last time chosen.
151        let feed_modes = FeedMode::ALL
152            .into_iter()
153            .fold(segmented_button::Model::builder(), |modes, mode| {
154                let label = match mode {
155                    FeedMode::Notes => fl!("feed-mode-notes"),
156                    FeedMode::Replies => fl!("feed-mode-replies"),
157                };
158                modes.insert(|choice| {
159                    let choice = choice.text(label).data(mode);
160                    if mode == config.feed_mode { choice.activate() } else { choice }
161                })
162            })
163            .build();
164
165        // Writing a note and looking at how it would show, for the control
166        // that chooses: writing, until the look is asked for.
167        let compose_tabs = [false, true]
168            .into_iter()
169            .fold(segmented_button::Model::builder(), |tabs, preview| {
170                let label = if preview { fl!("compose-tab-preview") } else { fl!("compose-tab-write") };
171                tabs.insert(|choice| {
172                    let choice = choice.text(label).data(preview);
173                    if preview { choice } else { choice.activate() }
174                })
175            })
176            .build();
177
178        // Which notifications show, for the control that chooses.
179        let notification_tabs = Tab::ALL
180            .into_iter()
181            .fold(segmented_button::Model::builder(), |tabs, tab| {
182                let label = match tab {
183                    Tab::All => fl!("notifications-tab-all"),
184                    Tab::Mentions => fl!("notifications-tab-mentions"),
185                    Tab::Reactions => fl!("notifications-tab-reactions"),
186                    Tab::Zaps => fl!("notifications-tab-zaps"),
187                };
188                tabs.insert(|choice| {
189                    let choice = choice.text(label).data(tab);
190                    if tab == Tab::All { choice.activate() } else { choice }
191                })
192            })
193            .build();
194
195        let reaction_suggestions = emoji::suggested(&config.reaction_emojis, REACTIONS_OFFERED);
196
197        // Views ask the store for pictures; the store sends the addresses
198        // it doesn't have down a channel, which a subscription drains.
199        let (image_store, image_requests) = ImageStore::new(images::DEFAULT_BUDGET_BYTES);
200        // And for what the pages notes link to say of themselves, likewise.
201        let (preview_store, preview_requests) = PreviewStore::new();
202
203        let app = AppModel {
204            core,
205            config,
206            popup: None,
207            keeper: Id::unique(),
208            popup_unfocused_at: None,
209            unread_told: false,
210            view_state,
211            screen: None,
212            nostr: None,
213            account: None,
214            login_input: String::new(),
215            login_input_hidden: true,
216            login_error: None,
217            login_refusal: None,
218            login_progress: LoginProgress::Idle,
219            signer: Signer::default(),
220            following: FeedState::new(0),
221            follows: None,
222            feeds_made: 0,
223            feed_checked_at: None,
224            feed_modes,
225            notifications: NotificationsState::default(),
226            notification_tabs,
227            pages: Vec::new(),
228            composer: None,
229            compose_tabs,
230            drafts: Drafts::default(),
231            draft_path: draft_path.clone(),
232            drafts_kept: HashMap::new(),
233            drafts_asked: false,
234            zap: None,
235            engagement: HashMap::new(),
236            engagement_asked: HashMap::new(),
237            seen_on: HashMap::new(),
238            pending_marks: HashSet::new(),
239            repost_menu: None,
240            reaction_menu: None,
241            who_menu: None,
242            reaction_suggestions,
243            share_copied: None,
244            picture_copied: None,
245            bookmarks: BookmarkState::Unknown,
246            bookmarks_asked_at: None,
247            bookmark_pending: None,
248            bookmark_first_list: false,
249            swept_at: None,
250            menu_open: false,
251            relays: RelaysState::default(),
252            media: MediaState::default(),
253            profiles: HashMap::new(),
254            profiles_requested: HashSet::new(),
255            nip05: HashMap::new(),
256            follow_pending: None,
257            images: image_store,
258            image_requests: Arc::new(Mutex::new(image_requests)),
259            previews: preview_store,
260            videos: Videos::default(),
261            preview_requests: Arc::new(Mutex::new(preview_requests)),
262            http: http::client(),
263            error_message: None,
264        };
265
266        let draft_task = Task::perform(drafts::load(draft_path), |text| cosmic::Action::App(Message::DraftLoaded(text)));
267
268        // Before any popup: see `keep_what_is_copied`.
269        let keeper = app.keep_what_is_copied();
270        let measured = app.measure_screen_soon();
271        (app, Task::batch([keeper, open_task, restore_task, draft_task, measured]))
272    }
273
274    /// Escape, pressed where nothing in the popup had a use for it of its
275    /// own (an open dropdown has: it closes). libcosmic listens for the key
276    /// and asks here what it means, which by default is nothing.
277    fn on_escape(&mut self) -> Task<cosmic::Action<Self::Message>> {
278        self.handle_escape()
279    }
280
281    fn on_close_requested(&self, id: Id) -> Option<Message> {
282        Some(Message::PopupClosed(id))
283    }
284
285    /// Nothing: there is no window but the popup. The button that opens it
286    /// is in the panel, and another process (see [`crate::button`]).
287    fn view(&self) -> Element<'_, Self::Message> {
288        cosmic::widget::Space::new().into()
289    }
290
291    /// The popup is drawn using this view method. The surface that keeps
292    /// what is copied shows nothing.
293    fn view_window(&self, id: Id) -> Element<'_, Self::Message> {
294        if id == self.keeper {
295            return cosmic::widget::Space::new().into();
296        }
297        self.view_popup(id)
298    }
299
300    /// Register subscriptions for this application.
301    fn subscription(&self) -> Subscription<Self::Message> {
302        // The feed is looked at for new notes every so often: often while
303        // the popup is open, now and then while it isn't. They wait to be
304        // asked for either way.
305        let look_every = if self.popup.is_some() { NEW_NOTES_EVERY_OPEN } else { NEW_NOTES_EVERY_CLOSED };
306
307        // A video that plays is looked at for its next picture, and one
308        // that is held now and then, while there is one.
309        let video = self.videos.tick_every(self.popup.is_some());
310
311        // How far the files on their way have got is shown as it changes.
312        let uploading = self.popup.is_some() && !self.media.uploads.is_empty();
313
314        Subscription::batch([
315            if uploading {
316                cosmic::iced::time::every(UPLOADS_SHOWN_EVERY).map(|_| Message::UploadTick)
317            } else {
318                Subscription::none()
319            },
320            video.map_or_else(Subscription::none, |every| cosmic::iced::time::every(every).map(|_| Message::VideoTick)),
321            cosmic::iced::time::every(look_every).map(|_| Message::CheckForNewNotes),
322            cosmic::iced::time::every(SWEEP_LOOK_EVERY).map(|_| Message::SweepStore),
323            // Watch for application configuration changes.
324            self.core().watch_config::<Config>(Self::APP_ID).map(|update| Message::UpdateConfig(update.config)),
325            // Pictures the views asked for and didn't have: one `LoadImage`
326            // each. `handle_load_image` decides which are actually fetched.
327            requests::subscription(&self.image_requests, Message::LoadImage),
328            // The pages notes link to, likewise: one `LoadPreview` each.
329            requests::subscription(&self.preview_requests, Message::LoadPreview),
330            // What the button in the panel says: that it was pressed, and
331            // in the end that it is gone.
332            Subscription::run(from_button),
333            // And what is said from outside: that a key was pressed that
334            // the desktop was told opens it.
335            Subscription::run(from_outside),
336            // The popup lost the keyboard: something else was clicked. And
337            // the keys of a list, where no widget had a use for the key: a
338            // text being typed takes them for itself. What they do is in
339            // `handlers::keys`.
340            cosmic::iced::event::listen_with(|event, status, _window| match event {
341                // A picture of the popup, wherever the keyboard is in it:
342                // no text takes Ctrl+Shift+S for itself.
343                cosmic::iced::Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, repeat: false, .. })
344                    if modifiers.control() && modifiers.shift() && matches!(key.as_ref(), Key::Character("s" | "S")) =>
345                {
346                    Some(Message::TakeScreenshot)
347                }
348                // Nor Ctrl+P: what is being written, as it would show, and
349                // back to writing it.
350                cosmic::iced::Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, repeat: false, .. })
351                    if modifiers.control()
352                        && !modifiers.shift()
353                        && !modifiers.alt()
354                        && !modifiers.logo()
355                        && matches!(key.as_ref(), Key::Character("p" | "P")) =>
356                {
357                    Some(Message::ToggleComposePreview)
358                }
359                // Ctrl+Enter is the text's while the keyboard is in it. Where
360                // it is not, as when the text is not what shows, it
361                // publishes all the same.
362                cosmic::iced::Event::Keyboard(keyboard::Event::KeyPressed {
363                    key: Key::Named(Named::Enter),
364                    modifiers,
365                    repeat: false,
366                    ..
367                }) if status == Status::Ignored && modifiers.control() && !modifiers.alt() && !modifiers.logo() => {
368                    Some(Message::Publish)
369                }
370                cosmic::iced::Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, repeat, .. })
371                    if status == Status::Ignored && !modifiers.command() && !modifiers.alt() && !modifiers.logo() =>
372                {
373                    match key.as_ref() {
374                        Key::Character("j") => Some(Message::StepNote(Step::Next)),
375                        Key::Character("k") => Some(Message::StepNote(Step::Previous)),
376                        Key::Named(Named::Home) => Some(Message::StepNote(Step::Top)),
377                        Key::Character("l") | Key::Named(Named::Enter) => Some(Message::OpenMarked),
378                        Key::Character("h") => Some(Message::GoBack),
379                        Key::Named(Named::Backspace) => Some(Message::Backspace { held: repeat }),
380                        Key::Character(".") => Some(Message::ShowWaiting),
381                        Key::Character("y") => Some(Message::ShareMarked),
382                        Key::Character(" ") => Some(Message::PlayMarked),
383                        Key::Character("r") => Some(Message::ReplyMarked),
384                        Key::Character("R") => Some(Message::RepostMarked),
385                        Key::Named(Named::ArrowDown) => Some(Message::StepChoice(Step::Next)),
386                        Key::Named(Named::ArrowUp) => Some(Message::StepChoice(Step::Previous)),
387                        Key::Character("z") => Some(Message::ZapMarked),
388                        Key::Character("b") => Some(Message::BookmarkMarked),
389                        Key::Character("B") => Some(Message::GoToBookmarks),
390                        Key::Character("s") => Some(Message::GoToSearch),
391                        Key::Character("?") => Some(Message::ShowKeys),
392                        _ => None,
393                    }
394                }
395                cosmic::iced::Event::PlatformSpecific(PlatformSpecific::Wayland(wayland::Event::Layer(
396                    LayerEvent::Unfocused,
397                    _,
398                    id,
399                ))) => Some(Message::PopupUnfocused(id)),
400                _ => None,
401            }),
402        ])
403    }
404
405    /// Handles messages emitted by the application and its widgets.
406    ///
407    /// This function dispatches messages to the appropriate handler modules:
408    /// - `handlers::navigation` - The popup, which view it shows, and the pages opened over the feed
409    /// - `handlers::auth` - Signing in and out
410    /// - `handlers::feed` - Loading the feed, other lists of notes, and authors' profiles
411    /// - `handlers::thread` - Opening a note's thread
412    /// - `handlers::profile` - Opening someone's profile
413    /// - `handlers::compose` - Writing and publishing notes, replies and quotes
414    /// - `handlers::media` - The account's media servers, and attaching files to what is being written
415    /// - `handlers::keys` - The keyboard, on a list: stepping through it, opening a row, going back
416    /// - `handlers::engagement` - What was made of notes, and liking and reposting them
417    /// - `handlers::bookmarks` - What the account has bookmarked, and bookmarking a note
418    /// - `handlers::zap` - Zapping a note: the invoice, and its receipt
419    /// - `handlers::images` - Fetching the pictures views ask for
420    /// - `handlers::previews` - Asking the pages notes link to what they say of themselves
421    /// - `handlers::video` - Playing a video, and finding what there is to play of a YouTube one
422    /// - `handlers::share` - Copying a link to a note that anyone can open
423    /// - `handlers::screenshot` - Taking a picture of the popup, from the popup
424    /// - `handlers::settings` - The settings: how large notes are set, how long they are kept, how much is logged
425    /// - `handlers::store` - Having the event store let go of what is old
426    /// - `handlers::notifications` - What others did that concerns the account
427    ///
428    /// Messages are not logged wholesale: several carry a page of notes, and
429    /// one carries what is typed in the sign-in field. Handlers log what
430    /// happened instead.
431    fn update(&mut self, message: Self::Message) -> Task<cosmic::Action<Self::Message>> {
432        let task = self.handle(message);
433        // Whatever the message did, the notifications may have come into
434        // view by it, or gone out of it.
435        self.watch_notifications();
436        // The button in the panel shows whether there are any not looked
437        // at: it is told when that changes.
438        let unread = self.unread_notifications() > 0;
439        if unread != self.unread_told {
440            self.unread_told = unread;
441            button::tell_unread(unread);
442        }
443        task
444    }
445
446    fn style(&self) -> Option<cosmic::iced::theme::Style> {
447        Some(cosmic::applet::style())
448    }
449}
450
451impl AppModel {
452    /// Do what `message` asks: the one place every message goes through.
453    fn handle(&mut self, message: Message) -> Task<cosmic::Action<Message>> {
454        match message {
455            // Navigation handlers
456            Message::TogglePopup => self.handle_toggle_popup(),
457            Message::StepNote(step) => self.handle_step_note(step),
458            Message::OpenMarked => self.handle_open_marked(),
459            Message::ShareMarked => self.handle_share_marked(),
460            Message::PlayMarked => self.handle_play_marked(),
461            Message::ReplyMarked => self.handle_reply_marked(),
462            Message::RepostMarked => self.handle_repost_marked(),
463            Message::StepChoice(step) => self.handle_step_choice(step),
464            Message::ZapMarked => self.handle_zap_marked(),
465            Message::BookmarkMarked => self.handle_bookmark_marked(),
466            Message::GoToBookmarks => self.handle_go_to_bookmarks(),
467            Message::GoToSearch => self.handle_go_to_search(),
468            Message::ShowKeys => self.handle_show_keys(),
469            Message::ShowWaiting => self.handle_show_waiting(),
470            Message::GoBack => self.handle_go_back(),
471            Message::Backspace { held } => self.handle_backspace(held),
472            Message::PopupClosed(id) => self.handle_popup_closed(id),
473            Message::PopupUnfocused(id) => self.handle_popup_unfocused(id),
474            Message::ButtonGone => cosmic::iced::exit(),
475            Message::ScreenMeasured(screen) => {
476                self.handle_screen_measured(screen);
477                Task::none()
478            }
479            Message::ClosePage => self.handle_close_page(),
480            Message::ToggleMenu => {
481                self.menu_open = !self.menu_open;
482                Task::none()
483            }
484            Message::CloseMenu => {
485                self.menu_open = false;
486                Task::none()
487            }
488            Message::OpenSettings => {
489                self.handle_open_settings();
490                Task::none()
491            }
492            Message::CloseSettings | Message::CloseKeys => self.show_list_view(),
493            Message::OpenKeys => {
494                self.handle_open_keys();
495                Task::none()
496            }
497
498            // Search handlers
499            Message::OpenSearch => self.handle_open_search(),
500            Message::SearchTyped(page, typed) => {
501                self.handle_search_typed(page, typed);
502                Task::none()
503            }
504            Message::Search(page) => self.handle_search(page),
505            Message::SearchShow(page, what) => self.handle_search_show(page, what),
506            Message::SearchFound { page, serial, what, result } => self.handle_search_found(page, serial, what, result),
507
508            Message::SearchNamed { page, name, person } => self.handle_search_named(page, &name, person),
509            Message::RelayInfoLoaded { page, serial, info } => {
510                self.handle_relay_info_loaded(page, serial, info);
511                Task::none()
512            }
513
514            // Relays handlers
515            Message::OpenRelays => self.handle_open_relays(),
516            Message::CloseRelays => self.show_list_view(),
517            Message::RelayListsLoaded { account, source, result } => self.handle_relay_lists_loaded(account, source, result),
518            Message::RelayUseLoaded(in_use) => {
519                self.relays.in_use = in_use;
520                Task::none()
521            }
522            Message::RelaySaid { relay, info } => {
523                self.relays.said.insert(relay, info);
524                Task::none()
525            }
526            Message::RelayTyped(section, typed) => {
527                self.relays.typed.insert(section, typed);
528                Task::none()
529            }
530            Message::AddRelay(section) => self.handle_add_relay(section),
531            Message::RemoveRelay(section, relay) => {
532                self.handle_remove_relay(section, &relay);
533                Task::none()
534            }
535            Message::ShiftRelay(section, relay, up) => {
536                self.handle_shift_relay(section, &relay, up);
537                Task::none()
538            }
539            Message::SaveRelays => self.handle_save_relays(),
540            Message::RelaysSaved { account, advertised, listed } => {
541                self.handle_relays_saved(account, advertised, listed);
542                Task::none()
543            }
544            // Media handlers
545            Message::OpenMedia => self.handle_open_media(),
546            Message::CloseMedia => self.handle_close_media(),
547            Message::MediaServersLoaded { account, source, result } => self.handle_media_servers_loaded(account, source, result),
548            Message::MediaServerTyped(typed) => {
549                self.media.typed = typed;
550                Task::none()
551            }
552            Message::AddMediaServer => {
553                self.handle_add_media_server();
554                Task::none()
555            }
556            Message::RemoveMediaServer(server) => {
557                self.handle_remove_media_server(&server);
558                Task::none()
559            }
560            Message::ShiftMediaServer(server, up) => {
561                self.handle_shift_media_server(&server, up);
562                Task::none()
563            }
564            Message::SaveMediaServers => self.handle_save_media_servers(),
565            Message::MediaServersSaved { account, result } => {
566                self.handle_media_servers_saved(account, result);
567                Task::none()
568            }
569            Message::AttachMedia => self.handle_attach_media(),
570            Message::MediaPicked(picked) => self.handle_media_picked(picked),
571            Message::ComposePaste => self.handle_compose_paste(),
572            Message::ComposePasted(pasted) => self.handle_compose_pasted(pasted),
573            Message::MediaUploaded { id, result } => self.handle_media_uploaded(id, result),
574            Message::CancelUpload(id) => {
575                self.handle_cancel_upload(id);
576                Task::none()
577            }
578            // Nothing changed but how far they have got, which is read
579            // when the view is drawn.
580            Message::UploadTick => Task::none(),
581            Message::ClearError => {
582                self.error_message = None;
583                Task::none()
584            }
585            // Image handlers
586            Message::CopyPicture(url) => self.handle_copy_picture(url),
587            Message::LoadImage(request) => self.handle_load_image(request),
588            Message::ImageLoaded(request, result) => {
589                self.handle_image_loaded(request, result);
590                Task::none()
591            }
592            // Link preview handlers
593            Message::LoadPreview(url) => self.handle_load_preview(url),
594            Message::PreviewLoaded(url, result) => {
595                self.handle_preview_loaded(url, result);
596                Task::none()
597            }
598
599            // Videos: the one that plays is the model's, and all there is
600            // to do is tell it.
601            Message::VideoPress(url) => self.handle_video_press(url),
602            Message::VideoFound(url, result) => {
603                self.handle_video_found(&url, result);
604                Task::none()
605            }
606            Message::VideoMute => {
607                self.videos.toggle_mute();
608                Task::none()
609            }
610            Message::VideoVolume(shown) => {
611                self.videos.set_volume(shown);
612                Task::none()
613            }
614            Message::VideoVolumeSet => {
615                self.videos.volume_set();
616                Task::none()
617            }
618            Message::VideoSound(over) => {
619                self.videos.sound_over(over);
620                Task::none()
621            }
622            Message::VideoSpeedMenu => {
623                self.videos.toggle_speed_menu();
624                Task::none()
625            }
626            Message::CloseVideoSpeedMenu => {
627                self.videos.close_speed_menu();
628                Task::none()
629            }
630            Message::VideoSpeed(speed) => {
631                self.videos.set_speed(speed);
632                Task::none()
633            }
634            Message::VideoSeeking(seconds) => {
635                self.videos.seeking(seconds);
636                Task::none()
637            }
638            Message::VideoSeek => {
639                self.videos.seek();
640                Task::none()
641            }
642            Message::VideoTick => {
643                self.videos.tick();
644                Task::none()
645            }
646
647            Message::CopyShareLink(id) => self.handle_copy_share_link(id),
648
649            Message::OpenNotifications => self.handle_open_notifications(),
650            Message::NotificationsLoaded { account, source, older, result } => {
651                self.handle_notifications_loaded(account, source, older, result)
652            }
653            Message::LoadOlderNotifications => self.handle_load_older_notifications(),
654            Message::SelectNotificationsTab(chosen) => self.handle_select_notifications_tab(chosen),
655            Message::ZapperKnown(account, result) => {
656                self.handle_zapper_known(account, result);
657                Task::none()
658            }
659
660            Message::ExpandNote(id) => {
661                self.handle_expand_note(id);
662                Task::none()
663            }
664            Message::CollapseNote(id) => self.handle_collapse_note(id),
665
666            Message::OpenUrl(url) => {
667                self.handle_open_url(&url);
668                Task::none()
669            }
670            Message::UpdateConfig(config) => self.handle_update_config(config),
671            Message::SetLogLevel(level) => {
672                self.handle_set_log_level(level);
673                Task::none()
674            }
675            Message::SetNoteTextSize(size) => {
676                self.handle_set_note_text_size(size);
677                Task::none()
678            }
679            Message::SetKeepDays(days) => self.handle_set_keep_days(days),
680            Message::SweepStore => self.sweep_store(),
681
682            // Auth handlers
683            Message::LoginInputChanged(input) => {
684                self.handle_login_input_changed(input);
685                Task::none()
686            }
687            Message::ToggleLoginInputVisibility => {
688                self.login_input_hidden = !self.login_input_hidden;
689                Task::none()
690            }
691            Message::SubmitLogin => self.handle_submit_login(),
692            Message::CancelLogin => {
693                self.signer.cancel_sign_in();
694                Task::none()
695            }
696            Message::CopyClientKey => self.handle_copy_client_key(),
697            Message::LoginComplete(result) => self.handle_login_complete(result),
698            Message::AccountRestored(result) => self.handle_account_restored(result),
699            Message::SignOut => self.handle_sign_out(),
700            Message::SignedOut(result) => {
701                self.handle_signed_out(result);
702                Task::none()
703            }
704
705            // Feed handlers
706            Message::NostrReady(result) => self.handle_nostr_ready(result),
707            Message::FeedCached(id, result) => self.handle_feed_cached(id, result),
708            Message::RefreshFeed => self.handle_refresh_feed(),
709            Message::FeedFetched { list, page, until, result } => self.handle_feed_fetched(list, page, until, result),
710            Message::CheckForNewNotes => self.handle_check_for_new_notes(),
711            Message::ShowNewNotes(id) => self.show_new_notes(id),
712            Message::LoadOlderNotes(id) => self.handle_load_older_notes(id),
713            Message::SelectFeedMode(chosen) => self.handle_select_feed_mode(chosen),
714            Message::ContactsLoaded { feed, source, result } => self.handle_contacts_loaded(feed, source, result),
715            Message::ProfilesCached { requested, found } => self.handle_profiles_cached(requested, found),
716            Message::ProfilesFetched(found) => self.handle_profiles_fetched(found),
717
718            // Thread handlers
719            Message::OpenThread(id, whereabouts) => self.handle_open_thread(id, whereabouts),
720            Message::ThreadLoaded { focused, source, result } => self.handle_thread_loaded(focused, source, result),
721
722            // Profile handlers
723            Message::OpenProfile(public_key) => self.handle_open_profile(public_key),
724            Message::CopyNpub(public_key) => self.handle_copy_npub(public_key),
725            Message::Nip05Checked { person, name, verified } => {
726                self.handle_nip05_checked(person, &name, verified);
727                Task::none()
728            }
729            Message::Follow { person, follow, first_list } => self.handle_follow(person, follow, first_list),
730            Message::FollowChanged { account, person, result } => self.handle_follow_changed(account, person, result),
731
732            // Engagement handlers
733            Message::EngagementLoaded { source, account, result } => {
734                self.handle_engagement_loaded(source, account, result);
735                Task::none()
736            }
737            Message::ToggleReactionMenu(id) => {
738                self.handle_toggle_reaction_menu(id);
739                Task::none()
740            }
741            Message::CloseReactionMenu => {
742                self.reaction_menu = None;
743                Task::none()
744            }
745            Message::OpenEmojiPicker => self.handle_open_emoji_picker(),
746            Message::EmojiSearchTyped(typed) => {
747                self.handle_emoji_search_typed(typed);
748                Task::none()
749            }
750            Message::EmojiGroup(group) => {
751                self.handle_emoji_group(group);
752                Task::none()
753            }
754            Message::React(id, reaction) => self.handle_react(id, reaction),
755            Message::ToggleRepostMenu(id) => {
756                self.handle_toggle_repost_menu(id);
757                Task::none()
758            }
759            Message::CloseRepostMenu => {
760                self.repost_menu = None;
761                Task::none()
762            }
763            Message::Repost(id) => self.handle_mark(id, Mark::Repost),
764            Message::ShowWho(note, what) => self.handle_show_who(note, what),
765            Message::WhoLoaded { note, what, result } => self.handle_who_loaded(note, what, result),
766            Message::CloseWho => {
767                self.who_menu = None;
768                Task::none()
769            }
770            Message::TakeScreenshot => self.handle_take_screenshot(),
771            Message::ScreenshotTaken(taken) => {
772                self.handle_screenshot_taken(taken);
773                Task::none()
774            }
775            Message::Marked { note, mark, result } => {
776                self.handle_marked(note, mark, result);
777                Task::none()
778            }
779
780            // Bookmark handlers
781            Message::BookmarksLoaded { account, source, result } => self.handle_bookmarks_loaded(account, source, result),
782            Message::Bookmark(id) => self.handle_bookmark(id),
783            Message::Bookmarked { account, note, result } => {
784                self.handle_bookmarked(account, note, result);
785                Task::none()
786            }
787            Message::OpenBookmarks => self.handle_open_bookmarks(),
788            Message::LoadBookmarkedNotes(page) => self.handle_load_bookmarked_notes(page),
789            Message::BookmarkedNotesLoaded { page, taken, from, to, notes } => {
790                self.handle_bookmarked_notes_loaded(page, taken, from, to, notes)
791            }
792
793            // Zap handlers
794            Message::ZapNote(id) => self.handle_zap_note(id),
795            Message::ZapAmountChanged(amount) => {
796                self.handle_zap_amount_changed(&amount);
797                Task::none()
798            }
799            Message::ZapCommentChanged(comment) => {
800                self.handle_zap_comment_changed(&comment);
801                Task::none()
802            }
803            Message::RequestZapInvoice => self.handle_request_zap_invoice(),
804            Message::ZapInvoiceReady { note, result } => self.handle_zap_invoice_ready(note, result),
805            Message::CopyZapInvoice => self.handle_copy_zap_invoice(),
806            Message::ZapReceiptAwaited { note, paid } => self.handle_zap_receipt_awaited(note, paid),
807            Message::CloseZap => self.handle_close_zap(),
808
809            // Composer handlers
810            Message::DraftKept { account, target, text, result } => self.handle_draft_kept(account, target, text, result),
811            Message::KeptDraftsLoaded { account, result } => {
812                self.handle_kept_drafts_loaded(account, result);
813                Task::none()
814            }
815            Message::DraftLoaded(text) => {
816                self.handle_draft_loaded(text);
817                Task::none()
818            }
819            Message::ComposeNote => self.handle_compose_note(),
820            Message::ComposeReply(id) => self.handle_compose_reply(id),
821            Message::ComposeQuote(id) => self.handle_compose_quote(id),
822            Message::ComposeEdited(action) => {
823                self.handle_compose_edited(action);
824                Task::none()
825            }
826            Message::SelectComposeTab(chosen) => self.handle_select_compose_tab(chosen),
827            Message::ToggleComposePreview => self.handle_toggle_compose_preview(),
828            Message::ComposePreviewed(note) => self.handle_compose_previewed(note),
829            Message::CloseComposer => self.handle_close_composer(),
830            Message::ComposerRubbedOut => self.handle_composer_rubbed_out(),
831            Message::DiscardDraft => self.handle_discard_draft(),
832            Message::ResumeComposer => self.handle_resume_composer(),
833            Message::Publish => self.handle_publish(),
834            Message::Published { target, result } => self.handle_published(target, result),
835        }
836    }
837}
838
839/// What is said to the window from outside, as messages: a keyboard
840/// shortcut of the desktop's toggles the popup as the button does.
841fn from_outside() -> impl cosmic::iced::futures::Stream<Item = Message> {
842    button::from_outside(button::socket_path(), Message::TogglePopup)
843}
844
845/// What the button in the panel says, as messages.
846fn from_button() -> impl cosmic::iced::futures::Stream<Item = Message> {
847    button::from_button(Message::TogglePopup, Message::ButtonGone)
848}