gled-ui 2.32.1

gled's egui interface, shared by the desktop app and the browser
Documentation
use crate::ui::logo::icon;
use crate::ui::logo::logo_image;
use egui::{Button, ViewportBuilder};
use egui::{Image, Rect, Vec2, ViewportCommand};
use egui_phosphor_icons::icons;
use std::{cell::RefCell, collections::HashSet};

thread_local! {
    /// Titles of the windows inside the page whose close button was clicked.
    static EMBEDDED_CLOSE_CLICKED: RefCell<HashSet<String>> = RefCell::new(HashSet::new());
}

/// Whether the close button of the window titled `title` was clicked, for
/// windows drawn inside the page (in the browser). Native windows report a
/// close request instead.
pub fn embedded_close_clicked(title: &str) -> bool {
    EMBEDDED_CLOSE_CLICKED.with(|clicked| clicked.borrow_mut().remove(title))
}

/// Draws a tool window's frame and contents into the viewport's `ui`. In a
/// browser, where tool windows are windows inside the page, egui's window
/// already has a title bar, so only the contents are drawn.
pub fn gled_window_frame(
    viewport_ui: &mut egui::Ui,
    title: &str,
    add_contents: impl FnOnce(&mut egui::Ui),
) {
    use egui::{CentralPanel, Id, LayerId, Ui, UiBuilder};

    let ctx = viewport_ui.ctx().clone();
    if ctx.embed_viewports() {
        // egui's window inside the page has a title but no close button.
        viewport_ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
            if ui.small_button(icons::X).on_hover_text("Close").clicked() {
                EMBEDDED_CLOSE_CLICKED
                    .with(|clicked| clicked.borrow_mut().insert(title.to_owned()));
            }
        });
        add_contents(viewport_ui);
        return;
    }

    let panel_frame = egui::Frame::new()
        .fill(ctx.global_style().visuals.window_fill())
        .stroke(ctx.global_style().visuals.widgets.noninteractive.fg_stroke);

    let mut root_ui = Ui::new(
        ctx.clone(),
        Id::new((ctx.viewport_id(), "gled_window_frame_panel")),
        UiBuilder::new()
            .layer_id(LayerId::background())
            .max_rect(ctx.content_rect()),
    );
    root_ui.set_clip_rect(ctx.content_rect());

    CentralPanel::default()
        .frame(panel_frame)
        .show(&mut root_ui, |ui| {
            let app_rect = ui.max_rect();

            let title_bar_height = 32.0;
            let title_bar_rect = {
                let mut rect = app_rect;
                rect.max.y = rect.min.y + title_bar_height;
                rect
            };
            title_bar_ui(ui, title_bar_rect, title);

            // Add the contents:
            let content_rect = {
                let mut rect = app_rect;
                rect.min.y = title_bar_rect.max.y;
                rect
            }
            .shrink(4.0);
            let mut content_ui = ui.new_child(UiBuilder::new().max_rect(content_rect));
            add_contents(&mut content_ui);
        });
}

fn title_bar_ui(ui: &mut egui::Ui, title_bar_rect: eframe::epaint::Rect, title: &str) {
    use egui::{Align2, FontId, Id, PointerButton, Sense, UiBuilder, vec2};

    let painter = ui.painter();

    let title_bar_response = ui.interact(
        title_bar_rect,
        Id::new("title_bar"),
        Sense::click_and_drag(),
    );

    Image::new(logo_image()).paint_at(
        ui,
        Rect::from_center_size(
            title_bar_rect.left_center() + Vec2::new(16.0, 0.0),
            Vec2::splat(20.0),
        ),
    );

    // Paint the title:
    painter.text(
        title_bar_rect.center(),
        Align2::CENTER_CENTER,
        format!("GLED - {title}"),
        FontId::proportional(20.0),
        ui.style().visuals.text_color(),
    );

    // Paint the line under the title:
    painter.line_segment(
        [
            title_bar_rect.left_bottom() + vec2(1.0, 0.0),
            title_bar_rect.right_bottom() + vec2(-1.0, 0.0),
        ],
        ui.visuals().widgets.noninteractive.bg_stroke,
    );

    // Interact with the title bar (drag to move window):
    if title_bar_response.double_clicked() {
        let is_maximized = ui.input(|i| i.viewport().maximized.unwrap_or(false));
        ui.ctx()
            .send_viewport_cmd(ViewportCommand::Maximized(!is_maximized));
    }

    if title_bar_response.drag_started_by(PointerButton::Primary) {
        ui.ctx().send_viewport_cmd(ViewportCommand::StartDrag);
    }

    ui.scope_builder(
        UiBuilder::new()
            .max_rect(title_bar_rect)
            .layout(egui::Layout::right_to_left(egui::Align::Center)),
        |ui| {
            ui.spacing_mut().item_spacing.x = 0.0;
            ui.visuals_mut().button_frame = false;
            ui.add_space(8.0);
            window_buttons(ui);
        },
    );
}

