cosmic_applet_avestruz/state.rs
1// SPDX-License-Identifier: MIT
2
3//! Application state for Avestruz.
4//!
5//! This module defines the main application model and view state types.
6//!
7//! The popup closes whenever something else is clicked, and its widget tree
8//! goes with it. Anything that should still be there when it opens again —
9//! the view, what was typed, the feed and the pages opened over it, how their
10//! rows measure and how far they are scrolled — lives here, not in a widget.
11//!
12//! ```mermaid
13//! flowchart LR
14//! model["AppModel"]
15//! model --> feed["following: FeedState. The feed"]
16//! model --> pages["pages: a stack of Page"]
17//! pages --> thread["Thread: ThreadState"]
18//! pages --> profile["Profile: ProfileState, with a FeedState of its notes"]
19//! pages --> bookmarks["Bookmarks: BookmarksPage"]
20//! pages --> search["Search: SearchPage"]
21//! model --> composer["composer, drafts: what is being written"]
22//! model --> zap["zap: ZapState"]
23//! model --> relays["relays: RelaysState"]
24//! model --> media["media: MediaState. Media servers, and files on their way to them"]
25//! model --> people["profiles, nip05: everyone, by public key"]
26//! model --> marks["engagement, bookmarks: what was made of notes"]
27//! model --> stores["images, previews: what was fetched"]
28//! ```
29//!
30//! Every list of notes keeps the same three things beside its notes: how
31//! tall each row measured ([`RowHeights`]), how far it is scrolled (a
32//! `Cell<f32>` a [`ScrollPosition`](crate::views::components::ScrollPosition)
33//! writes to), and what is on its way. That is what lets a list come back
34//! exactly as it was left.
35//!
36//! The whole of what is in the model, by what it is for, is in
37//! [`crate::guide::architecture`].
38
39use std::cell::Cell;
40use std::collections::{HashMap, HashSet};
41use std::path::PathBuf;
42use std::time::Instant;
43
44use cosmic::iced::task;
45use cosmic::iced::window::Id;
46use cosmic::widget::image;
47use cosmic::widget::{segmented_button, text_editor};
48use nostr_sdk::prelude::{Event, EventId, PublicKey, RelayUrl, Tag, Url};
49
50use crate::config::Config;
51use crate::drafts::Drafts;
52use crate::emoji::Group;
53use crate::images::{ImageRequest, ImageStore};
54use crate::nostr::account::{Account, CredentialError, Signer};
55use crate::nostr::blossom::{self, Sent};
56use crate::nostr::bookmarks::Bookmarks;
57use crate::nostr::client::{NostrService, RelayUse};
58use crate::nostr::compose::Target;
59use crate::nostr::engagement::{Doer, Engagement, Left, Mark};
60use crate::nostr::feed::{Feed, Pending};
61use crate::nostr::models::{Note, Profile};
62use crate::nostr::notifications::Notifications;
63use crate::nostr::relay_info::RelayInfo;
64use crate::nostr::relay_lists::{RelayLists, RelaySets, Section};
65use crate::nostr::search::SearchFor;
66use crate::nostr::thread::Thread;
67use crate::nostr::zap::Invoice;
68use crate::previews::PreviewStore;
69use crate::requests::Inbox;
70use crate::screen::Screen;
71use crate::video::Videos;
72use crate::views::components::RowHeights;
73
74/// Which way the list on show is stepped through from the keyboard, a row
75/// at a time.
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum Step {
78 /// To the row after the one at the top of what is in view.
79 Next,
80 /// To the one before it.
81 Previous,
82 /// To the very top of the list, and of whatever is above it.
83 Top,
84}
85
86/// Which view the popup shows.
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub enum ViewState {
89 /// Signing in: nobody is.
90 Login,
91 /// The feed: notes from the people the account follows.
92 Feed,
93 /// A page opened over the feed, a thread or a profile: the last one
94 /// opened.
95 Page,
96 /// The composer: a note or a reply being written.
97 Compose,
98 /// Zapping a note: choosing how much, or the invoice to pay.
99 Zap,
100 /// The settings: the account, and signing out.
101 Settings,
102 /// What the keys do.
103 Keys,
104 /// The account's relays: where it writes, where it reads, where it
105 /// searches.
106 Relays,
107 /// The account's media servers: where what it attaches to notes is
108 /// kept.
109 Media,
110}
111
112/// How far a sign-in has got.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum LoginProgress {
115 /// Nobody is signing in.
116 Idle,
117 /// The keyring is being asked to keep a secret key.
118 Storing,
119 /// A remote signer is being waited for. This can be called off.
120 Connecting,
121}
122
123/// A remote signer turned a sign-in down, or could not be reached.
124#[derive(Debug, Clone, PartialEq, Eq)]
125pub struct BunkerRefusal {
126 /// What it said, or what went wrong.
127 pub reason: String,
128 /// The key the signer knows this client by, or would have to: what to
129 /// authorize there. `None` if it never came to having one.
130 pub client: Option<PublicKey>,
131 /// The address had a secret in it, which may have been used up.
132 pub with_secret: bool,
133 /// That key was copied to the clipboard.
134 pub copied: bool,
135}
136
137/// How many older pages in a row may bring nothing to show before a list
138/// stops looking further back on its own.
139pub const BARREN_PAGES_MAX: u8 = 5;
140
141/// A list of someone's notes, as the model keeps it: the feed, or the notes
142/// on a profile.
143pub struct FeedState {
144 /// Which list this is, of all there have been. What is asked of the
145 /// store and the relays for it comes back with this, and finds the list
146 /// or finds it gone: a feed that started over, a profile that was closed.
147 pub id: u64,
148 /// Its notes, newest first.
149 pub feed: Feed,
150 /// How tall each of its rows has measured, by note.
151 pub heights: RowHeights<EventId>,
152 /// Which of its long notes show in full.
153 pub expanded: Expanded,
154 /// The newest notes are being fetched.
155 pub refreshing: bool,
156 /// An older page is being fetched.
157 pub loading_older: bool,
158 /// The relays had nothing older than the feed's last note.
159 pub end_reached: bool,
160 /// How many older pages in a row brought nothing to show: replies
161 /// only, to a list read without them. Looking further back stops at
162 /// [`BARREN_PAGES_MAX`] until it is asked for.
163 pub barren_pages: u8,
164 /// How far its list is scrolled, kept by the view: where to scroll back
165 /// to when it shows again after something else did, or the popup opens
166 /// again.
167 pub position: Cell<f32>,
168 /// The relays answered for its newest notes once, or failed to: it has
169 /// been filled, and is its reader's from here on.
170 pub settled: bool,
171 /// The notes that turned up since, waiting to be asked for.
172 pub pending: Pending,
173 /// The newest notes on their way were asked for by hand: they are
174 /// shown when they are here, with what waited.
175 pub show_when_fetched: bool,
176 /// The row the keyboard was last at, if it was at any: the one
177 /// marked (see [`crate::handlers::keys`]).
178 pub marked: Option<EventId>,
179}
180
181impl FeedState {
182 /// Whether the list stopped looking further back because page after
183 /// page had nothing to show, and waits to be asked.
184 pub fn paused(&self) -> bool {
185 self.barren_pages >= BARREN_PAGES_MAX && !self.end_reached && !self.loading_older
186 }
187
188 /// An empty list, the `id`th there has been.
189 pub fn new(id: u64) -> Self {
190 Self {
191 id,
192 feed: Feed::default(),
193 heights: RowHeights::default(),
194 expanded: Expanded::default(),
195 refreshing: false,
196 loading_older: false,
197 end_reached: false,
198 barren_pages: 0,
199 position: Cell::new(0.0),
200 settled: false,
201 pending: Pending::default(),
202 show_when_fetched: false,
203 marked: None,
204 }
205 }
206}
207
208/// One open thread, as the model keeps it.
209pub struct ThreadState {
210 /// The conversation, as far as it is known.
211 pub thread: Thread,
212 /// How tall each of its rows has measured, by note.
213 pub heights: RowHeights<EventId>,
214 /// Which of its long notes show in full, beside the one it was opened
215 /// for, which always does.
216 pub expanded: Expanded,
217 /// The relays are being asked about it.
218 pub loading: bool,
219 /// How far its list is scrolled, kept by the view: where to scroll back
220 /// to when a thread opened from this one is closed.
221 pub position: Cell<f32>,
222 /// The row the keyboard was last at, if it was at any: the one
223 /// marked (see [`crate::handlers::keys`]).
224 pub marked: Option<EventId>,
225}
226
227impl ThreadState {
228 /// `thread`, just opened: the relays are about to be asked.
229 pub fn new(thread: Thread) -> Self {
230 Self {
231 thread,
232 heights: RowHeights::default(),
233 expanded: Expanded::default(),
234 loading: true,
235 position: Cell::new(0.0),
236 marked: None,
237 }
238 }
239}
240
241/// One open profile, as the model keeps it. What its person says of
242/// themselves is with everyone else's, in [`AppModel::profiles`].
243pub struct ProfileState {
244 /// Whose it is.
245 pub public_key: PublicKey,
246 /// Their notes.
247 pub notes: FeedState,
248 /// Their `npub` was copied to the clipboard.
249 pub npub_copied: bool,
250 /// Why following them did not happen, the last time it was tried.
251 pub follow_problem: Option<FollowProblem>,
252 /// How far down the page their notes start, under who they are: kept
253 /// by the view. How far the page is scrolled when their first note is
254 /// at the top of what is in view.
255 pub notes_top: Cell<f32>,
256}
257
258impl ProfileState {
259 /// The profile of `public_key`, just opened, with `notes` to fill.
260 pub fn new(public_key: PublicKey, notes: FeedState) -> Self {
261 Self { public_key, notes, npub_copied: false, follow_problem: None, notes_top: Cell::new(0.0) }
262 }
263}
264
265/// The notes the account has bookmarked, as the bookmarks page keeps them.
266#[derive(Default)]
267pub struct BookmarkedNotes {
268 /// The notes bookmarked, the one bookmarked last first, as the
269 /// account's list had them when they were last taken from it.
270 pub ids: Vec<EventId>,
271 /// How many times they were taken from the list: none before the
272 /// bookmarks are known. What was asked about them comes back with
273 /// this, and finds them as they were or finds them taken anew.
274 pub taken: u64,
275 /// Those of `ids` that were found, in that order.
276 pub notes: Vec<Note>,
277 /// How many of `ids`, from the first, have been asked about.
278 pub asked: usize,
279 /// How many of those asked about are not shown: no relay has them, or
280 /// they are no notes a row shows.
281 pub missing: usize,
282 /// How many things that are not notes are bookmarked: articles,
283 /// hashtags and links, which other clients keep there.
284 pub others: usize,
285 /// The next of them are being looked up.
286 pub loading: bool,
287 /// How tall each of the rows has measured, by note.
288 pub heights: RowHeights<EventId>,
289 /// Which of the long ones show in full.
290 pub expanded: Expanded,
291 /// How far the list is scrolled, kept by the view.
292 pub position: Cell<f32>,
293 /// The row the keyboard was last at, if it was at any: the one
294 /// marked (see [`crate::handlers::keys`]).
295 pub marked: Option<EventId>,
296}
297
298impl BookmarkedNotes {
299 /// Whether every note bookmarked has been asked about.
300 pub fn all_asked(&self) -> bool {
301 self.asked >= self.ids.len()
302 }
303
304 /// How many bookmarks are not shown, as far as they were asked about.
305 pub fn hidden(&self) -> usize {
306 self.missing + self.others
307 }
308
309 /// Start over with the notes `bookmarks` has, from the top. Returns
310 /// whether that is another list of notes than was here: if it is the
311 /// same, what was found of it stays.
312 pub fn take(&mut self, bookmarks: &Bookmarks) -> bool {
313 let ids = bookmarks.notes();
314 self.others = bookmarks.others();
315 if self.taken > 0 && ids == self.ids {
316 return false;
317 }
318 *self = Self { ids, taken: self.taken + 1, others: self.others, ..Self::default() };
319 true
320 }
321}
322
323/// The account's bookmarks, as a page shows them.
324pub struct BookmarksPage {
325 /// Which page this is, as lists of notes are told apart (see
326 /// [`FeedState::id`]).
327 pub id: u64,
328 /// The notes bookmarked.
329 pub notes: BookmarkedNotes,
330}
331
332impl BookmarksPage {
333 /// The page `id`, just opened.
334 pub fn new(id: u64) -> Self {
335 Self { id, notes: BookmarkedNotes::default() }
336 }
337}
338
339/// Why following or unfollowing someone did not happen.
340#[derive(Debug, Clone, PartialEq, Eq)]
341pub enum FollowProblem {
342 /// The relays have no contact list of the account's, and a first one
343 /// is only written when the account says so.
344 NoList,
345 /// Something went wrong: what, in the user's language.
346 Failed(String),
347}
348
349/// How far a search for people, or for notes, has got.
350#[derive(Debug, Clone, Default, PartialEq, Eq)]
351pub enum SearchProgress {
352 /// Nothing was searched for.
353 #[default]
354 Idle,
355 /// The relays are being asked.
356 Searching,
357 /// They answered: what they found is on the page.
358 Found,
359 /// They didn't, and why: in the user's language.
360 Failed(String),
361}
362
363/// A search for people and notes, as its page keeps it. None of it is
364/// written anywhere: what was searched for is gone when the page is.
365pub struct SearchPage {
366 /// Which page this is, as lists of notes are told apart (see
367 /// [`FeedState::id`]).
368 pub id: u64,
369 /// What is typed where the search is written.
370 pub typed: String,
371 /// The search the page shows the answers to: which one, counted, and
372 /// its words. Answers to an earlier one are dropped.
373 pub serial: u64,
374 pub words: Option<String>,
375 /// The relay whose latest notes are on show, if it was a relay's
376 /// address that was typed, and what the relay says of itself, once it
377 /// has.
378 pub relay: Option<RelayUrl>,
379 pub relay_info: Option<RelayInfo>,
380 /// The name at a domain that is being asked of its domain.
381 pub naming: Option<String>,
382 /// Whether the people found are on show, or the notes.
383 pub what: SearchFor,
384 /// How far the search for people got, and who was found, the best
385 /// match first. Their profiles are with everyone else's.
386 pub people_progress: SearchProgress,
387 pub people: Vec<PublicKey>,
388 /// How far the search for notes got, and the notes found, the best
389 /// match first.
390 pub notes_progress: SearchProgress,
391 pub notes: Vec<Note>,
392 /// How tall the rows of the notes measured.
393 pub heights: RowHeights<EventId>,
394 /// Which of the long notes show in full.
395 pub expanded: Expanded,
396 /// How far the people are scrolled, and how far the notes.
397 pub people_position: Cell<f32>,
398 pub notes_position: Cell<f32>,
399 /// The row the keyboard was last at, if it was at any: the one
400 /// marked, of the notes found (see [`crate::handlers::keys`]).
401 pub marked: Option<EventId>,
402}
403
404impl SearchPage {
405 /// A search page with nothing searched for.
406 pub fn new(id: u64) -> Self {
407 Self {
408 id,
409 typed: String::new(),
410 serial: 0,
411 words: None,
412 relay: None,
413 relay_info: None,
414 naming: None,
415 what: SearchFor::default(),
416 people_progress: SearchProgress::default(),
417 people: Vec::new(),
418 notes_progress: SearchProgress::default(),
419 notes: Vec::new(),
420 heights: RowHeights::default(),
421 expanded: Expanded::default(),
422 people_position: Cell::new(0.0),
423 notes_position: Cell::new(0.0),
424 marked: None,
425 }
426 }
427
428 /// How far the list on show is scrolled.
429 pub fn position(&self) -> &Cell<f32> {
430 match self.what {
431 SearchFor::People => &self.people_position,
432 SearchFor::Notes => &self.notes_position,
433 }
434 }
435
436 /// How far the search for `what` got.
437 pub fn progress(&self, what: SearchFor) -> &SearchProgress {
438 match what {
439 SearchFor::People => &self.people_progress,
440 SearchFor::Notes => &self.notes_progress,
441 }
442 }
443}
444
445/// The account's relays, as the relays page shows and changes them.
446#[derive(Debug, Default)]
447pub struct RelaysState {
448 /// The account's relay lists as they were last read. `None` until
449 /// they were.
450 pub lists: Option<RelayLists>,
451 /// Whether `lists` is what the relays have, and not only what the
452 /// store had: nothing is changed until it is.
453 pub from_relays: bool,
454 /// The relays as the page has them: the lists', with what was changed
455 /// here and not saved yet.
456 pub edited: RelaySets,
457 /// What is typed where a relay is added, for each set of relays.
458 pub typed: HashMap<Section, String>,
459 /// How the relays this is connected to are doing, as of when the
460 /// page last asked.
461 pub in_use: HashMap<RelayUrl, RelayUse>,
462 /// What the relays that were asked what they support said of
463 /// themselves: `None` for one that hasn't said, or didn't.
464 pub said: HashMap<RelayUrl, Option<RelayInfo>>,
465 /// The lists whose private part is to be read when they are asked
466 /// for: more of them as more are needed (see
467 /// [`crate::handlers::relays`]).
468 pub open: HashSet<Section>,
469 /// The lists are being asked of the relays.
470 pub loading: bool,
471 /// The changed lists are on their way.
472 pub saving: bool,
473 /// The relays had no list of the account's when its relays were last
474 /// saved, and the account was told: saving again writes the first.
475 pub first_lists: bool,
476}
477
478impl RelaysState {
479 /// Whether the page has other relays than the lists do.
480 pub fn changed(&self) -> bool {
481 self.lists.as_ref().is_some_and(|lists| !lists.sets().same_as(&self.edited))
482 }
483
484 /// What is typed where a relay is added to `section`.
485 pub fn typed(&self, section: Section) -> &str {
486 self.typed.get(§ion).map_or("", String::as_str)
487 }
488}
489
490/// A file on its way to a media server, to be attached to what is being
491/// written.
492#[derive(Debug)]
493pub struct Upload {
494 /// Which one it is, of those there have been.
495 pub id: u64,
496 /// What it is attached to: where its address goes when it has one.
497 pub target: Target,
498 /// What the file is called.
499 pub name: String,
500 /// How large it is as it is sent, in bytes: nothing until it was read
501 /// and made ready.
502 pub size: Sent,
503 /// How much of it has been handed over to be sent.
504 pub sent: Sent,
505 /// The way to call it off.
506 pub handle: task::Handle,
507}
508
509impl Upload {
510 /// How far it has got, in hundredths, once there is something to
511 /// send. All of it handed over is not all of it taken: the server has
512 /// yet to say so, and the others to fetch it.
513 pub fn percent(&self) -> Option<usize> {
514 let size = self.size.load(std::sync::atomic::Ordering::Relaxed);
515 let sent = self.sent.load(std::sync::atomic::Ordering::Relaxed);
516 (size > 0).then(|| (sent.min(size) * 100 / size).min(99))
517 }
518}
519
520/// The account's media servers, as the media servers page shows and
521/// changes them, and what is on its way to them.
522#[derive(Debug, Default)]
523pub struct MediaState {
524 /// The account's server list as it was last read: `None` if it has
525 /// none, or was not read yet.
526 pub list: Option<Event>,
527 /// Whether the list was read at all, from the store or the relays.
528 pub read: bool,
529 /// Whether `list` is what the relays have, and not only what the
530 /// store had: nothing is changed until it is.
531 pub from_relays: bool,
532 /// The servers as the page has them: the list's, with what was
533 /// changed here and not saved yet. Files go to the first.
534 pub edited: Vec<Url>,
535 /// What is typed where a server is added.
536 pub typed: String,
537 /// The list is being asked of the relays.
538 pub loading: bool,
539 /// The changed list is on its way.
540 pub saving: bool,
541 /// The relays had no server list of the account's when its servers
542 /// were last saved, and the account was told: saving again writes
543 /// the first.
544 pub first_list: bool,
545 /// The desktop's file chooser is open, for what is to be attached.
546 pub picking: bool,
547 /// The files on their way, in the order they were attached.
548 pub uploads: Vec<Upload>,
549 /// How many files have been attached since the start: what the next
550 /// is told apart by.
551 pub attached: u64,
552 /// What a note says of each file that was sent, by its address
553 /// (NIP-92): said when a note that links to it goes out.
554 pub said: HashMap<String, Tag>,
555}
556
557impl MediaState {
558 /// The servers the account's list names, the one files go to first
559 /// at the head.
560 pub fn servers(&self) -> Vec<Url> {
561 blossom::servers(self.list.as_ref())
562 }
563
564 /// Whether the page has other servers than the list does.
565 pub fn changed(&self) -> bool {
566 self.read && self.servers() != self.edited
567 }
568
569 /// What a note that says `text` says of the files it links to that
570 /// were sent from here, in the order it links to them.
571 pub fn said_in(&self, text: &str) -> Vec<Tag> {
572 let mut linked: Vec<(usize, &Tag)> =
573 self.said.iter().filter_map(|(url, tag)| Some((text.find(url.as_str())?, tag))).collect();
574 linked.sort_by_key(|(at, _)| *at);
575 linked.into_iter().map(|(_, tag)| tag.clone()).collect()
576 }
577}
578
579/// How far the account's bookmarks are known.
580#[derive(Debug, Clone, Default, PartialEq, Eq)]
581pub enum BookmarkState {
582 /// Not asked yet, or not answered.
583 #[default]
584 Unknown,
585 /// As the account's newest bookmark list has them. Boxed: a list is
586 /// many times the size of having none.
587 Known(Box<Bookmarks>),
588 /// The list keeps something to itself that could not be read: why, in
589 /// the user's language. Nothing is bookmarked until it can be, since a
590 /// list written without it would lose it.
591 Unreadable(String),
592}
593
594/// How far finding out whether a name is someone's has got.
595#[derive(Debug, Clone, Copy, PartialEq, Eq)]
596pub enum Nip05State {
597 /// The domain is being asked.
598 Checking,
599 /// The domain says the name is theirs.
600 Verified,
601 /// The domain didn't say so: it says otherwise, or didn't answer.
602 Unverified,
603}
604
605/// The name at a domain someone says is theirs (NIP-05), and whether it is.
606#[derive(Debug, Clone, PartialEq, Eq)]
607pub struct Nip05Check {
608 /// The name, as their profile gave it when the domain was asked.
609 pub name: String,
610 pub state: Nip05State,
611}
612
613/// Something opened over the feed. Pages stack up, each opened from the one
614/// before, and each keeps what it shows and its place.
615pub enum Page {
616 /// A note's conversation. Boxed, as the others are: what a list of
617 /// notes keeps of its rows is more than a page should weigh in a stack.
618 Thread(Box<ThreadState>),
619 /// Someone's profile, and their notes. Boxed: a list of notes, with
620 /// the ones that wait for it, is several times the size of a thread.
621 Profile(Box<ProfileState>),
622 /// The notes the account has bookmarked. Boxed, as a profile is.
623 Bookmarks(Box<BookmarksPage>),
624 /// A search for people and notes. Boxed, as a profile is.
625 Search(Box<SearchPage>),
626 /// What the account is told of. Boxed, as a profile is.
627 Notifications(Box<NotificationsPage>),
628}
629
630impl Page {
631 /// How far the page's list is scrolled.
632 pub fn position(&self) -> f32 {
633 match self {
634 Self::Thread(state) => state.position.get(),
635 Self::Profile(state) => state.notes.position.get(),
636 Self::Bookmarks(page) => page.notes.position.get(),
637 Self::Search(page) => page.position().get(),
638 Self::Notifications(page) => page.position.get(),
639 }
640 }
641}
642
643/// A note, a reply or a quote being written.
644pub struct Composer {
645 /// What it is written to.
646 pub target: Target,
647 /// The note replied to or quoted, as the composer shows it above the
648 /// text.
649 pub about: Option<Note>,
650 /// The text, and where in it the cursor is.
651 pub content: text_editor::Content,
652 /// It is being signed and sent.
653 pub publishing: bool,
654 /// Why it did not go out, the last time it was tried.
655 pub error: Option<String>,
656 /// Whether what was written is kept as a draft is being asked:
657 /// Backspace was pressed to leave it, with something written. The
658 /// text is not written to while it is.
659 pub leaving: bool,
660 /// When the text was last changed, or Backspace last had nothing
661 /// left to rub out: a Backspace held down to rub out all of it is
662 /// not one that leaves.
663 pub rubbed: Option<Instant>,
664 /// What is written as it would show once it is out, while that is
665 /// looked at in place of the text. The text is not written to
666 /// meanwhile.
667 pub preview: Option<Preview>,
668}
669
670/// What is being written, as a row would show it if it went out as it is.
671pub struct Preview {
672 /// It, as a note: one with no id of its own yet.
673 pub note: Note,
674 /// Nothing, ever: a row is built with the notes its list shows in
675 /// full, and this is no list. What is written shows whole as it is.
676 pub expanded: Expanded,
677}
678
679impl Preview {
680 /// The preview of `note`.
681 pub fn of(note: Note) -> Self {
682 Self { note, expanded: Expanded::default() }
683 }
684}
685
686/// How far the zap of a note has got.
687pub enum ZapStage {
688 /// How much, and what to say, is being chosen.
689 Choosing,
690 /// The author's Lightning address is being asked for an invoice.
691 Requesting,
692 /// There is an invoice to pay.
693 Invoice {
694 invoice: Invoice,
695 /// The invoice as a QR code. `None` if it is too long for one, which
696 /// leaves copying it.
697 qr: Option<image::Handle>,
698 /// The invoice was copied to the clipboard.
699 copied: bool,
700 /// The wait for the receipt that says it was paid. Dropping it ends
701 /// the wait; `None` when there is nothing to wait for, or no more
702 /// time.
703 waiting: Option<task::Handle>,
704 },
705 /// The invoice was paid: the receipt said so.
706 Paid { sats: u64 },
707}
708
709/// A note being zapped.
710pub struct ZapState {
711 /// The note.
712 pub note: EventId,
713 /// Its author, who is paid.
714 pub recipient: PublicKey,
715 /// The author's Lightning address.
716 pub address: String,
717 /// How much, in sats, as typed: digits only.
718 pub amount: String,
719 /// What is said with it.
720 pub comment: String,
721 pub stage: ZapStage,
722 /// Why the last request for an invoice failed.
723 pub error: Option<String>,
724}
725
726impl ZapState {
727 /// The amount typed, in sats, if it is one that can be paid.
728 pub fn sats(&self) -> Option<u64> {
729 self.amount.parse().ok().filter(|sats| *sats > 0)
730 }
731}
732
733/// How many emoji are offered first to react with, beside the like and
734/// the way to all the others.
735pub(crate) const REACTIONS_OFFERED: usize = 8;
736
737/// A way to pass a note on: what its repost action offers.
738#[derive(Debug, Clone, Copy, PartialEq, Eq)]
739pub enum Passing {
740 /// Repost it as it is.
741 Repost,
742 /// Quote it in a note of one's own.
743 Quote,
744}
745
746impl Passing {
747 /// The ways there are to pass on a note, in the order they are
748 /// offered: one that the account has reposted (`reposted`) is not
749 /// reposted again.
750 pub fn open_to(reposted: bool) -> &'static [Passing] {
751 if reposted { &[Passing::Quote] } else { &[Passing::Repost, Passing::Quote] }
752 }
753}
754
755/// The ways to pass a note on, on offer under its repost action.
756#[derive(Debug, Clone, Copy, PartialEq, Eq)]
757pub struct RepostMenu {
758 /// The note it is for.
759 pub note: EventId,
760 /// Which of the ways the keyboard is at, once the keyboard was used
761 /// on the menu: it is shown as one the pointer is over, and Enter
762 /// takes it.
763 pub at: Option<Passing>,
764}
765
766impl RepostMenu {
767 /// The menu for `note`, as a click opens it: the keyboard at nothing.
768 pub fn of(note: EventId) -> Self {
769 Self { note, at: None }
770 }
771}
772
773/// How many of those who left something on a note are shown, at the
774/// most: more than anyone reads through, and few enough to ask after.
775pub const WHO_SHOWN: usize = 100;
776
777/// Who left something on a note, on show under the count of them: who
778/// reposted it, who reacted to it, or who zapped it.
779#[derive(Debug, Clone, PartialEq, Eq)]
780pub struct WhoMenu {
781 /// The note it is for.
782 pub note: EventId,
783 /// Which of its counts.
784 pub what: Left,
785 /// Who they are, once the store has been read.
786 pub people: Option<Vec<Doer>>,
787}
788
789/// What to react to a note with, on offer under its like: the emoji used
790/// most, or, once more were asked for, all there are.
791#[derive(Debug, Clone, PartialEq, Eq)]
792pub struct ReactionMenu {
793 /// The note it is for.
794 pub note: EventId,
795 /// Every emoji there is, to pick from, once asked for.
796 pub picker: Option<EmojiPicker>,
797}
798
799/// Every emoji there is, to pick one from: a group of them at a time, or
800/// those found by what is typed.
801#[derive(Debug, Clone, PartialEq, Eq)]
802pub struct EmojiPicker {
803 /// What is typed to find an emoji by.
804 pub typed: String,
805 /// The group on show while nothing is typed.
806 pub group: Group,
807}
808
809/// The notes whose rows show all they say, where a long note is cut until
810/// its reader asks for the rest: each with how far the top of its row is
811/// above the top of what is in view, which the row keeps as it is shown
812/// (see [`ScrollPosition`](crate::views::components::ScrollPosition)).
813/// Showing less of a note brings its row back into view by that much.
814///
815/// Each list has its own: a note shown in full in the feed is cut on its
816/// author's profile until it is asked for the rest there. A row that
817/// grew in a list that is not on show would move what that list shows
818/// when it is come back to.
819#[derive(Debug, Default)]
820pub struct Expanded {
821 notes: HashMap<EventId, Cell<f32>>,
822}
823
824impl Expanded {
825 /// Whether the note `id` shows in full.
826 pub fn has(&self, id: &EventId) -> bool {
827 self.notes.contains_key(id)
828 }
829
830 /// Where the row of the note `id` keeps how far its top is above what
831 /// is in view, if the note shows in full.
832 pub fn above(&self, id: &EventId) -> Option<&Cell<f32>> {
833 self.notes.get(id)
834 }
835
836 /// Show the note `id` in full from now on.
837 pub fn expand(&mut self, id: EventId) {
838 self.notes.entry(id).or_default();
839 }
840
841 /// Show the note `id` cut again. How far the top of its row was above
842 /// what is in view, if it showed in full: nothing, if its top was in
843 /// view.
844 pub fn collapse(&mut self, id: &EventId) -> Option<f32> {
845 self.notes.remove(id).map(|above| above.get())
846 }
847}
848
849/// What the account is told of, and how far finding it out has got.
850/// The model's, not a page's: it is kept up while no page shows it, for
851/// the count of what is new.
852#[derive(Debug, Default)]
853pub struct NotificationsState {
854 /// What others did that concerns the account.
855 pub list: Notifications,
856 /// The relays are being asked for the newest.
857 pub loading: bool,
858 /// They are being asked for the page before the oldest.
859 pub loading_older: bool,
860 /// They answered once: from then on they are asked only for what is
861 /// newer, or older, than what is known.
862 pub settled: bool,
863 /// They could not be asked, the one time they were: an empty list is
864 /// not known to be empty.
865 pub failed: bool,
866 /// When the oldest event the relays sent was written: where the page
867 /// before it ends.
868 pub oldest: Option<u64>,
869 /// The relays had nothing older.
870 pub end_reached: bool,
871 /// The account's Lightning address was asked, or is being asked,
872 /// which key signs its zap receipts.
873 pub zapper_asked: bool,
874 /// The notifications are being looked at: their page is on show, in
875 /// an open popup.
876 pub in_view: bool,
877 /// When they were last looked at before the visit under way: what was
878 /// written after is picked out for as long as the visit lasts.
879 pub seen_before: u64,
880}
881
882/// The page that shows what the account is told of: what its list keeps
883/// of its rows. What it shows is the model's (see [`NotificationsState`]).
884#[derive(Default)]
885pub struct NotificationsPage {
886 /// How tall each row measured, by the event it tells of.
887 pub heights: RowHeights<EventId>,
888 /// Which of the long notes among them show in full.
889 pub expanded: Expanded,
890 /// How far the list is scrolled, kept by the view.
891 pub position: Cell<f32>,
892 /// The row the keyboard was last at, if it was at any: the one
893 /// marked (see [`crate::handlers::keys`]).
894 pub marked: Option<EventId>,
895}
896
897/// The application model stores app-specific state used to describe its
898/// interface and drive its logic.
899pub struct AppModel {
900 /// Application state which is managed by the COSMIC runtime.
901 pub core: cosmic::Core,
902 /// Configuration data that persists between application runs.
903 pub config: Config,
904 /// The popup id.
905 pub popup: Option<Id>,
906 /// The surface that is there for as long as the window runs, and shows
907 /// nothing: what is copied is kept for as long as it is (see
908 /// `keep_what_is_copied`).
909 pub keeper: Id,
910 /// When the popup last closed because something outside it was
911 /// clicked: a press of the panel button is such a click, and is heard
912 /// of a moment later.
913 pub popup_unfocused_at: Option<Instant>,
914 /// What the button in the panel was last told: whether there is
915 /// something the account has not looked at.
916 pub unread_told: bool,
917 /// Which view the popup shows.
918 pub view_state: ViewState,
919 /// The screen the popup opens on: how tall it is, which the popup's
920 /// own height is a share of, and how many of its pixels a point is,
921 /// which pictures are kept by. `None` until that is known.
922 pub screen: Option<Screen>,
923
924 /// The relay client and event store, once the store is open.
925 pub nostr: Option<NostrService>,
926
927 /// The signed-in account. `None` when signed out, and at startup until
928 /// the account the config names has been looked up.
929 pub account: Option<Account>,
930 /// What is typed in the sign-in field. May be a secret key: it is cleared
931 /// as soon as it has been used.
932 pub login_input: String,
933 /// Whether the sign-in field hides what is typed.
934 pub login_input_hidden: bool,
935 /// Why the last sign-in attempt was refused.
936 pub login_error: Option<CredentialError>,
937 /// The last sign-in with a bunker address was turned down. Shown under
938 /// the field until what is in the field changes.
939 pub login_refusal: Option<BunkerRefusal>,
940 /// How far the sign-in under way has got.
941 pub login_progress: LoginProgress,
942 /// What signs for the account: its key from the keyring, or its remote
943 /// signer.
944 pub signer: Signer,
945
946 /// The feed: notes from the people the account follows.
947 pub following: FeedState,
948 /// Who the account follows, by its contact list. `None` until that is
949 /// known; empty when it follows nobody.
950 pub follows: Option<Vec<PublicKey>>,
951 /// How many lists of notes there have been: the next one's
952 /// [`FeedState::id`] comes after.
953 pub feeds_made: u64,
954 /// When the feed was last looked at for new notes.
955 pub feed_checked_at: Option<Instant>,
956 /// The choice between the ways a list of notes is read, as the control
957 /// that offers it keeps it: each choice carries its
958 /// [`FeedMode`](crate::nostr::feed::FeedMode), and
959 /// the one chosen is [`Config::feed_mode`].
960 pub feed_modes: segmented_button::SingleSelectModel,
961 /// What the account is told of.
962 pub notifications: NotificationsState,
963 /// Which of it shows: everything, or one kind.
964 pub notification_tabs: segmented_button::SingleSelectModel,
965
966 /// What was opened over the feed, one page from another, and not closed
967 /// yet. The last is the one on show, and Back closes it.
968 pub pages: Vec<Page>,
969
970 /// The note or reply being written, while the composer is open.
971 pub composer: Option<Composer>,
972 /// The choice between writing it and looking at how it would show, as
973 /// the control that offers it keeps it: each choice carries whether it
974 /// is the look, and the one chosen is whether [`Composer::preview`] is
975 /// there.
976 pub compose_tabs: segmented_button::SingleSelectModel,
977 /// What was written and left unpublished, by what it was written to.
978 pub drafts: Drafts,
979 /// Where the draft of a new note is kept between runs.
980 pub draft_path: PathBuf,
981 /// The drafts as the relay of this machine has them, for those it
982 /// has: what is sent there is what differs from this.
983 pub drafts_kept: HashMap<Target, String>,
984 /// Whether that relay was asked for the account's drafts.
985 pub drafts_asked: bool,
986
987 /// The note being zapped, while the zap view is open.
988 pub zap: Option<ZapState>,
989
990 /// What was made of the notes seen: replies, reposts, likes and zaps.
991 pub engagement: HashMap<EventId, Engagement>,
992 /// When each note's engagement was last asked for, so that it isn't
993 /// asked again right away.
994 pub engagement_asked: HashMap<EventId, Instant>,
995 /// The relays each note was seen on, for the notes seen on any.
996 pub seen_on: HashMap<EventId, Vec<RelayUrl>>,
997 /// The likes and reposts that are on their way to the relays, by note.
998 pub pending_marks: HashSet<(EventId, Mark)>,
999 /// The repost menu that is open, if one is: repost a note, or quote it.
1000 pub repost_menu: Option<RepostMenu>,
1001 /// What to react with is on offer, for one note.
1002 pub reaction_menu: Option<ReactionMenu>,
1003 /// Who left something on a note is on show, for one of its counts.
1004 pub who_menu: Option<WhoMenu>,
1005 /// The emoji offered first to react with: the ones used most (see
1006 /// [`crate::emoji::suggested`]), as the settings have them now.
1007 pub reaction_suggestions: Vec<String>,
1008 /// The note a share link to which was copied last, while the popup
1009 /// that was done in is open: its row says so.
1010 pub share_copied: Option<EventId>,
1011 /// The picture that was copied just now, if one was: where it is.
1012 pub picture_copied: Option<String>,
1013
1014 /// What the account has bookmarked.
1015 pub bookmarks: BookmarkState,
1016 /// When that was last asked for.
1017 pub bookmarks_asked_at: Option<Instant>,
1018 /// The note being bookmarked (`true`) or having its bookmark taken
1019 /// off, while the changed bookmark list is on its way. One at a time:
1020 /// each change is made to the list the last one left.
1021 pub bookmark_pending: Option<(EventId, bool)>,
1022 /// The relays had no bookmark list of the account's when a note was
1023 /// last bookmarked, and the account was told: bookmarking again writes
1024 /// the first.
1025 pub bookmark_first_list: bool,
1026 /// When the event store was last told to let go of what is old.
1027 pub swept_at: Option<Instant>,
1028 /// The menu behind the cog above the feed is open.
1029 pub menu_open: bool,
1030 /// The account's relays, as the relays page has them.
1031 pub relays: RelaysState,
1032 /// The account's media servers, as their page has them, and the files
1033 /// on their way to them.
1034 pub media: MediaState,
1035
1036 /// What is known about note authors.
1037 pub profiles: HashMap<PublicKey, Profile>,
1038 /// The authors whose profile has been asked for, found or not, so that
1039 /// nobody is asked about twice.
1040 pub profiles_requested: HashSet<PublicKey>,
1041 /// Whether the names people give as theirs are, for those whose
1042 /// profile was opened: nobody else's domain is asked.
1043 pub nip05: HashMap<PublicKey, Nip05Check>,
1044 /// The person being followed or unfollowed, while the changed contact
1045 /// list is on its way. One at a time: each change is made to the list
1046 /// the last one left.
1047 pub follow_pending: Option<PublicKey>,
1048
1049 /// Avatars and the images in notes, as far as they have loaded.
1050 pub images: ImageStore,
1051 /// The pictures views have asked `images` for, waiting to be turned into
1052 /// messages by a subscription.
1053 pub image_requests: Inbox<ImageRequest>,
1054 /// What the web pages notes link to say of themselves, as far as they
1055 /// were asked.
1056 pub previews: PreviewStore,
1057 /// The pages views have asked `previews` about, waiting likewise.
1058 pub preview_requests: Inbox<String>,
1059 /// The video that plays, or did last, in the row of the note that
1060 /// links to it.
1061 pub videos: Videos,
1062 /// The HTTP client everything from the web is fetched with.
1063 pub http: reqwest::Client,
1064
1065 /// Something went wrong that the user should know about.
1066 pub error_message: Option<String>,
1067}
1068
1069#[cfg(test)]
1070mod tests {
1071 use super::Expanded;
1072 use nostr_sdk::prelude::EventId;
1073
1074 #[test]
1075 fn a_note_shows_in_full_from_when_it_is_asked_to_until_it_is_asked_not_to() {
1076 let (one, other) = (EventId::from_byte_array([1; 32]), EventId::from_byte_array([2; 32]));
1077 let mut expanded = Expanded::default();
1078 assert!(!expanded.has(&one) && expanded.above(&one).is_none());
1079 assert_eq!(expanded.collapse(&one), None, "it was not in full");
1080
1081 expanded.expand(one);
1082 assert!(expanded.has(&one) && !expanded.has(&other));
1083 // Its row says how far its top is above what is in view, and
1084 // asking for it in full again forgets none of that.
1085 expanded.above(&one).unwrap().set(240.0);
1086 expanded.expand(one);
1087 assert_eq!(expanded.collapse(&one), Some(240.0));
1088 assert!(!expanded.has(&one));
1089 }
1090
1091 #[test]
1092 fn a_note_says_of_the_files_it_links_to_in_the_order_it_links_to_them_and_of_no_others() {
1093 use super::MediaState;
1094 use nostr_sdk::prelude::Tag;
1095
1096 let said = |url: &str| Tag::parse(["imeta", &format!("url {url}")]).unwrap();
1097 let (first, second, gone) =
1098 ("https://cdn.example.com/a.jpg", "https://cdn.example.com/b.png", "https://cdn.example.com/c.mp4");
1099 let mut media = MediaState::default();
1100 for url in [first, second, gone] {
1101 media.said.insert(url.to_string(), said(url));
1102 }
1103
1104 let text = format!("look {second}\nand {first}");
1105 assert_eq!(media.said_in(&text), [said(second), said(first)]);
1106 assert!(media.said_in("nothing attached").is_empty(), "an address taken out of the text takes its file out of the note");
1107 }
1108}