mitsuami-headless 2.2.0

In-memory mitsuami backend with deterministic measurement, for tests
Documentation
//! Scripted platform services for tests: records every request and lets
//! the test answer it.

use std::cell::RefCell;
use std::collections::{BTreeMap, VecDeque};
use std::path::PathBuf;
use std::rc::Rc;

use mitsuami_core::NodeId;
use mitsuami_core::services::{
    Alert, Launch, MenuBarData, MenuItemData, Notification, OpenFile, Reply, SaveFile, ServiceError, Services,
    find_menu_item,
};

/// A request waiting for the test to answer it.
pub struct Pending<Request, Answer> {
    pub request: Request,
    pub parent: Option<NodeId>,
    reply: Reply<Answer>,
}

impl<Request, Answer> Pending<Request, Answer> {
    /// Answers as the user would. Call `settle` afterwards to let waiting
    /// tasks continue.
    pub fn respond(self, answer: Answer) {
        (self.reply)(answer);
    }
}

pub type PendingAlert = Pending<Alert, usize>;
pub type PendingOpen = Pending<OpenFile, Option<Vec<PathBuf>>>;
pub type PendingSave = Pending<SaveFile, Option<PathBuf>>;
/// Items to move to the trash; the test moves them (or not) and answers.
pub type PendingTrash = Pending<Vec<PathBuf>, Result<(), ServiceError>>;
/// A file, folder or URL to open in another app.
pub type PendingLaunch = Pending<Launch, Result<(), ServiceError>>;

/// Takes out the requests asked for on `window`, keeping the others' order.
fn take_on<Request, Answer>(
    requests: &mut VecDeque<Pending<Request, Answer>>,
    window: NodeId,
) -> VecDeque<Pending<Request, Answer>> {
    let (taken, kept) = std::mem::take(requests).into_iter().partition(|p| p.parent == Some(window));
    *requests = kept;
    taken
}

#[derive(Default)]
struct State {
    clipboard: Option<String>,
    alerts: VecDeque<PendingAlert>,
    opens: VecDeque<PendingOpen>,
    saves: VecDeque<PendingSave>,
    trashes: VecDeque<PendingTrash>,
    launches: VecDeque<PendingLaunch>,
    /// The notifications showing, oldest first.
    notifications: Vec<Notification>,
    /// What `notify` answers: the platform taking it, until a test says
    /// the user turned notifications off.
    notification_answer: Option<ServiceError>,
    notification_activated: Option<Rc<dyn Fn(String)>>,
    menu: Option<MenuBarData>,
    window_menus: BTreeMap<NodeId, MenuBarData>,
    activate: Option<Rc<dyn Fn(u32)>>,
}

/// Install with [`Ui::set_services`](mitsuami_core::Ui::set_services).
#[derive(Default)]
pub struct FakeServices {
    state: Rc<RefCell<State>>,
}

/// The test's side of [`FakeServices`].
#[derive(Clone)]
pub struct FakeServicesHandle {
    state: Rc<RefCell<State>>,
}

impl FakeServices {
    pub fn new() -> (FakeServices, FakeServicesHandle) {
        let services = FakeServices::default();
        let handle = FakeServicesHandle { state: services.state.clone() };
        (services, handle)
    }
}

impl FakeServicesHandle {
    pub fn clipboard(&self) -> Option<String> {
        self.state.borrow().clipboard.clone()
    }

    /// Puts text on the fake clipboard, as if copied from another app.
    pub fn set_clipboard(&self, text: &str) {
        self.state.borrow_mut().clipboard = Some(text.to_owned());
    }

    /// The oldest alert still waiting for an answer.
    pub fn take_alert(&self) -> Option<PendingAlert> {
        self.state.borrow_mut().alerts.pop_front()
    }

    pub fn take_open_file(&self) -> Option<PendingOpen> {
        self.state.borrow_mut().opens.pop_front()
    }

    pub fn take_save_file(&self) -> Option<PendingSave> {
        self.state.borrow_mut().saves.pop_front()
    }

    /// The oldest request to trash items. Nothing has been moved: the
    /// test does what it wants the platform to have done, then answers.
    pub fn take_trash(&self) -> Option<PendingTrash> {
        self.state.borrow_mut().trashes.pop_front()
    }

    /// The oldest request to open something in another app.
    pub fn take_launch(&self) -> Option<PendingLaunch> {
        self.state.borrow_mut().launches.pop_front()
    }

    /// The notifications showing, oldest first: those withdrawn or
    /// clicked are gone, and one replaced by another with its id is where
    /// it was, with the new text.
    pub fn notifications(&self) -> Vec<Notification> {
        self.state.borrow().notifications.clone()
    }

    /// Makes `notify` fail with `error` from now on (`Cancelled`: the user
    /// turned the app's notifications off; `Unavailable`: nothing to show
    /// them), or show them again with `None`.
    pub fn set_notification_error(&self, error: Option<ServiceError>) {
        self.state.borrow_mut().notification_answer = error;
    }

    /// Clicks the notification with this id, as the user would: it goes
    /// from the list and the app hears of it. Returns `false` if there's
    /// none.
    pub fn click_notification(&self, id: &str) -> bool {
        let activated = {
            let mut state = self.state.borrow_mut();
            let Some(at) = state.notifications.iter().position(|n| n.id.as_deref() == Some(id)) else { return false };
            state.notifications.remove(at);
            state.notification_activated.clone()
        };
        if let Some(activated) = activated {
            activated(id.to_owned());
        }
        true
    }

