git clone https://garage44.eu/jeroen/cartopolis.gitcartopolis-agent · 2026-11-26T13:46:52Z
refactor(gui): the keyboard, the web's sky and the map's free area without egui The last things egui did for the interface, short of being removed: - The on-screen keyboard is the library's alone: it comes up while a library field has the focus and types through KeyEdits; egui's event injection, focus following and strip claiming are gone. Keys read Touches and type on the lift, several fingers at once; a held backspace repeats (0.45 s, then every 0.06 s); the character under a finger shows above its key. The top-or-bottom flip is decided once a field has settled and held, so a composer lifting above the keys does not make them flap. The web uses the browser's own keyboard. - The cosmos' sky on the web is Mesh2d on a camera of its own (no LibCamera there): ui-dom adds bevy_sprite_render; cosmos.rs paints nothing in egui anywhere (drive_cosmos). - The map's free area comes from the library's layout: each panel that takes room from the map carries data-reserves-map (right or bottom), and lib_host measures what they leave (bevy_ui natively, the DOM's boxes on the web) into UiInput::map_rect. panel_slots and its empty egui strips are gone; on a wide screen the search bar still stands beside an open panel. With no egui panel left, the panel-chain scan test and the "hand-drawn controls are named" rule check nothing and go, as do the egui helpers only they or egui's panels used.
crates/cartopolis/Cargo.toml | 4 +-
crates/cartopolis/src/source_rules.rs | 92 +-
crates/cartopolis/src/systems/dev/ui_probe.rs | 8 +
crates/cartopolis/src/systems/gui/chat_overlay.rs | 12 +-
crates/cartopolis/src/systems/gui/cosmos.rs | 784 ++++-----
crates/cartopolis/src/systems/gui/egui_manager.rs | 192 +--
.../src/systems/gui/egui_manager/tests.rs | 213 +--
crates/cartopolis/src/systems/gui/lib_about.rs | 2 +-
crates/cartopolis/src/systems/gui/lib_admin.rs | 2 +-
crates/cartopolis/src/systems/gui/lib_avatar.rs | 11 +-
crates/cartopolis/src/systems/gui/lib_chats.rs | 2 +-
crates/cartopolis/src/systems/gui/lib_cosmos.rs | 122 +-
.../cartopolis/src/systems/gui/lib_cosmos_sky.rs | 198 ++-
.../cartopolis/src/systems/gui/lib_design_room.rs | 4 +-
crates/cartopolis/src/systems/gui/lib_driver.rs | 2 +-
crates/cartopolis/src/systems/gui/lib_host.rs | 130 +-
crates/cartopolis/src/systems/gui/lib_interact.rs | 2 +-
crates/cartopolis/src/systems/gui/lib_keyboard.rs | 282 +--
crates/cartopolis/src/systems/gui/lib_layers.rs | 2 +-
.../cartopolis/src/systems/gui/lib_midas_link.rs | 4 +-
crates/cartopolis/src/systems/gui/lib_models.rs | 2 +-
crates/cartopolis/src/systems/gui/lib_places.rs | 2 +-
.../src/systems/gui/lib_release_approval.rs | 2 +-
crates/cartopolis/src/systems/gui/lib_script.rs | 2 +-
crates/cartopolis/src/systems/gui/lib_search.rs | 2 +-
crates/cartopolis/src/systems/gui/lib_settings.rs | 5 +-
.../cartopolis/src/systems/gui/lib_walk_guide.rs | 2 +-
crates/cartopolis/src/systems/gui/mod.rs | 3 +-
crates/cartopolis/src/systems/gui/motion.rs | 159 +-
.../src/systems/gui/onscreen_keyboard.rs | 1794 +++++++-------------
.../src/systems/gui/onscreen_keyboard/tests.rs | 841 ++++-----
crates/cartopolis/src/systems/gui/panel_slots.rs | 82 -
crates/cartopolis/src/systems/gui/plugin.rs | 49 +-
crates/cartopolis/src/systems/gui/theme/frames.rs | 28 -
crates/cartopolis/src/systems/gui/theme/metrics.rs | 4 +-
crates/cartopolis/src/systems/gui/theme/tests.rs | 2 +-
crates/cartopolis/src/systems/gui/ui_input.rs | 138 +-
crates/cartopolis/src/systems/mod.rs | 12 +-
crates/cartopolis/src/systems/nav/driver/tests.rs | 2 +-
crates/cartopolis/src/systems/net/user_store.rs | 3 +-
crates/cartopolis/src/systems/player/interact.rs | 4 +-
crates/mithril_bevy/src/access.rs | 22 +
crates/mithril_bevy/src/lib.rs | 4 +-
docs/notes/component-library-in-the-client.md | 28 +-
44 files changed, 2043 insertions(+), 3217 deletions(-)
diff --git a/crates/cartopolis/Cargo.toml b/crates/cartopolis/Cargo.toml
index b73e84e6..6f2bd97a 100644
--- a/crates/cartopolis/Cargo.toml
+++ b/crates/cartopolis/Cargo.toml
@@ -144,7 +144,9 @@ scalar-fallback = []
# backend the lane has: `ui-probe` draws them through `bevy_ui` (native),
# `ui-dom` as DOM over the canvas (the web build, `systems::lib_host`).
ui-lib = ["dep:mithril"]
-ui-dom = ["ui-lib", "mithril/dom"]
+# `bevy_sprite_render`: the cosmos' sky is Mesh2d on a camera of its own on
+# the web (`lib_cosmos_sky`); natively bevy_ui_render pulls it in.
+ui-dom = ["ui-lib", "mithril/dom", "bevy/bevy_sprite_render"]
ui-probe = [
"ui-lib",
"dep:mithril_bevy",
diff --git a/crates/cartopolis/src/source_rules.rs b/crates/cartopolis/src/source_rules.rs
index ccc15550..82349ae2 100644
--- a/crates/cartopolis/src/source_rules.rs
+++ b/crates/cartopolis/src/source_rules.rs
@@ -5,9 +5,8 @@
//! sources rather than the types because none of them is a type error: a
//! `Res<EguiManager>` compiles everywhere but the web, and a `NoFrustumCulling`
//! without `NotShadowCaster` compiles and draws, just into every shadow cascade.
-//! The panel chain (`egui_manager::every_root_ui_panel_is_in_the_chain`) and the
-//! one tile fixture (`cartopolis_geo::testdata`) are held the same way, where
-//! they live.
+//! The one tile fixture (`cartopolis_geo::testdata`) is held the same way,
+//! where it lives.
//!
//! Comment lines are skipped, so the comments explaining a rule can name what
//! it forbids.
@@ -138,90 +137,6 @@ fn no_frustum_culling_comes_with_not_shadow_caster() {
);
}
-/// A control painted by hand — a rect given a click sense and drawn over —
-/// carries no name of its own, so the client's `ui_tree` tool (egui's AccessKit
-/// tree, `systems/dev/mcp/screen.rs`) lists it as "clickable area (no label)"
-/// and nobody driving the client can tell it from the next one. Every such
-/// rect under `src/systems` is named where it is made: `theme::named(ui, resp,
-/// "What it does")`, or `resp.widget_info(..)` for a switch or a choice that
-/// has an on state. One that is not a control (a backdrop that only swallows
-/// touches) says so with an `// unnamed: <why>` comment on the line above.
-///
-/// Widgets that carry their own text (`Label`, `Button`, a `UiBuilder::sense`
-/// row, all `.sense(..)`) are left to it; a sense picked into a variable
-/// first is out of the scan's reach, so name those by hand all the same.
-/// `#[cfg(test)] mod`s are not scanned, nor a module's `tests.rs`.
-#[test]
-fn hand_drawn_controls_are_named() {
- const CALLS: &[&str] = &[
- "allocate_exact_size(",
- "allocate_rect(",
- "interact(",
- "map_disc(",
- ];
- const SENSES: &[&str] = &["Sense::click()", "Sense::click_and_drag()"];
- // A call split over lines names its sense up to this many lines after itself.
- const BACK: usize = 3;
- // The name may come this many lines after the sense.
- const AHEAD: usize = 10;
- let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/systems");
- let mut bad = Vec::new();
- for (path, text) in sources() {
- if !path.starts_with(&root) || path.ends_with("tests.rs") {
- continue;
- }
- let lines: Vec<&str> = text.lines().collect();
- // Everything from the test module on is tests.
- let end = (1..lines.len())
- .find(|&j| {
- lines[j - 1].trim_start().starts_with("#[cfg(test)]")
- && lines[j].trim_start().starts_with("mod ")
- })
- .unwrap_or(lines.len());
- for (i, line) in lines.iter().enumerate().take(end) {
- if is_comment(line)
- || line.contains(".sense(")
- || !SENSES.iter().any(|s| line.contains(s))
- {
- continue;
- }
- let Some(call) = (i.saturating_sub(BACK)..=i)
- .rev()
- .find(|&j| !is_comment(lines[j]) && CALLS.iter().any(|c| lines[j].contains(c)))
- else {
- continue;
- };
- let near = &lines[i.saturating_sub(BACK)..(i + AHEAD + 1).min(lines.len())];
- let named = near
- .iter()
- .any(|l| l.contains("named(") || l.contains("widget_info"));
- let marked = lines[call.saturating_sub(1)..=i]
- .iter()
- .any(|l| l.contains("// unnamed:"));
- if !named && !marked {
- let rel = path
- .strip_prefix(env!("CARGO_MANIFEST_DIR"))
- .unwrap_or(&path);
- bad.push(format!(
- "{}:{}: {}",
- rel.display(),
- call + 1,
- lines[call].trim()
- ));
- }
- }
- }
- assert!(
- bad.is_empty(),
- "a hand-drawn control has no name, so `ui_tree` shows it as \"clickable area (no \
- label)\". Name it right after it is made, with the words a person sees on it or a \
- short phrase for what it does: `let resp = theme::named(ui, resp, \"Send\");` (or \
- `resp.widget_info(|| egui::WidgetInfo::selected(..))` for a switch or a choice). If \
- it is not a control at all, put `// unnamed: <why>` on the line above it:\n{}",
- bad.join("\n")
- );
-}
-
/// `std::time::Instant::now()` and `SystemTime::now()` panic on wasm32 ("time
/// not implemented on this platform"), and a panic is `abort` there, so the
/// browser client dies: the watchdog's clock did it to every browser at its
@@ -313,7 +228,7 @@ fn every_animation_goes_through_motion() {
.collect();
assert!(
hits.is_empty(),
- "animate through `motion::presence` / `toggle` / `value` / `press`, never egui's `animate_*` directly:\n{}",
+ "take durations and curves from `systems::motion`, never egui's `animate_*` directly:\n{}",
hits.join("\n")
);
}
@@ -370,7 +285,6 @@ const EGUI_OWN_FILES: &[&str] = &[
// The chat pill over the map and the code editor draw their own fields.
"systems/gui/chat_overlay.rs",
"systems/gui/script_editor.rs",
- "systems/gui/onscreen_keyboard/",
// The developer tools (the dev panel, the Midas link, release approval):
// tooling, not the product's face. Bring them over when they are touched.
"systems/dev/",
diff --git a/crates/cartopolis/src/systems/dev/ui_probe.rs b/crates/cartopolis/src/systems/dev/ui_probe.rs
index 6e48eda0..c3d7e915 100644
--- a/crates/cartopolis/src/systems/dev/ui_probe.rs
+++ b/crates/cartopolis/src/systems/dev/ui_probe.rs
@@ -113,6 +113,14 @@ impl Plugin for UiProbePlugin {
.add_systems(
PostUpdate,
crate::systems::lib_splash::fade_lib_splash.after(mithril_bevy::DriveUi),
+ )
+ // The map's free area from the panels' laid-out boxes
+ // (`data-reserves-map`), for the next frame's chrome and pins.
+ .add_systems(
+ PostUpdate,
+ crate::systems::lib_host::measure_map_room
+ .after(mithril_bevy::DriveUi)
+ .after(bevy::ui::UiSystems::Layout),
);
// The camera and a call, the app's only: their pictures are images
// the app writes each frame (`mithril_bevy::LiveImages`).
diff --git a/crates/cartopolis/src/systems/gui/chat_overlay.rs b/crates/cartopolis/src/systems/gui/chat_overlay.rs
index 812e6ee5..047ab8d0 100644
--- a/crates/cartopolis/src/systems/gui/chat_overlay.rs
+++ b/crates/cartopolis/src/systems/gui/chat_overlay.rs
@@ -48,9 +48,9 @@
//! the way of that.
//!
//! **The sheet takes the keyboard's height on the frame the keys choose their
-//! edge.** `onscreen_keyboard::layout` picks its edge from where the focused
-//! field landed *this* frame, and flips to the **top** when the bottom slab
-//! would cover it. So the sheet reserves [`onscreen_keyboard::expected_height`]
+//! edge.** `onscreen_keyboard::choose_edge` picks its edge from where the
+//! focused field landed, and flips to the **top** when the bottom slab would
+//! cover it. So the sheet reserves [`onscreen_keyboard::expected_height_in`]
//! while the keys are up and on the frame its field claims them.
//!
//! **Everything ages on [`ChatState::clock`], not on `sent_at_ms`.** See that
@@ -543,9 +543,9 @@ fn clear_of_keyboard(mut rect: Rect, slab: Option<Rect>) -> Rect {
rect
}
-/// The map's rect in UI points: what the panels left of the screen at the
-/// end of the last pass (`EguiVerdict::map_rect`, in window points), or the
-/// whole viewport before there is one, less the on-screen keyboard.
+/// The map's rect in UI points: what the library's panels left of the
+/// screen at the last layout ([`UiInput::map_rect`], in window points), or
+/// the whole viewport before there is one, less the on-screen keyboard.
fn map_rect(
ui_input: &UiInput,
metrics: &UiMetrics,
diff --git a/crates/cartopolis/src/systems/gui/cosmos.rs b/crates/cartopolis/src/systems/gui/cosmos.rs
index b02c88a5..68764a52 100644
--- a/crates/cartopolis/src/systems/gui/cosmos.rs
+++ b/crates/cartopolis/src/systems/gui/cosmos.rs
@@ -2,8 +2,8 @@
//! nearest stars, the Milky Way, the galaxies round it and the edge of the
//! observable universe — as **one map at one scale**
//! (`docs/mockups/zoom-ladder/`). Past the ceiling the 3D camera waits over the
-//! place it left and the zoom moves `CameraState::cosmos_alt` instead; this paints
-//! what is out there, behind every panel.
+//! place it left and the zoom moves `CameraState::cosmos_alt` instead; this works
+//! out what is out there, drawn behind every panel.
//!
//! **To scale in the middle, squeezed towards the edge.** Every body sits at its
//! real place in one frame (the ecliptic, metres from the Sun) and is projected
@@ -42,24 +42,34 @@
//! moves from the Earth to the Sun to the galactic centre — each only once the
//! next one in is too small to lose.
//!
-//! Painted with egui on the background layer, before the panel chain, so the
-//! panels and the map's chrome stay on top. With the component library on
-//! (`CosmosLib::lib`, `lib_cosmos`) egui paints only the space and the two
-//! star fields, and every body, ring, orbit, line and label it worked out is
-//! published in `CosmosLib::lib_view` for the library to draw as boxes. Where
-//! the library has a camera of its own (`CosmosLib::sky`, the Bevy backend)
-//! egui paints nothing: the space and the star fields go out in
-//! `CosmosLib::lib_sky` for `lib_cosmos_sky` to draw as meshes under the boxes.
-
-use crate::systems::egui_manager::EguiRef;
+//! This works the frame out and draws none of it: every body, ring, orbit,
+//! line and label goes out in `CosmosLib::view` for the component library
+//! to draw as boxes (`lib_cosmos`), and the space behind them and the two
+//! star fields in `CosmosLib::sky` for `lib_cosmos_sky` to draw as meshes
+//! under the boxes. Positions are UI points from the screen's top left
+//! corner (`UiMetrics`).
+
use crate::systems::theme;
+use crate::systems::theme::Rgba8;
+use crate::systems::ui_input::UiMetrics;
use crate::utils::near_stars::NEAR_STARS;
use crate::utils::planets::{self, AU_M, LIGHT_M_S, LIGHT_YEAR_M, PLANETS};
use bevy::math::{DMat3, DQuat, DVec2, DVec3};
use bevy::prelude::*;
use bevy::tasks::{IoTaskPool, Task};
+use bevy::window::PrimaryWindow;
use cartopolis_geo::formats::galaxies::{Catalogue, Galaxies};
-use egui::{pos2, vec2, Color32, Pos2};
+
+/// A point on screen, UI points from the top left corner, y down.
+type Pos2 = Vec2;
+
+const fn pos2(x: f32, y: f32) -> Pos2 {
+ Vec2::new(x, y)
+}
+
+const fn vec2(x: f32, y: f32) -> Vec2 {
+ Vec2::new(x, y)
+}
/// The Earth's radius, metres.
const EARTH_R_M: f64 = 6_371_000.0;
@@ -69,24 +79,24 @@ const MOON_R_M: f64 = 1_737_400.0;
const MOON_DIST_M: f64 = 384_400_000.0;
/// Deep space behind it all.
-const SPACE: Color32 = Color32::from_rgb(0x04, 0x07, 0x0A);
-const EARTH_DAY: Color32 = Color32::from_rgb(0x5D, 0x8F, 0xBF);
-const EARTH_NIGHT: Color32 = Color32::from_rgb(0x0C, 0x1A, 0x2A);
-const MOON_DAY: Color32 = Color32::from_rgb(0xD9, 0xD6, 0xCC);
-const MOON_NIGHT: Color32 = Color32::from_rgb(0x26, 0x29, 0x2C);
-const SUN: Color32 = Color32::from_rgb(0xFF, 0xE8, 0xA8);
-const ORBIT: Color32 = Color32::from_rgba_unmultiplied_const(0xA0, 0xBE, 0xC8, 70);
-const LANE: Color32 = Color32::from_rgba_unmultiplied_const(0x5C, 0xC6, 0xC0, 60);
+const SPACE: Rgba8 = Rgba8::from_rgb(0x04, 0x07, 0x0A);
+const EARTH_DAY: Rgba8 = Rgba8::from_rgb(0x5D, 0x8F, 0xBF);
+const EARTH_NIGHT: Rgba8 = Rgba8::from_rgb(0x0C, 0x1A, 0x2A);
+const MOON_DAY: Rgba8 = Rgba8::from_rgb(0xD9, 0xD6, 0xCC);
+const MOON_NIGHT: Rgba8 = Rgba8::from_rgb(0x26, 0x29, 0x2C);
+const SUN: Rgba8 = Rgba8::from_rgb(0xFF, 0xE8, 0xA8);
+const ORBIT: Rgba8 = Rgba8::from_rgba_unmultiplied(0xA0, 0xBE, 0xC8, 70);
+const LANE: Rgba8 = Rgba8::from_rgba_unmultiplied(0x5C, 0xC6, 0xC0, 60);
/// Planet colours, Mercury to Neptune: a palette for content, not chrome.
-const PLANET_TONES: [Color32; 8] = [
- Color32::from_rgb(0xB5, 0xAE, 0xA4),
- Color32::from_rgb(0xF1, 0xD9, 0x9A),
+const PLANET_TONES: [Rgba8; 8] = [
+ Rgba8::from_rgb(0xB5, 0xAE, 0xA4),
+ Rgba8::from_rgb(0xF1, 0xD9, 0x9A),
EARTH_DAY,
- Color32::from_rgb(0xE0, 0x7A, 0x4F),
- Color32::from_rgb(0xE8, 0xC4, 0x9A),
- Color32::from_rgb(0xF0, 0xDC, 0xA0),
- Color32::from_rgb(0x9F, 0xE0, 0xE6),
- Color32::from_rgb(0x5B, 0x84, 0xE6),
+ Rgba8::from_rgb(0xE0, 0x7A, 0x4F),
+ Rgba8::from_rgb(0xE8, 0xC4, 0x9A),
+ Rgba8::from_rgb(0xF0, 0xDC, 0xA0),
+ Rgba8::from_rgb(0x9F, 0xE0, 0xE6),
+ Rgba8::from_rgb(0x5B, 0x84, 0xE6),
];
/// 0 below `lo`, 1 above `hi`, smooth on a log scale between.
@@ -99,8 +109,95 @@ fn fade_out(alt: f64, lo: f64, hi: f64) -> f32 {
1.0 - fade_in(alt, lo, hi)
}
-fn alpha(c: Color32, a: f32) -> Color32 {
- c.gamma_multiply(a.clamp(0.0, 1.0))
+fn alpha(c: Rgba8, a: f32) -> Rgba8 {
+ c.with_alpha_scaled(a)
+}
+
+/// A rectangle on screen, UI points, y down. Both edges count as inside.
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct Area {
+ min: Pos2,
+ max: Pos2,
+}
+
+impl Area {
+ fn from_min_size(min: Pos2, size: Vec2) -> Self {
+ Self {
+ min,
+ max: min + size,
+ }
+ }
+
+ fn width(&self) -> f32 {
+ self.max.x - self.min.x
+ }
+
+ fn height(&self) -> f32 {
+ self.max.y - self.min.y
+ }
+
+ fn left(&self) -> f32 {
+ self.min.x
+ }
+
+ fn top(&self) -> f32 {
+ self.min.y
+ }
+
+ fn bottom(&self) -> f32 {
+ self.max.y
+ }
+
+ fn center(&self) -> Pos2 {
+ (self.min + self.max) / 2.0
+ }
+
+ fn size(&self) -> Vec2 {
+ self.max - self.min
+ }
+
+ fn contains(&self, p: Pos2) -> bool {
+ self.min.x <= p.x && p.x <= self.max.x && self.min.y <= p.y && p.y <= self.max.y
+ }
+
+ fn contains_rect(&self, o: Area) -> bool {
+ self.contains(o.min) && self.contains(o.max)
+ }
+
+ fn intersects(&self, o: Area) -> bool {
+ self.min.x <= o.max.x
+ && o.min.x <= self.max.x
+ && self.min.y <= o.max.y
+ && o.min.y <= self.max.y
+ }
+
+ fn expand(&self, by: f32) -> Self {
+ self.shrink2(Vec2::splat(-by))
+ }
+
+ fn shrink2(&self, by: Vec2) -> Self {
+ Self {
+ min: self.min + by,
+ max: self.max - by,
+ }
+ }
+}
+
+/// Where a label's anchor point is on its text: `(0, 0)` its top left
+/// corner, `(0.5, 1)` the middle of its bottom edge.
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct Align(Vec2);
+
+impl Align {
+ const LEFT_BOTTOM: Self = Self(Vec2::new(0.0, 1.0));
+ const LEFT_CENTER: Self = Self(Vec2::new(0.0, 0.5));
+ const CENTER_BOTTOM: Self = Self(Vec2::new(0.5, 1.0));
+ const CENTER_TOP: Self = Self(Vec2::new(0.5, 0.0));
+
+ /// The rectangle of a `size` box anchored at `at`.
+ fn anchor_size(self, at: Pos2, size: Vec2) -> Area {
+ Area::from_min_size(at - size * self.0, size)
+ }
}
/// A distance in words: kilometres, then astronomical units, then light years.
@@ -145,69 +242,6 @@ fn thousands(n: u64) -> String {
out
}
-/// A label with a dark halo, so it reads over anything.
-fn label(p: &egui::Painter, at: Pos2, align: egui::Align2, text: &str, size: f32, ink: Color32) {
- let font = egui::FontId::proportional(size);
- let halo = alpha(theme::DARK32.ink, ink.a() as f32 / 255.0);
- for d in [
- vec2(1.0, 0.0),
- vec2(-1.0, 0.0),
- vec2(0.0, 1.0),
- vec2(0.0, -1.0),
- ] {
- p.text(at + d, align, text, font.clone(), halo);
- }
- p.text(at, align, text, font, ink);
-}
-
-/// A sphere seen from the camera, lit from one side: the dark disc, then the
-/// lit part as a strip between the limb and the terminator's ellipse (a strip
-/// fills a crescent as well as a gibbous phase, which a convex polygon cannot).
-/// `sun` is the sun's direction on screen (x right, y up); `toward` how far it
-/// stands towards the viewer, −1 behind the sphere to 1 behind the viewer.
-fn paint_lit_sphere(
- p: &egui::Painter,
- c: Pos2,
- r: f32,
- sun: Vec2,
- toward: f32,
- day: Color32,
- night: Color32,
-) {
- p.circle_filled(c, r, night);
- if r < 1.5 {
- p.circle_filled(c, r.max(1.0), day);
- return;
- }
- let u = if sun.length_squared() > 1e-8 {
- sun.normalize()
- } else {
- Vec2::X
- };
- // Screen y runs down.
- let (ux, uy) = (u.x, -u.y);
- let (vx, vy) = (-uy, ux);
- let mut mesh = egui::Mesh::default();
- let n = 32;
- for i in 0..=n {
- let a = -std::f32::consts::FRAC_PI_2 + std::f32::consts::PI * i as f32 / n as f32;
- let (s, co) = a.sin_cos();
- let limb = pos2(c.x + r * (co * ux + s * vx), c.y + r * (co * uy + s * vy));
- let term = pos2(
- c.x + r * (-toward * co * ux + s * vx),
- c.y + r * (-toward * co * uy + s * vy),
- );
- mesh.colored_vertex(limb, day);
- mesh.colored_vertex(term, day);
- if i > 0 {
- let k = 2 * i as u32;
- mesh.add_triangle(k - 2, k - 1, k);
- mesh.add_triangle(k - 1, k + 1, k);
- }
- }
- p.add(egui::Shape::mesh(mesh));
-}
-
/// The Sun's radius, metres.
const SUN_R_M: f64 = 696_000_000.0;
/// The parsec, metres.
@@ -257,11 +291,11 @@ const RINGS: [(f64, &str); 15] = [
(LIGHT_YEAR_M * 1.0e9, "1 billion light years"),
(LIGHT_YEAR_M * 1.0e10, "10 billion light years"),
];
-const GALAXY_DOT: Color32 = Color32::from_rgb(0xF2, 0xE8, 0xD8);
-const EDGE: Color32 = Color32::from_rgb(0xE8, 0xB8, 0x8A);
-const RING: Color32 = Color32::from_rgba_unmultiplied_const(0x9A, 0xB0, 0xB8, 46);
-const GALAXY_STAR: Color32 = Color32::from_rgb(0xD8, 0xE2, 0xFF);
-const GALAXY_BULGE: Color32 = Color32::from_rgb(0xFF, 0xE2, 0xAA);
+const GALAXY_DOT: Rgba8 = Rgba8::from_rgb(0xF2, 0xE8, 0xD8);
+const EDGE: Rgba8 = Rgba8::from_rgb(0xE8, 0xB8, 0x8A);
+const RING: Rgba8 = Rgba8::from_rgba_unmultiplied(0x9A, 0xB0, 0xB8, 46);
+const GALAXY_STAR: Rgba8 = Rgba8::from_rgb(0xD8, 0xE2, 0xFF);
+const GALAXY_BULGE: Rgba8 = Rgba8::from_rgb(0xFF, 0xE2, 0xAA);
/// Equatorial coordinates to ecliptic ones (both with x at the March equinox).
fn eq_to_ecl(v: DVec3) -> DVec3 {
@@ -419,7 +453,7 @@ impl View {
}
/// The Sun's direction on screen from a body, and how far it stands
- /// towards the viewer — what `paint_lit_sphere` takes.
+ /// towards the viewer — what `ShapeKind::Sphere` takes.
fn sunlight(&self, body: DVec3) -> (Vec2, f32) {
let s = (-body).normalize_or_zero();
(
@@ -440,37 +474,28 @@ fn apart(a: Pos2, b: Pos2, lo: f32, hi: f32) -> f32 {
/// `a` how strongly it shows.
struct Tag {
at: Pos2,
- align: egui::Align2,
+ align: Align,
text: String,
size: f32,
- ink: Color32,
+ ink: Rgba8,
a: f32,
}
impl Tag {
- /// Where the label's text stands, by egui's measure of it.
- fn rect(&self, p: &egui::Painter) -> egui::Rect {
- let g = p.layout_no_wrap(
- self.text.clone(),
- egui::FontId::proportional(self.size),
- alpha(self.ink, self.a),
- );
- self.align.anchor_size(self.at, g.size())
- }
-
- fn paint(&self, p: &egui::Painter) {
- label(
- p,
- self.at,
- self.align,
+ /// Where the label's text stands, measured over the face the library
+ /// sets it in (`place_pins::text_size`).
+ fn rect(&self) -> Area {
+ let size = crate::systems::place_pins::text_size(
&self.text,
self.size,
- alpha(self.ink, self.a),
+ crate::systems::place_pins::Face::Body,
+ 0.0,
);
+ self.align.anchor_size(self.at, size)
}
- /// The label for the library, where egui measured it.
- fn publish(&self, rect: egui::Rect) -> CosmosTag {
+ /// The label for the library, where it was measured.
+ fn publish(&self, rect: Area) -> CosmosTag {
CosmosTag {
min: rect.min,
size: rect.size(),
@@ -483,14 +508,14 @@ impl Tag {
}
/// The labels that find room, each with where its text stands.
-fn place_tags(p: &egui::Painter, tags: Vec<Tag>, screen: egui::Rect) -> Vec<(Tag, egui::Rect)> {
- let mut taken: Vec<egui::Rect> = Vec::new();
+fn place_tags(tags: Vec<Tag>, screen: Area) -> Vec<(Tag, Area)> {
+ let mut taken: Vec<Area> = Vec::new();
let mut placed = Vec::new();
for t in tags {
if alpha(t.ink, t.a).a() < 4 {
continue;
}
- let at = t.rect(p);
+ let at = t.rect();
let r = at.expand(2.0);
if !screen.contains_rect(r) || taken.iter().any(|o| o.intersects(r)) {
continue;
@@ -505,18 +530,18 @@ fn place_tags(p: &egui::Painter, tags: Vec<Tag>, screen: egui::Rect) -> Vec<(Tag
/// The cosmos for the component library: everything but the space behind
/// it and the two star fields (the Milky Way's 7,000 points and up to
-/// 50,000 galaxies, which a box each would make a node each: `CosmosSky`),
-/// as egui would paint it this frame. Points, egui's.
+/// 50,000 galaxies, which a box each would make a node each: `CosmosSky`).
+/// UI points.
#[derive(Clone, Debug, PartialEq, Default)]
pub struct CosmosFrame {
- /// In egui's paint order.
+ /// In paint order, the first at the bottom.
pub shapes: Vec<CosmosShape>,
/// The labels that found room, then the captions.
pub tags: Vec<CosmosTag>,
}
/// One body, ring or line: `alpha` is how strongly it shows, its colours
-/// are egui's constants.
+/// this module's constants.
#[derive(Clone, Debug, PartialEq)]
pub struct CosmosShape {
/// Stays with the same thing from frame to frame.
@@ -529,171 +554,148 @@ pub struct CosmosShape {
#[derive(Clone, Debug, PartialEq)]
pub enum ShapeKind {
Disc {
- c: Pos2,
+ c: Vec2,
r: f32,
- ink: Color32,
+ ink: Rgba8,
},
/// A circle's outline, `r` to the middle of the stroke.
Ring {
- c: Pos2,
+ c: Vec2,
r: f32,
width: f32,
- ink: Color32,
+ ink: Rgba8,
},
/// An orbit: an ellipse round `c`, `half` its half axes, the first
/// turned `angle_deg` clockwise from the screen's x.
Ellipse {
- c: Pos2,
- half: egui::Vec2,
+ c: Vec2,
+ half: Vec2,
angle_deg: f32,
- ink: Color32,
+ ink: Rgba8,
},
Line {
- a: Pos2,
- b: Pos2,
- ink: Color32,
+ a: Vec2,
+ b: Vec2,
+ ink: Rgba8,
},
- /// A sphere lit from one side (`paint_lit_sphere`'s arguments).
+ /// A sphere seen from the camera, lit from one side. `sun` is the Sun's
+ /// direction on screen (x right, y up); `toward` how far it stands
+ /// towards the viewer, −1 behind the sphere to 1 behind the viewer. The
+ /// lit part runs from the limb on the Sun's side to the terminator, an
+ /// ellipse through the two limb points across the Sun's direction and
+ /// the point `−toward · r` along it.
Sphere {
- c: Pos2,
+ c: Vec2,
r: f32,
sun: Vec2,
toward: f32,
- day: Color32,
- night: Color32,
+ day: Rgba8,
+ night: Rgba8,
},
}
-/// A label where egui measured it, its halo the dark theme's ink.
+/// A label where it was measured, its halo the dark theme's ink.
#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
#[derive(Clone, Debug, PartialEq)]
pub struct CosmosTag {
- pub min: Pos2,
- pub size: egui::Vec2,
+ pub min: Vec2,
+ pub size: Vec2,
pub text: String,
pub font: f32,
- pub ink: Color32,
+ pub ink: Rgba8,
pub alpha: f32,
}
-/// The space behind the cosmos and its two star fields, for the library's
-/// own camera to draw as meshes (`lib_cosmos_sky`). Points, egui's.
-#[cfg_attr(not(feature = "ui-probe"), allow(dead_code))]
+/// The space behind the cosmos and its two star fields, for a 2D camera to
+/// draw as meshes (`lib_cosmos_sky`). UI points.
+#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
#[derive(Clone, Debug, PartialEq, Default)]
pub struct CosmosSky {
- /// egui's points to physical pixels.
+ /// UI points to physical pixels (`UiMetrics::pixels_per_point`).
pub pixels_per_point: f32,
/// Space, its alpha the fade in past the ceiling, over the whole screen.
- pub space: Color32,
- /// The round hole the 3D globe shows through (`fill_around`): its
- /// middle and radius, `None` once the Earth is a painted disc.
- pub hole: Option<(Pos2, f32)>,
- /// The Milky Way's points, then the galaxies', in egui's paint order.
+ pub space: Rgba8,
+ /// The round hole the 3D globe shows through: its middle and radius,
+ /// `None` once the Earth is a drawn disc.
+ pub hole: Option<(Vec2, f32)>,
+ /// The Milky Way's points, then the galaxies', in paint order.
pub dots: Vec<SkyDot>,
}
/// One star field point: a square `r` each way from `at`.
-#[cfg_attr(not(feature = "ui-probe"), allow(dead_code))]
+#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SkyDot {
- pub at: Pos2,
+ pub at: Vec2,
pub r: f32,
- pub ink: Color32,
+ pub ink: Rgba8,
}
-/// The library's edition of the cosmos (`lib_cosmos`), inserted by it: with
-/// `lib` on, egui paints only the space and the star fields and publishes
-/// the rest in `lib_view` (`None` while the view is below the ceiling).
-/// With `sky` on as well (the library has a camera of its own to draw
-/// meshes on, `lib_cosmos_sky`), egui paints nothing at all and publishes
-/// the space and the star fields in `lib_sky`, counting each change in
-/// `sky_rev` so the meshes are rebuilt only when it moved.
+/// The cosmos as this frame has it, for the library to draw: the bodies,
+/// rings, lines and labels in `view` (`lib_cosmos`, `None` while the view
+/// is below the ceiling), the space and the star fields in `sky`
+/// (`lib_cosmos_sky`), each change of which `sky_rev` counts so the meshes
+/// are rebuilt only when it moved. Inserted by `lib_cosmos`.
#[derive(Resource, Default)]
pub struct CosmosLib {
- pub lib: bool,
- pub lib_view: Option<CosmosFrame>,
- pub sky: bool,
- pub lib_sky: Option<CosmosSky>,
+ pub view: Option<CosmosFrame>,
+ pub sky: Option<CosmosSky>,
pub sky_rev: u64,
}
-/// Where the bodies, rings and lines go: painted by egui, or kept for the
-/// library, which draws them as boxes.
-struct Out<'a> {
- p: &'a egui::Painter,
- lib: Option<Vec<CosmosShape>>,
+/// The frame's bodies, rings and lines, in paint order.
+#[derive(Default)]
+struct Out {
+ shapes: Vec<CosmosShape>,
}
-impl Out<'_> {
+impl Out {
fn push(&mut self, key: String, alpha: f32, kind: ShapeKind) {
- if let Some(v) = self.lib.as_mut() {
- v.push(CosmosShape { key, alpha, kind });
- }
+ self.shapes.push(CosmosShape { key, alpha, kind });
}
- fn disc(&mut self, key: impl Into<String>, c: Pos2, r: f32, ink: Color32, a: f32) {
- if self.lib.is_some() {
- self.push(key.into(), a, ShapeKind::Disc { c, r, ink });
- } else {
- self.p.circle_filled(c, r, alpha(ink, a));
- }
+ fn disc(&mut self, key: impl Into<String>, c: Pos2, r: f32, ink: Rgba8, a: f32) {
+ self.push(key.into(), a, ShapeKind::Disc { c, r, ink });
}
- fn ring(&mut self, key: impl Into<String>, c: Pos2, r: f32, width: f32, ink: Color32, a: f32) {
- if self.lib.is_some() {
- self.push(key.into(), a, ShapeKind::Ring { c, r, width, ink });
- } else {
- self.p
- .circle_stroke(c, r, egui::Stroke::new(width, alpha(ink, a)));
- }
+ fn ring(&mut self, key: impl Into<String>, c: Pos2, r: f32, width: f32, ink: Rgba8, a: f32) {
+ self.push(key.into(), a, ShapeKind::Ring { c, r, width, ink });
}
- fn line(&mut self, key: impl Into<String>, from: Pos2, to: Pos2, ink: Color32, a: f32) {
- if self.lib.is_some() {
- self.push(
- key.into(),
- a,
- ShapeKind::Line {
- a: from,
- b: to,
- ink,
- },
- );
- } else {
- self.p
- .line_segment([from, to], egui::Stroke::new(1.0, alpha(ink, a)));
- }
+ fn line(&mut self, key: impl Into<String>, from: Pos2, to: Pos2, ink: Rgba8, a: f32) {
+ self.push(
+ key.into(),
+ a,
+ ShapeKind::Line {
+ a: from,
+ b: to,
+ ink,
+ },
+ );
}
- /// A circle in the ecliptic plane round `about`: egui's polyline through
- /// the squeeze, or for the library the ellipse through its four ends.
+ /// A circle in the ecliptic plane round `about`, as the ellipse through
+ /// its four ends.
fn orbit(
&mut self,
key: impl Into<String>,
view: &View,
about: DVec3,
r: f64,
- ink: Color32,
+ ink: Rgba8,
a: f32,
) {
- if self.lib.is_some() {
- let (c, half, angle_deg) = orbit_ellipse(view, about, r);
- self.push(
- key.into(),
- a,
- ShapeKind::Ellipse {
- c,
- half,
- angle_deg,
- ink,
- },
- );
- } else {
- self.p.add(egui::Shape::line(
- ecliptic_circle(view, about, r),
- egui::Stroke::new(1.0, alpha(ink, a)),
- ));
- }
+ let (c, half, angle_deg) = orbit_ellipse(view, about, r);
+ self.push(
+ key.into(),
+ a,
+ ShapeKind::Ellipse {
+ c,
+ half,
+ angle_deg,
+ ink,
+ },
+ );
}
#[allow(clippy::too_many_arguments)]
@@ -704,26 +706,22 @@ impl Out<'_> {
r: f32,
sun: Vec2,
toward: f32,
- day: Color32,
- night: Color32,
+ day: Rgba8,
+ night: Rgba8,
a: f32,
) {
- if self.lib.is_some() {
- self.push(
- key.into(),
- a,
- ShapeKind::Sphere {
- c,
- r,
- sun,
- toward,
- day,
- night,
- },
- );
- } else {
- paint_lit_sphere(self.p, c, r, sun, toward, alpha(day, a), alpha(night, a));
- }
+ self.push(
+ key.into(),
+ a,
+ ShapeKind::Sphere {
+ c,
+ r,
+ sun,
+ toward,
+ day,
+ night,
+ },
+ );
}
}
@@ -731,7 +729,7 @@ impl Out<'_> {
/// that come out longest and shortest without the squeeze, each taken
/// through the squeeze end to end. The middle, the two half axes, and the
/// first's turn clockwise from the screen's x, degrees.
-fn orbit_ellipse(view: &View, about: DVec3, r: f64) -> (Pos2, egui::Vec2, f32) {
+fn orbit_ellipse(view: &View, about: DVec3, r: f64) -> (Pos2, Vec2, f32) {
let (a, b) = (view.plane(DVec3::X), view.plane(DVec3::Y));
let th = 0.5 * (2.0 * a.dot(b)).atan2(a.length_squared() - b.length_squared());
let at = |t: f64| view.at(about + DVec3::new(t.cos(), t.sin(), 0.0) * r);
@@ -740,7 +738,7 @@ fn orbit_ellipse(view: &View, about: DVec3, r: f64) -> (Pos2, egui::Vec2, f32) {
at(th + std::f64::consts::FRAC_PI_2),
at(th - std::f64::consts::FRAC_PI_2),
);
- let c = ((p0.to_vec2() + p1.to_vec2() + q0.to_vec2() + q1.to_vec2()) / 4.0).to_pos2();
+ let c = (p0 + p1 + q0 + q1) / 4.0;
let (major, minor) = ((p0 - p1) / 2.0, (q0 - q1) / 2.0);
(
c,
@@ -749,82 +747,36 @@ fn orbit_ellipse(view: &View, about: DVec3, r: f64) -> (Pos2, egui::Vec2, f32) {
)
}
-/// A circle in the ecliptic plane round `about`, through the view.
-fn ecliptic_circle(view: &View, about: DVec3, r: f64) -> Vec<Pos2> {
- (0..=128)
- .map(|i| {
- let a = std::f64::consts::TAU * f64::from(i) / 128.0;
- view.at(about + DVec3::new(a.cos(), a.sin(), 0.0) * r)
- })
- .collect()
-}
-
-/// Space over the whole screen but a round hole, where the 3D globe shows
-/// through: the four bands round the hole's square, then the ring between the
-/// square and the circle, its rays meeting the square's corners exactly.
-fn fill_around(p: &egui::Painter, screen: egui::Rect, c: Pos2, r: f32, ink: Color32) {
- let square = egui::Rect::from_center_size(c, vec2(2.0 * r, 2.0 * r));
- if !screen.intersects(square) {
- p.rect_filled(screen, 0.0, ink);
- return;
- }
- for band in [
- egui::Rect::from_min_max(screen.min, pos2(screen.max.x, square.min.y)),
- egui::Rect::from_min_max(pos2(screen.min.x, square.max.y), screen.max),
- egui::Rect::from_min_max(
- pos2(screen.min.x, square.min.y),
- pos2(square.min.x, square.max.y),
- ),
- egui::Rect::from_min_max(
- pos2(square.max.x, square.min.y),
- pos2(screen.max.x, square.max.y),
- ),
- ] {
- let band = band.intersect(screen);
- if band.width() > 0.0 && band.height() > 0.0 {
- p.rect_filled(band, 0.0, ink);
- }
- }
- let mut mesh = egui::Mesh::default();
- // A multiple of eight, so a ray falls on each corner.
- let n = 64;
- for i in 0..=n {
- let a = std::f32::consts::TAU * i as f32 / n as f32;
- let d = Vec2::from_angle(a);
- let edge = d / d.x.abs().max(d.y.abs());
- mesh.colored_vertex(c + vec2(d.x, d.y) * r, ink);
- mesh.colored_vertex(c + vec2(edge.x, edge.y) * r, ink);
- if i > 0 {
- let k = 2 * i as u32;
- mesh.add_triangle(k - 2, k - 1, k);
- mesh.add_triangle(k - 1, k + 1, k);
- }
- }
- p.add(egui::Shape::mesh(mesh));
-}
-
-/// Paint what is past the ceiling, while the view is out there, and frame the
-/// 3D globe to the size and place the Earth has there.
+/// Work out what is past the ceiling, while the view is out there, for the
+/// library to draw (`CosmosLib`), move the map by this frame's drag, and
+/// frame the 3D globe to the size and place the Earth has there.
#[allow(clippy::too_many_arguments)]
-pub fn render_cosmos(
- egui: EguiRef,
+pub fn drive_cosmos(
+ metrics: Res<UiMetrics>,
+ windows: Query<&Window, With<PrimaryWindow>>,
mut camera_state: ResMut<crate::resources::CameraState>,
dev: Res<crate::resources::DevPanelState>,
clock: Res<crate::systems::transit_live::WorldClock>,
globe: Res<crate::systems::globe::GlobeState>,
camera: Query<&Transform, With<crate::components::FreeCamera>>,
mut camera_lens: Query<(&Projection, &mut Camera), With<crate::components::FreeCamera>>,
- mut galaxy: Local<Vec<(DVec3, f32, Color32)>>,
+ mut galaxy: Local<Vec<(DVec3, f32, Rgba8)>>,
catalogue: Res<GalaxyCatalogue>,
mut lib: Option<ResMut<CosmosLib>>,
) {
// Nothing for the library unless a frame below says otherwise.
let mut published: Option<CosmosFrame> = None;
let mut published_sky: Option<CosmosSky> = None;
- let lib_on = lib.as_ref().is_some_and(|l| l.lib);
- let sky_on = lib_on && lib.as_ref().is_some_and(|l| l.sky);
- render_cosmos_frame(
- &egui,
+ // The hand, in UI points: the touch recogniser has moved the window's
+ // cursor to the finger.
+ let pointer = windows
+ .single()
+ .ok()
+ .and_then(Window::cursor_position)
+ .map(|p| metrics.window_to_ui(p));
+ cosmos_frame(
+ &metrics,
+ pointer,
&mut camera_state,
&dev,
&clock,
@@ -833,37 +785,36 @@ pub fn render_cosmos(
&mut camera_lens,
&mut galaxy,
&catalogue,
- lib_on,
- sky_on.then_some(&mut published_sky),
+ &mut published_sky,
&mut published,
);
if let Some(lib) = lib.as_mut() {
- if lib.lib_view != published {
- lib.lib_view = published;
+ if lib.view != published {
+ lib.view = published;
}
- if lib.lib_sky != published_sky {
- lib.lib_sky = published_sky;
+ if lib.sky != published_sky {
+ lib.sky = published_sky;
lib.sky_rev = lib.sky_rev.wrapping_add(1);
}
}
}
-/// [`render_cosmos`]'s frame: with `lib` on, paints only the space and the
-/// star fields and leaves the rest in `published`; given `sky` as well, paints
-/// nothing and leaves the space and the star fields in it.
+/// [`drive_cosmos`]'s frame: the bodies, rings and labels into `published`,
+/// the space and the star fields into `sky_out`; both left `None` below the
+/// ceiling.
#[allow(clippy::too_many_arguments)]
-fn render_cosmos_frame(
- egui: &EguiRef,
+fn cosmos_frame(
+ metrics: &UiMetrics,
+ pointer: Option<Pos2>,
camera_state: &mut crate::resources::CameraState,
dev: &crate::resources::DevPanelState,
clock: &crate::systems::transit_live::WorldClock,
globe: &crate::systems::globe::GlobeState,
camera: &Query<&Transform, With<crate::components::FreeCamera>>,
camera_lens: &mut Query<(&Projection, &mut Camera), With<crate::components::FreeCamera>>,
- galaxy: &mut Vec<(DVec3, f32, Color32)>,
+ galaxy: &mut Vec<(DVec3, f32, Rgba8)>,
catalogue: &GalaxyCatalogue,
- lib: bool,
- sky_out: Option<&mut Option<CosmosSky>>,
+ sky_out: &mut Option<CosmosSky>,
published: &mut Option<CosmosFrame>,
) {
let alt = camera_state.cosmos_alt;
@@ -880,18 +831,13 @@ fn render_cosmos_frame(
let Ok(tf) = camera.single() else {
return;
};
- let ctx = egui.ctx();
- let screen = ctx.content_rect();
- let p = ctx.layer_painter(egui::LayerId::background());
- let mut out = Out {
- p: &p,
- lib: lib.then(Vec::new),
- };
- // The space and the star fields, for the library's camera.
- let mut sky = sky_out.is_some().then(|| CosmosSky {
- pixels_per_point: ctx.pixels_per_point(),
+ let screen = Area::from_min_size(Pos2::ZERO, metrics.viewport_pts());
+ let mut out = Out::default();
+ // The space and the star fields, for the sky's meshes.
+ let mut sky = CosmosSky {
+ pixels_per_point: metrics.pixels_per_point(),
..Default::default()
- });
+ };
// Where the 3D camera waits, from the Earth's centre, and its height there.
let wait_m = crate::systems::free_camera::ORBIT_MAX_DISTANCE_SPACE;
let ceiling = wait_m - f64::from(globe.radius);
@@ -930,11 +876,11 @@ fn render_cosmos_frame(
// ── Moving about: a drag carries the point under the hand with it ──────
// Read through the squeeze, so a drag from the rim to the middle brings
// what was at the rim to the middle, however far out it is.
- let drag = std::mem::take(&mut camera_state.cosmos_drag) / ctx.zoom_factor();
+ // The drag is in the window's logical points, the map in UI points.
+ let drag = metrics.window_to_ui(std::mem::take(&mut camera_state.cosmos_drag));
let mut pan = view.plane(camera_state.cosmos_pan);
if drag != Vec2::ZERO {
- let at = ctx
- .input(|i| i.pointer.latest_pos())
+ let at = pointer
.filter(|at| screen.contains(*at))
.unwrap_or(view.centre);
pan += view.under(at - vec2(drag.x, drag.y)) - view.under(at);
@@ -964,7 +910,7 @@ fn render_cosmos_frame(
/ wide) as f32;
let solid = globe_r >= 2.0;
let sub = lens.physical_target_size().filter(|_| solid).map(|full| {
- let ppp = ctx.pixels_per_point();
+ let ppp = metrics.pixels_per_point();
let e = (earth_at - screen.min) * ppp;
let size = full.as_dvec2() * wide;
bevy::camera::SubCameraView {
@@ -981,14 +927,8 @@ fn render_cosmos_frame(
}
// A little past the limb, for the atmosphere's rim.
let hole = solid.then_some((earth_at, globe_r * 1.05));
- if let Some(sky) = sky.as_mut() {
- sky.space = alpha(SPACE, bd);
- sky.hole = hole;
- } else if let Some((c, r)) = hole {
- fill_around(&p, screen, c, r, alpha(SPACE, bd));
- } else {
- p.rect_filled(screen, 0.0, alpha(SPACE, bd));
- }
+ sky.space = alpha(SPACE, bd);
+ sky.hole = hole;
let mut tags: Vec<Tag> = Vec::new();
// ── The ruler ───────────────────────────────────────────────────────────
@@ -1004,10 +944,10 @@ fn render_cosmos_frame(
out.ring(format!("ring {words}"), view.centre, r, 1.0, RING, a);
ring_tags.push(Tag {
at: view.centre + vec2(r, -r) * std::f32::consts::FRAC_1_SQRT_2 + vec2(3.0, -2.0),
- align: egui::Align2::LEFT_BOTTOM,
+ align: Align::LEFT_BOTTOM,
text: words.to_string(),
size: theme::SIZE_TINY,
- ink: theme::DARK32.text_dim,
+ ink: theme::DARK.text_dim,
a,
});
}
@@ -1031,9 +971,8 @@ fn render_cosmos_frame(
// Once the whole galaxy is a few pixels its points are one dot.
let mw_r = view.size(gc, 50_000.0 * LIGHT_YEAR_M);
if mw_r > 4.0 {
- // One mesh of small squares: some 7,000 circles a frame was a
- // tessellation's worth of work for something this small.
- let mut mesh = egui::Mesh::default();
+ // Small squares in one mesh (`lib_cosmos_sky`): some 7,000
+ // circles a frame is a lot of work for something this small.
let r = 0.75;
for (pt, b, ink) in galaxy.iter() {
let q = view.at(*pt);
@@ -1041,37 +980,25 @@ fn render_cosmos_frame(
continue;
}
let ink = alpha(*ink, gx * b);
- if let Some(sky) = sky.as_mut() {
- sky.dots.push(SkyDot { at: q, r, ink });
- continue;
- }
- let i = mesh.vertices.len() as u32;
- for d in [vec2(-r, -r), vec2(r, -r), vec2(r, r), vec2(-r, r)] {
- mesh.colored_vertex(q + d, ink);
- }
- mesh.add_triangle(i, i + 1, i + 2);
- mesh.add_triangle(i, i + 2, i + 3);
- }
- if !mesh.is_empty() {
- p.add(egui::Shape::mesh(mesh));
+ sky.dots.push(SkyDot { at: q, r, ink });
}
} else {
out.disc("milky way", gc_at, mw_r.max(2.5), GALAXY_STAR, gx);
}
tags.push(Tag {
at: gc_at + vec2(0.0, -14.0),
- align: egui::Align2::CENTER_BOTTOM,
+ align: Align::CENTER_BOTTOM,
text: format!("Galactic centre · {} light years", thousands(GC_LY as u64)),
size: theme::SIZE_SUB,
- ink: theme::DARK32.text,
+ ink: theme::DARK.text,
a: gx * apart(gc_at, sun_at, 30.0, 80.0) * fade_out(alt, 2.0e21, 6.0e21),
});
tags.push(Tag {
at: gc_at + vec2(0.0, mw_r.max(2.5) + 8.0),
- align: egui::Align2::CENTER_TOP,
+ align: Align::CENTER_TOP,
text: "Milky Way · you".into(),
size: theme::SIZE_BODY,
- ink: theme::DARK32.cream,
+ ink: theme::DARK.cream,
a: gx * fade_in(alt, 2.0e21, 6.0e21),
});
}
@@ -1103,9 +1030,8 @@ fn render_cosmos_frame(
let names = if screen.width() < 600.0 { 12 } else { 30 };
let mut galaxy_tags = Vec::new();
if !catalogue.galaxies.is_empty() && near_a > 0.01 {
- let mut named = paint_galaxies(
- &p,
- sky.as_mut().map(|s| &mut s.dots),
+ let mut named = place_galaxies(
+ &mut sky.dots,
&view,
screen,
&catalogue.galaxies,
@@ -1127,14 +1053,14 @@ fn render_cosmos_frame(
for (g, q, a) in named.into_iter().take(names) {
galaxy_tags.push(Tag {
at: q + vec2(5.0, 0.0),
- align: egui::Align2::LEFT_CENTER,
+ align: Align::LEFT_CENTER,
text: format!(
"{} · {}",
g.name,
distance_words(g.light_years * LIGHT_YEAR_M)
),
size: theme::SIZE_TINY,
- ink: theme::DARK32.text,
+ ink: theme::DARK.text,
// At the top the whole survey is a dot; its names would bury it.
a: a * fade_out(alt, 1.0e26, 6.0e26),
});
@@ -1148,7 +1074,7 @@ fn render_cosmos_frame(
out.ring("edge", view.centre, edge_r, 1.5, EDGE, ea);
tags.push(Tag {
at: view.centre + vec2(0.0, -edge_r - 6.0),
- align: egui::Align2::CENTER_BOTTOM,
+ align: Align::CENTER_BOTTOM,
text: "Edge of the observable universe · 46 billion light years".into(),
size: theme::SIZE_SUB,
ink: EDGE,
@@ -1159,10 +1085,10 @@ fn render_cosmos_frame(
tags.push(Tag {
// Above the middle's own "Milky Way · you".
at: view.centre + vec2(mapped + 6.0, -6.0),
- align: egui::Align2::LEFT_BOTTOM,
+ align: Align::LEFT_BOTTOM,
text: "every galaxy mapped here · 2 billion light years".into(),
size: theme::SIZE_TINY,
- ink: theme::DARK32.text,
+ ink: theme::DARK.text,
a: ea * fade_in(alt, 3.0e25, 3.0e26),
});
}
@@ -1205,15 +1131,15 @@ fn render_cosmos_frame(
format!("star {i}"),
q,
if s.members > 1 { 3.5 } else { 2.5 },
- theme::DARK32.cream,
+ theme::DARK.cream,
a,
);
star_tags.push(Tag {
at: q + vec2(5.0, 0.0),
- align: egui::Align2::LEFT_CENTER,
+ align: Align::LEFT_CENTER,
text: format!("{} · {:.1} ly", s.name, s.light_years),
size: theme::SIZE_TINY,
- ink: theme::DARK32.text,
+ ink: theme::DARK.text,
a,
});
}
@@ -1255,14 +1181,14 @@ fn render_cosmos_frame(
);
planet_tags.push(Tag {
at: q + vec2(0.0, 7.0),
- align: egui::Align2::CENTER_TOP,
+ align: Align::CENTER_TOP,
text: format!(
"{} · {}",
planet.name,
light_time_words(xyz.distance(earth))
),
size: theme::SIZE_SUB,
- ink: theme::DARK32.cream,
+ ink: theme::DARK.cream,
a,
});
}
@@ -1320,14 +1246,7 @@ fn render_cosmos_frame(
);
}
// Home: the ring stays on the Earth, wherever the Earth has shrunk to.
- out.ring(
- "home",
- earth_at,
- earth_r + 6.0,
- 2.0,
- theme::BRAND.to_egui(),
- bd,
- );
+ out.ring("home", earth_at, earth_r + 6.0, 2.0, theme::BRAND, bd);
// ── Labels, the nearer first ────────────────────────────────────────────
let sun_words = if you_apart < 0.5 {
@@ -1338,15 +1257,15 @@ fn render_cosmos_frame(
let mut ordered = vec![
Tag {
at: earth_at + vec2(0.0, earth_r + 10.0),
- align: egui::Align2::CENTER_TOP,
+ align: Align::CENTER_TOP,
text: "Earth · you".into(),
size: theme::SIZE_BODY,
- ink: theme::DARK32.cream,
+ ink: theme::DARK.cream,
a: bd * you_apart,
},
Tag {
at: sun_at + vec2(0.0, sun_r + 10.0),
- align: egui::Align2::CENTER_TOP,
+ align: Align::CENTER_TOP,
text: sun_words,
size: theme::SIZE_BODY,
ink: SUN,
@@ -1354,14 +1273,14 @@ fn render_cosmos_frame(
},
Tag {
at: moon_at + vec2(8.0, 0.0),
- align: egui::Align2::LEFT_CENTER,
+ align: Align::LEFT_CENTER,
text: format!(
"Moon · {} · {}",
distance_words(MOON_DIST_M),
light_time_words(MOON_DIST_M)
),
size: theme::SIZE_SUB,
- ink: theme::DARK32.cream,
+ ink: theme::DARK.cream,
a: ma,
},
];
@@ -1411,7 +1330,7 @@ fn render_cosmos_frame(
if !said.is_empty() {
captions.push(Tag {
at: foot,
- align: egui::Align2::LEFT_BOTTOM,
+ align: Align::LEFT_BOTTOM,
text: {
let words = said.join(" · ");
let mut c = words.chars();
@@ -1420,41 +1339,30 @@ fn render_cosmos_frame(
.unwrap_or_default()
},
size: theme::SIZE_SUB,
- ink: theme::DARK32.text_dim,
+ ink: theme::DARK.text_dim,
a: bd,
});
}
captions.push(Tag {
at: foot - vec2(0.0, 18.0),
- align: egui::Align2::LEFT_BOTTOM,
+ align: Align::LEFT_BOTTOM,
text: "To scale in the middle, squeezed towards the edge · rings at light-travel distances"
.into(),
size: theme::SIZE_SUB,
- ink: theme::DARK32.text_dim,
+ ink: theme::DARK.text_dim,
a: ruler,
});
// Clear of the rail on the right and of the captions and the bar below.
let mut room = screen.shrink2(vec2(48.0, 8.0));
room.max.y = foot.y - 40.0;
- let placed = place_tags(&p, ordered, room);
- match out.lib.take() {
- None => {
- for t in &captions {
- t.paint(&p);
- }
- for (t, _) in &placed {
- t.paint(&p);
- }
- }
- Some(shapes) => {
- let mut tags: Vec<CosmosTag> = placed.iter().map(|(t, r)| t.publish(*r)).collect();
- tags.extend(captions.iter().map(|t| t.publish(t.rect(&p))));
- *published = Some(CosmosFrame { shapes, tags });
- }
- }
- if let Some(sky_out) = sky_out {
- *sky_out = sky;
- }
+ let placed = place_tags(ordered, room);
+ let mut tags: Vec<CosmosTag> = placed.iter().map(|(t, r)| t.publish(*r)).collect();
+ tags.extend(captions.iter().map(|t| t.publish(t.rect())));
+ *published = Some(CosmosFrame {
+ shapes: out.shapes,
+ tags,
+ });
+ *sky_out = Some(sky);
}
/// One galaxy past the Milky Way, placed in the map's frame.
@@ -1555,17 +1463,16 @@ fn galaxy_dot(log_lum: f32) -> f32 {
(0.6 + (log_lum - 8.0) * 0.45).clamp(0.6, 2.0)
}
-/// The galaxies, one mesh of small squares (forty thousand circles would each
-/// be their own shape), at most one per two-pixel bin so the survey's far shell,
-/// squeezed into the rim, is not drawn over itself many times. Answers the
-/// named ones on screen, brightest first, for labels. Given `dots`, paints
-/// nothing and leaves the squares there for the library's camera.
+/// The galaxies, as small squares into `dots` (one mesh, `lib_cosmos_sky`:
+/// forty thousand circles would each be their own shape), at most one per
+/// two-pixel bin so the survey's far shell, squeezed into the rim, is not
+/// drawn over itself many times. Answers the named ones on screen, for
+/// labels.
#[allow(clippy::too_many_arguments)]
-fn paint_galaxies<'a>(
- p: &egui::Painter,
- mut dots: Option<&mut Vec<SkyDot>>,
+fn place_galaxies<'a>(
+ dots: &mut Vec<SkyDot>,
view: &View,
- screen: egui::Rect,
+ screen: Area,
galaxies: &'a [PlacedGalaxy],
fade: impl Fn(&PlacedGalaxy) -> f32,
away_from: Pos2,
@@ -1576,7 +1483,6 @@ fn paint_galaxies<'a>(
(screen.height() / 2.0).ceil() as usize + 1,
);
let mut taken = vec![0u64; (w * h).div_ceil(64)];
- let mut mesh = egui::Mesh::default();
let mut named = Vec::new();
for g in galaxies {
let a = fade(g);
@@ -1607,23 +1513,11 @@ fn paint_galaxies<'a>(
(galaxy_dot(g.log_lum).max(1.0), 0.8)
};
let ink = alpha(GALAXY_DOT, a * ink);
- if let Some(dots) = dots.as_mut() {
- dots.push(SkyDot { at: q, r, ink });
- } else {
- let i = mesh.vertices.len() as u32;
- for d in [vec2(-r, -r), vec2(r, -r), vec2(r, r), vec2(-r, r)] {
- mesh.colored_vertex(q + d, ink);
- }
- mesh.add_triangle(i, i + 1, i + 2);
- mesh.add_triangle(i, i + 2, i + 3);
- }
+ dots.push(SkyDot { at: q, r, ink });
if !g.name.is_empty() {
named.push((g, q, a));
}
}
- if !mesh.is_empty() {
- p.add(egui::Shape::mesh(mesh));
- }
named
}
@@ -1661,7 +1555,7 @@ const ARMS: [(f32, f32, f32, f32, f32, f32, f32); 7] = [
/// fainter for it.
const ARM_REACH_DEG: f32 = 150.0;
/// Where H II regions glow along the arms.
-const GALAXY_HII: Color32 = Color32::from_rgb(0xFF, 0xA8, 0xC4);
+const GALAXY_HII: Rgba8 = Rgba8::from_rgb(0xFF, 0xA8, 0xC4);
/// The Milky Way as points, light years from its centre in its own plane (y
/// towards the Sun, x the way the Galaxy turns there, towards l = 90°), each
@@ -1671,7 +1565,7 @@ const GALAXY_HII: Color32 = Color32::from_rgb(0xFF, 0xA8, 0xC4);
/// and the boxy bulge in it; and the old disc, exponential with a 2.6 kpc
/// scale length (Bland-Hawthorn & Gerhard 2016). A fixed seed, so it is the
/// same galaxy every time.
-fn galaxy_points() -> Vec<(Vec2, f32, Color32)> {
+fn galaxy_points() -> Vec<(Vec2, f32, Rgba8)> {
let mut seed: u32 = 0x9E37_79B9;
let mut rnd = move || {
seed ^= seed << 13;
@@ -1814,7 +1708,7 @@ mod tests {
fn a_climb_moves_home_smoothly_and_never_off_screen() {
// The Earth (home) stays on screen from the ceiling to the top of the
// rail, and a 5 % climb never moves it, or the Sun, by a jump.
- let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0));
+ let screen = Area::from_min_size(Pos2::ZERO, vec2(800.0, 600.0));
let mut alt = 4.0e7;
let mut last: Option<(Pos2, Pos2)> = None;
while alt < crate::systems::zoom_rail::TOP_M {
@@ -1866,7 +1760,7 @@ mod tests {
// Andromeda (2.5 million ly) on the Local Group's rung, Virgo (54
// million) on the nearby galaxies', and the survey's reach (2 billion)
// on the cosmic web's.
- let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0));
+ let screen = Area::from_min_size(Pos2::ZERO, vec2(800.0, 600.0));
for (rung, ly) in [
(Rung::LocalGroup, 2.5e6),
(Rung::NearbyGalaxies, 5.4e7),
@@ -1886,7 +1780,7 @@ mod tests {
let v = view_at(crate::systems::zoom_rail::Scale::MilkyWay.overview());
let gc = gal_to_ecl(DVec3::X) * GC_LY * LIGHT_YEAR_M;
assert!(v.at(gc).distance(v.centre) < 5.0);
- let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0));
+ let screen = Area::from_min_size(Pos2::ZERO, vec2(800.0, 600.0));
let points = galaxy_points();
assert!(points.len() > 5_000);
for (pt, _, _) in points {
diff --git a/crates/cartopolis/src/systems/gui/egui_manager.rs b/crates/cartopolis/src/systems/gui/egui_manager.rs
index 1636395b..3aa1e65f 100644
--- a/crates/cartopolis/src/systems/gui/egui_manager.rs
+++ b/crates/cartopolis/src/systems/gui/egui_manager.rs
@@ -8,8 +8,7 @@
//! per-frame root `Ui` (egui 0.35 shows panels inside a `Ui`, not the `Context`).
//! - `begin_egui_frame` (PreUpdate) collects Bevy input, starts the egui frame,
//! and builds the shared root `Ui`.
-//! - UI systems run in Update: `egui_manager.ui_mut()` for panels,
-//! `egui_manager.ctx_mut()` for floating windows/areas.
+//! - What egui still draws runs in Update through `EguiRef::ctx()`.
//! - `end_egui_frame` (PostUpdate) finalizes the root `Ui` and tessellates the
//! output into `EguiRenderOutput`.
//! - `ExtractResourcePlugin` copies `EguiRenderOutput` to the render world.
@@ -77,19 +76,6 @@ pub struct EguiManager {
/// fallback for a frame that has **no** surface at all — see
/// [`begin_egui_frame`] — and a test app may run egui alone.
metrics: UiMetrics,
- /// Events produced by something *inside* the Update schedule that wants to
- /// reach egui as if a device had produced them — currently only
- /// `systems::onscreen_keyboard`, which is a keyboard drawn in egui and
- /// therefore cannot exist before the pass it types into has begun.
- ///
- /// Drained by [`begin_egui_frame`] into the **next** frame's `RawInput`,
- /// appended after the pointer batch exactly where the physical keyboard's
- /// events go. That placement is the point: `take_pass_events` splits the
- /// pointer stream so a press carries the position it had at its own point in
- /// the batch (`docs/notes/touch-input.md`), and a key event spliced into the
- /// middle of that would break the ordering contract for no gain — a key has
- /// no position.
- injected: Vec<egui::Event>,
/// What the panels left of the root `Ui` at the end of the last pass — the
/// map, in egui points. Read by [`Self::owns_click`]; `None` before the first
/// pass has ended.
@@ -104,89 +90,11 @@ pub struct EguiManager {
/// library's): a world click yields to it as it does to a panel. Set
/// each frame by `lib_host::bridge_input`, for the next frame.
overlay_owns_pointer: bool,
- /// A text field of a screen drawn beside egui holds the keyboard, so the
- /// game keys yield to it as to egui's own fields. Set each frame by
- /// `lib_host::bridge_input`, for the next frame.
- overlay_owns_keyboard: bool,
}
-/// The UI's scale and compactness are `systems::ui_input`'s, shared with the
-/// `UiMetrics` resource; named here too for the callers that grew up with it.
-pub use crate::systems::ui_input::COMPACT_WIDTH_PTS;
#[cfg(test)]
use crate::systems::ui_input::UI_SCALE_RANGE;
-/// What a compact right panel is exactly as wide as: **the screen**.
-///
-/// This used to read `viewport_w.max(240.0)` — a floor written so a very narrow
-/// window could not produce a degenerate sliver of a panel. On the web phone
-/// tier the floor inverted: the render budget's stage transform leaves a
-/// Fairphone 4 with ~215 pt of viewport, so the floor docked a panel **26 pt
-/// wider than the screen it sat in**, which is the exact failure it was added to
-/// prevent (`docs/notes/touch-input.md` recorded it as open). A compact panel
-/// *is* the viewport by definition, so there is nothing for a floor to protect:
-/// a 100 pt window gets a 100 pt panel, which is useless but honest, and the
-/// only genuinely degenerate input is a viewport that is not a width at all —
-/// zero before the first surface arrives, or NaN.
-#[must_use]
-pub fn compact_panel_width(viewport_w: f32) -> f32 {
- /// Stand-in for a viewport we do not have yet. Any positive number does;
- /// this one matches the old floor so a run that somehow reaches it looks the
- /// way it always did.
- const FALLBACK_PTS: f32 = 240.0;
- if viewport_w.is_finite() && viewport_w > 1.0 {
- viewport_w
- } else {
- FALLBACK_PTS
- }
-}
-
-/// Build a right-docked [`egui::Panel`] that adapts to the viewport: on a wide
-/// screen it docks beside the map at `wide_width` pt and stays resizable; on a
-/// compact (phone-ish) screen it fills the viewport and is fixed, since a resize
-/// handle is unusable on touch and a 320 pt dock would leave no map visible.
-///
-/// Takes `compact` / `viewport_w` as plain values (not `&EguiManager`) so it can
-/// be called after a caller has already taken `egui.ui_mut()` — building the
-/// panel then borrows nothing.
-pub fn responsive_right_panel(
- id: impl Into<egui::Id>,
- compact: bool,
- viewport_w: f32,
- wide_width: f32,
-) -> egui::Panel {
- // The page every panel shares (`theme::Palette::panel`, the midas hub's) and its
- // hairline, with room round the content. egui's own side-panel margin is
- // 8 x 2 pt, which set every title and row against the panel's edge; it was
- // 14 x 10 until 2026-11-08 ("less cramped"). The Chats screen sets its own
- // frame over this one.
- let frame = egui::Frame::NONE
- .fill(crate::systems::theme::p32().panel)
- .stroke(egui::Stroke::new(
- 1.0,
- crate::systems::theme::p32().panel_rim,
- ))
- .inner_margin(egui::Margin::symmetric(16, 14));
- if compact {
- egui::Panel::right(id)
- .frame(frame)
- .resizable(false)
- // No separator line: it has no neighbour to separate from, and egui
- // paints it at the panel's sliding edge on the root `Ui`, so while
- // another panel slid shut behind this one its line kept crossing the
- // open panel.
- .show_separator_line(false)
- // Fill the whole viewport — any inset leaves a strip of map peeking
- // down the left edge of the docked panel.
- .exact_size(compact_panel_width(viewport_w))
- } else {
- egui::Panel::right(id)
- .frame(frame)
- .resizable(true)
- .default_size(wide_width)
- }
-}
-
impl Default for EguiManager {
fn default() -> Self {
let ctx = egui::Context::default();
@@ -229,11 +137,9 @@ impl Default for EguiManager {
// The primary window's default resolution in `main.rs`; only ever
// used for the frames before the first `begin_egui_frame`.
metrics: UiMetrics::default(),
- injected: Vec::new(),
map_rect: None,
ui_animating: false,
overlay_owns_pointer: false,
- overlay_owns_keyboard: false,
}
}
}
@@ -251,14 +157,8 @@ fn geometry_still_current(repaint_delay: std::time::Duration, since_write: f32)
}
impl EguiManager {
- /// Borrow the egui context mutably. Only valid between `begin_egui_frame`
- /// and `end_egui_frame` (i.e. during the Update schedule). Use for floating
- /// windows/areas (`egui::Window`, `egui::Area`), which still take `&Context`.
- pub fn ctx_mut(&mut self) -> &mut egui::Context {
- &mut self.ctx
- }
-
- /// Borrow the egui context *shared* — same validity window as [`Self::ctx_mut`].
+ /// Borrow the egui context *shared*. Only valid between `begin_egui_frame`
+ /// and `end_egui_frame` (i.e. during the Update schedule).
///
/// `egui::Context` is `Sync` (an `Arc<RwLock<…>>` inside) and every
/// floating-`Area` call takes `&Context`, so a system that draws only its
@@ -270,10 +170,6 @@ impl EguiManager {
/// z-order is unaffected — each `Area` owns its own layer, ordered by
/// egui's memory, not by which system happened to register it first this
/// frame.
- ///
- /// (Worded without naming the mutable-parameter type next to the root-`Ui`
- /// accessor: `every_root_ui_panel_is_in_the_chain` scans source chunks for
- /// exactly that pair of tokens.)
pub fn ctx(&self) -> &egui::Context {
&self.ctx
}
@@ -286,13 +182,6 @@ impl EguiManager {
self.ui_animating
}
- /// Logical viewport size in points (physical pixels ÷ display scale), as egui
- /// lays out against it this frame.
- pub fn viewport_pts(&self) -> egui::Vec2 {
- let v = self.metrics.viewport_pts();
- egui::vec2(v.x, v.y)
- }
-
/// Record the surface this frame is laid out against, given the *display's*
/// scale factor — [`UiMetrics::set_surface`], which folds in the UI scale
/// and sanitises a zero or NaN display scale.
@@ -315,27 +204,6 @@ impl EguiManager {
self.metrics
}
- /// The *display's* own scale factor, with [`Self::ui_scale`] divided back
- /// out — physical pixels per window logical point, which is what winit
- /// reports and what `devicePixelRatio` is on the web.
- ///
- /// Exposed separately from [`Self::viewport_pts`] because the two answer
- /// different questions: layout wants points, but anything reasoning about
- /// *physical* size (a touch target in millimetres) needs the pixel density
- /// and the magnification apart, not multiplied together.
- pub fn display_scale(&self) -> f32 {
- self.metrics.display_scale()
- }
-
- /// Queue events for the next `RawInput` — see the `injected` field.
- ///
- /// Deliberately additive and un-deduplicated: the caller is producing the
- /// events a device would have produced, and a device is allowed to repeat
- /// itself.
- pub fn inject_events(&mut self, events: impl IntoIterator<Item = egui::Event>) {
- self.injected.extend(events);
- }
-
/// Convert a position in the window's logical points — which is what
/// `Window::cursor_position`, `TouchInput::position` and
/// `Camera::world_to_viewport` all speak — into egui points.
@@ -390,40 +258,6 @@ impl EguiManager {
self.overlay_owns_pointer = owns;
}
- /// Declare (each frame) that a text field beside egui has the keyboard —
- /// see the `overlay_owns_keyboard` field.
- #[cfg_attr(not(feature = "ui-probe"), allow(dead_code))]
- pub fn set_overlay_owns_keyboard(&mut self, owns: bool) {
- if self.overlay_owns_keyboard != owns {
- self.overlay_owns_keyboard = owns;
- }
- }
-
- /// A text field beside egui has the keyboard.
- #[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
- pub fn overlay_owns_keyboard(&self) -> bool {
- self.overlay_owns_keyboard
- }
-
- /// True on a narrow (phone-ish) viewport — see [`COMPACT_WIDTH_PTS`]. UI
- /// systems branch on this for a responsive layout.
- pub fn compact(&self) -> bool {
- self.viewport_pts().x < COMPACT_WIDTH_PTS
- }
-
- /// Borrow this frame's shared root `Ui`, for showing panels
- /// (`egui::Panel`, `egui::CentralPanel`). Only valid during Update.
- ///
- /// [`begin_egui_frame`] builds the root `Ui` unconditionally — including on a
- /// frame with no window at all — so during Update this cannot fail. It still
- /// panics rather than no-ops, because the one remaining way to reach it is a
- /// UI system registered in the wrong schedule, and that should be loud.
- pub fn ui_mut(&mut self) -> &mut egui::Ui {
- self.root_ui
- .as_mut()
- .expect("ui_mut() called outside an egui frame")
- }
-
/// egui's answers to `UiInput`'s questions this frame, for a press at the
/// window `cursor` — see [`publish_ui_input`].
pub fn verdict(&self, cursor: Option<Vec2>) -> EguiVerdict {
@@ -478,7 +312,6 @@ pub(crate) fn verdict_of(
/// later than when it was asked of egui directly.
pub fn publish_ui_input(mut egui: EguiMut, mut input: ResMut<UiInput>, windows: Query<&Window>) {
egui.set_overlay_owns_pointer(input.overlay_owns_pointer());
- egui.set_overlay_owns_keyboard(input.overlay_owns_keyboard());
let cursor = windows.iter().next().and_then(|w| w.cursor_position());
let verdict = egui.verdict(cursor);
if input.egui_verdict() != verdict {
@@ -1070,25 +903,6 @@ pub fn begin_egui_frame(
}
}
- // The in-app on-screen keyboard (`systems::onscreen_keyboard`), which is the
- // only keyboard two of our platforms have: NativeActivity brings up no IME at
- // all. It draws in Update, i.e. *inside* the pass it types into, so it cannot
- // put anything into this frame's `RawInput` — it queues instead, and lands one
- // frame later, here.
- //
- // Appended in the same place as the physical keyboard's events, after the
- // pointer batch, for the same reason: `take_pass_events` owns the ordering of
- // the pointer stream and a key event carries no position to order.
- //
- // Deliberately NOT behind `forward_keys`. That gate exists because egui keeps
- // focus on the last-clicked widget and would let a game key activate it; these
- // events are only produced while a text field is focused, and the very act of
- // tapping a key momentarily takes that focus away (which the keyboard puts
- // back) — so testing `text_edit_focused()` here would drop exactly the
- // keystroke that caused it.
- let injected = std::mem::take(&mut egui_manager.injected);
- events.extend(injected);
-
let screen_rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(logical_w, logical_h));
let mut viewport_info = egui::ViewportInfo::default();
diff --git a/crates/cartopolis/src/systems/gui/egui_manager/tests.rs b/crates/cartopolis/src/systems/gui/egui_manager/tests.rs
index d614fb6c..babc9e5f 100644
--- a/crates/cartopolis/src/systems/gui/egui_manager/tests.rs
+++ b/crates/cartopolis/src/systems/gui/egui_manager/tests.rs
@@ -100,9 +100,11 @@ fn a_brisk_tap_on_the_map_is_the_worlds_after_egui_saw_it_lift() {
.layer_id(egui::LayerId::background())
.max_rect(ctx.viewport_rect()),
);
- responsive_right_panel("panel", false, 1280.0, 260.0).show(&mut root, |ui| {
- ui.label("panel");
- });
+ egui::Panel::right("panel")
+ .default_size(260.0)
+ .show(&mut root, |ui| {
+ ui.label("panel");
+ });
map_rect = Some(root.available_rect_before_wrap());
drop(root);
let _ = ctx.end_pass_unpainted();
@@ -172,11 +174,6 @@ fn ui_metrics_and_ui_input_follow_the_manager() {
let mgr = app.world().resource::<EguiManager>();
let metrics = *app.world().resource::<UiMetrics>();
assert_eq!(metrics, mgr.metrics());
- assert_eq!(
- metrics.viewport_pts(),
- Vec2::new(mgr.viewport_pts().x, mgr.viewport_pts().y)
- );
- assert_eq!(metrics.compact(), mgr.compact());
let input = *app.world().resource::<UiInput>();
assert_eq!(input.egui_verdict(), mgr.verdict(None));
@@ -191,7 +188,6 @@ fn ui_metrics_and_ui_input_follow_the_manager() {
mgr.owns_click(false, None),
"the library's pointer reaches egui"
);
- assert!(mgr.overlay_owns_keyboard());
let keys = ButtonInput::<KeyCode>::default();
assert!(app
.world()
@@ -511,14 +507,12 @@ fn click_checkbox_with_drift(overlay: impl Fn(&egui::Context, egui::Rect), drift
let mut open = true;
let rect = std::cell::Cell::new(None);
let checked_ref = &mut checked;
- responsive_right_panel("layers_panel", false, 1280.0, 260.0).show_collapsible(
- &mut root,
- &mut open,
- |ui| {
+ egui::Panel::right("layers_panel")
+ .default_size(260.0)
+ .show_collapsible(&mut root, &mut open, |ui| {
let resp = ui.checkbox(checked_ref, "Buildings");
rect.set(Some(resp.rect));
- },
- );
+ });
overlay(&ctx, root.available_rect_before_wrap());
drop(root);
// The pass output is the paint job; this test only reads widget state.
@@ -605,8 +599,8 @@ fn ui_app(primary_window: Option<Window>) -> App {
}
/// The first thing every panel system does.
-fn touch_root_ui(mut egui: EguiMut) {
- let _ = egui.ui_mut();
+fn touch_root_ui(egui: EguiRef) {
+ let _ = egui.ctx();
}
/// The macOS shutdown crash (#2): Bevy despawns the window in `Last`, so the
@@ -659,10 +653,10 @@ fn a_degenerate_scale_factor_never_reaches_layout() {
let mut mgr = EguiManager::default();
for bad in [0.0, -1.0, f32::NAN] {
mgr.set_surface(UVec2::new(1280, 720), bad);
- assert_eq!(mgr.viewport_pts(), egui::vec2(1280.0, 720.0));
+ assert_eq!(mgr.metrics().viewport_pts(), Vec2::new(1280.0, 720.0));
}
mgr.set_surface(UVec2::new(2560, 1440), 2.0);
- assert_eq!(mgr.viewport_pts(), egui::vec2(1280.0, 720.0));
+ assert_eq!(mgr.metrics().viewport_pts(), Vec2::new(1280.0, 720.0));
}
/// The UI scale multiplies the widgets by dividing the viewport: the same
@@ -676,20 +670,8 @@ fn ui_scale_shrinks_the_viewport_it_magnifies() {
// Android, where a phone's whole 1080 px width reaches Bevy: 393 pt of
// viewport at a 2.75 scale factor, 262 pt of it after the magnification.
mgr.set_surface(UVec2::new(1080, 2280), 2.75);
- assert!((mgr.viewport_pts().x - 261.8).abs() < 0.1);
- assert!(mgr.compact());
-}
-
-/// A compact panel never exceeds the screen it docks in — which the old
-/// `viewport_w.max(240.0)` floor did on every web phone tier viewport under
-/// 240 pt, i.e. on the one device class the compact layout exists for.
-#[test]
-fn a_compact_panel_is_exactly_the_viewport() {
- assert_eq!(compact_panel_width(214.0), 214.0);
- assert_eq!(compact_panel_width(390.0), 390.0);
- // Only a viewport that is not a width falls back.
- assert_eq!(compact_panel_width(0.0), 240.0);
- assert_eq!(compact_panel_width(f32::NAN), 240.0);
+ assert!((mgr.metrics().viewport_pts().x - 261.8).abs() < 0.1);
+ assert!(mgr.metrics().compact());
}
/// Why [`phone_ui_scale`] is 1.0 on the web: the render budget's stage
@@ -705,15 +687,15 @@ fn the_web_phone_tier_has_no_room_to_magnify() {
let mut unscaled = EguiManager::default();
unscaled.metrics = UiMetrics::with_ui_scale(1.0);
unscaled.set_surface(surface, 2.75);
- assert!(unscaled.viewport_pts().x > 200.0, "usable at 1.0");
+ assert!(unscaled.metrics().viewport_pts().x > 200.0, "usable at 1.0");
let mut scaled = EguiManager::default();
scaled.metrics = UiMetrics::with_ui_scale(1.5);
scaled.set_surface(surface, 2.75);
assert!(
- scaled.viewport_pts().x < 240.0,
+ scaled.metrics().viewport_pts().x < 240.0,
"1.5× would dock a 240 pt panel in a {} pt viewport",
- scaled.viewport_pts().x
+ scaled.metrics().viewport_pts().x
);
}
@@ -748,52 +730,6 @@ fn window_to_ui_matches_the_bridge() {
);
}
-/// The seam the on-screen keyboard is built on: an event queued during
-/// `Update` must turn up in the **next** frame's `RawInput`, and the queue
-/// must be empty afterwards.
-///
-/// It cannot be the same frame — `begin_egui_frame` has already assembled
-/// `RawInput` and begun the pass by the time any UI system runs — and a queue
-/// that were not drained would replay the last character typed on every frame
-/// forever, which is the failure this pins.
-#[test]
-fn injected_events_reach_the_next_frames_input() {
- let mut app = ui_app(Some(Window::default()));
- app.update();
- app.world_mut()
- .resource_mut::<EguiManager>()
- .inject_events([egui::Event::Text("q".to_owned())]);
-
- let before = app
- .world()
- .resource::<EguiManager>()
- .ctx
- .input(|i| i.events.len());
- app.update();
-
- let mgr = app.world().resource::<EguiManager>();
- assert!(
- mgr.injected.is_empty(),
- "the injection queue was not drained"
- );
- assert!(
- mgr.ctx.input(|i| i
- .events
- .iter()
- .any(|e| matches!(e, egui::Event::Text(t) if t == "q"))),
- "the queued character never reached egui (had {before} events before)"
- );
-
- // And exactly once: a second frame with nothing queued must be quiet.
- app.update();
- let mgr = app.world().resource::<EguiManager>();
- assert!(
- !mgr.ctx
- .input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Text(_)))),
- "the injected event was replayed on a later frame"
- );
-}
-
/// The display scale and the UI magnification have to come apart again:
/// `set_surface` multiplies them into one number, and anything reasoning
/// about *physical* size (`onscreen_keyboard`'s 48 dp touch target) needs the
@@ -803,7 +739,7 @@ fn display_scale_survives_being_folded_into_the_surface() {
let mut mgr = EguiManager::default();
mgr.metrics = UiMetrics::with_ui_scale(1.5);
mgr.set_surface(UVec2::new(1080, 2280), 2.75);
- assert!((mgr.display_scale() - 2.75).abs() < 1e-4);
+ assert!((mgr.metrics().display_scale() - 2.75).abs() < 1e-4);
}
/// An out-of-range scale is clamped rather than obeyed: at 20× there is no
@@ -815,114 +751,3 @@ fn an_absurd_ui_scale_is_clamped() {
assert_eq!(clamped, want, "clamping {raw}");
}
}
-
-/// Every system that draws into the **shared root `Ui`** must be in the panel
-/// chain in `systems/gui/plugin.rs`, and this test is the guard the chain's comment used to
-/// say did not exist.
-///
-/// Leaving one out does not misplace a panel — it makes two panels swap
-/// composition order between frames, and because they share egui's single
-/// `Background` layer the one that lands underneath stops receiving clicks on
-/// those frames. The symptom is a control that ignores about half its
-/// presses; `layer_id_at` still answers `Background`, so no layer-level
-/// diagnostic sees it, and it cannot reproduce in a single-panel test.
-///
-/// This reads the sources rather than the schedule because the invariant is
-/// "draws into the root `Ui`" — a property of a function body, which the type
-/// system cannot express and a running `App` cannot be asked about.
-#[test]
-fn every_root_ui_panel_is_in_the_chain() {
- let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
- let mut files = Vec::new();
- let mut stack = vec![src.join("systems")];
- while let Some(dir) = stack.pop() {
- for e in std::fs::read_dir(&dir)
- .expect("systems/ is readable")
- .flatten()
- {
- let p = e.path();
- // A module's tests (`foo/tests.rs`) draw panels to test them,
- // and their functions sit at the top level there, where this
- // scan looks for systems.
- if p.is_dir() {
- stack.push(p);
- } else if p.extension().is_some_and(|x| x == "rs") && !p.ends_with("tests.rs") {
- files.push(p);
- }
- }
- }
-
- // The frame lifecycle brackets the panels by *schedule* (PreUpdate /
- // Update / PostUpdate + the render graph), not by ordering links, so it is
- // deliberately not in the chain.
- const LIFECYCLE: [&str; 3] = ["begin_egui_frame", "end_egui_frame", "egui_pass"];
-
- let mut drawers = Vec::new();
- for f in &files {
- let text = std::fs::read_to_string(f).expect("source is readable");
- // Split on top-level `fn ` starts; a body owns everything up to the next one.
- let mut idx: Vec<usize> = text
- .match_indices("\nfn ")
- .chain(text.match_indices("\npub fn "))
- .map(|(i, _)| i)
- .collect();
- idx.sort_unstable();
- idx.push(text.len());
- for w in idx.windows(2) {
- let chunk = &text[w[0]..w[1]];
- // A *system* that draws into the root `Ui` takes the manager
- // mutably; helpers like `responsive_right_panel` take plain
- // arguments and only build a widget, so they order nothing.
- if !chunk.contains("ui_mut()") || !chunk.contains("EguiMut") {
- continue;
- }
- let name = chunk
- .trim_start_matches(['\n'])
- .trim_start_matches("pub ")
- .trim_start_matches("fn ")
- .split(['(', '<'])
- .next()
- .unwrap_or("")
- .trim()
- .to_string();
- if !name.is_empty() && !LIFECYCLE.contains(&name.as_str()) {
- drawers.push(name);
- }
- }
- }
- // The scan works when it finds a drawer known to be one: the strip that
- // reserves the library's side panel (`panel_slots`), the last egui panel
- // in the root `Ui`. Not a count: egui's panels are going family by family
- // (the library draws them), so how many are left says nothing about the
- // scan.
- assert!(
- drawers.iter().any(|d| d == "reserve_library_panels"),
- "found only {drawers:?} root-`Ui` drawers, not `reserve_library_panels` — the scan has broken, not the chain"
- );
-
- // The chain is two chained halves (one per `ClientPhase`) chained to each
- // other, so it is found by its markers rather than by its first `.chain()`.
- let plugin = std::fs::read_to_string(src.join("systems/gui/plugin.rs"))
- .expect("systems/gui/plugin.rs is readable");
- let chain = plugin
- .split_once("// panel-chain:begin")
- .and_then(|(_, rest)| rest.split_once("// panel-chain:end"))
- .map(|(block, _)| block.to_string())
- .expect("the panel chain still exists in systems/gui/plugin.rs");
- assert!(
- chain.contains("drive_main_menu") && chain.contains("drive_dock"),
- "the chain block was extracted but looks wrong — the markers in \
- systems/gui/plugin.rs moved"
- );
-
- let missing: Vec<_> = drawers
- .iter()
- .filter(|d| !chain.contains(d.as_str()))
- .collect();
- assert!(
- missing.is_empty(),
- "these draw into the shared root `Ui` but are not in the panel chain: \
- {missing:?}\nAdd them to that tuple — an unordered pair swaps composition \
- order between frames and the panel underneath stops taking clicks."
- );
-}
diff --git a/crates/cartopolis/src/systems/gui/lib_about.rs b/crates/cartopolis/src/systems/gui/lib_about.rs
index c794c7ee..195a5345 100644
--- a/crates/cartopolis/src/systems/gui/lib_about.rs
+++ b/crates/cartopolis/src/systems/gui/lib_about.rs
@@ -120,7 +120,7 @@ fn panel(acts: &Acts, notices: &[Notice], compact: bool) -> View {
// block somebody may be looking for in a hurry, and the licence list is
// ~130 lines of scrolling.
view! {
- <div style={frame}>
+ <div style={frame} data-reserves-map="right">
<div style="display: flex; align-items: center; gap: 12px; min-height: 56px; padding: 0 12px 0 20px; border-bottom: 1px solid var(--m-border)">
<span style="color: var(--m-accent)">{icon(icons::ABOUT)}</span>
<h1 style="flex: 1; margin: 0; font-size: 19px; font-weight: 600; color: var(--m-text-strong)">"About"</h1>
diff --git a/crates/cartopolis/src/systems/gui/lib_admin.rs b/crates/cartopolis/src/systems/gui/lib_admin.rs
index 396f6f74..baea3c80 100644
--- a/crates/cartopolis/src/systems/gui/lib_admin.rs
+++ b/crates/cartopolis/src/systems/gui/lib_admin.rs
@@ -397,7 +397,7 @@ fn panel(l: &Live) -> View {
}
};
view! {
- <div style={frame}>
+ <div style={frame} data-reserves-map="right">
{header}
<div style="flex: 1; min-height: 0; overflow-y: auto; padding: 20px 20px 28px; display: flex; flex-direction: column; gap: 20px">
{notice}
diff --git a/crates/cartopolis/src/systems/gui/lib_avatar.rs b/crates/cartopolis/src/systems/gui/lib_avatar.rs
index 9e8c8ff1..8bcf26b8 100644
--- a/crates/cartopolis/src/systems/gui/lib_avatar.rs
+++ b/crates/cartopolis/src/systems/gui/lib_avatar.rs
@@ -5,9 +5,9 @@
//!
//! `ui::drive_avatar_chooser` seeds the draft, dresses the avatar in it
//! (`HumanDraft`) and aims the camera, which it takes from
-//! `AvatarChooserState::lib_close_up` and `lib_turn`; `panel_slots` keeps
-//! the panel's room in the map's layout — a sheet over the bottom half on a
-//! phone. Every change goes through the `DesignerState` methods of
+//! `AvatarChooserState::lib_close_up` and `lib_turn`; the panel's root marks
+//! the room it takes from the map (`data-reserves-map`, `ui_input::free_map`)
+//! — a sheet over the bottom half on a phone. Every change goes through the `DesignerState` methods of
//! `avatar_designer`.
//!
//! Drawn differently, because the library has no widget for them: a skin, an
@@ -1140,6 +1140,9 @@ fn panel(l: &Live) -> View {
designer::LIB_PANEL_WIDTH
)
};
+ // The room it takes from the map (`ui_input::RESERVES_MAP`): the
+ // dock, the pins and the names keep above the sheet, beside the panel.
+ let side = if l.compact { "bottom" } else { "right" };
let history = {
let l = l.clone();
move || -> View {
@@ -1205,7 +1208,7 @@ fn panel(l: &Live) -> View {
};
let close = l.act(Act::Close);
view! {
- <div style={frame}>
+ <div style={frame} data-reserves-map={side}>
<div style="display: flex; align-items: center; gap: 12px; min-height: 56px; padding: 0 12px 0 20px; border-bottom: 1px solid var(--m-border)">
<span style="color: var(--m-accent)">{icon(RightPanel::Appearance.icon())}</span>
<h1 style="flex: 1; margin: 0; font-size: 19px; font-weight: 600; color: var(--m-text-strong)">{RightPanel::Appearance.label()}</h1>
diff --git a/crates/cartopolis/src/systems/gui/lib_chats.rs b/crates/cartopolis/src/systems/gui/lib_chats.rs
index 4d2943ca..8876a76e 100644
--- a/crates/cartopolis/src/systems/gui/lib_chats.rs
+++ b/crates/cartopolis/src/systems/gui/lib_chats.rs
@@ -829,7 +829,7 @@ fn panel(l: &ChatsLive) -> View {
}
}
};
- view! { <div style={frame}>{route}</div> }
+ view! { <div style={frame} data-reserves-map="right">{route}</div> }
}
// ─── The list ────────────────────────────────────────────────────────────────
diff --git a/crates/cartopolis/src/systems/gui/lib_cosmos.rs b/crates/cartopolis/src/systems/gui/lib_cosmos.rs
index 3811abe0..4972c565 100644
--- a/crates/cartopolis/src/systems/gui/lib_cosmos.rs
+++ b/crates/cartopolis/src/systems/gui/lib_cosmos.rs
@@ -1,15 +1,13 @@
//! What lies past the globe's ceiling drawn by the component library
-//! (`lib_host`), beside egui's (`cosmos::render_cosmos`): the Sun, the
-//! planets and their orbits, the Earth and the Moon lit by the real Sun, the
-//! nearest stars and the lanes between them, the light-travel rings, the
-//! edge of the observable universe, and every label and caption.
+//! (`lib_host`): the Sun, the planets and their orbits, the Earth and the
+//! Moon lit by the real Sun, the nearest stars and the lanes between them,
+//! the light-travel rings, the edge of the observable universe, and every
+//! label and caption.
//!
-//! On with `CARTO_UI_LIB=cosmos` (or `1`). egui's system keeps all of the
-//! maths — the projection and its squeeze, the fades, which labels find
-//! room — and with `CosmosLib::lib` on paints at most the space round the
-//! globe's hole and the two star fields (below), publishing the rest of its
-//! frame in `CosmosLib::lib_view`. This mounts while that is `Some` and clears
-//! when it is `None` (below the ceiling).
+//! `cosmos::drive_cosmos` keeps all of the maths — the projection and its
+//! squeeze, the fades, which labels find room — and publishes its frame in
+//! `CosmosLib::view`. This mounts while that is `Some` and clears when it
+//! is `None` (below the ceiling).
//!
//! **One mount, restyled.** Every shape is one absolutely placed box and
//! every label one text box, each keyed (`"planet 3"`, `"ring 1 light
@@ -20,28 +18,27 @@
//! swept.
//!
//! **Built from boxes.** A disc is a `border-radius` box; a ring a bordered
-//! one; an orbit a bordered box as wide and high as egui's squeezed circle
-//! is across its two axes, turned by one `rotate()`; a lane a 1 px box
-//! turned onto its line. A lit sphere is one disc and one gradient: the
-//! terminator is egui's ellipse, which a circle through the same three
-//! points stands in for (through the two limb points across the Sun's
-//! direction and the point on that axis), lit inside it for a gibbous
-//! phase and outside it for a crescent — a hard edge, as egui's.
+//! one; an orbit a bordered box as wide and high as the squeezed circle is
+//! across its two axes, turned by one `rotate()`; a lane a 1 px box turned
+//! onto its line. A lit sphere is one disc and one gradient: the
+//! terminator is an ellipse, which a circle through the same three points
+//! stands in for (through the two limb points across the Sun's direction
+//! and the point on that axis), lit inside it for a gibbous phase and
+//! outside it for a crescent — a hard edge.
//!
//! **Not boxes**: the space behind everything (a full-screen fill with the
//! globe's round hole, under the star fields), the Milky Way's ~7,000
//! points and the galaxies' up to 50,000 — a node each would be the
-//! heaviest screen the library has, for one-pixel squares. On the Bevy
-//! backend `lib_cosmos_sky` draws them as two meshes on the library's own
-//! camera, under its UI; as DOM (the web) there is no such camera, and they
-//! stay painted on egui's background layer, under the DOM.
+//! heaviest screen the library has, for one-pixel squares.
+//! `lib_cosmos_sky` draws them as two meshes on a 2D camera under the
+//! library's screens, on both backends.
//!
-//! What differs: egui's halo is four offset copies of the text in the dark
-//! theme's ink, and so is this one's. On the Bevy backend a border radius
-//! is round, never elliptical, so an orbit seen at a slant comes out a
-//! rounded oblong rather than an ellipse (the DOM draws the ellipse);
-//! orbits are drawn only once the view looks down on them (egui's
-//! `face_on`), where they are close to round.
+//! A label's halo is four offset copies of its text in the dark theme's
+//! ink. On the Bevy backend a border radius is round, never elliptical, so
+//! an orbit seen at a slant comes out a rounded oblong rather than an
+//! ellipse (the DOM draws the ellipse); orbits are drawn only once the view
+//! looks down on them (`face_on` in `cosmos`), where they are close to
+//! round.
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
@@ -49,7 +46,6 @@ use std::rc::Rc;
use bevy::ecs::system::NonSendMarker;
use bevy::prelude::*;
-use egui::Color32;
// The library's, not Bevy's: an explicit import outranks the two globs.
use mithril::prelude::*;
@@ -58,6 +54,7 @@ use crate::systems::lib_pins::{boxed, px_scale};
use crate::systems::lib_settings::LibScreens;
use crate::systems::theme;
use crate::systems::theme::tokens::hex;
+use crate::systems::theme::Rgba8;
use crate::systems::ui_input::UiMetrics;
/// The cosmos' name in the library's host.
@@ -75,7 +72,7 @@ const MAX_HIDDEN: usize = 64;
/// How far out a terminator's circle may have its centre, as a share of the
/// sphere's radius: near a half phase the terminator's circle grows without
-/// bound towards egui's straight line.
+/// bound towards the straight line of a half phase.
const TERMINATOR_REACH: f32 = 8.0;
// ─── A keyed list of restyled boxes ─────────────────────────────────────────
@@ -203,7 +200,7 @@ fn shape_box(slot: Slot) -> View {
}
/// A label: its words over four copies one pixel off in the dark theme's
-/// ink, egui's halo, so it reads over anything.
+/// ink, a halo, so it reads over anything.
fn label_box(slot: Slot) -> View {
let style = slot.style;
let style = move || style.get();
@@ -237,34 +234,28 @@ thread_local! {
static MOUNTED: RefCell<Option<Live>> = const { RefCell::new(None) };
}
-/// Mounts the cosmos while egui publishes a frame of it, restyles it to
-/// each frame, and clears it below the ceiling. `PostUpdate`, before
-/// `DriveUi`, as every library screen; the cosmos' state is inserted here,
-/// the first frame.
+/// Mounts the cosmos while `cosmos::drive_cosmos` publishes a frame of it,
+/// restyles it to each frame, and clears it below the ceiling.
+/// `PostUpdate`, before `DriveUi`, as every library screen; the cosmos'
+/// state is inserted here, the first frame.
pub fn drive_lib_cosmos(
_main: NonSendMarker,
lib: Res<LibScreens>,
- cosmos: Option<ResMut<CosmosLib>>,
+ cosmos: Option<Res<CosmosLib>>,
metrics: Res<UiMetrics>,
mut commands: Commands,
) {
if !lib.cosmos {
return;
}
- let Some(mut cosmos) = cosmos else {
- commands.insert_resource(CosmosLib {
- lib: true,
- ..Default::default()
- });
+ let Some(cosmos) = cosmos else {
+ commands.insert_resource(CosmosLib::default());
return;
};
- if !cosmos.lib {
- cosmos.lib = true;
- }
let k = px_scale(metrics.ui_scale());
MOUNTED.with(|m| {
let mut m = m.borrow_mut();
- let Some(frame) = cosmos.lib_view.as_ref() else {
+ let Some(frame) = cosmos.view.as_ref() else {
if m.take().is_some() {
crate::systems::lib_host::clear_keyed(KEY);
}
@@ -309,7 +300,7 @@ pub fn drive_lib_cosmos(
/// The root: the whole window's corner, under every other library screen
/// (the map's names at -2 are the lowest of those), listening nowhere: a
/// drag over the cosmos moves the map. The shapes, then the labels over
-/// them, as egui paints them.
+/// them.
fn view_of(l: &Live) -> View {
let shapes = l.shapes.view(0, false);
let labels = l.labels.view(1, true);
@@ -321,11 +312,11 @@ fn view_of(l: &Live) -> View {
}
}
-/// An egui colour as CSS, opaque, and its own alpha (`ORBIT`, `LANE` and
-/// `RING` carry one), which goes into the box's opacity.
-fn solid(c: Color32) -> (String, f32) {
- let [r, g, b, a] = c.to_srgba_unmultiplied();
- (hex(theme::Rgba8::from_rgb(r, g, b)), f32::from(a) / 255.0)
+/// A colour as CSS, opaque, and its own alpha (`ORBIT`, `LANE` and `RING`
+/// carry one), which goes into the box's opacity.
+fn solid(c: Rgba8) -> (String, f32) {
+ let [r, g, b, a] = c.to_array();
+ (hex(Rgba8::from_rgb(r, g, b)), f32::from(a) / 255.0)
}
fn finite(v: &[f32]) -> bool {
@@ -342,7 +333,7 @@ fn round(w: f32, h: f32) -> String {
}
}
-/// One shape's box, stacked `z` in egui's paint order.
+/// One shape's box, stacked `z` in paint order.
fn shape_style(s: &CosmosShape, z: usize, k: f32) -> String {
let (body, ink_alpha, ok) = match &s.kind {
ShapeKind::Disc { c, r, ink } => {
@@ -445,28 +436,20 @@ fn shape_style(s: &CosmosShape, z: usize, k: f32) -> String {
format!("{body}; opacity: {o:.3}; z-index: {z}")
}
-/// A sphere seen from the camera, lit from one side (`cosmos::paint_lit_sphere`
-/// draws the same with a mesh). `sun` is the Sun's direction on screen, x
+/// A sphere seen from the camera, lit from one side
+/// (`cosmos::ShapeKind::Sphere`). `sun` is the Sun's direction on screen, x
/// right and y up; `toward` how far it stands towards the viewer, −1 behind
/// the sphere to 1 behind the viewer.
///
-/// egui's lit part runs from the limb on the Sun's side to the terminator,
-/// an ellipse through the two limb points across the Sun's direction and
-/// the point `−toward · r` along it. The circle through those three points
-/// has its centre `x0 = r(1 − t²)/2t` along the Sun's direction: for a
-/// gibbous phase (t > 0) the lit part is inside it, for a crescent outside.
-fn sphere(
- c: egui::Pos2,
- r: f32,
- sun: Vec2,
- toward: f32,
- day: Color32,
- night: Color32,
- k: f32,
-) -> String {
+/// The lit part runs from the limb on the Sun's side to the terminator, an
+/// ellipse through the two limb points across the Sun's direction and the
+/// point `−toward · r` along it. The circle through those three points has
+/// its centre `x0 = r(1 − t²)/2t` along the Sun's direction: for a gibbous
+/// phase (t > 0) the lit part is inside it, for a crescent outside.
+fn sphere(c: Vec2, r: f32, sun: Vec2, toward: f32, day: Rgba8, night: Rgba8, k: f32) -> String {
let (day, night) = (solid(day).0, solid(night).0);
if r < 1.5 {
- // Too small for a phase: egui's day over its night, as one dot.
+ // Too small for a phase: the day side, as one dot.
let r = r.max(1.0) * k;
return boxed(
c.x * k - r,
@@ -516,7 +499,8 @@ fn sphere(
)
}
-/// One label's box where egui measured it, its line as tall as egui's.
+/// One label's box where `cosmos` measured it, its line as tall as the
+/// measure.
fn label_style(t: &CosmosTag, z: usize, k: f32) -> String {
let (ink, a) = solid(t.ink);
let o = (a * t.alpha).clamp(0.0, 1.0);
diff --git a/crates/cartopolis/src/systems/gui/lib_cosmos_sky.rs b/crates/cartopolis/src/systems/gui/lib_cosmos_sky.rs
index 61ec31c0..248d3fdd 100644
--- a/crates/cartopolis/src/systems/gui/lib_cosmos_sky.rs
+++ b/crates/cartopolis/src/systems/gui/lib_cosmos_sky.rs
@@ -1,60 +1,83 @@
//! The space behind the cosmos and its two star fields — the full-screen
//! fill with the globe's round hole, the Milky Way's ~7,000 points and the
-//! galaxies' up to 50,000 — drawn as two Bevy 2D meshes on the library's own
-//! camera (`lib_host::LibCamera`), under the library's cosmos
-//! (`lib_cosmos`), which draws the bodies, rings and labels as boxes.
+//! galaxies' up to 50,000 — drawn as two Bevy 2D meshes under the library's
+//! cosmos (`lib_cosmos`), which draws the bodies, rings and labels as boxes.
//!
//! **Meshes, not nodes.** A node per one-pixel square would be the heaviest
-//! screen the library has. So `cosmos::render_cosmos` keeps the projection
-//! and publishes the frame's points (`CosmosLib::lib_sky`, egui's points),
-//! and this turns them into one mesh of small quads with vertex colours and
-//! one of the space round the hole, both on a `ColorMaterial`. Quads rather
-//! than `PrimitiveTopology::PointList`: wgpu has no point size (a point is
-//! one pixel on every backend, WebGPU and the phone's Vulkan included), and
-//! the dots are 1.5 to 4 points across.
+//! screen the library has. So `cosmos::drive_cosmos` keeps the projection
+//! and publishes the frame's points (`CosmosLib::sky`, UI points), and this
+//! turns them into one mesh of small quads with vertex colours and one of
+//! the space round the hole, both on a `ColorMaterial`. Quads rather than
+//! `PrimitiveTopology::PointList`: wgpu has no point size (a point is one
+//! pixel on every backend, WebGPU and the phone's Vulkan included), and the
+//! dots are 1.5 to 4 points across.
//!
-//! **Under the UI.** On a `Camera2d` the UI pass runs after the 2D passes
-//! (`bevy_ui_render` puts it after `Core2dSystems::PostProcess`), so every
-//! library node, the cosmos' boxes included, draws over these. The library's
-//! camera draws over the world camera's picture, and so over egui as well:
-//! while the cosmos shows, its space covers anything egui still draws.
+//! **Which camera.** On the Bevy backend (`ui-probe`) the meshes go on the
+//! library's own camera (`lib_host::LibCamera`): there the UI pass runs
+//! after the 2D passes (`bevy_ui_render` puts it after
+//! `Core2dSystems::PostProcess`), so every library node, the cosmos' boxes
+//! included, draws over them. As DOM (the web, `ui-dom`) the library has no
+//! camera — its screens are elements over the canvas, over everything the
+//! canvas shows — so this spawns a `Camera2d` of its own for the sky
+//! ([`SkyCamera`]), drawn after the world's camera and set up as the
+//! library's is: its own texture cleared to transparent, laid over the
+//! world's picture premultiplied. It is spawned the first time the sky
+//! shows, and switched off whenever it does not, so below the ceiling it
+//! costs no pass at all. Either camera draws over the world camera's whole
+//! picture, so while the cosmos shows, its space covers anything drawn
+//! into that picture.
//!
-//! **Rebuilt only when it moved.** egui counts each change of the published
-//! sky in `CosmosLib::sky_rev`; the meshes are rebuilt for a new count, or
-//! when the camera's size or scale changes, and only as the frame's upload
+//! **Rebuilt only when it moved.** `CosmosLib::sky_rev` counts each change
+//! of the published sky; the meshes are rebuilt for a new count, or when
+//! the camera's size or scale changes, and only as the frame's upload
//! ledger admits them (`stream_ledger::admit`): a refused rebuild keeps the
//! last meshes up and tries again next frame. Hidden below the ceiling.
-//!
-//! **Only where there is such a camera**: this sets `CosmosLib::sky` while
-//! the library's camera exists, which is what tells egui to stop painting the
-//! sky. As DOM (the web) there is none, and egui keeps painting it under the
-//! DOM.
use bevy::asset::RenderAssetUsages;
use bevy::mesh::{Indices, PrimitiveTopology};
use bevy::prelude::*;
use bevy::sprite_render::{AlphaMode2d, ColorMaterial, MeshMaterial2d};
-use egui::Color32;
use crate::systems::cosmos::{CosmosLib, CosmosSky};
-use crate::systems::lib_host::LibCamera;
use crate::systems::lib_settings::LibScreens;
+use crate::systems::theme::Rgba8;
/// One of the two meshes.
#[derive(Component)]
pub struct CosmosSkyPart;
+/// The sky's own 2D camera, where the library has none (the web: its
+/// screens are DOM over the canvas).
+#[cfg(not(feature = "ui-probe"))]
+#[derive(Component)]
+pub struct SkyCamera;
+
+/// The camera the sky is drawn on: the library's own on the Bevy backend.
+#[cfg(feature = "ui-probe")]
+type SkyOn = crate::systems::lib_host::LibCamera;
+#[cfg(not(feature = "ui-probe"))]
+type SkyOn = SkyCamera;
+
+/// Where the sky's own camera draws among the cameras on one target: after
+/// the world's (0), before the library's (100, absent wherever this one is
+/// spawned).
+#[cfg(not(feature = "ui-probe"))]
+const SKY_CAMERA_ORDER: isize = 50;
+
/// The meshes, their entities, and what they were last built for.
#[derive(Default)]
pub struct SkyState {
/// The space round the hole, and the star fields' squares.
fill: Option<(Entity, Handle<Mesh>)>,
dots: Option<(Entity, Handle<Mesh>)>,
- /// The `sky_rev` and the camera (logical size, logical pixels per egui
+ /// The `sky_rev` and the camera (logical size, logical pixels per UI
/// point) the meshes hold; `None` until built, and again once hidden.
built: Option<(u64, Vec2, f32)>,
/// Whether the last build had any squares.
any_dots: bool,
+ /// The sky's own camera has been asked for ([`SkyCamera`]).
+ #[cfg(not(feature = "ui-probe"))]
+ camera_spawned: bool,
}
/// Where the space mesh and the squares sit on the camera's z: the squares
@@ -62,14 +85,18 @@ pub struct SkyState {
const FILL_Z: f32 = 0.0;
const DOTS_Z: f32 = 0.5;
-/// Draws the cosmos' space and star fields on the library's camera while
-/// egui publishes them, and hides them otherwise. `PostUpdate`, after
-/// `cosmos::render_cosmos` (`Update`) has published the frame.
+/// Draws the cosmos' space and star fields while `cosmos::drive_cosmos`
+/// publishes them, and hides them otherwise. `PostUpdate`, after
+/// `drive_cosmos` (`Update`) has published the frame.
#[allow(clippy::too_many_arguments)]
pub fn drive_lib_cosmos_sky(
lib: Res<LibScreens>,
- cosmos: Option<ResMut<CosmosLib>>,
- cameras: Query<&Camera, With<LibCamera>>,
+ cosmos: Option<Res<CosmosLib>>,
+ mut cameras: Query<&mut Camera, With<SkyOn>>,
+ #[cfg(not(feature = "ui-probe"))] world: Query<
+ &bevy::camera::RenderTarget,
+ With<crate::components::FreeCamera>,
+ >,
mut parts: Query<&mut Visibility, With<CosmosSkyPart>>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
@@ -80,17 +107,33 @@ pub fn drive_lib_cosmos_sky(
return;
}
// Inserted by `lib_cosmos` on its first frame.
- let Some(mut cosmos) = cosmos else {
+ let Some(cosmos) = cosmos else {
return;
};
- let camera = cameras.single().ok();
- if cosmos.sky != camera.is_some() {
- cosmos.sky = camera.is_some();
- }
- let target =
- camera.and_then(|c| Some((c.logical_viewport_size()?, c.target_scaling_factor()?)));
let rev = cosmos.sky_rev;
- let (Some(sky), Some((size, scale_factor))) = (cosmos.lib_sky.as_ref(), target) else {
+ let sky = cosmos.sky.as_ref();
+ // Written only where the camera is the sky's own.
+ #[cfg_attr(feature = "ui-probe", allow(unused_mut))]
+ let mut camera = cameras.single_mut().ok();
+ // The sky's own camera: asked for the first time the sky shows, and on
+ // only while it does.
+ #[cfg(not(feature = "ui-probe"))]
+ {
+ if camera.is_none() && sky.is_some() && !state.camera_spawned {
+ spawn_sky_camera(&mut commands, world.single().ok().cloned());
+ state.camera_spawned = true;
+ }
+ if let Some(c) = camera.as_mut() {
+ let on = sky.is_some();
+ if c.is_active != on {
+ c.is_active = on;
+ }
+ }
+ }
+ let target = camera
+ .as_ref()
+ .and_then(|c| Some((c.logical_viewport_size()?, c.target_scaling_factor()?)));
+ let (Some(sky), Some((size, scale_factor))) = (sky, target) else {
state.built = None;
show(&mut parts, &state, false);
return;
@@ -98,7 +141,7 @@ pub fn drive_lib_cosmos_sky(
if size.x <= 0.0 || size.y <= 0.0 || scale_factor <= 0.0 || sky.pixels_per_point <= 0.0 {
return;
}
- // Logical pixels of the camera's target per egui point.
+ // Logical pixels of the camera's target per UI point.
let s = sky.pixels_per_point / scale_factor;
if state.fill.is_none() {
@@ -153,6 +196,32 @@ pub fn drive_lib_cosmos_sky(
show(&mut parts, &state, built);
}
+/// The sky's own camera, on the world camera's target: a `Camera2d` drawn
+/// after the world's, set up as `lib_host`'s `LibCamera` is. It has a
+/// texture of its own, laid over the target after, so it clears that
+/// texture to transparent each frame and lays it over premultiplied;
+/// uncleared, every frame would draw onto the last's.
+#[cfg(not(feature = "ui-probe"))]
+fn spawn_sky_camera(commands: &mut Commands, target: Option<bevy::camera::RenderTarget>) {
+ commands.spawn((
+ Camera2d,
+ Camera {
+ order: SKY_CAMERA_ORDER,
+ clear_color: bevy::camera::ClearColorConfig::Custom(Color::NONE),
+ output_mode: bevy::camera::CameraOutputMode::Write {
+ blend_state: Some(
+ bevy::render::render_resource::BlendState::PREMULTIPLIED_ALPHA_BLENDING,
+ ),
+ clear_color: bevy::camera::ClearColorConfig::None,
+ },
+ ..Default::default()
+ },
+ Msaa::Off,
+ target.unwrap_or_default(),
+ SkyCamera,
+ ));
+}
+
/// Shows or hides the two meshes; the squares only when there are any.
fn show(parts: &mut Query<&mut Visibility, With<CosmosSkyPart>>, state: &SkyState, on: bool) {
let mut set = |part: Option<&(Entity, Handle<Mesh>)>, on: bool| {
@@ -174,10 +243,10 @@ fn show(parts: &mut Query<&mut Visibility, With<CosmosSkyPart>>, state: &SkyStat
set(state.dots.as_ref(), on && state.any_dots);
}
-/// An egui colour (premultiplied sRGB) as the linear, straight-alpha vertex
-/// colour a `ColorMaterial` blends.
-fn linear(c: Color32) -> [f32; 4] {
- let [r, g, b, a] = c.to_srgba_unmultiplied();
+/// A theme colour (sRGB, straight alpha) as the linear, straight-alpha
+/// vertex colour a `ColorMaterial` blends.
+fn linear(c: Rgba8) -> [f32; 4] {
+ let [r, g, b, a] = c.to_array();
let lut = srgb_to_linear();
[
lut[usize::from(r)],
@@ -228,9 +297,9 @@ fn mesh_of(positions: Vec<[f32; 3]>, colours: Vec<[f32; 4]>, indices: Vec<u32>)
}
/// Space over the whole target but the round hole the globe shows through:
-/// egui's `fill_around` — the four bands round the hole's square, then the
-/// ring between the square and the circle, its rays meeting the square's
-/// corners exactly — in the camera's pixels.
+/// the four bands round the hole's square, then the ring between the
+/// square and the circle, its rays meeting the square's corners exactly —
+/// in the camera's pixels.
fn fill_mesh(sky: &CosmosSky, size: Vec2, s: f32) -> Mesh {
let frame = Frame { half: size / 2.0 };
let ink = linear(sky.space);
@@ -251,18 +320,15 @@ fn fill_mesh(sky: &CosmosSky, size: Vec2, s: f32) -> Mesh {
]);
idx.extend([i, i + 1, i + 2, i, i + 2, i + 3]);
};
- let hole = sky
- .hole
- .map(|(c, r)| (Vec2::new(c.x * s, c.y * s), r * s))
- .filter(|(c, r)| {
- c.is_finite()
- && r.is_finite()
- && *r > 0.0
- && c.x + r > 0.0
- && c.x - r < size.x
- && c.y + r > 0.0
- && c.y - r < size.y
- });
+ let hole = sky.hole.map(|(c, r)| (c * s, r * s)).filter(|(c, r)| {
+ c.is_finite()
+ && r.is_finite()
+ && *r > 0.0
+ && c.x + r > 0.0
+ && c.x - r < size.x
+ && c.y + r > 0.0
+ && c.y - r < size.y
+ });
let Some((c, r)) = hole else {
quad(&mut pos, 0.0, 0.0, size.x, size.y);
let colours = vec![ink; pos.len()];
@@ -293,7 +359,7 @@ fn fill_mesh(sky: &CosmosSky, size: Vec2, s: f32) -> Mesh {
mesh_of(pos, colours, idx)
}
-/// The star fields' squares, egui's paint order, in the camera's pixels.
+/// The star fields' squares, in the published order, in the camera's pixels.
fn dots_mesh(sky: &CosmosSky, size: Vec2, s: f32) -> Mesh {
let frame = Frame { half: size / 2.0 };
let n = sky.dots.len();
@@ -323,10 +389,10 @@ fn dots_mesh(sky: &CosmosSky, size: Vec2, s: f32) -> Mesh {
mod tests {
use super::*;
- fn sky(hole: Option<(egui::Pos2, f32)>) -> CosmosSky {
+ fn sky(hole: Option<(Vec2, f32)>) -> CosmosSky {
CosmosSky {
pixels_per_point: 1.0,
- space: Color32::from_rgb(4, 7, 10),
+ space: Rgba8::from_rgb(4, 7, 10),
hole,
dots: vec![],
}
@@ -341,7 +407,7 @@ mod tests {
#[test]
fn the_hole_s_ring_meets_the_circle_and_its_square() {
let size = Vec2::new(800.0, 600.0);
- let mesh = fill_mesh(&sky(Some((egui::pos2(400.0, 300.0), 100.0))), size, 1.0);
+ let mesh = fill_mesh(&sky(Some((Vec2::new(400.0, 300.0), 100.0))), size, 1.0);
// Four bands and 65 rays of two.
assert_eq!(mesh.count_vertices(), 16 + 130);
let Some(bevy::mesh::VertexAttributeValues::Float32x3(p)) =
@@ -359,13 +425,13 @@ mod tests {
}
#[test]
- fn a_square_lands_where_egui_put_it() {
+ fn a_square_lands_where_it_was_published() {
let mut sky = sky(None);
sky.pixels_per_point = 2.0;
sky.dots.push(crate::systems::cosmos::SkyDot {
- at: egui::pos2(10.0, 20.0),
+ at: Vec2::new(10.0, 20.0),
r: 1.0,
- ink: Color32::WHITE,
+ ink: Rgba8::WHITE,
});
// Twice the pixels per point at a scale factor of 1: 2 logical px.
let mesh = dots_mesh(&sky, Vec2::new(100.0, 100.0), 2.0);
diff --git a/crates/cartopolis/src/systems/gui/lib_design_room.rs b/crates/cartopolis/src/systems/gui/lib_design_room.rs
index 66b0e625..56b6bb2d 100644
--- a/crates/cartopolis/src/systems/gui/lib_design_room.rs
+++ b/crates/cartopolis/src/systems/gui/lib_design_room.rs
@@ -367,7 +367,7 @@ pub fn drive_lib_design_room(
// A right panel (the script editor itself) takes that side. On a
// phone the outliner and this do not fit side by side (egui's
// covered this one): the outliner first, this when it is not up.
- let narrow = size.x < crate::systems::egui_manager::COMPACT_WIDTH_PTS;
+ let narrow = size.x < crate::systems::ui_input::COMPACT_WIDTH_PTS;
let scripts = (open && right_panel.is(RightPanel::None) && !(narrow && show_outliner))
.then(|| {
let rows = script_rows(&room, &prims, &editor);
@@ -1077,7 +1077,7 @@ pub fn drive_lib_design_room_overlays(
// the outliner is up: there they took the same corner, and the gizmo
// drew over the outliner's header (the scripts panel gives way there
// for the same reason).
- let narrow = metrics.viewport_pts().x < crate::systems::egui_manager::COMPACT_WIDTH_PTS;
+ let narrow = metrics.viewport_pts().x < crate::systems::ui_input::COMPACT_WIDTH_PTS;
let crowded = narrow && !room.tree.is_empty();
let gizmo = (open && !crowded).then(|| {
let c = (GIZMO_W * 0.5, GIZMO_CANVAS_H * 0.5);
diff --git a/crates/cartopolis/src/systems/gui/lib_driver.rs b/crates/cartopolis/src/systems/gui/lib_driver.rs
index 1642b8bc..1b649044 100644
--- a/crates/cartopolis/src/systems/gui/lib_driver.rs
+++ b/crates/cartopolis/src/systems/gui/lib_driver.rs
@@ -43,7 +43,7 @@ use crate::systems::{icons, theme};
/// The navigation chrome's name in the library's host.
const KEY: &str = "driver";
-/// egui's `overlay_frame` without its margin, as a style: the surface and
+/// the overlay frame egui drew without its margin, as a style: the surface and
/// its rim. Border-box, so a width beside it is the frame's whole width.
const SURFACE: &str = "box-sizing: border-box; background: var(--m-surface); \
border: 1px solid var(--m-border); border-radius: var(--m-radius-lg); \
diff --git a/crates/cartopolis/src/systems/gui/lib_host.rs b/crates/cartopolis/src/systems/gui/lib_host.rs
index 3f46ee3d..db798926 100644
--- a/crates/cartopolis/src/systems/gui/lib_host.rs
+++ b/crates/cartopolis/src/systems/gui/lib_host.rs
@@ -92,7 +92,6 @@ pub fn prepare_bevy(
|| lib.scenario
|| lib.design_room
|| lib.admin
- || lib.keyboard
|| lib.chrome
|| lib.osd
|| lib.pins
@@ -253,6 +252,57 @@ pub fn bridge_input(
}
}
+/// The map's free area, from the library's own layout: the screen less the
+/// box of every element marked `data-reserves-map` (`ui_input::RESERVES_MAP`
+/// — the side panels and the Appearance sheet), each cut from the edge it
+/// names (`ui_input::free_map`). Written into `UiInput::map_rect` in window
+/// points, for the next frame's dock, search bar, round buttons, pins and
+/// names. `PostUpdate`, after `bevy_ui`'s layout, so the boxes are this
+/// frame's.
+#[cfg(feature = "ui-probe")]
+pub fn measure_map_room(world: &mut bevy::prelude::World) {
+ use bevy::math::{Rect, Vec2};
+
+ use crate::systems::ui_input::{free_map, MapSide, UiInput, UiMetrics, RESERVES_MAP};
+
+ if !world.contains_resource::<mithril_bevy::UiTree>() {
+ return;
+ }
+ let rooms: Vec<(MapSide, Rect)> = mithril_bevy::marked_rects(world, RESERVES_MAP)
+ .into_iter()
+ .filter_map(|(side, rect)| Some((MapSide::parse(&side)?, rect)))
+ .collect();
+ let metrics = world.resource::<UiMetrics>();
+ let k = metrics.ui_scale();
+ let map = free_map(
+ Rect::from_corners(Vec2::ZERO, metrics.viewport_pts()),
+ rooms,
+ );
+ let window = Rect::from_corners(map.min * k, map.max * k);
+ let mut input = world.resource_mut::<UiInput>();
+ if input.map_rect() != Some(window) {
+ input.set_map_rect(Some(window));
+ }
+}
+
+/// [`measure_map_room`] on the web: the marked elements' boxes as the
+/// browser laid them out (`getBoundingClientRect`), mapped from the screens'
+/// container onto the window. `PreUpdate`, reading the layout the browser
+/// made for the last frame, so nothing forces a reflow mid-frame.
+#[cfg(all(feature = "ui-dom", target_arch = "wasm32"))]
+pub fn measure_map_room_dom(
+ metrics: bevy::prelude::Res<crate::systems::ui_input::UiMetrics>,
+ mut input: bevy::prelude::ResMut<crate::systems::ui_input::UiInput>,
+) {
+ let window = metrics.viewport_pts() * metrics.ui_scale();
+ let Some(map) = dom::map_room(window) else {
+ return;
+ };
+ if input.map_rect() != Some(map) {
+ input.set_map_rect(Some(map));
+ }
+}
+
#[cfg(all(feature = "ui-dom", target_arch = "wasm32"))]
mod dom {
use std::cell::RefCell;
@@ -351,4 +401,82 @@ mod dom {
app.mounted.unmount(&app.renderer, &parent);
}
}
+
+ /// The map in window points (`window` its size): the container less
+ /// every `[data-reserves-map]` element's box, each mapped from the
+ /// container's CSS pixels onto the window — on the phone tier the canvas
+ /// is scaled by the render budget's stage transform, so a CSS pixel is
+ /// not a window point. `None` before anything has mounted.
+ pub fn map_room(window: bevy::math::Vec2) -> Option<bevy::math::Rect> {
+ use bevy::math::{Rect, Vec2};
+ use js_sys::Reflect;
+ use wasm_bindgen::JsValue;
+
+ use crate::systems::ui_input::{free_map, MapSide, RESERVES_MAP};
+
+ let container = document()?.get_element_by_id(CONTAINER)?;
+ let frame = client_rect(&container)?;
+ if frame.width() <= 0.0 || frame.height() <= 0.0 {
+ return None;
+ }
+ let k = Vec2::new(window.x / frame.width(), window.y / frame.height());
+ let to_window =
+ |r: Rect| Rect::from_corners((r.min - frame.min) * k, (r.max - frame.min) * k);
+ let select = Reflect::get(&container, &JsValue::from_str("querySelectorAll"))
+ .ok()?
+ .dyn_into::<js_sys::Function>()
+ .ok()?;
+ let list = select
+ .call1(&container, &JsValue::from_str(&format!("[{RESERVES_MAP}]")))
+ .ok()?;
+ let len = Reflect::get(&list, &JsValue::from_str("length"))
+ .ok()?
+ .as_f64()? as u32;
+ let mut rooms = Vec::new();
+ for i in 0..len {
+ let Ok(el) = Reflect::get_u32(&list, i) else {
+ continue;
+ };
+ let el: web_sys::Element = el.unchecked_into();
+ let Some(side) = el
+ .get_attribute(RESERVES_MAP)
+ .and_then(|v| MapSide::parse(&v))
+ else {
+ continue;
+ };
+ let Some(r) = client_rect(&el) else {
+ continue;
+ };
+ if r.width() > 0.0 && r.height() > 0.0 {
+ rooms.push((side, to_window(r)));
+ }
+ }
+ Some(free_map(Rect::from_corners(Vec2::ZERO, window), rooms))
+ }
+
+ /// `getBoundingClientRect()`, in CSS pixels, through `Reflect` (the
+ /// client's web-sys carries no `DomRect`).
+ fn client_rect(el: &wasm_bindgen::JsValue) -> Option<bevy::math::Rect> {
+ use js_sys::Reflect;
+ use wasm_bindgen::JsValue;
+
+ let rect = Reflect::get(el, &JsValue::from_str("getBoundingClientRect"))
+ .ok()?
+ .dyn_into::<js_sys::Function>()
+ .ok()?
+ .call0(el)
+ .ok()?;
+ let at = |name: &str| -> Option<f32> {
+ Reflect::get(&rect, &JsValue::from_str(name))
+ .ok()?
+ .as_f64()
+ .map(|v| v as f32)
+ };
+ Some(bevy::math::Rect::new(
+ at("left")?,
+ at("top")?,
+ at("right")?,
+ at("bottom")?,
+ ))
+ }
}
diff --git a/crates/cartopolis/src/systems/gui/lib_interact.rs b/crates/cartopolis/src/systems/gui/lib_interact.rs
index 2cd99199..bb0078ce 100644
--- a/crates/cartopolis/src/systems/gui/lib_interact.rs
+++ b/crates/cartopolis/src/systems/gui/lib_interact.rs
@@ -39,7 +39,7 @@ const PROMPT_KEY: &str = "interact_prompt";
/// The chip's name in the library's host.
const CHIP_KEY: &str = "attach_chip";
-/// egui's `overlay_frame`, as a style: the surface, its rim, 14 × 12 inside.
+/// the overlay frame egui drew, as a style: the surface, its rim, 14 × 12 inside.
const FRAME: &str = "box-sizing: border-box; padding: 12px 14px; \
background: var(--m-surface); border: 1px solid var(--m-border); \
border-radius: var(--m-radius-lg); box-shadow: var(--m-shadow)";
diff --git a/crates/cartopolis/src/systems/gui/lib_keyboard.rs b/crates/cartopolis/src/systems/gui/lib_keyboard.rs
index d83efb24..665eb932 100644
--- a/crates/cartopolis/src/systems/gui/lib_keyboard.rs
+++ b/crates/cartopolis/src/systems/gui/lib_keyboard.rs
@@ -1,51 +1,53 @@
-//! The on-screen keyboard drawn by the component library (`lib_host`),
-//! beside egui's (`onscreen_keyboard`): the same keys, layers, shift and
-//! place — the bottom edge, full width, or the top where egui's flips to
-//! clear its field — and it types into whichever field holds the keyboard,
-//! an egui `TextEdit` (the events egui's keys inject) or a library text
-//! field (`mithril_bevy::KeyEdits`, applied to the focused `EditableText`,
-//! Enter as the field's `keydown`).
+//! The on-screen keyboard's keys, drawn by the component library
+//! (`lib_host`): its state, placement and fingers are `onscreen_keyboard`'s,
+//! which raises the keys while a library text field has the focus. This
+//! draws them where they stand — the bottom edge, full width, or the top
+//! where they flip to clear their field — with the keys under a finger
+//! pressed and the character under each finger shown above its key; hands
+//! what they typed to the focused field (`mithril_bevy::KeyEdits`, Enter as
+//! the field's `keydown`); clears the field's focus when they are put away;
+//! and tells `onscreen_keyboard` where the field is.
//!
-//! On with `CARTO_UI_LIB=keyboard` where the platform wants the keys at all
-//! (`onscreen_keyboard::platform_wants_keyboard`: Android, a phone browser,
-//! `CARTO_OSK=1`). egui's keyboard then draws nothing
-//! (`OnScreenKeyboard::lib`) and keeps only its half: following egui's
-//! focus, putting it back after a tap on these keys, and claiming the strip
-//! so a tap on a key does not also press the egui widget under it. The
-//! keys carry `data-keep-focus`, so a press on one leaves a library field
-//! its focus (`mithril_bevy`'s `events.rs`).
-//!
-//! What egui's keys do and these do not yet: type on the lift of each
-//! finger (these type on a click, one finger), repeat a held backspace, and
-//! show the character under the finger above it.
+//! The keys carry `data-keep-focus`, so a press on one leaves the field its
+//! focus (`mithril_bevy`'s `events.rs`). They type from the fingers
+//! (`OnScreenKeyboard::track`), not their clicks; a click types only with no
+//! finger behind it (`OnScreenKeyboard::clicked`: the MCP server's `press`).
use std::cell::RefCell;
use std::rc::Rc;
use bevy::ecs::system::NonSendMarker;
+use bevy::input_focus::InputFocus;
use bevy::prelude::*;
+use bevy::text::EditableText;
+use bevy::ui::{ComputedNode, UiGlobalTransform};
use mithril::prelude::{el, signal, IntoView, Signal, View};
-use crate::systems::egui_manager::EguiMut;
-use crate::systems::lib_settings::LibScreens;
use crate::systems::onscreen_keyboard::{
- cap_at, Cap, KeyLayer, KeysTo, LibKey, OnScreenKeyboard, ShiftState,
+ cap_at, cap_name, Cap, KeyLayer, KeyPlace, OnScreenKeyboard, Preview, ShiftState, Stroke,
};
use crate::systems::{icons, theme};
+/// How many fingers get a key preview at once: two thumbs.
+const PREVIEW_SLOTS: usize = 2;
+
/// The keys as drawn, rebuilt when they move (a flip to the top, a resize).
#[derive(Clone, PartialEq)]
struct Geometry {
- slab: egui::Rect,
- keys: Vec<LibKey>,
+ slab: Rect,
+ keys: Vec<KeyPlace>,
}
#[derive(Clone)]
struct Live {
geometry: Geometry,
face: Signal<(KeyLayer, ShiftState)>,
- /// The keys tapped since the last frame, by row and column.
- taps: Rc<RefCell<Vec<(usize, usize)>>>,
+ /// The keys under a finger, by row and column.
+ held: Signal<Vec<(usize, usize)>>,
+ /// The key previews, relative to the slab.
+ previews: Signal<Vec<Preview>>,
+ /// The keys clicked since the last frame, by row and column.
+ clicks: Rc<RefCell<Vec<(usize, usize)>>>,
}
thread_local! {
@@ -53,62 +55,66 @@ thread_local! {
}
/// Mounts, feeds and unmounts the keyboard. `PostUpdate`, before
-/// `DriveUi`, as every library screen; after `render_onscreen_keyboard`
+/// `DriveUi`, as every library screen; after `drive_onscreen_keyboard`
/// (`Update`), which decides whether the keys are up and where.
pub fn drive_lib_keyboard(
_main: NonSendMarker,
- lib: Res<LibScreens>,
mut kb: ResMut<OnScreenKeyboard>,
- mut egui: EguiMut,
mut edits: ResMut<mithril_bevy::KeyEdits>,
- focus: Option<ResMut<bevy::input_focus::InputFocus>>,
+ focus: Option<ResMut<InputFocus>>,
+ fields: Query<(&ComputedNode, &UiGlobalTransform), With<EditableText>>,
+ time: Res<Time<Real>>,
) {
- if !lib.keyboard {
- return;
- }
- if !kb.lib {
- kb.lib = true;
- }
- // Last frame's taps, against the layer they were made on.
- let taps: Vec<(usize, usize)> = MOUNTED.with(|m| {
+ // Last frame's clicks, against the layer they were made on.
+ let clicks: Vec<(usize, usize)> = MOUNTED.with(|m| {
m.borrow()
.as_ref()
- .map(|live| std::mem::take(&mut *live.taps.borrow_mut()))
+ .map(|live| std::mem::take(&mut *live.clicks.borrow_mut()))
.unwrap_or_default()
});
- if !taps.is_empty() {
- let ctx = egui.ctx().clone();
- for (row, col) in taps {
- let Some(cap) = cap_at(kb.face().0, row, col) else {
- continue;
- };
- match kb.lib_tap(&ctx, cap) {
- Some((KeysTo::Egui, events)) => {
- if !events.is_empty() {
- egui.inject_events(events);
- }
- }
- Some((KeysTo::Library, events)) => {
- for edit in events.iter().filter_map(edit_of) {
- edits.push(edit);
- }
- }
- None => {}
- }
- }
+ let now = time.elapsed_secs_f64();
+ for (row, col) in clicks {
+ kb.clicked(row, col, now);
}
- // The keys went away from a library field (hide, Back): its focus too,
- // or the field would hold the keyboard and bring the keys straight back.
- if kb.take_lib_blur() {
- if let Some(mut focus) = focus {
- if focus.get().is_some() {
- focus.clear();
- }
+ for stroke in kb.take_strokes() {
+ edits.push(edit_of(stroke));
+ }
+
+ // The keys went away (hide, Back): the field's focus too, or the field
+ // would hold the keyboard and bring the keys straight back.
+ let blur = kb.take_blur();
+ let mut focused = None;
+ if let Some(mut focus) = focus {
+ if blur && focus.get().is_some() {
+ focus.clear();
}
+ focused = focus.get();
}
+ // Where the focused field stands, for the keys to get off it.
+ let field = focused.and_then(|e| {
+ let (node, transform) = fields.get(e).ok()?;
+ let k = node.inverse_scale_factor();
+ let size = node.size() * k;
+ (size.x > 0.0 && size.y > 0.0)
+ .then(|| (e, Rect::from_center_size(transform.translation * k, size)))
+ });
+ kb.set_field(field);
- let shown = kb.lib_keys().map(|(slab, keys)| Geometry { slab, keys });
+ let shown = kb.keys().map(|(slab, keys)| Geometry { slab, keys });
let face = kb.face();
+ let held = kb.held();
+ let previews: Vec<Preview> = match shown.as_ref() {
+ Some(g) => kb
+ .previews()
+ .into_iter()
+ .take(PREVIEW_SLOTS)
+ .map(|p| Preview {
+ rect: Rect::from_corners(p.rect.min - g.slab.min, p.rect.max - g.slab.min),
+ ch: p.ch,
+ })
+ .collect(),
+ None => Vec::new(),
+ };
MOUNTED.with(|m| {
let mut m = m.borrow_mut();
// Moved: drawn again where it stands now.
@@ -130,7 +136,9 @@ pub fn drive_lib_keyboard(
let live = Live {
geometry,
face: signal(face),
- taps: Rc::new(RefCell::new(Vec::new())),
+ held: signal(held),
+ previews: signal(previews),
+ clicks: Rc::new(RefCell::new(Vec::new())),
};
let p = theme::p();
crate::systems::lib_host::mount_keyed(
@@ -145,35 +153,27 @@ pub fn drive_lib_keyboard(
if live.face.get_untracked() != face {
live.face.set(face);
}
+ if live.held.peek(|now| *now != held) {
+ live.held.set(held);
+ }
+ if live.previews.peek(|now| *now != previews) {
+ live.previews.set(previews);
+ }
}
}
});
}
-/// egui's event for a key as the library's field takes it. A key's release
-/// is nothing: the press is the stroke.
-fn edit_of(event: &egui::Event) -> Option<mithril_bevy::KeyEdit> {
+/// A stroke as the library's field takes it.
+fn edit_of(stroke: Stroke) -> mithril_bevy::KeyEdit {
use mithril_bevy::KeyEdit;
- match event {
- egui::Event::Text(text) => Some(KeyEdit::Text(text.clone())),
- egui::Event::Key {
- key,
- pressed: true,
- modifiers,
- ..
- } => match key {
- egui::Key::Backspace => Some(KeyEdit::Backspace),
- egui::Key::Enter => Some(KeyEdit::Enter),
- egui::Key::ArrowLeft => Some(KeyEdit::Left {
- select: modifiers.shift,
- }),
- egui::Key::ArrowRight => Some(KeyEdit::Right {
- select: modifiers.shift,
- }),
- egui::Key::A if modifiers.command => Some(KeyEdit::SelectAll),
- _ => None,
- },
- _ => None,
+ match stroke {
+ Stroke::Text(text) => KeyEdit::Text(text),
+ Stroke::Backspace => KeyEdit::Backspace,
+ Stroke::Enter => KeyEdit::Enter,
+ Stroke::Left { select } => KeyEdit::Left { select },
+ Stroke::Right { select } => KeyEdit::Right { select },
+ Stroke::SelectAll => KeyEdit::SelectAll,
}
}
@@ -195,14 +195,15 @@ fn label(cap: Cap, shift: ShiftState, layer: KeyLayer) -> View {
let ch = if shift.alt() { alt } else { base };
ch.to_string().into_view()
}
- // The space bar is a bar, as egui's.
+ // The space bar is a bar: a word is a translation problem and a
+ // legibility problem at this size; the bar is neither.
Cap::Space => el("span")
.attr(
"style",
"display: block; width: 44%; height: 3px; border-radius: 2px; background: var(--m-text-dim)",
)
.into_view(),
- // A band across a line of text: what select-all does, as egui's.
+ // A band across a line of text: what select-all does, at any size.
Cap::SelectAll => el("span")
.attr(
"style",
@@ -230,10 +231,13 @@ fn label(cap: Cap, shift: ShiftState, layer: KeyLayer) -> View {
}
}
-/// A key's fill and ink, by role as egui's: characters raised, the
-/// modifiers back on the panel's surface, Enter in the accent, shift lit
-/// while armed and solid while locked.
-fn colours(cap: Cap, shift: ShiftState) -> (&'static str, &'static str) {
+/// A key's fill and ink, by role: characters raised, the modifiers back on
+/// the panel's surface, Enter in the accent, shift lit while armed and solid
+/// while locked; any key under a finger pressed.
+fn colours(cap: Cap, shift: ShiftState, down: bool) -> (&'static str, &'static str) {
+ if down {
+ return ("var(--m-accent-soft)", "var(--m-text)");
+ }
match cap {
Cap::Char { .. } | Cap::Space => ("var(--m-surface-raised)", "var(--m-text)"),
Cap::Enter => ("var(--m-accent)", "var(--m-on-accent)"),
@@ -243,9 +247,9 @@ fn colours(cap: Cap, shift: ShiftState) -> (&'static str, &'static str) {
}
}
-/// One key, at its rect within the slab, its face following the layer and
-/// shift.
-fn key(live: &Live, k: LibKey) -> View {
+/// One key, at its rect within the slab, its face following the layer,
+/// shift and the fingers on it.
+fn key(live: &Live, k: KeyPlace) -> View {
let origin = live.geometry.slab.min;
let place = format!(
"position: absolute; left: {:.1}px; top: {:.1}px; width: {:.1}px; height: {:.1}px; \
@@ -257,36 +261,91 @@ fn key(live: &Live, k: LibKey) -> View {
k.rect.width(),
k.rect.height(),
);
+ let (row, col) = (k.row, k.col);
let style = {
let face = live.face.clone();
+ let held = live.held.clone();
move || -> String {
let (layer, shift) = face.get();
- let (fill, ink) = cap_at(layer, k.row, k.col)
+ let down = held.get().contains(&(row, col));
+ let (fill, ink) = cap_at(layer, row, col)
.map_or(("var(--m-surface-raised)", "var(--m-text)"), |cap| {
- colours(cap, shift)
+ colours(cap, shift, down)
});
format!("{place} background: {fill}; color: {ink}")
}
};
- let face = {
+ let name = {
+ let face = live.face.clone();
+ move || -> String {
+ let (layer, shift) = face.get();
+ cap_at(layer, row, col).map_or_else(String::new, |cap| cap_name(cap, shift.alt()))
+ }
+ };
+ let glyph = {
let face = live.face.clone();
move || -> View {
let (layer, shift) = face.get();
- cap_at(layer, k.row, k.col).map_or(View::Empty, |cap| label(cap, shift, layer))
+ cap_at(layer, row, col).map_or(View::Empty, |cap| label(cap, shift, layer))
}
};
- let taps = live.taps.clone();
- let (row, col) = (k.row, k.col);
+ let clicks = live.clicks.clone();
el("button")
.attr("type", "button")
.attr("data-keep-focus", "1")
+ .attr("aria-label", name)
+ .attr("style", style)
+ .on("click", move |_| clicks.borrow_mut().push((row, col)))
+ .child(glyph)
+ .into_view()
+}
+
+/// The `slot`th key preview: a raised bubble with the character in it,
+/// hidden while fewer fingers are on character keys. Restyled in place, never
+/// rebuilt, as a finger moves.
+fn preview(live: &Live, slot: usize) -> View {
+ let style = {
+ let previews = live.previews.clone();
+ move || -> String {
+ previews.get().get(slot).map_or_else(
+ || "display: none".to_owned(),
+ |p| {
+ format!(
+ "position: absolute; left: {:.1}px; top: {:.1}px; width: {:.1}px; \
+ height: {:.1}px; display: flex; align-items: center; \
+ justify-content: center; background: var(--m-surface-raised); \
+ color: var(--m-text); border: 1px solid var(--m-border); \
+ border-radius: var(--m-radius); \
+ box-shadow: 0 4px 14px rgba(0, 0, 0, 0.47); \
+ font-size: {:.0}px; line-height: 1",
+ p.rect.min.x,
+ p.rect.min.y,
+ p.rect.width(),
+ p.rect.height(),
+ p.rect.height() * 0.55,
+ )
+ },
+ )
+ }
+ };
+ let text = {
+ let previews = live.previews.clone();
+ move || -> String {
+ previews
+ .get()
+ .get(slot)
+ .map_or_else(String::new, |p| p.ch.to_string())
+ }
+ };
+ el("div")
+ .attr("aria-hidden", "true")
.attr("style", style)
- .on("click", move |_| taps.borrow_mut().push((row, col)))
- .child(face)
+ .child(text)
.into_view()
}
-/// The slab: every key, absolute in a panel on the app's surface.
+/// The slab: every key, absolute in a panel on the app's surface, and the
+/// key previews over them.
fn keyboard(live: &Live) -> View {
let slab = live.geometry.slab;
let frame = format!(
@@ -298,13 +357,14 @@ fn keyboard(live: &Live) -> View {
slab.width(),
slab.height(),
);
- let keys: Vec<View> = live.geometry.keys.iter().map(|k| key(live, *k)).collect();
+ let mut children: Vec<View> = live.geometry.keys.iter().map(|k| key(live, *k)).collect();
+ children.extend((0..PREVIEW_SLOTS).map(|slot| preview(live, slot)));
el("div")
.attr("data-keep-focus", "1")
.attr("style", frame)
// A tap between two keys is the keyboard's, not the world's
// (`UiPointer` counts the elements that listen).
.on("click", |_| {})
- .children(keys)
+ .children(children)
.into_view()
}
diff --git a/crates/cartopolis/src/systems/gui/lib_layers.rs b/crates/cartopolis/src/systems/gui/lib_layers.rs
index b618d809..75c96d64 100644
--- a/crates/cartopolis/src/systems/gui/lib_layers.rs
+++ b/crates/cartopolis/src/systems/gui/lib_layers.rs
@@ -695,7 +695,7 @@ fn panel(l: &Live, counts: &Signal<[u64; 6]>, compact: bool) -> View {
}
};
view! {
- <div style={frame}>
+ <div style={frame} data-reserves-map="right">
<div style="display: flex; align-items: center; gap: 12px; min-height: 56px; padding: 0 12px 0 20px; border-bottom: 1px solid var(--m-border)">
<span style="color: var(--m-accent)">{icon(RightPanel::Layers.icon())}</span>
<h1 style="flex: 1; margin: 0; font-size: 19px; font-weight: 600; color: var(--m-text-strong)">"Layers"</h1>
diff --git a/crates/cartopolis/src/systems/gui/lib_midas_link.rs b/crates/cartopolis/src/systems/gui/lib_midas_link.rs
index 1d6a2091..e27ddaeb 100644
--- a/crates/cartopolis/src/systems/gui/lib_midas_link.rs
+++ b/crates/cartopolis/src/systems/gui/lib_midas_link.rs
@@ -46,7 +46,7 @@ const DISC: f32 = theme::ROUND_BUTTON_SIZE;
/// The card's and the bubble's content width, egui's figure.
const CARD_WIDTH: f32 = 230.0;
-/// egui's `overlay_frame` across: both paddings (14) and rims (1).
+/// the overlay frame egui drew across: both paddings (14) and rims (1).
const FRAME_X: f32 = 2.0 * 14.0 + 2.0;
type Acts = Rc<RefCell<Vec<LinkAct>>>;
@@ -307,7 +307,7 @@ fn disc_view(l: &Live) -> View {
// ─── The card and the bubble ─────────────────────────────────────────────────
-/// egui's `overlay_frame` in `rim`, as a style: border-box, so its width is
+/// the overlay frame egui drew in `rim`, as a style: border-box, so its width is
/// the column's.
fn frame(rim: &str, gap: f32) -> String {
format!(
diff --git a/crates/cartopolis/src/systems/gui/lib_models.rs b/crates/cartopolis/src/systems/gui/lib_models.rs
index 88ff3d61..af1b2435 100644
--- a/crates/cartopolis/src/systems/gui/lib_models.rs
+++ b/crates/cartopolis/src/systems/gui/lib_models.rs
@@ -601,7 +601,7 @@ fn panel(l: &Live) -> View {
};
let close = l.act(Act::Close);
view! {
- <div style={frame}>
+ <div style={frame} data-reserves-map="right">
<div style="display: flex; align-items: center; gap: 12px; min-height: 56px; padding: 0 12px 0 20px; border-bottom: 1px solid var(--m-border)">
<span style="color: var(--m-accent)">{icon(RightPanel::Models.icon())}</span>
<h1 style="flex: 1; margin: 0; font-size: 19px; font-weight: 600; color: var(--m-text-strong)">{RightPanel::Models.label()}</h1>
diff --git a/crates/cartopolis/src/systems/gui/lib_places.rs b/crates/cartopolis/src/systems/gui/lib_places.rs
index 12d39ef4..244a8e40 100644
--- a/crates/cartopolis/src/systems/gui/lib_places.rs
+++ b/crates/cartopolis/src/systems/gui/lib_places.rs
@@ -996,7 +996,7 @@ fn panel(l: &Live) -> View {
};
let close = l.act(Act::Close);
view! {
- <div style={frame}>
+ <div style={frame} data-reserves-map="right">
<div style="display: flex; align-items: center; gap: 12px; min-height: 56px; padding: 0 12px 0 20px; border-bottom: 1px solid var(--m-border)">
<span style="color: var(--m-accent)">{icon(RightPanel::Places.icon())}</span>
<h1 style="flex: 1; margin: 0; font-size: 19px; font-weight: 600; color: var(--m-text-strong)">"Places"</h1>
diff --git a/crates/cartopolis/src/systems/gui/lib_release_approval.rs b/crates/cartopolis/src/systems/gui/lib_release_approval.rs
index 8fa02e54..9bea6383 100644
--- a/crates/cartopolis/src/systems/gui/lib_release_approval.rs
+++ b/crates/cartopolis/src/systems/gui/lib_release_approval.rs
@@ -42,7 +42,7 @@ const KEY: &str = "release_approval";
/// Over every other library screen but the splash (1000).
const Z: i32 = 900;
-/// egui's `overlay_frame` across: both paddings (14) and rims (1).
+/// the overlay frame egui drew across: both paddings (14) and rims (1).
const FRAME_X: f32 = 2.0 * 14.0 + 2.0;
/// The window the card is centred in, px.
diff --git a/crates/cartopolis/src/systems/gui/lib_script.rs b/crates/cartopolis/src/systems/gui/lib_script.rs
index f48b987c..3dcac52d 100644
--- a/crates/cartopolis/src/systems/gui/lib_script.rs
+++ b/crates/cartopolis/src/systems/gui/lib_script.rs
@@ -535,7 +535,7 @@ fn panel(l: &Live) -> View {
};
let close = l.act(Act::Close);
view! {
- <div style={frame}>
+ <div style={frame} data-reserves-map="right">
<div style="display: flex; align-items: center; gap: 12px; min-height: 56px; padding: 0 12px 0 20px; border-bottom: 1px solid var(--m-border)">
<span style="color: var(--m-accent)">{icon(RightPanel::Script.icon())}</span>
<h1 style="flex: 1; margin: 0; font-size: 19px; font-weight: 600; color: var(--m-text-strong)">{RightPanel::Script.label()}</h1>
diff --git a/crates/cartopolis/src/systems/gui/lib_search.rs b/crates/cartopolis/src/systems/gui/lib_search.rs
index eda71fdb..402eea7e 100644
--- a/crates/cartopolis/src/systems/gui/lib_search.rs
+++ b/crates/cartopolis/src/systems/gui/lib_search.rs
@@ -530,7 +530,7 @@ fn panel(l: &Live, compact: bool, focus: bool) -> View {
let query = l.query.clone();
let close = l.act(Act::Close);
view! {
- <div style={frame}>
+ <div style={frame} data-reserves-map="right">
<div style="display: flex; align-items: center; gap: 12px; min-height: 56px; padding: 0 12px 0 20px; border-bottom: 1px solid var(--m-border)">
<span style="color: var(--m-accent)">{icon(RightPanel::Search.icon())}</span>
<h1 style="flex: 1; margin: 0; font-size: 19px; font-weight: 600; color: var(--m-text-strong)">"Search"</h1>
diff --git a/crates/cartopolis/src/systems/gui/lib_settings.rs b/crates/cartopolis/src/systems/gui/lib_settings.rs
index 61b25c51..c0e1a1c9 100644
--- a/crates/cartopolis/src/systems/gui/lib_settings.rs
+++ b/crates/cartopolis/src/systems/gui/lib_settings.rs
@@ -83,7 +83,6 @@ pub struct LibScreens {
pub scenario: bool,
pub design_room: bool,
pub admin: bool,
- pub keyboard: bool,
pub chrome: bool,
pub osd: bool,
pub pins: bool,
@@ -170,7 +169,6 @@ impl LibScreens {
scenario: all || named("scenario"),
design_room: all || named("design_room"),
admin: all || named("admin"),
- keyboard: all || named("keyboard"),
chrome: all || named("chrome"),
osd: all || named("osd"),
pins: all || named("pins"),
@@ -247,7 +245,6 @@ impl LibScreens {
scenario: named("scenario"),
design_room: named("design_room"),
admin: named("admin"),
- keyboard: named("keyboard"),
chrome: named("chrome"),
osd: named("osd"),
pins: named("pins"),
@@ -1736,7 +1733,7 @@ fn panel(l: &Live, compact: bool) -> View {
}
};
view! {
- <div style={frame}>
+ <div style={frame} data-reserves-map="right">
{header}
<div style="flex: 1; min-height: 0; overflow-y: auto; padding: 20px 20px 28px; display: flex; flex-direction: column; gap: 20px">
{body}
diff --git a/crates/cartopolis/src/systems/gui/lib_walk_guide.rs b/crates/cartopolis/src/systems/gui/lib_walk_guide.rs
index baebd4c9..1024a880 100644
--- a/crates/cartopolis/src/systems/gui/lib_walk_guide.rs
+++ b/crates/cartopolis/src/systems/gui/lib_walk_guide.rs
@@ -36,7 +36,7 @@ use crate::systems::{icons, theme};
/// The walking chrome's name in the library's host.
const KEY: &str = "walk_guide";
-/// egui's `overlay_frame`, as a style: the surface, its rim, 14 × 12 inside.
+/// the overlay frame egui drew, as a style: the surface, its rim, 14 × 12 inside.
/// Border-box, so a width below is the frame's whole width.
const FRAME: &str = "box-sizing: border-box; padding: 12px 14px; \
background: var(--m-surface); border: 1px solid var(--m-border); \
diff --git a/crates/cartopolis/src/systems/gui/mod.rs b/crates/cartopolis/src/systems/gui/mod.rs
index 3fc2efd4..8f0f881d 100644
--- a/crates/cartopolis/src/systems/gui/mod.rs
+++ b/crates/cartopolis/src/systems/gui/mod.rs
@@ -73,7 +73,7 @@ pub mod lib_chat_overlay;
pub mod lib_chrome;
#[cfg(feature = "ui-lib")]
pub mod lib_cosmos;
-#[cfg(feature = "ui-probe")]
+#[cfg(feature = "ui-lib")]
pub mod lib_cosmos_sky;
#[cfg(feature = "ui-lib")]
pub mod lib_design_room;
@@ -178,7 +178,6 @@ pub mod map_osd;
pub mod model_library;
pub mod motion;
pub mod onscreen_keyboard;
-pub mod panel_slots;
pub mod place_card;
pub mod place_names;
pub mod place_pins;
diff --git a/crates/cartopolis/src/systems/gui/motion.rs b/crates/cartopolis/src/systems/gui/motion.rs
index cf46630e..5d252f84 100644
--- a/crates/cartopolis/src/systems/gui/motion.rs
+++ b/crates/cartopolis/src/systems/gui/motion.rs
@@ -8,11 +8,8 @@
//! here. `docs/mockups/fluid-ui/` is the design; the second sheet has one
//! rule per layer.
//!
-//! Everything goes through egui's own `animate_*`, which asks for a repaint
-//! on every pass an animation is in progress and on no other, so the quiet-frame
-//! skip in `egui_manager::end_egui_frame` (`egui-quiet-frame-staleness.md`)
-//! stays exactly as useful as it was: a still UI costs nothing, a moving one
-//! redraws at the display's rate. Nothing here reads the clock itself.
+//! Nothing here reads the clock itself: a caller hands in its own elapsed
+//! time and takes the duration and the curve from here.
//!
//! **Reduced motion** (`AppPrefs::motion`, Settings ▸ General) zeroes coming
//! and going and keeps press and state: those are feedback, not decoration. It
@@ -22,9 +19,6 @@
use std::sync::atomic::{AtomicBool, Ordering};
-use egui::emath::TSTransform;
-use egui::{Context, Id, Ui};
-
/// A state change: colour and rim of on/off, hover, a tab, a label appearing,
/// the crossfade between the two spaces. Also egui's `Style::animation_time`.
pub const STATE: f32 = 0.2;
@@ -125,106 +119,6 @@ fn bezier(x1: f32, y1: f32, x2: f32, y2: f32, t: f32) -> f32 {
poly(y1, y2, s)
}
-/// How far a surface is between gone (0) and there (1), and which way it is going.
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub struct Presence {
- /// What the caller wants: shown or not.
- pub open: bool,
- /// Linear progress towards `open`, 0‥1.
- pub linear: f32,
- /// [`ease_out`] of `linear`: the opacity, and the fraction of the way in.
- pub t: f32,
-}
-
-impl Presence {
- /// Still worth drawing: open, or not yet gone. (Read by the tests only
- /// since `linger`'s cards went with egui's screens.)
- #[allow(dead_code)]
- #[must_use]
- pub fn visible(&self) -> bool {
- self.open || self.linear > 0.001
- }
-}
-
-/// The presence of a surface keyed by `id`, `enter` towards shown, `leave`
-/// towards gone ([`ENTER`] and [`LEAVE`] for a card; the keyboard answers a
-/// tap and takes [`LEAVE`] to come). A surface first seen while open starts
-/// from nothing, as egui's own `Area` fade-in does, rather than appearing
-/// settled. Both go to nothing under reduced motion.
-///
-/// A caller keeps drawing while [`Presence::visible`], and makes the surface
-/// non-interactive (`Area::interactable(pres.open)`, or `ui.disable()`) while
-/// it leaves, so a tap in the last 240 ms lands on what is underneath.
-pub fn presence_timed(ctx: &Context, id: Id, open: bool, enter: f32, leave: f32) -> Presence {
- let id = id.with("presence");
- let seen_id = id.with("seen");
- let seen =
- ctx.data_mut(|d| std::mem::replace(d.get_temp_mut_or_insert_with(seen_id, || false), true));
- if !seen && open {
- ctx.animate_bool_with_time(id, false, 0.0);
- }
- let secs = if reduced() {
- 0.0
- } else if open {
- enter
- } else {
- leave
- };
- let linear = ctx.animate_bool_with_time(id, open, secs);
- Presence {
- open,
- linear,
- t: ease_out(linear),
- }
-}
-
-/// Forget a surface's presence, so its next appearance under `id` arrives
-/// from nothing again — for a surface that is not drawn at all while away
-/// (the keyboard), whose `presence` would otherwise find it already seen.
-pub fn forget(ctx: &Context, id: Id) {
- let id = id.with("presence");
- ctx.data_mut(|d| {
- d.remove::<bool>(id.with("seen"));
- });
-}
-
-/// Apply a presence to the floating `Area` `ui` draws in: it comes up
-/// `lift` points from under its resting place and fades in, and goes the same
-/// way back. Call it first thing inside the area's closure. (Its first
-/// readers, the dock and the menu, come once session s651's redraw of both
-/// has landed; the cards use [`follow`], which is this plus the finger.)
-#[allow(dead_code)]
-pub fn enter(ui: &mut Ui, pres: Presence, lift: f32) {
- let t = pres.t.clamp(0.0, 1.0);
- ui.multiply_opacity(t);
- let layer = ui.layer_id();
- ui.ctx().set_transform_layer(
- layer,
- TSTransform::from_translation(egui::vec2(0.0, (1.0 - t) * lift)),
- );
-}
-
-/// Only the fade of a presence, for a surface that moves its paint rather
-/// than its layer (`shift_painted`).
-pub fn fade(ui: &mut Ui, pres: Presence) {
- ui.multiply_opacity(pres.t.clamp(0.0, 1.0));
-}
-
-/// Move what `layer` has painted this pass `lift` points towards where it
-/// came from, by the presence's remaining distance — the picture moves and
-/// the hit boxes do not. For a surface whose taps must land where it will
-/// rest from its first frame (the keyboard: a finger is already on its way
-/// to a key while it rises). Call it after the area has been shown.
-pub fn shift_painted(ctx: &Context, layer: egui::LayerId, pres: Presence, lift: f32) {
- let t = pres.t.clamp(0.0, 1.0);
- if t < 1.0 {
- ctx.transform_layer_shapes(
- layer,
- TSTransform::from_translation(egui::vec2(0.0, (1.0 - t) * lift)),
- );
- }
-}
-
/// A sheet's resting heights, lowest first: the title and the one action; the
/// tiles and the first facts; everything, scrolling.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
@@ -238,7 +132,6 @@ pub enum Rest {
#[cfg(test)]
mod tests {
use super::*;
- use crate::systems::egui_manager::UnpaintedPasses;
#[test]
fn the_curves_hit_their_ends_and_the_hubs_numbers() {
@@ -277,52 +170,4 @@ mod tests {
set_reduced(false);
assert_eq!(enter_time(), ENTER);
}
-
- /// Drive a context by hand: a presence first seen open starts from
- /// nothing, is in progress for [`ENTER`], and asks for repaints while it is.
- #[test]
- fn a_surface_first_seen_open_arrives_rather_than_appears() {
- let ctx = Context::default();
- let id = Id::new("card");
- let at = |time: f64, open: bool| {
- let raw = egui::RawInput {
- time: Some(time),
- ..Default::default()
- };
- ctx.begin_pass(raw);
- let pres = presence_timed(&ctx, id, open, ENTER, LEAVE);
- let out = ctx.end_pass_unpainted();
- let delay = out
- .viewport_output
- .get(&egui::ViewportId::ROOT)
- .map_or(std::time::Duration::MAX, |v| v.repaint_delay);
- (pres, delay)
- };
- set_reduced(false);
- let (first, delay) = at(0.0, true);
- assert!(first.open && first.linear < 0.5, "{first:?}");
- assert!(first.visible());
- assert!(
- delay.is_zero(),
- "an arriving surface asks to be drawn again: {delay:?}"
- );
- let (mid, _) = at(0.12, true);
- assert!(mid.linear > 0.2 && mid.linear < 0.6, "{mid:?}");
- assert!(mid.t > mid.linear, "ease-out runs ahead of linear: {mid:?}");
- let (done, _) = at(1.0, true);
- assert!(done.open && done.linear >= 1.0, "{done:?}");
- // A settled surface no longer asks to be drawn *now*. (Not `MAX`: a
- // fresh context asks for a look or two of its own in its first passes.)
- let (_, delay) = at(1.5, true);
- let (_, delay_later) = at(2.0, true);
- assert!(
- !delay.is_zero() || !delay_later.is_zero(),
- "a settled surface asks for nothing: {delay:?} / {delay_later:?}"
- );
- // Leaving: still visible for a while, then gone.
- let (leaving, _) = at(2.1, false);
- assert!(!leaving.open && leaving.visible(), "{leaving:?}");
- let (gone, _) = at(2.1 + f64::from(LEAVE) + 0.1, false);
- assert!(!gone.visible(), "{gone:?}");
- }
}
diff --git a/crates/cartopolis/src/systems/gui/onscreen_keyboard.rs b/crates/cartopolis/src/systems/gui/onscreen_keyboard.rs
index f5de6732..be2dd47f 100644
--- a/crates/cartopolis/src/systems/gui/onscreen_keyboard.rs
+++ b/crates/cartopolis/src/systems/gui/onscreen_keyboard.rs
@@ -2,77 +2,57 @@
//!
//! Android's NativeActivity brings up no soft keyboard at all (there is no Java
//! `InputMethodManager` on the other end of it — `docs/notes/android-build.md`),
-//! so every `egui::TextEdit` in the client can be *focused* on the phone and
-//! cannot be *typed into*. That is not a rough edge on a side feature: it is the
-//! address bar and the geo search, i.e. the front door of a routing client, plus
-//! bookmark rename, nearby chat and the assistant. The web build on a phone has
-//! the same problem from the other direction — the browser IME does come up, but
-//! it resizes the visual viewport out from under a WebGL canvas that winit sized
-//! from the layout viewport, and the field it is supposed to be serving ends up
-//! behind it.
+//! so every text field in the client can be *focused* on the phone and cannot be
+//! *typed into*. That is not a rough edge on a side feature: it is the address
+//! bar and the geo search, i.e. the front door of a routing client, plus bookmark
+//! rename, nearby chat and the assistant.
//!
-//! So the keys are drawn by us, and the characters are pushed into egui's own
-//! input queue as if a keyboard had produced them.
+//! This module is the keyboard's state and its input: whether the keys are up
+//! (a library text field has the focus — `UiInput::overlay_owns_keyboard`),
+//! where they stand, which fingers are on them and what they typed. The keys
+//! are drawn by the component library (`lib_keyboard`), which also hands what
+//! was typed to the focused field (`mithril_bevy::KeyEdits`) and tells this
+//! module where that field is, so the keys can get off it.
//!
-//! ## Three things about this are not obvious
+//! ## Two things about this are not obvious
//!
-//! **Tapping a key takes focus away from the field.** egui surrenders a focused
-//! widget's focus on any click that isn't on it (`SurrenderFocusOn::Clicks`, the
-//! default, evaluated inside the `TextEdit`'s own `interact`), and our keys are
-//! very much "not on it". So the field loses focus on the *first* key press, the
-//! injected character then has nowhere to go, and the keyboard — which triggers
-//! on `text_edit_focused()` — hides itself. The fix is to put focus back, in the
-//! same frame, right after the tap: [`restore_focus`]. Two consequences follow
-//! and both are load-bearing:
+//! **The keys read fingers, not clicks.** A key that typed on a click lost
+//! keystrokes in the two ways fast thumbs make most: a pointer is one finger, so
+//! a second thumb landing before the first lifted typed nothing; and a finger
+//! that drifted a few points before lifting was a drag, not a click. A phone
+//! keyboard types the key under each finger as it lifts, however it got there —
+//! so this reads Bevy's `Touches` ([`Finger`], [`OnScreenKeyboard::track`]).
+//! A click on a key with no finger behind it (the MCP server's `press`) still
+//! types ([`OnScreenKeyboard::clicked`]).
//!
-//! - **This system must run after every system that draws a text field**, or
-//! the surrender happens *after* our restore and undoes it. See the
-//! registration note in `gui::plugin`. It is also what makes `read_response` on
-//! the focused field return this frame's rect rather than nothing.
-//! - `Memory::request_focus` installs a **default** `EventFilter`, and
-//! `Focus::begin_pass` consults that filter *before* the `TextEdit` gets a
-//! chance to re-lock it. An injected `ArrowLeft` would therefore be read as
-//! "move focus left" for exactly one frame — cursor keys that eject you from
-//! the field you are editing. [`restore_focus`] re-locks the filter itself.
-//!
-//! **The events arrive one frame late, and that is the correct design.**
-//! `begin_egui_frame` assembles `RawInput` in `PreUpdate`; this system runs in
-//! `Update`, after the pass has already begun. So a tap enqueues onto
-//! [`EguiManager::inject_events`] and `begin_egui_frame` drains it into the
-//! *next* frame's events, alongside the ones the physical keyboard bridge
-//! produces and after the pointer batch — so the stream-order contract that
-//! `take_pass_events` exists to protect (`docs/notes/touch-input.md`) is
-//! untouched. It also gives the Enter key a free correctness property: the
-//! surrender-and-restore happens on the tap frame, the `Key::Enter` lands on the
-//! next one, and a single-line `TextEdit` answering it with "lose focus" is not
-//! then fought by a restore that already ran.
-//!
-//! **It lives above `Order::Foreground`, where the rest of the chrome is.** A
-//! keyboard that comes and goes cannot share an order with layers that stay:
-//! `move_to_top` is a flag read by a *stable* sort, so a layer that skips a frame
-//! sorts under everything that didn't and can never climb back. That is what made
-//! every reopened keyboard draw its keys over a sign-in backdrop that was quietly
-//! taking all the taps. [`draw`] has the mechanism.
-//!
-//! **It is an `Area`, not a root-`Ui` panel.** It draws over everything, and a
-//! panel would reserve space in a layout that has already been computed by the
-//! time we run. That also keeps it *out* of the panel `.chain()`, which is
-//! only about systems sharing the root `Ui` — `dock.rs` and `hud.rs`'s bar are
-//! the precedent, and `egui_manager`'s `every_root_ui_panel_is_in_the_chain`
-//! test keys off `ui_mut()`, which nothing here calls.
+//! **The edge is decided once per field, a few frames after it takes the
+//! focus.** The keys dock to the bottom, and flip to the top when they would
+//! cover the field being typed into. But a library screen with a field at its
+//! foot lifts above the keys by [`KeyboardInset`] — which is zero while the keys
+//! are at the top — so a flip decided every frame would see the lifted field
+//! clear, drop back, see it covered, and flip again. So the keys open at the
+//! bottom, let the screens lift for [`SETTLE_FRAMES`], then decide where the
+//! field ended up and keep that edge until the focus moves.
//!
//! ## What it does not do
//!
//! No IME, no prediction, no autocorrect, no long-press accents, no clipboard
-//! keys (Ctrl+V has no finger equivalent and paste is reachable from egui's own
-//! context menu on a long press). Nothing here is a substitute for a platform
-//! IME; it is what makes a text field usable at all on a platform that has none.
+//! keys. Nothing here is a substitute for a platform IME; it is what makes a
+//! text field usable at all on a platform that has none.
+
+// The keys' half — drawing them, reading what they typed — is `lib_keyboard`,
+// which only a `ui-probe` build has; without it the keyboard is never enabled
+// ([`platform_wants_keyboard`]) and that half's accessors have no caller.
+#![cfg_attr(not(feature = "ui-probe"), allow(dead_code))]
-use crate::systems::egui_manager::EguiMut;
+use bevy::input::mouse::MouseButtonInput;
+use bevy::input::touch::Touches;
+use bevy::input::ButtonState;
use bevy::prelude::*;
+use bevy::window::PrimaryWindow;
-use crate::systems::icons;
use crate::systems::theme;
+use crate::systems::ui_input::{UiInput, UiMetrics};
// ─── Platform predicate ───────────────────────────────────────────────────────
@@ -102,33 +82,29 @@ fn resolve_enabled(force_on: bool, override_present: bool, android: bool, web_ph
/// **Deliberately not a `cfg!` alone.** The web build runs on phones *and* on
/// desktops from the same binary, so a `cfg!(target_arch = "wasm32")` arm would
/// put a thumb keyboard under a mouse. The tier comes from [`crate::quality`],
-/// which `docs/notes/touch-input.md` is explicit about being the *one* detector
-/// in this client: it already answers "coarse pointer on a small viewport",
-/// decided by `index.html` before the module is fetched, and adding a second
-/// media query here is exactly how the UI ends up finger-sized on a machine
-/// rendering at desktop resolution.
+/// the one detector of "coarse pointer on a small viewport" in this client
+/// (`docs/notes/touch-input.md`).
///
/// Android is unconditional and does not consult the tier, because the reason
-/// there is not ergonomics but the total absence of an IME: a hypothetical
-/// Android tablet that `quality` calls `Desktop` still cannot type.
+/// there is not ergonomics but the total absence of an IME.
+///
+/// Only a build that can draw the keys has them: they are the component
+/// library's on `bevy_ui` (`ui-probe`). The DOM backend's fields are the
+/// browser's own, which bring its IME.
pub fn platform_wants_keyboard() -> bool {
- resolve_enabled(
- crate::env_flag("CARTO_OSK"),
- crate::env_value("CARTO_OSK").is_some(),
- cfg!(target_os = "android"),
- cfg!(target_arch = "wasm32") && crate::quality::is_phone(),
- )
+ cfg!(feature = "ui-probe")
+ && resolve_enabled(
+ crate::env_flag("CARTO_OSK"),
+ crate::env_value("CARTO_OSK").is_some(),
+ cfg!(target_os = "android"),
+ cfg!(target_arch = "wasm32") && crate::quality::is_phone(),
+ )
}
-/// The shortest a key may be, in egui points — Material's 48 dp minimum touch
-/// target converted through [`theme::dp_per_point`].
-///
-/// The conversion itself lives in `theme`, not here: the dock discs, the close
-/// button and the driver rail ask the same question, and this module having
-/// carried its own copy of the constant and the arithmetic is how a second
-/// answer got into the tree. What stays here is the one thing that is the
-/// keyboard's own — that a key is held to the *floor* a row is held to, because
-/// a key is pressed forty times in a row where a row is pressed once.
+/// The shortest a key may be, in UI points — Material's 48 dp minimum touch
+/// target converted through [`theme::dp_per_point`]. A key is held to the floor
+/// a row is held to, because a key is pressed forty times in a row where a row
+/// is pressed once.
fn min_key_height_pts(ui_scale: f32, display_scale: f32) -> f32 {
theme::min_touch_target_pts(theme::dp_per_point(
ui_scale,
@@ -206,8 +182,8 @@ pub enum Cap {
Shift,
/// Swap between [`KeyLayer::Letters`] and [`KeyLayer::Symbols`].
Layer,
- /// Put the keyboard away (and drop the field's focus with it — see
- /// [`OnScreenKeyboard::press`]).
+ /// Put the keyboard away, and the field's focus with it
+ /// ([`OnScreenKeyboard::take_blur`]).
Hide,
Left,
Right,
@@ -215,13 +191,30 @@ pub enum Cap {
///
/// **The one editing verb a finger cannot otherwise reach.** Selecting text
/// with a pointer is a press-drag-release across the glyphs, and on this
- /// client that gesture is already spoken for twice over: the touch bridge
- /// holds the emulated left button down for the whole gesture, and a finger
- /// held still on a field for half a second is the long-press that opens the
+ /// client a finger held still on a field is the long press that opens the
/// world context menu (`systems::touch`). So "replace what is in this field"
/// — which on an address bar or a search box is *most* of the editing anyone
- /// does — had no gesture at all, and the alternative was tapping backspace
- /// once per character.
+ /// does — had no gesture at all.
+ SelectAll,
+}
+
+/// What a key typed, for the focused field. The library's `KeyEdit` in all but
+/// name (`lib_keyboard` maps one onto the other): this module does not link
+/// the library, so it can be tested and built without it.
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub enum Stroke {
+ /// Characters, at the caret (over the selection).
+ Text(String),
+ Backspace,
+ /// The field's Enter: a newline in a textarea, a submit in a line.
+ Enter,
+ /// The caret a character left or right; `select` extends the selection.
+ Left {
+ select: bool,
+ },
+ Right {
+ select: bool,
+ },
SelectAll,
}
@@ -244,18 +237,13 @@ impl Key {
const COLUMNS: f32 = 10.0;
/// Rows: three of characters plus the action row. Kept as a constant because
-/// [`layout`] has to know the height before [`rows`] has been asked for anything
-/// — the dock edge depends on the total height, and the total height on the row
-/// count.
+/// [`layout`] has to know the height before [`rows`] has been asked for anything.
const ROW_COUNT: f32 = 4.0;
const LETTER_ROWS: [&str; 3] = ["qwertyuiop", "asdfghjkl", "zxcvbnm"];
-/// The symbol layer, as (base, alternate) pairs by position. Deliberately ASCII
-/// throughout: egui's bundled font is Ubuntu-Light plus a thin emoji subset
-/// (`systems::icons` documents how thin, and why the icons left it), and a `€`
-/// or a `¿` that renders
-/// as an empty box is worse than not offering it.
+/// The symbol layer, as (base, alternate) pairs by position. ASCII throughout,
+/// so no key can come out as an empty box in a font without it.
const SYMBOL_ROWS: [(&str, &str); 3] = [
("1234567890", "!@#$%^&*()"),
("-/:();&@\"", "_\\|[]{}~'"),
@@ -266,8 +254,7 @@ const SYMBOL_ROWS: [(&str, &str); 3] = [
///
/// **Shift is not a parameter**, and that is deliberate: a key carries both its
/// forms, so the geometry is identical in every shift state and a key can never
-/// move under a finger that is already on its way down. Shift only decides which
-/// of the two forms [`OnScreenKeyboard::press`] emits and [`paint_key`] draws.
+/// move under a finger that is already on its way down.
///
/// Row 3 is the same on both layers on purpose too: the keys that are not
/// letters — layer swap, cursor arrows, space, enter, hide — do not move when you
@@ -323,1221 +310,718 @@ fn rows(layer: KeyLayer) -> Vec<Vec<Key>> {
out
}
+/// The key at `row`, `col` on `layer` (the same slot on either layer is the
+/// same size, so the drawn keys keep their place across a layer swap).
+pub fn cap_at(layer: KeyLayer, row: usize, col: usize) -> Option<Cap> {
+ rows(layer).get(row)?.get(col).map(|k| k.cap)
+}
+
+/// A key's accessible name: the character it types, or in words what it does
+/// — the drawn keys carry no text of their own for most of them.
+pub fn cap_name(cap: Cap, alt: bool) -> String {
+ match cap {
+ Cap::Char { base, alt: shifted } => (if alt { shifted } else { base }).to_string(),
+ Cap::Space => "Space".into(),
+ Cap::Backspace => "Backspace".into(),
+ Cap::Enter => "Enter".into(),
+ Cap::Shift => "Shift".into(),
+ Cap::Layer => "123".into(),
+ Cap::Hide => "Hide the keyboard".into(),
+ Cap::Left => "Left".into(),
+ Cap::Right => "Right".into(),
+ Cap::SelectAll => "Select all".into(),
+ }
+}
+
// ─── Geometry ─────────────────────────────────────────────────────────────────
+//
+// All in UI points (the library's px), y down from the viewport's top-left.
-/// Gap between two keys, in points. Small: on a 274 pt viewport every point of
-/// gap is a point the keys do not get.
-const GAP: f32 = 3.0;
+/// Gap between two keys: the app's 6 px.
+const GAP: f32 = 6.0;
/// Padding between the slab's edge and the outermost keys.
-const PAD: f32 = 5.0;
+const PAD: f32 = 6.0;
/// Gap between the slab and the edge of the viewport it is docked to.
const EDGE_MARGIN: f32 = 6.0;
/// Ceiling on the slab, as a fraction of the viewport height. A keyboard that
/// eats more than this of a phone screen leaves nothing to type *into*; below
/// this the 48 dp key wins, above it the viewport does.
const MAX_HEIGHT_FRACTION: f32 = 0.45;
-/// Absolute floor on a key, in points. Only reachable on a viewport short enough
-/// that [`MAX_HEIGHT_FRACTION`] has already bitten; a key smaller than this is
-/// not a key.
-const MIN_KEY_HEIGHT_PTS: f32 = 18.0;
+/// Absolute floor on a key: a touch row's 40. Only reachable on a viewport
+/// short enough that [`MAX_HEIGHT_FRACTION`] has already bitten.
+const MIN_KEY_HEIGHT_PTS: f32 = 40.0;
+
+/// Which edge the keys are docked to.
+#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
+pub enum Edge {
+ #[default]
+ Bottom,
+ Top,
+}
/// Where the keyboard sits and how big its keys are.
#[derive(Clone, Copy, PartialEq, Debug)]
struct Slab {
- rect: egui::Rect,
+ rect: Rect,
key_h: f32,
/// Width of one column unit, gaps included.
unit_w: f32,
- /// The gaps it was laid out with.
- spacing: Spacing,
}
impl Slab {
/// The rect of a key `units` wide starting at column offset `col` in row
/// `row`. Each key is inset by half a [`GAP`] on every side, so the gaps
/// between neighbours come out even without the caller counting them.
- fn key_rect(&self, row: usize, col: f32, units: f32) -> egui::Rect {
- let Spacing { gap, pad, .. } = self.spacing;
- let x0 = self.rect.left() + pad + col * self.unit_w + gap * 0.5;
- let y0 = self.rect.top() + pad + row as f32 * (self.key_h + gap);
- egui::Rect::from_min_max(
- egui::pos2(x0, y0),
- egui::pos2(x0 + units * self.unit_w - gap, y0 + self.key_h),
- )
+ fn key_rect(&self, row: usize, col: f32, units: f32) -> Rect {
+ let x0 = self.rect.min.x + PAD + col * self.unit_w + GAP * 0.5;
+ let y0 = self.rect.min.y + PAD + row as f32 * (self.key_h + GAP);
+ Rect::new(x0, y0, x0 + units * self.unit_w - GAP, y0 + self.key_h)
}
}
-/// Lay the keyboard out against a viewport, given the minimum key height the
-/// touch-target rule asks for and (if known) the rect of the field being typed
-/// into.
-///
-/// **The dock edge is chosen by the field, not fixed to the bottom.** A phone
-/// panel fills the viewport, and the field can be anywhere in it; we cannot
-/// scroll the panel or shrink its layout, because by the time this runs the
-/// panel has already composed. So the one lever left is which edge to cover:
-/// bottom by default (where a keyboard belongs, and where the map is
-/// expendable), flipping to the top when the bottom slab would land on the
-/// field. If *both* edges would cover it — a field taller than the free space —
-/// bottom wins, because at least the caret is then above the keyboard rather
-/// than below it.
-///
-/// A library field passes `None` here: its screens get out of the keys' way
-/// themselves, and the flip would only put the keys over what they lifted.
-fn layout(viewport: egui::Rect, min_key_h: f32, field: Option<egui::Rect>) -> Slab {
- layout_with(viewport, min_key_h, field, Spacing::EGUI)
-}
-
-/// The gaps and the smallest key a keyboard is laid out with: egui's tight
-/// ones, or the library's calmer ones ([`Spacing::LIB`]).
-#[derive(Clone, Copy, PartialEq, Debug)]
-struct Spacing {
- gap: f32,
- pad: f32,
- min_key: f32,
-}
-
-impl Spacing {
- const EGUI: Spacing = Spacing {
- gap: GAP,
- pad: PAD,
- min_key: MIN_KEY_HEIGHT_PTS,
- };
- /// The library's keys (`lib_keyboard`): the app's 6 px gap, and never
- /// shorter than a touch row's 40.
- const LIB: Spacing = Spacing {
- gap: 6.0,
- pad: 6.0,
- min_key: 40.0,
- };
-}
-
-/// [`layout`] with the given [`Spacing`].
-fn layout_with(
- viewport: egui::Rect,
- min_key_h: f32,
- field: Option<egui::Rect>,
- spacing: Spacing,
-) -> Slab {
- let Spacing { gap, pad, min_key } = spacing;
+/// Lay the keyboard out against a viewport, docked to `edge`, given the
+/// minimum key height the touch-target rule asks for.
+fn layout(viewport: Rect, min_key_h: f32, edge: Edge) -> Slab {
let n = ROW_COUNT;
let max_h = viewport.height() * MAX_HEIGHT_FRACTION;
- let fits = ((max_h - 2.0 * pad - (n - 1.0) * gap) / n).max(min_key);
- let key_h = min_key_h.min(fits).max(min_key);
- let height = 2.0 * pad + n * key_h + (n - 1.0) * gap;
+ let fits = ((max_h - 2.0 * PAD - (n - 1.0) * GAP) / n).max(MIN_KEY_HEIGHT_PTS);
+ let key_h = min_key_h.min(fits).max(MIN_KEY_HEIGHT_PTS);
+ let height = 2.0 * PAD + n * key_h + (n - 1.0) * GAP;
let width = viewport.width();
- let unit_w = (width - 2.0 * pad) / COLUMNS;
-
- let bottom = egui::Rect::from_min_size(
- egui::pos2(viewport.left(), viewport.bottom() - EDGE_MARGIN - height),
- egui::vec2(width, height),
- );
- let top = egui::Rect::from_min_size(
- egui::pos2(viewport.left(), viewport.top() + EDGE_MARGIN),
- egui::vec2(width, height),
- );
-
- let covers = |slab: egui::Rect| field.is_some_and(|f| slab.intersects(f));
- let rect = if covers(bottom) && !covers(top) {
- top
- } else {
- bottom
- };
+ let unit_w = (width - 2.0 * PAD) / COLUMNS;
+ let top = match edge {
+ Edge::Bottom => viewport.max.y - EDGE_MARGIN - height,
+ Edge::Top => viewport.min.y + EDGE_MARGIN,
+ };
Slab {
- rect,
+ rect: Rect::new(viewport.min.x, top, viewport.min.x + width, top + height),
key_h,
unit_w,
- spacing,
}
}
+/// The edge for a field at `field`: the bottom (where a keyboard belongs, and
+/// where the map is expendable), flipping to the top when the bottom slab would
+/// cover the field. If *both* edges would cover it — a field taller than the
+/// free space — the bottom wins, because at least the caret is then above the
+/// keyboard rather than below it.
+fn choose_edge(viewport: Rect, min_key_h: f32, field: Option<Rect>) -> Edge {
+ let covers = |edge: Edge| {
+ let slab = layout(viewport, min_key_h, edge).rect;
+ field.is_some_and(|f| !slab.intersect(f).is_empty())
+ };
+ if covers(Edge::Bottom) && !covers(Edge::Top) {
+ Edge::Top
+ } else {
+ Edge::Bottom
+ }
+}
+
+/// Each key and its rect.
+fn key_rects(slab: &Slab, layer: KeyLayer) -> Vec<(usize, usize, Cap, Rect)> {
+ let mut out = Vec::new();
+ for (r, row) in rows(layer).iter().enumerate() {
+ let used: f32 = row.iter().map(|k| k.units).sum();
+ let mut col = (COLUMNS - used) * 0.5;
+ for (c, key) in row.iter().enumerate() {
+ out.push((r, c, key.cap, slab.key_rect(r, col, key.units)));
+ col += key.units;
+ }
+ }
+ out
+}
+
+/// Squared distance from `p` to `rect` (zero inside it).
+fn distance_sq(rect: Rect, p: Vec2) -> f32 {
+ let dx = (rect.min.x - p.x).max(0.0).max(p.x - rect.max.x);
+ let dy = (rect.min.y - p.y).max(0.0).max(p.y - rect.max.y);
+ dx * dx + dy * dy
+}
+
+/// The key a finger at `pos` is on: the one under it, or — in the gaps
+/// between keys, which a thumb lands in all the time — the nearest one.
+/// `None` off the slab.
+fn key_at(slab: &Slab, layer: KeyLayer, pos: Vec2) -> Option<(usize, usize, Cap, Rect)> {
+ if !slab.rect.contains(pos) {
+ return None;
+ }
+ key_rects(slab, layer)
+ .into_iter()
+ .min_by(|a, b| distance_sq(a.3, pos).total_cmp(&distance_sq(b.3, pos)))
+}
+
/// How much of the bottom edge the keys will take on this viewport — **whether
-/// or not they are currently up**.
+/// or not they are currently up** — in UI points: the slab plus its edge inset.
///
-/// For the one caller that cannot wait to be told. [`layout`] chooses its edge
-/// from where the focused field landed *this* frame, flipping to the top when
-/// the bottom slab would cover it, and there is no second chance: a floating
-/// composer that reserves nothing spends its first frame at the bottom, gets
-/// covered, and pushes the keyboard onto the top edge — over everything it was
-/// meant to leave visible — for as long as that field keeps focus. Reserving the
-/// predicted height keeps the field above the keys on the frame that decides.
-///
-/// Answers the height of the slab plus its edge inset, in points. The prediction
-/// is exact whenever the keys land at the bottom, which is the case it exists
-/// for: [`layout`] only varies the slab's *position* with the field, never its
-/// size.
+/// For the one caller that cannot wait to be told (`chat_overlay::
+/// keyboard_reserve`), which reserves the predicted height so its composer is
+/// above the keys on the frame they open.
#[must_use]
-pub fn expected_height(viewport: egui::Rect, ui_scale: f32, display_scale: f32) -> f32 {
- layout(viewport, min_key_height_pts(ui_scale, display_scale), None)
- .rect
- .height()
+pub fn expected_height_in(size: Vec2, ui_scale: f32, display_scale: f32) -> f32 {
+ layout(
+ Rect::from_corners(Vec2::ZERO, size),
+ min_key_height_pts(ui_scale, display_scale),
+ Edge::Bottom,
+ )
+ .rect
+ .height()
+ EDGE_MARGIN
}
-/// [`expected_height`] on a viewport `size` points in size, from its top-left:
-/// for callers that hold no egui rect (`chat_overlay::keyboard_reserve`).
-#[must_use]
-pub fn expected_height_in(size: bevy::math::Vec2, ui_scale: f32, display_scale: f32) -> f32 {
- expected_height(
- egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(size.x, size.y)),
- ui_scale,
- display_scale,
- )
+// ─── Fingers ──────────────────────────────────────────────────────────────────
+
+/// What happened to one finger (or the mouse) this frame, in UI points.
+#[derive(Clone, Copy, PartialEq, Debug)]
+pub struct FingerEvent {
+ pub id: u64,
+ pub phase: FingerPhase,
+ pub pos: Vec2,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum FingerPhase {
+ Start,
+ Move,
+ End,
+ Cancel,
+}
+
+/// One finger on the keys, tracked by its own touch id.
+#[derive(Clone, Copy, Debug)]
+struct Finger {
+ id: u64,
+ pos: Vec2,
+ /// When it went down, in seconds of real time.
+ down_at: f64,
+ /// When backspace last repeated under it.
+ repeated_at: Option<f64>,
+}
+
+/// The pseudo touch id for a mouse driving the keys (`CARTO_OSK` on a desktop).
+const MOUSE_FINGER: u64 = u64::MAX;
+/// Held this long, backspace starts repeating, every [`REPEAT_EVERY_S`].
+const REPEAT_AFTER_S: f64 = 0.45;
+const REPEAT_EVERY_S: f64 = 0.06;
+/// A click on a key within this long of a finger leaving the keys is that
+/// finger's, already typed; one later is a click with no finger behind it (the
+/// MCP server's `press`), which types.
+const CLICK_GRACE_S: f64 = 1.0;
+/// Frames the keys stand at the bottom before deciding their edge (module
+/// note): one for the screens to read [`KeyboardInset`] and lift, one for the
+/// layout to place them, one for `lib_keyboard` to measure the field.
+const SETTLE_FRAMES: u8 = 3;
+
+/// The character shown enlarged above a key under a finger — the phone
+/// keyboard's key preview, because the thumb is covering the key itself.
+#[derive(Clone, Copy, PartialEq, Debug)]
+pub struct Preview {
+ /// In UI points, absolute.
+ pub rect: Rect,
+ pub ch: char,
+}
+
+/// One key as drawn: its place in the rows and its rect, in UI points.
+#[derive(Clone, Copy, PartialEq, Debug)]
+pub struct KeyPlace {
+ pub row: usize,
+ pub col: usize,
+ pub rect: Rect,
}
// ─── Resource ─────────────────────────────────────────────────────────────────
/// The on-screen keyboard's whole state.
///
-/// A resource rather than a `Local` so the rest of the UI can ask whether the
-/// keyboard is up (and, eventually, get out from under it) without this system
-/// having to tell it.
+/// A resource so the rest of the UI can ask whether the keyboard is up and get
+/// out from under it ([`Self::slab`], [`KeyboardInset`]).
#[derive(Resource)]
pub struct OnScreenKeyboard {
/// Does this platform need us at all ([`platform_wants_keyboard`])? Resolved
- /// once, at construction: it cannot change during a run, and `quality`'s
- /// answer is a `OnceLock` anyway.
+ /// once, at construction: it cannot change during a run.
enabled: bool,
open: bool,
- /// The field we are typing into. Held across the frame in which egui takes
- /// focus away from it (see the module note), which is exactly why the
- /// trigger cannot just be `text_edit_focused()` read fresh every frame.
- target: Option<egui::Id>,
+ /// Put away (the hide key, Back) while its field still holds the focus:
+ /// stays down until the focus leaves, or the field's focus that is being
+ /// cleared would bring the keys straight back.
+ hidden: bool,
+ /// The focused field is to lose its focus ([`Self::take_blur`]).
+ blur: bool,
layer: KeyLayer,
shift: ShiftState,
- /// Last frame's slab, for [`Self::slab`].
+ edge: Edge,
+ /// Frames left before [`Self::edge`] is decided (module note).
+ settle: u8,
+ /// The focused field and its rect, last frame (`lib_keyboard`).
+ field: Option<(Entity, Rect)>,
+ /// This frame's slab, while the keys are up.
slab: Option<Slab>,
/// The fingers on the keys right now ([`Finger`]).
fingers: Vec<Finger>,
- /// Has this device sent a touch? Once it has, the pointer events the touch
- /// bridge synthesises for the primary finger are duplicates and are ignored.
+ /// Has this device sent a touch? Once it has, the mouse presses the touch
+ /// bridge synthesises for the primary finger are duplicates and ignored.
touch_seen: bool,
- /// The component library draws the keys (`lib_keyboard`,
- /// `CARTO_UI_LIB=keyboard`): egui's pass then only follows the focus and
- /// claims the strip ([`Self::lib_pass`]), and the keys type into an egui
- /// field or a library one, whichever holds the keyboard.
- pub lib: bool,
- /// A library text field holds the keyboard (and no egui field does).
- lib_field: bool,
- /// The hide key or Back put the keys away from a library field: its focus
- /// goes too, which only the library's system can do ([`Self::take_lib_blur`]).
- lib_blur: bool,
+ /// When a finger last left the keys ([`CLICK_GRACE_S`]).
+ finger_left_at: f64,
+ /// What the keys typed, for the focused field ([`Self::take_strokes`]).
+ strokes: Vec<Stroke>,
}
-/// How far the on-screen keyboard reaches up from the bottom edge, in egui
-/// points — which are the library's px (`lib_host::prepare_bevy` sets
-/// `UiScale` to egui's) — and 0 while it is down or docked to the top. A
+/// How far the on-screen keyboard reaches up from the bottom edge, in UI
+/// points (the library's px), and 0 while it is down or docked to the top. A
/// screen with a field at its foot (a composer) lifts by it. Written each
-/// frame by [`render_onscreen_keyboard`], whoever draws the keys.
+/// frame by [`drive_onscreen_keyboard`].
#[derive(Resource, Clone, Copy, PartialEq, Debug, Default)]
pub struct KeyboardInset(pub f32);
-/// One finger on the keys, tracked by its own touch id.
-///
-/// **Why the keys read touches rather than egui clicks.** A key used to type
-/// on `Response::clicked()`, and that lost keystrokes in the two ways fast
-/// thumbs make most: egui's pointer is one finger (`egui_manager::
-/// pointer_events` lets only the first finger down drive it), so a second thumb
-/// landing before the first lifted typed nothing; and a finger that drifted
-/// more than egui's ~6 pt click distance before lifting was a drag, not a
-/// click. A phone keyboard types the key under each finger as it lifts,
-/// however it got there — so this does.
-#[derive(Clone, Copy, Debug)]
-struct Finger {
- id: u64,
- pos: egui::Pos2,
- /// When it went down, in `InputState::time`.
- down_at: f64,
- /// When backspace last repeated under it.
- repeated_at: Option<f64>,
-}
-
-/// The pseudo touch id for a mouse driving the keys (`CARTO_OSK` on a desktop).
-const MOUSE_FINGER: u64 = u64::MAX;
-/// Held this long, backspace starts repeating, every [`REPEAT_EVERY_S`].
-const REPEAT_AFTER_S: f64 = 0.45;
-const REPEAT_EVERY_S: f64 = 0.06;
-
impl Default for OnScreenKeyboard {
fn default() -> Self {
let enabled = platform_wants_keyboard();
if enabled {
tracing::info!("on-screen keyboard enabled (no platform IME, or forced by CARTO_OSK)");
}
+ Self::new(enabled)
+ }
+}
+
+impl OnScreenKeyboard {
+ fn new(enabled: bool) -> Self {
Self {
enabled,
open: false,
- target: None,
+ hidden: false,
+ blur: false,
layer: KeyLayer::default(),
shift: ShiftState::default(),
+ edge: Edge::default(),
+ settle: 0,
+ field: None,
slab: None,
fingers: Vec::new(),
touch_seen: false,
- lib: false,
- lib_field: false,
- lib_blur: false,
+ finger_left_at: f64::NEG_INFINITY,
+ strokes: Vec::new(),
}
}
-}
-impl OnScreenKeyboard {
- /// Is the keyboard on screen right now? For an egui field, or (the
- /// library drawing the keys) a library one.
+ /// Is the keyboard on screen right now?
pub fn is_open(&self) -> bool {
- (self.open || self.lib_field) && self.enabled
+ self.open && self.enabled
}
- /// Put the keyboard away without typing anything.
+ /// Put the keyboard away without typing anything, and the field's focus
+ /// with it.
///
/// Exists for Android's Back gesture, which has to dismiss the keyboard
/// *before* it dismisses anything else — the system IME is the innermost
/// thing Back closes on every other Android app, and a keyboard you cannot
/// get rid of without submitting is worse than no keyboard.
pub fn dismiss(&mut self) {
- self.open = false;
- if self.lib_field {
- self.lib_field = false;
- self.lib_blur = true;
+ if self.open {
+ self.close();
+ self.hidden = true;
+ self.blur = true;
}
}
- // There was a `pub fn enabled()` here too — "does this platform get a keyboard
- // at all", as distinct from "is it up right now". Nothing consumed it, and
- // `[workspace.lints.rust] unused = "deny"` makes an accessor without a caller a
- // build failure rather than a warning. It comes back with the thing that wants
- // it: the natural one is a "tap to type" hint on the address bar, shown only
- // where a field is actually typeable.
-
- /// The rect the keyboard occupied on the last frame it drew — the area a
- /// caller must consider unavailable.
- pub fn slab(&self) -> Option<egui::Rect> {
- (self.open || self.lib_field)
+ fn close(&mut self) {
+ self.open = false;
+ self.slab = None;
+ self.fingers.clear();
+ }
+
+ /// The rect the keyboard occupies, in UI points — the area a caller must
+ /// consider unavailable.
+ pub fn slab(&self) -> Option<Rect> {
+ self.is_open()
.then_some(self.slab)
.flatten()
.map(|s| s.rect)
}
- /// Apply a key press, returning the egui events it produces.
- ///
- /// Pure: the whole state machine (layer, shift, open) is in here and nothing
- /// else, so it can be tested without a `Context`, a `World` or a screen.
- ///
- /// The event shapes are **not** invented here — they are the ones
- /// `egui_manager::begin_egui_frame`'s physical-keyboard bridge already
- /// produces, so a character typed on glass and a character typed on a USB
- /// keyboard are indistinguishable downstream:
- ///
- /// - a character (including space) is a bare `Event::Text`, with **no**
- /// accompanying `Event::Key`. That is not an omission: `bevy_key_to_egui`
- /// maps no letter or digit, so a physical `a` reaches egui as `Text("a")`
- /// alone, and shift is expressed by the *character* being `A` rather than
- /// by a modifier. Space is `Text(" ")` for the same reason plus one of
- /// its own — `Key::Space` is egui's "activate the focused widget", and a
- /// space bar that occasionally presses a button is a bad space bar.
- /// - Backspace, Enter and the cursor arrows are `Event::Key` only, since a
- /// real keyboard's `text` for them is a control character that the bridge
- /// filters out. Each is emitted as a **press followed by a release** in
- /// one batch: egui's `key_pressed` reads the event list, so the press
- /// registers, and the release keeps `keys_down` from accumulating a key
- /// that no finger is holding.
- fn press(&mut self, cap: Cap) -> Vec<egui::Event> {
- match cap {
- Cap::Char { base, alt } => {
- let ch = if self.shift.alt() { alt } else { base };
- self.shift = self.shift.consumed();
- vec![egui::Event::Text(ch.to_string())]
- }
- Cap::Space => vec![egui::Event::Text(" ".to_owned())],
- Cap::Backspace => key_stroke(egui::Key::Backspace),
- Cap::Enter => key_stroke(egui::Key::Enter),
- // **Shift turns the arrows into a selection**, which is the same
- // bargain a physical keyboard makes and the only one available here:
- // egui extends the selection for an arrow carrying `shift` and moves
- // the caret for one that does not (`text_selection::cursor_range`).
- //
- // Shift is deliberately *not* consumed by an arrow. It is a one-shot
- // for characters because a sentence needs exactly one capital; a
- // selection is grown one press at a time, and a shift that fell off
- // after the first character would mean re-arming it for every letter
- // of the word being selected.
- Cap::Left => key_stroke_with(egui::Key::ArrowLeft, self.selection_modifiers()),
- Cap::Right => key_stroke_with(egui::Key::ArrowRight, self.selection_modifiers()),
- // egui's own select-all chord, so this is the same code path a
- // desktop Ctrl+A takes rather than a second implementation.
- Cap::SelectAll => key_stroke_with(egui::Key::A, egui::Modifiers::COMMAND),
- Cap::Shift => {
- self.shift = self.shift.tapped();
- Vec::new()
- }
- Cap::Layer => {
- self.layer = match self.layer {
- KeyLayer::Letters => KeyLayer::Symbols,
- KeyLayer::Symbols => KeyLayer::Letters,
- };
- Vec::new()
- }
- Cap::Hide => {
- self.open = false;
- Vec::new()
- }
+ /// Where the keys stand and each key's place, while they are up.
+ pub fn keys(&self) -> Option<(Rect, Vec<KeyPlace>)> {
+ if !self.is_open() {
+ return None;
}
+ let slab = self.slab?;
+ let keys = key_rects(&slab, self.layer)
+ .into_iter()
+ .map(|(row, col, _, rect)| KeyPlace { row, col
… (cut)