findNativeSurface function
What covers the app in a runner /tree reply: a system alert, else the window's top-level view holding the UIKit-only elements (Flutter's own sit in another, or are hidden by a full-screen modal); null when only Flutter and the keyboard are on screen. With wholeApp (device mode, no Flutter) it is the app's alert or sheet, else the whole app, named from appId.
Implementation
({String name, List<Map<String, Object?>> roots})? findNativeSurface(Map<String, Object?> reply,
{bool wholeApp = false, String? appId}) {
final alerts = [
for (final a in (reply['alerts'] as List? ?? const []))
if (a is Map) a.cast<String, Object?>()
];
if (alerts.isNotEmpty) {
final label = alerts.first['label'] as String?;
return (name: label == null || label.isEmpty ? 'a system alert' : 'alert "$label"', roots: alerts);
}
final app = reply['app'];
if (app is! Map) return null;
if (wholeApp) return _wholeAppSurface(app.cast<String, Object?>(), appId);
final paths = <List<Map<String, Object?>>>[];
void walk(Map<String, Object?> n, List<Map<String, Object?>> path) {
if (_isKeyboard(n)) return;
final here = [...path, n];
if (_uikitOnly.contains(n['type'])) paths.add(here);
for (final c in _children(n)) {
walk(c, here);
}
}
walk(app.cast<String, Object?>(), const []);
if (paths.isEmpty) return null;
var common = paths.first;
for (final p in paths.skip(1)) {
var i = 0;
while (i < common.length && i < p.length && identical(common[i], p[i])) {
i++;
}
common = common.sublist(0, i);
}
final root = common[common.length < 3 ? common.length - 1 : 2];
return (name: _surfaceName([for (final p in paths) p.last]), roots: [root]);
}