GitCorner

Code

ossartcraftfigcraft🌐
b45255bb6fe2
//! The frameless window's title bar, driven through egui headless: its buttons minimise, maximise
//! and close the window, its empty space drags (double-click maximises), and the window's edges
//! resize it. A system-drawn title bar leaves all of that to the system.

use egui::{Event, PointerButton, Pos2, RawInput, Rect, ResizeDirection, ViewportCommand, ViewportId, pos2, vec2};
use figcraft_engine::Session;
use serde_json::json;

use crate::{FigApp, NoServices, TitleBar};

const SIZE: egui::Vec2 = vec2(1440.0, 900.0);

struct Ui {
    ctx: egui::Context,
    app: FigApp,
    time: f64,
    /// What the system reports about the window.
    maximized: bool,
    /// Modifier keys held during the next frames.
    modifiers: egui::Modifiers,
}

impl Ui {
    fn new(title_bar: TitleBar) -> Self {
        let mut app = FigApp::new(Session::new(), Box::new(NoServices));
        app.ui.title_bar = title_bar;
        let mut u = Self { ctx: egui::Context::default(), app, time: 0.0, maximized: false, modifiers: egui::Modifiers::NONE };
        for _ in 0..3 {
            u.frame(vec![]);
        }
        u
    }

    /// Run one frame; returns the window commands it sent.
    fn frame(&mut self, mut events: Vec<Event>) -> Vec<ViewportCommand> {
        self.time += 1.0 / 60.0;
        events.insert(0, Event::ModifiersChanged(self.modifiers));
        let mut input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, SIZE)), time: Some(self.time), events, ..Default::default() };
        input.viewports.entry(ViewportId::ROOT).or_default().maximized = Some(self.maximized);
        let app = &mut self.app;
        let mut out = self.ctx.run_ui(input, |ui| app.ui(ui));
        out.textures_delta.clear();
        out.viewport_output.get(&ViewportId::ROOT).map(|v| v.commands.clone()).unwrap_or_default()
    }

    fn button(&mut self, p: Pos2, pressed: bool) -> Vec<ViewportCommand> {
        self.frame(vec![
            Event::PointerMoved(p),
            Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() },
        ])
    }

    fn click(&mut self, p: Pos2) -> Vec<ViewportCommand> {
        let mut cmds = self.button(p, true);
        cmds.extend(self.button(p, false));
        cmds
    }

    /// Press on `p` and move away from it; the commands sent while dragging.
    fn drag(&mut self, p: Pos2, by: egui::Vec2) -> Vec<ViewportCommand> {
        let mut cmds = self.button(p, true);
        for k in 1..=5 {
            cmds.extend(self.frame(vec![Event::PointerMoved(p + by * (k as f32 / 5.0))]));
        }
        cmds.extend(self.button(p + by, false));
        cmds
    }
}

/// The middle of window button `k` (0 minimise, 1 maximise, 2 close) at the bar's right end.
fn window_button(k: usize) -> Pos2 {
    pos2(SIZE.x - 46.0 * (3 - k) as f32 + 23.0, crate::tabs::HEIGHT / 2.0)
}

/// Empty title bar space, right of the tabs.
const EMPTY: Pos2 = pos2(800.0, 20.0);

#[test]
fn window_buttons_minimise_maximise_and_close() {
    let mut u = Ui::new(TitleBar::Custom);
    assert!(u.click(window_button(0)).contains(&ViewportCommand::Minimized(true)));
    assert!(u.click(window_button(1)).contains(&ViewportCommand::Maximized(true)));
    u.click(window_button(2));
    assert!(u.frame(vec![]).contains(&ViewportCommand::Close));
}

/// Asserts closing the custom titlebar over a presenter with unsaved changes asks with the
/// unsaved-changes dialog instead of emitting `Close`.
#[test]
fn titlebar_close_asks_over_the_presenter_when_a_file_is_unsaved() {
    let mut u = Ui::new(TitleBar::Custom);
    let frame = u.app.session.execute("node.create", &json!({"type": "frame", "width": 402, "height": 874})).unwrap()["id"].clone();
    u.app.session.execute("proto.present", &json!({"start": frame})).unwrap();
    u.app.handle_ui_requests();
    u.frame(vec![]);
    assert!(u.app.ui.present.is_some());

    let commands = u.click(window_button(2));
    assert!(!commands.contains(&ViewportCommand::Close));
    assert!(u.app.ui.confirm_close);
    assert!(u.ctx.memory(|memory| memory.area_rect(egui::Id::unique(Some(crate::i18n::tr("Unsaved changes")))).is_some()));
}

