1use cosmic::iced::advanced::widget::operation::Scrollable;
23use cosmic::iced::advanced::widget::{self, Operation};
24use std::time::{Duration, Instant};
25
26use cosmic::applet::cosmic_panel_config::{CosmicPanelConfig, PanelAnchor};
27use cosmic::cosmic_config::ConfigGet;
28use cosmic::iced::platform_specific::runtime::wayland::layer_surface::{IcedMargin, SctkLayerSurfaceSettings};
29use cosmic::iced::platform_specific::shell::commands::layer_surface::{
30 Anchor, KeyboardInteractivity, Layer, destroy_layer_surface, get_layer_surface,
31};
32use cosmic::iced::widget::scrollable::{AbsoluteOffset, scroll_to};
33use cosmic::iced::window::{self, Id};
34use cosmic::iced::{Limits, Rectangle, Vector};
35use cosmic::prelude::*;
36use nostr_sdk::prelude::EventId;
37
38use crate::fl;
39use crate::handlers::relays::ALWAYS_READ;
40use crate::images::SCALE_UNKNOWN;
41use crate::links::{self, OpenError};
42use crate::messages::Message;
43use crate::screen::{self, Screen};
44use crate::state::{AppModel, BookmarksPage, Expanded, Page, ProfileState, SearchPage, ThreadState, ViewState};
45use crate::views::components::{
46 LIST_SCROLL_ID, POPUP_MAX_HEIGHT_UNMEASURED, POPUP_MAX_WIDTH, POPUP_MIN_HEIGHT, POPUP_MIN_WIDTH, RowHeights,
47};
48
49pub(crate) const MAX_OPEN_PAGES: usize = 16;
53
54const POPUP_NAMESPACE: &str = "avestruz";
56
57const KEEPER_NAMESPACE: &str = "avestruz-clipboard";
59
60const POPUP_GAP: i32 = 8;
62
63const SAME_PRESS: Duration = Duration::from_millis(400);
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub(crate) enum Wing {
70 Start,
71 Center,
72 End,
73}
74
75fn panel_wing() -> Wing {
78 let found = || {
79 let panel = std::env::var("COSMIC_PANEL_NAME").ok()?;
80 let config = CosmicPanelConfig::cosmic_config(&panel).ok()?;
81 let wings: Option<(Vec<String>, Vec<String>)> = config.get("plugins_wings").ok()?;
82 let center: Option<Vec<String>> = config.get("plugins_center").ok()?;
83 wing_of(crate::app::APP_ID, wings.as_ref(), center.as_deref())
84 };
85 found().unwrap_or(Wing::End)
86}
87
88fn wing_of(applet: &str, wings: Option<&(Vec<String>, Vec<String>)>, center: Option<&[String]>) -> Option<Wing> {
91 let among = |applets: &[String]| applets.iter().any(|named| named == applet);
92 match wings {
93 Some((start, _)) if among(start) => Some(Wing::Start),
94 Some((_, end)) if among(end) => Some(Wing::End),
95 _ if center.is_some_and(among) => Some(Wing::Center),
96 _ => None,
97 }
98}
99
100fn popup_anchor(panel: PanelAnchor, wing: Wing) -> Anchor {
105 let (edge, start, end) = match panel {
106 PanelAnchor::Top => (Anchor::TOP, Anchor::LEFT, Anchor::RIGHT),
107 PanelAnchor::Bottom => (Anchor::BOTTOM, Anchor::LEFT, Anchor::RIGHT),
108 PanelAnchor::Left => (Anchor::LEFT, Anchor::TOP, Anchor::BOTTOM),
109 PanelAnchor::Right => (Anchor::RIGHT, Anchor::TOP, Anchor::BOTTOM),
110 };
111 match wing {
112 Wing::Start => edge | start,
113 Wing::Center => edge,
114 Wing::End => edge | end,
115 }
116}
117
118fn max_height_on(room: Option<f32>) -> f32 {
122 match room {
123 Some(height) => (height - 2.0 * POPUP_GAP as f32).floor().max(POPUP_MIN_HEIGHT),
124 None => POPUP_MAX_HEIGHT_UNMEASURED,
125 }
126}
127
128const LAID_OUT_WITHIN: Duration = Duration::from_millis(500);
131
132fn measure(keeper: Id) -> Task<cosmic::Action<Message>> {
136 window::size(keeper).then(move |size| {
137 window::scale_factor(keeper)
138 .map(move |scale| cosmic::Action::App(Message::ScreenMeasured(screen::measured(size.height, scale))))
139 })
140}
141
142pub(crate) fn scroll_list_to(y: f32) -> Task<cosmic::Action<Message>> {
144 scroll_to(LIST_SCROLL_ID.clone(), AbsoluteOffset { x: None, y: Some(y) })
145}
146
147pub(crate) fn scroll_list_within(y: f32) -> Task<cosmic::Action<Message>> {
156 struct Within {
157 y: f32,
158 }
159
160 impl<T> Operation<T> for Within {
161 fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<T>)) {
162 operate(self);
163 }
164
165 fn scrollable(
166 &mut self,
167 id: Option<&widget::Id>,
168 bounds: Rectangle,
169 content_bounds: Rectangle,
170 _translation: Vector,
171 state: &mut dyn Scrollable,
172 ) {
173 if id == Some(&*LIST_SCROLL_ID) {
174 let furthest = (content_bounds.height - bounds.height).max(0.0);
175 state.scroll_to(AbsoluteOffset { x: None, y: Some(self.y.min(furthest)) });
176 }
177 }
178 }
179
180 cosmic::iced::advanced::widget::operate(Within { y })
181}
182
183impl AppModel {
184 pub(crate) fn popup_max_height(&self) -> f32 {
186 max_height_on(self.screen.map(|screen| screen.height))
187 }
188
189 pub(crate) fn screen_scale(&self) -> f32 {
193 self.screen.map_or(SCALE_UNKNOWN, |screen| screen.scale)
194 }
195
196 pub(crate) fn measure_screen(&self) -> Task<cosmic::Action<Message>> {
198 measure(self.keeper)
199 }
200
201 pub(crate) fn measure_screen_soon(&self) -> Task<cosmic::Action<Message>> {
204 let keeper = self.keeper;
205 Task::future(tokio::time::sleep(LAID_OUT_WITHIN)).then(move |()| measure(keeper))
206 }
207
208 pub fn handle_screen_measured(&mut self, screen: Option<Screen>) {
211 if let Some(screen) = screen {
212 if self.screen != Some(screen) {
213 tracing::debug!("the screen has {:.0} points for the popup, {} pixels to the point", screen.height, screen.scale);
214 }
215 self.screen = Some(screen);
216 }
217 }
218
219 pub(crate) fn keep_what_is_copied(&self) -> Task<cosmic::Action<Message>> {
236 get_layer_surface(SctkLayerSurfaceSettings {
237 id: self.keeper,
238 layer: Layer::Background,
239 keyboard_interactivity: KeyboardInteractivity::None,
240 anchor: Anchor::TOP | Anchor::BOTTOM | Anchor::LEFT,
241 namespace: KEEPER_NAMESPACE.into(),
242 size: Some((Some(1), None)),
244 input_zone: Some(Vec::new()),
246 exclusive_zone: 0,
247 ..SctkLayerSurfaceSettings::default()
248 })
249 }
250
251 pub fn handle_toggle_popup(&mut self) -> Task<cosmic::Action<Message>> {
260 if let Some(p) = self.popup.take() {
261 return Task::batch([destroy_layer_surface(p), self.popup_left()]);
262 }
263 if self.popup_unfocused_at.take().is_some_and(|at| at.elapsed() < SAME_PRESS) {
267 return Task::none();
268 }
269 let new_id = Id::unique();
270 self.popup.replace(new_id);
271 let anchor = popup_anchor(self.core.applet.anchor, panel_wing());
272 let settings = SctkLayerSurfaceSettings {
273 id: new_id,
274 layer: Layer::Top,
275 keyboard_interactivity: KeyboardInteractivity::Exclusive,
276 anchor,
277 namespace: POPUP_NAMESPACE.into(),
278 margin: IcedMargin { top: POPUP_GAP, right: POPUP_GAP, bottom: POPUP_GAP, left: POPUP_GAP },
279 size: None,
281 exclusive_zone: 0,
284 size_limits: Limits::NONE
285 .min_width(POPUP_MIN_WIDTH)
286 .max_width(POPUP_MAX_WIDTH)
287 .min_height(POPUP_MIN_HEIGHT)
288 .max_height(self.popup_max_height()),
289 ..SctkLayerSurfaceSettings::default()
290 };
291 Task::batch([
296 get_layer_surface(settings),
297 self.check_for_new_notes_if_stale(),
298 self.load_bookmarks(),
299 self.load_relay_lists(&ALWAYS_READ),
300 self.load_media_servers(),
301 self.load_drafts(),
302 self.measure_screen(),
303 ])
304 }
305
306 pub fn handle_popup_unfocused(&mut self, id: Id) -> Task<cosmic::Action<Message>> {
310 if self.popup != Some(id) {
311 return Task::none();
312 }
313 self.popup = None;
314 self.popup_unfocused_at = Some(Instant::now());
315 Task::batch([destroy_layer_surface(id), self.popup_left()])
316 }
317
318 pub fn handle_escape(&mut self) -> Task<cosmic::Action<Message>> {
322 let who = self.who_menu.take().is_some();
323 if who || self.repost_menu.is_some() || self.reaction_menu.is_some() || self.menu_open || self.videos.speed_menu() {
324 self.repost_menu = None;
325 self.reaction_menu = None;
326 self.menu_open = false;
327 self.videos.close_speed_menu();
328 Task::none()
329 } else if self.view_state == ViewState::Compose && self.composer.as_ref().is_some_and(|composer| composer.leaving) {
330 self.handle_resume_composer()
333 } else if self.popup.is_some() {
334 self.handle_toggle_popup()
335 } else {
336 Task::none()
337 }
338 }
339
340 pub fn handle_popup_closed(&mut self, id: Id) -> Task<cosmic::Action<Message>> {
344 if self.popup.as_ref() == Some(&id) {
345 self.popup = None;
346 }
347 self.popup_left()
348 }
349
350 fn popup_left(&mut self) -> Task<cosmic::Action<Message>> {
354 self.repost_menu = None;
355 self.reaction_menu = None;
356 self.who_menu = None;
357 self.menu_open = false;
358 self.share_copied = None;
359 self.picture_copied = None;
360 self.videos.pause();
361 self.keep_draft()
362 }
363
364 pub(crate) fn thread_on_top(&self) -> Option<&ThreadState> {
367 match self.pages.last() {
368 Some(Page::Thread(state)) => Some(state.as_ref()),
369 _ => None,
370 }
371 }
372
373 pub(crate) fn profile_on_top(&self) -> Option<&ProfileState> {
376 match self.pages.last() {
377 Some(Page::Profile(state)) => Some(state.as_ref()),
378 _ => None,
379 }
380 }
381
382 pub(crate) fn bookmarks_on_top(&self) -> Option<&BookmarksPage> {
385 match self.pages.last() {
386 Some(Page::Bookmarks(page)) => Some(page.as_ref()),
387 _ => None,
388 }
389 }
390
391 pub(crate) fn search_on_top(&self) -> Option<&SearchPage> {
393 match self.pages.last() {
394 Some(Page::Search(page)) => Some(page.as_ref()),
395 _ => None,
396 }
397 }
398
399 pub(crate) fn threads_mut(&mut self) -> impl Iterator<Item = &mut ThreadState> {
401 self.pages.iter_mut().filter_map(|page| match page {
402 Page::Thread(state) => Some(state.as_mut()),
403 Page::Profile(_) | Page::Bookmarks(_) | Page::Search(_) | Page::Notifications(_) => None,
404 })
405 }
406
407 pub(crate) fn profiles_mut(&mut self) -> impl Iterator<Item = &mut ProfileState> {
409 self.pages.iter_mut().filter_map(|page| match page {
410 Page::Profile(state) => Some(state.as_mut()),
411 Page::Thread(_) | Page::Bookmarks(_) | Page::Search(_) | Page::Notifications(_) => None,
412 })
413 }
414
415 pub(crate) fn open_page(&mut self, page: Page) -> Task<cosmic::Action<Message>> {
418 let kept = if self.view_state == ViewState::Compose {
422 let kept = self.keep_draft();
423 self.composer = None;
424 kept
425 } else {
426 Task::none()
427 };
428 if self.pages.len() >= MAX_OPEN_PAGES {
429 self.pages.remove(0);
430 }
431 self.pages.push(page);
432 self.view_state = ViewState::Page;
433 self.who_menu = None;
436 Task::batch([kept, scroll_list_to(0.0)])
437 }
438
439 pub fn handle_close_page(&mut self) -> Task<cosmic::Action<Message>> {
442 self.pages.pop();
443 self.show_list_view()
444 }
445
446 pub fn handle_open_settings(&mut self) {
448 self.menu_open = false;
449 self.view_state = ViewState::Settings;
450 }
451
452 pub fn handle_open_keys(&mut self) {
454 self.menu_open = false;
455 self.view_state = ViewState::Keys;
456 }
457
458 fn rows_on_show(&mut self) -> (&mut Expanded, &RowHeights<EventId>, f32) {
463 let page = match self.view_state {
464 ViewState::Page => self.pages.last_mut(),
465 _ => None,
466 };
467 let (expanded, heights, position) = match page {
468 Some(Page::Thread(state)) => (&mut state.expanded, &state.heights, &state.position),
469 Some(Page::Profile(state)) => (&mut state.notes.expanded, &state.notes.heights, &state.notes.position),
470 Some(Page::Bookmarks(page)) => (&mut page.notes.expanded, &page.notes.heights, &page.notes.position),
471 Some(Page::Search(page)) => (&mut page.expanded, &page.heights, &page.notes_position),
472 Some(Page::Notifications(page)) => (&mut page.expanded, &page.heights, &page.position),
473 None => (&mut self.following.expanded, &self.following.heights, &self.following.position),
474 };
475 (expanded, heights, position.get())
476 }
477
478 pub fn handle_expand_note(&mut self, id: EventId) {
482 let (expanded, heights, _) = self.rows_on_show();
483 expanded.expand(id);
484 heights.measure_anew(id);
485 }
486
487 pub fn handle_collapse_note(&mut self, id: EventId) -> Task<cosmic::Action<Message>> {
499 let (expanded, heights, position) = self.rows_on_show();
500 let Some(above) = expanded.collapse(&id) else {
501 return Task::none();
502 };
503 heights.measure_anew(id);
504 scroll_list_within((position - above).max(0.0))
505 }
506
507 pub(crate) fn show_list_view(&mut self) -> Task<cosmic::Action<Message>> {
510 match self.pages.last() {
511 Some(page) => {
512 self.view_state = ViewState::Page;
513 scroll_list_to(page.position())
514 }
515 None => {
516 self.view_state = ViewState::Feed;
517 self.restore_feed_position()
518 }
519 }
520 }
521
522 pub fn handle_open_url(&mut self, url: &str) {
525 match links::open_in_browser(url) {
526 Ok(()) => {}
527 Err(OpenError::NotWeb) => tracing::warn!("refused to open a link that is not a web address"),
528 Err(OpenError::Failed(e)) => {
529 tracing::error!("the link could not be opened: {e}");
530 self.error_message = Some(fl!("error-open-link", error = e));
531 }
532 }
533 }
534}
535
536#[cfg(test)]
537mod tests {
538 use super::{Wing, max_height_on, popup_anchor, wing_of};
539 use cosmic::applet::cosmic_panel_config::PanelAnchor;
540 use cosmic::iced::platform_specific::shell::commands::layer_surface::Anchor;
541
542 #[test]
543 fn the_popup_is_put_by_the_panels_edge_at_the_end_the_button_is_in() {
544 assert_eq!(popup_anchor(PanelAnchor::Top, Wing::End), Anchor::TOP | Anchor::RIGHT);
547 assert_eq!(popup_anchor(PanelAnchor::Top, Wing::Start), Anchor::TOP | Anchor::LEFT);
548 assert_eq!(popup_anchor(PanelAnchor::Top, Wing::Center), Anchor::TOP);
549 assert_eq!(popup_anchor(PanelAnchor::Bottom, Wing::Start), Anchor::BOTTOM | Anchor::LEFT);
550 assert_eq!(popup_anchor(PanelAnchor::Left, Wing::Start), Anchor::LEFT | Anchor::TOP);
552 assert_eq!(popup_anchor(PanelAnchor::Right, Wing::End), Anchor::RIGHT | Anchor::BOTTOM);
553 assert_eq!(popup_anchor(PanelAnchor::Right, Wing::Center), Anchor::RIGHT);
554 }
555
556 #[test]
557 fn the_button_is_in_the_part_of_the_panel_that_lists_it() {
558 let named = |names: &[&str]| names.iter().map(|name| (*name).to_string()).collect::<Vec<_>>();
559 let wings = (named(&["workspaces", "us"]), named(&["clock", "them"]));
560 let center = named(&["middle"]);
561 let wing = |applet| wing_of(applet, Some(&wings), Some(¢er));
562 assert_eq!(wing("us"), Some(Wing::Start));
563 assert_eq!(wing("them"), Some(Wing::End));
564 assert_eq!(wing("middle"), Some(Wing::Center));
565 assert_eq!(wing("nobody"), None);
567 assert_eq!(wing_of("us", None, None), None);
568 }
569
570 #[test]
571 fn the_popup_may_be_as_tall_as_its_screen_has_room_less_a_gap_at_either_end() {
572 assert_eq!(max_height_on(Some(2160.0 / 1.7 - 40.0)), 1_214.0);
575 assert_eq!(max_height_on(Some(2120.0)), 2_104.0);
576 assert_eq!(max_height_on(Some(824.0)), 808.0);
577 }
578
579 #[test]
580 fn a_screen_not_measured_yet_gets_a_popup_that_fits_any() {
581 assert_eq!(max_height_on(None), 600.0);
582 }
583
584 #[test]
585 fn a_very_short_screen_still_gets_the_least_a_popup_asks_for() {
586 assert_eq!(max_height_on(Some(310.0)), 300.0);
587 assert_eq!(max_height_on(Some(120.0)), 300.0);
588 }
589}