Skip to content

Commit a539e0e

Browse files
authored
[Android] Fix 1px edge clipping on Platform Views by preserving floating-point precision where possible and rounding otherwise instead of truncating (flutter#190311)
Fixes flutter#189834 It's kind of hard to see in the screenshots that Android studio device mirroring produces, but there's a 1px green border of the underlay box visible pre-change clearly on device. You can kind of see it if you click the screenshot and zoom in. Golden test screenshots: | | Unclipped | Clipped | | :--- | :---: | :---: | | **Pre-change** | <img src="https://github.com/user-attachments/assets/e1501fa4-d825-4ae0-a4d1-3c1d173e5694" width="250" alt="Pre-change Unclipped" /> | <img src="https://github.com/user-attachments/assets/46b58d99-5a3f-4c6f-b8c5-c19c880d937e" width="250" alt="Pre-change Clipped" /> | | **Post-change** | <img src="https://github.com/user-attachments/assets/16a3a92a-d3b3-45ea-a2ce-caf438a8dd35" width="250" alt="Post-change Unclipped" /> | <img src="https://github.com/user-attachments/assets/18d7926e-45b9-41a9-a255-8ed1477d1055" width="250" alt="Post-change Clipped" /> | Ai description of the changes, which is accurate (i checked) On Android devices with a fractional Device Pixel Ratio (`dpr`, e.g., `2.625` on 420dpi screens), converting between logical and physical pixels in floating point often yields values just below a whole integer (e.g., `1080 / 2.625 * 2.625 = 1079.999965`). Previously, the C++ Engine and Java embedding truncated these values to integers (`static_cast<int32_t>` / `(int)`), systematically shaving 1 physical pixel off the right and bottom edges of Platform Views, clip rectangles, and texture buffer sizes. This left a visible 1px line of underlying background content around the view. This PR fixes precision loss across three equivalence classes in the Android Platform View composition pipeline: ### 1. Plumb floating-point precision where native APIs accept floats (`RectF` / MethodChannel) * **Mutator Stack Clipping**: Updated `pushClipRect` and `pushClipRRect` in C++ JNI ([platform_view_android_jni_impl.cc](engine/src/flutter/shell/platform/android/platform_view_android_jni_impl.cc)) and Java ([FlutterMutatorsStack.java](engine/src/flutter/shell/platform/android/io/flutter/embedding/engine/mutatorsstack/FlutterMutatorsStack.java)) from integer `(IIII)V` to floating-point `(FFFF)V`, storing `RectF` and passing floats directly to Android `Path.addRect(RectF)`. * **Buffer Size Reporting**: Updated `PlatformViewBufferSize` width/height from `int` to `double` and changed `toLogicalPixels(double)` in ([PlatformViewsController.java](engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewsController.java)) to return fractional `double` values without integer casting or rounding. ### 2. Round onto the integer grid where Android APIs require integers * **View Layout & Sizing**: In C++ ([external_view_embedder.cc](engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder.cc) and [external_view_embedder_2.cc](engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder_2.cc)), replaced integer truncation with rounding: * View bounding boxes use `DlIRect::Round(GetViewRect(...))`. * Physical width/height conversion uses `std::round(size_points * dpr)` via `ToPhysicalPixels(...)`. ### 3. Sizing & Buffer Reporting by Composition Mode ([PlatformViewsController.java](engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewsController.java)) * **Virtual Display Mode**: Directly reports the requested logical dimensions (`request.newLogicalWidth`, `request.newLogicalHeight`), bypassing physical-to-logical round-trip conversion entirely. * **Texture Layer Hybrid Composition (TLHC)**: Because TLHC render targets only grow and never shrink, the controller reports the actual unshrunk physical render target size as an exact fractional `double` (`physicalPixels / getDisplayDensity()`). This allows the framework to size the texture 1:1 and clip it to the widget rather than scaling it down. ## Testing * **C++ Unit Test**: Added `PlatformViewSizeIsRoundedNotTruncated` to [external_view_embedder_unittests.cc](engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder_unittests.cc) verifying that full-screen dimensions (`1080x2400` at `dpr = 2.625`) round to `1080, 2400` rather than `1079, 2399`. * **Java Unit Tests**: Added `resizeAndroidView_reportsFractionalBufferSize` and `resizeAndroidView_reportsUnshrunkBufferSize` to [PlatformViewsControllerTest.java](engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/PlatformViewsControllerTest.java). * **Integration / Golden Test**: Added [platform_view_fractional_size_main_test.dart](dev/integration_tests/android_engine_test/test_driver/hcpp/platform_view_fractional_size_main_test.dart) and [platform_view_fractional_size_main.dart](dev/integration_tests/android_engine_test/lib/hcpp/platform_view_fractional_size_main.dart) with a green underlay box sized to `.75` physical pixels (`200.75` unclipped, `150.75` clipped). Truncation deterministically exposes a 1px green outline on any device, while rounding cleanly occludes the underlay.
1 parent 9448386 commit a539e0e

11 files changed

Lines changed: 534 additions & 66 deletions

File tree

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,6 @@
11
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
22
android.useAndroidX=true
3+
# This builtInKotlin flag was added automatically by Flutter migrator
4+
android.builtInKotlin=false
5+
# This newDsl flag was added automatically by Flutter migrator
6+
android.newDsl=false
Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
// Copyright 2014 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import 'dart:convert';
6+
7+
import 'package:android_driver_extensions/extension.dart';
8+
import 'package:flutter/foundation.dart';
9+
import 'package:flutter/gestures.dart';
10+
import 'package:flutter/material.dart';
11+
import 'package:flutter/rendering.dart';
12+
import 'package:flutter/services.dart';
13+
import 'package:flutter_driver/driver_extension.dart';
14+
15+
import '../src/allow_list_devices.dart';
16+
17+
/// The size of the platform view, in *physical* pixels.
18+
///
19+
/// Deliberately not a whole number of pixels. Android view geometry is
20+
/// integral, so the engine has to snap this to the pixel grid; if it truncates
21+
/// instead of rounding, the view ends up 200x200 and a line of
22+
/// [_underlayColor] is left uncovered along the right and bottom edges.
23+
///
24+
/// This is the same defect that a platform view covering the whole screen hits
25+
/// on a device whose device pixel ratio does not evenly divide its resolution
26+
/// (e.g. 1080 / 2.625 narrowed to a float, multiplied back out, is
27+
/// 1079.9999656677246), just provoked deterministically on any device.
28+
///
29+
/// See https://github.com/flutter/flutter/issues/189834.
30+
const double _viewPhysicalSize = 200.75;
31+
32+
/// The size of the clip applied to the platform view, in *physical* pixels.
33+
///
34+
/// Also deliberately not a whole number of pixels; the clip bounds are handed
35+
/// to `FlutterMutatorsStack.pushClipRect` and have the same rounding hazard.
36+
const double _clipPhysicalSize = 150.75;
37+
38+
const Color _backgroundColor = Colors.red;
39+
const Color _underlayColor = Colors.green;
40+
41+
void main() async {
42+
ensureAndroidDevice();
43+
enableFlutterDriverExtension(
44+
handler: (String? command) async {
45+
return json.encode(<String, Object?>{
46+
'supported': await HybridAndroidViewController.checkIfSupported(),
47+
});
48+
},
49+
commands: <CommandExtension>[nativeDriverCommands],
50+
);
51+
52+
// Run on full screen.
53+
await SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersive);
54+
runApp(const FractionalSizeApp());
55+
}
56+
57+
class FractionalSizeApp extends StatelessWidget {
58+
const FractionalSizeApp({super.key});
59+
60+
@override
61+
Widget build(BuildContext context) {
62+
return const MaterialApp(debugShowCheckedModeBanner: false, home: FractionalSizeHomePage());
63+
}
64+
}
65+
66+
class FractionalSizeHomePage extends StatefulWidget {
67+
const FractionalSizeHomePage({super.key});
68+
69+
@override
70+
State<FractionalSizeHomePage> createState() => _FractionalSizeHomePageState();
71+
}
72+
73+
class _FractionalSizeHomePageState extends State<FractionalSizeHomePage> {
74+
bool _isClipped = false;
75+
76+
void _toggleClip() {
77+
setState(() {
78+
_isClipped = !_isClipped;
79+
});
80+
}
81+
82+
@override
83+
Widget build(BuildContext context) {
84+
final double devicePixelRatio = MediaQuery.devicePixelRatioOf(context);
85+
final double viewSize = _viewPhysicalSize / devicePixelRatio;
86+
final double underlayPhysicalSize = (_isClipped ? _clipPhysicalSize : _viewPhysicalSize)
87+
.roundToDouble();
88+
final double underlaySize = underlayPhysicalSize / devicePixelRatio;
89+
90+
Widget platformView = const _HybridCompositionAndroidPlatformView(
91+
viewType: 'box_platform_view',
92+
);
93+
if (_isClipped) {
94+
platformView = ClipRect(
95+
clipper: _FractionalClipper(dimension: _clipPhysicalSize / devicePixelRatio),
96+
child: platformView,
97+
);
98+
}
99+
100+
// The platform view is pinned to the top left so that only its right and
101+
// bottom edges land on a fractional pixel, which is where the artifact
102+
// shows up.
103+
return Scaffold(
104+
backgroundColor: _backgroundColor,
105+
body: Stack(
106+
children: <Widget>[
107+
Positioned(
108+
left: 0,
109+
top: 0,
110+
width: underlaySize,
111+
height: underlaySize,
112+
child: const ColoredBox(color: _underlayColor),
113+
),
114+
Positioned(left: 0, top: 0, width: viewSize, height: viewSize, child: platformView),
115+
Positioned(
116+
left: 0,
117+
right: 0,
118+
bottom: 0,
119+
child: Center(
120+
child: ElevatedButton(
121+
key: const ValueKey<String>('toggle_clip_button'),
122+
onPressed: _toggleClip,
123+
child: Text(_isClipped ? 'Disable ClipRect' : 'Enable ClipRect'),
124+
),
125+
),
126+
),
127+
],
128+
),
129+
);
130+
}
131+
}
132+
133+
/// Clips to a square of [dimension] anchored at the top left of the widget.
134+
final class _FractionalClipper extends CustomClipper<Rect> {
135+
const _FractionalClipper({required this.dimension});
136+
137+
final double dimension;
138+
139+
@override
140+
Rect getClip(Size size) => Rect.fromLTWH(0, 0, dimension, dimension);
141+
142+
@override
143+
bool shouldReclip(covariant _FractionalClipper oldClipper) {
144+
return oldClipper.dimension != dimension;
145+
}
146+
}
147+
148+
final class _HybridCompositionAndroidPlatformView extends StatelessWidget {
149+
const _HybridCompositionAndroidPlatformView({required this.viewType});
150+
151+
final String viewType;
152+
153+
@override
154+
Widget build(BuildContext context) {
155+
return PlatformViewLink(
156+
viewType: viewType,
157+
surfaceFactory: (BuildContext context, PlatformViewController controller) {
158+
return AndroidViewSurface(
159+
controller: controller as AndroidViewController,
160+
gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{},
161+
hitTestBehavior: PlatformViewHitTestBehavior.transparent,
162+
);
163+
},
164+
onCreatePlatformView: (PlatformViewCreationParams params) {
165+
return PlatformViewsService.initHybridAndroidView(
166+
id: params.id,
167+
viewType: viewType,
168+
layoutDirection: TextDirection.ltr,
169+
creationParamsCodec: const StandardMessageCodec(),
170+
)
171+
..addOnPlatformViewCreatedListener(params.onPlatformViewCreated)
172+
..create();
173+
},
174+
);
175+
}
176+
}
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
// Copyright 2014 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import 'dart:convert';
6+
7+
import 'package:android_driver_extensions/native_driver.dart';
8+
import 'package:android_driver_extensions/skia_gold.dart';
9+
import 'package:flutter_driver/flutter_driver.dart';
10+
import 'package:test/test.dart';
11+
12+
import '../_luci_skia_gold_prelude.dart';
13+
14+
/// Regression test for https://github.com/flutter/flutter/issues/189834.
15+
///
16+
/// A platform view whose bounds do not land on whole physical pixels used to be
17+
/// *truncated* onto the pixel grid, both when sizing the view itself and when
18+
/// pushing clip rects onto the mutator stack. That shrinks the view by up to a
19+
/// pixel, uncovering a thin line of the Flutter content behind it along the
20+
/// right and bottom edges. These goldens should show a blue box over a red
21+
/// background with no green underlay line around the edges of the box.
22+
///
23+
/// For local debugging, a (local) golden-file is required as a baseline:
24+
///
25+
/// ```sh
26+
/// # Checkout HEAD, i.e. *before* changes you want to test.
27+
/// UPDATE_GOLDENS=1 flutter drive lib/hcpp/platform_view_fractional_size_main.dart
28+
///
29+
/// # Make your changes.
30+
///
31+
/// # Run the test against baseline.
32+
/// flutter drive lib/hcpp/platform_view_fractional_size_main.dart
33+
/// ```
34+
///
35+
/// For a convenient way to deflake a test, see `tool/deflake.dart`.
36+
void main() async {
37+
const goldenPrefix = 'hybrid_composition_pp_platform_view';
38+
39+
late final FlutterDriver flutterDriver;
40+
late final NativeDriver nativeDriver;
41+
42+
setUpAll(() async {
43+
if (isLuci) {
44+
await enableSkiaGoldComparator(namePrefix: 'android_engine_test$goldenVariant');
45+
}
46+
flutterDriver = await FlutterDriver.connect();
47+
nativeDriver = await AndroidNativeDriver.connect(flutterDriver);
48+
await nativeDriver.configureForScreenshotTesting();
49+
await flutterDriver.waitUntilFirstFrameRasterized();
50+
});
51+
52+
tearDownAll(() async {
53+
await nativeDriver.close();
54+
await flutterDriver.close();
55+
});
56+
57+
test('verify that HCPP is supported and enabled', () async {
58+
final response = json.decode(await flutterDriver.requestData('')) as Map<String, Object?>;
59+
60+
expect(response['supported'], true);
61+
}, timeout: Timeout.none);
62+
63+
test('should not leave an underlay-colored line along the edges of the view', () async {
64+
await expectLater(
65+
nativeDriver.screenshot(),
66+
matchesGoldenFile('$goldenPrefix.fractional_size.png'),
67+
);
68+
}, timeout: Timeout.none);
69+
70+
test('should not leave an underlay-colored line along the edges of the clip', () async {
71+
await flutterDriver.tap(find.byValueKey('toggle_clip_button'));
72+
await expectLater(
73+
nativeDriver.screenshot(),
74+
matchesGoldenFile('$goldenPrefix.fractional_size_clipped.png'),
75+
);
76+
}, timeout: Timeout.none);
77+
}