#[test]
fn maximise_button_restores_a_maximised_window() {
    let mut u = Ui::new(TitleBar::Custom);
    u.maximized = true;
    let cmds = u.click(window_button(1));
    assert!(cmds.contains(&ViewportCommand::Maximized(false)), "{cmds:?}");
}

#[test]
fn empty_bar_drags_the_window_and_double_click_maximises() {
    let mut u = Ui::new(TitleBar::Custom);
    assert!(u.drag(EMPTY, vec2(40.0, 10.0)).contains(&ViewportCommand::StartDrag));
    let mut cmds = u.click(EMPTY);
    cmds.extend(u.click(EMPTY));
    assert!(cmds.contains(&ViewportCommand::Maximized(true)), "{cmds:?}");
    // A single click on the bar does nothing to the window.
    u.time += 1.0;
    assert!(u.click(EMPTY).is_empty());
}

#[test]
fn edges_and_corners_resize_the_window() {
    let mut u = Ui::new(TitleBar::Custom);
    // Not while maximised.
    u.maximized = true;
    assert!(u.drag(pos2(SIZE.x - 2.0, SIZE.y - 2.0), vec2(-30.0, -30.0)).iter().all(|c| !matches!(c, ViewportCommand::BeginResize(_))));
    u.maximized = false;
    u.frame(vec![]);
    for (p, dir) in [
        (pos2(SIZE.x - 2.0, SIZE.y - 2.0), ResizeDirection::SouthEast),
        (pos2(SIZE.x - 2.0, 2.0), ResizeDirection::NorthEast),
        (pos2(2.0, SIZE.y - 2.0), ResizeDirection::SouthWest),
        (pos2(2.0, 450.0), ResizeDirection::West),
        (pos2(720.0, SIZE.y - 2.0), ResizeDirection::South),
        (pos2(720.0, 2.0), ResizeDirection::North),
    ] {
        // Pulled in towards the middle.
        let inward = ((SIZE / 2.0).to_pos2() - p).normalized() * 30.0;
        assert!(u.drag(p, inward).contains(&ViewportCommand::BeginResize(dir)), "{dir:?}");
    }
}

#[test]
fn tabs_and_new_tab_keep_their_clicks() {
    let mut u = Ui::new(TitleBar::Custom);
    u.app.ui.home = true;
    // The open file's tab switches to it.
    assert!(u.click(pos2(100.0, 20.0)).is_empty());
    assert!(!u.app.ui.home);
    // The `+` right of it opens a new file (found by clicking along the bar past the tab).
    let mut opened = false;
    for x in (180..320).step_by(4) {
        u.time += 1.0;
        assert!(u.click(pos2(x as f32, 20.0)).is_empty(), "{x}");
        if u.app.session.docs.len() > 1 {
            opened = true;
            break;
        }
    }
    assert!(opened, "the new-tab button took no click");
}

#[test]
fn many_tabs_do_not_cover_the_window_buttons() {
    let mut u = Ui::new(TitleBar::Custom);
    for _ in 0..24 {
        u.app.session.execute("file.new", &json!({})).unwrap();
    }
    u.frame(vec![]);
    let before = u.app.session.docs.len();
    u.click(pos2(SIZE.x - 222.0, 20.0));
    assert_eq!(u.app.session.docs.len(), before + 1, "the new-tab button must stay reachable");
    assert!(u.click(window_button(0)).contains(&ViewportCommand::Minimized(true)));
    assert!(u.click(window_button(1)).contains(&ViewportCommand::Maximized(true)));
    u.click(window_button(2));
    assert!(u.frame(vec![]).contains(&ViewportCommand::Close));
}