    /// Requests of any kind still waiting for an answer.
    pub fn pending_requests(&self) -> usize {
        let state = self.state.borrow();
        state.alerts.len() + state.opens.len() + state.saves.len() + state.trashes.len() + state.launches.len()
    }

    /// The menus the app installed.
    pub fn menu(&self) -> Option<MenuBarData> {
        self.state.borrow().menu.clone()
    }

    /// A window's own menus (a `MenuBar` in its content), without the app's.
    pub fn window_menu(&self, window: NodeId) -> Option<MenuBarData> {
        self.state.borrow().window_menus.get(&window).cloned()
    }

    /// The item at `path`, e.g. `["File", "Open Recent", "notes.txt"]`:
    /// a menu, its submenus, then the item's title. Looks in the app's
    /// menus, then in each window's.
    pub fn menu_item(&self, path: &[&str]) -> Option<MenuItemData> {
        let state = self.state.borrow();
        let (menu, rest) = path.split_first()?;
        state.menu.iter().chain(state.window_menus.values()).flat_map(|bar| &bar.menus).find_map(|data| {
            if data.title != *menu {
                return None;
            }
            find_menu_item(&data.entries, rest).cloned()
        })
    }

    /// Chooses the item at `path` (see [`menu_item`](Self::menu_item)),
    /// like a click or its shortcut would. Returns `false` if there is no
    /// such item or it is disabled.
    pub fn choose_menu_item(&self, path: &[&str]) -> bool {
        let Some(item) = self.menu_item(path).filter(|item| item.enabled) else { return false };
        let Some(activate) = self.state.borrow().activate.clone() else { return false };
        activate(item.id);
        true
    }
}

impl Services for FakeServices {
    fn clipboard_text(&mut self, reply: Reply<Option<String>>) {
        let text = self.state.borrow().clipboard.clone();
        reply(text);
    }

    fn set_clipboard_text(&mut self, text: &str, reply: Reply<Result<(), ServiceError>>) {
        self.state.borrow_mut().clipboard = Some(text.to_owned());
        reply(Ok(()));
    }

    fn alert(&mut self, parent: Option<NodeId>, alert: &Alert, reply: Reply<usize>) {
        self.state.borrow_mut().alerts.push_back(Pending { request: alert.clone(), parent, reply });
    }

    fn open_file(&mut self, parent: Option<NodeId>, request: &OpenFile, reply: Reply<Option<Vec<PathBuf>>>) {
        self.state.borrow_mut().opens.push_back(Pending { request: request.clone(), parent, reply });
    }

    fn save_file(&mut self, parent: Option<NodeId>, request: &SaveFile, reply: Reply<Option<PathBuf>>) {
        self.state.borrow_mut().saves.push_back(Pending { request: request.clone(), parent, reply });
    }

    fn trash(&mut self, parent: Option<NodeId>, paths: &[PathBuf], reply: Reply<Result<(), ServiceError>>) {
        self.state.borrow_mut().trashes.push_back(Pending { request: paths.to_vec(), parent, reply });
    }

    fn launch(&mut self, parent: Option<NodeId>, target: &Launch, reply: Reply<Result<(), ServiceError>>) {
        self.state.borrow_mut().launches.push_back(Pending { request: target.clone(), parent, reply });
    }

    fn notify(
        &mut self,
        notification: &Notification,
        activated: Rc<dyn Fn(String)>,
        reply: Reply<Result<(), ServiceError>>,
    ) {
        let answer = {
            let mut state = self.state.borrow_mut();
            match state.notification_answer.clone() {
                Some(error) => Err(error),
                None => {
                    match state.notifications.iter_mut().find(|n| n.id == notification.id) {
                        Some(shown) => *shown = notification.clone(),
                        None => state.notifications.push(notification.clone()),
                    }
                    state.notification_activated = Some(activated);
                    Ok(())
                }
            }
        };
        reply(answer);
    }

    fn withdraw_notification(&mut self, id: &str) {
        self.state.borrow_mut().notifications.retain(|n| n.id.as_deref() != Some(id));
    }

    /// Alerts and file dialogs asked for on the window answer as their
    /// cancel would. Those without a parent stay: the fake doesn't know
    /// which window is focused.
    fn window_destroyed(&mut self, window: NodeId) {
        let (alerts, opens, saves) = {
            let mut state = self.state.borrow_mut();
            (take_on(&mut state.alerts, window), take_on(&mut state.opens, window), take_on(&mut state.saves, window))
        };
        for alert in alerts {
            let cancel = alert.request.effective_buttons().len() - 1;
            alert.respond(cancel);
        }
        opens.into_iter().for_each(|open| open.respond(None));
        saves.into_iter().for_each(|save| save.respond(None));
    }

    fn set_menu(&mut self, window: Option<NodeId>, menu: &MenuBarData, activate: Rc<dyn Fn(u32)>) {
        let mut state = self.state.borrow_mut();
        match window {
            None => state.menu = Some(menu.clone()),
            Some(window) if menu.menus.is_empty() => _ = state.window_menus.remove(&window),
            Some(window) => _ = state.window_menus.insert(window, menu.clone()),
        }
        // Ids are unique across bars, and every bar reports to the same Ui.
        state.activate = Some(activate);
    }
}