Merge cherrypicks of ['googleplex-android-review.googlesource.com/42173541', 'googleplex-android-review.googlesource.com/42552066', 'googleplex-android-review.googlesource.com/42604129'] into 26Q4-release. Change-Id: I095f4f9e3036f489be6b832b5d25db2d75fb77c3
diff --git a/core/java/com/android/internal/widget/remotecompose/core/CoreDocument.java b/core/java/com/android/internal/widget/remotecompose/core/CoreDocument.java index 7205ac2..f1569c8 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/CoreDocument.java +++ b/core/java/com/android/internal/widget/remotecompose/core/CoreDocument.java
@@ -32,6 +32,7 @@ import com.android.internal.widget.remotecompose.core.operations.DrawContent; import com.android.internal.widget.remotecompose.core.operations.FloatConstant; import com.android.internal.widget.remotecompose.core.operations.FloatExpression; +import com.android.internal.widget.remotecompose.core.operations.FloatFunctionDefine; import com.android.internal.widget.remotecompose.core.operations.Header; import com.android.internal.widget.remotecompose.core.operations.IntegerExpression; import com.android.internal.widget.remotecompose.core.operations.NamedVariable; @@ -52,11 +53,13 @@ import com.android.internal.widget.remotecompose.core.operations.layout.managers.LayoutManager; import com.android.internal.widget.remotecompose.core.operations.layout.modifiers.ComponentModifiers; import com.android.internal.widget.remotecompose.core.operations.layout.modifiers.ModifierOperation; +import com.android.internal.widget.remotecompose.core.operations.layout.modifiers.ScrollModifierOperation; import com.android.internal.widget.remotecompose.core.operations.loom.LoomManager; import com.android.internal.widget.remotecompose.core.operations.loom.PatternCallback; import com.android.internal.widget.remotecompose.core.operations.utilities.ArrayAccess; import com.android.internal.widget.remotecompose.core.operations.utilities.IntMap; import com.android.internal.widget.remotecompose.core.operations.utilities.StringSerializer; +import com.android.internal.widget.remotecompose.core.semantics.ScrollableComponent; import com.android.internal.widget.remotecompose.core.serialize.MapSerializer; import com.android.internal.widget.remotecompose.core.serialize.Serializable; import com.android.internal.widget.remotecompose.core.types.IntegerConstant; @@ -80,18 +83,18 @@ // Semantic version public static final int MAJOR_VERSION = 1; - public static final int MINOR_VERSION = 4; + public static final int MINOR_VERSION = 5; public static final int PATCH_VERSION = 0; // Internal version level - public static final int DOCUMENT_API_LEVEL = 10; + public static final int DOCUMENT_API_LEVEL = 11; static final int PROFILE_WIDGETS = 0x100; static final int PROFILE_ANDROIDX = 0x200; // REMOVE IN PLATFORM public static final int PROFILE = PROFILE_ANDROIDX; // We also keep a more fine-grained BUILD number, exposed as // ID_API_LEVEL = DOCUMENT_API_LEVEL + BUILD - static final float BUILD = 0.1f; + static final float BUILD = 0.0f; private static final boolean UPDATE_VARIABLES_BEFORE_LAYOUT = false; @@ -113,6 +116,8 @@ private static final int DEFAULT_FEATURE_PRIORITY_FIX = 1; private static final int DEFAULT_FEATURE_LT_RESIZE = 1; private static final int DEFAULT_FEATURE_ARRAY_LISTENERS = 1; + private static final int DEFAULT_FEATURE_DISALLOW_INTERCEPT_TOUCH = 1; + private static final int DEFAULT_FEATURE_DATA_PASS_CANVAS_OPS = 1; public static final int OPTIMIZATION_NONE = 0; public static final int OPTIMIZATION_MEASURE_CACHE = 1; public static final int OPTIMIZATION_LAYOUT_BOUNDARIES = 2; @@ -140,6 +145,7 @@ boolean mUseFeaturePaintMeasure; boolean mUseFeaturePriorityFix; boolean mUseFeatureLTResize; + boolean mUseFeatureDataPassCanvasOps; int mMeasureVersion = DEFAULT_FEATURE_MEASURE_VERSION; int mTouchVersion = DEFAULT_FEATURE_TOUCH_VERSION; @@ -860,6 +866,12 @@ if (featureId == Header.FEATURE_ARRAY_LISTENERS) { return useFeature(featureId, DEFAULT_FEATURE_ARRAY_LISTENERS); } + if (featureId == Header.FEATURE_DISALLOW_INTERCEPT_TOUCH) { + return useFeature(featureId, DEFAULT_FEATURE_DISALLOW_INTERCEPT_TOUCH); + } + if (featureId == Header.FEATURE_DATA_PASS_CANVAS_OPS) { + return useFeature(featureId, DEFAULT_FEATURE_DATA_PASS_CANVAS_OPS); + } return useFeature(featureId, 0); } @@ -1248,9 +1260,13 @@ currentLastLayout = (LayoutComponent) component; } } else if (o instanceof Container) { - finishInflation(((Container) o).getList(), parent, currentLastLayout); - if (o instanceof CanvasOperations) { - ((CanvasOperations) o).setComponent(currentLastLayout); + if (o instanceof FloatFunctionDefine) { + finishInflation(((Container) o).getList(), null, null); + } else { + finishInflation(((Container) o).getList(), parent, currentLastLayout); + if (o instanceof CanvasOperations) { + ((CanvasOperations) o).setComponent(currentLastLayout); + } } } else if (o instanceof DrawContent) { ((DrawContent) o).setComponent(currentLastLayout); @@ -1303,6 +1319,7 @@ mUseFeaturePaintMeasure = useFeature(Header.FEATURE_PAINT_MEASURE); mUseFeaturePriorityFix = useFeature(Header.FEATURE_PRIORITY_FIX); mUseFeatureLTResize = useFeature(Header.FEATURE_LT_RESIZE); + mUseFeatureDataPassCanvasOps = useFeature(Header.FEATURE_DATA_PASS_CANVAS_OPS); mMeasureVersion = featureIntValue(Header.FEATURE_MEASURE_VERSION); int optLevel = featureIntValue(Header.FEATURE_OPTIMIZATION_LEVEL); @@ -1569,6 +1586,13 @@ if (op instanceof ComponentData) { op.apply(context); } + if (mUseFeatureDataPassCanvasOps && op instanceof LayoutComponent) { + LayoutComponent layoutComponent = (LayoutComponent) op; + CanvasOperations canvasOperations = layoutComponent.getCanvasOperations(); + if (canvasOperations != null) { + applyOperations(context, canvasOperations.getList()); + } + } applyOperations(context, ((Container) op).getList()); } else { op.apply(context); @@ -1850,6 +1874,163 @@ return hasComponentsTouchListeners || !mTouchListeners.isEmpty(); } + /** + * Returns true if the document declares vertical scrolling. + * + * <p>Checks the {@link Header#DOC_SCROLL} header property and the {@link RootContentBehavior} + * scroll mode, then every {@link ScrollableComponent}, {@link ScrollModifierOperation} and + * {@link ComponentModifiers} in the operations tree. The header property can only add vertical + * scrolling: a document with a vertical scroll container returns true whatever it says. + * + * <p>Note: this is a structural check that ignores layout and visibility. It returns true even + * if the scrollable content currently fits in its container, or is hidden. + * + * @return true if the document contains a vertical scroll container, or its header declares + * vertical scrolling + */ + public boolean hasVerticalScroll() { + if ((declaredScroll() & Header.SCROLL_VERTICAL) != 0) { + return true; + } + if ((mContentScroll & RootContentBehavior.SCROLL_VERTICAL) != 0) { + return true; + } + return hasVerticalScroll(mOperations); + } + + private static boolean hasVerticalScroll(@Nullable List<Operation> operations) { + if (operations == null) { + return false; + } + for (Operation op : operations) { + if (op instanceof ScrollableComponent + && ((ScrollableComponent) op).scrollDirection() + == ScrollableComponent.SCROLL_VERTICAL) { + return true; + } + if (op instanceof ScrollModifierOperation + && ((ScrollModifierOperation) op).isVerticalScroll()) { + return true; + } + if (op instanceof ComponentModifiers && ((ComponentModifiers) op).hasVerticalScroll()) { + return true; + } + if (op instanceof Container && hasVerticalScroll(((Container) op).getList())) { + return true; + } + } + return false; + } + + /** + * Returns true if the document declares horizontal scrolling. + * + * <p>Checks the {@link Header#DOC_SCROLL} header property and the {@link RootContentBehavior} + * scroll mode, then every {@link ScrollableComponent}, {@link ScrollModifierOperation} and + * {@link ComponentModifiers} in the operations tree. The header property can only add + * horizontal scrolling: a document with a horizontal scroll container returns true whatever it + * says. + * + * <p>Note: this is a structural check that ignores layout and visibility. It returns true even + * if the scrollable content currently fits in its container, or is hidden. + * + * @return true if the document contains a horizontal scroll container, or its header declares + * horizontal scrolling + */ + public boolean hasHorizontalScroll() { + if ((declaredScroll() & Header.SCROLL_HORIZONTAL) != 0) { + return true; + } + if ((mContentScroll & RootContentBehavior.SCROLL_HORIZONTAL) != 0) { + return true; + } + return hasHorizontalScroll(mOperations); + } + + private static boolean hasHorizontalScroll(@Nullable List<Operation> operations) { + if (operations == null) { + return false; + } + for (Operation op : operations) { + if (op instanceof ScrollableComponent + && ((ScrollableComponent) op).scrollDirection() + == ScrollableComponent.SCROLL_HORIZONTAL) { + return true; + } + if (op instanceof ScrollModifierOperation + && ((ScrollModifierOperation) op).isHorizontalScroll()) { + return true; + } + if (op instanceof ComponentModifiers + && ((ComponentModifiers) op).hasHorizontalScroll()) { + return true; + } + if (op instanceof Container && hasHorizontalScroll(((Container) op).getList())) { + return true; + } + } + return false; + } + + /** + * Returns the scroll directions declared by the {@link Header#DOC_SCROLL} header property, or 0 + * if there is none. The header is read when the document is loaded, so this doesn't need an + * initialized context. A value that isn't an INT declares nothing. + */ + private int declaredScroll() { + Object value = mHeader == null ? null : mHeader.get(Header.DOC_SCROLL); + return value instanceof Integer ? (Integer) value : 0; + } + + /** + * Returns true if there are active applied touch operations (e.g. scroll or drag). + * + * @return true if there are applied touch operations + */ + public boolean hasAppliedTouchOperations() { + return !mAppliedTouchOperations.isEmpty() || !mTouchListeners.isEmpty(); + } + + /** + * Returns true if any active applied touch operation can consume horizontal drag. + * + * @return true if horizontal scrolling or drag is supported + */ + public boolean canScrollHorizontally() { + if (!mTouchListeners.isEmpty()) { + return true; + } + for (Component component : mAppliedTouchOperations) { + if (component.hasHorizontalScroll()) { + return true; + } + if (!component.hasVerticalScroll()) { + return true; + } + } + return false; + } + + /** + * Returns true if any active applied touch operation can consume vertical drag. + * + * @return true if vertical scrolling or drag is supported + */ + public boolean canScrollVertically() { + if (!mTouchListeners.isEmpty()) { + return true; + } + for (Component component : mAppliedTouchOperations) { + if (component.hasVerticalScroll()) { + return true; + } + if (!component.hasHorizontalScroll()) { + return true; + } + } + return false; + } + // TODO support velocity estimate support, support regions /** @@ -2237,6 +2418,12 @@ mRepaintNext = 1; mRootLayoutComponent.clearNeedsBoundsAnimation(); mRootLayoutComponent.animatingBounds(context); + if (mRootLayoutComponent.needsMeasure()) { + mRootLayoutComponent.layout(context); + if (mLayoutCallback != null) { + mLayoutCallback.onRequestLayout(); + } + } } if (DEBUG) { String hierarchy = mRootLayoutComponent.displayHierarchy(); @@ -2551,6 +2738,7 @@ String str = context.getText(id); if (str != null) { sd.enable(ctl.isShaderValid(str)); + sd.apply(context); } } }
diff --git a/core/java/com/android/internal/widget/remotecompose/core/Limits.java b/core/java/com/android/internal/widget/remotecompose/core/Limits.java index c5b419a..e59c170 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/Limits.java +++ b/core/java/com/android/internal/widget/remotecompose/core/Limits.java
@@ -23,6 +23,9 @@ /** Default initial size of the wire buffer */ public static final int BUFFER_SIZE = 1024 * 1024; + /** Maximum size in bytes of the operations of a compressed document, once decompressed */ + public static int MAX_DECOMPRESSED_SIZE = 32 * 1024 * 1024; + /** Maximum number of entries in the ID lookup table (bitmaps, fonts, etc.) */ public static final int MAX_TABLE_SIZE = 1000; @@ -41,6 +44,9 @@ /** Maximum memory allowed for bitmaps in a single player instance (in bytes) */ public static int MAX_BITMAP_MEMORY = 20 * 1024 * 1024; + /** Maximum number of reusable offscreen bitmaps in the player pool */ + public static final int MAX_BITMAP_POOL_SIZE = 8; + /** Default maximum frames per second for the player */ public static int DEFAULT_MAX_FPS = 60; @@ -104,5 +110,39 @@ /** Allow host actions to be called from run actions */ public static boolean ENABLE_RUN_ACTION_HOST_ACTIONS = false; + /** + * Maximum vertices in a single 2D mesh. + * + * <p>Hard-capped by the platform: Android's {@code Canvas.drawVertices} takes {@code short[]} + * indices and Skia's {@code SkVertices} takes {@code uint16_t}, so 65535 is a ceiling rather + * than a policy choice. The value below is a deliberately stricter policy limit; raise it with + * evidence. + */ + public static final int MAX_MESH_2D_VERTICES = 16384; + + /** Maximum indices (3 per triangle) in a single 2D mesh. */ + public static final int MAX_MESH_2D_INDICES = 49152; + + /** Maximum meshes retained per document. Each holds its vertex arrays until replaced. */ + public static final int MAX_MESH_2D_COUNT = 64; + + /** + * Maximum {@code uCount * vCount} for a parametric mesh, before expansion to a triangle list. + * + * <p>This is the one an author trips: uCount and vCount multiply, so {@code 256 x 256} reads as + * two small numbers and is 65536 vertices. Checking the product at parse time is the difference + * between a clear rejection and a player-specific stall. + */ + public static final int MAX_MESH_2D_GRID = 16384; + + /** + * Maximum width control points on a spline path strip. + * + * <p>A ribbon's width profile is a shape, not a data set: a handful of control points and the + * monotonic fit does the rest. Anyone needing more than this wants the explicit vertex types + * instead. + */ + public static final int MAX_MESH_2D_WIDTH_SAMPLES = 64; + private Limits() {} }
diff --git a/core/java/com/android/internal/widget/remotecompose/core/Operations.java b/core/java/com/android/internal/widget/remotecompose/core/Operations.java index 5cdc204..8f04bb3 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/Operations.java +++ b/core/java/com/android/internal/widget/remotecompose/core/Operations.java
@@ -23,6 +23,7 @@ import android.annotation.NonNull; import android.annotation.Nullable; +import com.android.internal.widget.remotecompose.core.operations.AddMesh2D; import com.android.internal.widget.remotecompose.core.operations.BitmapData; import com.android.internal.widget.remotecompose.core.operations.BitmapFontData; import com.android.internal.widget.remotecompose.core.operations.BitmapTextMeasure; @@ -51,6 +52,7 @@ import com.android.internal.widget.remotecompose.core.operations.DrawCircle; import com.android.internal.widget.remotecompose.core.operations.DrawContent; import com.android.internal.widget.remotecompose.core.operations.DrawLine; +import com.android.internal.widget.remotecompose.core.operations.DrawMesh2D; import com.android.internal.widget.remotecompose.core.operations.DrawOval; import com.android.internal.widget.remotecompose.core.operations.DrawPath; import com.android.internal.widget.remotecompose.core.operations.DrawRect; @@ -61,6 +63,7 @@ import com.android.internal.widget.remotecompose.core.operations.DrawTextOnPath; import com.android.internal.widget.remotecompose.core.operations.DrawToBitmap; import com.android.internal.widget.remotecompose.core.operations.DrawTweenPath; +import com.android.internal.widget.remotecompose.core.operations.EventActionOperation; import com.android.internal.widget.remotecompose.core.operations.FloatConstant; import com.android.internal.widget.remotecompose.core.operations.FloatExpression; import com.android.internal.widget.remotecompose.core.operations.FloatFunctionCall; @@ -72,6 +75,7 @@ import com.android.internal.widget.remotecompose.core.operations.ImageAttribute; import com.android.internal.widget.remotecompose.core.operations.IncludeReferencedOperations; import com.android.internal.widget.remotecompose.core.operations.IntegerExpression; +import com.android.internal.widget.remotecompose.core.operations.MatrixFromMesh2D; import com.android.internal.widget.remotecompose.core.operations.MatrixFromPath; import com.android.internal.widget.remotecompose.core.operations.MatrixRestore; import com.android.internal.widget.remotecompose.core.operations.MatrixRotate; @@ -200,6 +204,9 @@ /// ///////////////////////////////////// public static final int HEADER = 0; + // Opcode 120 (0x78) is reserved: it is the first byte of a compressed document's operations + // (see Header#COMPRESS), so players that can't decompress stop on an unknown operation instead + // of misreading the document. public static final int LOAD_BITMAP = 4; public static final int THEME = 63; public static final int CLICK_AREA = 64; @@ -245,6 +252,12 @@ public static final int DATA_PATH = 123; public static final int DRAW_PATH = 124; public static final int DRAW_TWEEN_PATH = 125; + + // --- 2D vertex mesh family ------------------------------------------------- + // Deliberately separate from and independent of 3D + public static final int ADD_MESH_2D = 104; + public static final int DRAW_MESH_2D = 105; + public static final int MATRIX_FROM_MESH_2D = 106; public static final int DRAW_CONTENT = 139; public static final int MATRIX_SCALE = 126; public static final int MATRIX_TRANSLATE = 127; @@ -329,6 +342,11 @@ ///////////////////////////////////////// ====================== //////////////////////////////////////// + // Communication + //////////////////////////////////////// + public static final int EVENT_ACTION = 110; + + //////////////////////////////////////// // Layout commands /// ///////////////////////////////////// @@ -417,6 +435,7 @@ static UniqueIntMap<CompanionOperation> sMapV7Widgets; static UniqueIntMap<CompanionOperation> sMapV7WidgetsExperimental; static UniqueIntMap<CompanionOperation> sMapV7WidgetsDeprecated; + static UniqueIntMap<CompanionOperation> sAllOperationsV7; private static final Object sLock = new Object(); @@ -443,24 +462,111 @@ } } + /** Returns the companion operation reader for a given operation ID and API level. */ + public static @Nullable CompanionOperation getOperation(int apiLevel, int opId) { + UniqueIntMap<CompanionOperation> map = getAllKnownOperations(apiLevel); + return map != null ? map.get(opId) : null; + } + + /** Returns a map of all known operations across all profiles for the given api level */ + public static @Nullable UniqueIntMap<CompanionOperation> getAllKnownOperations(int apiLevel) { + synchronized (sLock) { + if (apiLevel <= 6) { + if (sMapV6 == null) { + sMapV6 = createMapV6(); + } + return sMapV6; + } + // API level 7 and above + if (sAllOperationsV7 == null) { + sAllOperationsV7 = new UniqueIntMap<>(); + fillDefaultVersionMap(sAllOperationsV7); + + sAllOperationsV7.put(REM, Rem::read); + sAllOperationsV7.put(MATRIX_CONSTANT, MatrixConstant::read); + sAllOperationsV7.put(MATRIX_EXPRESSION, MatrixExpression::read); + sAllOperationsV7.put(MATRIX_VECTOR_MATH, MatrixVectorMath::read); + + sAllOperationsV7.put(MATRIX_FROM_PATH, MatrixFromPath::read); + sAllOperationsV7.put(TEXT_SUBTEXT, TextSubtext::read); + sAllOperationsV7.put(BITMAP_TEXT_MEASURE, BitmapTextMeasure::read); + sAllOperationsV7.put( + DRAW_BITMAP_FONT_TEXT_RUN_ON_PATH, DrawBitmapFontTextOnPath::read); + sAllOperationsV7.put(DRAW_BITMAP_TEXT_ANCHORED, DrawBitmapTextAnchored::read); + sAllOperationsV7.put(DATA_SHADER, ShaderData::read); + sAllOperationsV7.put(DATA_FONT, FontData::read); + sAllOperationsV7.put(DRAW_TO_BITMAP, DrawToBitmap::read); + sAllOperationsV7.put(WAKE_IN, WakeIn::read); + sAllOperationsV7.put(ID_LOOKUP, IdLookup::read); + sAllOperationsV7.put(PATH_EXPRESSION, PathExpression::read); + sAllOperationsV7.put(PARTICLE_COMPARE, ParticlesCompare::read); + sAllOperationsV7.put(DYNAMIC_FLOAT_LIST, DataDynamicListFloat::read); + sAllOperationsV7.put(UPDATE_DYNAMIC_FLOAT_LIST, UpdateDynamicFloatList::read); + sAllOperationsV7.put(SKIP, Skip::read); + sAllOperationsV7.put(CORE_TEXT, CoreText::read); + sAllOperationsV7.put(TEXT_STYLE, TextStyle::read); + sAllOperationsV7.put(TEXT_TRANSFORM, TextTransform::read); + sAllOperationsV7.put(COLOR_THEME, ColorTheme::read); + + sAllOperationsV7.put(MODIFIER_ALIGN_BY, AlignByModifierOperation::read); + sAllOperationsV7.put(LAYOUT_COMPUTE, LayoutComputeOperation::read); + sAllOperationsV7.put(LAYOUT_FLOW, FlowLayout::read); + sAllOperationsV7.put(MODIFIER_MULTI_CLICK, MultiClickModifier::read); + sAllOperationsV7.put( + MODIFIER_DIMENSION_CONSTRAINTS, + DimensionConstraintsModifierOperation::read); + sAllOperationsV7.put(REFERENCED_OPERATIONS, ReferencedOperations::read); + sAllOperationsV7.put( + INCLUDE_REFERENCED_OPERATIONS, IncludeReferencedOperations::read); + + sAllOperationsV7.put(MACRO_DEFINE, PatternDefine::read); + sAllOperationsV7.put(MACRO_CALL, PatternInflation::read); + sAllOperationsV7.put(MACRO_ARGUMENT, PatternArgument::read); + sAllOperationsV7.put(MACRO_BLOCK, PatternBlock::read); + sAllOperationsV7.put(MACRO_FOR_EACH, PatternForEach::read); + sAllOperationsV7.put(LAYOUT_CUSTOM, Custom::read); + sAllOperationsV7.put(DATA_SOUND, SoundData::read); + sAllOperationsV7.put(SOUND_EXPRESSION, SoundExpression::read); + sAllOperationsV7.put(PLAY_SOUND, PlaySound::read); + sAllOperationsV7.put(EVENT_ACTION, EventActionOperation::read); + sAllOperationsV7.put(ADD_MESH_2D, AddMesh2D::read); + sAllOperationsV7.put(DRAW_MESH_2D, DrawMesh2D::read); + sAllOperationsV7.put(MATRIX_FROM_MESH_2D, MatrixFromMesh2D::read); + + sAllOperationsV7.put(ROOT_CONTENT_BEHAVIOR, RootContentBehavior::read); + } + return sAllOperationsV7; + } + } + /** Returns a map of operations for the given api level */ public static @Nullable UniqueIntMap<CompanionOperation> getOperations( int apiLevel, int profiles) { - if (apiLevel < 6) { - return createMapV6(); - } synchronized (sLock) { - switch (apiLevel) { - case 6: - if (sMapV6 == null) { - sMapV6 = createMapV6(); - } - return sMapV6; - default: // 7 and above - if (sMapV7 == null || !sMapV7.containsKey(profiles)) { - sMapV7 = createMapV7(sMapV7, profiles); - } - return sMapV7.get(profiles); + if (apiLevel <= 6) { + if (sMapV6 == null) { + sMapV6 = createMapV6(); + } + return sMapV6; + } + // API level 7 and above + if (sMapV7 == null || !sMapV7.containsKey(profiles)) { + sMapV7 = createMapV7(sMapV7, profiles); + } + return sMapV7.get(profiles); + } + } + + private static void populateMapFromAll( + UniqueIntMap<CompanionOperation> targetMap, int apiLevel, int... opIds) { + UniqueIntMap<CompanionOperation> allOps = getAllKnownOperations(apiLevel); + if (allOps == null) { + return; + } + for (int opId : opIds) { + CompanionOperation companion = allOps.get(opId); + if (companion != null) { + targetMap.put(opId, companion); } } } @@ -476,25 +582,28 @@ private static UniqueIntMap<CompanionOperation> createMapV7_Androidx() { if (sMapV7AndroidX == null) { sMapV7AndroidX = new UniqueIntMap<>(); - sMapV7AndroidX.put(MATRIX_FROM_PATH, MatrixFromPath::read); - sMapV7AndroidX.put(TEXT_SUBTEXT, TextSubtext::read); - sMapV7AndroidX.put(BITMAP_TEXT_MEASURE, BitmapTextMeasure::read); - sMapV7AndroidX.put(DRAW_BITMAP_FONT_TEXT_RUN_ON_PATH, DrawBitmapFontTextOnPath::read); - sMapV7AndroidX.put(DRAW_BITMAP_TEXT_ANCHORED, DrawBitmapTextAnchored::read); - sMapV7AndroidX.put(DATA_SHADER, ShaderData::read); - sMapV7AndroidX.put(DATA_FONT, FontData::read); - sMapV7AndroidX.put(DRAW_TO_BITMAP, DrawToBitmap::read); - sMapV7AndroidX.put(WAKE_IN, WakeIn::read); - sMapV7AndroidX.put(ID_LOOKUP, IdLookup::read); - sMapV7AndroidX.put(PATH_EXPRESSION, PathExpression::read); - sMapV7AndroidX.put(PARTICLE_COMPARE, ParticlesCompare::read); - sMapV7AndroidX.put(DYNAMIC_FLOAT_LIST, DataDynamicListFloat::read); - sMapV7AndroidX.put(UPDATE_DYNAMIC_FLOAT_LIST, UpdateDynamicFloatList::read); - sMapV7AndroidX.put(SKIP, Skip::read); - sMapV7AndroidX.put(CORE_TEXT, CoreText::read); - sMapV7AndroidX.put(TEXT_STYLE, TextStyle::read); - sMapV7AndroidX.put(TEXT_TRANSFORM, TextTransform::read); - sMapV7AndroidX.put(COLOR_THEME, ColorTheme::read); + populateMapFromAll( + sMapV7AndroidX, + 7, + MATRIX_FROM_PATH, + TEXT_SUBTEXT, + BITMAP_TEXT_MEASURE, + DRAW_BITMAP_FONT_TEXT_RUN_ON_PATH, + DRAW_BITMAP_TEXT_ANCHORED, + DATA_SHADER, + DATA_FONT, + DRAW_TO_BITMAP, + WAKE_IN, + ID_LOOKUP, + PATH_EXPRESSION, + PARTICLE_COMPARE, + DYNAMIC_FLOAT_LIST, + UPDATE_DYNAMIC_FLOAT_LIST, + SKIP, + CORE_TEXT, + TEXT_STYLE, + TEXT_TRANSFORM, + COLOR_THEME); } return sMapV7AndroidX; } @@ -502,27 +611,29 @@ private static UniqueIntMap<CompanionOperation> createMapV7_Androidx_Experimental() { if (sMapV7AndroidXExperimental == null) { sMapV7AndroidXExperimental = new UniqueIntMap<>(); - // add experimental operations for this profile here - sMapV7AndroidXExperimental.put(MODIFIER_ALIGN_BY, AlignByModifierOperation::read); - sMapV7AndroidXExperimental.put(LAYOUT_COMPUTE, LayoutComputeOperation::read); - sMapV7AndroidXExperimental.put(LAYOUT_FLOW, FlowLayout::read); - sMapV7AndroidXExperimental.put(MODIFIER_MULTI_CLICK, MultiClickModifier::read); - sMapV7AndroidXExperimental.put( - MODIFIER_DIMENSION_CONSTRAINTS, DimensionConstraintsModifierOperation::read); - - sMapV7AndroidXExperimental.put(REFERENCED_OPERATIONS, ReferencedOperations::read); - sMapV7AndroidXExperimental.put( - INCLUDE_REFERENCED_OPERATIONS, IncludeReferencedOperations::read); - - sMapV7AndroidXExperimental.put(MACRO_DEFINE, PatternDefine::read); - sMapV7AndroidXExperimental.put(MACRO_CALL, PatternInflation::read); - sMapV7AndroidXExperimental.put(MACRO_ARGUMENT, PatternArgument::read); - sMapV7AndroidXExperimental.put(MACRO_BLOCK, PatternBlock::read); - sMapV7AndroidXExperimental.put(MACRO_FOR_EACH, PatternForEach::read); - sMapV7AndroidXExperimental.put(LAYOUT_CUSTOM, Custom::read); - sMapV7AndroidXExperimental.put(DATA_SOUND, SoundData::read); - sMapV7AndroidXExperimental.put(SOUND_EXPRESSION, SoundExpression::read); - sMapV7AndroidXExperimental.put(PLAY_SOUND, PlaySound::read); + populateMapFromAll( + sMapV7AndroidXExperimental, + 7, + MODIFIER_ALIGN_BY, + LAYOUT_COMPUTE, + LAYOUT_FLOW, + MODIFIER_MULTI_CLICK, + MODIFIER_DIMENSION_CONSTRAINTS, + REFERENCED_OPERATIONS, + INCLUDE_REFERENCED_OPERATIONS, + MACRO_DEFINE, + MACRO_CALL, + MACRO_ARGUMENT, + MACRO_BLOCK, + MACRO_FOR_EACH, + LAYOUT_CUSTOM, + DATA_SOUND, + SOUND_EXPRESSION, + PLAY_SOUND, + EVENT_ACTION, + ADD_MESH_2D, + DRAW_MESH_2D, + MATRIX_FROM_MESH_2D); } return sMapV7AndroidXExperimental; } @@ -538,23 +649,26 @@ private static UniqueIntMap<CompanionOperation> createMapV7_Widgets() { if (sMapV7Widgets == null) { sMapV7Widgets = new UniqueIntMap<>(); - sMapV7Widgets.put(MATRIX_FROM_PATH, MatrixFromPath::read); - sMapV7Widgets.put(TEXT_SUBTEXT, TextSubtext::read); - sMapV7Widgets.put(BITMAP_TEXT_MEASURE, BitmapTextMeasure::read); - sMapV7Widgets.put(DRAW_BITMAP_FONT_TEXT_RUN_ON_PATH, DrawBitmapFontTextOnPath::read); - sMapV7Widgets.put(DRAW_BITMAP_TEXT_ANCHORED, DrawBitmapTextAnchored::read); - sMapV7Widgets.put(DRAW_TO_BITMAP, DrawToBitmap::read); - sMapV7Widgets.put(WAKE_IN, WakeIn::read); - sMapV7Widgets.put(ID_LOOKUP, IdLookup::read); - sMapV7Widgets.put(PATH_EXPRESSION, PathExpression::read); - sMapV7Widgets.put(PARTICLE_COMPARE, ParticlesCompare::read); - sMapV7Widgets.put(DYNAMIC_FLOAT_LIST, DataDynamicListFloat::read); - sMapV7Widgets.put(UPDATE_DYNAMIC_FLOAT_LIST, UpdateDynamicFloatList::read); - sMapV7Widgets.put(SKIP, Skip::read); - sMapV7Widgets.put(CORE_TEXT, CoreText::read); - sMapV7Widgets.put(TEXT_STYLE, TextStyle::read); - sMapV7Widgets.put(TEXT_TRANSFORM, TextTransform::read); - sMapV7Widgets.put(COLOR_THEME, ColorTheme::read); + populateMapFromAll( + sMapV7Widgets, + 7, + MATRIX_FROM_PATH, + TEXT_SUBTEXT, + BITMAP_TEXT_MEASURE, + DRAW_BITMAP_FONT_TEXT_RUN_ON_PATH, + DRAW_BITMAP_TEXT_ANCHORED, + DRAW_TO_BITMAP, + WAKE_IN, + ID_LOOKUP, + PATH_EXPRESSION, + PARTICLE_COMPARE, + DYNAMIC_FLOAT_LIST, + UPDATE_DYNAMIC_FLOAT_LIST, + SKIP, + CORE_TEXT, + TEXT_STYLE, + TEXT_TRANSFORM, + COLOR_THEME); } return sMapV7Widgets; } @@ -562,26 +676,27 @@ private static UniqueIntMap<CompanionOperation> createMapV7_Widgets_Experimental() { if (sMapV7WidgetsExperimental == null) { sMapV7WidgetsExperimental = new UniqueIntMap<>(); - // add experimental operations for this profile here - sMapV7WidgetsExperimental.put(MODIFIER_ALIGN_BY, AlignByModifierOperation::read); - sMapV7WidgetsExperimental.put(LAYOUT_COMPUTE, LayoutComputeOperation::read); - sMapV7WidgetsExperimental.put(LAYOUT_FLOW, FlowLayout::read); - sMapV7WidgetsExperimental.put(MODIFIER_MULTI_CLICK, MultiClickModifier::read); - sMapV7WidgetsExperimental.put( - MODIFIER_DIMENSION_CONSTRAINTS, DimensionConstraintsModifierOperation::read); - - sMapV7WidgetsExperimental.put(REFERENCED_OPERATIONS, ReferencedOperations::read); - sMapV7WidgetsExperimental.put( - INCLUDE_REFERENCED_OPERATIONS, IncludeReferencedOperations::read); - - sMapV7WidgetsExperimental.put(MACRO_DEFINE, PatternDefine::read); - sMapV7WidgetsExperimental.put(MACRO_CALL, PatternInflation::read); - sMapV7WidgetsExperimental.put(MACRO_ARGUMENT, PatternArgument::read); - sMapV7WidgetsExperimental.put(MACRO_BLOCK, PatternBlock::read); - sMapV7WidgetsExperimental.put(MACRO_FOR_EACH, PatternForEach::read); - sMapV7WidgetsExperimental.put(DATA_SOUND, SoundData::read); - sMapV7WidgetsExperimental.put(SOUND_EXPRESSION, SoundExpression::read); - sMapV7WidgetsExperimental.put(PLAY_SOUND, PlaySound::read); + populateMapFromAll( + sMapV7WidgetsExperimental, + 7, + MODIFIER_ALIGN_BY, + LAYOUT_COMPUTE, + LAYOUT_FLOW, + MODIFIER_MULTI_CLICK, + MODIFIER_DIMENSION_CONSTRAINTS, + REFERENCED_OPERATIONS, + INCLUDE_REFERENCED_OPERATIONS, + MACRO_DEFINE, + MACRO_CALL, + MACRO_ARGUMENT, + MACRO_BLOCK, + MACRO_FOR_EACH, + DATA_SOUND, + SOUND_EXPRESSION, + PLAY_SOUND, + ADD_MESH_2D, + DRAW_MESH_2D, + MATRIX_FROM_MESH_2D); } return sMapV7WidgetsExperimental; } @@ -713,7 +828,6 @@ map.put(DRAW_RECT, DrawRect::read); map.put(DRAW_ROUND_RECT, DrawRoundRect::read); map.put(DRAW_TEXT_ON_PATH, DrawTextOnPath::read); - // map.put(DRAW_TEXT_ON_CIRCLE, DrawTextOnCircle::read); map.put(DRAW_TEXT_RUN, DrawText::read); map.put(DRAW_BITMAP_FONT_TEXT_RUN, DrawBitmapFontText::read); map.put(DRAW_TWEEN_PATH, DrawTweenPath::read);
diff --git a/core/java/com/android/internal/widget/remotecompose/core/PaintContext.java b/core/java/com/android/internal/widget/remotecompose/core/PaintContext.java index 97c3956..ff32ec7 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/PaintContext.java +++ b/core/java/com/android/internal/widget/remotecompose/core/PaintContext.java
@@ -18,6 +18,7 @@ import android.annotation.NonNull; import android.annotation.Nullable; +import com.android.internal.widget.remotecompose.core.operations.layout.Component; import com.android.internal.widget.remotecompose.core.operations.layout.managers.LayoutManager; import com.android.internal.widget.remotecompose.core.operations.paint.PaintBundle; @@ -252,6 +253,37 @@ public abstract void drawTextOnPath(int textId, int pathId, float hOffset, float vOffset); /** + * Draws text along a circular arc. + * + * <p>Calculates text width with current paint metrics, determines the arc sweep angle based on + * the final radius ({@code radius + warpRadiusOffset}), and lays out text along an arc centered + * at ({@code centerX}, {@code centerY}). + * + * <p>Angles use standard degrees (0° at 3 o'clock, 90° at 6 o'clock, 180° at 9 + * o'clock, 270° at 12 o'clock). + * + * @param textId id of the text resource to draw + * @param centerX x-coordinate of the circle center in pixels + * @param centerY y-coordinate of the circle center in pixels + * @param radius base radius of the circle in pixels + * @param startAngle reference angle in degrees for text alignment + * @param warpRadiusOffset offset added to {@code radius} to adjust the final path radius + * @param alignment text alignment relative to {@code startAngle}: 0 (START), 1 (CENTER), 2 + * (END) + * @param placement arc direction and placement: 0 (OUTSIDE, clockwise), 1 (INSIDE, + * counter-clockwise) + */ + public void drawTextOnCircle( + int textId, + float centerX, + float centerY, + float radius, + float startAngle, + float warpRadiusOffset, + int alignment, + int placement) {} + + /** * Return the dimensions (left, top, right, bottom). Relative to a drawTextRun x=0, y=0; * * @param textId @@ -557,6 +589,70 @@ public abstract void matrixFromPath(int pathId, float fraction, float vOffset, int flags); /** + * Store the geometry of a 2D vertex mesh. + * + * <p>The engine does all the work - expression evaluation, half float widening, expanding a + * layout into a triangle list - and hands the backend flat arrays already in the shape {@code + * Canvas.drawVertices} and {@code SkVertices} want, so a backend copies rather than converts. + * Interleaved x,y is {@code SkPoint[]}; packed ARGB in an int32 is exactly {@code SkColor}'s + * layout. + * + * <p>Separate from {@link #drawMesh} because a mesh defined once and drawn repeatedly under + * different transforms should upload its vertices once. Backends that can cache get that for + * free; backends that cannot may treat this as a store and do the work in {@link #drawMesh}. + * + * <p>An empty array means the channel is absent. + * + * @param meshId the id to store the mesh under + * @param layout the mesh layout (one of {@code Mesh2DGenerator.LAYOUT_*}) + * @param uCount samples along u + * @param vCount samples along v + * @param verts x,y interleaved + * @param uv u,v interleaved, normalised 0..1 with (0,0) at the top left, or empty + * @param colors packed ARGB per vertex, or empty + * @param indices triangle list + */ + public void setMesh( + int meshId, + int layout, + int uCount, + int vCount, + @NonNull float[] verts, + @NonNull float[] uv, + @NonNull int[] colors, + @NonNull int[] indices) {} + + /** + * Draw a 2D vertex mesh previously stored by {@link #setMesh}. + * + * <p><b>This must leave the paint exactly as it found it.</b> Whatever it sets - shader, blend + * mode, style, colour - must be restored before it returns, including when the draw throws, and + * a draw that follows it must render identically whether or not a mesh was drawn in between. + * This is a hard requirement rather than a nicety: paint is canvas state, and a backend that + * borrows it must give it back. Nothing errors when it does not; the shapes are all correct and + * simply the wrong colour, which is the hardest kind of defect to attribute. + * + * <p>A mesh draw is not a paint command. It composes with {@code save}/{@code restore} exactly + * as {@code drawRect} does, and a document should never need to wrap it in a save block + * defensively. + * + * @param meshId the mesh to draw + * @param blend how vertex colour and texel combine + * @param imageId the bitmap to sample, 0 for untextured + */ + public void drawMesh(int meshId, int blend, int imageId) {} + + /** + * Multiply the local frame of a 2D mesh at {@code (u, v)} into the current canvas matrix. + * + * @param meshId the mesh to sample + * @param u the u parameter, 0..1 + * @param v the v parameter, 0..1 + * @param flags which parts of the local frame to apply + */ + public void matrixFromMesh(int meshId, float u, float v, int flags) {} + + /** * Redirect drawing to a bitmap (0 = back to main canvas) * * @param bitmapId id of bitmap to draw to or 0 to draw to the canvas @@ -610,4 +706,87 @@ public int getDensityBehavior() { return mContext.mDocument.mDensityBehavior; } + + private final java.util.ArrayList<Boolean> mOffscreenClipStack = new java.util.ArrayList<>(); + private final java.util.ArrayList<Component> mOffscreenCompStack = new java.util.ArrayList<>(); + private final java.util.ArrayList<Integer> mOffscreenBitmapIdStack = + new java.util.ArrayList<>(); + private @Nullable Component mOffscreenComponent = null; + private int mOffscreenBitmapId = 0; + + /** Releases any active offscreen bitmaps back to the offscreen bitmap pool. */ + public void releaseOffscreenBitmaps() { + com.android.internal.widget.remotecompose.core.operations.BitmapData + .releaseOffscreenBitmaps(mContext); + } + + /** + * Pushes an offscreen target component, bitmap ID, and clip flag onto the offscreen rendering + * stack. + * + * @param component the component currently being rendered offscreen, or null + * @param bitmapId the bitmap ID of the offscreen target + * @param clipped true if a clip rect was pushed on the offscreen canvas + */ + public void pushOffscreenTarget(@Nullable Component component, int bitmapId, boolean clipped) { + mOffscreenCompStack.add(mOffscreenComponent); + mOffscreenBitmapIdStack.add(mOffscreenBitmapId); + mOffscreenClipStack.add(clipped); + mOffscreenComponent = component; + mOffscreenBitmapId = bitmapId; + } + + /** + * Pops the current offscreen target component and returns whether a clip rect was pushed. + * + * @return true if a clip rect was pushed when this offscreen target was entered + */ + public boolean popOffscreenTarget() { + mOffscreenComponent = + mOffscreenCompStack.isEmpty() + ? null + : mOffscreenCompStack.remove(mOffscreenCompStack.size() - 1); + mOffscreenBitmapId = + mOffscreenBitmapIdStack.isEmpty() + ? 0 + : mOffscreenBitmapIdStack.remove(mOffscreenBitmapIdStack.size() - 1); + return !mOffscreenClipStack.isEmpty() + && mOffscreenClipStack.remove(mOffscreenClipStack.size() - 1); + } + + /** + * Returns whether there is an active component offscreen target on the stack. + * + * @return true if currently inside a component offscreen target + */ + public boolean hasActiveOffscreenTarget() { + return mOffscreenBitmapId != 0 || !mOffscreenBitmapIdStack.isEmpty(); + } + + /** + * Returns the bitmap ID of the enclosing offscreen target, or 0 if targeting the main canvas. + * + * @return the enclosing offscreen bitmap ID, or 0 + */ + public int getOffscreenBitmapId() { + return mOffscreenBitmapId; + } + + /** + * Sets the component currently being rendered to an offscreen bitmap. + * + * @param component the offscreen target component, or null + */ + public void setOffscreenComponent(@Nullable Component component) { + mOffscreenComponent = component; + } + + /** + * Returns the component currently being rendered to an offscreen bitmap, if any. + * + * @return the offscreen target component, or null + */ + public @Nullable Component getOffscreenComponent() { + return mOffscreenComponent; + } }
diff --git a/core/java/com/android/internal/widget/remotecompose/core/RecordingRemoteComposeBuffer.java b/core/java/com/android/internal/widget/remotecompose/core/RecordingRemoteComposeBuffer.java index 8c6c9de..f669889 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/RecordingRemoteComposeBuffer.java +++ b/core/java/com/android/internal/widget/remotecompose/core/RecordingRemoteComposeBuffer.java
@@ -1722,6 +1722,29 @@ int visibilityEasingType, int enterAnimation, int exitAnimation) { + addAnimationSpecModifier( + animationId, + motionDuration, + motionEasingType, + visibilityDuration, + visibilityEasingType, + enterAnimation, + exitAnimation, + -1, + -1); + } + + @Override + public void addAnimationSpecModifier( + int animationId, + float motionDuration, + int motionEasingType, + float visibilityDuration, + int visibilityEasingType, + int enterAnimation, + int exitAnimation, + int enterFunctionId, + int exitFunctionId) { addOperation( new AnimationSpec( animationId, @@ -1730,7 +1753,11 @@ visibilityDuration, visibilityEasingType, AnimationSpec.intToAnimation(enterAnimation), - AnimationSpec.intToAnimation(exitAnimation))); + AnimationSpec.intToAnimation(exitAnimation), + enterFunctionId, + exitFunctionId, + AnimationSpec.intToSequence(enterAnimation >> 8), + AnimationSpec.intToSequence(exitAnimation >> 8))); } @Override
diff --git a/core/java/com/android/internal/widget/remotecompose/core/RemoteComposeBuffer.java b/core/java/com/android/internal/widget/remotecompose/core/RemoteComposeBuffer.java index 847f345..c5aeeb0 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/RemoteComposeBuffer.java +++ b/core/java/com/android/internal/widget/remotecompose/core/RemoteComposeBuffer.java
@@ -18,6 +18,7 @@ import android.annotation.NonNull; import android.annotation.Nullable; +import com.android.internal.widget.remotecompose.core.operations.AddMesh2D; import com.android.internal.widget.remotecompose.core.operations.BitmapData; import com.android.internal.widget.remotecompose.core.operations.BitmapFontData; import com.android.internal.widget.remotecompose.core.operations.BitmapTextMeasure; @@ -46,6 +47,7 @@ import com.android.internal.widget.remotecompose.core.operations.DrawCircle; import com.android.internal.widget.remotecompose.core.operations.DrawContent; import com.android.internal.widget.remotecompose.core.operations.DrawLine; +import com.android.internal.widget.remotecompose.core.operations.DrawMesh2D; import com.android.internal.widget.remotecompose.core.operations.DrawOval; import com.android.internal.widget.remotecompose.core.operations.DrawPath; import com.android.internal.widget.remotecompose.core.operations.DrawRect; @@ -57,6 +59,7 @@ import com.android.internal.widget.remotecompose.core.operations.DrawTextOnPath; import com.android.internal.widget.remotecompose.core.operations.DrawToBitmap; import com.android.internal.widget.remotecompose.core.operations.DrawTweenPath; +import com.android.internal.widget.remotecompose.core.operations.EventActionOperation; import com.android.internal.widget.remotecompose.core.operations.FloatConstant; import com.android.internal.widget.remotecompose.core.operations.FloatExpression; import com.android.internal.widget.remotecompose.core.operations.FloatFunctionCall; @@ -67,6 +70,7 @@ import com.android.internal.widget.remotecompose.core.operations.IdLookup; import com.android.internal.widget.remotecompose.core.operations.ImageAttribute; import com.android.internal.widget.remotecompose.core.operations.IntegerExpression; +import com.android.internal.widget.remotecompose.core.operations.MatrixFromMesh2D; import com.android.internal.widget.remotecompose.core.operations.MatrixFromPath; import com.android.internal.widget.remotecompose.core.operations.MatrixRestore; import com.android.internal.widget.remotecompose.core.operations.MatrixRotate; @@ -191,6 +195,7 @@ import java.util.HashMap; import java.util.Map; import java.util.Set; +import java.util.Stack; /** Provides an abstract buffer to encode/decode RemoteCompose operations */ public class RemoteComposeBuffer { @@ -209,7 +214,7 @@ protected int mLastComponentId = 0; private int mGeneratedComponentId = -1; protected int mApiLevel = CoreDocument.DOCUMENT_API_LEVEL; - private final java.util.Stack<Integer> mPatternDefineOffsets = new java.util.Stack<>(); + private final Stack<Integer> mPatternDefineOffsets = new Stack<>(); protected int mProfileMask = 0; protected boolean mIsCustomMap = false; @@ -1020,6 +1025,9 @@ /** * inflate the buffer into a list of operations * + * <p>If the header has the {@link Header#COMPRESS} flag, the buffer contents are first replaced + * by the decompressed document. + * * @param operations the operations list to add to */ public void inflateFromBuffer( @@ -1032,6 +1040,11 @@ try { Header header = Header.readDirect(mBuffer); profiles = header.getProfiles(); + Object compression = header.get(Header.COMPRESS); + if (compression != null + && !Integer.valueOf(Header.COMPRESSION_NONE).equals(compression)) { + decompress(); + } } catch (IOException e) { throw new RuntimeException(e); } @@ -1064,6 +1077,18 @@ } /** + * Replaces the buffer contents with the decompressed document, so later inflations (e.g. {@link + * CoreDocument#reinflate()}) read it directly instead of decompressing again. + */ + private void decompress() throws IOException { + byte[] document = Header.decompressDocument(mBuffer.mBuffer, mBuffer.mSize); + mBuffer.mBuffer = document; + mBuffer.mMaxSize = document.length; + mBuffer.mSize = document.length; + mBuffer.setIndex(0); + } + + /** * copy the current buffer to a new one * * @return A new RemoteComposeBuffer @@ -2655,6 +2680,46 @@ return imageId; } + /** + * Create an offscreen bitmap buffer whose dimensions are dynamically sized to a target + * component. + * + * @param imageId the image id + * @return the image id + */ + public int createOffscreenBitmap(int imageId) { + return createOffscreenBitmap(imageId, 0); + } + + /** + * Create an offscreen bitmap buffer whose dimensions are dynamically sized to the specified + * component. + * + * @param imageId the image id + * @param componentId the component id (or 0 to use the active component) + * @return the image id + */ + public int createOffscreenBitmap(int imageId, int componentId) { + byte[] payload = + componentId != 0 + ? new byte[] { + (byte) (componentId >> 24), + (byte) (componentId >> 16), + (byte) (componentId >> 8), + (byte) componentId + } + : new byte[0]; + BitmapData.apply( + mBuffer, + imageId, + BitmapData.TYPE_RAW8888, + (short) 1, + BitmapData.ENCODING_COMPONENT_OFFSCREEN_BUFFER, + (short) 1, + payload); + return imageId; + } + /** */ public void drawOnBitmap(int imageId, int mode, int color) { DrawToBitmap.apply(mBuffer, imageId, mode, color); @@ -2775,6 +2840,25 @@ } /** + * Starts an event actions block. + * + * @param type the event type + * @param filter the filter metadata + * @param flags the routing flags + * @param dataIds optional target payload data mapping IDs + * @param condition optional conditional float expression RPN stream + */ + public void startEventActions( + int type, int filter, int flags, @Nullable int[] dataIds, @Nullable float[] condition) { + EventActionOperation.apply(mBuffer, type, filter, flags, dataIds, condition); + } + + /** Ends the current event actions block. */ + public void endEventActions() { + addContainerEnd(); + } + + /** * Add a debug message * * @param textId text id @@ -2881,16 +2965,38 @@ int documentApiLevel, int profileMask, @Nullable Set<Integer> supportedOperations) { mApiLevel = documentApiLevel; mProfileMask = profileMask; - Operations.UniqueIntMap<CompanionOperation> map = - Operations.getOperations(documentApiLevel, profileMask); - if (map != null) { - mMap = map; - if (supportedOperations == null) { + if (supportedOperations != null) { + // When explicit supported operations are provided, look up companion operation + // readers for each opcode across registered operations and build a custom map. + Operations.UniqueIntMap<CompanionOperation> allOps = + Operations.getAllKnownOperations(documentApiLevel); + Operations.UniqueIntMap<CompanionOperation> filteredMap = + new Operations.UniqueIntMap<>(); + if (allOps != null) { + for (Integer opId : supportedOperations) { + if (opId != null) { + int opcode = opId; + CompanionOperation companion = allOps.get(opcode); + if (companion != null) { + filteredMap.put(opcode, companion); + } + } + } + } + mMap = filteredMap; + mIsCustomMap = true; + mBuffer.setValidOperations(supportedOperations); + } else { + // Default behavior: look up operation companion readers defined for profile bitmask. + Operations.UniqueIntMap<CompanionOperation> map = + Operations.getOperations(documentApiLevel, profileMask); + if (map != null) { + mMap = map; supportedOperations = map.keySet(); } - } - if (supportedOperations != null) { - mBuffer.setValidOperations(supportedOperations); + if (supportedOperations != null) { + mBuffer.setValidOperations(supportedOperations); + } } } @@ -2989,6 +3095,117 @@ } /** + * Define a 2D vertex mesh. + * + * @param meshId the id the mesh is stored under + * @param type how the vertex data is supplied + * @param layout the domain topology + * @param uCount grid resolution along u + * @param vCount grid resolution along v + * @param flags reserved + * @param aux layout dependent, e.g. a path id for PATH_STRIP + * @param expressions the RPN expression groups, for the expression type + * @param indices the triangle list, for the literal types + * @param verts x,y pairs, for the literal types + * @param uv u,v pairs, for the literal types + * @param colors packed ARGB per vertex, for the literal types + */ + public void addMesh2D( + int meshId, + int type, + int layout, + int uCount, + int vCount, + int flags, + int aux, + float[][] expressions, + @Nullable int[] indices, + @Nullable float[] verts, + @Nullable float[] uv, + @Nullable int[] colors) { + AddMesh2D.apply( + mBuffer, + meshId, + type, + layout, + uCount, + vCount, + flags, + aux, + expressions, + indices, + verts, + uv, + colors); + } + + /** + * Define a ribbon along a path whose cross width is a spline through control points. + * + * <p>{@code widths} and {@code positions} may hold NaN variable ids, so the profile can be + * animated. + * + * @param meshId the id the mesh is stored under + * @param segments roughly how many quads to divide the path into; at least 1 + * @param pathId the path to follow + * @param widths the width control points, at least one, in the path's own units + * @param positions where each width sits along the path, 0..1, empty for evenly spaced + */ + public void addMesh2DPathStrip( + int meshId, + int segments, + int pathId, + @Nullable float[] widths, + @Nullable float[] positions) { + AddMesh2D.applyPathSplineStrip(mBuffer, meshId, segments, pathId, widths, positions); + } + + /** + * Define a spline width path strip that ends in a semicircle at each end. + * + * <p>As {@link #addMesh2DPathStrip}, with a round cap of radius half the ribbon's width at each + * end. The caps are extra columns rather than a slice of {@code segments}, so the body is + * sampled exactly as finely as the flat variant would sample it. + * + * @param meshId the id the mesh is stored under + * @param segments roughly how many quads to divide the path into, excluding the caps + * @param pathId the path to follow + * @param widths the width control points, at least one, in the path's own units + * @param positions where each width sits along the path, 0..1, empty for evenly spaced + */ + public void addMesh2DRoundStrip( + int meshId, + int segments, + int pathId, + @Nullable float[] widths, + @Nullable float[] positions) { + AddMesh2D.applySplineRoundStrip(mBuffer, meshId, segments, pathId, widths, positions); + } + + /** + * Draw a previously defined 2D vertex mesh. + * + * @param meshId the mesh to draw + * @param blend how vertex colour and texel combine + * @param imageId the bitmap to sample, 0 for untextured + */ + public void addDrawMesh2D(int meshId, int blend, int imageId) { + DrawMesh2D.apply(mBuffer, meshId, blend, imageId); + } + + /** + * Multiply the local frame of a 2D mesh at (u, v) into the current canvas matrix. + * + * @param meshId the mesh to read the surface from + * @param u the u parameter + * @param v the v parameter + * @param flags which parts of the local frame to apply + */ + public void setMatrixFromMesh2D(int meshId, float u, float v, int flags) { + MatrixFromMesh2D.apply(mBuffer, meshId, u, v, flags); + } + + /** * Add a component visibility operation * * @param valueId id of the value @@ -3136,6 +3353,41 @@ int visibilityEasingType, int enterAnimation, int exitAnimation) { + addAnimationSpecModifier( + animationId, + motionDuration, + motionEasingType, + visibilityDuration, + visibilityEasingType, + enterAnimation, + exitAnimation, + -1, + -1); + } + + /** + * Add an animation spec modifier with custom enter/exit function IDs + * + * @param animationId the animation id + * @param motionDuration the duration of the motion animation + * @param motionEasingType the type of easing for the motion animation + * @param visibilityDuration the duration of the visibility animation + * @param visibilityEasingType the type of easing for the visibility animation + * @param enterAnimation the type of animation when "entering" (newly visible) + * @param exitAnimation the type of animation when "exiting" (newly gone) + * @param enterFunctionId the function id for custom enter animation + * @param exitFunctionId the function id for custom exit animation + */ + public void addAnimationSpecModifier( + int animationId, + float motionDuration, + int motionEasingType, + float visibilityDuration, + int visibilityEasingType, + int enterAnimation, + int exitAnimation, + int enterFunctionId, + int exitFunctionId) { AnimationSpec.apply( mBuffer, animationId, @@ -3144,7 +3396,9 @@ visibilityDuration, visibilityEasingType, enterAnimation, - exitAnimation); + exitAnimation, + enterFunctionId, + exitFunctionId); } /**
diff --git a/core/java/com/android/internal/widget/remotecompose/core/RemoteContext.java b/core/java/com/android/internal/widget/remotecompose/core/RemoteContext.java index f73c8cd..d4fe05a 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/RemoteContext.java +++ b/core/java/com/android/internal/widget/remotecompose/core/RemoteContext.java
@@ -18,6 +18,7 @@ import android.annotation.NonNull; import android.annotation.Nullable; +import com.android.internal.widget.remotecompose.core.events.EventManager; import com.android.internal.widget.remotecompose.core.operations.FloatExpression; import com.android.internal.widget.remotecompose.core.operations.ShaderData; import com.android.internal.widget.remotecompose.core.operations.Theme; @@ -47,6 +48,7 @@ new RemoteComposeState(); // todo, is this a valid use of RemoteComposeState -- bbade@ private long mDocLoadTime; @Nullable protected PaintContext mPaintContext = null; + private final EventManager mEventManager; protected float mDensity = Float.NaN; private int mPaintTheme = -3; @NonNull ContextMode mMode = ContextMode.UNSET; @@ -84,7 +86,12 @@ } public RemoteContext(@NonNull RemoteClock clock) { - this.mClock = clock; + this(clock, new EventManager()); + } + + public RemoteContext(@NonNull RemoteClock clock, @NonNull EventManager eventManager) { + mClock = clock; + mEventManager = eventManager; setDocLoadTime(); mDocument = new CoreDocument(clock); // todo: is this a valid way to initialize? bbade@ } @@ -423,6 +430,10 @@ this.mClock = clock; } + public @NonNull EventManager getEventManager() { + return mEventManager; + } + /** * Load a font under an id * @@ -618,11 +629,19 @@ int height, long capabilities, @Nullable IntMap<Object> properties) { - mRemoteComposeState.setWindowWidth(width); - mRemoteComposeState.setWindowHeight(height); + int scaledWidth = width; + int scaledHeight = height; + if (mDocument.getDensityBehavior() == CoreDocument.DENSITY_BEHAVIOR_DP + && !Float.isNaN(mDensity) + && mDensity > 0f) { + scaledWidth = Math.round(width * mDensity); + scaledHeight = Math.round(height * mDensity); + } + mRemoteComposeState.setWindowWidth(scaledWidth); + mRemoteComposeState.setWindowHeight(scaledHeight); mDocument.setVersion(majorVersion, minorVersion, patchVersion); - mDocument.setWidth(width); - mDocument.setHeight(height); + mDocument.setWidth(scaledWidth); + mDocument.setHeight(scaledHeight); mDocument.setRequiredCapabilities(capabilities); mDocument.setProperties(properties); }
diff --git a/core/java/com/android/internal/widget/remotecompose/core/events/Event.java b/core/java/com/android/internal/widget/remotecompose/core/events/Event.java new file mode 100644 index 0000000..25d1ddf --- /dev/null +++ b/core/java/com/android/internal/widget/remotecompose/core/events/Event.java
@@ -0,0 +1,66 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.internal.widget.remotecompose.core.events; + +import android.annotation.Nullable; + +/** Representation of an event dispatched through the system. */ +public class Event { + private final int mType; + private final int mMetadata; + private final float[] mData; + + /** + * Constructs a new Event. + * + * @param type type identifying the event + * @param metadata metadata value associated with the event + * @param data optional payload data containing event properties + */ + public Event(int type, int metadata, @Nullable float[] data) { + mType = type; + mMetadata = metadata; + mData = data; + } + + /** + * Returns the event type. + * + * @return the integer event type + */ + public int getType() { + return mType; + } + + /** + * Returns the event metadata. + * + * @return the integer metadata + */ + public int getMetadata() { + return mMetadata; + } + + /** + * Returns the event data payload. + * + * @return the float array payload or null if empty + */ + public @Nullable float[] getData() { + return mData; + } +}
diff --git a/core/java/com/android/internal/widget/remotecompose/core/events/EventHandler.java b/core/java/com/android/internal/widget/remotecompose/core/events/EventHandler.java new file mode 100644 index 0000000..94c4b09 --- /dev/null +++ b/core/java/com/android/internal/widget/remotecompose/core/events/EventHandler.java
@@ -0,0 +1,44 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.internal.widget.remotecompose.core.events; + +import android.annotation.NonNull; + +import com.android.internal.widget.remotecompose.core.CoreDocument; +import com.android.internal.widget.remotecompose.core.RemoteContext; + +/** Interface representing components capable of handling dispatched [Event]s. */ +public interface EventHandler { + /** + * Checks if the handler supports the specified event type. + * + * @param eventType the event type to check + * @return true if the event type is supported, false otherwise + */ + boolean matchesEvent(int eventType); + + /** + * Handles the dispatched event. + * + * @param context the current paint and state context + * @param document the root document + * @param event the dispatched event + * @return integer status code resulting from handling the event + */ + int onEvent( + @NonNull RemoteContext context, @NonNull CoreDocument document, @NonNull Event event); +}
diff --git a/core/java/com/android/internal/widget/remotecompose/core/events/EventManager.java b/core/java/com/android/internal/widget/remotecompose/core/events/EventManager.java new file mode 100644 index 0000000..abb2fc0 --- /dev/null +++ b/core/java/com/android/internal/widget/remotecompose/core/events/EventManager.java
@@ -0,0 +1,86 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.internal.widget.remotecompose.core.events; + +import android.annotation.NonNull; + +import com.android.internal.widget.remotecompose.core.CoreDocument; +import com.android.internal.widget.remotecompose.core.RemoteContext; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** Manages event routing and registration of handlers. */ +public class EventManager { + /** Status indicating the event was not processed by any router or handler. */ + public static final int STATUS_UNHANDLED = 0; + + private final Map<Integer, EventRouter> mRouterMap = new HashMap<>(); + + private final Set<EventHandler> mEventHandlerSet = new HashSet<>(); + + /** + * Registers an [EventHandler] on all compatible registered routers. + * + * @param eventHandler the handler to register + */ + public void registerHandler(@NonNull EventHandler eventHandler) { + mEventHandlerSet.add(eventHandler); + for (Map.Entry<Integer, EventRouter> entry : mRouterMap.entrySet()) { + if (eventHandler.matchesEvent(entry.getKey())) { + entry.getValue().registerHandler(eventHandler); + } + } + } + + /** + * Registers an [EventRouter] for a specific event type. + * + * @param eventType the event type to route + * @param eventRouter the router to associate with the event type + */ + public void registerRouter(int eventType, @NonNull EventRouter eventRouter) { + if (mRouterMap.containsKey(eventType)) { + throw new IllegalStateException("Existing router for this event type."); + } + mRouterMap.put(eventType, eventRouter); + for (EventHandler eventHandler : mEventHandlerSet) { + if (eventHandler.matchesEvent(eventType)) { + eventRouter.registerHandler(eventHandler); + } + } + } + + /** + * Dispatches an event through the matching registered router. + * + * @param context the current paint and state context + * @param document the root document + * @param event the event to dispatch + * @return status code resulting from dispatching the event + */ + public int dispatchEvent( + @NonNull RemoteContext context, @NonNull CoreDocument document, @NonNull Event event) { + EventRouter router = mRouterMap.get(event.getType()); + if (router == null) { + return STATUS_UNHANDLED; + } + return router.routeEvent(context, document, event); + } +}
diff --git a/core/java/com/android/internal/widget/remotecompose/core/events/EventRouter.java b/core/java/com/android/internal/widget/remotecompose/core/events/EventRouter.java new file mode 100644 index 0000000..8b9ea7d --- /dev/null +++ b/core/java/com/android/internal/widget/remotecompose/core/events/EventRouter.java
@@ -0,0 +1,44 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.internal.widget.remotecompose.core.events; + +import android.annotation.NonNull; + +import com.android.internal.widget.remotecompose.core.CoreDocument; +import com.android.internal.widget.remotecompose.core.RemoteContext; + +/** Interface representing components capable of routing [Event]s to [EventHandler]s. */ +public interface EventRouter { + + /** + * Registers an [EventHandler] on the router. + * + * @param eventHandler the handler to register + */ + void registerHandler(@NonNull EventHandler eventHandler); + + /** + * Routes the dispatched event to its compatible handlers. + * + * @param context the current paint and state context + * @param document the root document + * @param event the dispatched event + * @return status code resulting from routing the event + */ + int routeEvent( + @NonNull RemoteContext context, @NonNull CoreDocument document, @NonNull Event event); +}
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/AddMesh2D.java b/core/java/com/android/internal/widget/remotecompose/core/operations/AddMesh2D.java new file mode 100644 index 0000000..70e974f --- /dev/null +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/AddMesh2D.java
@@ -0,0 +1,1225 @@ +/* + * Copyright (C) 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.internal.widget.remotecompose.core.operations; + +import static com.android.internal.widget.remotecompose.core.documentation.DocumentedOperation.FLOAT_ARRAY; +import static com.android.internal.widget.remotecompose.core.documentation.DocumentedOperation.INT; +import static com.android.internal.widget.remotecompose.core.documentation.DocumentedOperation.INT_ARRAY; + +import android.annotation.NonNull; +import android.annotation.Nullable; + +import com.android.internal.widget.remotecompose.core.Limits; +import com.android.internal.widget.remotecompose.core.Operation; +import com.android.internal.widget.remotecompose.core.Operations; +import com.android.internal.widget.remotecompose.core.PaintContext; +import com.android.internal.widget.remotecompose.core.PaintOperation; +import com.android.internal.widget.remotecompose.core.RemoteContext; +import com.android.internal.widget.remotecompose.core.VariableSupport; +import com.android.internal.widget.remotecompose.core.WireBuffer; +import com.android.internal.widget.remotecompose.core.documentation.DocumentationBuilder; +import com.android.internal.widget.remotecompose.core.operations.utilities.AnimatedFloatExpression; +import com.android.internal.widget.remotecompose.core.operations.utilities.CollectionsAccess; +import com.android.internal.widget.remotecompose.core.operations.utilities.Mesh2DGenerator; +import com.android.internal.widget.remotecompose.core.operations.utilities.NanMap; +import com.android.internal.widget.remotecompose.core.operations.utilities.easing.MonotonicSpline; +import com.android.internal.widget.remotecompose.core.serialize.MapSerializer; +import com.android.internal.widget.remotecompose.core.serialize.Serializable; + +import java.util.List; + +/** + * Defines a 2D vertex mesh. + * + * <p>One operation covers every way of supplying vertices, discriminated by {@code type}, because + * the literal and the parametric form differ only in how the data arrives - that is a field, not an + * operation. The 3D side spends two opcodes on this distinction; the 2D side does not repeat that, + * and {@code type} leaves room to add supply formats later without spending more opcode space. + * + * <p>The mesh is defined once and may be drawn repeatedly under different transforms by {@link + * DrawMesh2D}, which is why definition and drawing are separate operations: collapsing them would + * force the vertex data to be re-sent per draw. + * + * <p>Nothing here touches the 3D subsystem. There is no z, no normal, no camera, no light and no + * depth buffer; a mesh is positioned by the ordinary 2D canvas matrix. + */ +public class AddMesh2D extends PaintOperation implements VariableSupport, Serializable { + private static final int OP_CODE = Operations.ADD_MESH_2D; + private static final String CLASS_NAME = "AddMesh2D"; + + /** RPN expressions over {@code (u, v)}; topology implicit, no index array. */ + public static final int TYPE_EXPRESSION = 0; + + /** Explicit indices and vertices, 32 bit. The interop path for tool generated geometry. */ + public static final int TYPE_VALUES = 1; + + /** As {@link #TYPE_VALUES}, with positions and uv as IEEE half floats. A wire format only. */ + public static final int TYPE_F16_VALUES = 2; + + /** + * A ribbon along a path whose cross width is a monotonic spline through control points. + * + * <p>Always uses {@link Mesh2DGenerator#LAYOUT_PATH_STRIP}: the topology is exactly that of an + * ordinary path strip and only the source of the width differs. Where {@link #TYPE_EXPRESSION} + * spends expression tokens computing a width from {@code u}, this carries the widths + * themselves, which is both cheaper and far easier to author for the common case of a stroke + * that swells and tapers. Geometry only: uv is the identity mapping and there are no vertex + * colours, so colour comes from the paint or from a textured {@code drawMesh2D}. + */ + public static final int TYPE_PATH_SPLINE_STRIP = 3; + + /** + * As {@link #TYPE_PATH_SPLINE_STRIP}, but the ribbon ends in a semicircle instead of a squared + * off edge - the mesh equivalent of a round stroke cap. + * + * <p>Identical on the wire to the flat variant, and identical in topology: still {@link + * Mesh2DGenerator#LAYOUT_PATH_STRIP}, still two vertices across, still one quad per column. The + * caps are simply extra columns at each end whose {@code u} sweeps a quarter turn around the + * endpoint rather than advancing along the path, so the strip's own quads sweep out the half + * disc. Because the caps are added to the column budget rather than taken out of it, a rounded + * strip follows its path at the same resolution as a flat one with the same {@code segments}. + * + * <p>The cap radius is half the ribbon's width at that end, so a profile that tapers to zero + * ends in a point and one that ends wide ends in a correspondingly large dome. The number of + * columns in each cap is carried in the header's {@code flags} field; see {@link + * Mesh2DGenerator#roundCapSegments}. + */ + public static final int TYPE_SPLINE_ROUND_STRIP = 4; + + /** Index into the expression group array: x position. */ + private static final int EXP_X = 0; + + /** Index into the expression group array: y position. */ + private static final int EXP_Y = 1; + + /** Index into the expression group array: texture u. */ + private static final int EXP_TEX_U = 2; + + /** Index into the expression group array: texture v. */ + private static final int EXP_TEX_V = 3; + + /** Index into the expression group array: colour alpha, 0..1. */ + private static final int EXP_COLOR_A = 4; + + /** Index into the expression group array: colour red, 0..1. */ + private static final int EXP_COLOR_R = 5; + + /** Index into the expression group array: colour green, 0..1. */ + private static final int EXP_COLOR_G = 6; + + /** Index into the expression group array: colour blue, 0..1. */ + private static final int EXP_COLOR_B = 7; + + /** + * Index into the expression group array: the cross width of a strip, in the path's own units. + * + * <p>Only {@link Mesh2DGenerator#LAYOUT_PATH_STRIP} reads it. Because it is an expression over + * {@code (u, v)} rather than a constant, the ribbon's width can vary along its length - which + * is the whole reason a path strip is more than a thick stroke. Absent means a width of 1, + * leaving the strip one unit across. + */ + private static final int EXP_WIDTH = 8; + + /** The number of expression groups carried by {@link #TYPE_EXPRESSION}. */ + public static final int EXPRESSION_GROUPS = 9; + + /** A quarter turn, the angle a round end cap sweeps from its tip to the body of the strip. */ + private static final float HALF_PI = (float) (Math.PI * 0.5); + + private final int mMeshId; + private final int mType; + private final int mLayout; + private final int mUCount; + private final int mVCount; + private final int mFlags; + private final int mAux; + + // TYPE_EXPRESSION payload: one RPN array per group, empty when the group is absent. + private final float[][] mExpressions; + private final float[][] mOutExpressions; + + // TYPE_VALUES / TYPE_F16_VALUES payload. + private final int[] mSrcIndices; + private final float[] mSrcVerts; + private final float[] mOutSrcVerts; + private final float[] mSrcUv; + private final int[] mSrcColors; + + // Spline strip payload: the width control points and, optionally, where they sit. + private final float[] mWidths; + private final float[] mOutWidths; + private final float[] mWidthPositions; + private final float[] mOutWidthPositions; + + /** The fit through {@link #mOutWidths}, rebuilt lazily whenever a width input changes. */ + private @Nullable MonotonicSpline mWidthSpline; + + private boolean mWidthSplineValid; + + // Expanded geometry, in the exact layout drawVertices wants. + private float[] mVerts = new float[0]; + private float[] mUv = new float[0]; + private int[] mColors = new int[0]; + private int[] mIndices = new int[0]; + private boolean mMeshChanged = true; + + private final AnimatedFloatExpression mExpressionEvaluator = new AnimatedFloatExpression(); + private final float[] mScratchPosition = new float[2]; + private final float[] mScratchPathSample = new float[4]; + private float[] mScratchPolyline = new float[0]; + + @SuppressWarnings("UnknownNullness") // Annotations on a primitive array are compile error. + public AddMesh2D( + int meshId, + int type, + int layout, + int uCount, + int vCount, + int flags, + int aux, + float[][] expressions, + @Nullable int[] indices, + @Nullable float[] verts, + @Nullable float[] uv, + @Nullable int[] colors) { + this( + meshId, + type, + layout, + uCount, + vCount, + flags, + aux, + expressions, + indices, + verts, + uv, + colors, + null, + null); + } + + @SuppressWarnings("UnknownNullness") // Annotations on a primitive array are compile error. + public AddMesh2D( + int meshId, + int type, + int layout, + int uCount, + int vCount, + int flags, + int aux, + float[][] expressions, + @Nullable int[] indices, + @Nullable float[] verts, + @Nullable float[] uv, + @Nullable int[] colors, + @Nullable float[] widths, + @Nullable float[] widthPositions) { + mMeshId = meshId; + mType = type; + mLayout = layout; + mUCount = uCount; + mVCount = vCount; + mFlags = flags; + mAux = aux; + + mExpressions = new float[EXPRESSION_GROUPS][]; + mOutExpressions = new float[EXPRESSION_GROUPS][]; + for (int i = 0; i < EXPRESSION_GROUPS; i++) { + float[] group = + (expressions != null && i < expressions.length && expressions[i] != null) + ? expressions[i] + : new float[0]; + mExpressions[i] = group; + mOutExpressions[i] = new float[group.length]; + System.arraycopy(group, 0, mOutExpressions[i], 0, group.length); + } + + mSrcIndices = indices != null ? indices : new int[0]; + mSrcVerts = verts != null ? verts : new float[0]; + mOutSrcVerts = new float[mSrcVerts.length]; + System.arraycopy(mSrcVerts, 0, mOutSrcVerts, 0, mSrcVerts.length); + mSrcUv = uv != null ? uv : new float[0]; + mSrcColors = colors != null ? colors : new int[0]; + + mWidths = widths != null ? widths : new float[0]; + mOutWidths = new float[mWidths.length]; + System.arraycopy(mWidths, 0, mOutWidths, 0, mWidths.length); + mWidthPositions = widthPositions != null ? widthPositions : new float[0]; + mOutWidthPositions = new float[mWidthPositions.length]; + System.arraycopy(mWidthPositions, 0, mOutWidthPositions, 0, mWidthPositions.length); + } + + /** + * The id this mesh is stored under. + * + * @return the mesh id + */ + public int getMeshId() { + return mMeshId; + } + + /** + * The expanded vertex positions, x and y interleaved. + * + * @return the vertex array, valid after the mesh has been expanded + */ + public @NonNull float[] getVerts() { + return mVerts; + } + + /** + * The expanded triangle list. + * + * @return the index array, valid after the mesh has been expanded + */ + public @NonNull int[] getIndices() { + return mIndices; + } + + /** + * The expanded per-vertex colours, packed ARGB, empty when the mesh has none. + * + * @return the colour array, valid after the mesh has been expanded + */ + public @NonNull int[] getColors() { + return mColors; + } + + /** + * The expanded texture coordinates, u and v interleaved, empty when the mesh has none. + * + * @return the uv array, valid after the mesh has been expanded + */ + public @NonNull float[] getUv() { + return mUv; + } + + private static boolean isResolvableVariable(float v) { + return Float.isNaN(v) + && !AnimatedFloatExpression.isMathOperator(v) + && !NanMap.isDataVariable(v) + && !NanMap.isVar1(v); + } + + @Override + public void updateVariables(@NonNull RemoteContext context) { + for (int g = 0; g < EXPRESSION_GROUPS; g++) { + float[] src = mExpressions[g]; + float[] out = mOutExpressions[g]; + for (int i = 0; i < src.length; i++) { + float v = src[i]; + out[i] = isResolvableVariable(v) ? context.getFloat(Utils.idFromNan(v)) : v; + } + } + for (int i = 0; i < mSrcVerts.length; i++) { + float v = mSrcVerts[i]; + mOutSrcVerts[i] = isResolvableVariable(v) ? context.getFloat(Utils.idFromNan(v)) : v; + } + for (int i = 0; i < mWidths.length; i++) { + float v = mWidths[i]; + mOutWidths[i] = isResolvableVariable(v) ? context.getFloat(Utils.idFromNan(v)) : v; + } + for (int i = 0; i < mWidthPositions.length; i++) { + float v = mWidthPositions[i]; + mOutWidthPositions[i] = + isResolvableVariable(v) ? context.getFloat(Utils.idFromNan(v)) : v; + } + // The fit is over the resolved values, so any of them moving retires it. + mWidthSplineValid = false; + mMeshChanged = true; + } + + @Override + public void registerListening(@NonNull RemoteContext context) { + for (int g = 0; g < EXPRESSION_GROUPS; g++) { + for (float v : mExpressions[g]) { + if (Float.isNaN(v) + && !AnimatedFloatExpression.isMathOperator(v) + && !NanMap.isDataVariable(v)) { + context.listensTo(Utils.idFromNan(v), this); + } + } + } + for (float v : mSrcVerts) { + if (Float.isNaN(v) + && !AnimatedFloatExpression.isMathOperator(v) + && !NanMap.isDataVariable(v)) { + context.listensTo(Utils.idFromNan(v), this); + } + } + for (float v : mWidths) { + if (Float.isNaN(v) + && !AnimatedFloatExpression.isMathOperator(v) + && !NanMap.isDataVariable(v)) { + context.listensTo(Utils.idFromNan(v), this); + } + } + for (float v : mWidthPositions) { + if (Float.isNaN(v) + && !AnimatedFloatExpression.isMathOperator(v) + && !NanMap.isDataVariable(v)) { + context.listensTo(Utils.idFromNan(v), this); + } + } + } + + /** Whether {@code type} takes its width from control points rather than from an expression. */ + private static boolean isSplineStrip(int type) { + return type == TYPE_PATH_SPLINE_STRIP || type == TYPE_SPLINE_ROUND_STRIP; + } + + @Override + public void write(@NonNull WireBuffer buffer) { + if (isSplineStrip(mType)) { + // The caps sit outside the body, so subtract them back off to recover what the author + // asked for; applySplineStrip re-derives the same count from it. + int segments = Math.max(1, mUCount - 1 - 2 * roundCapColumns()); + applySplineStrip(buffer, mMeshId, mType, segments, mAux, mWidths, mWidthPositions); + return; + } + apply( + buffer, + mMeshId, + mType, + mLayout, + mUCount, + mVCount, + mFlags, + mAux, + mExpressions, + mSrcIndices, + mSrcVerts, + mSrcUv, + mSrcColors); + } + + /** + * Expand the definition into the flat arrays a rasteriser wants. + * + * <p>Kept separate from {@link #paint} so it can be driven directly by tests. + * + * @param context the context used to resolve path data and array collections + */ + public void expand(@NonNull RemoteContext context) { + if (mType == TYPE_EXPRESSION || isSplineStrip(mType)) { + expandParametric(context); + } else { + expandLiteral(); + } + mMeshChanged = false; + } + + private void expandLiteral() { + int vertexCount = mOutSrcVerts.length / 2; + if (mVerts.length != mOutSrcVerts.length) { + mVerts = new float[mOutSrcVerts.length]; + } + System.arraycopy(mOutSrcVerts, 0, mVerts, 0, mOutSrcVerts.length); + + if (mSrcUv.length == vertexCount * 2) { + if (mUv.length != mSrcUv.length) { + mUv = new float[mSrcUv.length]; + } + System.arraycopy(mSrcUv, 0, mUv, 0, mSrcUv.length); + } else { + mUv = new float[0]; + } + + if (mSrcColors.length == vertexCount) { + if (mColors.length != mSrcColors.length) { + mColors = new int[mSrcColors.length]; + } + System.arraycopy(mSrcColors, 0, mColors, 0, mSrcColors.length); + } else { + mColors = new int[0]; + } + + if (mIndices.length != mSrcIndices.length) { + mIndices = new int[mSrcIndices.length]; + } + System.arraycopy(mSrcIndices, 0, mIndices, 0, mSrcIndices.length); + } + + private void expandParametric(@NonNull RemoteContext context) { + int uCount = Math.max(1, mUCount); + int vCount = Math.max(1, mVCount); + int vertexCount = Mesh2DGenerator.vertexCount(mLayout, uCount, vCount); + int indexCount = Mesh2DGenerator.indexCount(mLayout, uCount, vCount); + + if (mVerts.length != vertexCount * 2) { + mVerts = new float[vertexCount * 2]; + } + if (mIndices.length != indexCount) { + mIndices = new int[indexCount]; + } + + boolean hasTex = + mOutExpressions[EXP_TEX_U].length > 0 || mOutExpressions[EXP_TEX_V].length > 0; + // uv is meaningful for every parametric mesh - the identity mapping is the common case - + // so it is always produced; the backend simply ignores it when nothing is textured. + if (mUv.length != vertexCount * 2) { + mUv = new float[vertexCount * 2]; + } + + boolean hasColor = + mOutExpressions[EXP_COLOR_A].length > 0 + || mOutExpressions[EXP_COLOR_R].length > 0 + || mOutExpressions[EXP_COLOR_G].length > 0 + || mOutExpressions[EXP_COLOR_B].length > 0; + if (hasColor) { + if (mColors.length != vertexCount) { + mColors = new int[vertexCount]; + } + } else { + mColors = new int[0]; + } + + int polylinePoints = 0; + if (mLayout == Mesh2DGenerator.LAYOUT_PATH_STRIP) { + polylinePoints = preparePolyline(context); + } + + boolean fan = mLayout == Mesh2DGenerator.LAYOUT_FAN; + for (int index = 0; index < vertexCount; index++) { + float u; + float v; + if (fan) { + if (index == 0) { + u = 0f; + v = 0f; + } else { + u = Mesh2DGenerator.domainU(mLayout, index - 1, uCount); + v = 1f; + } + } else { + int i = index % uCount; + int j = index / uCount; + u = Mesh2DGenerator.domainU(mLayout, i, uCount); + v = Mesh2DGenerator.domainV(j, vCount); + } + + if (mLayout == Mesh2DGenerator.LAYOUT_PATH_STRIP && polylinePoints > 0) { + positionOnPath(context, u, v, polylinePoints); + } else { + Mesh2DGenerator.defaultPosition(mLayout, u, v, mScratchPosition); + } + + float x = evaluate(context, EXP_X, u, v, mScratchPosition[0]); + float y = evaluate(context, EXP_Y, u, v, mScratchPosition[1]); + mVerts[index * 2] = x; + mVerts[index * 2 + 1] = y; + + if (hasTex) { + mUv[index * 2] = evaluate(context, EXP_TEX_U, u, v, u); + mUv[index * 2 + 1] = evaluate(context, EXP_TEX_V, u, v, v); + } else { + mUv[index * 2] = u; + mUv[index * 2 + 1] = v; + } + + if (hasColor) { + float a = evaluate(context, EXP_COLOR_A, u, v, 1f); + float r = evaluate(context, EXP_COLOR_R, u, v, 1f); + float g = evaluate(context, EXP_COLOR_G, u, v, 1f); + float b = evaluate(context, EXP_COLOR_B, u, v, 1f); + mColors[index] = packColor(a, r, g, b); + } + } + + Mesh2DGenerator.generateIndices(mLayout, uCount, vCount, mIndices); + } + + private int preparePolyline(@NonNull RemoteContext context) { + float[] pathData = context.getPathData(mAux); + if (pathData == null) { + return 0; + } + int capacity = Math.max(64, pathData.length * 8); + if (mScratchPolyline.length < capacity * 2) { + mScratchPolyline = new float[capacity * 2]; + } + return Mesh2DGenerator.flattenPath(pathData, mScratchPolyline); + } + + /** + * How many columns at each end of the strip are given over to a round cap. + * + * <p>Zero for every type but {@link #TYPE_SPLINE_ROUND_STRIP}. The count is clamped against + * {@link #mUCount} rather than trusted, because it arrives from the wire in a field that older + * documents left as a reserved zero and that a corrupt one could set to anything; at least one + * column must be left for the body or the strip would be nothing but caps. + */ + private int roundCapColumns() { + if (mType != TYPE_SPLINE_ROUND_STRIP || mFlags < 1) { + return 0; + } + int columns = mUCount - 1; + if (columns < 3) { + return 0; + } + return Math.min(mFlags, (columns - 1) / 2); + } + + private void positionOnPath(@NonNull RemoteContext context, float u, float v, int points) { + float fraction = u; + int capColumns = roundCapColumns(); + if (capColumns > 0) { + // The caps own the first and last capColumns columns of the u domain; the body is + // squeezed into what is left, so u is no longer the path fraction and has to be + // rescaled. At the joins the two agree exactly, which is what keeps the seam invisible. + float capSpan = capColumns / (float) (mUCount - 1); + if (u <= capSpan) { + capPosition(context, points, 0f, u / capSpan, v, -1f); + return; + } + if (u >= 1f - capSpan) { + capPosition(context, points, 1f, (1f - u) / capSpan, v, 1f); + return; + } + fraction = (u - capSpan) / (1f - 2f * capSpan); + } + Mesh2DGenerator.samplePolyline(mScratchPolyline, points, fraction, mScratchPathSample); + float halfWidth = strokeWidthAt(context, fraction, v) * 0.5f; + float offset = (v - 0.5f) * 2f * halfWidth; + // the normal is the tangent turned a quarter turn + float nx = -mScratchPathSample[3]; + float ny = mScratchPathSample[2]; + mScratchPosition[0] = mScratchPathSample[0] + nx * offset; + mScratchPosition[1] = mScratchPathSample[1] + ny * offset; + } + + /** + * Place a vertex on one of the two round caps. + * + * @param end 0 at the start of the path, 1 at its end + * @param sweep 0 at the tip of the cap, 1 where it meets the body + * @param outward 1 at the end of the path, -1 at the start, being the way the cap bulges + */ + private void capPosition( + @NonNull RemoteContext context, + int points, + float end, + float sweep, + float v, + float outward) { + Mesh2DGenerator.samplePolyline(mScratchPolyline, points, end, mScratchPathSample); + float halfWidth = strokeWidthAt(context, end, v) * 0.5f; + Mesh2DGenerator.roundCapPoint( + mScratchPathSample, halfWidth, sweep * HALF_PI, v, outward, mScratchPosition); + } + + /** + * The full cross width of the ribbon at {@code u}, in the path's own units. + * + * <p>Two sources, chosen by the type. The spline strips interpolate the width control points, + * and because those may be variables the fit is cached and rebuilt only when {@link + * #updateVariables} retires it. Everything else evaluates the width expression, which defaults + * to 1 and so leaves the strip one unit across. + */ + private float strokeWidthAt(@NonNull RemoteContext context, float u, float v) { + if (!isSplineStrip(mType)) { + return evaluate(context, EXP_WIDTH, u, v, 1f); + } + if (!mWidthSplineValid) { + mWidthSpline = Mesh2DGenerator.widthSpline(mOutWidths, mOutWidthPositions); + mWidthSplineValid = true; + } + return Mesh2DGenerator.widthAt(mWidthSpline, mOutWidths, u); + } + + private float evaluate( + @NonNull RemoteContext context, int group, float u, float v, float fallback) { + float[] exp = mOutExpressions[group]; + if (exp.length == 0) { + return fallback; + } + if (exp.length == 1 && !Float.isNaN(exp[0])) { + return exp[0]; + } + CollectionsAccess ca = context.getCollectionsAccess(); + if (ca == null) { + return mExpressionEvaluator.eval(exp, exp.length, u, v); + } else { + return mExpressionEvaluator.eval(ca, exp, exp.length, u, v); + } + } + + private static int packColor(float a, float r, float g, float b) { + int ai = clamp255(a); + int ri = clamp255(r); + int gi = clamp255(g); + int bi = clamp255(b); + return (ai << 24) | (ri << 16) | (gi << 8) | bi; + } + + private static int clamp255(float channel) { + if (Float.isNaN(channel)) { + return 0; + } + int value = (int) (channel * 255f + 0.5f); + if (value < 0) { + return 0; + } + return Math.min(value, 255); + } + + @Override + public void paint(@NonNull PaintContext context) { + RemoteContext remoteContext = context.getContext(); + if (mMeshChanged || mVerts.length == 0) { + expand(remoteContext); + } + context.setMesh(mMeshId, mLayout, mUCount, mVCount, mVerts, mUv, mColors, mIndices); + } + + @NonNull + @Override + public String toString() { + return CLASS_NAME + + " [" + + mMeshId + + "] type=" + + mType + + " layout=" + + mLayout + + " u=" + + mUCount + + " v=" + + mVCount + + " flags=" + + mFlags + + " aux=" + + mAux; + } + + /** + * The name of the class + * + * @return the name + */ + @NonNull + public static String name() { + return CLASS_NAME; + } + + /** + * The OP_CODE for this command + * + * @return the opcode + */ + public static int id() { + return OP_CODE; + } + + /** + * Write a 2D mesh definition to the buffer. + * + * @param buffer the buffer to add to + * @param meshId the id the mesh is stored under + * @param type how the vertex data is supplied + * @param layout the domain topology + * @param uCount grid resolution along u + * @param vCount grid resolution along v + * @param flags reserved + * @param aux layout dependent, e.g. a path id for PATH_STRIP + * @param expressions the RPN expression groups, for TYPE_EXPRESSION + * @param indices the triangle list, for the literal types + * @param verts x,y pairs, for the literal types + * @param uv u,v pairs, for the literal types + * @param colors packed ARGB per vertex, for the literal types + */ + public static void apply( + @NonNull WireBuffer buffer, + int meshId, + int type, + int layout, + int uCount, + int vCount, + int flags, + int aux, + float[][] expressions, + @Nullable int[] indices, + @Nullable float[] verts, + @Nullable float[] uv, + @Nullable int[] colors) { + validate(type, uCount, vCount, indices, verts, uv, colors); + + buffer.start(OP_CODE); + buffer.writeInt(meshId); + buffer.writeInt(type); + buffer.writeInt(layout); + buffer.writeInt(uCount); + buffer.writeInt(vCount); + buffer.writeInt(flags); + buffer.writeInt(aux); + + if (type == TYPE_EXPRESSION) { + for (int g = 0; g < EXPRESSION_GROUPS; g++) { + float[] group = + (expressions != null && g < expressions.length && expressions[g] != null) + ? expressions[g] + : null; + if (group == null) { + // an absent optional channel is a zero length, not a missing field + buffer.writeInt(0); + } else { + if (group.length > Limits.MAX_EXPRESSION_SIZE) { + throw new RuntimeException("Mesh2D expression too long"); + } + buffer.writeInt(group.length); + for (float datum : group) { + buffer.writeFloat(datum); + } + } + } + return; + } + + int[] safeIndices = indices != null ? indices : new int[0]; + float[] safeVerts = verts != null ? verts : new float[0]; + float[] safeUv = uv != null ? uv : new float[0]; + int[] safeColors = colors != null ? colors : new int[0]; + + buffer.writeInt(safeIndices.length); + for (int index : safeIndices) { + // 16 bit indices are settled by the platform: Android's drawVertices takes short[] + // and SkVertices takes uint16_t + buffer.writeShort(index & 0xFFFF); + } + + buffer.writeInt(safeVerts.length); + buffer.writeInt(safeUv.length); + buffer.writeInt(safeColors.length); + + if (type == TYPE_F16_VALUES) { + for (float value : safeVerts) { + buffer.writeShort(Mesh2DGenerator.floatToHalf(value)); + } + for (float value : safeUv) { + buffer.writeShort(Mesh2DGenerator.floatToHalf(value)); + } + } else { + for (float value : safeVerts) { + buffer.writeFloat(value); + } + for (float value : safeUv) { + buffer.writeFloat(value); + } + } + for (int color : safeColors) { + buffer.writeInt(color); + } + } + + /** + * Write a path strip whose cross width is a spline through control points. + * + * <p>The header is derived here rather than taken from the caller: the layout is always {@link + * Mesh2DGenerator#LAYOUT_PATH_STRIP} and the strip is two vertices across, so the only free + * choices are how finely the path is sampled and the widths themselves. + * + * <p>{@code widths} and {@code positions} may hold NaN variable ids, so the profile can be + * animated; the fit is rebuilt whenever one of them changes. + * + * @param buffer the buffer to add to + * @param meshId the id the mesh is stored under + * @param segments roughly how many quads to divide the path into; at least 1 + * @param pathId the path to follow + * @param widths the width control points, at least one, in the path's own units + * @param positions where each width sits along the path, 0..1, empty for evenly spaced + */ + public static void applyPathSplineStrip( + @NonNull WireBuffer buffer, + int meshId, + int segments, + int pathId, + @Nullable float[] widths, + @Nullable float[] positions) { + applySplineStrip( + buffer, meshId, TYPE_PATH_SPLINE_STRIP, segments, pathId, widths, positions); + } + + /** + * Write a spline width path strip that ends in a semicircle at each end. + * + * <p>Exactly {@link #applyPathSplineStrip} but for the type and the cap columns it adds; see + * {@link #TYPE_SPLINE_ROUND_STRIP}. {@code segments} still describes the body alone, so a + * rounded strip and a flat one with the same argument follow the path identically. + * + * @param buffer the buffer to add to + * @param meshId the id the mesh is stored under + * @param segments roughly how many quads to divide the path into, excluding the caps + * @param pathId the path to follow + * @param widths the width control points, at least one, in the path's own units + * @param positions where each width sits along the path, 0..1, empty for evenly spaced + */ + public static void applySplineRoundStrip( + @NonNull WireBuffer buffer, + int meshId, + int segments, + int pathId, + @Nullable float[] widths, + @Nullable float[] positions) { + applySplineStrip( + buffer, meshId, TYPE_SPLINE_ROUND_STRIP, segments, pathId, widths, positions); + } + + private static void applySplineStrip( + @NonNull WireBuffer buffer, + int meshId, + int type, + int segments, + int pathId, + @Nullable float[] widths, + @Nullable float[] positions) { + float[] safeWidths = widths != null ? widths : new float[0]; + float[] safePositions = positions != null ? positions : new float[0]; + int capSegments = + type == TYPE_SPLINE_ROUND_STRIP ? Mesh2DGenerator.roundCapSegments(segments) : 0; + validateSplineStrip(segments, capSegments, safeWidths, safePositions); + + buffer.start(OP_CODE); + buffer.writeInt(meshId); + buffer.writeInt(type); + buffer.writeInt(Mesh2DGenerator.LAYOUT_PATH_STRIP); + // segments quads need segments + 1 rings of vertices, two across, plus a cap at each end. + buffer.writeInt(segments + 1 + 2 * capSegments); + buffer.writeInt(2); + // flags carries the cap width so the reader can tell body columns from cap columns. + buffer.writeInt(capSegments); + buffer.writeInt(pathId); + + buffer.writeInt(safeWidths.length); + for (float width : safeWidths) { + buffer.writeFloat(width); + } + buffer.writeInt(safePositions.length); + for (float position : safePositions) { + buffer.writeFloat(position); + } + } + + private static void validateSplineStrip( + int segments, int capSegments, @NonNull float[] widths, @NonNull float[] positions) { + if (segments < 1) { + throw new RuntimeException("Mesh2D path strip needs at least 1 segment"); + } + if (widths.length < 1) { + throw new RuntimeException("Mesh2D path strip needs at least 1 width"); + } + if (widths.length > Limits.MAX_MESH_2D_WIDTH_SAMPLES) { + throw new RuntimeException( + "Mesh2D width sample count " + + widths.length + + " exceeds MAX_MESH_2D_WIDTH_SAMPLES (" + + Limits.MAX_MESH_2D_WIDTH_SAMPLES + + ")"); + } + if (positions.length != 0 && positions.length != widths.length) { + throw new RuntimeException( + "Mesh2D width positions (" + + positions.length + + ") must match widths (" + + widths.length + + ")"); + } + long grid = (long) (segments + 1 + 2 * capSegments) * 2L; + if (grid > Limits.MAX_MESH_2D_GRID) { + throw new RuntimeException( + "Mesh2D path strip " + + segments + + " segments exceeds MAX_MESH_2D_GRID (" + + Limits.MAX_MESH_2D_GRID + + ")"); + } + // A variable position is only known at playback, so only literals can be ordered here. + float previous = Float.NEGATIVE_INFINITY; + for (float position : positions) { + if (Float.isNaN(position)) { + previous = Float.NEGATIVE_INFINITY; + continue; + } + if (previous != Float.NEGATIVE_INFINITY && position <= previous) { + throw new RuntimeException("Mesh2D width positions must be increasing"); + } + previous = position; + } + } + + private static void validate( + int type, + int uCount, + int vCount, + @Nullable int[] indices, + @Nullable float[] verts, + @Nullable float[] uv, + @Nullable int[] colors) { + if (type == TYPE_EXPRESSION) { + long grid = (long) uCount * (long) vCount; + if (grid > Limits.MAX_MESH_2D_GRID) { + throw new RuntimeException( + "Mesh2D grid " + + uCount + + "x" + + vCount + + " exceeds MAX_MESH_2D_GRID (" + + Limits.MAX_MESH_2D_GRID + + ")"); + } + return; + } + int vertexCount = verts != null ? verts.length / 2 : 0; + if (vertexCount > Limits.MAX_MESH_2D_VERTICES) { + throw new RuntimeException( + "Mesh2D vertex count " + + vertexCount + + " exceeds MAX_MESH_2D_VERTICES (" + + Limits.MAX_MESH_2D_VERTICES + + ")"); + } + int uvCount = uv != null ? uv.length / 2 : 0; + if (uvCount > Limits.MAX_MESH_2D_VERTICES) { + throw new RuntimeException( + "Mesh2D UV count " + + uvCount + + " exceeds MAX_MESH_2D_VERTICES (" + + Limits.MAX_MESH_2D_VERTICES + + ")"); + } + int colorCount = colors != null ? colors.length : 0; + if (colorCount > Limits.MAX_MESH_2D_VERTICES) { + throw new RuntimeException( + "Mesh2D color count " + + colorCount + + " exceeds MAX_MESH_2D_VERTICES (" + + Limits.MAX_MESH_2D_VERTICES + + ")"); + } + int indexCount = indices != null ? indices.length : 0; + if (indexCount > Limits.MAX_MESH_2D_INDICES) { + throw new RuntimeException( + "Mesh2D index count " + + indexCount + + " exceeds MAX_MESH_2D_INDICES (" + + Limits.MAX_MESH_2D_INDICES + + ")"); + } + } + + /** + * Read this operation and add it to the list of operations + * + * @param buffer the buffer to read + * @param operations the list of operations that will be added to + */ + public static void read(@NonNull WireBuffer buffer, @NonNull List<Operation> operations) { + int meshId = buffer.readId(); + int type = buffer.readInt(); + int layout = buffer.readInt(); + int uCount = buffer.readInt(); + int vCount = buffer.readInt(); + int flags = buffer.readInt(); + int aux = buffer.readInt(); + + float[][] expressions = null; + int[] indices = null; + float[] verts = null; + float[] uv = null; + int[] colors = null; + float[] widths = null; + float[] widthPositions = null; + + if (isSplineStrip(type)) { + long grid = (long) uCount * (long) vCount; + if (grid > Limits.MAX_MESH_2D_GRID) { + throw new RuntimeException( + "Mesh2D grid exceeds MAX_MESH_2D_GRID (" + Limits.MAX_MESH_2D_GRID + ")"); + } + int widthCount = buffer.readInt(); + if (widthCount < 0 || widthCount > Limits.MAX_MESH_2D_WIDTH_SAMPLES) { + throw new RuntimeException( + "Mesh2D width sample count exceeds MAX_MESH_2D_WIDTH_SAMPLES (" + + Limits.MAX_MESH_2D_WIDTH_SAMPLES + + ")"); + } + widths = new float[widthCount]; + for (int i = 0; i < widthCount; i++) { + widths[i] = buffer.readNanId(); + } + int positionCount = buffer.readInt(); + if (positionCount < 0 || positionCount > Limits.MAX_MESH_2D_WIDTH_SAMPLES) { + throw new RuntimeException( + "Mesh2D width position count exceeds MAX_MESH_2D_WIDTH_SAMPLES (" + + Limits.MAX_MESH_2D_WIDTH_SAMPLES + + ")"); + } + widthPositions = new float[positionCount]; + for (int i = 0; i < positionCount; i++) { + widthPositions[i] = buffer.readNanId(); + } + } else if (type == TYPE_EXPRESSION) { + long grid = (long) uCount * (long) vCount; + if (grid > Limits.MAX_MESH_2D_GRID) { + throw new RuntimeException( + "Mesh2D grid exceeds MAX_MESH_2D_GRID (" + Limits.MAX_MESH_2D_GRID + ")"); + } + expressions = new float[EXPRESSION_GROUPS][]; + for (int g = 0; g < EXPRESSION_GROUPS; g++) { + int len = buffer.readInt(); + if (len < 0 || len > Limits.MAX_EXPRESSION_SIZE) { + throw new RuntimeException("Mesh2D expression too long"); + } + float[] group = new float[len]; + for (int i = 0; i < len; i++) { + group[i] = buffer.readNanId(); + } + expressions[g] = group; + } + } else { + int indexCount = buffer.readInt(); + if (indexCount < 0 || indexCount > Limits.MAX_MESH_2D_INDICES) { + throw new RuntimeException( + "Mesh2D index count exceeds MAX_MESH_2D_INDICES (" + + Limits.MAX_MESH_2D_INDICES + + ")"); + } + indices = new int[indexCount]; + for (int i = 0; i < indexCount; i++) { + indices[i] = buffer.readShort() & 0xFFFF; + } + + int vertsLen = buffer.readInt(); + int uvLen = buffer.readInt(); + int colorsLen = buffer.readInt(); + if (vertsLen < 0 || vertsLen / 2 > Limits.MAX_MESH_2D_VERTICES) { + throw new RuntimeException( + "Mesh2D vertex count exceeds MAX_MESH_2D_VERTICES (" + + Limits.MAX_MESH_2D_VERTICES + + ")"); + } + if (uvLen < 0 || uvLen / 2 > Limits.MAX_MESH_2D_VERTICES) { + throw new RuntimeException( + "Mesh2D UV count exceeds MAX_MESH_2D_VERTICES (" + + Limits.MAX_MESH_2D_VERTICES + + ")"); + } + if (colorsLen < 0 || colorsLen > Limits.MAX_MESH_2D_VERTICES) { + throw new RuntimeException( + "Mesh2D color count exceeds MAX_MESH_2D_VERTICES (" + + Limits.MAX_MESH_2D_VERTICES + + ")"); + } + + verts = new float[vertsLen]; + uv = new float[uvLen]; + colors = new int[colorsLen]; + + if (type == TYPE_F16_VALUES) { + // widened here, on read, so nothing downstream knows the document used halves + for (int i = 0; i < vertsLen; i++) { + verts[i] = Mesh2DGenerator.halfToFloat(buffer.readShort() & 0xFFFF); + } + for (int i = 0; i < uvLen; i++) { + uv[i] = Mesh2DGenerator.halfToFloat(buffer.readShort() & 0xFFFF); + } + } else { + for (int i = 0; i < vertsLen; i++) { + verts[i] = buffer.readNanId(); + } + for (int i = 0; i < uvLen; i++) { + uv[i] = buffer.readFloat(); + } + } + for (int i = 0; i < colorsLen; i++) { + colors[i] = buffer.readInt(); + } + } + + operations.add( + new AddMesh2D( + meshId, + type, + layout, + uCount, + vCount, + flags, + aux, + expressions, + indices, + verts, + uv, + colors, + widths, + widthPositions)); + } + + /** + * Populate the documentation with a description of this operation + * + * @param doc to append the description to. + */ + public static void documentation(@NonNull DocumentationBuilder doc) { + doc.operation("Canvas Operations", OP_CODE, CLASS_NAME) + .addedVersion(7) + .experimental(true) + .description( + "Define a 2D vertex mesh. Independent of the 3D subsystem: no z, no" + + " normals, no camera, no lights, no depth buffer. Positioned by" + + " the ordinary 2D canvas matrix.") + .field(INT, "meshId", "The id the mesh is stored under") + .field(INT, "type", "How the vertex data is supplied") + .possibleValues("TYPE_EXPRESSION", TYPE_EXPRESSION) + .possibleValues("TYPE_VALUES", TYPE_VALUES) + .possibleValues("TYPE_F16_VALUES", TYPE_F16_VALUES) + .possibleValues("TYPE_PATH_SPLINE_STRIP", TYPE_PATH_SPLINE_STRIP) + .possibleValues("TYPE_SPLINE_ROUND_STRIP", TYPE_SPLINE_ROUND_STRIP) + .field(INT, "layout", "The domain topology") + .possibleValues("LAYOUT_GRID", Mesh2DGenerator.LAYOUT_GRID) + .possibleValues("LAYOUT_POLAR", Mesh2DGenerator.LAYOUT_POLAR) + .possibleValues("LAYOUT_RING", Mesh2DGenerator.LAYOUT_RING) + .possibleValues("LAYOUT_STRIP", Mesh2DGenerator.LAYOUT_STRIP) + .possibleValues("LAYOUT_FAN", Mesh2DGenerator.LAYOUT_FAN) + .possibleValues("LAYOUT_PATH_STRIP", Mesh2DGenerator.LAYOUT_PATH_STRIP) + .field(INT, "uCount", "Grid resolution along u") + .field(INT, "vCount", "Grid resolution along v") + .field(INT, "flags", "Cap columns for TYPE_SPLINE_ROUND_STRIP, otherwise reserved") + .field(INT, "aux", "Layout dependent, e.g. a path id for PATH_STRIP") + .field(FLOAT_ARRAY, "expressions", "Eight RPN groups: x, y, texU, texV, a, r, g, b") + .field(INT_ARRAY, "indices", "Triangle list, 16 bit, for the literal types") + .field(FLOAT_ARRAY, "verts", "x,y pairs for the literal types") + .field(FLOAT_ARRAY, "uv", "u,v pairs for the literal types") + .field(INT_ARRAY, "colors", "Packed ARGB per vertex for the literal types") + .field(FLOAT_ARRAY, "widths", "Width control points, for the spline strip types") + .field( + FLOAT_ARRAY, + "widthPositions", + "Where each width sits along the path, 0..1, empty for evenly spaced"); + } + + @Override + public void serialize(@NonNull MapSerializer serializer) { + serializer + .addType(CLASS_NAME) + .add("meshId", mMeshId) + .add("type", mType) + .add("layout", mLayout) + .add("uCount", mUCount) + .add("vCount", mVCount) + .add("flags", mFlags) + .add("aux", mAux); + } +}
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/BitmapData.java b/core/java/com/android/internal/widget/remotecompose/core/operations/BitmapData.java index 8c9eb3f..bca6696 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/BitmapData.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/BitmapData.java
@@ -20,6 +20,7 @@ import com.android.internal.widget.remotecompose.core.Limits; import com.android.internal.widget.remotecompose.core.Operation; import com.android.internal.widget.remotecompose.core.Operations; +import com.android.internal.widget.remotecompose.core.PaintContext; import com.android.internal.widget.remotecompose.core.RemoteContext; import com.android.internal.widget.remotecompose.core.SerializableToString; import com.android.internal.widget.remotecompose.core.VariableProvider; @@ -59,6 +60,9 @@ /** allocates a new bitmap data with value = 0 */ public static final short ENCODING_EMPTY = 3; + /** allocates an offscreen buffer dynamically sized to a target component */ + public static final short ENCODING_COMPONENT_OFFSCREEN_BUFFER = 4; + /** The data is encoded as PNG_8888 (default) */ public static final short TYPE_PNG_8888 = 0; @@ -319,10 +323,419 @@ .field(DocumentedOperation.BYTE_ARRAY, "bitmap", "The raw or encoded bitmap data"); } + /** + * Returns the encoding type of this bitmap operation. + * + * @return the encoding constant (e.g. {@link #ENCODING_INLINE} or {@link + * #ENCODING_COMPONENT_OFFSCREEN_BUFFER}) + */ + public short getEncoding() { + return mEncoding; + } + + /** + * Returns the component ID encoded in the payload when {@link #getEncoding()} is {@link + * #ENCODING_COMPONENT_OFFSCREEN_BUFFER}, or 0 otherwise. + * + * @return the associated component ID or variable ID, or 0 + */ + public int getComponentId() { + if (mEncoding == ENCODING_COMPONENT_OFFSCREEN_BUFFER && mBitmap.length >= 4) { + return ((mBitmap[0] & 0xFF) << 24) + | ((mBitmap[1] & 0xFF) << 16) + | ((mBitmap[2] & 0xFF) << 8) + | (mBitmap[3] & 0xFF); + } + return 0; + } + + /** + * Updates the width of this bitmap operation. + * + * @param width the new width in pixels + */ + public void setWidth(int width) { + mImageWidth = width; + } + + /** + * Updates the height of this bitmap operation. + * + * @param height the new height in pixels + */ + public void setHeight(int height) { + mImageHeight = height; + } + + private static final byte[] EMPTY_BITMAP_BYTES = new byte[0]; + + private static final class PooledBitmap { + final Object mBitmap; + final int mWidth; + final int mHeight; + + PooledBitmap(@NonNull Object bitmap, int width, int height) { + mBitmap = bitmap; + mWidth = width; + mHeight = height; + } + } + + private static final class SavedBinding { + final BitmapData mBitmapData; + final PooledBitmap mPrevBitmap; + final int mPrevWidth; + final int mPrevHeight; + + SavedBinding( + @NonNull BitmapData bitmapData, + @NonNull PooledBitmap prevBitmap, + int prevWidth, + int prevHeight) { + mBitmapData = bitmapData; + mPrevBitmap = prevBitmap; + mPrevWidth = prevWidth; + mPrevHeight = prevHeight; + } + } + + private static final class ScopeFrame { + final java.util.ArrayList<PooledBitmap> mAcquired = new java.util.ArrayList<>(); + final java.util.ArrayList<SavedBinding> mSaved = new java.util.ArrayList<>(); + } + + private static final class OffscreenBitmapPool { + private int mNextPoolBitmapId = 0x70000000; + private final java.util.ArrayList<PooledBitmap> mFreeBitmapPool = + new java.util.ArrayList<>(); + private final java.util.ArrayList<PooledBitmap> mInUseBitmaps = new java.util.ArrayList<>(); + private final java.util.HashMap<Integer, PooledBitmap> mActiveIdToBitmap = + new java.util.HashMap<>(); + private final java.util.ArrayList<ScopeFrame> mScopeStack = new java.util.ArrayList<>(); + private int mMaxPooledWidth = 0; + private int mMaxPooledHeight = 0; + + private void returnBitmapToPool(PooledBitmap entry) { + if (entry == null || mFreeBitmapPool.contains(entry)) { + return; + } + if (mFreeBitmapPool.size() >= Limits.MAX_BITMAP_POOL_SIZE) { + int smallestIdx = 0; + int smallestArea = mFreeBitmapPool.get(0).mWidth * mFreeBitmapPool.get(0).mHeight; + for (int i = 1; i < mFreeBitmapPool.size(); i++) { + PooledBitmap b = mFreeBitmapPool.get(i); + int area = b.mWidth * b.mHeight; + if (area < smallestArea) { + smallestArea = area; + smallestIdx = i; + } + } + mFreeBitmapPool.remove(smallestIdx); + } + mFreeBitmapPool.add(entry); + } + + private PooledBitmap acquireBitmapFromPool( + @NonNull RemoteContext context, int reqWidth, int reqHeight) { + mMaxPooledWidth = Math.max(mMaxPooledWidth, reqWidth); + mMaxPooledHeight = Math.max(mMaxPooledHeight, reqHeight); + int bestIdx = -1; + int bestArea = Integer.MAX_VALUE; + for (int i = 0; i < mFreeBitmapPool.size(); i++) { + PooledBitmap candidate = mFreeBitmapPool.get(i); + if (candidate.mWidth >= reqWidth && candidate.mHeight >= reqHeight) { + int area = candidate.mWidth * candidate.mHeight; + if (area < bestArea) { + bestArea = area; + bestIdx = i; + } + } + } + if (bestIdx >= 0) { + PooledBitmap reused = mFreeBitmapPool.remove(bestIdx); + mInUseBitmaps.add(reused); + return reused; + } + if (!mFreeBitmapPool.isEmpty()) { + int smallestIdx = 0; + int smallestArea = mFreeBitmapPool.get(0).mWidth * mFreeBitmapPool.get(0).mHeight; + for (int i = 1; i < mFreeBitmapPool.size(); i++) { + PooledBitmap b = mFreeBitmapPool.get(i); + int area = b.mWidth * b.mHeight; + if (area < smallestArea) { + smallestArea = area; + smallestIdx = i; + } + } + mFreeBitmapPool.remove(smallestIdx); + } + int allocW = Math.max(reqWidth, mMaxPooledWidth); + int allocH = Math.max(reqHeight, mMaxPooledHeight); + if ((long) allocW * allocH * 4L > Limits.MAX_BITMAP_MEMORY) { + allocW = reqWidth; + allocH = reqHeight; + } + int slotId = mNextPoolBitmapId++; + context.loadBitmap( + slotId, ENCODING_EMPTY, TYPE_RAW8888, allocW, allocH, EMPTY_BITMAP_BYTES); + Object platformBitmap = + context.mRemoteComposeState != null + ? context.mRemoteComposeState.getFromId(slotId) + : null; + if (platformBitmap == null) { + return null; + } + PooledBitmap created = new PooledBitmap(platformBitmap, allocW, allocH); + mInUseBitmaps.add(created); + return created; + } + + void ensureBitmap( + @NonNull RemoteContext context, + @NonNull BitmapData bd, + int prevW, + int prevH, + int reqW, + int reqH) { + int imageId = bd.mImageId; + PooledBitmap current = mActiveIdToBitmap.get(imageId); + ScopeFrame topScope = + mScopeStack.isEmpty() ? null : mScopeStack.get(mScopeStack.size() - 1); + boolean ownedByCurrentScope = topScope == null || topScope.mAcquired.contains(current); + boolean keepExisting = + current != null + && ownedByCurrentScope + && current.mWidth >= reqW + && current.mHeight >= reqH; + if (!keepExisting) { + if (current != null) { + if (ownedByCurrentScope) { + mActiveIdToBitmap.remove(imageId); + mInUseBitmaps.remove(current); + if (topScope != null) { + topScope.mAcquired.remove(current); + } + returnBitmapToPool(current); + } else { + topScope.mSaved.add(new SavedBinding(bd, current, prevW, prevH)); + mActiveIdToBitmap.remove(imageId); + } + } + PooledBitmap acquired = acquireBitmapFromPool(context, reqW, reqH); + if (acquired != null && context.mRemoteComposeState != null) { + if (topScope != null) { + topScope.mAcquired.add(acquired); + } + mActiveIdToBitmap.put(imageId, acquired); + if (context.mRemoteComposeState.containsId(imageId)) { + context.mRemoteComposeState.updateData(imageId, acquired.mBitmap); + } else { + context.mRemoteComposeState.cacheData(imageId, acquired.mBitmap); + } + } + } + } + + void pushScope() { + mScopeStack.add(new ScopeFrame()); + } + + void popScope(@NonNull RemoteContext context) { + if (mScopeStack.isEmpty()) { + releaseAll(); + return; + } + ScopeFrame frame = mScopeStack.remove(mScopeStack.size() - 1); + for (int i = 0; i < frame.mAcquired.size(); i++) { + PooledBitmap b = frame.mAcquired.get(i); + mInUseBitmaps.remove(b); + returnBitmapToPool(b); + mActiveIdToBitmap.values().remove(b); + } + for (int i = frame.mSaved.size() - 1; i >= 0; i--) { + SavedBinding saved = frame.mSaved.get(i); + saved.mBitmapData.mImageWidth = saved.mPrevWidth; + saved.mBitmapData.mImageHeight = saved.mPrevHeight; + mActiveIdToBitmap.put(saved.mBitmapData.mImageId, saved.mPrevBitmap); + if (context.mRemoteComposeState != null) { + context.mRemoteComposeState.updateData( + saved.mBitmapData.mImageId, saved.mPrevBitmap.mBitmap); + } + } + } + + void resumeTargetCanvas(@NonNull PaintContext paintContext, int bitmapId) { + RemoteContext context = paintContext.getContext(); + Object prevObj = null; + if (!mScopeStack.isEmpty()) { + ScopeFrame frame = mScopeStack.get(mScopeStack.size() - 1); + for (int i = frame.mSaved.size() - 1; i >= 0; i--) { + SavedBinding saved = frame.mSaved.get(i); + if (saved.mBitmapData.mImageId == bitmapId) { + prevObj = saved.mPrevBitmap.mBitmap; + break; + } + } + } + if (prevObj != null && context.mRemoteComposeState != null) { + Object curObj = context.mRemoteComposeState.getFromId(bitmapId); + context.mRemoteComposeState.updateData(bitmapId, prevObj); + paintContext.drawToBitmap(bitmapId, 1, 0); + if (curObj != null) { + context.mRemoteComposeState.updateData(bitmapId, curObj); + } + } else { + paintContext.drawToBitmap(bitmapId, 1, 0); + } + } + + void releaseAll() { + for (int i = 0; i < mInUseBitmaps.size(); i++) { + returnBitmapToPool(mInUseBitmaps.get(i)); + } + mInUseBitmaps.clear(); + mActiveIdToBitmap.clear(); + mScopeStack.clear(); + } + } + + private static final java.util.WeakHashMap<RemoteContext, OffscreenBitmapPool> sPools = + new java.util.WeakHashMap<>(); + + private static @NonNull OffscreenBitmapPool getPool(@NonNull RemoteContext context) { + synchronized (sPools) { + OffscreenBitmapPool pool = sPools.get(context); + if (pool == null) { + pool = new OffscreenBitmapPool(); + sPools.put(context, pool); + } + return pool; + } + } + + /** + * Pushes a new offscreen bitmap pool scope for the given {@link RemoteContext}. + * + * @param context the current RemoteContext + */ + public static void pushOffscreenScope(@NonNull RemoteContext context) { + synchronized (sPools) { + getPool(context).pushScope(); + } + } + + /** + * Pops the current offscreen bitmap pool scope, returning bitmaps acquired in that scope to the + * pool and restoring any overwritten {@link BitmapData} bindings. + * + * @param context the current RemoteContext + */ + public static void popOffscreenScope(@NonNull RemoteContext context) { + synchronized (sPools) { + OffscreenBitmapPool pool = sPools.get(context); + if (pool != null) { + pool.popScope(context); + } + } + } + + /** + * Switches the active {@link PaintContext} canvas back to an enclosing offscreen target bitmap + * without erasing it or losing the current scope's bitmap binding. + * + * @param paintContext the current PaintContext + * @param bitmapId the enclosing offscreen target bitmap ID + */ + public static void resumeOffscreenTargetCanvas( + @NonNull PaintContext paintContext, int bitmapId) { + synchronized (sPools) { + OffscreenBitmapPool pool = sPools.get(paintContext.getContext()); + if (pool != null) { + pool.resumeTargetCanvas(paintContext, bitmapId); + } else { + paintContext.drawToBitmap(bitmapId, 1, 0); + } + } + } + + /** + * Releases all active offscreen bitmaps back to the offscreen bitmap pool for the given {@link + * RemoteContext}. + * + * @param context the current RemoteContext + */ + public static void releaseOffscreenBitmaps(@NonNull RemoteContext context) { + synchronized (sPools) { + OffscreenBitmapPool pool = sPools.get(context); + if (pool != null) { + pool.releaseAll(); + } + } + } + + /** + * Resolves the target component for a {@link #ENCODING_COMPONENT_OFFSCREEN_BUFFER} bitmap, + * updates its width and height to match the component bounds, and acquires a backing bitmap + * from the offscreen bitmap pool. + * + * @param context the current RemoteContext + */ + public void ensureOffscreenBitmap(@NonNull RemoteContext context) { + if (mEncoding != ENCODING_COMPONENT_OFFSCREEN_BUFFER) { + return; + } + com.android.internal.widget.remotecompose.core.operations.layout.Component targetComp = + null; + int compId = getComponentId(); + if (compId != 0) { + int resolved = context.getInteger(compId); + if (resolved != 0) { + compId = resolved; + } else { + float fVal = context.getFloat(compId); + if (!Float.isNaN(fVal) && fVal != 0f) { + compId = (int) fVal; + } + } + if (context.getDocument() != null) { + targetComp = context.getDocument().getComponent(compId); + } + } + if (targetComp == null && context.getPaintContext() != null) { + targetComp = context.getPaintContext().getOffscreenComponent(); + } + if (targetComp == null) { + targetComp = context.mLastComponent; + } + if (targetComp == null) { + return; + } + int prevW = mImageWidth; + int prevH = mImageHeight; + float x = (float) Math.floor(targetComp.getX()); + float y = (float) Math.floor(targetComp.getY()); + int reqW = Math.max(1, (int) Math.ceil((targetComp.getX() - x) + targetComp.getWidth())); + int reqH = Math.max(1, (int) Math.ceil((targetComp.getY() - y) + targetComp.getHeight())); + if (reqW < 1 + || reqH < 1 + || reqW > Limits.MAX_IMAGE_DIMENSION + || reqH > Limits.MAX_IMAGE_DIMENSION + || (long) reqW * reqH * 4L > Limits.MAX_BITMAP_MEMORY) { + throw new RuntimeException("Dimension of image is invalid " + reqW + "x" + reqH); + } + mImageWidth = reqW; + mImageHeight = reqH; + getPool(context).ensureBitmap(context, this, prevW, prevH, reqW, reqH); + } + @Override public void apply(@NonNull RemoteContext context) { context.putObject(mImageId, this); - context.loadBitmap(mImageId, mEncoding, mType, mImageWidth, mImageHeight, mBitmap); + if (mEncoding == ENCODING_COMPONENT_OFFSCREEN_BUFFER) { + ensureOffscreenBitmap(context); + } else { + context.loadBitmap(mImageId, mEncoding, mType, mImageWidth, mImageHeight, mBitmap); + } } @NonNull @@ -357,6 +770,8 @@ return "ENCODING_URL"; case ENCODING_FILE: return "ENCODING_FILE"; + case ENCODING_COMPONENT_OFFSCREEN_BUFFER: + return "ENCODING_COMPONENT_OFFSCREEN_BUFFER"; default: return "ENCODING_INVALID"; }
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/DrawContent.java b/core/java/com/android/internal/widget/remotecompose/core/operations/DrawContent.java index 53b4c77..72b9f2e 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/DrawContent.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/DrawContent.java
@@ -24,6 +24,7 @@ import com.android.internal.widget.remotecompose.core.PaintOperation; import com.android.internal.widget.remotecompose.core.WireBuffer; import com.android.internal.widget.remotecompose.core.documentation.DocumentationBuilder; +import com.android.internal.widget.remotecompose.core.operations.layout.Component; import com.android.internal.widget.remotecompose.core.operations.layout.LayoutComponent; import com.android.internal.widget.remotecompose.core.serialize.MapSerializer; import com.android.internal.widget.remotecompose.core.serialize.Serializable; @@ -37,6 +38,7 @@ private @Nullable LayoutComponent mComponent; boolean mInProcessing = false; + private @Nullable Component mProcessingComponent = null; @Override public void write(@NonNull WireBuffer buffer) { @@ -109,11 +111,41 @@ @Override public void paint(@NonNull PaintContext context) { - if (mComponent != null) { - if (!mInProcessing) { - mInProcessing = true; - mComponent.drawContent(context); - mInProcessing = false; + Component offscreenComp = context.getOffscreenComponent(); + boolean isOffscreenRoot = + offscreenComp != null && (mComponent == null || mComponent == offscreenComp); + Component target = + isOffscreenRoot + ? offscreenComp + : (mComponent != null ? mComponent : context.getContext().mLastComponent); + if (target != null && !(mInProcessing && mProcessingComponent == target)) { + boolean prevInProcessing = mInProcessing; + Component prevProcessingComp = mProcessingComponent; + mInProcessing = true; + mProcessingComponent = target; + try { + if (mComponent != null && !isOffscreenRoot && target instanceof LayoutComponent) { + ((LayoutComponent) target).drawContent(context); + } else if (isOffscreenRoot) { + context.setOffscreenComponent(null); + context.save(); + context.translate( + -(float) Math.floor(target.getX()), -(float) Math.floor(target.getY())); + try { + target.paintingComponent(context); + } finally { + context.restore(); + context.setOffscreenComponent(offscreenComp); + } + } else if (target.mAnimateMeasure != null) { + context.saveLayer( + target.getX(), target.getY(), target.getWidth(), target.getHeight()); + target.paintingComponent(context); + context.restore(); + } + } finally { + mInProcessing = prevInProcessing; + mProcessingComponent = prevProcessingComp; } } }
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/DrawMesh2D.java b/core/java/com/android/internal/widget/remotecompose/core/operations/DrawMesh2D.java new file mode 100644 index 0000000..147436d --- /dev/null +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/DrawMesh2D.java
@@ -0,0 +1,165 @@ +/* + * Copyright (C) 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.internal.widget.remotecompose.core.operations; + +import static com.android.internal.widget.remotecompose.core.documentation.DocumentedOperation.INT; + +import android.annotation.NonNull; + +import com.android.internal.widget.remotecompose.core.Operation; +import com.android.internal.widget.remotecompose.core.Operations; +import com.android.internal.widget.remotecompose.core.PaintContext; +import com.android.internal.widget.remotecompose.core.PaintOperation; +import com.android.internal.widget.remotecompose.core.WireBuffer; +import com.android.internal.widget.remotecompose.core.documentation.DocumentationBuilder; +import com.android.internal.widget.remotecompose.core.serialize.MapSerializer; +import com.android.internal.widget.remotecompose.core.serialize.Serializable; + +import java.util.List; + +/** + * Draws a 2D vertex mesh previously defined by {@link AddMesh2D}. + * + * <p>The image is named where it is used rather than bound by a separate operation, because 2D + * cannot afford an opcode for texture binding the way 3D can. {@code imageId} refers to a bitmap + * already in the document - the same ids {@code drawBitmap} uses - so there is no new loading + * mechanism. + * + * <p>The mesh is positioned by the ordinary 2D canvas matrix, so this composes with {@code + * save}/{@code restore}/{@code translate} exactly as {@code drawRect} does. + */ +public class DrawMesh2D extends PaintOperation implements Serializable { + private static final int OP_CODE = Operations.DRAW_MESH_2D; + private static final String CLASS_NAME = "DrawMesh2D"; + + /** + * Interpolate the per-vertex colours across each triangle and ignore any texture. + * + * <p>This is Android's behaviour when {@code colors} is supplied and {@code texs} is not. + */ + public static final int BLEND_COLORS_ONLY = 0; + + /** + * Multiply the sampled texel by the interpolated vertex colour. + * + * <p>This is Android's documented behaviour when both {@code texs} and {@code colors} are + * present, and exactly what the Skia path does with {@code kModulate}, so the two platforms + * agree for free. + */ + public static final int BLEND_MODULATE = 1; + + /** {@code imageId} value meaning the mesh is untextured. */ + public static final int NO_IMAGE = 0; + + private final int mMeshId; + private final int mBlend; + private final int mImageId; + + public DrawMesh2D(int meshId, int blend, int imageId) { + mMeshId = meshId; + mBlend = blend; + mImageId = imageId; + } + + @Override + public void write(@NonNull WireBuffer buffer) { + apply(buffer, mMeshId, mBlend, mImageId); + } + + @Override + public void paint(@NonNull PaintContext context) { + context.drawMesh(mMeshId, mBlend, mImageId); + } + + @NonNull + @Override + public String toString() { + return CLASS_NAME + " [" + mMeshId + "] blend=" + mBlend + " image=" + mImageId; + } + + /** + * The name of the class + * + * @return the name + */ + @NonNull + public static String name() { + return CLASS_NAME; + } + + /** + * The OP_CODE for this command + * + * @return the opcode + */ + public static int id() { + return OP_CODE; + } + + /** + * Draw a previously defined 2D mesh. + * + * @param buffer the buffer to add to + * @param meshId the mesh to draw + * @param blend how vertex colour and texel combine + * @param imageId the bitmap to sample, {@link #NO_IMAGE} for untextured + */ + public static void apply(@NonNull WireBuffer buffer, int meshId, int blend, int imageId) { + buffer.start(OP_CODE); + buffer.writeInt(meshId); + buffer.writeInt(blend); + buffer.writeInt(imageId); + } + + /** + * Read this operation and add it to the list of operations + * + * @param buffer the buffer to read + * @param operations the list of operations that will be added to + */ + public static void read(@NonNull WireBuffer buffer, @NonNull List<Operation> operations) { + int meshId = buffer.readId(); + int blend = buffer.readInt(); + int imageId = buffer.readInt(); + operations.add(new DrawMesh2D(meshId, blend, imageId)); + } + + /** + * Populate the documentation with a description of this operation + * + * @param doc to append the description to. + */ + public static void documentation(@NonNull DocumentationBuilder doc) { + doc.operation("Canvas Operations", OP_CODE, CLASS_NAME) + .addedVersion(7) + .experimental(true) + .description("Draw a 2D vertex mesh defined by AddMesh2D") + .field(INT, "meshId", "The mesh to draw") + .field(INT, "blend", "How vertex colour and texel combine") + .possibleValues("BLEND_COLORS_ONLY", BLEND_COLORS_ONLY) + .possibleValues("BLEND_MODULATE", BLEND_MODULATE) + .field(INT, "imageId", "The bitmap to sample, 0 = untextured"); + } + + @Override + public void serialize(@NonNull MapSerializer serializer) { + serializer + .addType(CLASS_NAME) + .add("meshId", mMeshId) + .add("blend", mBlend) + .add("imageId", mImageId); + } +}
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/DrawTextOnCircle.java b/core/java/com/android/internal/widget/remotecompose/core/operations/DrawTextOnCircle.java index d911be6..251cd6f 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/DrawTextOnCircle.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/DrawTextOnCircle.java
@@ -220,7 +220,15 @@ @Override public void paint(@NonNull PaintContext context) { - throw new UnsupportedOperationException("DrawTextOnCircle is not supported"); + context.drawTextOnCircle( + mTextId, + mCenterX, + mCenterY, + mRadius, + mStartAngle, + mWarpRadiusOffset, + mAlignment.ordinal(), + mPlacement.ordinal()); } @Override
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/DrawToBitmap.java b/core/java/com/android/internal/widget/remotecompose/core/operations/DrawToBitmap.java index d713e511..8bf123c 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/DrawToBitmap.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/DrawToBitmap.java
@@ -38,6 +38,7 @@ private final int mColor; public static final int MODE_NO_INITIALIZE = 1; + public static final int MODE_COMPONENT_ID = 2; public DrawToBitmap(int bitmapId, int mode, int color) { mBitmapId = bitmapId; @@ -122,7 +123,73 @@ @Override public void paint(@NonNull PaintContext context) { - context.drawToBitmap(getId(mBitmapId, context), mMode, mColor); + int id = getId(mBitmapId, context); + int mode = mMode; + int color = mColor; + if (id == 0) { + if (context.hasActiveOffscreenTarget()) { + if (context.popOffscreenTarget()) { + context.restore(); + } + int parentBitmapId = context.getOffscreenBitmapId(); + if (parentBitmapId != 0) { + BitmapData.resumeOffscreenTargetCanvas(context, parentBitmapId); + return; + } + } + context.drawToBitmap(0, mode, color); + return; + } + boolean isComponentOffscreen = (mode & MODE_COMPONENT_ID) != 0; + com.android.internal.widget.remotecompose.core.operations.layout.Component target = + context.getContext().mLastComponent; + if (isComponentOffscreen) { + mode &= ~MODE_COMPONENT_ID; + int compId = color; + if (compId > 0) { + int resolved = context.getContext().getInteger(compId); + if (resolved != 0) { + compId = resolved; + } else { + float fVal = context.getContext().getFloat(compId); + if (!Float.isNaN(fVal) && fVal != 0f) { + compId = (int) fVal; + } + } + } + if (context.getContext().getDocument() != null) { + com.android.internal.widget.remotecompose.core.operations.layout.Component found = + context.getContext().getDocument().getComponent(compId); + if (found != null) { + target = found; + } + } + color = 0; + } + Object obj = context.getContext().getObject(id); + if (obj instanceof BitmapData) { + BitmapData bd = (BitmapData) obj; + if (bd.getEncoding() == BitmapData.ENCODING_COMPONENT_OFFSCREEN_BUFFER) { + boolean hasClip = false; + com.android.internal.widget.remotecompose.core.operations.layout.Component + prevComp = context.getOffscreenComponent(); + context.setOffscreenComponent(target); + bd.ensureOffscreenBitmap(context.getContext()); + context.drawToBitmap(id, mode, color); + if (bd.getWidth() > 0 && bd.getHeight() > 0) { + context.save(); + context.clipRect(0f, 0f, bd.getWidth(), bd.getHeight()); + hasClip = true; + } + context.setOffscreenComponent(prevComp); + context.pushOffscreenTarget(target, id, hasClip); + return; + } + } + if (isComponentOffscreen) { + context.pushOffscreenTarget(target, id, false); + } + context.drawToBitmap(id, mode, color); } @Override
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/EventActionOperation.java b/core/java/com/android/internal/widget/remotecompose/core/operations/EventActionOperation.java new file mode 100644 index 0000000..ad1da32c --- /dev/null +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/EventActionOperation.java
@@ -0,0 +1,267 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.internal.widget.remotecompose.core.operations; + +import android.annotation.NonNull; +import android.annotation.Nullable; + +import com.android.internal.widget.remotecompose.core.CoreDocument; +import com.android.internal.widget.remotecompose.core.Limits; +import com.android.internal.widget.remotecompose.core.Operation; +import com.android.internal.widget.remotecompose.core.Operations; +import com.android.internal.widget.remotecompose.core.RemoteContext; +import com.android.internal.widget.remotecompose.core.WireBuffer; +import com.android.internal.widget.remotecompose.core.events.Event; +import com.android.internal.widget.remotecompose.core.events.EventHandler; +import com.android.internal.widget.remotecompose.core.events.EventManager; +import com.android.internal.widget.remotecompose.core.operations.layout.ActionOperation; +import com.android.internal.widget.remotecompose.core.operations.layout.Component; +import com.android.internal.widget.remotecompose.core.operations.layout.Container; + +import java.util.ArrayList; +import java.util.List; + +/** Handles dispatched events by mapping payloads and running nested actions conditionally. */ +public class EventActionOperation extends Operation + implements EventHandler, Container, ComponentData { + + private static final int OP_CODE = Operations.EVENT_ACTION; + private static final int VERSION = 0; + + /** The serializable class name. */ + public static final String CLASS_NAME = "EventActionOperation"; + + final int mType; + final int mFilter; + final int mFlags; + final @Nullable int[] mDataIds; + final @Nullable float[] mCondition; + @NonNull private final ArrayList<Operation> mOperations = new ArrayList<>(); + + /** + * Constructs a new EventActionOperation. + * + * @param type type identifying compatible events + * @param filter filter metadata required to match onEvent + * @param flags routing specific status flags returned on success + * @param dataIds optional mapping of input payload indices to target float variables + * @param condition optional RPN condition used to conditionally trigger actions + */ + public EventActionOperation( + int type, int filter, int flags, @Nullable int[] dataIds, @Nullable float[] condition) { + mType = type; + mFilter = filter; + mFlags = flags; + mDataIds = dataIds; + mCondition = condition; + } + + @Override + public boolean matchesEvent(int eventType) { + return eventType == mType; + } + + @Override + public int onEvent( + @NonNull RemoteContext context, @NonNull CoreDocument document, @NonNull Event event) { + + if (event.getMetadata() != mFilter) { + return EventManager.STATUS_UNHANDLED; + } + + if (mDataIds != null) { + float[] data = event.getData(); + if (data != null) { + int copyLength = Math.min(data.length, mDataIds.length); + for (int i = 0; i < copyLength; i++) { + // Ignore fields which the user has not set. + if (mDataIds[i] != 0) { + context.overrideFloat(mDataIds[i], data[i]); + } + } + } + } + + // Calculate the condition to determine whether we should run the actions. + boolean condition = true; + if (mCondition != null) { + // Create a temporary FloatExpression instance (id = -1 for inline evaluation) + FloatExpression expression = new FloatExpression(-1, mCondition, null); + // evaluate(context) automatically updates variable listeners & evaluates the RPN stack + float result = expression.evaluate(context); + condition = (result != 0f); // 1.0f represents true, 0.0f false + } + if (condition) { + for (Operation operation : mOperations) { + Component component = context.mLastComponent; + if (operation instanceof ActionOperation && component != null) { + // TODO(b/556845784): Component, X and Y are not used by runAction. + ((ActionOperation) operation).runAction(context, document, component, 0, 0); + } + } + return mFlags; + } + + return EventManager.STATUS_UNHANDLED; + } + + @Override + public void write(@NonNull WireBuffer buffer) { + apply(buffer, mType, mFilter, mFlags, mDataIds, mCondition); + } + + @Override + public void apply(@NonNull RemoteContext context) { + if (context.getMode() == RemoteContext.ContextMode.DATA) { + context.getEventManager().registerHandler(this); + } + } + + @Override + public @NonNull ArrayList<Operation> getList() { + return mOperations; + } + + @Override + public @NonNull String deepToString(@NonNull String indent) { + return indent + this; + } + + /** + * Serializes EventActionOperation attributes to the provided buffer. + * + * @param buffer the target wire buffer + * @param type the event type + * @param filter the filter metadata + * @param flags the routing flags + * @param dataIds optional target payload data mapping IDs + * @param condition optional conditional float expression RPN stream + */ + public static void apply( + @NonNull WireBuffer buffer, + int type, + int filter, + int flags, + @Nullable int[] dataIds, + @Nullable float[] condition) { + buffer.start(OP_CODE); + buffer.writeInt(VERSION); + buffer.writeInt(type); + buffer.writeInt(filter); + + // Common flags. + boolean isConditional = condition != null && condition.length > 0; + boolean hasData = dataIds != null && dataIds.length > 0; + buffer.writeShort(CommonFlagsUtil.pack(isConditional, hasData)); + + // Event specific flags. + buffer.writeShort(flags); + + if (hasData) { + int dataLen = dataIds.length; + if (dataLen > Limits.MAX_FUNCTION_ARGUMENTS) { + throw new RuntimeException("Too many data IDs passed to EventHandler"); + } + buffer.writeInt(dataLen); + for (int data : dataIds) { + buffer.writeInt(data); + } + } + + if (isConditional) { + int len = condition.length; + if (len > Limits.MAX_EXPRESSION_SIZE) { + throw new RuntimeException( + "Condition expression passed to EventHandler is too long"); + } + buffer.writeInt(len); + for (float v : condition) { + buffer.writeFloat(v); + } + } + } + + /** + * Deserializes and inflates EventActionOperation from the provided buffer. + * + * @param buffer the source wire buffer + * @param operations target collection to append the parsed operation + */ + public static void read(@NonNull WireBuffer buffer, @NonNull List<Operation> operations) { + int version = buffer.readInt(); + if (version != 0) { + throw new RuntimeException("Unsupported EventActionOperation version: " + version); + } + int type = buffer.readInt(); + int filter = buffer.readInt(); + int commonFlags = buffer.readShort(); + int flags = buffer.readShort(); + + int[] dataIds = null; + if (CommonFlagsUtil.hasData(commonFlags)) { + int dataLen = buffer.readInt(); + if (dataLen < 0 || dataLen > Limits.MAX_FUNCTION_ARGUMENTS) { + throw new RuntimeException("Too many data IDs: " + dataLen); + } + dataIds = new int[dataLen]; + for (int i = 0; i < dataLen; i++) { + dataIds[i] = buffer.readInt(); + } + } + + float[] condition = null; + if (CommonFlagsUtil.isConditional(commonFlags)) { + int len = buffer.readInt(); + if (len < 0 || len > Limits.MAX_EXPRESSION_SIZE) { + throw new RuntimeException("Float expression too long"); + } + condition = new float[len]; + for (int i = 0; i < condition.length; i++) { + condition[i] = buffer.readNanId(); + } + } + operations.add(new EventActionOperation(type, filter, flags, dataIds, condition)); + } + + /** Utility for packing and unpacking standard 16-bit common communication flags. */ + private static class CommonFlagsUtil { + // Flag definitions within the 16-bit common space: + private static final int FLAG_NONE = 0; + private static final int FLAG_UNCONDITIONAL = 1; // Skip condition evaluation (always true) + private static final int FLAG_NO_DATA = 1 << 1; // Skip event data (no variable write) + + private CommonFlagsUtil() {} + + /** Packs common boolean options into a 16-bit bitmask. */ + public static int pack(boolean isConditional, boolean hasData) { + int flags = FLAG_NONE; + if (!isConditional) flags |= FLAG_UNCONDITIONAL; + if (!hasData) flags |= FLAG_NO_DATA; + return flags; + } + + /** Returns true if the condition should be evaluated. */ + public static boolean isConditional(int commonFlags) { + return (commonFlags & FLAG_UNCONDITIONAL) == 0; + } + + /** Returns true if payload data IDs are present. */ + public static boolean hasData(int commonFlags) { + return (commonFlags & FLAG_NO_DATA) == 0; + } + } +}
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/FloatExpression.java b/core/java/com/android/internal/widget/remotecompose/core/operations/FloatExpression.java index 05b8528..f74471a 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/FloatExpression.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/FloatExpression.java
@@ -142,8 +142,19 @@ } else if (value_changed && mSpring != null) { if (isStartup) { mSpring.setInitialValue(v); + mSpring.setTargetValue(v); + mSpring.get(context.getAnimationTime()); + } else { + if (mSpring.isStopped()) { + // A settled spring stopped requesting frames, so its clock is frozen at the + // last painted one. Sync it to now before retargeting, or the next apply() + // integrates the whole idle gap in a single step; at equilibrium this cannot + // move the spring. A moving spring is already stepped every frame by apply(), + // and stepping it again here would cost it a frame of latency. + mSpring.get(context.getAnimationTime()); + } + mSpring.setTargetValue(v); } - mSpring.setTargetValue(v); } } @@ -205,6 +216,7 @@ mPreCalcValue.length); mSpring.setTargetValue(mLastCalculatedValue); mSpring.setInitialValue(mLastCalculatedValue); + mSpring.get(t); } catch (Exception e) { throw new RuntimeException( this.toString() + " len = " + mPreCalcValue.length, e); @@ -213,10 +225,12 @@ float lastComputedValue = mSpring.get(t); float epsilon = 0.01f; if (lastComputedValue != mLastAnimatedValue + || !mSpring.isStopped() || Math.abs(mSpring.getTargetValue() - lastComputedValue) > epsilon) { mLastAnimatedValue = lastComputedValue; context.loadFloat(mId, lastComputedValue); context.needsRepaint(); + markDirty(); } } else { // no animation float v = 0;
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/FloatFunctionDefine.java b/core/java/com/android/internal/widget/remotecompose/core/operations/FloatFunctionDefine.java index 4e55778..1f902a7 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/FloatFunctionDefine.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/FloatFunctionDefine.java
@@ -43,7 +43,10 @@ private static final String CLASS_NAME = "FunctionDefine"; private final int mId; private final @NonNull int[] mFloatVarId; - private boolean mCurrentlyExecuting = false; + private static final int MAX_EXECUTION_DEPTH = 16; + private static final ThreadLocal<Integer> sGlobalExecutionDepth = + ThreadLocal.withInitial(() -> 0); + private int mExecutionDepth = 0; @NonNull private ArrayList<Operation> mList = new ArrayList<>(); @NonNull AnimatedFloatExpression mExp = new AnimatedFloatExpression(); @@ -115,7 +118,7 @@ public static void read(@NonNull WireBuffer buffer, @NonNull List<Operation> operations) { int id = buffer.readId(); int varLen = buffer.readInt(); - if (varLen > Limits.MAX_FUNCTION_ARGUMENTS) { + if (varLen < 0 || varLen > Limits.MAX_FUNCTION_ARGUMENTS) { throw new IllegalArgumentException("Too many arguments"); } int[] varId = new int[varLen]; @@ -152,6 +155,13 @@ return mFloatVarId; } + /** + * @return the current execution depth of this function + */ + public int getExecutionDepth() { + return mExecutionDepth; + } + @Override public void apply(@NonNull RemoteContext context) {} @@ -161,18 +171,24 @@ * @param context the current RemoteContext */ public void execute(@NonNull RemoteContext context) { - if (mCurrentlyExecuting) { + int globalDepth = sGlobalExecutionDepth.get(); + if (mExecutionDepth >= MAX_EXECUTION_DEPTH || globalDepth >= MAX_EXECUTION_DEPTH) { throw new RuntimeException("Recursion not allowed"); } - mCurrentlyExecuting = true; - for (Operation op : mList) { - if (op instanceof VariableSupport) { - ((VariableSupport) op).updateVariables(context); - } + mExecutionDepth++; + sGlobalExecutionDepth.set(globalDepth + 1); + try { + for (Operation op : mList) { + if (op instanceof VariableSupport) { + ((VariableSupport) op).updateVariables(context); + } - context.incrementOpCount(); - op.apply(context); - mCurrentlyExecuting = false; + context.incrementOpCount(); + op.apply(context); + } + } finally { + mExecutionDepth--; + sGlobalExecutionDepth.set(globalDepth); } } }
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/Header.java b/core/java/com/android/internal/widget/remotecompose/core/operations/Header.java index a5d9a1f..d650d25 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/Header.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/Header.java
@@ -30,16 +30,24 @@ import com.android.internal.widget.remotecompose.core.Operations; import com.android.internal.widget.remotecompose.core.RemoteComposeOperation; import com.android.internal.widget.remotecompose.core.RemoteContext; +import com.android.internal.widget.remotecompose.core.VariableSupport; import com.android.internal.widget.remotecompose.core.WireBuffer; import com.android.internal.widget.remotecompose.core.documentation.DocumentationBuilder; import com.android.internal.widget.remotecompose.core.operations.utilities.IntMap; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; +import java.nio.ByteBuffer; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.zip.DataFormatException; +import java.util.zip.Deflater; +import java.util.zip.Inflater; /** * Describe some basic information for a RemoteCompose document @@ -47,7 +55,7 @@ * <p>It encodes the version of the document (following semantic versioning) as well as the * dimensions of the document in pixels. */ -public class Header extends Operation implements RemoteComposeOperation { +public class Header extends Operation implements RemoteComposeOperation, VariableSupport { private static final int OP_CODE = Operations.HEADER; private static final String CLASS_NAME = "Header"; private static final int MAGIC_NUMBER = 0x048C0000; // to uniquely identify the protocol @@ -153,6 +161,49 @@ /** Specify layout optimization level: 0 = none, 1 = partial, 2 = all */ public static final short FEATURE_OPTIMIZATION_LEVEL = 28; + /** + * Controls the usage of API ViewParent#requestDisallowInterceptTouchEvent when handling gesture + * propagation between RemoteCompose and host views. 0: disabled, 1: enabled. + */ + public static final short FEATURE_DISALLOW_INTERCEPT_TOUCH = 29; + + /** + * Controls whether CanvasOperations within LayoutComponents are evaluated during the DATA pass. + * 0: disabled, 1: enabled. + */ + public static final short FEATURE_DATA_PASS_CANVAS_OPS = 30; + + /** + * Compression of everything that follows the header: {@link #COMPRESSION_NONE} (or absent) for + * none, {@link #COMPRESSION_DEFLATE} for a zlib stream. The header itself is never compressed, + * so a compressed document can still be peeked with {@link #readDirect(InputStream)}. See + * {@link #compressDocument} and {@link #decompressDocument}. + */ + public static final short COMPRESS = 31; + + /** {@link #COMPRESS} value: the operations are stored as is. */ + public static final int COMPRESSION_NONE = 0; + + /** {@link #COMPRESS} value: the operations are a zlib (RFC 1950) DEFLATE stream. */ + public static final int COMPRESSION_DEFLATE = 1; + + /** + * Directions in which the document scrolls: {@link #SCROLL_HORIZONTAL}, {@link + * #SCROLL_VERTICAL}, or both combined. {@link CoreDocument#hasHorizontalScroll()} and {@link + * CoreDocument#hasVerticalScroll()} report these directions on top of the scroll containers + * they find, so a document can declare scrolling they can't find, e.g. a scroll driven by a + * touch expression. It can only add directions: a document with a scroll container reports it + * whatever this property says. Other bits are reserved: writers reject them, players ignore + * them. + */ + public static final short DOC_SCROLL = 32; + + /** {@link #DOC_SCROLL} flag: the document scrolls horizontally. */ + public static final int SCROLL_HORIZONTAL = 1; + + /** {@link #DOC_SCROLL} flag: the document scrolls vertically. */ + public static final int SCROLL_VERTICAL = 2; + /** The object is an integer */ private static final short DATA_TYPE_INT = 0; @@ -185,6 +236,10 @@ FEATURE_CLICK_VERSION, DOC_DENSITY_BEHAVIOR, FEATURE_OPTIMIZATION_LEVEL, + FEATURE_DISALLOW_INTERCEPT_TOUCH, + FEATURE_DATA_PASS_CANVAS_OPS, + COMPRESS, + DOC_SCROLL, }; private static final String[] KEY_NAMES = { "DOC_WIDTH", @@ -205,9 +260,25 @@ "ARRAY_LISTENERS", "CLICK_VERSION", "DENSITY_BEHAVIOR", - "OPTIMIZATION_LEVEL" + "OPTIMIZATION_LEVEL", + "DISALLOW_INTERCEPT_TOUCH", + "DATA_PASS_CANVAS_OPS", + "COMPRESS", + "DOC_SCROLL" }; + /** Offset of the property count in a properties header: opcode, then major, minor, patch. */ + private static final int PROPERTY_COUNT_OFFSET = 1 + 3 * 4; + + /** Offset of the first property in a properties header. */ + private static final int PROPERTIES_OFFSET = PROPERTY_COUNT_OFFSET + 4; + + /** Size of an INT property: tag, value length, value. */ + private static final int INT_PROPERTY_SIZE = 2 + 2 + 4; + + /** Size of the chunks used to deflate and inflate documents. */ + private static final int CHUNK_SIZE = 8 * 1024; + /** * It encodes the version of the document (following semantic versioning) as well as the * dimensions of the document in pixels. @@ -382,6 +453,16 @@ } @Override + public void registerListening(@NonNull RemoteContext context) { + if (context.getDensityBehavior() == CoreDocument.DENSITY_BEHAVIOR_DP) { + context.listensTo(RemoteContext.ID_DENSITY, this); + } + } + + @Override + public void updateVariables(@NonNull RemoteContext context) {} + + @Override public void apply(@NonNull RemoteContext context) { context.header( mMajorVersion, @@ -789,6 +870,154 @@ } /** + * Compresses a document: everything after the header becomes a zlib stream, and a {@link + * #COMPRESS} property is appended to the header. The rest of the header is copied as is, which + * keeps the document's version, and stays uncompressed so {@link #readDirect(InputStream)} can + * still peek at it. Players decompress transparently while inflating the document. + * + * @param document an uncompressed document with a properties (API level 7+) header + * @param size the number of valid bytes in {@code document} + * @return a new array holding the compressed document, or a copy of {@code document} if it is + * already compressed + * @throws IllegalArgumentException if the header is invalid or legacy (without properties) + */ + public static @NonNull byte[] compressDocument(@NonNull byte[] document, int size) { + ByteArrayInputStream stream = new ByteArrayInputStream(document, 0, size); + try { + Header header = readDirect(stream); + int headerSize = size - stream.available(); + if (header.mProperties == null) { + throw new IllegalArgumentException( + "Compression needs a header with properties (API level 7+)"); + } + Object compression = header.get(COMPRESS); + if (compression != null && !Integer.valueOf(COMPRESSION_NONE).equals(compression)) { + return Arrays.copyOf(document, size); + } + byte[] head = new byte[headerSize + INT_PROPERTY_SIZE]; + int headSize = copyHeaderWithoutCompress(document, headerSize, head, 1); + ByteBuffer.wrap(head, headSize, INT_PROPERTY_SIZE) + .putShort((short) (COMPRESS | (DATA_TYPE_INT << 10))) + .putShort((short) 4) + .putInt(COMPRESSION_DEFLATE); + ByteArrayOutputStream out = new ByteArrayOutputStream(size / 2 + INT_PROPERTY_SIZE); + out.write(head, 0, headSize + INT_PROPERTY_SIZE); + Deflater deflater = new Deflater(); + try { + deflater.setInput(document, headerSize, size - headerSize); + deflater.finish(); + byte[] chunk = new byte[CHUNK_SIZE]; + while (!deflater.finished()) { + out.write(chunk, 0, deflater.deflate(chunk)); + } + } finally { + deflater.end(); + } + return out.toByteArray(); + } catch (IOException e) { + throw new IllegalArgumentException("Invalid document header", e); + } + } + + /** + * Decompresses a document made by {@link #compressDocument}: inflates everything after the + * header and drops the {@link #COMPRESS} property, restoring the original document. + * + * @param document a document, compressed or not + * @param size the number of valid bytes in {@code document} + * @return a new array holding the uncompressed document, or a copy of {@code document} if it + * isn't compressed + * @throws IOException if the header is invalid or uses an unsupported compression, or if the + * compressed data is corrupted, truncated, followed by extra bytes, or inflates to more + * than {@link Limits#MAX_DECOMPRESSED_SIZE} bytes + */ + public static @NonNull byte[] decompressDocument(@NonNull byte[] document, int size) + throws IOException { + ByteArrayInputStream stream = new ByteArrayInputStream(document, 0, size); + Header header = readDirect(stream); + int headerSize = size - stream.available(); + Object compression = header.get(COMPRESS); + if (compression == null || Integer.valueOf(COMPRESSION_NONE).equals(compression)) { + return Arrays.copyOf(document, size); + } + if (!Integer.valueOf(COMPRESSION_DEFLATE).equals(compression)) { + throw new IOException("Unsupported document compression " + compression); + } + byte[] head = new byte[headerSize]; + int headSize = copyHeaderWithoutCompress(document, headerSize, head, 0); + ByteArrayOutputStream out = + new ByteArrayOutputStream((int) Math.min(4L * size, Limits.BUFFER_SIZE)); + out.write(head, 0, headSize); + Inflater inflater = new Inflater(); + try { + inflater.setInput(document, headerSize, size - headerSize); + byte[] chunk = new byte[CHUNK_SIZE]; + long inflated = 0; + while (!inflater.finished()) { + int count = inflater.inflate(chunk); + if (count == 0 && !inflater.finished()) { + throw new IOException( + inflater.needsInput() + ? "Truncated compressed document" + : "Invalid compressed document"); + } + inflated += count; + if (inflated > Limits.MAX_DECOMPRESSED_SIZE) { + throw new IOException( + "Decompressed document exceeds " + + Limits.MAX_DECOMPRESSED_SIZE + + " bytes"); + } + out.write(chunk, 0, count); + } + if (inflater.getRemaining() > 0) { + throw new IOException("Unexpected data after the compressed document"); + } + } catch (DataFormatException e) { + throw new IOException("Corrupted compressed document", e); + } finally { + inflater.end(); + } + return out.toByteArray(); + } + + /** + * Copies the properties header that starts {@code document} into {@code out}, without its + * {@link #COMPRESS} properties and with {@code extraProperties} added to the property count, + * and returns the number of bytes written. Properties are walked using their stored length, and + * must end exactly where {@link #readDirect} found the end of the header. + */ + private static int copyHeaderWithoutCompress( + @NonNull byte[] document, int headerSize, @NonNull byte[] out, int extraProperties) + throws IOException { + ByteBuffer in = ByteBuffer.wrap(document, 0, headerSize); + int count = in.getInt(PROPERTY_COUNT_OFFSET); + System.arraycopy(document, 0, out, 0, PROPERTY_COUNT_OFFSET); + int read = PROPERTIES_OFFSET; + int written = PROPERTIES_OFFSET; + int kept = 0; + int i = 0; + while (i < count && read + 4 <= headerSize) { + int end = read + 4 + (in.getShort(read + 2) & 0xFFFF); + if (end > headerSize) { + break; + } + if ((in.getShort(read) & 0x3F) != COMPRESS) { + System.arraycopy(document, read, out, written, end - read); + written += end - read; + kept++; + } + read = end; + i++; + } + if (i != count || read != headerSize) { + throw new IOException("Malformed header properties"); + } + ByteBuffer.wrap(out).putInt(PROPERTY_COUNT_OFFSET, kept + extraProperties); + return written; + } + + /** * Populate the documentation with a description of this operation * * @param doc to append the description to.
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/MatrixFromMesh2D.java b/core/java/com/android/internal/widget/remotecompose/core/operations/MatrixFromMesh2D.java new file mode 100644 index 0000000..31b7c19 --- /dev/null +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/MatrixFromMesh2D.java
@@ -0,0 +1,211 @@ +/* + * Copyright (C) 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.internal.widget.remotecompose.core.operations; + +import static com.android.internal.widget.remotecompose.core.documentation.DocumentedOperation.FLOAT; +import static com.android.internal.widget.remotecompose.core.documentation.DocumentedOperation.INT; + +import android.annotation.NonNull; + +import com.android.internal.widget.remotecompose.core.Operation; +import com.android.internal.widget.remotecompose.core.Operations; +import com.android.internal.widget.remotecompose.core.PaintContext; +import com.android.internal.widget.remotecompose.core.PaintOperation; +import com.android.internal.widget.remotecompose.core.RemoteContext; +import com.android.internal.widget.remotecompose.core.VariableSupport; +import com.android.internal.widget.remotecompose.core.WireBuffer; +import com.android.internal.widget.remotecompose.core.documentation.DocumentationBuilder; +import com.android.internal.widget.remotecompose.core.serialize.MapSerializer; +import com.android.internal.widget.remotecompose.core.serialize.Serializable; + +import java.util.List; + +/** + * Derives a 2D affine from a point on a mesh and multiplies it into the current canvas matrix. + * + * <p>The exact analogue of {@link MatrixFromPath}: a path is one dimensional and yields a transform + * at a fraction along it, a mesh is two dimensional and yields one at {@code (u, v)}. It draws + * nothing - it is a matrix operation that happens to read its numbers from a mesh. + * + * <p>This is what stops meshes being a closed world. Ordinary 2D drawing can be placed <b>onto</b> + * a deformed surface without any of it needing to know that meshes exist: attach a label to a + * waving flag, put icons around a ring, run text along a path strip. The content is drawn with the + * commands that already exist; the mesh only supplies the matrix. + * + * <p>The frame is built from the surface's partial derivatives at the point: + * + * <pre> + * [ du.x dv.x P.x ] + * [ du.y dv.y P.y ] + * </pre> + * + * so the unit square in local space maps onto the surface patch at {@code (u, v)}. + */ +public class MatrixFromMesh2D extends PaintOperation implements VariableSupport, Serializable { + private static final int OP_CODE = Operations.MATRIX_FROM_MESH_2D; + private static final String CLASS_NAME = "MatrixFromMesh2D"; + + /** Keep the origin only: content rides the surface, staying upright and unscaled. */ + public static final int FLAG_ORIGIN = 0; + + /** Keep origin and rotation: content turns with the surface. */ + public static final int FLAG_ROTATION = 1; + + /** Keep origin, rotation and scale: content stretches with the surface. */ + public static final int FLAG_SCALE = 2; + + /** Keep the full 2x3, skew included: the faithful case. */ + public static final int FLAG_FULL = 3; + + private final int mMeshId; + private final float mU; + private final float mV; + private final int mFlags; + private float mOutU; + private float mOutV; + + public MatrixFromMesh2D(int meshId, float u, float v, int flags) { + mMeshId = meshId; + mU = u; + mOutU = u; + mV = v; + mOutV = v; + mFlags = flags; + } + + @Override + public void updateVariables(@NonNull RemoteContext context) { + mOutU = Float.isNaN(mU) ? context.getFloat(Utils.idFromNan(mU)) : mU; + mOutV = Float.isNaN(mV) ? context.getFloat(Utils.idFromNan(mV)) : mV; + } + + @Override + public void registerListening(@NonNull RemoteContext context) { + if (Float.isNaN(mU)) { + context.listensTo(Utils.idFromNan(mU), this); + } + if (Float.isNaN(mV)) { + context.listensTo(Utils.idFromNan(mV), this); + } + } + + @Override + public void write(@NonNull WireBuffer buffer) { + apply(buffer, mMeshId, mU, mV, mFlags); + } + + @Override + public void paint(@NonNull PaintContext context) { + context.matrixFromMesh(mMeshId, mOutU, mOutV, mFlags); + } + + @NonNull + @Override + public String toString() { + return CLASS_NAME + + " [" + + mMeshId + + "] " + + Utils.floatToString(mU, mOutU) + + ", " + + Utils.floatToString(mV, mOutV) + + ", " + + mFlags; + } + + /** + * The name of the class + * + * @return the name + */ + @NonNull + public static String name() { + return CLASS_NAME; + } + + /** + * The OP_CODE for this command + * + * @return the opcode + */ + public static int id() { + return OP_CODE; + } + + /** + * Set the matrix from a point on a mesh. + * + * @param buffer the buffer to add to + * @param meshId the mesh to read the surface from + * @param u the u parameter, 0..1 + * @param v the v parameter, 0..1 + * @param flags which parts of the local frame to apply + */ + public static void apply(@NonNull WireBuffer buffer, int meshId, float u, float v, int flags) { + buffer.start(OP_CODE); + buffer.writeInt(meshId); + buffer.writeFloat(u); + buffer.writeFloat(v); + buffer.writeInt(flags); + } + + /** + * Read this operation and add it to the list of operations + * + * @param buffer the buffer to read + * @param operations the list of operations that will be added to + */ + public static void read(@NonNull WireBuffer buffer, @NonNull List<Operation> operations) { + int meshId = buffer.readId(); + float u = buffer.readNanId(); + float v = buffer.readNanId(); + int flags = buffer.readInt(); + operations.add(new MatrixFromMesh2D(meshId, u, v, flags)); + } + + /** + * Populate the documentation with a description of this operation + * + * @param doc to append the description to. + */ + public static void documentation(@NonNull DocumentationBuilder doc) { + doc.operation("Matrix Operations", OP_CODE, CLASS_NAME) + .addedVersion(7) + .experimental(true) + .description( + "Multiply the local frame of a 2D mesh at (u, v) into the current canvas" + + " matrix, so ordinary drawing can be placed onto a deformed" + + " surface") + .field(INT, "meshId", "The mesh to read the surface from") + .field(FLOAT, "u", "The u parameter [0..1]") + .field(FLOAT, "v", "The v parameter [0..1]") + .field(INT, "flags", "Which parts of the local frame to apply") + .possibleValues("FLAG_ORIGIN", FLAG_ORIGIN) + .possibleValues("FLAG_ROTATION", FLAG_ROTATION) + .possibleValues("FLAG_SCALE", FLAG_SCALE) + .possibleValues("FLAG_FULL", FLAG_FULL); + } + + @Override + public void serialize(@NonNull MapSerializer serializer) { + serializer + .addType(CLASS_NAME) + .add("meshId", mMeshId) + .add("u", mU, mOutU) + .add("v", mV, mOutV) + .add("flags", mFlags); + } +}
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/Component.java b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/Component.java index df682d4..668dca7 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/Component.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/Component.java
@@ -41,7 +41,9 @@ import com.android.internal.widget.remotecompose.core.operations.layout.measure.ComponentMeasurePool; import com.android.internal.widget.remotecompose.core.operations.layout.measure.Measurable; import com.android.internal.widget.remotecompose.core.operations.layout.measure.MeasurePass; +import com.android.internal.widget.remotecompose.core.operations.layout.modifiers.ComponentModifiers; import com.android.internal.widget.remotecompose.core.operations.layout.modifiers.LayoutComputeOperation; +import com.android.internal.widget.remotecompose.core.operations.layout.modifiers.ScrollModifierOperation; import com.android.internal.widget.remotecompose.core.operations.paint.PaintBundle; import com.android.internal.widget.remotecompose.core.operations.utilities.StringSerializer; import com.android.internal.widget.remotecompose.core.serialize.MapSerializer; @@ -114,6 +116,54 @@ return mList; } + /** + * Returns true if this component has horizontal scroll enabled. + * + * @return true if horizontal scroll is enabled + */ + public boolean hasHorizontalScroll() { + for (Operation op : mList) { + if (op instanceof ScrollModifierOperation) { + if (((ScrollModifierOperation) op).isHorizontalScroll()) { + return true; + } + } else if (op instanceof ComponentModifiers) { + if (((ComponentModifiers) op).hasHorizontalScroll()) { + return true; + } + } else if (op instanceof Component) { + if (((Component) op).hasHorizontalScroll()) { + return true; + } + } + } + return false; + } + + /** + * Returns true if this component has vertical scroll enabled. + * + * @return true if vertical scroll is enabled + */ + public boolean hasVerticalScroll() { + for (Operation op : mList) { + if (op instanceof ScrollModifierOperation) { + if (((ScrollModifierOperation) op).isVerticalScroll()) { + return true; + } + } else if (op instanceof ComponentModifiers) { + if (((ComponentModifiers) op).hasVerticalScroll()) { + return true; + } + } else if (op instanceof Component) { + if (((Component) op).hasVerticalScroll()) { + return true; + } + } + } + return false; + } + public float getX() { return mX; } @@ -559,6 +609,34 @@ } /** + * Returns true if this component is currently holding its pre-change layout space while playing + * a BEFORE exit animation. + */ + public boolean isHoldingLayoutForBeforeAnimation(@Nullable RemoteContext context) { + if (mFirstLayout + || context == null + || !context.isAnimationEnabled() + || !mAnimationSpec.isAnimationEnabled()) { + return false; + } + if (mVisibility != mScheduledVisibility + && Visibility.isVisible(mVisibility) + && (Visibility.isGone(mScheduledVisibility) + || Visibility.isInvisible(mScheduledVisibility))) { + return mAnimationSpec.getExitSequence() == AnimationSpec.SEQUENCE.BEFORE; + } + return false; + } + + /** Returns the effective visibility to use during measure passes. */ + public int getMeasureVisibility(@Nullable RemoteContext context) { + if (isHoldingLayoutForBeforeAnimation(context)) { + return mVisibility; + } + return mScheduledVisibility; + } + + /** * Set the visibility of the component * * @param visibility can be VISIBLE, INVISIBLE or GONE @@ -655,11 +733,16 @@ @Override public void layout(@NonNull RemoteContext context, @NonNull MeasurePass measure) { ComponentMeasure m = measure.get(this); + int targetVisibility = + isHoldingLayoutForBeforeAnimation(context) + ? mScheduledVisibility + : m.getVisibility(); if (!mFirstLayout && context.isAnimationEnabled() && mAnimationSpec.isAnimationEnabled() && m.getAllowsAnimation() - && !(this instanceof LayoutComponentContent)) { + && !(this instanceof LayoutComponentContent) + && !(Visibility.isGone(mVisibility) && Visibility.isGone(targetVisibility))) { if (mAnimateMeasure == null) { ComponentMeasurePool pool = context.getComponentMeasurePool(); ComponentMeasure origin = @@ -671,7 +754,7 @@ m.getY(), m.getW(), m.getH(), - m.getVisibility()); + targetVisibility); if (!target.same(origin)) { mAnimateMeasure = new AnimateMeasure( @@ -684,13 +767,20 @@ mAnimationSpec.getEnterAnimation(), mAnimationSpec.getExitAnimation(), mAnimationSpec.getMotionEasingType(), - mAnimationSpec.getVisibilityEasingType()); + mAnimationSpec.getVisibilityEasingType(), + mAnimationSpec.getEnterFunctionId(), + mAnimationSpec.getExitFunctionId(), + mAnimationSpec.getEnterSequence(), + mAnimationSpec.getExitSequence()); } else { pool.recycle(origin); pool.recycle(target); } } else { + int savedVis = m.getVisibility(); + m.setVisibility(targetVisibility); mAnimateMeasure.updateTarget(context, m, context.currentTime); + m.setVisibility(savedVis); } } if (mAnimateMeasure == null) { @@ -718,6 +808,8 @@ mAnimateMeasure.apply(context); updateComponentValues(context, mWidth, mHeight); if (mAnimateMeasure.isDone()) { + boolean triggerLayout = mAnimateMeasure.isBeforeLayout(); + mVisibility = mAnimateMeasure.getTarget().getVisibility(); ComponentMeasurePool pool = context.getComponentMeasurePool(); pool.recycle(mAnimateMeasure.getOriginal()); pool.recycle(mAnimateMeasure.getTarget()); @@ -725,6 +817,12 @@ if (mParent != null) { clearNeedsBoundsAnimation(); } + if (triggerLayout) { + invalidateMeasure(); + if (mParent != null) { + mParent.invalidateMeasure(); + } + } } else { markNeedsBoundsAnimation(); } @@ -1546,6 +1644,8 @@ if (context.isAnimationEnabled() && mAnimateMeasure != null) { mAnimateMeasure.paint(context); if (mAnimateMeasure.isDone()) { + boolean triggerLayout = mAnimateMeasure.isBeforeLayout(); + mVisibility = mAnimateMeasure.getTarget().getVisibility(); ComponentMeasurePool pool = context.getContext().getComponentMeasurePool(); pool.recycle(mAnimateMeasure.getOriginal()); pool.recycle(mAnimateMeasure.getTarget()); @@ -1553,6 +1653,12 @@ if (mParent != null) { clearNeedsBoundsAnimation(); } + if (triggerLayout) { + invalidateMeasure(); + if (mParent != null) { + mParent.invalidateMeasure(); + } + } needsRepaint(); } else { markNeedsBoundsAnimation();
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/LayoutComponent.java b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/LayoutComponent.java index cd4b81e..00551ed 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/LayoutComponent.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/LayoutComponent.java
@@ -101,6 +101,38 @@ return mVerticalScrollDelegate; } + @Override + public boolean hasHorizontalScroll() { + if (mHorizontalScrollDelegate != null || mComponentModifiers.hasHorizontalScroll()) { + return true; + } + if (super.hasHorizontalScroll()) { + return true; + } + for (Component c : mChildrenComponents) { + if (c.hasHorizontalScroll()) { + return true; + } + } + return false; + } + + @Override + public boolean hasVerticalScroll() { + if (mVerticalScrollDelegate != null || mComponentModifiers.hasVerticalScroll()) { + return true; + } + if (super.hasVerticalScroll()) { + return true; + } + for (Component c : mChildrenComponents) { + if (c.hasVerticalScroll()) { + return true; + } + } + return false; + } + public LayoutComponent( @Nullable Component parent, int componentId,
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/RootLayoutComponent.java b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/RootLayoutComponent.java index f141fd2..ed8cf6b7 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/RootLayoutComponent.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/RootLayoutComponent.java
@@ -370,7 +370,9 @@ mAnimationSpec.getEnterAnimation(), mAnimationSpec.getExitAnimation(), mAnimationSpec.getMotionEasingType(), - mAnimationSpec.getVisibilityEasingType()); + mAnimationSpec.getVisibilityEasingType(), + mAnimationSpec.getEnterFunctionId(), + mAnimationSpec.getExitFunctionId()); } else { mLastReportedOriginX = targetOriginX; mLastReportedOriginY = targetOriginY;
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/animation/AnimateMeasure.java b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/animation/AnimateMeasure.java index 33e203d..00e4b8e 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/animation/AnimateMeasure.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/animation/AnimateMeasure.java
@@ -21,6 +21,7 @@ import com.android.internal.widget.remotecompose.core.Operation; import com.android.internal.widget.remotecompose.core.PaintContext; import com.android.internal.widget.remotecompose.core.RemoteContext; +import com.android.internal.widget.remotecompose.core.operations.FloatFunctionDefine; import com.android.internal.widget.remotecompose.core.operations.layout.Component; import com.android.internal.widget.remotecompose.core.operations.layout.DecoratorComponent; import com.android.internal.widget.remotecompose.core.operations.layout.measure.ComponentMeasure; @@ -43,11 +44,16 @@ protected float mDurationVisibilityChange = mDuration; protected @NonNull AnimationSpec.ANIMATION mEnterAnimation = AnimationSpec.ANIMATION.FADE_IN; protected @NonNull AnimationSpec.ANIMATION mExitAnimation = AnimationSpec.ANIMATION.FADE_OUT; + protected @NonNull AnimationSpec.SEQUENCE mEnterSequence = AnimationSpec.SEQUENCE.CONCURRENT; + protected @NonNull AnimationSpec.SEQUENCE mExitSequence = AnimationSpec.SEQUENCE.CONCURRENT; + protected int mEnterFunctionId = -1; + protected int mExitFunctionId = -1; protected int mMotionEasingType = GeneralEasing.CUBIC_STANDARD; protected int mVisibilityEasingType = GeneralEasing.CUBIC_ACCELERATE; protected float mP = 0f; protected float mVp = 0f; + protected long mLastElapsed = 0L; @NonNull protected FloatAnimation mMotionEasing = @@ -70,7 +76,11 @@ @NonNull AnimationSpec.ANIMATION enterAnimation, @NonNull AnimationSpec.ANIMATION exitAnimation, int motionEasingType, - int visibilityEasingType) { + int visibilityEasingType, + int enterFunctionId, + int exitFunctionId, + @NonNull AnimationSpec.SEQUENCE enterSequence, + @NonNull AnimationSpec.SEQUENCE exitSequence) { this.mStartTime = startTime; this.mComponent = component; this.mOriginal = original; @@ -81,6 +91,10 @@ this.mExitAnimation = exitAnimation; this.mMotionEasingType = motionEasingType; this.mVisibilityEasingType = visibilityEasingType; + this.mEnterFunctionId = enterFunctionId; + this.mExitFunctionId = exitFunctionId; + this.mEnterSequence = enterSequence; + this.mExitSequence = exitSequence; float motionDuration = mDuration / 1000f; float visibilityDuration = mDurationVisibilityChange / 1000f; @@ -92,7 +106,175 @@ mMotionEasing.setTargetValue(1f); mVisibilityEasing.setTargetValue(1f); - component.mVisibility = target.getVisibility(); + if (!isBeforeLayout()) { + component.mVisibility = target.getVisibility(); + } + } + + public AnimateMeasure( + long startTime, + @NonNull Component component, + @NonNull ComponentMeasure original, + @NonNull ComponentMeasure target, + float duration, + float durationVisibilityChange, + @NonNull AnimationSpec.ANIMATION enterAnimation, + @NonNull AnimationSpec.ANIMATION exitAnimation, + int motionEasingType, + int visibilityEasingType, + int enterFunctionId, + int exitFunctionId) { + this( + startTime, + component, + original, + target, + duration, + durationVisibilityChange, + enterAnimation, + exitAnimation, + motionEasingType, + visibilityEasingType, + enterFunctionId, + exitFunctionId, + AnimationSpec.SEQUENCE.CONCURRENT, + AnimationSpec.SEQUENCE.CONCURRENT); + } + + public AnimateMeasure( + long startTime, + @NonNull Component component, + @NonNull ComponentMeasure original, + @NonNull ComponentMeasure target, + float duration, + float durationVisibilityChange, + @NonNull AnimationSpec.ANIMATION enterAnimation, + @NonNull AnimationSpec.ANIMATION exitAnimation, + int motionEasingType, + int visibilityEasingType) { + this( + startTime, + component, + original, + target, + duration, + durationVisibilityChange, + enterAnimation, + exitAnimation, + motionEasingType, + visibilityEasingType, + -1, + -1, + AnimationSpec.SEQUENCE.CONCURRENT, + AnimationSpec.SEQUENCE.CONCURRENT); + } + + /** Returns true if this animation transitions the component to GONE or INVISIBLE. */ + public boolean isExitTransition() { + return mOriginal.getVisibility() != mTarget.getVisibility() + && (mTarget.isGone() || mTarget.isInvisible()); + } + + /** + * Returns true if this animation transitions the component from GONE or INVISIBLE to VISIBLE. + */ + public boolean isEnterTransition() { + return mOriginal.getVisibility() != mTarget.getVisibility() + && (mOriginal.isGone() || mOriginal.isInvisible()) + && mTarget.isVisible(); + } + + /** + * Returns true if the visibility transition is configured to run before the layout change + * ({@link AnimationSpec.SEQUENCE#BEFORE}). + */ + public boolean isBeforeLayout() { + if (isExitTransition()) { + return mExitSequence == AnimationSpec.SEQUENCE.BEFORE; + } else if (isEnterTransition()) { + return mEnterSequence == AnimationSpec.SEQUENCE.BEFORE; + } + return false; + } + + /** + * Returns true if the visibility transition is configured to run after the layout change + * ({@link AnimationSpec.SEQUENCE#AFTER}). + */ + public boolean isAfterLayout() { + if (isExitTransition()) { + return mExitSequence == AnimationSpec.SEQUENCE.AFTER; + } else if (isEnterTransition()) { + return mEnterSequence == AnimationSpec.SEQUENCE.AFTER; + } + return false; + } + + private void executeCustomAnimation( + @NonNull PaintContext context, int functionId, float progress) { + if (functionId == -1) { + mComponent.paintingComponent(context); + return; + } + RemoteContext remoteContext = context.getContext(); + Object obj = remoteContext.getObject(functionId); + if (obj instanceof FloatFunctionDefine) { + FloatFunctionDefine fn = (FloatFunctionDefine) obj; + int[] args = fn.getArgs(); + float[] prevArgs = null; + int prevIdInt = 0; + if (fn.getExecutionDepth() > 0) { + prevArgs = new float[args.length]; + for (int i = 0; i < args.length; i++) { + prevArgs[i] = remoteContext.getFloat(args[i]); + } + prevIdInt = args.length >= 6 ? remoteContext.getInteger(args[5]) : 0; + } + + float x = (float) Math.floor(mComponent.getX()); + float y = (float) Math.floor(mComponent.getY()); + float w = (float) Math.ceil((mComponent.getX() - x) + mComponent.getWidth()); + float h = (float) Math.ceil((mComponent.getY() - y) + mComponent.getHeight()); + if (args.length >= 1) remoteContext.loadFloat(args[0], progress); + if (args.length >= 2) remoteContext.loadFloat(args[1], w); + if (args.length >= 3) remoteContext.loadFloat(args[2], h); + if (args.length >= 4) remoteContext.loadFloat(args[3], x); + if (args.length >= 5) remoteContext.loadFloat(args[4], y); + if (args.length >= 6) { + remoteContext.loadInteger(args[5], mComponent.getComponentId()); + remoteContext.loadFloat(args[5], mComponent.getComponentId()); + } + + Component prev = remoteContext.mLastComponent; + remoteContext.mLastComponent = mComponent; + com.android.internal.widget.remotecompose.core.operations.BitmapData.pushOffscreenScope( + remoteContext); + context.save(); + context.savePaint(); + paint.reset(); + paint.setColor(0f, 0f, 0f, 1f); + paint.setStyle(PaintBundle.STYLE_FILL); + context.applyPaint(paint); + try { + fn.execute(remoteContext); + } finally { + context.restorePaint(); + context.restore(); + com.android.internal.widget.remotecompose.core.operations.BitmapData + .popOffscreenScope(remoteContext); + remoteContext.mLastComponent = prev; + if (prevArgs != null) { + for (int i = 0; i < args.length; i++) { + remoteContext.loadFloat(args[i], prevArgs[i]); + } + if (args.length >= 6) { + remoteContext.loadInteger(args[5], prevIdInt); + } + } + } + } else { + mComponent.paintingComponent(context); + } } /** @@ -101,11 +283,20 @@ * @param currentTime the time we use to evaluate the animation */ public void update(long currentTime) { - long elapsed = currentTime - mStartTime; - float motionTimeInSeconds = elapsed / 1000f; - float visibilityTimeInSeconds = elapsed / 1000f; + mLastElapsed = currentTime - mStartTime; + float motionTimeInSeconds = mLastElapsed / 1000f; mP = mMotionEasing.get(motionTimeInSeconds); - mVp = mVisibilityEasing.get(visibilityTimeInSeconds); + if (isAfterLayout()) { + if (mLastElapsed < mDuration) { + mVp = 0f; + } else { + float visibilityTimeInSeconds = (mLastElapsed - mDuration) / 1000f; + mVp = mVisibilityEasing.get(visibilityTimeInSeconds); + } + } else { + float visibilityTimeInSeconds = mLastElapsed / 1000f; + mVp = mVisibilityEasing.get(visibilityTimeInSeconds); + } } @NonNull public PaintBundle paint = new PaintBundle(); @@ -117,6 +308,9 @@ mComponent.setY(getY()); mComponent.setWidth(getWidth()); mComponent.setHeight(getHeight()); + if (isDone()) { + mComponent.mVisibility = mTarget.getVisibility(); + } mComponent.updateVariables(context); float w = mComponent.getWidth(); @@ -137,8 +331,18 @@ public void paint(@NonNull PaintContext context) { apply(context.getContext()); if (mOriginal.getVisibility() != mTarget.getVisibility()) { - if (mTarget.isGone()) { + if (isEnterTransition() && isAfterLayout() && mLastElapsed < mDuration) { + return; + } + if (isExitTransition() && isAfterLayout() && mLastElapsed < mDuration) { + mComponent.paintingComponent(context); + return; + } + if (mTarget.isGone() || mTarget.isInvisible()) { switch (mExitAnimation) { + case CUSTOM: + executeCustomAnimation(context, mExitFunctionId, mVp); + break; case PARTICLE: // particleAnimation(context, component, original, target, vp) if (mParticleAnimation == null) { @@ -223,8 +427,11 @@ mParticleAnimation.animate(context, mComponent, mOriginal, mTarget, mVp); break; } - } else if (mOriginal.isGone() && mTarget.isVisible()) { + } else if ((mOriginal.isGone() || mOriginal.isInvisible()) && mTarget.isVisible()) { switch (mEnterAnimation) { + case CUSTOM: + executeCustomAnimation(context, mEnterFunctionId, mVp); + break; case ROTATE: float px = mTarget.getX() + mTarget.getW() / 2f; float py = mTarget.getY() + mTarget.getH() / 2f; @@ -320,7 +527,7 @@ mComponent.paintingComponent(context); } - if (mP >= 1f && mVp >= 1f) { + if (isDone()) { mComponent.mVisibility = mTarget.getVisibility(); mComponent.setX(mTarget.getX()); mComponent.setY(mTarget.getY()); @@ -330,22 +537,52 @@ } public boolean isDone() { + if (isBeforeLayout()) { + return mVp >= 1f; + } + if (isAfterLayout()) { + return mP >= 1f && mVp >= 1f && mLastElapsed >= mDuration; + } return mP >= 1f && mVp >= 1f; } public float getX() { + if (mOriginal.isGone()) { + return mTarget.getX(); + } + if (mTarget.isGone()) { + return mOriginal.getX(); + } return mOriginal.getX() * (1 - mP) + mTarget.getX() * mP; } public float getY() { + if (mOriginal.isGone()) { + return mTarget.getY(); + } + if (mTarget.isGone()) { + return mOriginal.getY(); + } return mOriginal.getY() * (1 - mP) + mTarget.getY() * mP; } public float getWidth() { + if (mOriginal.isGone()) { + return mTarget.getW(); + } + if (mTarget.isGone()) { + return mOriginal.getW(); + } return mOriginal.getW() * (1 - mP) + mTarget.getW() * mP; } public float getHeight() { + if (mOriginal.isGone()) { + return mTarget.getH(); + } + if (mTarget.isGone()) { + return mOriginal.getH(); + } return mOriginal.getH() * (1 - mP) + mTarget.getH() * mP; } @@ -393,11 +630,18 @@ || mTarget.getW() != targetW || mTarget.getH() != targetH || mTarget.getVisibility() != targetVisibility) { + if (mTarget.getVisibility() != targetVisibility) { + mOriginal.setVisibility(mTarget.getVisibility()); + mStartTime = currentTime; + } mTarget.setX(targetX); mTarget.setY(targetY); mTarget.setW(targetW); mTarget.setH(targetH); mTarget.setVisibility(targetVisibility); + if (!isBeforeLayout()) { + mComponent.mVisibility = targetVisibility; + } // We shouldn't reset the leftover animation time here // 1/ if we are eg fading out a component, and an updateTarget comes on, we don't want // to restart the full animation time
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/animation/AnimationSpec.java b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/animation/AnimationSpec.java index 01eaa994..287b2e6 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/animation/AnimationSpec.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/animation/AnimationSpec.java
@@ -44,6 +44,10 @@ int mVisibilityEasingType = GeneralEasing.CUBIC_STANDARD; @NonNull ANIMATION mEnterAnimation = ANIMATION.FADE_IN; @NonNull ANIMATION mExitAnimation = ANIMATION.FADE_OUT; + int mEnterFunctionId = -1; + int mExitFunctionId = -1; + @NonNull SEQUENCE mEnterSequence = SEQUENCE.CONCURRENT; + @NonNull SEQUENCE mExitSequence = SEQUENCE.CONCURRENT; private static final int OP_CODE = Operations.ANIMATION_SPEC; private static final String CLASS_NAME = "AnimationSpec"; @@ -55,7 +59,11 @@ float visibilityDuration, int visibilityEasingType, @NonNull ANIMATION enterAnimation, - @NonNull ANIMATION exitAnimation) { + @NonNull ANIMATION exitAnimation, + int enterFunctionId, + int exitFunctionId, + @NonNull SEQUENCE enterSequence, + @NonNull SEQUENCE exitSequence) { this.mAnimationId = animationId; this.mMotionDuration = motionDuration; this.mMotionEasingType = motionEasingType; @@ -63,6 +71,56 @@ this.mVisibilityEasingType = visibilityEasingType; this.mEnterAnimation = enterAnimation; this.mExitAnimation = exitAnimation; + this.mEnterFunctionId = enterFunctionId; + this.mExitFunctionId = exitFunctionId; + this.mEnterSequence = enterSequence; + this.mExitSequence = exitSequence; + } + + public AnimationSpec( + int animationId, + float motionDuration, + int motionEasingType, + float visibilityDuration, + int visibilityEasingType, + @NonNull ANIMATION enterAnimation, + @NonNull ANIMATION exitAnimation, + int enterFunctionId, + int exitFunctionId) { + this( + animationId, + motionDuration, + motionEasingType, + visibilityDuration, + visibilityEasingType, + enterAnimation, + exitAnimation, + enterFunctionId, + exitFunctionId, + SEQUENCE.CONCURRENT, + SEQUENCE.CONCURRENT); + } + + public AnimationSpec( + int animationId, + float motionDuration, + int motionEasingType, + float visibilityDuration, + int visibilityEasingType, + @NonNull ANIMATION enterAnimation, + @NonNull ANIMATION exitAnimation) { + this( + animationId, + motionDuration, + motionEasingType, + visibilityDuration, + visibilityEasingType, + enterAnimation, + exitAnimation, + -1, + -1, + SEQUENCE.CONCURRENT, + SEQUENCE.CONCURRENT); } public AnimationSpec() { @@ -115,6 +173,24 @@ return mExitAnimation; } + public int getEnterFunctionId() { + return mEnterFunctionId; + } + + public int getExitFunctionId() { + return mExitFunctionId; + } + + @NonNull + public SEQUENCE getEnterSequence() { + return mEnterSequence; + } + + @NonNull + public SEQUENCE getExitSequence() { + return mExitSequence; + } + @NonNull @Override public String toString() { @@ -137,6 +213,14 @@ + getEnterAnimation() + ", " + getExitAnimation() + + (mEnterFunctionId != -1 ? ", enterFunction=" + mEnterFunctionId : "") + + (mExitFunctionId != -1 ? ", exitFunction=" + mExitFunctionId : "") + + (mEnterSequence != SEQUENCE.CONCURRENT + ? ", enterSequence=" + mEnterSequence + : "") + + (mExitSequence != SEQUENCE.CONCURRENT + ? ", exitSequence=" + mExitSequence + : "") + "]"); } @@ -151,6 +235,18 @@ .add("visibilityEasingType", Easing.getString(getVisibilityEasingType())) .add("enterAnimation", getEnterAnimation()) .add("exitAnimation", getExitAnimation()); + if (mEnterFunctionId != -1) { + serializer.add("enterFunctionId", mEnterFunctionId); + } + if (mExitFunctionId != -1) { + serializer.add("exitFunctionId", mExitFunctionId); + } + if (mEnterSequence != SEQUENCE.CONCURRENT) { + serializer.add("enterSequence", mEnterSequence); + } + if (mExitSequence != SEQUENCE.CONCURRENT) { + serializer.add("exitSequence", mExitSequence); + } } public enum ANIMATION { @@ -161,7 +257,14 @@ SLIDE_TOP, SLIDE_BOTTOM, ROTATE, - PARTICLE + PARTICLE, + CUSTOM + } + + public enum SEQUENCE { + CONCURRENT, + BEFORE, + AFTER } @Override @@ -173,8 +276,10 @@ mMotionEasingType, mVisibilityDuration, mVisibilityEasingType, - mEnterAnimation.ordinal(), - mExitAnimation.ordinal()); + packAnimation(mEnterAnimation, mEnterSequence), + packAnimation(mExitAnimation, mExitSequence), + mEnterFunctionId, + mExitFunctionId); } @Override @@ -218,6 +323,36 @@ } /** + * Packs an ANIMATION and SEQUENCE into a single wire int. + * + * @param animation the animation type + * @param sequence the sequence relative to layout changes + * @return the packed integer + */ + public static int packAnimation(@NonNull ANIMATION animation, @NonNull SEQUENCE sequence) { + return (animation.ordinal() & 0xFF) | ((sequence.ordinal() & 0xFF) << 8); + } + + /** + * Maps int value to the corresponding SEQUENCE enum values + * + * @param value int value mapped to the enum + * @return the corresponding SEQUENCE enum value + */ + @NonNull + public static SEQUENCE intToSequence(int value) { + switch (value & 0xFF) { + case 1: + return SEQUENCE.BEFORE; + case 2: + return SEQUENCE.AFTER; + case 0: + default: + return SEQUENCE.CONCURRENT; + } + } + + /** * Maps int value to the corresponding ANIMATION enum values * * @param value int value mapped to the enum @@ -225,7 +360,7 @@ */ @NonNull public static ANIMATION intToAnimation(int value) { - switch (value) { + switch (value & 0xFF) { case 0: return ANIMATION.FADE_IN; case 1: @@ -242,6 +377,8 @@ return ANIMATION.ROTATE; case 7: return ANIMATION.PARTICLE; + case 8: + return ANIMATION.CUSTOM; default: return ANIMATION.FADE_IN; } @@ -268,6 +405,44 @@ int visibilityEasingType, int enterAnimation, int exitAnimation) { + apply( + buffer, + animationId, + motionDuration, + motionEasingType, + visibilityDuration, + visibilityEasingType, + enterAnimation, + exitAnimation, + -1, + -1); + } + + /** + * Write the operation to the buffer + * + * @param buffer a WireBuffer + * @param animationId the animation id + * @param motionDuration the duration of the motion animation + * @param motionEasingType the type of easing for the motion animation + * @param visibilityDuration the duration of the visibility animation + * @param visibilityEasingType the type of easing for the visibility animation + * @param enterAnimation the type of animation when "entering" (newly visible) + * @param exitAnimation the type of animation when "exiting" (newly gone) + * @param enterFunctionId the function id for custom enter animation + * @param exitFunctionId the function id for custom exit animation + */ + public static void apply( + @NonNull WireBuffer buffer, + int animationId, + float motionDuration, + int motionEasingType, + float visibilityDuration, + int visibilityEasingType, + int enterAnimation, + int exitAnimation, + int enterFunctionId, + int exitFunctionId) { buffer.start(Operations.ANIMATION_SPEC); buffer.writeInt(animationId); buffer.writeFloat(motionDuration); @@ -276,6 +451,13 @@ buffer.writeInt(visibilityEasingType); buffer.writeInt(enterAnimation); buffer.writeInt(exitAnimation); + if ((enterAnimation & 0xFF) == ANIMATION.CUSTOM.ordinal() + || (exitAnimation & 0xFF) == ANIMATION.CUSTOM.ordinal() + || enterFunctionId != -1 + || exitFunctionId != -1) { + buffer.writeInt(enterFunctionId); + buffer.writeInt(exitFunctionId); + } } /** @@ -290,8 +472,18 @@ int motionEasingType = buffer.readInt(); float visibilityDuration = buffer.readFloat(); int visibilityEasingType = buffer.readInt(); - ANIMATION enterAnimation = intToAnimation(buffer.readInt()); - ANIMATION exitAnimation = intToAnimation(buffer.readInt()); + int rawEnter = buffer.readInt(); + int rawExit = buffer.readInt(); + ANIMATION enterAnimation = intToAnimation(rawEnter); + ANIMATION exitAnimation = intToAnimation(rawExit); + SEQUENCE enterSequence = intToSequence(rawEnter >> 8); + SEQUENCE exitSequence = intToSequence(rawExit >> 8); + int enterFunctionId = -1; + int exitFunctionId = -1; + if (enterAnimation == ANIMATION.CUSTOM || exitAnimation == ANIMATION.CUSTOM) { + enterFunctionId = buffer.readId(); + exitFunctionId = buffer.readId(); + } AnimationSpec op = new AnimationSpec( animationId, @@ -300,7 +492,11 @@ visibilityDuration, visibilityEasingType, enterAnimation, - exitAnimation); + exitAnimation, + enterFunctionId, + exitFunctionId, + enterSequence, + exitSequence); operations.add(op); }
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/animation/RootAnimateMeasure.java b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/animation/RootAnimateMeasure.java index 091d819..2069db5 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/animation/RootAnimateMeasure.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/animation/RootAnimateMeasure.java
@@ -45,7 +45,9 @@ @NonNull AnimationSpec.ANIMATION enterAnimation, @NonNull AnimationSpec.ANIMATION exitAnimation, int motionEasingType, - int visibilityEasingType) { + int visibilityEasingType, + int enterFunctionId, + int exitFunctionId) { super( startTime, component, @@ -56,13 +58,49 @@ enterAnimation, exitAnimation, motionEasingType, - visibilityEasingType); + visibilityEasingType, + enterFunctionId, + exitFunctionId); this.mOriginalOriginX = originalOriginX; this.mOriginalOriginY = originalOriginY; this.mTargetOriginX = targetOriginX; this.mTargetOriginY = targetOriginY; } + public RootAnimateMeasure( + long startTime, + @NonNull Component component, + @NonNull ComponentMeasure original, + @NonNull ComponentMeasure target, + float originalOriginX, + float originalOriginY, + float targetOriginX, + float targetOriginY, + float duration, + float durationVisibilityChange, + @NonNull AnimationSpec.ANIMATION enterAnimation, + @NonNull AnimationSpec.ANIMATION exitAnimation, + int motionEasingType, + int visibilityEasingType) { + this( + startTime, + component, + original, + target, + originalOriginX, + originalOriginY, + targetOriginX, + targetOriginY, + duration, + durationVisibilityChange, + enterAnimation, + exitAnimation, + motionEasingType, + visibilityEasingType, + -1, + -1); + } + @Override public void apply(@NonNull RemoteContext context) { super.apply(context);
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/CollapsibleColumnLayout.java b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/CollapsibleColumnLayout.java index cb3cf8a..3ec2673 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/CollapsibleColumnLayout.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/CollapsibleColumnLayout.java
@@ -162,6 +162,9 @@ @Override public float minIntrinsicHeight(@NonNull RemoteContext context) { float height = computeModifierDefinedHeight(context, true); + if (mHeightModifier != null && mHeightModifier.isExact()) { + return height; + } if (!mChildrenComponents.isEmpty()) { Component c; if (context.useFeature(Header.FEATURE_PRIORITY_FIX)) { @@ -181,6 +184,9 @@ @Override public float minIntrinsicWidth(@NonNull RemoteContext context) { float width = computeModifierDefinedWidth(context, true); + if (mWidthModifier != null && mWidthModifier.isExact()) { + return width; + } if (!mChildrenComponents.isEmpty()) { Component c; if (context.useFeature(Header.FEATURE_PRIORITY_FIX)) {
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/CollapsibleRowLayout.java b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/CollapsibleRowLayout.java index d2d2e54..18a6839 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/CollapsibleRowLayout.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/CollapsibleRowLayout.java
@@ -162,6 +162,9 @@ @Override public float minIntrinsicHeight(@NonNull RemoteContext context) { float height = computeModifierDefinedHeight(context, true); + if (mHeightModifier != null && mHeightModifier.isExact()) { + return height; + } if (!mChildrenComponents.isEmpty()) { Component c; if (context.useFeature(Header.FEATURE_PRIORITY_FIX)) { @@ -181,6 +184,9 @@ @Override public float minIntrinsicWidth(@NonNull RemoteContext context) { float width = computeModifierDefinedWidth(context, true); + if (mWidthModifier != null && mWidthModifier.isExact()) { + return width; + } if (!mChildrenComponents.isEmpty()) { Component c; if (context.useFeature(Header.FEATURE_PRIORITY_FIX)) {
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/CoreText.java b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/CoreText.java index 3c163f4..5174814 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/CoreText.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/CoreText.java
@@ -26,6 +26,7 @@ import android.annotation.NonNull; import android.annotation.Nullable; +import com.android.internal.widget.remotecompose.core.CoreDocument; import com.android.internal.widget.remotecompose.core.Operation; import com.android.internal.widget.remotecompose.core.Operations; import com.android.internal.widget.remotecompose.core.PaintContext; @@ -240,6 +241,8 @@ } if (Float.isNaN(mFontSize)) { context.listensTo(Utils.idFromNan(mFontSize), this); + } else if (context.getDensityBehavior() == CoreDocument.DENSITY_BEHAVIOR_DP) { + context.listensTo(RemoteContext.ID_DENSITY, this); } if (Float.isNaN(mFontWeight)) { context.listensTo(Utils.idFromNan(mFontWeight), this); @@ -261,8 +264,16 @@ applyStyle((TextStyle) styleObj); } } + float prevFontSize = mFontSizeValue; mFontSizeValue = Float.isNaN(mFontSize) ? context.getFloat(Utils.idFromNan(mFontSize)) : mFontSize; + if (context.getDensityBehavior() == CoreDocument.DENSITY_BEHAVIOR_DP + && !Float.isNaN(mFontSize)) { + mFontSizeValue *= context.getDensity(); + } + if (prevFontSize != mFontSizeValue && mComputedTextLayout != null) { + invalidateMeasure(); + } mFontWeightValue = Float.isNaN(mFontWeight) ? context.getFloat(Utils.idFromNan(mFontWeight))
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/LayoutManager.java b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/LayoutManager.java index 5d41507..a353a15 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/LayoutManager.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/LayoutManager.java
@@ -244,6 +244,7 @@ } /** Returns whether the component has horizontal scrolling enabled. */ + @Override public boolean hasHorizontalScroll() { return mComponentModifiers.hasHorizontalScroll(); } @@ -259,6 +260,7 @@ } /** Returns whether the component has vertical scrolling enabled. */ + @Override public boolean hasVerticalScroll() { return mComponentModifiers.hasVerticalScroll(); }
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/TextLayout.java b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/TextLayout.java index 2bcc327..2a16f66 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/TextLayout.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/TextLayout.java
@@ -21,6 +21,7 @@ import android.annotation.NonNull; import android.annotation.Nullable; +import com.android.internal.widget.remotecompose.core.CoreDocument; import com.android.internal.widget.remotecompose.core.Operation; import com.android.internal.widget.remotecompose.core.Operations; import com.android.internal.widget.remotecompose.core.PaintContext; @@ -114,10 +115,15 @@ if (isAtLeastVersion7(context)) { if (Float.isNaN(mFontSize)) { context.listensTo(Utils.idFromNan(mFontSize), this); + } else if (context.getDensityBehavior() == CoreDocument.DENSITY_BEHAVIOR_DP) { + context.listensTo(RemoteContext.ID_DENSITY, this); } if (mIsDynamicColorEnabled) { context.listensTo(mColor, this); } + } else if (context.getDensityBehavior() == CoreDocument.DENSITY_BEHAVIOR_DP + && !Float.isNaN(mFontSize)) { + context.listensTo(RemoteContext.ID_DENSITY, this); } } @@ -136,11 +142,16 @@ @Override public void updateVariables(@NonNull RemoteContext context) { + float prevFontSize = mFontSizeValue; if (isAtLeastVersion7(context)) { mFontSizeValue = Float.isNaN(mFontSize) ? context.getFloat(Utils.idFromNan(mFontSize)) : mFontSize; + if (context.getDensityBehavior() == CoreDocument.DENSITY_BEHAVIOR_DP + && !Float.isNaN(mFontSize)) { + mFontSizeValue *= context.getDensity(); + } mTextAlignValue = (short) (mTextAlign & 0xFFFF); if (mIsDynamicColorEnabled) { @@ -156,9 +167,16 @@ } } else { mFontSizeValue = mFontSize; + if (context.getDensityBehavior() == CoreDocument.DENSITY_BEHAVIOR_DP + && !Float.isNaN(mFontSize)) { + mFontSizeValue *= context.getDensity(); + } mColorValue = mColor; mTextAlignValue = mTextAlign; } + if (prevFontSize != mFontSizeValue && mComputedTextLayout != null) { + invalidateMeasure(); + } String cachedString = context.getText(mTextId); if (cachedString != null && cachedString.equalsIgnoreCase(mCachedString)) { return;
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/policies/BaseModernMeasurePolicy.java b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/policies/BaseModernMeasurePolicy.java index c3ecae1..7b27af1 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/policies/BaseModernMeasurePolicy.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/policies/BaseModernMeasurePolicy.java
@@ -382,7 +382,7 @@ ComponentMeasure m = measure.get(layout); m.setW(measuredWidth); m.setH(measuredHeight); - m.setVisibility(layout.getScheduledVisibility()); + m.setVisibility(layout.getMeasureVisibility(context.getContext())); layout.internalLayoutMeasure(context, measure); }
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/policies/LegacyMeasurePolicy.java b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/policies/LegacyMeasurePolicy.java index 0b41455f..869b201 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/policies/LegacyMeasurePolicy.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/managers/policies/LegacyMeasurePolicy.java
@@ -189,7 +189,7 @@ ComponentMeasure m = measure.get(layout); m.setW(measuredWidth); m.setH(measuredHeight); - m.setVisibility(layout.getScheduledVisibility()); + m.setVisibility(layout.getMeasureVisibility(context.getContext())); layout.internalLayoutMeasure(context, measure); }
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/modifiers/DimensionModifierOperation.java b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/modifiers/DimensionModifierOperation.java index 4716231..a056960 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/layout/modifiers/DimensionModifierOperation.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/layout/modifiers/DimensionModifierOperation.java
@@ -17,6 +17,7 @@ import android.annotation.NonNull; +import com.android.internal.widget.remotecompose.core.CoreDocument; import com.android.internal.widget.remotecompose.core.Operation; import com.android.internal.widget.remotecompose.core.RemoteContext; import com.android.internal.widget.remotecompose.core.VariableSupport; @@ -84,13 +85,24 @@ @Override public void updateVariables(@NonNull RemoteContext context) { if (mType == Type.EXACT) { + float pre = mOutValue; mOutValue = Float.isNaN(mValue) ? context.getFloat(Utils.idFromNan(mValue)) : mValue; + if (context.getDensityBehavior() == CoreDocument.DENSITY_BEHAVIOR_DP) { + mOutValue *= context.getDensity(); + } + if (pre != mOutValue + && context.getDocument() != null + && context.getDocument().getRootLayoutComponent() != null) { + context.getDocument().getRootLayoutComponent().invalidateMeasure(); + } } if (mType == Type.EXACT_DP) { float pre = mOutValue; mOutValue = Float.isNaN(mValue) ? context.getFloat(Utils.idFromNan(mValue)) : mValue; mOutValue *= context.getDensity(); - if (pre != mOutValue) { + if (pre != mOutValue + && context.getDocument() != null + && context.getDocument().getRootLayoutComponent() != null) { context.getDocument().getRootLayoutComponent().invalidateMeasure(); } } @@ -102,11 +114,15 @@ if (Float.isNaN(mValue)) { context.listensTo(Utils.idFromNan(mValue), this); } + if (context.getDensityBehavior() == CoreDocument.DENSITY_BEHAVIOR_DP) { + context.listensTo(RemoteContext.ID_DENSITY, this); + } } if (mType == Type.EXACT_DP) { if (Float.isNaN(mValue)) { context.listensTo(Utils.idFromNan(mValue), this); } + context.listensTo(RemoteContext.ID_DENSITY, this); } }
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/paint/PaintBundle.java b/core/java/com/android/internal/widget/remotecompose/core/operations/paint/PaintBundle.java index c7d27f0..0019e1a 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/paint/PaintBundle.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/paint/PaintBundle.java
@@ -152,6 +152,12 @@ } else if (type == RADIAL_GRADIENT) { array[ret] = resolveFloatId(array[ret], buffer); ret++; + } else if (type == RADIAL_GRADIENT2) { + // startRadius, endX, endY, endRadius (startX/startY consumed above) + for (int j = 0; j < 4; j++) { + array[ret] = resolveFloatId(array[ret], buffer); + ret++; + } } ret++; // tileMode return ret; @@ -270,6 +276,9 @@ p.setPathEffect(pathEffect); break; + case ANTI_ALIAS: + // TODO enable this and fix add p.setAntiAlias((cmd >> 16) != 0); + break; default: System.err.println("error unknown Paint Type " + (cmd & 0xFFFF)); break; @@ -543,6 +552,36 @@ tileMode = array[ret++]; // tile Mode break; + case RADIAL_GRADIENT2: + if (len > 0) { + + for (int j = 0; j < len; j++) { + int color = array[ret++]; + if ((register & (1 << j)) != 0) { + context.listensTo(color, support); + } + } + } + len = array[ret++]; // stops + for (int j = 0; j < len; j++) { + registerFloat(array[ret++], context, support); + } + + // start x + registerFloat(array[ret++], context, support); + // start y + registerFloat(array[ret++], context, support); + // start radius + registerFloat(array[ret++], context, support); + // start center x + registerFloat(array[ret++], context, support); + // start center y + registerFloat(array[ret++], context, support); + // start radius + registerFloat(array[ret++], context, support); + + tileMode = array[ret++]; // tile Mode + break; /* see {@link #setSweepGradient} */ case SWEEP_GRADIENT: if (len > 0) { @@ -708,6 +747,18 @@ tileMode = array[ret++]; p.setRadialGradient(colors, stops, centerX, centerY, radius, tileMode); break; + case RADIAL_GRADIENT2: + startX = Float.intBitsToFloat(array[ret++]); + startY = Float.intBitsToFloat(array[ret++]); + float startR = Float.intBitsToFloat(array[ret++]); + endX = Float.intBitsToFloat(array[ret++]); + endY = Float.intBitsToFloat(array[ret++]); + float endR = Float.intBitsToFloat(array[ret++]); + + tileMode = array[ret++]; + p.setRadialGradient( + colors, stops, startX, startY, startR, endX, endY, endR, tileMode); + break; case SWEEP_GRADIENT: centerX = Float.intBitsToFloat(array[ret++]); centerY = Float.intBitsToFloat(array[ret++]); @@ -826,6 +877,7 @@ public static final int LINEAR_GRADIENT = 0; public static final int RADIAL_GRADIENT = 1; public static final int SWEEP_GRADIENT = 2; + public static final int RADIAL_GRADIENT2 = 3; private int mLastShaderSet = -1; private boolean mColorFilterSet = false; @@ -947,6 +999,60 @@ } /** + * Sets a shader that draws a radial gradient given the center and radius. + * + * @param colors The sRGB colors distributed between the center and edge + * @param idMask The id mask for the shader + * @param stops May be <code>null</code>. Valid values are between <code>0.0f</code> and <code> + * 1.0f</code>. The relative position of each corresponding color in the + * colors array. If <code>null</code>, colors are distributed evenly between the center and + * edge of the circle. + * @param startX The x-coordinate of the center of the starting circle of the radial gradient, + * often referred to as the focal point. + * @param startY The y-coordinate of the center of the starting circle of the radial gradient, + * often referred to as the focal point. + * @param startRadius The radius of the starting circle of the radial gradient, often referred + * to as the focal radius. Must be greater than or equal to zero. Value is 0.0f or greater + * @param endX The x-coordinate of the center of the radius for the end circle of the radial + * gradient + * @param endY The y-coordinate of the center of the radius for the end circle of the radial + * gradient + * @param endRadius The radius of the ending circle for this gradient. This must be strictly + * greater than zero. A radius value equal to zero is not allowed. Value is 0.0f or greater + * @param tileMode The Shader tiling mode + */ + public void setRadialGradient( + @NonNull int[] colors, + int idMask, + @Nullable float[] stops, + float startX, + float startY, + float startRadius, + float endX, + float endY, + float endRadius, + int tileMode) { + int len; + mArray[mPos++] = GRADIENT | (RADIAL_GRADIENT2 << 16); + mArray[mPos++] = (idMask << 16) | (len = colors.length); + for (int i = 0; i < len; i++) { + mArray[mPos++] = colors[i]; + } + mArray[mPos++] = len = (stops == null) ? 0 : stops.length; + + for (int i = 0; i < len; i++) { + mArray[mPos++] = Float.floatToRawIntBits(stops[i]); + } + mArray[mPos++] = Float.floatToRawIntBits(startX); + mArray[mPos++] = Float.floatToRawIntBits(startY); + mArray[mPos++] = Float.floatToRawIntBits(startRadius); + mArray[mPos++] = Float.floatToRawIntBits(endX); + mArray[mPos++] = Float.floatToRawIntBits(endY); + mArray[mPos++] = Float.floatToRawIntBits(endRadius); + mArray[mPos++] = tileMode; + } + + /** * Create a color filter that uses the specified color and Porter-Duff mode. * * @param color The ARGB source color used with the Porter-Duff mode @@ -1568,6 +1674,44 @@ ret++; ret++; // tileMode break; + case RADIAL_GRADIENT2: + // RadialGradient2 + if (len > 0) { + + for (int j = 0; j < len; j++) { + int color = array[ret]; + if ((register & (1 << j)) != 0) { + out[ret] = fixColor(color, context); + } + ret++; + } + } + len = array[ret++]; + if (len > 0) { + for (int j = 0; j < len; j++) { + out[ret] = fixFloatVar(array[ret], context); + ret++; + } + } + + // start + out[ret] = fixFloatVar(array[ret], context); + ret++; + out[ret] = fixFloatVar(array[ret], context); + ret++; + // start radius + out[ret] = fixFloatVar(array[ret], context); + ret++; + // end + out[ret] = fixFloatVar(array[ret], context); + ret++; + out[ret] = fixFloatVar(array[ret], context); + ret++; + // end radius + out[ret] = fixFloatVar(array[ret], context); + ret++; + ret++; // tileMode + break; case SWEEP_GRADIENT: // SweepGradient if (len > 0) { @@ -1783,6 +1927,37 @@ "tileMode", tileMode)); break; + case RADIAL_GRADIENT2: + startX = array[ret++]; + startY = array[ret++]; + int startR = array[ret++]; + endX = array[ret++]; + endY = array[ret++]; + int endR = array[ret++]; + tileMode = array[ret++]; + list.add( + orderedOf( + "type", + "RadialGradientFocal", + "colors", + colors, + "stops", + stops == null ? List.of() : stops, + "startX", + getVariable(startX), + "startY", + getVariable(startY), + "startR", + getVariable(startR), + "endX", + getVariable(endX), + "endY", + getVariable(endY), + "endR", + getVariable(endR), + "tileMode", + tileMode)); + break; case SWEEP_GRADIENT: centerX = array[ret++]; centerY = array[ret++];
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/paint/PaintChangeAdapter.java b/core/java/com/android/internal/widget/remotecompose/core/operations/paint/PaintChangeAdapter.java index e6f036d..888e9c8 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/paint/PaintChangeAdapter.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/paint/PaintChangeAdapter.java
@@ -104,6 +104,18 @@ int tileMode) {} @Override + public void setRadialGradient( + @NonNull int[] colors, + @Nullable float[] stops, + float startX, + float startY, + float startRadius, + float endX, + float endY, + float endRadius, + int tileMode) {} + + @Override public void setSweepGradient( @NonNull int[] colorsArray, @Nullable float[] stopsArray,
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/paint/PaintChanges.java b/core/java/com/android/internal/widget/remotecompose/core/operations/paint/PaintChanges.java index c014787..f2ab304 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/paint/PaintChanges.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/paint/PaintChanges.java
@@ -106,6 +106,39 @@ int tileMode); /** + * Sets a shader that draws a radial gradient given the center and radius. + * + * @param startX The x-coordinate of the center of the starting circle of the radial gradient, + * often referred to as the focal point. + * @param startY The y-coordinate of the center of the starting circle of the radial gradient, + * often referred to as the focal point. + * @param startRadius The radius of the starting circle of the radial gradient, often referred + * to as the focal radius. Must be greater than or equal to zero. + * @param endX The x-coordinate of the center of the radius for the end circle of the radial + * gradient + * @param endY The y-coordinate of the center of the radius for the end circle of the radial + * gradient + * @param endRadius The radius of the ending circle for this gradient. This must be strictly + * greater than zero. A radius value equal to zero is not allowed. + * @param colors The sRGB colors to be distributed between the center and edge of the circle + * @param stops May be <code>null</code>. Valid values are between <code>0.0f</code> and <code> + * 1.0f</code>. The relative position of each corresponding color in the colors array. If + * <code>null</code>, colors are distributed evenly between the center and edge of the + * circle. + * @param tileMode The Shader tiling mode + */ + void setRadialGradient( + @NonNull int[] colors, + @Nullable float[] stops, + float startX, + float startY, + float startRadius, + float endX, + float endY, + float endRadius, + int tileMode); + + /** * Set a sweep gradient fill * * @param stopsArray // todo: standardize naming to either "positions" or "stops"
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/paint/Painter.java b/core/java/com/android/internal/widget/remotecompose/core/operations/paint/Painter.java index 65edf79..2f83433 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/paint/Painter.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/paint/Painter.java
@@ -194,6 +194,44 @@ } /** + * Sets a shader that draws a radial gradient given the center and radius. + * + * @param startX The x-coordinate of the center of the starting circle of the radial gradient, + * often referred to as the focal point. + * @param startY The y-coordinate of the center of the starting circle of the radial gradient, + * often referred to as the focal point. + * @param startR The radius of the starting circle of the radial gradient, often referred to as + * the focal radius. Must be greater than or equal to zero. + * @param endX The x-coordinate of the center of the radius for the end circle of the radial + * gradient + * @param endY The y-coordinate of the center of the radius for the end circle of the radial + * gradient + * @param endR The radius of the ending circle for this gradient. This must be strictly greater + * than zero. A radius value equal to zero is not allowed. + * @param colors The sRGB colors to be distributed between the center and edge of the circle + * @param positions May be <code>null</code>. Valid values are between <code>0.0f</code> and + * <code>1.0f</code>. The relative position of each corresponding color in the colors array. + * If <code>null</code>, colors are distributed evenly between the center and edge of the + * circle. + * @param tileMode The Shader tiling mode + */ + @NonNull + public Painter setRadialGradient( + float startX, + float startY, + float startR, + float endX, + float endY, + float endR, + @NonNull int[] colors, + @Nullable float[] positions, + int tileMode) { + mPaint.setRadialGradient( + colors, 0, positions, startX, startY, startR, endX, endY, endR, tileMode); + return this; + } + + /** * Set a shader that draws a sweep gradient around a center point. * * @param centerX The x-coordinate of the center
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/utilities/Mesh2DGenerator.java b/core/java/com/android/internal/widget/remotecompose/core/operations/utilities/Mesh2DGenerator.java new file mode 100644 index 0000000..3a73308 --- /dev/null +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/utilities/Mesh2DGenerator.java
@@ -0,0 +1,930 @@ +/* + * Copyright (C) 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.internal.widget.remotecompose.core.operations.utilities; + +import android.annotation.NonNull; +import android.annotation.Nullable; + +import com.android.internal.widget.remotecompose.core.operations.utilities.easing.MonotonicSpline; + +/** + * Topology and domain helper for 2D vertex meshes. + * + * <p>A 2D mesh is a sampling of a {@code (u, v)} domain. The {@code layout} decides three things: + * + * <ul> + * <li>how {@code u} and {@code v} are sampled across the domain, + * <li>how the resulting vertices are connected into a triangle list (including whether the {@code + * u} axis wraps around, as it must for anything radial), + * <li>what the position is when the document supplies no position expression - so a {@code polar} + * mesh is a disc without the author having to spend expression tokens on {@code cos}/{@code + * sin}. + * </ul> + * + * <p>Position expressions, when present, always win: they produce cartesian x/y directly and the + * default below is ignored. The defaults are all built inside the unit square or unit circle + * centred on the origin, so the ordinary 2D canvas matrix ({@code translate}/{@code scale}) places + * and sizes them. + * + * <p>This class is deliberately free of any rendering or platform dependency: it computes flat + * arrays in the exact layout {@code Canvas.drawVertices} and {@code SkVertices} want. + */ +public final class Mesh2DGenerator { + + /** Rectangular domain: u across, v down. Warps, cloth, gradient fields, heat maps. */ + public static final int LAYOUT_GRID = 0; + + /** Disc: u is angle 0..1 mapped to 0..2pi, v is radius 0..1. */ + public static final int LAYOUT_POLAR = 1; + + /** Annulus: u is angle, v runs across a band between an inner radius and 1. */ + public static final int LAYOUT_RING = 2; + + /** Ribbon: u along, v across. Trails, variable width strokes. */ + public static final int LAYOUT_STRIP = 3; + + /** Triangle fan from a centre vertex: u is angle. Pie wedges, cones of light. */ + public static final int LAYOUT_FAN = 4; + + /** Ribbon following a path: u is arclength along the path in {@code aux}, v across. */ + public static final int LAYOUT_PATH_STRIP = 5; + + /** Default inner radius for {@link #LAYOUT_RING}, as a fraction of the outer radius. */ + public static final float DEFAULT_RING_INNER_RADIUS = 0.5f; + + private static final float TWO_PI = (float) (Math.PI * 2); + + private Mesh2DGenerator() {} + + /** + * Whether the u axis wraps, i.e. the last column of vertices connects back to the first. + * + * <p>Radial layouts wrap; rectangular ones do not. This also changes how u is sampled: a + * wrapping layout must not place a vertex at both u=0 and u=1, because they are the same point. + * + * @param layout one of the {@code LAYOUT_*} constants + * @return true if the u axis is periodic + */ + public static boolean wrapsU(int layout) { + return layout == LAYOUT_POLAR || layout == LAYOUT_RING || layout == LAYOUT_FAN; + } + + /** + * The number of vertices this layout produces. + * + * @param layout one of the {@code LAYOUT_*} constants + * @param uCount samples along u + * @param vCount samples along v + * @return the vertex count + */ + public static int vertexCount(int layout, int uCount, int vCount) { + if (layout == LAYOUT_FAN) { + // one shared centre vertex plus a rim + return uCount + 1; + } + return uCount * vCount; + } + + /** + * The number of indices this layout produces (3 per triangle). + * + * @param layout one of the {@code LAYOUT_*} constants + * @param uCount samples along u + * @param vCount samples along v + * @return the index count + */ + public static int indexCount(int layout, int uCount, int vCount) { + if (layout == LAYOUT_FAN) { + return uCount * 3; + } + if (vCount < 2 || uCount < 2) { + return 0; + } + int columns = wrapsU(layout) ? uCount : uCount - 1; + return columns * (vCount - 1) * 6; + } + + /** + * The u parameter for sample {@code i}. + * + * <p>A wrapping layout divides by {@code uCount} so that the sample after the last is the + * first; a non-wrapping one divides by {@code uCount - 1} so the domain is closed at both ends. + * + * @param layout one of the {@code LAYOUT_*} constants + * @param i the sample index along u + * @param uCount samples along u + * @return u in the range 0..1 + */ + public static float domainU(int layout, int i, int uCount) { + if (uCount <= 1) { + return 0f; + } + if (wrapsU(layout)) { + return i / (float) uCount; + } + return i / (float) (uCount - 1); + } + + /** + * The v parameter for sample {@code j}. + * + * @param j the sample index along v + * @param vCount samples along v + * @return v in the range 0..1 + */ + public static float domainV(int j, int vCount) { + if (vCount <= 1) { + return 0f; + } + return j / (float) (vCount - 1); + } + + /** + * Fill the triangle list for this layout. + * + * <p>Winding is consistent across every layout so a document can rely on it. + * + * @param layout one of the {@code LAYOUT_*} constants + * @param uCount samples along u + * @param vCount samples along v + * @param out the destination, at least {@link #indexCount} long + */ + public static void generateIndices(int layout, int uCount, int vCount, @NonNull int[] out) { + int k = 0; + if (layout == LAYOUT_FAN) { + // vertex 0 is the centre, 1..uCount are the rim + for (int i = 0; i < uCount; i++) { + out[k++] = 0; + out[k++] = 1 + i; + out[k++] = 1 + ((i + 1) % uCount); + } + return; + } + if (vCount < 2 || uCount < 2) { + return; + } + boolean wrap = wrapsU(layout); + int columns = wrap ? uCount : uCount - 1; + for (int j = 0; j < vCount - 1; j++) { + for (int i = 0; i < columns; i++) { + int i1 = wrap ? (i + 1) % uCount : i + 1; + int topLeft = j * uCount + i; + int topRight = j * uCount + i1; + int bottomLeft = (j + 1) * uCount + i; + int bottomRight = (j + 1) * uCount + i1; + + out[k++] = topLeft; + out[k++] = bottomLeft; + out[k++] = topRight; + + out[k++] = topRight; + out[k++] = bottomLeft; + out[k++] = bottomRight; + } + } + } + + /** + * The position a vertex takes when the document supplies no position expression. + * + * <p>Every default lives in the unit square or the unit circle centred on the origin; the + * canvas matrix is what places and sizes it. This is what lets {@code layout: polar} be useful + * without the author spending scarce expression tokens on trigonometry. + * + * @param layout one of the {@code LAYOUT_*} constants + * @param u the u parameter, 0..1 + * @param v the v parameter, 0..1 + * @param out a 2 element array receiving x then y + */ + public static void defaultPosition(int layout, float u, float v, @NonNull float[] out) { + float angle; + switch (layout) { + case LAYOUT_POLAR: + case LAYOUT_FAN: + angle = u * TWO_PI; + out[0] = v * (float) Math.cos(angle); + out[1] = v * (float) Math.sin(angle); + break; + case LAYOUT_RING: + angle = u * TWO_PI; + float radius = DEFAULT_RING_INNER_RADIUS + (1f - DEFAULT_RING_INNER_RADIUS) * v; + out[0] = radius * (float) Math.cos(angle); + out[1] = radius * (float) Math.sin(angle); + break; + case LAYOUT_GRID: + case LAYOUT_STRIP: + case LAYOUT_PATH_STRIP: + default: + out[0] = u; + out[1] = v; + break; + } + } + + /** + * Sample a flat path, as stored by {@code RemoteContext.loadPathData}, at a fraction of its + * arclength, returning position and unit tangent. + * + * <p>Used by {@link #LAYOUT_PATH_STRIP} to turn an existing path into a ribbon. Curves are + * flattened to line segments before measuring, which is what the players do to rasterise them + * anyway. + * + * @param polyline the flattened path as x,y pairs + * @param pointCount the number of x,y pairs in {@code polyline} + * @param fraction the position along the path, 0..1 + * @param out a 4 element array receiving x, y, tangentX, tangentY + */ + public static void samplePolyline( + @NonNull float[] polyline, int pointCount, float fraction, @NonNull float[] out) { + if (pointCount <= 0) { + out[0] = 0f; + out[1] = 0f; + out[2] = 1f; + out[3] = 0f; + return; + } + if (pointCount == 1) { + out[0] = polyline[0]; + out[1] = polyline[1]; + out[2] = 1f; + out[3] = 0f; + return; + } + + float total = 0f; + for (int i = 1; i < pointCount; i++) { + float dx = polyline[i * 2] - polyline[(i - 1) * 2]; + float dy = polyline[i * 2 + 1] - polyline[(i - 1) * 2 + 1]; + total += (float) Math.hypot(dx, dy); + } + if (total <= 0f) { + out[0] = polyline[0]; + out[1] = polyline[1]; + out[2] = 1f; + out[3] = 0f; + return; + } + + float target = Math.max(0f, Math.min(1f, fraction)) * total; + float walked = 0f; + for (int i = 1; i < pointCount; i++) { + float x0 = polyline[(i - 1) * 2]; + float y0 = polyline[(i - 1) * 2 + 1]; + float x1 = polyline[i * 2]; + float y1 = polyline[i * 2 + 1]; + float dx = x1 - x0; + float dy = y1 - y0; + float len = (float) Math.hypot(dx, dy); + if (len <= 0f) { + continue; + } + if (walked + len >= target) { + float t = (target - walked) / len; + out[0] = x0 + dx * t; + out[1] = y0 + dy * t; + out[2] = dx / len; + out[3] = dy / len; + return; + } + walked += len; + } + + // past the end: clamp to the final point and its incoming tangent + float x0 = polyline[(pointCount - 2) * 2]; + float y0 = polyline[(pointCount - 2) * 2 + 1]; + float x1 = polyline[(pointCount - 1) * 2]; + float y1 = polyline[(pointCount - 1) * 2 + 1]; + float dx = x1 - x0; + float dy = y1 - y0; + float len = (float) Math.hypot(dx, dy); + out[0] = x1; + out[1] = y1; + out[2] = len > 0f ? dx / len : 1f; + out[3] = len > 0f ? dy / len : 0f; + } + + /** + * Smallest gap forced between two spline knots. + * + * <p>Knot positions may be driven by document variables, so they can become equal or go + * backwards at runtime however carefully they were validated at authoring time. A zero gap + * divides by zero inside the spline and poisons the whole ribbon with NaN, so the knots are + * nudged apart instead. + */ + private static final float MIN_KNOT_GAP = 1e-6f; + + /** + * Build the spline that gives a path strip its cross width along the path. + * + * <p>Returns {@code null} when there is nothing to interpolate - no widths at all, or a single + * width, which is a constant and needs no spline. Callers must handle that case; see {@link + * #widthAt}. + * + * <p>{@code positions} is optional. When it is absent the widths are spread evenly over the + * path, so the first is the width at the start and the last is the width at the end. When it is + * present it must have one entry per width, each a fraction of arclength. + * + * @param widths the width control points, in the path's own units + * @param positions where each width sits along the path, 0..1, or null for evenly spaced + * @return the interpolating spline, or null when the width is constant or undefined + */ + public static @Nullable MonotonicSpline widthSpline( + @Nullable float[] widths, @Nullable float[] positions) { + if (widths == null || widths.length < 2) { + return null; + } + float[] knots = null; + if (positions != null && positions.length == widths.length) { + knots = new float[positions.length]; + float previous = Float.NEGATIVE_INFINITY; + for (int i = 0; i < positions.length; i++) { + float t = positions[i]; + if (Float.isNaN(t)) { + t = previous == Float.NEGATIVE_INFINITY ? 0f : previous + MIN_KNOT_GAP; + } else if (previous != Float.NEGATIVE_INFINITY && t <= previous) { + t = previous + MIN_KNOT_GAP; + } + knots[i] = t; + previous = t; + } + } + return new MonotonicSpline(knots, widths); + } + + /** + * The cross width of a path strip at a fraction of its arclength. + * + * <p>A negative width would fold the ribbon inside out, so it is clamped away. The monotonic + * fit will not overshoot between control points, but it does extrapolate past the ends. + * + * @param spline the spline from {@link #widthSpline}, or null when the width is constant + * @param widths the width control points the spline was built from + * @param fraction the position along the path, 0..1 + * @return the width, never negative + */ + public static float widthAt( + @Nullable MonotonicSpline spline, @Nullable float[] widths, float fraction) { + float width; + if (spline != null) { + width = spline.getPos(fraction); + } else if (widths != null && widths.length > 0) { + width = widths[0]; + } else { + return 1f; + } + if (Float.isNaN(width) || width < 0f) { + return 0f; + } + return width; + } + + /** + * The fewest columns a round end cap is ever drawn with. Below this the arc reads as a bevel. + */ + public static final int MIN_ROUND_CAP_SEGMENTS = 3; + + /** + * The most columns a round end cap is ever drawn with. Beyond this the arc is already smooth. + */ + public static final int MAX_ROUND_CAP_SEGMENTS = 16; + + /** + * How many columns of the strip to spend on each round end cap. + * + * <p>The caps are extra columns on top of the body rather than a slice out of it, so a rounded + * strip follows its path at exactly the same resolution as a flat one with the same {@code + * segments}. The count scales with the body so a finely sampled strip does not end in a visibly + * coarse arc, but it is clamped at both ends: three columns is the least that reads as round + * rather than chamfered, and past sixteen the extra vertices buy nothing a viewer can see. + * + * @param segments the number of columns spanning the path itself + * @return the number of columns in each cap + */ + public static int roundCapSegments(int segments) { + int cap = segments / 4; + if (cap < MIN_ROUND_CAP_SEGMENTS) { + return MIN_ROUND_CAP_SEGMENTS; + } + return Math.min(cap, MAX_ROUND_CAP_SEGMENTS); + } + + /** + * Place a vertex on a semicircular end cap of a path strip. + * + * <p>The cap is swept as a quarter turn, {@code angle} running from 0 at the tip to {@code + * PI/2} where the cap meets the body. At each angle the two edges of the strip sit at {@code + * +/- halfWidth * sin(angle)} across the path and {@code halfWidth * cos(angle)} beyond its + * end, so the segments joining them sweep out exactly the half disc of radius {@code + * halfWidth}: a true round cap, built from the strip's own quads rather than from extra fan + * geometry. At {@code angle == PI/2} the point coincides with the flat end of the body, so the + * cap joins it seamlessly; at {@code angle == 0} both edges meet at the tip, leaving one + * degenerate column that rasterises to nothing. + * + * @param sample position and unit tangent at the path end, as filled by {@link #samplePolyline} + * @param halfWidth half the strip's cross width at this end, which is the cap's radius + * @param angle 0 at the tip, {@code PI/2} at the base where the cap meets the body + * @param v the cross parameter, 0..1 + * @param outward 1 at the end of the path, -1 at the start, being the direction the cap bulges + * @param out a 2 element array receiving x then y + */ + public static void roundCapPoint( + @NonNull float[] sample, + float halfWidth, + float angle, + float v, + float outward, + @NonNull float[] out) { + float tx = sample[2]; + float ty = sample[3]; + // the normal is the tangent turned a quarter turn, matching the body of the strip + float nx = -ty; + float ny = tx; + float along = outward * halfWidth * (float) Math.cos(angle); + float across = (v - 0.5f) * 2f * halfWidth * (float) Math.sin(angle); + out[0] = sample[0] + tx * along + nx * across; + out[1] = sample[1] + ty * along + ny * across; + } + + /** + * Convert an IEEE 754 half float, as carried by {@code type: f16Values}, to a 32 bit float. + * + * <p>Half floats are a wire format only. They are widened here, on read, so the expression + * evaluator, the mesh cache and the {@code PaintContext} all see ordinary 32 bit floats and + * nothing downstream knows the document used them. + * + * @param half the 16 bit pattern, in the low bits of an int + * @return the value as a float + */ + public static float halfToFloat(int half) { + int sign = (half >>> 15) & 0x1; + int exponent = (half >>> 10) & 0x1F; + int mantissa = half & 0x3FF; + + int bits; + if (exponent == 0) { + if (mantissa == 0) { + // signed zero + bits = sign << 31; + } else { + // subnormal: normalise it + exponent = 127 - 15 + 1; + while ((mantissa & 0x400) == 0) { + mantissa <<= 1; + exponent--; + } + mantissa &= 0x3FF; + bits = (sign << 31) | (exponent << 23) | (mantissa << 13); + } + } else if (exponent == 0x1F) { + // infinity or NaN + bits = (sign << 31) | 0x7F800000 | (mantissa << 13); + } else { + bits = (sign << 31) | ((exponent - 15 + 127) << 23) | (mantissa << 13); + } + return Float.intBitsToFloat(bits); + } + + /** + * Convert a 32 bit float to an IEEE 754 half float for the {@code f16Values} wire format. + * + * <p>16 bits is ample for screen space coordinates and for uv in 0..1 - a half float is exact + * for integers up to 2048 and carries about three decimal digits - so 4096 is roughly where + * this stops being free. + * + * @param value the value to convert + * @return the 16 bit pattern, in the low bits of an int + */ + public static int floatToHalf(float value) { + int bits = Float.floatToRawIntBits(value); + int sign = (bits >>> 16) & 0x8000; + int exponent = (bits >>> 23) & 0xFF; + int mantissa = bits & 0x7FFFFF; + + if (exponent == 0xFF) { + // infinity or NaN; keep NaN non-zero in the mantissa + return sign | 0x7C00 | (mantissa != 0 ? 0x200 : 0); + } + + int unbiased = exponent - 127 + 15; + if (unbiased >= 0x1F) { + // overflow to infinity + return sign | 0x7C00; + } + if (unbiased <= 0) { + if (unbiased < -10) { + // underflow to signed zero + return sign; + } + // subnormal + mantissa |= 0x800000; + int shift = 14 - unbiased; + int half = mantissa >>> shift; + // round to nearest even + if (((mantissa >>> (shift - 1)) & 0x1) != 0) { + half++; + } + return sign | half; + } + + int half = (unbiased << 10) | (mantissa >>> 13); + // round to nearest even + if ((mantissa & 0x1000) != 0) { + half++; + } + return sign | half; + } + + /** + * Flatten stored path data into an x,y polyline. + * + * <p>Returns the number of points written. Curves are subdivided uniformly; this is only used + * to measure and place a ribbon, so a modest fixed subdivision is enough. + * + * @param pathData the path as stored by {@code RemoteContext.loadPathData}, may be null + * @param out destination for x,y pairs + * @return the number of points written + */ + public static int flattenPath(@Nullable float[] pathData, @NonNull float[] out) { + if (pathData == null) { + return 0; + } + final int subdivisions = 8; + int count = 0; + float cx = 0f; + float cy = 0f; + int i = 0; + while (i < pathData.length && count * 2 + 2 <= out.length) { + float cmd = pathData[i]; + if (!Float.isNaN(cmd)) { + i++; + continue; + } + int op = Float.floatToRawIntBits(cmd) & 0xFF; + switch (op) { + case PathCommands.MOVE: + if (i + 2 < pathData.length) { + cx = pathData[i + 1]; + cy = pathData[i + 2]; + out[count * 2] = cx; + out[count * 2 + 1] = cy; + count++; + } + i += 3; + break; + case PathCommands.LINE: + if (i + 2 < pathData.length) { + cx = pathData[i + 1]; + cy = pathData[i + 2]; + out[count * 2] = cx; + out[count * 2 + 1] = cy; + count++; + } + i += 3; + break; + case PathCommands.QUADRATIC: + if (i + 4 < pathData.length) { + float x1 = pathData[i + 1]; + float y1 = pathData[i + 2]; + float x2 = pathData[i + 3]; + float y2 = pathData[i + 4]; + for (int s = 1; s <= subdivisions; s++) { + if (count * 2 + 2 > out.length) { + break; + } + float t = s / (float) subdivisions; + float mt = 1f - t; + out[count * 2] = mt * mt * cx + 2 * mt * t * x1 + t * t * x2; + out[count * 2 + 1] = mt * mt * cy + 2 * mt * t * y1 + t * t * y2; + count++; + } + cx = x2; + cy = y2; + } + i += 5; + break; + case PathCommands.CUBIC: + if (i + 6 < pathData.length) { + float x1 = pathData[i + 1]; + float y1 = pathData[i + 2]; + float x2 = pathData[i + 3]; + float y2 = pathData[i + 4]; + float x3 = pathData[i + 5]; + float y3 = pathData[i + 6]; + for (int s = 1; s <= subdivisions; s++) { + if (count * 2 + 2 > out.length) { + break; + } + float t = s / (float) subdivisions; + float mt = 1f - t; + out[count * 2] = + mt * mt * mt * cx + + 3 * mt * mt * t * x1 + + 3 * mt * t * t * x2 + + t * t * t * x3; + out[count * 2 + 1] = + mt * mt * mt * cy + + 3 * mt * mt * t * y1 + + 3 * mt * t * t * y2 + + t * t * t * y3; + count++; + } + cx = x3; + cy = y3; + } + i += 7; + break; + case PathCommands.CLOSE: + i += 1; + break; + case PathCommands.DONE: + return count; + default: + i += 1; + break; + } + } + return count; + } + + /** Keep the origin only: content rides the surface, staying upright and unscaled. */ + public static final int FLAG_ORIGIN = 0; + + /** Keep origin and rotation: content turns with the surface. */ + public static final int FLAG_ROTATION = 1; + + /** Keep origin, rotation and scale: content stretches with the surface. */ + public static final int FLAG_SCALE = 2; + + /** Keep the full 2x3, skew included: the faithful case. */ + public static final int FLAG_FULL = 3; + + private static final float DEGENERATE_EPSILON = 1e-6f; + + /** + * Sample the surface at {@code (u, v)} from the expanded vertex array and build a 2x3 affine + * matrix {@code [duX, duY, dvX, dvY, originX, originY]} according to {@code flags}. + * + * @param layout one of the {@code LAYOUT_*} constants + * @param uCount samples along u + * @param vCount samples along v + * @param verts the expanded x,y vertex array + * @param u the u parameter, 0..1 + * @param v the v parameter, 0..1 + * @param flags which parts of the local frame to keep ({@code FLAG_*}) + * @param out a 6-element array receiving {@code [duX, duY, dvX, dvY, originX, originY]} + * @return true if the mesh had enough vertices to compute a matrix + */ + public static boolean computeMatrixFromMesh( + int layout, + int uCount, + int vCount, + @NonNull float[] verts, + float u, + float v, + int flags, + @NonNull float[] out) { + if (verts.length < 2 || out.length < 6) { + return false; + } + float[] frame = new float[6]; + sampleMeshFrame(layout, uCount, vCount, verts, u, v, frame); + buildMatrix(frame, flags, out); + return true; + } + + /** + * Sample the surface's local frame {@code [duX, duY, dvX, dvY, originX, originY]} at {@code (u, + * v)} directly from the expanded mesh vertices. + */ + public static void sampleMeshFrame( + int layout, + int uCount, + int vCount, + @NonNull float[] verts, + float u, + float v, + @NonNull float[] out) { + int uc = Math.max(2, uCount); + int vc = Math.max(2, vCount); + boolean wrap = wrapsU(layout); + float du = 1f / (wrap ? uc : (uc - 1)); + float dv = 1f / (vc - 1); + + float[] centre = new float[2]; + float[] uPlus = new float[2]; + float[] uMinus = new float[2]; + float[] vPlus = new float[2]; + float[] vMinus = new float[2]; + + sampleMeshPosition(layout, uCount, vCount, verts, u, v, centre); + + float uSpan; + if (wrap) { + sampleMeshPosition(layout, uCount, vCount, verts, u + du * 0.5f, v, uPlus); + sampleMeshPosition(layout, uCount, vCount, verts, u - du * 0.5f, v, uMinus); + uSpan = du; + } else { + float uHi = Math.min(1f, u + du * 0.5f); + float uLo = Math.max(0f, u - du * 0.5f); + sampleMeshPosition(layout, uCount, vCount, verts, uHi, v, uPlus); + sampleMeshPosition(layout, uCount, vCount, verts, uLo, v, uMinus); + uSpan = uHi - uLo; + if (uSpan <= 0f) { + uSpan = du; + } + } + + float vHi = Math.min(1f, v + dv * 0.5f); + float vLo = Math.max(0f, v - dv * 0.5f); + sampleMeshPosition(layout, uCount, vCount, verts, u, vHi, vPlus); + sampleMeshPosition(layout, uCount, vCount, verts, u, vLo, vMinus); + float vSpan = vHi - vLo; + if (vSpan <= 0f) { + vSpan = dv; + } + + out[0] = (uPlus[0] - uMinus[0]) / uSpan; + out[1] = (uPlus[1] - uMinus[1]) / uSpan; + out[2] = (vPlus[0] - vMinus[0]) / vSpan; + out[3] = (vPlus[1] - vMinus[1]) / vSpan; + out[4] = centre[0]; + out[5] = centre[1]; + } + + private static void sampleMeshPosition( + int layout, + int uCount, + int vCount, + @NonNull float[] verts, + float u, + float v, + @NonNull float[] out) { + int vertexCount = verts.length / 2; + if (vertexCount == 0) { + out[0] = 0f; + out[1] = 0f; + return; + } + if (layout == LAYOUT_FAN && uCount >= 1 && vertexCount == uCount + 1) { + float uNorm = ((u % 1f) + 1f) % 1f; + float fu = uNorm * uCount; + int i0 = ((int) Math.floor(fu)) % uCount; + int i1 = (i0 + 1) % uCount; + float tu = fu - (float) Math.floor(fu); + float rimX = (1f - tu) * verts[(1 + i0) * 2] + tu * verts[(1 + i1) * 2]; + float rimY = (1f - tu) * verts[(1 + i0) * 2 + 1] + tu * verts[(1 + i1) * 2 + 1]; + float vc = Math.max(0f, Math.min(1f, v)); + out[0] = (1f - vc) * verts[0] + vc * rimX; + out[1] = (1f - vc) * verts[1] + vc * rimY; + return; + } + if (uCount >= 2 && vCount >= 2 && uCount * vCount == vertexCount) { + int i0; + int i1; + float tu; + if (wrapsU(layout)) { + float uNorm = ((u % 1f) + 1f) % 1f; + float fu = uNorm * uCount; + i0 = ((int) Math.floor(fu)) % uCount; + i1 = (i0 + 1) % uCount; + tu = fu - (float) Math.floor(fu); + } else { + float fu = Math.max(0f, Math.min(1f, u)) * (uCount - 1); + i0 = (int) Math.floor(fu); + i1 = Math.min(uCount - 1, i0 + 1); + tu = fu - i0; + } + float fv = Math.max(0f, Math.min(1f, v)) * (vCount - 1); + int j0 = (int) Math.floor(fv); + int j1 = Math.min(vCount - 1, j0 + 1); + float tv = fv - j0; + out[0] = bilinear(verts, uCount, i0, j0, i1, j1, tu, tv, 0); + out[1] = bilinear(verts, uCount, i0, j0, i1, j1, tu, tv, 1); + return; + } + int nearest = + Math.max( + 0, + Math.min( + vertexCount - 1, + Math.round(Math.max(0f, Math.min(1f, u)) * (vertexCount - 1)))); + out[0] = verts[nearest * 2]; + out[1] = verts[nearest * 2 + 1]; + } + + private static float bilinear( + float[] verts, + int uCount, + int i0, + int j0, + int i1, + int j1, + float tu, + float tv, + int component) { + float v00 = verts[(j0 * uCount + i0) * 2 + component]; + float v10 = verts[(j0 * uCount + i1) * 2 + component]; + float v01 = verts[(j1 * uCount + i0) * 2 + component]; + float v11 = verts[(j1 * uCount + i1) * 2 + component]; + float top = v00 + (v10 - v00) * tu; + float bottom = v01 + (v11 - v01) * tu; + return top + (bottom - top) * tv; + } + + /** + * Turn a sampled surface frame into a 2x3 affine, honouring the requested level of detail and + * degrading gracefully where the patch is degenerate. + * + * @param frame duX, duY, dvX, dvY, originX, originY + * @param flags how much of the frame to keep + * @param out a 6 element array receiving the affine as duX, duY, dvX, dvY, originX, originY + */ + public static void buildMatrix(@NonNull float[] frame, int flags, @NonNull float[] out) { + float duX = frame[0]; + float duY = frame[1]; + float dvX = frame[2]; + float dvY = frame[3]; + float originX = frame[4]; + float originY = frame[5]; + + float duLength = (float) Math.hypot(duX, duY); + float dvLength = (float) Math.hypot(dvX, dvY); + float cross = duX * dvY - duY * dvX; + + int effective = flags; + if (effective >= FLAG_FULL && Math.abs(cross) < DEGENERATE_EPSILON) { + effective = FLAG_SCALE; + } + if (effective >= FLAG_SCALE + && (duLength < DEGENERATE_EPSILON || dvLength < DEGENERATE_EPSILON)) { + effective = FLAG_ROTATION; + } + if (effective >= FLAG_ROTATION && duLength < DEGENERATE_EPSILON) { + effective = FLAG_ORIGIN; + } + + float ux; + float uy; + float sign; + switch (effective) { + case FLAG_FULL: + out[0] = duX; + out[1] = duY; + out[2] = dvX; + out[3] = dvY; + break; + case FLAG_SCALE: + ux = duX / duLength; + uy = duY / duLength; + out[0] = ux * duLength; + out[1] = uy * duLength; + sign = cross < 0 ? -1f : 1f; + out[2] = -uy * dvLength * sign; + out[3] = ux * dvLength * sign; + break; + case FLAG_ROTATION: + ux = duX / duLength; + uy = duY / duLength; + sign = cross < 0 ? -1f : 1f; + out[0] = ux; + out[1] = uy; + out[2] = -uy * sign; + out[3] = ux * sign; + break; + case FLAG_ORIGIN: + default: + out[0] = 1f; + out[1] = 0f; + out[2] = 0f; + out[3] = 1f; + break; + } + out[4] = originX; + out[5] = originY; + } + + /** Path command opcodes, mirroring the encoding used by {@code PathData}. */ + private static final class PathCommands { + static final int MOVE = 10; + static final int LINE = 11; + static final int QUADRATIC = 12; + static final int CUBIC = 14; + static final int CLOSE = 15; + static final int DONE = 16; + + private PathCommands() {} + } +}
diff --git a/core/java/com/android/internal/widget/remotecompose/core/operations/utilities/easing/SpringStopEngine.java b/core/java/com/android/internal/widget/remotecompose/core/operations/utilities/easing/SpringStopEngine.java index 95ae27e..9fee5ff 100644 --- a/core/java/com/android/internal/widget/remotecompose/core/operations/utilities/easing/SpringStopEngine.java +++ b/core/java/com/android/internal/widget/remotecompose/core/operations/utilities/easing/SpringStopEngine.java
@@ -225,7 +225,7 @@ double k = mStiffness; double c = mDamping; // Estimate how many time we should over sample based on the frequency and current sampling - int overSample = (int) (1 + 9 / (Math.sqrt(mStiffness / mMass) * dt * 4)); + int overSample = (int) (1 + 9 * (Math.sqrt(mStiffness / mMass) * dt * 4)); overSample = Math.min(overSample, 1000); // Clamp to 1000 dt /= overSample;
diff --git a/core/java/com/android/internal/widget/remotecompose/player/RemoteComposePlayer.java b/core/java/com/android/internal/widget/remotecompose/player/RemoteComposePlayer.java index f5393e7..4e28dce 100644 --- a/core/java/com/android/internal/widget/remotecompose/player/RemoteComposePlayer.java +++ b/core/java/com/android/internal/widget/remotecompose/player/RemoteComposePlayer.java
@@ -45,6 +45,7 @@ import com.android.internal.widget.remotecompose.core.RemoteComposeBuffer; import com.android.internal.widget.remotecompose.core.RemoteContext; import com.android.internal.widget.remotecompose.core.RemoteContextActions; +import com.android.internal.widget.remotecompose.core.operations.Header; import com.android.internal.widget.remotecompose.core.operations.NamedVariable; import com.android.internal.widget.remotecompose.core.operations.RootContentBehavior; import com.android.internal.widget.remotecompose.core.operations.Theme; @@ -72,6 +73,7 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import java.util.ArrayList; import java.util.HashMap; import java.util.Map; @@ -378,6 +380,34 @@ } /** + * Returns true if the document declares vertical scrolling. + * + * <p>Note: this is a structural check that ignores layout and visibility. It returns true even + * if the scrollable content currently fits in its container, or is hidden. See {@link + * CoreDocument#hasVerticalScroll()}. + * + * @return true if the document contains a vertical scroll container, or its header declares + * vertical scrolling, false otherwise + */ + public boolean isVerticallyScrollable() { + return mInner.isVerticallyScrollable(); + } + + /** + * Returns true if the document declares horizontal scrolling. + * + * <p>Note: this is a structural check that ignores layout and visibility. It returns true even + * if the scrollable content currently fits in its container, or is hidden. See {@link + * CoreDocument#hasHorizontalScroll()}. + * + * @return true if the document contains a horizontal scroll container, or its header declares + * horizontal scrolling, false otherwise + */ + public boolean isHorizontallyScrollable() { + return mInner.isHorizontallyScrollable(); + } + + /** * Turn on debug information * * @param debugFlags 1 to set debug on @@ -517,6 +547,69 @@ this, gainFocus, direction, previouslyFocusedRect); } + private boolean useDisallowInterceptTouch() { + if (mInner != null && mInner.getDocument() != null) { + return mInner.getDocument().useFeature(Header.FEATURE_DISALLOW_INTERCEPT_TOUCH); + } + return true; + } + + @Override + public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { + super.requestDisallowInterceptTouchEvent(disallowIntercept); + if (!useDisallowInterceptTouch()) { + return; + } + if (!disallowIntercept) { + ViewParent parent = getParent(); + ViewParent scrollingAncestor = null; + while (parent != null) { + if (isScrollingAncestor(parent)) { + scrollingAncestor = parent; + break; + } + parent = parent.getParent(); + } + if (scrollingAncestor != null && scrollingAncestor.getParent() != null) { + scrollingAncestor.getParent().requestDisallowInterceptTouchEvent(true); + } + } + } + + private static boolean isScrollingAncestor(@NonNull ViewParent parent) { + if (parent instanceof View) { + View view = (View) parent; + return view.canScrollHorizontally(1) + || view.canScrollHorizontally(-1) + || view.canScrollVertically(1) + || view.canScrollVertically(-1); + } + return false; + } + + @Override + public void addFocusables(@NonNull ArrayList<View> views, int direction, int focusableMode) { + if (!useDisallowInterceptTouch()) { + super.addFocusables(views, direction, focusableMode); + return; + } + final int count = getChildCount(); + for (int i = 0; i < count; i++) { + final View child = getChildAt(i); + if (child.getVisibility() == VISIBLE) { + child.addFocusables(views, direction, focusableMode); + } + } + } + + @Override + public boolean requestFocus(int direction, @Nullable Rect previouslyFocusedRect) { + if (!useDisallowInterceptTouch()) { + return super.requestFocus(direction, previouslyFocusedRect); + } + return onRequestFocusInDescendants(direction, previouslyFocusedRect); + } + /** * Apply the content behavior (NONE|SCROLL_HORIZONTAL|SCROLL_VERTICAL) to the player, adding or * removing scrollviews as needed. @@ -947,18 +1040,22 @@ @Override public boolean performClick() { - ViewParent parent = getParent(); - if (parent instanceof View) { - ((View) parent).performClick(); + if (useDisallowInterceptTouch()) { + ViewParent parent = getParent(); + if (parent instanceof View) { + ((View) parent).performClick(); + } } return super.performClick(); } @Override public boolean performLongClick() { - ViewParent parent = getParent(); - if (parent instanceof View) { - ((View) parent).performLongClick(); + if (useDisallowInterceptTouch()) { + ViewParent parent = getParent(); + if (parent instanceof View) { + ((View) parent).performLongClick(); + } } return super.performLongClick(); } @@ -987,6 +1084,10 @@ */ public void setShaderControl(@NonNull ShaderControl ctl) { mShaderControl = ctl; + if (mInner != null && mInner.getDocument() != null) { + mInner.checkShaders(mShaderControl); + mInner.invalidate(); + } } /** This is a prepared document. */
diff --git a/core/java/com/android/internal/widget/remotecompose/player/platform/AndroidPaintContext.java b/core/java/com/android/internal/widget/remotecompose/player/platform/AndroidPaintContext.java index d942d49..16b068b 100644 --- a/core/java/com/android/internal/widget/remotecompose/player/platform/AndroidPaintContext.java +++ b/core/java/com/android/internal/widget/remotecompose/player/platform/AndroidPaintContext.java
@@ -24,6 +24,7 @@ import android.graphics.BitmapShader; import android.graphics.BlendMode; import android.graphics.Canvas; +import android.graphics.Color; import android.graphics.ComposePathEffect; import android.graphics.DashPathEffect; import android.graphics.DiscretePathEffect; @@ -62,6 +63,8 @@ import com.android.internal.widget.remotecompose.core.RcPlatformServices; import com.android.internal.widget.remotecompose.core.RemoteContext; import com.android.internal.widget.remotecompose.core.operations.ClipPath; +import com.android.internal.widget.remotecompose.core.operations.DrawMesh2D; +import com.android.internal.widget.remotecompose.core.operations.DrawTextOnCircle; import com.android.internal.widget.remotecompose.core.operations.ShaderData; import com.android.internal.widget.remotecompose.core.operations.Utils; import com.android.internal.widget.remotecompose.core.operations.layout.managers.CoreText; @@ -69,6 +72,7 @@ import com.android.internal.widget.remotecompose.core.operations.paint.PaintBundle; import com.android.internal.widget.remotecompose.core.operations.paint.PaintChanges; import com.android.internal.widget.remotecompose.core.operations.paint.PaintPathEffects; +import com.android.internal.widget.remotecompose.core.operations.utilities.Mesh2DGenerator; import java.util.ArrayList; import java.util.HashMap; @@ -213,9 +217,14 @@ mCanvas.save(); } + private final Paint mLayerPaint = new Paint(); + @Override public void saveLayer(float x, float y, float width, float height) { - mCanvas.saveLayer(x, y, x + width, y + height, mPaint); + mLayerPaint.reset(); + mLayerPaint.setAlpha(mPaint.getAlpha()); + mCanvas.saveLayer(x, y, x + width, y + height, mLayerPaint); + mPaint.setAlpha(255); } @Override @@ -304,7 +313,7 @@ mNode.setPivotX((Float) value * mNode.getWidth()); break; case GraphicsLayerModifierOperation.TRANSFORM_ORIGIN_Y: - mNode.setPivotY((Float) value * mNode.getWidth()); + mNode.setPivotY((Float) value * mNode.getHeight()); break; case GraphicsLayerModifierOperation.TRANSLATION_X: mNode.setTranslationX((Float) value); @@ -495,6 +504,68 @@ mCanvas.drawTextOnPath(getText(textId), getPath(pathId, 0, 1), hOffset, vOffset, mPaint); } + /** + * Draws text along a circular arc using Android {@link Path} and {@link Canvas#drawTextOnPath}. + * + * <p>Measures text width with the current {@link Paint}, calculates the arc sweep angle based + * on the final radius ({@code radius + warpRadiusOffset}), adjusts the starting angle for text + * alignment (START, CENTER, or END), and constructs an arc path using {@link Path#addArc}. + * + * <p>Placement specifies the drawing direction: {@code OUTSIDE} places text clockwise along the + * top of the arc, while {@code INSIDE} places text counter-clockwise along the bottom. + */ + @Override + public void drawTextOnCircle( + int textId, + float centerX, + float centerY, + float radius, + float startAngle, + float warpRadiusOffset, + int alignment, + int placement) { + String textToDraw = getText(textId); + if (textToDraw == null) { + return; + } + float textWidth = mPaint.measureText(textToDraw); + float finalRadius = radius + warpRadiusOffset; + if (finalRadius <= 0f) { + return; + } + // OUTSIDE placement draws text clockwise on top of the arc; + // INSIDE placement draws counterclockwise. + boolean clockwise = placement == DrawTextOnCircle.Placement.OUTSIDE.ordinal(); + float sweepDegrees = (float) Math.toDegrees(textWidth / finalRadius); + float finalStartAngle = startAngle; + if (!clockwise) { + sweepDegrees = -sweepDegrees; + if (alignment == DrawTextOnCircle.Alignment.CENTER.ordinal()) { + finalStartAngle = startAngle + Math.abs(sweepDegrees) / 2f; + } else if (alignment == DrawTextOnCircle.Alignment.END.ordinal()) { + finalStartAngle = startAngle + Math.abs(sweepDegrees); + } + } else { + if (alignment == DrawTextOnCircle.Alignment.CENTER.ordinal()) { + finalStartAngle = startAngle - sweepDegrees / 2f; + } else if (alignment == DrawTextOnCircle.Alignment.END.ordinal()) { + finalStartAngle = startAngle - sweepDegrees; + } + } + + Path path = new Path(); + path.addArc( + centerX - finalRadius, + centerY - finalRadius, + centerX + finalRadius, + centerY + finalRadius, + finalStartAngle, + sweepDegrees); + + mPaint.setTextAlign(Paint.Align.LEFT); + mCanvas.drawTextOnPath(textToDraw, path, 0f, 0f, mPaint); + } + private Paint.FontMetrics mCachedFontMetrics; @Override @@ -1140,14 +1211,31 @@ for (int i = 0; i < names.length; i++) { String name = names[i]; float[] val = data.getUniformFloats(name); - if (val.length == 1 && Float.isNaN(val[0])) { - // check if dynamic array - float[] values = - mContext.getCollectionsAccess() - .getDynamicFloats(Utils.idFromNan(val[0])); - shader.setFloatUniform(name, values); + if (val.length == 1) { + if (Float.isNaN(val[0])) { + int varId = Utils.idFromNan(val[0]); + float[] values = + mContext.getCollectionsAccess() != null + ? mContext.getCollectionsAccess() + .getDynamicFloats(varId) + : null; + if (values != null) { + shader.setFloatUniform(name, values); + } else { + shader.setFloatUniform(name, mContext.getFloat(varId)); + } + } else { + shader.setFloatUniform(name, val[0]); + } } else { - shader.setFloatUniform(name, val); + float[] evaluated = new float[val.length]; + for (int k = 0; k < val.length; k++) { + evaluated[k] = + Float.isNaN(val[k]) + ? mContext.getFloat(Utils.idFromNan(val[k])) + : val[k]; + } + shader.setFloatUniform(name, evaluated); } } names = data.getUniformIntegerNames(); @@ -1178,13 +1266,8 @@ @SuppressLint("ObsoleteSdkInt") @Override public void setBlendMode(int mode) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - Api29Impl.setBlendMode(mPaint, mode); - } else { - mPaint.setXfermode( - new android.graphics.PorterDuffXfermode( - remoteToAndroidPorterDuffMode(mode))); - } + + Api29Impl.setBlendMode(mPaint, mode); } @Override @@ -1258,6 +1341,41 @@ } @Override + public void setRadialGradient( + @NonNull int[] colors, + @Nullable float[] stops, + float startX, + float startY, + float startRadius, + float endX, + float endY, + float endRadius, + int tileMode) { + + // unavoidable short term allocation for now but little used API. + // Long term could cache the data + long[] colorLong = new long[colors.length]; + for (int i = 0; i < colorLong.length; i++) { + colorLong[i] = Color.pack(colors[i]); + } + mPaint.setShader( + new RadialGradient( + startX, + startY, + startRadius, + endX, + endY, + endRadius, + colorLong, + stops, + mTileModes[tileMode])); + + // The two-circle (focal) form needs API 31. Degrade to the end circle + // so the document still renders something sensible. + + } + + @Override public void setSweepGradient( @NonNull int[] colors, @Nullable float[] stops, @@ -1395,6 +1513,7 @@ // segmentation violation mPaint.setTypeface(Typeface.DEFAULT); mPaint.reset(); + releaseOffscreenBitmaps(); } private Path getPath(int path1Id, int path2Id, float tween, float start, float end) { @@ -1476,7 +1595,156 @@ mCanvas.concat(matrix); } - HashMap<Bitmap, Canvas> mCCache = new HashMap<>(); + /** Geometry for one 2D mesh, already in the shape {@code Canvas.drawVertices} wants. */ + private static final class Mesh2D { + final int mLayout; + final int mUCount; + final int mVCount; + final float[] mVerts; + final float[] mUv; + final int[] mColors; + final short[] mIndices; + + Mesh2D( + int layout, + int uCount, + int vCount, + float[] verts, + float[] uv, + int[] colors, + short[] indices) { + mLayout = layout; + mUCount = uCount; + mVCount = vCount; + mVerts = verts; + mUv = uv; + mColors = colors; + mIndices = indices; + } + } + + private final HashMap<Integer, Mesh2D> mMeshCache = new HashMap<>(); + private final HashMap<Integer, BitmapShader> mMeshShaderCache = new HashMap<>(); + + @Override + public void setMesh( + int meshId, + int layout, + int uCount, + int vCount, + @NonNull float[] verts, + @NonNull float[] uv, + @NonNull int[] colors, + @NonNull int[] indices) { + // Android's drawVertices takes short[] indices, so narrow once here rather than per frame. + short[] shortIndices = new short[indices.length]; + for (int i = 0; i < indices.length; i++) { + shortIndices[i] = (short) indices[i]; + } + float[] vertsCopy = verts.length > 0 ? verts.clone() : new float[0]; + float[] uvCopy = uv.length > 0 ? uv.clone() : new float[0]; + int[] colorsCopy = colors.length > 0 ? colors.clone() : new int[0]; + mMeshCache.put( + meshId, + new Mesh2D(layout, uCount, vCount, vertsCopy, uvCopy, colorsCopy, shortIndices)); + } + + @Override + public void drawMesh(int meshId, int blend, int imageId) { + Mesh2D mesh = mMeshCache.get(meshId); + if (mesh == null || mesh.mVerts.length == 0 || mesh.mIndices.length == 0) { + return; + } + + int vertexCount = mesh.mVerts.length; + int[] colors = mesh.mColors.length > 0 ? mesh.mColors : null; + + // drawVertices takes no bitmap: the texture comes from the paint's shader, and texs are + // coordinates in shader space. Passing texs with no shader is meaningless, so an + // untextured mesh must pass null. + Shader previousShader = mPaint.getShader(); + boolean shaderInstalled = false; + float[] texs = null; + + try { + if (imageId != DrawMesh2D.NO_IMAGE && mesh.mUv.length == mesh.mVerts.length) { + Bitmap bitmap = (Bitmap) mContext.mRemoteComposeState.getFromId(imageId); + if (bitmap != null) { + BitmapShader shader = mMeshShaderCache.get(imageId); + if (shader == null) { + shader = + new BitmapShader( + bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); + mMeshShaderCache.put(imageId, shader); + } + mPaint.setShader(shader); + shaderInstalled = true; + + // uv is normalised 0..1 with (0,0) at the top left, and both Android and Skia + // want image pixels, so the conversion is a plain multiply with no flip. The + // 3D path next door flips v for the GL convention; 2D deliberately does not. + int width = bitmap.getWidth(); + int height = bitmap.getHeight(); + texs = new float[mesh.mUv.length]; + for (int i = 0; i < mesh.mUv.length; i += 2) { + texs[i] = mesh.mUv[i] * width; + texs[i + 1] = mesh.mUv[i + 1] * height; + } + } + } + + if (blend == DrawMesh2D.BLEND_COLORS_ONLY) { + // colours only: ignore any texture and let the vertex colours through + texs = null; + if (shaderInstalled) { + mPaint.setShader(previousShader); + shaderInstalled = false; + } + } + + mCanvas.drawVertices( + Canvas.VertexMode.TRIANGLES, + vertexCount, + mesh.mVerts, + 0, + texs, + 0, + colors, + 0, + mesh.mIndices, + 0, + mesh.mIndices.length, + mPaint); + } finally { + // Paint is canvas state; a backend that borrows it must give it back, including when + // the draw throws. + if (shaderInstalled) { + mPaint.setShader(previousShader); + } + } + } + + @Override + public void matrixFromMesh(int meshId, float u, float v, int flags) { + Mesh2D mesh = mMeshCache.get(meshId); + if (mesh == null) { + return; + } + float[] affine = new float[6]; + if (!Mesh2DGenerator.computeMatrixFromMesh( + mesh.mLayout, mesh.mUCount, mesh.mVCount, mesh.mVerts, u, v, flags, affine)) { + return; + } + Matrix m = new Matrix(); + // [duX, duY, dvX, dvY, originX, originY] -> the 3x3 Android wants, row major + m.setValues( + new float[] { + affine[0], affine[2], affine[4], affine[1], affine[3], affine[5], 0f, 0f, 1f + }); + mCanvas.concat(m); + } + + java.util.WeakHashMap<Bitmap, Canvas> mCCache = new java.util.WeakHashMap<>(); @Override public void drawToBitmap(int bitmapId, int mode, int color) { @@ -1487,6 +1755,7 @@ mCanvas = mMainCanvas; return; } + mPaint.setAlpha(255); Bitmap bitmap = (Bitmap) mContext.mRemoteComposeState.getFromId(bitmapId); Objects.requireNonNull(bitmap); if (mCCache.containsKey(bitmap)) {
diff --git a/core/java/com/android/internal/widget/remotecompose/player/platform/RemoteComposeView.java b/core/java/com/android/internal/widget/remotecompose/player/platform/RemoteComposeView.java index a8af88d..f9d9efc 100644 --- a/core/java/com/android/internal/widget/remotecompose/player/platform/RemoteComposeView.java +++ b/core/java/com/android/internal/widget/remotecompose/player/platform/RemoteComposeView.java
@@ -617,6 +617,36 @@ } /** + * Returns true if the document declares vertical scrolling. + * + * <p>See {@link CoreDocument#hasVerticalScroll()}. + * + * @return true if the document contains a vertical scroll container, or its header declares + * vertical scrolling, false otherwise + */ + public boolean isVerticallyScrollable() { + if (mDocument == null) { + return false; + } + return mDocument.getDocument().hasVerticalScroll(); + } + + /** + * Returns true if the document declares horizontal scrolling. + * + * <p>See {@link CoreDocument#hasHorizontalScroll()}. + * + * @return true if the document contains a horizontal scroll container, or its header declares + * horizontal scrolling, false otherwise + */ + public boolean isHorizontallyScrollable() { + if (mDocument == null) { + return false; + } + return mDocument.getDocument().hasHorizontalScroll(); + } + + /** * Check shaders and disable them * * @param shaderControl the callback to validate the shader @@ -787,6 +817,13 @@ private VelocityTracker mVelocityTracker = null; + private boolean useDisallowInterceptTouch() { + if (mDocument != null) { + return mDocument.useFeature(Header.FEATURE_DISALLOW_INTERCEPT_TOUCH); + } + return true; + } + @Override public boolean onTouchEvent(@NonNull MotionEvent event) { int index = event.getActionIndex(); @@ -838,7 +875,9 @@ mVelocityTracker.clear(); } mVelocityTracker.addMovement(event); - requestDisallowInterceptTouchEvent(true); + if (useDisallowInterceptTouch() && doc.hasAppliedTouchOperations()) { + requestDisallowInterceptTouchEvent(true); + } invalidate(); return true; } @@ -848,7 +887,9 @@ case MotionEvent.ACTION_CANCEL: mInActionDown = false; - requestDisallowInterceptTouchEvent(false); + if (useDisallowInterceptTouch()) { + requestDisallowInterceptTouchEvent(false); + } if (doc.hasTouchListener()) { mVelocityTracker.computeCurrentVelocity(1000); float dx = mVelocityTracker.getXVelocity(pointerId); @@ -862,14 +903,16 @@ case MotionEvent.ACTION_UP: mLimiter.touchBoost(); mInActionDown = false; - requestDisallowInterceptTouchEvent(false); + if (useDisallowInterceptTouch()) { + requestDisallowInterceptTouchEvent(false); + } mActionCurrentPoint.x = (int) x; mActionCurrentPoint.y = (int) y; boolean handled = false; if (!mHasMoved) { if (mIsDoubleTap) { boolean handledDouble = doc.onDoubleClick(mARContext, x, y); - if (!handledDouble) { + if (useDisallowInterceptTouch() && !handledDouble) { performClick(); } mLastUpTime = 0; @@ -904,14 +947,28 @@ case MotionEvent.ACTION_MOVE: mLimiter.touchBoost(); + float dx = x - mDownX; + float dy = y - mDownY; if (!mHasMoved) { - float dx = x - mDownX; - float dy = y - mDownY; if (dx * dx + dy * dy > mTouchSlop * mTouchSlop) { mHasMoved = true; } } if (mInActionDown) { + if (useDisallowInterceptTouch() && mHasMoved) { + boolean isHorizontalDrag = Math.abs(dx) > Math.abs(dy); + boolean isVerticalDrag = Math.abs(dy) > Math.abs(dx); + + if (isHorizontalDrag && doc.canScrollHorizontally()) { + requestDisallowInterceptTouchEvent(true); + } else if (isVerticalDrag && doc.canScrollVertically()) { + requestDisallowInterceptTouchEvent(true); + } else if (isHorizontalDrag || isVerticalDrag) { + mInActionDown = false; + requestDisallowInterceptTouchEvent(false); + return false; + } + } mActionCurrentPoint.x = (int) x; mActionCurrentPoint.y = (int) y; if (mVelocityTracker != null) { @@ -957,13 +1014,15 @@ mErrorMessage = e.getMessage(); mDisable = true; } - if (!handled) { - ViewParent parent = getParent(); - if (parent instanceof View) { - ((View) parent).performClick(); + if (useDisallowInterceptTouch()) { + if (!handled) { + ViewParent parent = getParent(); + if (parent instanceof View) { + ((View) parent).performClick(); + } } + requestDisallowInterceptTouchEvent(false); } - requestDisallowInterceptTouchEvent(false); super.performClick(); invalidate(); return true; @@ -971,6 +1030,9 @@ @Override public boolean performLongClick() { + if (!useDisallowInterceptTouch()) { + return super.performLongClick(); + } if (USE_VIEW_AREA_CLICK && mHasClickAreas) { return super.performLongClick(); } @@ -1196,9 +1258,13 @@ mIsLongPressPerformed = true; mActionCurrentPoint.x = (int) mDownX; mActionCurrentPoint.y = (int) mDownY; - // b/546006609: it needs to be deferred as otherwise it causes - // IllegalStateException in ShortcutAndWidgetContainer. - post(this::performLongClick); + if (useDisallowInterceptTouch()) { + // b/546006609: it needs to be deferred as otherwise it causes + // IllegalStateException in ShortcutAndWidgetContainer. + post(this::performLongClick); + } else { + mDocument.getDocument().onLongPress(mARContext, mDownX, mDownY); + } nextFrame = 1; } else { int remaining = (int) (mLongPressTimeout - elapsed);