git clone https://garage44.eu/jeroen/cartopolis.gitcartopolis-agent · 2026-11-26T13:08:24Z
refactor(gui): media, sign-in, the developer's tools and the leftovers off egui The fifth family. Each egui system is a plain one the library edition reads; nothing visible is lost (every screen here had a complete library edition): - Calls, the camera, the face viewfinder (drive_call_screen, publish_camera, drive_face_viewfinder); egui's per-person and camera textures go, faces keep their JPEG bytes, and network.rs no longer makes egui texture handles nothing read. - Sign-in, welcome, the app update and the splash (drive_login_screen, drive_welcome, drive_app_update, drive_boot_splash). The sign-in card still holds the game keys while it is up: LoginScreen::modal feeds UiInput, not egui's set_modal (the_open_card_owns_the_game_keys). - Developer tools, the Midas link, the MCP log and release approval (drive_dev_panel, drive_link_button, publish_mcp_activity, drive_release_approval). MCP's ui_tree and press read only the library now; egui's AccessKit path is gone, as is keep_egui_fresh. - The OSD's egui fallback (drive_map_osd builds only the library edition's layout), dismiss reads UiInput, and the theme switch drives egui's visuals from egui_manager::follow_theme_visuals. The developer panel's readouts and the call's timer rewrite their text in place: rebuilt whole while they ticked, each was blank in any frame it was rebuilt (a node is not laid out in the frame that makes it), and a capture of the call showed an empty screen. The note says so. Dead egui theme widgets go (text_touch, theme controls, header, states, the painted discs and shadows). egui:: references in the client: 636, from 5,924 when the removal began.
crates/cartopolis/src/resources.rs | 7 +-
crates/cartopolis/src/systems/dev/dev_panel.rs | 537 +----
crates/cartopolis/src/systems/dev/mcp/overlay.rs | 126 +-
crates/cartopolis/src/systems/dev/mcp/screen.rs | 967 ++------
crates/cartopolis/src/systems/dev/midas_link.rs | 386 +--
crates/cartopolis/src/systems/dev/plugin.rs | 31 +-
.../cartopolis/src/systems/dev/release_approval.rs | 268 +--
crates/cartopolis/src/systems/dev/shot_harness.rs | 54 +-
crates/cartopolis/src/systems/gui/app_update.rs | 181 +-
crates/cartopolis/src/systems/gui/call_screen.rs | 2476 +-------------------
crates/cartopolis/src/systems/gui/camera_screen.rs | 1063 ++-------
crates/cartopolis/src/systems/gui/chats.rs | 2 +-
crates/cartopolis/src/systems/gui/discs.rs | 85 +-
crates/cartopolis/src/systems/gui/dismiss.rs | 83 +-
crates/cartopolis/src/systems/gui/egui_manager.rs | 60 +-
.../src/systems/gui/egui_manager/tests.rs | 42 +-
crates/cartopolis/src/systems/gui/faces.rs | 303 +--
.../cartopolis/src/systems/gui/lib_app_update.rs | 30 +-
crates/cartopolis/src/systems/gui/lib_call.rs | 131 +-
crates/cartopolis/src/systems/gui/lib_camera.rs | 167 +-
crates/cartopolis/src/systems/gui/lib_dev_panel.rs | 173 +-
.../src/systems/gui/lib_face_viewfinder.rs | 88 +-
crates/cartopolis/src/systems/gui/lib_login.rs | 34 +-
crates/cartopolis/src/systems/gui/lib_map_osd.rs | 51 +-
.../cartopolis/src/systems/gui/lib_mcp_overlay.rs | 33 +-
.../cartopolis/src/systems/gui/lib_midas_link.rs | 23 +-
.../src/systems/gui/lib_release_approval.rs | 30 +-
crates/cartopolis/src/systems/gui/lib_splash.rs | 59 +-
crates/cartopolis/src/systems/gui/lib_welcome.rs | 21 +-
crates/cartopolis/src/systems/gui/login_screen.rs | 889 +------
crates/cartopolis/src/systems/gui/map_osd.rs | 2417 ++++++-------------
crates/cartopolis/src/systems/gui/mod.rs | 1 -
crates/cartopolis/src/systems/gui/motion.rs | 29 +-
crates/cartopolis/src/systems/gui/plugin.rs | 51 +-
crates/cartopolis/src/systems/gui/splash.rs | 248 +-
crates/cartopolis/src/systems/gui/text_touch.rs | 199 --
crates/cartopolis/src/systems/gui/theme/brand.rs | 134 +-
.../cartopolis/src/systems/gui/theme/controls.rs | 410 ----
crates/cartopolis/src/systems/gui/theme/frames.rs | 532 +----
crates/cartopolis/src/systems/gui/theme/golden.rs | 1 -
.../src/systems/gui/theme/golden_colours.txt | 1 -
crates/cartopolis/src/systems/gui/theme/header.rs | 268 ---
.../src/systems/gui/theme/map_controls.rs | 130 +-
crates/cartopolis/src/systems/gui/theme/metrics.rs | 4 -
crates/cartopolis/src/systems/gui/theme/mod.rs | 133 --
crates/cartopolis/src/systems/gui/theme/palette.rs | 34 +-
crates/cartopolis/src/systems/gui/theme/states.rs | 326 ---
crates/cartopolis/src/systems/gui/theme/tests.rs | 37 +-
crates/cartopolis/src/systems/gui/ui_input.rs | 32 +-
crates/cartopolis/src/systems/gui/ui_theme.rs | 8 +-
crates/cartopolis/src/systems/gui/welcome.rs | 103 +-
crates/cartopolis/src/systems/map/plugin.rs | 8 +-
crates/cartopolis/src/systems/mod.rs | 4 +-
crates/cartopolis/src/systems/net/network.rs | 47 +-
crates/cartopolis/src/systems/net/plugin.rs | 9 +-
crates/cartopolis/src/systems/player/avatar.rs | 2 +-
docs/notes/component-library-in-the-client.md | 9 +-
docs/notes/driving-the-client-from-an-ide.md | 2 +-
docs/notes/egui-quiet-frame-staleness.md | 15 +-
docs/notes/profile-pictures.md | 19 +-
docs/notes/touch-input.md | 4 +-
docs/notes/web-client-is-the-world.md | 2 +-
62 files changed, 2143 insertions(+), 11476 deletions(-)
diff --git a/crates/cartopolis/src/resources.rs b/crates/cartopolis/src/resources.rs
index 4991a4f5..d1466d36 100644
--- a/crates/cartopolis/src/resources.rs
+++ b/crates/cartopolis/src/resources.rs
@@ -967,7 +967,7 @@ impl<'de> serde::Deserialize<'de> for SunMode {
/// measurement: frame timing, draw counts, upload and residency, pipeline health,
/// Bevy's own diagnostics, the capture tools, and the `CARTO_*` startup switches
/// — which came back the other way, out of Settings ▸ Graphics, for the mirror of
-/// this reason. See [`crate::systems::dev_panel::render_dev_panel`].
+/// this reason. See [`crate::systems::dev_panel::drive_dev_panel`].
///
/// What this struct must *not* grow is a render setting. Those moved to
/// [`AppPrefs`] and Settings ▸ Graphics, and the reason is still live: nothing
@@ -1172,12 +1172,11 @@ pub struct MarqueeState {
pub shift_add: bool,
}
-/// Texture catalog with decoded egui handles for thumbnail display.
+/// The texture catalogue. Its thumbnails are the fetched textures themselves
+/// (`PrimTextureCache::handles`, shown by `lib_object_editor`).
#[derive(Resource, Default)]
pub struct TextureLibrary {
pub entries: Vec<TextureEntry>,
- /// Registered egui textures (same key as `entries[i].id`) for thumbnail rendering.
- pub egui_handles: HashMap<String, egui::TextureHandle>,
}
/// Client-side cache of decoded texture images, keyed by texture id.
diff --git a/crates/cartopolis/src/systems/dev/dev_panel.rs b/crates/cartopolis/src/systems/dev/dev_panel.rs
index 8ab8df36..41c68e62 100644
--- a/crates/cartopolis/src/systems/dev/dev_panel.rs
+++ b/crates/cartopolis/src/systems/dev/dev_panel.rs
@@ -45,24 +45,18 @@
//! frame, jitter, triangles by producer, upload and residency), and does not
//! need a second per-frame moving average of its own kept alive to say it.
//!
-//! **The library draws it too** (`lib_dev_panel`, `CARTO_UI_LIB=dev_panel`).
-//! The readouts are worked out once, as [`DevSection`]s both editions draw;
-//! with [`DevTools::lib`] on this system publishes [`DevTools::lib_view`] and
-//! does the library's taps through `apply`, the code egui's controls run.
+//! **The library draws it** (`lib_dev_panel`). The readouts are worked out
+//! here, as [`DevSection`]s; [`drive_dev_panel`] publishes
+//! [`DevTools::lib_view`] and does the library's taps through `apply`.
//! Midas too: `midas_link` publishes the tab as `MidasTabView` and does its
-//! taps (`MidasAct`) in `MidasLink::apply_tab`, the code egui's
-//! `midas_link::midas_tab` runs.
+//! taps (`MidasAct`) in `MidasLink::apply_tab`.
-use crate::systems::egui_manager::EguiMut;
use web_time::Instant;
use bevy::diagnostic::DiagnosticsStore;
use bevy::ecs::system::SystemParam;
use bevy::prelude::*;
-use crate::systems::icons;
-use crate::systems::theme;
-
/// Which screen of the developer panel is showing.
///
/// A resource rather than a `Local` for the same reason [`crate::systems::settings::SettingsTab`]
@@ -76,14 +70,10 @@ use crate::systems::theme;
#[derive(Resource, Default)]
pub struct DevTools {
pub tab: DevTab,
- /// The library draws the panel (`lib_dev_panel`, `CARTO_UI_LIB=dev_panel`):
- /// [`render_dev_panel`] draws nothing and publishes
- /// [`lib_view`](Self::lib_view) instead, on every tab.
- pub lib: bool,
- /// What the library's edition shows, while `lib` is on and the panel is
- /// open.
+ /// What the library's edition (`lib_dev_panel`) shows, while the panel
+ /// is open.
pub lib_view: Option<DevPanelView>,
- /// Taps on the library's edition, done by [`render_dev_panel`] next
+ /// Taps on the library's edition, done by [`drive_dev_panel`] next
/// frame (`apply`).
pub lib_acts: Vec<DevAct>,
/// When the library's readouts were last handed over (`READOUT_PERIOD_S`).
@@ -101,7 +91,7 @@ pub enum DevTone {
/// One line of a readout section.
#[derive(Clone, Debug, PartialEq)]
pub enum DevRow {
- /// `name value` ([`stat`]). A name led by two spaces is a sub-row.
+ /// `name value`. A name led by two spaces is a sub-row.
Stat {
name: String,
value: String,
@@ -109,12 +99,11 @@ pub enum DevRow {
},
/// A monospace line on its own: a failed pipeline's label.
Mono(String, DevTone),
- /// A quiet explanation (`theme::note`).
+ /// A quiet explanation.
Note(String),
}
-/// A titled run of readout rows. Both editions draw the same sections, so
-/// the numbers and their wording are worked out once.
+/// A titled run of readout rows.
#[derive(Clone, Debug, PartialEq)]
pub struct DevSection {
pub title: &'static str,
@@ -177,7 +166,7 @@ pub enum DevBody {
}
/// What the developer panel shows this frame, published by
-/// [`render_dev_panel`] for the library's edition (`lib_dev_panel`).
+/// [`drive_dev_panel`] for the library's edition (`lib_dev_panel`).
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub struct DevPanelView {
@@ -185,7 +174,7 @@ pub struct DevPanelView {
pub body: DevBody,
}
-/// A tap on the library's edition, done by [`render_dev_panel`].
+/// A tap on the library's edition, done by [`drive_dev_panel`].
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub enum DevAct {
@@ -256,14 +245,13 @@ pub fn toggle_dev_panel_shortcut(
}
}
-/// Where the window opens, clear of the top-left disc column.
-///
-/// egui's default cascade puts a window near that corner, which is where the
-/// layers disc, the compass and the locate button already are. Only a default —
-/// the window is draggable and egui remembers where it was put.
+/// Where the sheet stands, clear of the top-left disc column (the layers
+/// disc, the compass and the locate button).
+#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub(crate) const DEV_PANEL_LEFT: f32 = 160.0;
-/// The window's width, egui's default and the library's sheet.
+/// The sheet's width.
+#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub(crate) const DEV_PANEL_WIDTH: f32 = 300.0;
/// How often the draw/triangle census is re-walked while the panel is open.
@@ -320,9 +308,9 @@ pub struct DevView<'w, 's> {
interact: Res<'w, crate::systems::interact::InteractState>,
}
-/// Draw the developer panel.
-pub fn render_dev_panel(
- mut egui: EguiMut,
+/// Measure what the developer panel shows, publish it for `lib_dev_panel`
+/// and do its taps.
+pub fn drive_dev_panel(
mut dev: ResMut<crate::resources::DevPanelState>,
mut tools: ResMut<DevTools>,
mut shot: ResMut<crate::resources::ScreenshotState>,
@@ -339,7 +327,7 @@ pub fn render_dev_panel(
mut commands: Commands,
) {
// The library's taps of last frame, before anything is measured.
- if tools.lib && !tools.lib_acts.is_empty() {
+ if !tools.lib_acts.is_empty() {
let acts = std::mem::take(&mut tools.lib_acts);
let fix = view.fix();
for act in acts {
@@ -365,23 +353,17 @@ pub fn render_dev_panel(
);
}
}
+ #[cfg(target_arch = "wasm32")]
+ let _ = &mut commands;
if !dev.open {
if tools.lib_view.is_some() {
tools.lib_view = None;
}
return;
}
- // Every number in this panel changes on its own, so the window has to be
- // redrawn on its own — without this the readout only updates on the frames
- // something else caused, i.e. it measures the frames *you* caused, which is
- // the opposite of what it is for.
- egui.animating();
-
- // The census is throttled and the fix is not, but both are measured before
- // the closure so the tab bodies are pure layout — and so the fix is measured
- // once for the two things that read it (the View rows and Copy as preset),
- // which it was not: it used to be re-derived from the same query on every
- // frame the panel was open, for a value only a click consumes.
+
+ // The census is throttled and the fix is not; the fix is measured once
+ // for the two things that read it (the View rows and Copy as preset).
let tab = tools.tab;
let now = time.elapsed_secs_f64();
let counts = if tab == DevTab::Frame {
@@ -398,132 +380,54 @@ pub fn render_dev_panel(
};
let fix = view.fix();
- // The library's edition is showing: hand it what to draw, draw nothing.
- if tools.lib {
- // Frame and Profiler numbers change every frame, and a library row
- // rebuilt every frame is never laid out: the tab showed nothing. Twice
- // a second, as the census already is, unless the tab changed.
- let ticking = matches!(tab, DevTab::Frame | DevTab::Profiler);
- let same_tab = tools.lib_view.as_ref().is_some_and(|v| v.tab == tab);
- if ticking && same_tab && tools.lib_at.is_some_and(|t| now - t < READOUT_PERIOD_S) {
- return;
+ // Frame and Profiler numbers change every frame, and a library row
+ // rebuilt every frame is never laid out: the tab showed nothing. Twice a
+ // second, as the census already is, unless the tab changed.
+ let ticking = matches!(tab, DevTab::Frame | DevTab::Profiler);
+ let same_tab = tools.lib_view.as_ref().is_some_and(|v| v.tab == tab);
+ if ticking && same_tab && tools.lib_at.is_some_and(|t| now - t < READOUT_PERIOD_S) {
+ return;
+ }
+ tools.lib_at = Some(now);
+ let body = match tab {
+ DevTab::Frame => {
+ DevBody::Readouts(frame_sections(&readouts, counts, readouts.entities.count()))
}
- tools.lib_at = Some(now);
- let body = match tab {
- DevTab::Frame => {
- DevBody::Readouts(frame_sections(&readouts, counts, readouts.entities.count()))
- }
- DevTab::View => DevBody::View {
- sections: camera_sections(fix, view.interact.address.as_deref()),
- group: shot.preset_group.clone(),
- can_copy: fix.is_some(),
- copied: copied_at.is_some_and(|t| t.elapsed().as_secs_f32() < COPIED_S),
- },
- DevTab::Profiler => DevBody::Readouts(profiler_sections(&readouts.diagnostics)),
- DevTab::Switches => {
- let rows: Vec<SwitchRow> = crate::resources::DebugSwitches::SWITCHES
- .iter()
- .filter_map(|&(name, label, help)| {
- Some(SwitchRow {
- name,
- label,
- help,
- on: prefs.debug_switches.get(name)?,
- })
+ DevTab::View => DevBody::View {
+ sections: camera_sections(fix, view.interact.address.as_deref()),
+ group: shot.preset_group.clone(),
+ can_copy: fix.is_some(),
+ copied: copied_at.is_some_and(|t| t.elapsed().as_secs_f32() < COPIED_S),
+ },
+ DevTab::Profiler => DevBody::Readouts(profiler_sections(&readouts.diagnostics)),
+ DevTab::Switches => {
+ let rows: Vec<SwitchRow> = crate::resources::DebugSwitches::SWITCHES
+ .iter()
+ .filter_map(|&(name, label, help)| {
+ Some(SwitchRow {
+ name,
+ label,
+ help,
+ on: prefs.debug_switches.get(name)?,
})
- .collect();
- DevBody::Switches {
- on: rows.iter().filter(|r| r.on).count(),
- rows,
- }
- }
- DevTab::Precision => {
- DevBody::Precision(precision_view(&precision_log, &precise_hand, &high))
+ })
+ .collect();
+ DevBody::Switches {
+ on: rows.iter().filter(|r| r.on).count(),
+ rows,
}
- #[cfg(not(target_arch = "wasm32"))]
- DevTab::Midas => DevBody::Midas(midas.tab_view()),
- #[cfg(target_arch = "wasm32")]
- DevTab::Midas => DevBody::Note(MIDAS_IN_THE_APPS),
- };
- let next = DevPanelView { tab, body };
- if tools.lib_view.as_ref() != Some(&next) {
- tools.lib_view = Some(next);
}
- return;
- }
- if tools.lib_view.is_some() {
- tools.lib_view = None;
- }
-
- // Edited as a copy and written back below, so an open Switches tab does not
- // mark `AppPrefs` changed on every frame it is open — which would put the
- // preferences autosave on the frame loop. The Settings panel does exactly
- // this, for exactly this reason.
- let mut edited = *prefs;
-
- let ctx = egui.ctx_mut();
- let mut open = true;
- egui::Window::new("Developer tools")
- .open(&mut open)
- .default_width(DEV_PANEL_WIDTH)
- .default_pos([DEV_PANEL_LEFT + theme::OSD_GAP, theme::OSD_MARGIN])
- .show(ctx, |ui| {
- ui.spacing_mut().item_spacing.y = 3.0;
- ui.horizontal_wrapped(|ui| {
- for candidate in DevTab::ALL {
- ui.selectable_value(&mut tools.tab, candidate, candidate.label());
- }
- });
- ui.separator();
- // A scroll area on every tab, not only the long ones: Switches is
- // nine checkboxes each with a paragraph under it, and a window that
- // is taller than a phone has no way to reach its own bottom.
- egui::ScrollArea::vertical()
- .auto_shrink([false, true])
- .max_height(520.0)
- .show(ui, |ui| match tools.tab {
- DevTab::Frame => {
- frame_tab(ui, &readouts, counts, readouts.entities.count());
- }
- DevTab::View => {
- view_tab(
- ui,
- fix,
- view.interact.address.as_deref(),
- &dev,
- &mut shot,
- &mut copied_at,
- );
- }
- DevTab::Profiler => profiler_tab(ui, &readouts.diagnostics),
- DevTab::Switches => switches_tab(ui, &mut edited),
- DevTab::Precision => {
- precision_tab(ui, &mut precision_log, &mut precise_hand, &mut high);
- }
- #[cfg(not(target_arch = "wasm32"))]
- DevTab::Midas => {
- crate::systems::midas_link::midas_tab(
- ui,
- &mut midas,
- &precision_log,
- &mut commands,
- );
- }
- #[cfg(target_arch = "wasm32")]
- DevTab::Midas => {
- let _ = &mut commands;
- theme::note(ui, MIDAS_IN_THE_APPS);
- }
- });
- });
- if edited != *prefs {
- *prefs = edited;
- }
- // Closing via the window's [x] only writes when it actually changed, to avoid
- // marking the resource changed every frame (which would re-run the lighting
- // update).
- if !open && dev.open {
- dev.open = false;
+ DevTab::Precision => {
+ DevBody::Precision(precision_view(&precision_log, &precise_hand, &high))
+ }
+ #[cfg(not(target_arch = "wasm32"))]
+ DevTab::Midas => DevBody::Midas(midas.tab_view()),
+ #[cfg(target_arch = "wasm32")]
+ DevTab::Midas => DevBody::Note(MIDAS_IN_THE_APPS),
+ };
+ let next = DevPanelView { tab, body };
+ if tools.lib_view.as_ref() != Some(&next) {
+ tools.lib_view = Some(next);
}
}
@@ -536,17 +440,21 @@ const MIDAS_IN_THE_APPS: &str =
const COPIED_S: f32 = 1.5;
/// The shot preset's group field, explained.
+#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub(crate) const GROUP_HELP: &str = "Subject this viewpoint is for — tunnels, bridges, doors. \
Captured by `cargo shots --only <group>`, into docs/img/<group>/. \
Leave blank to add it to the published documentation set.";
/// Copy as preset, explained.
+#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub(crate) const COPY_HELP: &str = "Copies this camera as a [[shot]] block for docs/shots.toml";
/// Under the View tab.
+#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub(crate) const CLOCK_NOTE: &str = "The clock and the weather are in Settings, under World.";
/// The indoor walk test's steps, before it starts.
+#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub(crate) const WALK_STEPS: [&str; 4] = [
"1. Start outside, under open sky.",
"2. Hold the phone still, then move it a little, until it says following.",
@@ -555,26 +463,31 @@ pub(crate) const WALK_STEPS: [&str; 4] = [
];
/// Under a greyed Start.
+#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub(crate) const NEEDS_A_PHONE: &str =
"Needs a phone: its back camera, motion sensors and magnetometer.";
/// Under Start.
+#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub(crate) const WALK_NOTE: &str =
"Uses the back camera and the motion sensors. Nothing the camera sees \
is kept. While it runs, things that sense hands near you feel yours.";
/// Under "Stand-in hand".
+#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub(crate) const STAND_IN_NOTE: &str =
"Lets your avatar's hand (or the view, in fly mode) play hand-sensing \
objects such as a theremin before high precision can place your phone. \
Scripts are told it is not precise.";
/// The precision log, empty.
+#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub(crate) const LOG_EMPTY_NOTE: &str =
"Nothing yet. Start the walk test above; what the camera and sensors \
report is written here every few seconds.";
/// Over the switches, none on.
+#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub(crate) const SWITCHES_NOTE: &str =
"Each switch removes a layer, or adds an instrument. All of them are \
read once, at startup — restart the app to apply a change. An \
@@ -582,11 +495,12 @@ pub(crate) const SWITCHES_NOTE: &str =
what is set here.";
/// Over the switches, `on` of them on.
+#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub(crate) fn switches_on(on: usize) -> String {
format!("{on} on — this run's rendering is not evidence. Restart to apply a change.")
}
-/// Do a tap on the library's edition: the same code egui's controls run.
+/// Do a tap on the library's edition.
///
/// Each resource is written only when the tap changes it: `DevPanelState`'s
/// `is_changed()` re-runs the lighting, `AppPrefs`' the autosave.
@@ -721,51 +635,6 @@ fn row_toned(name: impl Into<String>, value: impl Into<String>, tone: DevTone) -
}
}
-/// Draw readout sections as egui's panel always has: a header, its rows, and
-/// 5 pt between sections.
-fn draw_sections(ui: &mut egui::Ui, sections: &[DevSection]) {
- for (i, s) in sections.iter().enumerate() {
- if i > 0 {
- ui.add_space(5.0);
- }
- theme::section(ui, s.title);
- for r in &s.rows {
- match r {
- DevRow::Stat { name, value, tone } => {
- stat_colored(ui, name, value, tone_color(*tone));
- }
- DevRow::Mono(text, tone) => {
- ui.label(
- egui::RichText::new(text)
- .monospace()
- .size(theme::SIZE_TINY)
- .color(tone_color(*tone)),
- );
- }
- DevRow::Note(text) => theme::note(ui, text),
- }
- }
- }
-}
-
-fn tone_color(tone: DevTone) -> egui::Color32 {
- match tone {
- DevTone::Value => theme::p32().cream,
- DevTone::Dim => theme::p32().text_dim,
- DevTone::Error => theme::p32().error,
- }
-}
-
-/// Frame: is it fast, and what is it drawing?
-fn frame_tab(
- ui: &mut egui::Ui,
- readouts: &DevReadouts,
- counts: crate::systems::render_census::RenderCounts,
- entity_count: usize,
-) {
- draw_sections(ui, &frame_sections(readouts, counts, entity_count));
-}
-
/// The Frame tab's readouts.
fn frame_sections(
readouts: &DevReadouts,
@@ -924,62 +793,6 @@ fn camera_sections(fix: Option<ViewFix>, address: Option<&str>) -> Vec<DevSectio
]
}
-/// View: where the camera is, and how to reproduce this shot.
-fn view_tab(
- ui: &mut egui::Ui,
- fix: Option<ViewFix>,
- address: Option<&str>,
- dev: &crate::resources::DevPanelState,
- shot: &mut crate::resources::ScreenshotState,
- copied_at: &mut Option<Instant>,
-) {
- draw_sections(ui, &camera_sections(fix, address));
-
- ui.add_space(5.0);
- theme::section(ui, "Shot presets");
- // Every remembered camera position lives in `docs/shots.toml` and is captured
- // by `cargo shots`, not by this button — but a *new* position has to be found
- // by flying to it, so this copies the current camera out as a pasteable
- // `[[shot]]` block. That is the whole handoff from "looks good here" to
- // reproducible.
- //
- // **The group is the field worth filling in.** Left empty the preset joins the
- // documentation set, which is published: `cargo shots` regenerates it and the
- // README links every file. Named — `tunnels`, `bridges`, `doors` — it becomes a
- // subject to go and look at, captured by `cargo shots --only <group>` into its
- // own directory, and it stays out of the published set. A viewpoint that
- // clearly shows a tunnel mouth is worth keeping and is not a README image.
- ui.horizontal(|ui| {
- ui.label("group");
- ui.add(
- egui::TextEdit::singleline(&mut shot.preset_group)
- .hint_text("blank = README set")
- .desired_width(120.0),
- )
- .on_hover_text(GROUP_HELP);
- });
- ui.horizontal(|ui| {
- let copied = copied_at.is_some_and(|t| t.elapsed().as_secs_f32() < COPIED_S);
- if ui
- .add_enabled(
- fix.is_some(),
- egui::Button::new(format!("{} Copy as preset", icons::COPY)),
- )
- .on_hover_text(COPY_HELP)
- .clicked()
- {
- if let Some(v) = fix {
- copy_preset(v, &shot.preset_group, dev, copied_at);
- }
- }
- if copied {
- ui.label("copied");
- }
- });
-
- theme::note(ui, CLOCK_NOTE);
-}
-
/// Profiler: Bevy's own diagnostics, live.
///
/// **The app was already registering these and reading them from nowhere.**
@@ -1008,11 +821,6 @@ fn view_tab(
/// Absent columns say what would supply them. A profiler that shows an empty
/// table is indistinguishable from a profiler that measured zero, and the whole
/// argument for `--dump-state`'s "not measured" rows applies here unchanged.
-fn profiler_tab(ui: &mut egui::Ui, store: &DiagnosticsStore) {
- draw_sections(ui, &profiler_sections(store));
-}
-
-/// The Profiler tab's readouts.
fn profiler_sections(store: &DiagnosticsStore) -> Vec<DevSection> {
use bevy::diagnostic::{EntityCountDiagnosticsPlugin, FrameTimeDiagnosticsPlugin};
use bevy::render::diagnostic::MeshAllocatorDiagnosticPlugin;
@@ -1158,160 +966,6 @@ fn profiler_sections(store: &DiagnosticsStore) -> Vec<DevSection> {
]
}
-/// Switches: the `CARTO_*` bisecting switches, on the device.
-///
-/// **They were in Settings ▸ Graphics**, collapsed and last, under a header that
-/// had to say what they were not — because they are not quality knobs: several of
-/// them make the picture worse on purpose, and a run with one on is a run whose
-/// rendering proves nothing. A section that has to apologise for the panel it is
-/// in belongs in a different panel, and this is it.
-///
-/// They are on a *device* at all for the reason [`crate::resources::DebugSwitches`]
-/// records: on Android the alternative is `debug.carto.*` properties, i.e. a
-/// cable, an `adb` and a machine that is not the phone — and the Adreno sky bug
-/// spent four days with its own instrument built and unreachable by the person
-/// holding the device.
-/// The high-precision mode's log: what its sensors reported, as text to copy
-/// off the phone and paste into a chat — and, at the top, the indoor walk test
-/// (`docs/notes/indoor-positioning.md`) started from here, so it needs no avatar,
-/// no walk mode and no hidden button: the hand button only exists on foot.
-fn precision_tab(
- ui: &mut egui::Ui,
- log: &mut crate::systems::high_precision::HighPrecisionLog,
- hand: &mut crate::systems::prim_hand::PreciseHand,
- high: &mut crate::systems::high_precision::HighPrecision,
-) {
- walk_test(ui, log, high);
- ui.separator();
- theme::checkbox(ui, &mut hand.camera_stands_in, "Stand-in hand");
- theme::note(ui, STAND_IN_NOTE);
- ui.separator();
- if log.is_empty() {
- theme::note(ui, LOG_EMPTY_NOTE);
- return;
- }
- ui.horizontal(|ui| {
- if ui.button("Copy").clicked() {
- crate::utils::clipboard::set_text(&log.text());
- }
- if ui.button("Clear").clicked() {
- log.clear();
- }
- });
- egui::ScrollArea::vertical()
- .max_height(320.0)
- .stick_to_bottom(true)
- .show(ui, |ui| {
- ui.label(
- egui::RichText::new(log.tail())
- .monospace()
- .size(theme::SIZE_CHIP),
- );
- });
-}
-
-/// The indoor walk test: Start, what the tracking needs from you right now, a
-/// Round button that marks each pass in the log, and Stop.
-fn walk_test(
- ui: &mut egui::Ui,
- log: &mut crate::systems::high_precision::HighPrecisionLog,
- high: &mut crate::systems::high_precision::HighPrecision,
-) {
- use crate::systems::high_precision::{HandWord, HighPrecision};
- theme::section(ui, "Indoor walk test");
- let Some(word) = high.hand_word() else {
- for step in WALK_STEPS {
- ui.label(step);
- }
- ui.add_space(theme::OSD_GAP);
- // Drawn on a desktop too, greyed, so a capture shows the test as a
- // phone does.
- let available = HighPrecision::available();
- ui.add_enabled_ui(available, |ui| {
- if theme::primary_button_sized(ui, "Start", 140.0).clicked() {
- high.on = true;
- }
- });
- if !available {
- theme::note(ui, NEEDS_A_PHONE);
- }
- theme::note(ui, WALK_NOTE);
- return;
- };
- let tone = match word {
- HandWord::Following => theme::p32().accent_bright,
- HandWord::CameraBusy => theme::p32().warn,
- _ => theme::p32().text_dim,
- };
- ui.label(
- egui::RichText::new(word.text())
- .size(theme::SIZE_TITLE)
- .strong()
- .color(tone),
- );
- if let Some(problem) = high.problem() {
- ui.label(egui::RichText::new(problem).color(theme::p32().warn));
- }
- if let Some((ran, readings)) = high.running_for() {
- let s = ran.as_secs();
- theme::note(
- ui,
- &format!(
- "{}:{:02} running · round {} · {readings} field readings",
- s / 60,
- s % 60,
- high.rounds()
- ),
- );
- }
- ui.add_space(theme::OSD_GAP);
- ui.horizontal(|ui| {
- let next = format!("Round {}", high.rounds() + 1);
- if theme::primary_button_sized(ui, &next, 140.0).clicked() {
- high.mark_round(log);
- }
- if theme::secondary_button(ui, "", "Stop", 100.0).clicked() {
- high.on = false;
- }
- });
-}
-
-fn switches_tab(ui: &mut egui::Ui, prefs: &mut crate::resources::AppPrefs) {
- use crate::resources::DebugSwitches;
-
- let on = DebugSwitches::SWITCHES
- .iter()
- .filter(|(name, _, _)| prefs.debug_switches.get(name) == Some(true))
- .count();
- // The count, at the top, because these are read once at startup and "why does
- // it look like that" has to be answerable without remembering that you set one
- // a week ago.
- if on == 0 {
- theme::note(ui, SWITCHES_NOTE);
- } else {
- ui.label(
- egui::RichText::new(switches_on(on))
- .small()
- .color(theme::p32().accent_text),
- );
- }
- ui.add_space(4.0);
- for (name, label, help) in DebugSwitches::SWITCHES {
- let Some(value) = prefs.debug_switches.get_mut(name) else {
- // Unreachable while the table and `get_mut` agree, and a test pins
- // that they do. Skipping beats an `unwrap` in a UI system.
- continue;
- };
- theme::checkbox(ui, value, label);
- ui.label(
- egui::RichText::new(help)
- .small()
- .color(theme::p32().text_dim),
- );
- ui.add_space(4.0);
- }
-}
-
/// A camera fix, measured once per frame and read by both the View rows and the
/// "Copy as preset" button.
#[derive(Clone, Copy)]
@@ -1349,35 +1003,6 @@ impl DevView<'_, '_> {
}
}
-/// One `name value` row of a readout, with the name in a fixed column so a stack
-/// of them lines up and the value monospaced so a changing digit does not shift
-/// the ones beside it.
-///
-/// This is the whole layout vocabulary of the developer panel, deliberately: a
-/// panel of numbers wants to be scanned down the left edge, and the moment two
-/// rows disagree about where the value starts it stops being scannable.
-///
-/// The value in a chosen colour: cream for a measurement, another for the
-/// rows that report a failure or an absence.
-fn stat_colored(ui: &mut egui::Ui, name: &str, value: &str, color: egui::Color32) {
- ui.horizontal(|ui| {
- ui.add_sized(
- [88.0, ui.spacing().interact_size.y],
- egui::Label::new(
- egui::RichText::new(name)
- .size(theme::SIZE_SUB)
- .color(theme::p32().text_dim),
- ),
- );
- ui.label(
- egui::RichText::new(value)
- .monospace()
- .size(theme::SIZE_MONO)
- .color(color),
- );
- });
-}
-
/// `1234567` → `"1 234 567"`. A thin space rather than a comma because these are
/// counts read at a glance, and six unbroken digits are the reason a triangle
/// budget is hard to eyeball.
diff --git a/crates/cartopolis/src/systems/dev/mcp/overlay.rs b/crates/cartopolis/src/systems/dev/mcp/overlay.rs
index 6b70a9ca..e0bcca48 100644
--- a/crates/cartopolis/src/systems/dev/mcp/overlay.rs
+++ b/crates/cartopolis/src/systems/dev/mcp/overlay.rs
@@ -7,12 +7,11 @@
//! here, in a box over the map, as it happens — the tool, what it was asked for,
//! and what it answered.
//!
-//! It is a readout and nothing else. No buttons, `interactable(false)`, and it
-//! stands down while a right-hand panel is open, which is the rule every other
-//! floating box here follows: egui paints `Area`s above panels even at
-//! `Order::Background`, so disappearing is the only way to be *behind* one.
+//! It is a readout and nothing else: no buttons, nothing in it listens, and
+//! it stands down while a right-hand panel is open, as every other floating
+//! box over the map does. [`publish_mcp_activity`] decides what shows and
+//! `lib_mcp_overlay` draws it.
-use crate::systems::egui_manager::EguiRef;
use bevy::prelude::*;
use super::{McpBridge, Outcome};
@@ -27,16 +26,17 @@ const LINGER_S: f64 = 12.0;
/// The box's width. Fixed, because its content is a log: lines arrive at
/// unpredictable lengths and a box that resized around each one would twitch its
-/// way across the corner.
+/// way across the corner. Read by the library's log (`lib_mcp_overlay`), which
+/// is not built on Android.
+#[cfg_attr(target_os = "android", allow(dead_code))]
pub const WIDTH: f32 = 268.0;
/// The editor's log as the component library draws it
-/// (`lib_mcp_overlay`): with `lib` on, [`render_mcp_activity`] keeps
-/// deciding what shows and publishes it in `view`, and draws nothing.
+/// (`lib_mcp_overlay`): [`publish_mcp_activity`] decides what shows and
+/// publishes it in `view`.
#[derive(Resource, Default)]
#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub struct McpActivityLib {
- pub lib: bool,
/// What shows this frame; `None` hides the box.
pub view: Option<ActivityView>,
}
@@ -57,8 +57,9 @@ pub struct ActivityView {
pub lines: Vec<(String, String, Outcome)>,
}
-pub fn render_mcp_activity(
- egui: EguiRef,
+/// Decide what the editor's box shows this frame and publish it for
+/// `lib_mcp_overlay`.
+pub fn publish_mcp_activity(
bridge: Res<McpBridge>,
right_panel: Res<crate::resources::RightPanel>,
driver: Res<crate::systems::driver::DriverState>,
@@ -66,10 +67,9 @@ pub fn render_mcp_activity(
link: Option<Res<crate::systems::midas_link::MidasLink>>,
mut lib: Option<ResMut<McpActivityLib>>,
) {
- let lib_on = lib.as_ref().is_some_and(|l| l.lib);
// Driver mode owns the screen, and the top-right corner is where its trip
- // strip goes. There is no ambient "driver mode is on" that hides an `Area`,
- // so anything new that draws over the map opts out by hand — see
+ // strip goes. There is no ambient "driver mode is on" that hides a box
+ // over the map, so anything new that draws there opts out by hand — see
// `docs/notes/map-chrome.md`, which is a list of the things that did not.
if !right_panel.is(crate::resources::RightPanel::None) || driver.active {
publish(&mut lib, None);
@@ -85,106 +85,28 @@ pub fn render_mcp_activity(
publish(&mut lib, None);
return;
}
- // A capture in flight repaints for the whole of its settle, and egui would
- // otherwise re-present the frame it tessellated when the first line landed —
- // the spinner would be a still picture of a spinner.
- if bridge.busy() {
- egui.animating();
- }
// The Midas button holds the corner while the link is up; stand under it.
let below = if link.is_some_and(|l| l.config.on && l.linked()) {
theme::ROUND_BUTTON_SIZE + theme::OSD_GAP
} else {
0.0
};
- if lib_on {
- // A finished line goes on its own after `LINGER_S`: wake for it.
- if let Some(next) = live
+ let view = ActivityView {
+ below,
+ busy: bridge.busy(),
+ listen: bridge.listen.display().to_string(),
+ lines: live
.iter()
- .filter(|e| e.outcome != Outcome::Working)
- .map(|e| e.at + LINGER_S - now)
- .min_by(f64::total_cmp)
- {
- egui.ctx()
- .request_repaint_after(std::time::Duration::from_secs_f64(next.max(0.0)));
- }
- let view = ActivityView {
- below,
- busy: bridge.busy(),
- listen: bridge.listen.display().to_string(),
- lines: live
- .iter()
- .map(|e| (e.label.clone(), e.detail.clone(), e.outcome))
- .collect(),
- };
- publish(&mut lib, Some(view));
- return;
- }
-
- egui::Area::new(egui::Id::new("mcp_activity"))
- // Top-right: the compass, the locate button and the layers disc hold the
- // top-left column, the dock and the stick hold the bottom, and this is
- // the corner nothing else draws in outside driver mode.
- .anchor(
- egui::Align2::RIGHT_TOP,
- egui::vec2(-theme::OSD_MARGIN, theme::OSD_MARGIN + below),
- )
- // A readout over the map must not sense the taps meant for the world.
- .interactable(false)
- .show(egui.ctx(), |ui| {
- theme::overlay_frame().show(ui, |ui| {
- ui.set_width(WIDTH);
- ui.horizontal(|ui| {
- if bridge.busy() {
- ui.add(
- egui::Spinner::new()
- .size(theme::SIZE_SUB)
- .color(theme::p32().accent),
- );
- }
- ui.label(
- egui::RichText::new("Editor")
- .size(theme::SIZE_CHIP)
- .color(theme::p32().cream)
- .strong(),
- );
- ui.label(
- egui::RichText::new(bridge.listen.display().to_string())
- .size(theme::SIZE_TINY)
- .color(theme::p32().text_dim),
- );
- });
- for entry in live {
- let colour = match entry.outcome {
- Outcome::Working => theme::p32().accent,
- Outcome::Done => theme::p32().text_dim,
- Outcome::Failed => theme::p32().error,
- };
- ui.horizontal_top(|ui| {
- ui.label(
- egui::RichText::new(&entry.label)
- .size(theme::SIZE_TINY)
- .color(colour)
- .monospace(),
- );
- ui.add(
- egui::Label::new(
- egui::RichText::new(&entry.detail)
- .size(theme::SIZE_TINY)
- .color(theme::p32().text_dim),
- )
- .wrap(),
- );
- });
- }
- });
- });
+ .map(|e| (e.label.clone(), e.detail.clone(), e.outcome))
+ .collect(),
+ };
+ publish(&mut lib, Some(view));
}
/// Hand the library what shows, writing the resource only when it moved.
fn publish(lib: &mut Option<ResMut<McpActivityLib>>, view: Option<ActivityView>) {
if let Some(l) = lib.as_mut() {
- if l.lib && l.view != view {
+ if l.view != view {
l.view = view;
}
}
diff --git a/crates/cartopolis/src/systems/dev/mcp/screen.rs b/crates/cartopolis/src/systems/dev/mcp/screen.rs
index 7a312099..4b911096 100644
--- a/crates/cartopolis/src/systems/dev/mcp/screen.rs
+++ b/crates/cartopolis/src/systems/dev/mcp/screen.rs
@@ -1,62 +1,35 @@
//! The two tools about the screen itself: `ui_tree` lists the controls on the
//! screen, and `press` taps one the way a finger would.
//!
-//! **While the component library draws the interface (the default), both read
-//! its tree** ([`serve_lib`], `mithril_bevy::access_tree` / `press`): roles,
-//! names and rects from the mounted nodes, a press as the picking backend's
-//! pointer events on what its point hits. The same [`Snapshot`], the same
-//! answers and the same six-digit refs, folded from the node's path key
-//! rather than an egui `Id`. What follows is egui's path, used only when egui
-//! draws (`CARTO_UI_LIB=0`).
-//!
-//! **The labels come from egui's AccessKit tree, switched on only while a call
-//! is waiting.** egui keeps no label with a widget's rect outside debug builds
-//! (`WidgetRects` has ids, rects and senses; its `WidgetInfo` store is
-//! `debug_assertions`-only and gated on a debug style flag). What does carry
-//! role, label, hint and toggle state is the AccessKit node every widget fills
-//! when `Context::enable_accesskit` is on — built in the pass, handed out in
-//! `PlatformOutput::accesskit_update`, which this client's `end_egui_frame`
-//! never reads. So nothing here touches the egui bridge: an egui `Plugin`
-//! ([`ScreenHook`]) reads the tree in its `output_hook`, right after `end_pass`,
-//! when `prev_pass.widgets` is the pass that tree describes, and joins the two by
-//! `Id`. The rects come from `WidgetRects` (clipped `interact_rect`, moved to
-//! global points by the layer's transform), not from the nodes' bounds.
-//!
-//! AccessKit state is created at `begin_pass`, so switching it on mid-frame
-//! yields a tree one pass later: a `ui_tree` is answered two frames after it
-//! arrives, and it is switched off again once the queue is empty, so an idle
-//! client pays nothing.
-//!
-//! **A press is input, not an AccessKit action.** egui does honour
-//! `ActionRequest { action: Click }`, but that skips the hit test, so it would
-//! press a button under a sheet that a finger could not reach. Instead the same
-//! hook's `input_hook` appends events to the next `RawInput`, the sequence
-//! `egui_manager::pointer_events` makes for a finger (`Touch` start, move,
-//! press; then `Touch` end, release, `PointerGone`), on a frame of its own each.
-//! On a screen egui has never seen a touch on (a desktop), the touch events are
-//! left out — one `Event::Touch` makes egui's `has_touch_screen` true for good,
-//! which turns off drag-to-select in every label — and a long press, which egui
-//! only recognises from a touch, becomes the right click that opens the same
-//! context menus (`Response::context_menu` is either).
+//! **Both read the component library's tree** ([`serve`],
+//! `mithril_bevy::access_tree` / `press`): roles, names and rects from the
+//! mounted nodes, a press as the picking backend's pointer events on what its
+//! point hits, so a control under a sheet that a finger could not reach is not
+//! pressed. Each control goes by a six-digit ref folded from the node's path
+//! key, which is stable while the node's place in the tree is.
//!
//! **Text is withheld here as it is from a picture.** A text field's contents
-//! never leave: only its hint or the label it is `labelled_by`. Plain labels are
-//! not controls and are not listed (egui makes every label selectable, so they
-//! all sense a click). A clickable row with no label of its own is named by the
-//! text inside it — and that text is left out while online with an allow-list
+//! never leave: only its label. Plain text is not a control and is not
+//! listed. A clickable row with no label of its own is named by the text
+//! inside it — and that text is left out while online with an allow-list
//! narrower than everyone, the rule `pump` applies to the chrome in a `view`,
//! because a row in the chat panel is somebody's words.
+// Built without `ui-probe` there is no tree to read: [`serve`] refuses, and
+// the answers below go unused.
+#![cfg_attr(not(feature = "ui-probe"), allow(dead_code))]
-use std::collections::{HashMap, HashSet, VecDeque};
+use std::collections::HashSet;
+#[cfg(feature = "ui-probe")]
+use std::collections::VecDeque;
use bevy::prelude::*;
-use egui::accesskit::{self, Action, Role, Toggled};
use futures_channel::oneshot;
use serde_json::{json, Value};
+#[cfg(feature = "ui-probe")]
use super::agent::Audience;
use super::{DeviceRequest, McpBridge, Outcome, Reply};
-use crate::systems::egui_manager::EguiRef;
+#[cfg(feature = "ui-probe")]
use crate::systems::session::SessionState;
use cartopolis_mcp::args::AgentReply;
use cartopolis_mcp::device::{PressArgs, UiTreeArgs};
@@ -65,8 +38,6 @@ use cartopolis_mcp::device::{PressArgs, UiTreeArgs};
/// headless client idles at two frames a second (`mcp::pace_idle`), and a press
/// is several frames.
const STAGE_TIMEOUT_S: f64 = 15.0;
-/// Held past egui's own long-press threshold (`max_click_duration`) by this much.
-const LONG_MARGIN_S: f64 = 0.2;
/// Lines of a `ui_tree` answer; the data carries every control.
const LIST_MAX: usize = 120;
/// Lines of what is on screen after a `press`.
@@ -78,22 +49,19 @@ const LABEL_MAX: usize = 80;
const NAMELESS_MAX_SHARE: f32 = 0.25;
/// Text inside a clickable row: more pieces than this and it is a container.
const ROW_TEXT_MAX: usize = 4;
-/// The finger's id. Real fingers are numbered from zero by the platform.
-const FINGER: egui::TouchId = egui::TouchId(u64::MAX - 7);
// ---------------------------------------------------------------------------
// What is on the screen
// ---------------------------------------------------------------------------
-/// One control on the screen, in global egui points (the library's logical
-/// px are the same unit: both are physical px over display scale × UI scale).
+/// One control on the screen, in the library's logical px (physical px over
+/// display scale × UI scale).
#[derive(Clone, Debug, PartialEq)]
pub struct Control {
- /// egui's `Id` value, or the library's path key (`AccessNode::key`).
- /// Stable while the widget's id path, or the node's place in the tree, is.
+ /// The library's path key (`AccessNode::key`): stable while the node's
+ /// place in the tree is.
pub id: u64,
- /// What the drawing side presses it by: egui's `Id` again, or the
- /// library's `NodeId`, which a remount changes.
+ /// What the library presses it by: its `NodeId`, which a remount changes.
pub handle: u64,
pub kind: &'static str,
/// Empty when it has none (or when it is [`Self::withheld`]).
@@ -103,55 +71,24 @@ pub struct Control {
pub enabled: bool,
/// A checkbox's tick, a selectable's selection.
pub selected: Option<bool>,
- /// A slider's or number field's value.
+ /// A slider's value.
pub value: Option<f64>,
- /// A dropdown's chosen option (the library's; egui's says none).
+ /// A dropdown's chosen option.
pub choice: Option<String>,
- pub rect: egui::Rect,
+ pub rect: Rect,
/// Where a finger lands on it: its centre, or another point of it when the
/// centre is under another layer. `None` when all of it is covered.
- pub tap: Option<egui::Pos2>,
+ pub tap: Option<Vec2>,
}
-/// Every control of one pass, in reading order.
+/// Every control on the screen, in reading order.
#[derive(Clone, Debug)]
pub struct Snapshot {
- pub screen: egui::Rect,
+ pub screen: Rect,
pub controls: Vec<Control>,
pub withheld: usize,
}
-/// The kind a role is shown as, or `None` for one that is not a control.
-fn kind_of(role: Role) -> Option<&'static str> {
- Some(match role {
- Role::Button => "button",
- Role::CheckBox => "checkbox",
- Role::Switch => "switch",
- Role::RadioButton => "radio button",
- Role::Tab => "tab",
- Role::TextInput | Role::MultilineTextInput | Role::PasswordInput => "text field",
- Role::Slider => "slider",
- Role::SpinButton => "number field",
- Role::ComboBox => "dropdown",
- Role::Link => "link",
- Role::ColorWell => "colour picker",
- Role::Image => "image",
- Role::MenuItem => "menu item",
- Role::ListBoxOption => "option",
- // A `UiBuilder::sense` scope (a whole row that is one button), or a
- // widget that never said what it is.
- Role::GenericContainer | Role::Unknown => "clickable area",
- _ => return None,
- })
-}
-
-fn is_text_field(role: Role) -> bool {
- matches!(
- role,
- Role::TextInput | Role::MultilineTextInput | Role::PasswordInput
- )
-}
-
fn has_toggle(kind: &str) -> bool {
matches!(kind, "checkbox" | "switch" | "radio button")
}
@@ -169,103 +106,6 @@ enum Name {
Nothing,
}
-fn name_of(
- node: &accesskit::Node,
- nodes: &HashMap<u64, &accesskit::Node>,
- hide_text: bool,
-) -> Name {
- // A field's `labelled_by`, a control's own label. Never a text field's
- // value — that is what somebody typed.
- let by: Vec<&str> = node
- .labelled_by()
- .iter()
- .filter_map(|id| nodes.get(&id.0))
- .filter(|n| !is_text_field(n.role()))
- .filter_map(|n| n.label().or_else(|| n.value()))
- .filter(|s| !s.trim().is_empty())
- .collect();
- if !by.is_empty() {
- return Name::Own(by.join(" "));
- }
- if is_text_field(node.role()) {
- return match node.placeholder().filter(|s| !s.trim().is_empty()) {
- Some(hint) => Name::Own(hint.to_string()),
- None => Name::Nothing,
- };
- }
- if let Some(label) = node.label().filter(|s| !s.trim().is_empty()) {
- return Name::Own(label.to_string());
- }
- match inner_text(node, nodes) {
- None => Name::Container,
- Some(text) if text.is_empty() => Name::Nothing,
- Some(_) if hide_text => Name::Withheld,
- Some(text) => Name::Inner(text.join(" ")),
- }
-}
-
-/// The plain labels inside a node, in order — or `None` when it holds another
-/// control or more text than a row's worth.
-fn inner_text<'a>(
- root: &accesskit::Node,
- nodes: &HashMap<u64, &'a accesskit::Node>,
-) -> Option<Vec<&'a str>> {
- const VISITED_MAX: usize = 64;
- let mut out = Vec::new();
- let mut stack: Vec<u64> = root.children().iter().rev().map(|c| c.0).collect();
- let mut visited = 0;
- while let Some(id) = stack.pop() {
- visited += 1;
- if visited > VISITED_MAX {
- return None;
- }
- let Some(&node) = nodes.get(&id) else {
- continue;
- };
- let role = node.role();
- if role == Role::Label {
- // Every label senses a click (they are selectable), so a label's
- // Click action says nothing; its text is the row's name.
- if let Some(text) = node.value().filter(|s| !s.trim().is_empty()) {
- out.push(text);
- if out.len() > ROW_TEXT_MAX {
- return None;
- }
- }
- continue;
- }
- if is_text_field(role)
- || node.supports_action(Action::Click)
- || node.supports_action(Action::Focus)
- {
- return None;
- }
- stack.extend(node.children().iter().rev().map(|c| c.0));
- }
- Some(out)
-}
-
-/// The first of `spots` inside `rect` where `on_top` says this control's layer
-/// is the one a finger would reach: the centre, then the middles of its four
-/// sides, then its quarters.
-fn tap_point(rect: egui::Rect, mut on_top: impl FnMut(egui::Pos2) -> bool) -> Option<egui::Pos2> {
- const SPOTS: [(f32, f32); 9] = [
- (0.5, 0.5),
- (0.25, 0.5),
- (0.75, 0.5),
- (0.5, 0.25),
- (0.5, 0.75),
- (0.25, 0.25),
- (0.75, 0.25),
- (0.25, 0.75),
- (0.75, 0.75),
- ];
- SPOTS
- .iter()
- .map(|&(x, y)| rect.lerp_inside(egui::vec2(x, y)))
- .find(|&p| on_top(p))
-}
-
/// Cut a label to [`LABEL_MAX`] characters, on one line.
fn clip(text: &str) -> String {
let flat = text.split_whitespace().collect::<Vec<_>>().join(" ");
@@ -287,83 +127,25 @@ fn reading_order(controls: &mut [Control]) {
});
}
-/// Build the snapshot of the pass that just ended, from its AccessKit tree and
-/// its widget rects. Runs in [`ScreenHook::output_hook`].
-fn snapshot(ctx: &egui::Context, update: &accesskit::TreeUpdate, hide_text: bool) -> Snapshot {
- let nodes: HashMap<u64, &accesskit::Node> =
- update.nodes.iter().map(|(id, node)| (id.0, node)).collect();
- // `end_pass` has swapped the passes, so `prev_pass` is the one just drawn.
- let widgets: Vec<(egui::LayerId, egui::WidgetRect)> =
- ctx.viewport_for(egui::ViewportId::ROOT, |v| {
- v.prev_pass
- .widgets
- .layers()
- .flat_map(|(layer, rects)| rects.iter().map(move |w| (*layer, *w)))
- .collect()
- });
- let screen = ctx.viewport_rect();
- let mut seen = HashSet::new();
- let mut out = Snapshot {
- screen,
- controls: Vec::new(),
- withheld: 0,
- };
- for (layer, w) in widgets {
- if !(w.sense.senses_click() || w.sense.is_focusable()) || !seen.insert(w.id) {
- continue;
- }
- let node = nodes.get(&w.id.value()).copied();
- let role = node.map_or(Role::Unknown, |n| n.role());
- let Some(kind) = kind_of(role) else {
- continue;
- };
- let to_global = ctx
- .layer_transform_to_global(layer)
- .unwrap_or(egui::emath::TSTransform::IDENTITY);
- let rect = (to_global * w.interact_rect).intersect(screen);
- if !rect.is_positive() {
- continue;
- }
- let name = node.map_or(Name::Nothing, |n| name_of(n, &nodes, hide_text));
- let (label, withheld) = match name {
- Name::Container => continue,
- Name::Nothing if rect.area() > NAMELESS_MAX_SHARE * screen.area() => continue,
- Name::Nothing => (String::new(), false),
- Name::Own(text) | Name::Inner(text) => (clip(&text), false),
- Name::Withheld => (String::new(), true),
- };
- out.withheld += usize::from(withheld);
- let selected = node
- .and_then(|n| n.toggled())
- .map(|t| matches!(t, Toggled::True));
- let tap = tap_point(rect, |p| match ctx.layer_id_at(p) {
- None => true,
- Some(top) => top == layer,
- });
- out.controls.push(Control {
- id: w.id.value(),
- handle: w.id.value(),
- kind,
- label,
- withheld,
- enabled: w.enabled && !node.is_some_and(|n| n.is_disabled()),
- selected,
- value: node.and_then(|n| n.numeric_value()),
- choice: None,
- rect,
- tap,
- });
- }
- drop_shadows(&mut out.controls);
- reading_order(&mut out.controls);
- out
+/// A rect with room in it: wider and taller than nothing.
+fn is_positive(r: Rect) -> bool {
+ r.width() > 0.0 && r.height() > 0.0
}
-/// Drop a nameless control lying inside a named one: the `Area` or frame a
-/// map button stands in senses the same click, and listed it twice over, once
-/// with the button's name and once as an unlabelled area at the same place.
+fn area(r: Rect) -> f32 {
+ r.width() * r.height()
+}
+
+/// `inner` lies wholly inside `outer`.
+fn contains_rect(outer: Rect, inner: Rect) -> bool {
+ outer.contains(inner.min) && outer.contains(inner.max)
+}
+
+/// Drop a nameless control lying inside a named one: the box a map button
+/// stands in senses the same click, and listed it twice over, once with the
+/// button's name and once as an unlabelled area at the same place.
fn drop_shadows(controls: &mut Vec<Control>) {
- let named: Vec<egui::Rect> = controls
+ let named: Vec<Rect> = controls
.iter()
.filter(|c| !c.label.is_empty() || c.withheld)
.map(|c| c.rect)
@@ -371,15 +153,11 @@ fn drop_shadows(controls: &mut Vec<Control>) {
controls.retain(|c| {
!c.label.is_empty()
|| c.withheld
- || !named.iter().any(|r| r.expand(1.0).contains_rect(c.rect))
+ || !named.iter().any(|r| contains_rect(r.inflate(1.0), c.rect))
});
}
-// ---------------------------------------------------------------------------
-// The library side
-// ---------------------------------------------------------------------------
-
-/// The kind a library role is shown as, egui's words for the same controls.
+/// The kind a library role is shown as.
#[cfg(feature = "ui-probe")]
fn lib_kind(role: mithril_bevy::Role) -> Option<&'static str> {
use mithril_bevy::Role as R;
@@ -400,11 +178,10 @@ fn lib_kind(role: mithril_bevy::Role) -> Option<&'static str> {
})
}
-/// What a library node is called, by the rules [`name_of`] keeps for egui's:
-/// a field by its label or placeholder and never by what is typed in it; a
-/// control by its own name; else by the text inside it — its own words
-/// when it is one piece in a button, a link, a tab or an option, somebody's
-/// words (withheld while `hide_text`) when it is a row of several.
+/// What a library node is called: a field by its label and never by what is
+/// typed in it; a control by its own name; else by the text inside it — its
+/// own words when it is one piece in a button, a link, a tab or an option,
+/// somebody's words (withheld while `hide_text`) when it is a row of several.
#[cfg(feature = "ui-probe")]
fn lib_name(n: &mithril_bevy::AccessNode, hide_text: bool) -> Name {
use mithril_bevy::Role as R;
@@ -444,11 +221,7 @@ fn lib_name(n: &mithril_bevy::AccessNode, hide_text: bool) -> Name {
/// The library's controls as a [`Snapshot`], from its walk of the mounted
/// tree (`mithril_bevy::access_tree`).
#[cfg(feature = "ui-probe")]
-fn lib_controls(
- nodes: &[mithril_bevy::AccessNode],
- screen: egui::Rect,
- hide_text: bool,
-) -> Snapshot {
+fn lib_controls(nodes: &[mithril_bevy::AccessNode], screen: Rect, hide_text: bool) -> Snapshot {
let mut out = Snapshot {
screen,
controls: Vec::new(),
@@ -459,17 +232,13 @@ fn lib_controls(
let Some(kind) = lib_kind(n.role) else {
continue;
};
- let rect = egui::Rect::from_min_max(
- egui::pos2(n.rect.min.x, n.rect.min.y),
- egui::pos2(n.rect.max.x, n.rect.max.y),
- )
- .intersect(screen);
- if !rect.is_positive() {
+ let rect = n.rect.intersect(screen);
+ if !is_positive(rect) {
continue;
}
let (label, withheld) = match lib_name(n, hide_text) {
Name::Container => continue,
- Name::Nothing if rect.area() > NAMELESS_MAX_SHARE * screen.area() => continue,
+ Name::Nothing if area(rect) > NAMELESS_MAX_SHARE * area(screen) => continue,
Name::Nothing => (String::new(), false),
Name::Own(text) | Name::Inner(text) => (clip(&text), false),
Name::Withheld => (String::new(), true),
@@ -496,10 +265,7 @@ fn lib_controls(
value,
choice,
rect,
- tap: n
- .tap
- .map(|p| egui::pos2(p.x, p.y))
- .filter(|p| screen.contains(*p)),
+ tap: n.tap.filter(|p| screen.contains(*p)),
});
}
drop_shadows(&mut out.controls);
@@ -507,14 +273,10 @@ fn lib_controls(
out
}
-/// The library's screen now, or `None` when it has no root (egui draws).
+/// The library's screen now, or `None` when it has no root.
#[cfg(feature = "ui-probe")]
fn lib_snapshot(world: &World, hide_text: bool) -> Option<Snapshot> {
let screen = mithril_bevy::screen_rect(world)?;
- let screen = egui::Rect::from_min_max(
- egui::pos2(screen.min.x, screen.min.y),
- egui::pos2(screen.max.x, screen.max.y),
- );
Some(lib_controls(
&mithril_bevy::access_tree(world),
screen,
@@ -522,92 +284,17 @@ fn lib_snapshot(world: &World, hide_text: bool) -> Option<Snapshot> {
))
}
-// ---------------------------------------------------------------------------
-// The egui side
-// ---------------------------------------------------------------------------
-
-#[derive(Clone, Copy)]
-struct Want {
- /// The first pass whose tree will do.
- from_pass: u64,
- hide_text: bool,
-}
-
-/// Sits in egui's pass: counts passes, feeds the next pass the events a press
-/// queued, and reads the AccessKit tree when one is wanted. See the module note.
-#[derive(Default)]
-struct ScreenHook {
- passes: u64,
- want: Option<Want>,
- taken: Option<Snapshot>,
- inject: Vec<egui::Event>,
-}
-
-impl egui::plugin::Plugin for ScreenHook {
- fn debug_name(&self) -> &'static str {
- "cartopolis mcp screen"
- }
-
- fn input_hook(&mut self, _ctx: &egui::Context, input: &mut egui::RawInput) {
- self.passes += 1;
- // After the frame's own events, where `inject_events` puts the on-screen
- // keyboard's — a press is a frame of its own and carries its position.
- input.events.append(&mut self.inject);
- }
-
- fn output_hook(&mut self, ctx: &egui::Context, output: &mut egui::FullOutput) {
- let Some(want) = self.want else {
- return;
- };
- if self.passes < want.from_pass {
- return;
- }
- // `None` on the pass AccessKit was switched on in: wait for the next.
- let Some(update) = output.platform_output.accesskit_update.as_ref() else {
- return;
- };
- self.taken = Some(snapshot(ctx, update, want.hide_text));
- self.want = None;
- }
-}
-
-fn with_hook<R>(ctx: &egui::Context, f: impl FnOnce(&mut ScreenHook) -> R) -> Option<R> {
- let handle = ctx.plugin_opt::<ScreenHook>()?;
- let mut hook = handle.lock();
- Some(f(&mut hook))
-}
-
-/// Ask for the tree of a pass at least `ahead` passes after the current one.
-fn ask_snapshot(ctx: &egui::Context, ahead: u64, hide_text: bool) {
- with_hook(ctx, |h| {
- h.taken = None;
- h.want = Some(Want {
- from_pass: h.passes + ahead,
- hide_text,
- });
- });
-}
-
/// How a press is made.
#[derive(Clone, Debug)]
struct Plan {
control: Control,
- at: egui::Pos2,
- /// As a finger (with `Event::Touch`), or as a mouse.
+ at: Vec2,
+ /// As a finger, or as a mouse.
touch: bool,
long: bool,
}
impl Plan {
- /// A mouse has no long press; the right button opens the same menus.
- fn button(&self) -> egui::PointerButton {
- if self.long && !self.touch {
- egui::PointerButton::Secondary
- } else {
- egui::PointerButton::Primary
- }
- }
-
fn how(&self) -> &'static str {
match (self.long, self.touch) {
(false, _) => "tapped",
@@ -617,56 +304,12 @@ impl Plan {
}
}
-fn down_events(plan: &Plan) -> Vec<egui::Event> {
- let mut out = Vec::new();
- if plan.touch {
- out.push(egui::Event::Touch {
- device_id: egui::TouchDeviceId(0),
- id: FINGER,
- phase: egui::TouchPhase::Start,
- pos: plan.at,
- force: None,
- });
- }
- // Move first: egui hit-tests the press where the pointer is.
- out.push(egui::Event::PointerMoved(plan.at));
- out.push(egui::Event::PointerButton {
- pos: plan.at,
- button: plan.button(),
- pressed: true,
- modifiers: egui::Modifiers::default(),
- });
- out
-}
-
-fn up_events(plan: &Plan) -> Vec<egui::Event> {
- let mut out = Vec::new();
- if plan.touch {
- out.push(egui::Event::Touch {
- device_id: egui::TouchDeviceId(0),
- id: FINGER,
- phase: egui::TouchPhase::End,
- pos: plan.at,
- force: None,
- });
- }
- out.push(egui::Event::PointerButton {
- pos: plan.at,
- button: plan.button(),
- pressed: false,
- modifiers: egui::Modifiers::default(),
- });
- // Or egui goes on hovering what the finger left.
- out.push(egui::Event::PointerGone);
- out
-}
-
// ---------------------------------------------------------------------------
// Finding a control
// ---------------------------------------------------------------------------
/// The short number a control goes by in `ui_tree`: six digits folded from its
-/// egui id, because a model copies 6 digits more reliably than 20. A clash is
+/// id, because a model copies 6 digits more reliably than 20. A clash is
/// caught in [`resolve`].
pub fn short_ref(id: u64) -> u64 {
((id >> 32) ^ (id & 0xFFFF_FFFF)) % 1_000_000
@@ -841,7 +484,7 @@ fn round1(v: f32) -> f64 {
(f64::from(v) * 10.0).round() / 10.0
}
-fn control_json(c: &Control, screen: egui::Rect) -> Value {
+fn control_json(c: &Control, screen: Rect) -> Value {
let at = c.rect.center();
let (w, h) = (screen.width().max(1.0), screen.height().max(1.0));
let frac = |v: f32, len: f32| (f64::from(v / len) * 1000.0).round() / 1000.0;
@@ -1012,22 +655,24 @@ enum Ask {
Press { target: Target, long: bool },
}
+/// Frames a press is given to show what it did before the screen is read
+/// again: the handler runs in the press's frame (`drive_ui`), the screen's
+/// system takes the tap in the next, the state it changes is drawn and laid
+/// out in the one after.
+#[cfg(feature = "ui-probe")]
+const SETTLE_FRAMES: u64 = 3;
+
+#[cfg(feature = "ui-probe")]
enum Stage {
- /// Not started: ask for a tree.
Look,
- /// Waiting for the tree; `after` once the press has been made.
- Asked { after: Option<(Plan, Vec<Control>)> },
- /// The finger is down.
- Held {
+ Pressed {
plan: Plan,
- /// The pass in progress when the press was queued; the next one takes it.
- down_pass: u64,
- /// egui's clock on the pass that took the press.
- pressed_at: Option<f64>,
before: Vec<Control>,
+ frame: u64,
},
}
+#[cfg(feature = "ui-probe")]
struct Job {
label: &'static str,
ask: Ask,
@@ -1041,13 +686,9 @@ struct Job {
/// is input, and two at once would be one gesture.
#[derive(Resource, Default)]
pub struct ScreenPending {
- jobs: VecDeque<Job>,
- hooked: bool,
- accesskit: bool,
- /// The calls the library answers ([`serve_lib`]).
#[cfg(feature = "ui-probe")]
- lib_jobs: VecDeque<LibJob>,
- /// Frames [`serve_lib`] has seen, for a press's settling.
+ jobs: VecDeque<Job>,
+ /// Frames [`serve`] has seen, for a press's settling.
#[cfg(feature = "ui-probe")]
frames: u64,
}
@@ -1056,64 +697,10 @@ impl ScreenPending {
/// Something here keeps the frame rate up (`mcp::pace_idle`).
pub fn is_working(&self) -> bool {
#[cfg(feature = "ui-probe")]
- if !self.lib_jobs.is_empty() {
- return true;
- }
- !self.jobs.is_empty()
- }
-}
-
-/// Answer `ui_tree` and `press`, which the pump queues in `McpBridge::screen`.
-/// Reaches egui only through [`ScreenHook`], an egui plugin it installs on the
-/// first call, so it needs [`EguiRef`] and no place in the panel chain.
-pub fn serve(
- mut bridge: ResMut<McpBridge>,
- mut pending: ResMut<ScreenPending>,
- egui: EguiRef,
- session: Res<SessionState>,
- audience: Res<Audience>,
- real: Res<Time<Real>>,
-) {
- let now = real.elapsed_secs_f64();
- let hide_text = session.is_online() && !audience.everyone;
- for (label, ask, reply) in take_asks(&mut bridge, now) {
- pending.jobs.push_back(Job {
- label,
- ask,
- reply,
- stage: Stage::Look,
- since: now,
- });
- }
-
- let ctx = egui.ctx();
- if pending.jobs.is_empty() {
- if pending.accesskit {
- ctx.disable_accesskit();
- with_hook(ctx, |h| h.want = None);
- pending.accesskit = false;
- }
- return;
- }
- if !pending.hooked {
- ctx.add_plugin(ScreenHook::default());
- pending.hooked = true;
- }
- if !pending.accesskit {
- ctx.enable_accesskit();
- pending.accesskit = true;
- }
- let Some(job) = pending.jobs.front_mut() else {
- return;
- };
- if let Some(answered) = step(job, ctx, now, hide_text) {
- if let Some(job) = pending.jobs.pop_front() {
- answer(&mut bridge, job.label, job.reply, answered, now);
- }
- // The next call's clock starts now, not when it was queued.
- if let Some(next) = pending.jobs.front_mut() {
- next.since = now;
- }
+ let working = !self.jobs.is_empty();
+ #[cfg(not(feature = "ui-probe"))]
+ let working = false;
+ working
}
}
@@ -1153,70 +740,38 @@ fn take_asks(bridge: &mut McpBridge, now: f64) -> Vec<(&'static str, Ask, onesho
out
}
-/// Frames a library press is given to show what it did before the screen is
-/// read again: the handler runs in the press's frame (`drive_ui`), the
-/// screen's system takes the tap in the next, the state it changes is drawn
-/// and laid out in the one after.
-#[cfg(feature = "ui-probe")]
-const LIB_SETTLE_FRAMES: u64 = 3;
-
-#[cfg(feature = "ui-probe")]
-enum LibStage {
- Look,
- Pressed {
- plan: Plan,
- before: Vec<Control>,
- frame: u64,
- },
-}
-
-#[cfg(feature = "ui-probe")]
-struct LibJob {
- label: &'static str,
- ask: Ask,
- reply: oneshot::Sender<Reply>,
- stage: LibStage,
- since: f64,
-}
-
-/// Answer `ui_tree` and `press` from the component library's tree while the
-/// library draws the interface (it has a root: `CARTO_UI_LIB` is not `0`),
-/// before [`serve`] would take them to egui. Exclusive, on the main thread,
-/// because the library's host is thread-local and a press triggers pointer
-/// events in the world.
+/// Answer `ui_tree` and `press`, which the pump queues in `McpBridge::screen`,
+/// from the component library's tree. Exclusive, on the main thread, because
+/// the library's host is thread-local and a press triggers pointer events in
+/// the world.
///
-/// Unlike egui's, the library's tree is always there to read: a `ui_tree` is
-/// answered in the frame it arrives. A press triggers the pointer's down, up
-/// and click on what its point hits (`mithril_bevy::press`), so a covered
-/// control is not reached; the screen is read again [`LIB_SETTLE_FRAMES`]
-/// later. A screen drawn by egui beside the library (`CARTO_UI_LIB=<list>`)
-/// is not listed.
+/// The library's tree is always there to read: a `ui_tree` is answered in the
+/// frame it arrives. A press triggers the pointer's down, up and click on what
+/// its point hits (`mithril_bevy::press`), so a covered control is not
+/// reached; the screen is read again [`SETTLE_FRAMES`] later.
#[cfg(feature = "ui-probe")]
-pub fn serve_lib(world: &mut World) {
+pub fn serve(world: &mut World) {
let now = world.resource::<Time<Real>>().elapsed_secs_f64();
let hide_text =
world.resource::<SessionState>().is_online() && !world.resource::<Audience>().everyone;
- let lib_draws = mithril_bevy::screen_rect(world).is_some();
world.resource_scope(|world, mut pending: Mut<ScreenPending>| {
pending.frames += 1;
- if lib_draws {
- let asks = take_asks(&mut world.resource_mut::<McpBridge>(), now);
- for (label, ask, reply) in asks {
- pending.lib_jobs.push_back(LibJob {
- label,
- ask,
- reply,
- stage: LibStage::Look,
- since: now,
- });
- }
+ let asks = take_asks(&mut world.resource_mut::<McpBridge>(), now);
+ for (label, ask, reply) in asks {
+ pending.jobs.push_back(Job {
+ label,
+ ask,
+ reply,
+ stage: Stage::Look,
+ since: now,
+ });
}
let frame = pending.frames;
- let Some(job) = pending.lib_jobs.front_mut() else {
+ let Some(job) = pending.jobs.front_mut() else {
return;
};
- if let Some(answered) = step_lib(world, job, now, frame, hide_text) {
- if let Some(job) = pending.lib_jobs.pop_front() {
+ if let Some(answered) = step(world, job, now, frame, hide_text) {
+ if let Some(job) = pending.jobs.pop_front() {
answer(
&mut world.resource_mut::<McpBridge>(),
job.label,
@@ -1225,18 +780,37 @@ pub fn serve_lib(world: &mut World) {
now,
);
}
- if let Some(next) = pending.lib_jobs.front_mut() {
+ // The next call's clock starts now, not when it was queued.
+ if let Some(next) = pending.jobs.front_mut() {
next.since = now;
}
}
});
}
-/// Move one library call on; its answer once it has one.
+/// Built without the component library's bevy_ui backend there is no tree
+/// to read: every call is refused at once.
+#[cfg(not(feature = "ui-probe"))]
+pub fn serve(mut bridge: ResMut<McpBridge>, real: Res<Time<Real>>) {
+ let now = real.elapsed_secs_f64();
+ for (label, _, reply) in take_asks(&mut bridge, now) {
+ answer(
+ &mut bridge,
+ label,
+ reply,
+ AgentReply::refuse(
+ "This build has no interface the screen tools can read (built without `ui-probe`).",
+ ),
+ now,
+ );
+ }
+}
+
+/// Move one call on; its answer once it has one.
#[cfg(feature = "ui-probe")]
-fn step_lib(
+fn step(
world: &mut World,
- job: &mut LibJob,
+ job: &mut Job,
now: f64,
frame: u64,
hide_text: bool,
@@ -1247,9 +821,9 @@ fn step_lib(
read; the app may be in the background."
)));
}
- match std::mem::replace(&mut job.stage, LibStage::Look) {
- LibStage::Look => {
- // No root: the library stopped drawing; wait, as egui's waits.
+ match std::mem::replace(&mut job.stage, Stage::Look) {
+ Stage::Look => {
+ // No root: the library is not drawing yet; wait.
let snap = lib_snapshot(world, hide_text)?;
let (target, long) = match &job.ask {
Ask::Tree { contains } => return Some(tree_reply(&snap, contains.as_deref())),
@@ -1278,7 +852,7 @@ fn step_lib(
)));
};
let node = mithril_bevy::NodeId(control.handle);
- match mithril_bevy::press(world, node, Vec2::new(at.x, at.y)) {
+ match mithril_bevy::press(world, node, at) {
Ok(()) => {}
Err(mithril_bevy::PressError::Gone) => {
return Some(AgentReply::refuse(format!(
@@ -1292,7 +866,7 @@ fn step_lib(
)))
}
}
- job.stage = LibStage::Pressed {
+ job.stage = Stage::Pressed {
plan: Plan {
control,
at,
@@ -1305,18 +879,18 @@ fn step_lib(
job.since = now;
None
}
- LibStage::Pressed {
+ Stage::Pressed {
plan,
before,
frame: pressed,
} => {
- let snap = (frame >= pressed + LIB_SETTLE_FRAMES)
+ let snap = (frame >= pressed + SETTLE_FRAMES)
.then(|| lib_snapshot(world, hide_text))
.flatten();
match snap {
Some(snap) => Some(after_reply(&plan, &before, &snap)),
None => {
- job.stage = LibStage::Pressed {
+ job.stage = Stage::Pressed {
plan,
before,
frame: pressed,
@@ -1345,126 +919,9 @@ fn answer(
let _ = reply.send(Reply::Agent(Box::new(body)));
}
-/// Move one call on by what this frame allows; its answer once it has one.
-fn step(job: &mut Job, ctx: &egui::Context, now: f64, hide_text: bool) -> Option<AgentReply> {
- let stage = std::mem::replace(&mut job.stage, Stage::Look);
- if now - job.since > STAGE_TIMEOUT_S {
- // Never leave a finger on the glass.
- if let Stage::Held { plan, .. } = &stage {
- with_hook(ctx, |h| h.inject.extend(up_events(plan)));
- }
- return Some(AgentReply::refuse(format!(
- "The screen drew no new frame for {STAGE_TIMEOUT_S:.0} s, so there is nothing to \
- read; the app may be in the background."
- )));
- }
- match stage {
- Stage::Look => {
- // AccessKit was off for the pass in progress, so the next one.
- ask_snapshot(ctx, 1, hide_text);
- job.stage = Stage::Asked { after: None };
- job.since = now;
- None
- }
- Stage::Asked { after } => {
- let Some(snap) = with_hook(ctx, |h| h.taken.take()).flatten() else {
- job.stage = Stage::Asked { after };
- return None;
- };
- match (&job.ask, after) {
- (Ask::Tree { contains }, _) => Some(tree_reply(&snap, contains.as_deref())),
- (Ask::Press { .. }, Some((plan, before))) => {
- Some(after_reply(&plan, &before, &snap))
- }
- (Ask::Press { target, long }, None) => {
- let control = match resolve(&snap.controls, target) {
- Ok(c) => c.clone(),
- Err(why) => return Some(AgentReply::refuse(why)),
- };
- let name = mention(&control);
- if !control.enabled {
- return Some(AgentReply::refuse(format!(
- "{name} is disabled: pressing it would do nothing."
- )));
- }
- let Some(at) = control.tap else {
- return Some(AgentReply::refuse(format!(
- "{name} is covered by another window or sheet everywhere a finger \
- could land; close that first."
- )));
- };
- // A phone may not have been touched yet this run.
- let touch = cfg!(target_os = "android") || ctx.input(|i| i.has_touch_screen());
- let plan = Plan {
- control,
- at,
- touch,
- long: *long,
- };
- let down_pass = with_hook(ctx, |h| {
- h.inject.extend(down_events(&plan));
- h.passes
- })
- .unwrap_or_default();
- job.stage = Stage::Held {
- plan,
- down_pass,
- pressed_at: None,
- before: snap.controls,
- };
- job.since = now;
- None
- }
- }
- }
- Stage::Held {
- plan,
- down_pass,
- pressed_at,
- before,
- } => {
- // No hook means no pass has been counted: wait, finger and all.
- let passes = with_hook(ctx, |h| h.passes).unwrap_or_default();
- if passes <= down_pass {
- job.stage = Stage::Held {
- plan,
- down_pass,
- pressed_at,
- before,
- };
- return None;
- }
- let time = ctx.input(|i| i.time);
- let pressed = pressed_at.unwrap_or(time);
- if plan.long && plan.touch {
- let hold = ctx.options(|o| o.input_options.max_click_duration) + LONG_MARGIN_S;
- if time - pressed < hold {
- job.stage = Stage::Held {
- plan,
- down_pass,
- pressed_at: Some(pressed),
- before,
- };
- return None;
- }
- }
- // The release goes into the next pass, the UI answers it in that
- // pass or the one after, and the tree is read from that one.
- with_hook(ctx, |h| h.inject.extend(up_events(&plan)));
- ask_snapshot(ctx, 2, hide_text);
- job.stage = Stage::Asked {
- after: Some((plan, before)),
- };
- job.since = now;
- None
- }
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
- use crate::systems::egui_manager::UnpaintedPasses as _;
fn control(id: u64, kind: &'static str, label: &str) -> Control {
Control {
@@ -1477,11 +934,8 @@ mod tests {
selected: None,
value: None,
choice: None,
- rect: egui::Rect::from_min_size(
- egui::pos2(10.0, 10.0 * id as f32),
- egui::vec2(80.0, 24.0),
- ),
- tap: Some(egui::pos2(50.0, 10.0 * id as f32 + 12.0)),
+ rect: Rect::new(10.0, 10.0 * id as f32, 90.0, 10.0 * id as f32 + 24.0),
+ tap: Some(Vec2::new(50.0, 10.0 * id as f32 + 12.0)),
}
}
@@ -1587,15 +1041,6 @@ mod tests {
assert_eq!(clip("two\nlines"), "two lines");
}
- #[test]
- fn a_covered_centre_taps_elsewhere_or_nowhere() {
- let rect = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(100.0, 20.0));
- assert_eq!(tap_point(rect, |_| true), Some(egui::pos2(50.0, 10.0)));
- let left = tap_point(rect, |p| p.x < 40.0).unwrap();
- assert!(left.x < 40.0);
- assert_eq!(tap_point(rect, |_| false), None);
- }
-
#[test]
fn what_appeared_is_counted_once() {
let before = vec![control(1, "button", "Menu")];
@@ -1608,147 +1053,6 @@ mod tests {
assert!(appeared(&after, &before, 10).is_empty());
}
- #[test]
- fn a_long_press_without_touch_is_a_right_click() {
- let plan = |touch, long| Plan {
- control: control(1, "button", "A"),
- at: egui::pos2(5.0, 5.0),
- touch,
- long,
- };
- assert_eq!(plan(false, true).button(), egui::PointerButton::Secondary);
- assert_eq!(plan(true, true).button(), egui::PointerButton::Primary);
- let down = down_events(&plan(false, false));
- assert!(!down.iter().any(|e| matches!(e, egui::Event::Touch { .. })));
- let up = up_events(&plan(true, false));
- assert!(matches!(
- up.first(),
- Some(egui::Event::Touch {
- phase: egui::TouchPhase::End,
- ..
- })
- ));
- assert!(matches!(up.last(), Some(egui::Event::PointerGone)));
- }
-
- // --- Through a real egui context -------------------------------------
-
- struct Panel {
- on: bool,
- text: String,
- clicks: u32,
- long_touches: u32,
- }
-
- fn draw(ui: &mut egui::Ui, p: &mut Panel) {
- let r = ui.button("Open settings");
- if r.clicked() {
- p.clicks += 1;
- }
- if r.long_touched() {
- p.long_touches += 1;
- }
- crate::systems::theme::checkbox(ui, &mut p.on, "Show buildings");
- ui.add(egui::TextEdit::singleline(&mut p.text).hint_text("Message"));
- }
-
- fn pass(ctx: &egui::Context, time: f64, p: &mut Panel) {
- let raw = egui::RawInput {
- screen_rect: Some(egui::Rect::from_min_size(
- egui::Pos2::ZERO,
- egui::vec2(800.0, 600.0),
- )),
- time: Some(time),
- ..Default::default()
- };
- let _ = ctx.run_ui_unpainted(raw, |ui| draw(ui, p));
- }
-
- fn hooked() -> (egui::Context, Panel) {
- let ctx = egui::Context::default();
- ctx.add_plugin(ScreenHook::default());
- ctx.enable_accesskit();
- let panel = Panel {
- on: false,
- text: "meet me at the station".into(),
- clicks: 0,
- long_touches: 0,
- };
- (ctx, panel)
- }
-
- fn look(ctx: &egui::Context, p: &mut Panel, time: f64) -> Snapshot {
- ask_snapshot(ctx, 1, false);
- pass(ctx, time, p);
- with_hook(ctx, |h| h.taken.take())
- .flatten()
- .expect("a snapshot")
- }
-
- #[test]
- fn the_tree_names_controls_and_not_what_was_typed() {
- let (ctx, mut p) = hooked();
- pass(&ctx, 0.0, &mut p);
- let snap = look(&ctx, &mut p, 0.1);
- let find = |label: &str| snap.controls.iter().find(|c| c.label == label);
- assert_eq!(find("Open settings").map(|c| c.kind), Some("button"));
- let tick = find("Show buildings").expect("checkbox");
- assert_eq!((tick.kind, tick.selected), ("checkbox", Some(false)));
- assert_eq!(find("Message").map(|c| c.kind), Some("text field"));
- let all = format!("{:?}", tree_reply(&snap, None).data);
- assert!(!all.contains("station"), "{all}");
- assert!(!snap.controls.iter().any(|c| c.label.contains("station")));
- }
-
- #[test]
- fn a_press_clicks_the_control_under_it() {
- for touch in [false, true] {
- let (ctx, mut p) = hooked();
- pass(&ctx, 0.0, &mut p);
- let snap = look(&ctx, &mut p, 0.1);
- let button = resolve(&snap.controls, &Target::Label("open settings".into()))
- .unwrap()
- .clone();
- let plan = Plan {
- at: button.tap.unwrap(),
- control: button,
- touch,
- long: false,
- };
- with_hook(&ctx, |h| h.inject.extend(down_events(&plan)));
- pass(&ctx, 0.2, &mut p);
- with_hook(&ctx, |h| h.inject.extend(up_events(&plan)));
- pass(&ctx, 0.3, &mut p);
- assert_eq!(p.clicks, 1, "touch: {touch}");
- }
- }
-
- #[test]
- fn a_held_finger_is_a_long_touch() {
- let (ctx, mut p) = hooked();
- pass(&ctx, 0.0, &mut p);
- let snap = look(&ctx, &mut p, 0.1);
- let button = resolve(&snap.controls, &Target::Label("Open settings".into()))
- .unwrap()
- .clone();
- let plan = Plan {
- at: button.tap.unwrap(),
- control: button,
- touch: true,
- long: true,
- };
- with_hook(&ctx, |h| h.inject.extend(down_events(&plan)));
- let hold = ctx.options(|o| o.input_options.max_click_duration) + LONG_MARGIN_S;
- let mut t = 0.2;
- while t < 0.2 + hold + 0.1 {
- pass(&ctx, t, &mut p);
- t += 0.1;
- }
- with_hook(&ctx, |h| h.inject.extend(up_events(&plan)));
- pass(&ctx, t, &mut p);
- assert_eq!(p.long_touches, 1);
- }
-
// --- Through the component library's tree ----------------------------
/// A library screen mounted in a world of its own, laid out in rows
@@ -1793,7 +1097,7 @@ mod tests {
let walk = &snap.controls[2];
assert_eq!((walk.rect.width(), walk.rect.height()), (100.0, 16.0));
assert_eq!(walk.tap, Some(walk.rect.center()));
- // The ref scheme is egui's: six digits folded from the id.
+ // Six digits folded from the id.
let r = reply.data["controls"][2]["ref"].as_u64().unwrap();
assert_eq!(r, short_ref(walk.id));
assert_eq!(
@@ -1833,12 +1137,7 @@ mod tests {
.unwrap()
.clone();
let at = save.tap.unwrap();
- mithril_bevy::press(
- &mut world,
- mithril_bevy::NodeId(save.handle),
- Vec2::new(at.x, at.y),
- )
- .unwrap();
+ mithril_bevy::press(&mut world, mithril_bevy::NodeId(save.handle), at).unwrap();
mithril_bevy::drive_ui(&mut world);
assert_eq!(saves.get(), 1);
let delete = resolve(&snap.controls, &Target::Label("delete".into())).unwrap();
diff --git a/crates/cartopolis/src/systems/dev/midas_link.rs b/crates/cartopolis/src/systems/dev/midas_link.rs
index 994f0882..42b1f101 100644
--- a/crates/cartopolis/src/systems/dev/midas_link.rs
+++ b/crates/cartopolis/src/systems/dev/midas_link.rs
@@ -39,7 +39,6 @@ use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use crate::systems::high_precision::{HighPrecision, HighPrecisionLog, Recording};
-use crate::systems::theme;
/// The hub this workspace runs, as a phone reaches it.
pub const DEFAULT_HUB: &str = "midas.cartopolis.org";
@@ -223,8 +222,6 @@ impl Sense {
pub struct Told {
pub session: String,
pub text: String,
- /// When it was told, so the map repaints for a new one.
- pub at: web_time::Instant,
/// When it goes on its own; `None` keeps it until tapped or replaced.
pub until: Option<web_time::Instant>,
}
@@ -245,7 +242,6 @@ impl Told {
Some(Self {
session: call.session.clone(),
text,
- at: now,
until,
})
}
@@ -281,11 +277,9 @@ pub struct MidasLink {
/// What a session asked to tell the person (`tell`), shown beside the
/// button until it is tapped away, replaced, or its time is up.
pub told: Option<Told>,
- /// The component library draws the button, the card and the bubble
- /// (`lib_midas_link`): [`draw_link_button`] keeps deciding and draws
- /// nothing.
- pub lib: bool,
- /// What the library draws, published each frame; `None` hides it all.
+ /// The button, the card and the bubble as the component library draws
+ /// them (`lib_midas_link`), published each frame by
+ /// [`drive_link_button`]; `None` hides it all.
pub lib_view: Option<LinkView>,
/// The library's taps, done next frame by [`MidasLink::apply`].
pub lib_acts: Vec<LinkAct>,
@@ -294,7 +288,7 @@ pub struct MidasLink {
jobs: Option<McpJobs>,
}
-/// A tap on the Midas button, its card or the bubble, from either edition.
+/// A tap on the Midas button, its card or the bubble.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LinkAct {
/// The button: opens the card, or closes it.
@@ -309,9 +303,9 @@ pub enum LinkAct {
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub struct LinkView {
- /// The button's right edge in from the window's, egui points.
+ /// The button's right edge in from the window's, ui points.
pub right: f32,
- /// Its top edge, egui points.
+ /// Its top edge, ui points.
pub top: f32,
/// A call just came in: the glow's strength, 1 fading to 0.
pub glow: Option<f32>,
@@ -337,7 +331,7 @@ pub struct ToldView {
pub text: String,
}
-/// A tap in Developer tools ▸ Midas, from either edition, done by
+/// A tap in Developer tools ▸ Midas, done by
/// [`MidasLink::apply_tab`]. The library's fields keep their own words, so
/// the acts that use them carry them.
#[derive(Clone, Debug, PartialEq)]
@@ -419,7 +413,6 @@ impl Default for MidasLink {
push_shot: None,
card_open: false,
told: None,
- lib: false,
lib_view: None,
lib_acts: Vec::new(),
#[cfg(mcp)]
@@ -429,7 +422,7 @@ impl Default for MidasLink {
}
impl MidasLink {
- /// A tap on the button, the card or the bubble: what both editions do.
+ /// A tap on the button, the card or the bubble.
pub fn apply(&mut self, a: LinkAct) {
match a {
LinkAct::Toggle => self.card_open = !self.card_open,
@@ -438,7 +431,7 @@ impl MidasLink {
}
}
- /// A tap in Developer tools ▸ Midas: what both editions' buttons do.
+ /// A tap in Developer tools ▸ Midas.
/// `log` is what Precision log sends; `commands` takes a screenshot.
pub fn apply_tab(&mut self, a: MidasAct, log: &HighPrecisionLog, commands: &mut Commands) {
match a {
@@ -575,7 +568,6 @@ impl MidasLink {
self.told = tell.then(|| Told {
session: "s669".to_string(),
text: "I am walking you to the Vismarkt. Tap the camera button when you are there, and I will take it from there.".to_string(),
- at: web_time::Instant::now(),
until: None,
});
self.config.on = true;
@@ -1420,138 +1412,30 @@ fn push(link: &mut MidasLink, text: &str, files: Vec<Value>) {
link.pushed = link.pushed.wrapping_add(1);
}
-/// Developer tools ▸ Midas, egui's edition. Its buttons do
-/// [`MidasLink::apply_tab`], as the library's do (`lib_dev_panel`).
-pub fn midas_tab(
- ui: &mut egui::Ui,
- link: &mut MidasLink,
- log: &HighPrecisionLog,
- commands: &mut Commands,
-) {
- theme::section(ui, "Midas");
- let message = link.shared().message.clone();
- if !link.config.paired() {
- theme::note(ui, PAIR_NOTE);
- theme::note(ui, PAIR_HOW);
- ui.horizontal(|ui| {
- ui.label("hub");
- ui.text_edit_singleline(&mut link.hub_draft);
- });
- ui.horizontal(|ui| {
- ui.label("code");
- ui.text_edit_singleline(&mut link.code_draft);
- });
- if theme::primary_button_sized(ui, "Pair", 140.0).clicked() {
- let act = MidasAct::Pair {
- hub: link.hub_draft.clone(),
- code: link.code_draft.clone(),
- };
- link.apply_tab(act, log, commands);
- }
- if let Some(m) = message {
- theme::note(ui, &m);
- }
- return;
- }
- let state = link.shared().state.clone();
- ui.label(format!("{} · {}", link.config.name, link.config.hub));
- let mut on = link.config.on;
- theme::checkbox(ui, &mut on, "Link on");
- if on != link.config.on {
- link.apply_tab(MidasAct::LinkOn(on), log, commands);
- }
- theme::note(ui, if link.config.on { &state } else { OFF_NOTE });
- if let Some((tool, session)) = link.recent_call(30.0) {
- theme::note(ui, &format!("{session} asked for {tool}"));
- }
- ui.separator();
- theme::section(ui, "Send to a session");
- let sessions = link.shared().sessions.clone();
- let chosen = link.config.send_to.clone();
- let label = chosen.as_deref().map_or_else(
- || "choose…".to_string(),
- |id| {
- sessions
- .iter()
- .find(|(s, _)| s == id)
- .map_or_else(|| id.to_string(), |(s, t)| format!("{s} · {t}"))
- },
- );
- let mut send_to = chosen.clone();
- let mut refresh = false;
- ui.horizontal(|ui| {
- egui::ComboBox::from_id_salt("midas_send_to")
- .selected_text(label)
- .width(200.0)
- .show_ui(ui, |ui| {
- for (id, title) in &sessions {
- ui.selectable_value(&mut send_to, Some(id.clone()), format!("{id} · {title}"));
- }
- });
- refresh = ui.button("Refresh").clicked();
- });
- if send_to != chosen {
- link.apply_tab(MidasAct::SendTo(send_to), log, commands);
- }
- if refresh {
- link.apply_tab(MidasAct::Refresh, log, commands);
- }
- ui.add(
- egui::TextEdit::multiline(&mut link.text_draft)
- .hint_text(WORDS_HINT)
- .desired_rows(2),
- );
- let mut act = None;
- ui.horizontal_wrapped(|ui| {
- let words = link.text_draft.clone();
- if ui.button("Precision log").clicked() {
- act = Some(MidasAct::SendLog(words.clone()));
- }
- if ui.button("Screenshot").clicked() {
- act = Some(MidasAct::SendShot(words.clone()));
- }
- if ui.button("Words only").clicked() {
- act = Some(MidasAct::SendWords(words));
- }
- });
- if let Some(a) = act {
- link.apply_tab(a, log, commands);
- }
- if let Some(m) = message {
- theme::note(ui, &m);
- }
- crate::systems::release_approval::key_section(ui);
- ui.separator();
- if ui.button("Unpair").clicked() {
- link.apply_tab(MidasAct::Unpair, log, commands);
- }
-}
-
/// How long the button glows after a call comes in.
const GLOW_S: f32 = 1.5;
-/// The card beside the button: fixed, because an anchored size-to-content
-/// `Area` grows a little every frame (`map-chrome.md`).
-const CARD_WIDTH: f32 = 230.0;
/// The Midas disc in the top-right corner, there exactly while the link is up
/// — not greyed when it is down, gone — because a session can then drive this
/// app as its account: walk, talk, move the camera. A green dot says linked; a
/// call coming in makes it glow rather than spell the call out, and a tap
-/// opens a card with which session asked for what, and as whom.
+/// opens a card with which session asked for what, and as whom. A session's
+/// `tell` shows in a bubble beside it.
///
/// It replaced a text chip at the top centre and, on the phone, the editor's
/// activity box (`mcp::overlay`), which between them covered the top of the
/// map with a socket path and a tool name wrapped one syllable a line.
-#[allow(clippy::too_many_arguments)]
-pub fn draw_link_button(
- egui: crate::systems::egui_manager::EguiRef,
+///
+/// Decides all of it and publishes it in [`MidasLink::lib_view`] for
+/// `lib_midas_link`, and does that screen's taps.
+pub fn drive_link_button(
mut link: ResMut<MidasLink>,
identity: Option<Res<crate::resources::AuthIdentity>>,
right_panel: Res<crate::resources::RightPanel>,
driver: Res<crate::systems::driver::DriverState>,
- mut seen: Local<(bool, Option<web_time::Instant>, Option<web_time::Instant>)>,
+ metrics: Res<crate::systems::ui_input::UiMetrics>,
) {
- // The library's taps of last frame, done as egui's are.
+ // The library's taps of last frame.
if !link.lib_acts.is_empty() {
for a in std::mem::take(&mut link.lib_acts) {
link.apply(a);
@@ -1568,19 +1452,6 @@ pub fn draw_link_button(
{
link.told = None;
}
- // The link and the call change on the worker's thread, and a `tell` in
- // `serve_calls`, which egui never hears of: without a repaint the button
- // would appear, glow, or speak only at the next touch
- // (`egui-quiet-frame-staleness.md`).
- let now_seen = (
- up,
- last.as_ref().map(|(_, _, at)| *at),
- link.told.as_ref().map(|t| t.at),
- );
- if *seen != now_seen {
- *seen = now_seen;
- egui.ctx().request_repaint();
- }
// Under an open panel, or in driver mode, whose trip strip has this corner.
if !up || !right_panel.is(crate::resources::RightPanel::None) || driver.active {
link.card_open = false;
@@ -1591,219 +1462,28 @@ pub fn draw_link_button(
}
let age = last.as_ref().map(|(_, _, at)| at.elapsed().as_secs_f32());
let glow = age.filter(|a| *a < GLOW_S).map(|a| 1.0 - a / GLOW_S);
- if glow.is_some() {
- egui.animating();
- }
- let ctx = egui.ctx();
- let size = theme::ROUND_BUTTON_SIZE;
- let mut toggle = false;
// A second column, left of the map's round buttons under the search bar
// (`dock::right_column`): the top right corner is your face now.
// On a phone on its side the column lies down as a row beside the bar,
// and this takes the margin under the bar.
- let view = egui.viewport_pts();
let left_of_column =
- crate::systems::dock::right_column(bevy::math::Vec2::new(view.x, view.y), false, false)
- .beside();
- if link.lib {
- // The repaints egui's card and bubble ask for, so the library's
- // "just now" ages and a timed bubble goes.
- if link.card_open && age.is_some() {
- ctx.request_repaint_after(std::time::Duration::from_secs(30));
- }
- if let Some(until) = link.told.as_ref().and_then(|t| t.until) {
- ctx.request_repaint_after(until.saturating_duration_since(web_time::Instant::now()));
- }
- let who = identity.as_deref().and_then(|i| i.username.clone());
- let view = LinkView {
- right: left_of_column,
- top: crate::systems::dock::reserved_top(),
- glow,
- card: link.card_open.then(|| LinkCardView {
- call: card_call(last.as_ref(), age),
- acts: card_acts(who),
- }),
- told: link.told.as_ref().map(|t| ToldView {
- session: t.session.clone(),
- text: t.text.clone(),
- }),
- };
- if link.lib_view.as_ref() != Some(&view) {
- link.lib_view = Some(view);
- }
- return;
- }
- egui::Area::new(egui::Id::new("midas_link_button"))
- .anchor(
- egui::Align2::RIGHT_TOP,
- egui::vec2(-left_of_column, crate::systems::dock::reserved_top()),
- )
- .show(ctx, |ui| {
- let (resp, face) = theme::map_disc(
- ui,
- size,
- false,
- theme::p32().accent_ring,
- egui::Sense::click(),
- );
- let resp = theme::named(ui, resp, "Midas");
- let p = ui.painter();
- if let Some(g) = glow {
- p.circle_stroke(
- face.center,
- face.radius + 2.0 + 6.0 * (1.0 - g),
- egui::Stroke::new(
- 3.0 * g,
- egui::Color32::from(theme::midas_gold()).gamma_multiply(g),
- ),
- );
- }
- theme::paint_midas_mark(p, face.center, face.radius);
- let dot = face.center + egui::vec2(1.0, -1.0) * face.radius * 0.74;
- p.circle_filled(dot, 5.0, theme::CALL_ACCEPT_GREEN);
- p.circle_stroke(dot, 5.0, egui::Stroke::new(1.5, theme::p32().ink));
- toggle = resp.on_hover_text("Midas").clicked();
- });
- // The card and the bubble share the place left of the button; with both
- // up, the bubble stands under the card.
- let beside = -(left_of_column + size + theme::OSD_GAP);
- let top = crate::systems::dock::reserved_top();
- let bubble_top = if link.card_open {
- draw_link_card(
- ctx,
- &mut link,
- identity.as_deref(),
- last.as_ref(),
- age,
- beside,
- top,
- toggle,
- ) + theme::OSD_GAP
- } else {
- if toggle {
- link.apply(LinkAct::Toggle);
- }
- top
+ crate::systems::dock::right_column(metrics.viewport_pts(), false, false).beside();
+ let who = identity.as_deref().and_then(|i| i.username.clone());
+ let view = LinkView {
+ right: left_of_column,
+ top: crate::systems::dock::reserved_top(),
+ glow,
+ card: link.card_open.then(|| LinkCardView {
+ call: card_call(last.as_ref(), age),
+ acts: card_acts(who),
+ }),
+ told: link.told.as_ref().map(|t| ToldView {
+ session: t.session.clone(),
+ text: t.text.clone(),
+ }),
};
- draw_told(ctx, &mut link, beside, bubble_top, bubble_top == top, size);
-}
-
-/// The card a tap on the button opens: which session asked for what last,
-/// and as whom. Returns its bottom edge.
-#[allow(clippy::too_many_arguments)]
-fn draw_link_card(
- ctx: &egui::Context,
- link: &mut MidasLink,
- identity: Option<&crate::resources::AuthIdentity>,
- last: Option<&(String, String, web_time::Instant)>,
- age: Option<f32>,
- beside: f32,
- top: f32,
- toggle: bool,
-) -> f32 {
- let who = identity.and_then(|i| i.username.clone());
- let card = egui::Area::new(egui::Id::new("midas_link_card"))
- .anchor(egui::Align2::RIGHT_TOP, egui::vec2(beside, top))
- .show(ctx, |ui| {
- theme::overlay_frame().show(ui, |ui| {
- ui.set_width(CARD_WIDTH);
- ui.spacing_mut().item_spacing.y = 3.0;
- ui.label(
- egui::RichText::new("Midas linked")
- .size(theme::SIZE_SUB)
- .color(theme::p32().cream)
- .strong(),
- );
- ui.label(
- egui::RichText::new(card_call(last, age))
- .size(theme::SIZE_CHIP)
- .color(theme::midas_gold()),
- );
- ui.label(
- egui::RichText::new(card_acts(who))
- .size(theme::SIZE_TINY)
- .color(theme::p32().text_dim),
- );
- });
- });
- if age.is_some() {
- // "just now" turns into minutes on its own.
- ctx.request_repaint_after(std::time::Duration::from_secs(30));
- }
- // A second tap closes it, on the button or on the card.
- let tap = card.response.interact(egui::Sense::click());
- tap.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Close"));
- if toggle || tap.clicked() {
- link.apply(LinkAct::CloseCard);
- }
- card.response.rect.bottom()
-}
-
-/// What a session said with `tell`, in a bubble beside the button — with a
-/// tail pointing at it when nothing stands between — so the person can follow
-/// a session driving the phone without leaving the app for the Midas page. A
-/// tap takes it down.
-fn draw_told(
- ctx: &egui::Context,
- link: &mut MidasLink,
- beside: f32,
- top: f32,
- by_the_button: bool,
- button: f32,
-) {
- let Some(told) = &link.told else {
- return;
- };
- if let Some(until) = told.until {
- ctx.request_repaint_after(until.saturating_duration_since(web_time::Instant::now()));
- }
- let bubble = egui::Area::new(egui::Id::new("midas_link_told"))
- .anchor(egui::Align2::RIGHT_TOP, egui::vec2(beside, top))
- .show(ctx, |ui| {
- theme::overlay_frame()
- .stroke(egui::Stroke::new(
- 1.0,
- egui::Color32::from(theme::midas_gold()).gamma_multiply(0.6),
- ))
- .show(ui, |ui| {
- ui.set_width(CARD_WIDTH);
- ui.spacing_mut().item_spacing.y = 4.0;
- ui.label(
- egui::RichText::new(&told.session)
- .size(theme::SIZE_CHIP)
- .color(theme::midas_gold())
- .strong(),
- );
- ui.add(
- egui::Label::new(
- egui::RichText::new(&told.text)
- .size(theme::SIZE_BODY)
- .color(theme::p32().cream),
- )
- .wrap(),
- );
- });
- });
- let rect = bubble.response.rect;
- if by_the_button {
- // Level with the disc's centre, across the gap to it.
- let y = rect.top() + button / 2.0;
- let tail = vec![
- egui::pos2(rect.right() - 1.0, y - 7.0),
- egui::pos2(rect.right() + theme::OSD_GAP - 1.0, y),
- egui::pos2(rect.right() - 1.0, y + 7.0),
- ];
- ctx.layer_painter(bubble.response.layer_id)
- .add(egui::Shape::convex_polygon(
- tail,
- theme::p32().overlay,
- egui::Stroke::NONE,
- ));
- }
- let tap = bubble.response.interact(egui::Sense::click());
- tap.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Dismiss"));
- if tap.clicked() {
- link.apply(LinkAct::DismissTold);
+ if link.lib_view.as_ref() != Some(&view) {
+ link.lib_view = Some(view);
}
}
diff --git a/crates/cartopolis/src/systems/dev/plugin.rs b/crates/cartopolis/src/systems/dev/plugin.rs
index 78574f7f..a59a8ee8 100644
--- a/crates/cartopolis/src/systems/dev/plugin.rs
+++ b/crates/cartopolis/src/systems/dev/plugin.rs
@@ -83,7 +83,7 @@ impl Plugin for DevPlugin {
)
.chain()
.in_set(ClientPhase::Input),
- systems::midas_link::draw_link_button
+ systems::midas_link::drive_link_button
.in_set(ClientPhase::Present)
.after(systems::locate::place_locate_arrow),
),
@@ -93,7 +93,7 @@ impl Plugin for DevPlugin {
Update,
(
systems::dev_panel::toggle_dev_panel_shortcut,
- systems::dev_panel::render_dev_panel,
+ systems::dev_panel::drive_dev_panel,
)
.in_set(ClientPhase::Input),
)
@@ -206,16 +206,6 @@ impl Plugin for ShotHarnessPlugin {
.add_systems(
Update,
(
- // Anywhere in Update is early enough: it only has to beat
- // PostUpdate's `end_egui_frame`, which is what would otherwise
- // reuse an older frame's tessellation for the capture.
- //
- // Gated, because in a live run this is a cost paid every frame
- // for a capture that may be minutes away — and between calls
- // the ordinary skip is what the client wants.
- systems::shot_harness::keep_egui_fresh
- .run_if(systems::shot_harness::shot_in_progress)
- .in_set(ClientPhase::Input),
systems::shot_harness::place_camera
.before(systems::geo_nav::apply_teleport)
.in_set(ClientPhase::Input),
@@ -511,8 +501,9 @@ impl Plugin for McpPlugin {
)
.in_set(ClientPhase::Input),
);
- // `ui_tree` and `press`: egui through a plugin of its own, so no place
- // in the panel chain — only after the pump that queues them.
+ // `ui_tree` and `press`: answered from the component library's tree
+ // (exclusive: its host is thread-local), after the pump that queues
+ // them.
app.init_resource::<systems::mcp::screen::ScreenPending>()
.add_systems(
Update,
@@ -520,16 +511,6 @@ impl Plugin for McpPlugin {
.after(systems::mcp::pump)
.in_set(ClientPhase::Input),
);
- // While the component library draws, it answers them first from its
- // own tree (exclusive: its host is thread-local).
- #[cfg(feature = "ui-probe")]
- app.add_systems(
- Update,
- systems::mcp::screen::serve_lib
- .after(systems::mcp::pump)
- .before(systems::mcp::screen::serve)
- .in_set(ClientPhase::Input),
- );
// The map's questions: a point, a building, a stop, the sky. In
// `Input`, where a prim's `Transform` is in the sim's flat frame
// (`prim_geo::strip_prim_lift`), which `check_geometry` relies on.
@@ -598,7 +579,7 @@ impl Plugin for McpPlugin {
// the Midas link, whose button says so (`midas_link`).
app.add_systems(
Update,
- systems::mcp::overlay::render_mcp_activity
+ systems::mcp::overlay::publish_mcp_activity
.after(systems::place_pins::place_map_pins)
.in_set(ClientPhase::Present),
);
diff --git a/crates/cartopolis/src/systems/dev/release_approval.rs b/crates/cartopolis/src/systems/dev/release_approval.rs
index 72e06a66..f0a8c79f 100644
--- a/crates/cartopolis/src/systems/dev/release_approval.rs
+++ b/crates/cartopolis/src/systems/dev/release_approval.rs
@@ -13,7 +13,7 @@
//! the fingerprint.
//!
//! Developer tools ▸ Midas also makes the key and keeps the Claude API key
-//! ([`key_section`]), and the link's `release_key` tool tells a session the
+//! ([`key_view`], [`key_act`]), and the link's `release_key` tool tells a session the
//! key's public half, which goes into the server's and the app's
//! `RELEASE_KEYS`.
@@ -24,9 +24,7 @@ use serde::Deserialize;
use sha2::{Digest, Sha256};
use crate::platform::release_key::{self, Signing};
-use crate::systems::egui_manager::EguiRef;
use crate::systems::release_review::{self, Verdict};
-use crate::systems::theme;
/// Where the code of a release is read from, by commit id: a commit id names
/// its content, so this host can refuse but not substitute.
@@ -35,6 +33,7 @@ const REPOSITORY: &str = "https://code.garage44.eu/jeroen/cartopolis";
/// Largest package this phone downloads to check: the APK is about 80 MB.
const MAX_PACKAGE: u64 = 300 * 1024 * 1024;
const MAX_MANIFEST: u64 = 64 * 1024;
+#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub(crate) const CARD_WIDTH: f32 = 420.0;
/// What a release says it is: the server's `release.json`, with the APK
@@ -103,16 +102,14 @@ struct State {
outcome: Option<(String, String)>,
/// Developer tools ▸ Midas ▸ Release key, read once.
key: Option<KeyView>,
- /// The component library draws the card (`lib_release_approval`):
- /// [`render_release_approval`] keeps its logic and draws nothing.
- lib: bool,
- /// The card as the library draws it, published each frame.
+ /// The card as the library draws it (`lib_release_approval`), published
+ /// each frame by [`drive_release_approval`].
lib_view: Option<ApprovalView>,
/// The library's taps, done next frame by [`act`].
lib_acts: Vec<ApprovalAct>,
}
-/// A tap on the card, from either edition.
+/// A tap on the card.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub enum ApprovalAct {
@@ -170,7 +167,7 @@ pub struct KeySectionView {
pub message: Option<String>,
}
-/// A tap in the Release key section, from either edition.
+/// A tap in the Release key section.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub enum KeyAct {
@@ -189,29 +186,18 @@ struct KeyView {
public: Option<String>,
location: Option<String>,
message: Option<String>,
- /// Whether a Claude API key is kept, and the field to type a new one in.
+ /// Whether a Claude API key is kept.
has_api_key: bool,
- api_key_draft: String,
}
static STATE: Mutex<State> = Mutex::new(State {
request: None,
outcome: None,
key: None,
- lib: false,
lib_view: None,
lib_acts: Vec::new(),
});
-/// The library draws the card from now on (`lib_release_approval`).
-#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
-pub fn set_lib() {
- let mut s = state();
- if !s.lib {
- s.lib = true;
- }
-}
-
/// The card as published this frame, for the library.
#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub fn lib_view() -> Option<ApprovalView> {
@@ -507,7 +493,7 @@ fn hash(url: &str, package: &Package) -> Result<(), String> {
Ok(())
}
-/// Developer tools ▸ Midas ▸ Release key as both editions show it, read once;
+/// Developer tools ▸ Midas ▸ Release key as the library shows it, read once;
/// `None` where releases are not approved (not the owner's Android phone).
pub fn key_view() -> Option<KeySectionView> {
if !release_key::available() {
@@ -554,7 +540,7 @@ pub fn key_view() -> Option<KeySectionView> {
})
}
-/// Make the release key or keep a Claude API key: what both editions' buttons
+/// Make the release key or keep a Claude API key: what the library's buttons
/// do.
pub fn key_act(a: KeyAct) {
match a {
@@ -586,57 +572,11 @@ pub fn key_act(a: KeyAct) {
}
}
-/// Developer tools ▸ Midas ▸ Release key.
-pub fn key_section(ui: &mut egui::Ui) {
- let Some(view) = key_view() else {
- return;
- };
- ui.separator();
- theme::section(ui, "Release key");
- match &view.public {
- None => {
- theme::note(ui, KEY_MAKE_NOTE);
- if theme::primary_button_sized(ui, "Make release key", 200.0).clicked() {
- key_act(KeyAct::Make);
- }
- }
- Some(key) => {
- theme::note(ui, &view.kept);
- ui.label(egui::RichText::new(&view.short).monospace());
- if ui.button("Copy public key").clicked() {
- ui.ctx().copy_text(key.clone());
- }
- theme::note(ui, KEY_TOOL_NOTE);
- }
- }
- theme::note(ui, view.api_note);
- let mut draft = state()
- .key
- .as_ref()
- .map_or_else(String::new, |k| k.api_key_draft.clone());
- ui.horizontal(|ui| {
- ui.add(
- egui::TextEdit::singleline(&mut draft)
- .password(true)
- .hint_text("sk-ant-…")
- .desired_width(200.0),
- );
- if ui.button("Save key").clicked() {
- key_act(KeyAct::SaveApiKey(std::mem::take(&mut draft)));
- }
- });
- if let Some(k) = state().key.as_mut() {
- k.api_key_draft = draft;
- }
- if let Some(m) = &view.message {
- let _ = theme::inline_error(ui, m);
- }
-}
-
/// The release in front of the owner, over everything; and the fingerprint
-/// sheet's outcome once it is answered.
-pub fn render_release_approval(egui: EguiRef) {
- // The library's taps of last frame, done as egui's buttons do them.
+/// sheet's outcome once it is answered. Publishes the card for
+/// `lib_release_approval` and does its taps.
+pub fn drive_release_approval() {
+ // The library's taps of last frame.
let acts = std::mem::take(&mut state().lib_acts);
for a in acts {
let open = state().request.clone();
@@ -686,135 +626,13 @@ pub fn render_release_approval(egui: EguiRef) {
}
}
}
- egui.ctx()
- .request_repaint_after(std::time::Duration::from_millis(300));
- }
- let ctx = egui.ctx();
- // The checks and the review run on a thread: show their progress.
- if matches!(request.phase, Phase::Checking(_)) || matches!(request.review, Review::Pending(_)) {
- ctx.request_repaint_after(std::time::Duration::from_millis(500));
- }
- {
- let mut s = state();
- if s.lib {
- let view = approval_view(&request);
- if s.lib_view.as_ref() != Some(&view) {
- s.lib_view = Some(view);
- }
- return;
- }
}
- let screen = ctx.content_rect();
- let width = CARD_WIDTH.min(screen.width() - 2.0 * theme::OSD_MARGIN);
- egui::Area::new(egui::Id::new("release_approval_veil"))
- .order(egui::Order::Foreground)
- .fixed_pos(screen.min)
- .show(ctx, |ui| {
- ui.painter()
- .rect_filled(screen, 0.0, theme::DARK32.ink.gamma_multiply(0.86));
- // unnamed: a blocker under the card, not a control
- ui.allocate_rect(screen, egui::Sense::click_and_drag());
- });
- let mut approve = false;
- let mut decline = false;
- egui::Area::new(egui::Id::new("release_approval_card"))
- .order(egui::Order::Foreground)
- .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO)
- .show(ctx, |ui| {
- theme::overlay_frame().show(ui, |ui| {
- ui.set_width(width);
- let title = approval_title(&request);
- ui.label(
- egui::RichText::new(title)
- .size(theme::SIZE_HEADING)
- .color(theme::p32().cream),
- );
- line(
- ui,
- &format!("Asked by {} · {}", request.session, request.source),
- );
- ui.add_space(6.0);
- verdict_block(ui, &request.review);
- egui::ScrollArea::vertical()
- .max_height(screen.height() * 0.45)
- .show(ui, |ui| {
- if let Review::Done(v) = &request.review {
- for f in &v.findings {
- ui.horizontal_wrapped(|ui| {
- ui.label(egui::RichText::new("!").color(theme::p32().error));
- ui.label(
- egui::RichText::new(format!("{} {}", f.file, f.lines))
- .monospace(),
- );
- });
- line(ui, &f.why);
- }
- }
- egui::CollapsingHeader::new("What changes, and what this phone checked")
- .default_open(false)
- .show(ui, |ui| {
- if let Some(r) = &request.release {
- theme::section(
- ui,
- &format!("What changes · {}", r.changes.len()),
- );
- if r.changes.is_empty() {
- line(ui, "The release lists no changes.");
- }
- for c in &r.changes {
- ui.label(format!("• {c}"));
- }
- line(ui, &format!("Version code {}", r.code));
- }
- theme::section(ui, "Checks");
- if let Phase::Checking(what) = &request.phase {
- ui.horizontal(|ui| {
- ui.add(egui::Spinner::new().color(theme::p32().accent));
- line(ui, what);
- });
- }
- for c in &request.checks {
- let mark = if c.ok {
- crate::systems::icons::CHECK
- } else {
- "!"
- };
- let colour = if c.ok {
- theme::p32().accent
- } else {
- theme::p32().error
- };
- ui.horizontal_wrapped(|ui| {
- ui.label(egui::RichText::new(mark).color(colour));
- ui.label(&c.line);
- });
- }
- });
- });
- ui.add_space(8.0);
- let ready = ready(&request);
- let label = approve_label(&request);
- let width = ui.available_width();
- if ui
- .add_enabled_ui(ready, |ui| theme::primary_button_sized(ui, label, width))
- .inner
- .clicked()
- {
- approve = true;
- }
- if not_green(&request) {
- line(ui, NOT_GREEN);
- }
- if ui.button("Not now").clicked() {
- decline = true;
- }
- });
- });
- if approve {
- act(&request, ApprovalAct::Approve);
- }
- if decline {
- act(&request, ApprovalAct::Decline);
+ // The checks and the review run on a thread: their progress shows as the
+ // view moves.
+ let view = approval_view(&request);
+ let mut s = state();
+ if s.lib_view.as_ref() != Some(&view) {
+ s.lib_view = Some(view);
}
}
@@ -840,15 +658,7 @@ fn not_green(request: &Request) -> bool {
request.phase == Phase::Ready && !ready(request) && settled
}
-fn approve_label(request: &Request) -> &'static str {
- if request.phase == Phase::Signing {
- "Waiting for your fingerprint…"
- } else {
- "Approve with fingerprint"
- }
-}
-
-/// A tap on Approve or Not now, from either edition.
+/// A tap on Approve or Not now.
fn act(request: &Request, a: ApprovalAct) {
match a {
ApprovalAct::Approve => {
@@ -953,36 +763,6 @@ fn approval_view(request: &Request) -> ApprovalView {
}
}
-/// Claude's verdict, at the top of the card: what the owner decides on.
-fn verdict_block(ui: &mut egui::Ui, review: &Review) {
- match verdict_view(review) {
- VerdictView::Pending(what) => {
- ui.horizontal(|ui| {
- ui.add(egui::Spinner::new().color(theme::p32().accent));
- ui.label(
- egui::RichText::new("Claude is checking this release")
- .size(theme::SIZE_BODY)
- .color(theme::p32().cream),
- );
- });
- line(ui, &what);
- }
- VerdictView::Said { title, green, body } => {
- let colour = if green {
- theme::p32().accent
- } else {
- theme::p32().error
- };
- ui.label(
- egui::RichText::new(title)
- .size(theme::SIZE_BODY)
- .color(colour),
- );
- ui.label(body);
- }
- }
-}
-
fn set_phase(phase: Phase) {
if let Some(r) = state().request.as_mut() {
r.phase = phase;
@@ -996,11 +776,3 @@ fn answer(request: &Request, words: String) {
s.lib_view = None;
s.outcome = Some((request.session.clone(), words));
}
-
-fn line(ui: &mut egui::Ui, text: &str) {
- ui.label(
- egui::RichText::new(text)
- .size(theme::SIZE_SUB)
- .color(theme::p32().text_dim),
- );
-}
diff --git a/crates/cartopolis/src/systems/dev/shot_harness.rs b/crates/cartopolis/src/systems/dev/shot_harness.rs
index 67004f8a..b9cc83d1 100644
--- a/crates/cartopolis/src/systems/dev/shot_harness.rs
+++ b/crates/cartopolis/src/systems/dev/shot_harness.rs
@@ -24,7 +24,7 @@
//! an offscreen image. Nothing appears on the desktop, no compositor can
//! occlude (and blacken) the captured frame, and the run needs no display
//! server. `resources::HeadlessSurface` stands in for the missing `Window`
-//! wherever one is needed (egui layout, screen-space LOD).
+//! wherever one is needed (UI layout, screen-space LOD).
//! * **Settle-on-idle.** Rather than a fixed sleep, each capture waits until
//! the tile streams go quiet ([`MapStream::streaming_busy`] /
//! [`GlobeState::streaming_busy`]) for `--settle` seconds, capped by
@@ -32,7 +32,7 @@
//! * **No user-store writes.** The interactive session's saved location is
//! neither restored nor overwritten by a scripted run.
//!
-//! The egui overlay is part of the capture (it carries the HUD's altitude and
+//! The interface is part of the capture (it carries the HUD's altitude and
//! coordinates, which is what makes a shot self-documenting); pass `--hide-ui`
//! for chrome-free images. The toggle-able panels (dev lighting/weather, layers,
//! bookmarks, AI, avatar chooser) are closed by default and can't be opened by
@@ -289,7 +289,7 @@ pub struct ShotHarness {
pub settle: f32,
/// Hard cap on the wait per shot.
pub wait: f32,
- /// Leave the egui overlay out of the capture.
+ /// Leave the interface out of the capture.
pub hide_ui: bool,
/// UI panels to open for the capture (`dev`, `layers`, `bookmarks`,
/// `avatar`, `stats`, or `all`) — see [`open_scripted_ui`]. Empty = just the
@@ -2052,7 +2052,7 @@ impl ShotHarness {
})
}
- /// Whether shot `i` drops the egui overlay.
+ /// Whether shot `i` leaves the interface out.
pub fn hide_ui_for(&self, i: usize) -> bool {
self.shots
.get(i)
@@ -2194,7 +2194,7 @@ impl ShotHarness {
}
/// Parse a `--size` string ("1280x720"). Also read in `main` to size the window
-/// to the offscreen target — egui scissors against the window, so the two must
+/// to the offscreen target — the UI scissors against the window, so the two must
/// agree or wgpu validation kills the run (see the `shot_size` comment there).
pub fn parse_size(size: &str) -> Option<UVec2> {
let (w, h) = size.split_once(['x', 'X'])?;
@@ -2389,7 +2389,7 @@ pub fn harness_active(harness: Option<Res<ShotHarness>>) -> bool {
/// True while the harness has a viewpoint to work on.
///
/// The run condition for every system that *holds* something for the duration of
-/// a capture — the camera mode, the egui refresh, the panels a `--ui` list opens.
+/// a capture — the camera mode, the panels a `--ui` list opens.
/// Under `--shot` it is true for the whole run, so nothing about a scripted
/// capture changes. Under a live harness it is false between calls, which is what
/// hands the client back to whoever is sitting in front of it: a camera mode held
@@ -2398,33 +2398,6 @@ pub fn shot_in_progress(harness: Option<Res<ShotHarness>>, progress: Res<ShotPro
harness.is_some_and(|h| progress.index < h.shots.len())
}
-/// Keep egui's geometry in step with the world for the whole of a scripted run.
-///
-/// **A settled capture could otherwise show chrome from twenty seconds earlier.**
-/// `egui_manager::end_egui_frame` skips the tessellate → upload chain whenever
-/// egui reports `repaint_delay == Duration::MAX`, and redraws the last-written
-/// primitives instead — which is free and correct for the thing it was written
-/// for, a static menu bar under a mouse that has not moved. It is not correct
-/// for an overlay whose content comes from the **ECS**: egui's repaint signal
-/// answers "has anything I know about changed", and it knows nothing about the
-/// camera. So a run that flies somewhere and then goes quiet — which is exactly
-/// what `--settle` is — keeps painting the shapes from the last frame egui
-/// happened to consider interesting.
-///
-/// It was found the way these things are: a `--shot-mode earth` capture from
-/// 14,000 km carried a scale bar reading "200 m", the altitude the camera had on
-/// frame 2 of the run, while `drive_map_controls` had correctly drawn no bar at
-/// all for the twenty seconds since. Anything read off the world and drawn into
-/// the overlay could be that stale — the clock, the coordinates, the compass
-/// needle, an open panel's contents — and nothing about the image says so.
-///
-/// Forcing the write costs one tessellation per frame, in the one kind of run
-/// that is already spending 250 ms a frame on a software rasteriser and whose
-/// entire purpose is the picture at the end of it. The live app keeps the skip.
-pub fn keep_egui_fresh(mut render_output: ResMut<crate::systems::egui_manager::EguiRenderOutput>) {
- render_output.force_next_write = true;
-}
-
/// The two floating cards a `--ui` list can raise, plus the preferences a shot
/// may override — bundled into one parameter because [`open_scripted_ui`] is at
/// Bevy's sixteen-parameter ceiling and adding a seventeenth does not fail as a
@@ -2682,7 +2655,7 @@ const UI_ELEMENTS: &[&str] = &[
"callfolded",
// The Midas button as it stands while the device link is up, and its
// card open, and a session's message beside it
- // (`midas_link::draw_link_button`).
+ // (`midas_link::drive_link_button`).
"midaslink",
"midascard",
"midastell",
@@ -2714,7 +2687,7 @@ pub fn open_scripted_ui(
mut nav: ResMut<crate::systems::geo_nav::GeoNavState>,
mut cards: ScriptedCards,
mut store: ResMut<crate::systems::user_store::UserStore>,
- egui: crate::systems::egui_manager::EguiRef,
+ metrics: Res<crate::systems::ui_input::UiMetrics>,
mut done: Local<Option<usize>>,
) {
if *done == Some(progress.index) {
@@ -2795,10 +2768,8 @@ pub fn open_scripted_ui(
view_altitude_m: 9_000.0,
});
if want("ring") || want("placering") {
- // The middle of the view. A headless run draws egui at scale 1, where
- // window points and ui points are the same.
- let size = egui.viewport_pts();
- cards.context_menu.screen_pos = Vec2::new(size.x, size.y) / 2.0;
+ // The middle of the view, in ui points.
+ cards.context_menu.screen_pos = metrics.viewport_pts() / 2.0;
cards.context_menu.hit_prim_id = None;
cards.context_menu.lat_lng = harness.shots.get(progress.index).map(|s| (s.lat, s.lng));
}
@@ -5796,8 +5767,9 @@ fn fire_capture(
target: Option<&ShotTarget>,
shot_state: &mut ScreenshotState,
) {
- // `--hide-ui`: drop this frame's egui geometry (ui::suppress_egui_for_screenshot
- // reads `hide_ui` in PostUpdate; ui::drive_screenshots clears it next frame).
+ // `--hide-ui`: leave the interface out of this frame (`lib_host::
+ // hide_for_snapshots` stands the library's camera down while `hide_ui` is
+ // set; ui::drive_screenshots clears it next frame).
shot_state.hide_ui = harness.hide_ui_for(progress.index);
progress.fired = true;
progress.fired_at = progress.elapsed;
diff --git a/crates/cartopolis/src/systems/gui/app_update.rs b/crates/cartopolis/src/systems/gui/app_update.rs
index c8147a18..3a3e08cc 100644
--- a/crates/cartopolis/src/systems/gui/app_update.rs
+++ b/crates/cartopolis/src/systems/gui/app_update.rs
@@ -6,26 +6,20 @@
//! where it is and passes the tap on. Ignored, the pill's update still goes in:
//! the updater installs it when the person leaves the app.
//!
-//! Both are `Foreground` areas over everything, outside the panel chain, like
-//! the calendar's reminder. The too-old card claims the whole screen, so no
-//! tap reaches the map or a panel beneath it: nothing there works until the
-//! update is in.
+//! The component library draws both (`systems::lib_app_update`);
+//! [`drive_app_update`] asks the updater, publishes what shows and does what a
+//! tap there asked for. The too-old card claims the whole screen, so no tap
+//! reaches the map or a panel beneath it: nothing there works until the update
+//! is in.
use bevy::prelude::*;
use crate::platform::update::{self, UpdateStatus};
-use crate::systems::egui_manager::EguiRef;
-use crate::systems::{icons, theme};
/// How often the updater is asked: a JNI call, and a download's progress moves
/// visibly at this rate.
const POLL_S: f64 = 0.5;
-/// Width of the pill and of the card, fixed for the reason
-/// [`crate::systems::place_card`]'s is: a size-to-content `Area` grows otherwise.
-const PILL_WIDTH: f32 = 340.0;
-const CARD_WIDTH: f32 = 360.0;
-
#[derive(Resource, Default)]
pub struct AppUpdate {
status: UpdateStatus,
@@ -35,15 +29,11 @@ pub struct AppUpdate {
/// What a scripted capture shows instead (`--ui updateready`, `updatetooold`,
/// `updating`), as on a phone; `None` on every other shot and in use.
pub capture: Option<Capture>,
- /// The component library draws the pill and the card
- /// (`systems::lib_app_update`): this system then draws nothing, but still
- /// asks the updater, publishes what to show ([`Self::lib_view`]) and does
- /// what a tap there asked for ([`Self::lib_action`]).
- pub lib: bool,
+ /// What to show, for the library's edition, which hands a tap back in
+ /// [`Self::lib_action`].
pub lib_view: UpdateView,
pub lib_action: Option<UpdateAction>,
}
-
/// A stand-in for the updater and the server's answer, for a capture.
#[derive(Clone, Debug)]
pub struct Capture {
@@ -51,7 +41,7 @@ pub struct Capture {
pub too_old: bool,
}
-/// What is on screen, in either edition.
+/// What is on screen.
#[derive(Clone, Debug, Default, PartialEq)]
pub enum UpdateView {
#[default]
@@ -84,7 +74,7 @@ pub enum TooOld {
Elsewhere,
}
-/// A tap, in either edition.
+/// A tap on the pill or the card.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UpdateAction {
Install,
@@ -95,7 +85,7 @@ pub enum UpdateAction {
/// The line under "Installing…" and a download on the too-old card.
pub const CLOSES: &str = "Cartopolis closes when the update is in; a notification opens it again.";
-/// The too-old card's text, in either edition: the title and the lines.
+/// The too-old card's text: the title and the lines.
#[must_use]
pub fn too_old_text(t: &TooOld) -> (&'static str, &'static str) {
match t {
@@ -171,7 +161,8 @@ impl AppUpdate {
}
}
-pub fn render_app_update(egui: EguiRef, mut state: ResMut<AppUpdate>, time: Res<Time<Real>>) {
+/// Asks the updater, publishes what shows, and does what a tap asked for.
+pub fn drive_app_update(mut state: ResMut<AppUpdate>, time: Res<Time<Real>>) {
// A tap the library's edition handed back.
if let Some(action) = state.lib_action {
state.lib_action = None;
@@ -189,155 +180,11 @@ pub fn render_app_update(egui: EguiRef, mut state: ResMut<AppUpdate>, time: Res<
(update::too_old(), update::can_install())
};
let view = state.view(too_old, installable);
- if state.lib {
- if state.lib_view != view {
- state.lib_view = view;
- }
- return;
- }
- let action = match &view {
- UpdateView::None => None,
- UpdateView::Pill { title, line, ready } => pill(&egui, title, line, *ready),
- UpdateView::TooOld(t) => too_old_card(&egui, t),
- };
- if let Some(action) = action {
- state.act(action);
+ if state.lib_view != view {
+ state.lib_view = view;
}
}
-/// "Update ready", with Install — and once tapped, how far it is.
-fn pill(egui: &EguiRef, title: &str, line: &str, ready: bool) -> Option<UpdateAction> {
- let ctx = egui.ctx();
- let width = PILL_WIDTH.min(egui.viewport_pts().x - 2.0 * theme::OSD_MARGIN);
- let mut action = None;
- egui::Area::new(egui::Id::new("app_update_pill"))
- .order(egui::Order::Foreground)
- // Under the search bar, which has the top edge.
- .anchor(
- egui::Align2::CENTER_TOP,
- egui::vec2(0.0, crate::systems::dock::reserved_top()),
- )
- .show(ctx, |ui| {
- crate::systems::theme::glass_frame().show(ui, |ui| {
- ui.set_width(width);
- ui.horizontal(|ui| {
- ui.label(
- egui::RichText::new(icons::DOWNLOAD)
- .size(theme::SIZE_TITLE)
- .color(theme::p32().accent),
- );
- ui.vertical(|ui| {
- ui.label(
- egui::RichText::new(title)
- .size(theme::SIZE_BODY)
- .color(theme::p32().cream),
- );
- ui.label(
- egui::RichText::new(line)
- .size(theme::SIZE_SUB)
- .color(theme::p32().text_dim),
- );
- });
- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- if ready {
- if theme::close_button(ui).clicked() {
- action = Some(UpdateAction::Dismiss);
- }
- if theme::primary_button_sized(ui, "Install", 0.0).clicked() {
- action = Some(UpdateAction::Install);
- }
- } else {
- ui.add(
- egui::Spinner::new()
- .size(theme::SIZE_BODY)
- .color(theme::p32().accent),
- );
- }
- });
- });
- });
- });
- action
-}
-
-/// "Update Cartopolis to continue": the map dimmed, nothing else answers.
-fn too_old_card(egui: &EguiRef, t: &TooOld) -> Option<UpdateAction> {
- let ctx = egui.ctx();
- let screen = ctx.content_rect();
- let width = CARD_WIDTH.min(screen.width() - 2.0 * theme::OSD_MARGIN);
- egui::Area::new(egui::Id::new("app_update_veil"))
- .order(egui::Order::Foreground)
- .fixed_pos(screen.min)
- .show(ctx, |ui| {
- ui.painter()
- .rect_filled(screen, 0.0, theme::DARK32.ink.gamma_multiply(0.82));
- // Every tap on the veil is taken here, so none reaches the world.
- // unnamed: a blocker under the card, not a control
- ui.allocate_rect(screen, egui::Sense::click_and_drag());
- });
- let mut tapped = false;
- let (heading, text) = too_old_text(t);
- egui::Area::new(egui::Id::new("app_update_card"))
- .order(egui::Order::Foreground)
- .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO)
- .show(ctx, |ui| {
- theme::overlay_frame().show(ui, |ui| {
- ui.set_width(width);
- ui.vertical_centered(|ui| {
- ui.label(
- egui::RichText::new(icons::DOWNLOAD)
- .size(theme::SIZE_PANEL_TITLE)
- .color(theme::p32().accent),
- );
- ui.add_space(4.0);
- title(ui, heading);
- if let TooOld::Fetching { fraction, line: mb } = t {
- ui.add_space(8.0);
- ui.add(
- egui::ProgressBar::new(*fraction)
- .desired_height(8.0)
- .fill(theme::p32().accent),
- );
- line(ui, mb);
- }
- line(ui, text);
- if let TooOld::Offer { failed } = t {
- if let Some(why) = failed {
- ui.add_space(4.0);
- let _ = theme::inline_error(ui, &format!("Did not work: {why}"));
- }
- ui.add_space(8.0);
- let label = if failed.is_some() {
- "Try again"
- } else {
- "Update now"
- };
- if theme::primary_button_sized(ui, label, ui.available_width()).clicked() {
- tapped = true;
- }
- }
- });
- });
- });
- tapped.then_some(UpdateAction::Install)
-}
-
-fn title(ui: &mut egui::Ui, text: &str) {
- ui.label(
- egui::RichText::new(text)
- .size(theme::SIZE_HEADING)
- .color(theme::p32().cream),
- );
-}
-
-fn line(ui: &mut egui::Ui, text: &str) {
- ui.label(
- egui::RichText::new(text)
- .size(theme::SIZE_SUB)
- .color(theme::p32().text_dim),
- );
-}
-
/// "34 of 80 MB", or "34 MB" when the server sent no length.
fn megabytes(done: u64, total: u64) -> String {
const MB: u64 = 1024 * 1024;
diff --git a/crates/cartopolis/src/systems/gui/call_screen.rs b/crates/cartopolis/src/systems/gui/call_screen.rs
index a9e76f4a..8fd59833 100644
--- a/crates/cartopolis/src/systems/gui/call_screen.rs
+++ b/crates/cartopolis/src/systems/gui/call_screen.rs
@@ -1,5 +1,6 @@
//! The call screen: a call ringing, the call you are in, and the bar either
-//! folds down to (`systems::calls` is the call itself; this only draws it).
+//! folds down to (`systems::calls` is the call itself; this decides what of
+//! it shows, and `lib_call` draws it).
//!
//! Laid out the way Signal and WhatsApp lay theirs out, because that is the
//! screen everybody already knows how to use:
@@ -22,11 +23,9 @@
//! and the map stay usable during a call. Tapping the bar unfolds it. It is
//! never *ended* by a gesture: hanging up and declining are buttons.
//!
-//! Every surface here is an `Area` at `Order::Foreground` rather than part of a
-//! panel: a call rings over whichever panel is open, and must be hang-up-able
-//! from anywhere.
+//! The screen rings over whichever panel is open, and must be hang-up-able
+//! from anywhere: the library draws it over every other screen.
-use crate::systems::egui_manager::EguiMut;
use std::collections::{HashMap, HashSet};
use bevy::prelude::*;
@@ -34,10 +33,10 @@ use bevy::prelude::*;
use crate::resources::{AuthIdentity, OnlineSession};
use crate::systems::calls::{camera_available, CallRequest, Calls, Ringing, SELF_TILE};
use crate::systems::chat::ChatState;
-use crate::systems::chats::{paint_avatar, ChatKind};
use crate::systems::icons;
use crate::systems::private_chat::channel_key;
-use crate::systems::theme::{self, CallTone, CALL_BUTTON_LARGE, CALL_BUTTON_SMALL};
+use crate::systems::theme;
+use crate::systems::ui_input::UiMetrics;
use cartopolis_core::{CallAction, CallSettings};
/// How long the controls stay up over a picture after the last touch.
@@ -48,32 +47,31 @@ const NOTICE_SECS: f32 = 6.0;
const BAR_MAX_WIDTH: f32 = 440.0;
/// Inset of the screen's controls from its edges. More than the map's
/// `OSD_MARGIN` at the bottom: a phone's gesture bar lives there.
+#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub(crate) const EDGE: f32 = 16.0;
+#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub(crate) const BOTTOM_EDGE: f32 = 28.0;
// ─── The component library's edition (`lib_call`) ────────────────────────────
//
-// With `CallScreenLib::lib` on, this system still decides everything — what
-// rings, what shows, when the controls fade, who is large — but draws
-// nothing: it publishes a `CallView` each frame, and the library's system
-// draws it, with each video tile a `bevy:` image it writes the frames into.
-// A tap there comes back as a `CallAct` and is done by `apply`, which egui's
-// own buttons call too.
-
-/// The bridge to the library's call screen: whether it draws, what it
-/// draws, and the taps it handed back.
+// This system decides everything — what rings, what shows, when the controls
+// fade, who is large — and draws nothing: it publishes a `CallView` each
+// frame, and the library's system draws it, with each video tile a `bevy:`
+// image it writes the frames into. A tap there comes back as a `CallAct` and
+// is done by `apply`.
+
+/// The bridge to the library's call screen: what it draws, and the taps it
+/// handed back.
#[derive(Resource, Default)]
#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub struct CallScreenLib {
- /// The library draws the call screen; egui's system only decides.
- pub lib: bool,
/// What it draws this frame; `None` when nothing of a call shows.
pub view: Option<CallView>,
/// Taps from the library, done next frame by [`apply`].
pub acts: Vec<CallAct>,
}
-/// Everything of a call on screen, in egui points.
+/// Everything of a call on screen, in UI points.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub struct CallView {
@@ -130,7 +128,7 @@ pub struct PersonView {
pub reaction: Option<String>,
}
-/// The call you are in, as `in_call_screen` lays it out.
+/// The call you are in.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub struct InCallView {
@@ -378,15 +376,12 @@ pub enum CallAct {
ClearNotice,
}
-/// Do a tap on the call screen: the code egui's buttons run, for both
-/// editions.
-#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
+/// Do a tap on the call screen.
fn apply(
act: CallAct,
calls: &mut Calls,
st: &mut CallScreenState,
request: &mut Option<CallRequest>,
- ctx: &egui::Context,
) {
let now = || Some(web_time::Instant::now());
match act {
@@ -435,7 +430,7 @@ fn apply(
calls.camera_on = true;
}
}
- CallAct::CopyLink(link) => ctx.copy_text(link),
+ CallAct::CopyLink(link) => crate::utils::clipboard::set_text(&link),
CallAct::SplitRooms(n) => {
*request = Some(CallRequest::Control(split_into_rooms(calls, n)));
}
@@ -462,7 +457,6 @@ fn apply(
cartopolis_core::meeting::MeetingObject::Note { kind, text },
));
}
- st.note_draft.clear();
}
CallAct::PostRecord => calls.post_record_now(),
CallAct::BannerOpen => {
@@ -477,16 +471,10 @@ fn apply(
}
}
-/// The screen's own state between frames: textures and timers, nothing the
+/// The screen's own state between frames: timers and choices, nothing the
/// call needs.
#[derive(Default)]
pub struct CallScreenState {
- /// Each person's newest picture, uploaded only when it changed: a texture
- /// per person, reused, so a call is one small upload per picture received
- /// rather than a texture allocated per frame (`docs/notes/upload-bursts.md`).
- tiles: HashMap<u64, egui::TextureHandle>,
- /// Each shared screen's newest picture, the same way.
- screens: HashMap<u64, egui::TextureHandle>,
/// The sheet open over the call screen.
sheet: Option<Sheet>,
/// The person a host tapped in the people sheet.
@@ -497,8 +485,7 @@ pub struct CallScreenState {
big: Option<u64>,
/// Who was waiting at the last frame, to say when somebody new knocks.
waiting_seen: Vec<u64>,
- /// The note being written in the notes sheet, and what kind it is.
- note_draft: String,
+ /// The kind of note the notes sheet adds.
note_kind: Option<cartopolis_core::meeting::NoteKind>,
/// Calls that were ringing last frame, to unfold the screen for a new one.
ringing_before: HashSet<Vec<u8>>,
@@ -514,8 +501,6 @@ pub struct CallScreenState {
struct Person {
id: u64,
name: String,
- /// Their picture and its width over its height, when their camera is on.
- texture: Option<(egui::TextureId, f32)>,
speaking: bool,
/// A raised hand's place in the queue.
hand: Option<u32>,
@@ -535,10 +520,11 @@ enum Mode<'a> {
InCall,
}
-/// Draw the call screen, the folded bar, ringing banners and call notices.
+/// Decide the call screen, the folded bar, ringing banners and call notices,
+/// publish them for the library's edition (`lib_call`), and do the taps it
+/// handed back.
#[allow(clippy::too_many_arguments)]
-pub fn render_call_screen(
- mut egui: EguiMut,
+pub fn drive_call_screen(
mut calls: ResMut<Calls>,
identity: Res<AuthIdentity>,
chat: Res<ChatState>,
@@ -546,18 +532,17 @@ pub fn render_call_screen(
mut st: Local<CallScreenState>,
right_panel: Res<crate::resources::RightPanel>,
sheet: Res<crate::systems::chat_overlay::ChatOverlay>,
+ metrics: Res<UiMetrics>,
mut lib: Option<ResMut<CallScreenLib>>,
) {
calls.screen_shown = false;
- // The library's taps of last frame, done as egui's buttons do them.
- let lib_on = lib.as_ref().is_some_and(|l| l.lib);
+ // The library's taps of last frame.
if let Some(l) = lib.as_mut() {
if !l.acts.is_empty() {
let acts = std::mem::take(&mut l.acts);
- let ctx = egui.ctx_mut().clone();
let mut request = None;
for a in acts {
- apply(a, &mut calls, &mut st, &mut request, &ctx);
+ apply(a, &mut calls, &mut st, &mut request);
}
if request.is_some() {
calls.request = request;
@@ -565,7 +550,6 @@ pub fn render_call_screen(
}
}
if online.is_none() && !calls.demo {
- st.tiles.clear();
if let Some(l) = lib.as_mut() {
l.view = None;
}
@@ -601,29 +585,19 @@ pub fn render_call_screen(
}
if ringing.is_empty() && active.is_none() && calls.notice.is_none() {
- st.tiles.clear();
if let Some(l) = lib.as_mut() {
l.view = None;
}
return;
}
- let ctx = egui.ctx_mut().clone();
// Folded over the map, the call is a row of tiles at the top of it
// (`docs/mockups/chat-overlay`, v3); over a panel that is the whole
- // screen it is the green bar, and the bar shows no picture: leave the
- // newest waiting (`fresh`) for when the screen comes back rather than
- // upload it unseen. The library's edition writes the pictures itself
- // (`lib_call`), into images of its own.
- let map_shown = !(egui.compact() && !right_panel.is(crate::resources::RightPanel::None));
+ // screen it is the green bar, and the bar shows no picture: the newest
+ // is left waiting (`fresh`) for when the screen comes back. The
+ // library's edition writes the pictures itself (`lib_call`).
+ let map_shown = !(metrics.compact() && !right_panel.is(crate::resources::RightPanel::None));
let tiles_shown = calls.minimized && active.is_some() && map_shown;
- if lib_on {
- st.tiles.clear();
- st.screens.clear();
- } else if !calls.minimized || tiles_shown {
- let CallScreenState { tiles, screens, .. } = &mut *st;
- upload_pictures(&ctx, &mut calls, tiles, screens);
- }
let label_of = |group: &[u8]| {
let key = channel_key(group);
@@ -632,10 +606,7 @@ pub fn render_call_screen(
.find(|c| c.key == key)
.map(|c| crate::systems::private_chat::peer_of_label(&c.label).to_string())
};
- let viewport = egui.viewport_pts();
- let full = egui::Rect::from_min_size(egui::Pos2::ZERO, viewport);
- let mut request = None;
- let mut clear_notice = false;
+ let viewport = metrics.viewport_pts();
// ── The full screen ────────────────────────────────────────────────────
// The controls come up whenever the call screen does (a call starting, or
@@ -653,104 +624,8 @@ pub fn render_call_screen(
} else {
ringing.first().map(Mode::Incoming)
};
- if lib_on {
- if mode.is_some() {
- calls.screen_shown = true;
- // Wakes for the pulse, the timer and the controls' fade.
- ctx.request_repaint_after(std::time::Duration::from_millis(50));
- }
- let top = if chat.sharing.is_empty() {
- theme::OSD_MARGIN
- } else {
- theme::OSD_MARGIN + 44.0
- };
- let bar_width = (viewport.x - 2.0 * theme::OSD_MARGIN).min(BAR_MAX_WIDTH);
- let banners: Vec<&Ringing> = match &mode {
- Some(Mode::Incoming(first)) => {
- ringing.iter().filter(|r| r.group != first.group).collect()
- }
- _ => ringing.iter().collect(),
- };
- let strip_open = active.as_ref().is_some_and(|group| {
- let key = channel_key(group);
- sheet.composing && chat.channels.get(chat.active).is_some_and(|c| c.key == key)
- });
- let view = lib_view(
- &mut calls,
- &mut st,
- &chat,
- &label_of,
- mode.as_ref(),
- &banners,
- active.as_deref(),
- LibTop {
- top,
- width: bar_width,
- tiles_shown,
- strip_open,
- },
- viewport,
- );
- if let Some(l) = lib.as_mut() {
- if l.view.as_ref() != Some(&view) {
- l.view = Some(view);
- }
- }
- if request.is_some() {
- calls.request = request;
- }
- return;
- }
- if let Some(mode) = &mode {
+ if mode.is_some() {
calls.screen_shown = true;
- egui::Area::new(egui::Id::new("call_screen"))
- .fixed_pos(egui::Pos2::ZERO)
- .order(egui::Order::Foreground)
- .show(&ctx, |ui| {
- theme::dark_here(|| {
- // Dark in both themes, as a phone's call screen is.
- theme::use_dark_visuals(ui);
- ui.set_clip_rect(full);
- // Swallow every touch the controls do not take, so nothing
- // reaches the map or the panels underneath.
- let backdrop = ui.allocate_rect(full, egui::Sense::click());
- let backdrop = theme::named(ui, backdrop, "Show or hide the controls");
- ui.painter().rect_filled(full, 0.0, theme::p32().ink);
- match mode {
- Mode::Incoming(r) => {
- let chat_label = label_of(&r.group);
- if incoming_screen(ui, full, r, chat_label.as_deref(), &mut request) {
- calls.minimized = true;
- }
- }
- Mode::InCall => {
- if backdrop.clicked() {
- st.controls = !st.controls;
- st.touched = Some(web_time::Instant::now());
- }
- let group = active.clone().unwrap_or_default();
- let key = channel_key(&group);
- let lines = chat
- .channels
- .iter()
- .find(|c| c.key == key)
- .map_or(&[][..], |c| c.lines.as_slice());
- in_call_screen(
- ui,
- full,
- &mut calls,
- &mut st,
- label_of(&group),
- &me,
- lines,
- &mut request,
- );
- }
- }
- // Repaint for the pulse, the timer and the controls' fade.
- ctx.request_repaint_after(std::time::Duration::from_millis(50));
- })
- });
}
// ── The folded bar and the banners at the top ──────────────────────────
@@ -766,202 +641,33 @@ pub fn render_call_screen(
Some(Mode::Incoming(first)) => ringing.iter().filter(|r| r.group != first.group).collect(),
_ => ringing.iter().collect(),
};
- let folded_call = calls.minimized && active.is_some();
- let notice = st.notice.as_ref().map(|(n, _)| n.clone());
- if folded_call || !banners.is_empty() || notice.is_some() {
- egui::Area::new(egui::Id::new("call_bar"))
- .anchor(egui::Align2::CENTER_TOP, egui::vec2(0.0, top))
- .order(egui::Order::Foreground)
- .show(&ctx, |ui| {
- // Pinned, never left to the contents: a size-to-content `Area`
- // that centres anything feeds its own width back and grows
- // (`hud`'s module note).
- ui.set_width(bar_width);
- ui.spacing_mut().item_spacing.y = 6.0;
- if folded_call {
- let group = active.clone().unwrap_or_default();
- // The chat sheet open on this call's chat carries its
- // keys in a strip; the tiles then need only the way back.
- let key = channel_key(&group);
- let strip_open = sheet.composing
- && chat.channels.get(chat.active).is_some_and(|c| c.key == key);
- let unfold = if tiles_shown {
- folded_tiles(ui, bar_width, &mut calls, &st, !strip_open, &mut request)
- } else {
- folded_bar(
- ui,
- bar_width,
- &mut calls,
- label_of(&group),
- &me,
- &mut request,
- )
- };
- if unfold {
- calls.minimized = false;
- st.controls = true;
- st.touched = Some(web_time::Instant::now());
- }
- }
- for r in &banners {
- let chat_label = label_of(&r.group);
- if ringing_banner(
- ui,
- bar_width,
- r,
- chat_label.as_deref(),
- active.is_some(),
- &mut request,
- ) && active.is_none()
- {
- calls.minimized = false;
- }
- }
- if let Some(text) = ¬ice {
- if notice_chip(ui, bar_width, text) {
- clear_notice = true;
- }
- }
- });
- }
-
- if request.is_some() {
- calls.request = request;
- }
- if clear_notice {
- calls.notice = None;
- st.notice = None;
- }
-}
-
-/// Upload each person's newest picture, and forget the textures of anybody no
-/// longer sending.
-fn upload_pictures(
- ctx: &egui::Context,
- calls: &mut Calls,
- tiles: &mut HashMap<u64, egui::TextureHandle>,
- screens: &mut HashMap<u64, egui::TextureHandle>,
-) {
- upload(ctx, calls.pictures_mut(), tiles, "call-video");
- upload(ctx, calls.screens_mut(), screens, "call-screen");
-}
-
-fn upload<'a>(
- ctx: &egui::Context,
- pictures: impl Iterator<Item = (u64, &'a mut crate::systems::calls::Picture)>,
- tiles: &mut HashMap<u64, egui::TextureHandle>,
- name: &str,
-) {
- let mut present = HashSet::new();
- for (id, p) in pictures {
- present.insert(id);
- if !p.fresh {
- continue;
- }
- p.fresh = false;
- // Opaque pictures are premultiplied already, which skips the
- // per-pixel multiply `from_rgba_unmultiplied` would do.
- let image = egui::ColorImage::from_rgba_premultiplied(
- [p.width as usize, p.height as usize],
- &p.rgba,
- );
- match tiles.get_mut(&id) {
- Some(t) => t.set(image, egui::TextureOptions::LINEAR),
- None => {
- let t =
- ctx.load_texture(format!("{name}-{id}"), image, egui::TextureOptions::LINEAR);
- tiles.insert(id, t);
- }
+ // The chat sheet open on this call's chat carries its keys in a strip;
+ // the tiles then need only the way back.
+ let strip_open = active.as_ref().is_some_and(|group| {
+ let key = channel_key(group);
+ sheet.composing && chat.channels.get(chat.active).is_some_and(|c| c.key == key)
+ });
+ let view = lib_view(
+ &mut calls,
+ &mut st,
+ &chat,
+ &label_of,
+ mode.as_ref(),
+ &banners,
+ active.as_deref(),
+ LibTop {
+ top,
+ width: bar_width,
+ tiles_shown,
+ strip_open,
+ },
+ viewport,
+ );
+ if let Some(l) = lib.as_mut() {
+ if l.view.as_ref() != Some(&view) {
+ l.view = Some(view);
}
}
- tiles.retain(|id, _| present.contains(id));
-}
-
-fn texture_of(
- tiles: &HashMap<u64, egui::TextureHandle>,
- id: u64,
-) -> Option<(egui::TextureId, f32)> {
- tiles.get(&id).map(|t| {
- let [w, h] = t.size();
- (t.id(), w as f32 / h.max(1) as f32)
- })
-}
-
-/// The part of a picture of shape `aspect` that fills `rect` when cropped to
-/// it, centred.
-fn cover_uv(aspect: f32, rect: egui::Rect) -> egui::Rect {
- let target = rect.width() / rect.height().max(1.0);
- if aspect > target {
- let w = target / aspect;
- egui::Rect::from_min_max(
- egui::pos2((1.0 - w) * 0.5, 0.0),
- egui::pos2((1.0 + w) * 0.5, 1.0),
- )
- } else {
- let h = aspect / target;
- egui::Rect::from_min_max(
- egui::pos2(0.0, (1.0 - h) * 0.5),
- egui::pos2(1.0, (1.0 + h) * 0.5),
- )
- }
-}
-
-/// The largest rect of shape `aspect` inside `rect`, centred.
-pub(crate) fn contain(aspect: f32, rect: egui::Rect) -> egui::Rect {
- let target = rect.width() / rect.height().max(1.0);
- let size = if aspect > target {
- egui::vec2(rect.width(), rect.width() / aspect)
- } else {
- egui::vec2(rect.height() * aspect, rect.height())
- };
- egui::Rect::from_center_size(rect.center(), size)
-}
-
-/// Paint a picture into `rect`, cropped to fill it — always on a portrait
-/// screen, which is a phone, where a call is full-screen video whatever the
-/// other camera sends. Only an upright picture on a wide window (a phone
-/// calling a desktop) is letterboxed, or it would be cut to a strip.
-fn paint_picture(
- ui: &egui::Ui,
- rect: egui::Rect,
- (id, aspect): (egui::TextureId, f32),
- radius: u8,
- always_fill: bool,
-) {
- let tall_picture_on_wide_rect = aspect < 1.0 && rect.width() > rect.height();
- let (rect, uv) = if always_fill || !tall_picture_on_wide_rect {
- (rect, cover_uv(aspect, rect))
- } else {
- (
- contain(aspect, rect),
- egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)),
- )
- };
- egui::Image::new((id, rect.size()))
- .uv(uv)
- .corner_radius(egui::CornerRadius::same(radius))
- .paint_at(ui, rect);
-}
-
-/// A vertical shade over a picture's top or bottom edge, so white text and
-/// controls read on any picture.
-fn paint_shade(p: &egui::Painter, rect: egui::Rect, dark_at_top: bool) {
- let dark = egui::Color32::from_black_alpha(150);
- let clear = egui::Color32::TRANSPARENT;
- let (top, bottom) = if dark_at_top {
- (dark, clear)
- } else {
- (clear, dark)
- };
- let mut mesh = egui::Mesh::default();
- let i = mesh.vertices.len() as u32;
- mesh.colored_vertex(rect.left_top(), top);
- mesh.colored_vertex(rect.right_top(), top);
- mesh.colored_vertex(rect.right_bottom(), bottom);
- mesh.colored_vertex(rect.left_bottom(), bottom);
- mesh.add_triangle(i, i + 1, i + 2);
- mesh.add_triangle(i, i + 2, i + 3);
- p.add(mesh);
}
/// A call's status line: the timer once it is up, or where it has got to.
@@ -977,570 +683,6 @@ fn status_line(calls: &Calls, others: usize) -> String {
}
}
-/// Text centred at `pos`, one line.
-fn centred(p: &egui::Painter, pos: egui::Pos2, text: &str, size: f32, color: egui::Color32) {
- p.text(
- pos,
- egui::Align2::CENTER_CENTER,
- text,
- egui::FontId::proportional(size),
- color,
- );
-}
-
-/// A call button placed with its centre at `c`.
-fn button_at(
- ui: &mut egui::Ui,
- c: egui::Pos2,
- icon: &str,
- tip: &str,
- tone: CallTone,
- d: f32,
-) -> bool {
- let rect = egui::Rect::from_center_size(c, egui::Vec2::splat(d));
- ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
- theme::call_button(ui, icon, tip, tone, d).clicked()
- })
- .inner
-}
-
-/// The fold-down arrow in the top-left corner.
-fn fold_button(ui: &mut egui::Ui, full: egui::Rect) -> bool {
- let d = 40.0;
- let c = egui::pos2(full.min.x + EDGE + d * 0.5, full.min.y + EDGE + d * 0.5);
- let rect = egui::Rect::from_center_size(c, egui::Vec2::splat(d));
- let resp = ui.interact(rect, egui::Id::new("call_fold"), egui::Sense::click());
- let resp = theme::named(ui, resp, "Back to the app")
- .on_hover_text("Back to the app — the call carries on");
- let p = ui.painter();
- if resp.hovered() {
- p.circle_filled(c, d * 0.5, egui::Color32::from_white_alpha(30));
- }
- centred(p, c, icons::BACK, 24.0, theme::p32().cream);
- resp.clicked()
-}
-
-/// The lock line every call screen carries: what makes it a private call.
-fn encrypted_line(p: &egui::Painter, pos: egui::Pos2, agent: bool) {
- // An agent's end of the call is the agent: what it hears goes on to a
- // model provider, and the person talking to it should see that before
- // saying anything (`docs/mockups/voice-agent/`).
- let (text, colour) = if agent {
- (
- format!("{} AI agent · what you say goes to OpenAI", icons::LOCK),
- theme::p32().warn,
- )
- } else {
- (
- format!("{} End-to-end encrypted", icons::LOCK),
- theme::p32().text_dim,
- )
- };
- centred(p, pos, &text, theme::SIZE_SUB, colour);
-}
-
-/// A call coming in, over the whole screen.
-fn incoming_screen(
- ui: &mut egui::Ui,
- full: egui::Rect,
- r: &Ringing,
- chat_label: Option<&str>,
- request: &mut Option<CallRequest>,
-) -> bool {
- let name = r.who.join(", ");
- let p = ui.painter().clone();
- let x = full.center().x;
- let h = full.height();
- let disc_c = egui::pos2(x, full.min.y + h * 0.30);
- let disc = (full.width().min(h) * 0.34).clamp(96.0, 150.0);
- // A slow pulse around the initial: the screen is ringing, not frozen.
- let t = ui.input(|i| i.time) as f32;
- for k in 0..2 {
- let phase = ((t * 0.6) + k as f32 * 0.5).fract();
- let radius = disc * 0.5 * (1.0 + phase * 0.55);
- let alpha = ((1.0 - phase) * 60.0) as u8;
- p.circle_stroke(
- disc_c,
- radius,
- egui::Stroke::new(2.0, egui::Color32::from_white_alpha(alpha)),
- );
- }
- paint_avatar(&p, disc_c, &name, ChatKind::Private, disc);
- let below = disc_c.y + disc * 0.5;
- centred(
- &p,
- egui::pos2(x, below + 40.0),
- &name,
- 28.0,
- theme::p32().cream,
- );
- let what = match chat_label {
- Some(chat) if !chat.eq_ignore_ascii_case(&name) => format!("Incoming call · {chat}"),
- _ => "Incoming call".to_string(),
- };
- centred(
- &p,
- egui::pos2(x, below + 72.0),
- &what,
- theme::SIZE_BODY,
- theme::p32().text,
- );
- encrypted_line(&p, egui::pos2(x, below + 96.0), r.agent);
-
- // Folded, it keeps ringing as a banner at the top.
- let folded = fold_button(ui, full);
-
- // Decline left, Answer right, at thumb height.
- let row_y = full.max.y - BOTTOM_EDGE - CALL_BUTTON_LARGE * 0.5 - 28.0;
- let spread = (full.width() * 0.26).clamp(70.0, 150.0);
- let decline = egui::pos2(x - spread, row_y);
- let answer = egui::pos2(x + spread, row_y);
- if button_at(
- ui,
- decline,
- icons::CALL_END,
- "Decline",
- CallTone::HangUp,
- CALL_BUTTON_LARGE,
- ) {
- *request = Some(CallRequest::Dismiss(r.group.clone()));
- }
- if button_at(
- ui,
- answer,
- icons::CALL,
- "Answer",
- CallTone::Accept,
- CALL_BUTTON_LARGE,
- ) {
- *request = Some(CallRequest::Join(r.group.clone()));
- }
- let label_y = row_y + CALL_BUTTON_LARGE * 0.5 + 16.0;
- centred(
- &p,
- egui::pos2(decline.x, label_y),
- "Decline",
- theme::SIZE_SUB,
- theme::p32().text,
- );
- centred(
- &p,
- egui::pos2(answer.x, label_y),
- "Answer",
- theme::SIZE_SUB,
- theme::p32().text,
- );
- folded
-}
-
-/// The call you are in, over the whole screen.
-#[allow(clippy::too_many_arguments)]
-fn in_call_screen(
- ui: &mut egui::Ui,
- full: egui::Rect,
- calls: &mut Calls,
- st: &mut CallScreenState,
- chat_label: Option<String>,
- me: &str,
- lines: &[crate::systems::chat::ChatLine],
- request: &mut Option<CallRequest>,
-) {
- if calls.waiting_to_join() {
- waiting_screen(ui, full, calls, st, chat_label.as_deref(), request);
- return;
- }
- // Somebody new knocking is news to a host, wherever the people sheet is.
- let waiting = calls.extras().waiting;
- if calls.hosting() {
- if let Some(w) = waiting
- .iter()
- .find(|w| !st.waiting_seen.contains(&w.participant))
- {
- calls.notice = Some(format!(
- "{} is waiting to join. Admit them under People.",
- w.username
- ));
- }
- }
- st.waiting_seen = waiting.iter().map(|w| w.participant).collect();
- let mut people: Vec<Person> = calls
- .others()
- .into_iter()
- .map(|(id, name)| person_of(calls, &st.tiles, id, name))
- .collect();
- // A breakout room shows only who is in it.
- let my_room = calls.me().map_or(0, |m| m.room);
- people.retain(|p| calls.member(p.id).map_or(0, |m| m.room) == my_room);
- people.sort_by(|a, b| a.name.cmp(&b.name));
- let own = texture_of(&st.tiles, SELF_TILE);
- let sharer = calls.sharer();
- let screen = sharer.and_then(|s| texture_of(&st.screens, s));
- let any_picture = screen.is_some()
- || people.iter().any(|p| p.texture.is_some())
- || (people.is_empty() && own.is_some());
- // Over a picture the controls fade after a while; over initials they stay,
- // and so do they while a sheet is open.
- if !any_picture || st.sheet.is_some() {
- st.controls = true;
- } else if st
- .touched
- .is_none_or(|t| t.elapsed().as_secs_f32() > CONTROLS_HIDE_SECS)
- {
- st.controls = false;
- }
- let show_controls = st.controls;
-
- let p = ui.painter().clone();
- let x = full.center().x;
- let status = status_line(calls, people.len());
- let title = if people.is_empty() || people.len() > 3 {
- chat_label.unwrap_or_else(|| "Calling…".into())
- } else {
- people
- .iter()
- .map(|p| p.name.as_str())
- .collect::<Vec<_>>()
- .join(", ")
- };
- let mut self_person = person_of(calls, &st.tiles, SELF_TILE, "You".into());
- self_person.muted = calls.muted;
- self_person.speaking = calls.speaking(SELF_TILE);
-
- // ── The stage ──────────────────────────────────────────────────────────
- let top_room = 72.0;
- let bottom_room = CALL_BUTTON_LARGE + BOTTOM_EDGE + 30.0;
- let stage = egui::Rect::from_min_max(
- egui::pos2(full.min.x + 8.0, full.min.y + top_room),
- egui::pos2(full.max.x - 8.0, full.max.y - bottom_room),
- );
- let mut pip = own;
- let mut centre_title = false;
- if let (Some(tex), Some(who)) = (screen, sharer) {
- // A shared screen is the stage: drawn whole, never cropped, with
- // everybody (you too) in a strip beside it or under it.
- pip = None;
- let portrait = stage.height() > stage.width();
- let mut tiles: Vec<&Person> = people.iter().collect();
- tiles.push(&self_person);
- let (screen_rect, strip) = if portrait {
- let h = (stage.width() / tex.1.max(0.1)).min(stage.height() * 0.55);
- let screen_rect = egui::Rect::from_min_size(stage.min, egui::vec2(stage.width(), h));
- let strip = egui::Rect::from_min_max(
- egui::pos2(stage.min.x, screen_rect.max.y + 8.0),
- stage.max,
- );
- (screen_rect, strip)
- } else {
- let w = (stage.width() * 0.78).min(stage.width() - 160.0);
- let screen_rect = egui::Rect::from_min_size(stage.min, egui::vec2(w, stage.height()));
- let strip = egui::Rect::from_min_max(
- egui::pos2(screen_rect.max.x + 8.0, stage.min.y),
- stage.max,
- );
- (screen_rect, strip)
- };
- p.rect_filled(screen_rect, 14.0, egui::Color32::from_black_alpha(160));
- let shown = contain(tex.1, screen_rect);
- egui::Image::new((tex.0, shown.size()))
- .corner_radius(egui::CornerRadius::same(10))
- .paint_at(ui, shown);
- let name = calls.name_of(who).unwrap_or("Somebody").to_string();
- let chip_text = format!("{} {name} is presenting", icons::SCREEN_SHARE);
- name_chip(
- &p,
- egui::pos2(screen_rect.min.x + 8.0, screen_rect.min.y + 8.0),
- &chip_text,
- false,
- );
- let cols = if portrait { 2 } else { 1 };
- grid(ui, strip, &tiles, cols);
- } else if let Some(big) = speaker_of(calls, st, &people) {
- // One person large (the spotlight, or whoever talks), everybody else
- // in a row under them.
- pip = None;
- let strip_h = (stage.height() * 0.22).clamp(70.0, 150.0);
- let big_rect = egui::Rect::from_min_max(
- stage.min,
- egui::pos2(stage.max.x, stage.max.y - strip_h - 8.0),
- );
- let strip =
- egui::Rect::from_min_max(egui::pos2(stage.min.x, stage.max.y - strip_h), stage.max);
- let big_person = people
- .iter()
- .find(|p| p.id == big)
- .expect("chosen from people");
- grid(ui, big_rect, &[big_person], 1);
- let mut rest: Vec<&Person> = people.iter().filter(|p| p.id != big).collect();
- rest.push(&self_person);
- let cols = rest.len();
- grid(ui, strip, &rest, cols);
- } else {
- match people.len() {
- 0 => {
- // Still ringing them: your own camera is the backdrop, if it is on.
- if let Some(tex) = own {
- paint_picture(ui, full, tex, 0, true);
- p.rect_filled(full, 0.0, egui::Color32::from_black_alpha(70));
- pip = None;
- }
- centre_title = true;
- }
- 1 => {
- let person = &people[0];
- match person.texture {
- Some(tex) => {
- paint_picture(ui, full, tex, 0, false);
- tile_badges(&p, stage, person);
- }
- None => centre_title = true,
- }
- }
- _ => {
- // You are one of the tiles in a group, last, rather than a
- // window laid over somebody else's.
- pip = None;
- let mut tiles: Vec<&Person> = people.iter().collect();
- tiles.push(&self_person);
- let n = tiles.len();
- let portrait = stage.height() > stage.width();
- let cols = if portrait {
- if n <= 3 {
- 1
- } else {
- 2
- }
- } else {
- (n as f32).sqrt().ceil() as usize
- };
- grid(ui, stage, &tiles, cols);
- }
- }
- }
- if centre_title {
- // No picture to look at: the person, large, in the middle.
- let disc = (full.width().min(full.height()) * 0.34).clamp(96.0, 150.0);
- let c = egui::pos2(x, full.min.y + full.height() * 0.34);
- let speaking = people.first().is_some_and(|p| p.speaking);
- if speaking {
- p.circle_stroke(
- c,
- disc * 0.5 + 6.0,
- egui::Stroke::new(3.0, theme::p32().accent_ring),
- );
- }
- paint_avatar(&p, c, &title, ChatKind::Private, disc);
- if let Some(r) = people.first().and_then(|p| p.reaction.as_deref()) {
- centred(
- &p,
- c + egui::vec2(disc * 0.42, disc * 0.36),
- r,
- 40.0,
- theme::p32().cream,
- );
- }
- centred(
- &p,
- egui::pos2(x, c.y + disc * 0.5 + 40.0),
- &title,
- 28.0,
- theme::p32().cream,
- );
- centred(
- &p,
- egui::pos2(x, c.y + disc * 0.5 + 72.0),
- &status,
- theme::SIZE_BODY,
- theme::p32().text,
- );
- }
-
- // ── Your own picture, in the corner ────────────────────────────────────
- if let Some(tex) = pip {
- let w = (full.width() * 0.28).clamp(90.0, 180.0);
- let h = w / tex.1.max(0.1);
- let h = h.min(full.height() * 0.32);
- let w = h * tex.1;
- let top = if show_controls {
- full.min.y + 76.0
- } else {
- full.min.y + EDGE
- };
- let rect =
- egui::Rect::from_min_size(egui::pos2(full.max.x - EDGE - w, top), egui::vec2(w, h));
- p.rect_filled(rect.expand(1.0), 13.0, egui::Color32::from_black_alpha(120));
- paint_picture(ui, rect, tex, 12, true);
- p.rect_stroke(
- rect,
- 12.0,
- egui::Stroke::new(1.0, egui::Color32::from_white_alpha(60)),
- egui::StrokeKind::Outside,
- );
- if calls.muted {
- let badge = egui::pos2(rect.min.x + 16.0, rect.max.y - 16.0);
- p.circle_filled(badge, 12.0, theme::p32().cream);
- centred(&p, badge, icons::MIC_OFF, 14.0, theme::p32().ink);
- }
- if let Some(r) = calls.reaction_of(SELF_TILE) {
- centred(
- &p,
- egui::pos2(rect.max.x - 18.0, rect.max.y - 20.0),
- &r.emoji,
- 26.0,
- theme::p32().cream,
- );
- }
- }
-
- if show_controls {
- // ── The top: fold, name, timer, people ─────────────────────────────
- if any_picture {
- paint_shade(
- &p,
- egui::Rect::from_min_size(full.min, egui::vec2(full.width(), 120.0)),
- true,
- );
- paint_shade(
- &p,
- egui::Rect::from_min_max(egui::pos2(full.min.x, full.max.y - 180.0), full.max),
- false,
- );
- }
- if fold_button(ui, full) {
- calls.minimized = true;
- }
- if people_button(ui, full, calls) {
- st.sheet = Some(Sheet::People);
- st.picked = None;
- }
- if centre_title {
- encrypted_line(
- &p,
- egui::pos2(x, full.min.y + EDGE + 20.0),
- calls.with_agent(),
- );
- } else {
- centred(
- &p,
- egui::pos2(x, full.min.y + EDGE + 14.0),
- &title,
- theme::SIZE_HEADING,
- theme::p32().cream,
- );
- centred(
- &p,
- egui::pos2(x, full.min.y + EDGE + 38.0),
- &format!("{} {status}", icons::LOCK),
- theme::SIZE_SUB,
- theme::p32().text,
- );
- }
- dock(ui, full, calls, st, request);
- meeting_chips(ui, full, calls, request);
- }
- let _ = me;
-
- // ── Captions, above the keys, whether or not the keys show ─────────────
- if let Some((who, text)) = calls.caption_now() {
- let width = (full.width() - 2.0 * EDGE).min(640.0);
- let galley = p.layout(
- text,
- egui::FontId::proportional(theme::SIZE_BODY + 2.0),
- theme::p32().cream,
- width - 28.0,
- );
- let h = galley.size().y + 30.0;
- let bottom = if show_controls {
- full.max.y - BOTTOM_EDGE - CALL_BUTTON_LARGE - 40.0
- } else {
- full.max.y - BOTTOM_EDGE
- };
- let rect = egui::Rect::from_min_size(
- egui::pos2(full.center().x - width * 0.5, bottom - h),
- egui::vec2(width, h),
- );
- p.rect_filled(
- rect,
- egui::CornerRadius::same(14),
- egui::Color32::from_black_alpha(205),
- );
- p.text(
- rect.min + egui::vec2(14.0, 8.0),
- egui::Align2::LEFT_TOP,
- who,
- egui::FontId::proportional(theme::SIZE_TINY),
- theme::p32().accent_ring,
- );
- p.galley(
- rect.min + egui::vec2(14.0, 24.0),
- galley,
- theme::p32().cream,
- );
- }
-
- // ── A sheet over it all ────────────────────────────────────────────────
- if let Some(sheet) = st.sheet {
- let shade = ui.interact(
- full,
- egui::Id::new("call_sheet_shade"),
- egui::Sense::click(),
- );
- let shade = theme::named(ui, shade, "Dismiss");
- p.rect_filled(full, 0.0, egui::Color32::from_black_alpha(140));
- let width = full.width().min(520.0);
- let left = full.center().x - width * 0.5;
- let max_h = full.height() * 0.8;
- let mut close = shade.clicked();
- let _ = left;
- egui::Area::new(egui::Id::new("call_sheet"))
- .order(egui::Order::Foreground)
- .anchor(egui::Align2::CENTER_BOTTOM, egui::Vec2::ZERO)
- .show(ui.ctx(), |ui| {
- theme::use_dark_visuals(ui);
- ui.set_width(width);
- ui.set_max_height(max_h);
- let frame = egui::Frame::NONE
- .fill(theme::p32().surface)
- .stroke(egui::Stroke::new(1.0, theme::p32().overlay_line))
- .corner_radius(egui::CornerRadius {
- nw: 22,
- ne: 22,
- sw: 0,
- se: 0,
- })
- .inner_margin(egui::Margin {
- left: 16,
- right: 16,
- top: 10,
- bottom: 28,
- });
- // Pinned to the bottom edge whatever its height.
- frame.show(ui, |ui| {
- ui.set_width(width - 32.0);
- let (grab, _) = ui
- .allocate_exact_size(egui::vec2(width - 32.0, 14.0), egui::Sense::hover());
- ui.painter().rect_filled(
- egui::Rect::from_center_size(grab.center(), egui::vec2(38.0, 5.0)),
- 3.0,
- theme::p32().text_dim,
- );
- egui::ScrollArea::vertical().max_height(max_h - 60.0).show(
- ui,
- |ui| match sheet {
- Sheet::More => more_sheet(ui, calls, st, request, &mut close),
- Sheet::People => people_sheet(ui, calls, st, request),
- Sheet::Leave => leave_sheet(ui, calls, request, &mut close),
- Sheet::Notes => notes_sheet(ui, calls, st, lines, request),
- },
- );
- });
- });
- if close {
- st.sheet = None;
- st.picked = None;
- }
- }
-}
-
/// The sheet open over the call screen.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Sheet {
@@ -1555,15 +697,11 @@ pub enum Sheet {
}
/// The reactions offered, in the order the row shows them.
+#[cfg_attr(not(feature = "ui-lib"), allow(dead_code))]
pub(crate) const REACTIONS: [&str; 6] = ["👍", "👏", "😂", "❤", "🎉", "😮"];
/// Somebody on the call screen, from the call's roster.
-fn person_of(
- calls: &Calls,
- tiles: &HashMap<u64, egui::TextureHandle>,
- id: u64,
- name: String,
-) -> Person {
+fn person_of(calls: &Calls, id: u64, name: String) -> Person {
let member = if id == SELF_TILE {
calls.me()
} else {
@@ -1571,7 +709,6 @@ fn person_of(
};
Person {
id,
- texture: texture_of(tiles, id),
speaking: calls.speaking(id),
hand: member.and_then(|m| m.hand),
muted: member.is_some_and(|m| m.muted),
@@ -1582,1442 +719,55 @@ fn person_of(
}
}
-/// Lay `tiles` out in an even grid of `cols` columns over `area`.
-fn grid(ui: &egui::Ui, area: egui::Rect, tiles: &[&Person], cols: usize) {
- let n = tiles.len().max(1);
- let cols = cols.clamp(1, n);
- let rows = n.div_ceil(cols);
- let gap = 8.0;
- let cell = egui::vec2(
- (area.width() - gap * (cols - 1) as f32) / cols as f32,
- (area.height() - gap * (rows - 1) as f32) / rows as f32,
- );
- for (i, person) in tiles.iter().enumerate() {
- let (r, c) = (i / cols, i % cols);
- let rect = egui::Rect::from_min_size(
- area.min + egui::vec2(c as f32 * (cell.x + gap), r as f32 * (cell.y + gap)),
- cell,
- );
- grid_tile(ui, rect, person);
+/// Who is large in Speaker view, if it is on: the hosts' spotlight first,
+/// then whoever is talking, kept until somebody else talks. Needs two others,
+/// or the one other person fills the screen anyway.
+fn speaker_of(calls: &Calls, st: &mut CallScreenState, people: &[Person]) -> Option<u64> {
+ if let Some(s) = calls.extras().spotlight {
+ if people.iter().any(|p| p.id == s) {
+ return Some(s);
+ }
}
-}
-
-/// A name on a dark chip with its top-left at `at`, as tiles carry it.
-fn name_chip(p: &egui::Painter, at: egui::Pos2, text: &str, bottom: bool) -> egui::Rect {
- let galley = p.layout_no_wrap(
- text.to_string(),
- egui::FontId::proportional(theme::SIZE_SUB),
- theme::p32().cream,
- );
- let pad = egui::vec2(8.0, 3.0);
- let size = galley.size() + 2.0 * pad;
- let min = if bottom {
- at - egui::vec2(0.0, size.y)
- } else {
- at
- };
- let chip = egui::Rect::from_min_size(min, size);
- p.rect_filled(
- chip,
- egui::CornerRadius::same(theme::RADIUS_PILL),
- egui::Color32::from_black_alpha(160),
- );
- p.galley(chip.min + pad, galley, theme::p32().cream);
- chip
-}
-
-/// What a tile says about its person besides the picture: the name with the
-/// microphone's state, a raised hand's place in the queue, a reaction.
-fn tile_badges(p: &egui::Painter, rect: egui::Rect, person: &Person) {
- let mic = if person.held {
- format!("{} ", icons::LOCK)
- } else if person.muted {
- format!("{} ", icons::MIC_OFF)
- } else {
- String::new()
- };
- let host = if person.host {
- format!(" {}", icons::HOST)
- } else {
- String::new()
- };
- name_chip(
- p,
- egui::pos2(rect.min.x + 8.0, rect.max.y - 8.0),
- &format!("{mic}{}{host}", person.name),
- true,
- );
- if let Some(n) = person.hand {
- let text = format!("{} {n}", icons::HAND);
- let galley = p.layout_no_wrap(
- text,
- egui::FontId::proportional(theme::SIZE_SUB),
- theme::p32().ink,
- );
- let pad = egui::vec2(8.0, 3.0);
- let chip =
- egui::Rect::from_min_size(rect.min + egui::vec2(8.0, 8.0), galley.size() + 2.0 * pad);
- p.rect_filled(
- chip,
- egui::CornerRadius::same(theme::RADIUS_PILL),
- theme::p32().warn,
- );
- p.galley(chip.min + pad, galley, theme::p32().ink);
+ if !st.speaker_view || people.len() < 2 {
+ return None;
}
- if let Some(r) = &person.reaction {
- centred(
- p,
- egui::pos2(rect.max.x - 26.0, rect.max.y - 30.0),
- r,
- 34.0,
- theme::p32().cream,
- );
+ if let Some(talking) = people.iter().find(|p| p.speaking) {
+ st.big = Some(talking.id);
+ }
+ match st.big {
+ Some(b) if people.iter().any(|p| p.id == b) => Some(b),
+ _ => people.first().map(|p| p.id),
}
}
-/// One person in a group call's grid.
-fn grid_tile(ui: &egui::Ui, rect: egui::Rect, person: &Person) {
- let p = ui.painter();
- let radius = 14u8;
- match person.texture {
- Some(tex) => paint_picture(ui, rect, tex, radius, true),
- None => {
- p.rect_filled(rect, radius, theme::p32().surface_raised);
- let d = (rect.width().min(rect.height()) * 0.42).clamp(32.0, 120.0);
- paint_avatar(p, rect.center(), &person.name, ChatKind::Private, d);
- }
- }
- tile_badges(p, rect, person);
- if person.speaking {
- p.rect_stroke(
- rect,
- radius,
- egui::Stroke::new(3.0, theme::p32().accent_ring),
- egui::StrokeKind::Inside,
- );
- }
- let _ = person.id;
-}
-
-/// The people button, top right: how many are in the call, and a gold count of
-/// raised hands. Answers whether it was pressed.
-fn people_button(ui: &mut egui::Ui, full: egui::Rect, calls: &Calls) -> bool {
- let d = 40.0;
- let c = egui::pos2(full.max.x - EDGE - d * 0.5, full.min.y + EDGE + d * 0.5);
- let rect = egui::Rect::from_center_size(c, egui::Vec2::splat(d));
- let resp = ui.interact(rect, egui::Id::new("call_people"), egui::Sense::click());
- let resp = theme::named(ui, resp, "People in the call").on_hover_text("People in the call");
- let p = ui.painter();
- p.circle_filled(
- c,
- d * 0.5,
- egui::Color32::from_white_alpha(if resp.hovered() { 46 } else { 30 }),
- );
- centred(p, c, icons::GROUP, 22.0, theme::p32().cream);
- let hands = calls.members().iter().filter(|m| m.hand.is_some()).count()
- + if calls.hosting() {
- calls.extras().waiting.len()
- } else {
- 0
- };
- let (count, fill, ink) = if hands > 0 {
- (hands, theme::p32().warn, theme::p32().ink)
- } else {
- (
- calls.members().len(),
- theme::p32().surface_raised,
- theme::p32().cream,
- )
- };
- if count > 0 {
- let b = c + egui::vec2(d * 0.38, -d * 0.36);
- p.circle_filled(b, 9.0, fill);
- centred(p, b, &count.to_string(), theme::SIZE_TINY, ink);
- }
- resp.click
… (cut)