‎engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder.cc‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
// found in the LICENSE file.
44

55
#include "flutter/shell/platform/android/external_view_embedder/external_view_embedder.h"
6+
7+
#include <cmath>
8+
69
#include "flow/view_slicer.h"
710
#include "flutter/common/constants.h"
811
#include "flutter/fml/synchronization/waitable_event.h"
@@ -11,6 +14,26 @@
1114

1215
namespace flutter {
1316

17+
namespace {
18+
19+
// Converts a size in logical pixels to the whole number of physical pixels the
20+
// platform view should be laid out at.
21+
//
22+
// Android view geometry is integral, so this conversion is lossy no matter
23+
// what, but it must *round* rather than truncate. `size_points * dpr` is
24+
// computed in double precision from a float `size_points`, so a platform view
25+
// that exactly covers the screen lands a hair under the physical size (e.g.
26+
// 1079.99996 for a 1080px wide screen at a device pixel ratio of 2.625).
27+
// Truncating that drops a pixel off the right and bottom edges, and the Flutter
28+
// content behind the platform view shows through as a thin line.
29+
//
30+
// See https://github.com/flutter/flutter/issues/189834.
31+
int32_t ToPhysicalPixels(DlScalar size_points, double device_pixel_ratio) {
32+
return static_cast<int32_t>(std::round(size_points * device_pixel_ratio));
33+
}
34+
35+
} // namespace
36+
1437
AndroidExternalViewEmbedder::AndroidExternalViewEmbedder(
1538
const AndroidContext& android_context,
1639
std::shared_ptr<PlatformViewAndroidJNI> jni_facade,
@@ -100,7 +123,9 @@ void AndroidExternalViewEmbedder::SubmitFlutterView(
100123
}
101124

102125
for (int64_t view_id : composition_order_) {
103-
DlRect view_rect = GetViewRect(view_id);
126+
// Round, rather than truncate, the bounds onto the pixel grid. See
127+
// `ToPhysicalPixels` for why.
128+
const DlIRect view_rect = DlIRect::Round(GetViewRect(view_id));
104129
const EmbeddedViewParams& params = view_params_.at(view_id);
105130
// Display the platform view. If it's already displayed, then it's
106131
// just positioned and sized.
@@ -110,8 +135,8 @@ void AndroidExternalViewEmbedder::SubmitFlutterView(
110135
view_rect.GetY(), //
111136
view_rect.GetWidth(), //
112137
view_rect.GetHeight(), //
113-
params.sizePoints().width * device_pixel_ratio_,
114-
params.sizePoints().height * device_pixel_ratio_,
138+
ToPhysicalPixels(params.sizePoints().width, device_pixel_ratio_),
139+
ToPhysicalPixels(params.sizePoints().height, device_pixel_ratio_),
115140
params.mutatorsStack() //
116141
);
117142
std::unordered_map<int64_t, DlRect>::const_iterator overlay =

‎engine/src/flutter/shell/platform/android/external_view_embedder/external_view_embedder_2.cc‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
// found in the LICENSE file.
44

55
#include "flutter/shell/platform/android/external_view_embedder/external_view_embedder_2.h"
6+
7+
#include <cmath>
8+
69
#include "display_list/dl_color.h"
710
#include "flow/view_slicer.h"
811
#include "flutter/fml/synchronization/waitable_event.h"
@@ -12,6 +15,26 @@
1215

1316
namespace flutter {
1417

18+
namespace {
19+
20+
// Converts a size in logical pixels to the whole number of physical pixels the
21+
// platform view should be laid out at.
22+
//
23+
// Android view geometry is integral, so this conversion is lossy no matter
24+
// what, but it must *round* rather than truncate. `size_points * dpr` is
25+
// computed in double precision from a float `size_points`, so a platform view
26+
// that exactly covers the screen lands a hair under the physical size (e.g.
27+
// 1079.99996 for a 1080px wide screen at a device pixel ratio of 2.625).
28+
// Truncating that drops a pixel off the right and bottom edges, and the Flutter
29+
// content behind the platform view shows through as a thin line.
30+
//
31+
// See https://github.com/flutter/flutter/issues/189834.
32+
int32_t ToPhysicalPixels(DlScalar size_points, double device_pixel_ratio) {
33+
return static_cast<int32_t>(std::round(size_points * device_pixel_ratio));
34+
}
35+
36+
} // namespace
37+
1538
AndroidExternalViewEmbedder2::AndroidExternalViewEmbedder2(
1639
const AndroidContext& android_context,
1740
std::shared_ptr<PlatformViewAndroidJNI> jni_facade,
@@ -178,16 +201,19 @@ void AndroidExternalViewEmbedder2::SubmitFlutterView(
178201
}
179202

180203
for (int64_t view_id : composition_order) {
181-
DlRect view_rect = GetViewRect(view_id, view_params);
204+
// Round, rather than truncate, the bounds onto the pixel grid. See
205+
// `ToPhysicalPixels` for why.
206+
const DlIRect view_rect =
207+
DlIRect::Round(GetViewRect(view_id, view_params));
182208
const EmbeddedViewParams& params = view_params.at(view_id);
183209
jni_facade->onDisplayPlatformView2(
184210
view_id, //
185211
view_rect.GetX(), //
186212
view_rect.GetY(), //
187213
view_rect.GetWidth(), //
188214
view_rect.GetHeight(), //
189-
params.sizePoints().width * device_pixel_ratio,
190-
params.sizePoints().height * device_pixel_ratio,
215+
ToPhysicalPixels(params.sizePoints().width, device_pixel_ratio),
216+
ToPhysicalPixels(params.sizePoints().height, device_pixel_ratio),
191217
params.mutatorsStack() //
192218
);
193219
// Remove from views visible last frame, so we can hide the rest.

0 commit comments

Comments
 (0)