diff --git a/lib/main.dart b/lib/main.dart index 390b8084..af5b2dc5 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -216,10 +216,6 @@ 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 @@ -339,6 +335,12 @@ class MeshCoreApp extends StatelessWidget { @override Widget build(BuildContext context) { + // Android keeps a keyboard inset after the keyboard is gone when the app is + // backgrounded mid-animation (#1231, flutter/flutter#191156). + return StaleKeyboardInsetRepair(child: _withProviders()); + } + + Widget _withProviders() { return MultiProvider( providers: [ ChangeNotifierProvider.value(value: storageHealth), diff --git a/lib/services/stale_keyboard_inset_guard.dart b/lib/services/stale_keyboard_inset_guard.dart index 8249c72b..8e46fac7 100644 --- a/lib/services/stale_keyboard_inset_guard.dart +++ b/lib/services/stale_keyboard_inset_guard.dart @@ -1,10 +1,10 @@ import 'dart:async'; +import 'package:flutter/foundation.dart'; 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. @@ -56,28 +56,21 @@ class StaleKeyboardInsetGuard with WidgetsBindingObserver { '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; - } + /// The guard the app runs, talking to Android over the platform channel. + static StaleKeyboardInsetGuard forApp() => StaleKeyboardInsetGuard( + flutterInsetBottom: () => + WidgetsBinding + .instance + .platformDispatcher + .implicitView + ?.viewInsets + .bottom ?? + 0, + queryNative: _queryChannel, + reapplyInsets: _reapplyChannel, + log: (level, message) => + appLogger.log(message, tag: 'KeyboardInset', level: level), + ); static Future _queryChannel() async { final state = await _channel.invokeMapMethod( @@ -199,3 +192,41 @@ class StaleKeyboardInsetGuard with WidgetsBindingObserver { void dispose() => _timer?.cancel(); } + +/// Runs a [StaleKeyboardInsetGuard] for as long as it is in the tree. Android +/// only: the native side exists there alone, and web on an Android browser +/// has no such channel. +class StaleKeyboardInsetRepair extends StatefulWidget { + const StaleKeyboardInsetRepair({super.key, required this.child}); + + final Widget child; + + @override + State createState() => + _StaleKeyboardInsetRepairState(); +} + +class _StaleKeyboardInsetRepairState extends State { + StaleKeyboardInsetGuard? _guard; + + @override + void initState() { + super.initState(); + if (kIsWeb || defaultTargetPlatform != TargetPlatform.android) return; + final guard = _guard = StaleKeyboardInsetGuard.forApp(); + WidgetsBinding.instance.addObserver(guard); + } + + @override + void dispose() { + final guard = _guard; + if (guard != null) { + WidgetsBinding.instance.removeObserver(guard); + guard.dispose(); + } + super.dispose(); + } + + @override + Widget build(BuildContext context) => widget.child; +} diff --git a/test/app/stale_keyboard_inset_app_test.dart b/test/app/stale_keyboard_inset_app_test.dart new file mode 100644 index 00000000..0a380351 --- /dev/null +++ b/test/app/stale_keyboard_inset_app_test.dart @@ -0,0 +1,158 @@ +// #1231 / #1283: the running app, not only the guard class, repairs a keyboard +// inset Android has already dropped (flutter/flutter#191156). Built from the +// app's root widget, so it fails on any code that never starts the guard. + +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/main.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/ble_debug_log_service.dart'; +import 'package:meshcore_open/services/block_service.dart'; +import 'package:meshcore_open/services/chat_text_scale_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:meshcore_open/services/mesh_topology_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/radio_preset_service.dart'; +import 'package:meshcore_open/services/storage_health_service.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/services/timeout_prediction_service.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/services/ui_view_state_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const _channel = MethodChannel('meshcore_open/keyboard_insets'); + +/// Android's side of the channel: the keyboard is hidden. +class _FakeAndroid { + final calls = []; + + Future handle(MethodCall call) async { + calls.add(call.method); + return switch (call.method) { + 'getImeState' => { + 'supported': true, + 'available': true, + 'sdkInt': 37, + 'imeVisible': false, + 'imeBottomPx': 0, + 'navBottomPx': 126, + }, + 'reapplyInsets' => 'reapplied', + _ => null, + }; + } +} + +Future _pumpApp(WidgetTester tester) async { + final storage = StorageService(); + final settings = AppSettingsService(); + await tester.pumpWidget( + MeshCoreApp( + storageHealth: StorageHealthService(), + connector: MeshCoreConnector(), + retryService: MessageRetryService(), + pathHistoryService: PathHistoryService(storage), + meshTopologyService: MeshTopologyService(), + storage: storage, + appSettingsService: settings, + bleDebugLogService: BleDebugLogService(), + appDebugLogService: AppDebugLogService(), + mapTileCacheService: MapTileCacheService(), + chatTextScaleService: ChatTextScaleService(), + translationService: TranslationService(settings), + uiViewStateService: UiViewStateService(), + timeoutPredictionService: TimeoutPredictionService(storage), + blockService: BlockService(), + radioPresetService: RadioPresetService(), + ), + ); + await tester.pump(); +} + +void main() { + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PackageInfo.setMockInitialValues( + appName: 'Offband MeshCore', + packageName: 'app.offband.meshcore', + version: '1.9.0', + buildNumber: '1', + buildSignature: '', + ); + await PrefsManager.initialize(); + }); + + testWidgets( + 'the app re-applies a keyboard inset Android has dropped', + variant: TargetPlatformVariant.only(TargetPlatform.android), + (tester) async { + final android = _fakeAndroid(tester); + await _pumpApp(tester); + + await _staleInsetAfterResume(tester); + + expect(android.calls, contains('reapplyInsets')); + await _unmount(tester); + }, + ); + + testWidgets( + 'off Android the app never asks the native side', + variant: TargetPlatformVariant.only(TargetPlatform.iOS), + (tester) async { + final android = _fakeAndroid(tester); + await _pumpApp(tester); + + await _staleInsetAfterResume(tester); + + expect(android.calls, isEmpty); + await _unmount(tester); + }, + ); + + testWidgets( + 'once the app is gone the guard stops', + variant: TargetPlatformVariant.only(TargetPlatform.android), + (tester) async { + final android = _fakeAndroid(tester); + await _pumpApp(tester); + await _unmount(tester); + + await _staleInsetAfterResume(tester); + + expect(android.calls, isEmpty); + }, + ); +} + +_FakeAndroid _fakeAndroid(WidgetTester tester) { + final android = _FakeAndroid(); + final messenger = tester.binding.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(_channel, android.handle); + addTearDown(() { + messenger.setMockMethodCallHandler(_channel, null); + tester.view.reset(); + }); + return android; +} + +/// Backgrounded mid-animation: Flutter is handed the keyboard-open inset +/// again on the way back, with no keyboard on screen. +Future _staleInsetAfterResume(WidgetTester tester) async { + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + tester.view.viewInsets = const FakeViewPadding(bottom: 846); + await tester.pump(const Duration(milliseconds: 600)); + await tester.pump(const Duration(milliseconds: 600)); +} + +Future _unmount(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(const Duration(milliseconds: 60)); +}