nandi/jolt-nativepublic Fork 0
c4f56b0a96ecb29336e2cf16c522b794ae62ad3f
Commits
Clone
git clone https://git.rickub.com/nandi/jolt-native.git
git clone ssh://git@rickub.com/nandi/jolt-native.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Bring vidya in cfd3e36 · on c4f56b0a96ecb29336e2cf16c522b794ae62ad3f · nandi · 19d ago
chrome.rs · 297 lines · 10.2 KBRust Blame HistoryRaw
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
//! System chrome (status bar / nav bar) safe areas.
//!
//! Android NativeActivity draws **edge-to-edge**: the window fills under the
//! system status bar (clock, battery, …) and the gesture/nav bar. Without an
//! explicit reserve, app chrome and labels sit under those system widgets.
//!
//! Call [`reserve_system_chrome`] once at the start of every frame (before any
//! other `TopBottomPanel` / `SidePanel` / `CentralPanel`), or use
//! [`top_header`] which does that for you.
//!
//! Prefer injecting measured insets via [`set_system_chrome`] or
//! [`sync_system_chrome_from_android`] (from `AndroidApp::content_rect` or
//! WindowInsets) so reserves match the device — hardcoded fallbacks are
//! intentionally tight for modern gesture-nav phones.

use egui::{Align2, Context, Frame, Id, Margin, Sense, Ui, WidgetText, Window};

use crate::Theme;

/// Temp-data id for app-supplied measured insets (see [`set_system_chrome`]).
const SYSTEM_CHROME_ID: &str = "vidya.system_chrome";
/// Last measured nav-band height when the keyboard was hidden.
const NAV_HINT_ID: &str = "vidya.nav_bottom_hint";

/// Insets for system status / navigation chrome on edge-to-edge surfaces.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SystemChrome {
    /// Space under the status bar (clock, indicators).
    pub top: f32,
    /// Space above the system gesture / 3-button nav bar.
    pub nav_bottom: f32,
    /// Extra reserve when the soft keyboard is visible (sits above [`nav_bottom`]).
    pub ime_bottom: f32,
}

impl SystemChrome {
    pub const ZERO: Self = Self {
        top: 0.0,
        nav_bottom: 0.0,
        ime_bottom: 0.0,
    };

    /// Combined bottom inset (nav + IME).
    #[inline]
    pub fn bottom(self) -> f32 {
        self.nav_bottom + self.ime_bottom
    }

    pub fn is_zero(self) -> bool {
        self.top <= 0.0 && self.bottom() <= 0.0
    }

    /// Build from status + nav insets (no IME reserve).
    pub fn from_insets(top: f32, nav_bottom: f32) -> Self {
        Self {
            top: top.max(0.0),
            nav_bottom: nav_bottom.max(0.0),
            ime_bottom: 0.0,
        }
    }
}

/// Inject measured system insets for this frame (egui points).
///
/// Call once per frame **before** [`reserve_system_chrome`]. When set,
/// [`system_chrome`] uses these values instead of the platform fallbacks and
/// does **not** add focus-based IME padding on top (measured insets already
/// reflect keyboard visibility from `content_rect` / WindowInsets).
pub fn set_system_chrome(ctx: &Context, chrome: SystemChrome) {
    ctx.data_mut(|d| d.insert_temp(Id::new(SYSTEM_CHROME_ID), chrome));
}