/// Close and maximize, for windows that draw their own title bar.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn window_buttons(ui: &mut egui::Ui) {
    let button_height = 20.0;

    let close_response = ui
        .add(Button::new(icons::X.regular().size(button_height)))
        .on_hover_text("Close the window");
    if close_response.clicked() {
        ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close);
    }

    ui.add_space(2.0);

    let is_maximized = ui.input(|i| i.viewport().maximized.unwrap_or(false));
    if is_maximized {
        let maximized_response = ui
            .add(Button::new(icons::ARROWS_IN.regular().size(button_height)))
            .on_hover_text("Restore window");
        if maximized_response.clicked() {
            ui.ctx()
                .send_viewport_cmd(ViewportCommand::Maximized(false));
        }
    } else {
        let maximized_response = ui
            .add(Button::new(icons::ARROWS_OUT.regular().size(button_height)))
            .on_hover_text("Maximize window");
        if maximized_response.clicked() {
            ui.ctx().send_viewport_cmd(ViewportCommand::Maximized(true));
        }
    }
}

/// Brings a window to the front and gives it focus, once per pending request.
/// A window that is already open stays where it is, so opening it again has to
/// ask for this.
pub(crate) fn raise(ctx: &egui::Context, pending: &mut bool) {
    if std::mem::take(pending) {
        ctx.send_viewport_cmd(ViewportCommand::Focus);
    }
}

/// A dialog titled `title`, belonging to another window: it cannot be
/// maximized or minimized away from the window it blocks, and sits above it.
pub(crate) fn dialog_viewport_builder(title: &str) -> ViewportBuilder {
    tool_window_builder(title)
        .with_resizable(false)
        .with_minimize_button(false)
        .with_maximize_button(false)
}

/// In a browser: fullscreen on and off. A page cannot close its tab, so
/// there is no close button.
#[cfg(target_arch = "wasm32")]
pub(crate) fn window_buttons(ui: &mut egui::Ui) {
    let button_height = 20.0;
    let fullscreen = crate::platform::is_fullscreen();
    let (icon, hint) = if fullscreen {
        (icons::ARROWS_IN, "Leave fullscreen")
    } else {
        (icons::ARROWS_OUT, "Fullscreen")
    };
    if ui
        .add(Button::new(icon.regular().size(button_height)))
        .on_hover_text(hint)
        .clicked()
    {
        crate::platform::set_fullscreen(!fullscreen);
    }
}

/// A gled window: on the desktop without the system's decorations, as gled
/// draws its own title bar; in the browser, where windows are inside the
/// page, with egui's title bar and close button.
pub fn default_viewport_builder() -> ViewportBuilder {
    ViewportBuilder::default()
        .with_app_id("de.photonenkollektiv.gled")
        .with_icon(icon())
        .with_decorations(cfg!(target_arch = "wasm32"))
}

/// A tool window titled `title`.
pub fn tool_window_builder(title: &str) -> ViewportBuilder {
    default_viewport_builder().with_title(format!("gled - {title}"))
}