Merge pull request #1279 from OffbandMesh/fix/1231-stale-keyboard-inset

fix(#1231): repair a stale keyboard inset on Android
pull/1293/head
Strycher 2 days ago committed by GitHub
commit bb7a5df8cb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -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<String, Any?> {
// 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"
}
}

@ -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,

@ -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

@ -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<NativeImeState?> Function() queryNative,
required Future<ReapplyResult> 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<NativeImeState?> _queryChannel() async {
final state = await _channel.invokeMapMethod<String, Object?>(
'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<ReapplyResult> _reapplyChannel() async {
final result = await _channel.invokeMethod<String>('reapplyInsets');
return switch (result) {
'reapplied' => ReapplyResult.reapplied,
'keyboard_visible' => ReapplyResult.keyboardVisible,
_ => ReapplyResult.unavailable,
};
}
final double Function() _flutterInsetBottom;
final Future<NativeImeState?> Function() _queryNative;
final Future<ReapplyResult> 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<void> _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<void>.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();
}

@ -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<void>? 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<String> 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<void>();
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);
});
}
Loading…
Cancel
Save

Powered by TurnKey Linux.