mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-26 04:23:01 +01:00
Host GridCraft's egui UI on craft-libs next's runtime
The runtime's four hooks in the desktop and web shells, the close path decided by SheetApp::close_decision, Escape read through the window's cancel where no GridCraft widget has the keyboard, the grid as the window's host canvas, the interface scale as the runtime's RootEnv scale, fonts through craft_ui::fonts::load with the chrome's families, the update dialogs on a DialogHost, and app-local copies of the removed capture slot, combo menu and window viewports; the print controls on craft-print's ui feature. Test harnesses that run the app install the runtime.
This commit is contained in:
1 parent
cf877fb11a
commit
2c4652d3d8
57 files changed
+2932
-414
No files matched your search
Generated
+1390
-151
File diff suppressed because it is too large.
Load diff
@@ -93,6 +93,14 @@ epaint_default_fonts = "0.37"
|
||||
# One native window per workbook: the window list, Window menu titles and the immediate-viewport
|
||||
# driver. Same craft-libs revision as craft-update above.
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs", rev = "cd87dc61f77d8470b2e9e6a1236f9a84ee0a64de", default-features = false, features = ["ui"] }
|
||||
# The UI runtime GridCraft's egui UI is hosted by (`crates/ui-egui/src/framework.rs`): who the app is
|
||||
# to the framework's dialogs, the runtime's key bindings, the theme mode, window placement and the
|
||||
# printer controls. Same craft-libs revision as above.
|
||||
craft-behavior = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs", rev = "cd87dc61f77d8470b2e9e6a1236f9a84ee0a64de" }
|
||||
craft-host = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs", rev = "cd87dc61f77d8470b2e9e6a1236f9a84ee0a64de" }
|
||||
craft-keymap = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs", rev = "cd87dc61f77d8470b2e9e6a1236f9a84ee0a64de" }
|
||||
craft-theme = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs", rev = "cd87dc61f77d8470b2e9e6a1236f9a84ee0a64de" }
|
||||
craft-print = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs", rev = "cd87dc61f77d8470b2e9e6a1236f9a84ee0a64de", features = ["ui"] }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
|
||||
@@ -49,6 +49,7 @@ pub fn start() {
|
||||
canvas,
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
gridcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
|
||||
let inbox: Inbox = Inbox::default();
|
||||
let mut session = Session::new();
|
||||
// In host mode the host sends the workbook to edit; no sample meanwhile.
|
||||
@@ -158,6 +159,7 @@ impl eframe::App for WebShell {
|
||||
});
|
||||
}
|
||||
self.app.logic(ctx);
|
||||
self.app.close_path(ctx);
|
||||
// Store changed preferences straight away: a reload or closed tab runs no exit code (#1562).
|
||||
let changed = self.prefs.changed(&self.app);
|
||||
if !changed.is_empty() {
|
||||
@@ -177,6 +179,7 @@ impl eframe::App for WebShell {
|
||||
/// Forwards a browser frame's raw input to the shared app before eframe handles it.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.app.raw_input_hook(ctx, raw);
|
||||
self.app.before_input(ctx);
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
|
||||
@@ -32,7 +32,7 @@ winit = { version = "0.30", default-features = false, features = ["x11", "waylan
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# Same craft-libs revision as the workspace's craft-update and craft-window (see the root
|
||||
# Cargo.toml).
|
||||
craft-print = { git = "https://github.com/aiongg/craft-libs", rev = "cd87dc61f77d8470b2e9e6a1236f9a84ee0a64de" }
|
||||
craft-print = { workspace = true }
|
||||
craft-update = { workspace = true }
|
||||
rfd = { workspace = true }
|
||||
arboard = { workspace = true, features = ["image-data"] }
|
||||
|
||||
@@ -45,13 +45,12 @@ impl eframe::App for App {
|
||||
}
|
||||
self.0.logic(ctx);
|
||||
self.1.logic(&mut self.0, ctx);
|
||||
if ctx.input(|input| input.viewport().close_requested()) && self.0.printing.busy() {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
}
|
||||
self.0.close_path(ctx);
|
||||
}
|
||||
/// Forwards raw input to the shared app, then opens every non-empty dropped file path as a workbook.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.0.raw_input_hook(ctx, raw);
|
||||
self.0.before_input(ctx);
|
||||
// Files dropped on the window open as workbooks.
|
||||
for f in std::mem::take(&mut raw.dropped_files) {
|
||||
if let Some(p) = f.path().to_str().map(str::to_string).filter(|p| !p.is_empty()) {
|
||||
@@ -59,7 +58,8 @@ impl eframe::App for App {
|
||||
}
|
||||
}
|
||||
}
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
gridcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
|
||||
self.1.show(&mut self.0, ui);
|
||||
}
|
||||
fn on_exit(&mut self) {
|
||||
@@ -393,6 +393,7 @@ fn main() -> eframe::Result<()> {
|
||||
let Some(mut app) = pending.take() else {
|
||||
return Err("the app was already created".into());
|
||||
};
|
||||
gridcraft_ui_egui::framework::install(&cc.egui_ctx)?;
|
||||
SheetApp::setup_context_for_language(&cc.egui_ctx, app.ui.dark, app.ui.language);
|
||||
if let Some(port) = control_port {
|
||||
match control_server::start(port, control_token.clone(), cc.egui_ctx.clone()) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Desktop spooler adapter. Discovery and submission never run on the UI thread.
|
||||
use gridcraft_ui_egui::printing::{Discover, Duplex, Printer, Settings, Submit};
|
||||
use gridcraft_ui_egui::printing::{Destination, Discover, Duplex, Printer, Settings, Submit};
|
||||
|
||||
/// Returns a printer-discovery closure that enumerates `craft_print::printers()` on a named background thread and sends the mapped list through a channel.
|
||||
pub fn discover() -> Discover {
|
||||
@@ -8,7 +8,7 @@ pub fn discover() -> Discover {
|
||||
let _ = std::thread::Builder::new().name("print-discovery".into()).spawn(move || {
|
||||
let printers = craft_print::printers()
|
||||
.into_iter()
|
||||
.map(|printer| Printer { name: printer.name, label: printer.description, default: printer.default })
|
||||
.map(|printer| Printer::new(printer.name).label(printer.description).is_default(printer.default))
|
||||
.collect();
|
||||
let _ = sender.send(printers);
|
||||
});
|
||||
@@ -34,12 +34,16 @@ pub fn submit() -> Submit {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
let worker = std::thread::Builder::new().name("print-submit".into()).spawn(move || {
|
||||
let job = craft_print::Job {
|
||||
printer: Some(settings.printer),
|
||||
printer: match settings.destination {
|
||||
Destination::Printer(name) => Some(name),
|
||||
_ => None,
|
||||
},
|
||||
copies: settings.copies.clamp(1, 999),
|
||||
duplex: settings.duplex.map(|value| match value {
|
||||
Duplex::LongEdge => craft_print::Duplex::LongEdge,
|
||||
Duplex::ShortEdge => craft_print::Duplex::ShortEdge,
|
||||
Duplex::Off => craft_print::Duplex::Off,
|
||||
duplex: settings.duplex.and_then(|value| match value {
|
||||
Duplex::LongEdge => Some(craft_print::Duplex::LongEdge),
|
||||
Duplex::ShortEdge => Some(craft_print::Duplex::ShortEdge),
|
||||
Duplex::Off => Some(craft_print::Duplex::Off),
|
||||
_ => None,
|
||||
}),
|
||||
grayscale: settings.grayscale,
|
||||
scaling: craft_print::Scaling::ShrinkToFit,
|
||||
|
||||
@@ -9,9 +9,15 @@ description = "GridCraft egui frontend (Excel-style UI); swappable — nothing b
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
# The shared capture slot (`craft_ui::capture`) comes from the one craft-libs revision every
|
||||
# craft-libs dependency uses (see the root Cargo.toml).
|
||||
# The UI runtime that hosts this egui UI (`src/framework.rs`) and the framework dialogs, from the
|
||||
# one craft-libs revision every craft-libs dependency uses (see the root Cargo.toml).
|
||||
craft-ui = { git = "https://github.com/aiongg/craft-libs", rev = "cd87dc61f77d8470b2e9e6a1236f9a84ee0a64de" }
|
||||
craft-behavior = { workspace = true }
|
||||
craft-host = { workspace = true }
|
||||
craft-keymap = { workspace = true }
|
||||
craft-print = { workspace = true }
|
||||
craft-theme = { workspace = true }
|
||||
craft-window = { workspace = true }
|
||||
gridcraft-engine = { workspace = true }
|
||||
gridcraft-chart = { workspace = true }
|
||||
# `monochrome_emoji_fonts` restores the Noto Emoji and emoji-icon faces that 0.37 moved behind
|
||||
@@ -42,7 +48,6 @@ gridcraft-xlsx = { workspace = true, features = ["test-support"] }
|
||||
craft-update = { workspace = true }
|
||||
# The desktop's preferred language for the first-run interface language.
|
||||
sys-locale = { workspace = true }
|
||||
craft-window = { workspace = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
# Read the browser's preferred language for the first-run web interface language.
|
||||
|
||||
@@ -88,6 +88,8 @@ impl SheetApp {
|
||||
arrange_windows: None,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
updates_rt: Default::default(),
|
||||
framework_dialogs: Default::default(),
|
||||
framework_host: crate::framework::host(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,7 +104,7 @@ impl SheetApp {
|
||||
|
||||
/// Sets up fonts and visuals for a specific persisted interface language.
|
||||
pub fn setup_context_for_language(ctx: &egui::Context, dark: bool, language: i18n::Language) {
|
||||
ctx.set_fonts(theme::font_definitions_for_language(language));
|
||||
craft_ui::fonts::load(ctx, theme::font_definitions_for_language(language));
|
||||
theme::apply(ctx, dark);
|
||||
}
|
||||
|
||||
@@ -123,7 +125,6 @@ impl SheetApp {
|
||||
self.desktop_dark = Some(answer);
|
||||
}
|
||||
self.sync_theme_preference(ctx);
|
||||
self.sync_input_options(ctx);
|
||||
// The geometry captures are bound to. Native frames recorded it from their fresh
|
||||
// `RawInput` in `raw_input_hook` (including hidden logic-only ticks); the epoch is
|
||||
// monotonic, so a resize back to the original values is still a new epoch and old pixels
|
||||
@@ -139,7 +140,6 @@ impl SheetApp {
|
||||
// Printing feedback is polled once per frame, here, so hidden windows and logic-only
|
||||
// frames still see worker completion. `ui` and the desktop app no longer poll it.
|
||||
self.poll_printing(ctx);
|
||||
self.guard_window_close(ctx);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
updates_ui::tick(self, ctx);
|
||||
// Files read asynchronously (web file picker, dropped files).
|
||||
@@ -212,8 +212,6 @@ impl SheetApp {
|
||||
}
|
||||
// The language the widgets translate with this frame (see `i18n::current`).
|
||||
i18n::set_current(&ctx, self.ui.language);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
updates_ui::show(self, &ctx);
|
||||
let t = theme::Tokens::get(&ctx);
|
||||
// A host can turn the File tab off while Backstage is already open: close it.
|
||||
if !self.chrome.file_tab {
|
||||
@@ -256,6 +254,12 @@ impl SheetApp {
|
||||
widgets::toast(self, &ctx);
|
||||
// Last, so its resize cursors win over the widgets under the window edges.
|
||||
ribbon::window_frame(self, &ctx);
|
||||
// The update flow and the framework dialogs run once per frame, in the root window.
|
||||
if ctx.viewport_id() == egui::ViewportId::ROOT {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
updates_ui::show(self, &ctx);
|
||||
self.run_framework_dialogs(ui);
|
||||
}
|
||||
self.flush_viewport_commands(&ctx);
|
||||
// Requests are admitted in `logic`, for the root viewport, so only its pass issues them.
|
||||
if ctx.viewport_id() == egui::ViewportId::ROOT {
|
||||
@@ -524,7 +528,7 @@ mod lifecycle_tests {
|
||||
fn a_logic_only_tick_polls_printing_feedback() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = app();
|
||||
app.printing.printers.push(crate::printing::Printer { name: "Queue".into(), label: String::new(), default: true });
|
||||
app.printing.printers.push(crate::printing::Printer::new("Queue").is_default(true));
|
||||
app.run("ui.printSettings", serde_json::json!({"printer": "Queue"})).unwrap();
|
||||
app.services.print_native = Some(Box::new(|_, _| {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
|
||||
@@ -81,7 +81,7 @@ impl SheetApp {
|
||||
return;
|
||||
}
|
||||
if self.prepared_fonts {
|
||||
ctx.set_fonts(theme::pinned_font_definitions());
|
||||
craft_ui::fonts::load(ctx, theme::pinned_font_definitions());
|
||||
theme::apply(ctx, self.ui.dark);
|
||||
} else {
|
||||
SheetApp::setup_context_for_language(ctx, self.ui.dark, self.ui.language);
|
||||
@@ -107,7 +107,7 @@ impl SheetApp {
|
||||
if used == self.fonts_bound {
|
||||
return;
|
||||
}
|
||||
ctx.set_fonts(theme::font_definitions_with(self.ui.language, &used));
|
||||
craft_ui::fonts::load(ctx, theme::font_definitions_with(self.ui.language, &used));
|
||||
self.fonts_bound = used;
|
||||
self.fonts_rebind = true;
|
||||
ctx.request_repaint();
|
||||
|
||||
@@ -27,27 +27,6 @@ impl SheetApp {
|
||||
self.effective_dark = ctx.theme() == egui::Theme::Dark;
|
||||
}
|
||||
|
||||
/// Keeps egui's own keyboard zoom and quit shortcuts off and applies GridCraft's zoom factor.
|
||||
pub(super) fn sync_input_options(&mut self, ctx: &egui::Context) {
|
||||
// Interface size: the preference owns the zoom factor, so egui's own Ctrl/Cmd +/-/0 zoom
|
||||
// keys stay off (they would also swallow GridCraft's shortcuts).
|
||||
if ctx.options(|o| o.zoom_with_keyboard) {
|
||||
ctx.options_mut(|o| o.zoom_with_keyboard = false);
|
||||
}
|
||||
// egui closes the window on Ctrl+Q (and with Shift or Alt held too) without asking to save
|
||||
// (#1443). Excel for Windows has no such key (Ctrl+Q is Quick Analysis). With a native
|
||||
// window per workbook egui's Cmd+Q would close only the window it was typed in: the menu
|
||||
// bar's Quit item has the key instead (it asks about unsaved workbooks first).
|
||||
if (ctx.os() != egui::os::OperatingSystem::Mac || self.native_windows) && ctx.options(|o| !o.quit_shortcuts.is_empty()) {
|
||||
ctx.options_mut(|o| o.quit_shortcuts.clear());
|
||||
}
|
||||
let zoom = self.ui.zoom_factor();
|
||||
if (ctx.zoom_factor() - zoom).abs() > 0.001 {
|
||||
ctx.set_zoom_factor(zoom);
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
/// Look for a newer release once, in the background, as the desktop app starts (a no-op on the
|
||||
/// web). A found release opens the update prompt; nothing is shown when GridCraft is current.
|
||||
pub fn start_update_check(&mut self) {
|
||||
|
||||
@@ -1,28 +1,35 @@
|
||||
use craft_ui::shell::embed::CloseDecision;
|
||||
|
||||
use super::{SaveAnswer, SheetApp, json};
|
||||
|
||||
impl SheetApp {
|
||||
/// Holds back a window close (the close button, Alt+F4, the OS quitting the app) while a
|
||||
/// workbook has unsaved changes, and asks about them first.
|
||||
pub(super) fn guard_window_close(&mut self, ctx: &egui::Context) {
|
||||
if self.native_windows || self.allow_close || !ctx.input(|i| i.viewport().close_requested()) {
|
||||
return;
|
||||
/// The root window was asked to close (the close button, Alt+F4, the OS quitting the app): whether it closes
|
||||
/// now. A running print job holds it. With a native window per workbook the close is that window's
|
||||
/// ([`crate::doc_windows`]) unless the app is quitting. Otherwise unsaved changes hold it while they are asked
|
||||
/// about.
|
||||
pub fn close_decision(&mut self, ctx: &egui::Context) -> CloseDecision {
|
||||
if self.printing.busy() {
|
||||
return CloseDecision::Hold;
|
||||
}
|
||||
if self.allow_close {
|
||||
return CloseDecision::Close;
|
||||
}
|
||||
if self.native_windows {
|
||||
return CloseDecision::Hold;
|
||||
}
|
||||
// A cell still being edited is part of the workbook, as for File › Close.
|
||||
if !self.commit_edit(0, 0, false, false) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
return;
|
||||
return CloseDecision::Hold;
|
||||
}
|
||||
// The macro step editor asks about its own unsaved steps and debug run first; once it has
|
||||
// closed, the window close goes on.
|
||||
if self.dialog.as_ref().is_some_and(|d| d.name == "macroEditor") {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
crate::macro_editor::request_close(self, true);
|
||||
return;
|
||||
return CloseDecision::Hold;
|
||||
}
|
||||
if !self.session.documents().iter().any(|d| d.is_dirty()) {
|
||||
return;
|
||||
return CloseDecision::Close;
|
||||
}
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
match self.dialog.as_mut() {
|
||||
// Already asking about a workbook (File › Close): answering it now goes on to quit.
|
||||
Some(d) if d.name() == "saveChanges" => {
|
||||
@@ -30,6 +37,7 @@ impl SheetApp {
|
||||
}
|
||||
_ => self.continue_quit(ctx),
|
||||
}
|
||||
CloseDecision::Hold
|
||||
}
|
||||
|
||||
/// Asks about the next unsaved workbook before quitting, in its window, or closes the app
|
||||
|
||||
@@ -233,12 +233,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui) {
|
||||
});
|
||||
});
|
||||
bs.text_edit_focused = ctx.text_edit_focused();
|
||||
if !typing
|
||||
&& app.dialog.is_none()
|
||||
&& app.message.is_none()
|
||||
&& !egui::Popup::is_any_open(&ctx)
|
||||
&& ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape))
|
||||
{
|
||||
if !typing && app.dialog.is_none() && app.message.is_none() && !egui::Popup::is_any_open(&ctx) && crate::framework::consume_escape(&ctx) {
|
||||
out.close = true;
|
||||
}
|
||||
if let Some(page) = out.page {
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
//! One-shot completion slots for screenshot requests.
|
||||
//!
|
||||
//! Applications retain request IDs, output paths, deadlines, settling policy, geometry epochs and
|
||||
//! aggregate admission budgets. This module only correlates one capture with one slot, checks the
|
||||
//! retained image against a per-image byte bound, and wakes the owning viewport.
|
||||
//!
|
||||
//! [`CaptureSlot::new`] does not issue a screenshot command. Send the returned [`egui::ScreenshotCallback`]
|
||||
//! with [`egui::ViewportCommand::Screenshot`] when the application decides the capture is due, or
|
||||
//! complete it directly from a headless renderer. The callback holds only a weak reference to the
|
||||
//! slot, so dropping or cancelling the request releases its image and makes late results inert.
|
||||
//!
|
||||
//! Every retry needs a fresh slot and a fresh callback from [`CaptureSlot::new`]; a callback is
|
||||
//! one-shot, and a slot ignores completions after its result was taken, cancelled or dropped. The
|
||||
//! slot does not track whether a request is still open: keep that pending/closed distinction in the
|
||||
//! application's request record.
|
||||
//!
|
||||
//! A completion that publishes its result just before a concurrent [`CaptureSlot::cancel`] or drop
|
||||
//! can still deliver its single wakeup afterwards. That extra repaint is harmless: if the
|
||||
//! cancellation won, the image is released and a later [`CaptureSlot::take`] returns `None`; if
|
||||
//! `take` won first, the caller already owns the result and nothing else changes. A completion that
|
||||
//! observes a cancelled or taken slot stores no image and does not wake. Cancellation and completion
|
||||
//! are therefore not atomic with respect to the wakeup, and this module never waits for another
|
||||
//! thread while holding the slot lock.
|
||||
//!
|
||||
//! [`CaptureSlot`] holds a strong [`egui::Context`]. Keep it in the application's request record;
|
||||
//! storing it in `Context`-owned data (`egui::Memory::data` or a registered plugin) forms a
|
||||
//! `Context` → slot → `Context` cycle that keeps both alive.
|
||||
|
||||
use std::mem::size_of;
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
|
||||
|
||||
use egui::{Color32, ColorImage, Context, ScreenshotCallback, ViewportId};
|
||||
|
||||
/// Why a completed screenshot was rejected and released.
|
||||
///
|
||||
/// The enum is `#[non_exhaustive]`: consumers should match the known variants and use a wildcard
|
||||
/// arm for a future rejection reason.
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CaptureError {
|
||||
/// The checked `width * height` pixel count, or its `width * height * size_of::<Color32>()`
|
||||
/// byte count, overflowed `usize`.
|
||||
DimensionsOverflow { width: usize, height: usize },
|
||||
/// The pixel buffer does not match the reported image dimensions, or the image has zero width
|
||||
/// or height.
|
||||
MalformedImage { width: usize, height: usize, pixels: usize },
|
||||
/// The checked image size exceeds the slot's per-image byte bound.
|
||||
ImageTooLarge { bytes: usize, max_bytes: usize },
|
||||
}
|
||||
|
||||
impl core::fmt::Display for CaptureError {
|
||||
/// Format a human-readable rejection reason. The wording is informative only and is not an
|
||||
/// API contract; the variants keep checked-overflow, malformed-image and size-cap cases
|
||||
/// distinguishable.
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
Self::DimensionsOverflow { width, height } => {
|
||||
write!(f, "screenshot dimensions {width}×{height} overflow the checked pixel or byte count")
|
||||
}
|
||||
Self::MalformedImage { width, height, pixels } => write!(f, "screenshot has {pixels} pixels for its {width}×{height} dimensions"),
|
||||
Self::ImageTooLarge { bytes, max_bytes } => write!(f, "screenshot uses {bytes} bytes, over the {max_bytes}-byte per-image limit"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for CaptureError {}
|
||||
|
||||
enum SlotState {
|
||||
Pending,
|
||||
Ready(Result<Arc<ColorImage>, CaptureError>),
|
||||
Taken,
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
struct Shared {
|
||||
state: Mutex<SlotState>,
|
||||
/// The live request owns the strong context; the callback only upgrades it briefly to wake.
|
||||
context: Context,
|
||||
viewport: ViewportId,
|
||||
max_image_bytes: usize,
|
||||
}
|
||||
|
||||
/// The live request side of a capture. Keep it alive until the result is taken or the request is
|
||||
/// cancelled; dropping it cancels the completion and releases any retained image.
|
||||
///
|
||||
/// This type is `Send + Sync`; the application may hold it in its request record and poll
|
||||
/// [`Self::take`] from its logic pass. Do not store it in `Context`-owned storage: the slot holds a
|
||||
/// strong [`egui::Context`], so `egui::Memory::data` or a registered plugin would create a cycle.
|
||||
#[must_use = "the slot must be kept alive to receive and take the screenshot"]
|
||||
pub struct CaptureSlot {
|
||||
shared: Arc<Shared>,
|
||||
}
|
||||
|
||||
impl CaptureSlot {
|
||||
/// Create a completion slot and its one-shot callback.
|
||||
///
|
||||
/// `max_image_bytes` bounds the single retained image only. The application must separately
|
||||
/// reserve its aggregate in-flight/completed budget before issuing the request.
|
||||
///
|
||||
/// This function does not send a viewport command. If the request is issued in a UI pass, send
|
||||
/// the callback with [`egui::ViewportCommand::Screenshot`]; a pending screenshot command itself
|
||||
/// requests the paint needed while the window is hidden. Issue that command at most once per
|
||||
/// slot, after the application has settled the frame it wants; every retry needs a fresh slot
|
||||
/// and callback.
|
||||
pub fn new(context: &Context, viewport: ViewportId, max_image_bytes: usize) -> (Self, ScreenshotCallback) {
|
||||
let shared = Arc::new(Shared { state: Mutex::new(SlotState::Pending), context: context.clone(), viewport, max_image_bytes });
|
||||
let weak = Arc::downgrade(&shared);
|
||||
let callback = ScreenshotCallback::new(move |image| complete(&weak, image));
|
||||
(Self { shared }, callback)
|
||||
}
|
||||
|
||||
/// Take the completed result, at most once.
|
||||
///
|
||||
/// Returns `None` while the capture is pending, after it was cancelled or dropped, and after a
|
||||
/// previous call already took the image or error. The slot cannot distinguish those states;
|
||||
/// the application's request record owns the pending/closed distinction. Invalid images are
|
||||
/// returned as an error so the application can report completion failure with its own request
|
||||
/// identity.
|
||||
pub fn take(&self) -> Option<Result<Arc<ColorImage>, CaptureError>> {
|
||||
let mut state = lock(&self.shared.state);
|
||||
if !matches!(&*state, SlotState::Ready(_)) {
|
||||
return None;
|
||||
}
|
||||
match core::mem::replace(&mut *state, SlotState::Taken) {
|
||||
SlotState::Ready(result) => Some(result),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Cancel the request and release any completed image.
|
||||
///
|
||||
/// A completion that published its result before this call may still deliver one harmless
|
||||
/// repaint afterwards; the slot retains no image and a later [`Self::take`] returns `None`. A
|
||||
/// completion that observes the cancellation stores no image and does not wake. Calling `cancel`
|
||||
/// after [`Self::take`] is harmless. Any retained image is dropped after the slot mutex is
|
||||
/// unlocked.
|
||||
pub fn cancel(&self) {
|
||||
close(&self.shared);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
/// Nonblocking probe used by the wakeup test to prove that the slot mutex is free while the
|
||||
/// repaint observer runs.
|
||||
fn lock_is_free(&self) -> bool {
|
||||
self.shared.state.try_lock().is_ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
/// Count strong references to the shared slot state, proving callbacks retain none.
|
||||
fn state_strong_count(&self) -> usize {
|
||||
Arc::strong_count(&self.shared)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
/// A weak handle to the shared state, used to inject a second completion directly when egui has
|
||||
/// already consumed the public callback.
|
||||
fn state_weak(&self) -> Weak<Shared> {
|
||||
Arc::downgrade(&self.shared)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for CaptureSlot {
|
||||
/// Cancel the request as the slot goes away. A later completion upgrades no live state and
|
||||
/// releases its image, a retained ready image is dropped, and no repaint is requested. Results
|
||||
/// already taken by the caller are unaffected.
|
||||
fn drop(&mut self) {
|
||||
close(&self.shared);
|
||||
}
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for CaptureSlot {
|
||||
/// Format only the viewport and omit the remaining fields. The retained image and error payload
|
||||
/// are deliberately hidden so logging cannot hold or dump screenshot contents.
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
f.debug_struct("CaptureSlot").field("viewport", &self.shared.viewport).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// Lock the slot state, recovering from poisoning instead of panicking. The guard must be
|
||||
/// released before entering the egui context or a repaint observer; completion and close do so
|
||||
/// before waking the viewport.
|
||||
fn lock(state: &Mutex<SlotState>) -> MutexGuard<'_, SlotState> {
|
||||
state.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Mark the slot closed and drop any retained image after releasing the mutex.
|
||||
fn close(shared: &Shared) {
|
||||
let previous = {
|
||||
let mut state = lock(&shared.state);
|
||||
core::mem::replace(&mut *state, SlotState::Cancelled)
|
||||
};
|
||||
drop(previous);
|
||||
}
|
||||
|
||||
/// Validate a completed image, store it, and wake the owning viewport.
|
||||
///
|
||||
/// The slot lock is released before calling into the context, so a repaint observer may call
|
||||
/// [`CaptureSlot::take`] or [`CaptureSlot::cancel`] re-entrantly. Inside an observer, only consume or
|
||||
/// release that value; any further `Context` access must happen outside the observer.
|
||||
/// [`egui::Context::request_repaint_of`] takes egui's context lock. Ordinary `Ui` closures and egui
|
||||
/// 0.37 plugin hooks run outside that lock, as do renderer/worker callbacks. Repaint observers and
|
||||
/// request-repaint callbacks run under it: completing from either would deadlock when requesting
|
||||
/// the repaint. This function never waits under the slot lock.
|
||||
fn complete(weak: &Weak<Shared>, image: Arc<ColorImage>) {
|
||||
let Some(shared) = weak.upgrade() else {
|
||||
// The request was dropped; the image is released here without a reply.
|
||||
return;
|
||||
};
|
||||
let result = checked_image(image, shared.max_image_bytes);
|
||||
let should_wake = {
|
||||
let mut state = lock(&shared.state);
|
||||
if matches!(&*state, SlotState::Pending) {
|
||||
*state = SlotState::Ready(result);
|
||||
true
|
||||
} else {
|
||||
// Cancelled, already taken, or (defensively) completed twice: drop the image.
|
||||
false
|
||||
}
|
||||
};
|
||||
// The slot lock is released before calling into the context, so a repaint observer may take
|
||||
// the result or cancel the request re-entrantly without deadlocking.
|
||||
if should_wake {
|
||||
shared.context.request_repaint_of(shared.viewport);
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate `image` against the slot's per-image byte bound before publishing it.
|
||||
///
|
||||
/// Zero width or height is malformed before any arithmetic; the pixel count and its byte size use
|
||||
/// checked multiplication; the buffer length must equal `width * height`; and only then is the
|
||||
/// byte count compared with `max_image_bytes`, rejecting a count greater than it (equality is
|
||||
/// accepted). `max_image_bytes` bounds this one image, not an aggregate request budget. Returns the
|
||||
/// same `Arc` without waking the viewport or requesting a repaint.
|
||||
fn checked_image(image: Arc<ColorImage>, max_image_bytes: usize) -> Result<Arc<ColorImage>, CaptureError> {
|
||||
let [width, height] = image.size;
|
||||
if width == 0 || height == 0 {
|
||||
return Err(CaptureError::MalformedImage { width, height, pixels: image.pixels.len() });
|
||||
}
|
||||
let pixels = width.checked_mul(height).ok_or(CaptureError::DimensionsOverflow { width, height })?;
|
||||
let bytes = pixels.checked_mul(size_of::<Color32>()).ok_or(CaptureError::DimensionsOverflow { width, height })?;
|
||||
if image.pixels.len() != pixels {
|
||||
return Err(CaptureError::MalformedImage { width, height, pixels: image.pixels.len() });
|
||||
}
|
||||
if bytes > max_image_bytes {
|
||||
return Err(CaptureError::ImageTooLarge { bytes, max_bytes: max_image_bytes });
|
||||
}
|
||||
Ok(image)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,491 @@
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Barrier};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Allocate a filled `Arc<ColorImage>` fixture of `size` with every pixel set to `color`.
|
||||
fn image(size: [usize; 2], color: egui::Color32) -> Arc<ColorImage> {
|
||||
Arc::new(ColorImage::filled(size, color))
|
||||
}
|
||||
|
||||
/// Install a repaint observer and return the viewport requests it records.
|
||||
fn observe_repaints(ctx: &Context) -> Arc<Mutex<Vec<ViewportId>>> {
|
||||
let requests = Arc::new(Mutex::new(Vec::new()));
|
||||
let observed = requests.clone();
|
||||
ctx.set_repaint_observer(move |info| observed.lock().unwrap().push(info.viewport_id));
|
||||
requests
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Compile-time assertion that `CaptureSlot` and `ScreenshotCallback` are `Send + Sync`.
|
||||
fn slot_is_send_and_sync() {
|
||||
/// Compile-time helper requiring `T: Send + Sync`; the enclosing test uses it to
|
||||
/// assert the public capture types are thread-safe.
|
||||
fn assert_send_sync<T: Send + Sync>() {}
|
||||
assert_send_sync::<CaptureSlot>();
|
||||
assert_send_sync::<ScreenshotCallback>();
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Two independent slots for different viewports may complete in reverse order; each `take`
|
||||
/// returns exactly its own image and dimensions.
|
||||
fn distinct_requests_complete_in_reverse_order() {
|
||||
let ctx = Context::default();
|
||||
let first_viewport = ViewportId::from_hash_of("first-window");
|
||||
let second_viewport = ViewportId::from_hash_of("second-window");
|
||||
let (first, first_callback) = CaptureSlot::new(&ctx, first_viewport, 1024);
|
||||
let (second, second_callback) = CaptureSlot::new(&ctx, second_viewport, 1024);
|
||||
let first_image = image([2, 1], egui::Color32::RED);
|
||||
let second_image = image([1, 3], egui::Color32::BLUE);
|
||||
|
||||
// The renderer may answer the later request first.
|
||||
second_callback.complete(second_image.clone());
|
||||
first_callback.complete(first_image.clone());
|
||||
|
||||
let taken_first = first.take().unwrap().unwrap();
|
||||
let taken_second = second.take().unwrap().unwrap();
|
||||
assert!(Arc::ptr_eq(&taken_first, &first_image));
|
||||
assert!(Arc::ptr_eq(&taken_second, &second_image));
|
||||
assert_eq!(taken_first.size, [2, 1]);
|
||||
assert_eq!(taken_second.size, [1, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Slots keep separate results and byte caps: a 2×2 image over the first slot's 4-byte cap is
|
||||
/// rejected as too large while the second stays pending, then the second accepts its own image and
|
||||
/// a taken slot remains empty.
|
||||
fn slots_do_not_share_results_or_byte_bounds() {
|
||||
let ctx = Context::default();
|
||||
let first_viewport = ViewportId::from_hash_of("first-slot");
|
||||
let second_viewport = ViewportId::from_hash_of("second-slot");
|
||||
let (first, first_callback) = CaptureSlot::new(&ctx, first_viewport, 4);
|
||||
let (second, second_callback) = CaptureSlot::new(&ctx, second_viewport, 16);
|
||||
|
||||
let rejected_for_first = image([2, 2], egui::Color32::RED);
|
||||
first_callback.complete(rejected_for_first);
|
||||
|
||||
assert!(second.take().is_none(), "completing one slot leaves the other pending");
|
||||
assert!(matches!(first.take(), Some(Err(CaptureError::ImageTooLarge { bytes: 16, max_bytes: 4 }))));
|
||||
|
||||
let accepted_for_second = image([2, 2], egui::Color32::BLUE);
|
||||
second_callback.complete(accepted_for_second.clone());
|
||||
assert!(Arc::ptr_eq(&second.take().unwrap().unwrap(), &accepted_for_second));
|
||||
assert!(first.take().is_none(), "a taken slot stays empty");
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Cloned callbacks share one completion: the first result wins, the losing image is released, and
|
||||
/// `take` yields the result only once.
|
||||
fn callback_clones_share_one_completion_and_take_is_single_use() {
|
||||
let ctx = Context::default();
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
|
||||
let duplicate = callback.clone();
|
||||
let first_image = image([1, 1], egui::Color32::RED);
|
||||
let second_image = image([1, 1], egui::Color32::BLUE);
|
||||
let weak_loser = Arc::downgrade(&second_image);
|
||||
|
||||
callback.complete(first_image.clone());
|
||||
duplicate.complete(second_image);
|
||||
assert!(weak_loser.upgrade().is_none(), "the losing completion releases its image");
|
||||
|
||||
let taken = slot.take().unwrap().unwrap();
|
||||
assert!(Arc::ptr_eq(&taken, &first_image), "the first completion wins");
|
||||
assert!(slot.take().is_none(), "the result is taken once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// After `take`, both a duplicate callback and a direct completion release their images without
|
||||
/// storing a result or requesting a repaint.
|
||||
fn duplicate_completion_after_take_neither_stores_nor_wakes() {
|
||||
let ctx = Context::default();
|
||||
let requests = observe_repaints(&ctx);
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
|
||||
let duplicate_callback = callback.clone();
|
||||
let first_image = image([1, 1], egui::Color32::RED);
|
||||
callback.complete(first_image.clone());
|
||||
assert!(Arc::ptr_eq(&slot.take().unwrap().unwrap(), &first_image));
|
||||
assert_eq!(requests.lock().unwrap().len(), 1, "the first completion wakes");
|
||||
|
||||
let duplicate_image = image([1, 1], egui::Color32::BLUE);
|
||||
let weak_duplicate = Arc::downgrade(&duplicate_image);
|
||||
duplicate_callback.complete(duplicate_image);
|
||||
|
||||
assert!(weak_duplicate.upgrade().is_none(), "a duplicate after take is released");
|
||||
assert!(slot.take().is_none());
|
||||
assert_eq!(requests.lock().unwrap().len(), 1, "a duplicate after take does not wake");
|
||||
|
||||
// Deliver a second completion straight to the slot; egui already consumed its callback.
|
||||
let direct_image = image([1, 1], egui::Color32::GREEN);
|
||||
let weak_direct = Arc::downgrade(&direct_image);
|
||||
complete(&slot.state_weak(), direct_image);
|
||||
assert!(weak_direct.upgrade().is_none(), "a direct second completion after take is released");
|
||||
assert!(slot.take().is_none());
|
||||
assert_eq!(requests.lock().unwrap().len(), 1, "a direct second completion after take does not wake");
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// An early `take` returns `None` without closing the request; a later completion still delivers.
|
||||
fn take_before_completion_is_empty_and_keeps_the_request_open() {
|
||||
let ctx = Context::default();
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
|
||||
assert!(slot.take().is_none());
|
||||
let expected = image([1, 1], egui::Color32::RED);
|
||||
callback.complete(expected.clone());
|
||||
assert!(Arc::ptr_eq(&slot.take().unwrap().unwrap(), &expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Cancelling before completion releases a late image, leaves `take` empty, and suppresses the
|
||||
/// repaint wakeup.
|
||||
fn cancel_releases_late_images_without_waking() {
|
||||
let ctx = Context::default();
|
||||
let requests = observe_repaints(&ctx);
|
||||
let viewport = ViewportId::from_hash_of("cancelled-window");
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, viewport, 1024);
|
||||
slot.cancel();
|
||||
|
||||
let late_image = image([2, 2], egui::Color32::RED);
|
||||
let weak_image = Arc::downgrade(&late_image);
|
||||
callback.complete(late_image.clone());
|
||||
drop(late_image);
|
||||
|
||||
assert!(weak_image.upgrade().is_none(), "a cancelled slot releases the late image");
|
||||
assert!(slot.take().is_none());
|
||||
assert!(requests.lock().unwrap().is_empty(), "cancellation suppresses the wakeup");
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// A ready slot retains its image and has woken once; `cancel` releases the image and does not wake
|
||||
/// again.
|
||||
fn cancel_after_ready_releases_the_image() {
|
||||
let ctx = Context::default();
|
||||
let requests = observe_repaints(&ctx);
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
|
||||
let completed = image([2, 2], egui::Color32::RED);
|
||||
let weak_image = Arc::downgrade(&completed);
|
||||
callback.complete(completed.clone());
|
||||
drop(completed);
|
||||
assert!(weak_image.upgrade().is_some(), "the ready slot retains the image");
|
||||
assert_eq!(requests.lock().unwrap().len(), 1, "the completion woke the viewport");
|
||||
|
||||
slot.cancel();
|
||||
|
||||
assert!(weak_image.upgrade().is_none(), "cancel releases a ready image");
|
||||
assert!(slot.take().is_none());
|
||||
assert_eq!(requests.lock().unwrap().len(), 1, "cancellation itself does not wake");
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Dropping the slot releases an image that is only retained by the completed slot.
|
||||
fn dropping_the_slot_releases_a_completed_image() {
|
||||
let ctx = Context::default();
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
|
||||
let completed = image([2, 2], egui::Color32::RED);
|
||||
callback.complete(completed.clone());
|
||||
let weak_image = Arc::downgrade(&completed);
|
||||
drop(completed);
|
||||
assert!(weak_image.upgrade().is_some(), "the slot retains the completed image");
|
||||
|
||||
drop(slot);
|
||||
assert!(weak_image.upgrade().is_none(), "dropping the slot releases its image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// A completion after the slot is dropped releases the image and does not wake the viewport.
|
||||
fn late_completion_after_drop_is_inert() {
|
||||
let ctx = Context::default();
|
||||
let requests = observe_repaints(&ctx);
|
||||
let viewport = ViewportId::ROOT;
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, viewport, 1024);
|
||||
drop(slot);
|
||||
|
||||
let late_image = image([1, 1], egui::Color32::RED);
|
||||
let weak_image = Arc::downgrade(&late_image);
|
||||
callback.complete(late_image.clone());
|
||||
drop(late_image);
|
||||
|
||||
assert!(weak_image.upgrade().is_none());
|
||||
assert!(requests.lock().unwrap().is_empty(), "a late result does not wake the viewport");
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Callbacks hold only a weak reference: the slot state has one strong owner, dropping the slot
|
||||
/// releases the context and state, and a later completion is inert.
|
||||
fn callback_retains_only_a_weak_reference_to_live_state() {
|
||||
let ctx = Context::default();
|
||||
let requests = observe_repaints(&ctx);
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
|
||||
let callback_clone = callback.clone();
|
||||
assert_eq!(slot.state_strong_count(), 1, "the callback must not own the slot state");
|
||||
|
||||
let weak_state = slot.state_weak();
|
||||
drop(slot);
|
||||
assert!(weak_state.upgrade().is_none(), "dropping the slot releases its context and state");
|
||||
|
||||
let late_image = image([1, 1], egui::Color32::RED);
|
||||
let weak_image = Arc::downgrade(&late_image);
|
||||
callback_clone.complete(late_image.clone());
|
||||
drop(late_image);
|
||||
assert!(weak_image.upgrade().is_none());
|
||||
assert!(requests.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// A completion distinguishes the per-image size cap, a malformed pixel buffer, and overflow of
|
||||
/// the pixel or byte count; a returned error is taken at most once.
|
||||
fn rejects_oversized_malformed_and_overflowing_images() {
|
||||
let ctx = Context::default();
|
||||
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 16);
|
||||
callback.complete(image([3, 3], egui::Color32::RED));
|
||||
assert!(matches!(slot.take(), Some(Err(CaptureError::ImageTooLarge { bytes: 36, max_bytes: 16 }))));
|
||||
assert!(slot.take().is_none(), "a completion error is reported once");
|
||||
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
|
||||
callback.complete(Arc::new(ColorImage { size: [2, 2], source_size: egui::Vec2::ZERO, pixels: vec![egui::Color32::RED; 3] }));
|
||||
assert!(matches!(slot.take(), Some(Err(CaptureError::MalformedImage { width: 2, height: 2, pixels: 3 }))));
|
||||
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
|
||||
callback.complete(Arc::new(ColorImage { size: [usize::MAX, 2], source_size: egui::Vec2::ZERO, pixels: Vec::new() }));
|
||||
assert!(matches!(slot.take(), Some(Err(CaptureError::DimensionsOverflow { width, height })) if width == usize::MAX && height == 2));
|
||||
|
||||
// The pixel count fits but the byte count does not.
|
||||
let wide = usize::MAX / 2;
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
|
||||
callback.complete(Arc::new(ColorImage { size: [wide, 1], source_size: egui::Vec2::ZERO, pixels: Vec::new() }));
|
||||
assert!(matches!(slot.take(), Some(Err(CaptureError::DimensionsOverflow { width, height })) if width == wide && height == 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Oversized and malformed images are dropped immediately and each rejection still wakes the error
|
||||
/// consumer exactly once before `take` reports it.
|
||||
fn rejected_oversized_and_malformed_images_are_released_before_take() {
|
||||
let ctx = Context::default();
|
||||
let requests = observe_repaints(&ctx);
|
||||
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 16);
|
||||
let oversized = image([3, 3], egui::Color32::RED);
|
||||
let weak_oversized = Arc::downgrade(&oversized);
|
||||
callback.complete(oversized);
|
||||
assert!(weak_oversized.upgrade().is_none(), "an oversized image is released");
|
||||
assert_eq!(*requests.lock().unwrap(), [ViewportId::ROOT], "rejection wakes the error consumer");
|
||||
assert!(matches!(slot.take(), Some(Err(CaptureError::ImageTooLarge { bytes: 36, max_bytes: 16 }))));
|
||||
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
|
||||
let malformed = Arc::new(ColorImage { size: [2, 2], source_size: egui::Vec2::ZERO, pixels: vec![egui::Color32::RED; 3] });
|
||||
let weak_malformed = Arc::downgrade(&malformed);
|
||||
callback.complete(malformed);
|
||||
assert!(weak_malformed.upgrade().is_none(), "a malformed image is released");
|
||||
assert_eq!(*requests.lock().unwrap(), [ViewportId::ROOT, ViewportId::ROOT]);
|
||||
assert!(matches!(slot.take(), Some(Err(CaptureError::MalformedImage { width: 2, height: 2, pixels: 3 }))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Any zero width or height is rejected as malformed before overflow or size-cap decisions, even
|
||||
/// for extreme extents such as `usize::MAX × 0`.
|
||||
fn zero_area_images_are_rejected_even_with_extreme_extents() {
|
||||
let ctx = Context::default();
|
||||
|
||||
for size in [[0, 4], [4, 0], [0, 0], [usize::MAX, 0], [0, usize::MAX]] {
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
|
||||
callback.complete(Arc::new(ColorImage { size, source_size: egui::Vec2::ZERO, pixels: Vec::new() }));
|
||||
let rejected = slot.take();
|
||||
assert!(
|
||||
matches!(rejected, Some(Err(CaptureError::MalformedImage { width, height, pixels }))
|
||||
if width == size[0] && height == size[1] && pixels == 0),
|
||||
"zero-area image {size:?} must be rejected"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// A 2×2 image at exactly the 16-byte cap is accepted: the bound is inclusive.
|
||||
fn accepts_an_image_exactly_at_the_byte_bound() {
|
||||
let ctx = Context::default();
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 16);
|
||||
let exact = image([2, 2], egui::Color32::GREEN);
|
||||
callback.complete(exact.clone());
|
||||
assert!(Arc::ptr_eq(&slot.take().unwrap().unwrap(), &exact));
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// A worker thread completes a child-window slot; every recorded wake belongs to that slot's
|
||||
/// viewport and the expected image is delivered.
|
||||
fn another_thread_completes_and_wakes_only_the_owning_viewport() {
|
||||
let ctx = Context::default();
|
||||
let requests = observe_repaints(&ctx);
|
||||
let viewport = ViewportId::from_hash_of("child-window");
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, viewport, 1024);
|
||||
let expected = image([1, 1], egui::Color32::RED);
|
||||
let sent = expected.clone();
|
||||
|
||||
let handle = std::thread::spawn(move || callback.complete(sent));
|
||||
handle.join().unwrap();
|
||||
|
||||
let requested = requests.lock().unwrap();
|
||||
assert!(!requested.is_empty(), "completion wakes the owning viewport");
|
||||
assert!(requested.iter().all(|requested_viewport| *requested_viewport == viewport), "completion wakes only the owning viewport: {requested:?}");
|
||||
drop(requested);
|
||||
assert!(Arc::ptr_eq(&slot.take().unwrap().unwrap(), &expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// The repaint observer can `take` the image re-entrantly: `try_lock` succeeds during the wakeup,
|
||||
/// proving the slot lock is released before `request_repaint_of`.
|
||||
fn wakeup_runs_after_the_slot_lock_is_released() {
|
||||
let ctx = Context::default();
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 1024);
|
||||
let slot = Arc::new(slot);
|
||||
let weak_slot = Arc::downgrade(&slot);
|
||||
let observed = Arc::new(AtomicBool::new(false));
|
||||
let lock_free = Arc::new(AtomicBool::new(true));
|
||||
let taken = Arc::new(AtomicBool::new(false));
|
||||
let observer_observed = observed.clone();
|
||||
let observer_lock_free = lock_free.clone();
|
||||
let observer_taken = taken.clone();
|
||||
ctx.set_repaint_observer(move |info| {
|
||||
if info.viewport_id == ViewportId::ROOT {
|
||||
observer_observed.store(true, Ordering::SeqCst);
|
||||
if let Some(slot) = weak_slot.upgrade() {
|
||||
if slot.lock_is_free() {
|
||||
observer_taken.store(slot.take().is_some(), Ordering::SeqCst);
|
||||
} else {
|
||||
observer_lock_free.store(false, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
callback.complete(image([1, 1], egui::Color32::RED));
|
||||
|
||||
assert!(observed.load(Ordering::SeqCst), "completion wakes the owning viewport");
|
||||
assert!(lock_free.load(Ordering::SeqCst), "the slot lock is released before the wakeup");
|
||||
assert!(taken.load(Ordering::SeqCst), "the observer can consume the image reentrantly");
|
||||
assert!(slot.take().is_none());
|
||||
}
|
||||
|
||||
/// Complete, cancel and take all racing on one slot. Every interleaving must leave at most one
|
||||
/// wake and at most one taken result, and every image must be released once the slot and result
|
||||
/// are dropped.
|
||||
#[test]
|
||||
fn complete_cancel_and_take_race_without_retaining_or_double_waking() {
|
||||
const RACE_TRIALS: usize = 100;
|
||||
|
||||
for trial in 0..RACE_TRIALS {
|
||||
let ctx = Context::default();
|
||||
let requests = observe_repaints(&ctx);
|
||||
let viewport = ViewportId::from_hash_of("race-window");
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, viewport, 4096);
|
||||
let slot = Arc::new(slot);
|
||||
let completed = image([1, 1], egui::Color32::RED);
|
||||
let weak_image = Arc::downgrade(&completed);
|
||||
let barrier = Arc::new(Barrier::new(3));
|
||||
|
||||
let taken = std::thread::scope(|scope| {
|
||||
let completion_barrier = barrier.clone();
|
||||
let completion_image = completed.clone();
|
||||
scope.spawn(move || {
|
||||
completion_barrier.wait();
|
||||
callback.complete(completion_image);
|
||||
});
|
||||
|
||||
let cancel_barrier = barrier.clone();
|
||||
let cancel_slot = slot.clone();
|
||||
scope.spawn(move || {
|
||||
cancel_barrier.wait();
|
||||
cancel_slot.cancel();
|
||||
});
|
||||
|
||||
barrier.wait();
|
||||
slot.take()
|
||||
});
|
||||
|
||||
let wake_count = requests.lock().unwrap().len();
|
||||
assert!(wake_count <= 1, "trial {trial}: one completion wakes at most once, got {wake_count}");
|
||||
if taken.is_some() {
|
||||
assert_eq!(wake_count, 1, "trial {trial}: a published result wakes exactly once");
|
||||
}
|
||||
if let Some(result) = &taken {
|
||||
match result {
|
||||
Ok(taken_image) => assert!(Arc::ptr_eq(taken_image, &completed), "trial {trial}: only the completed image is returned"),
|
||||
Err(error) => panic!("trial {trial}: a valid image was rejected: {error:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
drop(taken);
|
||||
drop(slot);
|
||||
drop(completed);
|
||||
assert!(weak_image.upgrade().is_none(), "trial {trial}: the slot and any taken result release the image");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// A zero byte budget rejects any nonempty image as too large and wakes once.
|
||||
fn zero_budget_rejects_a_nonempty_image_and_wakes() {
|
||||
let ctx = Context::default();
|
||||
let requests = observe_repaints(&ctx);
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 0);
|
||||
callback.complete(image([1, 1], egui::Color32::GREEN));
|
||||
assert!(matches!(slot.take(), Some(Err(CaptureError::ImageTooLarge { bytes: 4, max_bytes: 0 }))));
|
||||
assert_eq!(*requests.lock().unwrap(), [ViewportId::ROOT]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Two threads racing on `take` produce exactly one result, and a subsequent take is empty.
|
||||
fn concurrent_takers_receive_the_result_exactly_once() {
|
||||
let ctx = Context::default();
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, ViewportId::ROOT, 4);
|
||||
let expected = image([1, 1], egui::Color32::GREEN);
|
||||
callback.complete(expected.clone());
|
||||
let barrier = Barrier::new(3);
|
||||
let results = std::thread::scope(|scope| {
|
||||
let first = scope.spawn(|| {
|
||||
barrier.wait();
|
||||
slot.take()
|
||||
});
|
||||
let second = scope.spawn(|| {
|
||||
barrier.wait();
|
||||
slot.take()
|
||||
});
|
||||
barrier.wait();
|
||||
[first.join().unwrap(), second.join().unwrap()]
|
||||
});
|
||||
assert_eq!(results.iter().filter(|result| result.is_some()).count(), 1);
|
||||
for result in results.into_iter().flatten() {
|
||||
assert!(Arc::ptr_eq(&result.unwrap(), &expected));
|
||||
}
|
||||
assert!(slot.take().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// A renderer thread can complete a capture while a UI closure is blocked; the image is delivered
|
||||
/// and the owning child viewport is woken exactly once.
|
||||
fn renderer_completion_during_a_live_ui_pass_can_wake_and_deliver() {
|
||||
let ctx = Context::default();
|
||||
let requests = observe_repaints(&ctx);
|
||||
let viewport = ViewportId::from_hash_of("render-readback");
|
||||
let (slot, callback) = CaptureSlot::new(&ctx, viewport, 4);
|
||||
let expected = image([1, 1], egui::Color32::GREEN);
|
||||
let sent = expected.clone();
|
||||
let (start_tx, start_rx) = std::sync::mpsc::channel();
|
||||
let (done_tx, done_rx) = std::sync::mpsc::channel();
|
||||
std::thread::scope(|scope| {
|
||||
scope.spawn(move || {
|
||||
start_rx.recv().unwrap();
|
||||
callback.complete(sent);
|
||||
done_tx.send(()).unwrap();
|
||||
});
|
||||
let mut start_tx = Some(start_tx);
|
||||
let mut output = ctx.run_ui(Default::default(), |ui| {
|
||||
ui.label("A live frame while readback completes");
|
||||
if let Some(tx) = start_tx.take() {
|
||||
tx.send(()).unwrap();
|
||||
done_rx.recv_timeout(std::time::Duration::from_secs(3)).expect("readback must complete while the UI closure is active");
|
||||
}
|
||||
});
|
||||
// This synchronization test has no renderer to apply the atlas upload.
|
||||
output.textures_delta.clear();
|
||||
});
|
||||
assert!(Arc::ptr_eq(&slot.take().unwrap().unwrap(), &expected));
|
||||
assert_eq!(requests.lock().unwrap().iter().filter(|id| **id == viewport).count(), 1);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
//! The drop-down menu of the ribbon's combo fields (font name and size): a menu under a field that
|
||||
//! scrolls its rows and can keep a header (the filter field) in place above them.
|
||||
|
||||
use egui::{Frame, Popup, PopupCloseBehavior, RectAlign, Response, ScrollArea, TextWrapMode, Ui};
|
||||
|
||||
/// A menu under a field that opens and closes on the field's clicks, closes on a click, and opens
|
||||
/// below the field or above it, never beside it.
|
||||
pub(crate) struct Menu<'a> {
|
||||
popup: Popup<'a>,
|
||||
field: egui::Rect,
|
||||
height: f32,
|
||||
}
|
||||
|
||||
impl<'a> Menu<'a> {
|
||||
/// The menu under `field`, a widget in `ui`.
|
||||
pub(crate) fn new(ui: &Ui, field: &Response) -> Self {
|
||||
let flipped: &'static [RectAlign] = if ui.ctx().global_style().right_to_left { &[RectAlign::TOP_END] } else { &[RectAlign::TOP_START] };
|
||||
Self { popup: Popup::menu(field).align_alternatives(flipped), field: field.rect, height: ui.spacing().combo_height }
|
||||
}
|
||||
|
||||
/// The most height of the menu's contents, inside its frame; the room on the field's roomier
|
||||
/// side caps it.
|
||||
pub(crate) fn height(mut self, height: f32) -> Self {
|
||||
self.height = height;
|
||||
self
|
||||
}
|
||||
|
||||
/// Shows `add` in the menu while it is open, scrolling when it is taller than the menu.
|
||||
/// Returns what `add` returned, or `None` while the menu is closed.
|
||||
pub(crate) fn show_ui<R>(self, add: impl FnOnce(&mut Ui) -> R) -> Option<R> {
|
||||
self.show(|_| (), |ui, ()| add(ui))
|
||||
}
|
||||
|
||||
/// Shows `header` at the top of the menu and `list` under it while the menu is open, and
|
||||
/// returns what `list` returned. `list` gets what `header` returned. Only `list` scrolls; the
|
||||
/// header stays in place.
|
||||
pub(crate) fn show_ui_with_header<H, R>(self, header: impl FnOnce(&mut Ui) -> H, list: impl FnOnce(&mut Ui, H) -> R) -> Option<R> {
|
||||
self.show(header, list)
|
||||
}
|
||||
|
||||
fn show<H, R>(self, header: impl FnOnce(&mut Ui) -> H, list: impl FnOnce(&mut Ui, H) -> R) -> Option<R> {
|
||||
let Self { popup, field, height } = self;
|
||||
let ctx = popup.ctx().clone();
|
||||
let screen = ctx.content_rect();
|
||||
let room = (screen.bottom() - field.bottom()).max(field.top() - screen.top());
|
||||
let style = egui::style::StyleModifier::from(egui::containers::menu::menu_style);
|
||||
let mut popup_style = (*ctx.global_style()).clone();
|
||||
style.apply(&mut popup_style);
|
||||
let frame = Frame::popup(&popup_style).total_margin().sum().y;
|
||||
let height = height.min(room - frame).max(0.0);
|
||||
popup
|
||||
.width(field.width())
|
||||
.style(style)
|
||||
.close_behavior(PopupCloseBehavior::CloseOnClick)
|
||||
.show(|ui| {
|
||||
ui.set_min_width(ui.available_width());
|
||||
// egui offers the popup last pass's height; offer the full height so a list that
|
||||
// shrank (a filter with no matches) grows back.
|
||||
ui.set_max_height(height);
|
||||
let header = header(ui);
|
||||
// Labels widen a narrow menu rather than wrap early, as in egui's combo box.
|
||||
ui.style_mut().wrap_mode = Some(TextWrapMode::Extend);
|
||||
ScrollArea::vertical().max_height(ui.available_height().max(0.0)).show(ui, |ui| list(ui, header)).inner
|
||||
})
|
||||
.map(|shown| shown.inner)
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@
|
||||
|
||||
use std::sync::mpsc::Sender;
|
||||
|
||||
use craft_ui::capture::CaptureSlot;
|
||||
use crate::capture::CaptureSlot;
|
||||
use gridcraft_engine::core::CellRef;
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ pub fn place(app: &mut SheetApp, ui: &Ui, resp: &egui::Response, geo: &Geo, sh:
|
||||
return false;
|
||||
};
|
||||
let ctx = ui.ctx().clone();
|
||||
if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
if crate::framework::escape_pressed(&ctx) {
|
||||
app.grid.placing = None;
|
||||
app.grid.place_start = None;
|
||||
return true;
|
||||
|
||||
@@ -186,7 +186,7 @@ pub(super) fn place_window<'a>(
|
||||
// Escape and Enter are used up either way: left in the frame's input, the dialog would
|
||||
// read them as its own and close or confirm. When another field owned them, that field
|
||||
// (drawn before the dialogs) has read them already, and nothing more happens here.
|
||||
if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape) | i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) {
|
||||
if crate::framework::consume_escape(&ctx) | ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) {
|
||||
if !other_field {
|
||||
d.refs.collapsed = None;
|
||||
}
|
||||
|
||||
@@ -400,7 +400,7 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
open_url(&u);
|
||||
}
|
||||
}
|
||||
if ctx.input(|i| i.key_pressed(Key::Escape)) || !win_open {
|
||||
if crate::framework::escape_pressed(&ctx) || !win_open {
|
||||
// In Solver Options, Escape (or closing the window) cancels the options only.
|
||||
if in_solver_options(&d) {
|
||||
cancel_solver_options(&mut d);
|
||||
|
||||
@@ -18,10 +18,12 @@
|
||||
//!
|
||||
//! [`Session::windows`]: gridcraft_engine::Session::windows
|
||||
|
||||
use craft_window::{CASCADE_STEP, Frame, Rect, Viewports, WindowEvent, WindowId, WindowList, cascade};
|
||||
use craft_window::{WindowId, WindowList};
|
||||
use egui::Rect;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::SheetApp;
|
||||
use crate::viewports::{CASCADE_STEP, Viewports, WindowEvent};
|
||||
|
||||
/// The native windows (see the module docs).
|
||||
pub struct DocWindows {
|
||||
@@ -40,8 +42,7 @@ impl DocWindows {
|
||||
/// Takes over `app`'s windows. `base` is the root window's builder, used for new windows.
|
||||
pub fn new(app: &mut SheetApp, base: egui::ViewportBuilder, quit_with_last_window: bool) -> DocWindows {
|
||||
app.native_windows = true;
|
||||
// The root window keeps the desktop's frame, so every window does.
|
||||
DocWindows { list: WindowList::new(), viewports: Viewports::new(Frame::Desktop), base, quit_with_last_window, root_hidden: false }
|
||||
DocWindows { list: WindowList::new(), viewports: Viewports::default(), base, quit_with_last_window, root_hidden: false }
|
||||
}
|
||||
|
||||
/// The platform default for the last window closing: macOS keeps running, others quit.
|
||||
@@ -91,7 +92,7 @@ impl DocWindows {
|
||||
let (monitor, infos) = ctx.input(|i| (i.viewport().monitor_size, i.raw.viewports.clone()));
|
||||
// Platforms that don't report the monitor (Wayland, tests) get a common laptop screen.
|
||||
let size = monitor.filter(|m| m.x > 0.0 && m.y > 0.0).unwrap_or(egui::vec2(1280.0, 800.0));
|
||||
let mut rects = arrange_rects(arrange, ids.len(), Rect::new(0.0, 0.0, size.x, size.y));
|
||||
let mut rects = arrange_rects(arrange, ids.len(), Rect::from_min_size(egui::Pos2::ZERO, size));
|
||||
if arrange == "cascade" {
|
||||
// The active window goes in front: the last step of the cascade.
|
||||
rects.reverse();
|
||||
@@ -100,8 +101,8 @@ impl DocWindows {
|
||||
let vp = self.viewports.viewport_id(*id);
|
||||
// Inner size is what can be set: take off the frame the window has now.
|
||||
let frame = infos.get(&vp).and_then(|v| Some(v.outer_rect?.size() - v.inner_rect?.size())).unwrap_or(egui::Vec2::ZERO);
|
||||
ctx.send_viewport_cmd_to(vp, egui::ViewportCommand::OuterPosition(egui::pos2(r.x, r.y)));
|
||||
ctx.send_viewport_cmd_to(vp, egui::ViewportCommand::InnerSize((egui::vec2(r.width, r.height) - frame).max(egui::vec2(240.0, 160.0))));
|
||||
ctx.send_viewport_cmd_to(vp, egui::ViewportCommand::OuterPosition(r.min));
|
||||
ctx.send_viewport_cmd_to(vp, egui::ViewportCommand::InnerSize((r.size() - frame).max(egui::vec2(240.0, 160.0))));
|
||||
}
|
||||
if let Some(first) = ids.first() {
|
||||
self.viewports.focus(ctx, *first);
|
||||
@@ -123,7 +124,7 @@ impl DocWindows {
|
||||
// The window the engine brought forward, else the most recently focused.
|
||||
let next = app.session.active_window().and_then(|w| self.find(w)).or_else(|| self.list.active());
|
||||
match next {
|
||||
Some(id) => self.viewports.adopt(ctx, &self.list, id),
|
||||
Some(id) => self.viewports.adopt(ctx, id),
|
||||
None => self.viewports.set_root(None),
|
||||
}
|
||||
}
|
||||
@@ -205,7 +206,7 @@ impl DocWindows {
|
||||
match event {
|
||||
WindowEvent::Focused(_) => {}
|
||||
WindowEvent::CloseRequested(id) => {
|
||||
if let Some(w) = self.close_requested(app, &ctx, id) {
|
||||
if let Some(w) = self.close_requested(app, id) {
|
||||
requested = Some(w);
|
||||
}
|
||||
}
|
||||
@@ -228,16 +229,13 @@ impl DocWindows {
|
||||
|
||||
/// A window's close button. Returns the window to bring forward when the close needs an
|
||||
/// answer (or moved focus); `None` when nothing changed.
|
||||
fn close_requested(&mut self, app: &mut SheetApp, ctx: &egui::Context, id: WindowId) -> Option<u64> {
|
||||
let is_root = self.viewports.root() == Some(id);
|
||||
/// The root window's close request is held by the app's close path ([`SheetApp::close_decision`]),
|
||||
/// so closing it closes only its workbook window, as for any other window.
|
||||
fn close_requested(&mut self, app: &mut SheetApp, id: WindowId) -> Option<u64> {
|
||||
if app.allow_close {
|
||||
// Quitting: every workbook has been answered for; the root's close ends the app.
|
||||
return None;
|
||||
}
|
||||
if is_root {
|
||||
// eframe would end the app with the root window; closing it is the app's decision.
|
||||
ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::CancelClose);
|
||||
}
|
||||
let window = *self.list.get(id)?;
|
||||
app.enter_window(window);
|
||||
app.run_or_alert("window.close", json!({"window": window}));
|
||||
@@ -271,34 +269,28 @@ pub fn arrange_rects(arrange: &str, n: usize, bounds: Rect) -> Vec<Rect> {
|
||||
let count = n as f32;
|
||||
match arrange {
|
||||
"horizontal" => {
|
||||
let h = bounds.height / count;
|
||||
(0..n).map(|i| Rect::new(bounds.x, bounds.y + h * i as f32, bounds.width, h)).collect()
|
||||
let h = bounds.height() / count;
|
||||
(0..n).map(|i| Rect::from_min_size(bounds.min + egui::vec2(0.0, h * i as f32), egui::vec2(bounds.width(), h))).collect()
|
||||
}
|
||||
"vertical" => {
|
||||
let w = bounds.width / count;
|
||||
(0..n).map(|i| Rect::new(bounds.x + w * i as f32, bounds.y, w, bounds.height)).collect()
|
||||
let w = bounds.width() / count;
|
||||
(0..n).map(|i| Rect::from_min_size(bounds.min + egui::vec2(w * i as f32, 0.0), egui::vec2(w, bounds.height()))).collect()
|
||||
}
|
||||
"cascade" => {
|
||||
let shift = CASCADE_STEP * (count - 1.0);
|
||||
let size = [(bounds.width - shift).max(bounds.width * 0.5), (bounds.height - shift).max(bounds.height * 0.5)];
|
||||
let mut previous = Rect::new(bounds.x - CASCADE_STEP, bounds.y - CASCADE_STEP, size[0], size[1]);
|
||||
(0..n)
|
||||
.map(|_| {
|
||||
previous = cascade(previous, size, bounds, CASCADE_STEP);
|
||||
previous
|
||||
})
|
||||
.collect()
|
||||
let size = egui::vec2((bounds.width() - shift).max(bounds.width() * 0.5), (bounds.height() - shift).max(bounds.height() * 0.5));
|
||||
craft_behavior::placement::cascade_rects(bounds, size, n, CASCADE_STEP)
|
||||
}
|
||||
_ => {
|
||||
let cols = (count.sqrt().ceil() as usize).max(1);
|
||||
let rows = n.div_ceil(cols);
|
||||
let h = bounds.height / rows as f32;
|
||||
let h = bounds.height() / rows as f32;
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let (row, col) = (i / cols, i % cols);
|
||||
let in_row = if row + 1 == rows { n - row * cols } else { cols };
|
||||
let w = bounds.width / in_row as f32;
|
||||
Rect::new(bounds.x + w * col as f32, bounds.y + h * row as f32, w, h)
|
||||
let w = bounds.width() / in_row as f32;
|
||||
Rect::from_min_size(bounds.min + egui::vec2(w * col as f32, h * row as f32), egui::vec2(w, h))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
//! The craft-ui runtime, hosted from GridCraft's own eframe `App` (craft-libs docs/craft-framework.md, section 2.2).
|
||||
//! The desktop app calls [`install`] once, [`SheetApp::before_input`] in `raw_input_hook`, [`SheetApp::close_path`]
|
||||
//! last in `logic`, and [`before_ui`] first in `ui`; the browser build and tests install with [`install_headless`].
|
||||
//! The framework dialogs run on [`SheetApp::framework_dialogs`] after GridCraft's own UI.
|
||||
//!
|
||||
//! The runtime takes Escape, Tab and the clipboard events for the whole window unless one of GridCraft's own egui
|
||||
//! widgets has the keyboard. The window's Escape is read with [`escape_pressed`] and taken with [`consume_escape`];
|
||||
//! the grid is declared to the runtime with [`host_canvas`], which keeps Tab, the edit chords and the clipboard
|
||||
//! events in egui's input for GridCraft's shortcuts.
|
||||
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use craft_host::target::ShellInfo;
|
||||
use craft_host::{AppInfo, Host};
|
||||
use craft_keymap::Overrides;
|
||||
use craft_ui::fonts::{I18nScripts, SystemFonts, UiFonts};
|
||||
use craft_ui::runtime::commands::{CommandInput, CommandSet as _, QuitCommand};
|
||||
use craft_ui::runtime::env::{RootEnv, Scale};
|
||||
use craft_ui::runtime::focus::{EditSet, KeepKeys, KeyUse};
|
||||
use craft_ui::runtime::frame::{FrameInput, FrameOutput};
|
||||
use craft_ui::runtime::keys::{Intent, with_window_intents};
|
||||
use craft_ui::shell::embed;
|
||||
use craft_window::system::WindowSystem;
|
||||
|
||||
use crate::SheetApp;
|
||||
|
||||
/// Each pass of the root window, first in `App::ui`: hands the runtime the native window it answers the hit test of
|
||||
/// (Windows) and fits the window to its monitor once.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use craft_ui::shell::embed::before_ui;
|
||||
|
||||
/// The id every OS window of the app carries, as the main window's builder sets it.
|
||||
const APP_ID: &str = "ai.storyteller.gridcraft";
|
||||
|
||||
/// The scripts of the interface languages, for the font stack.
|
||||
static SCRIPTS: I18nScripts = I18nScripts;
|
||||
|
||||
/// The runtime's first font stack: egui's bundled faces and no installed system fonts. GridCraft's own definitions
|
||||
/// ([`SheetApp::setup_context_for_language`]) replace it before anything is drawn.
|
||||
fn ui_fonts() -> UiFonts<'static> {
|
||||
UiFonts::new(&SCRIPTS).system_fonts(SystemFonts::Off)
|
||||
}
|
||||
|
||||
fn install_with(ctx: &egui::Context, shell: ShellInfo, windows: Arc<dyn WindowSystem>) -> Result<(), String> {
|
||||
let spec = craft_ui::InstallSpec::new(shell, windows).app_id(APP_ID);
|
||||
embed::install(ctx, spec, &ui_fonts()).map(drop).map_err(|error| format!("the UI runtime could not be installed: {error}"))
|
||||
}
|
||||
|
||||
/// Installs the runtime on the desktop window's context, once, before the first pass. GridCraft draws its own title
|
||||
/// bar (and, where the desktop leaves the frame to the app, its own window buttons), so no frame decision is handed
|
||||
/// over and the runtime answers no hit test of the window.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn install(ctx: &egui::Context) -> Result<(), String> {
|
||||
let shell = ShellInfo::default().backend(craft_host::target::Backend::from_env());
|
||||
install_with(ctx, shell, Arc::new(craft_window::system::SystemWindows))
|
||||
}
|
||||
|
||||
/// Installs the runtime on a context with no native window of its own: the browser build's canvas and test windows.
|
||||
pub fn install_headless(ctx: &egui::Context) {
|
||||
if let Err(error) = install_with(ctx, ShellInfo::default(), Arc::new(craft_window::system::NoWindows)) {
|
||||
log::warn!("{error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Who GridCraft is to the framework's dialogs (the update dialogs show its name and icon).
|
||||
pub(crate) fn host() -> Arc<Host> {
|
||||
Arc::new(
|
||||
Host::builder(AppInfo { id: "gridcraft", name: "GridCraft", version: env!("CARGO_PKG_VERSION") })
|
||||
.icon_png(include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.gridcraft.png"))
|
||||
.build(),
|
||||
)
|
||||
}
|
||||
|
||||
/// GridCraft quits through its own Quit (the macOS app menu, the last window closing, an update's restart), which
|
||||
/// asks about every unsaved workbook in its window, and Ctrl+Q is no quit key on Windows and Linux (Excel's Quick
|
||||
/// Analysis), so the framework's `window.quit` is unbound. Overrides are keyed by command id, which the command set
|
||||
/// gives.
|
||||
fn command_overrides() -> Arc<Overrides> {
|
||||
static OVERRIDES: OnceLock<Arc<Overrides>> = OnceLock::new();
|
||||
OVERRIDES
|
||||
.get_or_init(|| {
|
||||
let mut overrides = Overrides::new();
|
||||
overrides.insert(QuitCommand::Quit.id(), Vec::new());
|
||||
Arc::new(overrides)
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
impl SheetApp {
|
||||
/// The framework's part of `App::raw_input_hook`, once per frame before the first pass: takes what the runtime
|
||||
/// gathered since the last frame and gives the coming passes the root values (theme mode, interface scale).
|
||||
pub fn before_input(&mut self, ctx: &egui::Context) {
|
||||
embed::before_input(ctx, |output| self.frame_input(output));
|
||||
}
|
||||
|
||||
/// The root values of this frame. GridCraft registers no commands with the runtime (it unbinds the framework's
|
||||
/// quit, [`command_overrides`]) and lets it toggle no chrome, so the output carries nothing it acts on. The
|
||||
/// interface scale is the Interface Size preference: the runtime is the one writer of egui's zoom factor.
|
||||
fn frame_input(&mut self, _output: FrameOutput) -> FrameInput {
|
||||
let mode = if self.effective_dark { craft_theme::Mode::Dark } else { craft_theme::Mode::Light };
|
||||
let root = RootEnv::new().mode(mode).scale(Scale::new(self.ui.zoom_factor()));
|
||||
FrameInput::new(root).commands(CommandInput::new().overrides(command_overrides())).host(Arc::clone(&self.framework_host))
|
||||
}
|
||||
|
||||
/// The framework's part of `App::logic`, last, after GridCraft's own logic and the native windows': the root
|
||||
/// window's close path, decided by [`SheetApp::close_decision`].
|
||||
pub fn close_path(&mut self, ctx: &egui::Context) {
|
||||
embed::logic(ctx, || self.close_decision(ctx));
|
||||
}
|
||||
|
||||
/// The framework dialogs open on [`SheetApp::framework_dialogs`], once per frame after GridCraft's own UI.
|
||||
pub(crate) fn run_framework_dialogs(&mut self, ui: &mut egui::Ui) {
|
||||
self.framework_dialogs.run(ui);
|
||||
}
|
||||
}
|
||||
|
||||
/// Declares the grid `id`, drawn in this pass, as the window's document canvas. With nothing focused it is the
|
||||
/// window's key target: Tab, the edit chords and the clipboard events stay in egui's input for GridCraft's shortcuts,
|
||||
/// as do the arrows, Enter and the page keys.
|
||||
pub(crate) fn host_canvas(ctx: &egui::Context, id: egui::Id) {
|
||||
const KEYS: KeyUse = KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(EditSet::ALL);
|
||||
craft_ui::runtime::focus::host_canvas(ctx, id, KEYS);
|
||||
}
|
||||
|
||||
/// Whether Escape was pressed in this pass: from egui while one of GridCraft's own widgets or popups has the
|
||||
/// keyboard, otherwise the window's cancel, which the runtime routes to no component. Leaves it for later readers.
|
||||
pub(crate) fn escape_pressed(ctx: &egui::Context) -> bool {
|
||||
ctx.input(|i| i.key_pressed(egui::Key::Escape)) || window_cancel(ctx, false)
|
||||
}
|
||||
|
||||
/// Takes a plain Escape pressed in this pass, from egui or as the window's cancel: no later reader sees it.
|
||||
pub(crate) fn consume_escape(ctx: &egui::Context) -> bool {
|
||||
ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) || take_window_cancel(ctx)
|
||||
}
|
||||
|
||||
/// Takes the window's cancel (an Escape while nothing has framework focus) when it is there: no later reader sees it.
|
||||
pub(crate) fn take_window_cancel(ctx: &egui::Context) -> bool {
|
||||
window_cancel(ctx, true)
|
||||
}
|
||||
|
||||
/// Whether the window's cancel is there and untaken; `take` takes it.
|
||||
fn window_cancel(ctx: &egui::Context, take: bool) -> bool {
|
||||
let mut pending = false;
|
||||
with_window_intents(ctx, false, |intents| {
|
||||
pending = if take { intents.take(Intent::Cancel) } else { intents.untaken(&Intent::Cancel) };
|
||||
take && pending
|
||||
});
|
||||
pending
|
||||
}
|
||||
@@ -648,19 +648,22 @@ fn handle_context_menu_and_keyboard(app: &mut SheetApp, input: &InteractionInput
|
||||
if primary_clicked || resp.drag_started() {
|
||||
resp.request_focus();
|
||||
}
|
||||
crate::framework::host_canvas(&ctx, resp.id);
|
||||
keyboard(app, &ctx, resp, geo, sh);
|
||||
}
|
||||
|
||||
/// Whether Esc was pressed this frame, with any modifiers; every Esc press is then spent, so the
|
||||
/// grid's own Esc doesn't also drop a pending copy or Format Painter.
|
||||
/// Whether Esc was pressed this frame, with any modifiers, in egui's input or as the window's
|
||||
/// cancel; every Esc press is then spent, so the grid's own Esc doesn't also drop a pending copy or
|
||||
/// Format Painter.
|
||||
fn spend_escape(ctx: &egui::Context) -> bool {
|
||||
ctx.input_mut(|i| {
|
||||
let in_egui = ctx.input_mut(|i| {
|
||||
let pressed = i.key_pressed(egui::Key::Escape);
|
||||
if pressed {
|
||||
i.events.retain(|e| !matches!(e, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }));
|
||||
}
|
||||
pressed
|
||||
})
|
||||
});
|
||||
in_egui || crate::framework::take_window_cancel(ctx)
|
||||
}
|
||||
|
||||
fn handle_dragging(app: &mut SheetApp, input: &InteractionInput<'_>) {
|
||||
@@ -810,7 +813,7 @@ fn handle_release(app: &mut SheetApp, input: &InteractionInput<'_>) {
|
||||
Drag::Fill { target: Some(t), menu: true } => {
|
||||
if let Some(p) = pos
|
||||
&& t != sel.current()
|
||||
&& !ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
|
||||
&& !crate::framework::consume_escape(&ctx)
|
||||
{
|
||||
app.grid.fill_menu = Some((sel.current(), t, geo.mirror_pos(p)));
|
||||
}
|
||||
|
||||
@@ -221,7 +221,7 @@ pub(super) fn context_menu(app: &mut SheetApp, ui: &mut egui::Ui) {
|
||||
// menu, so it doesn't count as a click elsewhere.
|
||||
let opened_now = app.grid.context_menu_frame == ui.ctx().cumulative_frame_nr();
|
||||
if close
|
||||
|| ui.input(|i| i.key_pressed(egui::Key::Escape))
|
||||
|| crate::framework::escape_pressed(ui.ctx())
|
||||
|| (!opened_now
|
||||
&& ui.input(|i| i.pointer.any_pressed())
|
||||
&& !resp.response.contains_pointer()
|
||||
@@ -428,7 +428,7 @@ pub(super) fn object_menu(app: &mut SheetApp, ui: &mut egui::Ui) {
|
||||
});
|
||||
});
|
||||
if close
|
||||
|| ui.input(|i| i.key_pressed(egui::Key::Escape))
|
||||
|| crate::framework::escape_pressed(ui.ctx())
|
||||
|| (ui.input(|i| i.pointer.any_pressed())
|
||||
&& !resp.response.contains_pointer()
|
||||
&& !resp.response.hovered()
|
||||
|
||||
@@ -120,15 +120,7 @@ impl KeyTips {
|
||||
} else if self.prefix.is_some() && !matches!(key, Key::ShiftLeft | Key::ShiftRight) {
|
||||
handled = true;
|
||||
if *key == Key::Escape {
|
||||
// Escape pops one level; at a single-letter level it
|
||||
// returns to the armed root (empty prefix).
|
||||
if let Some(prefix) = self.prefix.as_mut() {
|
||||
if prefix.is_empty() {
|
||||
self.prefix = None;
|
||||
} else {
|
||||
prefix.pop();
|
||||
}
|
||||
}
|
||||
self.back();
|
||||
} else if key.name().len() == 1 {
|
||||
let next = format!("{}{key_name}", self.prefix.as_deref().unwrap_or_default(), key_name = key.name());
|
||||
match keytip_table::lookup(&next) {
|
||||
@@ -171,9 +163,25 @@ impl KeyTips {
|
||||
ctx.input_mut(|i| {
|
||||
i.events = events.into_iter().enumerate().filter_map(|(index, event)| (!consumed.contains(&index)).then_some(event)).collect()
|
||||
});
|
||||
// With none of GridCraft's widgets focused (the File view), the runtime takes Escape as the
|
||||
// window's cancel.
|
||||
if self.prefix.is_some() && crate::framework::take_window_cancel(ctx) {
|
||||
self.back();
|
||||
}
|
||||
actions
|
||||
}
|
||||
|
||||
/// Escape pops one level; at a single-letter level it returns to the armed root (empty prefix).
|
||||
fn back(&mut self) {
|
||||
if let Some(prefix) = self.prefix.as_mut() {
|
||||
if prefix.is_empty() {
|
||||
self.prefix = None;
|
||||
} else {
|
||||
prefix.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(&mut self, action: Action, actions: &mut Vec<Action>) {
|
||||
self.prefix = None;
|
||||
actions.push(action);
|
||||
|
||||
@@ -17,10 +17,12 @@ pub const UPDATE_APP: craft_update::app::App = craft_update::app::App {
|
||||
|
||||
pub mod backstage;
|
||||
mod border_preview;
|
||||
mod capture;
|
||||
mod cell_pictures;
|
||||
mod chartcache;
|
||||
pub mod chartview;
|
||||
pub mod code_editor;
|
||||
mod combo_menu;
|
||||
pub mod control;
|
||||
pub mod control_ui;
|
||||
mod craft_fonts_policy;
|
||||
@@ -37,6 +39,7 @@ pub mod form_controls;
|
||||
pub mod formula_bar;
|
||||
mod formula_locale;
|
||||
pub mod frame;
|
||||
pub mod framework;
|
||||
pub mod function_library;
|
||||
pub mod grid;
|
||||
pub mod i18n;
|
||||
@@ -59,6 +62,7 @@ mod text_direction;
|
||||
pub mod theme;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod updates_ui;
|
||||
mod viewports;
|
||||
pub mod widgets;
|
||||
mod window_ui;
|
||||
pub mod wordart;
|
||||
@@ -347,6 +351,11 @@ pub struct SheetApp {
|
||||
/// The update check, the startup prompt and a running self-update (desktop only).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
updates_rt: updates_ui::Runtime,
|
||||
/// The framework dialogs GridCraft keeps as values (the update dialogs), run once per frame
|
||||
/// after GridCraft's own UI in the root window's pass.
|
||||
pub framework_dialogs: craft_ui::dialog::DialogHost,
|
||||
/// Who GridCraft is to the framework's dialogs.
|
||||
framework_host: std::sync::Arc<craft_host::Host>,
|
||||
}
|
||||
|
||||
/// Strips the engine's error prefixes for message boxes.
|
||||
|
||||
@@ -959,7 +959,7 @@ pub fn window(app: &mut SheetApp, ctx: &egui::Context, d: &mut Dialog, open: &mu
|
||||
*open = false;
|
||||
}
|
||||
}
|
||||
if ctx.input(|i| i.key_pressed(egui::Key::Escape)) && ed.picker.is_some() {
|
||||
if crate::framework::escape_pressed(&ctx) && ed.picker.is_some() {
|
||||
ed.picker = None;
|
||||
}
|
||||
prompts(app, ctx, &mut ed, open);
|
||||
@@ -1110,7 +1110,7 @@ fn prompts(app: &mut SheetApp, ctx: &egui::Context, ed: &mut Editor, open: &mut
|
||||
ui.label("Keep the changes the macro has made so far? They are one undo step either way.");
|
||||
ui.add_space(8.0);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button("Cancel").clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
if ui.button("Cancel").clicked() || crate::framework::escape_pressed(ui.ctx()) {
|
||||
answer = Some(None);
|
||||
}
|
||||
if ui.button("Undo Changes").clicked() {
|
||||
@@ -1147,7 +1147,7 @@ fn prompts(app: &mut SheetApp, ctx: &egui::Context, ed: &mut Editor, open: &mut
|
||||
ui.label(egui::RichText::new(format!("Save changes to macro “{}”?", ed.draft.name)).strong());
|
||||
ui.add_space(8.0);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button("Cancel").clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
if ui.button("Cancel").clicked() || crate::framework::escape_pressed(ui.ctx()) {
|
||||
answer = Some(None);
|
||||
}
|
||||
if ui.button("Don't Save").clicked() {
|
||||
|
||||
@@ -216,7 +216,7 @@ pub fn question_box(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
ui.add(egui::Label::new(&q.text).wrap());
|
||||
ui.add_space(8.0);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button("Cancel").clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
if ui.button("Cancel").clicked() || crate::framework::escape_pressed(ui.ctx()) {
|
||||
answer = Some(None);
|
||||
}
|
||||
// Right to left: list the choices reversed, so the first one ends up next to Cancel
|
||||
|
||||
@@ -332,7 +332,7 @@ fn format_chart(app: &mut SheetApp, ui: &mut Ui) {
|
||||
let b = ui.add(egui::DragValue::new(&mut h).prefix("Height ").range(range(current.1)));
|
||||
if a.drag_stopped() || a.lost_focus() || b.drag_stopped() || b.lost_focus() {
|
||||
ui.data_mut(|d| d.remove::<(f32, f32)>(draft));
|
||||
if !ui.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
if !crate::framework::escape_pressed(ui.ctx()) {
|
||||
// Only an edited dimension is sent: the other keeps what the chart has, however
|
||||
// large a file made it.
|
||||
let mut params = serde_json::Map::new();
|
||||
@@ -363,7 +363,7 @@ fn chart_slider(ui: &mut Ui, draft: egui::Id, value: u32, range: std::ops::Range
|
||||
let r = ui.add(egui::Slider::new(&mut current, range).text(label));
|
||||
if r.drag_stopped() || r.clicked() || r.lost_focus() {
|
||||
ui.data_mut(|d| d.remove::<u32>(draft));
|
||||
if ui.input(|i| i.key_pressed(egui::Key::Escape)) || current == value { None } else { Some(current) }
|
||||
if crate::framework::escape_pressed(ui.ctx()) || current == value { None } else { Some(current) }
|
||||
} else if r.dragged() || r.has_focus() {
|
||||
ui.data_mut(|d| d.insert_temp(draft, current));
|
||||
None
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::{Align2, Color32, FontId, Key, Painter, Pos2, Rect, Stroke, StrokeKind, TextEdit, pos2, vec2};
|
||||
use egui::{Align2, Color32, FontId, Painter, Pos2, Rect, Stroke, StrokeKind, TextEdit, pos2, vec2};
|
||||
use gridcraft_engine::cf::CfCache;
|
||||
use gridcraft_engine::cmd::print::{self, HfContext};
|
||||
use gridcraft_engine::model::{HfPage, Sheet, SheetViewMode, Workbook};
|
||||
@@ -468,7 +468,7 @@ pub fn go_to(app: &mut SheetApp, footer: bool) {
|
||||
/// Edits a header/footer section across left/center/right, cancels on Esc, switches sections and preserves focus/caret while the page scrolls.
|
||||
fn editor(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, pg: &PageGrid) {
|
||||
let Some(mut e) = app.grid.hf_edit.take() else { return };
|
||||
if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) {
|
||||
if crate::framework::consume_escape(ui.ctx()) {
|
||||
app.grid.hf_edit = Some(e);
|
||||
cancel(app);
|
||||
return;
|
||||
@@ -823,7 +823,7 @@ fn ruler_margins(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, pg: &PageGrid
|
||||
ui.ctx().set_cursor_icon(if edge.horizontal() { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::ResizeVertical });
|
||||
};
|
||||
if let Some(d) = app.grid.ruler_drag.clone() {
|
||||
if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) {
|
||||
if crate::framework::consume_escape(ui.ctx()) {
|
||||
app.grid.ruler_drag = None;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,33 +1,27 @@
|
||||
//! Localized print-page wording around the shared, backend-independent controls.
|
||||
use craft_ui::printing::Labels;
|
||||
pub use craft_ui::printing::{Discover, Duplex, Feedback, Printer, Settings, State, Submit};
|
||||
//! The print page's printer controls (craft-print's `PrintPanel` over its `State`) and their
|
||||
//! localized feedback. The panel's own words come from the framework host.
|
||||
pub use craft_print::ui::{Destination, Discover, Duplex, Feedback, Printer, Settings, State, Submit};
|
||||
|
||||
/// Draws the shared print controls.
|
||||
/// Draws the shared print controls and the feedback of the last discovery or job.
|
||||
///
|
||||
/// `craft_ui::printing::State::show` also calls `poll`, so this path polls a second time on top of
|
||||
/// [`crate::SheetApp::poll_printing`] in `logic`. That poll is idempotent (it only drains worker
|
||||
/// messages into the same state), and the logic-side poll is what lets a hidden window and a
|
||||
/// logic-only frame see completion, so it stays. Splitting poll out of the shared `show` API is a
|
||||
/// craft-ui follow-up, not a GridCraft-local change.
|
||||
/// `State::run` also polls the workers, on top of [`crate::SheetApp::poll_printing`] in `logic`.
|
||||
/// That poll is idempotent (it only drains worker messages into the same state), and the
|
||||
/// logic-side poll is what lets a hidden window and a logic-only frame see completion, so it stays.
|
||||
pub fn show(state: &mut State, ui: &mut egui::Ui, discover: &Discover, translate: impl Fn(&str) -> String) {
|
||||
let labels = Labels {
|
||||
printer: &translate("Printer"),
|
||||
select_printer: &translate("Select a printer"),
|
||||
refresh: &translate("Refresh printers"),
|
||||
copies: &translate("Copies"),
|
||||
duplex: &translate("Two-sided printing"),
|
||||
printer_default: &translate("Printer default"),
|
||||
one_sided: &translate("One-sided"),
|
||||
long_edge: &translate("Two-sided: long edge"),
|
||||
short_edge: &translate("Two-sided: short edge"),
|
||||
grayscale: &translate("Grayscale"),
|
||||
};
|
||||
state.show(ui, egui::Id::unique("gridcraft_print_settings"), discover, &labels);
|
||||
ui.push_id("gridcraft_print_settings", |ui| state.run(ui, discover));
|
||||
if let Some(message) = &state.message {
|
||||
ui.label(feedback(message, crate::i18n::current(ui.ctx()), translate));
|
||||
}
|
||||
}
|
||||
|
||||
/// The printer queue the settings name; empty for none.
|
||||
fn printer_name(settings: &Settings) -> &str {
|
||||
match &settings.destination {
|
||||
Destination::Printer(name) => name,
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// Read print settings/status, or validate an explicit update before changing anything.
|
||||
/// `refresh: true` starts discovery only; this command never submits a job or opens a dialog.
|
||||
pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<&Discover>) -> Result<serde_json::Value, String> {
|
||||
@@ -45,7 +39,7 @@ pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<
|
||||
if !state.printers.iter().any(|available| available.name == printer) {
|
||||
return Err("printer must be a name from the discovered list".into());
|
||||
}
|
||||
next.printer = printer.to_owned();
|
||||
next.destination = Destination::Printer(printer.to_owned());
|
||||
}
|
||||
if let Some(value) = object.get("copies") {
|
||||
let copies = value.as_u64().filter(|copies| (1..=999).contains(copies)).ok_or("copies must be an integer from 1 to 999")?;
|
||||
@@ -81,10 +75,11 @@ pub fn settings(state: &mut State, params: &serde_json::Value, discover: Option<
|
||||
Some(Feedback::Submitted(receipt)) => ("submitted", receipt.as_str()),
|
||||
Some(Feedback::Failed(error)) => ("failed", error.as_str()),
|
||||
Some(Feedback::WorkerStopped) => ("workerStopped", ""),
|
||||
Some(_) => ("unknown", ""),
|
||||
};
|
||||
Ok(json!({
|
||||
"printer": state.settings.printer, "copies": state.settings.copies,
|
||||
"duplex": match state.settings.duplex { None => "printerDefault", Some(Duplex::Off) => "off", Some(Duplex::LongEdge) => "longEdge", Some(Duplex::ShortEdge) => "shortEdge" },
|
||||
"printer": printer_name(&state.settings), "copies": state.settings.copies,
|
||||
"duplex": match state.settings.duplex { Some(Duplex::Off) => "off", Some(Duplex::LongEdge) => "longEdge", Some(Duplex::ShortEdge) => "shortEdge", _ => "printerDefault" },
|
||||
"grayscale": state.settings.grayscale,
|
||||
"printers": state.printers.iter().map(|printer| json!({"name": printer.name, "default": printer.default})).collect::<Vec<Value>>(),
|
||||
"busy": state.busy(), "discovering": state.discovering(), "ready": state.ready(), "status": status, "detail": detail,
|
||||
@@ -101,5 +96,6 @@ pub fn feedback(message: &Feedback, language: crate::i18n::Language, translate:
|
||||
Feedback::Submitted(receipt) => translate("Print job submitted: {receipt}").replace("{receipt}", receipt),
|
||||
Feedback::Failed(error) => translate("Print failed: {error}").replace("{error}", &language.tr_error(error)),
|
||||
Feedback::WorkerStopped => translate("Print failed: the printing worker stopped."),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
@@ -248,7 +248,7 @@ fn combo_popup(
|
||||
if filter {
|
||||
height += ui.spacing().interact_size.y + 4.0 * spacing + 1.0;
|
||||
}
|
||||
let menu = craft_ui::combo::Menu::new(ui, &field).height(height);
|
||||
let menu = crate::combo_menu::Menu::new(ui, &field).height(height);
|
||||
let text_id = anchor.id.with(salt).with("__combo_text");
|
||||
let sel0 = st.sel;
|
||||
let shown = if filter {
|
||||
|
||||
@@ -270,7 +270,7 @@ pub fn sheet_tabs(app: &mut SheetApp, ui: &mut Ui) {
|
||||
ed.request_focus();
|
||||
}
|
||||
if ed.lost_focus() {
|
||||
if !ui.input(|i| i.key_pressed(egui::Key::Escape)) && text != name {
|
||||
if !crate::framework::escape_pressed(ui.ctx()) && text != name {
|
||||
app.run_or_alert("sheet.rename", json!({"sheet": i, "name": text}));
|
||||
}
|
||||
app.grid.renaming_tab = None;
|
||||
|
||||
@@ -93,7 +93,7 @@ impl SheetApp {
|
||||
/// Resolve outside clicks before the ribbon/tabs can save or switch the workbook.
|
||||
pub(crate) fn before_ui(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
let Some(ed) = &app.text_box_editor else { return };
|
||||
if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) {
|
||||
if crate::framework::consume_escape(&ctx) {
|
||||
app.cancel_text_box_edit();
|
||||
ctx.memory_mut(|m| m.surrender_focus(editor_id()));
|
||||
return;
|
||||
|
||||
@@ -526,6 +526,13 @@ pub(super) fn font_definitions_impl(
|
||||
if let Some(ui) = fonts.families.get(&FontFamily::Name(UI.into())).cloned() {
|
||||
fonts.families.insert(FontFamily::Proportional, ui);
|
||||
}
|
||||
// The framework's dialogs draw in two families of their own besides the proportional and
|
||||
// monospace ones: the signature family follows the proportional one, and the semibold family
|
||||
// (titles, strong text) is the bold UI face. A family left out draws missing-glyph boxes.
|
||||
let proportional = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
|
||||
let bold = fonts.families.get(&FontFamily::Name(UI_BOLD.into())).cloned().unwrap_or_else(|| proportional.clone());
|
||||
fonts.families.insert(craft_ui::fonts::FontRef::signature().family(), proportional);
|
||||
fonts.families.insert(FontFamily::Name(craft_ui::fonts::SEMIBOLD.into()), bold);
|
||||
// Installed workbook fonts, so a cell's chosen font actually renders in it. They are bound
|
||||
// after the proportional chain has the script faces, which their chains end with.
|
||||
for (family, faces) in installed {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
//! One background check at startup (and on Help ▸ Check for Updates…) and the modal prompt that
|
||||
//! offers the new release: Update and Restart (direct self-update), Download or Later. The flow
|
||||
//! itself is `craft_update::updater::Updater`.
|
||||
//! itself is `craft_update::updater::Updater`; its dialogs run on the app's
|
||||
//! [`DialogHost`](craft_ui::dialog::DialogHost).
|
||||
|
||||
use craft_update::CheckResultResponse;
|
||||
use craft_ui::dialog::DialogResult;
|
||||
use craft_update::stack_dialogs::{CheckChoice, UpdateCheckDialog};
|
||||
use craft_update::updater::{Action, Status, Updater};
|
||||
|
||||
use crate::SheetApp;
|
||||
@@ -35,9 +37,9 @@ pub(crate) fn start(app: &mut SheetApp, manual: bool) {
|
||||
pub(crate) fn tick(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
let rt = &mut app.updates_rt;
|
||||
if std::mem::take(&mut rt.manual) {
|
||||
rt.updater.check_now(ctx);
|
||||
rt.updater.check_now();
|
||||
} else if rt.startup {
|
||||
rt.updater.check_at_start(ctx);
|
||||
rt.updater.check_at_start();
|
||||
}
|
||||
rt.updater.tick(ctx);
|
||||
}
|
||||
@@ -54,28 +56,50 @@ fn result_window_shows(status: &Status, prompt_open: bool) -> bool {
|
||||
!prompt_open && !matches!(status, Status::Idle)
|
||||
}
|
||||
|
||||
/// One frame of the update flow, before the dialog host runs: answers the result dialog closed in
|
||||
/// the last pass, drives the startup prompt, and keeps the result dialog open and current while the
|
||||
/// updater has something to report.
|
||||
pub(crate) fn show(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
// The close for a ready update waits until no workbook holds unsaved work.
|
||||
let clean = !app.session.documents().iter().any(|d| d.is_dirty());
|
||||
match app.updates_rt.updater.show_if(ctx, clean) {
|
||||
Action::OpenUrl(url) => {
|
||||
if let Some(open) = &app.services.open_url {
|
||||
open(&url);
|
||||
}
|
||||
// Answered before the dialog is kept open below, so a dismissed outcome does not open again at once.
|
||||
match app.framework_dialogs.take::<UpdateCheckDialog>() {
|
||||
Some(DialogResult::Ok(CheckChoice::CheckNow | CheckChoice::CheckAgain)) => app.updates_rt.manual = true,
|
||||
// The next `run` asks the window to close once nothing is unsaved.
|
||||
Some(DialogResult::Ok(CheckChoice::RestartToUpdate)) => app.updates_rt.updater.restart_to_update(),
|
||||
Some(DialogResult::Ok(CheckChoice::Update)) => {
|
||||
app.updates_rt.updater.request_install(clean);
|
||||
}
|
||||
Some(DialogResult::Ok(CheckChoice::Download)) => open_url(app, &crate::UPDATE_APP.releases_url()),
|
||||
// Closing the dialog dismisses the outcome it showed.
|
||||
Some(_) => app.updates_rt.updater.dismiss_status(),
|
||||
None => {}
|
||||
}
|
||||
match app.updates_rt.updater.run(&mut app.framework_dialogs, clean) {
|
||||
Action::OpenUrl(url) => open_url(app, &url),
|
||||
// Quit closes every workbook window. The install helper starts once the app exits.
|
||||
Action::Close => app.request_quit(ctx),
|
||||
Action::None => {}
|
||||
_ => {}
|
||||
}
|
||||
let rt = &mut app.updates_rt;
|
||||
if result_window_shows(rt.updater.status(), rt.updater.prompt_open()) {
|
||||
match craft_update::CheckResultDialog::new(&crate::UPDATE_APP, VERSION).show(ctx, rt.updater.status()) {
|
||||
CheckResultResponse::Close => rt.updater.dismiss_status(),
|
||||
CheckResultResponse::CheckAgain => rt.updater.check_now(ctx),
|
||||
// The next `show_if` asks the window to close once nothing is unsaved.
|
||||
CheckResultResponse::RestartToUpdate => rt.updater.restart_to_update(),
|
||||
CheckResultResponse::None => {}
|
||||
}
|
||||
let updater = &app.updates_rt.updater;
|
||||
let shows = result_window_shows(updater.status(), updater.prompt_open());
|
||||
let (status, installing, message) = (updater.status().clone(), updater.is_installing(), updater.status_message());
|
||||
let dialogs = &mut app.framework_dialogs;
|
||||
if shows && !dialogs.is_open::<UpdateCheckDialog>() {
|
||||
dialogs.open(UpdateCheckDialog::new(VERSION));
|
||||
} else if !shows && dialogs.is_open::<UpdateCheckDialog>() {
|
||||
dialogs.cancel::<UpdateCheckDialog>(ctx);
|
||||
}
|
||||
if let Some(dialog) = dialogs.get_mut::<UpdateCheckDialog>() {
|
||||
dialog.set_status(status);
|
||||
dialog.set_installing(installing);
|
||||
dialog.set_message(message);
|
||||
}
|
||||
}
|
||||
|
||||
fn open_url(app: &SheetApp, url: &str) {
|
||||
if let Some(open) = &app.services.open_url {
|
||||
open(url);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
//! Shows each open workbook window as an egui immediate viewport, one native window each.
|
||||
//!
|
||||
//! Call [`Viewports::show`] once per frame from the root viewport's UI. The root viewport stays the
|
||||
//! app's: the window mapped to it with [`Viewports::set_root`] is drawn into the root UI, and every
|
||||
//! other window gets its own viewport, placed one cascade step from the window used last. Close and
|
||||
//! quit policy stays with the app: the driver reports [`WindowEvent`]s.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use craft_window::{WindowId, WindowList};
|
||||
use egui::{Context, Pos2, Rect, Ui, Vec2, ViewportBuilder, ViewportCommand, ViewportId};
|
||||
|
||||
/// How far right and down a new window opens from the window used last, in points: about one
|
||||
/// title bar.
|
||||
pub const CASCADE_STEP: f32 = 28.0;
|
||||
|
||||
/// How far a maximized window's frame may reach past its monitor's edges: a window rectangle that
|
||||
/// starts up to this far left of or above a monitor is on that monitor.
|
||||
const FRAME_OVERSHOOT: f32 = 16.0;
|
||||
|
||||
/// Something that happened to a window this frame. The app decides what follows.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum WindowEvent {
|
||||
/// The window got focus. The driver has already made it the list's active window.
|
||||
Focused(WindowId),
|
||||
/// The user asked to close the window (its close button, Alt+F4, ⌘W through the desktop).
|
||||
/// A child window stays open until the app closes it in the [`WindowList`], so the app can ask
|
||||
/// to save first. The root window's close request is the app's close path to hold.
|
||||
CloseRequested(WindowId),
|
||||
}
|
||||
|
||||
/// What the driver remembers about a window between frames.
|
||||
#[derive(Default)]
|
||||
struct Seen {
|
||||
focused: bool,
|
||||
/// The window's outer rectangle as it last reported it.
|
||||
outer: Option<Rect>,
|
||||
inner_size: Option<Vec2>,
|
||||
monitor_size: Option<Vec2>,
|
||||
/// The cascade position chosen when the window was created; repeated every frame so egui sees
|
||||
/// an unchanged builder.
|
||||
position: Option<Pos2>,
|
||||
/// The root viewport's title, sent as a command when it changes.
|
||||
title: Option<String>,
|
||||
}
|
||||
|
||||
/// The windows of a [`WindowList`] as egui viewports (see the module docs).
|
||||
#[derive(Default)]
|
||||
pub struct Viewports {
|
||||
root: Option<WindowId>,
|
||||
seen: HashMap<WindowId, Seen>,
|
||||
}
|
||||
|
||||
impl Viewports {
|
||||
/// The window drawn into the root viewport.
|
||||
pub fn root(&self) -> Option<WindowId> {
|
||||
self.root
|
||||
}
|
||||
|
||||
/// Maps window `id` to the root viewport, or none.
|
||||
pub fn set_root(&mut self, id: Option<WindowId>) {
|
||||
if let Some(id) = id {
|
||||
// The root is a different native window: forget the child's focus and title.
|
||||
self.seen.insert(id, Seen::default());
|
||||
}
|
||||
self.root = id;
|
||||
}
|
||||
|
||||
/// Moves window `id` into the root viewport, for when the root's own window closes while others
|
||||
/// stay open. The root window takes `id`'s position and size and gets focus; `id`'s data and
|
||||
/// [`WindowId`] are unchanged, so its UI state carries over.
|
||||
pub fn adopt(&mut self, ctx: &Context, id: WindowId) {
|
||||
let (outer, inner_size) = self.seen.get(&id).map_or((None, None), |seen| (seen.outer, seen.inner_size));
|
||||
self.set_root(Some(id));
|
||||
if let Some(rect) = outer {
|
||||
ctx.send_viewport_cmd_to(ViewportId::ROOT, ViewportCommand::OuterPosition(rect.min));
|
||||
}
|
||||
if let Some(size) = inner_size {
|
||||
ctx.send_viewport_cmd_to(ViewportId::ROOT, ViewportCommand::InnerSize(size));
|
||||
}
|
||||
ctx.send_viewport_cmd_to(ViewportId::ROOT, ViewportCommand::Focus);
|
||||
}
|
||||
|
||||
/// The egui viewport showing window `id`.
|
||||
pub fn viewport_id(&self, id: WindowId) -> ViewportId {
|
||||
if self.root == Some(id) { ViewportId::ROOT } else { child_viewport_id(id) }
|
||||
}
|
||||
|
||||
/// Brings window `id` to the front.
|
||||
pub fn focus(&self, ctx: &Context, id: WindowId) {
|
||||
ctx.send_viewport_cmd_to(self.viewport_id(id), ViewportCommand::Focus);
|
||||
}
|
||||
|
||||
/// Draws every window of `windows`: the root's into `ui`, every other one in an immediate
|
||||
/// viewport built by `builder` (with system decorations) and drawn by `content`. Returns what
|
||||
/// happened to the windows this frame.
|
||||
pub fn show<T>(
|
||||
&mut self,
|
||||
ui: &mut Ui,
|
||||
windows: &mut WindowList<T>,
|
||||
mut builder: impl FnMut(WindowId, &T) -> ViewportBuilder,
|
||||
mut content: impl FnMut(&mut Ui, WindowId, &mut T),
|
||||
) -> Vec<WindowEvent> {
|
||||
self.seen.retain(|id, _| windows.contains(*id));
|
||||
let ctx = ui.ctx().clone();
|
||||
let mut events = Vec::new();
|
||||
|
||||
if let Some(root) = self.root.filter(|&id| windows.contains(id)) {
|
||||
if let Some(title) = windows.get(root).and_then(|data| builder(root, data).title) {
|
||||
let seen = self.seen.entry(root).or_default();
|
||||
if seen.title.as_ref() != Some(&title) {
|
||||
ctx.send_viewport_cmd_to(ViewportId::ROOT, ViewportCommand::Title(title.clone()));
|
||||
seen.title = Some(title);
|
||||
}
|
||||
}
|
||||
if let Some(data) = windows.get_mut(root) {
|
||||
content(ui, root, data);
|
||||
}
|
||||
self.record(Snapshot::read(&ctx), windows, root, &mut events);
|
||||
}
|
||||
|
||||
let children: Vec<WindowId> = windows.ids().filter(|&id| self.root != Some(id)).collect();
|
||||
for id in children {
|
||||
let Some(data) = windows.get(id) else { continue };
|
||||
let mut viewport = builder(id, data).with_decorations(true);
|
||||
let position = match self.seen.get(&id) {
|
||||
Some(seen) => seen.position,
|
||||
None => self.place(windows, id, &viewport),
|
||||
};
|
||||
if let Some(position) = position {
|
||||
viewport = viewport.with_position(position);
|
||||
}
|
||||
self.seen.entry(id).or_default().position = position;
|
||||
|
||||
let Some(data) = windows.get_mut(id) else { continue };
|
||||
let snapshot = ctx.show_viewport_immediate(child_viewport_id(id), viewport, |child_ui, _class| {
|
||||
content(child_ui, id, data);
|
||||
Snapshot::read(child_ui.ctx())
|
||||
});
|
||||
self.record(snapshot, windows, id, &mut events);
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
fn record<T>(&mut self, snapshot: Snapshot, windows: &mut WindowList<T>, id: WindowId, events: &mut Vec<WindowEvent>) {
|
||||
let Snapshot { close, focused, outer, inner, monitor } = snapshot;
|
||||
let seen = self.seen.entry(id).or_default();
|
||||
seen.outer = outer;
|
||||
seen.inner_size = inner.map(|r| r.size()).or(seen.inner_size);
|
||||
seen.monitor_size = monitor.or(seen.monitor_size);
|
||||
if focused && !seen.focused {
|
||||
windows.focus(id);
|
||||
events.push(WindowEvent::Focused(id));
|
||||
}
|
||||
seen.focused = focused;
|
||||
if close {
|
||||
events.push(WindowEvent::CloseRequested(id));
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a new window opens: one cascade step from the window used most recently whose
|
||||
/// rectangle is known, within that window's monitor. `None` when no window's rectangle is known.
|
||||
fn place<T>(&self, windows: &WindowList<T>, id: WindowId, viewport: &ViewportBuilder) -> Option<Pos2> {
|
||||
let (previous_id, previous) = windows.recent().filter(|&w| w != id).find_map(|w| Some((w, self.seen.get(&w)?.outer?)))?;
|
||||
let seen = self.seen.get(&previous_id);
|
||||
let frame = seen.and_then(|s| s.inner_size).map(|inner| previous.size() - inner).unwrap_or_default();
|
||||
let size = viewport.inner_size.map(|s| s + frame).unwrap_or(previous.size());
|
||||
let bounds = monitor_bounds(previous, seen?.monitor_size?);
|
||||
Some(craft_behavior::placement::cascade(previous, size, bounds, CASCADE_STEP).min)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a window reported in its pass.
|
||||
struct Snapshot {
|
||||
close: bool,
|
||||
focused: bool,
|
||||
outer: Option<Rect>,
|
||||
inner: Option<Rect>,
|
||||
monitor: Option<Vec2>,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
fn read(ctx: &Context) -> Self {
|
||||
ctx.input(|i| {
|
||||
let v = i.viewport();
|
||||
Self {
|
||||
close: v.close_requested(),
|
||||
focused: v.focused.unwrap_or(false),
|
||||
outer: v.outer_rect,
|
||||
inner: v.inner_rect,
|
||||
monitor: v.monitor_size,
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The egui viewport of a window that is not in the root viewport.
|
||||
pub fn child_viewport_id(id: WindowId) -> ViewportId {
|
||||
ViewportId::from_hash_of(("craft_window", id.get()))
|
||||
}
|
||||
|
||||
/// The monitor `window` is on, for a desktop of monitors of one `monitor` size side by side: egui
|
||||
/// reports only the size of the window's monitor, not where it is.
|
||||
fn monitor_bounds(window: Rect, monitor: Vec2) -> Rect {
|
||||
let tile = |pos: f32, len: f32| if len > 0.0 { ((pos + FRAME_OVERSHOOT) / len).floor() * len } else { 0.0 };
|
||||
Rect::from_min_size(egui::pos2(tile(window.min.x, monitor.x), tile(window.min.y, monitor.y)), monitor)
|
||||
}
|
||||
@@ -303,7 +303,7 @@ pub fn committed_text(ui: &mut Ui, id: egui::Id, current: &str, width: Option<f3
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut text).id(id).desired_width(width));
|
||||
if r.lost_focus() {
|
||||
ui.data_mut(|d| d.remove::<String>(draft));
|
||||
return (!ui.input(|i| i.key_pressed(egui::Key::Escape))).then_some(text);
|
||||
return (!crate::framework::escape_pressed(ui.ctx())).then_some(text);
|
||||
}
|
||||
if r.has_focus() {
|
||||
ui.data_mut(|d| d.insert_temp(draft, text));
|
||||
@@ -598,7 +598,7 @@ pub fn message_box(app: &mut SheetApp, ctx: &egui::Context) {
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button(" OK ").clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter) || i.key_pressed(egui::Key::Escape)) {
|
||||
if ui.button(" OK ").clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter)) || crate::framework::escape_pressed(ui.ctx()) {
|
||||
close = true;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -13,14 +13,17 @@ fn editing(text: &str, formula_bar: bool) -> egui_kittest::Harness<'static, Shee
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
session.execute("cell.set", json!({"cell": "A1", "input": text})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
SheetApp::new(session, Default::default()),
|
||||
);
|
||||
let mut h = egui_kittest::Harness::builder()
|
||||
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
|
||||
.with_size(vec2(1200.0, 800.0))
|
||||
.build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
SheetApp::new(session, Default::default()),
|
||||
);
|
||||
h.run_steps(4);
|
||||
if formula_bar {
|
||||
h.get_by_label(text).click();
|
||||
|
||||
@@ -49,6 +49,7 @@ fn primary_text_bounds(galley: &egui::Galley) -> (f32, f32) {
|
||||
#[test]
|
||||
fn cjk_and_latin_share_a_baseline_in_cells_and_window_titles() {
|
||||
let ctx = Context::default();
|
||||
gridcraft_ui_egui::framework::install_headless(&ctx);
|
||||
ctx.set_pixels_per_point(2.0);
|
||||
activate(&ctx, theme::font_definitions_for_language(Language::Zh));
|
||||
for role in [theme::CELL, theme::CELL_BOLD, theme::CELL_ITALIC, theme::CELL_BOLD_ITALIC, theme::UI_BOLD] {
|
||||
@@ -72,6 +73,7 @@ fn mixed_script_wrapping_keeps_fixed_row_clips_alignment_and_editor_height() {
|
||||
const TEXT: &str = "中文ABC2026\n文字xyz123";
|
||||
for zoom in [80, 100, 280] {
|
||||
let ctx = Context::default();
|
||||
gridcraft_ui_egui::framework::install_headless(&ctx);
|
||||
ctx.set_pixels_per_point(2.0);
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
@@ -139,6 +141,7 @@ fn same_row_cells_keep_their_baseline_with_baseline_aligned_fallbacks() {
|
||||
for valign in ["Top", "Bottom", "Center"] {
|
||||
let mixed = if wraps[1] && valign == "Top" { "Hello\n中文" } else { "Hello 中文" };
|
||||
let ctx = Context::default();
|
||||
gridcraft_ui_egui::framework::install_headless(&ctx);
|
||||
ctx.set_pixels_per_point(2.0);
|
||||
activate(&ctx, theme::font_definitions_for_language(Language::Zh));
|
||||
let mut session = Session::new();
|
||||
|
||||
@@ -14,9 +14,11 @@ use gridcraft_ui_egui::{Services, SheetApp};
|
||||
|
||||
pub type Harness = egui_kittest::Harness<'static, SheetApp>;
|
||||
|
||||
/// A kittest builder with the deterministic font set and GridCraft's visuals installed.
|
||||
/// A kittest builder with the UI runtime, the deterministic font set and GridCraft's visuals
|
||||
/// installed.
|
||||
pub fn builder<State>() -> HarnessBuilder<State> {
|
||||
egui_kittest::Harness::builder().with_context_setup(|ctx| {
|
||||
gridcraft_ui_egui::framework::install_headless(ctx);
|
||||
ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions());
|
||||
gridcraft_ui_egui::theme::apply(ctx, false);
|
||||
})
|
||||
@@ -33,7 +35,7 @@ pub fn prepare(mut app: SheetApp) -> SheetApp {
|
||||
app
|
||||
}
|
||||
|
||||
/// Drive `app`'s `logic` then `ui` each frame in a harness built with `builder`.
|
||||
/// Drive `app`'s `logic`, its close path, then `ui` each frame in a harness built with `builder`.
|
||||
///
|
||||
/// Tests that need a non-standard size, step timing, OS or pixel ratio configure the builder
|
||||
/// here so those details stay explicit; the shared font and lifecycle setup lives in `builder`
|
||||
@@ -43,6 +45,7 @@ pub fn harness_with(builder: HarnessBuilder<SheetApp>, app: SheetApp, steps: usi
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.close_path(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
|
||||
@@ -42,6 +42,7 @@ impl Desk {
|
||||
fn new(quit_with_last_window: bool) -> Desk {
|
||||
INFOS.with(|i| i.borrow_mut().clear());
|
||||
let ctx = Context::default();
|
||||
gridcraft_ui_egui::framework::install_headless(&ctx);
|
||||
ctx.set_embed_viewports(false);
|
||||
Context::set_immediate_viewport_renderer(|ctx, viewport| {
|
||||
let id = viewport.ids.this;
|
||||
@@ -77,6 +78,7 @@ impl Desk {
|
||||
}
|
||||
app.logic(&ctx);
|
||||
windows.logic(app, &ctx);
|
||||
app.close_path(&ctx);
|
||||
windows.show(app, ui);
|
||||
});
|
||||
record(out);
|
||||
@@ -458,8 +460,8 @@ fn arrange_all_lays_out_the_native_windows_active_first() {
|
||||
// Without parameters, as a script calls it: tiled.
|
||||
let r = desk.app.run("view.arrangeAll", json!({})).unwrap();
|
||||
assert_eq!(r["arrange"], "tiled");
|
||||
let tiled = gridcraft_ui_egui::doc_windows::arrange_rects("tiled", 3, craft_window::Rect::new(0.0, 0.0, 1000.0, 800.0));
|
||||
let r = |x, y, w, h| craft_window::Rect::new(x, y, w, h);
|
||||
let r = |x, y, w, h| egui::Rect::from_min_size(egui::pos2(x, y), egui::vec2(w, h));
|
||||
let tiled = gridcraft_ui_egui::doc_windows::arrange_rects("tiled", 3, r(0.0, 0.0, 1000.0, 800.0));
|
||||
assert_eq!(tiled, [r(0.0, 0.0, 500.0, 400.0), r(500.0, 0.0, 500.0, 400.0), r(0.0, 400.0, 1000.0, 400.0)]);
|
||||
}
|
||||
|
||||
|
||||
@@ -25,13 +25,17 @@ fn harness(selection: &str) -> egui_kittest::Harness<'static, SheetApp> {
|
||||
session.execute("home.columnWidth", json!({"cols": "A:D", "width": 100})).unwrap();
|
||||
session.execute("home.rowHeight", json!({"rows": "1:4", "height": 60})).unwrap();
|
||||
session.execute("selection.set", json!({"range": selection})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder().with_step_dt(1.0 / 60.0).with_size(vec2(1200.0, 800.0)).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
SheetApp::new(session, Default::default()),
|
||||
);
|
||||
let mut h = egui_kittest::Harness::builder()
|
||||
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
|
||||
.with_step_dt(1.0 / 60.0)
|
||||
.with_size(vec2(1200.0, 800.0))
|
||||
.build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
SheetApp::new(session, Default::default()),
|
||||
);
|
||||
h.run_steps(4);
|
||||
h.state_mut().session.active_mut().unwrap().undo.clear();
|
||||
h.state_mut().session.journal.clear();
|
||||
|
||||
@@ -27,6 +27,7 @@ fn ctrl_shift_a() -> Event {
|
||||
/// A cell editor holding `text`, caret at the end.
|
||||
fn editing(text: &str) -> (Context, SheetApp) {
|
||||
let ctx = Context::default();
|
||||
gridcraft_ui_egui::framework::install_headless(&ctx);
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
let mut app = crate::common::app(session);
|
||||
|
||||
@@ -18,6 +18,7 @@ fn frame(ctx: &Context, app: &mut SheetApp) -> egui::FullOutput {
|
||||
/// The caret painted while editing A1 over `fill` (`None`: no fill), with the app in `dark` mode.
|
||||
fn caret(fill: Option<&str>, dark: bool) -> Color32 {
|
||||
let ctx = Context::default();
|
||||
gridcraft_ui_egui::framework::install_headless(&ctx);
|
||||
theme::apply(&ctx, dark);
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
|
||||
@@ -12,8 +12,12 @@ use serde_json::{Value as Json, json};
|
||||
type Harness = egui_kittest::Harness<'static, SheetApp>;
|
||||
|
||||
fn harness(s: Session) -> Harness {
|
||||
let mut h =
|
||||
egui_kittest::Harness::builder().with_os(OperatingSystem::Mac).with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|
||||
let mut h = egui_kittest::Harness::builder()
|
||||
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
|
||||
.with_os(OperatingSystem::Mac)
|
||||
.with_size(vec2(1400.0, 900.0))
|
||||
.with_step_dt(1.0 / 60.0)
|
||||
.build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
|
||||
@@ -38,6 +38,7 @@ fn fixture() -> (Harness, Ids) {
|
||||
let button = id(s.execute("insert.button", json!({"at": "E12", "text": "Mark it", "macro": "Mark"})).unwrap());
|
||||
s.execute("selection.set", json!({"cell": "A20"})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder()
|
||||
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
|
||||
.with_size(vec2(1400.0, 900.0))
|
||||
.with_step_dt(1.0 / 60.0)
|
||||
.with_os(egui::os::OperatingSystem::Mac)
|
||||
@@ -591,6 +592,7 @@ fn insert_tab() -> Harness {
|
||||
let mut app = SheetApp::new(s, Default::default());
|
||||
app.ui.ribbon_tab = "Insert".into();
|
||||
let mut h = egui_kittest::Harness::builder()
|
||||
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
|
||||
.with_size(vec2(1400.0, 900.0))
|
||||
.with_step_dt(1.0 / 60.0)
|
||||
.with_os(egui::os::OperatingSystem::Mac)
|
||||
|
||||
@@ -31,6 +31,7 @@ fn visible(ctx: &Context, editor: &str) -> bool {
|
||||
fn cell_formula_helpers_hide_when_scrolled_out_and_return_with_the_editor() {
|
||||
for text in ["=SU", "=SUM("] {
|
||||
let ctx = Context::default();
|
||||
gridcraft_ui_egui::framework::install_headless(&ctx);
|
||||
ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions());
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
@@ -57,6 +58,7 @@ fn cell_formula_helpers_hide_when_scrolled_out_and_return_with_the_editor() {
|
||||
#[test]
|
||||
fn hidden_row_and_column_hide_the_wrapped_editor_until_unhidden() {
|
||||
let ctx = Context::default();
|
||||
gridcraft_ui_egui::framework::install_headless(&ctx);
|
||||
ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions());
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
@@ -95,6 +97,7 @@ fn paints_visible_text(output: &egui::FullOutput, text: &str, cells: Rect) -> bo
|
||||
/// Formula-bar help stays visible while the sheet scrolls.
|
||||
fn formula_bar_hint_remains_visible_when_the_worksheet_scrolls() {
|
||||
let ctx = Context::default();
|
||||
gridcraft_ui_egui::framework::install_headless(&ctx);
|
||||
ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions());
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
@@ -112,6 +115,7 @@ fn formula_bar_hint_remains_visible_when_the_worksheet_scrolls() {
|
||||
/// Cell argument help is clipped to the worksheet instead of painting over the headers.
|
||||
fn cell_argument_hint_is_clipped_to_the_worksheet() {
|
||||
let ctx = Context::default();
|
||||
gridcraft_ui_egui::framework::install_headless(&ctx);
|
||||
ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions());
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
@@ -131,6 +135,7 @@ fn cell_argument_hint_is_clipped_to_the_worksheet() {
|
||||
/// An editor for a scrolled-out cell still handles Esc.
|
||||
fn scrolled_out_cell_editor_still_handles_escape() {
|
||||
let ctx = Context::default();
|
||||
gridcraft_ui_egui::framework::install_headless(&ctx);
|
||||
ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions());
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
@@ -162,6 +167,7 @@ fn scrolled_out_cell_editor_still_handles_escape() {
|
||||
/// The editor and its helper clip below the frozen top row, stay hidden while the cell is under it, and return on scroll-back.
|
||||
fn cell_editor_and_helper_stay_below_the_frozen_top_row() {
|
||||
let ctx = Context::default();
|
||||
gridcraft_ui_egui::framework::install_headless(&ctx);
|
||||
ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions());
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
@@ -214,6 +220,7 @@ fn cell_editor_and_helper_stay_below_the_frozen_top_row() {
|
||||
fn frozen_column_editor_paints_in_both_panes_on_a_right_to_left_sheet() {
|
||||
for (cell, text) in [("A2", "frozen"), ("B2", "scrolling")] {
|
||||
let ctx = Context::default();
|
||||
gridcraft_ui_egui::framework::install_headless(&ctx);
|
||||
ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions());
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
@@ -257,6 +264,7 @@ fn frozen_column_editor_paints_in_both_panes_on_a_right_to_left_sheet() {
|
||||
fn argument_hint_shows_the_function_description() {
|
||||
// #363: inside DATEDIF( the hint lists the units the third argument takes.
|
||||
let ctx = Context::default();
|
||||
gridcraft_ui_egui::framework::install_headless(&ctx);
|
||||
ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions());
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
|
||||
@@ -23,6 +23,7 @@ fn frames(ctx: &Context, app: &mut SheetApp) {
|
||||
/// The editor's text field rect while A1 (narrow, wrap on or off) is edited with [`TEXT`].
|
||||
fn editor_rect(wrap: bool) -> Rect {
|
||||
let ctx = Context::default();
|
||||
gridcraft_ui_egui::framework::install_headless(&ctx);
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
session.execute("home.columnWidth", json!({"cols": "A:A", "chars": 12})).unwrap();
|
||||
@@ -47,6 +48,7 @@ fn a_wrap_text_cell_edits_wrapped_at_the_column_width() {
|
||||
#[test]
|
||||
fn a_short_wrap_text_edit_stays_one_line_tall() {
|
||||
let ctx = Context::default();
|
||||
gridcraft_ui_egui::framework::install_headless(&ctx);
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
session.execute("home.wrapText", json!({"range": "A1", "on": true})).unwrap();
|
||||
@@ -64,6 +66,7 @@ fn a_short_wrap_text_edit_stays_one_line_tall() {
|
||||
#[test]
|
||||
fn the_editor_measures_the_text_at_the_fields_wrap_width() {
|
||||
let ctx = Context::default();
|
||||
gridcraft_ui_egui::framework::install_headless(&ctx);
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
session.execute("home.columnWidth", json!({"cols": "A:A", "chars": 12})).unwrap();
|
||||
@@ -91,6 +94,7 @@ fn the_editor_measures_the_text_at_the_fields_wrap_width() {
|
||||
fn an_unwrapped_multiline_edit_shows_every_line() {
|
||||
let field = |text: &str| {
|
||||
let ctx = Context::default();
|
||||
gridcraft_ui_egui::framework::install_headless(&ctx);
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
let mut app = crate::common::app(session);
|
||||
|
||||
@@ -16,11 +16,11 @@ fn interface_size_applies_persists_and_clamps() {
|
||||
},
|
||||
crate::common::app(session),
|
||||
);
|
||||
h.run_steps(2);
|
||||
crate::support::frames(&mut h, 2);
|
||||
assert_eq!(h.ctx.zoom_factor(), 1.0);
|
||||
|
||||
h.state_mut().run("view.interfaceScale", json!({"percent": 125})).unwrap();
|
||||
h.run_steps(2);
|
||||
crate::support::frames(&mut h, 2);
|
||||
assert_eq!(h.ctx.zoom_factor(), 1.25);
|
||||
let saved: UiState = serde_json::from_str(&serde_json::to_string(&h.state().ui).unwrap()).unwrap();
|
||||
assert_eq!(saved.interface_scale, 125);
|
||||
@@ -31,7 +31,7 @@ fn interface_size_applies_persists_and_clamps() {
|
||||
assert!(h.state_mut().run("view.interfaceScale", json!({})).is_err(), "no value is an error, not a dialog");
|
||||
assert!(h.state_mut().run("view.interfaceScale", json!({"percent": "huge"})).is_err());
|
||||
h.state_mut().run("view.interfaceScale", json!({"percent": "auto"})).unwrap();
|
||||
h.run_steps(2);
|
||||
crate::support::frames(&mut h, 2);
|
||||
assert_eq!(h.ctx.zoom_factor(), 1.0);
|
||||
|
||||
// A malformed or out-of-range ui.json keeps the other preferences.
|
||||
|
||||
@@ -20,14 +20,17 @@ fn harness_with(services: Services) -> Harness {
|
||||
session.new_workbook();
|
||||
let mut app = SheetApp::new(session, services);
|
||||
app.ui.ribbon_tab = "Automate".into();
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
let mut h = egui_kittest::Harness::builder()
|
||||
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
|
||||
.with_size(egui::vec2(1400.0, 900.0))
|
||||
.build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
@@ -566,14 +569,15 @@ fn the_editor_fits_a_narrow_window() {
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
let app = SheetApp::new(session, Default::default());
|
||||
let mut h = egui_kittest::Harness::builder().with_size(size).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
let mut h =
|
||||
egui_kittest::Harness::builder().with_context_setup(gridcraft_ui_egui::framework::install_headless).with_size(size).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(4);
|
||||
three(&mut h);
|
||||
h.run_steps(4);
|
||||
|
||||
@@ -16,14 +16,17 @@ fn harness(tab: &str) -> Harness {
|
||||
session.new_workbook();
|
||||
let mut app = SheetApp::new(session, Default::default());
|
||||
app.ui.ribbon_tab = tab.into();
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
let mut h = egui_kittest::Harness::builder()
|
||||
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
|
||||
.with_size(egui::vec2(1280.0, 800.0))
|
||||
.build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
@@ -115,14 +118,17 @@ fn the_macros_dialog_lists_scripts_and_the_vba_project_beside_macros() {
|
||||
s.execute("macro.save", json!({"name": "Mark", "steps": []})).unwrap();
|
||||
let mut app = SheetApp::new(s, Default::default());
|
||||
app.ui.ribbon_tab = "Automate".into();
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
let mut h = egui_kittest::Harness::builder()
|
||||
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
|
||||
.with_size(egui::vec2(1280.0, 800.0))
|
||||
.build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(3);
|
||||
h.state_mut().open_dialog("macros", json!({}));
|
||||
h.run_steps(2);
|
||||
@@ -260,14 +266,17 @@ fn the_macros_dialog_offers_trust_for_scripts_that_came_with_a_file() {
|
||||
s.active_mut().unwrap().scripts_trusted = false;
|
||||
let mut app = SheetApp::new(s, Default::default());
|
||||
app.ui.ribbon_tab = "Automate".into();
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
let mut h = egui_kittest::Harness::builder()
|
||||
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
|
||||
.with_size(egui::vec2(1280.0, 800.0))
|
||||
.build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(3);
|
||||
h.state_mut().open_dialog("macros", json!({}));
|
||||
h.run_steps(2);
|
||||
@@ -291,14 +300,15 @@ fn the_macros_and_record_macro_dialogs_fit_a_narrow_window() {
|
||||
s.new_workbook();
|
||||
s.execute("macro.save", json!({"name": "Tidy", "steps": []})).unwrap();
|
||||
let app = SheetApp::new(s, Default::default());
|
||||
let mut h = egui_kittest::Harness::builder().with_size(size).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
let mut h =
|
||||
egui_kittest::Harness::builder().with_context_setup(gridcraft_ui_egui::framework::install_headless).with_size(size).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(3);
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size);
|
||||
for (dialog, labels) in [("macros", &["Run", "Delete", "Options…", "Cancel"][..]), ("recordMacro", &["OK", "Cancel"][..])] {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Native print onboarding preserves engine PDF generation and submits the selected settings.
|
||||
use gridcraft_engine::Session;
|
||||
use gridcraft_ui_egui::printing::{Duplex, Feedback, Printer};
|
||||
use gridcraft_ui_egui::printing::{Destination, Duplex, Feedback, Printer};
|
||||
use gridcraft_ui_egui::{Services, SheetApp};
|
||||
use serde_json::json;
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
@@ -25,7 +25,7 @@ fn native_print_uses_selected_settings_and_reports_spool_errors() {
|
||||
let pdf = app.run("file.print", json!({"sheets":"active"})).unwrap();
|
||||
assert!(pdf["base64"].as_str().is_some(), "the engine still returns PDF bytes without submitting");
|
||||
assert!(jobs.borrow().is_empty(), "opening settings/exporting does not spool");
|
||||
app.printing.printers.push(Printer { name: "Chosen queue".into(), label: String::new(), default: false });
|
||||
app.printing.printers.push(Printer::new("Chosen queue"));
|
||||
let configured = app.run("ui.printSettings", json!({"printer":"Chosen queue", "copies":3,"duplex":"shortEdge","grayscale":true})).unwrap();
|
||||
assert_eq!(configured["ready"], true);
|
||||
assert_eq!(configured["printers"][0]["name"], "Chosen queue");
|
||||
@@ -34,7 +34,7 @@ fn native_print_uses_selected_settings_and_reports_spool_errors() {
|
||||
let jobs = jobs.borrow();
|
||||
assert_eq!(jobs.len(), 1);
|
||||
assert!(jobs[0].0.starts_with(b"%PDF"));
|
||||
assert_eq!(jobs[0].1.printer, "Chosen queue");
|
||||
assert_eq!(jobs[0].1.destination, Destination::Printer("Chosen queue".into()));
|
||||
assert_eq!(jobs[0].1.copies, 3);
|
||||
assert_eq!(jobs[0].1.duplex, Some(Duplex::ShortEdge));
|
||||
assert!(jobs[0].1.grayscale);
|
||||
@@ -53,7 +53,7 @@ fn print_settings_are_visible_in_a_narrow_window() {
|
||||
app.run("cell.set", json!({"cell":"A1", "input":"A sheet to print"})).unwrap();
|
||||
app.services.printers = Some(Box::new(|| {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
sender.send(vec![Printer { name: "Test queue".into(), label: String::new(), default: true }]).unwrap();
|
||||
sender.send(vec![Printer::new("Test queue").is_default(true)]).unwrap();
|
||||
receiver
|
||||
}));
|
||||
app.services.print_native = Some(Box::new(|_, _| {
|
||||
@@ -70,7 +70,7 @@ fn print_settings_are_visible_in_a_narrow_window() {
|
||||
app,
|
||||
);
|
||||
harness.run_steps(5);
|
||||
assert!(!harness.get_by_label("Refresh printers").accesskit_node().is_disabled());
|
||||
assert!(!harness.get_by_label("Refresh").accesskit_node().is_disabled());
|
||||
assert!(!harness.get_by_label("Grayscale").accesskit_node().is_disabled());
|
||||
harness.get_by_label("Grayscale").click();
|
||||
harness.run_steps(2);
|
||||
@@ -84,7 +84,7 @@ fn invalid_print_settings_are_rejected_without_partial_changes() {
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
let mut app = SheetApp::new(session, Services::default());
|
||||
app.printing.printers.push(Printer { name: "Queue".into(), label: String::new(), default: true });
|
||||
app.printing.printers.push(Printer::new("Queue").is_default(true));
|
||||
let before = app.run("ui.printSettings", json!({})).unwrap();
|
||||
for params in [
|
||||
json!({"printer":"Missing"}),
|
||||
@@ -110,7 +110,7 @@ fn repeated_fast_jobs_each_surface_an_identical_receipt() {
|
||||
let mut session = Session::new();
|
||||
session.new_workbook();
|
||||
let mut app = SheetApp::new(session, Services::default());
|
||||
app.printing.printers.push(Printer { name: "Queue".into(), label: String::new(), default: true });
|
||||
app.printing.printers.push(Printer::new("Queue").is_default(true));
|
||||
app.run("ui.printSettings", json!({"printer":"Queue"})).unwrap();
|
||||
app.services.print_native = Some(Box::new(|_, _| {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
|
||||
@@ -53,6 +53,7 @@ fn fixture() -> (Harness, Objects) {
|
||||
slicer: ObjRef::new(ObjKind::Slicer, slicer),
|
||||
};
|
||||
let mut h = egui_kittest::Harness::builder()
|
||||
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
|
||||
.with_size(vec2(1400.0, 900.0))
|
||||
.with_step_dt(1.0 / 60.0)
|
||||
.with_os(egui::os::OperatingSystem::Mac)
|
||||
|
||||
@@ -18,6 +18,7 @@ fn render_pivot_field_buttons(dark: bool) -> Vec<Shape> {
|
||||
let mut app = crate::common::app(session);
|
||||
app.ui.dark = dark;
|
||||
let ctx = egui::Context::default();
|
||||
gridcraft_ui_egui::framework::install_headless(&ctx);
|
||||
let mut output = egui::FullOutput::default();
|
||||
for _ in 0..6 {
|
||||
output = ctx.run_ui(RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1200.0, 800.0))), ..Default::default() }, |ui| {
|
||||
@@ -76,14 +77,17 @@ fn the_field_list_scrollbar_sits_at_the_pane_edge() {
|
||||
session.execute("range.setValues", json!({"range": "A1", "values": [names.clone(), (1..=14).collect::<Vec<i32>>()]})).unwrap();
|
||||
session.execute("insert.pivotTable", json!({"source": "Sheet1!A1:N2", "destination": "Sheet1!A5", "rows": ["F1"], "values": ["F2"]})).unwrap();
|
||||
session.execute("selection.set", json!({"cell": "A5"})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
SheetApp::new(session, Default::default()),
|
||||
);
|
||||
let mut h = egui_kittest::Harness::builder()
|
||||
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
|
||||
.with_size(vec2(1200.0, 800.0))
|
||||
.build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
SheetApp::new(session, Default::default()),
|
||||
);
|
||||
h.run_steps(4);
|
||||
let first = h.get_by_label("F1").rect();
|
||||
// A floating scrollbar is drawn while the pointer is over its area.
|
||||
|
||||
@@ -190,6 +190,7 @@ fn view_animations_sets_and_toggles_without_a_dialog() {
|
||||
fn agents_find_run_and_read_the_setting_over_the_control_channel() {
|
||||
let mut a = app();
|
||||
let ctx = egui::Context::default();
|
||||
gridcraft_ui_egui::framework::install_headless(&ctx);
|
||||
let found = reply(control::handle(&mut a, &ctx, "engine.commands", &json!({"search": "animations"})));
|
||||
let entry = found["result"].as_array().and_then(|all| all.iter().find(|c| c["id"] == "view.animations")).cloned().unwrap();
|
||||
assert_eq!((&entry["label"], &entry["ui"]), (&json!("Animations"), &json!(true)));
|
||||
|
||||
@@ -39,3 +39,13 @@ pub fn services_harness(services: Services, steps: usize) -> Harness {
|
||||
pub fn app_harness(app: SheetApp, steps: usize) -> Harness {
|
||||
harness_with(builder().with_size(egui::vec2(1200.0, 800.0)), app, steps)
|
||||
}
|
||||
|
||||
/// Runs `n` frames as the desktop and web shells do: the app hands the runtime its frame input
|
||||
/// (theme mode, interface scale) before each one.
|
||||
pub fn frames(h: &mut Harness, n: usize) {
|
||||
for _ in 0..n {
|
||||
let ctx = h.ctx.clone();
|
||||
h.state_mut().before_input(&ctx);
|
||||
h.step();
|
||||
}
|
||||
}
|
||||
@@ -25,14 +25,17 @@ fn fixture_of(kind: &str) -> (Harness, u32) {
|
||||
let shape = session.execute("insert.shape", json!({"kind": kind, "at": "D3", "width": 160, "height": height})).unwrap();
|
||||
shape["shape"].as_u64().unwrap() as u32
|
||||
};
|
||||
let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
SheetApp::new(session, Default::default()),
|
||||
);
|
||||
let mut h = egui_kittest::Harness::builder()
|
||||
.with_context_setup(gridcraft_ui_egui::framework::install_headless)
|
||||
.with_size(vec2(1200.0, 800.0))
|
||||
.build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
SheetApp::new(session, Default::default()),
|
||||
);
|
||||
h.run_steps(4);
|
||||
h.state_mut().selected_object = None;
|
||||
h.run_steps(2);
|
||||
|
||||
Reference in new issue
Block a user