/// Read measured insets from [`AndroidApp::content_rect`] and call
/// [`set_system_chrome`].
///
/// Call once per frame on Android **before** [`reserve_system_chrome`]. When the
/// soft keyboard is open, `content_rect` shrinks and the derived bottom inset
/// includes the IME height so layout tracks the real keyboard band — even when
/// the user dismisses the keyboard via the IME close button while a text field
/// still holds focus.
#[cfg(target_os = "android")]
pub fn sync_system_chrome_from_android(
    ctx: &Context,
    app: &winit::platform::android::activity::AndroidApp,
) {
    const NAV_FALLBACK: f32 = 20.0;
    /// Minimum extra inset beyond the nav band before treating the IME as visible.
    const IME_VISIBLE_THRESHOLD: f32 = 48.0;

    let rect = app.content_rect();
    let ppp = ctx.pixels_per_point().max(0.01);
    let screen = ctx.screen_rect();

    let top = (rect.top as f32 / ppp).max(0.0);
    let content_bottom_pt = rect.bottom as f32 / ppp;
    let total_bottom = (screen.height() - content_bottom_pt).max(0.0);

    let nav_hint = ctx
        .data(|d| d.get_temp::<f32>(Id::new(NAV_HINT_ID)))
        .unwrap_or(NAV_FALLBACK);

    // Derive keyboard visibility from content_rect, not wants_keyboard_input():
    // dismissing the IME hides the keyboard but often leaves text focus.
    let keyboard_visible = total_bottom > nav_hint + IME_VISIBLE_THRESHOLD;

    if keyboard_visible {
        let nav = nav_hint.clamp(0.0, total_bottom);
        set_system_chrome(
            ctx,
            SystemChrome {
                top,
                nav_bottom: nav,
                ime_bottom: (total_bottom - nav).max(0.0),
            },
        );
    } else {
        ctx.data_mut(|d| d.insert_temp(Id::new(NAV_HINT_ID), total_bottom));
        set_system_chrome(ctx, SystemChrome::from_insets(top, total_bottom));
    }
}

/// Platform defaults for edge-to-edge drawing.
///
/// Fallback values are **tight** for modern gesture-nav phones (≈24–28 dp
/// status, ≈16–24 dp gesture handle). Prefer [`set_system_chrome`] or
/// [`sync_system_chrome_from_android`] with measured `content_rect` /
/// WindowInsets when available.
///
/// When a text field holds focus (`Context::wants_keyboard_input`), the bottom
/// inset grows so bottom bars / compose fields sit **above** the soft keyboard
/// (NativeActivity rarely resizes the GL surface for IME).
pub fn system_chrome(ctx: &Context) -> SystemChrome {
    #[cfg(target_os = "android")]
    {
        let measured = ctx.data(|d| d.get_temp::<SystemChrome>(Id::new(SYSTEM_CHROME_ID)));
        const TOP_FALLBACK: f32 = 36.0;
        const NAV_FALLBACK: f32 = 20.0;
        let top = match measured {
            Some(c) if c.top >= 8.0 => c.top,
            Some(c) => c.top.max(TOP_FALLBACK),
            None => TOP_FALLBACK,
        };

        if let Some(m) = measured {
            let chrome = SystemChrome {
                top,
                nav_bottom: m.nav_bottom.max(0.0),
                ime_bottom: m.ime_bottom.max(0.0),
            };
            // content_rect / WindowInsets may still be animating with the IME.
            if chrome.ime_bottom > NAV_FALLBACK {
                ctx.request_repaint();
            }
            return chrome;
        }

        let mut nav_bottom = NAV_FALLBACK;
        let mut ime_bottom = 0.0;

        if ctx.wants_keyboard_input() {
            let h = ctx.screen_rect().height();
            let ime_fallback = (h * 0.40).clamp(240.0, h * 0.52);
            nav_bottom = NAV_FALLBACK.min(ime_fallback);
            ime_bottom = (ime_fallback - nav_bottom).max(0.0);
            ctx.request_repaint();
        }

        SystemChrome {
            top,
            nav_bottom,
            ime_bottom,
        }
    }
    #[cfg(not(target_os = "android"))]
    {
        let _ = ctx;
        SystemChrome::ZERO
    }
}