#[test]
fn close_button_on_inactive_tab_closes_it_without_switching() {
    let mut u = Ui::new(TitleBar::Custom);
    u.app.session.execute("file.new", &json!({})).unwrap();
    u.app.session.execute("file.new", &json!({})).unwrap();
    let active_uid = u.app.session.docs[u.app.session.active].uid;
    let inactive_uid = u.app.session.docs[1].uid;
    let close_button = pos2(270.0, 20.0);
    u.frame(vec![Event::PointerMoved(close_button)]);
    u.click(close_button);
    assert!(
        !u.app.session.docs.iter().any(|doc| doc.uid == inactive_uid),
        "docs={}, active={}, last_error={:?}, target_dirty={}",
        u.app.session.docs.len(),
        u.app.session.active,
        u.app.ui.last_error,
        u.app.session.docs.iter().find(|doc| doc.uid == inactive_uid).is_some_and(|doc| doc.is_dirty())
    );
    assert_eq!(u.app.session.docs[u.app.session.active].uid, active_uid);
}

#[test]
fn closing_a_tab_before_the_active_one_keeps_the_active_file() {
    let mut u = Ui::new(TitleBar::Custom);
    for _ in 0..3 {
        u.app.session.execute("file.new", &json!({})).unwrap();
    }
    u.app.session.execute("doc.switch", &json!({"index": 2})).unwrap();
    let active_uid = u.app.session.docs[u.app.session.active].uid;
    let closed_uid = u.app.session.docs[0].uid;
    let close_button = pos2(156.0, 20.0);
    u.frame(vec![Event::PointerMoved(close_button)]);
    u.click(close_button);
    assert!(!u.app.session.docs.iter().any(|doc| doc.uid == closed_uid));
    assert_eq!(u.app.session.docs[u.app.session.active].uid, active_uid);
}

#[test]
fn dragging_a_tab_along_the_bar_reorders_it_without_detaching() {
    let mut u = Ui::new(TitleBar::Custom);
    for name in ["Two", "Three", "Four"] {
        u.app.session.execute("file.new", &json!({"name": name})).unwrap();
    }
    let moved_uid = u.app.session.docs[0].uid;
    let active_uid = u.app.session.docs[u.app.session.active].uid;
    u.frame(vec![]);
    let commands = u.drag(pos2(100.0, 20.0), vec2(310.0, 0.0));
    assert!(!commands.contains(&ViewportCommand::StartDrag), "{commands:?}");
    assert_eq!(
        u.app.session.docs[2].uid,
        moved_uid,
        "order={:?}, active={}, error={:?}",
        u.app.session.docs.iter().map(|d| d.uid).collect::<Vec<_>>(),
        u.app.session.active,
        u.app.ui.last_error
    );
    assert_eq!(u.app.session.docs[u.app.session.active].uid, active_uid);
}

#[test]
fn a_system_title_bar_leaves_the_window_alone() {
    let mut u = Ui::new(TitleBar::Native);
    assert!(!u.click(window_button(2)).contains(&ViewportCommand::Close));
    assert!(u.drag(EMPTY, vec2(40.0, 10.0)).is_empty());
    assert!(u.drag(pos2(SIZE.x - 2.0, SIZE.y - 2.0), vec2(-30.0, -30.0)).iter().all(|c| !matches!(c, ViewportCommand::BeginResize(_))));
}

/// The main window's first tab closing: (its file's uid, the close button of the first tab).
fn first_tab(u: &Ui) -> (u64, Pos2) {
    (u.app.session.docs[0].uid, pos2(156.0, 20.0))
}

/// Whether file `uid` is still open in a tab.
fn open(u: &Ui, uid: u64) -> bool {
    u.app.session.docs.iter().any(|d| d.uid == uid)
}

/// Whether the unsaved-changes question is on screen.
fn asking(u: &Ui) -> bool {
    u.ctx.memory(|memory| memory.area_rect(egui::Id::unique(Some(crate::i18n::tr("Unsaved changes")))).is_some())
}

