LauncherInstrumentation.java 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416
  1. /*
  2. * Copyright (C) 2018 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.android.launcher3.tapl;
  17. import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
  18. import static android.content.pm.PackageManager.DONT_KILL_APP;
  19. import static android.content.pm.PackageManager.MATCH_ALL;
  20. import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
  21. import static com.android.launcher3.tapl.TestHelpers.getOverviewPackageName;
  22. import static com.android.launcher3.testing.TestProtocol.NORMAL_STATE_ORDINAL;
  23. import android.app.ActivityManager;
  24. import android.app.Instrumentation;
  25. import android.app.UiAutomation;
  26. import android.content.ComponentName;
  27. import android.content.ContentProviderClient;
  28. import android.content.ContentResolver;
  29. import android.content.Context;
  30. import android.content.pm.PackageManager;
  31. import android.content.pm.ProviderInfo;
  32. import android.content.res.Resources;
  33. import android.graphics.Insets;
  34. import android.graphics.Point;
  35. import android.graphics.Rect;
  36. import android.net.Uri;
  37. import android.os.Bundle;
  38. import android.os.Parcelable;
  39. import android.os.RemoteException;
  40. import android.os.SystemClock;
  41. import android.text.TextUtils;
  42. import android.util.Log;
  43. import android.view.InputDevice;
  44. import android.view.MotionEvent;
  45. import android.view.Surface;
  46. import android.view.ViewConfiguration;
  47. import android.view.WindowManager;
  48. import android.view.accessibility.AccessibilityEvent;
  49. import androidx.annotation.NonNull;
  50. import androidx.test.InstrumentationRegistry;
  51. import androidx.test.uiautomator.By;
  52. import androidx.test.uiautomator.BySelector;
  53. import androidx.test.uiautomator.Configurator;
  54. import androidx.test.uiautomator.Direction;
  55. import androidx.test.uiautomator.StaleObjectException;
  56. import androidx.test.uiautomator.UiDevice;
  57. import androidx.test.uiautomator.UiObject2;
  58. import androidx.test.uiautomator.Until;
  59. import com.android.launcher3.ResourceUtils;
  60. import com.android.launcher3.testing.TestProtocol;
  61. import com.android.systemui.shared.system.QuickStepContract;
  62. import org.junit.Assert;
  63. import java.io.ByteArrayOutputStream;
  64. import java.io.IOException;
  65. import java.lang.ref.WeakReference;
  66. import java.util.ArrayList;
  67. import java.util.Collection;
  68. import java.util.Collections;
  69. import java.util.Deque;
  70. import java.util.LinkedList;
  71. import java.util.List;
  72. import java.util.concurrent.TimeoutException;
  73. import java.util.function.Consumer;
  74. import java.util.function.Function;
  75. import java.util.function.Supplier;
  76. import java.util.regex.Pattern;
  77. import java.util.stream.Collectors;
  78. /**
  79. * The main tapl object. The only object that can be explicitly constructed by the using code. It
  80. * produces all other objects.
  81. */
  82. public final class LauncherInstrumentation {
  83. private static final String TAG = "Tapl";
  84. private static final int ZERO_BUTTON_STEPS_FROM_BACKGROUND_TO_HOME = 20;
  85. private static final int GESTURE_STEP_MS = 16;
  86. private static long START_TIME = System.currentTimeMillis();
  87. private static final Pattern EVENT_TOUCH_DOWN = getTouchEventPattern("ACTION_DOWN");
  88. private static final Pattern EVENT_TOUCH_UP = getTouchEventPattern("ACTION_UP");
  89. private static final Pattern EVENT_TOUCH_CANCEL = getTouchEventPattern("ACTION_CANCEL");
  90. private static final Pattern EVENT_PILFER_POINTERS = Pattern.compile("pilferPointers");
  91. static final Pattern EVENT_START = Pattern.compile("start:");
  92. static final Pattern EVENT_TOUCH_DOWN_TIS = getTouchEventPatternTIS("ACTION_DOWN");
  93. static final Pattern EVENT_TOUCH_UP_TIS = getTouchEventPatternTIS("ACTION_UP");
  94. // Types for launcher containers that the user is interacting with. "Background" is a
  95. // pseudo-container corresponding to inactive launcher covered by another app.
  96. public enum ContainerType {
  97. WORKSPACE, ALL_APPS, OVERVIEW, WIDGETS, BACKGROUND, FALLBACK_OVERVIEW
  98. }
  99. public enum NavigationModel {ZERO_BUTTON, TWO_BUTTON, THREE_BUTTON}
  100. // Where the gesture happens: outside of Launcher, inside or from inside to outside and
  101. // whether the gesture recognition triggers pilfer.
  102. public enum GestureScope {
  103. OUTSIDE_WITHOUT_PILFER, OUTSIDE_WITH_PILFER, INSIDE, INSIDE_TO_OUTSIDE
  104. }
  105. ;
  106. // Base class for launcher containers.
  107. static abstract class VisibleContainer {
  108. protected final LauncherInstrumentation mLauncher;
  109. protected VisibleContainer(LauncherInstrumentation launcher) {
  110. mLauncher = launcher;
  111. launcher.setActiveContainer(this);
  112. }
  113. protected abstract ContainerType getContainerType();
  114. /**
  115. * Asserts that the launcher is in the mode matching 'this' object.
  116. *
  117. * @return UI object for the container.
  118. */
  119. final UiObject2 verifyActiveContainer() {
  120. mLauncher.assertTrue("Attempt to use a stale container",
  121. this == sActiveContainer.get());
  122. return mLauncher.verifyContainerType(getContainerType());
  123. }
  124. }
  125. public interface Closable extends AutoCloseable {
  126. void close();
  127. }
  128. private static final String WORKSPACE_RES_ID = "workspace";
  129. private static final String APPS_RES_ID = "apps_view";
  130. private static final String OVERVIEW_RES_ID = "overview_panel";
  131. private static final String WIDGETS_RES_ID = "widgets_list_view";
  132. private static final String CONTEXT_MENU_RES_ID = "deep_shortcuts_container";
  133. public static final int WAIT_TIME_MS = 10000;
  134. private static final String SYSTEMUI_PACKAGE = "com.android.systemui";
  135. private static final String ANDROID_PACKAGE = "android";
  136. private static WeakReference<VisibleContainer> sActiveContainer = new WeakReference<>(null);
  137. private final UiDevice mDevice;
  138. private final Instrumentation mInstrumentation;
  139. private int mExpectedRotation = Surface.ROTATION_0;
  140. private final Uri mTestProviderUri;
  141. private final Deque<String> mDiagnosticContext = new LinkedList<>();
  142. private Function<Long, String> mSystemHealthSupplier;
  143. private Consumer<ContainerType> mOnSettledStateAction;
  144. private LogEventChecker mEventChecker;
  145. private boolean mCheckEventsForSuccessfulGestures = false;
  146. private Runnable mOnLauncherCrashed;
  147. private static Pattern getTouchEventPattern(String prefix, String action) {
  148. // The pattern includes sanity checks that we don't get a multi-touch events or other
  149. // surprises.
  150. return Pattern.compile(
  151. prefix + ": MotionEvent.*?action=" + action + ".*?id\\[0\\]=0"
  152. + ".*?toolType\\[0\\]=TOOL_TYPE_FINGER.*?buttonState=0.*?pointerCount=1");
  153. }
  154. private static Pattern getTouchEventPattern(String action) {
  155. return getTouchEventPattern("Touch event", action);
  156. }
  157. private static Pattern getTouchEventPatternTIS(String action) {
  158. return getTouchEventPattern("TouchInteractionService.onInputEvent", action);
  159. }
  160. /**
  161. * Constructs the root of TAPL hierarchy. You get all other objects from it.
  162. */
  163. public LauncherInstrumentation() {
  164. this(InstrumentationRegistry.getInstrumentation());
  165. }
  166. /**
  167. * Constructs the root of TAPL hierarchy. You get all other objects from it.
  168. * Deprecated: use the constructor without parameters instead.
  169. */
  170. @Deprecated
  171. public LauncherInstrumentation(Instrumentation instrumentation) {
  172. mInstrumentation = instrumentation;
  173. mDevice = UiDevice.getInstance(instrumentation);
  174. // Launcher should run in test harness so that custom accessibility protocol between
  175. // Launcher and TAPL is enabled. In-process tests enable this protocol with a direct call
  176. // into Launcher.
  177. assertTrue("Device must run in a test harness",
  178. TestHelpers.isInLauncherProcess() || ActivityManager.isRunningInTestHarness());
  179. final String testPackage = getContext().getPackageName();
  180. final String targetPackage = mInstrumentation.getTargetContext().getPackageName();
  181. // Launcher package. As during inproc tests the tested launcher may not be selected as the
  182. // current launcher, choosing target package for inproc. For out-of-proc, use the installed
  183. // launcher package.
  184. final String authorityPackage = testPackage.equals(targetPackage) ?
  185. getLauncherPackageName() :
  186. targetPackage;
  187. String testProviderAuthority = authorityPackage + ".TestInfo";
  188. mTestProviderUri = new Uri.Builder()
  189. .scheme(ContentResolver.SCHEME_CONTENT)
  190. .authority(testProviderAuthority)
  191. .build();
  192. mInstrumentation.getUiAutomation().grantRuntimePermission(
  193. testPackage, "android.permission.WRITE_SECURE_SETTINGS");
  194. PackageManager pm = getContext().getPackageManager();
  195. ProviderInfo pi = pm.resolveContentProvider(
  196. testProviderAuthority, MATCH_ALL | MATCH_DISABLED_COMPONENTS);
  197. assertNotNull("Cannot find content provider for " + testProviderAuthority, pi);
  198. ComponentName cn = new ComponentName(pi.packageName, pi.name);
  199. if (pm.getComponentEnabledSetting(cn) != COMPONENT_ENABLED_STATE_ENABLED) {
  200. if (TestHelpers.isInLauncherProcess()) {
  201. getContext().getPackageManager().setComponentEnabledSetting(
  202. cn, COMPONENT_ENABLED_STATE_ENABLED, DONT_KILL_APP);
  203. } else {
  204. try {
  205. mDevice.executeShellCommand("pm enable " + cn.flattenToString());
  206. } catch (IOException e) {
  207. fail(e.toString());
  208. }
  209. }
  210. }
  211. }
  212. public void enableCheckEventsForSuccessfulGestures() {
  213. mCheckEventsForSuccessfulGestures = true;
  214. }
  215. public void setOnLauncherCrashed(Runnable onLauncherCrashed) {
  216. mOnLauncherCrashed = onLauncherCrashed;
  217. }
  218. Context getContext() {
  219. return mInstrumentation.getContext();
  220. }
  221. Bundle getTestInfo(String request) {
  222. try (ContentProviderClient client = getContext().getContentResolver()
  223. .acquireContentProviderClient(mTestProviderUri)) {
  224. return client.call(request, null, null);
  225. } catch (RemoteException e) {
  226. throw new RuntimeException(e);
  227. }
  228. }
  229. Insets getTargetInsets() {
  230. return getTestInfo(TestProtocol.REQUEST_WINDOW_INSETS)
  231. .getParcelable(TestProtocol.TEST_INFO_RESPONSE_FIELD);
  232. }
  233. void setActiveContainer(VisibleContainer container) {
  234. sActiveContainer = new WeakReference<>(container);
  235. }
  236. public NavigationModel getNavigationModel() {
  237. final Context baseContext = mInstrumentation.getTargetContext();
  238. try {
  239. // Workaround, use constructed context because both the instrumentation context and the
  240. // app context are not constructed with resources that take overlays into account
  241. final Context ctx = baseContext.createPackageContext(getLauncherPackageName(), 0);
  242. for (int i = 0; i < 100; ++i) {
  243. final int currentInteractionMode = getCurrentInteractionMode(ctx);
  244. final NavigationModel model = getNavigationModel(currentInteractionMode);
  245. log("Interaction mode = " + currentInteractionMode + " (" + model + ")");
  246. if (model != null) return model;
  247. Thread.sleep(100);
  248. }
  249. fail("Can't detect navigation mode");
  250. } catch (Exception e) {
  251. fail(e.toString());
  252. }
  253. return NavigationModel.THREE_BUTTON;
  254. }
  255. public static NavigationModel getNavigationModel(int currentInteractionMode) {
  256. if (QuickStepContract.isGesturalMode(currentInteractionMode)) {
  257. return NavigationModel.ZERO_BUTTON;
  258. } else if (QuickStepContract.isSwipeUpMode(currentInteractionMode)) {
  259. return NavigationModel.TWO_BUTTON;
  260. } else if (QuickStepContract.isLegacyMode(currentInteractionMode)) {
  261. return NavigationModel.THREE_BUTTON;
  262. }
  263. return null;
  264. }
  265. static void log(String message) {
  266. Log.d(TAG, message);
  267. }
  268. Closable addContextLayer(String piece) {
  269. mDiagnosticContext.addLast(piece);
  270. log("Entering context: " + piece);
  271. return () -> {
  272. log("Leaving context: " + piece);
  273. mDiagnosticContext.removeLast();
  274. };
  275. }
  276. public void dumpViewHierarchy() {
  277. final ByteArrayOutputStream stream = new ByteArrayOutputStream();
  278. try {
  279. mDevice.dumpWindowHierarchy(stream);
  280. stream.flush();
  281. stream.close();
  282. for (String line : stream.toString().split("\\r?\\n")) {
  283. Log.e(TAG, line.trim());
  284. }
  285. } catch (IOException e) {
  286. Log.e(TAG, "error dumping XML to logcat", e);
  287. }
  288. }
  289. private String getSystemAnomalyMessage() {
  290. try {
  291. {
  292. final StringBuilder sb = new StringBuilder();
  293. UiObject2 object = mDevice.findObject(By.res("android", "alertTitle"));
  294. if (object != null) {
  295. sb.append("TITLE: ").append(object.getText());
  296. }
  297. object = mDevice.findObject(By.res("android", "message"));
  298. if (object != null) {
  299. sb.append(" PACKAGE: ").append(object.getApplicationPackage())
  300. .append(" MESSAGE: ").append(object.getText());
  301. }
  302. if (sb.length() != 0) {
  303. return "System alert popup is visible: " + sb;
  304. }
  305. }
  306. if (hasSystemUiObject("keyguard_status_view")) return "Phone is locked";
  307. if (!mDevice.hasObject(By.textStartsWith(""))) return "Screen is empty";
  308. final String navigationModeError = getNavigationModeMismatchError();
  309. if (navigationModeError != null) return navigationModeError;
  310. } catch (Throwable e) {
  311. Log.w(TAG, "getSystemAnomalyMessage failed", e);
  312. }
  313. return null;
  314. }
  315. public void checkForAnomaly() {
  316. final String systemAnomalyMessage = getSystemAnomalyMessage();
  317. if (systemAnomalyMessage != null) {
  318. Assert.fail(formatSystemHealthMessage(formatErrorWithEvents(
  319. "http://go/tapl : Tests are broken by a non-Launcher system error: "
  320. + systemAnomalyMessage, false)));
  321. }
  322. }
  323. private String getVisiblePackages() {
  324. return mDevice.findObjects(By.textStartsWith(""))
  325. .stream()
  326. .map(LauncherInstrumentation::getApplicationPackageSafe)
  327. .distinct()
  328. .filter(pkg -> pkg != null && !"com.android.systemui".equals(pkg))
  329. .collect(Collectors.joining(", "));
  330. }
  331. private static String getApplicationPackageSafe(UiObject2 object) {
  332. try {
  333. return object.getApplicationPackage();
  334. } catch (StaleObjectException e) {
  335. // We are looking at all object in the system; external ones can suddenly go away.
  336. return null;
  337. }
  338. }
  339. private String getVisibleStateMessage() {
  340. if (hasLauncherObject(CONTEXT_MENU_RES_ID)) return "Context Menu";
  341. if (hasLauncherObject(WIDGETS_RES_ID)) return "Widgets";
  342. if (hasLauncherObject(OVERVIEW_RES_ID)) return "Overview";
  343. if (hasLauncherObject(WORKSPACE_RES_ID)) return "Workspace";
  344. if (hasLauncherObject(APPS_RES_ID)) return "AllApps";
  345. return "Background (" + getVisiblePackages() + ")";
  346. }
  347. public void setSystemHealthSupplier(Function<Long, String> supplier) {
  348. this.mSystemHealthSupplier = supplier;
  349. }
  350. public void setOnSettledStateAction(Consumer<ContainerType> onSettledStateAction) {
  351. mOnSettledStateAction = onSettledStateAction;
  352. }
  353. private String formatSystemHealthMessage(String message) {
  354. final String testPackage = getContext().getPackageName();
  355. mInstrumentation.getUiAutomation().grantRuntimePermission(
  356. testPackage, "android.permission.READ_LOGS");
  357. mInstrumentation.getUiAutomation().grantRuntimePermission(
  358. testPackage, "android.permission.PACKAGE_USAGE_STATS");
  359. final String systemHealth = mSystemHealthSupplier != null
  360. ? mSystemHealthSupplier.apply(START_TIME)
  361. : TestHelpers.getSystemHealthMessage(getContext(), START_TIME);
  362. if (systemHealth != null) {
  363. return message
  364. + ",\nperhaps linked to system health problems:\n<<<<<<<<<<<<<<<<<<\n"
  365. + systemHealth + "\n>>>>>>>>>>>>>>>>>>";
  366. }
  367. return message;
  368. }
  369. private String formatErrorWithEvents(String message, boolean checkEvents) {
  370. if (mEventChecker != null) {
  371. final LogEventChecker eventChecker = mEventChecker;
  372. mEventChecker = null;
  373. if (checkEvents) {
  374. final String eventMismatch = eventChecker.verify(0, false);
  375. if (eventMismatch != null) {
  376. message = message + ", having produced " + eventMismatch;
  377. }
  378. } else {
  379. eventChecker.finishNoWait();
  380. }
  381. }
  382. dumpDiagnostics();
  383. log("Hierarchy dump for: " + message);
  384. dumpViewHierarchy();
  385. return message;
  386. }
  387. private void dumpDiagnostics() {
  388. Log.e("b/156287114", "Input:");
  389. logShellCommand("dumpsys input");
  390. Log.e("b/156287114", "TIS:");
  391. logShellCommand("dumpsys activity service TouchInteractionService");
  392. }
  393. private void logShellCommand(String command) {
  394. try {
  395. for (String line : mDevice.executeShellCommand(command).split("\\n")) {
  396. SystemClock.sleep(10);
  397. Log.d("b/156287114", line);
  398. }
  399. } catch (IOException e) {
  400. Log.d("b/156287114", "Failed to execute " + command);
  401. }
  402. }
  403. private void fail(String message) {
  404. checkForAnomaly();
  405. Assert.fail(formatSystemHealthMessage(formatErrorWithEvents(
  406. "http://go/tapl : " + getContextDescription() + message
  407. + " (visible state: " + getVisibleStateMessage() + ")", true)));
  408. }
  409. private String getContextDescription() {
  410. return mDiagnosticContext.isEmpty() ? "" : String.join(", ", mDiagnosticContext) + "; ";
  411. }
  412. void assertTrue(String message, boolean condition) {
  413. if (!condition) {
  414. fail(message);
  415. }
  416. }
  417. void assertNotNull(String message, Object object) {
  418. assertTrue(message, object != null);
  419. }
  420. private void failEquals(String message, Object actual) {
  421. fail(message + ". " + "Actual: " + actual);
  422. }
  423. private void assertEquals(String message, int expected, int actual) {
  424. if (expected != actual) {
  425. fail(message + " expected: " + expected + " but was: " + actual);
  426. }
  427. }
  428. void assertEquals(String message, String expected, String actual) {
  429. if (!TextUtils.equals(expected, actual)) {
  430. fail(message + " expected: '" + expected + "' but was: '" + actual + "'");
  431. }
  432. }
  433. void assertEquals(String message, long expected, long actual) {
  434. if (expected != actual) {
  435. fail(message + " expected: " + expected + " but was: " + actual);
  436. }
  437. }
  438. void assertNotEquals(String message, int unexpected, int actual) {
  439. if (unexpected == actual) {
  440. failEquals(message, actual);
  441. }
  442. }
  443. public void setExpectedRotation(int expectedRotation) {
  444. mExpectedRotation = expectedRotation;
  445. }
  446. public String getNavigationModeMismatchError() {
  447. final NavigationModel navigationModel = getNavigationModel();
  448. final boolean hasRecentsButton = hasSystemUiObject("recent_apps");
  449. final boolean hasHomeButton = hasSystemUiObject("home");
  450. if ((navigationModel == NavigationModel.THREE_BUTTON) != hasRecentsButton) {
  451. return "Presence of recents button doesn't match the interaction mode, mode="
  452. + navigationModel.name() + ", hasRecents=" + hasRecentsButton;
  453. }
  454. if ((navigationModel != NavigationModel.ZERO_BUTTON) != hasHomeButton) {
  455. return "Presence of home button doesn't match the interaction mode, mode="
  456. + navigationModel.name() + ", hasHome=" + hasHomeButton;
  457. }
  458. return null;
  459. }
  460. private UiObject2 verifyContainerType(ContainerType containerType) {
  461. waitForLauncherInitialized();
  462. assertEquals("Unexpected display rotation",
  463. mExpectedRotation, mDevice.getDisplayRotation());
  464. // b/148422894
  465. String error = null;
  466. for (int i = 0; i != 600; ++i) {
  467. error = getNavigationModeMismatchError();
  468. if (error == null) break;
  469. sleep(100);
  470. }
  471. assertTrue(error, error == null);
  472. log("verifyContainerType: " + containerType);
  473. final UiObject2 container = verifyVisibleObjects(containerType);
  474. if (mOnSettledStateAction != null) mOnSettledStateAction.accept(containerType);
  475. return container;
  476. }
  477. private UiObject2 verifyVisibleObjects(ContainerType containerType) {
  478. try (Closable c = addContextLayer(
  479. "but the current state is not " + containerType.name())) {
  480. switch (containerType) {
  481. case WORKSPACE: {
  482. if (mDevice.isNaturalOrientation()) {
  483. waitForLauncherObject(APPS_RES_ID);
  484. } else {
  485. waitUntilLauncherObjectGone(APPS_RES_ID);
  486. }
  487. waitUntilLauncherObjectGone(OVERVIEW_RES_ID);
  488. waitUntilLauncherObjectGone(WIDGETS_RES_ID);
  489. return waitForLauncherObject(WORKSPACE_RES_ID);
  490. }
  491. case WIDGETS: {
  492. waitUntilLauncherObjectGone(WORKSPACE_RES_ID);
  493. waitUntilLauncherObjectGone(APPS_RES_ID);
  494. waitUntilLauncherObjectGone(OVERVIEW_RES_ID);
  495. return waitForLauncherObject(WIDGETS_RES_ID);
  496. }
  497. case ALL_APPS: {
  498. waitUntilLauncherObjectGone(WORKSPACE_RES_ID);
  499. waitUntilLauncherObjectGone(OVERVIEW_RES_ID);
  500. waitUntilLauncherObjectGone(WIDGETS_RES_ID);
  501. return waitForLauncherObject(APPS_RES_ID);
  502. }
  503. case OVERVIEW: {
  504. if (hasAllAppsInOverview()) {
  505. waitForLauncherObject(APPS_RES_ID);
  506. } else {
  507. waitUntilLauncherObjectGone(APPS_RES_ID);
  508. }
  509. waitUntilLauncherObjectGone(WORKSPACE_RES_ID);
  510. waitUntilLauncherObjectGone(WIDGETS_RES_ID);
  511. return waitForLauncherObject(OVERVIEW_RES_ID);
  512. }
  513. case FALLBACK_OVERVIEW: {
  514. return waitForFallbackLauncherObject(OVERVIEW_RES_ID);
  515. }
  516. case BACKGROUND: {
  517. waitUntilLauncherObjectGone(WORKSPACE_RES_ID);
  518. waitUntilLauncherObjectGone(APPS_RES_ID);
  519. waitUntilLauncherObjectGone(OVERVIEW_RES_ID);
  520. waitUntilLauncherObjectGone(WIDGETS_RES_ID);
  521. return null;
  522. }
  523. default:
  524. fail("Invalid state: " + containerType);
  525. return null;
  526. }
  527. }
  528. }
  529. public void waitForLauncherInitialized() {
  530. for (int i = 0; i < 100; ++i) {
  531. if (getTestInfo(
  532. TestProtocol.REQUEST_IS_LAUNCHER_INITIALIZED).
  533. getBoolean(TestProtocol.TEST_INFO_RESPONSE_FIELD)) {
  534. return;
  535. }
  536. SystemClock.sleep(100);
  537. }
  538. fail("Launcher didn't initialize");
  539. }
  540. Parcelable executeAndWaitForEvent(Runnable command,
  541. UiAutomation.AccessibilityEventFilter eventFilter, Supplier<String> message) {
  542. try {
  543. final AccessibilityEvent event =
  544. mInstrumentation.getUiAutomation().executeAndWaitForEvent(
  545. command, eventFilter, WAIT_TIME_MS);
  546. assertNotNull("executeAndWaitForEvent returned null (this can't happen)", event);
  547. final Parcelable parcelableData = event.getParcelableData();
  548. event.recycle();
  549. return parcelableData;
  550. } catch (TimeoutException e) {
  551. fail(message.get());
  552. return null;
  553. }
  554. }
  555. /**
  556. * Presses nav bar home button.
  557. *
  558. * @return the Workspace object.
  559. */
  560. public Workspace pressHome() {
  561. try (LauncherInstrumentation.Closable e = eventsCheck()) {
  562. waitForLauncherInitialized();
  563. // Click home, then wait for any accessibility event, then wait until accessibility
  564. // events stop.
  565. // We need waiting for any accessibility event generated after pressing Home because
  566. // otherwise waitForIdle may return immediately in case when there was a big enough
  567. // pause in accessibility events prior to pressing Home.
  568. final String action;
  569. final boolean launcherWasVisible = isLauncherVisible();
  570. if (getNavigationModel() == NavigationModel.ZERO_BUTTON) {
  571. checkForAnomaly();
  572. final Point displaySize = getRealDisplaySize();
  573. if (hasLauncherObject(CONTEXT_MENU_RES_ID)) {
  574. linearGesture(
  575. displaySize.x / 2, displaySize.y - 1,
  576. displaySize.x / 2, 0,
  577. ZERO_BUTTON_STEPS_FROM_BACKGROUND_TO_HOME,
  578. false, GestureScope.INSIDE_TO_OUTSIDE);
  579. try (LauncherInstrumentation.Closable c = addContextLayer(
  580. "Swiped up from context menu to home")) {
  581. waitUntilLauncherObjectGone(CONTEXT_MENU_RES_ID);
  582. }
  583. }
  584. if (hasLauncherObject(WORKSPACE_RES_ID)) {
  585. log(action = "already at home");
  586. } else {
  587. log("Hierarchy before swiping up to home:");
  588. dumpViewHierarchy();
  589. action = "swiping up to home";
  590. try (LauncherInstrumentation.Closable c = addContextLayer(action)) {
  591. swipeToState(
  592. displaySize.x / 2, displaySize.y - 1,
  593. displaySize.x / 2, 0,
  594. ZERO_BUTTON_STEPS_FROM_BACKGROUND_TO_HOME, NORMAL_STATE_ORDINAL,
  595. launcherWasVisible
  596. ? GestureScope.INSIDE_TO_OUTSIDE
  597. : GestureScope.OUTSIDE_WITH_PILFER);
  598. }
  599. }
  600. } else {
  601. log("Hierarchy before clicking home:");
  602. dumpViewHierarchy();
  603. action = "clicking home button";
  604. try (LauncherInstrumentation.Closable c = addContextLayer(action)) {
  605. if (!isLauncher3() && getNavigationModel() == NavigationModel.TWO_BUTTON) {
  606. expectEvent(TestProtocol.SEQUENCE_TIS, EVENT_TOUCH_DOWN_TIS);
  607. expectEvent(TestProtocol.SEQUENCE_TIS, EVENT_TOUCH_UP_TIS);
  608. }
  609. runToState(
  610. waitForSystemUiObject("home")::click,
  611. NORMAL_STATE_ORDINAL,
  612. !hasLauncherObject(WORKSPACE_RES_ID)
  613. && (hasLauncherObject(APPS_RES_ID)
  614. || hasLauncherObject(OVERVIEW_RES_ID)));
  615. }
  616. }
  617. try (LauncherInstrumentation.Closable c = addContextLayer(
  618. "performed action to switch to Home - " + action)) {
  619. return getWorkspace();
  620. }
  621. }
  622. }
  623. boolean isLauncherVisible() {
  624. mDevice.waitForIdle();
  625. return hasLauncherObject(By.textStartsWith(""));
  626. }
  627. /**
  628. * Gets the Workspace object if the current state is "active home", i.e. workspace. Fails if the
  629. * launcher is not in that state.
  630. *
  631. * @return Workspace object.
  632. */
  633. @NonNull
  634. public Workspace getWorkspace() {
  635. try (LauncherInstrumentation.Closable c = addContextLayer("want to get workspace object")) {
  636. return new Workspace(this);
  637. }
  638. }
  639. /**
  640. * Gets the Workspace object if the current state is "background home", i.e. some other app is
  641. * active. Fails if the launcher is not in that state.
  642. *
  643. * @return Background object.
  644. */
  645. @NonNull
  646. public Background getBackground() {
  647. return new Background(this);
  648. }
  649. /**
  650. * Gets the Widgets object if the current state is showing all widgets. Fails if the launcher is
  651. * not in that state.
  652. *
  653. * @return Widgets object.
  654. */
  655. @NonNull
  656. public Widgets getAllWidgets() {
  657. try (LauncherInstrumentation.Closable c = addContextLayer("want to get widgets")) {
  658. return new Widgets(this);
  659. }
  660. }
  661. @NonNull
  662. public AddToHomeScreenPrompt getAddToHomeScreenPrompt() {
  663. try (LauncherInstrumentation.Closable c = addContextLayer("want to get widget cell")) {
  664. return new AddToHomeScreenPrompt(this);
  665. }
  666. }
  667. /**
  668. * Gets the Overview object if the current state is showing the overview panel. Fails if the
  669. * launcher is not in that state.
  670. *
  671. * @return Overview object.
  672. */
  673. @NonNull
  674. public Overview getOverview() {
  675. try (LauncherInstrumentation.Closable c = addContextLayer("want to get overview")) {
  676. return new Overview(this);
  677. }
  678. }
  679. /**
  680. * Gets the All Apps object if the current state is showing the all apps panel opened by swiping
  681. * from workspace. Fails if the launcher is not in that state. Please don't call this method if
  682. * App Apps was opened by swiping up from Overview, as it won't fail and will return an
  683. * incorrect object.
  684. *
  685. * @return All Aps object.
  686. */
  687. @NonNull
  688. public AllApps getAllApps() {
  689. try (LauncherInstrumentation.Closable c = addContextLayer("want to get all apps object")) {
  690. return new AllApps(this);
  691. }
  692. }
  693. /**
  694. * Gets the All Apps object if the current state is showing the all apps panel opened by swiping
  695. * from overview. Fails if the launcher is not in that state. Please don't call this method if
  696. * App Apps was opened by swiping up from home, as it won't fail and will return an
  697. * incorrect object.
  698. *
  699. * @return All Aps object.
  700. */
  701. @NonNull
  702. public AllAppsFromOverview getAllAppsFromOverview() {
  703. try (LauncherInstrumentation.Closable c = addContextLayer("want to get all apps object")) {
  704. return new AllAppsFromOverview(this);
  705. }
  706. }
  707. /**
  708. * Gets the Options Popup Menu object if the current state is showing the popup menu. Fails if
  709. * the launcher is not in that state.
  710. *
  711. * @return Options Popup Menu object.
  712. */
  713. @NonNull
  714. public OptionsPopupMenu getOptionsPopupMenu() {
  715. try (LauncherInstrumentation.Closable c = addContextLayer(
  716. "want to get context menu object")) {
  717. return new OptionsPopupMenu(this);
  718. }
  719. }
  720. void waitUntilLauncherObjectGone(String resId) {
  721. waitUntilGoneBySelector(getLauncherObjectSelector(resId));
  722. }
  723. void waitUntilLauncherObjectGone(BySelector selector) {
  724. waitUntilGoneBySelector(makeLauncherSelector(selector));
  725. }
  726. private void waitUntilGoneBySelector(BySelector launcherSelector) {
  727. assertTrue("Unexpected launcher object visible: " + launcherSelector,
  728. mDevice.wait(Until.gone(launcherSelector),
  729. WAIT_TIME_MS));
  730. }
  731. private boolean hasSystemUiObject(String resId) {
  732. return mDevice.hasObject(By.res(SYSTEMUI_PACKAGE, resId));
  733. }
  734. @NonNull
  735. UiObject2 waitForSystemUiObject(String resId) {
  736. final UiObject2 object = mDevice.wait(
  737. Until.findObject(By.res(SYSTEMUI_PACKAGE, resId)), WAIT_TIME_MS);
  738. assertNotNull("Can't find a systemui object with id: " + resId, object);
  739. return object;
  740. }
  741. @NonNull
  742. List<UiObject2> getObjectsInContainer(UiObject2 container, String resName) {
  743. try {
  744. return container.findObjects(getLauncherObjectSelector(resName));
  745. } catch (StaleObjectException e) {
  746. fail("The container disappeared from screen");
  747. return null;
  748. }
  749. }
  750. @NonNull
  751. UiObject2 waitForObjectInContainer(UiObject2 container, String resName) {
  752. try {
  753. final UiObject2 object = container.wait(
  754. Until.findObject(getLauncherObjectSelector(resName)),
  755. WAIT_TIME_MS);
  756. assertNotNull("Can't find a view in Launcher, id: " + resName + " in container: "
  757. + container.getResourceName(), object);
  758. return object;
  759. } catch (StaleObjectException e) {
  760. fail("The container disappeared from screen");
  761. return null;
  762. }
  763. }
  764. @NonNull
  765. UiObject2 waitForObjectInContainer(UiObject2 container, BySelector selector) {
  766. try {
  767. final UiObject2 object = container.wait(
  768. Until.findObject(selector),
  769. WAIT_TIME_MS);
  770. assertNotNull("Can't find a view in Launcher, id: " + selector + " in container: "
  771. + container.getResourceName(), object);
  772. return object;
  773. } catch (StaleObjectException e) {
  774. fail("The container disappeared from screen");
  775. return null;
  776. }
  777. }
  778. private boolean hasLauncherObject(String resId) {
  779. return mDevice.hasObject(getLauncherObjectSelector(resId));
  780. }
  781. boolean hasLauncherObject(BySelector selector) {
  782. return mDevice.hasObject(makeLauncherSelector(selector));
  783. }
  784. private BySelector makeLauncherSelector(BySelector selector) {
  785. return By.copy(selector).pkg(getLauncherPackageName());
  786. }
  787. @NonNull
  788. UiObject2 waitForLauncherObject(String resName) {
  789. return waitForObjectBySelector(getLauncherObjectSelector(resName));
  790. }
  791. @NonNull
  792. UiObject2 waitForLauncherObject(BySelector selector) {
  793. return waitForObjectBySelector(makeLauncherSelector(selector));
  794. }
  795. @NonNull
  796. UiObject2 tryWaitForLauncherObject(BySelector selector, long timeout) {
  797. return tryWaitForObjectBySelector(makeLauncherSelector(selector), timeout);
  798. }
  799. @NonNull
  800. UiObject2 waitForFallbackLauncherObject(String resName) {
  801. return waitForObjectBySelector(getOverviewObjectSelector(resName));
  802. }
  803. @NonNull
  804. UiObject2 waitForAndroidObject(String resId) {
  805. final UiObject2 object = mDevice.wait(
  806. Until.findObject(By.res(ANDROID_PACKAGE, resId)), WAIT_TIME_MS);
  807. assertNotNull("Can't find a android object with id: " + resId, object);
  808. return object;
  809. }
  810. private UiObject2 waitForObjectBySelector(BySelector selector) {
  811. final UiObject2 object = mDevice.wait(Until.findObject(selector), WAIT_TIME_MS);
  812. assertNotNull("Can't find a view in Launcher, selector: " + selector, object);
  813. return object;
  814. }
  815. private UiObject2 tryWaitForObjectBySelector(BySelector selector, long timeout) {
  816. return mDevice.wait(Until.findObject(selector), timeout);
  817. }
  818. BySelector getLauncherObjectSelector(String resName) {
  819. return By.res(getLauncherPackageName(), resName);
  820. }
  821. BySelector getOverviewObjectSelector(String resName) {
  822. return By.res(getOverviewPackageName(), resName);
  823. }
  824. String getLauncherPackageName() {
  825. return mDevice.getLauncherPackageName();
  826. }
  827. boolean isFallbackOverview() {
  828. return !getOverviewPackageName().equals(getLauncherPackageName());
  829. }
  830. @NonNull
  831. public UiDevice getDevice() {
  832. return mDevice;
  833. }
  834. private static String eventListToString(List<Integer> actualEvents) {
  835. if (actualEvents.isEmpty()) return "no events";
  836. return "["
  837. + actualEvents.stream()
  838. .map(state -> TestProtocol.stateOrdinalToString(state))
  839. .collect(Collectors.joining(", "))
  840. + "]";
  841. }
  842. void runToState(Runnable command, int expectedState, boolean requireEvent) {
  843. if (requireEvent) {
  844. runToState(command, expectedState);
  845. } else {
  846. command.run();
  847. }
  848. }
  849. void runToState(Runnable command, int expectedState) {
  850. final List<Integer> actualEvents = new ArrayList<>();
  851. executeAndWaitForEvent(
  852. command,
  853. event -> isSwitchToStateEvent(event, expectedState, actualEvents),
  854. () -> "Failed to receive an event for the state change: expected ["
  855. + TestProtocol.stateOrdinalToString(expectedState)
  856. + "], actual: " + eventListToString(actualEvents));
  857. }
  858. private boolean isSwitchToStateEvent(
  859. AccessibilityEvent event, int expectedState, List<Integer> actualEvents) {
  860. if (!TestProtocol.SWITCHED_TO_STATE_MESSAGE.equals(event.getClassName())) return false;
  861. final Bundle parcel = (Bundle) event.getParcelableData();
  862. final int actualState = parcel.getInt(TestProtocol.STATE_FIELD);
  863. actualEvents.add(actualState);
  864. return actualState == expectedState;
  865. }
  866. void swipeToState(int startX, int startY, int endX, int endY, int steps, int expectedState,
  867. GestureScope gestureScope) {
  868. runToState(
  869. () -> linearGesture(startX, startY, endX, endY, steps, false, gestureScope),
  870. expectedState);
  871. }
  872. int getBottomGestureSize() {
  873. return ResourceUtils.getNavbarSize(
  874. ResourceUtils.NAVBAR_BOTTOM_GESTURE_SIZE, getResources()) + 1;
  875. }
  876. int getBottomGestureMarginInContainer(UiObject2 container) {
  877. final int bottomGestureStartOnScreen = getRealDisplaySize().y - getBottomGestureSize();
  878. return getVisibleBounds(container).bottom - bottomGestureStartOnScreen;
  879. }
  880. void clickLauncherObject(UiObject2 object) {
  881. expectEvent(TestProtocol.SEQUENCE_MAIN, LauncherInstrumentation.EVENT_TOUCH_DOWN);
  882. expectEvent(TestProtocol.SEQUENCE_MAIN, LauncherInstrumentation.EVENT_TOUCH_UP);
  883. if (!isLauncher3() && getNavigationModel() != NavigationModel.THREE_BUTTON) {
  884. expectEvent(TestProtocol.SEQUENCE_TIS, LauncherInstrumentation.EVENT_TOUCH_DOWN_TIS);
  885. expectEvent(TestProtocol.SEQUENCE_TIS, LauncherInstrumentation.EVENT_TOUCH_UP_TIS);
  886. }
  887. object.click();
  888. }
  889. void scrollToLastVisibleRow(
  890. UiObject2 container,
  891. Collection<UiObject2> items,
  892. int topPaddingInContainer) {
  893. final UiObject2 lowestItem = Collections.max(items, (i1, i2) ->
  894. Integer.compare(getVisibleBounds(i1).top, getVisibleBounds(i2).top));
  895. final int itemRowCurrentTopOnScreen = getVisibleBounds(lowestItem).top;
  896. final Rect containerRect = getVisibleBounds(container);
  897. final int itemRowNewTopOnScreen = containerRect.top + topPaddingInContainer;
  898. final int distance = itemRowCurrentTopOnScreen - itemRowNewTopOnScreen + getTouchSlop();
  899. final int bottomGestureMarginInContainer = getBottomGestureMarginInContainer(container);
  900. scroll(
  901. container,
  902. Direction.DOWN,
  903. new Rect(
  904. 0,
  905. containerRect.height() - distance - bottomGestureMarginInContainer,
  906. 0,
  907. bottomGestureMarginInContainer),
  908. 10,
  909. true);
  910. }
  911. void scroll(
  912. UiObject2 container, Direction direction, Rect margins, int steps, boolean slowDown) {
  913. final Rect rect = getVisibleBounds(container);
  914. if (margins != null) {
  915. rect.left += margins.left;
  916. rect.top += margins.top;
  917. rect.right -= margins.right;
  918. rect.bottom -= margins.bottom;
  919. }
  920. final int startX;
  921. final int startY;
  922. final int endX;
  923. final int endY;
  924. switch (direction) {
  925. case UP: {
  926. startX = endX = rect.centerX();
  927. startY = rect.top;
  928. endY = rect.bottom - 1;
  929. }
  930. break;
  931. case DOWN: {
  932. startX = endX = rect.centerX();
  933. startY = rect.bottom - 1;
  934. endY = rect.top;
  935. }
  936. break;
  937. case LEFT: {
  938. startY = endY = rect.centerY();
  939. startX = rect.left;
  940. endX = rect.right - 1;
  941. }
  942. break;
  943. case RIGHT: {
  944. startY = endY = rect.centerY();
  945. startX = rect.right - 1;
  946. endX = rect.left;
  947. }
  948. break;
  949. default:
  950. fail("Unsupported direction");
  951. return;
  952. }
  953. executeAndWaitForEvent(
  954. () -> linearGesture(
  955. startX, startY, endX, endY, steps, slowDown, GestureScope.INSIDE),
  956. event -> TestProtocol.SCROLL_FINISHED_MESSAGE.equals(event.getClassName()),
  957. () -> "Didn't receive a scroll end message: " + startX + ", " + startY
  958. + ", " + endX + ", " + endY);
  959. }
  960. // Inject a swipe gesture. Inject exactly 'steps' motion points, incrementing event time by a
  961. // fixed interval each time.
  962. public void linearGesture(int startX, int startY, int endX, int endY, int steps,
  963. boolean slowDown,
  964. GestureScope gestureScope) {
  965. log("linearGesture: " + startX + ", " + startY + " -> " + endX + ", " + endY);
  966. final long downTime = SystemClock.uptimeMillis();
  967. final Point start = new Point(startX, startY);
  968. final Point end = new Point(endX, endY);
  969. sendPointer(downTime, downTime, MotionEvent.ACTION_DOWN, start, gestureScope);
  970. final long endTime = movePointer(start, end, steps, downTime, slowDown, gestureScope);
  971. sendPointer(downTime, endTime, MotionEvent.ACTION_UP, end, gestureScope);
  972. }
  973. long movePointer(Point start, Point end, int steps, long downTime, boolean slowDown,
  974. GestureScope gestureScope) {
  975. long endTime = movePointer(
  976. downTime, downTime, steps * GESTURE_STEP_MS, start, end, gestureScope);
  977. if (slowDown) {
  978. endTime = movePointer(downTime, endTime + GESTURE_STEP_MS, 5 * GESTURE_STEP_MS, end,
  979. end, gestureScope);
  980. }
  981. return endTime;
  982. }
  983. void waitForIdle() {
  984. mDevice.waitForIdle();
  985. }
  986. int getTouchSlop() {
  987. return ViewConfiguration.get(getContext()).getScaledTouchSlop();
  988. }
  989. public Resources getResources() {
  990. return getContext().getResources();
  991. }
  992. private static MotionEvent getMotionEvent(long downTime, long eventTime, int action,
  993. float x, float y) {
  994. MotionEvent.PointerProperties properties = new MotionEvent.PointerProperties();
  995. properties.id = 0;
  996. properties.toolType = Configurator.getInstance().getToolType();
  997. MotionEvent.PointerCoords coords = new MotionEvent.PointerCoords();
  998. coords.pressure = 1;
  999. coords.size = 1;
  1000. coords.x = x;
  1001. coords.y = y;
  1002. return MotionEvent.obtain(downTime, eventTime, action, 1,
  1003. new MotionEvent.PointerProperties[]{properties},
  1004. new MotionEvent.PointerCoords[]{coords},
  1005. 0, 0, 1.0f, 1.0f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0);
  1006. }
  1007. public void sendPointer(long downTime, long currentTime, int action, Point point,
  1008. GestureScope gestureScope) {
  1009. final boolean notLauncher3 = !isLauncher3();
  1010. switch (action) {
  1011. case MotionEvent.ACTION_DOWN:
  1012. if (gestureScope != GestureScope.OUTSIDE_WITH_PILFER
  1013. && gestureScope != GestureScope.OUTSIDE_WITHOUT_PILFER) {
  1014. expectEvent(TestProtocol.SEQUENCE_MAIN, EVENT_TOUCH_DOWN);
  1015. }
  1016. if (notLauncher3 && getNavigationModel() != NavigationModel.THREE_BUTTON) {
  1017. expectEvent(TestProtocol.SEQUENCE_TIS, EVENT_TOUCH_DOWN_TIS);
  1018. }
  1019. break;
  1020. case MotionEvent.ACTION_UP:
  1021. if (notLauncher3 && gestureScope != GestureScope.INSIDE
  1022. && (gestureScope == GestureScope.OUTSIDE_WITH_PILFER
  1023. || gestureScope == GestureScope.INSIDE_TO_OUTSIDE)) {
  1024. expectEvent(TestProtocol.SEQUENCE_PILFER, EVENT_PILFER_POINTERS);
  1025. }
  1026. if (gestureScope != GestureScope.OUTSIDE_WITH_PILFER
  1027. && gestureScope != GestureScope.OUTSIDE_WITHOUT_PILFER) {
  1028. expectEvent(TestProtocol.SEQUENCE_MAIN,
  1029. gestureScope == GestureScope.INSIDE
  1030. || gestureScope == GestureScope.OUTSIDE_WITHOUT_PILFER
  1031. ? EVENT_TOUCH_UP : EVENT_TOUCH_CANCEL);
  1032. }
  1033. if (notLauncher3 && getNavigationModel() != NavigationModel.THREE_BUTTON) {
  1034. expectEvent(TestProtocol.SEQUENCE_TIS, EVENT_TOUCH_UP_TIS);
  1035. }
  1036. break;
  1037. }
  1038. final MotionEvent event = getMotionEvent(downTime, currentTime, action, point.x, point.y);
  1039. assertTrue("injectInputEvent failed",
  1040. mInstrumentation.getUiAutomation().injectInputEvent(event, true));
  1041. event.recycle();
  1042. }
  1043. public long movePointer(long downTime, long startTime, long duration, Point from, Point to,
  1044. GestureScope gestureScope) {
  1045. log("movePointer: " + from + " to " + to);
  1046. final Point point = new Point();
  1047. long steps = duration / GESTURE_STEP_MS;
  1048. long currentTime = startTime;
  1049. for (long i = 0; i < steps; ++i) {
  1050. sleep(GESTURE_STEP_MS);
  1051. currentTime += GESTURE_STEP_MS;
  1052. final float progress = (currentTime - startTime) / (float) duration;
  1053. point.x = from.x + (int) (progress * (to.x - from.x));
  1054. point.y = from.y + (int) (progress * (to.y - from.y));
  1055. sendPointer(downTime, currentTime, MotionEvent.ACTION_MOVE, point, gestureScope);
  1056. }
  1057. return currentTime;
  1058. }
  1059. public static int getCurrentInteractionMode(Context context) {
  1060. return getSystemIntegerRes(context, "config_navBarInteractionMode");
  1061. }
  1062. @NonNull
  1063. UiObject2 clickAndGet(
  1064. @NonNull final UiObject2 target, @NonNull String resName, Pattern longClickEvent) {
  1065. final Point targetCenter = target.getVisibleCenter();
  1066. final long downTime = SystemClock.uptimeMillis();
  1067. sendPointer(downTime, downTime, MotionEvent.ACTION_DOWN, targetCenter, GestureScope.INSIDE);
  1068. expectEvent(TestProtocol.SEQUENCE_MAIN, longClickEvent);
  1069. final UiObject2 result = waitForLauncherObject(resName);
  1070. sendPointer(downTime, SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, targetCenter,
  1071. GestureScope.INSIDE);
  1072. return result;
  1073. }
  1074. private static int getSystemIntegerRes(Context context, String resName) {
  1075. Resources res = context.getResources();
  1076. int resId = res.getIdentifier(resName, "integer", "android");
  1077. if (resId != 0) {
  1078. return res.getInteger(resId);
  1079. } else {
  1080. Log.e(TAG, "Failed to get system resource ID. Incompatible framework version?");
  1081. return -1;
  1082. }
  1083. }
  1084. private static int getSystemDimensionResId(Context context, String resName) {
  1085. Resources res = context.getResources();
  1086. int resId = res.getIdentifier(resName, "dimen", "android");
  1087. if (resId != 0) {
  1088. return resId;
  1089. } else {
  1090. Log.e(TAG, "Failed to get system resource ID. Incompatible framework version?");
  1091. return -1;
  1092. }
  1093. }
  1094. static void sleep(int duration) {
  1095. SystemClock.sleep(duration);
  1096. }
  1097. int getEdgeSensitivityWidth() {
  1098. try {
  1099. final Context context = mInstrumentation.getTargetContext().createPackageContext(
  1100. getLauncherPackageName(), 0);
  1101. return context.getResources().getDimensionPixelSize(
  1102. getSystemDimensionResId(context, "config_backGestureInset")) + 1;
  1103. } catch (PackageManager.NameNotFoundException e) {
  1104. fail("Can't get edge sensitivity: " + e);
  1105. return 0;
  1106. }
  1107. }
  1108. Point getRealDisplaySize() {
  1109. final Point size = new Point();
  1110. getContext().getSystemService(WindowManager.class).getDefaultDisplay().getRealSize(size);
  1111. return size;
  1112. }
  1113. public void enableDebugTracing() {
  1114. getTestInfo(TestProtocol.REQUEST_ENABLE_DEBUG_TRACING);
  1115. }
  1116. public boolean hasAllAppsInOverview() {
  1117. // Vertical bar layouts don't contain all apps
  1118. if (!mDevice.isNaturalOrientation()) {
  1119. return false;
  1120. }
  1121. // Portrait two button (quickstep) always has all apps.
  1122. if (getNavigationModel() == NavigationModel.TWO_BUTTON) {
  1123. return true;
  1124. }
  1125. // Overview actions hide all apps
  1126. if (overviewActionsEnabled()) {
  1127. return false;
  1128. }
  1129. // ...otherwise there should be all apps
  1130. return true;
  1131. }
  1132. private boolean overviewActionsEnabled() {
  1133. return getTestInfo(TestProtocol.REQUEST_OVERVIEW_ACTIONS_ENABLED).getBoolean(
  1134. TestProtocol.TEST_INFO_RESPONSE_FIELD);
  1135. }
  1136. boolean overviewShareEnabled() {
  1137. return getTestInfo(TestProtocol.REQUEST_OVERVIEW_SHARE_ENABLED).getBoolean(
  1138. TestProtocol.TEST_INFO_RESPONSE_FIELD);
  1139. }
  1140. private void disableSensorRotation() {
  1141. getTestInfo(TestProtocol.REQUEST_MOCK_SENSOR_ROTATION);
  1142. }
  1143. public void disableDebugTracing() {
  1144. getTestInfo(TestProtocol.REQUEST_DISABLE_DEBUG_TRACING);
  1145. }
  1146. public int getTotalPssKb() {
  1147. return getTestInfo(TestProtocol.REQUEST_TOTAL_PSS_KB).
  1148. getInt(TestProtocol.TEST_INFO_RESPONSE_FIELD);
  1149. }
  1150. public Integer getPid() {
  1151. final Bundle testInfo = getTestInfo(TestProtocol.REQUEST_PID);
  1152. return testInfo != null ? testInfo.getInt(TestProtocol.TEST_INFO_RESPONSE_FIELD) : null;
  1153. }
  1154. public void produceJavaLeak() {
  1155. getTestInfo(TestProtocol.REQUEST_JAVA_LEAK);
  1156. }
  1157. public void produceNativeLeak() {
  1158. getTestInfo(TestProtocol.REQUEST_NATIVE_LEAK);
  1159. }
  1160. public void produceViewLeak() {
  1161. getTestInfo(TestProtocol.REQUEST_VIEW_LEAK);
  1162. }
  1163. public ArrayList<ComponentName> getRecentTasks() {
  1164. ArrayList<ComponentName> tasks = new ArrayList<>();
  1165. ArrayList<String> components = getTestInfo(TestProtocol.REQUEST_RECENT_TASKS_LIST)
  1166. .getStringArrayList(TestProtocol.TEST_INFO_RESPONSE_FIELD);
  1167. for (String s : components) {
  1168. tasks.add(ComponentName.unflattenFromString(s));
  1169. }
  1170. return tasks;
  1171. }
  1172. public void clearLauncherData() {
  1173. getTestInfo(TestProtocol.REQUEST_CLEAR_DATA);
  1174. }
  1175. public Closable eventsCheck() {
  1176. Assert.assertTrue("Nested event checking", mEventChecker == null);
  1177. disableSensorRotation();
  1178. final Integer initialPid = getPid();
  1179. final LogEventChecker eventChecker = new LogEventChecker(this);
  1180. if (eventChecker.start()) mEventChecker = eventChecker;
  1181. return () -> {
  1182. if (initialPid != null && initialPid.intValue() != getPid()) {
  1183. if (mOnLauncherCrashed != null) mOnLauncherCrashed.run();
  1184. checkForAnomaly();
  1185. Assert.fail(
  1186. formatSystemHealthMessage(
  1187. formatErrorWithEvents("Launcher crashed", false)));
  1188. }
  1189. if (mEventChecker != null) {
  1190. mEventChecker = null;
  1191. if (mCheckEventsForSuccessfulGestures) {
  1192. final String message = eventChecker.verify(WAIT_TIME_MS, true);
  1193. if (message != null) {
  1194. dumpDiagnostics();
  1195. checkForAnomaly();
  1196. Assert.fail(formatSystemHealthMessage(
  1197. "http://go/tapl : successful gesture produced " + message));
  1198. }
  1199. } else {
  1200. eventChecker.finishNoWait();
  1201. }
  1202. }
  1203. };
  1204. }
  1205. boolean isLauncher3() {
  1206. return "com.android.launcher3".equals(getLauncherPackageName());
  1207. }
  1208. void expectEvent(String sequence, Pattern expected) {
  1209. if (mEventChecker != null) {
  1210. mEventChecker.expectPattern(sequence, expected);
  1211. } else {
  1212. Log.d(TAG, "Expecting: " + sequence + " / " + expected);
  1213. }
  1214. }
  1215. Rect getVisibleBounds(UiObject2 object) {
  1216. try {
  1217. return object.getVisibleBounds();
  1218. } catch (Throwable t) {
  1219. fail(t.toString());
  1220. return null;
  1221. }
  1222. }
  1223. }