From 200f0f5ab75d93b3c5fd106215b6c2df514b61b2 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:15:31 -0500 Subject: [PATCH] fix(#1231): repair a stale keyboard inset on Android Backgrounding the app while the keyboard animates makes the Flutter engine re-dispatch the insets it cached when the keyboard opened (flutter/flutter#191156, fixed upstream on master only by #191453). Flutter then keeps a keyboard inset with no keyboard: the chat stays shrunk and the bottom bar loses its safe-area padding. Once metrics and lifecycle settle for 500 ms, a nonzero Flutter inset is checked against Android's root insets. If Android says the keyboard is hidden, the insets are re-applied (the native side re-checks the keyboard in the same main-thread turn) and the result is checked. Silent per Ben's decision: WARN on a repair, INFO when it clears, ERROR when it does not or a native call fails. Remove once the pinned Flutter contains #191453. Co-Authored-By: Claude Opus 5.5 --- .../meshcore_open/KeyboardInsetFunctions.kt | 72 ++++++ .../meshcore/meshcore_open/MainActivity.kt | 2 + lib/main.dart | 5 + lib/services/stale_keyboard_inset_guard.dart | 201 ++++++++++++++++ .../stale_keyboard_inset_guard_test.dart | 215 ++++++++++++++++++ 5 files changed, 495 insertions(+) create mode 100644 android/app/src/main/kotlin/com/meshcore/meshcore_open/KeyboardInsetFunctions.kt create mode 100644 lib/services/stale_keyboard_inset_guard.dart create mode 100644 test/services/stale_keyboard_inset_guard_test.dart diff --git a/android/app/src/main/kotlin/com/meshcore/meshcore_open/KeyboardInsetFunctions.kt b/android/app/src/main/kotlin/com/meshcore/meshcore_open/KeyboardInsetFunctions.kt new file mode 100644 index 00000000..67715bd1 --- /dev/null +++ b/android/app/src/main/kotlin/com/meshcore/meshcore_open/KeyboardInsetFunctions.kt @@ -0,0 +1,72 @@ +package com.meshcore.meshcore_open + +import android.os.Build +import android.view.WindowInsets +import io.flutter.embedding.android.FlutterActivity +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.plugin.common.MethodChannel + +/** + * Lets Dart ask Android whether the keyboard is really showing, and ask for the + * window insets to be dispatched again (#1231). + * + * Works around flutter/flutter#191156: when the app is backgrounded while the + * keyboard is animating, the engine's `ImeSyncDeferringInsetsCallback.onEnd` + * re-dispatches the insets it cached when the keyboard opened, and Flutter keeps + * a keyboard inset with no keyboard on screen. A fresh dispatch reaches Flutter, + * because the engine's `animating` flag is already cleared by then. + * + * Remove this file, and the Dart guard that calls it, once the pinned Flutter + * contains flutter/flutter#191453. + */ +class KeyboardInsetFunctions( + private val activity: FlutterActivity, +) { + private val channelName = "meshcore_open/keyboard_insets" + + fun configureFlutterEngine(flutterEngine: FlutterEngine) { + MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channelName) + .setMethodCallHandler { call, result -> + when (call.method) { + "getImeState" -> result.success(imeState()) + "reapplyInsets" -> result.success(reapplyInsets()) + else -> result.notImplemented() + } + } + } + + private fun imeState(): Map { + // The engine installs the deferring callback only on API 30+, so the + // bug cannot occur below it. + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { + return mapOf("supported" to false, "sdkInt" to Build.VERSION.SDK_INT) + } + val insets = activity.window?.decorView?.rootWindowInsets + ?: return mapOf( + "supported" to true, + "available" to false, + "sdkInt" to Build.VERSION.SDK_INT, + ) + return mapOf( + "supported" to true, + "available" to true, + "sdkInt" to Build.VERSION.SDK_INT, + "imeVisible" to insets.isVisible(WindowInsets.Type.ime()), + "imeBottomPx" to insets.getInsets(WindowInsets.Type.ime()).bottom, + "navBottomPx" to insets.getInsets(WindowInsets.Type.navigationBars()).bottom, + ) + } + + /** + * Re-checks the keyboard in the same main-thread turn as the request, so a + * keyboard that opened after Dart's last read is never sent a dispatch. + */ + private fun reapplyInsets(): String { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return "unsupported" + val view = activity.window?.decorView ?: return "no_window" + val insets = view.rootWindowInsets ?: return "no_insets" + if (insets.isVisible(WindowInsets.Type.ime())) return "keyboard_visible" + view.requestApplyInsets() + return "reapplied" + } +} diff --git a/android/app/src/main/kotlin/com/meshcore/meshcore_open/MainActivity.kt b/android/app/src/main/kotlin/com/meshcore/meshcore_open/MainActivity.kt index a13128f8..3556b536 100644 --- a/android/app/src/main/kotlin/com/meshcore/meshcore_open/MainActivity.kt +++ b/android/app/src/main/kotlin/com/meshcore/meshcore_open/MainActivity.kt @@ -7,6 +7,7 @@ import io.flutter.plugin.common.MethodChannel class MainActivity : FlutterActivity() { private val usbFunctions by lazy { MeshcoreUsbFunctions(this) } private val appExitInfoFunctions by lazy { AppExitInfoFunctions(this) } + private val keyboardInsetFunctions by lazy { KeyboardInsetFunctions(this) } private val appLifecycleChannelName = "meshcore_open/app_lifecycle" @@ -14,6 +15,7 @@ class MainActivity : FlutterActivity() { super.configureFlutterEngine(flutterEngine) usbFunctions.configureFlutterEngine(flutterEngine) appExitInfoFunctions.configureFlutterEngine(flutterEngine) + keyboardInsetFunctions.configureFlutterEngine(flutterEngine) MethodChannel( flutterEngine.dartExecutor.binaryMessenger, diff --git a/lib/main.dart b/lib/main.dart index 177a5878..390b8084 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -36,6 +36,7 @@ import 'services/block_service.dart'; import 'services/window_geometry_service.dart'; import 'services/store_consolidation_service.dart'; import 'services/stale_history_sweep.dart'; +import 'services/stale_keyboard_inset_guard.dart'; import 'services/storage_health_service.dart'; import 'services/radio_preset_service.dart'; import 'storage/cross_radio_copy_cleanup.dart'; @@ -215,6 +216,10 @@ void main() async { }, ); + // Android keeps a keyboard inset after the keyboard is gone when the app is + // backgrounded mid-animation (#1231, flutter/flutter#191156). + StaleKeyboardInsetGuard.install(); + // Report why the previous process died, if it did (#906). Scheduled after the // first frame and deliberately not awaited: #334 is the leading hypothesis for // the ANRs this exists to diagnose, so the collector must not itself add work diff --git a/lib/services/stale_keyboard_inset_guard.dart b/lib/services/stale_keyboard_inset_guard.dart new file mode 100644 index 00000000..8249c72b --- /dev/null +++ b/lib/services/stale_keyboard_inset_guard.dart @@ -0,0 +1,201 @@ +import 'dart:async'; + +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +import '../utils/app_logger.dart'; +import '../utils/platform_info.dart'; +import 'app_debug_log_service.dart'; + +/// Android's own view of the keyboard, read from the window's root insets. +class NativeImeState { + const NativeImeState({ + required this.visible, + required this.imeBottomPx, + required this.navBottomPx, + }); + + final bool visible; + final int imeBottomPx; + final int navBottomPx; +} + +/// What Android did with a re-apply request. It re-checks the keyboard itself, +/// on the main thread, so a keyboard that opened after [NativeImeState] was +/// read is never handed a keyboard-closed dispatch. +enum ReapplyResult { reapplied, keyboardVisible, unavailable } + +/// Repairs a keyboard inset that Flutter keeps after the keyboard has gone +/// (#1231), silently, logging every repair. +/// +/// Works around flutter/flutter#191156: backgrounding the app while the +/// keyboard animates makes the engine re-dispatch the insets it cached when the +/// keyboard opened. Flutter then shrinks the screen by a keyboard that is not +/// there and drops the bottom bar's safe-area padding, so the bar slides under +/// the system buttons. Nothing corrects it until the keyboard opens again. +/// +/// Once metrics and lifecycle have been quiet for [settle], a nonzero Flutter +/// inset is checked against Android; if Android says the keyboard is hidden, +/// the insets are dispatched again and the result is checked. +/// +/// Remove this, and `KeyboardInsetFunctions.kt`, once the pinned Flutter +/// contains flutter/flutter#191453. +class StaleKeyboardInsetGuard with WidgetsBindingObserver { + StaleKeyboardInsetGuard({ + required double Function() flutterInsetBottom, + required Future Function() queryNative, + required Future Function() reapplyInsets, + required void Function(AppDebugLogLevel level, String message) log, + this.settle = const Duration(milliseconds: 500), + }) : _flutterInsetBottom = flutterInsetBottom, + _queryNative = queryNative, + _reapplyInsets = reapplyInsets, + _log = log; + + static const MethodChannel _channel = MethodChannel( + 'meshcore_open/keyboard_insets', + ); + + static StaleKeyboardInsetGuard? _installed; + + /// Registers the guard with the binding. Android only; elsewhere a no-op. + static void install() { + if (!PlatformInfo.isAndroid || _installed != null) return; + final guard = StaleKeyboardInsetGuard( + flutterInsetBottom: () => + WidgetsBinding + .instance + .platformDispatcher + .implicitView + ?.viewInsets + .bottom ?? + 0, + queryNative: _queryChannel, + reapplyInsets: _reapplyChannel, + log: (level, message) => + appLogger.log(message, tag: 'KeyboardInset', level: level), + ); + WidgetsBinding.instance.addObserver(guard); + _installed = guard; + } + + static Future _queryChannel() async { + final state = await _channel.invokeMapMethod( + 'getImeState', + ); + if (state == null || + state['supported'] != true || + state['available'] != true) { + return null; + } + return NativeImeState( + visible: state['imeVisible'] == true, + imeBottomPx: (state['imeBottomPx'] as int?) ?? 0, + navBottomPx: (state['navBottomPx'] as int?) ?? 0, + ); + } + + static Future _reapplyChannel() async { + final result = await _channel.invokeMethod('reapplyInsets'); + return switch (result) { + 'reapplied' => ReapplyResult.reapplied, + 'keyboard_visible' => ReapplyResult.keyboardVisible, + _ => ReapplyResult.unavailable, + }; + } + + final double Function() _flutterInsetBottom; + final Future Function() _queryNative; + final Future Function() _reapplyInsets; + final void Function(AppDebugLogLevel level, String message) _log; + final Duration settle; + + Timer? _timer; + bool _checking = false; + bool _foreground = true; + AppLifecycleState? _lastLifecycle; + DateTime? _lastLifecycleAt; + + @override + void didChangeMetrics() { + if (_foreground) _schedule(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + _lastLifecycle = state; + _lastLifecycleAt = DateTime.now(); + _foreground = state == AppLifecycleState.resumed; + if (_foreground) { + _schedule(); + } else { + _timer?.cancel(); + } + } + + void _schedule() { + _timer?.cancel(); + _timer = Timer(settle, () => unawaited(_check())); + } + + Future _check() async { + if (_checking || !_foreground) return; + final stale = _flutterInsetBottom(); + if (stale <= 0) return; + _checking = true; + try { + final native = await _queryNative(); + if (native == null || native.visible || !_foreground) return; + + final detail = + 'Flutter bottom=${stale.round()}px, Android keyboard hidden ' + '(ime=${native.imeBottomPx}px, nav=${native.navBottomPx}px), ' + 'last lifecycle=${_describeLifecycle()}'; + switch (await _reapplyInsets()) { + case ReapplyResult.keyboardVisible: + return; + case ReapplyResult.unavailable: + _log( + AppDebugLogLevel.error, + 'Stale keyboard inset, and Android could not re-apply insets: ' + '$detail.', + ); + return; + case ReapplyResult.reapplied: + _log( + AppDebugLogLevel.warning, + 'Stale keyboard inset: $detail. Re-applied insets.', + ); + } + + await Future.delayed(settle); + if (!_foreground) return; + final after = _flutterInsetBottom(); + if (after <= 0) { + _log(AppDebugLogLevel.info, 'Stale keyboard inset cleared.'); + return; + } + final recheck = await _queryNative(); + if (recheck != null && recheck.visible) return; + _log( + AppDebugLogLevel.error, + 'Stale keyboard inset still present after re-apply: Flutter ' + 'bottom=${after.round()}px, Android keyboard hidden.', + ); + } catch (error) { + _log(AppDebugLogLevel.error, 'Keyboard inset check failed: $error'); + } finally { + _checking = false; + } + } + + String _describeLifecycle() { + final state = _lastLifecycle; + final at = _lastLifecycleAt; + if (state == null || at == null) return 'none since launch'; + final ago = DateTime.now().difference(at).inMilliseconds; + return '${state.name} ${ago}ms ago'; + } + + void dispose() => _timer?.cancel(); +} diff --git a/test/services/stale_keyboard_inset_guard_test.dart b/test/services/stale_keyboard_inset_guard_test.dart new file mode 100644 index 00000000..a8cd868e --- /dev/null +++ b/test/services/stale_keyboard_inset_guard_test.dart @@ -0,0 +1,215 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/services/stale_keyboard_inset_guard.dart'; + +/// Stands in for Flutter's view inset and Android's window insets (#1231). +class _Bench { + double flutterInset = 0; + NativeImeState? native = const NativeImeState( + visible: false, + imeBottomPx: 0, + navBottomPx: 126, + ); + Object? queryError; + + /// What Flutter's inset becomes once Android re-dispatches; null = unchanged. + double? insetAfterReapply = 0; + ReapplyResult reapplyResult = ReapplyResult.reapplied; + + /// When set, the native query waits on it, so a test can act mid-check. + Completer? queryGate; + + int queries = 0; + int reapplies = 0; + final logs = <(AppDebugLogLevel, String)>[]; + + late final StaleKeyboardInsetGuard guard = StaleKeyboardInsetGuard( + flutterInsetBottom: () => flutterInset, + queryNative: () async { + queries++; + if (queryGate != null) await queryGate!.future; + if (queryError != null) throw queryError!; + return native; + }, + reapplyInsets: () async { + reapplies++; + if (reapplyResult != ReapplyResult.reapplied) return reapplyResult; + if (insetAfterReapply != null) { + flutterInset = insetAfterReapply!; + guard.didChangeMetrics(); + } + return reapplyResult; + }, + log: (level, message) => logs.add((level, message)), + ); + + Iterable at(AppDebugLogLevel level) => + logs.where((e) => e.$1 == level).map((e) => e.$2); +} + +const _settle = Duration(milliseconds: 500); + +void main() { + testWidgets('a stale inset on resume is re-applied and logged', ( + tester, + ) async { + final bench = _Bench()..flutterInset = 846; + + bench.guard.didChangeAppLifecycleState(AppLifecycleState.paused); + bench.guard.didChangeAppLifecycleState(AppLifecycleState.resumed); + bench.guard.didChangeMetrics(); + await tester.pump(_settle); + await tester.pump(_settle); + + expect(bench.reapplies, 1); + expect(bench.at(AppDebugLogLevel.warning).single, contains('846')); + expect(bench.at(AppDebugLogLevel.warning).single, contains('resumed')); + expect(bench.at(AppDebugLogLevel.info).single, contains('cleared')); + expect(bench.at(AppDebugLogLevel.error), isEmpty); + }); + + testWidgets('a keyboard that is really open is left alone', (tester) async { + final bench = _Bench() + ..flutterInset = 846 + ..native = const NativeImeState( + visible: true, + imeBottomPx: 972, + navBottomPx: 126, + ); + + bench.guard.didChangeMetrics(); + await tester.pump(_settle); + await tester.pump(_settle); + + expect(bench.queries, 1); + expect(bench.reapplies, 0); + expect(bench.logs, isEmpty); + }); + + testWidgets('a normal close that settles inside the window does nothing', ( + tester, + ) async { + final bench = _Bench()..flutterInset = 846; + + bench.guard.didChangeMetrics(); + await tester.pump(const Duration(milliseconds: 300)); + bench.flutterInset = 0; + bench.guard.didChangeMetrics(); + await tester.pump(_settle); + await tester.pump(_settle); + + expect(bench.queries, 0); + expect(bench.reapplies, 0); + expect(bench.logs, isEmpty); + }); + + testWidgets('a re-apply that does not clear the inset logs an error', ( + tester, + ) async { + final bench = _Bench() + ..flutterInset = 846 + ..insetAfterReapply = null; + + bench.guard.didChangeMetrics(); + await tester.pump(_settle); + await tester.pump(_settle); + + expect(bench.reapplies, 1); + expect(bench.at(AppDebugLogLevel.error).single, contains('still')); + expect(bench.at(AppDebugLogLevel.info), isEmpty); + }); + + testWidgets('a re-apply Android cannot perform logs an error', ( + tester, + ) async { + final bench = _Bench() + ..flutterInset = 846 + ..reapplyResult = ReapplyResult.unavailable; + + bench.guard.didChangeMetrics(); + await tester.pump(_settle); + await tester.pump(_settle); + + expect(bench.reapplies, 1); + expect(bench.at(AppDebugLogLevel.error).single, contains('846')); + expect(bench.at(AppDebugLogLevel.warning), isEmpty); + }); + + testWidgets('a keyboard that opened before the re-apply is left alone', ( + tester, + ) async { + final bench = _Bench() + ..flutterInset = 846 + ..reapplyResult = ReapplyResult.keyboardVisible; + + bench.guard.didChangeMetrics(); + await tester.pump(_settle); + await tester.pump(_settle); + + expect(bench.reapplies, 1); + expect(bench.logs, isEmpty); + }); + + testWidgets('backgrounding mid-check stops the repair', (tester) async { + final bench = _Bench() + ..flutterInset = 846 + ..queryGate = Completer(); + + bench.guard.didChangeMetrics(); + await tester.pump(_settle); + expect(bench.queries, 1); + bench.guard.didChangeAppLifecycleState(AppLifecycleState.paused); + bench.queryGate!.complete(); + await tester.pump(_settle); + await tester.pump(_settle); + + expect(bench.reapplies, 0); + expect(bench.logs, isEmpty); + }); + + testWidgets('a failing native query logs an error, never a silent pass', ( + tester, + ) async { + final bench = _Bench() + ..flutterInset = 846 + ..queryError = StateError('channel gone'); + + bench.guard.didChangeMetrics(); + await tester.pump(_settle); + + expect(bench.reapplies, 0); + expect(bench.at(AppDebugLogLevel.error).single, contains('channel gone')); + }); + + testWidgets('no check runs while the app is in the background', ( + tester, + ) async { + final bench = _Bench()..flutterInset = 846; + + bench.guard.didChangeAppLifecycleState(AppLifecycleState.paused); + bench.guard.didChangeMetrics(); + await tester.pump(_settle); + await tester.pump(_settle); + + expect(bench.queries, 0); + expect(bench.reapplies, 0); + }); + + testWidgets('a platform without the native check does nothing', ( + tester, + ) async { + final bench = _Bench() + ..flutterInset = 846 + ..native = null; + + bench.guard.didChangeMetrics(); + await tester.pump(_settle); + await tester.pump(_settle); + + expect(bench.reapplies, 0); + expect(bench.logs, isEmpty); + }); +}