Merge "Move cell layout tests to deviceless tests" into main

This commit is contained in:
Sihua Ma authored and Android (Google) Code Review committed 2024-05-08 16:50:44 +00:00
commit 8128575f46
12 files changed
+14 -5

No files matched your search

@@ -1,162 +0,0 @@
/*
* Copyright (C) 2023 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.launcher3.celllayout;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
import android.graphics.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
public class CellLayoutTestCaseReader {
public abstract static class TestSection {
State state;
public TestSection(State state) {
this.state = state;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
}
public static class Comment extends TestSection {
public Comment() {
super(State.COMMENT);
}
}
public static class Arguments extends TestSection {
String[] arguments;
public Arguments(String[] arguments) {
super(State.ARGUMENTS);
this.arguments = arguments;
}
}
public static class Board extends TestSection {
public Point gridSize;
public String board;
public Board(Point gridSize, String board) {
super(State.BOARD);
this.gridSize = gridSize;
this.board = board;
}
}
public enum State {
START,
ARGUMENTS,
BOARD,
END,
COMMENT
}
String mTest;
protected CellLayoutTestCaseReader(String test) {
mTest = test;
}
public static CellLayoutTestCaseReader readFromFile(String fileName) throws IOException {
String fileStr = new BufferedReader(new InputStreamReader(
getInstrumentation().getContext().getAssets().open(fileName))
).lines().collect(Collectors.joining("\n"));
return new CellLayoutTestCaseReader(fileStr);
}
private State getStateFromLine(String line) {
String typeWithColons = line.trim().split(" ")[0].trim();
String type = typeWithColons.substring(0, typeWithColons.length() - 1);
try {
return Enum.valueOf(State.class, type.toUpperCase());
} catch (Exception e) {
throw new RuntimeException(
"The given tag " + typeWithColons + " doesn't match with the existing tags");
}
}
private String removeTag(String line) {
return line.split(":")[1];
}
private TestSection parseNextLine(Iterator<String> it) {
String line = it.next();
if (line.trim().charAt(0) == '#') {
return new Comment();
}
State state = getStateFromLine(line);
line = removeTag(line);
switch (state) {
case ARGUMENTS:
return new Arguments(parseArgumentsLine(line));
case BOARD:
Point grid = parseGridSize(line);
return new Board(grid, parseBoard(it, grid.y));
default:
return new Comment();
}
}
public List<TestSection> parse() {
List<TestSection> sections = new ArrayList<>();
String[] lines = mTest.split("\n");
Iterator<String> it = Arrays.stream(lines).iterator();
while (it.hasNext()) {
TestSection section = parseNextLine(it);
if (section.state == State.COMMENT) {
continue;
}
sections.add(section);
}
return sections;
}
private String parseBoard(Iterator<String> it, int rows) {
StringBuilder board = new StringBuilder();
for (int j = 0; j < rows; j++) {
board.append(it.next() + "\n");
}
return board.toString();
}
private String[] parseArgumentsLine(String line) {
return Arrays.stream(line.trim().split(" ")).map(String::trim).toArray(String[]::new);
}
private Point parseGridSize(String line) {
String[] values = line.toLowerCase(Locale.ROOT).split("x");
int x = Integer.parseInt(values[0].trim());
int y = Integer.parseInt(values[1].trim());
return new Point(x, y);
}
}
@@ -1,79 +0,0 @@
/*
* Copyright (C) 2023 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.launcher3.celllayout;
import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_DESKTOP;
import android.view.View;
import com.android.launcher3.CellLayout;
import com.android.launcher3.Launcher;
import com.android.launcher3.celllayout.board.CellLayoutBoard;
import com.android.launcher3.views.DoubleShadowBubbleTextView;
import java.util.ArrayList;
import java.util.List;
public class CellLayoutTestUtils {
public static ArrayList<CellLayoutBoard> workspaceToBoards(Launcher launcher) {
ArrayList<CellLayoutBoard> boards = new ArrayList<>();
for (CellLayout cellLayout : launcher.getWorkspace().mWorkspaceScreens) {
int count = cellLayout.getShortcutsAndWidgets().getChildCount();
for (int i = 0; i < count; i++) {
View callView = cellLayout.getShortcutsAndWidgets().getChildAt(i);
CellLayoutLayoutParams params =
(CellLayoutLayoutParams) callView.getLayoutParams();
CellPosMapper.CellPos pos = launcher.getCellPosMapper().mapPresenterToModel(
params.getCellX(), params.getCellY(),
launcher.getWorkspace().getCellLayoutId(cellLayout), CONTAINER_DESKTOP);
int screenId = pos.screenId;
for (int j = boards.size(); j <= screenId; j++) {
boards.add(new CellLayoutBoard(cellLayout.getCountX(), cellLayout.getCountY()));
}
CellLayoutBoard board = boards.get(screenId);
// is icon
if (callView instanceof DoubleShadowBubbleTextView) {
board.addIcon(pos.cellX, pos.cellY);
} else {
// is widget
board.addWidget(pos.cellX, pos.cellY, params.cellHSpan,
params.cellVSpan);
}
}
}
return boards;
}
public static CellLayoutBoard viewsToBoard(List<View> views, int width, int height) {
CellLayoutBoard board = new CellLayoutBoard(width, height);
for (View callView : views) {
CellLayoutLayoutParams params = (CellLayoutLayoutParams) callView.getLayoutParams();
// is icon
if (callView instanceof DoubleShadowBubbleTextView) {
board.addIcon(params.getCellX(), params.getCellY());
} else {
// is widget
board.addWidget(params.getCellX(), params.getCellY(), params.cellHSpan,
params.cellVSpan);
}
}
return board;
}
}
@@ -1,179 +0,0 @@
/*
* Copyright (C) 2024 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.launcher3.celllayout
import android.content.Context
import android.graphics.Point
import android.util.Log
import android.view.View
import androidx.core.view.get
import androidx.test.core.app.ApplicationProvider
import com.android.launcher3.CellLayout
import com.android.launcher3.celllayout.board.CellLayoutBoard
import com.android.launcher3.celllayout.board.IconPoint
import com.android.launcher3.celllayout.board.PermutedBoardComparator
import com.android.launcher3.celllayout.board.WidgetRect
import com.android.launcher3.celllayout.testgenerator.RandomBoardGenerator
import com.android.launcher3.util.ActivityContextWrapper
import com.android.launcher3.views.DoubleShadowBubbleTextView
import java.util.Random
import org.junit.Assert
import org.junit.Rule
import org.junit.Test
private class HotseatReorderTestCase(
val startBoard: CellLayoutBoard,
val endBoard: CellLayoutBoard
) {
override fun toString(): String {
return "$startBoard#endBoard:\n$endBoard"
}
}
class HotseatReorderUnitTest {
private val applicationContext: Context =
ActivityContextWrapper(ApplicationProvider.getApplicationContext())
@JvmField @Rule var cellLayoutBuilder = UnitTestCellLayoutBuilderRule()
/**
* This test generates random CellLayout configurations and then try to reorder it and makes
* sure the result is a valid board meaning it didn't remove any widget or icon.
*/
@Test
fun generateValidTests() {
val generator = Random(Companion.SEED.toLong())
for (i in 0 until Companion.TOTAL_OF_CASES_GENERATED) {
// Using a new seed so that we can replicate the same test cases.
val seed = generator.nextInt()
Log.d(Companion.TAG, "Seed = $seed")
val testCase: HotseatReorderTestCase =
generateRandomTestCase(RandomBoardGenerator(Random(seed.toLong())))
Log.d(Companion.TAG, "testCase = $testCase")
Assert.assertTrue(
"invalid case $i",
PermutedBoardComparator().compare(testCase.startBoard, testCase.endBoard) == 0
)
}
}
private fun addViewInCellLayout(
cellLayout: CellLayout,
cellX: Int,
cellY: Int,
spanX: Int,
spanY: Int,
isWidget: Boolean
) {
val cell =
if (isWidget) View(applicationContext)
else DoubleShadowBubbleTextView(applicationContext)
cell.layoutParams = CellLayoutLayoutParams(cellX, cellY, spanX, spanY)
cellLayout.addViewToCellLayout(
cell,
-1,
cell.id,
cell.layoutParams as CellLayoutLayoutParams,
true
)
}
private fun solve(board: CellLayoutBoard): CellLayout {
val cl = cellLayoutBuilder.createCellLayout(board.width, board.height, false)
// The views have to be sorted or the result can vary
board.icons
.map(IconPoint::getCoord)
.sortedWith(
Comparator.comparing { p: Any -> (p as Point).x }
.thenComparing { p: Any -> (p as Point).y }
)
.forEach { p ->
addViewInCellLayout(
cellLayout = cl,
cellX = p.x,
cellY = p.y,
spanX = 1,
spanY = 1,
isWidget = false
)
}
board.widgets
.sortedWith(
Comparator.comparing(WidgetRect::getCellX).thenComparing(WidgetRect::getCellY)
)
.forEach { widget ->
addViewInCellLayout(
cl,
widget.cellX,
widget.cellY,
widget.spanX,
widget.spanY,
isWidget = true
)
}
if (cl.makeSpaceForHotseatMigration(true)) {
commitTempPosition(cl)
}
return cl
}
private fun commitTempPosition(cellLayout: CellLayout) {
val count = cellLayout.shortcutsAndWidgets.childCount
for (i in 0 until count) {
val params = cellLayout.shortcutsAndWidgets[i].layoutParams as CellLayoutLayoutParams
params.cellX = params.tmpCellX
params.cellY = params.tmpCellY
}
}
private fun boardFromCellLayout(cellLayout: CellLayout): CellLayoutBoard {
val views = mutableListOf<View>()
for (i in 0 until cellLayout.shortcutsAndWidgets.childCount) {
views.add(cellLayout.shortcutsAndWidgets.getChildAt(i))
}
return CellLayoutTestUtils.viewsToBoard(views, cellLayout.countX, cellLayout.countY)
}
private fun generateRandomTestCase(
boardGenerator: RandomBoardGenerator
): HotseatReorderTestCase {
val width: Int = boardGenerator.getRandom(3, Companion.MAX_BOARD_SIZE)
val height: Int = boardGenerator.getRandom(3, Companion.MAX_BOARD_SIZE)
val targetWidth: Int = boardGenerator.getRandom(1, width - 2)
val targetHeight: Int = boardGenerator.getRandom(1, height - 2)
val board: CellLayoutBoard =
boardGenerator.generateBoard(width, height, targetWidth * targetHeight)
val finishBoard: CellLayoutBoard = boardFromCellLayout(solve(board))
return HotseatReorderTestCase(board, finishBoard)
}
companion object {
private const val MAX_BOARD_SIZE = 13
/**
* There is nothing special about this numbers, the random seed is just to be able to
* reproduce the test cases and the height and width is a random number similar to what
* users expect on their devices
*/
private const val SEED = -194162315
private const val TOTAL_OF_CASES_GENERATED = 300
private const val TAG = "HotseatReorderUnitTest"
}
}
@@ -1,301 +0,0 @@
/*
* Copyright (C) 2023 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.launcher3.celllayout;
import static androidx.test.core.app.ApplicationProvider.getApplicationContext;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import android.content.Context;
import android.graphics.Point;
import android.util.Log;
import android.view.View;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import com.android.launcher3.CellLayout;
import com.android.launcher3.MultipageCellLayout;
import com.android.launcher3.celllayout.board.CellLayoutBoard;
import com.android.launcher3.celllayout.board.IconPoint;
import com.android.launcher3.celllayout.board.PermutedBoardComparator;
import com.android.launcher3.celllayout.board.WidgetRect;
import com.android.launcher3.celllayout.testgenerator.RandomBoardGenerator;
import com.android.launcher3.celllayout.testgenerator.RandomMultiBoardGenerator;
import com.android.launcher3.util.ActivityContextWrapper;
import com.android.launcher3.views.DoubleShadowBubbleTextView;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
@SmallTest
@RunWith(AndroidJUnit4.class)
public class ReorderAlgorithmUnitTest {
private static final String TAG = "ReorderAlgorithmUnitTest";
private static final char MAIN_WIDGET_TYPE = 'z';
// There is nothing special about this numbers, the random seed is just to be able to reproduce
// the test cases and the height and width is a random number similar to what users expect on
// their devices
private static final int SEED = 897;
private static final int MAX_BOARD_SIZE = 13;
private static final int TOTAL_OF_CASES_GENERATED = 300;
private Context mApplicationContext;
@Rule
public UnitTestCellLayoutBuilderRule mCellLayoutBuilder = new UnitTestCellLayoutBuilderRule();
/**
* This test reads existing test cases and makes sure the CellLayout produces the same
* output for each of them for a given input.
*/
@Test
public void testAllCases() throws IOException {
List<ReorderAlgorithmUnitTestCase> testCases = getTestCases(
"ReorderAlgorithmUnitTest/reorder_algorithm_test_cases");
mApplicationContext = new ActivityContextWrapper(getApplicationContext());
List<Integer> failingCases = new ArrayList<>();
for (int i = 0; i < testCases.size(); i++) {
try {
evaluateTestCase(testCases.get(i), false);
} catch (AssertionError e) {
e.printStackTrace();
failingCases.add(i);
}
}
assertEquals("Some test cases failed " + Arrays.toString(failingCases.toArray()), 0,
failingCases.size());
}
/**
* This test generates random CellLayout configurations and then try to reorder it and makes
* sure the result is a valid board meaning it didn't remove any widget or icon.
*/
@Test
public void generateValidTests() {
Random generator = new Random(SEED);
mApplicationContext = new ActivityContextWrapper(getApplicationContext());
for (int i = 0; i < TOTAL_OF_CASES_GENERATED; i++) {
// Using a new seed so that we can replicate the same test cases.
int seed = generator.nextInt();
Log.d(TAG, "Seed = " + seed);
ReorderAlgorithmUnitTestCase testCase = generateRandomTestCase(
new RandomBoardGenerator(new Random(seed))
);
Log.d(TAG, "testCase = " + testCase);
assertTrue("invalid case " + i,
validateIntegrity(testCase.startBoard, testCase.endBoard, testCase));
}
}
/**
* Same as above but testing the Multipage CellLayout.
*/
@Test
public void generateValidTests_Multi() {
Random generator = new Random(SEED);
mApplicationContext = new ActivityContextWrapper(getApplicationContext());
for (int i = 0; i < TOTAL_OF_CASES_GENERATED; i++) {
// Using a new seed so that we can replicate the same test cases.
int seed = generator.nextInt();
Log.d(TAG, "Seed = " + seed);
ReorderAlgorithmUnitTestCase testCase = generateRandomTestCase(
new RandomMultiBoardGenerator(new Random(seed))
);
Log.d(TAG, "testCase = " + testCase);
assertTrue("invalid case " + i,
validateIntegrity(testCase.startBoard, testCase.endBoard, testCase));
}
}
private void addViewInCellLayout(CellLayout cellLayout, int cellX, int cellY, int spanX,
int spanY, boolean isWidget) {
View cell = isWidget ? new View(mApplicationContext) : new DoubleShadowBubbleTextView(
mApplicationContext);
cell.setLayoutParams(new CellLayoutLayoutParams(cellX, cellY, spanX, spanY));
cellLayout.addViewToCellLayout(cell, -1, cell.getId(),
(CellLayoutLayoutParams) cell.getLayoutParams(), true);
}
public ItemConfiguration solve(CellLayoutBoard board, int x, int y, int spanX,
int spanY, int minSpanX, int minSpanY, boolean isMulti) {
CellLayout cl = mCellLayoutBuilder.createCellLayout(board.getWidth(), board.getHeight(),
isMulti);
// The views have to be sorted or the result can vary
board.getIcons()
.stream()
.map(IconPoint::getCoord)
.sorted(Comparator.comparing(p -> ((Point) p).x).thenComparing(p -> ((Point) p).y))
.forEach(p -> addViewInCellLayout(cl, p.x, p.y, 1, 1, false));
board.getWidgets()
.stream()
.sorted(Comparator
.comparing(WidgetRect::getCellX)
.thenComparing(WidgetRect::getCellY)
).forEach(
widget -> addViewInCellLayout(cl, widget.getCellX(), widget.getCellY(),
widget.getSpanX(), widget.getSpanY(), true)
);
int[] testCaseXYinPixels = new int[2];
cl.regionToCenterPoint(x, y, spanX, spanY, testCaseXYinPixels);
ItemConfiguration configuration = new ItemConfiguration();
cl.copyCurrentStateToSolution(configuration);
ItemConfiguration solution = cl.createReorderAlgorithm()
.calculateReorder(
new ReorderParameters(
testCaseXYinPixels[0],
testCaseXYinPixels[1],
spanX,
spanY,
minSpanX,
minSpanY,
null,
configuration
)
);
if (solution == null) {
solution = new ItemConfiguration();
solution.isSolution = false;
}
if (!solution.isSolution) {
cl.copyCurrentStateToSolution(solution);
if (cl instanceof MultipageCellLayout) {
solution =
((MultipageCellLayout) cl).createReorderAlgorithm().removeSeamFromSolution(
solution);
}
solution.isSolution = false;
}
return solution;
}
public CellLayoutBoard boardFromSolution(ItemConfiguration solution, int width,
int height) {
// Update the views with solution value
solution.map.forEach((key, val) -> key.setLayoutParams(
new CellLayoutLayoutParams(val.cellX, val.cellY, val.spanX, val.spanY)));
CellLayoutBoard board = CellLayoutTestUtils.viewsToBoard(
new ArrayList<>(solution.map.keySet()), width, height);
if (solution.isSolution) {
board.addWidget(solution.cellX, solution.cellY, solution.spanX, solution.spanY,
MAIN_WIDGET_TYPE);
}
return board;
}
public void evaluateTestCase(ReorderAlgorithmUnitTestCase testCase, boolean isMultiCellLayout) {
ItemConfiguration solution = solve(testCase.startBoard, testCase.x, testCase.y,
testCase.spanX, testCase.spanY, testCase.minSpanX, testCase.minSpanY,
isMultiCellLayout);
assertEquals("should be a valid solution", solution.isSolution, testCase.isValidSolution);
Log.d(TAG, "test case:" + testCase);
if (testCase.isValidSolution) {
CellLayoutBoard finishBoard = boardFromSolution(solution,
testCase.startBoard.getWidth(), testCase.startBoard.getHeight());
Log.d(TAG, "finishBoard case:" + finishBoard);
assertTrue("End result and test case result board doesn't match ",
finishBoard.compareTo(testCase.endBoard) == 0);
}
}
private ReorderAlgorithmUnitTestCase generateRandomTestCase(
RandomBoardGenerator boardGenerator) {
ReorderAlgorithmUnitTestCase testCase = new ReorderAlgorithmUnitTestCase();
boolean isMultiCellLayout = boardGenerator instanceof RandomMultiBoardGenerator;
int width = isMultiCellLayout
? boardGenerator.getRandom(3, MAX_BOARD_SIZE / 2) * 2
: boardGenerator.getRandom(3, MAX_BOARD_SIZE);
int height = boardGenerator.getRandom(3, MAX_BOARD_SIZE);
int targetWidth = boardGenerator.getRandom(1, width - 2);
int targetHeight = boardGenerator.getRandom(1, height - 2);
int minTargetWidth = boardGenerator.getRandom(1, targetWidth);
int minTargetHeight = boardGenerator.getRandom(1, targetHeight);
int x = boardGenerator.getRandom(0, width - targetWidth);
int y = boardGenerator.getRandom(0, height - targetHeight);
CellLayoutBoard board = boardGenerator.generateBoard(width, height,
targetWidth * targetHeight);
ItemConfiguration solution = solve(board, x, y, targetWidth, targetHeight,
minTargetWidth, minTargetHeight, isMultiCellLayout);
CellLayoutBoard finishBoard = boardFromSolution(solution, board.getWidth(),
board.getHeight());
testCase.startBoard = board;
testCase.endBoard = finishBoard;
testCase.isValidSolution = solution.isSolution;
testCase.x = x;
testCase.y = y;
testCase.spanX = targetWidth;
testCase.spanY = targetHeight;
testCase.minSpanX = minTargetWidth;
testCase.minSpanY = minTargetHeight;
testCase.type = solution.area() == 1 ? "icon" : "widget";
return testCase;
}
/**
* Makes sure the final solution has valid integrity meaning that the number and sizes of
* widgets is the expect and there are no missing widgets.
*/
public boolean validateIntegrity(CellLayoutBoard startBoard, CellLayoutBoard finishBoard,
ReorderAlgorithmUnitTestCase testCase) {
if (!testCase.isValidSolution) {
// if we couldn't place the widget then the solution should be identical to the board
return startBoard.compareTo(finishBoard) == 0;
}
WidgetRect addedWidget = finishBoard.getWidgetOfType(MAIN_WIDGET_TYPE);
finishBoard.removeItem(MAIN_WIDGET_TYPE);
Comparator<CellLayoutBoard> comparator = new PermutedBoardComparator();
if (comparator.compare(startBoard, finishBoard) != 0) {
return false;
}
return addedWidget.getSpanX() >= testCase.minSpanX
&& addedWidget.getSpanY() >= testCase.minSpanY;
}
private static List<ReorderAlgorithmUnitTestCase> getTestCases(String testPath)
throws IOException {
List<ReorderAlgorithmUnitTestCase> cases = new ArrayList<>();
Iterator<CellLayoutTestCaseReader.TestSection> iterableSection =
CellLayoutTestCaseReader.readFromFile(testPath).parse().iterator();
while (iterableSection.hasNext()) {
cases.add(ReorderAlgorithmUnitTestCase.readNextCase(iterableSection));
}
return cases;
}
}
@@ -1,153 +0,0 @@
/*
* Copyright (C) 2023 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.launcher3.celllayout;
import com.android.launcher3.celllayout.board.CellLayoutBoard;
import java.util.Iterator;
/**
* Represents a test case for {@code ReorderAlgorithmUnitTest}. The test cases are generated from
* text, an example of a test is the following:
*
* board: 10x8
* aaaaaaaaai
* bbbbbcciii
* ---------f
* ---------f
* ---------f
* ---------i
* iiddddddii
* iieeiiiiii
* arguments: 2 5 7 1 3 1 widget valid
* board: 10x8
* bbbbbbbbbi
* eeeeecciii
* ---------a
* ---------a
* ---------a
* --zzzzzzzi
* iiddddddii
* iiffiiiiii
*
*
* This represents a Workspace boards and a dragged widget that wants to be dropped on the
* workspace. The endBoard represents the result from such drag
* The first board is the startBoard, the arguments are as follow: cellX, cellY, widget spanX,
* widget spanY, minimum spanX, minimum spanX, type of object being drag (icon, widget, folder ),
* if the resulting board is a valid solution or not reorder was found.
*
* For more information on how to read the board please go to the text file
* reorder_algorithm_test_cases
*/
public class ReorderAlgorithmUnitTestCase {
CellLayoutBoard startBoard;
int x, y, spanX, spanY, minSpanX, minSpanY;
String type;
boolean isValidSolution;
CellLayoutBoard endBoard;
public static ReorderAlgorithmUnitTestCase readNextCase(
Iterator<CellLayoutTestCaseReader.TestSection> sections) {
ReorderAlgorithmUnitTestCase testCase = new ReorderAlgorithmUnitTestCase();
CellLayoutTestCaseReader.Board startBoard =
(CellLayoutTestCaseReader.Board) sections.next();
testCase.startBoard = CellLayoutBoard.boardFromString(startBoard.board);
CellLayoutTestCaseReader.Arguments arguments =
(CellLayoutTestCaseReader.Arguments) sections.next();
testCase.x = Integer.parseInt(arguments.arguments[0]);
testCase.y = Integer.parseInt(arguments.arguments[1]);
testCase.spanX = Integer.parseInt(arguments.arguments[2]);
testCase.spanY = Integer.parseInt(arguments.arguments[3]);
testCase.minSpanX = Integer.parseInt(arguments.arguments[4]);
testCase.minSpanY = Integer.parseInt(arguments.arguments[5]);
testCase.type = arguments.arguments[6];
testCase.isValidSolution = arguments.arguments[7].compareTo("valid") == 0;
CellLayoutTestCaseReader.Board endBoard = (CellLayoutTestCaseReader.Board) sections.next();
testCase.endBoard = CellLayoutBoard.boardFromString(endBoard.board);
return testCase;
}
public CellLayoutBoard getStartBoard() {
return startBoard;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getSpanX() {
return spanX;
}
public void setSpanX(int spanX) {
this.spanX = spanX;
}
public int getSpanY() {
return spanY;
}
public void setSpanY(int spanY) {
this.spanY = spanY;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isValidSolution() {
return isValidSolution;
}
public void setValidSolution(boolean validSolution) {
isValidSolution = validSolution;
}
public CellLayoutBoard getEndBoard() {
return endBoard;
}
public void setEndBoard(CellLayoutBoard endBoard) {
this.endBoard = endBoard;
}
@Override
public String toString() {
String valid = isValidSolution ? "valid" : "invalid";
return startBoard + "arguments: " + x + " " + y + " " + spanX + " " + spanY + " " + minSpanX
+ " " + minSpanY + " " + type + " " + valid + "\n" + endBoard;
}
}
@@ -1,201 +0,0 @@
/*
* Copyright (C) 2024 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.launcher3.celllayout
import android.content.Context
import android.util.ArrayMap
import android.view.View
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.launcher3.CellLayout
import com.android.launcher3.Reorderable
import com.android.launcher3.celllayout.ReorderPreviewAnimation.Companion.HINT_DURATION
import com.android.launcher3.celllayout.ReorderPreviewAnimation.Companion.PREVIEW_DURATION
import com.android.launcher3.util.ActivityContextWrapper
import com.android.launcher3.util.MultiTranslateDelegate
import com.android.launcher3.util.MultiTranslateDelegate.INDEX_REORDER_BOUNCE_OFFSET
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
class Mock(context: Context) : Reorderable, View(context) {
init {
mLeft = 0
mRight = 100
}
private val translateDelegate = MultiTranslateDelegate(this)
private var scaleForReorderBounce = 1f
override fun getTranslateDelegate(): MultiTranslateDelegate {
return translateDelegate
}
override fun setReorderBounceScale(scale: Float) {
scaleForReorderBounce = scale
}
override fun getReorderBounceScale(): Float {
return scaleForReorderBounce
}
fun toAnimationValues(): AnimationValues {
return AnimationValues(
(translateDelegate.getTranslationX(INDEX_REORDER_BOUNCE_OFFSET).value * 100).toInt(),
(translateDelegate.getTranslationY(INDEX_REORDER_BOUNCE_OFFSET).value * 100).toInt(),
(scaleForReorderBounce * 100).toInt()
)
}
}
data class AnimationValues(val dx: Int, val dy: Int, val scale: Int)
@SmallTest
@RunWith(AndroidJUnit4::class)
class ReorderPreviewAnimationTest {
@JvmField @Rule var cellLayoutBuilder = UnitTestCellLayoutBuilderRule()
private val applicationContext =
ActivityContextWrapper(ApplicationProvider.getApplicationContext())
/**
* @param animationTime the time of the animation we will check the state against.
* @param mode the mode either PREVIEW_DURATION or HINT_DURATION.
* @param valueToMatch the state of the animation we expect to see at animationTime.
* @param isAfterReverse if the animation is finish and we are returning to the beginning.
*/
private fun testAnimationAtGivenProgress(
animationTime: Int,
mode: Int,
valueToMatch: AnimationValues
) {
val view = Mock(applicationContext)
val cellLayout = cellLayoutBuilder.createCellLayout(100, 100, false)
val map = ArrayMap<Reorderable, ReorderPreviewAnimation<Mock>>()
val animation =
ReorderPreviewAnimation(
view,
mode,
3,
3,
1,
7,
1,
1,
CellLayout.REORDER_PREVIEW_MAGNITUDE,
cellLayout,
map
)
// Remove delay because it's randomly generated and it can slightly change the results.
animation.animator.startDelay = 0
animation.animator.currentPlayTime = animationTime.toLong()
val currentValue = view.toAnimationValues()
assert(currentValue == valueToMatch) {
"The value of the animation $currentValue at $animationTime time (milliseconds) doesn't match the given value $valueToMatch"
}
}
@Test
fun testAnimationModePreview() {
testAnimationAtGivenProgress(
PREVIEW_DURATION * 0,
ReorderPreviewAnimation.MODE_PREVIEW,
AnimationValues(dx = 0, dy = 0, scale = 100)
)
testAnimationAtGivenProgress(
PREVIEW_DURATION / 2,
ReorderPreviewAnimation.MODE_PREVIEW,
AnimationValues(dx = 2, dy = -5, scale = 98)
)
testAnimationAtGivenProgress(
PREVIEW_DURATION / 3,
ReorderPreviewAnimation.MODE_PREVIEW,
AnimationValues(dx = 1, dy = -2, scale = 99)
)
testAnimationAtGivenProgress(
PREVIEW_DURATION,
ReorderPreviewAnimation.MODE_PREVIEW,
AnimationValues(dx = 5, dy = -10, scale = 96)
)
// MODE_PREVIEW oscillates and goes back to 0,0
testAnimationAtGivenProgress(
PREVIEW_DURATION * 2,
ReorderPreviewAnimation.MODE_PREVIEW,
AnimationValues(dx = 0, dy = 0, scale = 100)
)
testAnimationAtGivenProgress(
PREVIEW_DURATION * 99,
ReorderPreviewAnimation.MODE_PREVIEW,
AnimationValues(dx = 5, dy = -10, scale = 96)
)
testAnimationAtGivenProgress(
PREVIEW_DURATION * 98,
ReorderPreviewAnimation.MODE_PREVIEW,
AnimationValues(dx = 0, dy = 0, scale = 100)
)
testAnimationAtGivenProgress(
(PREVIEW_DURATION * 1.5).toInt(),
ReorderPreviewAnimation.MODE_PREVIEW,
AnimationValues(dx = 2, dy = -5, scale = 98)
)
}
@Test
fun testAnimationModeHint() {
testAnimationAtGivenProgress(
HINT_DURATION * 0,
ReorderPreviewAnimation.MODE_HINT,
AnimationValues(dx = 0, dy = 0, scale = 100)
)
testAnimationAtGivenProgress(
HINT_DURATION,
ReorderPreviewAnimation.MODE_HINT,
AnimationValues(dx = -5, dy = 10, scale = 96)
)
testAnimationAtGivenProgress(
HINT_DURATION / 2,
ReorderPreviewAnimation.MODE_HINT,
AnimationValues(dx = -2, dy = 5, scale = 98)
)
testAnimationAtGivenProgress(
HINT_DURATION / 3,
ReorderPreviewAnimation.MODE_HINT,
AnimationValues(dx = -1, dy = 2, scale = 99)
)
testAnimationAtGivenProgress(
HINT_DURATION,
ReorderPreviewAnimation.MODE_HINT,
AnimationValues(dx = -5, dy = 10, scale = 96)
)
// After one cycle the animationValues should always be the top values and don't cycle.
testAnimationAtGivenProgress(
HINT_DURATION * 2,
ReorderPreviewAnimation.MODE_HINT,
AnimationValues(dx = -5, dy = 10, scale = 96)
)
testAnimationAtGivenProgress(
HINT_DURATION * 99,
ReorderPreviewAnimation.MODE_HINT,
AnimationValues(dx = -5, dy = 10, scale = 96)
)
}
}
@@ -1,47 +0,0 @@
/*
* Copyright (C) 2022 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.launcher3.celllayout;
import android.graphics.Point;
import com.android.launcher3.celllayout.board.CellLayoutBoard;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ReorderTestCase {
public List<CellLayoutBoard> mStart;
public Point moveMainTo;
public List<List<CellLayoutBoard>> mEnd;
public ReorderTestCase(List<CellLayoutBoard> start, Point moveMainTo,
List<CellLayoutBoard>... end) {
mStart = start;
this.moveMainTo = moveMainTo;
mEnd = Arrays.asList(end);
}
public ReorderTestCase(String start, Point moveMainTo, String ... end) {
mStart = CellLayoutBoard.boardListFromString(start);
this.moveMainTo = moveMainTo;
mEnd = Arrays
.asList(end)
.stream()
.map(CellLayoutBoard::boardListFromString)
.collect(Collectors.toList());
}
}
@@ -1,96 +0,0 @@
/*
* Copyright (C) 2024 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.launcher3.celllayout
import android.content.Context
import android.graphics.Point
import android.view.View
import androidx.test.core.app.ApplicationProvider
import com.android.launcher3.CellLayout
import com.android.launcher3.CellLayoutContainer
import com.android.launcher3.DeviceProfile
import com.android.launcher3.InvariantDeviceProfile
import com.android.launcher3.MultipageCellLayout
import com.android.launcher3.util.ActivityContextWrapper
import org.junit.rules.TestWatcher
import org.junit.runner.Description
/**
* Create CellLayouts to be used in Unit testing and make sure to set the DeviceProfile back to
* normal.
*/
class UnitTestCellLayoutBuilderRule : TestWatcher() {
private var prevNumColumns = 0
private var prevNumRows = 0
private val applicationContext =
ActivityContextWrapper(ApplicationProvider.getApplicationContext())
private val container =
object : CellLayoutContainer {
override fun getCellLayoutId(cellLayout: CellLayout): Int = 0
override fun getCellLayoutIndex(cellLayout: CellLayout): Int = 0
override fun getPanelCount(): Int = 1
override fun getPageDescription(pageIndex: Int): String = ""
}
override fun starting(description: Description?) {
val dp = getDeviceProfile()
prevNumColumns = dp.inv.numColumns
prevNumRows = dp.inv.numRows
}
override fun finished(description: Description?) {
val dp = getDeviceProfile()
dp.inv.numColumns = prevNumColumns
dp.inv.numRows = prevNumRows
}
fun createCellLayout(width: Int, height: Int, isMulti: Boolean): CellLayout {
val dp = getDeviceProfile()
// modify the device profile.
dp.inv.numColumns = if (isMulti) width / 2 else width
dp.inv.numRows = height
dp.cellLayoutBorderSpacePx = Point(0, 0)
val cl =
if (isMulti) MultipageCellLayout(getWrappedContext(applicationContext, dp))
else CellLayout(getWrappedContext(applicationContext, dp), container)
// I put a very large number for width and height so that all the items can fit, it doesn't
// need to be exact, just bigger than the sum of cell border
cl.measure(
View.MeasureSpec.makeMeasureSpec(10000, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(10000, View.MeasureSpec.EXACTLY)
)
return cl
}
private fun getDeviceProfile(): DeviceProfile =
InvariantDeviceProfile.INSTANCE[applicationContext].getDeviceProfile(applicationContext)
.copy(applicationContext)
private fun getWrappedContext(context: Context, dp: DeviceProfile): Context {
return object : ActivityContextWrapper(context) {
override fun getDeviceProfile(): DeviceProfile {
return dp
}
}
}
}
@@ -1,22 +0,0 @@
/*
* Copyright (C) 2023 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.launcher3.celllayout.testgenerator
import java.util.Random
abstract class DeterministicRandomGenerator(private val generator: Random) {
fun getRandom(start: Int, end: Int): Int = start + (if (end == 0) 0 else generator.nextInt(end))
}
@@ -1,73 +0,0 @@
/*
* Copyright (C) 2023 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.launcher3.celllayout.testgenerator
import android.graphics.Rect
import com.android.launcher3.celllayout.board.CellLayoutBoard
import java.util.Random
/** Generates a random CellLayoutBoard. */
open class RandomBoardGenerator(generator: Random) : DeterministicRandomGenerator(generator) {
companion object {
// This is the max number of widgets because we encode the widgets as letters A-Z and we
// already have some of those letter used by other things so 22 is a safe number
val MAX_NUMBER_OF_WIDGETS = 22
}
/**
* @param remainingEmptySpaces the maximum number of spaces we will fill with icons and widgets
* meaning that if the number is 100 we will try to fill the board with at most 100 spaces
* usually less than 100.
* @return a randomly generated board filled with icons and widgets.
*/
open fun generateBoard(width: Int, height: Int, remainingEmptySpaces: Int): CellLayoutBoard {
val cellLayoutBoard = CellLayoutBoard(width, height)
return fillBoard(cellLayoutBoard, Rect(0, 0, width, height), remainingEmptySpaces)
}
protected fun fillBoard(
board: CellLayoutBoard,
area: Rect,
remainingEmptySpacesArg: Int
): CellLayoutBoard {
var remainingEmptySpaces = remainingEmptySpacesArg
if (area.height() * area.width() <= 0) return board
val width = getRandom(1, area.width())
val height = getRandom(1, area.height())
val x = area.left + getRandom(0, area.width() - width)
val y = area.top + getRandom(0, area.height() - height)
if (remainingEmptySpaces > 0) {
remainingEmptySpaces -= width * height
}
if (board.widgets.size <= MAX_NUMBER_OF_WIDGETS && width * height > 1) {
board.addWidget(x, y, width, height)
} else {
board.addIcon(x, y)
}
if (remainingEmptySpaces < 0) {
// optimization, no need to keep going
return board
}
fillBoard(board, Rect(area.left, area.top, area.right, y), remainingEmptySpaces)
fillBoard(board, Rect(area.left, y, x, area.bottom), remainingEmptySpaces)
fillBoard(board, Rect(x, y + height, area.right, area.bottom), remainingEmptySpaces)
fillBoard(board, Rect(x + width, y, area.right, y + height), remainingEmptySpaces)
return board
}
}
@@ -1,36 +0,0 @@
/*
* Copyright (C) 2023 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.launcher3.celllayout.testgenerator
import android.graphics.Rect
import com.android.launcher3.celllayout.board.CellLayoutBoard
import java.util.Random
class RandomMultiBoardGenerator(generator: Random) : RandomBoardGenerator(generator) {
override fun generateBoard(
width: Int,
height: Int,
remainingEmptySpaces: Int
): CellLayoutBoard {
val cellLayoutBoard = CellLayoutBoard(width, height)
fillBoard(cellLayoutBoard, Rect(0, 0, width / 2, height), remainingEmptySpaces / 2)
return fillBoard(
cellLayoutBoard,
Rect(width / 2, 0, width, height),
remainingEmptySpaces / 2
)
}
}