cosmic_applet_avestruz/messages.rs
1// SPDX-License-Identifier: MIT
2
3//! Application messages for Avestruz.
4//!
5//! This module defines all the messages that can be sent to update the application state.
6//!
7//! A message is the only thing that changes the model (see
8//! [`crate::guide::architecture`]). There are three kinds of them, told
9//! apart by where they come from:
10//!
11//! ```mermaid
12//! flowchart LR
13//! reader(["The reader"]) -->|"pressed, typed, scrolled"| did["What was done: OpenThread, Like, Publish"]
14//! timer(["A timer, the config watch, a view that needs a picture"]) --> time["What is due: CheckForNewNotes, SweepStore, LoadImage"]
15//! task(["A task that finished"]) --> answer["What came back: FeedFetched, ThreadLoaded, Published"]
16//! did --> update["app: update"]
17//! time --> update
18//! answer --> update
19//! ```
20//!
21//! A message of the third kind says what it is an answer to (a list's
22//! id, a search's serial number, an account's public key), so that its
23//! handler can tell an answer that came too late from one that is still
24//! wanted.
25//!
26//! Messages are `Debug`, and may end up in a log: one that would carry
27//! what is typed in the sign-in field carries a [`SecretInput`] instead,
28//! which prints nothing.
29
30use std::collections::HashMap;
31use std::fmt;
32use std::path::PathBuf;
33
34use cosmic::iced::core::window::Screenshot;
35use cosmic::iced::window::Id;
36use cosmic::widget::{segmented_button, text_editor};
37use nostr_sdk::prelude::{Event, EventId, PublicKey, RelayUrl, Tag, Url};
38
39use crate::config::{Config, LogLevel};
40use crate::emoji::Group;
41use crate::handlers::media::Pasted;
42use crate::images::{ImageRequest, LoadedImage};
43use crate::media::MediaError;
44use crate::nostr::account::{Account, SignError, SignInError};
45use crate::nostr::blossom::{Attachment, UploadError};
46use crate::nostr::bookmarks::Bookmarks;
47use crate::nostr::client::{FetchError, FollowError, ListError, NostrService, Notified, PublishError, RelayUse, Source};
48use crate::nostr::compose::Target;
49use crate::nostr::engagement::{Doer, Left, Mark, Reaction, Standing};
50use crate::nostr::feed::FeedPage;
51use crate::nostr::models::{Note, Profile};
52use crate::nostr::outbox::Whereabouts;
53use crate::nostr::relay_info::RelayInfo;
54use crate::nostr::relay_lists::{ListedRelays, RelayLists, Section};
55use crate::nostr::search::{Found, SearchFor};
56use crate::nostr::zap::{Invoice, ZapError};
57use crate::previews::Linked;
58use crate::screen::Screen;
59use crate::state::Step;
60use crate::video::Speed;
61use crate::youtube::FindError;
62
63/// Text from the sign-in field, which may be a secret key.
64///
65/// Messages are `Debug`, and whatever is `Debug` ends up in a log sooner or
66/// later. This never prints what it holds.
67#[derive(Clone)]
68pub struct SecretInput(pub String);
69
70impl fmt::Debug for SecretInput {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 f.write_str("SecretInput(…)")
73 }
74}
75
76/// Why what was written, or a repost, did not go out.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub enum PublishFailure {
79 /// The note it is about — replied to, reposted — is not in the event
80 /// store any more, and the relays did not send it again.
81 NoteGone,
82 /// It could not be signed, or the relays did not take it.
83 Failed(PublishError),
84}
85
86/// Why a file was not attached to what is being written.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub enum AttachFailure {
89 /// It could not be read from where it is.
90 Read(String),
91 /// It is not something to send (see [`crate::media`]).
92 Media(MediaError),
93 /// The authorization to send it could not be signed.
94 Sign(SignError),
95 /// No media server took it: each that was tried, and why not.
96 Refused(Vec<(Url, UploadError)>),
97}
98
99/// Application messages for state updates
100#[derive(Debug, Clone)]
101pub enum Message {
102 // Popup management
103 /// Toggle the popup window visibility
104 TogglePopup,
105 /// `j`, `k` or Home was pressed where no text is being typed: on to the next note of the feed, back to the one before, or to its very top
106 StepNote(Step),
107 /// `l` or Enter was pressed where no widget had a use for it: open the row the keyboard is at
108 OpenMarked,
109 /// `y` was pressed there: copy a share link to the note the keyboard is at
110 ShareMarked,
111 /// Space was pressed there: play the video the note the keyboard is at links to first, or hold it; or follow its link, if that is first
112 PlayMarked,
113 /// `r` was pressed there: reply to the note the keyboard is at
114 ReplyMarked,
115 /// `R` was pressed there: offer the ways to pass on the note the keyboard is at
116 RepostMarked,
117 /// An arrow up or down was pressed there: to the way before, or the next, of the ways a menu offers
118 StepChoice(Step),
119 /// `z` was pressed there: zap the note the keyboard is at
120 ZapMarked,
121 /// `b` was pressed there: bookmark the note the keyboard is at, or take its bookmark off
122 BookmarkMarked,
123 /// `B` was pressed there: show the bookmarks
124 GoToBookmarks,
125 /// `s` was pressed there: show a page to search on
126 GoToSearch,
127 /// `?` was pressed there: show what the keys do
128 ShowKeys,
129 /// `.` was pressed there: show the notes that wait for the list on show
130 ShowWaiting,
131 /// `h` was pressed there: go back, as the arrow at the top of the view does
132 GoBack,
133 /// Backspace was pressed there, or is `held` down: go back; out of the composer too, which `h` is not
134 Backspace { held: bool },
135 /// Popup window was closed
136 PopupClosed(Id),
137 /// The popup lost the keyboard: something outside it was clicked
138 PopupUnfocused(Id),
139 /// The button in the panel is gone: there is nothing left to open the popup with
140 ButtonGone,
141 /// The screen the popup opens on: how tall it is, and how many of its pixels a point is, if that could be found out
142 ScreenMeasured(Option<Screen>),
143
144 // Subscription/background events
145 /// Configuration was updated
146 UpdateConfig(Config),
147 /// The event store is open and relays are connecting (or the store failed to open)
148 NostrReady(Result<NostrService, String>),
149
150 // Signing in
151 /// The user edited the sign-in field
152 LoginInputChanged(SecretInput),
153 /// Show or hide what is typed in the sign-in field
154 ToggleLoginInputVisibility,
155 /// Sign in with the key in the sign-in field
156 SubmitLogin,
157 /// Call off a sign-in that is waiting on a remote signer
158 CancelLogin,
159 /// Copy the key a remote signer knows this client by, to authorize it there
160 CopyClientKey,
161 /// Signing in finished: the account, or why nobody was signed in
162 LoginComplete(Result<Account, SignInError>),
163 /// The account named in the config was looked up in the keyring at startup
164 AccountRestored(Result<Account, String>),
165 /// Sign the account out
166 SignOut,
167 /// The account's secret key left the keyring (or the keyring refused)
168 SignedOut(Result<(), String>),
169
170 // The feed, and the lists of notes on profiles
171 /// The notes of a list already in the event store were read. With the
172 /// list's id.
173 FeedCached(u64, Result<Vec<Note>, String>),
174 /// Ask the relays for the newest notes of the feed
175 RefreshFeed,
176 /// A page of the list of notes `list` arrived from the relays: the newest, or the
177 /// one before the note written at `until`
178 FeedFetched { list: u64, page: FeedPage, until: Option<u64>, result: Result<Vec<Note>, FetchError> },
179 /// It is time to look for new notes for the feed
180 CheckForNewNotes,
181 /// Show the notes that wait for the list with this id, and go to its top
182 ShowNewNotes(u64),
183 /// The list with this id was scrolled near its end, or asked to look further back:
184 /// fetch the page before its oldest note
185 LoadOlderNotes(u64),
186 /// Which notes the lists show was chosen: with replies, or without
187 SelectFeedMode(segmented_button::Entity),
188 /// Who the account follows, as far as one source knows: `None` if it has
189 /// no contact list of theirs. With the id of the feed it was asked for.
190 ContactsLoaded { feed: u64, source: Source, result: Result<Option<Vec<PublicKey>>, FetchError> },
191 /// Profiles of note authors were read from the event store; the rest are asked of the relays
192 ProfilesCached { requested: Vec<PublicKey>, found: Vec<(PublicKey, Profile)> },
193 /// Profiles arrived, as they stand now: from the relays, or read from the event store
194 ProfilesFetched(Vec<(PublicKey, Profile)>),
195
196 // Threads
197 /// Show the thread of this note, which may be where the second says
198 /// if it is not at hand
199 OpenThread(EventId, Whereabouts),
200 /// The conversation around a thread's note, as far as one source knows it
201 ThreadLoaded { focused: EventId, source: Source, result: Result<Vec<Note>, FetchError> },
202
203 // Profiles
204 /// Show this person's profile
205 OpenProfile(PublicKey),
206 /// Copy this person's `npub` to the clipboard
207 CopyNpub(PublicKey),
208 /// The domain in the name this person gives as theirs was asked whether it is
209 Nip05Checked { person: PublicKey, name: String, verified: bool },
210 /// Follow this person, or stop following them. `first_list` when the account
211 /// agreed to a first contact list being written, having none
212 Follow { person: PublicKey, follow: bool, first_list: bool },
213 /// The contact list of `account` changed for this person, or didn't: who it follows now
214 FollowChanged { account: PublicKey, person: PublicKey, result: Result<Vec<PublicKey>, FollowError> },
215
216 // Navigation
217 /// Close the page on show, a thread or a profile: back to what it was opened from
218 ClosePage,
219 /// Show what the cog above the feed offers, or put it away
220 ToggleMenu,
221 /// Put away what the cog above the feed offers
222 CloseMenu,
223 /// Show the settings
224 OpenSettings,
225 /// Leave the settings
226 CloseSettings,
227 /// Show what the keys do, in place of the list on show
228 OpenKeys,
229 /// Back from what the keys do to the list that was on show
230 CloseKeys,
231
232 // Search
233 /// Show a page to search for people and notes on
234 OpenSearch,
235 /// What is typed on this search page changed
236 SearchTyped(u64, String),
237 /// Search for what is typed on this search page, or open what it names
238 Search(u64),
239 /// Show the people this search page found, or the notes
240 SearchShow(u64, SearchFor),
241 /// What this search page's search, the one so numbered, found of people or of notes; or that it didn't
242 SearchFound { page: u64, serial: u64, what: SearchFor, result: Result<Found, FetchError> },
243
244 /// The domain of the name typed on this search page said whose it is, or didn't
245 SearchNamed { page: u64, name: String, person: Option<PublicKey> },
246 /// What the relay this search page shows says of itself, for the search so numbered
247 RelayInfoLoaded { page: u64, serial: u64, info: Option<RelayInfo> },
248
249 // Relays
250 /// Show the account's relays
251 OpenRelays,
252 /// Leave the account's relays
253 CloseRelays,
254 /// The relay lists of `account`, as far as one source knows
255 RelayListsLoaded { account: PublicKey, source: Source, result: Result<RelayLists, FetchError> },
256 /// How the relays this is connected to are doing
257 RelayUseLoaded(HashMap<RelayUrl, RelayUse>),
258 /// What is typed where a relay is added to this set changed
259 RelayTyped(Section, String),
260 /// Add the relay typed to this set
261 AddRelay(Section),
262 /// Take this relay out of this set
263 RemoveRelay(Section, RelayUrl),
264 /// Move this relay a place up this set (`true`), or down
265 ShiftRelay(Section, RelayUrl, bool),
266 /// Write the relays as the page has them to the account's lists
267 SaveRelays,
268 /// The relay lists of `account` were changed, or weren't: each as it is now, of those there was a change to
269 RelaysSaved {
270 account: PublicKey,
271 advertised: Option<Result<Option<Event>, ListError>>,
272 listed: Vec<(Section, Result<ListedRelays, ListError>)>,
273 },
274 /// A relay on the relays page said what it is, or didn't
275 RelaySaid { relay: RelayUrl, info: Option<RelayInfo> },
276
277 // Media servers, and what is attached to a note
278 /// Show the account's media servers
279 OpenMedia,
280 /// Leave the account's media servers
281 CloseMedia,
282 /// The media server list of `account`, as far as one source knows
283 MediaServersLoaded { account: PublicKey, source: Source, result: Result<Option<Event>, FetchError> },
284 /// What is typed where a media server is added changed
285 MediaServerTyped(String),
286 /// Add the media server typed
287 AddMediaServer,
288 /// Take this media server out
289 RemoveMediaServer(Url),
290 /// Move this media server a place up (`true`), or down
291 ShiftMediaServer(Url, bool),
292 /// Write the media servers as the page has them to the account's list
293 SaveMediaServers,
294 /// The media server list of `account` was changed, or wasn't: as it is now
295 MediaServersSaved { account: PublicKey, result: Result<Option<Event>, ListError> },
296 /// Pick what is to be attached to what is being written
297 AttachMedia,
298 /// The file chooser is done: with these files, with none, or it could not be opened
299 MediaPicked(Result<Vec<PathBuf>, String>),
300 /// Ctrl+V was pressed in the composer
301 ComposePaste,
302 /// What was on the clipboard when it was
303 ComposePasted(Option<Pasted>),
304 /// The file so numbered is on a media server, or isn't
305 MediaUploaded { id: u64, result: Result<Attachment, AttachFailure> },
306 /// Call off the file so numbered, which is on its way
307 CancelUpload(u64),
308 /// Time to show how far the files on their way have got
309 UploadTick,
310
311 /// Log this much from now on
312 SetLogLevel(LogLevel),
313 /// Set the text of notes in this size from now on
314 SetNoteTextSize(u16),
315 /// Keep other people's notes in the event store for this many days from now on; `0` is for good
316 SetKeepDays(u32),
317 /// It is time to see whether the event store is to let go of what is old
318 SweepStore,
319
320 // Composing
321 /// The draft of a new note was read from where it is kept between runs
322 DraftLoaded(String),
323 /// The relay of this machine took this text as the draft of `account` for this target, or didn't
324 DraftKept { account: PublicKey, target: Target, text: String, result: Result<(), String> },
325 /// The drafts of `account` that the relay of this machine keeps, each with what it says of the files it links to
326 KeptDraftsLoaded { account: PublicKey, result: Result<Vec<(Target, String, Vec<Tag>)>, String> },
327 /// Write a new note
328 ComposeNote,
329 /// Write a reply to this note
330 ComposeReply(EventId),
331 /// Write a note that quotes this note
332 ComposeQuote(EventId),
333 /// Something was typed, selected or moved in the composer
334 ComposeEdited(text_editor::Action),
335 /// Writing or looking at how it would show was chosen, in the composer
336 SelectComposeTab(segmented_button::Entity),
337 /// The other of writing and looking at how it would show (Ctrl+P)
338 ToggleComposePreview,
339 /// What is being written, with the notes it quotes that were found
340 ComposePreviewed(Note),
341 /// Leave the composer, keeping what was written
342 CloseComposer,
343 /// Backspace was pressed in the composer's text with nothing left in it: leave the composer
344 ComposerRubbedOut,
345 /// Leave the composer, and keep nothing of what was written
346 DiscardDraft,
347 /// Not leaving the composer after all: go on writing
348 ResumeComposer,
349 /// Sign what was written and send it to the relays
350 Publish,
351 /// What was written to `target` went out as this note, or didn't
352 Published { target: Target, result: Result<Note, PublishFailure> },
353
354 // What was made of notes
355 /// How many answered, reposted, liked and zapped these notes, as far as one source knows
356 /// and for the account whose likes and reposts were told apart; and which relays they were seen on
357 EngagementLoaded { source: Source, account: Option<PublicKey>, result: Result<Standing, FetchError> },
358 /// Offer what to react to this note with, or put the offer away if it is showing
359 ToggleReactionMenu(EventId),
360 /// Put that offer away
361 CloseReactionMenu,
362 /// Show every emoji there is to react with, in place of the few offered first
363 OpenEmojiPicker,
364 /// What to find an emoji by was typed
365 EmojiSearchTyped(String),
366 /// Show this group of emoji to pick from
367 EmojiGroup(Group),
368 /// React to this note: with a like, or with an emoji
369 React(EventId, Reaction),
370 /// Show what can be done to pass this note on, repost it or quote it, or put that away
371 ToggleRepostMenu(EventId),
372 /// Put away what can be done to pass a note on
373 CloseRepostMenu,
374 /// Repost this note
375 Repost(EventId),
376 /// Show who left this on this note, under the count of them, or put that away if it shows
377 ShowWho(EventId, Left),
378 /// Who left this on this note was read from the store, or could not be
379 WhoLoaded { note: EventId, what: Left, result: Result<Vec<Doer>, FetchError> },
380 /// Put away who left something on a note
381 CloseWho,
382 /// Ctrl+Shift+S: take a picture of the popup
383 TakeScreenshot,
384 /// The renderer handed over what it drew of the popup, to be written to a file
385 ScreenshotTaken(Screenshot),
386 /// The account's like or repost of this note went out, or didn't
387 Marked { note: EventId, mark: Mark, result: Result<(), PublishFailure> },
388
389 // Bookmarks
390 /// What `account` has bookmarked, as far as one source knows
391 BookmarksLoaded { account: PublicKey, source: Source, result: Result<Bookmarks, ListError> },
392 /// Bookmark this note, or take its bookmark off if it has one
393 Bookmark(EventId),
394 /// The bookmark list of `account` changed for this note, or didn't: what it has bookmarked now
395 Bookmarked { account: PublicKey, note: EventId, result: Result<Bookmarks, ListError> },
396 /// Show the notes the account has bookmarked
397 OpenBookmarks,
398 /// The bookmarks page with this id was scrolled near the end of the notes it shows:
399 /// look up the next of them
400 LoadBookmarkedNotes(u64),
401 /// The notes bookmarked `from`th to `to`th were looked up for the bookmarks page with this id,
402 /// as it had them the `taken`th time it took them from the list: those that were found
403 BookmarkedNotesLoaded { page: u64, taken: u64, from: usize, to: usize, notes: Vec<Note> },
404
405 // Zapping
406 /// Zap this note
407 ZapNote(EventId),
408 /// The amount to zap was typed, or a preset chosen
409 ZapAmountChanged(String),
410 /// The comment to go with a zap was typed
411 ZapCommentChanged(String),
412 /// Ask the author's Lightning address for an invoice of the amount chosen
413 RequestZapInvoice,
414 /// The invoice for the zap of this note came, or why it didn't
415 ZapInvoiceReady { note: EventId, result: Result<Invoice, ZapError> },
416 /// Copy the invoice on show to the clipboard
417 CopyZapInvoice,
418 /// The wait for the receipt of this note's zap ended: with the invoice paid, or with nothing
419 ZapReceiptAwaited { note: EventId, paid: Option<String> },
420 /// Leave the zap view
421 CloseZap,
422
423 // Pictures
424 /// A view needs this picture
425 LoadImage(ImageRequest),
426 /// A picture was clicked with the right button: put the picture at this address on the clipboard
427 CopyPicture(String),
428 /// The picture arrived, or why it didn't
429 ImageLoaded(ImageRequest, Result<LoadedImage, String>),
430
431 // Link previews
432 /// A view needs what the web page at this address says of itself
433 LoadPreview(String),
434 /// What the page at this address says of itself, or why there is nothing to show
435 PreviewLoaded(String, Result<Linked, String>),
436
437 // Videos
438 /// The video at this address was pressed: play it, or hold it if it plays
439 VideoPress(String),
440 /// What there is to play of the YouTube video at this address was found: the address of a stream, or why not
441 VideoFound(String, Result<String, FindError>),
442 /// Turn the sound of the video that plays off, or back on
443 VideoMute,
444 /// The slider of the sound of the video that plays is being dragged: make it this loud, from nothing (0) to whole (1)
445 VideoVolume(f64),
446 /// That slider was let go
447 VideoVolumeSet,
448 /// The pointer came over the sound controls of the video that plays (`true`), or left them
449 VideoSound(bool),
450 /// Open the menu of speeds a video plays at, or close it if it is open
451 VideoSpeedMenu,
452 /// Put that menu away
453 CloseVideoSpeedMenu,
454 /// Play videos at this speed from now on
455 VideoSpeed(Speed),
456 /// The video that plays is being dragged to this many seconds in
457 VideoSeeking(f64),
458 /// It was let go there
459 VideoSeek,
460 /// Time to look at the video that plays: for a new picture, how far in it is, whether it ended
461 VideoTick,
462
463 // Sharing
464 /// Copy a link to this note that anyone can open
465 CopyShareLink(EventId),
466
467 // Notifications
468 /// Show what the account is told of
469 OpenNotifications,
470 /// A page of what the account is told of was read from the store, or came from the relays:
471 /// the newest, or, if `older`, the one before the oldest known
472 NotificationsLoaded { account: PublicKey, source: Source, older: bool, result: Result<Notified, FetchError> },
473 /// The list of notifications was scrolled near its end: look for older ones
474 LoadOlderNotifications,
475 /// Show this kind of notification
476 SelectNotificationsTab(segmented_button::Entity),
477 /// The account's Lightning address said which key signs its zap receipts, or could not be asked
478 ZapperKnown(PublicKey, Result<Option<PublicKey>, String>),
479
480 // Long notes
481 /// Show all this note says, in its row
482 ExpandNote(EventId),
483 /// Show this note cut again, as a row first shows a long one
484 CollapseNote(EventId),
485
486 // Links
487 /// A link in a note was clicked: open it in the browser
488 OpenUrl(String),
489
490 // Errors
491 /// Dismiss the error banner
492 ClearError,
493}