/// Reserve top/bottom strips so **no** subsequent panel or central content can
/// paint under the system status or navigation bars.
///
/// Call this **once per frame**, before other panels. Safe to call when insets
/// are zero (no-op on desktop).
///
/// When the soft keyboard is open, the IME reserve does **not** absorb pointer
/// events so swipe typing on the system keyboard is not blocked. Only the nav
/// strip keeps a hover sink so widgets behind the gesture bar cannot steal taps.
pub fn reserve_system_chrome(ctx: &Context, theme: &Theme) {
    let chrome = system_chrome(ctx);
    if chrome.is_zero() {
        return;
    }

    let top_band = Frame::new()
        .fill(theme.palette.headerbar_bg)
        .inner_margin(Margin::ZERO);
    let nav_band = Frame::new()
        .fill(theme.palette.window_bg)
        .inner_margin(Margin::ZERO);
    // Transparent — only reserves layout; must not paint over the IME.
    let ime_band = Frame::NONE;

    if chrome.top > 0.0 {
        egui::TopBottomPanel::top("vidya_system_chrome_top")
            .exact_height(chrome.top)
            .frame(top_band)
            .show_separator_line(false)
            .show(ctx, |_ui| {});
    }

    // Bottom panels stack upward: declare nav first (screen edge), then IME.
    if chrome.nav_bottom > 0.0 {
        egui::TopBottomPanel::bottom("vidya_system_chrome_nav")
            .exact_height(chrome.nav_bottom)
            .frame(nav_band)
            .show_separator_line(false)
            .show(ctx, |ui| {
                ui.allocate_exact_size(ui.available_size(), Sense::hover());
            });
    }

    if chrome.ime_bottom > 0.0 {
        egui::TopBottomPanel::bottom("vidya_system_chrome_ime")
            .exact_height(chrome.ime_bottom)
            .frame(ime_band)
            .show_separator_line(false)
            .show(ctx, |ui| {
                // Pass touches through to the system keyboard (swipe / glide typing).
                ui.allocate_exact_size(ui.available_size(), Sense::empty());
            });
    }
}

/// Top app header with system status bar already reserved.
///
/// Preferred entry for shell chrome: apps cannot place title/status text under
/// the clock / indicators. Also reserves the bottom system nav band.
///
/// ```ignore
/// vidya::top_header(ctx, &theme, |ui| {
///     ui.horizontal(|ui| {
///         vidya::title(ui, &theme, "My App");
///     });
/// });
/// ```
pub fn top_header(ctx: &Context, theme: &Theme, add_contents: impl FnOnce(&mut Ui)) {
    reserve_system_chrome(ctx, theme);
    egui::TopBottomPanel::top("vidya_app_header")
        .frame(theme.header_frame())
        .show_separator_line(false)
        .show(ctx, add_contents);
}

/// Centered modal-style window with themed card chrome.
///
/// Defaults: non-collapsible, **resizable**, centered, [`Theme::card_frame`].
/// Chain `.default_size` / `.min_width` / `.resizable(false)` as needed, then
/// `.show`.
///
/// ```ignore
/// vidya::dialog("Rename", &theme)
///     .default_width(360.0)
///     .min_width(280.0)
///     .show(ctx, |ui| { /* … */ });
/// ```
pub fn dialog<'a>(title: impl Into<WidgetText> + 'a, theme: &Theme) -> Window<'a> {
    Window::new(title)
        .collapsible(false)
        .resizable(true)
        .anchor(Align2::CENTER_CENTER, [0.0, 0.0])
        .frame(theme.card_frame())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn system_chrome_bottom_sums_nav_and_ime() {
        let c = SystemChrome {
            top: 36.0,
            nav_bottom: 20.0,
            ime_bottom: 400.0,
        };
        assert!((c.bottom() - 420.0).abs() < f32::EPSILON);
        assert!(!c.is_zero());
    }

    #[test]
    fn from_insets_zeroes_ime() {
        let c = SystemChrome::from_insets(36.0, 20.0);
        assert_eq!(c.ime_bottom, 0.0);
        assert_eq!(c.nav_bottom, 20.0);
    }
}