Skip to content

Commit 323badc

Browse files
Update TLHC PlatformViewWrapper offset without requesting layout (flutter#194899)
Currently when a TLHC platform view scrolls, `PlatformViewsController.offset` updates the `FrameLayout.LayoutParams` margins and calls `viewWrapper.setLayoutParams(layoutParams)`. Calling `setLayoutParams` triggers `requestLayout()`, which forces a full measure/layout pass and causes `PlatformViewWrapper` to re-record its display list and re-render the embedded view into the render target on every scroll frame, even though only the wrapper's offset changed. 1. Moves offset handling into `PlatformViewWrapper.setOffset(newLeft, newTop)`. 2. Keeps `FrameLayout.LayoutParams` margins updated in place so that any subsequent layout pass preserves the offset, and when already laid out, translates the view directly with `offsetLeftAndRight` and `offsetTopAndBottom` instead of calling `setLayoutParams`. 3. Calls `onScrollChanged` after translating so `ViewTreeObserver.OnScrollChangedListener`s (e.g. `PopupWindow` and ad viewability trackers) still fire when the view moves without a layout pass. 4. Simplifies `PlatformViewWrapper.onTouchEvent` to translate touches using `getLeft()` and `getTop()`, matching `FlutterMutatorView`. Left is before, right is after. There's still some jitter on the right because the recording process running on the device seems to push us in to missing a couple frames, but it's nothing like the bad feedback loop on the left, and also isn't visible locally when I test. https://github.com/user-attachments/assets/8295b58f-4e3b-4399-8535-a6520c533220 Fixes flutter#183626 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. <!-- Links --> [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md Co-authored-by: Gray Mackall <[email protected]>
1 parent 950bf4e commit 323badc

4 files changed

Lines changed: 204 additions & 36 deletions

File tree

‎engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewWrapper.java‎

Lines changed: 38 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,11 @@
1111
import android.graphics.Matrix;
1212
import android.graphics.PorterDuff;
1313
import android.graphics.Rect;
14+
import android.view.Gravity;
1415
import android.view.MotionEvent;
1516
import android.view.Surface;
1617
import android.view.View;
18+
import android.view.ViewGroup;
1719
import android.view.ViewParent;
1820
import android.view.ViewTreeObserver;
1921
import android.view.accessibility.AccessibilityEvent;
@@ -40,10 +42,6 @@
4042
public class PlatformViewWrapper extends FrameLayout {
4143
private static final String TAG = "PlatformViewWrapper";
4244

43-
private int prevLeft;
44-
private int prevTop;
45-
private int left;
46-
private int top;
4745
private AndroidTouchProcessor touchProcessor;
4846
private PlatformViewRenderTarget renderTarget;
4947

@@ -82,15 +80,41 @@ public void setTouchProcessor(@Nullable AndroidTouchProcessor newTouchProcessor)
8280
}
8381

8482
/**
85-
* Sets the layout parameters for this view.
83+
* Moves this view to the given position, in the parent's coordinate space.
8684
*
87-
* @param params The new parameters.
85+
* <p>Only the position of the wrapper changes, which never affects the content rendered into the
86+
* {@link PlatformViewRenderTarget}. To avoid re-rendering the embedded view every frame while
87+
* scrolling, this doesn't request a layout pass (which would also force this view's display list
88+
* to be re-recorded). Instead, the view is translated directly, which only updates its {@code
89+
* RenderNode} properties.
90+
*
91+
* <p>The layout params are kept in sync so that any later layout pass keeps the view at the same
92+
* position.
93+
*
94+
* @param newLeft The new left position, in physical pixels.
95+
* @param newTop The new top position, in physical pixels.
8896
*/
89-
public void setLayoutParams(@NonNull FrameLayout.LayoutParams params) {
90-
super.setLayoutParams(params);
91-
92-
left = params.leftMargin;
93-
top = params.topMargin;
97+
public void setOffset(int newLeft, int newTop) {
98+
final ViewGroup.LayoutParams params = getLayoutParams();
99+
if (params instanceof FrameLayout.LayoutParams) {
100+
final FrameLayout.LayoutParams frameParams = (FrameLayout.LayoutParams) params;
101+
frameParams.leftMargin = newLeft;
102+
frameParams.topMargin = newTop;
103+
frameParams.gravity = Gravity.LEFT | Gravity.TOP;
104+
}
105+
// If the view hasn't been laid out yet, the initial layout pass will position the view using
106+
// the layout params.
107+
if (isLaidOut()) {
108+
final int dx = newLeft - getLeft();
109+
final int dy = newTop - getTop();
110+
if (dx != 0 || dy != 0) {
111+
offsetLeftAndRight(dx);
112+
offsetTopAndBottom(dy);
113+
// Notify ViewTreeObserver.OnScrollChangedListeners (e.g., PopupWindow, AdMob viewability)
114+
// that this view moved without a layout pass, matching RecyclerView.dispatchOnScrolled.
115+
onScrollChanged(getScrollX(), getScrollY(), getScrollX(), getScrollY());
116+
}
117+
}
94118
}
95119

96120
public void resizeRenderTarget(int width, int height) {
@@ -229,26 +253,10 @@ public boolean onTouchEvent(@NonNull MotionEvent event) {
229253
return super.onTouchEvent(event);
230254
}
231255
gestureTracker.onTouchEvent(event, this::requestUnbuffered);
256+
// The parent transformed this event into this view's coordinate space using the view's current
257+
// position, so the same position maps it back into the parent's (the FlutterView's) space.
232258
final Matrix screenMatrix = new Matrix();
233-
switch (event.getAction()) {
234-
case MotionEvent.ACTION_DOWN:
235-
prevLeft = left;
236-
prevTop = top;
237-
screenMatrix.postTranslate(left, top);
238-
break;
239-
case MotionEvent.ACTION_MOVE:
240-
// While the view is dragged, use the left and top positions as
241-
// they were at the moment the touch event fired.
242-
screenMatrix.postTranslate(prevLeft, prevTop);
243-
prevLeft = left;
244-
prevTop = top;
245-
break;
246-
case MotionEvent.ACTION_UP:
247-
case MotionEvent.ACTION_CANCEL:
248-
default:
249-
screenMatrix.postTranslate(left, top);
250-
break;
251-
}
259+
screenMatrix.postTranslate(getLeft(), getTop());
252260
return touchProcessor.onTouchEvent(event, screenMatrix);
253261
}
254262

‎engine/src/flutter/shell/platform/android/io/flutter/plugin/platform/PlatformViewsController.java‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -328,12 +328,7 @@ public void offset(int viewId, double top, double left) {
328328
}
329329
final int physicalTop = toPhysicalPixels(top);
330330
final int physicalLeft = toPhysicalPixels(left);
331-
final FrameLayout.LayoutParams layoutParams =
332-
(FrameLayout.LayoutParams) viewWrapper.getLayoutParams();
333-
layoutParams.topMargin = physicalTop;
334-
layoutParams.leftMargin = physicalLeft;
335-
layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
336-
viewWrapper.setLayoutParams(layoutParams);
331+
viewWrapper.setOffset(physicalLeft, physicalTop);
337332
}
338333

339334
@Override

‎engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/PlatformViewWrapperTest.java‎

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
import android.content.Context;
1414
import android.graphics.Canvas;
1515
import android.graphics.Color;
16+
import android.graphics.Matrix;
17+
import android.view.Gravity;
1618
import android.view.MotionEvent;
1719
import android.view.Surface;
1820
import android.view.View;
@@ -25,6 +27,7 @@
2527
import androidx.test.ext.junit.runners.AndroidJUnit4;
2628
import io.flutter.embedding.android.AndroidTouchProcessor;
2729
import io.flutter.embedding.engine.renderer.FlutterRenderer;
30+
import java.util.List;
2831
import org.junit.Test;
2932
import org.junit.runner.RunWith;
3033
import org.mockito.ArgumentCaptor;
@@ -300,6 +303,123 @@ void requestUnbuffered(MotionEvent event) {
300303
assertFalse(view.getFlutterWonGesture());
301304
}
302305

306+
/** Adds {@code wrapper} to a laid out parent at the given position. */
307+
private FrameLayout layOutInParent(PlatformViewWrapper wrapper, int left, int top) {
308+
final FrameLayout.LayoutParams params =
309+
new FrameLayout.LayoutParams(10, 10, Gravity.LEFT | Gravity.TOP);
310+
params.leftMargin = left;
311+
params.topMargin = top;
312+
wrapper.setLayoutParams(params);
313+
final FrameLayout parent = new FrameLayout(ctx);
314+
parent.addView(wrapper);
315+
parent.measure(
316+
View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY),
317+
View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY));
318+
parent.layout(0, 0, 100, 100);
319+
return parent;
320+
}
321+
322+
@Test
323+
public void setOffset_movesViewWithoutRequestingLayout() {
324+
final int[] scrollChangedCalls = new int[1];
325+
final PlatformViewWrapper wrapper =
326+
new PlatformViewWrapper(ctx) {
327+
@Override
328+
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
329+
super.onScrollChanged(l, t, oldl, oldt);
330+
scrollChangedCalls[0]++;
331+
}
332+
};
333+
final FrameLayout parent = layOutInParent(wrapper, 1, 2);
334+
assertEquals(1, wrapper.getLeft());
335+
assertEquals(2, wrapper.getTop());
336+
assertFalse(wrapper.isLayoutRequested());
337+
338+
wrapper.setOffset(30, 40);
339+
340+
// The view is moved immediately, without a layout pass, and scroll listeners are notified.
341+
assertFalse(wrapper.isLayoutRequested());
342+
assertFalse(parent.isLayoutRequested());
343+
assertEquals(30, wrapper.getLeft());
344+
assertEquals(40, wrapper.getTop());
345+
assertEquals(40, wrapper.getRight());
346+
assertEquals(50, wrapper.getBottom());
347+
assertEquals(1, scrollChangedCalls[0]);
348+
349+
// Setting the same offset again is a no-op.
350+
wrapper.setOffset(30, 40);
351+
assertEquals(1, scrollChangedCalls[0]);
352+
353+
// The layout params are kept in sync, so a later layout pass keeps the position.
354+
final FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) wrapper.getLayoutParams();
355+
assertEquals(30, params.leftMargin);
356+
assertEquals(40, params.topMargin);
357+
parent.requestLayout();
358+
parent.measure(
359+
View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY),
360+
View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY));
361+
parent.layout(0, 0, 100, 100);
362+
assertEquals(30, wrapper.getLeft());
363+
assertEquals(40, wrapper.getTop());
364+
}
365+
366+
@Test
367+
public void setOffset_beforeLayout_onlyUpdatesLayoutParams() {
368+
final PlatformViewWrapper wrapper = new PlatformViewWrapper(ctx);
369+
wrapper.setLayoutParams(new FrameLayout.LayoutParams(10, 10));
370+
371+
wrapper.setOffset(30, 40);
372+
373+
final FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) wrapper.getLayoutParams();
374+
assertEquals(30, params.leftMargin);
375+
assertEquals(40, params.topMargin);
376+
assertEquals(Gravity.LEFT | Gravity.TOP, params.gravity);
377+
assertEquals(0, wrapper.getLeft());
378+
assertEquals(0, wrapper.getTop());
379+
}
380+
381+
@Test
382+
public void setOffset_whileLayoutRequested_stillMovesImmediately() {
383+
final PlatformViewWrapper wrapper = new PlatformViewWrapper(ctx);
384+
layOutInParent(wrapper, 1, 2);
385+
wrapper.requestLayout();
386+
assertTrue(wrapper.isLayoutRequested());
387+
388+
wrapper.setOffset(30, 40);
389+
390+
assertEquals(30, wrapper.getLeft());
391+
assertEquals(40, wrapper.getTop());
392+
}
393+
394+
@Test
395+
public void onTouchEvent_translatesByCurrentPosition() {
396+
final AndroidTouchProcessor touchProcessor = mock(AndroidTouchProcessor.class);
397+
final PlatformViewWrapper wrapper = new PlatformViewWrapper(ctx);
398+
wrapper.setTouchProcessor(touchProcessor);
399+
layOutInParent(wrapper, 5, 6);
400+
final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class);
401+
402+
final MotionEvent downEvent =
403+
MotionEvent.obtain(100, 100, MotionEvent.ACTION_DOWN, 1.0f, 1.0f, 0);
404+
wrapper.onTouchEvent(downEvent);
405+
406+
// The view moves (e.g. the list scrolls) in the middle of the gesture.
407+
wrapper.setOffset(15, 26);
408+
final MotionEvent moveEvent =
409+
MotionEvent.obtain(100, 101, MotionEvent.ACTION_MOVE, 2.0f, 2.0f, 0);
410+
wrapper.onTouchEvent(moveEvent);
411+
412+
verify(touchProcessor, times(2)).onTouchEvent(any(MotionEvent.class), matrixCaptor.capture());
413+
final List<Matrix> matrices = matrixCaptor.getAllValues();
414+
final float[] values = new float[9];
415+
matrices.get(0).getValues(values);
416+
assertEquals(5f, values[Matrix.MTRANS_X], 0f);
417+
assertEquals(6f, values[Matrix.MTRANS_Y], 0f);
418+
matrices.get(1).getValues(values);
419+
assertEquals(15f, values[Matrix.MTRANS_X], 0f);
420+
assertEquals(26f, values[Matrix.MTRANS_Y], 0f);
421+
}
422+
303423
@Implements(ViewGroup.class)
304424
public static class ShadowViewGroup extends org.robolectric.shadows.ShadowViewGroup {
305425
@Implementation

‎engine/src/flutter/shell/platform/android/test/io/flutter/plugin/platform/PlatformViewsControllerTest.java‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2121,6 +2121,51 @@ public void onRejectGesture_informsViewWrapperFlutterWonGesture_forTextureLayer(
21212121
assertFalse(wrapper.getFlutterWonGesture());
21222122
}
21232123

2124+
@Test
2125+
@Config(shadows = {ShadowFlutterJNI.class, ShadowPlatformTaskQueue.class})
2126+
public void offset_updatesViewWrapperOffsetWithoutRequestingLayout() {
2127+
final PlatformViewsController platformViewsController = new PlatformViewsController();
2128+
final int platformViewId = 0;
2129+
2130+
final PlatformViewFactory viewFactory = mock(PlatformViewFactory.class);
2131+
final PlatformView platformView = mock(PlatformView.class);
2132+
final View androidView = new View(ApplicationProvider.getApplicationContext());
2133+
when(platformView.getView()).thenReturn(androidView);
2134+
when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView);
2135+
platformViewsController.getRegistry().registerViewFactory("testType", viewFactory);
2136+
2137+
final FlutterJNI jni = new FlutterJNI();
2138+
jni.attachToNative();
2139+
platformViewsController.setFlutterJNI(jni);
2140+
attach(jni, platformViewsController);
2141+
2142+
createPlatformView(
2143+
jni, platformViewsController, platformViewId, "testType", /* hybrid=*/ false);
2144+
2145+
final PlatformViewWrapper wrapper = platformViewsController.getViewWrapper(platformViewId);
2146+
assertNotNull(wrapper);
2147+
final View parent = (View) wrapper.getParent();
2148+
parent.measure(
2149+
View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY),
2150+
View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY));
2151+
parent.layout(0, 0, 100, 100);
2152+
assertFalse(wrapper.isLayoutRequested());
2153+
2154+
final Map<String, Object> offsetArgs = new HashMap<>();
2155+
offsetArgs.put("id", platformViewId);
2156+
offsetArgs.put("top", 20.0);
2157+
offsetArgs.put("left", 10.0);
2158+
jni.handlePlatformMessage(
2159+
"flutter/platform_views",
2160+
encodeMethodCall(new MethodCall("offset", offsetArgs)),
2161+
/*replyId=*/ 0,
2162+
/*messageData=*/ 0);
2163+
2164+
assertFalse(wrapper.isLayoutRequested());
2165+
assertEquals(10, wrapper.getLeft());
2166+
assertEquals(20, wrapper.getTop());
2167+
}
2168+
21242169
private static ByteBuffer encodeMethodCall(MethodCall call) {
21252170
final ByteBuffer buffer = StandardMethodCodec.INSTANCE.encodeMethodCall(call);
21262171
buffer.rewind();

0 commit comments

Comments
 (0)