mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-25 23:35:47 -06:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
11b9bb31fa | ||
|
|
792f7c2812 | ||
|
|
0998f6725d | ||
|
|
a41be21ccf | ||
|
|
55aa8c8c2e |
Generated
+150
-1401
File diff suppressed because it is too large
Load Diff
+30
-38
@@ -30,29 +30,29 @@ gridcraft-math = { path = "crates/math" }
|
||||
# ui-egui, craft-print in the app, craft-web-api and craft-web-host in the web app) comes from one
|
||||
# craft-libs revision.
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0", features = ["ui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "=0.1.0", features = ["egui"] }
|
||||
# PDF RunLength encoding; this revision also fixes the vendored JBIG2 dependency for Git consumers.
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0", default-features = false }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ff142b3ad58aa7306676749428f4f2f9b277b5dd", version = "0.1.0", default-features = false }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f7e0d7fd5577e102b4634bcbe062e649eb68165f", version = "0.1.0" }
|
||||
# Compound files ([MS-CFB]) and password-encrypted OOXML packages ([MS-OFFCRYPTO]).
|
||||
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
|
||||
craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "0.1.0" }
|
||||
# OPC zip packages (parts, relationships, the zip writer) under `crates/xlsx/src/package.rs`.
|
||||
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
|
||||
# Delimited text (CSV, TSV) and SYLK; `crates/xlsx/src/csv.rs` and `crates/engine/src/io/sylk.rs`
|
||||
# turn them into workbooks.
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "0.1.0" }
|
||||
# The native JSON workbook (`.json`, `.scjson`): read, written, and kept newer macros written back.
|
||||
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9a6d894200221fcfedc274870c30394d404f859d", version = "0.1.0" }
|
||||
# Excel 97-2003 (.xls, BIFF8) workbooks; `crates/xlsx/src/xls.rs` maps them onto the model.
|
||||
# SpreadsheetML worksheet/drawing/string/package XML; workbook model mapping stays in gridcraft-xlsx.
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "3b8e426a260695af840a2cd79a064d40778f939e", version = "0.1.0" }
|
||||
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c", version = "=0.1.0" }
|
||||
|
||||
# foundation
|
||||
thiserror = "2"
|
||||
@@ -92,15 +92,7 @@ skrifa = { version = "0.44", default-features = false, features = ["std"] }
|
||||
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/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", 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/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
|
||||
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", default-features = false, features = ["egui"] }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
@@ -128,18 +120,18 @@ debug = 0
|
||||
|
||||
# Keep the complete egui family and native event bridge on reviewed fork commits.
|
||||
[patch.crates-io]
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
@@ -18,8 +18,8 @@ gridcraft-engine = { workspace = true }
|
||||
gridcraft-ui-egui = { workspace = true }
|
||||
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
|
||||
# The page command API (storytold/craft-libs#413): window.gridcraft over the control channel.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9", version = "0.1.0" }
|
||||
egui = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -49,7 +49,6 @@ 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.
|
||||
@@ -159,7 +158,6 @@ 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() {
|
||||
@@ -179,7 +177,6 @@ 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 = { workspace = true }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9" }
|
||||
craft-update = { workspace = true }
|
||||
rfd = { workspace = true }
|
||||
arboard = { workspace = true, features = ["image-data"] }
|
||||
|
||||
@@ -66,12 +66,13 @@ impl eframe::App for App {
|
||||
}
|
||||
self.app.logic(ctx);
|
||||
self.windows.logic(&mut self.app, ctx);
|
||||
self.app.close_path(ctx);
|
||||
if ctx.input(|input| input.viewport().close_requested()) && self.app.printing.busy() {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
}
|
||||
}
|
||||
/// 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.app.raw_input_hook(ctx, raw);
|
||||
self.app.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()) {
|
||||
@@ -79,8 +80,7 @@ impl eframe::App for App {
|
||||
}
|
||||
}
|
||||
}
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
gridcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
self.windows.show(&mut self.app, ui);
|
||||
}
|
||||
fn on_exit(&mut self) {
|
||||
@@ -543,7 +543,6 @@ 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()) {
|
||||
|
||||
+10
-12
@@ -1,12 +1,15 @@
|
||||
//! Desktop spooler adapter. Discovery and submission never run on the UI thread.
|
||||
use gridcraft_ui_egui::printing::{Destination, Discover, Duplex, Printer, Settings, Submit};
|
||||
use gridcraft_ui_egui::printing::{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 {
|
||||
Box::new(|| {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
let _ = std::thread::Builder::new().name("print-discovery".into()).spawn(move || {
|
||||
let printers = craft_print::printers().into_iter().map(Printer::from).collect();
|
||||
let printers = craft_print::printers()
|
||||
.into_iter()
|
||||
.map(|printer| Printer { name: printer.name, label: printer.description, default: printer.default })
|
||||
.collect();
|
||||
let _ = sender.send(printers);
|
||||
});
|
||||
receiver
|
||||
@@ -31,17 +34,12 @@ 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: match settings.destination {
|
||||
Destination::Printer(name) => Some(name),
|
||||
_ => None,
|
||||
},
|
||||
printer: Some(settings.printer),
|
||||
copies: settings.copies.clamp(1, 999),
|
||||
collate: settings.collate,
|
||||
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,
|
||||
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,
|
||||
}),
|
||||
grayscale: settings.grayscale,
|
||||
scaling: craft_print::Scaling::ShrinkToFit,
|
||||
|
||||
@@ -11,4 +11,7 @@ disallowed-methods = [
|
||||
{ path = "std::time::SystemTime::now", reason = "traps on wasm; read the clock only off wasm" },
|
||||
]
|
||||
|
||||
disallowed-types = [
|
||||
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
|
||||
]
|
||||
cognitive-complexity-threshold = 30
|
||||
|
||||
@@ -9,15 +9,9 @@ description = "GridCraft egui frontend (Excel-style UI); swappable — nothing b
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
# 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/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-behavior = { workspace = true }
|
||||
craft-host = { workspace = true }
|
||||
craft-keymap = { workspace = true }
|
||||
craft-print = { workspace = true }
|
||||
craft-theme = { workspace = true }
|
||||
craft-window = { workspace = true }
|
||||
# The shared capture slot (`craft_ui::capture`) comes from the one craft-libs revision every
|
||||
# craft-libs dependency uses (see the root Cargo.toml).
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9" }
|
||||
gridcraft-engine = { workspace = true }
|
||||
gridcraft-chart = { workspace = true }
|
||||
# `monochrome_emoji_fonts` restores the Noto Emoji and emoji-icon faces that 0.37 moved behind
|
||||
@@ -48,6 +42,7 @@ 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,8 +88,6 @@ impl SheetApp {
|
||||
arrange_windows: None,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
updates_rt: Default::default(),
|
||||
framework_dialogs: Default::default(),
|
||||
framework_host: crate::framework::host(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,7 +102,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) {
|
||||
craft_ui::fonts::load(ctx, theme::font_definitions_for_language(language));
|
||||
ctx.set_fonts(theme::font_definitions_for_language(language));
|
||||
theme::apply(ctx, dark);
|
||||
}
|
||||
|
||||
@@ -125,6 +123,7 @@ 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
|
||||
@@ -140,6 +139,7 @@ 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).
|
||||
@@ -213,6 +213,8 @@ 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 {
|
||||
@@ -255,12 +257,6 @@ 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 {
|
||||
@@ -377,7 +373,6 @@ mod lifecycle_tests {
|
||||
/// A font-gated early-returning pass does not lose the queued step; the hook offers it again and a later real pass applies it.
|
||||
fn a_font_gated_pass_offers_the_synthetic_step_again() {
|
||||
let ctx = egui::Context::default();
|
||||
crate::framework::install_headless(&ctx);
|
||||
ctx.set_fonts(theme::font_definitions());
|
||||
let mut app = app();
|
||||
app.fonts_ready = true;
|
||||
@@ -530,7 +525,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::new("Queue").is_default(true));
|
||||
app.printing.printers.push(crate::printing::Printer { name: "Queue".into(), label: String::new(), 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 {
|
||||
craft_ui::fonts::load(ctx, theme::pinned_font_definitions());
|
||||
ctx.set_fonts(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;
|
||||
}
|
||||
craft_ui::fonts::load(ctx, theme::font_definitions_with(self.ui.language, &used));
|
||||
ctx.set_fonts(theme::font_definitions_with(self.ui.language, &used));
|
||||
self.fonts_bound = used;
|
||||
self.fonts_rebind = true;
|
||||
ctx.request_repaint();
|
||||
|
||||
@@ -27,6 +27,27 @@ 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.
|
||||
/// A nightly channel has no update feed of its own: the Launcher installs and replaces it.
|
||||
|
||||
@@ -1,35 +1,28 @@
|
||||
use craft_ui::shell::embed::CloseDecision;
|
||||
|
||||
use super::{SaveAnswer, SheetApp, json};
|
||||
|
||||
impl SheetApp {
|
||||
/// 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;
|
||||
/// 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;
|
||||
}
|
||||
// A cell still being edited is part of the workbook, as for File › Close.
|
||||
if !self.commit_edit(0, 0, false, false) {
|
||||
return CloseDecision::Hold;
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
return;
|
||||
}
|
||||
// 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 CloseDecision::Hold;
|
||||
return;
|
||||
}
|
||||
if !self.session.documents().iter().any(|d| d.is_dirty()) {
|
||||
return CloseDecision::Close;
|
||||
return;
|
||||
}
|
||||
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" => {
|
||||
@@ -37,7 +30,6 @@ impl SheetApp {
|
||||
}
|
||||
_ => self.continue_quit(ctx),
|
||||
}
|
||||
CloseDecision::Hold
|
||||
}
|
||||
|
||||
/// Asks about the next unsaved workbook before quitting, in its window, or closes the app
|
||||
|
||||
@@ -233,7 +233,12 @@ 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) && crate::framework::consume_escape(&ctx) {
|
||||
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))
|
||||
{
|
||||
out.close = true;
|
||||
}
|
||||
if let Some(page) = out.page {
|
||||
@@ -676,7 +681,7 @@ fn save_as(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &mut Outcom
|
||||
let current = SAVE_TYPES.iter().find(|(ext, _)| *ext == fmt).map_or("Excel Workbook (*.xlsx)", |(_, label)| *label);
|
||||
ui.horizontal(|ui| {
|
||||
let label = ui.label(lang.tr("Save as type"));
|
||||
egui::ComboBox::from_id_salt("backstage_save_type")
|
||||
craft_ui::ComboBox::from_id_salt("backstage_save_type")
|
||||
.width(280.0)
|
||||
.selected_text(lang.tr(current))
|
||||
.show_ui(ui, |ui| {
|
||||
|
||||
@@ -63,7 +63,7 @@ fn general_options(app: &mut SheetApp, ui: &mut Ui, lang: Language) {
|
||||
"dark" => "Dark",
|
||||
_ => "Light",
|
||||
};
|
||||
egui::ComboBox::from_id_salt("backstage_theme")
|
||||
craft_ui::ComboBox::from_id_salt("backstage_theme")
|
||||
.width(160.0)
|
||||
.selected_text(lang.tr(current))
|
||||
.show_ui(ui, |ui| {
|
||||
@@ -77,7 +77,7 @@ fn general_options(app: &mut SheetApp, ui: &mut Ui, lang: Language) {
|
||||
.labelled_by(label.id);
|
||||
ui.end_row();
|
||||
let label = ui.label(lang.tr("Interface language"));
|
||||
egui::ComboBox::from_id_salt("backstage_language")
|
||||
craft_ui::ComboBox::from_id_salt("backstage_language")
|
||||
.width(160.0)
|
||||
.selected_text(lang.name())
|
||||
.show_ui(ui, |ui| {
|
||||
|
||||
@@ -22,7 +22,7 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
|
||||
let pages: Vec<Json> = bs.preview.as_ref().and_then(|(_, p)| p.get("pageList")).and_then(Json::as_array).cloned().unwrap_or_default();
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(340.0);
|
||||
ui.set_width(250.0);
|
||||
if let Some(discover) = &app.services.printers {
|
||||
crate::printing::show(&mut app.printing, ui, discover, |label| lang.tr(label).to_owned());
|
||||
}
|
||||
@@ -35,7 +35,7 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
|
||||
}
|
||||
ui.add_space(16.0);
|
||||
let scope = if bs.print_all { "Print Entire Workbook" } else { "Print Active Sheets" };
|
||||
egui::ComboBox::from_id_salt("backstage_print_scope")
|
||||
craft_ui::ComboBox::from_id_salt("backstage_print_scope")
|
||||
.width(230.0)
|
||||
.selected_text(lang.tr(scope))
|
||||
.show_ui(ui, |ui| {
|
||||
|
||||
@@ -1,251 +0,0 @@
|
||||
//! 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;
|
||||
@@ -1,491 +0,0 @@
|
||||
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);
|
||||
}
|
||||
@@ -326,15 +326,14 @@ mod tests {
|
||||
// --- frames ---
|
||||
|
||||
fn harness(s: Session) -> Harness {
|
||||
let mut h =
|
||||
egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).with_context_setup(crate::framework::install_headless).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
SheetApp::new(s, Default::default()),
|
||||
);
|
||||
let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
SheetApp::new(s, Default::default()),
|
||||
);
|
||||
h.run_steps(8);
|
||||
h
|
||||
}
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
//! 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 crate::capture::CaptureSlot;
|
||||
use craft_ui::capture::CaptureSlot;
|
||||
use gridcraft_engine::core::CellRef;
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
|
||||
@@ -284,7 +284,6 @@ fn one_admitted_capture_issues_one_callback_and_replies_once() {
|
||||
let mut h = egui_kittest::Harness::builder()
|
||||
.with_size(egui::vec2(900.0, 700.0))
|
||||
.with_context_setup(|ctx| {
|
||||
crate::framework::install_headless(ctx);
|
||||
ctx.set_fonts(crate::theme::pinned_font_definitions());
|
||||
crate::theme::apply(ctx, false);
|
||||
})
|
||||
|
||||
@@ -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 crate::framework::escape_pressed(&ctx) {
|
||||
if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
app.grid.placing = None;
|
||||
app.grid.place_start = None;
|
||||
return true;
|
||||
|
||||
@@ -222,7 +222,7 @@ pub fn contributors_ui(ui: &mut egui::Ui) {
|
||||
}
|
||||
ui.separator();
|
||||
ui.label("Sort");
|
||||
egui::ComboBox::from_id_salt("credits_sort").selected_text(v.key.label().0).show_ui(ui, |ui| {
|
||||
craft_ui::ComboBox::from_id_salt("credits_sort").selected_text(v.key.label().0).show_ui(ui, |ui| {
|
||||
for k in SortKey::ALL {
|
||||
if ui.selectable_label(v.key == k, k.label().0).clicked() {
|
||||
v.key = k;
|
||||
|
||||
@@ -493,7 +493,7 @@ pub(super) fn solver(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, conf
|
||||
ui.horizontal(|ui| {
|
||||
ref_edit(app, ui, d, "newLhs", RefLabel::Named("Constraint Cell Reference"), 130.0);
|
||||
let op = text(d, "newOp");
|
||||
egui::ComboBox::from_id_salt("solverOp")
|
||||
craft_ui::ComboBox::from_id_salt("solverOp")
|
||||
.selected_text(op.clone())
|
||||
.width(60.0)
|
||||
.show_ui(ui, |ui| {
|
||||
@@ -539,7 +539,7 @@ pub(super) fn solver(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, conf
|
||||
"evolutionary" => "Evolutionary",
|
||||
_ => "GRG Nonlinear",
|
||||
};
|
||||
egui::ComboBox::from_id_salt("solverMethod")
|
||||
craft_ui::ComboBox::from_id_salt("solverMethod")
|
||||
.selected_text(label(&method))
|
||||
.show_ui(ui, |ui| {
|
||||
for m in ["grg", "simplex", "evolutionary"] {
|
||||
|
||||
@@ -118,7 +118,7 @@ pub(super) fn format_cells(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog
|
||||
ui.checkbox(&mut st.align.shrink, lang.tr("Shrink to fit"));
|
||||
}
|
||||
"Font" => {
|
||||
egui::ComboBox::from_label(lang.tr("Font")).selected_text(st.font.name.clone()).show_ui(ui, |ui| {
|
||||
craft_ui::ComboBox::from_label(lang.tr("Font")).selected_text(st.font.name.clone()).show_ui(ui, |ui| {
|
||||
for f in crate::fonts::families() {
|
||||
ui.selectable_value(&mut st.font.name, f.clone(), f.clone());
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ pub(super) fn insert_function(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dia
|
||||
let menu_was_open = egui::Popup::is_any_open(ui.ctx());
|
||||
let picker = ui.horizontal(|ui| {
|
||||
let label = ui.label(language.tr("Or select a category:"));
|
||||
egui::ComboBox::from_id_salt("insertFunctionCategory")
|
||||
craft_ui::ComboBox::from_id_salt("insertFunctionCategory")
|
||||
.width(220.0)
|
||||
.selected_text(language.tr(&category))
|
||||
.show_ui(ui, |ui| {
|
||||
@@ -48,7 +48,7 @@ pub(super) fn insert_function(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dia
|
||||
// Enter on the category list or in its menu opens it or picks a category, as Space does
|
||||
// (egui clicks a focused control on either key); it does not also confirm the dialog.
|
||||
let picker = picker.inner;
|
||||
if menu_was_open || picker.has_focus() || egui::ComboBox::is_open(ui.ctx(), picker.id) {
|
||||
if menu_was_open || picker.has_focus() || craft_ui::ComboBox::is_open(ui.ctx(), picker.id) {
|
||||
ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
|
||||
}
|
||||
if category != saved {
|
||||
|
||||
@@ -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 crate::framework::consume_escape(ctx) | ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) {
|
||||
if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape) | 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 crate::framework::escape_pressed(ctx) || !win_open {
|
||||
if ctx.input(|i| i.key_pressed(Key::Escape)) || !win_open {
|
||||
// In Solver Options, Escape (or closing the window) cancels the options only.
|
||||
if in_solver_options(&d) {
|
||||
cancel_solver_options(&mut d);
|
||||
@@ -655,7 +655,7 @@ pub(super) fn form_fields(app: &SheetApp, ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
let cur = d.values.get(key).and_then(Json::as_str).unwrap_or("").to_string();
|
||||
if d.name == "dataValidation" {
|
||||
let selected = options.iter().find(|(val, _)| *val == cur).map(|(_, text)| lang.tr(text)).unwrap_or("");
|
||||
egui::ComboBox::from_id_salt(("dataValidation", key))
|
||||
craft_ui::ComboBox::from_id_salt(("dataValidation", key))
|
||||
.selected_text(selected)
|
||||
.width(300.0)
|
||||
.show_ui(ui, |ui| {
|
||||
|
||||
@@ -337,7 +337,7 @@ fn levels_table(ui: &mut egui::Ui, levels: &mut [Json], selected: &mut usize, ch
|
||||
.iter()
|
||||
.find(|(l, _, _)| l.eq_ignore_ascii_case(&col))
|
||||
.map_or_else(|| column_label(lang, &col.to_ascii_uppercase()), |(_, t, _)| t.clone());
|
||||
let r = egui::ComboBox::from_id_salt(("col", i)).selected_text(shown).width(w).show_ui(ui, |ui| {
|
||||
let r = craft_ui::ComboBox::from_id_salt(("col", i)).selected_text(shown).width(w).show_ui(ui, |ui| {
|
||||
for (letters, label, _) in choices {
|
||||
ui.selectable_value(&mut col, letters.clone(), label);
|
||||
}
|
||||
@@ -353,7 +353,7 @@ fn levels_table(ui: &mut egui::Ui, levels: &mut [Json], selected: &mut usize, ch
|
||||
"fontColor" => "Font Color",
|
||||
_ => "Cell Values",
|
||||
});
|
||||
let r = egui::ComboBox::from_id_salt(("by", i)).selected_text(by_label).width(w).show_ui(ui, |ui| {
|
||||
let r = craft_ui::ComboBox::from_id_salt(("by", i)).selected_text(by_label).width(w).show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut by, "values".into(), lang.tr("Cell Values"));
|
||||
ui.selectable_value(&mut by, "cellColor".into(), lang.tr("Cell Color"));
|
||||
ui.selectable_value(&mut by, "fontColor".into(), lang.tr("Font Color"));
|
||||
@@ -368,7 +368,7 @@ fn levels_table(ui: &mut egui::Ui, levels: &mut [Json], selected: &mut usize, ch
|
||||
let (asc_label, desc_label) = (lang.tr(asc_label), lang.tr(desc_label));
|
||||
let mut desc = lv["order"].as_str() == Some("desc");
|
||||
let order_label = if desc { desc_label } else { asc_label };
|
||||
let r = egui::ComboBox::from_id_salt(("order", i)).selected_text(order_label).width(w).show_ui(ui, |ui| {
|
||||
let r = craft_ui::ComboBox::from_id_salt(("order", i)).selected_text(order_label).width(w).show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut desc, false, asc_label);
|
||||
ui.selectable_value(&mut desc, true, desc_label);
|
||||
});
|
||||
|
||||
@@ -18,12 +18,10 @@
|
||||
//!
|
||||
//! [`Session::windows`]: gridcraft_engine::Session::windows
|
||||
|
||||
use craft_window::{WindowId, WindowList};
|
||||
use egui::Rect;
|
||||
use craft_window::{CASCADE_STEP, Frame, Rect, Viewports, WindowEvent, WindowId, WindowList, cascade};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::SheetApp;
|
||||
use crate::viewports::{CASCADE_STEP, Viewports, WindowEvent};
|
||||
|
||||
/// The native windows (see the module docs).
|
||||
pub struct DocWindows {
|
||||
@@ -42,7 +40,8 @@ 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;
|
||||
DocWindows { list: WindowList::new(), viewports: Viewports::default(), base, quit_with_last_window, root_hidden: false }
|
||||
// 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 }
|
||||
}
|
||||
|
||||
/// The platform default for the last window closing: macOS keeps running, others quit.
|
||||
@@ -92,7 +91,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::from_min_size(egui::Pos2::ZERO, size));
|
||||
let mut rects = arrange_rects(arrange, ids.len(), Rect::new(0.0, 0.0, size.x, size.y));
|
||||
if arrange == "cascade" {
|
||||
// The active window goes in front: the last step of the cascade.
|
||||
rects.reverse();
|
||||
@@ -101,8 +100,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(r.min));
|
||||
ctx.send_viewport_cmd_to(vp, egui::ViewportCommand::InnerSize((r.size() - frame).max(egui::vec2(240.0, 160.0))));
|
||||
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))));
|
||||
}
|
||||
if let Some(first) = ids.first() {
|
||||
self.viewports.focus(ctx, *first);
|
||||
@@ -124,7 +123,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, id),
|
||||
Some(id) => self.viewports.adopt(ctx, &self.list, id),
|
||||
None => self.viewports.set_root(None),
|
||||
}
|
||||
}
|
||||
@@ -206,7 +205,7 @@ impl DocWindows {
|
||||
match event {
|
||||
WindowEvent::Focused(_) => {}
|
||||
WindowEvent::CloseRequested(id) => {
|
||||
if let Some(w) = self.close_requested(app, id) {
|
||||
if let Some(w) = self.close_requested(app, &ctx, id) {
|
||||
requested = Some(w);
|
||||
}
|
||||
}
|
||||
@@ -229,13 +228,16 @@ 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.
|
||||
/// 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> {
|
||||
fn close_requested(&mut self, app: &mut SheetApp, ctx: &egui::Context, id: WindowId) -> Option<u64> {
|
||||
let is_root = self.viewports.root() == Some(id);
|
||||
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,28 +273,34 @@ 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::from_min_size(bounds.min + egui::vec2(0.0, h * i as f32), egui::vec2(bounds.width(), h))).collect()
|
||||
let h = bounds.height / count;
|
||||
(0..n).map(|i| Rect::new(bounds.x, bounds.y + h * i as f32, bounds.width, h)).collect()
|
||||
}
|
||||
"vertical" => {
|
||||
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()
|
||||
let w = bounds.width / count;
|
||||
(0..n).map(|i| Rect::new(bounds.x + w * i as f32, bounds.y, w, bounds.height)).collect()
|
||||
}
|
||||
"cascade" => {
|
||||
let shift = CASCADE_STEP * (count - 1.0);
|
||||
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 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 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::from_min_size(bounds.min + egui::vec2(w * col as f32, h * row as f32), egui::vec2(w, h))
|
||||
let w = bounds.width / in_row as f32;
|
||||
Rect::new(bounds.x + w * col as f32, bounds.y + h * row as f32, w, h)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1,152 +0,0 @@
|
||||
//! 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. A grid that holds egui focus keeps Escape and the clipboard
|
||||
//! events in egui as one of GridCraft's own widgets does.
|
||||
|
||||
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 mut root = RootEnv::new().mode(mode).scale(Scale::new(self.ui.zoom_factor()));
|
||||
// GridCraft's rule for every text field, the framework's ones included (the print page's Copies): Escape
|
||||
// leaves the field, and only the next Escape reaches the view (it closes File).
|
||||
root.escape_leaves_fields = true;
|
||||
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. 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,22 +648,19 @@ 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, 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.
|
||||
/// 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.
|
||||
fn spend_escape(ctx: &egui::Context) -> bool {
|
||||
let in_egui = ctx.input_mut(|i| {
|
||||
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<'_>) {
|
||||
@@ -813,7 +810,7 @@ fn handle_release(app: &mut SheetApp, input: &InteractionInput<'_>) {
|
||||
Drag::Fill { target: Some(t), menu: true } => {
|
||||
if let Some(p) = pos
|
||||
&& t != sel.current()
|
||||
&& !crate::framework::consume_escape(&ctx)
|
||||
&& !ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
|
||||
{
|
||||
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
|
||||
|| crate::framework::escape_pressed(ui.ctx())
|
||||
|| ui.input(|i| i.key_pressed(egui::Key::Escape))
|
||||
|| (!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
|
||||
|| crate::framework::escape_pressed(ui.ctx())
|
||||
|| ui.input(|i| i.key_pressed(egui::Key::Escape))
|
||||
|| (ui.input(|i| i.pointer.any_pressed())
|
||||
&& !resp.response.contains_pointer()
|
||||
&& !resp.response.hovered()
|
||||
|
||||
@@ -407,7 +407,6 @@ fn upward_text_with_middle_align_is_centred_in_a_merged_block() {
|
||||
/// One grid frame of `app` in a headless context.
|
||||
fn grid_frame(app: &mut crate::SheetApp) {
|
||||
let ctx = egui::Context::default();
|
||||
crate::framework::install_headless(&ctx);
|
||||
let screen = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(1200.0, 800.0));
|
||||
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| super::show(app, ui));
|
||||
out.textures_delta.clear(); // nothing consumes the uploads in a headless test
|
||||
|
||||
@@ -120,7 +120,15 @@ impl KeyTips {
|
||||
} else if self.prefix.is_some() && !matches!(key, Key::ShiftLeft | Key::ShiftRight) {
|
||||
handled = true;
|
||||
if *key == Key::Escape {
|
||||
self.back();
|
||||
// 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();
|
||||
}
|
||||
}
|
||||
} 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) {
|
||||
@@ -163,25 +171,9 @@ 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,13 +17,11 @@ pub const UPDATE_APP: craft_update::app::App = craft_update::app::App {
|
||||
|
||||
pub mod backstage;
|
||||
mod border_preview;
|
||||
mod capture;
|
||||
mod cell_pictures;
|
||||
pub mod channel;
|
||||
mod chartcache;
|
||||
pub mod chartview;
|
||||
pub mod code_editor;
|
||||
mod combo_menu;
|
||||
pub mod control;
|
||||
pub mod control_ui;
|
||||
mod craft_fonts_policy;
|
||||
@@ -40,7 +38,6 @@ 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;
|
||||
@@ -63,8 +60,6 @@ mod text_direction;
|
||||
pub mod theme;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod updates_ui;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod viewports;
|
||||
pub mod widgets;
|
||||
mod window_ui;
|
||||
pub mod wordart;
|
||||
@@ -353,11 +348,6 @@ 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 crate::framework::escape_pressed(ctx) && ed.picker.is_some() {
|
||||
if ctx.input(|i| i.key_pressed(egui::Key::Escape)) && 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() || crate::framework::escape_pressed(ui.ctx()) {
|
||||
if ui.button("Cancel").clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
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() || crate::framework::escape_pressed(ui.ctx()) {
|
||||
if ui.button("Cancel").clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
answer = Some(None);
|
||||
}
|
||||
if ui.button("Don't Save").clicked() {
|
||||
@@ -1880,7 +1880,7 @@ fn step_tab(app: &mut SheetApp, ui: &mut Ui, d: &mut Dialog, ed: &mut Editor) {
|
||||
(CompareOp::Contains, "contains"),
|
||||
];
|
||||
let label = ops.iter().find(|(o, _)| *o == op).map_or("", |x| x.1);
|
||||
egui::ComboBox::from_id_salt(("me_op", &path)).selected_text(label).show_ui(ui, |ui| {
|
||||
craft_ui::ComboBox::from_id_salt(("me_op", &path)).selected_text(label).show_ui(ui, |ui| {
|
||||
for (o, l) in ops {
|
||||
ui.selectable_value(&mut op2, o, l);
|
||||
}
|
||||
@@ -2120,7 +2120,7 @@ fn inputs_tab(app: &mut SheetApp, ui: &mut Ui, d: &mut Dialog, ed: &mut Editor)
|
||||
ui.label(label);
|
||||
let mut ty = i.col_types.get(c).copied().unwrap_or(ColType::Any);
|
||||
let before_ty = ty;
|
||||
egui::ComboBox::from_id_salt(("me_ty", c)).selected_text(type_name(ty)).show_ui(ui, |ui| {
|
||||
craft_ui::ComboBox::from_id_salt(("me_ty", c)).selected_text(type_name(ty)).show_ui(ui, |ui| {
|
||||
for x in [ColType::Any, ColType::Number, ColType::Text, ColType::Date, ColType::Bool] {
|
||||
ui.selectable_value(&mut ty, x, type_name(x));
|
||||
}
|
||||
|
||||
@@ -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() || crate::framework::escape_pressed(ui.ctx()) {
|
||||
if ui.button("Cancel").clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
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 !crate::framework::escape_pressed(ui.ctx()) {
|
||||
if !ui.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
// 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 crate::framework::escape_pressed(ui.ctx()) || current == value { None } else { Some(current) }
|
||||
if ui.input(|i| i.key_pressed(egui::Key::Escape)) || 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, Painter, Pos2, Rect, Stroke, StrokeKind, TextEdit, pos2, vec2};
|
||||
use egui::{Align2, Color32, FontId, Key, 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 crate::framework::consume_escape(ui.ctx()) {
|
||||
if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) {
|
||||
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 crate::framework::consume_escape(ui.ctx()) {
|
||||
if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) {
|
||||
app.grid.ruler_drag = None;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -181,7 +181,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui) {
|
||||
if ui.button(lang.tr("Calculated Field…")).clicked() {
|
||||
app.run_or_alert("pivot.calculatedField", json!({"pivot": name}));
|
||||
}
|
||||
egui::ComboBox::from_id_salt("pv_layout")
|
||||
craft_ui::ComboBox::from_id_salt("pv_layout")
|
||||
.selected_text(lang.tr("Report Layout"))
|
||||
.show_ui(ui, |ui| {
|
||||
for (l, v) in [("Compact", "compact"), ("Outline", "outline"), ("Tabular", "tabular")] {
|
||||
|
||||
@@ -1,27 +1,33 @@
|
||||
//! 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};
|
||||
//! 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};
|
||||
|
||||
/// Draws the shared print controls and the feedback of the last discovery or job.
|
||||
/// Draws the shared print controls.
|
||||
///
|
||||
/// `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.
|
||||
/// `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.
|
||||
pub fn show(state: &mut State, ui: &mut egui::Ui, discover: &Discover, translate: impl Fn(&str) -> String) {
|
||||
ui.push_id("gridcraft_print_settings", |ui| state.run(ui, discover));
|
||||
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);
|
||||
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> {
|
||||
@@ -39,7 +45,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.destination = Destination::Printer(printer.to_owned());
|
||||
next.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")?;
|
||||
@@ -75,11 +81,10 @@ 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": 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" },
|
||||
"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" },
|
||||
"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,
|
||||
@@ -96,6 +101,5 @@ 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 = crate::combo_menu::Menu::new(ui, &field).height(height);
|
||||
let menu = craft_ui::combo::Menu::new(ui, &field).height(height);
|
||||
let text_id = anchor.id.with(salt).with("__combo_text");
|
||||
let sel0 = st.sel;
|
||||
let shown = if filter {
|
||||
|
||||
@@ -107,7 +107,7 @@ pub(super) fn view(app: &mut SheetApp, ui: &mut Ui) {
|
||||
"dark" => "Dark",
|
||||
_ => "Light",
|
||||
};
|
||||
egui::ComboBox::from_id_salt("display_theme")
|
||||
craft_ui::ComboBox::from_id_salt("display_theme")
|
||||
.selected_text(lang.tr(label))
|
||||
.width(88.0)
|
||||
.show_ui(ui, |ui| {
|
||||
@@ -131,7 +131,7 @@ pub(super) fn view(app: &mut SheetApp, ui: &mut Ui) {
|
||||
let label = ui.label(egui::RichText::new(lang.tr("Interface size")).font(theme::ui_font(11.5)).color(t.text_dim));
|
||||
let current = app.ui.interface_scale;
|
||||
let text = |v: u16| if v == 100 { lang.tr("Auto").to_string() } else { format!("{v}%") };
|
||||
egui::ComboBox::from_id_salt("ui_interface_size")
|
||||
craft_ui::ComboBox::from_id_salt("ui_interface_size")
|
||||
.width(120.0)
|
||||
.selected_text(egui::RichText::new(text(current)).font(theme::ui_font(12.5)))
|
||||
.show_ui(ui, |ui| {
|
||||
@@ -148,7 +148,7 @@ pub(super) fn view(app: &mut SheetApp, ui: &mut Ui) {
|
||||
// the current language so it stays readable; the choices are always shown in their own script.
|
||||
ui.vertical(|ui| {
|
||||
let label = ui.label(egui::RichText::new(lang.tr("Interface language")).font(theme::ui_font(11.5)).color(t.text_dim));
|
||||
egui::ComboBox::from_id_salt("ui_language")
|
||||
craft_ui::ComboBox::from_id_salt("ui_language")
|
||||
.width(120.0)
|
||||
.selected_text(egui::RichText::new(lang.name()).font(theme::ui_font(12.5)))
|
||||
.show_ui(ui, |ui| {
|
||||
|
||||
@@ -270,7 +270,7 @@ pub fn sheet_tabs(app: &mut SheetApp, ui: &mut Ui) {
|
||||
ed.request_focus();
|
||||
}
|
||||
if ed.lost_focus() {
|
||||
if !crate::framework::escape_pressed(ui.ctx()) && text != name {
|
||||
if !ui.input(|i| i.key_pressed(egui::Key::Escape)) && 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 crate::framework::consume_escape(ctx) {
|
||||
if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) {
|
||||
app.cancel_text_box_edit();
|
||||
ctx.memory_mut(|m| m.surrender_focus(editor_id()));
|
||||
return;
|
||||
|
||||
@@ -526,11 +526,6 @@ 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 signature family follows the proportional one; a family left out draws
|
||||
// missing-glyph boxes. Its semibold role falls back to the proportional family when the
|
||||
// definitions have no semibold family.
|
||||
let proportional = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
|
||||
fonts.families.insert(craft_ui::fonts::FontRef::signature().family(), proportional);
|
||||
// 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,10 +1,8 @@
|
||||
//! 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`; its dialogs run on the app's
|
||||
//! [`DialogHost`](craft_ui::dialog::DialogHost).
|
||||
//! itself is `craft_update::updater::Updater`.
|
||||
|
||||
use craft_ui::dialog::DialogResult;
|
||||
use craft_update::stack_dialogs::{CheckChoice, UpdateCheckDialog};
|
||||
use craft_update::CheckResultResponse;
|
||||
use craft_update::updater::{Action, Status, Updater};
|
||||
|
||||
use crate::SheetApp;
|
||||
@@ -37,9 +35,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();
|
||||
rt.updater.check_now(ctx);
|
||||
} else if rt.startup {
|
||||
rt.updater.check_at_start();
|
||||
rt.updater.check_at_start(ctx);
|
||||
}
|
||||
rt.updater.tick(ctx);
|
||||
}
|
||||
@@ -56,50 +54,28 @@ 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());
|
||||
// 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);
|
||||
match app.updates_rt.updater.show_if(ctx, clean) {
|
||||
Action::OpenUrl(url) => {
|
||||
if let Some(open) = &app.services.open_url {
|
||||
open(&url);
|
||||
}
|
||||
}
|
||||
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 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);
|
||||
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 => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,207 +0,0 @@
|
||||
//! 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 (!crate::framework::escape_pressed(ui.ctx())).then_some(text);
|
||||
return (!ui.input(|i| i.key_pressed(egui::Key::Escape))).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)) || crate::framework::escape_pressed(ui.ctx()) {
|
||||
if ui.button(" OK ").clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter) || i.key_pressed(egui::Key::Escape)) {
|
||||
close = true;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -13,17 +13,14 @@ 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_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()),
|
||||
);
|
||||
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()),
|
||||
);
|
||||
h.run_steps(4);
|
||||
if formula_bar {
|
||||
h.get_by_label(text).click();
|
||||
|
||||
@@ -49,7 +49,6 @@ 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] {
|
||||
@@ -73,7 +72,6 @@ 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();
|
||||
@@ -141,7 +139,6 @@ 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,12 +14,10 @@ use gridcraft_ui_egui::{Services, SheetApp};
|
||||
|
||||
pub type Harness = egui_kittest::Harness<'static, SheetApp>;
|
||||
|
||||
/// A kittest builder with the UI runtime, the deterministic font set and GridCraft's visuals
|
||||
/// installed.
|
||||
/// A kittest builder with 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);
|
||||
craft_ui::fonts::load(ctx, gridcraft_ui_egui::theme::pinned_font_definitions());
|
||||
ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions());
|
||||
gridcraft_ui_egui::theme::apply(ctx, false);
|
||||
})
|
||||
}
|
||||
@@ -35,7 +33,7 @@ pub fn prepare(mut app: SheetApp) -> SheetApp {
|
||||
app
|
||||
}
|
||||
|
||||
/// Drive `app`'s `logic`, its close path, then `ui` each frame in a harness built with `builder`.
|
||||
/// Drive `app`'s `logic` 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`
|
||||
@@ -45,7 +43,6 @@ 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,7 +42,6 @@ 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;
|
||||
@@ -78,7 +77,6 @@ impl Desk {
|
||||
}
|
||||
app.logic(&ctx);
|
||||
windows.logic(app, &ctx);
|
||||
app.close_path(&ctx);
|
||||
windows.show(app, ui);
|
||||
});
|
||||
record(out);
|
||||
@@ -460,8 +458,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 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));
|
||||
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);
|
||||
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,17 +25,13 @@ 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_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()),
|
||||
);
|
||||
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()),
|
||||
);
|
||||
h.run_steps(4);
|
||||
h.state_mut().session.active_mut().unwrap().undo.clear();
|
||||
h.state_mut().session.journal.clear();
|
||||
|
||||
@@ -27,7 +27,6 @@ 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,7 +18,6 @@ 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,12 +12,8 @@ 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_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(
|
||||
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(
|
||||
|ui, app: &mut SheetApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
|
||||
@@ -114,8 +114,7 @@ fn escape_leaves_file_fields_before_closing_the_view() {
|
||||
let copies = h.state().printing.settings.copies;
|
||||
|
||||
h.key_press(egui::Key::Escape);
|
||||
// With GridCraft's frame input, as the shells give it: Escape leaves the framework's fields too.
|
||||
crate::support::frames(&mut h, 3);
|
||||
h.run_steps(3);
|
||||
assert_eq!(page(&h), Some(page_id), "Esc in {label} keeps File open");
|
||||
assert!(!h.ctx.text_edit_focused(), "Esc leaves {label}");
|
||||
assert_eq!(h.state().session.active().unwrap().revision, revision, "Esc does not commit {label}");
|
||||
@@ -126,8 +125,7 @@ fn escape_leaves_file_fields_before_closing_the_view() {
|
||||
}
|
||||
|
||||
h.key_press(egui::Key::Escape);
|
||||
// With GridCraft's frame input, as the shells give it: Escape leaves the framework's fields too.
|
||||
crate::support::frames(&mut h, 3);
|
||||
h.run_steps(3);
|
||||
assert_eq!(page(&h), None, "the next Esc returns to the sheet");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,6 @@ 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)
|
||||
@@ -592,7 +591,6 @@ 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,7 +31,6 @@ 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();
|
||||
@@ -58,7 +57,6 @@ 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();
|
||||
@@ -97,7 +95,6 @@ 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();
|
||||
@@ -115,7 +112,6 @@ 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();
|
||||
@@ -135,7 +131,6 @@ 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();
|
||||
@@ -167,7 +162,6 @@ 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();
|
||||
@@ -220,7 +214,6 @@ 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();
|
||||
@@ -264,7 +257,6 @@ 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,7 +23,6 @@ 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();
|
||||
@@ -48,7 +47,6 @@ 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();
|
||||
@@ -66,7 +64,6 @@ 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();
|
||||
@@ -94,7 +91,6 @@ 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);
|
||||
|
||||
@@ -37,9 +37,7 @@ fn right_click_row_header(h: &mut Harness, cell: &str) {
|
||||
h.input_mut().events.push(Event::PointerMoved(pos));
|
||||
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE });
|
||||
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE });
|
||||
// The runtime takes one press per frame: the release arrives in the next frame, and the frame
|
||||
// after it shows what the click did.
|
||||
h.run_steps(3);
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -70,9 +68,7 @@ fn right_click_col_header(h: &mut Harness, cell: &str) {
|
||||
h.input_mut().events.push(Event::PointerMoved(pos));
|
||||
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE });
|
||||
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE });
|
||||
// The runtime takes one press per frame: the release arrives in the next frame, and the frame
|
||||
// after it shows what the click did.
|
||||
h.run_steps(3);
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
/// As in Excel, the row and column header menus offer Format Cells… for the selected lines.
|
||||
|
||||
@@ -16,11 +16,11 @@ fn interface_size_applies_persists_and_clamps() {
|
||||
},
|
||||
crate::common::app(session),
|
||||
);
|
||||
crate::support::frames(&mut h, 2);
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.ctx.zoom_factor(), 1.0);
|
||||
|
||||
h.state_mut().run("view.interfaceScale", json!({"percent": 125})).unwrap();
|
||||
crate::support::frames(&mut h, 2);
|
||||
h.run_steps(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();
|
||||
crate::support::frames(&mut h, 2);
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.ctx.zoom_factor(), 1.0);
|
||||
|
||||
// A malformed or out-of-range ui.json keeps the other preferences.
|
||||
|
||||
@@ -20,18 +20,14 @@ 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_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.close_path(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
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,
|
||||
);
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
@@ -570,16 +566,14 @@ 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_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.close_path(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
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,
|
||||
);
|
||||
h.run_steps(4);
|
||||
three(&mut h);
|
||||
h.run_steps(4);
|
||||
|
||||
@@ -16,17 +16,14 @@ 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_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,
|
||||
);
|
||||
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,
|
||||
);
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
@@ -118,17 +115,14 @@ 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_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,
|
||||
);
|
||||
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,
|
||||
);
|
||||
h.run_steps(3);
|
||||
h.state_mut().open_dialog("macros", json!({}));
|
||||
h.run_steps(2);
|
||||
@@ -266,17 +260,14 @@ 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_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,
|
||||
);
|
||||
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,
|
||||
);
|
||||
h.run_steps(3);
|
||||
h.state_mut().open_dialog("macros", json!({}));
|
||||
h.run_steps(2);
|
||||
@@ -300,15 +291,14 @@ 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_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,
|
||||
);
|
||||
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,
|
||||
);
|
||||
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"][..])] {
|
||||
|
||||
@@ -39,9 +39,7 @@ fn click_cell(h: &mut Harness, cell: &str) {
|
||||
Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE },
|
||||
Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE },
|
||||
]);
|
||||
// The runtime takes one press per frame: the release arrives in the next frame, and the frame
|
||||
// after it shows what the click did.
|
||||
h.run_steps(3);
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
fn text(h: &mut Harness, text: &str) {
|
||||
|
||||
@@ -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::{Destination, Duplex, Feedback, Printer};
|
||||
use gridcraft_ui_egui::printing::{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::new("Chosen queue"));
|
||||
app.printing.printers.push(Printer { name: "Chosen queue".into(), label: String::new(), default: false });
|
||||
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.destination, Destination::Printer("Chosen queue".into()));
|
||||
assert_eq!(jobs[0].1.printer, "Chosen queue");
|
||||
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::new("Test queue").is_default(true)]).unwrap();
|
||||
sender.send(vec![Printer { name: "Test queue".into(), label: String::new(), 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").accesskit_node().is_disabled());
|
||||
assert!(!harness.get_by_label("Refresh printers").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::new("Queue").is_default(true));
|
||||
app.printing.printers.push(Printer { name: "Queue".into(), label: String::new(), 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::new("Queue").is_default(true));
|
||||
app.printing.printers.push(Printer { name: "Queue".into(), label: String::new(), 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,7 +53,6 @@ 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,7 +18,6 @@ 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| {
|
||||
@@ -77,17 +76,14 @@ 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_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()),
|
||||
);
|
||||
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()),
|
||||
);
|
||||
h.run_steps(4);
|
||||
let first = h.get_by_label("F1").rect();
|
||||
// A floating scrollbar is drawn while the pointer is over its area.
|
||||
|
||||
@@ -34,9 +34,7 @@ fn double_click(h: &mut egui_kittest::Harness<'_, SheetApp>, pos: Pos2) {
|
||||
Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE },
|
||||
Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE },
|
||||
]);
|
||||
// The runtime takes one press per frame: the release arrives in the next frame, and the frame
|
||||
// after it shows what the click did.
|
||||
h.run_steps(3);
|
||||
h.run_steps(2);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -52,9 +52,7 @@ fn click(h: &mut Harness, pos: Pos2, button: PointerButton) {
|
||||
h.input_mut().events.push(Event::PointerMoved(pos));
|
||||
h.input_mut().events.push(Event::PointerButton { pos, button, pressed: true, modifiers: Modifiers::NONE });
|
||||
h.input_mut().events.push(Event::PointerButton { pos, button, pressed: false, modifiers: Modifiers::NONE });
|
||||
// The runtime takes one press per frame: the release arrives in the next frame, and the frame
|
||||
// after it shows what the click did.
|
||||
h.run_steps(3);
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
fn open(h: &mut Harness, menu: Menu) {
|
||||
|
||||
@@ -91,8 +91,7 @@ fn click_at(h: &mut H, pos: egui::Pos2) {
|
||||
h.input_mut().events.push(Event::PointerMoved(pos));
|
||||
press(h, pos, true);
|
||||
press(h, pos, false);
|
||||
// The runtime takes one press per frame: the release arrives in the next frame.
|
||||
h.run_steps(4);
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
fn key(h: &mut H, k: Key, m: Modifiers) {
|
||||
|
||||
@@ -190,7 +190,6 @@ 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,13 +39,3 @@ 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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,9 +43,7 @@ fn input_message_hides_while_the_list_is_open() {
|
||||
h.input_mut().events.push(Event::PointerMoved(pos));
|
||||
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
|
||||
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
// The runtime takes one press per frame: the release arrives in the next frame, and the frame
|
||||
// after it shows what the click did.
|
||||
h.run_steps(3);
|
||||
h.run_steps(2);
|
||||
|
||||
assert!(h.state().grid.list_picker.is_some(), "the dropdown arrow opens the list");
|
||||
assert!(h.query_by_label("Green").is_some(), "the list shows its items");
|
||||
|
||||
@@ -202,9 +202,7 @@ fn typing_over_the_open_dropdown_replaces_it_with_the_searched_list() {
|
||||
h.input_mut().events.push(Event::PointerMoved(pos));
|
||||
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
|
||||
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
// The runtime takes one press per frame: the release arrives in the next frame, and the frame
|
||||
// after it shows what the click did.
|
||||
h.run_steps(3);
|
||||
h.run_steps(2);
|
||||
assert!(h.state().grid.list_picker.is_some(), "the arrow opens the full list");
|
||||
assert!(shown(&h, "Paris - France"));
|
||||
|
||||
|
||||
@@ -25,17 +25,14 @@ 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_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()),
|
||||
);
|
||||
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()),
|
||||
);
|
||||
h.run_steps(4);
|
||||
h.state_mut().selected_object = None;
|
||||
h.run_steps(2);
|
||||
|
||||
Reference in New Issue
Block a user