/// #2032: closing a tab whose file has unsaved changes asks Don't Save / Cancel / Save, as
/// closing the window does, instead of a toast that left the tab open. Escape (or Cancel) keeps the
/// tab, Don't Save closes it, Alt+click closes it without asking, and File ▸ Close tab asks too.
#[test]
fn closing_a_tab_with_unsaved_changes_asks() {
    use crate::windows::{CloseAnswer, TabClose, answer_close_tab};
    let mut u = Ui::new(TitleBar::Custom);
    u.app.session.execute("file.new", &json!({})).unwrap();
    u.app.session.execute("doc.switch", &json!({"index": 0})).unwrap();
    u.app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
    let (uid, close) = first_tab(&u);
    u.frame(vec![Event::PointerMoved(close)]);
    u.click(close);
    u.frame(vec![]);
    assert!(open(&u, uid), "the tab waits for an answer");
    assert_eq!(u.app.ui.close_tab, Some(TabClose::Ask(uid)));
    assert!(asking(&u), "the question is on screen");
    // Escape is Cancel: the tab stays, with its changes.
    u.frame(vec![Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }]);
    u.frame(vec![]);
    assert!(open(&u, uid), "Escape keeps the tab");
    assert!(u.app.ui.close_tab.is_none(), "and ends the question");
    // Don't Save closes it.
    u.click(close);
    assert_eq!(u.app.ui.close_tab, Some(TabClose::Ask(uid)));
    let ctx = u.ctx.clone();
    answer_close_tab(&mut u.app, &ctx, CloseAnswer::DontSave);
    assert!(!open(&u, uid), "Don't Save closes the tab");
    // Alt+click drops the changes without asking.
    u.app.session.execute("doc.switch", &json!({"index": 0})).unwrap();
    u.app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
    u.app.session.execute("file.new", &json!({})).unwrap();
    let (uid, close) = first_tab(&u);
    u.frame(vec![Event::PointerMoved(close)]);
    u.modifiers = egui::Modifiers::ALT;
    u.click(close);
    u.modifiers = egui::Modifiers::NONE;
    assert!(!open(&u, uid), "Alt+click closes without asking");
    assert!(u.app.ui.close_tab.is_none());
    // File ▸ Close tab (and its shortcut) asks about the file shown.
    u.app.session.execute("doc.switch", &json!({"index": 0})).unwrap();
    u.app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
    let uid = u.app.session.docs[0].uid;
    crate::menus::invoke(&mut u.app, "file.close");
    assert_eq!(u.app.ui.close_tab, Some(TabClose::Ask(uid)));
    assert!(open(&u, uid));
}

/// #2032: Save in the question saves the file, then closes its tab; a file without a path asks
/// where with Save as first and the tab stays open until it is saved.
#[test]
fn save_in_the_tab_question_saves_then_closes() {
    let dir = std::env::temp_dir().join(format!("figcraft-tab-close-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("kept.figcraft");
    let mut u = Ui::new(TitleBar::Custom);
    u.app.session.execute("file.new", &json!({})).unwrap();
    u.app.session.execute("doc.switch", &json!({"index": 0})).unwrap();
    u.app.session.execute("file.save", &json!({"path": path.to_string_lossy()})).unwrap();
    let saved = std::fs::metadata(&path).unwrap().len();
    u.app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap();
    let (uid, close) = first_tab(&u);
    u.frame(vec![Event::PointerMoved(close)]);
    u.click(close);
    u.frame(vec![]);
    assert!(asking(&u));
    // Enter answers Save.
    u.frame(vec![Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }]);
    for _ in 0..3 {
        u.frame(vec![]);
    }
    assert!(!open(&u, uid), "saved, then closed");
    assert!(std::fs::metadata(&path).unwrap().len() > saved, "the rectangle was saved");
    // No path: Save as starts (headless: no dialog can open), and the tab stays open.
    u.app.session.execute("doc.switch", &json!({"index": 0})).unwrap();
    u.app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap();
    let (uid, close) = first_tab(&u);
    u.frame(vec![Event::PointerMoved(close)]);
    u.click(close);
    let ctx = u.ctx.clone();
    crate::windows::answer_close_tab(&mut u.app, &ctx, crate::windows::CloseAnswer::Save);
    for _ in 0..3 {
        u.frame(vec![]);
    }
    assert!(open(&u, uid), "nothing saved it: the tab stays");
    assert!(u.app.ui.close_tab.is_none());
    let _ = std::fs::remove_dir_all(&dir);
}