Skip to main content

cosmic_applet_avestruz/handlers/
navigation.rs

1// SPDX-License-Identifier: MIT
2
3//! Navigation message handlers for Avestruz.
4//!
5//! This module handles the popup's lifecycle, how tall it may be, and
6//! which view it shows.
7//!
8//! The popup may be as tall as the screen it opens on has room: all of
9//! it, but what the panel keeps for itself and a gap at either end. A
10//! view with a long list in it is that tall, and one with little to show
11//! is as tall as what it shows. How much room there is is asked when the
12//! window starts and again each time the popup opens (see
13//! [`crate::screen`]): the popup opens at once with the last answer, and
14//! takes the new one when it comes, if it differs.
15//!
16//! Under everything is the feed. Threads and profiles open over it as
17//! pages, one from another, and stack up; Back closes the last. Each keeps
18//! what it shows and its place, so going back is to where one was. The
19//! composer, the zap view and the settings show in place of whatever list
20//! was on show, and leave it as it was.
21
22use 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
49/// How many pages can be open one over another. Opening one more closes
50/// the first: each holds a list of notes, and the applet runs for as long
51/// as the session does.
52pub(crate) const MAX_OPEN_PAGES: usize = 16;
53
54/// The name the compositor knows the popup's surface by.
55const POPUP_NAMESPACE: &str = "avestruz";
56
57/// What the compositor knows the surface that keeps what is copied by.
58const KEEPER_NAMESPACE: &str = "avestruz-clipboard";
59
60/// The room between the popup and the edges of the screen, and the panel.
61const POPUP_GAP: i32 = 8;
62
63/// How long after the popup closed for a click outside it a press of the
64/// panel button is taken to be that click: the button is outside it.
65const SAME_PRESS: Duration = Duration::from_millis(400);
66
67/// Which part of the panel an applet sits in.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub(crate) enum Wing {
70    Start,
71    Center,
72    End,
73}
74
75/// Which part of its panel the button is in, as the panel's settings have
76/// it: the end, where no panel says (run by hand, there is none).
77fn 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
88/// Which part of a panel the applet `applet` is in, by the lists of what
89/// is at its two ends and in its middle. `None` if it is in none of them.
90fn 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
100/// Where on its screen the popup is put: against the edge the panel is on,
101/// and along that edge at the end the button is in, or in the middle if
102/// the button is. Under the button, as near as can be told: the window
103/// is told which panel and which part of it, not where in it.
104fn 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
118/// How tall the popup may be on a screen that has `room` for it, if that
119/// is known: all of it but the gap at either end, in whole points, and
120/// what fits any screen if it isn't.
121fn 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
128/// How long the surface that says what the screen is like is given to be
129/// laid out, when the window starts, before it is asked.
130const LAID_OUT_WITHIN: Duration = Duration::from_millis(500);
131
132/// Ask the surface `keeper`, which reaches from the top of its screen to
133/// the bottom, what the screen is like: how tall the compositor made it,
134/// and the scale it is drawn at (see [`crate::screen`]).
135fn 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
142/// Scroll the list of the view on show to `y` from its top.
143pub(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
147/// Scroll the list of the view on show to `y` from its top, or as far as
148/// it goes, if that is less.
149///
150/// A scroller told to go past its end shows its end and keeps the place
151/// it was told, to go there when what it holds has grown that long. That
152/// suits a list that is still filling. It does not suit one that just
153/// got shorter under its reader, which would move by itself later; this
154/// leaves the scroller where it shows.
155pub(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    /// How tall the popup may be: as tall as its screen has room.
185    pub(crate) fn popup_max_height(&self) -> f32 {
186        max_height_on(self.screen.map(|screen| screen.height))
187    }
188
189    /// How many pixels a point is on the screen the popup opens on: what
190    /// pictures are made for. Until the screen has said, more than on
191    /// most, so that what is made meanwhile is sharp on any.
192    pub(crate) fn screen_scale(&self) -> f32 {
193        self.screen.map_or(SCALE_UNKNOWN, |screen| screen.scale)
194    }
195
196    /// Ask what the screen is like that the popup opens on.
197    pub(crate) fn measure_screen(&self) -> Task<cosmic::Action<Message>> {
198        measure(self.keeper)
199    }
200
201    /// Ask what the screen is like once the surface that says so has had
202    /// the time to be laid out: when the window starts.
203    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    /// What the screen is like was found out, or wasn't: the last answer
209    /// stands until there is another.
210    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    /// Open the surface that keeps what is copied, and says what the
220    /// screen is like: a point wide, down the edge of the screen from top
221    /// to bottom, under every window, that shows nothing and takes
222    /// neither the keyboard nor the pointer.
223    ///
224    /// What is copied is the copier's to hand over when it is pasted, and
225    /// the toolkit keeps it with the first surface it opened, for as long
226    /// as that is there. The popup is gone at the next click anywhere
227    /// else, which is where something copied is on its way to: copied
228    /// from the popup alone, a link was not there to paste. So a surface
229    /// is opened before any popup, and stays.
230    ///
231    /// Being there, it is also what is asked how much room the screen
232    /// has for the popup, and at what scale it is drawn (see
233    /// [`crate::screen`]): it is as tall as the compositor makes a
234    /// surface that reaches from the top of the screen to the bottom.
235    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            // As tall as the compositor makes it, between the two edges.
243            size: Some((Some(1), None)),
244            // No part of it takes a click.
245            input_zone: Some(Vec::new()),
246            exclusive_zone: 0,
247            ..SctkLayerSurfaceSettings::default()
248        })
249    }
250
251    /// Handle popup toggle: open it by the panel, or close it.
252    ///
253    /// The popup is a surface of the window's own on the compositor, not
254    /// the panel's (see [`crate::button`]), so it is not the panel that
255    /// places it under the button: it is put against the edge the panel
256    /// is on, at the end of it the button is nearer (see [`popup_anchor`]).
257    /// It has the keyboard while it is open, as a popup of the panel's
258    /// has.
259    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        // The press that asks for it now is the click that closed it a
264        // moment ago: the popup was open, and the button was pressed to
265        // close it.
266        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            // As large as what is in it, within its limits.
280            size: None,
281            // Beside whatever keeps room for itself at an edge, as the
282            // panel does: not over it.
283            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        // It opens on what it showed when it closed, at the same place
292        // (see `list_scroller`). What is new since is looked for, and
293        // waits to be asked for; what was bookmarked elsewhere since is
294        // looked for too. The screen may not be the one it was.
295        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    /// The popup lost the keyboard, which it has while it is open:
307    /// something outside it was clicked. It closes, as a popup of the
308    /// panel's does, with everything in it kept as it is.
309    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    /// Escape was pressed: put away what was opened last. A menu open
319    /// over the list, if one is; the popup itself otherwise, as a click
320    /// outside it would, with everything in it kept as it is.
321    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            // Asked whether what was written is kept: neither, it is
331            // gone on with.
332            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    /// Handle popup closed event. What is in the composer is kept: the
341    /// popup closes whenever something else is clicked, and may not be opened
342    /// again before the session ends.
343    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    /// The popup closed, either way. What is in the composer is kept; a
351    /// menu left open is not there to be found when the popup opens again;
352    /// and a video that played is held where it was.
353    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    /// The thread on show, or under what is: the page opened last, if it
365    /// is one.
366    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    /// The profile on show, or under what is: the page opened last, if it
374    /// is one.
375    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    /// The bookmarks page on show, or under what is: the page opened
383    /// last, if it is one.
384    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    /// The search on show, if a search is the page on top.
392    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    /// Every open thread, on show or under other pages.
400    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    /// Every open profile, on show or under other pages.
408    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    /// Show `page` over whatever is on show now, from its top: the scroller
416    /// has the place of the list it was opened from.
417    pub(crate) fn open_page(&mut self, page: Page) -> Task<cosmic::Action<Message>> {
418        // Somebody named in what is being written, or a note it quotes, may
419        // have been pressed to get here, where the composer shows how it
420        // would look: what was written is kept, as the way back keeps it.
421        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        // One of those who left something on a note may have been pressed
434        // to get here: the list of them is not there to come back to.
435        self.who_menu = None;
436        Task::batch([kept, scroll_list_to(0.0)])
437    }
438
439    /// Close the page on show: back to the page it was opened from, or to
440    /// the feed, where that was left.
441    pub fn handle_close_page(&mut self) -> Task<cosmic::Action<Message>> {
442        self.pages.pop();
443        self.show_list_view()
444    }
445
446    /// Show the settings, in place of the list on show.
447    pub fn handle_open_settings(&mut self) {
448        self.menu_open = false;
449        self.view_state = ViewState::Settings;
450    }
451
452    /// Show what the keys do, in place of the list on show.
453    pub fn handle_open_keys(&mut self) {
454        self.menu_open = false;
455        self.view_state = ViewState::Keys;
456    }
457
458    /// What the list of notes on show keeps of its rows: which of its
459    /// long notes show in full, how tall each row measured, and how far
460    /// it is scrolled. The list of the page opened last, or else the
461    /// feed's.
462    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    /// Show all the note `id` says, in its row in the list on show.
479    /// Nothing is scrolled: the row grows down from where it is, and
480    /// what is under it makes room.
481    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    /// Show the note `id` cut again, in the row that showed all of it.
488    ///
489    /// A row that shrinks leaves what is in view further down the list,
490    /// and if its top was above what is in view, the note itself out of
491    /// sight: the list is scrolled back to the top of the row, so that
492    /// what its reader sees is the note they folded. With its top in
493    /// view, nothing moves but what is under it.
494    ///
495    /// Either way the list is told where it is, within what is left of
496    /// it. Its scroller would otherwise keep a place past its new end,
497    /// and go there by itself when the list next grew.
498    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    /// Show the list that is under whatever was opened over it: the page
508    /// opened last, or else the feed, each where it was left.
509    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    /// Open a link from a note in the system's browser, if it is a web
523    /// link (see [`crate::links`]).
524    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        // A panel along the top: under it, at the left, in the middle or
545        // at the right, as the button is.
546        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        // A panel down a side: beside it, at its top, middle or bottom.
551        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(&center));
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        // In none of them, or in a panel that lists nothing.
566        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        // 2160 pixels at 170% under a panel of 40 points, at 100%, and a
573        // small laptop's 1080 at 125%.
574        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}