diff options
404 files changed, 13964 insertions, 6574 deletions
diff --git a/apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java b/apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java index cd86d6a4d6c7..a65205500651 100644 --- a/apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java +++ b/apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java @@ -155,6 +155,7 @@ public class UserLifecycleTests { public void tearDown() throws Exception { setSystemProperty("debug.usercontroller.user_switch_timeout_ms", mUserSwitchTimeoutMs); mBroadcastWaiter.close(); + mUserSwitchWaiter.close(); for (int userId : mUsersToRemove) { try { mUm.removeUser(userId); @@ -207,10 +208,10 @@ public class UserLifecycleTests { while (mRunner.keepRunning()) { mRunner.pauseTiming(); final int userId = createUserNoFlags(); - mRunner.resumeTiming(); - Log.i(TAG, "Starting timer"); - runThenWaitForBroadcasts(userId, () -> { + mRunner.resumeTiming(); + Log.i(TAG, "Starting timer"); + mIam.startUserInBackground(userId); }, Intent.ACTION_USER_STARTED); @@ -360,10 +361,10 @@ public class UserLifecycleTests { }, Intent.ACTION_MEDIA_MOUNTED); mUserSwitchWaiter.runThenWaitUntilSwitchCompleted(startUser, () -> { - mRunner.resumeTiming(); - Log.i(TAG, "Starting timer"); - runThenWaitForBroadcasts(userId, () -> { + mRunner.resumeTiming(); + Log.i(TAG, "Starting timer"); + mAm.switchUser(startUser); }, Intent.ACTION_USER_STOPPED); @@ -423,7 +424,7 @@ public class UserLifecycleTests { final int userId = createManagedProfile(); // Start the profile initially, then stop it. Similar to setQuietModeEnabled. startUserInBackgroundAndWaitForUnlock(userId); - stopUser(userId, true); + stopUserAfterWaitingForBroadcastIdle(userId, true); mRunner.resumeTiming(); Log.i(TAG, "Starting timer"); @@ -478,7 +479,7 @@ public class UserLifecycleTests { installPreexistingApp(userId, DUMMY_PACKAGE_NAME); startUserInBackgroundAndWaitForUnlock(userId); startApp(userId, DUMMY_PACKAGE_NAME); - stopUser(userId, true); + stopUserAfterWaitingForBroadcastIdle(userId, true); SystemClock.sleep(1_000); // 1 second cool-down before re-starting profile. mRunner.resumeTiming(); Log.i(TAG, "Starting timer"); @@ -675,6 +676,19 @@ public class UserLifecycleTests { return success[0]; } + /** + * Waits for broadcast idle before stopping a user, to prevent timeouts on stop user. + * Stopping a user heavily depends on broadcast queue, and that gets crowded after user creation + * or user switches, which leads to a timeout on stopping user and cause the tests to be flaky. + * Do not call this method while timing is on. i.e. between mRunner.resumeTiming() and + * mRunner.pauseTiming(). Otherwise it would cause the test results to be spiky. + */ + private void stopUserAfterWaitingForBroadcastIdle(int userId, boolean force) + throws RemoteException { + ShellHelper.runShellCommand("am wait-for-broadcast-idle"); + stopUser(userId, force); + } + private void stopUser(int userId, boolean force) throws RemoteException { final CountDownLatch latch = new CountDownLatch(1); mIam.stopUser(userId, force /* force */, new IStopUserCallback.Stub() { @@ -710,7 +724,7 @@ public class UserLifecycleTests { attestTrue("Didn't switch back to user, " + origUser, origUser == mAm.getCurrentUser()); if (stopNewUser) { - stopUser(testUser, true); + stopUserAfterWaitingForBroadcastIdle(testUser, true); attestFalse("Failed to stop user " + testUser, mAm.isUserRunning(testUser)); } diff --git a/apct-tests/perftests/multiuser/src/android/multiuser/UserSwitchWaiter.java b/apct-tests/perftests/multiuser/src/android/multiuser/UserSwitchWaiter.java index 228d14c3a05b..82245977760b 100644 --- a/apct-tests/perftests/multiuser/src/android/multiuser/UserSwitchWaiter.java +++ b/apct-tests/perftests/multiuser/src/android/multiuser/UserSwitchWaiter.java @@ -17,61 +17,87 @@ package android.multiuser; import android.app.ActivityManager; +import android.app.IActivityManager; +import android.app.IUserSwitchObserver; import android.app.UserSwitchObserver; import android.os.RemoteException; import android.util.Log; import com.android.internal.util.FunctionalUtils; -import java.util.concurrent.CountDownLatch; +import java.io.Closeable; +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; -public class UserSwitchWaiter { +public class UserSwitchWaiter implements Closeable { private final String mTag; private final int mTimeoutInSecond; + private final IActivityManager mActivityManager; + private final IUserSwitchObserver mUserSwitchObserver = new UserSwitchObserver() { + @Override + public void onUserSwitchComplete(int newUserId) { + getSemaphoreSwitchComplete(newUserId).release(); + } + + @Override + public void onLockedBootComplete(int newUserId) { + getSemaphoreBootComplete(newUserId).release(); + } + }; + + private final Map<Integer, Semaphore> mSemaphoresMapSwitchComplete = new ConcurrentHashMap<>(); + private Semaphore getSemaphoreSwitchComplete(final int userId) { + return mSemaphoresMapSwitchComplete.computeIfAbsent(userId, + (Integer absentKey) -> new Semaphore(0)); + } + + private final Map<Integer, Semaphore> mSemaphoresMapBootComplete = new ConcurrentHashMap<>(); + private Semaphore getSemaphoreBootComplete(final int userId) { + return mSemaphoresMapBootComplete.computeIfAbsent(userId, + (Integer absentKey) -> new Semaphore(0)); + } - public UserSwitchWaiter(String tag, int timeoutInSecond) { + public UserSwitchWaiter(String tag, int timeoutInSecond) throws RemoteException { mTag = tag; mTimeoutInSecond = timeoutInSecond; + mActivityManager = ActivityManager.getService(); + + mActivityManager.registerUserSwitchObserver(mUserSwitchObserver, mTag); + } + + @Override + public void close() throws IOException { + try { + mActivityManager.unregisterUserSwitchObserver(mUserSwitchObserver); + } catch (RemoteException e) { + Log.e(mTag, "Failed to unregister user switch observer", e); + } } public void runThenWaitUntilSwitchCompleted(int userId, FunctionalUtils.ThrowingRunnable runnable, Runnable onFail) throws RemoteException { - final CountDownLatch latch = new CountDownLatch(1); - ActivityManager.getService().registerUserSwitchObserver( - new UserSwitchObserver() { - @Override - public void onUserSwitchComplete(int newUserId) throws RemoteException { - if (userId == newUserId) { - latch.countDown(); - } - } - }, mTag); + final Semaphore semaphore = getSemaphoreSwitchComplete(userId); + semaphore.drainPermits(); runnable.run(); - waitForLatch(latch, onFail); + waitForSemaphore(semaphore, onFail); } public void runThenWaitUntilBootCompleted(int userId, FunctionalUtils.ThrowingRunnable runnable, Runnable onFail) throws RemoteException { - final CountDownLatch latch = new CountDownLatch(1); - ActivityManager.getService().registerUserSwitchObserver( - new UserSwitchObserver() { - @Override - public void onLockedBootComplete(int newUserId) { - if (userId == newUserId) { - latch.countDown(); - } - } - }, mTag); + final Semaphore semaphore = getSemaphoreBootComplete(userId); + semaphore.drainPermits(); runnable.run(); - waitForLatch(latch, onFail); + waitForSemaphore(semaphore, onFail); } - private void waitForLatch(CountDownLatch latch, Runnable onFail) { + private void waitForSemaphore(Semaphore semaphore, Runnable onFail) { boolean success = false; try { - success = latch.await(mTimeoutInSecond, TimeUnit.SECONDS); + success = semaphore.tryAcquire(mTimeoutInSecond, TimeUnit.SECONDS); } catch (InterruptedException e) { Log.e(mTag, "Thread interrupted unexpectedly.", e); } diff --git a/apct-tests/perftests/surfaceflinger/AndroidManifest.xml b/apct-tests/perftests/surfaceflinger/AndroidManifest.xml index c908d6ae4cff..26f25863f055 100644 --- a/apct-tests/perftests/surfaceflinger/AndroidManifest.xml +++ b/apct-tests/perftests/surfaceflinger/AndroidManifest.xml @@ -16,6 +16,10 @@ <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="android.perftests.surfaceflinger"> + <!-- permission needed to write perfetto trace and read/write simpleperf report --> + <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" /> + <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> + <application android:label="SurfaceFlingerPerfTests"> <uses-library android:name="android.test.runner" /> <activity android:name="android.surfaceflinger.SurfaceFlingerTestActivity" diff --git a/apex/jobscheduler/service/java/com/android/server/job/controllers/FlexibilityController.java b/apex/jobscheduler/service/java/com/android/server/job/controllers/FlexibilityController.java index 3ca1ad58955d..9d364782a57f 100644 --- a/apex/jobscheduler/service/java/com/android/server/job/controllers/FlexibilityController.java +++ b/apex/jobscheduler/service/java/com/android/server/job/controllers/FlexibilityController.java @@ -16,6 +16,7 @@ package com.android.server.job.controllers; +import static android.text.format.DateUtils.DAY_IN_MILLIS; import static android.text.format.DateUtils.HOUR_IN_MILLIS; import static android.text.format.DateUtils.MINUTE_IN_MILLIS; @@ -31,6 +32,7 @@ import android.annotation.NonNull; import android.annotation.Nullable; import android.app.job.JobInfo; import android.content.Context; +import android.content.pm.PackageManager; import android.os.Looper; import android.os.UserHandle; import android.provider.DeviceConfig; @@ -80,31 +82,26 @@ public final class FlexibilityController extends StateController { private static final long NO_LIFECYCLE_END = Long.MAX_VALUE; /** - * Keeps track of what flexible constraints are satisfied at the moment. - * Is updated by the other controllers. - */ - @VisibleForTesting - @GuardedBy("mLock") - int mSatisfiedFlexibleConstraints; - - /** Hard cutoff to remove flexible constraints. */ - private long mDeadlineProximityLimitMs = - FcConfig.DEFAULT_DEADLINE_PROXIMITY_LIMIT_MS; - - /** * The default deadline that all flexible constraints should be dropped by if a job lacks * a deadline. */ private long mFallbackFlexibilityDeadlineMs = FcConfig.DEFAULT_FALLBACK_FLEXIBILITY_DEADLINE_MS; - @GuardedBy("mLock") + private long mRescheduledJobDeadline = FcConfig.DEFAULT_RESCHEDULED_JOB_DEADLINE_MS; + private long mMaxRescheduledDeadline = FcConfig.DEFAULT_MAX_RESCHEDULED_DEADLINE_MS; + @VisibleForTesting + @GuardedBy("mLock") boolean mFlexibilityEnabled = FcConfig.DEFAULT_FLEXIBILITY_ENABLED; private long mMinTimeBetweenFlexibilityAlarmsMs = FcConfig.DEFAULT_MIN_TIME_BETWEEN_FLEXIBILITY_ALARMS_MS; + /** Hard cutoff to remove flexible constraints. */ + private long mDeadlineProximityLimitMs = + FcConfig.DEFAULT_DEADLINE_PROXIMITY_LIMIT_MS; + /** * The percent of a job's lifecycle to drop number of required constraints. * mPercentToDropConstraints[i] denotes that at x% of a Jobs lifecycle, @@ -113,6 +110,17 @@ public final class FlexibilityController extends StateController { private int[] mPercentToDropConstraints; @VisibleForTesting + boolean mDeviceSupportsFlexConstraints; + + /** + * Keeps track of what flexible constraints are satisfied at the moment. + * Is updated by the other controllers. + */ + @VisibleForTesting + @GuardedBy("mLock") + int mSatisfiedFlexibleConstraints; + + @VisibleForTesting @GuardedBy("mLock") final FlexibilityTracker mFlexibilityTracker; @VisibleForTesting @@ -120,7 +128,6 @@ public final class FlexibilityController extends StateController { final FlexibilityAlarmQueue mFlexibilityAlarmQueue; @VisibleForTesting final FcConfig mFcConfig; - @VisibleForTesting final PrefetchController mPrefetchController; @@ -168,6 +175,9 @@ public final class FlexibilityController extends StateController { public FlexibilityController( JobSchedulerService service, PrefetchController prefetchController) { super(service); + mDeviceSupportsFlexConstraints = !mContext.getPackageManager().hasSystemFeature( + PackageManager.FEATURE_AUTOMOTIVE); + mFlexibilityEnabled &= mDeviceSupportsFlexConstraints; mFlexibilityTracker = new FlexibilityTracker(NUM_FLEXIBLE_CONSTRAINTS); mFcConfig = new FcConfig(); mFlexibilityAlarmQueue = new FlexibilityAlarmQueue( @@ -187,10 +197,14 @@ public final class FlexibilityController extends StateController { @GuardedBy("mLock") public void maybeStartTrackingJobLocked(JobStatus js, JobStatus lastJob) { if (js.hasFlexibilityConstraint()) { - mFlexibilityTracker.add(js); - js.setTrackingController(JobStatus.TRACKING_FLEXIBILITY); final long nowElapsed = sElapsedRealtimeClock.millis(); + if (!mDeviceSupportsFlexConstraints) { + js.setFlexibilityConstraintSatisfied(nowElapsed, true); + return; + } js.setFlexibilityConstraintSatisfied(nowElapsed, isFlexibilitySatisfiedLocked(js)); + mFlexibilityTracker.add(js); + js.setTrackingController(JobStatus.TRACKING_FLEXIBILITY); mFlexibilityAlarmQueue.scheduleDropNumConstraintsAlarm(js, nowElapsed); } } @@ -321,6 +335,12 @@ public final class FlexibilityController extends StateController { // There is no deadline and no estimated launch time. return NO_LIFECYCLE_END; } + if (js.getNumFailures() > 1) { + // Number of failures will not equal one as per restriction in JobStatus constructor. + return earliest + Math.min( + (long) Math.scalb(mRescheduledJobDeadline, js.getNumFailures() - 2), + mMaxRescheduledDeadline); + } return js.getLatestRunTimeElapsed() == JobStatus.NO_LATEST_RUNTIME ? earliest + mFallbackFlexibilityDeadlineMs : js.getLatestRunTimeElapsed(); } @@ -340,7 +360,6 @@ public final class FlexibilityController extends StateController { return percentInTime; } - /** The elapsed time that marks when the next constraint should be dropped. */ @VisibleForTesting @ElapsedRealtimeLong @GuardedBy("mLock") @@ -351,7 +370,6 @@ public final class FlexibilityController extends StateController { } /** The elapsed time that marks when the next constraint should be dropped. */ - @VisibleForTesting @ElapsedRealtimeLong @GuardedBy("mLock") long getNextConstraintDropTimeElapsedLocked(JobStatus js, long earliest, long latest) { @@ -406,7 +424,7 @@ public final class FlexibilityController extends StateController { final ArraySet<JobStatus> changedJobs = new ArraySet<>(); synchronized (mLock) { final long nowElapsed = sElapsedRealtimeClock.millis(); - for (int j = 1; j <= mFlexibilityTracker.size(); j++) { + for (int j = 0; j < mFlexibilityTracker.size(); j++) { final ArraySet<JobStatus> jobs = mFlexibilityTracker .getJobsByNumRequiredConstraints(j); for (int i = 0; i < jobs.size(); i++) { @@ -445,7 +463,7 @@ public final class FlexibilityController extends StateController { FlexibilityTracker(int numFlexibleConstraints) { mTrackedJobs = new ArrayList<>(); - for (int i = 0; i < numFlexibleConstraints; i++) { + for (int i = 0; i <= numFlexibleConstraints; i++) { mTrackedJobs.add(new ArraySet<JobStatus>()); } } @@ -457,15 +475,15 @@ public final class FlexibilityController extends StateController { Slog.wtfStack(TAG, "Asked for a larger number of constraints than exists."); return null; } - return mTrackedJobs.get(numRequired - 1); + return mTrackedJobs.get(numRequired); } /** adds a JobStatus object based on number of required flexible constraints. */ public void add(JobStatus js) { - if (js.getNumRequiredFlexibleConstraints() <= 0) { + if (js.getNumRequiredFlexibleConstraints() < 0) { return; } - mTrackedJobs.get(js.getNumRequiredFlexibleConstraints() - 1).add(js); + mTrackedJobs.get(js.getNumRequiredFlexibleConstraints()).add(js); } /** Removes a JobStatus object. */ @@ -473,7 +491,7 @@ public final class FlexibilityController extends StateController { if (js.getNumRequiredFlexibleConstraints() == 0) { return; } - mTrackedJobs.get(js.getNumRequiredFlexibleConstraints() - 1).remove(js); + mTrackedJobs.get(js.getNumRequiredFlexibleConstraints()).remove(js); } public void resetJobNumDroppedConstraints(JobStatus js, long nowElapsed) { @@ -498,21 +516,15 @@ public final class FlexibilityController extends StateController { /** * Adjusts number of required flexible constraints and sorts it into the tracker. * Returns false if the job status's number of flexible constraints is now 0. - * Jobs with 0 required flexible constraints are removed from the tracker. */ - public boolean adjustJobsRequiredConstraints(JobStatus js, int n, long nowElapsed) { - if (n == 0) { - return false; - } - remove(js); - js.adjustNumRequiredFlexibleConstraints(n); - js.setFlexibilityConstraintSatisfied(nowElapsed, isFlexibilitySatisfiedLocked(js)); - if (js.getNumRequiredFlexibleConstraints() <= 0) { - maybeStopTrackingJobLocked(js, null, false); - return false; + public boolean adjustJobsRequiredConstraints(JobStatus js, int adjustBy, long nowElapsed) { + if (adjustBy != 0) { + remove(js); + js.adjustNumRequiredFlexibleConstraints(adjustBy); + js.setFlexibilityConstraintSatisfied(nowElapsed, isFlexibilitySatisfiedLocked(js)); + add(js); } - add(js); - return true; + return js.getNumRequiredFlexibleConstraints() > 0; } public int size() { @@ -531,6 +543,8 @@ public final class FlexibilityController extends StateController { js.printUniqueId(pw); pw.print(" from "); UserHandle.formatUid(pw, js.getSourceUid()); + pw.print(" Num Required Constraints: "); + pw.print(js.getNumRequiredFlexibleConstraints()); pw.println(); } } @@ -551,20 +565,24 @@ public final class FlexibilityController extends StateController { } public void scheduleDropNumConstraintsAlarm(JobStatus js, long nowElapsed) { - long nextTimeElapsed; synchronized (mLock) { final long earliest = getLifeCycleBeginningElapsedLocked(js); final long latest = getLifeCycleEndElapsedLocked(js, earliest); - nextTimeElapsed = getNextConstraintDropTimeElapsedLocked(js, earliest, latest); + final long nextTimeElapsed = + getNextConstraintDropTimeElapsedLocked(js, earliest, latest); + + if (latest - nowElapsed < mDeadlineProximityLimitMs) { + mFlexibilityTracker.adjustJobsRequiredConstraints(js, + -js.getNumRequiredFlexibleConstraints(), nowElapsed); + return; + } if (nextTimeElapsed == NO_LIFECYCLE_END) { // There is no known or estimated next time to drop a constraint. removeAlarmForKey(js); return; } - if (latest - nextTimeElapsed < mDeadlineProximityLimitMs) { - mFlexibilityTracker.adjustJobsRequiredConstraints( - js, -js.getNumRequiredFlexibleConstraints(), nowElapsed); + addAlarm(js, latest - mDeadlineProximityLimitMs); return; } addAlarm(js, nextTimeElapsed); @@ -579,20 +597,8 @@ public final class FlexibilityController extends StateController { for (int i = 0; i < expired.size(); i++) { JobStatus js = expired.valueAt(i); boolean wasFlexibilitySatisfied = js.isConstraintSatisfied(CONSTRAINT_FLEXIBLE); - - final long earliest = getLifeCycleBeginningElapsedLocked(js); - final long latest = getLifeCycleEndElapsedLocked(js, earliest); - - if (latest - nowElapsed < mDeadlineProximityLimitMs) { - mFlexibilityTracker.adjustJobsRequiredConstraints(js, - -js.getNumRequiredFlexibleConstraints(), nowElapsed); - } else { - long nextTimeElapsed = - getNextConstraintDropTimeElapsedLocked(js, earliest, latest); - if (mFlexibilityTracker.adjustJobsRequiredConstraints(js, -1, nowElapsed) - && nextTimeElapsed != NO_LIFECYCLE_END) { - mFlexibilityAlarmQueue.addAlarm(js, nextTimeElapsed); - } + if (mFlexibilityTracker.adjustJobsRequiredConstraints(js, -1, nowElapsed)) { + scheduleDropNumConstraintsAlarm(js, nowElapsed); } if (wasFlexibilitySatisfied != js.isConstraintSatisfied(CONSTRAINT_FLEXIBLE)) { changedJobs.add(js); @@ -619,6 +625,10 @@ public final class FlexibilityController extends StateController { FC_CONFIG_PREFIX + "min_alarm_time_flexibility_ms"; static final String KEY_PERCENTS_TO_DROP_NUM_FLEXIBLE_CONSTRAINTS = FC_CONFIG_PREFIX + "percents_to_drop_num_flexible_constraints"; + static final String KEY_MAX_RESCHEDULED_DEADLINE_MS = + FC_CONFIG_PREFIX + "max_rescheduled_deadline_ms"; + static final String KEY_RESCHEDULED_JOB_DEADLINE_MS = + FC_CONFIG_PREFIX + "rescheduled_job_deadline_ms"; private static final boolean DEFAULT_FLEXIBILITY_ENABLED = false; @VisibleForTesting @@ -628,6 +638,8 @@ public final class FlexibilityController extends StateController { private static final long DEFAULT_MIN_TIME_BETWEEN_FLEXIBILITY_ALARMS_MS = MINUTE_IN_MILLIS; @VisibleForTesting final int[] DEFAULT_PERCENT_TO_DROP_FLEXIBLE_CONSTRAINTS = {50, 60, 70, 80}; + private static final long DEFAULT_RESCHEDULED_JOB_DEADLINE_MS = HOUR_IN_MILLIS; + private static final long DEFAULT_MAX_RESCHEDULED_DEADLINE_MS = 5 * DAY_IN_MILLIS; /** * If false the controller will not track new jobs @@ -643,13 +655,18 @@ public final class FlexibilityController extends StateController { /** The percentages of a jobs' lifecycle to drop the number of required constraints. */ public int[] PERCENTS_TO_DROP_NUM_FLEXIBLE_CONSTRAINTS = DEFAULT_PERCENT_TO_DROP_FLEXIBLE_CONSTRAINTS; + /** Initial fallback flexible deadline for rescheduled jobs. */ + public long RESCHEDULED_JOB_DEADLINE_MS = DEFAULT_RESCHEDULED_JOB_DEADLINE_MS; + /** The max deadline for rescheduled jobs. */ + public long MAX_RESCHEDULED_DEADLINE_MS = DEFAULT_MAX_RESCHEDULED_DEADLINE_MS; @GuardedBy("mLock") public void processConstantLocked(@NonNull DeviceConfig.Properties properties, @NonNull String key) { switch (key) { case KEY_FLEXIBILITY_ENABLED: - FLEXIBILITY_ENABLED = properties.getBoolean(key, DEFAULT_FLEXIBILITY_ENABLED); + FLEXIBILITY_ENABLED = properties.getBoolean(key, DEFAULT_FLEXIBILITY_ENABLED) + && mDeviceSupportsFlexConstraints; if (mFlexibilityEnabled != FLEXIBILITY_ENABLED) { mFlexibilityEnabled = FLEXIBILITY_ENABLED; mShouldReevaluateConstraints = true; @@ -662,6 +679,22 @@ public final class FlexibilityController extends StateController { } } break; + case KEY_RESCHEDULED_JOB_DEADLINE_MS: + RESCHEDULED_JOB_DEADLINE_MS = + properties.getLong(key, DEFAULT_RESCHEDULED_JOB_DEADLINE_MS); + if (mRescheduledJobDeadline != RESCHEDULED_JOB_DEADLINE_MS) { + mRescheduledJobDeadline = RESCHEDULED_JOB_DEADLINE_MS; + mShouldReevaluateConstraints = true; + } + break; + case KEY_MAX_RESCHEDULED_DEADLINE_MS: + MAX_RESCHEDULED_DEADLINE_MS = + properties.getLong(key, DEFAULT_MAX_RESCHEDULED_DEADLINE_MS); + if (mMaxRescheduledDeadline != MAX_RESCHEDULED_DEADLINE_MS) { + mMaxRescheduledDeadline = MAX_RESCHEDULED_DEADLINE_MS; + mShouldReevaluateConstraints = true; + } + break; case KEY_DEADLINE_PROXIMITY_LIMIT: DEADLINE_PROXIMITY_LIMIT_MS = properties.getLong(key, DEFAULT_DEADLINE_PROXIMITY_LIMIT_MS); @@ -733,6 +766,14 @@ public final class FlexibilityController extends StateController { pw.increaseIndent(); pw.print(KEY_FLEXIBILITY_ENABLED, FLEXIBILITY_ENABLED).println(); + pw.print(KEY_DEADLINE_PROXIMITY_LIMIT, DEADLINE_PROXIMITY_LIMIT_MS).println(); + pw.print(KEY_FALLBACK_FLEXIBILITY_DEADLINE, FALLBACK_FLEXIBILITY_DEADLINE_MS).println(); + pw.print(KEY_MIN_TIME_BETWEEN_FLEXIBILITY_ALARMS_MS, + MIN_TIME_BETWEEN_FLEXIBILITY_ALARMS_MS).println(); + pw.print(KEY_PERCENTS_TO_DROP_NUM_FLEXIBLE_CONSTRAINTS, + PERCENTS_TO_DROP_NUM_FLEXIBLE_CONSTRAINTS).println(); + pw.print(KEY_RESCHEDULED_JOB_DEADLINE_MS, RESCHEDULED_JOB_DEADLINE_MS).println(); + pw.print(KEY_MAX_RESCHEDULED_DEADLINE_MS, MAX_RESCHEDULED_DEADLINE_MS).println(); pw.decreaseIndent(); } @@ -748,9 +789,15 @@ public final class FlexibilityController extends StateController { @GuardedBy("mLock") public void dumpControllerStateLocked(IndentingPrintWriter pw, Predicate<JobStatus> predicate) { pw.println("# Constraints Satisfied: " + Integer.bitCount(mSatisfiedFlexibleConstraints)); + pw.print("Satisfied Flexible Constraints: "); + JobStatus.dumpConstraints(pw, mSatisfiedFlexibleConstraints); + pw.println(); pw.println(); mFlexibilityTracker.dump(pw, predicate); + pw.println(); + mFlexibilityAlarmQueue.dump(pw); + pw.println(); mFcConfig.dump(pw); } } diff --git a/apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java b/apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java index 4ce6b32166c1..4320db09aef5 100644 --- a/apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java +++ b/apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java @@ -572,8 +572,11 @@ public final class JobStatus { (latestRunTimeElapsedMillis - earliestRunTimeElapsedMillis) >= MIN_WINDOW_FOR_FLEXIBILITY_MS; + // The first time a job is rescheduled it will not be subject to flexible constraints. + // Otherwise, every consecutive reschedule increases a jobs' flexibility deadline. if (!isRequestedExpeditedJob() && satisfiesMinWindowException + && numFailures != 1 && lacksSomeFlexibleConstraints) { mNumRequiredFlexibleConstraints = NUM_SYSTEM_WIDE_FLEXIBLE_CONSTRAINTS + (mPreferUnmetered ? 1 : 0); @@ -1928,35 +1931,38 @@ public final class JobStatus { proto.end(token); } - void dumpConstraints(PrintWriter pw, int constraints) { - if ((constraints&CONSTRAINT_CHARGING) != 0) { + static void dumpConstraints(PrintWriter pw, int constraints) { + if ((constraints & CONSTRAINT_CHARGING) != 0) { pw.print(" CHARGING"); } - if ((constraints& CONSTRAINT_BATTERY_NOT_LOW) != 0) { + if ((constraints & CONSTRAINT_BATTERY_NOT_LOW) != 0) { pw.print(" BATTERY_NOT_LOW"); } - if ((constraints& CONSTRAINT_STORAGE_NOT_LOW) != 0) { + if ((constraints & CONSTRAINT_STORAGE_NOT_LOW) != 0) { pw.print(" STORAGE_NOT_LOW"); } - if ((constraints&CONSTRAINT_TIMING_DELAY) != 0) { + if ((constraints & CONSTRAINT_TIMING_DELAY) != 0) { pw.print(" TIMING_DELAY"); } - if ((constraints&CONSTRAINT_DEADLINE) != 0) { + if ((constraints & CONSTRAINT_DEADLINE) != 0) { pw.print(" DEADLINE"); } - if ((constraints&CONSTRAINT_IDLE) != 0) { + if ((constraints & CONSTRAINT_IDLE) != 0) { pw.print(" IDLE"); } - if ((constraints&CONSTRAINT_CONNECTIVITY) != 0) { + if ((constraints & CONSTRAINT_CONNECTIVITY) != 0) { pw.print(" CONNECTIVITY"); } - if ((constraints&CONSTRAINT_CONTENT_TRIGGER) != 0) { + if ((constraints & CONSTRAINT_FLEXIBLE) != 0) { + pw.print(" FLEXIBILITY"); + } + if ((constraints & CONSTRAINT_CONTENT_TRIGGER) != 0) { pw.print(" CONTENT_TRIGGER"); } - if ((constraints&CONSTRAINT_DEVICE_NOT_DOZING) != 0) { + if ((constraints & CONSTRAINT_DEVICE_NOT_DOZING) != 0) { pw.print(" DEVICE_NOT_DOZING"); } - if ((constraints&CONSTRAINT_BACKGROUND_NOT_RESTRICTED) != 0) { + if ((constraints & CONSTRAINT_BACKGROUND_NOT_RESTRICTED) != 0) { pw.print(" BACKGROUND_NOT_RESTRICTED"); } if ((constraints & CONSTRAINT_PREFETCH) != 0) { @@ -2242,6 +2248,14 @@ public final class JobStatus { ((requiredConstraints | CONSTRAINT_WITHIN_QUOTA | CONSTRAINT_TARE_WEALTH) & ~satisfiedConstraints)); pw.println(); + if (hasFlexibilityConstraint()) { + pw.print("Num Required Flexible constraints: "); + pw.print(getNumRequiredFlexibleConstraints()); + pw.println(); + pw.print("Num Dropped Flexible constraints: "); + pw.print(getNumDroppedFlexibleConstraints()); + pw.println(); + } pw.println("Constraint history:"); pw.increaseIndent(); diff --git a/apex/jobscheduler/service/java/com/android/server/tare/Agent.java b/apex/jobscheduler/service/java/com/android/server/tare/Agent.java index cd815e5c2b14..4fe021a35f98 100644 --- a/apex/jobscheduler/service/java/com/android/server/tare/Agent.java +++ b/apex/jobscheduler/service/java/com/android/server/tare/Agent.java @@ -1328,7 +1328,6 @@ class Agent { @GuardedBy("mLock") void dumpLocked(IndentingPrintWriter pw) { - pw.println(); mBalanceThresholdAlarmQueue.dump(pw); pw.println(); diff --git a/apex/jobscheduler/service/java/com/android/server/tare/EconomicPolicy.java b/apex/jobscheduler/service/java/com/android/server/tare/EconomicPolicy.java index 2fb0c1a36e07..22a2f5163538 100644 --- a/apex/jobscheduler/service/java/com/android/server/tare/EconomicPolicy.java +++ b/apex/jobscheduler/service/java/com/android/server/tare/EconomicPolicy.java @@ -405,6 +405,10 @@ public abstract class EconomicPolicy { return "PROMOTION"; case REGULATION_DEMOTION: return "DEMOTION"; + case REGULATION_BG_RESTRICTED: + return "BG_RESTRICTED"; + case REGULATION_BG_UNRESTRICTED: + return "BG_UNRESTRICTED"; } return "UNKNOWN_REGULATION:" + Integer.toHexString(eventId); } diff --git a/apex/jobscheduler/service/java/com/android/server/tare/Ledger.java b/apex/jobscheduler/service/java/com/android/server/tare/Ledger.java index e91ed1287e1b..620d1a0da76f 100644 --- a/apex/jobscheduler/service/java/com/android/server/tare/Ledger.java +++ b/apex/jobscheduler/service/java/com/android/server/tare/Ledger.java @@ -247,7 +247,7 @@ class Ledger { boolean printedTransactionTitle = false; for (int t = 0; t < Math.min(MAX_TRANSACTION_COUNT, numRecentTransactions); ++t) { - final int idx = (mTransactionIndex - t + MAX_TRANSACTION_COUNT) % MAX_TRANSACTION_COUNT; + final int idx = (mTransactionIndex + t) % MAX_TRANSACTION_COUNT; final Transaction transaction = mTransactions[idx]; if (transaction == null) { continue; diff --git a/api/OWNERS b/api/OWNERS index 4d8ed0347f43..bf6216c168e8 100644 --- a/api/OWNERS +++ b/api/OWNERS @@ -3,7 +3,7 @@ hansson@google.com # Modularization team file:platform/packages/modules/common:/OWNERS -per-file Android.bp = file:platform/build/soong:/OWNERS +per-file Android.bp = file:platform/build/soong:/OWNERS #{LAST_RESORT_SUGGESTION} # For metalava team to disable lint checks in platform -per-file Android.bp = aurimas@google.com,emberrose@google.com,sjgilbert@google.com
\ No newline at end of file +per-file Android.bp = aurimas@google.com,emberrose@google.com,sjgilbert@google.com diff --git a/cmds/bootanimation/BootAnimation.cpp b/cmds/bootanimation/BootAnimation.cpp index dae4570456cd..814800bcd9e5 100644 --- a/cmds/bootanimation/BootAnimation.cpp +++ b/cmds/bootanimation/BootAnimation.cpp @@ -615,10 +615,6 @@ void BootAnimation::resizeSurface(int newWidth, int newHeight) { mWidth = limitedSize.width; mHeight = limitedSize.height; - SurfaceComposerClient::Transaction t; - t.setSize(mFlingerSurfaceControl, mWidth, mHeight); - t.apply(); - EGLConfig config = getEglConfig(mDisplay); EGLSurface surface = eglCreateWindowSurface(mDisplay, config, mFlingerSurface.get(), nullptr); if (eglMakeCurrent(mDisplay, surface, surface, mContext) == EGL_FALSE) { diff --git a/cmds/idmap2/idmap2d/Idmap2Service.cpp b/cmds/idmap2/idmap2d/Idmap2Service.cpp index 073d987f5dad..083bbf01bf5b 100644 --- a/cmds/idmap2/idmap2d/Idmap2Service.cpp +++ b/cmds/idmap2/idmap2d/Idmap2Service.cpp @@ -235,9 +235,11 @@ Status Idmap2Service::createFabricatedOverlay( for (const auto& res : overlay.entries) { if (res.dataType == Res_value::TYPE_STRING) { - builder.SetResourceValue(res.resourceName, res.dataType, res.stringData.value()); + builder.SetResourceValue(res.resourceName, res.dataType, res.stringData.value(), + res.configuration.value_or(std::string())); } else { - builder.SetResourceValue(res.resourceName, res.dataType, res.data); + builder.SetResourceValue(res.resourceName, res.dataType, res.data, + res.configuration.value_or(std::string())); } } diff --git a/cmds/idmap2/idmap2d/aidl/core/android/os/FabricatedOverlayInternalEntry.aidl b/cmds/idmap2/idmap2d/aidl/core/android/os/FabricatedOverlayInternalEntry.aidl index a6824da8c424..c773e112997d 100644 --- a/cmds/idmap2/idmap2d/aidl/core/android/os/FabricatedOverlayInternalEntry.aidl +++ b/cmds/idmap2/idmap2d/aidl/core/android/os/FabricatedOverlayInternalEntry.aidl @@ -24,4 +24,5 @@ parcelable FabricatedOverlayInternalEntry { int dataType; int data; @nullable @utf8InCpp String stringData; + @nullable @utf8InCpp String configuration; }
\ No newline at end of file diff --git a/cmds/idmap2/include/idmap2/FabricatedOverlay.h b/cmds/idmap2/include/idmap2/FabricatedOverlay.h index 2fc4d43b798a..05b0618131c9 100644 --- a/cmds/idmap2/include/idmap2/FabricatedOverlay.h +++ b/cmds/idmap2/include/idmap2/FabricatedOverlay.h @@ -39,10 +39,11 @@ struct FabricatedOverlay { Builder& SetOverlayable(const std::string& name); Builder& SetResourceValue(const std::string& resource_name, uint8_t data_type, - uint32_t data_value); + uint32_t data_value, const std::string& configuration); Builder& SetResourceValue(const std::string& resource_name, uint8_t data_type, - const std::string& data_string_value); + const std::string& data_string_value, + const std::string& configuration); WARN_UNUSED Result<FabricatedOverlay> Build(); @@ -52,6 +53,7 @@ struct FabricatedOverlay { DataType data_type; DataValue data_value; std::string data_string_value; + std::string configuration; }; std::string package_name_; diff --git a/cmds/idmap2/include/idmap2/ResourceContainer.h b/cmds/idmap2/include/idmap2/ResourceContainer.h index c3ba4640bd77..2452ff0784ce 100644 --- a/cmds/idmap2/include/idmap2/ResourceContainer.h +++ b/cmds/idmap2/include/idmap2/ResourceContainer.h @@ -66,7 +66,7 @@ struct OverlayData { struct Value { std::string resource_name; - std::variant<ResourceIdValue, TargetValue> value; + std::variant<ResourceIdValue, TargetValueWithConfig> value; }; struct InlineStringPoolData { diff --git a/cmds/idmap2/include/idmap2/ResourceMapping.h b/cmds/idmap2/include/idmap2/ResourceMapping.h index 5a0a384f75a3..21862a3635d5 100644 --- a/cmds/idmap2/include/idmap2/ResourceMapping.h +++ b/cmds/idmap2/include/idmap2/ResourceMapping.h @@ -69,7 +69,8 @@ class ResourceMapping { // If `allow_rewriting_` is true, then the overlay-to-target map will be populated if the target // resource id is mapped to an overlay resource id. Result<Unit> AddMapping(ResourceId target_resource, - const std::variant<OverlayData::ResourceIdValue, TargetValue>& value); + const std::variant<OverlayData::ResourceIdValue, + TargetValueWithConfig>& value); TargetResourceMap target_map_; OverlayResourceMap overlay_map_; diff --git a/cmds/idmap2/include/idmap2/ResourceUtils.h b/cmds/idmap2/include/idmap2/ResourceUtils.h index 414aa064ada7..8ec749602c4a 100644 --- a/cmds/idmap2/include/idmap2/ResourceUtils.h +++ b/cmds/idmap2/include/idmap2/ResourceUtils.h @@ -43,6 +43,11 @@ struct TargetValue { std::string data_string_value; }; +struct TargetValueWithConfig { + TargetValue value; + std::string config; +}; + namespace utils { // Returns whether the Res_value::data_type represents a dynamic or regular resource reference. diff --git a/cmds/idmap2/libidmap2/FabricatedOverlay.cpp b/cmds/idmap2/libidmap2/FabricatedOverlay.cpp index 5bbe08524c18..bde9b0be4361 100644 --- a/cmds/idmap2/libidmap2/FabricatedOverlay.cpp +++ b/cmds/idmap2/libidmap2/FabricatedOverlay.cpp @@ -70,19 +70,22 @@ FabricatedOverlay::Builder& FabricatedOverlay::Builder::SetOverlayable(const std } FabricatedOverlay::Builder& FabricatedOverlay::Builder::SetResourceValue( - const std::string& resource_name, uint8_t data_type, uint32_t data_value) { - entries_.emplace_back(Entry{resource_name, data_type, data_value, ""}); + const std::string& resource_name, uint8_t data_type, uint32_t data_value, + const std::string& configuration) { + entries_.emplace_back(Entry{resource_name, data_type, data_value, "", configuration}); return *this; } FabricatedOverlay::Builder& FabricatedOverlay::Builder::SetResourceValue( - const std::string& resource_name, uint8_t data_type, const std::string& data_string_value) { - entries_.emplace_back(Entry{resource_name, data_type, 0, data_string_value}); + const std::string& resource_name, uint8_t data_type, const std::string& data_string_value, + const std::string& configuration) { + entries_.emplace_back(Entry{resource_name, data_type, 0, data_string_value, configuration}); return *this; } Result<FabricatedOverlay> FabricatedOverlay::Builder::Build() { - using EntryMap = std::map<std::string, TargetValue>; + using ConfigMap = std::map<std::string, TargetValue>; + using EntryMap = std::map<std::string, ConfigMap>; using TypeMap = std::map<std::string, EntryMap>; using PackageMap = std::map<std::string, TypeMap>; PackageMap package_map; @@ -123,11 +126,16 @@ Result<FabricatedOverlay> FabricatedOverlay::Builder::Build() { auto entry = type->second.find(entry_name.to_string()); if (entry == type->second.end()) { - entry = type->second.insert(std::make_pair(entry_name.to_string(), TargetValue())).first; + entry = type->second.insert(std::make_pair(entry_name.to_string(), ConfigMap())).first; } - entry->second = TargetValue{ - res_entry.data_type, res_entry.data_value, res_entry.data_string_value}; + auto value = entry->second.find(res_entry.configuration); + if (value == entry->second.end()) { + value = entry->second.insert(std::make_pair(res_entry.configuration, TargetValue())).first; + } + + value->second = TargetValue{res_entry.data_type, res_entry.data_value, + res_entry.data_string_value}; } pb::FabricatedOverlay overlay_pb; @@ -145,15 +153,18 @@ Result<FabricatedOverlay> FabricatedOverlay::Builder::Build() { type_pb->set_name(type.first); for (auto& entry : type.second) { - auto entry_pb = type_pb->add_entries(); - entry_pb->set_name(entry.first); - pb::ResourceValue* value = entry_pb->mutable_res_value(); - value->set_data_type(entry.second.data_type); - if (entry.second.data_type == Res_value::TYPE_STRING) { - auto ref = string_pool.MakeRef(entry.second.data_string_value); - value->set_data_value(ref.index()); - } else { - value->set_data_value(entry.second.data_value); + for (const auto& value: entry.second) { + auto entry_pb = type_pb->add_entries(); + entry_pb->set_name(entry.first); + entry_pb->set_configuration(value.first); + pb::ResourceValue* pb_value = entry_pb->mutable_res_value(); + pb_value->set_data_type(value.second.data_type); + if (value.second.data_type == Res_value::TYPE_STRING) { + auto ref = string_pool.MakeRef(value.second.data_string_value); + pb_value->set_data_value(ref.index()); + } else { + pb_value->set_data_value(value.second.data_value); + } } } } @@ -330,8 +341,9 @@ Result<OverlayData> FabContainer::GetOverlayData(const OverlayManifestInfo& info entry.name().c_str()); const auto& res_value = entry.res_value(); result.pairs.emplace_back(OverlayData::Value{ - name, TargetValue{.data_type = static_cast<uint8_t>(res_value.data_type()), - .data_value = res_value.data_value()}}); + name, TargetValueWithConfig{.config = entry.configuration(), .value = TargetValue{ + .data_type = static_cast<uint8_t>(res_value.data_type()), + .data_value = res_value.data_value()}}}); } } } diff --git a/cmds/idmap2/libidmap2/ResourceContainer.cpp b/cmds/idmap2/libidmap2/ResourceContainer.cpp index a62472c8f11e..0e3590486c6f 100644 --- a/cmds/idmap2/libidmap2/ResourceContainer.cpp +++ b/cmds/idmap2/libidmap2/ResourceContainer.cpp @@ -226,8 +226,10 @@ Result<OverlayData> CreateResourceMapping(ResourceId id, const ZipAssetsProvider *target_resource, OverlayData::ResourceIdValue{overlay_resource->data, rewrite_id}}); } else { overlay_data.pairs.emplace_back( - OverlayData::Value{*target_resource, TargetValue{.data_type = overlay_resource->dataType, - .data_value = overlay_resource->data}}); + OverlayData::Value{*target_resource, TargetValueWithConfig{ + .config = std::string(), + .value = TargetValue{.data_type = overlay_resource->dataType, + .data_value = overlay_resource->data}}}); } } diff --git a/cmds/idmap2/libidmap2/ResourceMapping.cpp b/cmds/idmap2/libidmap2/ResourceMapping.cpp index 3bbbf248c87d..8ebe5aa46e73 100644 --- a/cmds/idmap2/libidmap2/ResourceMapping.cpp +++ b/cmds/idmap2/libidmap2/ResourceMapping.cpp @@ -160,7 +160,7 @@ Result<ResourceMapping> ResourceMapping::FromContainers(const TargetResourceCont Result<Unit> ResourceMapping::AddMapping( ResourceId target_resource, - const std::variant<OverlayData::ResourceIdValue, TargetValue>& value) { + const std::variant<OverlayData::ResourceIdValue, TargetValueWithConfig>& value) { if (target_map_.find(target_resource) != target_map_.end()) { return Error(R"(target resource id "0x%08x" mapped to multiple values)", target_resource); } @@ -176,8 +176,8 @@ Result<Unit> ResourceMapping::AddMapping( overlay_map_.insert(std::make_pair(overlay_resource->overlay_id, target_resource)); } } else { - auto overlay_value = std::get<TargetValue>(value); - target_map_.insert(std::make_pair(target_resource, overlay_value)); + auto overlay_value = std::get<TargetValueWithConfig>(value); + target_map_.insert(std::make_pair(target_resource, overlay_value.value)); } return Unit{}; diff --git a/cmds/idmap2/libidmap2/proto/fabricated_v1.proto b/cmds/idmap2/libidmap2/proto/fabricated_v1.proto index a392b2b6d856..c7a79b31e151 100644 --- a/cmds/idmap2/libidmap2/proto/fabricated_v1.proto +++ b/cmds/idmap2/libidmap2/proto/fabricated_v1.proto @@ -46,6 +46,7 @@ message ResourceEntry { oneof value { ResourceValue res_value = 2; } + string configuration = 3; } message ResourceValue { diff --git a/cmds/idmap2/tests/FabricatedOverlayTests.cpp b/cmds/idmap2/tests/FabricatedOverlayTests.cpp index 91331ca1cc76..e804c879ee82 100644 --- a/cmds/idmap2/tests/FabricatedOverlayTests.cpp +++ b/cmds/idmap2/tests/FabricatedOverlayTests.cpp @@ -43,10 +43,17 @@ TEST(FabricatedOverlayTests, OverlayInfo) { TEST(FabricatedOverlayTests, SetResourceValue) { auto overlay = FabricatedOverlay::Builder("com.example.overlay", "SandTheme", "com.example.target") - .SetResourceValue("com.example.target:integer/int1", Res_value::TYPE_INT_DEC, 1U) - .SetResourceValue("com.example.target.split:integer/int2", Res_value::TYPE_INT_DEC, 2U) - .SetResourceValue("string/int3", Res_value::TYPE_REFERENCE, 0x7f010000) - .SetResourceValue("com.example.target:string/string1", Res_value::TYPE_STRING, "foobar") + .SetResourceValue( + "com.example.target:integer/int1", Res_value::TYPE_INT_DEC, 1U, "port") + .SetResourceValue( + "com.example.target.split:integer/int2", Res_value::TYPE_INT_DEC, 2U, "land") + .SetResourceValue( + "string/int3", Res_value::TYPE_REFERENCE, 0x7f010000, "xxhdpi-v7") + .SetResourceValue( + "com.example.target:string/string1", + Res_value::TYPE_STRING, + "foobar", + "en-rUS-normal-xxhdpi-v21") .Build(); ASSERT_TRUE(overlay); auto container = FabricatedOverlayContainer::FromOverlay(std::move(*overlay)); @@ -66,44 +73,48 @@ TEST(FabricatedOverlayTests, SetResourceValue) { auto& it = pairs->pairs[0]; ASSERT_EQ("com.example.target:integer/int1", it.resource_name); - auto entry = std::get_if<TargetValue>(&it.value); + auto entry = std::get_if<TargetValueWithConfig>(&it.value); ASSERT_NE(nullptr, entry); - ASSERT_EQ(1U, entry->data_value); - ASSERT_EQ(Res_value::TYPE_INT_DEC, entry->data_type); + ASSERT_EQ(1U, entry->value.data_value); + ASSERT_EQ(Res_value::TYPE_INT_DEC, entry->value.data_type); + ASSERT_EQ("port", entry->config); it = pairs->pairs[1]; ASSERT_EQ("com.example.target:string/int3", it.resource_name); - entry = std::get_if<TargetValue>(&it.value); + entry = std::get_if<TargetValueWithConfig>(&it.value); ASSERT_NE(nullptr, entry); - ASSERT_EQ(0x7f010000, entry->data_value); - ASSERT_EQ(Res_value::TYPE_REFERENCE, entry->data_type); + ASSERT_EQ(0x7f010000, entry->value.data_value); + ASSERT_EQ(Res_value::TYPE_REFERENCE, entry->value.data_type); + ASSERT_EQ("xxhdpi-v7", entry->config); it = pairs->pairs[2]; ASSERT_EQ("com.example.target:string/string1", it.resource_name); - entry = std::get_if<TargetValue>(&it.value); + entry = std::get_if<TargetValueWithConfig>(&it.value); ASSERT_NE(nullptr, entry); - ASSERT_EQ(Res_value::TYPE_STRING, entry->data_type); - ASSERT_EQ(std::string("foobar"), string_pool.string8At(entry->data_value).value_or("")); + ASSERT_EQ(Res_value::TYPE_STRING, entry->value.data_type); + ASSERT_EQ(std::string("foobar"), string_pool.string8At(entry->value.data_value).value_or("")); + ASSERT_EQ("en-rUS-normal-xxhdpi-v21", entry->config); it = pairs->pairs[3]; ASSERT_EQ("com.example.target.split:integer/int2", it.resource_name); - entry = std::get_if<TargetValue>(&it.value); + entry = std::get_if<TargetValueWithConfig>(&it.value); ASSERT_NE(nullptr, entry); - ASSERT_EQ(2U, entry->data_value); - ASSERT_EQ(Res_value::TYPE_INT_DEC, entry->data_type); + ASSERT_EQ(2U, entry->value.data_value); + ASSERT_EQ(Res_value::TYPE_INT_DEC, entry->value.data_type); + ASSERT_EQ("land", entry->config); } TEST(FabricatedOverlayTests, SetResourceValueBadArgs) { { auto builder = FabricatedOverlay::Builder("com.example.overlay", "SandTheme", "com.example.target") - .SetResourceValue("int1", Res_value::TYPE_INT_DEC, 1U); + .SetResourceValue("int1", Res_value::TYPE_INT_DEC, 1U, ""); ASSERT_FALSE(builder.Build()); } { auto builder = FabricatedOverlay::Builder("com.example.overlay", "SandTheme", "com.example.target") - .SetResourceValue("com.example.target:int2", Res_value::TYPE_INT_DEC, 1U); + .SetResourceValue("com.example.target:int2", Res_value::TYPE_INT_DEC, 1U, ""); ASSERT_FALSE(builder.Build()); } } @@ -112,8 +123,9 @@ TEST(FabricatedOverlayTests, SerializeAndDeserialize) { auto overlay = FabricatedOverlay::Builder("com.example.overlay", "SandTheme", "com.example.target") .SetOverlayable("TestResources") - .SetResourceValue("com.example.target:integer/int1", Res_value::TYPE_INT_DEC, 1U) - .SetResourceValue("com.example.target:string/string1", Res_value::TYPE_STRING, "foobar") + .SetResourceValue("com.example.target:integer/int1", Res_value::TYPE_INT_DEC, 1U, "") + .SetResourceValue( + "com.example.target:string/string1", Res_value::TYPE_STRING, "foobar", "") .Build(); ASSERT_TRUE(overlay); TemporaryFile tf; @@ -142,17 +154,17 @@ TEST(FabricatedOverlayTests, SerializeAndDeserialize) { auto& it = pairs->pairs[0]; ASSERT_EQ("com.example.target:integer/int1", it.resource_name); - auto entry = std::get_if<TargetValue>(&it.value); + auto entry = std::get_if<TargetValueWithConfig>(&it.value); ASSERT_NE(nullptr, entry); - EXPECT_EQ(1U, entry->data_value); - EXPECT_EQ(Res_value::TYPE_INT_DEC, entry->data_type); + EXPECT_EQ(1U, entry->value.data_value); + EXPECT_EQ(Res_value::TYPE_INT_DEC, entry->value.data_type); it = pairs->pairs[1]; ASSERT_EQ("com.example.target:string/string1", it.resource_name); - entry = std::get_if<TargetValue>(&it.value); + entry = std::get_if<TargetValueWithConfig>(&it.value); ASSERT_NE(nullptr, entry); - ASSERT_EQ(Res_value::TYPE_STRING, entry->data_type); - ASSERT_EQ(std::string("foobar"), string_pool.string8At(entry->data_value).value_or("")); + ASSERT_EQ(Res_value::TYPE_STRING, entry->value.data_type); + ASSERT_EQ(std::string("foobar"), string_pool.string8At(entry->value.data_value).value_or("")); } } // namespace android::idmap2 diff --git a/cmds/idmap2/tests/IdmapTests.cpp b/cmds/idmap2/tests/IdmapTests.cpp index a3799f98c90c..ee9a424b3050 100644 --- a/cmds/idmap2/tests/IdmapTests.cpp +++ b/cmds/idmap2/tests/IdmapTests.cpp @@ -261,9 +261,9 @@ TEST(IdmapTests, FabricatedOverlay) { auto frro = FabricatedOverlay::Builder("com.example.overlay", "SandTheme", "test.target") .SetOverlayable("TestResources") - .SetResourceValue("integer/int1", Res_value::TYPE_INT_DEC, 2U) - .SetResourceValue("string/str1", Res_value::TYPE_REFERENCE, 0x7f010000) - .SetResourceValue("string/str2", Res_value::TYPE_STRING, "foobar") + .SetResourceValue("integer/int1", Res_value::TYPE_INT_DEC, 2U, "") + .SetResourceValue("string/str1", Res_value::TYPE_REFERENCE, 0x7f010000, "") + .SetResourceValue("string/str2", Res_value::TYPE_STRING, "foobar", "") .Build(); ASSERT_TRUE(frro); diff --git a/cmds/idmap2/tests/ResourceMappingTests.cpp b/cmds/idmap2/tests/ResourceMappingTests.cpp index c05abcf31532..ca9a444bcb05 100644 --- a/cmds/idmap2/tests/ResourceMappingTests.cpp +++ b/cmds/idmap2/tests/ResourceMappingTests.cpp @@ -194,9 +194,9 @@ TEST(ResourceMappingTests, InlineResources) { TEST(ResourceMappingTests, FabricatedOverlay) { auto frro = FabricatedOverlay::Builder("com.example.overlay", "SandTheme", "test.target") .SetOverlayable("TestResources") - .SetResourceValue("integer/int1", Res_value::TYPE_INT_DEC, 2U) - .SetResourceValue("string/str1", Res_value::TYPE_REFERENCE, 0x7f010000) - .SetResourceValue("string/str2", Res_value::TYPE_STRING, "foobar") + .SetResourceValue("integer/int1", Res_value::TYPE_INT_DEC, 2U, "") + .SetResourceValue("string/str1", Res_value::TYPE_REFERENCE, 0x7f010000, "") + .SetResourceValue("string/str2", Res_value::TYPE_STRING, "foobar", "") .Build(); ASSERT_TRUE(frro); diff --git a/config/preloaded-classes-denylist b/config/preloaded-classes-denylist index 02f2df6167a5..502d8c6dadb1 100644 --- a/config/preloaded-classes-denylist +++ b/config/preloaded-classes-denylist @@ -9,3 +9,4 @@ android.net.rtp.AudioGroup android.net.rtp.AudioStream android.net.rtp.RtpStream java.util.concurrent.ThreadLocalRandom +com.android.internal.jank.InteractionJankMonitor$InstanceHolder diff --git a/core/api/current.txt b/core/api/current.txt index e0433399f374..317f8eb5c6b5 100644 --- a/core/api/current.txt +++ b/core/api/current.txt @@ -32264,6 +32264,7 @@ package android.os { method @NonNull @RequiresPermission(anyOf={"android.permission.MANAGE_USERS", "android.permission.QUERY_USERS", "android.permission.INTERACT_ACROSS_USERS"}, conditional=true) public android.content.pm.UserProperties getUserProperties(@NonNull android.os.UserHandle); method public android.os.Bundle getUserRestrictions(); method @RequiresPermission(anyOf={"android.permission.MANAGE_USERS", "android.permission.INTERACT_ACROSS_USERS"}, conditional=true) public android.os.Bundle getUserRestrictions(android.os.UserHandle); + method @NonNull @RequiresPermission(anyOf={"android.permission.MANAGE_USERS", "android.permission.INTERACT_ACROSS_USERS"}) public java.util.List<android.os.UserHandle> getVisibleUsers(); method public boolean hasUserRestriction(String); method public boolean isDemoUser(); method public static boolean isHeadlessSystemUserMode(); @@ -52986,6 +52987,22 @@ package android.view.inputmethod { method public android.view.inputmethod.CursorAnchorInfo.Builder setSelectionRange(int, int); } + public final class DeleteGesture extends android.view.inputmethod.HandwritingGesture implements android.os.Parcelable { + method public int describeContents(); + method @NonNull public android.graphics.RectF getDeletionArea(); + method public int getGranularity(); + method public void writeToParcel(@NonNull android.os.Parcel, int); + field @NonNull public static final android.os.Parcelable.Creator<android.view.inputmethod.DeleteGesture> CREATOR; + } + + public static final class DeleteGesture.Builder { + ctor public DeleteGesture.Builder(); + method @NonNull public android.view.inputmethod.DeleteGesture build(); + method @NonNull public android.view.inputmethod.DeleteGesture.Builder setDeletionArea(@NonNull android.graphics.RectF); + method @NonNull public android.view.inputmethod.DeleteGesture.Builder setFallbackText(@Nullable String); + method @NonNull public android.view.inputmethod.DeleteGesture.Builder setGranularity(int); + } + public final class EditorBoundsInfo implements android.os.Parcelable { method public int describeContents(); method @Nullable public android.graphics.RectF getEditorBounds(); @@ -53080,6 +53097,12 @@ package android.view.inputmethod { field public int token; } + public abstract class HandwritingGesture { + method @Nullable public String getFallbackText(); + field public static final int GRANULARITY_CHARACTER = 2; // 0x2 + field public static final int GRANULARITY_WORD = 1; // 0x1 + } + public final class InlineSuggestion implements android.os.Parcelable { method public int describeContents(); method @NonNull public android.view.inputmethod.InlineSuggestionInfo getInfo(); @@ -53170,6 +53193,7 @@ package android.view.inputmethod { method @Nullable public CharSequence getTextBeforeCursor(@IntRange(from=0) int, int); method public boolean performContextMenuAction(int); method public boolean performEditorAction(int); + method public default void performHandwritingGesture(@NonNull android.view.inputmethod.HandwritingGesture, @Nullable java.util.concurrent.Executor, @Nullable java.util.function.IntConsumer); method public boolean performPrivateCommand(String, android.os.Bundle); method public default boolean performSpellCheck(); method public boolean reportFullscreenMode(boolean); @@ -53391,6 +53415,38 @@ package android.view.inputmethod { method public android.view.inputmethod.InputMethodSubtype.InputMethodSubtypeBuilder setSubtypeNameResId(int); } + public final class InsertGesture extends android.view.inputmethod.HandwritingGesture implements android.os.Parcelable { + method public int describeContents(); + method @Nullable public android.graphics.PointF getInsertionPoint(); + method @Nullable public String getTextToInsert(); + method public void writeToParcel(@NonNull android.os.Parcel, int); + field @NonNull public static final android.os.Parcelable.Creator<android.view.inputmethod.InsertGesture> CREATOR; + } + + public static final class InsertGesture.Builder { + ctor public InsertGesture.Builder(); + method @NonNull public android.view.inputmethod.InsertGesture build(); + method @NonNull public android.view.inputmethod.InsertGesture.Builder setFallbackText(@Nullable String); + method @NonNull public android.view.inputmethod.InsertGesture.Builder setInsertionPoint(@NonNull android.graphics.PointF); + method @NonNull public android.view.inputmethod.InsertGesture.Builder setTextToInsert(@NonNull String); + } + + public final class SelectGesture extends android.view.inputmethod.HandwritingGesture implements android.os.Parcelable { + method public int describeContents(); + method public int getGranularity(); + method @NonNull public android.graphics.RectF getSelectionArea(); + method public void writeToParcel(@NonNull android.os.Parcel, int); + field @NonNull public static final android.os.Parcelable.Creator<android.view.inputmethod.SelectGesture> CREATOR; + } + + public static final class SelectGesture.Builder { + ctor public SelectGesture.Builder(); + method @NonNull public android.view.inputmethod.SelectGesture build(); + method @NonNull public android.view.inputmethod.SelectGesture.Builder setFallbackText(@Nullable String); + method @NonNull public android.view.inputmethod.SelectGesture.Builder setGranularity(int); + method @NonNull public android.view.inputmethod.SelectGesture.Builder setSelectionArea(@NonNull android.graphics.RectF); + } + public final class SurroundingText implements android.os.Parcelable { ctor public SurroundingText(@NonNull CharSequence, @IntRange(from=0) int, @IntRange(from=0) int, @IntRange(from=0xffffffff) int); method public int describeContents(); diff --git a/core/api/system-current.txt b/core/api/system-current.txt index a0cc4f0d6775..2b2f2023bef6 100644 --- a/core/api/system-current.txt +++ b/core/api/system-current.txt @@ -320,6 +320,7 @@ package android { field public static final String START_ACTIVITIES_FROM_BACKGROUND = "android.permission.START_ACTIVITIES_FROM_BACKGROUND"; field public static final String START_CROSS_PROFILE_ACTIVITIES = "android.permission.START_CROSS_PROFILE_ACTIVITIES"; field public static final String START_REVIEW_PERMISSION_DECISIONS = "android.permission.START_REVIEW_PERMISSION_DECISIONS"; + field public static final String START_TASKS_FROM_RECENTS = "android.permission.START_TASKS_FROM_RECENTS"; field public static final String STATUS_BAR_SERVICE = "android.permission.STATUS_BAR_SERVICE"; field public static final String STOP_APP_SWITCHES = "android.permission.STOP_APP_SWITCHES"; field public static final String SUBSTITUTE_NOTIFICATION_APP_NAME = "android.permission.SUBSTITUTE_NOTIFICATION_APP_NAME"; @@ -507,7 +508,7 @@ package android.app { public class ActivityOptions { method public int getLaunchTaskId(); - method @RequiresPermission("android.permission.START_TASKS_FROM_RECENTS") public void setLaunchTaskId(int); + method @RequiresPermission(android.Manifest.permission.START_TASKS_FROM_RECENTS) public void setLaunchTaskId(int); } public class AlarmManager { diff --git a/core/api/test-current.txt b/core/api/test-current.txt index fefdfd8d7b15..f45298a630cd 100644 --- a/core/api/test-current.txt +++ b/core/api/test-current.txt @@ -42,7 +42,6 @@ package android { field public static final String SET_AND_VERIFY_LOCKSCREEN_CREDENTIALS = "android.permission.SET_AND_VERIFY_LOCKSCREEN_CREDENTIALS"; field public static final String SET_GAME_SERVICE = "android.permission.SET_GAME_SERVICE"; field public static final String SET_KEYBOARD_LAYOUT = "android.permission.SET_KEYBOARD_LAYOUT"; - field public static final String START_TASKS_FROM_RECENTS = "android.permission.START_TASKS_FROM_RECENTS"; field public static final String SUSPEND_APPS = "android.permission.SUSPEND_APPS"; field public static final String TEST_BIOMETRIC = "android.permission.TEST_BIOMETRIC"; field public static final String TEST_MANAGE_ROLLBACKS = "android.permission.TEST_MANAGE_ROLLBACKS"; @@ -3204,6 +3203,11 @@ package android.widget { method public android.widget.ListView getMenuListView(); } + public class RatingBar extends android.widget.AbsSeekBar { + field public static final String PLURALS_MAX = "max"; + field public static final String PLURALS_RATING = "rating"; + } + public class Spinner extends android.widget.AbsSpinner implements android.content.DialogInterface.OnClickListener { method public boolean isPopupShowing(); } diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java index 25ef6e833565..c2b315f7088d 100644 --- a/core/java/android/app/Activity.java +++ b/core/java/android/app/Activity.java @@ -980,7 +980,8 @@ public class Activity extends ContextThemeWrapper boolean mEnterAnimationComplete; private boolean mIsInMultiWindowMode; - private boolean mIsInPictureInPictureMode; + /** @hide */ + boolean mIsInPictureInPictureMode; private boolean mShouldDockBigOverlays; diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java index b383d7daafd0..db7681640c67 100644 --- a/core/java/android/app/ActivityThread.java +++ b/core/java/android/app/ActivityThread.java @@ -4177,7 +4177,8 @@ public final class ActivityThread extends ClientTransactionHandler private void schedulePauseWithUserLeavingHint(ActivityClientRecord r) { final ClientTransaction transaction = ClientTransaction.obtain(this.mAppThread, r.token); transaction.setLifecycleStateRequest(PauseActivityItem.obtain(r.activity.isFinishing(), - /* userLeaving */ true, r.activity.mConfigChangeFlags, /* dontReport */ false)); + /* userLeaving */ true, r.activity.mConfigChangeFlags, /* dontReport */ false, + /* autoEnteringPip */ false)); executeTransaction(transaction); } @@ -4965,12 +4966,18 @@ public final class ActivityThread extends ClientTransactionHandler @Override public void handlePauseActivity(ActivityClientRecord r, boolean finished, boolean userLeaving, - int configChanges, PendingTransactionActions pendingActions, String reason) { + int configChanges, boolean autoEnteringPip, PendingTransactionActions pendingActions, + String reason) { if (userLeaving) { performUserLeavingActivity(r); } r.activity.mConfigChangeFlags |= configChanges; + if (autoEnteringPip) { + // Set mIsInPictureInPictureMode earlier in case of auto-enter-pip, see also + // {@link Activity#enterPictureInPictureMode(PictureInPictureParams)}. + r.activity.mIsInPictureInPictureMode = true; + } performPauseActivity(r, finished, reason, pendingActions); // Make sure any pending writes are now committed. diff --git a/core/java/android/app/AppOpsManager.java b/core/java/android/app/AppOpsManager.java index d6b90a2792a9..2a5916dfb6a8 100644 --- a/core/java/android/app/AppOpsManager.java +++ b/core/java/android/app/AppOpsManager.java @@ -1906,7 +1906,6 @@ public class AppOpsManager { OP_SCHEDULE_EXACT_ALARM, OP_MANAGE_MEDIA, OP_TURN_SCREEN_ON, - OP_GET_USAGE_STATS, }; static final AppOpInfo[] sAppOpInfos = new AppOpInfo[]{ diff --git a/core/java/android/app/ClientTransactionHandler.java b/core/java/android/app/ClientTransactionHandler.java index 389da2d094d5..f322ca9654ed 100644 --- a/core/java/android/app/ClientTransactionHandler.java +++ b/core/java/android/app/ClientTransactionHandler.java @@ -96,8 +96,8 @@ public abstract class ClientTransactionHandler { /** Pause the activity. */ public abstract void handlePauseActivity(@NonNull ActivityClientRecord r, boolean finished, - boolean userLeaving, int configChanges, PendingTransactionActions pendingActions, - String reason); + boolean userLeaving, int configChanges, boolean autoEnteringPip, + PendingTransactionActions pendingActions, String reason); /** * Resume the activity. diff --git a/core/java/android/app/NotificationChannelGroup.java b/core/java/android/app/NotificationChannelGroup.java index 807bd5764cba..2b245aae915f 100644 --- a/core/java/android/app/NotificationChannelGroup.java +++ b/core/java/android/app/NotificationChannelGroup.java @@ -20,7 +20,6 @@ import android.annotation.SystemApi; import android.annotation.TestApi; import android.compat.annotation.UnsupportedAppUsage; import android.content.Intent; -import android.content.pm.ParceledListSlice; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; @@ -68,7 +67,7 @@ public final class NotificationChannelGroup implements Parcelable { private CharSequence mName; private String mDescription; private boolean mBlocked; - private ParceledListSlice<NotificationChannel> mChannels; + private List<NotificationChannel> mChannels = new ArrayList<>(); // Bitwise representation of fields that have been changed by the user private int mUserLockedFields; @@ -103,8 +102,7 @@ public final class NotificationChannelGroup implements Parcelable { } else { mDescription = null; } - mChannels = in.readParcelable( - NotificationChannelGroup.class.getClassLoader(), ParceledListSlice.class); + in.readParcelableList(mChannels, NotificationChannel.class.getClassLoader(), android.app.NotificationChannel.class); mBlocked = in.readBoolean(); mUserLockedFields = in.readInt(); } @@ -131,7 +129,7 @@ public final class NotificationChannelGroup implements Parcelable { } else { dest.writeByte((byte) 0); } - dest.writeParcelable(mChannels, flags); + dest.writeParcelableList(mChannels, flags); dest.writeBoolean(mBlocked); dest.writeInt(mUserLockedFields); } @@ -161,7 +159,7 @@ public final class NotificationChannelGroup implements Parcelable { * Returns the list of channels that belong to this group */ public List<NotificationChannel> getChannels() { - return mChannels == null ? new ArrayList<>() : mChannels.getList(); + return mChannels; } /** @@ -195,8 +193,15 @@ public final class NotificationChannelGroup implements Parcelable { /** * @hide */ + public void addChannel(NotificationChannel channel) { + mChannels.add(channel); + } + + /** + * @hide + */ public void setChannels(List<NotificationChannel> channels) { - mChannels = new ParceledListSlice<>(channels); + mChannels = channels; } /** @@ -331,7 +336,7 @@ public final class NotificationChannelGroup implements Parcelable { proto.write(NotificationChannelGroupProto.NAME, mName.toString()); proto.write(NotificationChannelGroupProto.DESCRIPTION, mDescription); proto.write(NotificationChannelGroupProto.IS_BLOCKED, mBlocked); - for (NotificationChannel channel : mChannels.getList()) { + for (NotificationChannel channel : mChannels) { channel.dumpDebug(proto, NotificationChannelGroupProto.CHANNELS); } proto.end(token); diff --git a/core/java/android/app/servertransaction/PauseActivityItem.java b/core/java/android/app/servertransaction/PauseActivityItem.java index 813e0f93a1f7..965e761ebfb3 100644 --- a/core/java/android/app/servertransaction/PauseActivityItem.java +++ b/core/java/android/app/servertransaction/PauseActivityItem.java @@ -39,13 +39,14 @@ public class PauseActivityItem extends ActivityLifecycleItem { private boolean mUserLeaving; private int mConfigChanges; private boolean mDontReport; + private boolean mAutoEnteringPip; @Override public void execute(ClientTransactionHandler client, ActivityClientRecord r, PendingTransactionActions pendingActions) { Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityPause"); - client.handlePauseActivity(r, mFinished, mUserLeaving, mConfigChanges, pendingActions, - "PAUSE_ACTIVITY_ITEM"); + client.handlePauseActivity(r, mFinished, mUserLeaving, mConfigChanges, mAutoEnteringPip, + pendingActions, "PAUSE_ACTIVITY_ITEM"); Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER); } @@ -71,7 +72,7 @@ public class PauseActivityItem extends ActivityLifecycleItem { /** Obtain an instance initialized with provided params. */ public static PauseActivityItem obtain(boolean finished, boolean userLeaving, int configChanges, - boolean dontReport) { + boolean dontReport, boolean autoEnteringPip) { PauseActivityItem instance = ObjectPool.obtain(PauseActivityItem.class); if (instance == null) { instance = new PauseActivityItem(); @@ -80,6 +81,7 @@ public class PauseActivityItem extends ActivityLifecycleItem { instance.mUserLeaving = userLeaving; instance.mConfigChanges = configChanges; instance.mDontReport = dontReport; + instance.mAutoEnteringPip = autoEnteringPip; return instance; } @@ -94,6 +96,7 @@ public class PauseActivityItem extends ActivityLifecycleItem { instance.mUserLeaving = false; instance.mConfigChanges = 0; instance.mDontReport = true; + instance.mAutoEnteringPip = false; return instance; } @@ -105,6 +108,7 @@ public class PauseActivityItem extends ActivityLifecycleItem { mUserLeaving = false; mConfigChanges = 0; mDontReport = false; + mAutoEnteringPip = false; ObjectPool.recycle(this); } @@ -117,6 +121,7 @@ public class PauseActivityItem extends ActivityLifecycleItem { dest.writeBoolean(mUserLeaving); dest.writeInt(mConfigChanges); dest.writeBoolean(mDontReport); + dest.writeBoolean(mAutoEnteringPip); } /** Read from Parcel. */ @@ -125,6 +130,7 @@ public class PauseActivityItem extends ActivityLifecycleItem { mUserLeaving = in.readBoolean(); mConfigChanges = in.readInt(); mDontReport = in.readBoolean(); + mAutoEnteringPip = in.readBoolean(); } public static final @NonNull Creator<PauseActivityItem> CREATOR = @@ -148,7 +154,8 @@ public class PauseActivityItem extends ActivityLifecycleItem { } final PauseActivityItem other = (PauseActivityItem) o; return mFinished == other.mFinished && mUserLeaving == other.mUserLeaving - && mConfigChanges == other.mConfigChanges && mDontReport == other.mDontReport; + && mConfigChanges == other.mConfigChanges && mDontReport == other.mDontReport + && mAutoEnteringPip == other.mAutoEnteringPip; } @Override @@ -158,12 +165,14 @@ public class PauseActivityItem extends ActivityLifecycleItem { result = 31 * result + (mUserLeaving ? 1 : 0); result = 31 * result + mConfigChanges; result = 31 * result + (mDontReport ? 1 : 0); + result = 31 * result + (mAutoEnteringPip ? 1 : 0); return result; } @Override public String toString() { return "PauseActivityItem{finished=" + mFinished + ",userLeaving=" + mUserLeaving - + ",configChanges=" + mConfigChanges + ",dontReport=" + mDontReport + "}"; + + ",configChanges=" + mConfigChanges + ",dontReport=" + mDontReport + + ",autoEnteringPip=" + mAutoEnteringPip + "}"; } } diff --git a/core/java/android/app/servertransaction/TransactionExecutor.java b/core/java/android/app/servertransaction/TransactionExecutor.java index 25ff8a78a0c8..de1d38a64163 100644 --- a/core/java/android/app/servertransaction/TransactionExecutor.java +++ b/core/java/android/app/servertransaction/TransactionExecutor.java @@ -227,7 +227,8 @@ public class TransactionExecutor { break; case ON_PAUSE: mTransactionHandler.handlePauseActivity(r, false /* finished */, - false /* userLeaving */, 0 /* configChanges */, mPendingActions, + false /* userLeaving */, 0 /* configChanges */, + false /* autoEnteringPip */, mPendingActions, "LIFECYCLER_PAUSE_ACTIVITY"); break; case ON_STOP: diff --git a/core/java/android/companion/CompanionDeviceManager.java b/core/java/android/companion/CompanionDeviceManager.java index 8ffc6a28bef3..c1a3c1934dbb 100644 --- a/core/java/android/companion/CompanionDeviceManager.java +++ b/core/java/android/companion/CompanionDeviceManager.java @@ -1008,6 +1008,22 @@ public final class CompanionDeviceManager { } } + /** + * Checks whether the calling companion application is currently bound. + * + * @return true if application is bound, false otherwise + * @hide + */ + @UserHandleAware + public boolean isCompanionApplicationBound() { + try { + return mService.isCompanionApplicationBound( + mContext.getOpPackageName(), mContext.getUserId()); + } catch (RemoteException e) { + throw e.rethrowFromSystemServer(); + } + } + private boolean checkFeaturePresent() { boolean featurePresent = mService != null; if (!featurePresent && DEBUG) { diff --git a/core/java/android/companion/ICompanionDeviceManager.aidl b/core/java/android/companion/ICompanionDeviceManager.aidl index 6e6e18765639..17e313252010 100644 --- a/core/java/android/companion/ICompanionDeviceManager.aidl +++ b/core/java/android/companion/ICompanionDeviceManager.aidl @@ -80,4 +80,6 @@ interface ICompanionDeviceManager { void attachSystemDataTransport(String packageName, int userId, int associationId, in ParcelFileDescriptor fd); void detachSystemDataTransport(String packageName, int userId, int associationId); + + boolean isCompanionApplicationBound(String packageName, int userId); } diff --git a/core/java/android/content/om/FabricatedOverlay.java b/core/java/android/content/om/FabricatedOverlay.java index 5efc1f9f7cca..3ca056097c1f 100644 --- a/core/java/android/content/om/FabricatedOverlay.java +++ b/core/java/android/content/om/FabricatedOverlay.java @@ -112,6 +112,28 @@ public class FabricatedOverlay { * @param resourceName name of the target resource to overlay (in the form * [package]:type/entry) * @param dataType the data type of the new value + * @param value the unsigned 32 bit integer representing the new value + * @param configuration The string representation of the config this overlay is enabled for + * + * @see android.util.TypedValue#type + */ + public Builder setResourceValue(@NonNull String resourceName, int dataType, int value, + String configuration) { + final FabricatedOverlayInternalEntry entry = new FabricatedOverlayInternalEntry(); + entry.resourceName = resourceName; + entry.dataType = dataType; + entry.data = value; + entry.configuration = configuration; + mEntries.add(entry); + return this; + } + + /** + * Sets the value of the fabricated overlay + * + * @param resourceName name of the target resource to overlay (in the form + * [package]:type/entry) + * @param dataType the data type of the new value * @param value the string representing the new value * * @see android.util.TypedValue#type @@ -125,6 +147,28 @@ public class FabricatedOverlay { return this; } + /** + * Sets the value of the fabricated overlay + * + * @param resourceName name of the target resource to overlay (in the form + * [package]:type/entry) + * @param dataType the data type of the new value + * @param value the string representing the new value + * @param configuration The string representation of the config this overlay is enabled for + * + * @see android.util.TypedValue#type + */ + public Builder setResourceValue(@NonNull String resourceName, int dataType, String value, + String configuration) { + final FabricatedOverlayInternalEntry entry = new FabricatedOverlayInternalEntry(); + entry.resourceName = resourceName; + entry.dataType = dataType; + entry.stringData = value; + entry.configuration = configuration; + mEntries.add(entry); + return this; + } + /** Builds an immutable fabricated overlay. */ public FabricatedOverlay build() { final FabricatedOverlayInternal overlay = new FabricatedOverlayInternal(); diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java index 5839b877a448..8e2a5eaff2d2 100644 --- a/core/java/android/content/pm/PackageManager.java +++ b/core/java/android/content/pm/PackageManager.java @@ -8065,7 +8065,7 @@ public abstract class PackageManager { } PackageParser.Package pkg = parser.parsePackage(apkFile, 0, false); - if ((flagsBits & GET_SIGNATURES) != 0) { + if ((flagsBits & GET_SIGNATURES) != 0 || (flagsBits & GET_SIGNING_CERTIFICATES) != 0) { PackageParser.collectCertificates(pkg, false /* skipVerify */); } return PackageParser.generatePackageInfo(pkg, null, (int) flagsBits, 0, 0, null, diff --git a/core/java/android/inputmethodservice/IInputMethodWrapper.java b/core/java/android/inputmethodservice/IInputMethodWrapper.java index 3d593872757d..05daf63fdd5d 100644 --- a/core/java/android/inputmethodservice/IInputMethodWrapper.java +++ b/core/java/android/inputmethodservice/IInputMethodWrapper.java @@ -81,6 +81,7 @@ class IInputMethodWrapper extends IInputMethod.Stub private static final int DO_INIT_INK_WINDOW = 120; private static final int DO_FINISH_STYLUS_HANDWRITING = 130; private static final int DO_UPDATE_TOOL_TYPE = 140; + private static final int DO_REMOVE_STYLUS_HANDWRITING_WINDOW = 150; final WeakReference<InputMethodServiceInternal> mTarget; final Context mContext; @@ -254,6 +255,10 @@ class IInputMethodWrapper extends IInputMethod.Stub inputMethod.finishStylusHandwriting(); return; } + case DO_REMOVE_STYLUS_HANDWRITING_WINDOW: { + inputMethod.removeStylusHandwritingWindow(); + return; + } } Log.w(TAG, "Unhandled message code: " + msg.what); @@ -434,4 +439,10 @@ class IInputMethodWrapper extends IInputMethod.Stub public void finishStylusHandwriting() { mCaller.executeOrSendMessage(mCaller.obtainMessage(DO_FINISH_STYLUS_HANDWRITING)); } + + @BinderThread + @Override + public void removeStylusHandwritingWindow() { + mCaller.executeOrSendMessage(mCaller.obtainMessage(DO_REMOVE_STYLUS_HANDWRITING_WINDOW)); + } } diff --git a/core/java/android/inputmethodservice/IRemoteInputConnectionInvoker.java b/core/java/android/inputmethodservice/IRemoteInputConnectionInvoker.java index e38e61122786..3260713a7d14 100644 --- a/core/java/android/inputmethodservice/IRemoteInputConnectionInvoker.java +++ b/core/java/android/inputmethodservice/IRemoteInputConnectionInvoker.java @@ -17,6 +17,7 @@ package android.inputmethodservice; import android.annotation.AnyThread; +import android.annotation.CallbackExecutor; import android.annotation.NonNull; import android.annotation.Nullable; import android.os.Bundle; @@ -24,9 +25,13 @@ import android.os.RemoteException; import android.view.KeyEvent; import android.view.inputmethod.CompletionInfo; import android.view.inputmethod.CorrectionInfo; +import android.view.inputmethod.DeleteGesture; import android.view.inputmethod.ExtractedText; import android.view.inputmethod.ExtractedTextRequest; +import android.view.inputmethod.HandwritingGesture; import android.view.inputmethod.InputContentInfo; +import android.view.inputmethod.InsertGesture; +import android.view.inputmethod.SelectGesture; import android.view.inputmethod.SurroundingText; import android.view.inputmethod.TextAttribute; @@ -35,6 +40,8 @@ import com.android.internal.inputmethod.IRemoteInputConnection; import com.android.internal.inputmethod.InputConnectionCommandHeader; import java.util.Objects; +import java.util.concurrent.Executor; +import java.util.function.IntConsumer; /** * A stateless wrapper of {@link com.android.internal.inputmethod.IRemoteInputConnection} to @@ -591,6 +598,27 @@ final class IRemoteInputConnectionInvoker { } } + @AnyThread + public void performHandwritingGesture( + @NonNull HandwritingGesture gesture, @Nullable @CallbackExecutor Executor executor, + @Nullable IntConsumer consumer) { + // TODO(b/210039666): implement resultReceiver + try { + if (gesture instanceof SelectGesture) { + mConnection.performHandwritingSelectGesture( + createHeader(), (SelectGesture) gesture, null); + } else if (gesture instanceof InsertGesture) { + mConnection.performHandwritingInsertGesture( + createHeader(), (InsertGesture) gesture, null); + } else if (gesture instanceof DeleteGesture) { + mConnection.performHandwritingDeleteGesture( + createHeader(), (DeleteGesture) gesture, null); + } + } catch (RemoteException e) { + // TODO(b/210039666): return result + } + } + /** * Invokes {@link IRemoteInputConnection#requestCursorUpdates(InputConnectionCommandHeader, int, * int, AndroidFuture)}. diff --git a/core/java/android/inputmethodservice/InputMethodService.java b/core/java/android/inputmethodservice/InputMethodService.java index c2027b136f0e..48b9b8869cae 100644 --- a/core/java/android/inputmethodservice/InputMethodService.java +++ b/core/java/android/inputmethodservice/InputMethodService.java @@ -621,7 +621,7 @@ public class InputMethodService extends AbstractInputMethodService { private boolean mDestroyed; private boolean mOnPreparedStylusHwCalled; - /** Stylus handwriting Ink window. */ + /** Stylus handwriting Ink window. */ private InkWindow mInkWindow; /** @@ -708,9 +708,6 @@ public class InputMethodService extends AbstractInputMethodService { mConfigTracker.onInitialize(params.configChanges); mPrivOps.set(params.privilegedOperations); InputMethodPrivilegedOperationsRegistry.put(params.token, mPrivOps); - if (params.stylusHandWritingSupported) { - mInkWindow = new InkWindow(mWindow.getContext()); - } mNavigationBarController.onNavButtonFlagsChanged(params.navigationBarFlags); attachToken(params.token); Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER); @@ -744,9 +741,6 @@ public class InputMethodService extends AbstractInputMethodService { attachToWindowToken(token); mToken = token; mWindow.setToken(token); - if (mInkWindow != null) { - mInkWindow.setToken(token); - } } /** @@ -785,7 +779,7 @@ public class InputMethodService extends AbstractInputMethodService { mInputConnection = null; // free-up cached InkWindow surface on detaching from current client. if (mInkWindow != null) { - mInkWindow.hide(true /* remove */); + removeHandwritingInkWindow(); } } @@ -972,6 +966,7 @@ public class InputMethodService extends AbstractInputMethodService { Log.d(TAG, "Input should have started before starting Stylus handwriting."); return; } + maybeCreateInkWindow(); if (!mOnPreparedStylusHwCalled) { // prepare hasn't been called by Stylus HOVER. onPrepareStylusHandwriting(); @@ -1031,12 +1026,24 @@ public class InputMethodService extends AbstractInputMethodService { */ @Override public void initInkWindow() { + maybeCreateInkWindow(); mInkWindow.initOnly(); onPrepareStylusHandwriting(); mOnPreparedStylusHwCalled = true; } /** + * Create and attach token to Ink window if it wasn't already created. + */ + private void maybeCreateInkWindow() { + if (mInkWindow == null) { + mInkWindow = new InkWindow(mWindow.getContext()); + mInkWindow.setToken(mToken); + } + // TODO(b/243571274): set an idle-timeout after which InkWindow is removed. + } + + /** * {@inheritDoc} * @hide */ @@ -1047,6 +1054,15 @@ public class InputMethodService extends AbstractInputMethodService { /** * {@inheritDoc} + * @hide + */ + @Override + public void removeStylusHandwritingWindow() { + InputMethodService.this.removeStylusHandwritingWindow(); + } + + /** + * {@inheritDoc} */ @MainThread @Override @@ -2511,6 +2527,7 @@ public class InputMethodService extends AbstractInputMethodService { mHandwritingEventReceiver.dispose(); mHandwritingEventReceiver = null; + // TODO(b/243571274): set an idle-timeout after which InkWindow is removed. mInkWindow.hide(false /* remove */); mPrivOps.resetStylusHandwriting(requestId); @@ -2519,6 +2536,27 @@ public class InputMethodService extends AbstractInputMethodService { } /** + * Remove Stylus handwriting window. + * Typically, this is called when {@link InkWindow} should no longer be holding a surface in + * memory. + */ + private void removeStylusHandwritingWindow() { + if (mInkWindow != null) { + if (mHandwritingRequestId.isPresent()) { + // if handwriting session is still ongoing. This shouldn't happen. + finishStylusHandwriting(); + } + removeHandwritingInkWindow(); + } + } + + private void removeHandwritingInkWindow() { + mInkWindow.hide(true /* remove */); + mInkWindow.destroy(); + mInkWindow = null; + } + + /** * Sets the duration after which an ongoing stylus handwriting session that hasn't received new * {@link MotionEvent}s will time out and {@link #finishStylusHandwriting()} will be called. * diff --git a/core/java/android/inputmethodservice/RemoteInputConnection.java b/core/java/android/inputmethodservice/RemoteInputConnection.java index 2711c4f0db1f..694293c62bd7 100644 --- a/core/java/android/inputmethodservice/RemoteInputConnection.java +++ b/core/java/android/inputmethodservice/RemoteInputConnection.java @@ -17,6 +17,7 @@ package android.inputmethodservice; import android.annotation.AnyThread; +import android.annotation.CallbackExecutor; import android.annotation.IntRange; import android.annotation.NonNull; import android.annotation.Nullable; @@ -28,6 +29,7 @@ import android.view.inputmethod.CompletionInfo; import android.view.inputmethod.CorrectionInfo; import android.view.inputmethod.ExtractedText; import android.view.inputmethod.ExtractedTextRequest; +import android.view.inputmethod.HandwritingGesture; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputContentInfo; import android.view.inputmethod.SurroundingText; @@ -41,6 +43,8 @@ import com.android.internal.inputmethod.InputConnectionProtoDumper; import java.lang.ref.WeakReference; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import java.util.function.IntConsumer; /** * Takes care of remote method invocations of {@link InputConnection} in the IME side. @@ -411,6 +415,13 @@ final class RemoteInputConnection implements InputConnection { } @AnyThread + public void performHandwritingGesture( + @NonNull HandwritingGesture gesture, @Nullable @CallbackExecutor Executor executor, + @Nullable IntConsumer consumer) { + mInvoker.performHandwritingGesture(gesture, executor, consumer); + } + + @AnyThread public boolean requestCursorUpdates(int cursorUpdateMode) { if (mCancellationGroup.isCanceled()) { return false; diff --git a/core/java/android/os/BatteryStats.java b/core/java/android/os/BatteryStats.java index 9d05cec06d01..09a52e452f9a 100644 --- a/core/java/android/os/BatteryStats.java +++ b/core/java/android/os/BatteryStats.java @@ -955,7 +955,16 @@ public abstract class BatteryStats { public static final int NUM_WIFI_BATCHED_SCAN_BINS = 5; - public static final int NUM_USER_ACTIVITY_TYPES = PowerManager.USER_ACTIVITY_EVENT_MAX + 1; + /** + * Note that these must match the constants in android.os.PowerManager. + * Also, if the user activity types change, the BatteryStatsImpl.VERSION must + * also be bumped. + */ + static final String[] USER_ACTIVITY_TYPES = { + "other", "button", "touch", "accessibility", "attention" + }; + + public static final int NUM_USER_ACTIVITY_TYPES = USER_ACTIVITY_TYPES.length; public abstract void noteUserActivityLocked(int type); public abstract boolean hasUserActivity(); @@ -6159,7 +6168,7 @@ public abstract class BatteryStats { } sb.append(val); sb.append(" "); - sb.append(PowerManager.userActivityEventToString(i)); + sb.append(Uid.USER_ACTIVITY_TYPES[i]); } } if (hasData) { diff --git a/core/java/android/os/IUserManager.aidl b/core/java/android/os/IUserManager.aidl index fa6b1189f1da..88649cbf9e42 100644 --- a/core/java/android/os/IUserManager.aidl +++ b/core/java/android/os/IUserManager.aidl @@ -129,6 +129,7 @@ interface IUserManager { boolean isUserRunning(int userId); boolean isUserForeground(int userId); boolean isUserVisible(int userId); + List<UserHandle> getVisibleUsers(); boolean isUserNameSet(int userId); boolean hasRestrictedProfiles(int userId); boolean requestQuietModeEnabled(String callingPackage, boolean enableQuietMode, int userId, in IntentSender target, int flags); diff --git a/core/java/android/os/PowerManager.java b/core/java/android/os/PowerManager.java index a3a3e3f80f3d..01b75d104e5e 100644 --- a/core/java/android/os/PowerManager.java +++ b/core/java/android/os/PowerManager.java @@ -348,44 +348,6 @@ public final class PowerManager { public static final int USER_ACTIVITY_EVENT_DEVICE_STATE = 6; /** - * @hide - */ - public static final int USER_ACTIVITY_EVENT_MAX = USER_ACTIVITY_EVENT_DEVICE_STATE; - - /** - * @hide - */ - @IntDef(prefix = { "USER_ACTIVITY_EVENT_" }, value = { - USER_ACTIVITY_EVENT_OTHER, - USER_ACTIVITY_EVENT_BUTTON, - USER_ACTIVITY_EVENT_TOUCH, - USER_ACTIVITY_EVENT_ACCESSIBILITY, - USER_ACTIVITY_EVENT_ATTENTION, - USER_ACTIVITY_EVENT_FACE_DOWN, - USER_ACTIVITY_EVENT_DEVICE_STATE, - }) - @Retention(RetentionPolicy.SOURCE) - public @interface UserActivityEvent{} - - /** - * - * Convert the user activity event to a string for debugging purposes. - * @hide - */ - public static String userActivityEventToString(@UserActivityEvent int userActivityEvent) { - switch (userActivityEvent) { - case USER_ACTIVITY_EVENT_OTHER: return "other"; - case USER_ACTIVITY_EVENT_BUTTON: return "button"; - case USER_ACTIVITY_EVENT_TOUCH: return "touch"; - case USER_ACTIVITY_EVENT_ACCESSIBILITY: return "accessibility"; - case USER_ACTIVITY_EVENT_ATTENTION: return "attention"; - case USER_ACTIVITY_EVENT_FACE_DOWN: return "faceDown"; - case USER_ACTIVITY_EVENT_DEVICE_STATE: return "deviceState"; - default: return Integer.toString(userActivityEvent); - } - } - - /** * User activity flag: If already dimmed, extend the dim timeout * but do not brighten. This flag is useful for keeping the screen on * a little longer without causing a visible change such as when diff --git a/core/java/android/os/UserManager.java b/core/java/android/os/UserManager.java index ca0af2cf07af..f6aaee8e3de0 100644 --- a/core/java/android/os/UserManager.java +++ b/core/java/android/os/UserManager.java @@ -1995,7 +1995,8 @@ public class UserManager { /** @hide */ public UserManager(Context context, IUserManager service) { mService = service; - mContext = context.getApplicationContext(); + Context appContext = context.getApplicationContext(); + mContext = (appContext == null ? context : appContext); mUserId = context.getUserId(); } @@ -2885,6 +2886,21 @@ public class UserManager { } /** + * Gets the visible users (as defined by {@link #isUserVisible()}. + * + * @return visible users at the moment. + */ + @RequiresPermission(anyOf = {Manifest.permission.MANAGE_USERS, + Manifest.permission.INTERACT_ACROSS_USERS}) + public @NonNull List<UserHandle> getVisibleUsers() { + try { + return mService.getVisibleUsers(); + } catch (RemoteException re) { + throw re.rethrowFromSystemServer(); + } + } + + /** * Return whether the context user is running in an "unlocked" state. * <p> * On devices with direct boot, a user is unlocked only after they've diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java index 8a50e79e8598..14598d558caa 100644 --- a/core/java/android/provider/Settings.java +++ b/core/java/android/provider/Settings.java @@ -9187,14 +9187,12 @@ public final class Settings { public static final String SCREENSAVER_DEFAULT_COMPONENT = "screensaver_default_component"; /** - * The complications that are enabled to be shown over the screensaver by the user. Holds - * a comma separated list of - * {@link com.android.settingslib.dream.DreamBackend.ComplicationType}. + * Whether complications are enabled to be shown over the screensaver by the user. * * @hide */ - public static final String SCREENSAVER_ENABLED_COMPLICATIONS = - "screensaver_enabled_complications"; + public static final String SCREENSAVER_COMPLICATIONS_ENABLED = + "screensaver_complications_enabled"; /** diff --git a/core/java/android/service/selectiontoolbar/RemoteSelectionToolbar.java b/core/java/android/service/selectiontoolbar/RemoteSelectionToolbar.java index 95bcda5f7c55..9292e9608261 100644 --- a/core/java/android/service/selectiontoolbar/RemoteSelectionToolbar.java +++ b/core/java/android/service/selectiontoolbar/RemoteSelectionToolbar.java @@ -1317,7 +1317,6 @@ final class RemoteSelectionToolbar { contentContainer.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); contentContainer.setTag(FloatingToolbar.FLOATING_TOOLBAR_TAG); - contentContainer.setContentDescription(FloatingToolbar.FLOATING_TOOLBAR_TAG); contentContainer.setClipToOutline(true); return contentContainer; } diff --git a/core/java/android/util/FeatureFlagUtils.java b/core/java/android/util/FeatureFlagUtils.java index b73ff901052f..0338cebf75c6 100644 --- a/core/java/android/util/FeatureFlagUtils.java +++ b/core/java/android/util/FeatureFlagUtils.java @@ -97,10 +97,6 @@ public class FeatureFlagUtils { /** @hide */ public static final String SETTINGS_AUTO_TEXT_WRAPPING = "settings_auto_text_wrapping"; - /** Flag to enable/disable guest mode UX changes as mentioned in b/214031645 - * @hide - */ - public static final String SETTINGS_GUEST_MODE_UX_CHANGES = "settings_guest_mode_ux_changes"; /** Support Clear Calling feature. * @hide @@ -150,7 +146,6 @@ public class FeatureFlagUtils { DEFAULT_FLAGS.put(SETTINGS_APP_ALLOW_DARK_THEME_ACTIVATION_AT_BEDTIME, "true"); DEFAULT_FLAGS.put(SETTINGS_HIDE_SECOND_LAYER_PAGE_NAVIGATE_UP_BUTTON_IN_TWO_PANE, "true"); DEFAULT_FLAGS.put(SETTINGS_AUTO_TEXT_WRAPPING, "false"); - DEFAULT_FLAGS.put(SETTINGS_GUEST_MODE_UX_CHANGES, "true"); DEFAULT_FLAGS.put(SETTINGS_ENABLE_CLEAR_CALLING, "false"); DEFAULT_FLAGS.put(SETTINGS_ACCESSIBILITY_SIMPLE_CURSOR, "false"); DEFAULT_FLAGS.put(SETTINGS_NEW_KEYBOARD_UI, "false"); diff --git a/core/java/android/view/IWindowManager.aidl b/core/java/android/view/IWindowManager.aidl index 8aa113dfc8e6..229de31ddcba 100644 --- a/core/java/android/view/IWindowManager.aidl +++ b/core/java/android/view/IWindowManager.aidl @@ -413,11 +413,6 @@ interface IWindowManager boolean hasNavigationBar(int displayId); /** - * Get the position of the nav bar - */ - int getNavBarPosition(int displayId); - - /** * Lock the device immediately with the specified options (can be null). */ @UnsupportedAppUsage(maxTargetSdk = 30, trackingBug = 170729553) diff --git a/core/java/android/view/InsetsState.java b/core/java/android/view/InsetsState.java index 9f426a176a08..45d28da73c6b 100644 --- a/core/java/android/view/InsetsState.java +++ b/core/java/android/view/InsetsState.java @@ -351,6 +351,20 @@ public class InsetsState implements Parcelable { return insets; } + // TODO: Remove this once the task bar is treated as navigation bar. + public Insets calculateInsetsWithInternalTypes(Rect frame, @InternalInsetsType int[] types, + boolean ignoreVisibility) { + Insets insets = Insets.NONE; + for (int i = types.length - 1; i >= 0; i--) { + InsetsSource source = mSources[types[i]]; + if (source == null) { + continue; + } + insets = Insets.max(source.calculateInsets(frame, ignoreVisibility), insets); + } + return insets; + } + public Insets calculateInsets(Rect frame, @InsetsType int types, InsetsVisibilities overrideVisibilities) { Insets insets = Insets.NONE; diff --git a/core/java/android/view/SurfaceControl.java b/core/java/android/view/SurfaceControl.java index 84f04c12cf51..e0f02d6e567a 100644 --- a/core/java/android/view/SurfaceControl.java +++ b/core/java/android/view/SurfaceControl.java @@ -130,7 +130,6 @@ public final class SurfaceControl implements Parcelable { float x, float y); private static native void nativeSetScale(long transactionObj, long nativeObject, float x, float y); - private static native void nativeSetSize(long transactionObj, long nativeObject, int w, int h); private static native void nativeSetTransparentRegionHint(long transactionObj, long nativeObject, Region region); private static native void nativeSetAlpha(long transactionObj, long nativeObject, float alpha); @@ -274,6 +273,9 @@ public final class SurfaceControl implements Parcelable { private static native void nativeSanitize(long transactionObject); private static native void nativeSetDestinationFrame(long transactionObj, long nativeObject, int l, int t, int r, int b); + private static native void nativeSetDefaultApplyToken(IBinder token); + private static native IBinder nativeGetDefaultApplyToken(); + /** * Transforms that can be applied to buffers as they are displayed to a window. @@ -2774,6 +2776,22 @@ public final class SurfaceControl implements Parcelable { } /** + * + * @hide + */ + public static void setDefaultApplyToken(IBinder token) { + nativeSetDefaultApplyToken(token); + } + + /** + * + * @hide + */ + public static IBinder getDefaultApplyToken() { + return nativeGetDefaultApplyToken(); + } + + /** * Apply the transaction, clearing it's state, and making it usable * as a new transaction. */ @@ -2954,7 +2972,6 @@ public final class SurfaceControl implements Parcelable { @IntRange(from = 0) int w, @IntRange(from = 0) int h) { checkPreconditions(sc); mResizedSurfaces.put(sc, new Point(w, h)); - nativeSetSize(mNativeObject, sc.mNativeObject, w, h); return this; } diff --git a/core/java/android/view/SurfaceView.java b/core/java/android/view/SurfaceView.java index a66427843af0..b6c92e3fd264 100644 --- a/core/java/android/view/SurfaceView.java +++ b/core/java/android/view/SurfaceView.java @@ -914,7 +914,7 @@ public class SurfaceView extends View implements ViewRootImpl.SurfaceChangedCall && mRequestedVisible; final boolean sizeChanged = mSurfaceWidth != myWidth || mSurfaceHeight != myHeight; final boolean windowVisibleChanged = mWindowVisibility != mLastWindowVisibility; - getLocationInSurface(mLocation); + getLocationInWindow(mLocation); final boolean positionChanged = mWindowSpaceLeft != mLocation[0] || mWindowSpaceTop != mLocation[1]; final boolean layoutSizeChanged = getWidth() != mScreenRect.width() @@ -925,7 +925,6 @@ public class SurfaceView extends View implements ViewRootImpl.SurfaceChangedCall if (creating || formatChanged || sizeChanged || visibleChanged || (mUseAlpha && alphaChanged) || windowVisibleChanged || positionChanged || layoutSizeChanged || hintChanged) { - getLocationInWindow(mLocation); if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " " + "Changes: creating=" + creating diff --git a/core/java/android/view/WindowLayout.java b/core/java/android/view/WindowLayout.java index 57a0330e3c18..5ed9d2f90a72 100644 --- a/core/java/android/view/WindowLayout.java +++ b/core/java/android/view/WindowLayout.java @@ -118,11 +118,11 @@ public class WindowLayout { } if (cutoutMode == LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES) { if (displayFrame.width() < displayFrame.height()) { - displayCutoutSafeExceptMaybeBars.top = Integer.MIN_VALUE; - displayCutoutSafeExceptMaybeBars.bottom = Integer.MAX_VALUE; + displayCutoutSafeExceptMaybeBars.top = MIN_Y; + displayCutoutSafeExceptMaybeBars.bottom = MAX_Y; } else { - displayCutoutSafeExceptMaybeBars.left = Integer.MIN_VALUE; - displayCutoutSafeExceptMaybeBars.right = Integer.MAX_VALUE; + displayCutoutSafeExceptMaybeBars.left = MIN_X; + displayCutoutSafeExceptMaybeBars.right = MAX_X; } } final boolean layoutInsetDecor = (attrs.flags & FLAG_LAYOUT_INSET_DECOR) != 0; @@ -132,23 +132,23 @@ public class WindowLayout { final Insets systemBarsInsets = state.calculateInsets( displayFrame, WindowInsets.Type.systemBars(), requestedVisibilities); if (systemBarsInsets.left > 0) { - displayCutoutSafeExceptMaybeBars.left = Integer.MIN_VALUE; + displayCutoutSafeExceptMaybeBars.left = MIN_X; } if (systemBarsInsets.top > 0) { - displayCutoutSafeExceptMaybeBars.top = Integer.MIN_VALUE; + displayCutoutSafeExceptMaybeBars.top = MIN_Y; } if (systemBarsInsets.right > 0) { - displayCutoutSafeExceptMaybeBars.right = Integer.MAX_VALUE; + displayCutoutSafeExceptMaybeBars.right = MAX_X; } if (systemBarsInsets.bottom > 0) { - displayCutoutSafeExceptMaybeBars.bottom = Integer.MAX_VALUE; + displayCutoutSafeExceptMaybeBars.bottom = MAX_Y; } } if (type == TYPE_INPUT_METHOD) { final InsetsSource navSource = state.peekSource(ITYPE_NAVIGATION_BAR); if (navSource != null && navSource.calculateInsets(displayFrame, true).bottom > 0) { // The IME can always extend under the bottom cutout if the navbar is there. - displayCutoutSafeExceptMaybeBars.bottom = Integer.MAX_VALUE; + displayCutoutSafeExceptMaybeBars.bottom = MAX_Y; } } final boolean attachedInParent = attachedWindowFrame != null && !layoutInScreen; diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/model/WifiModel.kt b/core/java/android/view/inputmethod/DeleteGesture.aidl index 1b7332265b7a..e9f31dd470ef 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/model/WifiModel.kt +++ b/core/java/android/view/inputmethod/DeleteGesture.aidl @@ -14,16 +14,6 @@ * limitations under the License. */ -package com.android.systemui.statusbar.pipeline.wifi.data.model +package android.view.inputmethod; -/** Provides information about the current wifi state. */ -data class WifiModel( - /** See [android.net.wifi.WifiInfo.ssid]. */ - val ssid: String? = null, - /** See [android.net.wifi.WifiInfo.isPasspointAp]. */ - val isPasspointAccessPoint: Boolean = false, - /** See [android.net.wifi.WifiInfo.isOsuAp]. */ - val isOnlineSignUpForPasspointAccessPoint: Boolean = false, - /** See [android.net.wifi.WifiInfo.passpointProviderFriendlyName]. */ - val passpointProviderFriendlyName: String? = null, -) +parcelable DeleteGesture;
\ No newline at end of file diff --git a/core/java/android/view/inputmethod/DeleteGesture.java b/core/java/android/view/inputmethod/DeleteGesture.java new file mode 100644 index 000000000000..257254e5737a --- /dev/null +++ b/core/java/android/view/inputmethod/DeleteGesture.java @@ -0,0 +1,193 @@ +/* + * 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 android.view.inputmethod; + +import android.annotation.NonNull; +import android.annotation.Nullable; +import android.annotation.SuppressLint; +import android.graphics.RectF; +import android.os.Parcel; +import android.os.Parcelable; +import android.widget.TextView; + +import java.util.Objects; + +/** + * A sub-class of {@link HandwritingGesture} for deleting an area of text. + * This class holds the information required for deletion of text in + * toolkit widgets like {@link TextView}. + */ +public final class DeleteGesture extends HandwritingGesture implements Parcelable { + + private @Granularity int mGranularity; + private RectF mArea; + + private DeleteGesture(@Granularity int granularity, RectF area, String fallbackText) { + mArea = area; + mGranularity = granularity; + mFallbackText = fallbackText; + } + + private DeleteGesture(@NonNull final Parcel source) { + mFallbackText = source.readString8(); + mGranularity = source.readInt(); + mArea = source.readTypedObject(RectF.CREATOR); + } + + /** + * Returns Granular level on which text should be operated. + * @see HandwritingGesture#GRANULARITY_CHARACTER + * @see HandwritingGesture#GRANULARITY_WORD + */ + @Granularity + public int getGranularity() { + return mGranularity; + } + + /** + * Returns the deletion area {@link RectF} in screen coordinates. + * + * Getter for deletion area set with {@link DeleteGesture.Builder#setDeletionArea(RectF)}. + * {@code null} if area was not set. + */ + @NonNull + public RectF getDeletionArea() { + return mArea; + } + + /** + * Builder for {@link DeleteGesture}. This class is not designed to be thread-safe. + */ + public static final class Builder { + private int mGranularity; + private RectF mArea; + private String mFallbackText; + + /** + * Set text deletion granularity. Intersecting words/characters will be + * included in the operation. + * @param granularity {@link HandwritingGesture#GRANULARITY_WORD} or + * {@link HandwritingGesture#GRANULARITY_CHARACTER}. + * @return {@link Builder}. + */ + @NonNull + @SuppressLint("MissingGetterMatchingBuilder") + public Builder setGranularity(@Granularity int granularity) { + mGranularity = granularity; + return this; + } + + /** + * Set rectangular single/multiline text deletion area intersecting with text. + * + * The resulting deletion would be performed for all text intersecting rectangle. The + * deletion includes the first word/character in the rectangle, and the last + * word/character in the rectangle, and includes everything in between even if it's not + * in the rectangle. + * + * Intersection is determined using + * {@link #setGranularity(int)}. e.g. {@link HandwritingGesture#GRANULARITY_WORD} includes + * all the words with their width/height center included in the deletion rectangle. + * @param area {@link RectF} (in screen coordinates) for which text will be deleted. + * @see HandwritingGesture#GRANULARITY_WORD + * @see HandwritingGesture#GRANULARITY_CHARACTER + */ + @SuppressLint("MissingGetterMatchingBuilder") + @NonNull + public Builder setDeletionArea(@NonNull RectF area) { + mArea = area; + return this; + } + + /** + * Set fallback text that will be committed at current cursor position if there is no + * applicable text beneath the area of gesture. + * @param fallbackText text to set + */ + @NonNull + public Builder setFallbackText(@Nullable String fallbackText) { + mFallbackText = fallbackText; + return this; + } + + /** + * @return {@link DeleteGesture} using parameters in this {@link DeleteGesture.Builder}. + * @throws IllegalArgumentException if one or more positional parameters are not specified. + */ + @NonNull + public DeleteGesture build() { + if (mArea == null || mArea.isEmpty()) { + throw new IllegalArgumentException("Deletion area must be set."); + } + if (mGranularity <= GRANULARITY_UNDEFINED) { + throw new IllegalArgumentException("Deletion granularity must be set."); + } + return new DeleteGesture(mGranularity, mArea, mFallbackText); + } + } + + /** + * Used to make this class parcelable. + */ + public static final @android.annotation.NonNull Creator<DeleteGesture> CREATOR = + new Creator<DeleteGesture>() { + @Override + public DeleteGesture createFromParcel(Parcel source) { + return new DeleteGesture(source); + } + + @Override + public DeleteGesture[] newArray(int size) { + return new DeleteGesture[size]; + } + }; + + @Override + public int hashCode() { + return Objects.hash(mArea, mGranularity, mFallbackText); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof DeleteGesture)) return false; + + DeleteGesture that = (DeleteGesture) o; + + if (mGranularity != that.mGranularity) return false; + if (!Objects.equals(mFallbackText, that.mFallbackText)) return false; + return Objects.equals(mArea, that.mArea); + } + + @Override + public int describeContents() { + return 0; + } + + /** + * Used to package this object into a {@link Parcel}. + * + * @param dest The {@link Parcel} to be written. + * @param flags The flags used for parceling. + */ + @Override + public void writeToParcel(@NonNull Parcel dest, int flags) { + dest.writeString8(mFallbackText); + dest.writeInt(mGranularity); + dest.writeTypedObject(mArea, flags); + } +} diff --git a/core/java/android/view/inputmethod/HandwritingGesture.java b/core/java/android/view/inputmethod/HandwritingGesture.java new file mode 100644 index 000000000000..15824aeb0aeb --- /dev/null +++ b/core/java/android/view/inputmethod/HandwritingGesture.java @@ -0,0 +1,94 @@ +/* + * 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 android.view.inputmethod; + +import android.annotation.IntDef; +import android.annotation.Nullable; +import android.graphics.RectF; +import android.inputmethodservice.InputMethodService; +import android.view.MotionEvent; + +import java.util.concurrent.Executor; +import java.util.function.IntConsumer; + +/** + * Base class for Stylus handwriting gesture. + * + * During a stylus handwriting session, user can perform a stylus gesture operation like + * {@link SelectGesture}, {@link DeleteGesture}, {@link InsertGesture} on an + * area of text. IME is responsible for listening to Stylus {@link MotionEvent} using + * {@link InputMethodService#onStylusHandwritingMotionEvent} and interpret if it can translate to a + * gesture operation. + * While creating Gesture operations {@link SelectGesture}, {@link DeleteGesture}, + * , {@code Granularity} helps pick the correct granular level of text like word level + * {@link #GRANULARITY_WORD}, or character level {@link #GRANULARITY_CHARACTER}. + * + * @see InputConnection#performHandwritingGesture(HandwritingGesture, Executor, IntConsumer) + * @see InputMethodService#onStartStylusHandwriting() + */ +public abstract class HandwritingGesture { + + HandwritingGesture() {} + + static final int GRANULARITY_UNDEFINED = 0; + + /** + * Operate text per word basis. e.g. if selection includes width-wise center of the word, + * whole word is selected. + * <p> Strategy of operating at a granular level is maintained in the UI toolkit. + * A character/word/line is included if its center is within the gesture rectangle. + * e.g. if a selection {@link RectF} with {@link #GRANULARITY_WORD} includes width-wise + * center of the word, it should be selected. + * Similarly, text in a line should be included in the operation if rectangle includes + * line height center.</p> + * Refer to https://www.unicode.org/reports/tr29/#Word_Boundaries for more detail on how word + * breaks are decided. + */ + public static final int GRANULARITY_WORD = 1; + + /** + * Operate on text per character basis. i.e. each character is selected based on its + * intersection with selection rectangle. + * <p> Strategy of operating at a granular level is maintained in the UI toolkit. + * A character/word/line is included if its center is within the gesture rectangle. + * e.g. if a selection {@link RectF} with {@link #GRANULARITY_CHARACTER} includes width-wise + * center of the character, it should be selected. + * Similarly, text in a line should be included in the operation if rectangle includes + * line height center.</p> + */ + public static final int GRANULARITY_CHARACTER = 2; + + /** + * Granular level on which text should be operated. + */ + @IntDef({GRANULARITY_CHARACTER, GRANULARITY_WORD}) + @interface Granularity {} + + @Nullable + String mFallbackText; + + /** + * The fallback text that will be committed at current cursor position if there is no applicable + * text beneath the area of gesture. + * For example, select can fail if gesture is drawn over area that has no text beneath. + * example 2: join can fail if the gesture is drawn over text but there is no whitespace. + */ + @Nullable + public String getFallbackText() { + return mFallbackText; + } +} diff --git a/core/java/android/view/inputmethod/InputConnection.java b/core/java/android/view/inputmethod/InputConnection.java index dac1be6f5a13..7b0270a1859f 100644 --- a/core/java/android/view/inputmethod/InputConnection.java +++ b/core/java/android/view/inputmethod/InputConnection.java @@ -16,6 +16,7 @@ package android.view.inputmethod; +import android.annotation.CallbackExecutor; import android.annotation.IntDef; import android.annotation.IntRange; import android.annotation.NonNull; @@ -31,6 +32,8 @@ import com.android.internal.util.Preconditions; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; +import java.util.concurrent.Executor; +import java.util.function.IntConsumer; /** * The InputConnection interface is the communication channel from an @@ -968,6 +971,17 @@ public interface InputConnection { boolean performPrivateCommand(String action, Bundle data); /** + * Perform a handwriting gesture on text. + * + * @param gesture the gesture to perform + * @param executor if the caller passes a non-null consumer TODO(b/210039666): complete doc + * @param consumer if the caller passes a non-null receiver, the editor must invoke this + */ + default void performHandwritingGesture( + @NonNull HandwritingGesture gesture, @Nullable @CallbackExecutor Executor executor, + @Nullable IntConsumer consumer) {} + + /** * The editor is requested to call * {@link InputMethodManager#updateCursorAnchorInfo(android.view.View, CursorAnchorInfo)} at * once, as soon as possible, regardless of cursor/anchor position changes. This flag can be diff --git a/core/java/android/view/inputmethod/InputConnectionWrapper.java b/core/java/android/view/inputmethod/InputConnectionWrapper.java index 7a88a75f93ad..56beddf2ef38 100644 --- a/core/java/android/view/inputmethod/InputConnectionWrapper.java +++ b/core/java/android/view/inputmethod/InputConnectionWrapper.java @@ -16,6 +16,7 @@ package android.view.inputmethod; +import android.annotation.CallbackExecutor; import android.annotation.IntRange; import android.annotation.NonNull; import android.annotation.Nullable; @@ -25,6 +26,9 @@ import android.view.KeyEvent; import com.android.internal.util.Preconditions; +import java.util.concurrent.Executor; +import java.util.function.IntConsumer; + /** * <p>Wrapper class for proxying calls to another InputConnection. Subclass and have fun! */ @@ -323,6 +327,17 @@ public class InputConnectionWrapper implements InputConnection { * @throws NullPointerException if the target is {@code null}. */ @Override + public void performHandwritingGesture( + @NonNull HandwritingGesture gesture, @Nullable @CallbackExecutor Executor executor, + @Nullable IntConsumer consumer) { + mTarget.performHandwritingGesture(gesture, executor, consumer); + } + + /** + * {@inheritDoc} + * @throws NullPointerException if the target is {@code null}. + */ + @Override public boolean requestCursorUpdates(int cursorUpdateMode) { return mTarget.requestCursorUpdates(cursorUpdateMode); } diff --git a/core/java/android/view/inputmethod/InputMethod.java b/core/java/android/view/inputmethod/InputMethod.java index bfe6ae6447d0..978bfc7af60d 100644 --- a/core/java/android/view/inputmethod/InputMethod.java +++ b/core/java/android/view/inputmethod/InputMethod.java @@ -410,4 +410,11 @@ public interface InputMethod { // intentionally empty } + /** + * Remove stylus handwriting window. + * @hide + */ + default void removeStylusHandwritingWindow() { + // intentionally empty + } } diff --git a/core/java/android/view/inputmethod/InsertGesture.aidl b/core/java/android/view/inputmethod/InsertGesture.aidl new file mode 100644 index 000000000000..9cdb14a8b3ab --- /dev/null +++ b/core/java/android/view/inputmethod/InsertGesture.aidl @@ -0,0 +1,19 @@ +/* + * 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 android.view.inputmethod; + +parcelable InsertGesture;
\ No newline at end of file diff --git a/core/java/android/view/inputmethod/InsertGesture.java b/core/java/android/view/inputmethod/InsertGesture.java new file mode 100644 index 000000000000..2cf015a33283 --- /dev/null +++ b/core/java/android/view/inputmethod/InsertGesture.java @@ -0,0 +1,172 @@ +/* + * 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 android.view.inputmethod; + +import android.annotation.NonNull; +import android.annotation.SuppressLint; +import android.graphics.PointF; +import android.os.Parcel; +import android.os.Parcelable; +import android.text.TextUtils; +import android.widget.TextView; + +import androidx.annotation.Nullable; + +import java.util.Objects; + +/** + * A sub-class of {@link HandwritingGesture} for inserting text at the defined insertion point. + * This class holds the information required for insertion of text in + * toolkit widgets like {@link TextView}. + */ +public final class InsertGesture extends HandwritingGesture implements Parcelable { + + private String mTextToInsert; + private PointF mPoint; + + private InsertGesture(String text, PointF point, String fallbackText) { + mPoint = point; + mTextToInsert = text; + mFallbackText = fallbackText; + } + + private InsertGesture(final Parcel source) { + mFallbackText = source.readString8(); + mTextToInsert = source.readString8(); + mPoint = source.readTypedObject(PointF.CREATOR); + } + + /** Returns the text that will be inserted at {@link #getInsertionPoint()} **/ + @Nullable + public String getTextToInsert() { + return mTextToInsert; + } + + /** + * Returns the insertion point {@link PointF} (in screen coordinates) where + * {@link #getTextToInsert()} will be inserted. + */ + @Nullable + public PointF getInsertionPoint() { + return mPoint; + } + + /** + * Builder for {@link InsertGesture}. This class is not designed to be thread-safe. + */ + public static final class Builder { + private String mText; + private PointF mPoint; + private String mFallbackText; + + /** set the text that will be inserted at {@link #setInsertionPoint(PointF)} **/ + @NonNull + @SuppressLint("MissingGetterMatchingBuilder") + public Builder setTextToInsert(@NonNull String text) { + mText = text; + return this; + } + + /** + * Sets the insertion point (in screen coordinates) where {@link #setTextToInsert(String)} + * should be inserted. + */ + @NonNull + @SuppressLint("MissingGetterMatchingBuilder") + public Builder setInsertionPoint(@NonNull PointF point) { + mPoint = point; + return this; + } + + /** + * Set fallback text that will be committed at current cursor position if there is no + * applicable text beneath the area of gesture. + * @param fallbackText text to set + */ + @NonNull + public Builder setFallbackText(@Nullable String fallbackText) { + mFallbackText = fallbackText; + return this; + } + + /** + * @return {@link InsertGesture} using parameters in this {@link InsertGesture.Builder}. + * @throws IllegalArgumentException if one or more positional parameters are not specified. + */ + @NonNull + public InsertGesture build() { + if (mPoint == null) { + throw new IllegalArgumentException("Insertion point must be set."); + } + if (TextUtils.isEmpty(mText)) { + throw new IllegalArgumentException("Text to insert must be non-empty."); + } + return new InsertGesture(mText, mPoint, mFallbackText); + } + } + + /** + * Used to make this class parcelable. + */ + public static final @android.annotation.NonNull Creator<InsertGesture> CREATOR = + new Creator<InsertGesture>() { + @Override + public InsertGesture createFromParcel(Parcel source) { + return new InsertGesture(source); + } + + @Override + public InsertGesture[] newArray(int size) { + return new InsertGesture[size]; + } + }; + + @Override + public int hashCode() { + return Objects.hash(mPoint, mTextToInsert, mFallbackText); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof InsertGesture)) return false; + + InsertGesture that = (InsertGesture) o; + + if (!Objects.equals(mFallbackText, that.mFallbackText)) return false; + if (!Objects.equals(mTextToInsert, that.mTextToInsert)) return false; + return Objects.equals(mPoint, that.mPoint); + } + + @Override + public int describeContents() { + return 0; + } + + /** + * Used to package this object into a {@link Parcel}. + * + * @param dest The {@link Parcel} to be written. + * @param flags The flags used for parceling. + */ + @Override + public void writeToParcel(@NonNull Parcel dest, int flags) { + dest.writeString8(mFallbackText); + dest.writeString8(mTextToInsert); + dest.writeTypedObject(mPoint, flags); + } +} diff --git a/core/java/android/view/inputmethod/SelectGesture.aidl b/core/java/android/view/inputmethod/SelectGesture.aidl new file mode 100644 index 000000000000..65da4f340e8c --- /dev/null +++ b/core/java/android/view/inputmethod/SelectGesture.aidl @@ -0,0 +1,19 @@ +/* + * 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 android.view.inputmethod; + +parcelable SelectGesture;
\ No newline at end of file diff --git a/core/java/android/view/inputmethod/SelectGesture.java b/core/java/android/view/inputmethod/SelectGesture.java new file mode 100644 index 000000000000..f3cd71e1eed9 --- /dev/null +++ b/core/java/android/view/inputmethod/SelectGesture.java @@ -0,0 +1,191 @@ +/* + * 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 android.view.inputmethod; + +import android.annotation.NonNull; +import android.annotation.Nullable; +import android.annotation.SuppressLint; +import android.graphics.RectF; +import android.os.Parcel; +import android.os.Parcelable; +import android.widget.TextView; + +import java.util.Objects; + +/** + * A sub-class of {@link HandwritingGesture} for selecting an area of text. + * This class holds the information required for selection of text in + * toolkit widgets like {@link TextView}. + */ +public final class SelectGesture extends HandwritingGesture implements Parcelable { + + private @Granularity int mGranularity; + private RectF mArea; + + private SelectGesture(int granularity, RectF area, String fallbackText) { + mArea = area; + mGranularity = granularity; + mFallbackText = fallbackText; + } + + private SelectGesture(@NonNull Parcel source) { + mFallbackText = source.readString8(); + mGranularity = source.readInt(); + mArea = source.readTypedObject(RectF.CREATOR); + } + + /** + * Returns Granular level on which text should be operated. + * @see #GRANULARITY_CHARACTER + * @see #GRANULARITY_WORD + */ + @Granularity + public int getGranularity() { + return mGranularity; + } + + /** + * Returns the Selection area {@link RectF} in screen coordinates. + * + * Getter for selection area set with {@link Builder#setSelectionArea(RectF)}. {@code null} + * if area was not set. + */ + @NonNull + public RectF getSelectionArea() { + return mArea; + } + + + /** + * Builder for {@link SelectGesture}. This class is not designed to be thread-safe. + */ + public static final class Builder { + private int mGranularity; + private RectF mArea; + private String mFallbackText; + + /** + * Define text selection granularity. Intersecting words/characters will be + * included in the operation. + * @param granularity {@link HandwritingGesture#GRANULARITY_WORD} or + * {@link HandwritingGesture#GRANULARITY_CHARACTER}. + * @return {@link Builder}. + */ + @NonNull + @SuppressLint("MissingGetterMatchingBuilder") + public Builder setGranularity(@Granularity int granularity) { + mGranularity = granularity; + return this; + } + + /** + * Set rectangular single/multiline text selection area intersecting with text. + * + * The resulting selection would be performed for all text intersecting rectangle. The + * selection includes the first word/character in the rectangle, and the last + * word/character in the rectangle, and includes everything in between even if it's not + * in the rectangle. + * + * Intersection is determined using + * {@link #setGranularity(int)}. e.g. {@link HandwritingGesture#GRANULARITY_WORD} includes + * all the words with their width/height center included in the selection rectangle. + * @param area {@link RectF} (in screen coordinates) for which text will be selection. + */ + @NonNull + @SuppressLint("MissingGetterMatchingBuilder") + public Builder setSelectionArea(@NonNull RectF area) { + mArea = area; + return this; + } + + /** + * Set fallback text that will be committed at current cursor position if there is no + * applicable text beneath the area of gesture. + * @param fallbackText text to set + */ + @NonNull + public Builder setFallbackText(@Nullable String fallbackText) { + mFallbackText = fallbackText; + return this; + } + + /** + * @return {@link SelectGesture} using parameters in this {@link InsertGesture.Builder}. + * @throws IllegalArgumentException if one or more positional parameters are not specified. + */ + @NonNull + public SelectGesture build() { + if (mArea == null || mArea.isEmpty()) { + throw new IllegalArgumentException("Selection area must be set."); + } + if (mGranularity <= GRANULARITY_UNDEFINED) { + throw new IllegalArgumentException("Selection granularity must be set."); + } + return new SelectGesture(mGranularity, mArea, mFallbackText); + } + } + + /** + * Used to make this class parcelable. + */ + public static final @android.annotation.NonNull Parcelable.Creator<SelectGesture> CREATOR = + new Parcelable.Creator<SelectGesture>() { + @Override + public SelectGesture createFromParcel(Parcel source) { + return new SelectGesture(source); + } + + @Override + public SelectGesture[] newArray(int size) { + return new SelectGesture[size]; + } + }; + + @Override + public int hashCode() { + return Objects.hash(mGranularity, mArea, mFallbackText); + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof SelectGesture)) return false; + + SelectGesture that = (SelectGesture) o; + + if (mGranularity != that.mGranularity) return false; + if (!Objects.equals(mFallbackText, that.mFallbackText)) return false; + return Objects.equals(mArea, that.mArea); + } + + @Override + public int describeContents() { + return 0; + } + + /** + * Used to package this object into a {@link Parcel}. + * + * @param dest The {@link Parcel} to be written. + * @param flags The flags used for parceling. + */ + @Override + public void writeToParcel(@NonNull Parcel dest, int flags) { + dest.writeString8(mFallbackText); + dest.writeInt(mGranularity); + dest.writeTypedObject(mArea, flags); + } +} diff --git a/core/java/android/widget/ExpandableListView.java b/core/java/android/widget/ExpandableListView.java index e243aae81da4..efe3fd468e37 100644 --- a/core/java/android/widget/ExpandableListView.java +++ b/core/java/android/widget/ExpandableListView.java @@ -31,6 +31,7 @@ import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.SoundEffectConstants; import android.view.View; +import android.view.accessibility.AccessibilityNodeInfo; import android.widget.ExpandableListConnector.PositionMetadata; import com.android.internal.R; @@ -1144,6 +1145,24 @@ public class ExpandableListView extends ListView { return new ExpandableListContextMenuInfo(view, packedPosition, id); } + /** @hide */ + @Override + public void onInitializeAccessibilityNodeInfoForItem( + View view, int position, AccessibilityNodeInfo info) { + super.onInitializeAccessibilityNodeInfoForItem(view, position, info); + + final PositionMetadata metadata = mConnector.getUnflattenedPos(position); + if (metadata.position.type == ExpandableListPosition.GROUP) { + if (isGroupExpanded(metadata.position.groupPos)) { + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_COLLAPSE); + } else { + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_EXPAND); + } + } + + metadata.recycle(); + } + /** * Gets the ID of the group or child at the given <code>position</code>. * This is useful since there is no ListAdapter ID -> ExpandableListAdapter diff --git a/core/java/android/widget/LinearLayout.java b/core/java/android/widget/LinearLayout.java index fa84407c5c4d..7314ad83bd0c 100644 --- a/core/java/android/widget/LinearLayout.java +++ b/core/java/android/widget/LinearLayout.java @@ -732,6 +732,10 @@ public class LinearLayout extends ViewGroup { * @hide Pending API consideration. Currently only used internally by the system. */ protected boolean hasDividerBeforeChildAt(int childIndex) { + if (mShowDividers == SHOW_DIVIDER_NONE) { + // Short-circuit to save iteration over child views. + return false; + } if (childIndex == getVirtualChildCount()) { // Check whether the end divider should draw. return (mShowDividers & SHOW_DIVIDER_END) != 0; @@ -746,6 +750,24 @@ public class LinearLayout extends ViewGroup { } /** + * Determines whether or not there's a divider after a specified child index. + * + * @param childIndex Index of child to check for following divider + * @return true if there should be a divider after the child at childIndex + */ + private boolean hasDividerAfterChildAt(int childIndex) { + if (mShowDividers == SHOW_DIVIDER_NONE) { + // Short-circuit to save iteration over child views. + return false; + } + if (allViewsAreGoneAfter(childIndex)) { + // This is the last view that's not gone, check if end divider is enabled. + return (mShowDividers & SHOW_DIVIDER_END) != 0; + } + return (mShowDividers & SHOW_DIVIDER_MIDDLE) != 0; + } + + /** * Checks whether all (virtual) child views before the given index are gone. */ private boolean allViewsAreGoneBefore(int childIndex) { @@ -759,6 +781,20 @@ public class LinearLayout extends ViewGroup { } /** + * Checks whether all (virtual) child views after the given index are gone. + */ + private boolean allViewsAreGoneAfter(int childIndex) { + final int count = getVirtualChildCount(); + for (int i = childIndex + 1; i < count; i++) { + final View child = getVirtualChildAt(i); + if (child != null && child.getVisibility() != GONE) { + return false; + } + } + return true; + } + + /** * Measures the children when the orientation of this LinearLayout is set * to {@link #VERTICAL}. * @@ -1295,6 +1331,7 @@ public class LinearLayout extends ViewGroup { if (useLargestChild && (widthMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.UNSPECIFIED)) { mTotalLength = 0; + nonSkippedChildCount = 0; for (int i = 0; i < count; ++i) { final View child = getVirtualChildAt(i); @@ -1308,6 +1345,11 @@ public class LinearLayout extends ViewGroup { continue; } + nonSkippedChildCount++; + if (hasDividerBeforeChildAt(i)) { + mTotalLength += mDividerWidth; + } + final LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams(); if (isExactly) { @@ -1319,6 +1361,10 @@ public class LinearLayout extends ViewGroup { lp.leftMargin + lp.rightMargin + getNextLocationOffset(child)); } } + + if (nonSkippedChildCount > 0 && hasDividerBeforeChildAt(count)) { + mTotalLength += mDividerWidth; + } } // Add in our padding @@ -1347,6 +1393,7 @@ public class LinearLayout extends ViewGroup { maxHeight = -1; mTotalLength = 0; + nonSkippedChildCount = 0; for (int i = 0; i < count; ++i) { final View child = getVirtualChildAt(i); @@ -1354,6 +1401,11 @@ public class LinearLayout extends ViewGroup { continue; } + nonSkippedChildCount++; + if (hasDividerBeforeChildAt(i)) { + mTotalLength += mDividerWidth; + } + final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final float childWeight = lp.weight; if (childWeight > 0) { @@ -1423,6 +1475,10 @@ public class LinearLayout extends ViewGroup { } } + if (nonSkippedChildCount > 0 && hasDividerBeforeChildAt(count)) { + mTotalLength += mDividerWidth; + } + // Add in our padding mTotalLength += mPaddingLeft + mPaddingRight; // TODO: Should we update widthSize with the new total length? @@ -1810,7 +1866,13 @@ public class LinearLayout extends ViewGroup { break; } - if (hasDividerBeforeChildAt(childIndex)) { + if (isLayoutRtl) { + // Because rtl rendering occurs in the reverse direction, we need to check + // after the child rather than before (since after=left in this context) + if (hasDividerAfterChildAt(childIndex)) { + childLeft += mDividerWidth; + } + } else if (hasDividerBeforeChildAt(childIndex)) { childLeft += mDividerWidth; } diff --git a/core/java/android/widget/RatingBar.java b/core/java/android/widget/RatingBar.java index f946fe6d8314..ec0d86295f8a 100644 --- a/core/java/android/widget/RatingBar.java +++ b/core/java/android/widget/RatingBar.java @@ -16,17 +16,22 @@ package android.widget; +import android.annotation.TestApi; import android.compat.annotation.UnsupportedAppUsage; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.shapes.RectShape; import android.graphics.drawable.shapes.Shape; import android.util.AttributeSet; +import android.util.PluralsMessageFormatter; import android.view.accessibility.AccessibilityNodeInfo; import android.view.inspector.InspectableProperty; import com.android.internal.R; +import java.util.HashMap; + + /** * A RatingBar is an extension of SeekBar and ProgressBar that shows a rating in * stars. The user can touch/drag or use arrow keys to set the rating when using @@ -53,6 +58,20 @@ import com.android.internal.R; public class RatingBar extends AbsSeekBar { /** + * Key used for generating Text-to-Speech output regarding the current star rating. + * @hide + */ + @TestApi + public static final String PLURALS_RATING = "rating"; + + /** + * Key used for generating Text-to-Speech output regarding the maximum star count. + * @hide + */ + @TestApi + public static final String PLURALS_MAX = "max"; + + /** * A callback that notifies clients when the rating has been changed. This * includes changes that were initiated by the user through a touch gesture * or arrow key/trackball as well as changes that were initiated @@ -354,6 +373,16 @@ public class RatingBar extends AbsSeekBar { if (canUserSetProgress()) { info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SET_PROGRESS); } + + final float scaledMax = getMax() * getStepSize(); + final HashMap<String, Object> params = new HashMap(); + params.put(PLURALS_RATING, getRating()); + params.put(PLURALS_MAX, scaledMax); + info.setStateDescription(PluralsMessageFormatter.format( + getContext().getResources(), + params, + R.string.rating_label + )); } @Override diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java index 1c7c5829d2bc..cd1c23cdc75f 100644 --- a/core/java/android/widget/TextView.java +++ b/core/java/android/widget/TextView.java @@ -4891,24 +4891,24 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * <p>Line-break style specifies the line-break strategies that can be used * for text wrapping. The line-break style affects rule-based line breaking - * by specifying the strictness of line-breaking rules.</p> + * by specifying the strictness of line-breaking rules. * - * <p>The following are types of line-break styles:</p> + * <p>The following are types of line-break styles: * <ul> - * <li>{@link LineBreakConfig#LINE_BREAK_STYLE_LOOSE}</li> - * <li>{@link LineBreakConfig#LINE_BREAK_STYLE_NORMAL}</li> - * <li>{@link LineBreakConfig#LINE_BREAK_STYLE_STRICT}</li> + * <li>{@link LineBreakConfig#LINE_BREAK_STYLE_LOOSE} + * <li>{@link LineBreakConfig#LINE_BREAK_STYLE_NORMAL} + * <li>{@link LineBreakConfig#LINE_BREAK_STYLE_STRICT} * </ul> * * <p>The default line-break style is * {@link LineBreakConfig#LINE_BREAK_STYLE_NONE}, which specifies that no - * line-breaking rules are used.</p> + * line-breaking rules are used. * * <p>See the * <a href="https://www.w3.org/TR/css-text-3/#line-break-property" class="external"> - * line-break property</a> for more information.</p> + * line-break property</a> for more information. * - * @param lineBreakStyle The line break style for the text. + * @param lineBreakStyle The line-break style for the text. */ public void setLineBreakStyle(@LineBreakConfig.LineBreakStyle int lineBreakStyle) { if (mLineBreakStyle != lineBreakStyle) { @@ -4927,17 +4927,17 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * <p>The line-break word style affects dictionary-based line breaking by * providing phrase-based line-breaking opportunities. Use * {@link LineBreakConfig#LINE_BREAK_WORD_STYLE_PHRASE} to specify - * phrase-based line breaking.</p> + * phrase-based line breaking. * * <p>The default line-break word style is * {@link LineBreakConfig#LINE_BREAK_WORD_STYLE_NONE}, which specifies that - * no line-breaking word style is used.</p> + * no line-breaking word style is used. * * <p>See the * <a href="https://www.w3.org/TR/css-text-3/#word-break-property" class="external"> - * word-break property</a> for more information.</p> + * word-break property</a> for more information. * - * @param lineBreakWordStyle The line break word style for the text. + * @param lineBreakWordStyle The line-break word style for the text. */ public void setLineBreakWordStyle(@LineBreakConfig.LineBreakWordStyle int lineBreakWordStyle) { mUserSpeficiedLineBreakwordStyle = true; diff --git a/core/java/android/window/ITaskFragmentOrganizerController.aidl b/core/java/android/window/ITaskFragmentOrganizerController.aidl index 8407d10bc3ea..884ca77ea377 100644 --- a/core/java/android/window/ITaskFragmentOrganizerController.aidl +++ b/core/java/android/window/ITaskFragmentOrganizerController.aidl @@ -16,8 +16,10 @@ package android.window; +import android.os.IBinder; import android.view.RemoteAnimationDefinition; import android.window.ITaskFragmentOrganizer; +import android.window.WindowContainerTransaction; /** @hide */ interface ITaskFragmentOrganizerController { @@ -46,8 +48,15 @@ interface ITaskFragmentOrganizerController { void unregisterRemoteAnimations(in ITaskFragmentOrganizer organizer, int taskId); /** - * Checks if an activity organized by a {@link android.window.TaskFragmentOrganizer} and - * only occupies a portion of Task bounds. - */ + * Checks if an activity organized by a {@link android.window.TaskFragmentOrganizer} and + * only occupies a portion of Task bounds. + */ boolean isActivityEmbedded(in IBinder activityToken); + + /** + * Notifies the server that the organizer has finished handling the given transaction. The + * server should apply the given {@link WindowContainerTransaction} for the necessary changes. + */ + void onTransactionHandled(in ITaskFragmentOrganizer organizer, in IBinder transactionToken, + in WindowContainerTransaction wct); } diff --git a/core/java/android/window/TaskFragmentOrganizer.java b/core/java/android/window/TaskFragmentOrganizer.java index cd15df84debd..7359172289cd 100644 --- a/core/java/android/window/TaskFragmentOrganizer.java +++ b/core/java/android/window/TaskFragmentOrganizer.java @@ -26,7 +26,6 @@ import static android.window.TaskFragmentTransaction.TYPE_TASK_FRAGMENT_VANISHED import android.annotation.CallSuper; import android.annotation.NonNull; import android.annotation.Nullable; -import android.annotation.SuppressLint; import android.annotation.TestApi; import android.content.Intent; import android.content.res.Configuration; @@ -141,6 +140,28 @@ public class TaskFragmentOrganizer extends WindowOrganizer { } /** + * Notifies the server that the organizer has finished handling the given transaction. The + * server should apply the given {@link WindowContainerTransaction} for the necessary changes. + * + * @param transactionToken {@link TaskFragmentTransaction#getTransactionToken()} from + * {@link #onTransactionReady(TaskFragmentTransaction)} + * @param wct {@link WindowContainerTransaction} that the server should apply for + * update of the transaction. + * @see com.android.server.wm.WindowOrganizerController#enforceTaskPermission for permission + * requirement. + * @hide + */ + public void onTransactionHandled(@NonNull IBinder transactionToken, + @NonNull WindowContainerTransaction wct) { + wct.setTaskFragmentOrganizer(mInterface); + try { + getController().onTransactionHandled(mInterface, transactionToken, wct); + } catch (RemoteException e) { + throw e.rethrowFromSystemServer(); + } + } + + /** * Called when a TaskFragment is created and organized by this organizer. * * @param wct The {@link WindowContainerTransaction} to make any changes with if needed. No @@ -227,12 +248,8 @@ public class TaskFragmentOrganizer extends WindowOrganizer { /** * Called when the transaction is ready so that the organizer can update the TaskFragments based * on the changes in transaction. - * Note: {@link WindowOrganizer#applyTransaction} permission requirement is conditional for - * {@link TaskFragmentOrganizer}. - * @see com.android.server.wm.WindowOrganizerController#enforceTaskPermission * @hide */ - @SuppressLint("AndroidFrameworkRequiresPermission") public void onTransactionReady(@NonNull TaskFragmentTransaction transaction) { final WindowContainerTransaction wct = new WindowContainerTransaction(); final List<TaskFragmentTransaction.Change> changes = transaction.getChanges(); @@ -274,8 +291,9 @@ public class TaskFragmentOrganizer extends WindowOrganizer { "Unknown TaskFragmentEvent=" + change.getType()); } } - // TODO(b/240519866): notify TaskFragmentOrganizerController that the transition is done. - applyTransaction(wct); + + // Notify the server, and the server should apply the WindowContainerTransaction. + onTransactionHandled(transaction.getTransactionToken(), wct); } @Override diff --git a/core/java/android/window/TaskFragmentTransaction.java b/core/java/android/window/TaskFragmentTransaction.java index 07e8e8c473c6..84a5fea9f57f 100644 --- a/core/java/android/window/TaskFragmentTransaction.java +++ b/core/java/android/window/TaskFragmentTransaction.java @@ -23,6 +23,7 @@ import android.annotation.NonNull; import android.annotation.Nullable; import android.content.Intent; import android.content.res.Configuration; +import android.os.Binder; import android.os.Bundle; import android.os.IBinder; import android.os.Parcel; @@ -41,19 +42,31 @@ import java.util.List; */ public final class TaskFragmentTransaction implements Parcelable { + /** Unique token to represent this transaction. */ + private final IBinder mTransactionToken; + + /** Changes in this transaction. */ private final ArrayList<Change> mChanges = new ArrayList<>(); - public TaskFragmentTransaction() {} + public TaskFragmentTransaction() { + mTransactionToken = new Binder(); + } private TaskFragmentTransaction(Parcel in) { + mTransactionToken = in.readStrongBinder(); in.readTypedList(mChanges, Change.CREATOR); } @Override public void writeToParcel(@NonNull Parcel dest, int flags) { + dest.writeStrongBinder(mTransactionToken); dest.writeTypedList(mChanges); } + public IBinder getTransactionToken() { + return mTransactionToken; + } + /** Adds a {@link Change} to this transaction. */ public void addChange(@Nullable Change change) { if (change != null) { @@ -74,7 +87,9 @@ public final class TaskFragmentTransaction implements Parcelable { @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("TaskFragmentTransaction{changes=["); + sb.append("TaskFragmentTransaction{token="); + sb.append(mTransactionToken); + sb.append(" changes=["); for (int i = 0; i < mChanges.size(); ++i) { if (i > 0) { sb.append(','); diff --git a/core/java/android/window/TransitionInfo.java b/core/java/android/window/TransitionInfo.java index b263b08d6abc..dc1f612534e2 100644 --- a/core/java/android/window/TransitionInfo.java +++ b/core/java/android/window/TransitionInfo.java @@ -119,6 +119,12 @@ public final class TransitionInfo implements Parcelable { /** The container is going to show IME on its task after the transition. */ public static final int FLAG_WILL_IME_SHOWN = 1 << 11; + /** The container attaches owner profile thumbnail for cross profile animation. */ + public static final int FLAG_CROSS_PROFILE_OWNER_THUMBNAIL = 1 << 12; + + /** The container attaches work profile thumbnail for cross profile animation. */ + public static final int FLAG_CROSS_PROFILE_WORK_THUMBNAIL = 1 << 13; + /** @hide */ @IntDef(prefix = { "FLAG_" }, value = { FLAG_NONE, @@ -508,6 +514,11 @@ public final class TransitionInfo implements Parcelable { return mFlags; } + /** Whether the given change flags has included in this change. */ + public boolean hasFlags(@ChangeFlags int flags) { + return (mFlags & flags) != 0; + } + /** * @return the bounds of the container before the change. It may be empty if the container * is coming into existence. diff --git a/core/java/com/android/internal/app/ResolverActivity.java b/core/java/com/android/internal/app/ResolverActivity.java index f67e78572402..c8bc204bd9aa 100644 --- a/core/java/com/android/internal/app/ResolverActivity.java +++ b/core/java/com/android/internal/app/ResolverActivity.java @@ -1283,9 +1283,6 @@ public class ResolverActivity extends Activity implements } if (target != null) { - if (intent != null && isLaunchingTargetInOtherProfile()) { - prepareIntentForCrossProfileLaunch(intent); - } safelyStartActivity(target); // Rely on the ActivityManager to pop up a dialog regarding app suspension @@ -1298,15 +1295,6 @@ public class ResolverActivity extends Activity implements return true; } - private void prepareIntentForCrossProfileLaunch(Intent intent) { - intent.fixUris(UserHandle.myUserId()); - } - - private boolean isLaunchingTargetInOtherProfile() { - return mMultiProfilePagerAdapter.getCurrentUserHandle().getIdentifier() - != UserHandle.myUserId(); - } - @VisibleForTesting public void safelyStartActivity(TargetInfo cti) { // We're dispatching intents that might be coming from legacy apps, so @@ -1513,9 +1501,6 @@ public class ResolverActivity extends Activity implements findViewById(R.id.button_open).setOnClickListener(v -> { Intent intent = otherProfileResolveInfo.getResolvedIntent(); - if (intent != null) { - prepareIntentForCrossProfileLaunch(intent); - } safelyStartActivityAsUser(otherProfileResolveInfo, inactiveAdapter.mResolverListController.getUserHandle()); finish(); diff --git a/core/java/com/android/internal/app/SuggestedLocaleAdapter.java b/core/java/com/android/internal/app/SuggestedLocaleAdapter.java index fcdcb2dadb54..8f6bc438ed9f 100644 --- a/core/java/com/android/internal/app/SuggestedLocaleAdapter.java +++ b/core/java/com/android/internal/app/SuggestedLocaleAdapter.java @@ -217,7 +217,11 @@ public class SuggestedLocaleAdapter extends BaseAdapter implements Filterable { case TYPE_HEADER_ALL_OTHERS: TextView textView = (TextView) itemView; if (itemType == TYPE_HEADER_SUGGESTED) { - setTextTo(textView, R.string.language_picker_section_suggested); + if (mCountryMode) { + setTextTo(textView, R.string.language_picker_regions_section_suggested); + } else { + setTextTo(textView, R.string.language_picker_section_suggested); + } } else { if (mCountryMode) { setTextTo(textView, R.string.region_picker_section_all); diff --git a/core/java/com/android/internal/app/chooser/DisplayResolveInfo.java b/core/java/com/android/internal/app/chooser/DisplayResolveInfo.java index 96cc5e1bd7d2..5f4a9cd5141e 100644 --- a/core/java/com/android/internal/app/chooser/DisplayResolveInfo.java +++ b/core/java/com/android/internal/app/chooser/DisplayResolveInfo.java @@ -172,12 +172,14 @@ public class DisplayResolveInfo implements TargetInfo, Parcelable { @Override public boolean startAsCaller(ResolverActivity activity, Bundle options, int userId) { + prepareIntentForCrossProfileLaunch(mResolvedIntent, userId); activity.startActivityAsCaller(mResolvedIntent, options, false, userId); return true; } @Override public boolean startAsUser(Activity activity, Bundle options, UserHandle user) { + prepareIntentForCrossProfileLaunch(mResolvedIntent, user.getIdentifier()); activity.startActivityAsUser(mResolvedIntent, options, user); return false; } @@ -222,6 +224,13 @@ public class DisplayResolveInfo implements TargetInfo, Parcelable { } }; + private static void prepareIntentForCrossProfileLaunch(Intent intent, int targetUserId) { + final int currentUserId = UserHandle.myUserId(); + if (targetUserId != currentUserId) { + intent.fixUris(currentUserId); + } + } + private DisplayResolveInfo(Parcel in) { mDisplayLabel = in.readCharSequence(); mExtendedInfo = in.readCharSequence(); diff --git a/core/java/com/android/internal/inputmethod/IInputMethod.aidl b/core/java/com/android/internal/inputmethod/IInputMethod.aidl index 5db2e84845f5..9182d1dc56bf 100644 --- a/core/java/com/android/internal/inputmethod/IInputMethod.aidl +++ b/core/java/com/android/internal/inputmethod/IInputMethod.aidl @@ -40,7 +40,6 @@ oneway interface IInputMethod { IBinder token; IInputMethodPrivilegedOperations privilegedOperations; int configChanges; - boolean stylusHandWritingSupported; int navigationBarFlags; } @@ -86,4 +85,6 @@ oneway interface IInputMethod { void initInkWindow(); void finishStylusHandwriting(); + + void removeStylusHandwritingWindow(); } diff --git a/core/java/com/android/internal/inputmethod/IRemoteInputConnection.aidl b/core/java/com/android/internal/inputmethod/IRemoteInputConnection.aidl index a7dd6f13b02d..7a219c61bafb 100644 --- a/core/java/com/android/internal/inputmethod/IRemoteInputConnection.aidl +++ b/core/java/com/android/internal/inputmethod/IRemoteInputConnection.aidl @@ -17,11 +17,15 @@ package com.android.internal.inputmethod; import android.os.Bundle; +import android.os.ResultReceiver; import android.view.KeyEvent; import android.view.inputmethod.CompletionInfo; import android.view.inputmethod.CorrectionInfo; +import android.view.inputmethod.DeleteGesture; import android.view.inputmethod.ExtractedTextRequest; import android.view.inputmethod.InputContentInfo; +import android.view.inputmethod.InsertGesture; +import android.view.inputmethod.SelectGesture; import android.view.inputmethod.TextAttribute; import com.android.internal.infra.AndroidFuture; @@ -86,6 +90,15 @@ import com.android.internal.inputmethod.InputConnectionCommandHeader; void performPrivateCommand(in InputConnectionCommandHeader header, String action, in Bundle data); + void performHandwritingSelectGesture(in InputConnectionCommandHeader header, + in SelectGesture gesture, in ResultReceiver resultReceiver); + + void performHandwritingInsertGesture(in InputConnectionCommandHeader header, + in InsertGesture gesture, in ResultReceiver resultReceiver); + + void performHandwritingDeleteGesture(in InputConnectionCommandHeader header, + in DeleteGesture gesture, in ResultReceiver resultReceiver); + void setComposingRegion(in InputConnectionCommandHeader header, int start, int end); void setComposingRegionWithTextAttribute(in InputConnectionCommandHeader header, int start, diff --git a/core/java/com/android/internal/inputmethod/RemoteInputConnectionImpl.java b/core/java/com/android/internal/inputmethod/RemoteInputConnectionImpl.java index b63ce1b22cdb..c65a69f05797 100644 --- a/core/java/com/android/internal/inputmethod/RemoteInputConnectionImpl.java +++ b/core/java/com/android/internal/inputmethod/RemoteInputConnectionImpl.java @@ -31,6 +31,7 @@ import android.annotation.Nullable; import android.os.Bundle; import android.os.Handler; import android.os.Looper; +import android.os.ResultReceiver; import android.os.Trace; import android.util.Log; import android.util.proto.ProtoOutputStream; @@ -39,11 +40,15 @@ import android.view.View; import android.view.ViewRootImpl; import android.view.inputmethod.CompletionInfo; import android.view.inputmethod.CorrectionInfo; +import android.view.inputmethod.DeleteGesture; import android.view.inputmethod.DumpableInputConnection; import android.view.inputmethod.ExtractedTextRequest; +import android.view.inputmethod.HandwritingGesture; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputContentInfo; import android.view.inputmethod.InputMethodManager; +import android.view.inputmethod.InsertGesture; +import android.view.inputmethod.SelectGesture; import android.view.inputmethod.TextAttribute; import android.view.inputmethod.TextSnapshot; @@ -970,6 +975,67 @@ public final class RemoteInputConnectionImpl extends IRemoteInputConnection.Stub @Dispatching(cancellable = true) @Override + public void performHandwritingSelectGesture( + InputConnectionCommandHeader header, SelectGesture gesture, + ResultReceiver resultReceiver) { + performHandwritingGestureInternal(header, gesture, resultReceiver); + } + + @Dispatching(cancellable = true) + @Override + public void performHandwritingInsertGesture( + InputConnectionCommandHeader header, InsertGesture gesture, + ResultReceiver resultReceiver) { + performHandwritingGestureInternal(header, gesture, resultReceiver); + } + + @Dispatching(cancellable = true) + @Override + public void performHandwritingDeleteGesture( + InputConnectionCommandHeader header, DeleteGesture gesture, + ResultReceiver resultReceiver) { + performHandwritingGestureInternal(header, gesture, resultReceiver); + } + + private <T extends HandwritingGesture> void performHandwritingGestureInternal( + InputConnectionCommandHeader header, T gesture, ResultReceiver resultReceiver) { + dispatchWithTracing("performHandwritingGesture", () -> { + if (header.mSessionId != mCurrentSessionId.get()) { + return; // cancelled + } + InputConnection ic = getInputConnection(); + if (ic == null || !isActive()) { + Log.w(TAG, "performHandwritingGesture on inactive InputConnection"); + return; + } + // TODO(b/210039666): implement resultReceiver + ic.performHandwritingGesture(gesture, null, null); + }); + } + + /** + * Dispatches {@link InputConnection#requestCursorUpdates(int)}. + * + * <p>This method is intended to be called only from {@link InputMethodManager}.</p> + * @param cursorUpdateMode the mode for {@link InputConnection#requestCursorUpdates(int, int)} + * @param cursorUpdateFilter the filter for + * {@link InputConnection#requestCursorUpdates(int, int)} + * @param imeDisplayId displayId on which IME is displayed. + */ + @Dispatching(cancellable = true) + public void requestCursorUpdatesFromImm(int cursorUpdateMode, int cursorUpdateFilter, + int imeDisplayId) { + final int currentSessionId = mCurrentSessionId.get(); + dispatchWithTracing("requestCursorUpdatesFromImm", () -> { + if (currentSessionId != mCurrentSessionId.get()) { + return; // cancelled + } + requestCursorUpdatesInternal(cursorUpdateMode, cursorUpdateFilter, imeDisplayId); + }); + } + + @Dispatching(cancellable = true) + @Override public void requestCursorUpdates(InputConnectionCommandHeader header, int cursorUpdateMode, int imeDisplayId, AndroidFuture future /* T=Boolean */) { dispatchWithTracing("requestCursorUpdates", future, () -> { diff --git a/core/java/com/android/internal/jank/InteractionJankMonitor.java b/core/java/com/android/internal/jank/InteractionJankMonitor.java index 72de78c148f8..fc4e041058b1 100644 --- a/core/java/com/android/internal/jank/InteractionJankMonitor.java +++ b/core/java/com/android/internal/jank/InteractionJankMonitor.java @@ -87,6 +87,7 @@ import android.annotation.IntDef; import android.annotation.NonNull; import android.annotation.UiThread; import android.annotation.WorkerThread; +import android.app.ActivityThread; import android.content.Context; import android.os.Build; import android.os.Handler; @@ -292,7 +293,10 @@ public class InteractionJankMonitor { UIINTERACTION_FRAME_INFO_REPORTED__INTERACTION_TYPE__SHADE_CLEAR_ALL, }; - private static volatile InteractionJankMonitor sInstance; + private static class InstanceHolder { + public static final InteractionJankMonitor INSTANCE = + new InteractionJankMonitor(new HandlerThread(DEFAULT_WORKER_NAME)); + } private final DeviceConfig.OnPropertiesChangedListener mPropertiesChangedListener = this::updateProperties; @@ -384,15 +388,7 @@ public class InteractionJankMonitor { * @return instance of InteractionJankMonitor */ public static InteractionJankMonitor getInstance() { - // Use DCL here since this method might be invoked very often. - if (sInstance == null) { - synchronized (InteractionJankMonitor.class) { - if (sInstance == null) { - sInstance = new InteractionJankMonitor(new HandlerThread(DEFAULT_WORKER_NAME)); - } - } - } - return sInstance; + return InstanceHolder.INSTANCE; } /** @@ -402,6 +398,11 @@ public class InteractionJankMonitor { */ @VisibleForTesting public InteractionJankMonitor(@NonNull HandlerThread worker) { + // Check permission early. + DeviceConfig.enforceReadPermission( + ActivityThread.currentApplication().getApplicationContext(), + DeviceConfig.NAMESPACE_INTERACTION_JANK_MONITOR); + mRunningTrackers = new SparseArray<>(); mTimeoutActions = new SparseArray<>(); mWorker = worker; diff --git a/core/java/com/android/internal/util/FastDataOutput.java b/core/java/com/android/internal/util/FastDataOutput.java index c9e8f8f08229..5b6075ec54ce 100644 --- a/core/java/com/android/internal/util/FastDataOutput.java +++ b/core/java/com/android/internal/util/FastDataOutput.java @@ -59,7 +59,7 @@ public class FastDataOutput implements DataOutput, Flushable, Closeable { /** * Values that have been "interned" by {@link #writeInternedUTF(String)}. */ - private final HashMap<String, Short> mStringRefs = new HashMap<>(); + private final HashMap<String, Integer> mStringRefs = new HashMap<>(); /** * @deprecated callers must specify {@code use4ByteSequence} so they make a @@ -256,7 +256,7 @@ public class FastDataOutput implements DataOutput, Flushable, Closeable { * @see FastDataInput#readInternedUTF() */ public void writeInternedUTF(@NonNull String s) throws IOException { - Short ref = mStringRefs.get(s); + Integer ref = mStringRefs.get(s); if (ref != null) { writeShort(ref); } else { @@ -265,7 +265,7 @@ public class FastDataOutput implements DataOutput, Flushable, Closeable { // We can only safely intern when we have remaining values; if we're // full we at least sent the string value above - ref = (short) mStringRefs.size(); + ref = mStringRefs.size(); if (ref < MAX_UNSIGNED_SHORT) { mStringRefs.put(s, ref); } diff --git a/core/java/com/android/internal/widget/floatingtoolbar/LocalFloatingToolbarPopup.java b/core/java/com/android/internal/widget/floatingtoolbar/LocalFloatingToolbarPopup.java index 95a4e1238e06..bc729f10d74c 100644 --- a/core/java/com/android/internal/widget/floatingtoolbar/LocalFloatingToolbarPopup.java +++ b/core/java/com/android/internal/widget/floatingtoolbar/LocalFloatingToolbarPopup.java @@ -1475,7 +1475,6 @@ public final class LocalFloatingToolbarPopup implements FloatingToolbarPopup { contentContainer.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); contentContainer.setTag(FloatingToolbar.FLOATING_TOOLBAR_TAG); - contentContainer.setContentDescription(FloatingToolbar.FLOATING_TOOLBAR_TAG); contentContainer.setClipToOutline(true); return contentContainer; } diff --git a/core/jni/OWNERS b/core/jni/OWNERS index 671e63493323..7f50204fb842 100644 --- a/core/jni/OWNERS +++ b/core/jni/OWNERS @@ -49,7 +49,7 @@ per-file android_hardware_SensorManager* = arthuri@google.com, bduddie@google.co per-file *Zygote* = file:/ZYGOTE_OWNERS per-file core_jni_helpers.* = file:/ZYGOTE_OWNERS per-file fd_utils.* = file:/ZYGOTE_OWNERS -per-file Android.bp = file:platform/build/soong:/OWNERS +per-file Android.bp = file:platform/build/soong:/OWNERS #{LAST_RESORT_SUGGESTION} per-file android_animation_* = file:/core/java/android/animation/OWNERS per-file android_app_admin_* = file:/core/java/android/app/admin/OWNERS per-file android_hardware_Usb* = file:/services/usb/OWNERS diff --git a/core/jni/android_view_SurfaceControl.cpp b/core/jni/android_view_SurfaceControl.cpp index 9ae16304b6c8..bc299fd0f1fe 100644 --- a/core/jni/android_view_SurfaceControl.cpp +++ b/core/jni/android_view_SurfaceControl.cpp @@ -820,14 +820,6 @@ static void nativeSetStretchEffect(JNIEnv* env, jclass clazz, jlong transactionO transaction->setStretchEffect(ctrl, stretch); } -static void nativeSetSize(JNIEnv* env, jclass clazz, jlong transactionObj, - jlong nativeObject, jint w, jint h) { - auto transaction = reinterpret_cast<SurfaceComposerClient::Transaction*>(transactionObj); - - SurfaceControl* const ctrl = reinterpret_cast<SurfaceControl *>(nativeObject); - transaction->setSize(ctrl, w, h); -} - static void nativeSetFlags(JNIEnv* env, jclass clazz, jlong transactionObj, jlong nativeObject, jint flags, jint mask) { auto transaction = reinterpret_cast<SurfaceComposerClient::Transaction*>(transactionObj); @@ -2121,6 +2113,20 @@ static jint nativeGetLayerId(JNIEnv* env, jclass clazz, jlong nativeSurfaceContr return surface->getLayerId(); } +static void nativeSetDefaultApplyToken(JNIEnv* env, jclass clazz, jobject applyToken) { + sp<IBinder> token(ibinderForJavaObject(env, applyToken)); + if (token == nullptr) { + ALOGE("Null apply token provided."); + return; + } + SurfaceComposerClient::Transaction::setDefaultApplyToken(token); +} + +static jobject nativeGetDefaultApplyToken(JNIEnv* env, jclass clazz) { + sp<IBinder> token = SurfaceComposerClient::Transaction::getDefaultApplyToken(); + return javaObjectForIBinder(env, token); +} + // ---------------------------------------------------------------------------- static const JNINativeMethod sSurfaceControlMethods[] = { @@ -2163,8 +2169,6 @@ static const JNINativeMethod sSurfaceControlMethods[] = { (void*)nativeSetPosition }, {"nativeSetScale", "(JJFF)V", (void*)nativeSetScale }, - {"nativeSetSize", "(JJII)V", - (void*)nativeSetSize }, {"nativeSetTransparentRegionHint", "(JJLandroid/graphics/Region;)V", (void*)nativeSetTransparentRegionHint }, {"nativeSetDamageRegion", "(JJLandroid/graphics/Region;)V", @@ -2343,6 +2347,10 @@ static const JNINativeMethod sSurfaceControlMethods[] = { (void*) nativeSanitize }, {"nativeSetDestinationFrame", "(JJIIII)V", (void*)nativeSetDestinationFrame }, + {"nativeSetDefaultApplyToken", "(Landroid/os/IBinder;)V", + (void*)nativeSetDefaultApplyToken }, + {"nativeGetDefaultApplyToken", "()Landroid/os/IBinder;", + (void*)nativeGetDefaultApplyToken }, // clang-format on }; diff --git a/core/jni/com_android_internal_os_LongArrayMultiStateCounter.cpp b/core/jni/com_android_internal_os_LongArrayMultiStateCounter.cpp index 0ebf2dddd7eb..5b946d5c8d3a 100644 --- a/core/jni/com_android_internal_os_LongArrayMultiStateCounter.cpp +++ b/core/jni/com_android_internal_os_LongArrayMultiStateCounter.cpp @@ -99,12 +99,13 @@ static void throwWriteRE(JNIEnv *env, binder_status_t status) { jniThrowRuntimeException(env, "Could not write LongArrayMultiStateCounter to Parcel"); } -#define THROW_ON_WRITE_ERROR(expr) \ - { \ - binder_status_t status = expr; \ - if (status != STATUS_OK) { \ - throwWriteRE(env, status); \ - } \ +#define THROW_AND_RETURN_ON_WRITE_ERROR(expr) \ + { \ + binder_status_t status = expr; \ + if (status != STATUS_OK) { \ + throwWriteRE(env, status); \ + return; \ + } \ } static void native_writeToParcel(JNIEnv *env, jobject self, jlong nativePtr, jobject jParcel, @@ -114,14 +115,15 @@ static void native_writeToParcel(JNIEnv *env, jobject self, jlong nativePtr, job ndk::ScopedAParcel parcel(AParcel_fromJavaParcel(env, jParcel)); uint16_t stateCount = counter->getStateCount(); - THROW_ON_WRITE_ERROR(AParcel_writeInt32(parcel.get(), stateCount)); + THROW_AND_RETURN_ON_WRITE_ERROR(AParcel_writeInt32(parcel.get(), stateCount)); // LongArrayMultiStateCounter has at least state 0 const std::vector<uint64_t> &anyState = counter->getCount(0); - THROW_ON_WRITE_ERROR(AParcel_writeInt32(parcel.get(), anyState.size())); + THROW_AND_RETURN_ON_WRITE_ERROR(AParcel_writeInt32(parcel.get(), anyState.size())); for (battery::state_t state = 0; state < stateCount; state++) { - THROW_ON_WRITE_ERROR(ndk::AParcel_writeVector(parcel.get(), counter->getCount(state))); + THROW_AND_RETURN_ON_WRITE_ERROR( + ndk::AParcel_writeVector(parcel.get(), counter->getCount(state))); } } @@ -130,35 +132,37 @@ static void throwReadRE(JNIEnv *env, binder_status_t status) { jniThrowRuntimeException(env, "Could not read LongArrayMultiStateCounter from Parcel"); } -#define THROW_ON_READ_ERROR(expr) \ - { \ - binder_status_t status = expr; \ - if (status != STATUS_OK) { \ - throwReadRE(env, status); \ - } \ +#define THROW_AND_RETURN_ON_READ_ERROR(expr) \ + { \ + binder_status_t status = expr; \ + if (status != STATUS_OK) { \ + throwReadRE(env, status); \ + return 0L; \ + } \ } static jlong native_initFromParcel(JNIEnv *env, jclass theClass, jobject jParcel) { ndk::ScopedAParcel parcel(AParcel_fromJavaParcel(env, jParcel)); int32_t stateCount; - THROW_ON_READ_ERROR(AParcel_readInt32(parcel.get(), &stateCount)); + THROW_AND_RETURN_ON_READ_ERROR(AParcel_readInt32(parcel.get(), &stateCount)); int32_t arrayLength; - THROW_ON_READ_ERROR(AParcel_readInt32(parcel.get(), &arrayLength)); + THROW_AND_RETURN_ON_READ_ERROR(AParcel_readInt32(parcel.get(), &arrayLength)); - battery::LongArrayMultiStateCounter *counter = - new battery::LongArrayMultiStateCounter(stateCount, std::vector<uint64_t>(arrayLength)); + auto counter = std::make_unique<battery::LongArrayMultiStateCounter>(stateCount, + std::vector<uint64_t>( + arrayLength)); std::vector<uint64_t> value; value.reserve(arrayLength); for (battery::state_t state = 0; state < stateCount; state++) { - THROW_ON_READ_ERROR(ndk::AParcel_readVector(parcel.get(), &value)); + THROW_AND_RETURN_ON_READ_ERROR(ndk::AParcel_readVector(parcel.get(), &value)); counter->setValue(state, value); } - return reinterpret_cast<jlong>(counter); + return reinterpret_cast<jlong>(counter.release()); } static jint native_getStateCount(jlong nativePtr) { diff --git a/core/jni/com_android_internal_os_LongMultiStateCounter.cpp b/core/jni/com_android_internal_os_LongMultiStateCounter.cpp index 8c69d276fe6a..1712b3a8512b 100644 --- a/core/jni/com_android_internal_os_LongMultiStateCounter.cpp +++ b/core/jni/com_android_internal_os_LongMultiStateCounter.cpp @@ -109,12 +109,13 @@ static void throwWriteRE(JNIEnv *env, binder_status_t status) { jniThrowRuntimeException(env, "Could not write LongMultiStateCounter to Parcel"); } -#define THROW_ON_WRITE_ERROR(expr) \ - { \ - binder_status_t status = expr; \ - if (status != STATUS_OK) { \ - throwWriteRE(env, status); \ - } \ +#define THROW_AND_RETURN_ON_WRITE_ERROR(expr) \ + { \ + binder_status_t status = expr; \ + if (status != STATUS_OK) { \ + throwWriteRE(env, status); \ + return; \ + } \ } static void native_writeToParcel(JNIEnv *env, jobject self, jlong nativePtr, jobject jParcel, @@ -123,10 +124,10 @@ static void native_writeToParcel(JNIEnv *env, jobject self, jlong nativePtr, job ndk::ScopedAParcel parcel(AParcel_fromJavaParcel(env, jParcel)); uint16_t stateCount = counter->getStateCount(); - THROW_ON_WRITE_ERROR(AParcel_writeInt32(parcel.get(), stateCount)); + THROW_AND_RETURN_ON_WRITE_ERROR(AParcel_writeInt32(parcel.get(), stateCount)); for (battery::state_t state = 0; state < stateCount; state++) { - THROW_ON_WRITE_ERROR(AParcel_writeInt64(parcel.get(), counter->getCount(state))); + THROW_AND_RETURN_ON_WRITE_ERROR(AParcel_writeInt64(parcel.get(), counter->getCount(state))); } } @@ -135,29 +136,30 @@ static void throwReadRE(JNIEnv *env, binder_status_t status) { jniThrowRuntimeException(env, "Could not read LongMultiStateCounter from Parcel"); } -#define THROW_ON_READ_ERROR(expr) \ - { \ - binder_status_t status = expr; \ - if (status != STATUS_OK) { \ - throwReadRE(env, status); \ - } \ +#define THROW_AND_RETURN_ON_READ_ERROR(expr) \ + { \ + binder_status_t status = expr; \ + if (status != STATUS_OK) { \ + throwReadRE(env, status); \ + return 0L; \ + } \ } static jlong native_initFromParcel(JNIEnv *env, jclass theClass, jobject jParcel) { ndk::ScopedAParcel parcel(AParcel_fromJavaParcel(env, jParcel)); int32_t stateCount; - THROW_ON_READ_ERROR(AParcel_readInt32(parcel.get(), &stateCount)); + THROW_AND_RETURN_ON_READ_ERROR(AParcel_readInt32(parcel.get(), &stateCount)); - battery::LongMultiStateCounter *counter = new battery::LongMultiStateCounter(stateCount, 0); + auto counter = std::make_unique<battery::LongMultiStateCounter>(stateCount, 0); for (battery::state_t state = 0; state < stateCount; state++) { int64_t value; - THROW_ON_READ_ERROR(AParcel_readInt64(parcel.get(), &value)); + THROW_AND_RETURN_ON_READ_ERROR(AParcel_readInt64(parcel.get(), &value)); counter->setValue(state, value); } - return reinterpret_cast<jlong>(counter); + return reinterpret_cast<jlong>(counter.release()); } static jint native_getStateCount(jlong nativePtr) { diff --git a/core/proto/android/os/tombstone.proto b/core/proto/android/os/tombstone.proto new file mode 100644 index 000000000000..2d3b1f3ae220 --- /dev/null +++ b/core/proto/android/os/tombstone.proto @@ -0,0 +1,30 @@ +/* + * 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. + */ + +syntax = "proto2"; + +package android.os; + +option java_multiple_files = true; + +message TombstoneWithHeadersProto { + // The original proto tombstone bytes. + // Proto located at: system/core/debuggerd/proto/tombstone.proto + optional bytes tombstone = 1; + + // The count of dropped dropbox entries due to rate limiting. + optional int32 dropped_count = 2; +}
\ No newline at end of file diff --git a/core/res/Android.bp b/core/res/Android.bp index c42517d8a873..93ce7832824b 100644 --- a/core/res/Android.bp +++ b/core/res/Android.bp @@ -73,18 +73,18 @@ genrule { ":remote-color-resources-compile-colors", ], out: ["remote-color-resources.apk"], - cmd: "$(location aapt2) link -o $(out) --manifest $(in)" + cmd: "$(location aapt2) link -o $(out) --manifest $(in)", } genrule { name: "remote-color-resources-arsc", srcs: [":remote-color-resources-apk"], out: ["res/raw/remote_views_color_resources.arsc"], - cmd: "mkdir -p $(genDir)/remote-color-resources-arsc && " - + "unzip -x $(in) resources.arsc -d $(genDir)/remote-color-resources-arsc && " - + "mkdir -p $$(dirname $(out)) && " - + "mv $(genDir)/remote-color-resources-arsc/resources.arsc $(out) && " - + "echo 'Created $(out)'" + cmd: "mkdir -p $(genDir)/remote-color-resources-arsc && " + + "unzip -x $(in) resources.arsc -d $(genDir)/remote-color-resources-arsc && " + + "mkdir -p $$(dirname $(out)) && " + + "mv $(genDir)/remote-color-resources-arsc/resources.arsc $(out) && " + + "echo 'Created $(out)'", } genrule { @@ -95,11 +95,11 @@ genrule { "remote_color_resources_res/symbols.xml", ], out: ["remote_views_color_resources.zip"], - cmd: "INPUTS=($(in)) && " - + "RES_DIR=$$(dirname $$(dirname $${INPUTS[0]})) && " - + "mkdir -p $$RES_DIR/values && " - + "cp $${INPUTS[1]} $$RES_DIR/values && " - + "$(location soong_zip) -o $(out) -C $$RES_DIR -D $$RES_DIR" + cmd: "INPUTS=($(in)) && " + + "RES_DIR=$$(dirname $$(dirname $${INPUTS[0]})) && " + + "mkdir -p $$RES_DIR/values && " + + "cp $${INPUTS[1]} $$RES_DIR/values && " + + "$(location soong_zip) -o $(out) -C $$RES_DIR -D $$RES_DIR", } android_app { @@ -154,31 +154,21 @@ java_genrule { cmd: "cp $(in) $(out)", } -// This logic can be removed once robolectric's transition to binary resources is complete -filegroup { - name: "robolectric_framework_raw_res_files", - srcs: [ - "assets/**/*", - "res/**/*", - ":remote-color-resources-arsc", - ], -} - // Generate a text file containing a list of permissions that non-system apps // are allowed to obtain. genrule { - name: "permission-list-normal", - out: ["permission-list-normal.txt"], - srcs: ["AndroidManifest.xml"], - cmd: "cat $(in) " + - // xmllint has trouble accessing attributes under the android namespace. - // Strip these prefixes prior to processing with xmllint. - " | sed -r 's/android:(name|protectionLevel)/\\1/g' " + - " | $(location xmllint) /dev/stdin --xpath " + - " '//permission[not(contains(@protectionLevel, \"signature\"))]/@name'" + - // The result of xmllint is name="value" pairs. Format these to just the - // permission name, one per-line. - " | sed -r 's/\\s*name=\\s*//g' | tr -d '\"'" + - " > $(out)", - tools: ["xmllint"] + name: "permission-list-normal", + out: ["permission-list-normal.txt"], + srcs: ["AndroidManifest.xml"], + cmd: "cat $(in) " + + // xmllint has trouble accessing attributes under the android namespace. + // Strip these prefixes prior to processing with xmllint. + " | sed -r 's/android:(name|protectionLevel)/\\1/g' " + + " | $(location xmllint) /dev/stdin --xpath " + + " '//permission[not(contains(@protectionLevel, \"signature\"))]/@name'" + + // The result of xmllint is name="value" pairs. Format these to just the + // permission name, one per-line. + " | sed -r 's/\\s*name=\\s*//g' | tr -d '\"'" + + " > $(out)", + tools: ["xmllint"], } diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml index 3fbd7973d81f..cd518cea8d87 100644 --- a/core/res/AndroidManifest.xml +++ b/core/res/AndroidManifest.xml @@ -2975,7 +2975,7 @@ <permission android:name="android.permission.REAL_GET_TASKS" android:protectionLevel="signature|privileged" /> - <!-- @TestApi Allows an application to start a task from a ActivityManager#RecentTaskInfo. + <!-- @SystemApi Allows an application to start a task from a ActivityManager#RecentTaskInfo. @hide --> <permission android:name="android.permission.START_TASKS_FROM_RECENTS" android:protectionLevel="signature|privileged|recents" /> diff --git a/core/res/res/layout/floating_popup_container.xml b/core/res/res/layout/floating_popup_container.xml index ca0373773577..776a35d15ef0 100644 --- a/core/res/res/layout/floating_popup_container.xml +++ b/core/res/res/layout/floating_popup_container.xml @@ -16,6 +16,7 @@ */ --> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/floating_popup_container" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="0dp" diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml index b59cf7fd3bcb..116b15051e7d 100644 --- a/core/res/res/values/config.xml +++ b/core/res/res/values/config.xml @@ -2392,9 +2392,6 @@ <!-- The list of supported dream complications --> <integer-array name="config_supportedDreamComplications"> </integer-array> - <!-- The list of dream complications which should be enabled by default --> - <integer-array name="config_dreamComplicationsEnabledByDefault"> - </integer-array> <!-- Are we allowed to dream while not plugged in? --> <bool name="config_dreamsEnabledOnBattery">false</bool> diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml index b7da6ae31ce3..e5b1cf9be748 100644 --- a/core/res/res/values/strings.xml +++ b/core/res/res/values/strings.xml @@ -3365,6 +3365,13 @@ <!-- Default not selected text used by accessibility for an element that can be selected or unselected. [CHAR LIMIT=NONE] --> <string name="not_selected">not selected</string> + <!-- Default label text used by accessibility for ratingbars. [CHAR LIMIT=NONE] --> + <string name ="rating_label">{ rating, plural, + =1 {One star out of {max}} + other {# stars out of {max}} + } + </string> + <!-- Default state description for indeterminate progressbar. [CHAR LIMIT=NONE] --> <string name="in_progress">in progress</string> @@ -5422,8 +5429,10 @@ <!-- Hint text in a search edit box (used to filter long language / country lists) [CHAR LIMIT=25] --> <string name="search_language_hint">Type language name</string> - <!-- List section subheader for the language picker, containing a list of suggested languages determined by the default region [CHAR LIMIT=30] --> + <!-- List section subheader for the language picker, containing a list of suggested languages [CHAR LIMIT=30] --> <string name="language_picker_section_suggested">Suggested</string> + <!-- "List section subheader for the language picker, containing a list of suggested regions available for that language [CHAR LIMIT=30] --> + <string name="language_picker_regions_section_suggested">Suggested</string> <!-- List section subheader for the language picker, containing a list of suggested languages determined by the default region [CHAR LIMIT=30] --> <string name="language_picker_section_suggested_bilingual">Suggested languages</string> @@ -5750,7 +5759,7 @@ <!-- Content for the log access confirmation dialog. [CHAR LIMIT=NONE]--> <string name="log_access_confirmation_body">Device logs record what happens on your device. Apps can use these logs to find and fix issues.\n\nSome logs may contain sensitive info, so only allow apps you trust to access all device logs. - \n\nIf you don’t allow this app to access all device logs, it can still access its own logs. Your device manufacturer may still be able to access some logs or info on your device. Learn more + \n\nIf you don’t allow this app to access all device logs, it can still access its own logs. Your device manufacturer may still be able to access some logs or info on your device. </string> <!-- Privacy notice do not show [CHAR LIMIT=20] --> diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml index d60fc209ebc1..d7836c12e9d6 100644 --- a/core/res/res/values/symbols.xml +++ b/core/res/res/values/symbols.xml @@ -925,6 +925,7 @@ <java-symbol type="string" name="mobile_provisioning_apn" /> <java-symbol type="string" name="mobile_provisioning_url" /> <java-symbol type="string" name="quick_contacts_not_available" /> + <java-symbol type="string" name="rating_label" /> <java-symbol type="string" name="reboot_to_update_package" /> <java-symbol type="string" name="reboot_to_update_prepare" /> <java-symbol type="string" name="reboot_to_update_title" /> @@ -2228,7 +2229,6 @@ <java-symbol type="string" name="config_dreamsDefaultComponent" /> <java-symbol type="bool" name="config_dreamsOnlyEnabledForSystemUser" /> <java-symbol type="array" name="config_supportedDreamComplications" /> - <java-symbol type="array" name="config_dreamComplicationsEnabledByDefault" /> <java-symbol type="array" name="config_disabledDreamComponents" /> <java-symbol type="bool" name="config_dismissDreamOnActivityStart" /> <java-symbol type="string" name="config_loggable_dream_prefix" /> @@ -3141,6 +3141,7 @@ <java-symbol type="string" name="language_picker_section_all" /> <java-symbol type="string" name="region_picker_section_all" /> <java-symbol type="string" name="language_picker_section_suggested" /> + <java-symbol type="string" name="language_picker_regions_section_suggested" /> <java-symbol type="string" name="language_picker_section_suggested_bilingual" /> <java-symbol type="string" name="region_picker_section_suggested_bilingual" /> <java-symbol type="string" name="language_selection_title" /> diff --git a/core/tests/coretests/src/android/app/servertransaction/ObjectPoolTests.java b/core/tests/coretests/src/android/app/servertransaction/ObjectPoolTests.java index 0a5a4d5a9adb..993ecf66c25b 100644 --- a/core/tests/coretests/src/android/app/servertransaction/ObjectPoolTests.java +++ b/core/tests/coretests/src/android/app/servertransaction/ObjectPoolTests.java @@ -221,15 +221,15 @@ public class ObjectPoolTests { @Test public void testRecyclePauseActivityItemItem() { - PauseActivityItem emptyItem = PauseActivityItem.obtain(false, false, 0, false); - PauseActivityItem item = PauseActivityItem.obtain(true, true, 5, true); + PauseActivityItem emptyItem = PauseActivityItem.obtain(false, false, 0, false, false); + PauseActivityItem item = PauseActivityItem.obtain(true, true, 5, true, true); assertNotSame(item, emptyItem); assertFalse(item.equals(emptyItem)); item.recycle(); assertEquals(item, emptyItem); - PauseActivityItem item2 = PauseActivityItem.obtain(true, false, 5, true); + PauseActivityItem item2 = PauseActivityItem.obtain(true, false, 5, true, true); assertSame(item, item2); assertFalse(item2.equals(emptyItem)); } diff --git a/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java b/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java index e9bbdbee576c..b292d7dfafe2 100644 --- a/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java +++ b/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java @@ -234,7 +234,8 @@ public class TransactionParcelTests { public void testPause() { // Write to parcel PauseActivityItem item = PauseActivityItem.obtain(true /* finished */, - true /* userLeaving */, 135 /* configChanges */, true /* dontReport */); + true /* userLeaving */, 135 /* configChanges */, true /* dontReport */, + true /* autoEnteringPip */); writeAndPrepareForReading(item); // Read from parcel and assert diff --git a/core/tests/coretests/src/android/widget/FloatingToolbarUtils.java b/core/tests/coretests/src/android/widget/FloatingToolbarUtils.java index c6f592447c22..2d3ed9510534 100644 --- a/core/tests/coretests/src/android/widget/FloatingToolbarUtils.java +++ b/core/tests/coretests/src/android/widget/FloatingToolbarUtils.java @@ -16,13 +16,12 @@ package android.widget; -import static com.android.internal.widget.floatingtoolbar.FloatingToolbar.FLOATING_TOOLBAR_TAG; - import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import android.content.res.Resources; import android.support.test.uiautomator.By; +import android.support.test.uiautomator.BySelector; import android.support.test.uiautomator.UiDevice; import android.support.test.uiautomator.Until; @@ -33,25 +32,27 @@ import com.android.internal.R; final class FloatingToolbarUtils { private final UiDevice mDevice; + private static final BySelector TOOLBAR_CONTAINER_SELECTOR = + By.res("android", "floating_popup_container"); FloatingToolbarUtils() { mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); } void waitForFloatingToolbarPopup() { - mDevice.wait(Until.findObject(By.desc(FLOATING_TOOLBAR_TAG)), 500); + mDevice.wait(Until.findObject(TOOLBAR_CONTAINER_SELECTOR), 500); } void assertFloatingToolbarIsDisplayed() { waitForFloatingToolbarPopup(); - assertThat(mDevice.hasObject(By.desc(FLOATING_TOOLBAR_TAG))).isTrue(); + assertThat(mDevice.hasObject(TOOLBAR_CONTAINER_SELECTOR)).isTrue(); } void assertFloatingToolbarContainsItem(String itemLabel) { waitForFloatingToolbarPopup(); assertWithMessage("Expected to find item labelled [" + itemLabel + "]") .that(mDevice.hasObject( - By.desc(FLOATING_TOOLBAR_TAG).hasDescendant(By.text(itemLabel)))) + TOOLBAR_CONTAINER_SELECTOR.hasDescendant(By.text(itemLabel)))) .isTrue(); } @@ -59,14 +60,14 @@ final class FloatingToolbarUtils { waitForFloatingToolbarPopup(); assertWithMessage("Expected to not find item labelled [" + itemLabel + "]") .that(mDevice.hasObject( - By.desc(FLOATING_TOOLBAR_TAG).hasDescendant(By.text(itemLabel)))) + TOOLBAR_CONTAINER_SELECTOR.hasDescendant(By.text(itemLabel)))) .isFalse(); } void assertFloatingToolbarContainsItemAtIndex(String itemLabel, int index) { waitForFloatingToolbarPopup(); assertWithMessage("Expected to find item labelled [" + itemLabel + "] at index " + index) - .that(mDevice.findObject(By.desc(FLOATING_TOOLBAR_TAG)) + .that(mDevice.findObject(TOOLBAR_CONTAINER_SELECTOR) .findObjects(By.clickable(true)) .get(index) .getChildren() @@ -77,7 +78,7 @@ final class FloatingToolbarUtils { void clickFloatingToolbarItem(String label) { waitForFloatingToolbarPopup(); - mDevice.findObject(By.desc(FLOATING_TOOLBAR_TAG)) + mDevice.findObject(TOOLBAR_CONTAINER_SELECTOR) .findObject(By.text(label)) .click(); } @@ -85,13 +86,13 @@ final class FloatingToolbarUtils { void clickFloatingToolbarOverflowItem(String label) { // TODO: There might be a benefit to combining this with "clickFloatingToolbarItem" method. waitForFloatingToolbarPopup(); - mDevice.findObject(By.desc(FLOATING_TOOLBAR_TAG)) + mDevice.findObject(TOOLBAR_CONTAINER_SELECTOR) .findObject(By.desc(str(R.string.floating_toolbar_open_overflow_description))) .click(); mDevice.wait( - Until.findObject(By.desc(FLOATING_TOOLBAR_TAG).hasDescendant(By.text(label))), + Until.findObject(TOOLBAR_CONTAINER_SELECTOR.hasDescendant(By.text(label))), 1000); - mDevice.findObject(By.desc(FLOATING_TOOLBAR_TAG)) + mDevice.findObject(TOOLBAR_CONTAINER_SELECTOR) .findObject(By.text(label)) .click(); } diff --git a/core/tests/coretests/src/com/android/internal/os/LongArrayMultiStateCounterTest.java b/core/tests/coretests/src/com/android/internal/os/LongArrayMultiStateCounterTest.java index 9eb4ccb2663b..a22dd1c63ddf 100644 --- a/core/tests/coretests/src/com/android/internal/os/LongArrayMultiStateCounterTest.java +++ b/core/tests/coretests/src/com/android/internal/os/LongArrayMultiStateCounterTest.java @@ -18,6 +18,8 @@ package com.android.internal.os; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; + import android.os.Parcel; import androidx.test.filters.SmallTest; @@ -149,4 +151,14 @@ public class LongArrayMultiStateCounterTest { container.getValues(counts); assertThat(counts).isEqualTo(expected); } + + @Test + public void createFromBadParcel() { + // Check we don't crash the runtime if the Parcel data is bad (b/243434675). + Parcel parcel = Parcel.obtain(); + parcel.writeInt(2); + parcel.setDataPosition(0); + assertThrows(RuntimeException.class, + () -> LongArrayMultiStateCounter.CREATOR.createFromParcel(parcel)); + } } diff --git a/core/tests/coretests/src/com/android/internal/os/LongMultiStateCounterTest.java b/core/tests/coretests/src/com/android/internal/os/LongMultiStateCounterTest.java index e717ebbc997c..fc86ebe1c10e 100644 --- a/core/tests/coretests/src/com/android/internal/os/LongMultiStateCounterTest.java +++ b/core/tests/coretests/src/com/android/internal/os/LongMultiStateCounterTest.java @@ -18,6 +18,8 @@ package com.android.internal.os; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; + import android.os.Parcel; import androidx.test.filters.SmallTest; @@ -198,4 +200,14 @@ public class LongMultiStateCounterTest { assertThat(newCounter.getCount(0)).isEqualTo(116); } + + @Test + public void createFromBadParcel() { + // Check we don't crash the runtime if the Parcel data is bad (b/243434675). + Parcel parcel = Parcel.obtain(); + parcel.writeInt(13); + parcel.setDataPosition(0); + assertThrows(RuntimeException.class, + () -> LongMultiStateCounter.CREATOR.createFromParcel(parcel)); + } } diff --git a/core/tests/mockingcoretests/src/android/app/activity/ActivityThreadClientTest.java b/core/tests/mockingcoretests/src/android/app/activity/ActivityThreadClientTest.java index f4a6f025074e..613eddd30c8a 100644 --- a/core/tests/mockingcoretests/src/android/app/activity/ActivityThreadClientTest.java +++ b/core/tests/mockingcoretests/src/android/app/activity/ActivityThreadClientTest.java @@ -298,8 +298,8 @@ public class ActivityThreadClientTest { private void pauseActivity(ActivityClientRecord r) { mThread.handlePauseActivity(r, false /* finished */, - false /* userLeaving */, 0 /* configChanges */, null /* pendingActions */, - "test"); + false /* userLeaving */, 0 /* configChanges */, false /* autoEnteringPip */, + null /* pendingActions */, "test"); } private void stopActivity(ActivityClientRecord r) { diff --git a/data/etc/services.core.protolog.json b/data/etc/services.core.protolog.json index 03d22ac44f6a..6aedcd493f5c 100644 --- a/data/etc/services.core.protolog.json +++ b/data/etc/services.core.protolog.json @@ -2065,6 +2065,12 @@ "group": "WM_DEBUG_CONFIGURATION", "at": "com\/android\/server\/wm\/ActivityRecord.java" }, + "-108248992": { + "message": "Defer transition ready for TaskFragmentTransaction=%s", + "level": "VERBOSE", + "group": "WM_DEBUG_WINDOW_TRANSITIONS", + "at": "com\/android\/server\/wm\/TaskFragmentOrganizerController.java" + }, "-106400104": { "message": "Preload recents with %s", "level": "DEBUG", @@ -2113,6 +2119,12 @@ "group": "WM_DEBUG_STATES", "at": "com\/android\/server\/wm\/TaskFragment.java" }, + "-79016993": { + "message": "Continue transition ready for TaskFragmentTransaction=%s", + "level": "VERBOSE", + "group": "WM_DEBUG_WINDOW_TRANSITIONS", + "at": "com\/android\/server\/wm\/TaskFragmentOrganizerController.java" + }, "-70719599": { "message": "Unregister remote animations for organizer=%s uid=%d pid=%d", "level": "VERBOSE", @@ -2659,6 +2671,12 @@ "group": "WM_DEBUG_ANIM", "at": "com\/android\/server\/wm\/WindowContainer.java" }, + "390947100": { + "message": "Screenshotting %s [%s]", + "level": "VERBOSE", + "group": "WM_DEBUG_WINDOW_TRANSITIONS", + "at": "com\/android\/server\/wm\/Transition.java" + }, "397382873": { "message": "Moving to PAUSED: %s %s", "level": "VERBOSE", @@ -4177,6 +4195,12 @@ "group": "WM_DEBUG_FOCUS_LIGHT", "at": "com\/android\/server\/wm\/InputMonitor.java" }, + "2004282287": { + "message": "Override sync-method for %s because seamless rotating", + "level": "VERBOSE", + "group": "WM_DEBUG_WINDOW_TRANSITIONS", + "at": "com\/android\/server\/wm\/Transition.java" + }, "2010476671": { "message": "Animation done in %s: reportedVisible=%b okToDisplay=%b okToAnimate=%b startingDisplayed=%b", "level": "VERBOSE", diff --git a/data/fonts/fonts.xml b/data/fonts/fonts.xml index f8c015f28a50..8e2a59cd848a 100644 --- a/data/fonts/fonts.xml +++ b/data/fonts/fonts.xml @@ -39,7 +39,11 @@ <axis tag="wdth" stylevalue="100" /> <axis tag="wght" stylevalue="300" /> </font> - <font weight="400" style="normal">RobotoStatic-Regular.ttf</font> + <font weight="400" style="normal">Roboto-Regular.ttf + <axis tag="ital" stylevalue="0" /> + <axis tag="wdth" stylevalue="100" /> + <axis tag="wght" stylevalue="400" /> + </font> <font weight="500" style="normal">Roboto-Regular.ttf <axis tag="ital" stylevalue="0" /> <axis tag="wdth" stylevalue="100" /> diff --git a/graphics/java/android/graphics/text/LineBreakConfig.java b/graphics/java/android/graphics/text/LineBreakConfig.java index 48aecd61fc19..d0327159b04d 100644 --- a/graphics/java/android/graphics/text/LineBreakConfig.java +++ b/graphics/java/android/graphics/text/LineBreakConfig.java @@ -28,7 +28,7 @@ import java.util.Objects; * * <p>See the * <a href="https://www.w3.org/TR/css-text-3/#line-break-property" class="external"> - * line-break property</a> for more information.</p> + * line-break property</a> for more information. */ public final class LineBreakConfig { @@ -72,7 +72,7 @@ public final class LineBreakConfig { * * <p>Support for this line-break word style depends on locale. If the * current locale does not support phrase-based text wrapping, this setting - * has no effect.</p> + * has no effect. */ public static final int LINE_BREAK_WORD_STYLE_PHRASE = 1; @@ -194,7 +194,7 @@ public final class LineBreakConfig { * Constructor with line-break parameters. * * <p>Use {@link LineBreakConfig.Builder} to create the - * {@code LineBreakConfig} instance.</p> + * {@code LineBreakConfig} instance. */ private LineBreakConfig(@LineBreakStyle int lineBreakStyle, @LineBreakWordStyle int lineBreakWordStyle, boolean autoPhraseBreaking) { diff --git a/libs/WindowManager/Jetpack/src/androidx/window/extensions/layout/WindowLayoutComponentImpl.java b/libs/WindowManager/Jetpack/src/androidx/window/extensions/layout/WindowLayoutComponentImpl.java index 6bfb16a3c22d..f24401f0cd53 100644 --- a/libs/WindowManager/Jetpack/src/androidx/window/extensions/layout/WindowLayoutComponentImpl.java +++ b/libs/WindowManager/Jetpack/src/androidx/window/extensions/layout/WindowLayoutComponentImpl.java @@ -20,21 +20,26 @@ import static android.view.Display.DEFAULT_DISPLAY; import static androidx.window.common.CommonFoldingFeature.COMMON_STATE_FLAT; import static androidx.window.common.CommonFoldingFeature.COMMON_STATE_HALF_OPENED; +import static androidx.window.util.ExtensionHelper.isZero; import static androidx.window.util.ExtensionHelper.rotateRectToDisplayRotation; import static androidx.window.util.ExtensionHelper.transformToWindowSpaceRect; -import android.annotation.Nullable; import android.app.Activity; import android.app.ActivityClient; import android.app.Application; import android.app.WindowConfiguration; +import android.content.ComponentCallbacks; import android.content.Context; +import android.content.res.Configuration; import android.graphics.Rect; import android.os.Bundle; import android.os.IBinder; import android.util.ArrayMap; +import android.window.WindowContext; import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.UiContext; import androidx.window.common.CommonFoldingFeature; import androidx.window.common.DeviceStateManagerFoldingFeatureProducer; import androidx.window.common.EmptyLifecycleCallbacksAdapter; @@ -58,11 +63,14 @@ import java.util.function.Consumer; public class WindowLayoutComponentImpl implements WindowLayoutComponent { private static final String TAG = "SampleExtension"; - private final Map<Activity, Consumer<WindowLayoutInfo>> mWindowLayoutChangeListeners = + private final Map<Context, Consumer<WindowLayoutInfo>> mWindowLayoutChangeListeners = new ArrayMap<>(); private final DataProducer<List<CommonFoldingFeature>> mFoldingFeatureProducer; + private final Map<IBinder, WindowContextConfigListener> mWindowContextConfigListeners = + new ArrayMap<>(); + public WindowLayoutComponentImpl(@NonNull Context context) { ((Application) context.getApplicationContext()) .registerActivityLifecycleCallbacks(new NotifyOnConfigurationChanged()); @@ -78,14 +86,42 @@ public class WindowLayoutComponentImpl implements WindowLayoutComponent { * @param activity hosting a {@link android.view.Window} * @param consumer interested in receiving updates to {@link WindowLayoutInfo} */ + @Override public void addWindowLayoutInfoListener(@NonNull Activity activity, @NonNull Consumer<WindowLayoutInfo> consumer) { + addWindowLayoutInfoListener((Context) activity, consumer); + } + + /** + * Similar to {@link #addWindowLayoutInfoListener(Activity, Consumer)}, but takes a UI Context + * as a parameter. + */ + // TODO(b/204073440): Add @Override to hook the API in WM extensions library. + public void addWindowLayoutInfoListener(@NonNull @UiContext Context context, + @NonNull Consumer<WindowLayoutInfo> consumer) { + if (mWindowLayoutChangeListeners.containsKey(context) + || mWindowLayoutChangeListeners.containsValue(consumer)) { + // Early return if the listener or consumer has been registered. + return; + } + if (!context.isUiContext()) { + throw new IllegalArgumentException("Context must be a UI Context, which should be" + + " an Activity or a WindowContext"); + } mFoldingFeatureProducer.getData((features) -> { // Get the WindowLayoutInfo from the activity and pass the value to the layoutConsumer. - WindowLayoutInfo newWindowLayout = getWindowLayoutInfo(activity, features); + WindowLayoutInfo newWindowLayout = getWindowLayoutInfo(context, features); consumer.accept(newWindowLayout); }); - mWindowLayoutChangeListeners.put(activity, consumer); + mWindowLayoutChangeListeners.put(context, consumer); + + if (context instanceof WindowContext) { + final IBinder windowContextToken = context.getWindowContextToken(); + final WindowContextConfigListener listener = + new WindowContextConfigListener(windowContextToken); + context.registerComponentCallbacks(listener); + mWindowContextConfigListeners.put(windowContextToken, listener); + } } /** @@ -93,18 +129,30 @@ public class WindowLayoutComponentImpl implements WindowLayoutComponent { * * @param consumer no longer interested in receiving updates to {@link WindowLayoutInfo} */ + @Override public void removeWindowLayoutInfoListener(@NonNull Consumer<WindowLayoutInfo> consumer) { + for (Context context : mWindowLayoutChangeListeners.keySet()) { + if (!mWindowLayoutChangeListeners.get(context).equals(consumer)) { + continue; + } + if (context instanceof WindowContext) { + final IBinder token = context.getWindowContextToken(); + context.unregisterComponentCallbacks(mWindowContextConfigListeners.get(token)); + mWindowContextConfigListeners.remove(token); + } + break; + } mWindowLayoutChangeListeners.values().remove(consumer); } @NonNull - Set<Activity> getActivitiesListeningForLayoutChanges() { + Set<Context> getContextsListeningForLayoutChanges() { return mWindowLayoutChangeListeners.keySet(); } private boolean isListeningForLayoutChanges(IBinder token) { - for (Activity activity: getActivitiesListeningForLayoutChanges()) { - if (token.equals(activity.getWindow().getAttributes().token)) { + for (Context context: getContextsListeningForLayoutChanges()) { + if (token.equals(Context.getToken(context))) { return true; } } @@ -138,10 +186,10 @@ public class WindowLayoutComponentImpl implements WindowLayoutComponent { } private void onDisplayFeaturesChanged(List<CommonFoldingFeature> storedFeatures) { - for (Activity activity : getActivitiesListeningForLayoutChanges()) { + for (Context context : getContextsListeningForLayoutChanges()) { // Get the WindowLayoutInfo from the activity and pass the value to the layoutConsumer. - Consumer<WindowLayoutInfo> layoutConsumer = mWindowLayoutChangeListeners.get(activity); - WindowLayoutInfo newWindowLayout = getWindowLayoutInfo(activity, storedFeatures); + Consumer<WindowLayoutInfo> layoutConsumer = mWindowLayoutChangeListeners.get(context); + WindowLayoutInfo newWindowLayout = getWindowLayoutInfo(context, storedFeatures); layoutConsumer.accept(newWindowLayout); } } @@ -149,11 +197,12 @@ public class WindowLayoutComponentImpl implements WindowLayoutComponent { /** * Translates the {@link DisplayFeature} into a {@link WindowLayoutInfo} when a * valid state is found. - * @param activity a proxy for the {@link android.view.Window} that contains the + * @param context a proxy for the {@link android.view.Window} that contains the + * {@link DisplayFeature}. */ - private WindowLayoutInfo getWindowLayoutInfo( - @NonNull Activity activity, List<CommonFoldingFeature> storedFeatures) { - List<DisplayFeature> displayFeatureList = getDisplayFeatures(activity, storedFeatures); + private WindowLayoutInfo getWindowLayoutInfo(@NonNull @UiContext Context context, + List<CommonFoldingFeature> storedFeatures) { + List<DisplayFeature> displayFeatureList = getDisplayFeatures(context, storedFeatures); return new WindowLayoutInfo(displayFeatureList); } @@ -170,18 +219,18 @@ public class WindowLayoutComponentImpl implements WindowLayoutComponent { * bounds are not valid, constructing a {@link FoldingFeature} will throw an * {@link IllegalArgumentException} since this can cause negative UI effects down stream. * - * @param activity a proxy for the {@link android.view.Window} that contains the + * @param context a proxy for the {@link android.view.Window} that contains the * {@link DisplayFeature}. * are within the {@link android.view.Window} of the {@link Activity} */ private List<DisplayFeature> getDisplayFeatures( - @NonNull Activity activity, List<CommonFoldingFeature> storedFeatures) { + @NonNull @UiContext Context context, List<CommonFoldingFeature> storedFeatures) { List<DisplayFeature> features = new ArrayList<>(); - if (!shouldReportDisplayFeatures(activity)) { + if (!shouldReportDisplayFeatures(context)) { return features; } - int displayId = activity.getDisplay().getDisplayId(); + int displayId = context.getDisplay().getDisplayId(); for (CommonFoldingFeature baseFeature : storedFeatures) { Integer state = convertToExtensionState(baseFeature.getState()); if (state == null) { @@ -189,9 +238,9 @@ public class WindowLayoutComponentImpl implements WindowLayoutComponent { } Rect featureRect = baseFeature.getRect(); rotateRectToDisplayRotation(displayId, featureRect); - transformToWindowSpaceRect(activity, featureRect); + transformToWindowSpaceRect(context, featureRect); - if (!isRectZero(featureRect)) { + if (!isZero(featureRect)) { // TODO(b/228641877): Remove guarding when fixed. features.add(new FoldingFeature(featureRect, baseFeature.getType(), state)); } @@ -203,15 +252,21 @@ public class WindowLayoutComponentImpl implements WindowLayoutComponent { * Checks whether display features should be reported for the activity. * TODO(b/238948678): Support reporting display features in all windowing modes. */ - private boolean shouldReportDisplayFeatures(@NonNull Activity activity) { - int displayId = activity.getDisplay().getDisplayId(); + private boolean shouldReportDisplayFeatures(@NonNull @UiContext Context context) { + int displayId = context.getDisplay().getDisplayId(); if (displayId != DEFAULT_DISPLAY) { // Display features are not supported on secondary displays. return false; } - final int taskWindowingMode = ActivityClient.getInstance().getTaskWindowingMode( - activity.getActivityToken()); - if (taskWindowingMode == -1) { + final int windowingMode; + if (context instanceof Activity) { + windowingMode = ActivityClient.getInstance().getTaskWindowingMode( + context.getActivityToken()); + } else { + windowingMode = context.getResources().getConfiguration().windowConfiguration + .getWindowingMode(); + } + if (windowingMode == -1) { // If we cannot determine the task windowing mode for any reason, it is likely that we // won't be able to determine its position correctly as well. DisplayFeatures' bounds // in this case can't be computed correctly, so we should skip. @@ -219,36 +274,43 @@ public class WindowLayoutComponentImpl implements WindowLayoutComponent { } // It is recommended not to report any display features in multi-window mode, since it // won't be possible to synchronize the display feature positions with window movement. - return !WindowConfiguration.inMultiWindowMode(taskWindowingMode); + return !WindowConfiguration.inMultiWindowMode(windowingMode); } - /** - * Returns {@link true} if a {@link Rect} has zero width and zero height, - * {@code false} otherwise. - */ - private boolean isRectZero(Rect rect) { - return rect.width() == 0 && rect.height() == 0; + private void onDisplayFeaturesChangedIfListening(@NonNull IBinder token) { + if (isListeningForLayoutChanges(token)) { + mFoldingFeatureProducer.getData( + WindowLayoutComponentImpl.this::onDisplayFeaturesChanged); + } } private final class NotifyOnConfigurationChanged extends EmptyLifecycleCallbacksAdapter { @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { super.onActivityCreated(activity, savedInstanceState); - onDisplayFeaturesChangedIfListening(activity); + onDisplayFeaturesChangedIfListening(activity.getActivityToken()); } @Override public void onActivityConfigurationChanged(Activity activity) { super.onActivityConfigurationChanged(activity); - onDisplayFeaturesChangedIfListening(activity); + onDisplayFeaturesChangedIfListening(activity.getActivityToken()); + } + } + + private final class WindowContextConfigListener implements ComponentCallbacks { + final IBinder mToken; + + WindowContextConfigListener(IBinder token) { + mToken = token; } - private void onDisplayFeaturesChangedIfListening(Activity activity) { - IBinder token = activity.getWindow().getAttributes().token; - if (token == null || isListeningForLayoutChanges(token)) { - mFoldingFeatureProducer.getData( - WindowLayoutComponentImpl.this::onDisplayFeaturesChanged); - } + @Override + public void onConfigurationChanged(@NonNull Configuration newConfig) { + onDisplayFeaturesChangedIfListening(mToken); } + + @Override + public void onLowMemory() {} } } diff --git a/libs/WindowManager/Jetpack/src/androidx/window/util/BaseDataProducer.java b/libs/WindowManager/Jetpack/src/androidx/window/util/BaseDataProducer.java index 0da44ac36a6e..cbaa27712015 100644 --- a/libs/WindowManager/Jetpack/src/androidx/window/util/BaseDataProducer.java +++ b/libs/WindowManager/Jetpack/src/androidx/window/util/BaseDataProducer.java @@ -16,6 +16,7 @@ package androidx.window.util; +import androidx.annotation.GuardedBy; import androidx.annotation.NonNull; import java.util.LinkedHashSet; @@ -25,25 +26,45 @@ import java.util.function.Consumer; /** * Base class that provides the implementation for the callback mechanism of the - * {@link DataProducer} API. + * {@link DataProducer} API. This class is thread safe for adding, removing, and notifying + * consumers. * * @param <T> The type of data this producer returns through {@link DataProducer#getData}. */ public abstract class BaseDataProducer<T> implements DataProducer<T> { + + private final Object mLock = new Object(); + @GuardedBy("mLock") private final Set<Consumer<T>> mCallbacks = new LinkedHashSet<>(); + /** + * Adds a callback to the set of callbacks listening for data. Data is delivered through + * {@link BaseDataProducer#notifyDataChanged(Object)}. This method is thread safe. Callers + * should ensure that callbacks are thread safe. + * @param callback that will receive data from the producer. + */ @Override public final void addDataChangedCallback(@NonNull Consumer<T> callback) { - mCallbacks.add(callback); - Optional<T> currentData = getCurrentData(); - currentData.ifPresent(callback); - onListenersChanged(mCallbacks); + synchronized (mLock) { + mCallbacks.add(callback); + Optional<T> currentData = getCurrentData(); + currentData.ifPresent(callback); + onListenersChanged(mCallbacks); + } } + /** + * Removes a callback to the set of callbacks listening for data. This method is thread safe + * for adding. + * @param callback that was registered in + * {@link BaseDataProducer#addDataChangedCallback(Consumer)}. + */ @Override public final void removeDataChangedCallback(@NonNull Consumer<T> callback) { - mCallbacks.remove(callback); - onListenersChanged(mCallbacks); + synchronized (mLock) { + mCallbacks.remove(callback); + onListenersChanged(mCallbacks); + } } protected void onListenersChanged(Set<Consumer<T>> callbacks) {} @@ -56,11 +77,14 @@ public abstract class BaseDataProducer<T> implements DataProducer<T> { /** * Called to notify all registered consumers that the data provided - * by {@link DataProducer#getData} has changed. + * by {@link DataProducer#getData} has changed. Calls to this are thread save but callbacks need + * to ensure thread safety. */ protected void notifyDataChanged(T value) { - for (Consumer<T> callback : mCallbacks) { - callback.accept(value); + synchronized (mLock) { + for (Consumer<T> callback : mCallbacks) { + callback.accept(value); + } } } }
\ No newline at end of file diff --git a/libs/WindowManager/Jetpack/src/androidx/window/util/ExtensionHelper.java b/libs/WindowManager/Jetpack/src/androidx/window/util/ExtensionHelper.java index 2a593f15a9de..31bf96313a95 100644 --- a/libs/WindowManager/Jetpack/src/androidx/window/util/ExtensionHelper.java +++ b/libs/WindowManager/Jetpack/src/androidx/window/util/ExtensionHelper.java @@ -21,14 +21,15 @@ import static android.view.Surface.ROTATION_180; import static android.view.Surface.ROTATION_270; import static android.view.Surface.ROTATION_90; -import android.app.Activity; +import android.content.Context; import android.graphics.Rect; import android.hardware.display.DisplayManagerGlobal; import android.view.DisplayInfo; import android.view.Surface; +import android.view.WindowManager; import androidx.annotation.NonNull; -import androidx.annotation.Nullable; +import androidx.annotation.UiContext; /** * Util class for both Sidecar and Extensions. @@ -86,12 +87,9 @@ public final class ExtensionHelper { } /** Transforms rectangle from absolute coordinate space to the window coordinate space. */ - public static void transformToWindowSpaceRect(Activity activity, Rect inOutRect) { - Rect windowRect = getWindowBounds(activity); - if (windowRect == null) { - inOutRect.setEmpty(); - return; - } + public static void transformToWindowSpaceRect(@NonNull @UiContext Context context, + Rect inOutRect) { + Rect windowRect = getWindowBounds(context); if (!Rect.intersects(inOutRect, windowRect)) { inOutRect.setEmpty(); return; @@ -103,9 +101,9 @@ public final class ExtensionHelper { /** * Gets the current window bounds in absolute coordinates. */ - @Nullable - private static Rect getWindowBounds(@NonNull Activity activity) { - return activity.getWindowManager().getCurrentWindowMetrics().getBounds(); + @NonNull + private static Rect getWindowBounds(@NonNull @UiContext Context context) { + return context.getSystemService(WindowManager.class).getCurrentWindowMetrics().getBounds(); } /** diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationAdapter.java b/libs/WindowManager/Shell/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationAdapter.java new file mode 100644 index 000000000000..cc4db933ec9f --- /dev/null +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationAdapter.java @@ -0,0 +1,234 @@ +/* + * 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.wm.shell.activityembedding; + +import static android.graphics.Matrix.MSCALE_X; +import static android.graphics.Matrix.MTRANS_X; +import static android.graphics.Matrix.MTRANS_Y; + +import android.annotation.CallSuper; +import android.graphics.Point; +import android.graphics.Rect; +import android.view.Choreographer; +import android.view.SurfaceControl; +import android.view.animation.Animation; +import android.view.animation.Transformation; +import android.window.TransitionInfo; + +import androidx.annotation.NonNull; + +/** + * Wrapper to handle the ActivityEmbedding animation update in one + * {@link SurfaceControl.Transaction}. + */ +class ActivityEmbeddingAnimationAdapter { + + /** + * If {@link #mOverrideLayer} is set to this value, we don't want to override the surface layer. + */ + private static final int LAYER_NO_OVERRIDE = -1; + + final Animation mAnimation; + final TransitionInfo.Change mChange; + final SurfaceControl mLeash; + + final Transformation mTransformation = new Transformation(); + final float[] mMatrix = new float[9]; + final float[] mVecs = new float[4]; + final Rect mRect = new Rect(); + private boolean mIsFirstFrame = true; + private int mOverrideLayer = LAYER_NO_OVERRIDE; + + ActivityEmbeddingAnimationAdapter(@NonNull Animation animation, + @NonNull TransitionInfo.Change change) { + this(animation, change, change.getLeash()); + } + + /** + * @param leash the surface to animate, which is not necessary the same as + * {@link TransitionInfo.Change#getLeash()}, it can be a screenshot for example. + */ + ActivityEmbeddingAnimationAdapter(@NonNull Animation animation, + @NonNull TransitionInfo.Change change, @NonNull SurfaceControl leash) { + mAnimation = animation; + mChange = change; + mLeash = leash; + } + + /** + * Surface layer to be set at the first frame of the animation. We will not set the layer if it + * is set to {@link #LAYER_NO_OVERRIDE}. + */ + final void overrideLayer(int layer) { + mOverrideLayer = layer; + } + + /** Called on frame update. */ + final void onAnimationUpdate(@NonNull SurfaceControl.Transaction t, long currentPlayTime) { + if (mIsFirstFrame) { + t.show(mLeash); + if (mOverrideLayer != LAYER_NO_OVERRIDE) { + t.setLayer(mLeash, mOverrideLayer); + } + mIsFirstFrame = false; + } + + // Extract the transformation to the current time. + mAnimation.getTransformation(Math.min(currentPlayTime, mAnimation.getDuration()), + mTransformation); + t.setFrameTimelineVsync(Choreographer.getInstance().getVsyncId()); + onAnimationUpdateInner(t); + } + + /** To be overridden by subclasses to adjust the animation surface change. */ + void onAnimationUpdateInner(@NonNull SurfaceControl.Transaction t) { + final Point offset = mChange.getEndRelOffset(); + mTransformation.getMatrix().postTranslate(offset.x, offset.y); + t.setMatrix(mLeash, mTransformation.getMatrix(), mMatrix); + t.setAlpha(mLeash, mTransformation.getAlpha()); + // Get current animation position. + final int positionX = Math.round(mMatrix[MTRANS_X]); + final int positionY = Math.round(mMatrix[MTRANS_Y]); + // The exiting surface starts at position: Change#getEndRelOffset() and moves with + // positionX varying. Offset our crop region by the amount we have slided so crop + // regions stays exactly on the original container in split. + final int cropOffsetX = offset.x - positionX; + final int cropOffsetY = offset.y - positionY; + final Rect cropRect = new Rect(); + cropRect.set(mChange.getEndAbsBounds()); + // Because window crop uses absolute position. + cropRect.offsetTo(0, 0); + cropRect.offset(cropOffsetX, cropOffsetY); + t.setCrop(mLeash, cropRect); + } + + /** Called after animation finished. */ + @CallSuper + void onAnimationEnd(@NonNull SurfaceControl.Transaction t) { + onAnimationUpdate(t, mAnimation.getDuration()); + } + + final long getDurationHint() { + return mAnimation.computeDurationHint(); + } + + /** + * Should be used when the {@link TransitionInfo.Change} is in split with others, and wants to + * animate together as one. This adapter will offset the animation leash to make the animate of + * two windows look like a single window. + */ + static class SplitAdapter extends ActivityEmbeddingAnimationAdapter { + private final boolean mIsLeftHalf; + private final int mWholeAnimationWidth; + + /** + * @param isLeftHalf whether this is the left half of the animation. + * @param wholeAnimationWidth the whole animation windows width. + */ + SplitAdapter(@NonNull Animation animation, @NonNull TransitionInfo.Change change, + boolean isLeftHalf, int wholeAnimationWidth) { + super(animation, change); + mIsLeftHalf = isLeftHalf; + mWholeAnimationWidth = wholeAnimationWidth; + if (wholeAnimationWidth == 0) { + throw new IllegalArgumentException("SplitAdapter must provide wholeAnimationWidth"); + } + } + + @Override + void onAnimationUpdateInner(@NonNull SurfaceControl.Transaction t) { + final Point offset = mChange.getEndRelOffset(); + float posX = offset.x; + final float posY = offset.y; + // This window is half of the whole animation window. Offset left/right to make it + // look as one with the other half. + mTransformation.getMatrix().getValues(mMatrix); + final int changeWidth = mChange.getEndAbsBounds().width(); + final float scaleX = mMatrix[MSCALE_X]; + final float totalOffset = mWholeAnimationWidth * (1 - scaleX) / 2; + final float curOffset = changeWidth * (1 - scaleX) / 2; + final float offsetDiff = totalOffset - curOffset; + if (mIsLeftHalf) { + posX += offsetDiff; + } else { + posX -= offsetDiff; + } + mTransformation.getMatrix().postTranslate(posX, posY); + t.setMatrix(mLeash, mTransformation.getMatrix(), mMatrix); + t.setAlpha(mLeash, mTransformation.getAlpha()); + } + } + + /** + * Should be used for the animation of the snapshot of a {@link TransitionInfo.Change} that has + * size change. + */ + static class SnapshotAdapter extends ActivityEmbeddingAnimationAdapter { + + SnapshotAdapter(@NonNull Animation animation, @NonNull TransitionInfo.Change change, + @NonNull SurfaceControl snapshotLeash) { + super(animation, change, snapshotLeash); + } + + @Override + void onAnimationUpdateInner(@NonNull SurfaceControl.Transaction t) { + // Snapshot should always be placed at the top left of the animation leash. + mTransformation.getMatrix().postTranslate(0, 0); + t.setMatrix(mLeash, mTransformation.getMatrix(), mMatrix); + t.setAlpha(mLeash, mTransformation.getAlpha()); + } + + @Override + void onAnimationEnd(@NonNull SurfaceControl.Transaction t) { + super.onAnimationEnd(t); + // Remove the screenshot leash after animation is finished. + t.remove(mLeash); + } + } + + /** + * Should be used for the animation of the {@link TransitionInfo.Change} that has size change. + */ + static class BoundsChangeAdapter extends ActivityEmbeddingAnimationAdapter { + + BoundsChangeAdapter(@NonNull Animation animation, @NonNull TransitionInfo.Change change) { + super(animation, change); + } + + @Override + void onAnimationUpdateInner(@NonNull SurfaceControl.Transaction t) { + final Point offset = mChange.getEndRelOffset(); + mTransformation.getMatrix().postTranslate(offset.x, offset.y); + t.setMatrix(mLeash, mTransformation.getMatrix(), mMatrix); + t.setAlpha(mLeash, mTransformation.getAlpha()); + + // The following applies an inverse scale to the clip-rect so that it crops "after" the + // scale instead of before. + mVecs[1] = mVecs[2] = 0; + mVecs[0] = mVecs[3] = 1; + mTransformation.getMatrix().mapVectors(mVecs); + mVecs[0] = 1.f / mVecs[0]; + mVecs[3] = 1.f / mVecs[3]; + final Rect clipRect = mTransformation.getClipRect(); + mRect.left = (int) (clipRect.left * mVecs[0] + 0.5f); + mRect.right = (int) (clipRect.right * mVecs[0] + 0.5f); + mRect.top = (int) (clipRect.top * mVecs[3] + 0.5f); + mRect.bottom = (int) (clipRect.bottom * mVecs[3] + 0.5f); + t.setCrop(mLeash, mRect); + } + } +} diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationRunner.java b/libs/WindowManager/Shell/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationRunner.java new file mode 100644 index 000000000000..7e0795d11153 --- /dev/null +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationRunner.java @@ -0,0 +1,290 @@ +/* + * 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.wm.shell.activityembedding; + +import static android.view.WindowManager.TRANSIT_CHANGE; +import static android.view.WindowManagerPolicyConstants.TYPE_LAYER_OFFSET; + +import android.animation.Animator; +import android.animation.ValueAnimator; +import android.content.Context; +import android.graphics.Point; +import android.graphics.Rect; +import android.os.IBinder; +import android.util.Log; +import android.view.SurfaceControl; +import android.view.animation.Animation; +import android.window.TransitionInfo; +import android.window.WindowContainerToken; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +import com.android.internal.annotations.VisibleForTesting; +import com.android.wm.shell.common.ScreenshotUtils; +import com.android.wm.shell.transition.Transitions; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BiFunction; + +/** To run the ActivityEmbedding animations. */ +class ActivityEmbeddingAnimationRunner { + + private static final String TAG = "ActivityEmbeddingAnimR"; + + private final ActivityEmbeddingController mController; + @VisibleForTesting + final ActivityEmbeddingAnimationSpec mAnimationSpec; + + ActivityEmbeddingAnimationRunner(@NonNull Context context, + @NonNull ActivityEmbeddingController controller) { + mController = controller; + mAnimationSpec = new ActivityEmbeddingAnimationSpec(context); + } + + /** Creates and starts animation for ActivityEmbedding transition. */ + void startAnimation(@NonNull IBinder transition, @NonNull TransitionInfo info, + @NonNull SurfaceControl.Transaction startTransaction, + @NonNull SurfaceControl.Transaction finishTransaction) { + final Animator animator = createAnimator(info, startTransaction, finishTransaction, + () -> mController.onAnimationFinished(transition)); + startTransaction.apply(); + animator.start(); + } + + /** + * Sets transition animation scale settings value. + * @param scale The setting value of transition animation scale. + */ + void setAnimScaleSetting(float scale) { + mAnimationSpec.setAnimScaleSetting(scale); + } + + /** Creates the animator for the given {@link TransitionInfo}. */ + @VisibleForTesting + @NonNull + Animator createAnimator(@NonNull TransitionInfo info, + @NonNull SurfaceControl.Transaction startTransaction, + @NonNull SurfaceControl.Transaction finishTransaction, + @NonNull Runnable animationFinishCallback) { + final List<ActivityEmbeddingAnimationAdapter> adapters = + createAnimationAdapters(info, startTransaction); + long duration = 0; + for (ActivityEmbeddingAnimationAdapter adapter : adapters) { + duration = Math.max(duration, adapter.getDurationHint()); + } + final ValueAnimator animator = ValueAnimator.ofFloat(0, 1); + animator.setDuration(duration); + animator.addUpdateListener((anim) -> { + // Update all adapters in the same transaction. + final SurfaceControl.Transaction t = new SurfaceControl.Transaction(); + for (ActivityEmbeddingAnimationAdapter adapter : adapters) { + adapter.onAnimationUpdate(t, animator.getCurrentPlayTime()); + } + t.apply(); + }); + animator.addListener(new Animator.AnimatorListener() { + @Override + public void onAnimationStart(Animator animation) {} + + @Override + public void onAnimationEnd(Animator animation) { + final SurfaceControl.Transaction t = new SurfaceControl.Transaction(); + for (ActivityEmbeddingAnimationAdapter adapter : adapters) { + adapter.onAnimationEnd(t); + } + t.apply(); + animationFinishCallback.run(); + } + + @Override + public void onAnimationCancel(Animator animation) {} + + @Override + public void onAnimationRepeat(Animator animation) {} + }); + return animator; + } + + /** + * Creates list of {@link ActivityEmbeddingAnimationAdapter} to handle animations on all window + * changes. + */ + @NonNull + private List<ActivityEmbeddingAnimationAdapter> createAnimationAdapters( + @NonNull TransitionInfo info, @NonNull SurfaceControl.Transaction startTransaction) { + for (TransitionInfo.Change change : info.getChanges()) { + if (change.getMode() == TRANSIT_CHANGE + && !change.getStartAbsBounds().equals(change.getEndAbsBounds())) { + return createChangeAnimationAdapters(info, startTransaction); + } + } + if (Transitions.isClosingType(info.getType())) { + return createCloseAnimationAdapters(info); + } + return createOpenAnimationAdapters(info); + } + + @NonNull + private List<ActivityEmbeddingAnimationAdapter> createOpenAnimationAdapters( + @NonNull TransitionInfo info) { + return createOpenCloseAnimationAdapters(info, true /* isOpening */, + mAnimationSpec::loadOpenAnimation); + } + + @NonNull + private List<ActivityEmbeddingAnimationAdapter> createCloseAnimationAdapters( + @NonNull TransitionInfo info) { + return createOpenCloseAnimationAdapters(info, false /* isOpening */, + mAnimationSpec::loadCloseAnimation); + } + + /** + * Creates {@link ActivityEmbeddingAnimationAdapter} for OPEN and CLOSE types of transition. + * @param isOpening {@code true} for OPEN type, {@code false} for CLOSE type. + */ + @NonNull + private List<ActivityEmbeddingAnimationAdapter> createOpenCloseAnimationAdapters( + @NonNull TransitionInfo info, boolean isOpening, + @NonNull BiFunction<TransitionInfo.Change, Rect, Animation> animationProvider) { + // We need to know if the change window is only a partial of the whole animation screen. + // If so, we will need to adjust it to make the whole animation screen looks like one. + final List<TransitionInfo.Change> openingChanges = new ArrayList<>(); + final List<TransitionInfo.Change> closingChanges = new ArrayList<>(); + final Rect openingWholeScreenBounds = new Rect(); + final Rect closingWholeScreenBounds = new Rect(); + for (TransitionInfo.Change change : info.getChanges()) { + final Rect bounds = new Rect(change.getEndAbsBounds()); + final Point offset = change.getEndRelOffset(); + bounds.offsetTo(offset.x, offset.y); + if (Transitions.isOpeningType(change.getMode())) { + openingChanges.add(change); + openingWholeScreenBounds.union(bounds); + } else { + closingChanges.add(change); + closingWholeScreenBounds.union(bounds); + } + } + + // For OPEN transition, open windows should be above close windows. + // For CLOSE transition, open windows should be below close windows. + int offsetLayer = TYPE_LAYER_OFFSET; + final List<ActivityEmbeddingAnimationAdapter> adapters = new ArrayList<>(); + for (TransitionInfo.Change change : openingChanges) { + final ActivityEmbeddingAnimationAdapter adapter = createOpenCloseAnimationAdapter( + change, animationProvider, openingWholeScreenBounds); + if (isOpening) { + adapter.overrideLayer(offsetLayer++); + } + adapters.add(adapter); + } + for (TransitionInfo.Change change : closingChanges) { + final ActivityEmbeddingAnimationAdapter adapter = createOpenCloseAnimationAdapter( + change, animationProvider, closingWholeScreenBounds); + if (!isOpening) { + adapter.overrideLayer(offsetLayer++); + } + adapters.add(adapter); + } + return adapters; + } + + @NonNull + private ActivityEmbeddingAnimationAdapter createOpenCloseAnimationAdapter( + @NonNull TransitionInfo.Change change, + @NonNull BiFunction<TransitionInfo.Change, Rect, Animation> animationProvider, + @NonNull Rect wholeAnimationBounds) { + final Animation animation = animationProvider.apply(change, wholeAnimationBounds); + final Rect bounds = new Rect(change.getEndAbsBounds()); + final Point offset = change.getEndRelOffset(); + bounds.offsetTo(offset.x, offset.y); + if (bounds.left == wholeAnimationBounds.left + && bounds.right != wholeAnimationBounds.right) { + // This is the left split of the whole animation window. + return new ActivityEmbeddingAnimationAdapter.SplitAdapter(animation, change, + true /* isLeftHalf */, wholeAnimationBounds.width()); + } else if (bounds.left != wholeAnimationBounds.left + && bounds.right == wholeAnimationBounds.right) { + // This is the right split of the whole animation window. + return new ActivityEmbeddingAnimationAdapter.SplitAdapter(animation, change, + false /* isLeftHalf */, wholeAnimationBounds.width()); + } + // Open/close window that fills the whole animation. + return new ActivityEmbeddingAnimationAdapter(animation, change); + } + + @NonNull + private List<ActivityEmbeddingAnimationAdapter> createChangeAnimationAdapters( + @NonNull TransitionInfo info, @NonNull SurfaceControl.Transaction startTransaction) { + final List<ActivityEmbeddingAnimationAdapter> adapters = new ArrayList<>(); + for (TransitionInfo.Change change : info.getChanges()) { + if (change.getMode() == TRANSIT_CHANGE + && !change.getStartAbsBounds().equals(change.getEndAbsBounds())) { + // This is the window with bounds change. + final WindowContainerToken parentToken = change.getParent(); + final Rect parentBounds; + if (parentToken != null) { + TransitionInfo.Change parentChange = info.getChange(parentToken); + parentBounds = parentChange != null + ? parentChange.getEndAbsBounds() + : change.getEndAbsBounds(); + } else { + parentBounds = change.getEndAbsBounds(); + } + final Animation[] animations = + mAnimationSpec.createChangeBoundsChangeAnimations(change, parentBounds); + // Adapter for the starting screenshot leash. + final SurfaceControl screenshotLeash = createScreenshot(change, startTransaction); + if (screenshotLeash != null) { + // The screenshot leash will be removed in SnapshotAdapter#onAnimationEnd + adapters.add(new ActivityEmbeddingAnimationAdapter.SnapshotAdapter( + animations[0], change, screenshotLeash)); + } else { + Log.e(TAG, "Failed to take screenshot for change=" + change); + } + // Adapter for the ending bounds changed leash. + adapters.add(new ActivityEmbeddingAnimationAdapter.BoundsChangeAdapter( + animations[1], change)); + continue; + } + + // These are the other windows that don't have bounds change in the same transition. + final Animation animation; + if (!TransitionInfo.isIndependent(change, info)) { + // No-op if it will be covered by the changing parent window. + animation = ActivityEmbeddingAnimationSpec.createNoopAnimation(change); + } else if (Transitions.isClosingType(change.getMode())) { + animation = mAnimationSpec.createChangeBoundsCloseAnimation(change); + } else { + animation = mAnimationSpec.createChangeBoundsOpenAnimation(change); + } + adapters.add(new ActivityEmbeddingAnimationAdapter(animation, change)); + } + return adapters; + } + + /** Takes a screenshot of the given {@link TransitionInfo.Change} surface. */ + @Nullable + private SurfaceControl createScreenshot(@NonNull TransitionInfo.Change change, + @NonNull SurfaceControl.Transaction startTransaction) { + final Rect cropBounds = new Rect(change.getStartAbsBounds()); + cropBounds.offsetTo(0, 0); + return ScreenshotUtils.takeScreenshot(startTransaction, change.getLeash(), cropBounds, + Integer.MAX_VALUE); + } +} diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationSpec.java b/libs/WindowManager/Shell/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationSpec.java new file mode 100644 index 000000000000..6f06f28caff2 --- /dev/null +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationSpec.java @@ -0,0 +1,212 @@ +/* + * 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.wm.shell.activityembedding; + + +import android.content.Context; +import android.graphics.Point; +import android.graphics.Rect; +import android.view.animation.AlphaAnimation; +import android.view.animation.Animation; +import android.view.animation.AnimationSet; +import android.view.animation.AnimationUtils; +import android.view.animation.ClipRectAnimation; +import android.view.animation.Interpolator; +import android.view.animation.LinearInterpolator; +import android.view.animation.ScaleAnimation; +import android.view.animation.TranslateAnimation; +import android.window.TransitionInfo; + +import androidx.annotation.NonNull; + +import com.android.internal.R; +import com.android.internal.policy.TransitionAnimation; +import com.android.wm.shell.transition.Transitions; + +/** Animation spec for ActivityEmbedding transition. */ +// TODO(b/206557124): provide an easier way to customize animation +class ActivityEmbeddingAnimationSpec { + + private static final String TAG = "ActivityEmbeddingAnimSpec"; + private static final int CHANGE_ANIMATION_DURATION = 517; + private static final int CHANGE_ANIMATION_FADE_DURATION = 80; + private static final int CHANGE_ANIMATION_FADE_OFFSET = 30; + + private final Context mContext; + private final TransitionAnimation mTransitionAnimation; + private final Interpolator mFastOutExtraSlowInInterpolator; + private final LinearInterpolator mLinearInterpolator; + private float mTransitionAnimationScaleSetting; + + ActivityEmbeddingAnimationSpec(@NonNull Context context) { + mContext = context; + mTransitionAnimation = new TransitionAnimation(mContext, false /* debug */, TAG); + mFastOutExtraSlowInInterpolator = AnimationUtils.loadInterpolator( + mContext, android.R.interpolator.fast_out_extra_slow_in); + mLinearInterpolator = new LinearInterpolator(); + } + + /** + * Sets transition animation scale settings value. + * @param scale The setting value of transition animation scale. + */ + void setAnimScaleSetting(float scale) { + mTransitionAnimationScaleSetting = scale; + } + + /** For window that doesn't need to be animated. */ + @NonNull + static Animation createNoopAnimation(@NonNull TransitionInfo.Change change) { + // Noop but just keep the window showing/hiding. + final float alpha = Transitions.isClosingType(change.getMode()) ? 0f : 1f; + return new AlphaAnimation(alpha, alpha); + } + + /** Animation for window that is opening in a change transition. */ + @NonNull + Animation createChangeBoundsOpenAnimation(@NonNull TransitionInfo.Change change) { + final Rect bounds = change.getEndAbsBounds(); + final Point offset = change.getEndRelOffset(); + // The window will be animated in from left or right depends on its position. + final int startLeft = offset.x == 0 ? -bounds.width() : bounds.width(); + + // The position should be 0-based as we will post translate in + // ActivityEmbeddingAnimationAdapter#onAnimationUpdate + final Animation animation = new TranslateAnimation(startLeft, 0, 0, 0); + animation.setInterpolator(mFastOutExtraSlowInInterpolator); + animation.setDuration(CHANGE_ANIMATION_DURATION); + animation.initialize(bounds.width(), bounds.height(), bounds.width(), bounds.height()); + animation.scaleCurrentDuration(mTransitionAnimationScaleSetting); + return animation; + } + + /** Animation for window that is closing in a change transition. */ + @NonNull + Animation createChangeBoundsCloseAnimation(@NonNull TransitionInfo.Change change) { + final Rect bounds = change.getEndAbsBounds(); + final Point offset = change.getEndRelOffset(); + // The window will be animated out to left or right depends on its position. + final int endLeft = offset.x == 0 ? -bounds.width() : bounds.width(); + + // The position should be 0-based as we will post translate in + // ActivityEmbeddingAnimationAdapter#onAnimationUpdate + final Animation animation = new TranslateAnimation(0, endLeft, 0, 0); + animation.setInterpolator(mFastOutExtraSlowInInterpolator); + animation.setDuration(CHANGE_ANIMATION_DURATION); + animation.initialize(bounds.width(), bounds.height(), bounds.width(), bounds.height()); + animation.scaleCurrentDuration(mTransitionAnimationScaleSetting); + return animation; + } + + /** + * Animation for window that is changing (bounds change) in a change transition. + * @return the return array always has two elements. The first one is for the start leash, and + * the second one is for the end leash. + */ + @NonNull + Animation[] createChangeBoundsChangeAnimations(@NonNull TransitionInfo.Change change, + @NonNull Rect parentBounds) { + // Both start bounds and end bounds are in screen coordinates. We will post translate + // to the local coordinates in ActivityEmbeddingAnimationAdapter#onAnimationUpdate + final Rect startBounds = change.getStartAbsBounds(); + final Rect endBounds = change.getEndAbsBounds(); + float scaleX = ((float) startBounds.width()) / endBounds.width(); + float scaleY = ((float) startBounds.height()) / endBounds.height(); + // Start leash is a child of the end leash. Reverse the scale so that the start leash won't + // be scaled up with its parent. + float startScaleX = 1.f / scaleX; + float startScaleY = 1.f / scaleY; + + // The start leash will be fade out. + final AnimationSet startSet = new AnimationSet(false /* shareInterpolator */); + final Animation startAlpha = new AlphaAnimation(1f, 0f); + startAlpha.setInterpolator(mLinearInterpolator); + startAlpha.setDuration(CHANGE_ANIMATION_FADE_DURATION); + startAlpha.setStartOffset(CHANGE_ANIMATION_FADE_OFFSET); + startSet.addAnimation(startAlpha); + final Animation startScale = new ScaleAnimation(startScaleX, startScaleX, startScaleY, + startScaleY); + startScale.setInterpolator(mFastOutExtraSlowInInterpolator); + startScale.setDuration(CHANGE_ANIMATION_DURATION); + startSet.addAnimation(startScale); + startSet.initialize(startBounds.width(), startBounds.height(), endBounds.width(), + endBounds.height()); + startSet.scaleCurrentDuration(mTransitionAnimationScaleSetting); + + // The end leash will be moved into the end position while scaling. + final AnimationSet endSet = new AnimationSet(true /* shareInterpolator */); + endSet.setInterpolator(mFastOutExtraSlowInInterpolator); + final Animation endScale = new ScaleAnimation(scaleX, 1, scaleY, 1); + endScale.setDuration(CHANGE_ANIMATION_DURATION); + endSet.addAnimation(endScale); + // The position should be 0-based as we will post translate in + // ActivityEmbeddingAnimationAdapter#onAnimationUpdate + final Animation endTranslate = new TranslateAnimation(startBounds.left - endBounds.left, 0, + 0, 0); + endTranslate.setDuration(CHANGE_ANIMATION_DURATION); + endSet.addAnimation(endTranslate); + // The end leash is resizing, we should update the window crop based on the clip rect. + final Rect startClip = new Rect(startBounds); + final Rect endClip = new Rect(endBounds); + startClip.offsetTo(0, 0); + endClip.offsetTo(0, 0); + final Animation clipAnim = new ClipRectAnimation(startClip, endClip); + clipAnim.setDuration(CHANGE_ANIMATION_DURATION); + endSet.addAnimation(clipAnim); + endSet.initialize(startBounds.width(), startBounds.height(), parentBounds.width(), + parentBounds.height()); + endSet.scaleCurrentDuration(mTransitionAnimationScaleSetting); + + return new Animation[]{startSet, endSet}; + } + + @NonNull + Animation loadOpenAnimation(@NonNull TransitionInfo.Change change, + @NonNull Rect wholeAnimationBounds) { + final boolean isEnter = Transitions.isOpeningType(change.getMode()); + final Animation animation; + // TODO(b/207070762): + // 1. Implement clearTop version: R.anim.task_fragment_clear_top_close_enter/exit + // 2. Implement edgeExtension version + animation = mTransitionAnimation.loadDefaultAnimationRes(isEnter + ? R.anim.task_fragment_open_enter + : R.anim.task_fragment_open_exit); + final Rect bounds = change.getEndAbsBounds(); + animation.initialize(bounds.width(), bounds.height(), + wholeAnimationBounds.width(), wholeAnimationBounds.height()); + animation.scaleCurrentDuration(mTransitionAnimationScaleSetting); + return animation; + } + + @NonNull + Animation loadCloseAnimation(@NonNull TransitionInfo.Change change, + @NonNull Rect wholeAnimationBounds) { + final boolean isEnter = Transitions.isOpeningType(change.getMode()); + final Animation animation; + // TODO(b/207070762): + // 1. Implement clearTop version: R.anim.task_fragment_clear_top_close_enter/exit + // 2. Implement edgeExtension version + animation = mTransitionAnimation.loadDefaultAnimationRes(isEnter + ? R.anim.task_fragment_close_enter + : R.anim.task_fragment_close_exit); + final Rect bounds = change.getEndAbsBounds(); + animation.initialize(bounds.width(), bounds.height(), + wholeAnimationBounds.width(), wholeAnimationBounds.height()); + animation.scaleCurrentDuration(mTransitionAnimationScaleSetting); + return animation; + } +} diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/activityembedding/ActivityEmbeddingController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/activityembedding/ActivityEmbeddingController.java index b305897b77ae..e0004fcaa060 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/activityembedding/ActivityEmbeddingController.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/activityembedding/ActivityEmbeddingController.java @@ -18,8 +18,11 @@ package com.android.wm.shell.activityembedding; import static android.window.TransitionInfo.FLAG_IS_EMBEDDED; +import static java.util.Objects.requireNonNull; + import android.content.Context; import android.os.IBinder; +import android.util.ArrayMap; import android.view.SurfaceControl; import android.window.TransitionInfo; import android.window.TransitionRequestInfo; @@ -28,6 +31,7 @@ import android.window.WindowContainerTransaction; import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import com.android.internal.annotations.VisibleForTesting; import com.android.wm.shell.sysui.ShellInit; import com.android.wm.shell.transition.Transitions; @@ -37,15 +41,37 @@ import com.android.wm.shell.transition.Transitions; public class ActivityEmbeddingController implements Transitions.TransitionHandler { private final Context mContext; - private final Transitions mTransitions; - - public ActivityEmbeddingController(Context context, ShellInit shellInit, - Transitions transitions) { - mContext = context; - mTransitions = transitions; - if (Transitions.ENABLE_SHELL_TRANSITIONS) { - shellInit.addInitCallback(this::onInit, this); - } + @VisibleForTesting + final Transitions mTransitions; + @VisibleForTesting + final ActivityEmbeddingAnimationRunner mAnimationRunner; + + /** + * Keeps track of the currently-running transition callback associated with each transition + * token. + */ + private final ArrayMap<IBinder, Transitions.TransitionFinishCallback> mTransitionCallbacks = + new ArrayMap<>(); + + private ActivityEmbeddingController(@NonNull Context context, @NonNull ShellInit shellInit, + @NonNull Transitions transitions) { + mContext = requireNonNull(context); + mTransitions = requireNonNull(transitions); + mAnimationRunner = new ActivityEmbeddingAnimationRunner(context, this); + + shellInit.addInitCallback(this::onInit, this); + } + + /** + * Creates {@link ActivityEmbeddingController}, returns {@code null} if the feature is not + * supported. + */ + @Nullable + public static ActivityEmbeddingController create(@NonNull Context context, + @NonNull ShellInit shellInit, @NonNull Transitions transitions) { + return Transitions.ENABLE_SHELL_TRANSITIONS + ? new ActivityEmbeddingController(context, shellInit, transitions) + : null; } /** Registers to handle transitions. */ @@ -66,9 +92,9 @@ public class ActivityEmbeddingController implements Transitions.TransitionHandle } } - // TODO(b/207070762) Implement AE animation. - startTransaction.apply(); - finishCallback.onTransitionFinished(null /* wct */, null /* wctCB */); + // Start ActivityEmbedding animation. + mTransitionCallbacks.put(transition, finishCallback); + mAnimationRunner.startAnimation(transition, info, startTransaction, finishTransaction); return true; } @@ -79,6 +105,21 @@ public class ActivityEmbeddingController implements Transitions.TransitionHandle return null; } + @Override + public void setAnimScaleSetting(float scale) { + mAnimationRunner.setAnimScaleSetting(scale); + } + + /** Called when the animation is finished. */ + void onAnimationFinished(@NonNull IBinder transition) { + final Transitions.TransitionFinishCallback callback = + mTransitionCallbacks.remove(transition); + if (callback == null) { + throw new IllegalStateException("No finish callback found"); + } + callback.onTransitionFinished(null /* wct */, null /* wctCB */); + } + private static boolean isEmbedded(@NonNull TransitionInfo.Change change) { return (change.getFlags() & FLAG_IS_EMBEDDED) != 0; } diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/Bubble.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/Bubble.java index 2c02006c8ca5..99b8885acdef 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/Bubble.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/Bubble.java @@ -821,7 +821,7 @@ public class Bubble implements BubbleViewProvider { /** * Description of current bubble state. */ - public void dump(@NonNull PrintWriter pw, @NonNull String[] args) { + public void dump(@NonNull PrintWriter pw) { pw.print("key: "); pw.println(mKey); pw.print(" showInShade: "); pw.println(showInShade()); pw.print(" showDot: "); pw.println(showDot()); @@ -831,7 +831,7 @@ public class Bubble implements BubbleViewProvider { pw.print(" suppressNotif: "); pw.println(shouldSuppressNotification()); pw.print(" autoExpand: "); pw.println(shouldAutoExpand()); if (mExpandedView != null) { - mExpandedView.dump(pw, args); + mExpandedView.dump(pw); } } diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java index de26b54971ca..dcbb272feab8 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java @@ -72,7 +72,6 @@ import android.service.notification.NotificationListenerService; import android.service.notification.NotificationListenerService.RankingMap; import android.util.Log; import android.util.Pair; -import android.util.Slog; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; @@ -100,6 +99,7 @@ import com.android.wm.shell.onehanded.OneHandedController; import com.android.wm.shell.onehanded.OneHandedTransitionCallback; import com.android.wm.shell.pip.PinnedStackListenerForwarder; import com.android.wm.shell.sysui.ConfigurationChangeListener; +import com.android.wm.shell.sysui.ShellCommandHandler; import com.android.wm.shell.sysui.ShellController; import com.android.wm.shell.sysui.ShellInit; @@ -159,6 +159,7 @@ public class BubbleController implements ConfigurationChangeListener { private final TaskViewTransitions mTaskViewTransitions; private final SyncTransactionQueue mSyncQueue; private final ShellController mShellController; + private final ShellCommandHandler mShellCommandHandler; // Used to post to main UI thread private final ShellExecutor mMainExecutor; @@ -229,6 +230,7 @@ public class BubbleController implements ConfigurationChangeListener { public BubbleController(Context context, ShellInit shellInit, + ShellCommandHandler shellCommandHandler, ShellController shellController, BubbleData data, @Nullable BubbleStackView.SurfaceSynchronizer synchronizer, @@ -252,6 +254,7 @@ public class BubbleController implements ConfigurationChangeListener { TaskViewTransitions taskViewTransitions, SyncTransactionQueue syncQueue) { mContext = context; + mShellCommandHandler = shellCommandHandler; mShellController = shellController; mLauncherApps = launcherApps; mBarService = statusBarService == null @@ -431,6 +434,7 @@ public class BubbleController implements ConfigurationChangeListener { mCurrentProfiles = userProfiles; mShellController.addConfigurationChangeListener(this); + mShellCommandHandler.addDumpCallback(this::dump, this); } @VisibleForTesting @@ -538,7 +542,6 @@ public class BubbleController implements ConfigurationChangeListener { if (mNotifEntryToExpandOnShadeUnlock != null) { expandStackAndSelectBubble(mNotifEntryToExpandOnShadeUnlock); - mNotifEntryToExpandOnShadeUnlock = null; } updateStack(); @@ -925,15 +928,6 @@ public class BubbleController implements ConfigurationChangeListener { return (isSummary && isSuppressedSummary) || isSuppressedBubble; } - private void removeSuppressedSummaryIfNecessary(String groupKey, Consumer<String> callback) { - if (mBubbleData.isSummarySuppressed(groupKey)) { - mBubbleData.removeSuppressedSummary(groupKey); - if (callback != null) { - callback.accept(mBubbleData.getSummaryKey(groupKey)); - } - } - } - /** Promote the provided bubble from the overflow view. */ public void promoteBubbleFromOverflow(Bubble bubble) { mLogger.log(bubble, BubbleLogger.Event.BUBBLE_OVERFLOW_REMOVE_BACK_TO_STACK); @@ -1519,14 +1513,15 @@ public class BubbleController implements ConfigurationChangeListener { /** * Description of current bubble state. */ - private void dump(PrintWriter pw, String[] args) { + private void dump(PrintWriter pw, String prefix) { pw.println("BubbleController state:"); - mBubbleData.dump(pw, args); + mBubbleData.dump(pw); pw.println(); if (mStackView != null) { - mStackView.dump(pw, args); + mStackView.dump(pw); } pw.println(); + mImpl.mCachedState.dump(pw); } /** @@ -1711,28 +1706,12 @@ public class BubbleController implements ConfigurationChangeListener { } @Override - public boolean isStackExpanded() { - return mCachedState.isStackExpanded(); - } - - @Override @Nullable public Bubble getBubbleWithShortcutId(String shortcutId) { return mCachedState.getBubbleWithShortcutId(shortcutId); } @Override - public void removeSuppressedSummaryIfNecessary(String groupKey, Consumer<String> callback, - Executor callbackExecutor) { - mMainExecutor.execute(() -> { - Consumer<String> cb = callback != null - ? (key) -> callbackExecutor.execute(() -> callback.accept(key)) - : null; - BubbleController.this.removeSuppressedSummaryIfNecessary(groupKey, cb); - }); - } - - @Override public void collapseStack() { mMainExecutor.execute(() -> { BubbleController.this.collapseStack(); @@ -1761,13 +1740,6 @@ public class BubbleController implements ConfigurationChangeListener { } @Override - public void openBubbleOverflow() { - mMainExecutor.execute(() -> { - BubbleController.this.openBubbleOverflow(); - }); - } - - @Override public boolean handleDismissalInterception(BubbleEntry entry, @Nullable List<BubbleEntry> children, IntConsumer removeCallback, Executor callbackExecutor) { @@ -1882,18 +1854,6 @@ public class BubbleController implements ConfigurationChangeListener { mMainExecutor.execute( () -> BubbleController.this.onNotificationPanelExpandedChanged(expanded)); } - - @Override - public void dump(PrintWriter pw, String[] args) { - try { - mMainExecutor.executeBlocking(() -> { - BubbleController.this.dump(pw, args); - mCachedState.dump(pw); - }); - } catch (InterruptedException e) { - Slog.e(TAG, "Failed to dump BubbleController in 2s"); - } - } } /** diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleData.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleData.java index fa86c8436647..c64133f0b668 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleData.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleData.java @@ -1136,7 +1136,7 @@ public class BubbleData { /** * Description of current bubble data state. */ - public void dump(PrintWriter pw, String[] args) { + public void dump(PrintWriter pw) { pw.print("selected: "); pw.println(mSelectedBubble != null ? mSelectedBubble.getKey() @@ -1147,13 +1147,13 @@ public class BubbleData { pw.print("stack bubble count: "); pw.println(mBubbles.size()); for (Bubble bubble : mBubbles) { - bubble.dump(pw, args); + bubble.dump(pw); } pw.print("overflow bubble count: "); pw.println(mOverflowBubbles.size()); for (Bubble bubble : mOverflowBubbles) { - bubble.dump(pw, args); + bubble.dump(pw); } pw.print("summaryKeys: "); diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleExpandedView.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleExpandedView.java index 2666a0e186b3..cfbe1b3caf7a 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleExpandedView.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleExpandedView.java @@ -1044,7 +1044,7 @@ public class BubbleExpandedView extends LinearLayout { /** * Description of current expanded view state. */ - public void dump(@NonNull PrintWriter pw, @NonNull String[] args) { + public void dump(@NonNull PrintWriter pw) { pw.print("BubbleExpandedView"); pw.print(" taskId: "); pw.println(mTaskId); pw.print(" stackView: "); pw.println(mStackView); diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java index 2d0be066beb5..aeaf6eda9809 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleStackView.java @@ -111,6 +111,9 @@ public class BubbleStackView extends FrameLayout public static final boolean HOME_GESTURE_ENABLED = SystemProperties.getBoolean("persist.wm.debug.bubbles_home_gesture", true); + public static final boolean ENABLE_FLING_TO_DISMISS_BUBBLE = + SystemProperties.getBoolean("persist.wm.debug.fling_to_dismiss_bubble", true); + private static final String TAG = TAG_WITH_CLASS_NAME ? "BubbleStackView" : TAG_BUBBLES; /** How far the flyout needs to be dragged before it's dismissed regardless of velocity. */ @@ -299,7 +302,7 @@ public class BubbleStackView extends FrameLayout private BubblesNavBarGestureTracker mBubblesNavBarGestureTracker; /** Description of current animation controller state. */ - public void dump(PrintWriter pw, String[] args) { + public void dump(PrintWriter pw) { pw.println("Stack view state:"); String bubblesOnScreen = BubbleDebugConfig.formatBubblesString( @@ -313,8 +316,8 @@ public class BubbleStackView extends FrameLayout pw.print(" expandedContainerMatrix: "); pw.println(mExpandedViewContainer.getAnimationMatrix()); - mStackAnimationController.dump(pw, args); - mExpandedAnimationController.dump(pw, args); + mStackAnimationController.dump(pw); + mExpandedAnimationController.dump(pw); if (mExpandedBubble != null) { pw.println("Expanded bubble state:"); diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/Bubbles.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/Bubbles.java index 37b96ffe5cd1..0e97e9e74114 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/Bubbles.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/Bubbles.java @@ -35,7 +35,6 @@ import androidx.annotation.Nullable; import com.android.wm.shell.common.annotations.ExternalThread; -import java.io.PrintWriter; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.HashMap; @@ -91,18 +90,6 @@ public interface Bubbles { */ boolean isBubbleExpanded(String key); - /** @return {@code true} if stack of bubbles is expanded or not. */ - boolean isStackExpanded(); - - /** - * Removes a group key indicating that the summary for this group should no longer be - * suppressed. - * - * @param callback If removed, this callback will be called with the summary key of the group - */ - void removeSuppressedSummaryIfNecessary(String groupKey, Consumer<String> callback, - Executor callbackExecutor); - /** Tell the stack of bubbles to collapse. */ void collapseStack(); @@ -130,9 +117,6 @@ public interface Bubbles { /** Called for any taskbar changes. */ void onTaskbarChanged(Bundle b); - /** Open the overflow view. */ - void openBubbleOverflow(); - /** * We intercept notification entries (including group summaries) dismissed by the user when * there is an active bubble associated with it. We do this so that developers can still @@ -252,9 +236,6 @@ public interface Bubbles { */ void onUserRemoved(int removedUserId); - /** Description of current bubble state. */ - void dump(PrintWriter pw, String[] args); - /** Listener to find out about stack expansion / collapse events. */ interface BubbleExpandListener { /** diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedAnimationController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedAnimationController.java index b521cb6a3d38..b91062f891e8 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedAnimationController.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/ExpandedAnimationController.java @@ -19,6 +19,7 @@ package com.android.wm.shell.bubbles.animation; import static android.view.View.LAYOUT_DIRECTION_RTL; import static com.android.wm.shell.bubbles.BubblePositioner.NUM_VISIBLE_WHEN_RESTING; +import static com.android.wm.shell.bubbles.BubbleStackView.ENABLE_FLING_TO_DISMISS_BUBBLE; import static com.android.wm.shell.bubbles.BubbleStackView.HOME_GESTURE_ENABLED; import android.content.res.Resources; @@ -366,6 +367,7 @@ public class ExpandedAnimationController mMagnetizedBubbleDraggingOut.setMagnetListener(listener); mMagnetizedBubbleDraggingOut.setHapticsEnabled(true); mMagnetizedBubbleDraggingOut.setFlingToTargetMinVelocity(FLING_TO_DISMISS_MIN_VELOCITY); + mMagnetizedBubbleDraggingOut.setFlingToTargetEnabled(ENABLE_FLING_TO_DISMISS_BUBBLE); } private void springBubbleTo(View bubble, float x, float y) { @@ -468,7 +470,7 @@ public class ExpandedAnimationController } /** Description of current animation controller state. */ - public void dump(PrintWriter pw, String[] args) { + public void dump(PrintWriter pw) { pw.println("ExpandedAnimationController state:"); pw.print(" isActive: "); pw.println(isActiveController()); pw.print(" animatingExpand: "); pw.println(mAnimatingExpand); diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/StackAnimationController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/StackAnimationController.java index 0a1b4d70fb2b..961722ba9bc0 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/StackAnimationController.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/animation/StackAnimationController.java @@ -17,6 +17,7 @@ package com.android.wm.shell.bubbles.animation; import static com.android.wm.shell.bubbles.BubblePositioner.NUM_VISIBLE_WHEN_RESTING; +import static com.android.wm.shell.bubbles.BubbleStackView.ENABLE_FLING_TO_DISMISS_BUBBLE; import android.content.ContentResolver; import android.content.res.Resources; @@ -431,7 +432,7 @@ public class StackAnimationController extends } /** Description of current animation controller state. */ - public void dump(PrintWriter pw, String[] args) { + public void dump(PrintWriter pw) { pw.println("StackAnimationController state:"); pw.print(" isActive: "); pw.println(isActiveController()); pw.print(" restingStackPos: "); @@ -1028,6 +1029,7 @@ public class StackAnimationController extends }; mMagnetizedStack.setHapticsEnabled(true); mMagnetizedStack.setFlingToTargetMinVelocity(FLING_TO_DISMISS_MIN_VELOCITY); + mMagnetizedStack.setFlingToTargetEnabled(ENABLE_FLING_TO_DISMISS_BUBBLE); } final ContentResolver contentResolver = mLayout.getContext().getContentResolver(); diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/TvPipModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/TvPipModule.java index e22c9517f4ab..8022e9b1cd81 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/TvPipModule.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/TvPipModule.java @@ -66,6 +66,7 @@ public abstract class TvPipModule { @Provides static Optional<Pip> providePip( Context context, + ShellInit shellInit, ShellController shellController, TvPipBoundsState tvPipBoundsState, TvPipBoundsAlgorithm tvPipBoundsAlgorithm, @@ -84,6 +85,7 @@ public abstract class TvPipModule { return Optional.of( TvPipController.create( context, + shellInit, shellController, tvPipBoundsState, tvPipBoundsAlgorithm, diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java index a6a04cf67b3c..7a736ccab5d1 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java @@ -85,6 +85,7 @@ import com.android.wm.shell.transition.Transitions; import com.android.wm.shell.unfold.ShellUnfoldProgressProvider; import com.android.wm.shell.unfold.UnfoldAnimationController; import com.android.wm.shell.unfold.UnfoldTransitionHandler; +import com.android.wm.shell.windowdecor.WindowDecorViewModel; import java.util.Optional; @@ -294,25 +295,33 @@ public abstract class WMShellBaseModule { // Workaround for dynamic overriding with a default implementation, see {@link DynamicOverride} @BindsOptionalOf @DynamicOverride - abstract FullscreenTaskListener optionalFullscreenTaskListener(); + abstract FullscreenTaskListener<?> optionalFullscreenTaskListener(); @WMSingleton @Provides - static FullscreenTaskListener provideFullscreenTaskListener( - @DynamicOverride Optional<FullscreenTaskListener> fullscreenTaskListener, + static FullscreenTaskListener<?> provideFullscreenTaskListener( + @DynamicOverride Optional<FullscreenTaskListener<?>> fullscreenTaskListener, ShellInit shellInit, ShellTaskOrganizer shellTaskOrganizer, SyncTransactionQueue syncQueue, - Optional<RecentTasksController> recentTasksOptional) { + Optional<RecentTasksController> recentTasksOptional, + Optional<WindowDecorViewModel<?>> windowDecorViewModelOptional) { if (fullscreenTaskListener.isPresent()) { return fullscreenTaskListener.get(); } else { return new FullscreenTaskListener(shellInit, shellTaskOrganizer, syncQueue, - recentTasksOptional); + recentTasksOptional, windowDecorViewModelOptional); } } // + // Window Decoration + // + + @BindsOptionalOf + abstract WindowDecorViewModel<?> optionalWindowDecorViewModel(); + + // // Unfold transition // @@ -627,11 +636,12 @@ public abstract class WMShellBaseModule { @WMSingleton @Provides - static ActivityEmbeddingController provideActivityEmbeddingController( + static Optional<ActivityEmbeddingController> provideActivityEmbeddingController( Context context, ShellInit shellInit, Transitions transitions) { - return new ActivityEmbeddingController(context, shellInit, transitions); + return Optional.ofNullable( + ActivityEmbeddingController.create(context, shellInit, transitions)); } // @@ -679,14 +689,14 @@ public abstract class WMShellBaseModule { Optional<SplitScreenController> splitScreenOptional, Optional<Pip> pipOptional, Optional<PipTouchHandler> pipTouchHandlerOptional, - FullscreenTaskListener fullscreenTaskListener, + FullscreenTaskListener<?> fullscreenTaskListener, Optional<UnfoldAnimationController> unfoldAnimationController, Optional<UnfoldTransitionHandler> unfoldTransitionHandler, Optional<FreeformComponents> freeformComponents, Optional<RecentTasksController> recentTasksOptional, Optional<OneHandedController> oneHandedControllerOptional, Optional<HideDisplayCutoutController> hideDisplayCutoutControllerOptional, - ActivityEmbeddingController activityEmbeddingOptional, + Optional<ActivityEmbeddingController> activityEmbeddingOptional, Transitions transitions, StartingWindowController startingWindow, @ShellCreateTriggerOverride Optional<Object> overriddenCreateTrigger) { diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java index 2bcc134f9dd5..c64d1134a4ab 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java @@ -55,6 +55,7 @@ import com.android.wm.shell.draganddrop.DragAndDropController; import com.android.wm.shell.freeform.FreeformComponents; import com.android.wm.shell.freeform.FreeformTaskListener; import com.android.wm.shell.freeform.FreeformTaskTransitionHandler; +import com.android.wm.shell.fullscreen.FullscreenTaskListener; import com.android.wm.shell.onehanded.OneHandedController; import com.android.wm.shell.pip.Pip; import com.android.wm.shell.pip.PipAnimationController; @@ -145,6 +146,7 @@ public abstract class WMShellModule { @Provides static BubbleController provideBubbleController(Context context, ShellInit shellInit, + ShellCommandHandler shellCommandHandler, ShellController shellController, BubbleData data, FloatingContentCoordinator floatingContentCoordinator, @@ -165,7 +167,7 @@ public abstract class WMShellModule { @ShellBackgroundThread ShellExecutor bgExecutor, TaskViewTransitions taskViewTransitions, SyncTransactionQueue syncQueue) { - return new BubbleController(context, shellInit, shellController, data, + return new BubbleController(context, shellInit, shellCommandHandler, shellController, data, null /* synchronizer */, floatingContentCoordinator, new BubbleDataRepository(context, launcherApps, mainExecutor), statusBarService, windowManager, windowManagerShellWrapper, userManager, @@ -232,6 +234,7 @@ public abstract class WMShellModule { ShellInit shellInit, Transitions transitions, WindowDecorViewModel<?> windowDecorViewModel, + FullscreenTaskListener<?> fullscreenTaskListener, FreeformTaskListener<?> freeformTaskListener) { // TODO(b/238217847): Temporarily add this check here until we can remove the dynamic // override for this controller from the base module @@ -239,7 +242,7 @@ public abstract class WMShellModule { ? shellInit : null; return new FreeformTaskTransitionHandler(init, transitions, - windowDecorViewModel, freeformTaskListener); + windowDecorViewModel, fullscreenTaskListener, freeformTaskListener); } // diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskListener.java b/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskListener.java index ab66107399c6..8dcdda1895e6 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskListener.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskListener.java @@ -187,12 +187,14 @@ public class FreeformTaskListener<T extends AutoCloseable> RunningTaskInfo taskInfo, SurfaceControl.Transaction startT, SurfaceControl.Transaction finishT) { - T windowDecor = mWindowDecorOfVanishedTasks.get(taskInfo.taskId); - mWindowDecorOfVanishedTasks.remove(taskInfo.taskId); + T windowDecor; final State<T> state = mTasks.get(taskInfo.taskId); if (state != null) { - windowDecor = windowDecor == null ? state.mWindowDecoration : windowDecor; + windowDecor = state.mWindowDecoration; state.mWindowDecoration = null; + } else { + windowDecor = + mWindowDecorOfVanishedTasks.removeReturnOld(taskInfo.taskId); } mWindowDecorationViewModel.setupWindowDecorationForTransition( taskInfo, startT, finishT, windowDecor); @@ -231,7 +233,8 @@ public class FreeformTaskListener<T extends AutoCloseable> if (mWindowDecorOfVanishedTasks.size() == 0) { return; } - Log.w(TAG, "Clearing window decors of vanished tasks. There could be visual defects " + ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS, + "Clearing window decors of vanished tasks. There could be visual defects " + "if any of them is used later in transitions."); for (int i = 0; i < mWindowDecorOfVanishedTasks.size(); ++i) { releaseWindowDecor(mWindowDecorOfVanishedTasks.valueAt(i)); diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskTransitionHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskTransitionHandler.java index a1e9f938d280..30f625e24118 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskTransitionHandler.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/freeform/FreeformTaskTransitionHandler.java @@ -32,6 +32,7 @@ import android.window.WindowContainerTransaction; import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import com.android.wm.shell.fullscreen.FullscreenTaskListener; import com.android.wm.shell.sysui.ShellInit; import com.android.wm.shell.transition.Transitions; import com.android.wm.shell.windowdecor.WindowDecorViewModel; @@ -50,6 +51,7 @@ public class FreeformTaskTransitionHandler private final Transitions mTransitions; private final FreeformTaskListener<?> mFreeformTaskListener; + private final FullscreenTaskListener<?> mFullscreenTaskListener; private final WindowDecorViewModel<?> mWindowDecorViewModel; private final List<IBinder> mPendingTransitionTokens = new ArrayList<>(); @@ -58,8 +60,10 @@ public class FreeformTaskTransitionHandler ShellInit shellInit, Transitions transitions, WindowDecorViewModel<?> windowDecorViewModel, + FullscreenTaskListener<?> fullscreenTaskListener, FreeformTaskListener<?> freeformTaskListener) { mTransitions = transitions; + mFullscreenTaskListener = fullscreenTaskListener; mFreeformTaskListener = freeformTaskListener; mWindowDecorViewModel = windowDecorViewModel; if (shellInit != null && Transitions.ENABLE_SHELL_TRANSITIONS) { @@ -150,10 +154,16 @@ public class FreeformTaskTransitionHandler TransitionInfo.Change change, SurfaceControl.Transaction startT, SurfaceControl.Transaction finishT) { - if (change.getTaskInfo().getWindowingMode() != WINDOWING_MODE_FREEFORM) { - return false; + switch (change.getTaskInfo().getWindowingMode()){ + case WINDOWING_MODE_FREEFORM: + mFreeformTaskListener.createWindowDecoration(change, startT, finishT); + break; + case WINDOWING_MODE_FULLSCREEN: + mFullscreenTaskListener.createWindowDecoration(change, startT, finishT); + break; + default: + return false; } - mFreeformTaskListener.createWindowDecoration(change, startT, finishT); // Intercepted transition to manage the window decorations. Let other handlers animate. return false; @@ -164,15 +174,22 @@ public class FreeformTaskTransitionHandler ArrayList<AutoCloseable> windowDecors, SurfaceControl.Transaction startT, SurfaceControl.Transaction finishT) { - if (change.getTaskInfo().getWindowingMode() != WINDOWING_MODE_FREEFORM) { - return false; + final AutoCloseable windowDecor; + switch (change.getTaskInfo().getWindowingMode()) { + case WINDOWING_MODE_FREEFORM: + windowDecor = mFreeformTaskListener.giveWindowDecoration(change.getTaskInfo(), + startT, finishT); + break; + case WINDOWING_MODE_FULLSCREEN: + windowDecor = mFullscreenTaskListener.giveWindowDecoration(change.getTaskInfo(), + startT, finishT); + break; + default: + windowDecor = null; } - final AutoCloseable windowDecor = - mFreeformTaskListener.giveWindowDecoration(change.getTaskInfo(), startT, finishT); if (windowDecor != null) { windowDecors.add(windowDecor); } - // Intercepted transition to manage the window decorations. Let other handlers animate. return false; } @@ -197,24 +214,29 @@ public class FreeformTaskTransitionHandler } boolean handled = false; + boolean adopted = false; final ActivityManager.RunningTaskInfo taskInfo = change.getTaskInfo(); if (type == Transitions.TRANSIT_MAXIMIZE && taskInfo.getWindowingMode() == WINDOWING_MODE_FULLSCREEN) { handled = true; windowDecor = mFreeformTaskListener.giveWindowDecoration( change.getTaskInfo(), startT, finishT); - // TODO(b/235638450): Let fullscreen task listener adopt the window decor. + adopted = mFullscreenTaskListener.adoptWindowDecoration(change, + startT, finishT, windowDecor); } if (type == Transitions.TRANSIT_RESTORE_FROM_MAXIMIZE && taskInfo.getWindowingMode() == WINDOWING_MODE_FREEFORM) { handled = true; - // TODO(b/235638450): Let fullscreen task listener transfer the window decor. - mFreeformTaskListener.adoptWindowDecoration(change, startT, finishT, windowDecor); + windowDecor = mFullscreenTaskListener.giveWindowDecoration( + change.getTaskInfo(), startT, finishT); + adopted = mFreeformTaskListener.adoptWindowDecoration(change, + startT, finishT, windowDecor); } - releaseWindowDecor(windowDecor); - + if (!adopted) { + releaseWindowDecor(windowDecor); + } return handled; } @@ -225,7 +247,7 @@ public class FreeformTaskTransitionHandler releaseWindowDecor(windowDecor); } mFreeformTaskListener.onTaskTransitionFinished(); - // TODO(b/235638450): Dispatch it to fullscreen task listener. + mFullscreenTaskListener.onTaskTransitionFinished(); finishCallback.onTransitionFinished(null, null); } diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/fullscreen/FullscreenTaskListener.java b/libs/WindowManager/Shell/src/com/android/wm/shell/fullscreen/FullscreenTaskListener.java index 0ba4afc24c45..0d75bc451b72 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/fullscreen/FullscreenTaskListener.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/fullscreen/FullscreenTaskListener.java @@ -16,16 +16,21 @@ package com.android.wm.shell.fullscreen; +import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM; + import static com.android.wm.shell.ShellTaskOrganizer.TASK_LISTENER_TYPE_FULLSCREEN; import static com.android.wm.shell.ShellTaskOrganizer.taskListenerTypeToString; +import android.app.ActivityManager; import android.app.ActivityManager.RunningTaskInfo; import android.graphics.Point; -import android.util.Slog; +import android.util.Log; import android.util.SparseArray; import android.view.SurfaceControl; +import android.window.TransitionInfo; import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import com.android.internal.protolog.common.ProtoLog; import com.android.wm.shell.ShellTaskOrganizer; @@ -34,36 +39,49 @@ import com.android.wm.shell.protolog.ShellProtoLogGroup; import com.android.wm.shell.recents.RecentTasksController; import com.android.wm.shell.sysui.ShellInit; import com.android.wm.shell.transition.Transitions; +import com.android.wm.shell.windowdecor.WindowDecorViewModel; import java.io.PrintWriter; import java.util.Optional; /** * Organizes tasks presented in {@link android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN}. + * @param <T> the type of window decoration instance */ -public class FullscreenTaskListener implements ShellTaskOrganizer.TaskListener { +public class FullscreenTaskListener<T extends AutoCloseable> + implements ShellTaskOrganizer.TaskListener { private static final String TAG = "FullscreenTaskListener"; private final ShellTaskOrganizer mShellTaskOrganizer; - private final SyncTransactionQueue mSyncQueue; - private final Optional<RecentTasksController> mRecentTasksOptional; - private final SparseArray<TaskData> mDataByTaskId = new SparseArray<>(); + private final SparseArray<State<T>> mTasks = new SparseArray<>(); + private final SparseArray<T> mWindowDecorOfVanishedTasks = new SparseArray<>(); + private static class State<T extends AutoCloseable> { + RunningTaskInfo mTaskInfo; + SurfaceControl mLeash; + T mWindowDecoration; + } + private final SyncTransactionQueue mSyncQueue; + private final Optional<RecentTasksController> mRecentTasksOptional; + private final Optional<WindowDecorViewModel<T>> mWindowDecorViewModelOptional; /** * This constructor is used by downstream products. */ public FullscreenTaskListener(SyncTransactionQueue syncQueue) { - this(null /* shellInit */, null /* shellTaskOrganizer */, syncQueue, Optional.empty()); + this(null /* shellInit */, null /* shellTaskOrganizer */, syncQueue, Optional.empty(), + Optional.empty()); } public FullscreenTaskListener(ShellInit shellInit, ShellTaskOrganizer shellTaskOrganizer, SyncTransactionQueue syncQueue, - Optional<RecentTasksController> recentTasksOptional) { + Optional<RecentTasksController> recentTasksOptional, + Optional<WindowDecorViewModel<T>> windowDecorViewModelOptional) { mShellTaskOrganizer = shellTaskOrganizer; mSyncQueue = syncQueue; mRecentTasksOptional = recentTasksOptional; + mWindowDecorViewModelOptional = windowDecorViewModelOptional; // Note: Some derivative FullscreenTaskListener implementations do not use ShellInit if (shellInit != null) { shellInit.addInitCallback(this::onInit, this); @@ -76,55 +94,204 @@ public class FullscreenTaskListener implements ShellTaskOrganizer.TaskListener { @Override public void onTaskAppeared(RunningTaskInfo taskInfo, SurfaceControl leash) { - if (mDataByTaskId.get(taskInfo.taskId) != null) { + if (mTasks.get(taskInfo.taskId) != null) { throw new IllegalStateException("Task appeared more than once: #" + taskInfo.taskId); } ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TASK_ORG, "Fullscreen Task Appeared: #%d", taskInfo.taskId); final Point positionInParent = taskInfo.positionInParent; - mDataByTaskId.put(taskInfo.taskId, new TaskData(leash, positionInParent)); - - if (Transitions.ENABLE_SHELL_TRANSITIONS) return; - mSyncQueue.runInSync(t -> { - // Reset several properties back to fullscreen (PiP, for example, leaves all these - // properties in a bad state). - t.setWindowCrop(leash, null); - t.setPosition(leash, positionInParent.x, positionInParent.y); - t.setAlpha(leash, 1f); - t.setMatrix(leash, 1, 0, 0, 1); - t.show(leash); - }); + final State<T> state = new State(); + state.mLeash = leash; + state.mTaskInfo = taskInfo; + mTasks.put(taskInfo.taskId, state); updateRecentsForVisibleFullscreenTask(taskInfo); + if (Transitions.ENABLE_SHELL_TRANSITIONS) return; + if (shouldShowWindowDecor(taskInfo) && mWindowDecorViewModelOptional.isPresent()) { + SurfaceControl.Transaction t = new SurfaceControl.Transaction(); + state.mWindowDecoration = + mWindowDecorViewModelOptional.get().createWindowDecoration(taskInfo, + leash, t, t); + t.apply(); + } else { + mSyncQueue.runInSync(t -> { + // Reset several properties back to fullscreen (PiP, for example, leaves all these + // properties in a bad state). + t.setWindowCrop(leash, null); + t.setPosition(leash, positionInParent.x, positionInParent.y); + t.setAlpha(leash, 1f); + t.setMatrix(leash, 1, 0, 0, 1); + t.show(leash); + }); + } } @Override public void onTaskInfoChanged(RunningTaskInfo taskInfo) { - if (Transitions.ENABLE_SHELL_TRANSITIONS) return; - + final State<T> state = mTasks.get(taskInfo.taskId); + final Point oldPositionInParent = state.mTaskInfo.positionInParent; + state.mTaskInfo = taskInfo; + if (state.mWindowDecoration != null) { + mWindowDecorViewModelOptional.get().onTaskInfoChanged( + state.mTaskInfo, state.mWindowDecoration); + } updateRecentsForVisibleFullscreenTask(taskInfo); + if (Transitions.ENABLE_SHELL_TRANSITIONS) return; - final TaskData data = mDataByTaskId.get(taskInfo.taskId); - final Point positionInParent = taskInfo.positionInParent; - if (!positionInParent.equals(data.positionInParent)) { - data.positionInParent.set(positionInParent.x, positionInParent.y); + final Point positionInParent = state.mTaskInfo.positionInParent; + if (!oldPositionInParent.equals(state.mTaskInfo.positionInParent)) { mSyncQueue.runInSync(t -> { - t.setPosition(data.surface, positionInParent.x, positionInParent.y); + t.setPosition(state.mLeash, positionInParent.x, positionInParent.y); }); } } @Override - public void onTaskVanished(RunningTaskInfo taskInfo) { - if (mDataByTaskId.get(taskInfo.taskId) == null) { - Slog.e(TAG, "Task already vanished: #" + taskInfo.taskId); + public void onTaskVanished(ActivityManager.RunningTaskInfo taskInfo) { + final State<T> state = mTasks.get(taskInfo.taskId); + if (state == null) { + // This is possible if the transition happens before this method. return; } - - mDataByTaskId.remove(taskInfo.taskId); - ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TASK_ORG, "Fullscreen Task Vanished: #%d", taskInfo.taskId); + mTasks.remove(taskInfo.taskId); + + if (Transitions.ENABLE_SHELL_TRANSITIONS) { + // Save window decorations of closing tasks so that we can hand them over to the + // transition system if this method happens before the transition. In case where the + // transition didn't happen, it'd be cleared when the next transition finished. + if (state.mWindowDecoration != null) { + mWindowDecorOfVanishedTasks.put(taskInfo.taskId, state.mWindowDecoration); + } + return; + } + releaseWindowDecor(state.mWindowDecoration); + } + + /** + * Creates a window decoration for a transition. + * + * @param change the change of this task transition that needs to have the task layer as the + * leash + */ + public void createWindowDecoration(TransitionInfo.Change change, + SurfaceControl.Transaction startT, SurfaceControl.Transaction finishT) { + final State<T> state = createOrUpdateTaskState(change.getTaskInfo(), change.getLeash()); + if (!mWindowDecorViewModelOptional.isPresent() + || !shouldShowWindowDecor(state.mTaskInfo)) { + return; + } + + state.mWindowDecoration = mWindowDecorViewModelOptional.get().createWindowDecoration( + state.mTaskInfo, state.mLeash, startT, finishT); + } + + /** + * Adopt the incoming window decoration and lets the window decoration prepare for a transition. + * + * @param change the change of this task transition that needs to have the task layer as the + * leash + * @param startT the start transaction of this transition + * @param finishT the finish transaction of this transition + * @param windowDecor the window decoration to adopt + * @return {@code true} if it adopts the window decoration; {@code false} otherwise + */ + public boolean adoptWindowDecoration( + TransitionInfo.Change change, + SurfaceControl.Transaction startT, + SurfaceControl.Transaction finishT, + @Nullable AutoCloseable windowDecor) { + if (!mWindowDecorViewModelOptional.isPresent() + || !shouldShowWindowDecor(change.getTaskInfo())) { + return false; + } + final State<T> state = createOrUpdateTaskState(change.getTaskInfo(), change.getLeash()); + state.mWindowDecoration = mWindowDecorViewModelOptional.get().adoptWindowDecoration( + windowDecor); + if (state.mWindowDecoration != null) { + mWindowDecorViewModelOptional.get().setupWindowDecorationForTransition( + state.mTaskInfo, startT, finishT, state.mWindowDecoration); + return true; + } else { + state.mWindowDecoration = mWindowDecorViewModelOptional.get().createWindowDecoration( + state.mTaskInfo, state.mLeash, startT, finishT); + return false; + } + } + + /** + * Clear window decors of vanished tasks. + */ + public void onTaskTransitionFinished() { + if (mWindowDecorOfVanishedTasks.size() == 0) { + return; + } + ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS, + "Clearing window decors of vanished tasks. There could be visual defects " + + "if any of them is used later in transitions."); + for (int i = 0; i < mWindowDecorOfVanishedTasks.size(); ++i) { + releaseWindowDecor(mWindowDecorOfVanishedTasks.valueAt(i)); + } + mWindowDecorOfVanishedTasks.clear(); + } + + /** + * Gives out the ownership of the task's window decoration. The given task is leaving (of has + * left) this task listener. This is the transition system asking for the ownership. + * + * @param taskInfo the maximizing task + * @return the window decor of the maximizing task if any + */ + public T giveWindowDecoration( + ActivityManager.RunningTaskInfo taskInfo, + SurfaceControl.Transaction startT, + SurfaceControl.Transaction finishT) { + T windowDecor; + final State<T> state = mTasks.get(taskInfo.taskId); + if (state != null) { + windowDecor = state.mWindowDecoration; + state.mWindowDecoration = null; + } else { + windowDecor = + mWindowDecorOfVanishedTasks.removeReturnOld(taskInfo.taskId); + } + if (mWindowDecorViewModelOptional.isPresent()) { + mWindowDecorViewModelOptional.get().setupWindowDecorationForTransition( + taskInfo, startT, finishT, windowDecor); + } + + return windowDecor; + } + + private State<T> createOrUpdateTaskState(ActivityManager.RunningTaskInfo taskInfo, + SurfaceControl leash) { + State<T> state = mTasks.get(taskInfo.taskId); + if (state != null) { + updateTaskInfo(taskInfo); + return state; + } + + state = new State<T>(); + state.mTaskInfo = taskInfo; + state.mLeash = leash; + mTasks.put(taskInfo.taskId, state); + + return state; + } + + private State<T> updateTaskInfo(ActivityManager.RunningTaskInfo taskInfo) { + final State<T> state = mTasks.get(taskInfo.taskId); + state.mTaskInfo = taskInfo; + return state; + } + + private void releaseWindowDecor(T windowDecor) { + try { + windowDecor.close(); + } catch (Exception e) { + Log.e(TAG, "Failed to release window decoration.", e); + } } private void updateRecentsForVisibleFullscreenTask(RunningTaskInfo taskInfo) { @@ -148,17 +315,17 @@ public class FullscreenTaskListener implements ShellTaskOrganizer.TaskListener { } private SurfaceControl findTaskSurface(int taskId) { - if (!mDataByTaskId.contains(taskId)) { + if (!mTasks.contains(taskId)) { throw new IllegalArgumentException("There is no surface for taskId=" + taskId); } - return mDataByTaskId.get(taskId).surface; + return mTasks.get(taskId).mLeash; } @Override public void dump(@NonNull PrintWriter pw, String prefix) { final String innerPrefix = prefix + " "; pw.println(prefix + this); - pw.println(innerPrefix + mDataByTaskId.size() + " Tasks"); + pw.println(innerPrefix + mTasks.size() + " Tasks"); } @Override @@ -166,16 +333,10 @@ public class FullscreenTaskListener implements ShellTaskOrganizer.TaskListener { return TAG + ":" + taskListenerTypeToString(TASK_LISTENER_TYPE_FULLSCREEN); } - /** - * Per-task data for each managed task. - */ - private static class TaskData { - public final SurfaceControl surface; - public final Point positionInParent; - - public TaskData(SurfaceControl surface, Point positionInParent) { - this.surface = surface; - this.positionInParent = positionInParent; - } + private static boolean shouldShowWindowDecor(RunningTaskInfo taskInfo) { + return taskInfo.getConfiguration().windowConfiguration.getDisplayWindowingMode() + == WINDOWING_MODE_FREEFORM; } + + } diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/onehanded/OneHanded.java b/libs/WindowManager/Shell/src/com/android/wm/shell/onehanded/OneHanded.java index 76c0f41997ad..7129165a78dc 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/onehanded/OneHanded.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/onehanded/OneHanded.java @@ -37,16 +37,6 @@ public interface OneHanded { } /** - * Return one handed settings enabled or not. - */ - boolean isOneHandedEnabled(); - - /** - * Return swipe to notification settings enabled or not. - */ - boolean isSwipeToNotificationEnabled(); - - /** * Enters one handed mode. */ void startOneHanded(); @@ -80,9 +70,4 @@ public interface OneHanded { * transition start or finish */ void registerTransitionCallback(OneHandedTransitionCallback callback); - - /** - * Notifies when user switch complete - */ - void onUserSwitch(int userId); } diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/onehanded/OneHandedController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/onehanded/OneHandedController.java index 9149204b94ce..e0c4fe8c4fba 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/onehanded/OneHandedController.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/onehanded/OneHandedController.java @@ -59,6 +59,7 @@ import com.android.wm.shell.sysui.KeyguardChangeListener; import com.android.wm.shell.sysui.ShellCommandHandler; import com.android.wm.shell.sysui.ShellController; import com.android.wm.shell.sysui.ShellInit; +import com.android.wm.shell.sysui.UserChangeListener; import java.io.PrintWriter; @@ -67,7 +68,7 @@ import java.io.PrintWriter; */ public class OneHandedController implements RemoteCallable<OneHandedController>, DisplayChangeController.OnDisplayChangingListener, ConfigurationChangeListener, - KeyguardChangeListener { + KeyguardChangeListener, UserChangeListener { private static final String TAG = "OneHandedController"; private static final String ONE_HANDED_MODE_OFFSET_PERCENTAGE = @@ -76,8 +77,8 @@ public class OneHandedController implements RemoteCallable<OneHandedController>, public static final String SUPPORT_ONE_HANDED_MODE = "ro.support_one_handed_mode"; - private volatile boolean mIsOneHandedEnabled; - private volatile boolean mIsSwipeToNotificationEnabled; + private boolean mIsOneHandedEnabled; + private boolean mIsSwipeToNotificationEnabled; private boolean mIsShortcutEnabled; private boolean mTaskChangeToExit; private boolean mLockedDisabled; @@ -294,6 +295,7 @@ public class OneHandedController implements RemoteCallable<OneHandedController>, mState.addSListeners(mTutorialHandler); mShellController.addConfigurationChangeListener(this); mShellController.addKeyguardChangeListener(this); + mShellController.addUserChangeListener(this); } public OneHanded asOneHanded() { @@ -627,7 +629,8 @@ public class OneHandedController implements RemoteCallable<OneHandedController>, stopOneHanded(); } - private void onUserSwitch(int newUserId) { + @Override + public void onUserChanged(int newUserId, @NonNull Context userContext) { unregisterSettingObservers(); mUserId = newUserId; registerSettingObservers(newUserId); @@ -718,18 +721,6 @@ public class OneHandedController implements RemoteCallable<OneHandedController>, } @Override - public boolean isOneHandedEnabled() { - // This is volatile so return directly - return mIsOneHandedEnabled; - } - - @Override - public boolean isSwipeToNotificationEnabled() { - // This is volatile so return directly - return mIsSwipeToNotificationEnabled; - } - - @Override public void startOneHanded() { mMainExecutor.execute(() -> { OneHandedController.this.startOneHanded(); @@ -770,13 +761,6 @@ public class OneHandedController implements RemoteCallable<OneHandedController>, OneHandedController.this.registerTransitionCallback(callback); }); } - - @Override - public void onUserSwitch(int userId) { - mMainExecutor.execute(() -> { - OneHandedController.this.onUserSwitch(userId); - }); - } } /** diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/Pip.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/Pip.java index 93172f82edd1..c06881ae6ad7 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/Pip.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/Pip.java @@ -51,12 +51,6 @@ public interface Pip { } /** - * Registers the session listener for the current user. - */ - default void registerSessionListenerForCurrentUser() { - } - - /** * Sets both shelf visibility and its height. * * @param visible visibility of shelf. diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipController.java index fc97f310ad4e..ac3407dd1ca1 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipController.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipController.java @@ -92,6 +92,7 @@ import com.android.wm.shell.sysui.KeyguardChangeListener; import com.android.wm.shell.sysui.ShellCommandHandler; import com.android.wm.shell.sysui.ShellController; import com.android.wm.shell.sysui.ShellInit; +import com.android.wm.shell.sysui.UserChangeListener; import com.android.wm.shell.transition.Transitions; import java.io.PrintWriter; @@ -105,7 +106,8 @@ import java.util.function.Consumer; * Manages the picture-in-picture (PIP) UI and states for Phones. */ public class PipController implements PipTransitionController.PipTransitionCallback, - RemoteCallable<PipController>, ConfigurationChangeListener, KeyguardChangeListener { + RemoteCallable<PipController>, ConfigurationChangeListener, KeyguardChangeListener, + UserChangeListener { private static final String TAG = "PipController"; private Context mContext; @@ -528,7 +530,7 @@ public class PipController implements PipTransitionController.PipTransitionCallb }); mOneHandedController.ifPresent(controller -> { - controller.asOneHanded().registerTransitionCallback( + controller.registerTransitionCallback( new OneHandedTransitionCallback() { @Override public void onStartFinished(Rect bounds) { @@ -542,8 +544,11 @@ public class PipController implements PipTransitionController.PipTransitionCallb }); }); + mMediaController.registerSessionListenerForCurrentUser(); + mShellController.addConfigurationChangeListener(this); mShellController.addKeyguardChangeListener(this); + mShellController.addUserChangeListener(this); } @Override @@ -557,6 +562,12 @@ public class PipController implements PipTransitionController.PipTransitionCallb } @Override + public void onUserChanged(int newUserId, @NonNull Context userContext) { + // Re-register the media session listener when switching users + mMediaController.registerSessionListenerForCurrentUser(); + } + + @Override public void onConfigurationChanged(Configuration newConfig) { mPipBoundsAlgorithm.onConfigurationChanged(mContext); mTouchHandler.onConfigurationChanged(); @@ -644,10 +655,6 @@ public class PipController implements PipTransitionController.PipTransitionCallb } } - private void registerSessionListenerForCurrentUser() { - mMediaController.registerSessionListenerForCurrentUser(); - } - private void onSystemUiStateChanged(boolean isValidState, int flag) { mTouchHandler.onSystemUiStateChanged(isValidState); } @@ -968,13 +975,6 @@ public class PipController implements PipTransitionController.PipTransitionCallb } @Override - public void registerSessionListenerForCurrentUser() { - mMainExecutor.execute(() -> { - PipController.this.registerSessionListenerForCurrentUser(); - }); - } - - @Override public void setShelfHeight(boolean visible, int height) { mMainExecutor.execute(() -> { PipController.this.setShelfHeight(visible, height); diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMotionHelper.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMotionHelper.java index 44d22029a5e9..afb64c9eec41 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMotionHelper.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipMotionHelper.java @@ -33,6 +33,7 @@ import android.content.Context; import android.graphics.PointF; import android.graphics.Rect; import android.os.Debug; +import android.os.SystemProperties; import com.android.internal.protolog.common.ProtoLog; import com.android.wm.shell.R; @@ -58,6 +59,8 @@ import kotlin.jvm.functions.Function0; public class PipMotionHelper implements PipAppOpsListener.Callback, FloatingContentCoordinator.FloatingContent { + public static final boolean ENABLE_FLING_TO_DISMISS_PIP = + SystemProperties.getBoolean("persist.wm.debug.fling_to_dismiss_pip", true); private static final String TAG = "PipMotionHelper"; private static final boolean DEBUG = false; @@ -704,6 +707,7 @@ public class PipMotionHelper implements PipAppOpsListener.Callback, loc[1] = animatedPipBounds.top; } }; + mMagnetizedPip.setFlingToTargetEnabled(ENABLE_FLING_TO_DISMISS_PIP); } return mMagnetizedPip; diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipController.java index a24d9618032d..4e1b0469eb96 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipController.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/tv/TvPipController.java @@ -32,6 +32,8 @@ import android.graphics.Rect; import android.os.RemoteException; import android.view.Gravity; +import androidx.annotation.NonNull; + import com.android.internal.protolog.common.ProtoLog; import com.android.wm.shell.R; import com.android.wm.shell.WindowManagerShellWrapper; @@ -51,6 +53,8 @@ import com.android.wm.shell.pip.PipTransitionController; import com.android.wm.shell.protolog.ShellProtoLogGroup; import com.android.wm.shell.sysui.ConfigurationChangeListener; import com.android.wm.shell.sysui.ShellController; +import com.android.wm.shell.sysui.ShellInit; +import com.android.wm.shell.sysui.UserChangeListener; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -64,7 +68,7 @@ import java.util.Set; public class TvPipController implements PipTransitionController.PipTransitionCallback, TvPipBoundsController.PipBoundsListener, TvPipMenuController.Delegate, TvPipNotificationController.Delegate, DisplayController.OnDisplaysChangedListener, - ConfigurationChangeListener { + ConfigurationChangeListener, UserChangeListener { private static final String TAG = "TvPipController"; static final boolean DEBUG = false; @@ -105,6 +109,11 @@ public class TvPipController implements PipTransitionController.PipTransitionCal private final PipMediaController mPipMediaController; private final TvPipNotificationController mPipNotificationController; private final TvPipMenuController mTvPipMenuController; + private final PipTransitionController mPipTransitionController; + private final TaskStackListenerImpl mTaskStackListener; + private final PipParamsChangedForwarder mPipParamsChangedForwarder; + private final DisplayController mDisplayController; + private final WindowManagerShellWrapper mWmShellWrapper; private final ShellExecutor mMainExecutor; private final TvPipImpl mImpl = new TvPipImpl(); @@ -121,6 +130,7 @@ public class TvPipController implements PipTransitionController.PipTransitionCal public static Pip create( Context context, + ShellInit shellInit, ShellController shellController, TvPipBoundsState tvPipBoundsState, TvPipBoundsAlgorithm tvPipBoundsAlgorithm, @@ -138,6 +148,7 @@ public class TvPipController implements PipTransitionController.PipTransitionCal ShellExecutor mainExecutor) { return new TvPipController( context, + shellInit, shellController, tvPipBoundsState, tvPipBoundsAlgorithm, @@ -157,6 +168,7 @@ public class TvPipController implements PipTransitionController.PipTransitionCal private TvPipController( Context context, + ShellInit shellInit, ShellController shellController, TvPipBoundsState tvPipBoundsState, TvPipBoundsAlgorithm tvPipBoundsAlgorithm, @@ -170,11 +182,12 @@ public class TvPipController implements PipTransitionController.PipTransitionCal TaskStackListenerImpl taskStackListener, PipParamsChangedForwarder pipParamsChangedForwarder, DisplayController displayController, - WindowManagerShellWrapper wmShell, + WindowManagerShellWrapper wmShellWrapper, ShellExecutor mainExecutor) { mContext = context; mMainExecutor = mainExecutor; mShellController = shellController; + mDisplayController = displayController; mTvPipBoundsState = tvPipBoundsState; mTvPipBoundsState.setDisplayId(context.getDisplayId()); @@ -193,16 +206,32 @@ public class TvPipController implements PipTransitionController.PipTransitionCal mAppOpsListener = pipAppOpsListener; mPipTaskOrganizer = pipTaskOrganizer; - pipTransitionController.registerPipTransitionCallback(this); + mPipTransitionController = pipTransitionController; + mPipParamsChangedForwarder = pipParamsChangedForwarder; + mTaskStackListener = taskStackListener; + mWmShellWrapper = wmShellWrapper; + shellInit.addInitCallback(this::onInit, this); + } + + private void onInit() { + mPipTransitionController.registerPipTransitionCallback(this); loadConfigurations(); - registerPipParamsChangedListener(pipParamsChangedForwarder); - registerTaskStackListenerCallback(taskStackListener); - registerWmShellPinnedStackListener(wmShell); - displayController.addDisplayWindowListener(this); + registerPipParamsChangedListener(mPipParamsChangedForwarder); + registerTaskStackListenerCallback(mTaskStackListener); + registerWmShellPinnedStackListener(mWmShellWrapper); + registerSessionListenerForCurrentUser(); + mDisplayController.addDisplayWindowListener(this); mShellController.addConfigurationChangeListener(this); + mShellController.addUserChangeListener(this); + } + + @Override + public void onUserChanged(int newUserId, @NonNull Context userContext) { + // Re-register the media session listener when switching users + registerSessionListenerForCurrentUser(); } @Override @@ -679,11 +708,6 @@ public class TvPipController implements PipTransitionController.PipTransitionCal } private class TvPipImpl implements Pip { - @Override - public void registerSessionListenerForCurrentUser() { - mMainExecutor.execute(() -> { - TvPipController.this.registerSessionListenerForCurrentUser(); - }); - } + // Not used } } diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/sysui/KeyguardChangeListener.java b/libs/WindowManager/Shell/src/com/android/wm/shell/sysui/KeyguardChangeListener.java index 1c0b35894acd..9df863163b50 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/sysui/KeyguardChangeListener.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/sysui/KeyguardChangeListener.java @@ -21,13 +21,13 @@ package com.android.wm.shell.sysui; */ public interface KeyguardChangeListener { /** - * Notifies the Shell that the keyguard is showing (and if so, whether it is occluded). + * Called when the keyguard is showing (and if so, whether it is occluded). */ default void onKeyguardVisibilityChanged(boolean visible, boolean occluded, boolean animatingDismiss) {} /** - * Notifies the Shell when the keyguard dismiss animation has finished. + * Called when the keyguard dismiss animation has finished. * * TODO(b/206741900) deprecate this path once we're able to animate the PiP window as part of * keyguard dismiss animation. diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/sysui/ShellController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/sysui/ShellController.java index 52ffb46bb39c..57993948886b 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/sysui/ShellController.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/sysui/ShellController.java @@ -25,7 +25,9 @@ import static android.content.pm.ActivityInfo.CONFIG_UI_MODE; import static com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_SYSUI_EVENTS; +import android.content.Context; import android.content.pm.ActivityInfo; +import android.content.pm.UserInfo; import android.content.res.Configuration; import androidx.annotation.NonNull; @@ -36,6 +38,7 @@ import com.android.wm.shell.common.ShellExecutor; import com.android.wm.shell.common.annotations.ExternalThread; import java.io.PrintWriter; +import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; /** @@ -53,6 +56,9 @@ public class ShellController { new CopyOnWriteArrayList<>(); private final CopyOnWriteArrayList<KeyguardChangeListener> mKeyguardChangeListeners = new CopyOnWriteArrayList<>(); + private final CopyOnWriteArrayList<UserChangeListener> mUserChangeListeners = + new CopyOnWriteArrayList<>(); + private Configuration mLastConfiguration; @@ -102,6 +108,22 @@ public class ShellController { mKeyguardChangeListeners.remove(listener); } + /** + * Adds a new user-change listener. The user change callbacks are not made in any + * particular order. + */ + public void addUserChangeListener(UserChangeListener listener) { + mUserChangeListeners.remove(listener); + mUserChangeListeners.add(listener); + } + + /** + * Removes an existing user-change listener. + */ + public void removeUserChangeListener(UserChangeListener listener) { + mUserChangeListeners.remove(listener); + } + @VisibleForTesting void onConfigurationChanged(Configuration newConfig) { // The initial config is send on startup and doesn't trigger listener callbacks @@ -144,6 +166,8 @@ public class ShellController { @VisibleForTesting void onKeyguardVisibilityChanged(boolean visible, boolean occluded, boolean animatingDismiss) { + ProtoLog.v(WM_SHELL_SYSUI_EVENTS, "Keyguard visibility changed: visible=%b " + + "occluded=%b animatingDismiss=%b", visible, occluded, animatingDismiss); for (KeyguardChangeListener listener : mKeyguardChangeListeners) { listener.onKeyguardVisibilityChanged(visible, occluded, animatingDismiss); } @@ -151,17 +175,35 @@ public class ShellController { @VisibleForTesting void onKeyguardDismissAnimationFinished() { + ProtoLog.v(WM_SHELL_SYSUI_EVENTS, "Keyguard dismiss animation finished"); for (KeyguardChangeListener listener : mKeyguardChangeListeners) { listener.onKeyguardDismissAnimationFinished(); } } + @VisibleForTesting + void onUserChanged(int newUserId, @NonNull Context userContext) { + ProtoLog.v(WM_SHELL_SYSUI_EVENTS, "User changed: id=%d", newUserId); + for (UserChangeListener listener : mUserChangeListeners) { + listener.onUserChanged(newUserId, userContext); + } + } + + @VisibleForTesting + void onUserProfilesChanged(@NonNull List<UserInfo> profiles) { + ProtoLog.v(WM_SHELL_SYSUI_EVENTS, "User profiles changed"); + for (UserChangeListener listener : mUserChangeListeners) { + listener.onUserProfilesChanged(profiles); + } + } + public void dump(@NonNull PrintWriter pw, String prefix) { final String innerPrefix = prefix + " "; pw.println(prefix + TAG); pw.println(innerPrefix + "mConfigChangeListeners=" + mConfigChangeListeners.size()); pw.println(innerPrefix + "mLastConfiguration=" + mLastConfiguration); pw.println(innerPrefix + "mKeyguardChangeListeners=" + mKeyguardChangeListeners.size()); + pw.println(innerPrefix + "mUserChangeListeners=" + mUserChangeListeners.size()); } /** @@ -220,5 +262,17 @@ public class ShellController { mMainExecutor.execute(() -> ShellController.this.onKeyguardDismissAnimationFinished()); } + + @Override + public void onUserChanged(int newUserId, @NonNull Context userContext) { + mMainExecutor.execute(() -> + ShellController.this.onUserChanged(newUserId, userContext)); + } + + @Override + public void onUserProfilesChanged(@NonNull List<UserInfo> profiles) { + mMainExecutor.execute(() -> + ShellController.this.onUserProfilesChanged(profiles)); + } } } diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/sysui/ShellInterface.java b/libs/WindowManager/Shell/src/com/android/wm/shell/sysui/ShellInterface.java index 254c253b0042..2108c824ac6f 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/sysui/ShellInterface.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/sysui/ShellInterface.java @@ -16,9 +16,14 @@ package com.android.wm.shell.sysui; +import android.content.Context; +import android.content.pm.UserInfo; import android.content.res.Configuration; +import androidx.annotation.NonNull; + import java.io.PrintWriter; +import java.util.List; /** * General interface for notifying the Shell of common SysUI events like configuration or keyguard @@ -59,4 +64,14 @@ public interface ShellInterface { * Notifies the Shell when the keyguard dismiss animation has finished. */ default void onKeyguardDismissAnimationFinished() {} + + /** + * Notifies the Shell when the user changes. + */ + default void onUserChanged(int newUserId, @NonNull Context userContext) {} + + /** + * Notifies the Shell when a profile belonging to the user changes. + */ + default void onUserProfilesChanged(@NonNull List<UserInfo> profiles) {} } diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/FakeConnectivityInfoCollector.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/sysui/UserChangeListener.java index 710e5f6eacd3..3d0909f6128d 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/FakeConnectivityInfoCollector.kt +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/sysui/UserChangeListener.java @@ -14,20 +14,26 @@ * limitations under the License. */ -package com.android.systemui.statusbar.pipeline +package com.android.wm.shell.sysui; -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.asStateFlow +import android.content.Context; +import android.content.pm.UserInfo; + +import androidx.annotation.NonNull; + +import java.util.List; /** - * A test-friendly implementation of [ConnectivityInfoCollector] that just emits whatever value it - * receives in [emitValue]. + * Callbacks for when the user or user's profiles changes. */ -class FakeConnectivityInfoCollector : ConnectivityInfoCollector { - private val _rawConnectivityInfoFlow = MutableStateFlow(RawConnectivityInfo()) - override val rawConnectivityInfoFlow = _rawConnectivityInfoFlow.asStateFlow() +public interface UserChangeListener { + /** + * Called when the current (parent) user changes. + */ + default void onUserChanged(int newUserId, @NonNull Context userContext) {} - suspend fun emitValue(value: RawConnectivityInfo) { - _rawConnectivityInfoFlow.emit(value) - } + /** + * Called when a profile belonging to the user changes. + */ + default void onUserProfilesChanged(@NonNull List<UserInfo> profiles) {} } diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java index 6c659667a4a7..cff60f5e5b6c 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java @@ -44,6 +44,8 @@ import static android.view.WindowManager.TRANSIT_RELAUNCH; import static android.view.WindowManager.TRANSIT_TO_BACK; import static android.view.WindowManager.TRANSIT_TO_FRONT; import static android.view.WindowManager.transitTypeToString; +import static android.window.TransitionInfo.FLAG_CROSS_PROFILE_OWNER_THUMBNAIL; +import static android.window.TransitionInfo.FLAG_CROSS_PROFILE_WORK_THUMBNAIL; import static android.window.TransitionInfo.FLAG_DISPLAY_HAS_ALERT_WINDOWS; import static android.window.TransitionInfo.FLAG_IS_DISPLAY; import static android.window.TransitionInfo.FLAG_IS_VOICE_INTERACTION; @@ -903,11 +905,10 @@ public class DefaultTransitionHandler implements Transitions.TransitionHandler { private void attachThumbnail(@NonNull ArrayList<Animator> animations, @NonNull Runnable finishCallback, TransitionInfo.Change change, TransitionInfo.AnimationOptions options, float cornerRadius) { - final boolean isTask = change.getTaskInfo() != null; final boolean isOpen = Transitions.isOpeningType(change.getMode()); final boolean isClose = Transitions.isClosingType(change.getMode()); if (isOpen) { - if (options.getType() == ANIM_OPEN_CROSS_PROFILE_APPS && isTask) { + if (options.getType() == ANIM_OPEN_CROSS_PROFILE_APPS) { attachCrossProfileThumbnailAnimation(animations, finishCallback, change, cornerRadius); } else if (options.getType() == ANIM_THUMBNAIL_SCALE_UP) { @@ -922,8 +923,13 @@ public class DefaultTransitionHandler implements Transitions.TransitionHandler { @NonNull Runnable finishCallback, TransitionInfo.Change change, float cornerRadius) { final Rect bounds = change.getEndAbsBounds(); // Show the right drawable depending on the user we're transitioning to. - final Drawable thumbnailDrawable = change.getTaskInfo().userId == mCurrentUserId - ? mContext.getDrawable(R.drawable.ic_account_circle) : mEnterpriseThumbnailDrawable; + final Drawable thumbnailDrawable = change.hasFlags(FLAG_CROSS_PROFILE_OWNER_THUMBNAIL) + ? mContext.getDrawable(R.drawable.ic_account_circle) + : change.hasFlags(FLAG_CROSS_PROFILE_WORK_THUMBNAIL) + ? mEnterpriseThumbnailDrawable : null; + if (thumbnailDrawable == null) { + return; + } final HardwareBuffer thumbnail = mTransitionAnimation.createCrossProfileAppsThumbnail( thumbnailDrawable, bounds); if (thumbnail == null) { diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/IShellTransitions.aidl b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/IShellTransitions.aidl index bdcdb63d2cd6..cc4d268a0000 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/IShellTransitions.aidl +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/IShellTransitions.aidl @@ -34,4 +34,9 @@ interface IShellTransitions { * Unregisters a remote transition handler. */ oneway void unregisterRemote(in RemoteTransition remoteTransition) = 2; + + /** + * Retrieves the apply-token used by transactions in Shell + */ + IBinder getShellApplyToken() = 3; } diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/Transitions.java b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/Transitions.java index 26d0ec637ccf..d2e8624171f6 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/Transitions.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/Transitions.java @@ -219,6 +219,8 @@ public class Transitions implements RemoteCallable<Transitions> { + "use ShellInit callbacks to ensure proper ordering"); } mHandlers.add(handler); + // Set initial scale settings. + handler.setAnimScaleSetting(mTransitionAnimationScaleSetting); ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TRANSITIONS, "addHandler: %s", handler.getClass().getSimpleName()); } @@ -956,6 +958,11 @@ public class Transitions implements RemoteCallable<Transitions> { transitions.mRemoteTransitionHandler.removeFiltered(remoteTransition); }); } + + @Override + public IBinder getShellApplyToken() { + return SurfaceControl.Transaction.getDefaultApplyToken(); + } } private class SettingsObserver extends ContentObserver { diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CaptionWindowDecoration.java b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CaptionWindowDecoration.java index dc3deb1a927c..8b13721ef428 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CaptionWindowDecoration.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CaptionWindowDecoration.java @@ -142,7 +142,7 @@ public class CaptionWindowDecoration extends WindowDecoration<WindowDecorLinearL return; } - if (oldDecorationSurface != mDecorationContainerSurface) { + if (oldDecorationSurface != mDecorationContainerSurface || mDragResizeListener == null) { closeDragResizeListener(); mDragResizeListener = new DragResizeInputListener( mContext, diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/CommonAssertions.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/CommonAssertions.kt index 330c9c95e484..cb74315732ab 100644 --- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/CommonAssertions.kt +++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/CommonAssertions.kt @@ -20,6 +20,7 @@ package com.android.wm.shell.flicker import android.view.Surface import com.android.server.wm.flicker.FlickerTestParameter import com.android.server.wm.flicker.helpers.WindowUtils +import com.android.server.wm.flicker.traces.layers.LayerTraceEntrySubject import com.android.server.wm.flicker.traces.layers.LayersTraceSubject import com.android.server.wm.traces.common.IComponentMatcher import com.android.server.wm.traces.common.region.Region @@ -94,25 +95,27 @@ fun FlickerTestParameter.layerKeepVisible( fun FlickerTestParameter.splitAppLayerBoundsBecomesVisible( component: IComponentMatcher, - splitLeftTop: Boolean + landscapePosLeft: Boolean, + portraitPosTop: Boolean ) { assertLayers { - this.isInvisible(component) + this.notContains(SPLIT_SCREEN_DIVIDER_COMPONENT.or(component), isOptional = true) .then() - .isInvisible(SPLIT_SCREEN_DIVIDER_COMPONENT) - .isVisible(component) + .isInvisible(SPLIT_SCREEN_DIVIDER_COMPONENT.or(component)) .then() - .isVisible(SPLIT_SCREEN_DIVIDER_COMPONENT) - .splitAppLayerBoundsSnapToDivider(component, splitLeftTop, endRotation) + .splitAppLayerBoundsSnapToDivider( + component, landscapePosLeft, portraitPosTop, endRotation) } } fun FlickerTestParameter.splitAppLayerBoundsBecomesInvisible( component: IComponentMatcher, - splitLeftTop: Boolean + landscapePosLeft: Boolean, + portraitPosTop: Boolean ) { assertLayers { - this.splitAppLayerBoundsSnapToDivider(component, splitLeftTop, endRotation) + this.splitAppLayerBoundsSnapToDivider( + component, landscapePosLeft, portraitPosTop, endRotation) .then() .isVisible(component, true) .then() @@ -122,58 +125,96 @@ fun FlickerTestParameter.splitAppLayerBoundsBecomesInvisible( fun FlickerTestParameter.splitAppLayerBoundsIsVisibleAtEnd( component: IComponentMatcher, - splitLeftTop: Boolean + landscapePosLeft: Boolean, + portraitPosTop: Boolean ) { assertLayersEnd { - val dividerRegion = layer(SPLIT_SCREEN_DIVIDER_COMPONENT).visibleRegion.region - visibleRegion(component).coversAtMost( - if (splitLeftTop) { - getSplitLeftTopRegion(dividerRegion, endRotation) - } else { - getSplitRightBottomRegion(dividerRegion, endRotation) - } - ) + splitAppLayerBoundsSnapToDivider(component, landscapePosLeft, portraitPosTop, endRotation) } } fun FlickerTestParameter.splitAppLayerBoundsKeepVisible( component: IComponentMatcher, - splitLeftTop: Boolean + landscapePosLeft: Boolean, + portraitPosTop: Boolean ) { assertLayers { - this.splitAppLayerBoundsSnapToDivider(component, splitLeftTop, endRotation) + splitAppLayerBoundsSnapToDivider(component, landscapePosLeft, portraitPosTop, endRotation) } } fun FlickerTestParameter.splitAppLayerBoundsChanges( component: IComponentMatcher, - splitLeftTop: Boolean + landscapePosLeft: Boolean, + portraitPosTop: Boolean ) { assertLayers { - if (splitLeftTop) { - this.splitAppLayerBoundsSnapToDivider(component, splitLeftTop, endRotation) + if (landscapePosLeft) { + this.splitAppLayerBoundsSnapToDivider( + component, landscapePosLeft, portraitPosTop, endRotation) .then() .isInvisible(component) .then() - .splitAppLayerBoundsSnapToDivider(component, splitLeftTop, endRotation) + .splitAppLayerBoundsSnapToDivider( + component, landscapePosLeft, portraitPosTop, endRotation) } else { - this.splitAppLayerBoundsSnapToDivider(component, splitLeftTop, endRotation) + this.splitAppLayerBoundsSnapToDivider( + component, landscapePosLeft, portraitPosTop, endRotation) } } } fun LayersTraceSubject.splitAppLayerBoundsSnapToDivider( component: IComponentMatcher, - splitLeftTop: Boolean, + landscapePosLeft: Boolean, + portraitPosTop: Boolean, rotation: Int ): LayersTraceSubject { return invoke("splitAppLayerBoundsSnapToDivider") { - val dividerRegion = it.layer(SPLIT_SCREEN_DIVIDER_COMPONENT).visibleRegion.region - it.visibleRegion(component).coversAtMost( - if (splitLeftTop) { - getSplitLeftTopRegion(dividerRegion, rotation) + it.splitAppLayerBoundsSnapToDivider(component, landscapePosLeft, portraitPosTop, rotation) + } +} + +fun LayerTraceEntrySubject.splitAppLayerBoundsSnapToDivider( + component: IComponentMatcher, + landscapePosLeft: Boolean, + portraitPosTop: Boolean, + rotation: Int +): LayerTraceEntrySubject { + val displayBounds = WindowUtils.getDisplayBounds(rotation) + return invoke { + val dividerRegion = layer(SPLIT_SCREEN_DIVIDER_COMPONENT).visibleRegion.region + visibleRegion(component).coversAtMost( + if (displayBounds.width > displayBounds.height) { + if (landscapePosLeft) { + Region.from( + 0, + 0, + (dividerRegion.bounds.left + dividerRegion.bounds.right) / 2, + displayBounds.bounds.bottom) + } else { + Region.from( + (dividerRegion.bounds.left + dividerRegion.bounds.right) / 2, + 0, + displayBounds.bounds.right, + displayBounds.bounds.bottom + ) + } } else { - getSplitRightBottomRegion(dividerRegion, rotation) + if (portraitPosTop) { + Region.from( + 0, + 0, + displayBounds.bounds.right, + (dividerRegion.bounds.top + dividerRegion.bounds.bottom) / 2) + } else { + Region.from( + 0, + (dividerRegion.bounds.top + dividerRegion.bounds.bottom) / 2, + displayBounds.bounds.right, + displayBounds.bounds.bottom + ) + } } ) } @@ -185,6 +226,10 @@ fun FlickerTestParameter.appWindowBecomesVisible( assertWm { this.isAppWindowInvisible(component) .then() + .notContains(component, isOptional = true) + .then() + .isAppWindowInvisible(component, isOptional = true) + .then() .isAppWindowVisible(component) } } @@ -208,7 +253,7 @@ fun FlickerTestParameter.appWindowIsVisibleAtEnd( } fun FlickerTestParameter.appWindowKeepVisible( - component: IComponentMatcher + component: IComponentMatcher ) { assertWm { this.isAppWindowVisible(component) @@ -316,39 +361,3 @@ fun getSecondaryRegion(dividerRegion: Region, rotation: Int): Region { ) } } - -fun getSplitLeftTopRegion(dividerRegion: Region, rotation: Int): Region { - val displayBounds = WindowUtils.getDisplayBounds(rotation) - return if (displayBounds.width > displayBounds.height) { - Region.from( - 0, - 0, - (dividerRegion.bounds.left + dividerRegion.bounds.right) / 2, - displayBounds.bounds.bottom) - } else { - Region.from( - 0, - 0, - displayBounds.bounds.right, - (dividerRegion.bounds.top + dividerRegion.bounds.bottom) / 2) - } -} - -fun getSplitRightBottomRegion(dividerRegion: Region, rotation: Int): Region { - val displayBounds = WindowUtils.getDisplayBounds(rotation) - return if (displayBounds.width > displayBounds.height) { - Region.from( - (dividerRegion.bounds.left + dividerRegion.bounds.right) / 2, - 0, - displayBounds.bounds.right, - displayBounds.bounds.bottom - ) - } else { - Region.from( - 0, - (dividerRegion.bounds.top + dividerRegion.bounds.bottom) / 2, - displayBounds.bounds.right, - displayBounds.bounds.bottom - ) - } -} diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/bubble/MultiBubblesScreen.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/bubble/MultiBubblesScreen.kt index 1950e486f34b..3ad92f87421b 100644 --- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/bubble/MultiBubblesScreen.kt +++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/bubble/MultiBubblesScreen.kt @@ -21,6 +21,7 @@ import android.platform.test.annotations.Postsubmit import android.platform.test.annotations.Presubmit import androidx.test.filters.RequiresDevice import androidx.test.uiautomator.By +import androidx.test.uiautomator.UiObject2 import androidx.test.uiautomator.Until import com.android.server.wm.flicker.FlickerParametersRunnerFactory import com.android.server.wm.flicker.FlickerTestParameter @@ -58,26 +59,27 @@ open class MultiBubblesScreen(testSpec: FlickerTestParameter) : BaseBubbleScreen setup { test { for (i in 1..3) { - val addBubbleBtn = waitAndGetAddBubbleBtn() - addBubbleBtn?.run { addBubbleBtn.click() } ?: error("Add Bubble not found") + val addBubbleBtn = waitAndGetAddBubbleBtn() ?: error("Add Bubble not found") + addBubbleBtn.click() + SystemClock.sleep(1000) } val showBubble = device.wait( Until.findObject( By.res(SYSTEM_UI_PACKAGE, BUBBLE_RES_NAME) ), FIND_OBJECT_TIMEOUT - ) - showBubble?.run { showBubble.click() } ?: error("Show bubble not found") + ) ?: error("Show bubble not found") + showBubble.click() SystemClock.sleep(1000) } } transitions { - val bubbles = device.wait( + val bubbles: List<UiObject2> = device.wait( Until.findObjects( By.res(SYSTEM_UI_PACKAGE, BUBBLE_RES_NAME) ), FIND_OBJECT_TIMEOUT ) ?: error("No bubbles found") for (entry in bubbles) { - entry?.run { entry.click() } ?: error("Bubble not found") + entry.click() SystemClock.sleep(1000) } } diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/helpers/SplitScreenHelper.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/helpers/SplitScreenHelper.kt index 240e8711d43e..e7f9d9a9d73d 100644 --- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/helpers/SplitScreenHelper.kt +++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/helpers/SplitScreenHelper.kt @@ -105,6 +105,25 @@ class SplitScreenHelper( .waitForAndVerify() } + fun splitFromOverview(tapl: LauncherInstrumentation) { + // Note: The initial split position in landscape is different between tablet and phone. + // In landscape, tablet will let the first app split to right side, and phone will + // split to left side. + if (tapl.isTablet) { + tapl.workspace.switchToOverview().overviewActions + .clickSplit() + .currentTask + .open() + } else { + tapl.workspace.switchToOverview().currentTask + .tapMenu() + .tapSplitMenuItem() + .currentTask + .open() + } + SystemClock.sleep(TIMEOUT_MS) + } + fun dragFromNotificationToSplit( instrumentation: Instrumentation, device: UiDevice, diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/CopyContentInSplit.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/CopyContentInSplit.kt index f69107eae638..d23881475ad6 100644 --- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/CopyContentInSplit.kt +++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/CopyContentInSplit.kt @@ -92,12 +92,12 @@ class CopyContentInSplit(testSpec: FlickerTestParameter) : SplitScreenBase(testS @Presubmit @Test fun primaryAppBoundsKeepVisible() = testSpec.splitAppLayerBoundsKeepVisible( - primaryApp, splitLeftTop = true) + primaryApp, landscapePosLeft = true, portraitPosTop = true) @Presubmit @Test fun textEditAppBoundsKeepVisible() = testSpec.splitAppLayerBoundsKeepVisible( - textEditApp, splitLeftTop = false) + textEditApp, landscapePosLeft = false, portraitPosTop = false) @Presubmit @Test diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByDivider.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByDivider.kt index cd92db74af95..ba40c2740bb1 100644 --- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByDivider.kt +++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByDivider.kt @@ -98,7 +98,7 @@ class DismissSplitScreenByDivider (testSpec: FlickerTestParameter) : SplitScreen @Presubmit @Test fun primaryAppBoundsBecomesInvisible() = testSpec.splitAppLayerBoundsBecomesInvisible( - primaryApp, splitLeftTop = false) + primaryApp, landscapePosLeft = false, portraitPosTop = false) @Presubmit @Test diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByGoHome.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByGoHome.kt index 127ac1e7162b..6828589656d6 100644 --- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByGoHome.kt +++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DismissSplitScreenByGoHome.kt @@ -96,12 +96,12 @@ class DismissSplitScreenByGoHome( @Presubmit @Test fun primaryAppBoundsBecomesInvisible() = testSpec.splitAppLayerBoundsBecomesInvisible( - primaryApp, splitLeftTop = false) + primaryApp, landscapePosLeft = false, portraitPosTop = false) @Presubmit @Test fun secondaryAppBoundsBecomesInvisible() = testSpec.splitAppLayerBoundsBecomesInvisible( - secondaryApp, splitLeftTop = true) + secondaryApp, landscapePosLeft = true, portraitPosTop = true) @Presubmit @Test diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DragDividerToResize.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DragDividerToResize.kt index 0f4d98d69c00..9ac7c230096b 100644 --- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DragDividerToResize.kt +++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/DragDividerToResize.kt @@ -108,12 +108,12 @@ class DragDividerToResize (testSpec: FlickerTestParameter) : SplitScreenBase(tes @Presubmit @Test fun primaryAppBoundsChanges() = testSpec.splitAppLayerBoundsChanges( - primaryApp, splitLeftTop = false) + primaryApp, landscapePosLeft = false, portraitPosTop = false) @Presubmit @Test fun secondaryAppBoundsChanges() = testSpec.splitAppLayerBoundsChanges( - secondaryApp, splitLeftTop = true) + secondaryApp, landscapePosLeft = true, portraitPosTop = true) /** {@inheritDoc} */ @Postsubmit diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromAllApps.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromAllApps.kt index 9564d975194b..8401c1a910b8 100644 --- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromAllApps.kt +++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromAllApps.kt @@ -94,12 +94,12 @@ class EnterSplitScreenByDragFromAllApps( @Presubmit @Test fun primaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd( - primaryApp, splitLeftTop = false) + primaryApp, landscapePosLeft = false, portraitPosTop = false) @Presubmit @Test fun secondaryAppBoundsBecomesVisible() = testSpec.splitAppLayerBoundsBecomesVisible( - secondaryApp, splitLeftTop = true) + secondaryApp, landscapePosLeft = true, portraitPosTop = true) @Presubmit @Test diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromNotification.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromNotification.kt index 3b59716180b6..168afda119a9 100644 --- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromNotification.kt +++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromNotification.kt @@ -109,12 +109,12 @@ class EnterSplitScreenByDragFromNotification( @Presubmit @Test fun primaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd( - primaryApp, splitLeftTop = false) + primaryApp, landscapePosLeft = false, portraitPosTop = false) @Presubmit @Test fun secondaryAppBoundsBecomesVisible() = testSpec.splitAppLayerBoundsBecomesVisible( - sendNotificationApp, splitLeftTop = true) + sendNotificationApp, landscapePosLeft = true, portraitPosTop = true) @Presubmit @Test diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromTaskbar.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromTaskbar.kt index 3de98723e132..c1fce5f40b57 100644 --- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromTaskbar.kt +++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenByDragFromTaskbar.kt @@ -97,12 +97,12 @@ class EnterSplitScreenByDragFromTaskbar( @Presubmit @Test fun primaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd( - primaryApp, splitLeftTop = false) + primaryApp, landscapePosLeft = false, portraitPosTop = false) @Presubmit @Test fun secondaryAppBoundsBecomesVisible() = testSpec.splitAppLayerBoundsBecomesVisible( - secondaryApp, splitLeftTop = true) + secondaryApp, landscapePosLeft = true, portraitPosTop = true) @Presubmit @Test diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenFromOverview.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenFromOverview.kt new file mode 100644 index 000000000000..8cb5d7c24ced --- /dev/null +++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/EnterSplitScreenFromOverview.kt @@ -0,0 +1,177 @@ +/* + * 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.wm.shell.flicker.splitscreen + +import android.platform.test.annotations.Postsubmit +import android.platform.test.annotations.Presubmit +import androidx.test.filters.RequiresDevice +import com.android.server.wm.flicker.FlickerParametersRunnerFactory +import com.android.server.wm.flicker.FlickerTestParameter +import com.android.server.wm.flicker.FlickerTestParameterFactory +import com.android.server.wm.flicker.annotation.Group1 +import com.android.server.wm.flicker.dsl.FlickerBuilder +import com.android.wm.shell.flicker.appWindowBecomesVisible +import com.android.wm.shell.flicker.helpers.SplitScreenHelper +import com.android.wm.shell.flicker.layerBecomesVisible +import com.android.wm.shell.flicker.layerIsVisibleAtEnd +import com.android.wm.shell.flicker.splitAppLayerBoundsBecomesVisible +import com.android.wm.shell.flicker.splitAppLayerBoundsIsVisibleAtEnd +import com.android.wm.shell.flicker.splitScreenDividerBecomesVisible +import org.junit.FixMethodOrder +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.MethodSorters +import org.junit.runners.Parameterized + +/** + * Test enter split screen from Overview. + * + * To run this test: `atest WMShellFlickerTests:EnterSplitScreenFromOverview` + */ +@RequiresDevice +@RunWith(Parameterized::class) +@Parameterized.UseParametersRunnerFactory(FlickerParametersRunnerFactory::class) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@Group1 +class EnterSplitScreenFromOverview(testSpec: FlickerTestParameter) : SplitScreenBase(testSpec) { + + override val transition: FlickerBuilder.() -> Unit + get() = { + super.transition(this) + setup { + eachRun { + tapl.workspace.switchToOverview().dismissAllTasks() + primaryApp.launchViaIntent(wmHelper) + secondaryApp.launchViaIntent(wmHelper) + tapl.goHome() + wmHelper.StateSyncBuilder() + .withAppTransitionIdle() + .withHomeActivityVisible() + .waitForAndVerify() + } + } + transitions { + SplitScreenHelper.splitFromOverview(tapl) + SplitScreenHelper.waitForSplitComplete(wmHelper, primaryApp, secondaryApp) + } + } + + @Presubmit + @Test + fun splitScreenDividerBecomesVisible() = testSpec.splitScreenDividerBecomesVisible() + + @Presubmit + @Test + fun primaryAppLayerIsVisibleAtEnd() = testSpec.layerIsVisibleAtEnd(primaryApp) + + @Presubmit + @Test + fun secondaryAppLayerBecomesVisible() = testSpec.layerBecomesVisible(secondaryApp) + + @Presubmit + @Test + fun primaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd( + primaryApp, landscapePosLeft = tapl.isTablet, portraitPosTop = false) + + @Presubmit + @Test + fun secondaryAppBoundsBecomesVisible() = testSpec.splitAppLayerBoundsBecomesVisible( + secondaryApp, landscapePosLeft = !tapl.isTablet, portraitPosTop = true) + + @Presubmit + @Test + fun primaryAppWindowBecomesVisible() = testSpec.appWindowBecomesVisible(primaryApp) + + @Presubmit + @Test + fun secondaryAppWindowBecomesVisible() = testSpec.appWindowBecomesVisible(secondaryApp) + + /** {@inheritDoc} */ + @Postsubmit + @Test + override fun entireScreenCovered() = + super.entireScreenCovered() + + /** {@inheritDoc} */ + @Postsubmit + @Test + override fun navBarLayerIsVisibleAtStartAndEnd() = + super.navBarLayerIsVisibleAtStartAndEnd() + + /** {@inheritDoc} */ + @Postsubmit + @Test + override fun navBarLayerPositionAtStartAndEnd() = + super.navBarLayerPositionAtStartAndEnd() + + /** {@inheritDoc} */ + @Postsubmit + @Test + override fun navBarWindowIsAlwaysVisible() = + super.navBarWindowIsAlwaysVisible() + + /** {@inheritDoc} */ + @Postsubmit + @Test + override fun statusBarLayerIsVisibleAtStartAndEnd() = + super.statusBarLayerIsVisibleAtStartAndEnd() + + /** {@inheritDoc} */ + @Postsubmit + @Test + override fun statusBarLayerPositionAtStartAndEnd() = + super.statusBarLayerPositionAtStartAndEnd() + + /** {@inheritDoc} */ + @Postsubmit + @Test + override fun statusBarWindowIsAlwaysVisible() = + super.statusBarWindowIsAlwaysVisible() + + /** {@inheritDoc} */ + @Postsubmit + @Test + override fun taskBarLayerIsVisibleAtStartAndEnd() = + super.taskBarLayerIsVisibleAtStartAndEnd() + + /** {@inheritDoc} */ + @Postsubmit + @Test + override fun taskBarWindowIsAlwaysVisible() = + super.taskBarWindowIsAlwaysVisible() + + /** {@inheritDoc} */ + @Postsubmit + @Test + override fun visibleLayersShownMoreThanOneConsecutiveEntry() = + super.visibleLayersShownMoreThanOneConsecutiveEntry() + + /** {@inheritDoc} */ + @Postsubmit + @Test + override fun visibleWindowsShownMoreThanOneConsecutiveEntry() = + super.visibleWindowsShownMoreThanOneConsecutiveEntry() + + companion object { + @Parameterized.Parameters(name = "{0}") + @JvmStatic + fun getParams(): List<FlickerTestParameter> { + return FlickerTestParameterFactory.getInstance().getConfigNonRotationTests( + repetitions = SplitScreenHelper.TEST_REPETITIONS) + } + } +} diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchAppByDoubleTapDivider.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchAppByDoubleTapDivider.kt index bdfd9c7de32f..153056188d24 100644 --- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchAppByDoubleTapDivider.kt +++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchAppByDoubleTapDivider.kt @@ -94,12 +94,12 @@ class SwitchAppByDoubleTapDivider (testSpec: FlickerTestParameter) : SplitScreen @Presubmit @Test fun primaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd( - primaryApp, splitLeftTop = true) + primaryApp, landscapePosLeft = true, portraitPosTop = true) @Presubmit @Test fun secondaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd( - secondaryApp, splitLeftTop = false) + secondaryApp, landscapePosLeft = false, portraitPosTop = false) @Presubmit @Test diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromAnotherApp.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromAnotherApp.kt index da954d97aec2..20544bd2fc2f 100644 --- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromAnotherApp.kt +++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromAnotherApp.kt @@ -98,12 +98,12 @@ class SwitchBackToSplitFromAnotherApp(testSpec: FlickerTestParameter) : SplitScr @Presubmit @Test fun primaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd( - primaryApp, splitLeftTop = false) + primaryApp, landscapePosLeft = false, portraitPosTop = false) @Presubmit @Test fun secondaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd( - secondaryApp, splitLeftTop = true) + secondaryApp, landscapePosLeft = true, portraitPosTop = true) @Presubmit @Test diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromHome.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromHome.kt index db89ff52178b..5a8604f2dccc 100644 --- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromHome.kt +++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromHome.kt @@ -97,12 +97,12 @@ class SwitchBackToSplitFromHome(testSpec: FlickerTestParameter) : SplitScreenBas @Presubmit @Test fun primaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd( - primaryApp, splitLeftTop = false) + primaryApp, landscapePosLeft = false, portraitPosTop = false) @Presubmit @Test fun secondaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd( - secondaryApp, splitLeftTop = true) + secondaryApp, landscapePosLeft = true, portraitPosTop = true) @Presubmit @Test diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromRecent.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromRecent.kt index c23cdb610671..adea66a49c46 100644 --- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromRecent.kt +++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/splitscreen/SwitchBackToSplitFromRecent.kt @@ -99,12 +99,12 @@ class SwitchBackToSplitFromRecent(testSpec: FlickerTestParameter) : SplitScreenB @Presubmit @Test fun primaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd( - primaryApp, splitLeftTop = false) + primaryApp, landscapePosLeft = false, portraitPosTop = false) @Presubmit @Test fun secondaryAppBoundsIsVisibleAtEnd() = testSpec.splitAppLayerBoundsIsVisibleAtEnd( - secondaryApp, splitLeftTop = true) + secondaryApp, landscapePosLeft = true, portraitPosTop = true) @Presubmit @Test diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationRunnerTests.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationRunnerTests.java new file mode 100644 index 000000000000..b2e45a6b3a5c --- /dev/null +++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationRunnerTests.java @@ -0,0 +1,79 @@ +/* + * 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.wm.shell.activityembedding; + +import static android.view.WindowManager.TRANSIT_OPEN; +import static android.window.TransitionInfo.FLAG_IS_EMBEDDED; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +import android.window.TransitionInfo; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.filters.SmallTest; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; + +/** + * Tests for {@link ActivityEmbeddingAnimationRunner}. + * + * Build/Install/Run: + * atest WMShellUnitTests:ActivityEmbeddingAnimationRunnerTests + */ +@SmallTest +@RunWith(AndroidJUnit4.class) +public class ActivityEmbeddingAnimationRunnerTests extends ActivityEmbeddingAnimationTestBase { + + @Before + public void setup() { + super.setUp(); + doNothing().when(mController).onAnimationFinished(any()); + } + + @Test + public void testStartAnimation() { + final TransitionInfo info = new TransitionInfo(TRANSIT_OPEN, 0); + final TransitionInfo.Change embeddingChange = createChange(); + embeddingChange.setFlags(FLAG_IS_EMBEDDED); + info.addChange(embeddingChange); + doReturn(mAnimator).when(mAnimRunner).createAnimator(any(), any(), any(), any()); + + mAnimRunner.startAnimation(mTransition, info, mStartTransaction, mFinishTransaction); + + final ArgumentCaptor<Runnable> finishCallback = ArgumentCaptor.forClass(Runnable.class); + verify(mAnimRunner).createAnimator(eq(info), eq(mStartTransaction), eq(mFinishTransaction), + finishCallback.capture()); + verify(mStartTransaction).apply(); + verify(mAnimator).start(); + verifyNoMoreInteractions(mFinishTransaction); + verify(mController, never()).onAnimationFinished(any()); + + // Call onAnimationFinished() when the animation is finished. + finishCallback.getValue().run(); + + verify(mController).onAnimationFinished(mTransition); + } +} diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationTestBase.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationTestBase.java new file mode 100644 index 000000000000..84befdddabdb --- /dev/null +++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationTestBase.java @@ -0,0 +1,83 @@ +/* + * 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.wm.shell.activityembedding; + +import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assume.assumeTrue; +import static org.mockito.Mockito.mock; + +import android.animation.Animator; +import android.annotation.CallSuper; +import android.os.IBinder; +import android.view.SurfaceControl; +import android.window.TransitionInfo; +import android.window.WindowContainerToken; + +import com.android.wm.shell.ShellTestCase; +import com.android.wm.shell.sysui.ShellInit; +import com.android.wm.shell.transition.Transitions; + +import org.junit.Before; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +/** TestBase for ActivityEmbedding animation. */ +abstract class ActivityEmbeddingAnimationTestBase extends ShellTestCase { + + @Mock + ShellInit mShellInit; + @Mock + Transitions mTransitions; + @Mock + IBinder mTransition; + @Mock + SurfaceControl.Transaction mStartTransaction; + @Mock + SurfaceControl.Transaction mFinishTransaction; + @Mock + Transitions.TransitionFinishCallback mFinishCallback; + @Mock + Animator mAnimator; + + ActivityEmbeddingController mController; + ActivityEmbeddingAnimationRunner mAnimRunner; + ActivityEmbeddingAnimationSpec mAnimSpec; + + @CallSuper + @Before + public void setUp() { + assumeTrue(Transitions.ENABLE_SHELL_TRANSITIONS); + MockitoAnnotations.initMocks(this); + mController = ActivityEmbeddingController.create(mContext, mShellInit, mTransitions); + assertNotNull(mController); + mAnimRunner = mController.mAnimationRunner; + assertNotNull(mAnimRunner); + mAnimSpec = mAnimRunner.mAnimationSpec; + assertNotNull(mAnimSpec); + spyOn(mController); + spyOn(mAnimRunner); + spyOn(mAnimSpec); + } + + /** Creates a mock {@link TransitionInfo.Change}. */ + static TransitionInfo.Change createChange() { + return new TransitionInfo.Change(mock(WindowContainerToken.class), + mock(SurfaceControl.class)); + } +} diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingControllerTests.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingControllerTests.java index bfe3b5468085..cf43b0030d2a 100644 --- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingControllerTests.java +++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/activityembedding/ActivityEmbeddingControllerTests.java @@ -16,52 +16,117 @@ package com.android.wm.shell.activityembedding; -import static com.android.dx.mockito.inline.extended.ExtendedMockito.spy; +import static android.view.WindowManager.TRANSIT_OPEN; +import static android.window.TransitionInfo.FLAG_IS_EMBEDDED; -import static org.junit.Assume.assumeTrue; +import static com.android.dx.mockito.inline.extended.ExtendedMockito.never; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.times; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; -import android.content.Context; +import android.window.TransitionInfo; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.SmallTest; -import com.android.wm.shell.ShellTestCase; -import com.android.wm.shell.sysui.ShellInit; -import com.android.wm.shell.transition.Transitions; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; /** - * Tests for the activity embedding controller. + * Tests for {@link ActivityEmbeddingController}. * * Build/Install/Run: * atest WMShellUnitTests:ActivityEmbeddingControllerTests */ @SmallTest @RunWith(AndroidJUnit4.class) -public class ActivityEmbeddingControllerTests extends ShellTestCase { - - private @Mock Context mContext; - private @Mock ShellInit mShellInit; - private @Mock Transitions mTransitions; - private ActivityEmbeddingController mController; +public class ActivityEmbeddingControllerTests extends ActivityEmbeddingAnimationTestBase { @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - mController = spy(new ActivityEmbeddingController(mContext, mShellInit, mTransitions)); + public void setup() { + super.setUp(); + doReturn(mAnimator).when(mAnimRunner).createAnimator(any(), any(), any(), any()); } @Test - public void instantiate_addInitCallback() { - assumeTrue(Transitions.ENABLE_SHELL_TRANSITIONS); - verify(mShellInit, times(1)).addInitCallback(any(), any()); + public void testInstantiate() { + verify(mShellInit).addInitCallback(any(), any()); + } + + @Test + public void testOnInit() { + mController.onInit(); + + verify(mTransitions).addHandler(mController); + } + + @Test + public void testSetAnimScaleSetting() { + mController.setAnimScaleSetting(1.0f); + + verify(mAnimRunner).setAnimScaleSetting(1.0f); + verify(mAnimSpec).setAnimScaleSetting(1.0f); + } + + @Test + public void testStartAnimation_containsNonActivityEmbeddingChange() { + final TransitionInfo info = new TransitionInfo(TRANSIT_OPEN, 0); + final TransitionInfo.Change embeddingChange = createChange(); + embeddingChange.setFlags(FLAG_IS_EMBEDDED); + final TransitionInfo.Change nonEmbeddingChange = createChange(); + info.addChange(embeddingChange); + info.addChange(nonEmbeddingChange); + + // No-op + assertFalse(mController.startAnimation(mTransition, info, mStartTransaction, + mFinishTransaction, mFinishCallback)); + verify(mAnimRunner, never()).startAnimation(any(), any(), any(), any()); + verifyNoMoreInteractions(mStartTransaction); + verifyNoMoreInteractions(mFinishTransaction); + verifyNoMoreInteractions(mFinishCallback); + } + + @Test + public void testStartAnimation_onlyActivityEmbeddingChange() { + final TransitionInfo info = new TransitionInfo(TRANSIT_OPEN, 0); + final TransitionInfo.Change embeddingChange = createChange(); + embeddingChange.setFlags(FLAG_IS_EMBEDDED); + info.addChange(embeddingChange); + + // No-op + assertTrue(mController.startAnimation(mTransition, info, mStartTransaction, + mFinishTransaction, mFinishCallback)); + verify(mAnimRunner).startAnimation(mTransition, info, mStartTransaction, + mFinishTransaction); + verify(mStartTransaction).apply(); + verifyNoMoreInteractions(mFinishTransaction); + } + + @Test + public void testOnAnimationFinished() { + // Should not call finish when there is no transition. + assertThrows(IllegalStateException.class, + () -> mController.onAnimationFinished(mTransition)); + + final TransitionInfo info = new TransitionInfo(TRANSIT_OPEN, 0); + final TransitionInfo.Change embeddingChange = createChange(); + embeddingChange.setFlags(FLAG_IS_EMBEDDED); + info.addChange(embeddingChange); + mController.startAnimation(mTransition, info, mStartTransaction, + mFinishTransaction, mFinishCallback); + + verify(mFinishCallback, never()).onTransitionFinished(any(), any()); + mController.onAnimationFinished(mTransition); + verify(mFinishCallback).onTransitionFinished(any(), any()); + + // Should not call finish when the finish has already been called. + assertThrows(IllegalStateException.class, + () -> mController.onAnimationFinished(mTransition)); } } diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/onehanded/OneHandedControllerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/onehanded/OneHandedControllerTest.java index 90645ce4747d..cf8297eec061 100644 --- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/onehanded/OneHandedControllerTest.java +++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/onehanded/OneHandedControllerTest.java @@ -171,6 +171,11 @@ public class OneHandedControllerTest extends OneHandedTestCase { } @Test + public void testControllerRegistersUserChangeListener() { + verify(mMockShellController, times(1)).addUserChangeListener(any()); + } + + @Test public void testDefaultShouldNotInOneHanded() { // Assert default transition state is STATE_NONE assertThat(mSpiedTransitionState.getState()).isEqualTo(STATE_NONE); diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipControllerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipControllerTest.java index 9ed8d84d665f..eb5726bebb74 100644 --- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipControllerTest.java +++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipControllerTest.java @@ -23,6 +23,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -77,9 +78,9 @@ import java.util.Set; public class PipControllerTest extends ShellTestCase { private PipController mPipController; private ShellInit mShellInit; + private ShellController mShellController; @Mock private ShellCommandHandler mMockShellCommandHandler; - @Mock private ShellController mMockShellController; @Mock private DisplayController mMockDisplayController; @Mock private PhonePipMenuController mMockPhonePipMenuController; @Mock private PipAppOpsListener mMockPipAppOpsListener; @@ -110,8 +111,10 @@ public class PipControllerTest extends ShellTestCase { return null; }).when(mMockExecutor).execute(any()); mShellInit = spy(new ShellInit(mMockExecutor)); + mShellController = spy(new ShellController(mShellInit, mMockShellCommandHandler, + mMockExecutor)); mPipController = new PipController(mContext, mShellInit, mMockShellCommandHandler, - mMockShellController, mMockDisplayController, mMockPipAppOpsListener, + mShellController, mMockDisplayController, mMockPipAppOpsListener, mMockPipBoundsAlgorithm, mMockPipKeepClearAlgorithm, mMockPipBoundsState, mMockPipMotionHelper, mMockPipMediaController, mMockPhonePipMenuController, mMockPipTaskOrganizer, mMockPipTransitionState, @@ -135,12 +138,22 @@ public class PipControllerTest extends ShellTestCase { @Test public void instantiatePipController_registerConfigChangeListener() { - verify(mMockShellController, times(1)).addConfigurationChangeListener(any()); + verify(mShellController, times(1)).addConfigurationChangeListener(any()); } @Test public void instantiatePipController_registerKeyguardChangeListener() { - verify(mMockShellController, times(1)).addKeyguardChangeListener(any()); + verify(mShellController, times(1)).addKeyguardChangeListener(any()); + } + + @Test + public void instantiatePipController_registerUserChangeListener() { + verify(mShellController, times(1)).addUserChangeListener(any()); + } + + @Test + public void instantiatePipController_registerMediaListener() { + verify(mMockPipMediaController, times(1)).registerSessionListenerForCurrentUser(); } @Test @@ -167,7 +180,7 @@ public class PipControllerTest extends ShellTestCase { ShellInit shellInit = new ShellInit(mMockExecutor); assertNull(PipController.create(spyContext, shellInit, mMockShellCommandHandler, - mMockShellController, mMockDisplayController, mMockPipAppOpsListener, + mShellController, mMockDisplayController, mMockPipAppOpsListener, mMockPipBoundsAlgorithm, mMockPipKeepClearAlgorithm, mMockPipBoundsState, mMockPipMotionHelper, mMockPipMediaController, mMockPhonePipMenuController, mMockPipTaskOrganizer, mMockPipTransitionState, @@ -264,4 +277,11 @@ public class PipControllerTest extends ShellTestCase { verify(mMockPipBoundsState).setKeepClearAreas(Set.of(keepClearArea), Set.of()); } + + @Test + public void onUserChangeRegisterMediaListener() { + reset(mMockPipMediaController); + mShellController.asShell().onUserChanged(100, mContext); + verify(mMockPipMediaController, times(1)).registerSessionListenerForCurrentUser(); + } } diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/sysui/ShellControllerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/sysui/ShellControllerTest.java index 39e58ffcf9c7..d6ddba9e927d 100644 --- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/sysui/ShellControllerTest.java +++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/sysui/ShellControllerTest.java @@ -17,11 +17,15 @@ package com.android.wm.shell.sysui; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import android.content.Context; +import android.content.pm.UserInfo; import android.content.res.Configuration; import android.testing.AndroidTestingRunner; import android.testing.TestableLooper; +import androidx.annotation.NonNull; import androidx.test.filters.SmallTest; import androidx.test.platform.app.InstrumentationRegistry; @@ -35,6 +39,8 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import java.util.ArrayList; +import java.util.List; import java.util.Locale; @SmallTest @@ -42,22 +48,29 @@ import java.util.Locale; @TestableLooper.RunWithLooper(setAsMainLooper = true) public class ShellControllerTest extends ShellTestCase { + private static final int TEST_USER_ID = 100; + @Mock private ShellInit mShellInit; @Mock private ShellCommandHandler mShellCommandHandler; @Mock private ShellExecutor mExecutor; + @Mock + private Context mTestUserContext; private ShellController mController; private TestConfigurationChangeListener mConfigChangeListener; private TestKeyguardChangeListener mKeyguardChangeListener; + private TestUserChangeListener mUserChangeListener; + @Before public void setUp() { MockitoAnnotations.initMocks(this); mKeyguardChangeListener = new TestKeyguardChangeListener(); mConfigChangeListener = new TestConfigurationChangeListener(); + mUserChangeListener = new TestUserChangeListener(); mController = new ShellController(mShellInit, mShellCommandHandler, mExecutor); mController.onConfigurationChanged(getConfigurationCopy()); } @@ -68,6 +81,46 @@ public class ShellControllerTest extends ShellTestCase { } @Test + public void testAddUserChangeListener_ensureCallback() { + mController.addUserChangeListener(mUserChangeListener); + + mController.onUserChanged(TEST_USER_ID, mTestUserContext); + assertTrue(mUserChangeListener.userChanged == 1); + assertTrue(mUserChangeListener.lastUserContext == mTestUserContext); + } + + @Test + public void testDoubleAddUserChangeListener_ensureSingleCallback() { + mController.addUserChangeListener(mUserChangeListener); + mController.addUserChangeListener(mUserChangeListener); + + mController.onUserChanged(TEST_USER_ID, mTestUserContext); + assertTrue(mUserChangeListener.userChanged == 1); + assertTrue(mUserChangeListener.lastUserContext == mTestUserContext); + } + + @Test + public void testAddRemoveUserChangeListener_ensureNoCallback() { + mController.addUserChangeListener(mUserChangeListener); + mController.removeUserChangeListener(mUserChangeListener); + + mController.onUserChanged(TEST_USER_ID, mTestUserContext); + assertTrue(mUserChangeListener.userChanged == 0); + assertTrue(mUserChangeListener.lastUserContext == null); + } + + @Test + public void testUserProfilesChanged() { + mController.addUserChangeListener(mUserChangeListener); + + ArrayList<UserInfo> profiles = new ArrayList<>(); + profiles.add(mock(UserInfo.class)); + profiles.add(mock(UserInfo.class)); + mController.onUserProfilesChanged(profiles); + assertTrue(mUserChangeListener.lastUserProfiles.equals(profiles)); + } + + @Test public void testAddKeyguardChangeListener_ensureCallback() { mController.addKeyguardChangeListener(mKeyguardChangeListener); @@ -332,4 +385,27 @@ public class ShellControllerTest extends ShellTestCase { dismissAnimationFinished++; } } + + private class TestUserChangeListener implements UserChangeListener { + // Counts of number of times each of the callbacks are called + public int userChanged; + public int lastUserId; + public Context lastUserContext; + public int userProfilesChanged; + public List<? extends UserInfo> lastUserProfiles; + + + @Override + public void onUserChanged(int newUserId, @NonNull Context userContext) { + userChanged++; + lastUserId = newUserId; + lastUserContext = userContext; + } + + @Override + public void onUserProfilesChanged(@NonNull List<UserInfo> profiles) { + userProfilesChanged++; + lastUserProfiles = profiles; + } + } } diff --git a/packages/SettingsLib/MainSwitchPreference/res/layout-v33/settingslib_main_switch_bar.xml b/packages/SettingsLib/MainSwitchPreference/res/layout-v33/settingslib_main_switch_bar.xml index 35d13230a3b7..2aa26e321a91 100644 --- a/packages/SettingsLib/MainSwitchPreference/res/layout-v33/settingslib_main_switch_bar.xml +++ b/packages/SettingsLib/MainSwitchPreference/res/layout-v33/settingslib_main_switch_bar.xml @@ -20,6 +20,11 @@ android:layout_height="wrap_content" android:layout_width="match_parent" android:background="?android:attr/colorBackground" + android:minHeight="?android:attr/listPreferredItemHeight" + android:paddingEnd="?android:attr/listPreferredItemPaddingEnd" + android:paddingStart="?android:attr/listPreferredItemPaddingStart" + android:paddingTop="@dimen/settingslib_switchbar_margin" + android:paddingBottom="@dimen/settingslib_switchbar_margin" android:orientation="vertical"> <LinearLayout @@ -27,7 +32,6 @@ android:minHeight="@dimen/settingslib_min_switch_bar_height" android:layout_height="wrap_content" android:layout_width="match_parent" - android:layout_margin="@dimen/settingslib_switchbar_margin" android:paddingStart="@dimen/settingslib_switchbar_padding_left" android:paddingEnd="@dimen/settingslib_switchbar_padding_right"> diff --git a/packages/SettingsLib/Spa/.idea/codeStyles/Project.xml b/packages/SettingsLib/Spa/.idea/codeStyles/Project.xml index cb757d34dfb4..9578fcf0f4cd 100644 --- a/packages/SettingsLib/Spa/.idea/codeStyles/Project.xml +++ b/packages/SettingsLib/Spa/.idea/codeStyles/Project.xml @@ -1,6 +1,15 @@ <component name="ProjectCodeStyleConfiguration"> <code_scheme name="Project" version="173"> <JetCodeStyleSettings> + <option name="PACKAGES_TO_USE_STAR_IMPORTS"> + <value /> + </option> + <option name="PACKAGES_IMPORT_LAYOUT"> + <value> + <package name="" alias="false" withSubpackages="true" /> + <package name="" alias="true" withSubpackages="true" /> + </value> + </option> <option name="NAME_COUNT_TO_USE_STAR_IMPORT" value="2147483647" /> <option name="NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS" value="2147483647" /> </JetCodeStyleSettings> diff --git a/packages/SettingsLib/Spa/gallery/src/com/android/settingslib/spa/gallery/page/SettingsPagerPage.kt b/packages/SettingsLib/Spa/gallery/src/com/android/settingslib/spa/gallery/page/SettingsPagerPage.kt index 5351ea65da47..df48517fb1fb 100644 --- a/packages/SettingsLib/Spa/gallery/src/com/android/settingslib/spa/gallery/page/SettingsPagerPage.kt +++ b/packages/SettingsLib/Spa/gallery/src/com/android/settingslib/spa/gallery/page/SettingsPagerPage.kt @@ -17,11 +17,7 @@ package com.android.settingslib.spa.gallery.page import android.os.Bundle -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.android.settingslib.spa.framework.api.SettingsPageProvider import com.android.settingslib.spa.framework.compose.navigator @@ -29,7 +25,10 @@ import com.android.settingslib.spa.framework.theme.SettingsTheme import com.android.settingslib.spa.widget.preference.Preference import com.android.settingslib.spa.widget.preference.PreferenceModel import com.android.settingslib.spa.widget.scaffold.SettingsPager -import com.android.settingslib.spa.widget.ui.SettingsTitle +import com.android.settingslib.spa.widget.scaffold.SettingsScaffold +import com.android.settingslib.spa.widget.ui.PlaceholderTitle + +private const val TITLE = "Sample SettingsPager" object SettingsPagerPageProvider : SettingsPageProvider { override val name = "SettingsPager" @@ -42,7 +41,7 @@ object SettingsPagerPageProvider : SettingsPageProvider { @Composable fun EntryItem() { Preference(object : PreferenceModel { - override val title = "Sample SettingsPager" + override val title = TITLE override val onClick = navigator(name) }) } @@ -50,9 +49,9 @@ object SettingsPagerPageProvider : SettingsPageProvider { @Composable private fun SettingsPagerPage() { - SettingsPager(listOf("Personal", "Work")) { - Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { - SettingsTitle(title = "Page $it") + SettingsScaffold(title = TITLE) { + SettingsPager(listOf("Personal", "Work")) { + PlaceholderTitle("Page $it") } } } diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/LogCompositions.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/LogCompositions.kt new file mode 100644 index 000000000000..4eef2a8ffbbf --- /dev/null +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/LogCompositions.kt @@ -0,0 +1,39 @@ +/* + * 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.settingslib.spa.framework.compose + +import android.util.Log +import androidx.compose.runtime.Composable +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.remember + +const val ENABLE_LOG_COMPOSITIONS = false + +data class LogCompositionsRef(var count: Int) + +// Note the inline function below which ensures that this function is essentially +// copied at the call site to ensure that its logging only recompositions from the +// original call site. +@Suppress("NOTHING_TO_INLINE") +@Composable +inline fun LogCompositions(tag: String, msg: String) { + if (ENABLE_LOG_COMPOSITIONS) { + val ref = remember { LogCompositionsRef(0) } + SideEffect { ref.count++ } + Log.d(tag, "Compositions $msg: ${ref.count}") + } +} diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/Pager.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/Pager.kt new file mode 100644 index 000000000000..bf338574c42d --- /dev/null +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/Pager.kt @@ -0,0 +1,339 @@ +/* + * 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.settingslib.spa.framework.compose + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.calculateEndPadding +import androidx.compose.foundation.layout.calculateStartPadding +import androidx.compose.foundation.layout.wrapContentSize +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.Stable +import androidx.compose.runtime.remember +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.nestedscroll.NestedScrollConnection +import androidx.compose.ui.input.nestedscroll.NestedScrollSource +import androidx.compose.ui.input.nestedscroll.nestedScroll +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.Velocity +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.flow.collect +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.drop +import kotlinx.coroutines.flow.filter + +/** + * ************************************************************************************************* + * This file was forked from + * https://github.com/google/accompanist/blob/main/pager/src/main/java/com/google/accompanist/pager/Pager.kt + * and will be removed once it lands in AndroidX. + */ + +/** + * A horizontally scrolling layout that allows users to flip between items to the left and right. + * + * @sample com.google.accompanist.sample.pager.HorizontalPagerSample + * + * @param count the number of pages. + * @param modifier the modifier to apply to this layout. + * @param state the state object to be used to control or observe the pager's state. + * @param reverseLayout reverse the direction of scrolling and layout, when `true` items will be + * composed from the end to the start and [PagerState.currentPage] == 0 will mean + * the first item is located at the end. + * @param itemSpacing horizontal spacing to add between items. + * @param key the scroll position will be maintained based on the key, which means if you + * add/remove items before the current visible item the item with the given key will be kept as the + * first visible one. + * @param content a block which describes the content. Inside this block you can reference + * [PagerScope.currentPage] and other properties in [PagerScope]. + */ +@Composable +fun HorizontalPager( + count: Int, + modifier: Modifier = Modifier, + state: PagerState = rememberPagerState(), + reverseLayout: Boolean = false, + itemSpacing: Dp = 0.dp, + contentPadding: PaddingValues = PaddingValues(0.dp), + verticalAlignment: Alignment.Vertical = Alignment.CenterVertically, + key: ((page: Int) -> Any)? = null, + content: @Composable PagerScope.(page: Int) -> Unit, +) { + Pager( + count = count, + state = state, + modifier = modifier, + isVertical = false, + reverseLayout = reverseLayout, + itemSpacing = itemSpacing, + verticalAlignment = verticalAlignment, + key = key, + contentPadding = contentPadding, + content = content + ) +} + +/** + * A vertically scrolling layout that allows users to flip between items to the top and bottom. + * + * @sample com.google.accompanist.sample.pager.VerticalPagerSample + * + * @param count the number of pages. + * @param modifier the modifier to apply to this layout. + * @param state the state object to be used to control or observe the pager's state. + * @param reverseLayout reverse the direction of scrolling and layout, when `true` items will be + * composed from the bottom to the top and [PagerState.currentPage] == 0 will mean + * the first item is located at the bottom. + * @param itemSpacing vertical spacing to add between items. + * @param key the scroll position will be maintained based on the key, which means if you + * add/remove items before the current visible item the item with the given key will be kept as the + * first visible one. + * @param content a block which describes the content. Inside this block you can reference + * [PagerScope.currentPage] and other properties in [PagerScope]. + */ +@Composable +fun VerticalPager( + count: Int, + modifier: Modifier = Modifier, + state: PagerState = rememberPagerState(), + reverseLayout: Boolean = false, + itemSpacing: Dp = 0.dp, + contentPadding: PaddingValues = PaddingValues(0.dp), + horizontalAlignment: Alignment.Horizontal = Alignment.CenterHorizontally, + key: ((page: Int) -> Any)? = null, + content: @Composable() (PagerScope.(page: Int) -> Unit), +) { + Pager( + count = count, + state = state, + modifier = modifier, + isVertical = true, + reverseLayout = reverseLayout, + itemSpacing = itemSpacing, + horizontalAlignment = horizontalAlignment, + key = key, + contentPadding = contentPadding, + content = content + ) +} + +@Composable +internal fun Pager( + count: Int, + modifier: Modifier, + state: PagerState, + reverseLayout: Boolean, + itemSpacing: Dp, + isVertical: Boolean, + key: ((page: Int) -> Any)?, + contentPadding: PaddingValues, + verticalAlignment: Alignment.Vertical = Alignment.CenterVertically, + horizontalAlignment: Alignment.Horizontal = Alignment.CenterHorizontally, + content: @Composable PagerScope.(page: Int) -> Unit, +) { + require(count >= 0) { "pageCount must be >= 0" } + + LaunchedEffect(count) { + state.currentPage = minOf(count - 1, state.currentPage).coerceAtLeast(0) + } + + // Once a fling (scroll) has finished, notify the state + LaunchedEffect(state) { + // When a 'scroll' has finished, notify the state + snapshotFlow { state.isScrollInProgress } + .filter { !it } + // initially isScrollInProgress is false as well and we want to start receiving + // the events only after the real scroll happens. + .drop(1) + .collect { state.onScrollFinished() } + } + LaunchedEffect(state) { + snapshotFlow { state.mostVisiblePageLayoutInfo?.index } + .distinctUntilChanged() + .collect { state.updateCurrentPageBasedOnLazyListState() } + } + val density = LocalDensity.current + val layoutDirection = LocalLayoutDirection.current + LaunchedEffect(density, contentPadding, isVertical, layoutDirection, reverseLayout, state) { + with(density) { + // this should be exposed on LazyListLayoutInfo instead. b/200920410 + state.afterContentPadding = if (isVertical) { + if (!reverseLayout) { + contentPadding.calculateBottomPadding() + } else { + contentPadding.calculateTopPadding() + } + } else { + if (!reverseLayout) { + contentPadding.calculateEndPadding(layoutDirection) + } else { + contentPadding.calculateStartPadding(layoutDirection) + } + }.roundToPx() + } + } + + val pagerScope = remember(state) { PagerScopeImpl(state) } + + // We only consume nested flings in the main-axis, allowing cross-axis flings to propagate + // as normal + val consumeFlingNestedScrollConnection = remember(isVertical) { + ConsumeFlingNestedScrollConnection( + consumeHorizontal = !isVertical, + consumeVertical = isVertical, + ) + } + + if (isVertical) { + LazyColumn( + state = state.lazyListState, + verticalArrangement = Arrangement.spacedBy(itemSpacing, verticalAlignment), + horizontalAlignment = horizontalAlignment, + reverseLayout = reverseLayout, + contentPadding = contentPadding, + modifier = modifier, + ) { + items( + count = count, + key = key, + ) { page -> + Box( + Modifier + // We don't any nested flings to continue in the pager, so we add a + // connection which consumes them. + // See: https://github.com/google/accompanist/issues/347 + .nestedScroll(connection = consumeFlingNestedScrollConnection) + // Constraint the content height to be <= than the height of the pager. + .fillParentMaxHeight() + .wrapContentSize() + ) { + pagerScope.content(page) + } + } + } + } else { + LazyRow( + state = state.lazyListState, + verticalAlignment = verticalAlignment, + horizontalArrangement = Arrangement.spacedBy(itemSpacing, horizontalAlignment), + reverseLayout = reverseLayout, + contentPadding = contentPadding, + modifier = modifier, + ) { + items( + count = count, + key = key, + ) { page -> + Box( + Modifier + // We don't any nested flings to continue in the pager, so we add a + // connection which consumes them. + // See: https://github.com/google/accompanist/issues/347 + .nestedScroll(connection = consumeFlingNestedScrollConnection) + // Constraint the content width to be <= than the width of the pager. + .fillParentMaxWidth() + .wrapContentSize() + ) { + pagerScope.content(page) + } + } + } + } +} + +private class ConsumeFlingNestedScrollConnection( + private val consumeHorizontal: Boolean, + private val consumeVertical: Boolean, +) : NestedScrollConnection { + override fun onPostScroll( + consumed: Offset, + available: Offset, + source: NestedScrollSource + ): Offset = when (source) { + // We can consume all resting fling scrolls so that they don't propagate up to the + // Pager + NestedScrollSource.Fling -> available.consume(consumeHorizontal, consumeVertical) + else -> Offset.Zero + } + + override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity { + // We can consume all post fling velocity on the main-axis + // so that it doesn't propagate up to the Pager + return available.consume(consumeHorizontal, consumeVertical) + } +} + +private fun Offset.consume( + consumeHorizontal: Boolean, + consumeVertical: Boolean, +): Offset = Offset( + x = if (consumeHorizontal) this.x else 0f, + y = if (consumeVertical) this.y else 0f, +) + +private fun Velocity.consume( + consumeHorizontal: Boolean, + consumeVertical: Boolean, +): Velocity = Velocity( + x = if (consumeHorizontal) this.x else 0f, + y = if (consumeVertical) this.y else 0f, +) + +/** + * Scope for [HorizontalPager] content. + */ +@Stable +interface PagerScope { + /** + * Returns the current selected page + */ + val currentPage: Int + + /** + * The current offset from the start of [currentPage], as a ratio of the page width. + */ + val currentPageOffset: Float +} + +private class PagerScopeImpl( + private val state: PagerState, +) : PagerScope { + override val currentPage: Int get() = state.currentPage + override val currentPageOffset: Float get() = state.currentPageOffset +} + +/** + * Calculate the offset for the given [page] from the current scroll position. This is useful + * when using the scroll position to apply effects or animations to items. + * + * The returned offset can positive or negative, depending on whether which direction the [page] is + * compared to the current scroll position. + * + * @sample com.google.accompanist.sample.pager.HorizontalPagerWithOffsetTransition + */ +fun PagerScope.calculateCurrentOffsetForPage(page: Int): Float { + return (currentPage - page) + currentPageOffset +} diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/PagerState.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/PagerState.kt new file mode 100644 index 000000000000..21ba11739af0 --- /dev/null +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/compose/PagerState.kt @@ -0,0 +1,318 @@ +/* + * 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.settingslib.spa.framework.compose + +import androidx.annotation.FloatRange +import androidx.annotation.IntRange +import androidx.compose.foundation.MutatePriority +import androidx.compose.foundation.gestures.ScrollScope +import androidx.compose.foundation.gestures.ScrollableState +import androidx.compose.foundation.interaction.InteractionSource +import androidx.compose.foundation.lazy.LazyListItemInfo +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.Stable +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.Saver +import androidx.compose.runtime.saveable.listSaver +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import kotlin.math.abs +import kotlin.math.absoluteValue +import kotlin.math.roundToInt + +/** + * ************************************************************************************************* + * This file was forked from + * https://github.com/google/accompanist/blob/main/pager/src/main/java/com/google/accompanist/pager/PagerState.kt + * and will be removed once it lands in AndroidX. + */ + +/** + * Creates a [PagerState] that is remembered across compositions. + * + * Changes to the provided values for [initialPage] will **not** result in the state being + * recreated or changed in any way if it has already + * been created. + * + * @param initialPage the initial value for [PagerState.currentPage] + */ +@Composable +fun rememberPagerState( + @IntRange(from = 0) initialPage: Int = 0, +): PagerState = rememberSaveable(saver = PagerState.Saver) { + PagerState( + currentPage = initialPage, + ) +} + +/** + * A state object that can be hoisted to control and observe scrolling for [HorizontalPager]. + * + * In most cases, this will be created via [rememberPagerState]. + * + * @param currentPage the initial value for [PagerState.currentPage] + */ +@Stable +class PagerState( + @IntRange(from = 0) currentPage: Int = 0, +) : ScrollableState { + // Should this be public? + internal val lazyListState = LazyListState(firstVisibleItemIndex = currentPage) + + private var _currentPage by mutableStateOf(currentPage) + + // finds the page which has larger visible area within the viewport not including paddings + internal val mostVisiblePageLayoutInfo: LazyListItemInfo? + get() { + val layoutInfo = lazyListState.layoutInfo + return layoutInfo.visibleItemsInfo.maxByOrNull { + val start = maxOf(it.offset, 0) + val end = minOf( + it.offset + it.size, layoutInfo.viewportEndOffset - afterContentPadding) + end - start + } + } + + internal var afterContentPadding = 0 + + private val currentPageLayoutInfo: LazyListItemInfo? + get() = lazyListState.layoutInfo.visibleItemsInfo.lastOrNull { + it.index == currentPage + } + + /** + * [InteractionSource] that will be used to dispatch drag events when this + * list is being dragged. If you want to know whether the fling (or animated scroll) is in + * progress, use [isScrollInProgress]. + */ + val interactionSource: InteractionSource + get() = lazyListState.interactionSource + + /** + * The number of pages to display. + */ + @get:IntRange(from = 0) + val pageCount: Int by derivedStateOf { + lazyListState.layoutInfo.totalItemsCount + } + + /** + * The index of the currently selected page. This may not be the page which is + * currently displayed on screen. + * + * To update the scroll position, use [scrollToPage] or [animateScrollToPage]. + */ + @get:IntRange(from = 0) + var currentPage: Int + get() = _currentPage + internal set(value) { + if (value != _currentPage) { + _currentPage = value + } + } + + /** + * The current offset from the start of [currentPage], as a ratio of the page width. + * + * To update the scroll position, use [scrollToPage] or [animateScrollToPage]. + */ + val currentPageOffset: Float by derivedStateOf { + currentPageLayoutInfo?.let { + // We coerce since itemSpacing can make the offset > 1f. + // We don't want to count spacing in the offset so cap it to 1f + (-it.offset / it.size.toFloat()).coerceIn(-1f, 1f) + } ?: 0f + } + + /** + * The target page for any on-going animations. + */ + private var animationTargetPage: Int? by mutableStateOf(null) + + /** + * Animate (smooth scroll) to the given page to the middle of the viewport. + * + * Cancels the currently running scroll, if any, and suspends until the cancellation is + * complete. + * + * @param page the page to animate to. Must be >= 0. + * @param pageOffset the percentage of the page size to offset, from the start of [page]. + * Must be in the range -1f..1f. + */ + suspend fun animateScrollToPage( + @IntRange(from = 0) page: Int, + @FloatRange(from = -1.0, to = 1.0) pageOffset: Float = 0f, + ) { + requireCurrentPage(page, "page") + requireCurrentPageOffset(pageOffset, "pageOffset") + try { + animationTargetPage = page + + // pre-jump to nearby item for long jumps as an optimization + // the same trick is done in ViewPager2 + val oldPage = lazyListState.firstVisibleItemIndex + if (abs(page - oldPage) > 3) { + lazyListState.scrollToItem(if (page > oldPage) page - 3 else page + 3) + } + + if (pageOffset.absoluteValue <= 0.005f) { + // If the offset is (close to) zero, just call animateScrollToItem and we're done + lazyListState.animateScrollToItem(index = page) + } else { + // Else we need to figure out what the offset is in pixels... + lazyListState.scroll { } // this will await for the first layout. + val layoutInfo = lazyListState.layoutInfo + var target = layoutInfo.visibleItemsInfo + .firstOrNull { it.index == page } + + if (target != null) { + // If we have access to the target page layout, we can calculate the pixel + // offset from the size + lazyListState.animateScrollToItem( + index = page, + scrollOffset = (target.size * pageOffset).roundToInt() + ) + } else if (layoutInfo.visibleItemsInfo.isNotEmpty()) { + // If we don't, we use the current page size as a guide + val currentSize = layoutInfo.visibleItemsInfo.first().size + lazyListState.animateScrollToItem( + index = page, + scrollOffset = (currentSize * pageOffset).roundToInt() + ) + + // The target should be visible now + target = lazyListState.layoutInfo.visibleItemsInfo.firstOrNull { + it.index == page + } + + if (target != null && target.size != currentSize) { + // If the size we used for calculating the offset differs from the actual + // target page size, we need to scroll again. This doesn't look great, + // but there's not much else we can do. + lazyListState.animateScrollToItem( + index = page, + scrollOffset = (target.size * pageOffset).roundToInt() + ) + } + } + } + } finally { + // We need to manually call this, as the `animateScrollToItem` call above will happen + // in 1 frame, which is usually too fast for the LaunchedEffect in Pager to detect + // the change. This is especially true when running unit tests. + onScrollFinished() + } + } + + /** + * Instantly brings the item at [page] to the middle of the viewport. + * + * Cancels the currently running scroll, if any, and suspends until the cancellation is + * complete. + * + * @param page the page to snap to. Must be >= 0. + * @param pageOffset the percentage of the page size to offset, from the start of [page]. + * Must be in the range -1f..1f. + */ + suspend fun scrollToPage( + @IntRange(from = 0) page: Int, + @FloatRange(from = -1.0, to = 1.0) pageOffset: Float = 0f, + ) { + requireCurrentPage(page, "page") + requireCurrentPageOffset(pageOffset, "pageOffset") + try { + animationTargetPage = page + + // First scroll to the given page. It will now be laid out at offset 0 + lazyListState.scrollToItem(index = page) + updateCurrentPageBasedOnLazyListState() + + // If we have a start spacing, we need to offset (scroll) by that too + if (pageOffset.absoluteValue > 0.0001f) { + currentPageLayoutInfo?.let { + scroll { + scrollBy(it.size * pageOffset) + } + } + } + } finally { + // We need to manually call this, as the `scroll` call above will happen in 1 frame, + // which is usually too fast for the LaunchedEffect in Pager to detect the change. + // This is especially true when running unit tests. + onScrollFinished() + } + } + + internal fun updateCurrentPageBasedOnLazyListState() { + // Then update the current page to our layout page + mostVisiblePageLayoutInfo?.let { + currentPage = it.index + } + } + + internal fun onScrollFinished() { + // Clear the animation target page + animationTargetPage = null + } + + override suspend fun scroll( + scrollPriority: MutatePriority, + block: suspend ScrollScope.() -> Unit + ) = lazyListState.scroll(scrollPriority, block) + + override fun dispatchRawDelta(delta: Float): Float { + return lazyListState.dispatchRawDelta(delta) + } + + override val isScrollInProgress: Boolean + get() = lazyListState.isScrollInProgress + + override fun toString(): String = "PagerState(" + + "pageCount=$pageCount, " + + "currentPage=$currentPage, " + + "currentPageOffset=$currentPageOffset" + + ")" + + private fun requireCurrentPage(value: Int, name: String) { + require(value >= 0) { "$name[$value] must be >= 0" } + } + + private fun requireCurrentPageOffset(value: Float, name: String) { + require(value in -1f..1f) { "$name must be >= 0 and <= 1" } + } + + companion object { + /** + * The default [Saver] implementation for [PagerState]. + */ + val Saver: Saver<PagerState, *> = listSaver( + save = { + listOf<Any>( + it.currentPage, + ) + }, + restore = { + PagerState( + currentPage = it[0] as Int, + ) + } + ) + } +} diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/theme/SettingsDimension.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/theme/SettingsDimension.kt index 7d3e10768e46..965436847c64 100644 --- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/theme/SettingsDimension.kt +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/theme/SettingsDimension.kt @@ -32,4 +32,10 @@ object SettingsDimension { bottom = itemPaddingVertical, ) val itemPaddingAround = 8.dp + + /** The size when app icon is displayed in list. */ + val appIconItemSize = 32.dp + + /** The size when app icon is displayed in App info page. */ + val appIconInfoSize = 48.dp } diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/Collections.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/Collections.kt new file mode 100644 index 000000000000..ba253368d505 --- /dev/null +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/Collections.kt @@ -0,0 +1,33 @@ +/* + * 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.settingslib.spa.framework.util + +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope + +suspend inline fun <R, T> Iterable<T>.asyncMap(crossinline transform: (T) -> R): List<R> = + coroutineScope { + map { item -> + async { transform(item) } + }.awaitAll() + } + +suspend inline fun <T> Iterable<T>.asyncFilter(crossinline predicate: (T) -> Boolean): List<T> = + asyncMap { item -> item to predicate(item) } + .filter { it.second } + .map { it.first } diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/Flows.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/Flows.kt new file mode 100644 index 000000000000..999d8d7dd16a --- /dev/null +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/Flows.kt @@ -0,0 +1,58 @@ +/* + * 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.settingslib.spa.framework.util + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.State +import androidx.compose.runtime.snapshotFlow +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChangedBy +import kotlinx.coroutines.flow.filterNotNull +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.map + +inline fun <T, R> Flow<List<T>>.asyncMapItem(crossinline transform: (T) -> R): Flow<List<R>> = + map { list -> list.asyncMap(transform) } + +@OptIn(ExperimentalCoroutinesApi::class) +inline fun <T, R> Flow<T>.mapState(crossinline block: (T) -> State<R>): Flow<R> = + flatMapLatest { snapshotFlow { block(it).value } } + +fun <T1, T2> Flow<T1>.waitFirst(flow: Flow<T2>): Flow<T1> = + combine(flow.distinctUntilChangedBy {}) { value, _ -> value } + +class StateFlowBridge<T> { + private val stateFlow = MutableStateFlow<T?>(null) + val flow = stateFlow.filterNotNull() + + fun setIfAbsent(value: T) { + if (stateFlow.value == null) { + stateFlow.value = value + } + } + + @Composable + fun Sync(state: State<T>) { + LaunchedEffect(state.value) { + stateFlow.value = state.value + } + } +} diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/Actions.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/Actions.kt index 0a41a1a95936..c9602543b364 100644 --- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/Actions.kt +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/Actions.kt @@ -18,6 +18,7 @@ package com.android.settingslib.spa.widget.scaffold import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.ArrowBack +import androidx.compose.material.icons.outlined.MoreVert import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.runtime.Composable @@ -44,3 +45,15 @@ private fun BackAction(contentDescription: String, onClick: () -> Unit) { ) } } + +@Composable +fun MoreOptionsAction(onClick: () -> Unit) { + IconButton(onClick) { + Icon( + imageVector = Icons.Outlined.MoreVert, + contentDescription = stringResource( + id = androidx.appcompat.R.string.abc_action_menu_overflow_description, + ) + ) + } +} diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/RegularScaffold.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/RegularScaffold.kt index 3325d5382f2e..9a17b2a8cb78 100644 --- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/RegularScaffold.kt +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/RegularScaffold.kt @@ -22,15 +22,10 @@ import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold -import androidx.compose.material3.SmallTopAppBar -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview -import com.android.settingslib.spa.framework.theme.SettingsDimension import com.android.settingslib.spa.framework.theme.SettingsTheme /** @@ -39,28 +34,13 @@ import com.android.settingslib.spa.framework.theme.SettingsTheme * For example, this is for the pages with some preferences and is scrollable when the items out of * the screen. */ -@OptIn(ExperimentalMaterial3Api::class) @Composable fun RegularScaffold( title: String, actions: @Composable RowScope.() -> Unit = {}, content: @Composable () -> Unit, ) { - Scaffold( - topBar = { - SmallTopAppBar( - title = { - Text( - text = title, - modifier = Modifier.padding(SettingsDimension.itemPaddingAround), - ) - }, - navigationIcon = { NavigateUp() }, - actions = actions, - colors = settingsTopAppBarColors(), - ) - }, - ) { paddingValues -> + SettingsScaffold(title, actions) { paddingValues -> Column(Modifier.verticalScroll(rememberScrollState())) { Spacer(Modifier.padding(paddingValues)) content() @@ -68,12 +48,6 @@ fun RegularScaffold( } } -@Composable -internal fun settingsTopAppBarColors() = TopAppBarDefaults.largeTopAppBarColors( - containerColor = SettingsTheme.colorScheme.surfaceHeader, - scrolledContainerColor = SettingsTheme.colorScheme.surfaceHeader, -) - @Preview @Composable private fun RegularScaffoldPreview() { diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsPager.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsPager.kt index 1ec2390741ed..e0e9b951065b 100644 --- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsPager.kt +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsPager.kt @@ -20,13 +20,14 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.material3.TabRow import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +import com.android.settingslib.spa.framework.compose.HorizontalPager +import com.android.settingslib.spa.framework.compose.rememberPagerState import com.android.settingslib.spa.framework.theme.SettingsDimension +import kotlin.math.absoluteValue +import kotlinx.coroutines.launch @Composable fun SettingsPager(titles: List<String>, content: @Composable (page: Int) -> Unit) { @@ -37,10 +38,11 @@ fun SettingsPager(titles: List<String>, content: @Composable (page: Int) -> Unit } Column { - var currentPage by rememberSaveable { mutableStateOf(0) } + val coroutineScope = rememberCoroutineScope() + val pagerState = rememberPagerState() TabRow( - selectedTabIndex = currentPage, + selectedTabIndex = pagerState.currentPage, modifier = Modifier.padding(horizontal = SettingsDimension.itemPaddingEnd), containerColor = Color.Transparent, indicator = {}, @@ -49,12 +51,19 @@ fun SettingsPager(titles: List<String>, content: @Composable (page: Int) -> Unit titles.forEachIndexed { page, title -> SettingsTab( title = title, - selected = currentPage == page, - onClick = { currentPage = page }, + selected = pagerState.currentPage == page, + currentPageOffset = pagerState.currentPageOffset.absoluteValue, + onClick = { + coroutineScope.launch { + pagerState.animateScrollToPage(page) + } + }, ) } } - content(currentPage) + HorizontalPager(count = titles.size, state = pagerState) { page -> + content(page) + } } } diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsScaffold.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsScaffold.kt new file mode 100644 index 000000000000..ee453f246623 --- /dev/null +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsScaffold.kt @@ -0,0 +1,73 @@ +/* + * 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.settingslib.spa.widget.scaffold + +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SmallTopAppBar +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.tooling.preview.Preview +import com.android.settingslib.spa.framework.theme.SettingsDimension +import com.android.settingslib.spa.framework.theme.SettingsTheme + +/** + * A [Scaffold] which content is can be full screen when needed. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun SettingsScaffold( + title: String, + actions: @Composable RowScope.() -> Unit = {}, + content: @Composable (PaddingValues) -> Unit, +) { + Scaffold( + topBar = { + SmallTopAppBar( + title = { + Text( + text = title, + modifier = Modifier.padding(SettingsDimension.itemPaddingAround), + ) + }, + navigationIcon = { NavigateUp() }, + actions = actions, + colors = settingsTopAppBarColors(), + ) + }, + content = content, + ) +} + +@Composable +internal fun settingsTopAppBarColors() = TopAppBarDefaults.largeTopAppBarColors( + containerColor = SettingsTheme.colorScheme.surfaceHeader, + scrolledContainerColor = SettingsTheme.colorScheme.surfaceHeader, +) + +@Preview +@Composable +private fun SettingsScaffoldPreview() { + SettingsTheme { + SettingsScaffold(title = "Display") {} + } +} diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsTab.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsTab.kt index 16d8dbc9bf74..30a4349e942f 100644 --- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsTab.kt +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/scaffold/SettingsTab.kt @@ -26,6 +26,7 @@ import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.lerp import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.android.settingslib.spa.framework.theme.SettingsShape @@ -35,8 +36,12 @@ import com.android.settingslib.spa.framework.theme.SettingsTheme internal fun SettingsTab( title: String, selected: Boolean, + currentPageOffset: Float, onClick: () -> Unit, ) { + // Shows a color transition during pager scroll. + // 0f -> Selected, 1f -> Not selected + val colorFraction = if (selected) (currentPageOffset * 2).coerceAtMost(1f) else 1f Tab( selected = selected, onClick = onClick, @@ -44,29 +49,33 @@ internal fun SettingsTab( .height(48.dp) .padding(horizontal = 4.dp, vertical = 6.dp) .clip(SettingsShape.CornerMedium) - .background(color = when { - selected -> SettingsTheme.colorScheme.primaryContainer - else -> SettingsTheme.colorScheme.surface - }), + .background( + color = lerp( + start = SettingsTheme.colorScheme.primaryContainer, + stop = SettingsTheme.colorScheme.surface, + fraction = colorFraction, + ), + ), ) { Text( text = title, style = MaterialTheme.typography.labelLarge, - color = when { - selected -> SettingsTheme.colorScheme.onPrimaryContainer - else -> SettingsTheme.colorScheme.secondaryText - }, + color = lerp( + start = SettingsTheme.colorScheme.onPrimaryContainer, + stop = SettingsTheme.colorScheme.secondaryText, + fraction = colorFraction, + ), ) } } @Preview @Composable -private fun SettingsTabPreview() { +fun SettingsTabPreview() { SettingsTheme { Column { - SettingsTab(title = "Personal", selected = true) {} - SettingsTab(title = "Work", selected = false) {} + SettingsTab(title = "Personal", selected = true, currentPageOffset = 0f) {} + SettingsTab(title = "Work", selected = false, currentPageOffset = 0f) {} } } } diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/ui/Text.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/ui/Text.kt index a414c89dc24c..59b413cef56e 100644 --- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/ui/Text.kt +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/ui/Text.kt @@ -16,10 +16,14 @@ package com.android.settingslib.spa.widget.ui +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.State +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier @Composable fun SettingsTitle(title: State<String>) { @@ -50,3 +54,17 @@ fun SettingsBody(body: String) { ) } } + +@Composable +fun PlaceholderTitle(title: String) { + Box( + modifier = Modifier.fillMaxSize(), + contentAlignment = Alignment.Center, + ) { + Text( + text = title, + color = MaterialTheme.colorScheme.onSurface, + style = MaterialTheme.typography.titleLarge, + ) + } +} diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/scaffold/SettingsPagerKtTest.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/scaffold/SettingsPagerKtTest.kt index f608e1003163..0c84eac45cb7 100644 --- a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/scaffold/SettingsPagerKtTest.kt +++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/scaffold/SettingsPagerKtTest.kt @@ -18,6 +18,7 @@ package com.android.settingslib.spa.widget.scaffold import androidx.compose.runtime.Composable import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsNotDisplayed import androidx.compose.ui.test.assertIsNotSelected import androidx.compose.ui.test.assertIsSelected import androidx.compose.ui.test.junit4.createComposeRule @@ -43,7 +44,7 @@ class SettingsPagerKtTest { composeTestRule.onNodeWithText("Personal").assertIsSelected() composeTestRule.onNodeWithText("Page 0").assertIsDisplayed() composeTestRule.onNodeWithText("Work").assertIsNotSelected() - composeTestRule.onNodeWithText("Page 1").assertDoesNotExist() + composeTestRule.onNodeWithText("Page 1").assertIsNotDisplayed() } @Test @@ -55,7 +56,7 @@ class SettingsPagerKtTest { composeTestRule.onNodeWithText("Work").performClick() composeTestRule.onNodeWithText("Personal").assertIsNotSelected() - composeTestRule.onNodeWithText("Page 0").assertDoesNotExist() + composeTestRule.onNodeWithText("Page 0").assertIsNotDisplayed() composeTestRule.onNodeWithText("Work").assertIsSelected() composeTestRule.onNodeWithText("Page 1").assertIsDisplayed() } diff --git a/packages/SettingsLib/SpaPrivileged/Android.bp b/packages/SettingsLib/SpaPrivileged/Android.bp index ecbb219c64b5..a6469b5172bb 100644 --- a/packages/SettingsLib/SpaPrivileged/Android.bp +++ b/packages/SettingsLib/SpaPrivileged/Android.bp @@ -28,5 +28,8 @@ android_library { "SettingsLib", "androidx.compose.runtime_runtime", ], - kotlincflags: ["-Xjvm-default=all"], + kotlincflags: [ + "-Xjvm-default=all", + "-Xopt-in=kotlin.RequiresOptIn", + ], } diff --git a/packages/SettingsLib/SpaPrivileged/res/values/strings.xml b/packages/SettingsLib/SpaPrivileged/res/values/strings.xml new file mode 100644 index 000000000000..b2302a58229c --- /dev/null +++ b/packages/SettingsLib/SpaPrivileged/res/values/strings.xml @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + 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. +--> +<resources> + <!-- [CHAR LIMIT=25] Text shown when there are no applications to display. --> + <string name="no_applications">No apps.</string> + <!-- [CHAR LIMIT=NONE] Menu for manage apps to control whether system processes are shown --> + <string name="menu_show_system">Show system</string> + <!-- [CHAR LIMIT=NONE] Menu for manage apps to control whether system processes are hidden --> + <string name="menu_hide_system">Hide system</string> + <!-- Preference summary text for an app when it is allowed for a permission. [CHAR LIMIT=45] --> + <string name="app_permission_summary_allowed">Allowed</string> + <!-- Preference summary text for an app when it is disallowed for a permission. [CHAR LIMIT=45] --> + <string name="app_permission_summary_not_allowed">Not allowed</string> +</resources> diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppListModel.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppListModel.kt new file mode 100644 index 000000000000..00eb60b6ec7a --- /dev/null +++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppListModel.kt @@ -0,0 +1,29 @@ +package com.android.settingslib.spaprivileged.model.app + +import android.content.pm.ApplicationInfo +import android.icu.text.CollationKey +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import kotlinx.coroutines.flow.Flow + +data class AppEntry<T : AppRecord>( + val record: T, + val label: String, + val labelCollationKey: CollationKey, +) + +interface AppListModel<T : AppRecord> { + fun getSpinnerOptions(): List<String> = emptyList() + fun transform(userIdFlow: Flow<Int>, appListFlow: Flow<List<ApplicationInfo>>): Flow<List<T>> + fun filter(userIdFlow: Flow<Int>, option: Int, recordListFlow: Flow<List<T>>): Flow<List<T>> + + suspend fun onFirstLoaded(recordList: List<T>) {} + fun getComparator(option: Int): Comparator<AppEntry<T>> = compareBy( + { it.labelCollationKey }, + { it.record.app.packageName }, + { it.record.app.uid }, + ) + + @Composable + fun getSummary(option: Int, record: T): State<String>? +} diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppListViewModel.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppListViewModel.kt new file mode 100644 index 000000000000..9265158b3b4a --- /dev/null +++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppListViewModel.kt @@ -0,0 +1,125 @@ +/* + * 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.settingslib.spaprivileged.model.app + +import android.app.Application +import android.content.pm.ApplicationInfo +import android.content.pm.UserInfo +import android.icu.text.Collator +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.viewModelScope +import com.android.settingslib.spa.framework.util.StateFlowBridge +import com.android.settingslib.spa.framework.util.asyncMapItem +import com.android.settingslib.spa.framework.util.waitFirst +import java.util.concurrent.ConcurrentHashMap +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.shareIn +import kotlinx.coroutines.plus + +internal data class AppListData<T : AppRecord>( + val appEntries: List<AppEntry<T>>, + val option: Int, +) { + fun filter(predicate: (AppEntry<T>) -> Boolean) = + AppListData(appEntries.filter(predicate), option) +} + +@OptIn(ExperimentalCoroutinesApi::class) +internal class AppListViewModel<T : AppRecord>( + application: Application, +) : AndroidViewModel(application) { + val userInfo = StateFlowBridge<UserInfo>() + val listModel = StateFlowBridge<AppListModel<T>>() + val showSystem = StateFlowBridge<Boolean>() + val option = StateFlowBridge<Int>() + val searchQuery = StateFlowBridge<String>() + + private val appsRepository = AppsRepository(application) + private val appRepository = AppRepositoryImpl(application) + private val collator = Collator.getInstance().freeze() + private val labelMap = ConcurrentHashMap<String, String>() + private val scope = viewModelScope + Dispatchers.Default + + private val userIdFlow = userInfo.flow.map { it.id } + + private val recordListFlow = listModel.flow + .flatMapLatest { it.transform(userIdFlow, appsRepository.loadApps(userInfo.flow)) } + .shareIn(scope = scope, started = SharingStarted.Eagerly, replay = 1) + + private val systemFilteredFlow = appsRepository.showSystemPredicate(userIdFlow, showSystem.flow) + .combine(recordListFlow) { showAppPredicate, recordList -> + recordList.filter { showAppPredicate(it.app) } + } + + val appListDataFlow = option.flow.flatMapLatest(::filterAndSort) + .combine(searchQuery.flow) { appListData, searchQuery -> + appListData.filter { + it.label.contains(other = searchQuery, ignoreCase = true) + } + } + .shareIn(scope = scope, started = SharingStarted.Eagerly, replay = 1) + + init { + scheduleOnFirstLoaded() + } + + private fun filterAndSort(option: Int) = listModel.flow.flatMapLatest { listModel -> + listModel.filter(userIdFlow, option, systemFilteredFlow) + .asyncMapItem { record -> + val label = getLabel(record.app) + AppEntry( + record = record, + label = label, + labelCollationKey = collator.getCollationKey(label), + ) + } + .map { appEntries -> + AppListData( + appEntries = appEntries.sortedWith(listModel.getComparator(option)), + option = option, + ) + } + } + + private fun scheduleOnFirstLoaded() { + recordListFlow + .waitFirst(appListDataFlow) + .combine(listModel.flow) { recordList, listModel -> + listModel.maybePreFetchLabels(recordList) + listModel.onFirstLoaded(recordList) + } + .launchIn(scope) + } + + private fun AppListModel<T>.maybePreFetchLabels(recordList: List<T>) { + if (getSpinnerOptions().isNotEmpty()) { + for (record in recordList) { + getLabel(record.app) + } + } + } + + private fun getLabel(app: ApplicationInfo) = labelMap.computeIfAbsent(app.packageName) { + appRepository.loadLabel(app) + } +} diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppRepository.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppRepository.kt index 7ffa9384bfe2..34f12af28dce 100644 --- a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppRepository.kt +++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppRepository.kt @@ -31,6 +31,8 @@ import kotlinx.coroutines.withContext fun rememberAppRepository(): AppRepository = rememberContext(::AppRepositoryImpl) interface AppRepository { + fun loadLabel(app: ApplicationInfo): String + @Composable fun produceLabel(app: ApplicationInfo): State<String> @@ -38,9 +40,11 @@ interface AppRepository { fun produceIcon(app: ApplicationInfo): State<Drawable?> } -private class AppRepositoryImpl(private val context: Context) : AppRepository { +internal class AppRepositoryImpl(private val context: Context) : AppRepository { private val packageManager = context.packageManager + override fun loadLabel(app: ApplicationInfo): String = app.loadLabel(packageManager).toString() + @Composable override fun produceLabel(app: ApplicationInfo) = produceState(initialValue = "", app) { withContext(Dispatchers.Default) { diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppsRepository.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppsRepository.kt new file mode 100644 index 000000000000..6a6462098230 --- /dev/null +++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/model/app/AppsRepository.kt @@ -0,0 +1,114 @@ +/* + * 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.settingslib.spaprivileged.model.app + +import android.content.Context +import android.content.Intent +import android.content.pm.ApplicationInfo +import android.content.pm.PackageManager +import android.content.pm.ResolveInfo +import android.content.pm.UserInfo +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.flowOn +import kotlinx.coroutines.flow.map + +class AppsRepository(context: Context) { + private val packageManager = context.packageManager + + fun loadApps(userInfoFlow: Flow<UserInfo>): Flow<List<ApplicationInfo>> = userInfoFlow + .map { loadApps(it) } + .flowOn(Dispatchers.Default) + + private suspend fun loadApps(userInfo: UserInfo): List<ApplicationInfo> { + return coroutineScope { + val hiddenSystemModulesDeferred = async { + packageManager.getInstalledModules(0) + .filter { it.isHidden } + .map { it.packageName } + .toSet() + } + val flags = PackageManager.ApplicationInfoFlags.of( + ((if (userInfo.isAdmin) PackageManager.MATCH_ANY_USER else 0) or + PackageManager.MATCH_DISABLED_COMPONENTS or + PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS).toLong() + ) + val installedApplicationsAsUser = + packageManager.getInstalledApplicationsAsUser(flags, userInfo.id) + + val hiddenSystemModules = hiddenSystemModulesDeferred.await() + installedApplicationsAsUser.filter { app -> + app.isInAppList(hiddenSystemModules) + } + } + } + + fun showSystemPredicate( + userIdFlow: Flow<Int>, + showSystemFlow: Flow<Boolean>, + ): Flow<(app: ApplicationInfo) -> Boolean> = + userIdFlow.combine(showSystemFlow) { userId, showSystem -> + showSystemPredicate(userId, showSystem) + } + + private suspend fun showSystemPredicate( + userId: Int, + showSystem: Boolean, + ): (app: ApplicationInfo) -> Boolean { + if (showSystem) return { true } + val homeOrLauncherPackages = loadHomeOrLauncherPackages(userId) + return { app -> + app.isUpdatedSystemApp || !app.isSystemApp || app.packageName in homeOrLauncherPackages + } + } + + private suspend fun loadHomeOrLauncherPackages(userId: Int): Set<String> { + val launchIntent = Intent(Intent.ACTION_MAIN, null).addCategory(Intent.CATEGORY_LAUNCHER) + // If we do not specify MATCH_DIRECT_BOOT_AWARE or MATCH_DIRECT_BOOT_UNAWARE, system will + // derive and update the flags according to the user's lock state. When the user is locked, + // components with ComponentInfo#directBootAware == false will be filtered. We should + // explicitly include both direct boot aware and unaware component here. + val flags = PackageManager.ResolveInfoFlags.of( + (PackageManager.MATCH_DISABLED_COMPONENTS or + PackageManager.MATCH_DIRECT_BOOT_AWARE or + PackageManager.MATCH_DIRECT_BOOT_UNAWARE).toLong() + ) + return coroutineScope { + val launcherActivities = async { + packageManager.queryIntentActivitiesAsUser(launchIntent, flags, userId) + } + val homeActivities = ArrayList<ResolveInfo>() + packageManager.getHomeActivities(homeActivities) + (launcherActivities.await() + homeActivities) + .map { it.activityInfo.packageName } + .toSet() + } + } + + companion object { + private fun ApplicationInfo.isInAppList(hiddenSystemModules: Set<String>) = + when { + packageName in hiddenSystemModules -> false + enabled -> true + enabledSetting == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER -> true + else -> false + } + } +} diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfo.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfo.kt index d802b049b830..99deb707a351 100644 --- a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfo.kt +++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfo.kt @@ -29,8 +29,10 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.android.settingslib.spa.framework.compose.rememberDrawablePainter +import com.android.settingslib.spa.framework.theme.SettingsDimension import com.android.settingslib.spa.widget.ui.SettingsBody import com.android.settingslib.spa.widget.ui.SettingsTitle import com.android.settingslib.spaprivileged.model.app.PackageManagers @@ -41,25 +43,35 @@ fun AppInfo(packageName: String, userId: Int) { Column( modifier = Modifier .fillMaxWidth() - .padding(16.dp), - horizontalAlignment = Alignment.CenterHorizontally) { + .padding( + horizontal = SettingsDimension.itemPaddingStart, + vertical = SettingsDimension.itemPaddingVertical, + ), + horizontalAlignment = Alignment.CenterHorizontally, + ) { val packageInfo = remember { PackageManagers.getPackageInfoAsUser(packageName, userId) } - Box(modifier = Modifier.padding(8.dp)) { - AppIcon(app = packageInfo.applicationInfo, size = 48) + Box(modifier = Modifier.padding(SettingsDimension.itemPaddingAround)) { + AppIcon(app = packageInfo.applicationInfo, size = SettingsDimension.appIconInfoSize) } AppLabel(packageInfo.applicationInfo) - Spacer(modifier = Modifier.height(4.dp)) - SettingsBody(packageInfo.versionName) + AppVersion(packageInfo.versionName) } } @Composable -fun AppIcon(app: ApplicationInfo, size: Int) { +private fun AppVersion(versionName: String?) { + if (versionName == null) return + Spacer(modifier = Modifier.height(4.dp)) + SettingsBody(versionName) +} + +@Composable +fun AppIcon(app: ApplicationInfo, size: Dp) { val appRepository = rememberAppRepository() Image( painter = rememberDrawablePainter(appRepository.produceIcon(app).value), contentDescription = null, - modifier = Modifier.size(size.dp) + modifier = Modifier.size(size) ) } diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfoPage.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfoPage.kt index 06d7547be309..9b45318ffd82 100644 --- a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfoPage.kt +++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppInfoPage.kt @@ -16,15 +16,8 @@ package com.android.settingslib.spaprivileged.template.app -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text import androidx.compose.runtime.Composable -import androidx.compose.ui.Modifier -import com.android.settingslib.spa.framework.theme.SettingsDimension +import com.android.settingslib.spa.widget.scaffold.RegularScaffold import com.android.settingslib.spa.widget.ui.Footer @Composable @@ -35,15 +28,7 @@ fun AppInfoPage( footerText: String, content: @Composable () -> Unit, ) { - // TODO: Replace with SettingsScaffold - Column(Modifier.verticalScroll(rememberScrollState())) { - Text( - text = title, - modifier = Modifier.padding(SettingsDimension.itemPadding), - color = MaterialTheme.colorScheme.onSurface, - style = MaterialTheme.typography.headlineMedium, - ) - + RegularScaffold(title = title) { AppInfo(packageName, userId) content() diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppList.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppList.kt new file mode 100644 index 000000000000..315dc5d6ff70 --- /dev/null +++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppList.kt @@ -0,0 +1,102 @@ +/* + * 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.settingslib.spaprivileged.template.app + +import android.content.pm.UserInfo +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.lifecycle.viewmodel.compose.viewModel +import com.android.settingslib.spa.framework.compose.LogCompositions +import com.android.settingslib.spa.framework.compose.toState +import com.android.settingslib.spa.framework.theme.SettingsDimension +import com.android.settingslib.spa.widget.ui.PlaceholderTitle +import com.android.settingslib.spaprivileged.R +import com.android.settingslib.spaprivileged.model.app.AppListData +import com.android.settingslib.spaprivileged.model.app.AppListModel +import com.android.settingslib.spaprivileged.model.app.AppListViewModel +import com.android.settingslib.spaprivileged.model.app.AppRecord +import kotlinx.coroutines.Dispatchers + +private const val TAG = "AppList" + +@Composable +internal fun <T : AppRecord> AppList( + userInfo: UserInfo, + listModel: AppListModel<T>, + showSystem: State<Boolean>, + option: State<Int>, + searchQuery: State<String>, + appItem: @Composable (itemState: AppListItemModel<T>) -> Unit, +) { + LogCompositions(TAG, userInfo.id.toString()) + val appListData = loadAppEntries(userInfo, listModel, showSystem, option, searchQuery) + AppListWidget(appListData, listModel, appItem) +} + +@Composable +private fun <T : AppRecord> AppListWidget( + appListData: State<AppListData<T>?>, + listModel: AppListModel<T>, + appItem: @Composable (itemState: AppListItemModel<T>) -> Unit, +) { + appListData.value?.let { (list, option) -> + if (list.isEmpty()) { + PlaceholderTitle(stringResource(R.string.no_applications)) + return + } + LazyColumn( + modifier = Modifier.fillMaxSize(), + state = rememberLazyListState(), + contentPadding = PaddingValues(bottom = SettingsDimension.itemPaddingVertical), + ) { + items(count = list.size, key = { option to list[it].record.app.packageName }) { + val appEntry = list[it] + val summary = listModel.getSummary(option, appEntry.record) ?: "".toState() + val itemModel = remember(appEntry) { + AppListItemModel(appEntry.record, appEntry.label, summary) + } + appItem(itemModel) + } + } + } +} + +@Composable +private fun <T : AppRecord> loadAppEntries( + userInfo: UserInfo, + listModel: AppListModel<T>, + showSystem: State<Boolean>, + option: State<Int>, + searchQuery: State<String>, +): State<AppListData<T>?> { + val viewModel: AppListViewModel<T> = viewModel(key = userInfo.id.toString()) + viewModel.userInfo.setIfAbsent(userInfo) + viewModel.listModel.setIfAbsent(listModel) + viewModel.showSystem.Sync(showSystem) + viewModel.option.Sync(option) + viewModel.searchQuery.Sync(searchQuery) + + return viewModel.appListDataFlow.collectAsState(null, Dispatchers.Default) +} diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppListItem.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppListItem.kt new file mode 100644 index 000000000000..ac3f8ff79091 --- /dev/null +++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppListItem.kt @@ -0,0 +1,64 @@ +/* + * 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.settingslib.spaprivileged.template.app + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.runtime.remember +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.tooling.preview.Preview +import com.android.settingslib.spa.framework.compose.toState +import com.android.settingslib.spa.framework.theme.SettingsDimension +import com.android.settingslib.spa.framework.theme.SettingsTheme +import com.android.settingslib.spa.widget.preference.Preference +import com.android.settingslib.spa.widget.preference.PreferenceModel +import com.android.settingslib.spaprivileged.model.app.AppRecord + +class AppListItemModel<T : AppRecord>( + val record: T, + val label: String, + val summary: State<String>, +) + +@Composable +fun <T : AppRecord> AppListItem( + itemModel: AppListItemModel<T>, + onClick: () -> Unit, +) { + Preference(remember { + object : PreferenceModel { + override val title = itemModel.label + override val summary = itemModel.summary + override val icon = @Composable { + AppIcon(app = itemModel.record.app, size = SettingsDimension.appIconItemSize) + } + override val onClick = onClick + } + }) +} + +@Preview +@Composable +private fun AppListItemPreview() { + SettingsTheme { + val record = object : AppRecord { + override val app = LocalContext.current.applicationInfo + } + val itemModel = AppListItemModel<AppRecord>(record, "Chrome", "Allowed".toState()) + AppListItem(itemModel) {} + } +} diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppListPage.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppListPage.kt new file mode 100644 index 000000000000..dc30e796f64f --- /dev/null +++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/AppListPage.kt @@ -0,0 +1,86 @@ +/* + * 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.settingslib.spaprivileged.template.app + +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import com.android.settingslib.spa.framework.compose.stateOf +import com.android.settingslib.spa.widget.scaffold.MoreOptionsAction +import com.android.settingslib.spa.widget.scaffold.SettingsScaffold +import com.android.settingslib.spaprivileged.R +import com.android.settingslib.spaprivileged.model.app.AppListModel +import com.android.settingslib.spaprivileged.model.app.AppRecord +import com.android.settingslib.spaprivileged.template.common.WorkProfilePager + +@Composable +fun <T : AppRecord> AppListPage( + title: String, + listModel: AppListModel<T>, + appItem: @Composable (itemState: AppListItemModel<T>) -> Unit, +) { + val showSystem = rememberSaveable { mutableStateOf(false) } + // TODO: Use SearchScaffold here. + SettingsScaffold( + title = title, + actions = { + ShowSystemAction(showSystem.value) { showSystem.value = it } + }, + ) { paddingValues -> + Spacer(Modifier.padding(paddingValues)) + WorkProfilePager { userInfo -> + // TODO: Add a Spinner here. + AppList( + userInfo = userInfo, + listModel = listModel, + showSystem = showSystem, + option = stateOf(0), + searchQuery = stateOf(""), + appItem = appItem, + ) + } + } +} + +@Composable +private fun ShowSystemAction(showSystem: Boolean, setShowSystem: (showSystem: Boolean) -> Unit) { + var expanded by remember { mutableStateOf(false) } + MoreOptionsAction { expanded = true } + DropdownMenu( + expanded = expanded, + onDismissRequest = { expanded = false }, + ) { + val menuText = if (showSystem) R.string.menu_hide_system else R.string.menu_show_system + DropdownMenuItem( + text = { Text(stringResource(menuText)) }, + onClick = { + expanded = false + setShowSystem(!showSystem) + }, + ) + } +} diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppInfoPage.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppInfoPage.kt index 430ac5409711..298ecd5106ea 100644 --- a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppInfoPage.kt +++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppInfoPage.kt @@ -17,6 +17,7 @@ package com.android.settingslib.spaprivileged.template.app import android.content.Context +import android.content.pm.ApplicationInfo import android.os.Bundle import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect @@ -28,21 +29,24 @@ import androidx.compose.ui.res.stringResource import androidx.navigation.NavType import androidx.navigation.navArgument import com.android.settingslib.spa.framework.api.SettingsPageProvider +import com.android.settingslib.spa.framework.compose.navigator import com.android.settingslib.spa.framework.compose.rememberContext import com.android.settingslib.spa.widget.preference.SwitchPreference import com.android.settingslib.spa.widget.preference.SwitchPreferenceModel import com.android.settingslib.spaprivileged.model.app.AppRecord import com.android.settingslib.spaprivileged.model.app.PackageManagers +import com.android.settingslib.spaprivileged.model.app.toRoute import kotlinx.coroutines.Dispatchers +private const val NAME = "TogglePermissionAppInfoPage" private const val PERMISSION = "permission" private const val PACKAGE_NAME = "packageName" private const val USER_ID = "userId" -open class TogglePermissionAppInfoPageProvider( +internal class TogglePermissionAppInfoPageProvider( private val factory: TogglePermissionAppListModelFactory, ) : SettingsPageProvider { - override val name = "TogglePermissionAppInfoPage" + override val name = NAME override val arguments = listOf( navArgument(PERMISSION) { type = NavType.StringType }, @@ -60,8 +64,11 @@ open class TogglePermissionAppInfoPageProvider( TogglePermissionAppInfoPage(listModel, packageName, userId) } - fun getRoute(permissionType: String, packageName: String, userId: Int): String = - "$name/$permissionType/$packageName/$userId" + companion object { + @Composable + internal fun navigator(permissionType: String, app: ApplicationInfo) = + navigator(route = "$NAME/$permissionType/${app.toRoute()}") + } } @Composable diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppListModel.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppListModel.kt index 3782f7cd301e..70ff9a478af5 100644 --- a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppListModel.kt +++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppListModel.kt @@ -20,14 +20,25 @@ import android.content.Context import android.content.pm.ApplicationInfo import androidx.compose.runtime.Composable import androidx.compose.runtime.State +import androidx.compose.ui.res.stringResource +import com.android.settingslib.spa.framework.api.SettingsPageProvider +import com.android.settingslib.spa.framework.compose.rememberContext +import com.android.settingslib.spa.framework.util.asyncMapItem +import com.android.settingslib.spa.widget.preference.Preference +import com.android.settingslib.spa.widget.preference.PreferenceModel import com.android.settingslib.spaprivileged.model.app.AppRecord +import kotlinx.coroutines.flow.Flow interface TogglePermissionAppListModel<T : AppRecord> { val pageTitleResId: Int val switchTitleResId: Int val footerResId: Int + fun transform(userIdFlow: Flow<Int>, appListFlow: Flow<List<ApplicationInfo>>): Flow<List<T>> = + appListFlow.asyncMapItem(::transformItem) + fun transformItem(app: ApplicationInfo): T + fun filter(userIdFlow: Flow<Int>, recordListFlow: Flow<List<T>>): Flow<List<T>> @Composable fun isAllowed(record: T): State<Boolean?> @@ -41,4 +52,24 @@ interface TogglePermissionAppListModelFactory { permission: String, context: Context, ): TogglePermissionAppListModel<out AppRecord> + + fun createPageProviders(): List<SettingsPageProvider> = listOf( + TogglePermissionAppListPageProvider(this), + TogglePermissionAppInfoPageProvider(this), + ) + + @Composable + fun EntryItem(permissionType: String) { + val listModel = rememberModel(permissionType) + Preference( + object : PreferenceModel { + override val title = stringResource(listModel.pageTitleResId) + override val onClick = TogglePermissionAppListPageProvider.navigator(permissionType) + } + ) + } } + +@Composable +internal fun TogglePermissionAppListModelFactory.rememberModel(permission: String) = + rememberContext { context -> createModel(permission, context) } diff --git a/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppListPage.kt b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppListPage.kt new file mode 100644 index 000000000000..107bf942a2d6 --- /dev/null +++ b/packages/SettingsLib/SpaPrivileged/src/com/android/settingslib/spaprivileged/template/app/TogglePermissionAppListPage.kt @@ -0,0 +1,106 @@ +/* + * 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.settingslib.spaprivileged.template.app + +import android.content.Context +import android.content.pm.ApplicationInfo +import android.os.Bundle +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.remember +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.navigation.NavType +import androidx.navigation.navArgument +import com.android.settingslib.spa.framework.api.SettingsPageProvider +import com.android.settingslib.spa.framework.compose.navigator +import com.android.settingslib.spaprivileged.R +import com.android.settingslib.spaprivileged.model.app.AppListModel +import com.android.settingslib.spaprivileged.model.app.AppRecord +import kotlinx.coroutines.flow.Flow + +private const val NAME = "TogglePermissionAppList" +private const val PERMISSION = "permission" + +internal class TogglePermissionAppListPageProvider( + private val factory: TogglePermissionAppListModelFactory, +) : SettingsPageProvider { + override val name = NAME + + override val arguments = listOf( + navArgument(PERMISSION) { type = NavType.StringType }, + ) + + @Composable + override fun Page(arguments: Bundle?) { + checkNotNull(arguments) + val permissionType = checkNotNull(arguments.getString(PERMISSION)) + TogglePermissionAppList(permissionType) + } + + @Composable + private fun TogglePermissionAppList(permissionType: String) { + val listModel = factory.rememberModel(permissionType) + val context = LocalContext.current + val internalListModel = remember { + TogglePermissionInternalAppListModel(context, listModel) + } + AppListPage( + title = stringResource(listModel.pageTitleResId), + listModel = internalListModel, + ) { itemModel -> + AppListItem( + itemModel = itemModel, + onClick = TogglePermissionAppInfoPageProvider.navigator( + permissionType = permissionType, + app = itemModel.record.app, + ), + ) + } + } + + companion object { + @Composable + internal fun navigator(permissionType: String) = navigator(route = "$NAME/$permissionType") + } +} + +private class TogglePermissionInternalAppListModel<T : AppRecord>( + private val context: Context, + private val listModel: TogglePermissionAppListModel<T>, +) : AppListModel<T> { + override fun transform(userIdFlow: Flow<Int>, appListFlow: Flow<List<ApplicationInfo>>) = + listModel.transform(userIdFlow, appListFlow) + + override fun filter(userIdFlow: Flow<Int>, option: Int, recordListFlow: Flow<List<T>>) = + listModel.filter(userIdFlow, recordListFlow) + + @Composable + override fun getSummary(option: Int, record: T): State<String> { + val allowed = listModel.isAllowed(record) + return remember { + derivedStateOf { + when (allowed.value) { + true -> context.getString(R.string.app_permission_summary_allowed) + false -> context.getString(R.string.app_permission_summary_not_allowed) + else -> "" + } + } + } + } +} diff --git a/packages/SettingsLib/res/values/strings.xml b/packages/SettingsLib/res/values/strings.xml index aab0d3a08154..06d7bb49c809 100644 --- a/packages/SettingsLib/res/values/strings.xml +++ b/packages/SettingsLib/res/values/strings.xml @@ -1601,21 +1601,6 @@ <!-- Content description of the no calling for accessibility (not shown on the screen). [CHAR LIMIT=NONE] --> <string name="accessibility_no_calling">No calling.</string> - <!-- Screensaver overlay which displays the time. [CHAR LIMIT=20] --> - <string name="dream_complication_title_time">Time</string> - <!-- Screensaver overlay which displays the date. [CHAR LIMIT=20] --> - <string name="dream_complication_title_date">Date</string> - <!-- Screensaver overlay which displays the weather. [CHAR LIMIT=20] --> - <string name="dream_complication_title_weather">Weather</string> - <!-- Screensaver overlay which displays air quality. [CHAR LIMIT=20] --> - <string name="dream_complication_title_aqi">Air Quality</string> - <!-- Screensaver overlay which displays cast info. [CHAR LIMIT=20] --> - <string name="dream_complication_title_cast_info">Cast Info</string> - <!-- Screensaver overlay which displays home controls. [CHAR LIMIT=20] --> - <string name="dream_complication_title_home_controls">Home Controls</string> - <!-- Screensaver overlay which displays smartspace. [CHAR LIMIT=20] --> - <string name="dream_complication_title_smartspace">Smartspace</string> - <!-- Title for a screen allowing the user to choose a profile picture. [CHAR LIMIT=NONE] --> <string name="avatar_picker_title">Choose a profile picture</string> diff --git a/packages/SettingsLib/src/com/android/settingslib/Utils.java b/packages/SettingsLib/src/com/android/settingslib/Utils.java index b9c4030d9d0e..a822e185479a 100644 --- a/packages/SettingsLib/src/com/android/settingslib/Utils.java +++ b/packages/SettingsLib/src/com/android/settingslib/Utils.java @@ -600,6 +600,9 @@ public class Utils { * Returns the WifiInfo for the underlying WiFi network of the VCN network, returns null if the * input NetworkCapabilities is not for a VCN network with underlying WiFi network. * + * TODO(b/238425913): Move this method to be inside systemui not settingslib once we've migrated + * off of {@link WifiStatusTracker} and {@link NetworkControllerImpl}. + * * @param networkCapabilities NetworkCapabilities of the network. */ @Nullable diff --git a/packages/SettingsLib/src/com/android/settingslib/dream/DreamBackend.java b/packages/SettingsLib/src/com/android/settingslib/dream/DreamBackend.java index 22586171e5cf..1606540da3fd 100644 --- a/packages/SettingsLib/src/com/android/settingslib/dream/DreamBackend.java +++ b/packages/SettingsLib/src/com/android/settingslib/dream/DreamBackend.java @@ -17,7 +17,6 @@ package com.android.settingslib.dream; import android.annotation.IntDef; -import android.annotation.Nullable; import android.content.ComponentName; import android.content.Context; import android.content.Intent; @@ -32,17 +31,14 @@ import android.os.ServiceManager; import android.provider.Settings; import android.service.dreams.DreamService; import android.service.dreams.IDreamManager; -import android.text.TextUtils; import android.util.Log; -import com.android.settingslib.R; - import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Comparator; -import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -64,18 +60,21 @@ public class DreamBackend { public String toString() { StringBuilder sb = new StringBuilder(DreamInfo.class.getSimpleName()); sb.append('[').append(caption); - if (isActive) + if (isActive) { sb.append(",active"); + } sb.append(',').append(componentName); - if (settingsComponentName != null) + if (settingsComponentName != null) { sb.append("settings=").append(settingsComponentName); + } return sb.append(']').toString(); } } @Retention(RetentionPolicy.SOURCE) @IntDef({WHILE_CHARGING, WHILE_DOCKED, EITHER, NEVER}) - public @interface WhenToDream {} + public @interface WhenToDream { + } public static final int WHILE_CHARGING = 0; public static final int WHILE_DOCKED = 1; @@ -96,7 +95,8 @@ public class DreamBackend { COMPLICATION_TYPE_SMARTSPACE }) @Retention(RetentionPolicy.SOURCE) - public @interface ComplicationType {} + public @interface ComplicationType { + } public static final int COMPLICATION_TYPE_TIME = 1; public static final int COMPLICATION_TYPE_DATE = 2; @@ -114,8 +114,6 @@ public class DreamBackend { private final boolean mDreamsActivatedOnDockByDefault; private final Set<ComponentName> mDisabledDreams; private final Set<Integer> mSupportedComplications; - private final Set<Integer> mDefaultEnabledComplications; - private static DreamBackend sInstance; public static DreamBackend getInstance(Context context) { @@ -147,13 +145,6 @@ public class DreamBackend { com.android.internal.R.array.config_supportedDreamComplications)) .boxed() .collect(Collectors.toSet()); - - mDefaultEnabledComplications = Arrays.stream(resources.getIntArray( - com.android.internal.R.array.config_dreamComplicationsEnabledByDefault)) - .boxed() - // A complication can only be enabled by default if it is also supported. - .filter(mSupportedComplications::contains) - .collect(Collectors.toSet()); } public List<DreamInfo> getDreamInfos() { @@ -251,11 +242,12 @@ public class DreamBackend { return null; } - public @WhenToDream int getWhenToDreamSetting() { + @WhenToDream + public int getWhenToDreamSetting() { return isActivatedOnDock() && isActivatedOnSleep() ? EITHER : isActivatedOnDock() ? WHILE_DOCKED - : isActivatedOnSleep() ? WHILE_CHARGING - : NEVER; + : isActivatedOnSleep() ? WHILE_CHARGING + : NEVER; } public void setWhenToDream(@WhenToDream int whenToDream) { @@ -283,98 +275,29 @@ public class DreamBackend { } } - /** Returns whether a particular complication is enabled */ - public boolean isComplicationEnabled(@ComplicationType int complication) { - return getEnabledComplications().contains(complication); - } - /** Gets all complications which have been enabled by the user. */ public Set<Integer> getEnabledComplications() { - final String enabledComplications = Settings.Secure.getString( - mContext.getContentResolver(), - Settings.Secure.SCREENSAVER_ENABLED_COMPLICATIONS); - - if (enabledComplications == null) { - return mDefaultEnabledComplications; - } - - return parseFromString(enabledComplications); + return getComplicationsEnabled() ? mSupportedComplications : Collections.emptySet(); } - /** Gets all dream complications which are supported on this device. **/ - public Set<Integer> getSupportedComplications() { - return mSupportedComplications; - } - - /** - * Enables or disables a particular dream complication. - * - * @param complicationType The dream complication to be enabled/disabled. - * @param value If true, the complication is enabled. Otherwise it is disabled. - */ - public void setComplicationEnabled(@ComplicationType int complicationType, boolean value) { - if (!mSupportedComplications.contains(complicationType)) return; - - Set<Integer> enabledComplications = getEnabledComplications(); - if (value) { - enabledComplications.add(complicationType); - } else { - enabledComplications.remove(complicationType); - } - - Settings.Secure.putString(mContext.getContentResolver(), - Settings.Secure.SCREENSAVER_ENABLED_COMPLICATIONS, - convertToString(enabledComplications)); + /** Sets complication enabled state. */ + public void setComplicationsEnabled(boolean enabled) { + Settings.Secure.putInt(mContext.getContentResolver(), + Settings.Secure.SCREENSAVER_COMPLICATIONS_ENABLED, enabled ? 1 : 0); } /** - * Gets the title of a particular complication type to be displayed to the user. If there - * is no title, null is returned. + * Gets whether complications are enabled on this device */ - @Nullable - public CharSequence getComplicationTitle(@ComplicationType int complicationType) { - int res = 0; - switch (complicationType) { - case COMPLICATION_TYPE_TIME: - res = R.string.dream_complication_title_time; - break; - case COMPLICATION_TYPE_DATE: - res = R.string.dream_complication_title_date; - break; - case COMPLICATION_TYPE_WEATHER: - res = R.string.dream_complication_title_weather; - break; - case COMPLICATION_TYPE_AIR_QUALITY: - res = R.string.dream_complication_title_aqi; - break; - case COMPLICATION_TYPE_CAST_INFO: - res = R.string.dream_complication_title_cast_info; - break; - case COMPLICATION_TYPE_HOME_CONTROLS: - res = R.string.dream_complication_title_home_controls; - break; - case COMPLICATION_TYPE_SMARTSPACE: - res = R.string.dream_complication_title_smartspace; - break; - default: - return null; - } - return mContext.getString(res); - } - - private static String convertToString(Set<Integer> set) { - return set.stream() - .map(String::valueOf) - .collect(Collectors.joining(",")); + public boolean getComplicationsEnabled() { + return Settings.Secure.getInt( + mContext.getContentResolver(), + Settings.Secure.SCREENSAVER_COMPLICATIONS_ENABLED, 1) == 1; } - private static Set<Integer> parseFromString(String string) { - if (TextUtils.isEmpty(string)) { - return new HashSet<>(); - } - return Arrays.stream(string.split(",")) - .map(Integer::parseInt) - .collect(Collectors.toSet()); + /** Gets all dream complications which are supported on this device. **/ + public Set<Integer> getSupportedComplications() { + return mSupportedComplications; } public boolean isEnabled() { @@ -416,10 +339,11 @@ public class DreamBackend { public void setActiveDream(ComponentName dream) { logd("setActiveDream(%s)", dream); - if (mDreamManager == null) + if (mDreamManager == null) { return; + } try { - ComponentName[] dreams = { dream }; + ComponentName[] dreams = {dream}; mDreamManager.setDreamComponents(dream == null ? null : dreams); } catch (RemoteException e) { Log.w(TAG, "Failed to set active dream to " + dream, e); @@ -427,8 +351,9 @@ public class DreamBackend { } public ComponentName getActiveDream() { - if (mDreamManager == null) + if (mDreamManager == null) { return null; + } try { ComponentName[] dreams = mDreamManager.getDreamComponents(); return dreams != null && dreams.length > 0 ? dreams[0] : null; diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/dream/DreamBackendTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/dream/DreamBackendTest.java index 86f7850cf1f2..52b9227fb373 100644 --- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/dream/DreamBackendTest.java +++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/dream/DreamBackendTest.java @@ -21,6 +21,7 @@ import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import android.content.ContentResolver; import android.content.Context; import android.content.res.Resources; @@ -34,29 +35,35 @@ import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowSettings; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + @RunWith(RobolectricTestRunner.class) @Config(shadows = {ShadowSettings.ShadowSecure.class}) public final class DreamBackendTest { private static final int[] SUPPORTED_DREAM_COMPLICATIONS = {1, 2, 3}; - private static final int[] DEFAULT_DREAM_COMPLICATIONS = {1, 3, 4}; + private static final List<Integer> SUPPORTED_DREAM_COMPLICATIONS_LIST = Arrays.stream( + SUPPORTED_DREAM_COMPLICATIONS).boxed().collect( + Collectors.toList()); @Mock private Context mContext; + @Mock + private ContentResolver mMockResolver; private DreamBackend mBackend; @Before public void setUp() { MockitoAnnotations.initMocks(this); when(mContext.getApplicationContext()).thenReturn(mContext); + when(mContext.getContentResolver()).thenReturn(mMockResolver); final Resources res = mock(Resources.class); when(mContext.getResources()).thenReturn(res); when(res.getIntArray( com.android.internal.R.array.config_supportedDreamComplications)).thenReturn( SUPPORTED_DREAM_COMPLICATIONS); - when(res.getIntArray( - com.android.internal.R.array.config_dreamComplicationsEnabledByDefault)).thenReturn( - DEFAULT_DREAM_COMPLICATIONS); when(res.getStringArray( com.android.internal.R.array.config_disabledDreamComponents)).thenReturn( new String[]{}); @@ -69,31 +76,25 @@ public final class DreamBackendTest { } @Test - public void testSupportedComplications() { - assertThat(mBackend.getSupportedComplications()).containsExactly(1, 2, 3); - } - - @Test - public void testGetEnabledDreamComplications_default() { - assertThat(mBackend.getEnabledComplications()).containsExactly(1, 3); - } - - @Test - public void testEnableComplication() { - mBackend.setComplicationEnabled(/* complicationType= */ 2, true); - assertThat(mBackend.getEnabledComplications()).containsExactly(1, 2, 3); + public void testComplicationsEnabledByDefault() { + assertThat(mBackend.getComplicationsEnabled()).isTrue(); + assertThat(mBackend.getEnabledComplications()).containsExactlyElementsIn( + SUPPORTED_DREAM_COMPLICATIONS_LIST); } @Test - public void testEnableComplication_notSupported() { - mBackend.setComplicationEnabled(/* complicationType= */ 5, true); - assertThat(mBackend.getEnabledComplications()).containsExactly(1, 3); + public void testEnableComplicationExplicitly() { + mBackend.setComplicationsEnabled(true); + assertThat(mBackend.getEnabledComplications()).containsExactlyElementsIn( + SUPPORTED_DREAM_COMPLICATIONS_LIST); + assertThat(mBackend.getComplicationsEnabled()).isTrue(); } @Test - public void testDisableComplication() { - mBackend.setComplicationEnabled(/* complicationType= */ 1, false); - assertThat(mBackend.getEnabledComplications()).containsExactly(3); + public void testDisableComplications() { + mBackend.setComplicationsEnabled(false); + assertThat(mBackend.getEnabledComplications()).isEmpty(); + assertThat(mBackend.getComplicationsEnabled()).isFalse(); } } diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/MainSwitchBarTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/MainSwitchBarTest.java index d86bd014988e..24037caf4e6c 100644 --- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/MainSwitchBarTest.java +++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/MainSwitchBarTest.java @@ -16,6 +16,8 @@ package com.android.settingslib.widget; +import static android.graphics.text.LineBreakConfig.LINE_BREAK_WORD_STYLE_PHRASE; + import static com.google.common.truth.Truth.assertThat; import android.content.Context; @@ -97,4 +99,14 @@ public class MainSwitchBarTest { assertThat(mBar.getVisibility()).isEqualTo(View.GONE); } + + @Test + public void setTitle_shouldSetCorrectLineBreakStyle() { + final String title = "title"; + + mBar.setTitle(title); + final TextView textView = ((TextView) mBar.findViewById(R.id.switch_text)); + + assertThat(textView.getLineBreakWordStyle()).isEqualTo(LINE_BREAK_WORD_STYLE_PHRASE); + } } diff --git a/packages/SystemUI/AndroidManifest.xml b/packages/SystemUI/AndroidManifest.xml index 652e281e67e9..78dea891bc12 100644 --- a/packages/SystemUI/AndroidManifest.xml +++ b/packages/SystemUI/AndroidManifest.xml @@ -85,6 +85,7 @@ <uses-permission android:name="android.permission.CONTROL_VPN" /> <uses-permission android:name="android.permission.PEERS_MAC_ADDRESS"/> <uses-permission android:name="android.permission.READ_WIFI_CREDENTIAL"/> + <uses-permission android:name="android.permission.NETWORK_STACK"/> <!-- Physical hardware --> <uses-permission android:name="android.permission.MANAGE_USB" /> <uses-permission android:name="android.permission.CONTROL_DISPLAY_BRIGHTNESS" /> diff --git a/packages/SystemUI/res-keyguard/values-land/dimens.xml b/packages/SystemUI/res-keyguard/values-land/dimens.xml index 4e92884f39f3..a4e7a5f12db4 100644 --- a/packages/SystemUI/res-keyguard/values-land/dimens.xml +++ b/packages/SystemUI/res-keyguard/values-land/dimens.xml @@ -22,7 +22,6 @@ <dimen name="keyguard_eca_top_margin">0dp</dimen> <dimen name="keyguard_eca_bottom_margin">2dp</dimen> <dimen name="keyguard_password_height">26dp</dimen> - <dimen name="num_pad_entry_row_margin_bottom">0dp</dimen> <!-- The size of PIN text in the PIN unlock method. --> <integer name="scaled_password_text_size">26</integer> diff --git a/packages/SystemUI/res-keyguard/values-sw360dp-land/dimens.xml b/packages/SystemUI/res-keyguard/values-sw360dp-land/dimens.xml index f465be4f5228..0421135b31a5 100644 --- a/packages/SystemUI/res-keyguard/values-sw360dp-land/dimens.xml +++ b/packages/SystemUI/res-keyguard/values-sw360dp-land/dimens.xml @@ -22,7 +22,6 @@ <dimen name="keyguard_eca_top_margin">4dp</dimen> <dimen name="keyguard_eca_bottom_margin">4dp</dimen> <dimen name="keyguard_password_height">50dp</dimen> - <dimen name="num_pad_entry_row_margin_bottom">4dp</dimen> <!-- The size of PIN text in the PIN unlock method. --> <integer name="scaled_password_text_size">40</integer> diff --git a/packages/SystemUI/res-keyguard/values/dimens.xml b/packages/SystemUI/res-keyguard/values/dimens.xml index acf3e4dcf02a..32871f0abb4f 100644 --- a/packages/SystemUI/res-keyguard/values/dimens.xml +++ b/packages/SystemUI/res-keyguard/values/dimens.xml @@ -86,7 +86,7 @@ <!-- Spacing around each button used for PIN view --> <dimen name="num_pad_key_width">72dp</dimen> - <dimen name="num_pad_entry_row_margin_bottom">16dp</dimen> + <dimen name="num_pad_entry_row_margin_bottom">12dp</dimen> <dimen name="num_pad_row_margin_bottom">6dp</dimen> <dimen name="num_pad_key_margin_end">12dp</dimen> diff --git a/packages/SystemUI/res/layout/new_status_bar_wifi_group.xml b/packages/SystemUI/res/layout/new_status_bar_wifi_group.xml new file mode 100644 index 000000000000..753ba2f21faf --- /dev/null +++ b/packages/SystemUI/res/layout/new_status_bar_wifi_group.xml @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- +** +** Copyright 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. +*/ +--> +<com.android.systemui.statusbar.pipeline.wifi.ui.view.ModernStatusBarWifiView + xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/wifi_combo" + android:layout_width="wrap_content" + android:layout_height="match_parent" + android:gravity="center_vertical" > + + <include layout="@layout/status_bar_wifi_group_inner" /> + +</com.android.systemui.statusbar.pipeline.wifi.ui.view.ModernStatusBarWifiView> diff --git a/packages/SystemUI/res/layout/status_bar_wifi_group.xml b/packages/SystemUI/res/layout/status_bar_wifi_group.xml index 35cce25d45a7..6cb6993bb762 100644 --- a/packages/SystemUI/res/layout/status_bar_wifi_group.xml +++ b/packages/SystemUI/res/layout/status_bar_wifi_group.xml @@ -18,70 +18,11 @@ --> <com.android.systemui.statusbar.StatusBarWifiView xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:systemui="http://schemas.android.com/apk/res-auto" android:id="@+id/wifi_combo" android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="center_vertical" > - <com.android.keyguard.AlphaOptimizedLinearLayout - android:id="@+id/wifi_group" - android:layout_width="wrap_content" - android:layout_height="match_parent" - android:gravity="center_vertical" - android:layout_marginStart="2.5dp" - > - <FrameLayout - android:id="@+id/inout_container" - android:layout_height="17dp" - android:layout_width="wrap_content" - android:gravity="center_vertical" > - <ImageView - android:id="@+id/wifi_in" - android:layout_height="wrap_content" - android:layout_width="wrap_content" - android:src="@drawable/ic_activity_down" - android:visibility="gone" - android:paddingEnd="2dp" - /> - <ImageView - android:id="@+id/wifi_out" - android:layout_height="wrap_content" - android:layout_width="wrap_content" - android:src="@drawable/ic_activity_up" - android:paddingEnd="2dp" - android:visibility="gone" - /> - </FrameLayout> - <FrameLayout - android:id="@+id/wifi_combo" - android:layout_height="wrap_content" - android:layout_width="wrap_content" - android:gravity="center_vertical" > - <com.android.systemui.statusbar.AlphaOptimizedImageView - android:id="@+id/wifi_signal" - android:layout_height="@dimen/status_bar_wifi_signal_size" - android:layout_width="@dimen/status_bar_wifi_signal_size" /> - </FrameLayout> + <include layout="@layout/status_bar_wifi_group_inner" /> - <View - android:id="@+id/wifi_signal_spacer" - android:layout_width="@dimen/status_bar_wifi_signal_spacer_width" - android:layout_height="4dp" - android:visibility="gone" /> - - <!-- Looks like CarStatusBar uses this... --> - <ViewStub - android:id="@+id/connected_device_signals_stub" - android:layout="@layout/connected_device_signal" - android:layout_width="wrap_content" - android:layout_height="wrap_content" /> - - <View - android:id="@+id/wifi_airplane_spacer" - android:layout_width="@dimen/status_bar_airplane_spacer_width" - android:layout_height="4dp" - android:visibility="gone" - /> - </com.android.keyguard.AlphaOptimizedLinearLayout> -</com.android.systemui.statusbar.StatusBarWifiView> +</com.android.systemui.statusbar.StatusBarWifiView>
\ No newline at end of file diff --git a/packages/SystemUI/res/layout/status_bar_wifi_group_inner.xml b/packages/SystemUI/res/layout/status_bar_wifi_group_inner.xml new file mode 100644 index 000000000000..0ea0653ab89f --- /dev/null +++ b/packages/SystemUI/res/layout/status_bar_wifi_group_inner.xml @@ -0,0 +1,82 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- +** +** Copyright 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. +*/ +--> + +<merge xmlns:android="http://schemas.android.com/apk/res/android"> + + <com.android.keyguard.AlphaOptimizedLinearLayout + android:id="@+id/wifi_group" + android:layout_width="wrap_content" + android:layout_height="match_parent" + android:gravity="center_vertical" + android:layout_marginStart="2.5dp" + > + <FrameLayout + android:id="@+id/inout_container" + android:layout_height="17dp" + android:layout_width="wrap_content" + android:gravity="center_vertical" > + <ImageView + android:id="@+id/wifi_in" + android:layout_height="wrap_content" + android:layout_width="wrap_content" + android:src="@drawable/ic_activity_down" + android:visibility="gone" + android:paddingEnd="2dp" + /> + <ImageView + android:id="@+id/wifi_out" + android:layout_height="wrap_content" + android:layout_width="wrap_content" + android:src="@drawable/ic_activity_up" + android:paddingEnd="2dp" + android:visibility="gone" + /> + </FrameLayout> + <FrameLayout + android:id="@+id/wifi_combo" + android:layout_height="wrap_content" + android:layout_width="wrap_content" + android:gravity="center_vertical" > + <com.android.systemui.statusbar.AlphaOptimizedImageView + android:id="@+id/wifi_signal" + android:layout_height="@dimen/status_bar_wifi_signal_size" + android:layout_width="@dimen/status_bar_wifi_signal_size" /> + </FrameLayout> + + <View + android:id="@+id/wifi_signal_spacer" + android:layout_width="@dimen/status_bar_wifi_signal_spacer_width" + android:layout_height="4dp" + android:visibility="gone" /> + + <!-- Looks like CarStatusBar uses this... --> + <ViewStub + android:id="@+id/connected_device_signals_stub" + android:layout="@layout/connected_device_signal" + android:layout_width="wrap_content" + android:layout_height="wrap_content" /> + + <View + android:id="@+id/wifi_airplane_spacer" + android:layout_width="@dimen/status_bar_airplane_spacer_width" + android:layout_height="4dp" + android:visibility="gone" + /> + </com.android.keyguard.AlphaOptimizedLinearLayout> +</merge> diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml index 7c1fdd548066..ae30089358fe 100644 --- a/packages/SystemUI/res/values/dimens.xml +++ b/packages/SystemUI/res/values/dimens.xml @@ -1179,7 +1179,6 @@ <item name="shutdown_scrim_behind_alpha" format="float" type="dimen">0.95</item> <!-- Output switcher panel related dimensions --> - <dimen name="media_output_dialog_list_margin">12dp</dimen> <dimen name="media_output_dialog_list_max_height">355dp</dimen> <dimen name="media_output_dialog_header_album_icon_size">72dp</dimen> <dimen name="media_output_dialog_header_back_icon_size">32dp</dimen> diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/regionsampling/RegionSamplingInstance.kt b/packages/SystemUI/shared/src/com/android/systemui/shared/regionsampling/RegionSamplingInstance.kt index 0146795f4988..dd2e55d4e7d7 100644 --- a/packages/SystemUI/shared/src/com/android/systemui/shared/regionsampling/RegionSamplingInstance.kt +++ b/packages/SystemUI/shared/src/com/android/systemui/shared/regionsampling/RegionSamplingInstance.kt @@ -35,6 +35,7 @@ open class RegionSamplingInstance( ) { private var isDark = RegionDarkness.DEFAULT private var samplingBounds = Rect() + private val tmpScreenLocation = IntArray(2) @VisibleForTesting var regionSampler: RegionSamplingHelper? = null /** @@ -99,10 +100,21 @@ open class RegionSamplingInstance( isDark = convertToClockDarkness(isRegionDark) updateFun.updateColors() } - + /** + * The method getLocationOnScreen is used to obtain the view coordinates + * relative to its left and top edges on the device screen. + * Directly accessing the X and Y coordinates of the view returns the + * location relative to its parent view instead. + */ override fun getSampledRegion(sampledView: View): Rect { - samplingBounds = Rect(sampledView.left, sampledView.top, - sampledView.right, sampledView.bottom) + val screenLocation = tmpScreenLocation + sampledView.getLocationOnScreen(screenLocation) + val left = screenLocation[0] + val top = screenLocation[1] + samplingBounds.left = left + samplingBounds.top = top + samplingBounds.right = left + sampledView.width + samplingBounds.bottom = top + sampledView.height return samplingBounds } diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/rotation/RotationButtonController.java b/packages/SystemUI/shared/src/com/android/systemui/shared/rotation/RotationButtonController.java index b29dc835a6f4..22bffda33918 100644 --- a/packages/SystemUI/shared/src/com/android/systemui/shared/rotation/RotationButtonController.java +++ b/packages/SystemUI/shared/src/com/android/systemui/shared/rotation/RotationButtonController.java @@ -49,6 +49,7 @@ import android.view.accessibility.AccessibilityManager; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; +import com.android.internal.annotations.VisibleForTesting; import com.android.internal.logging.UiEvent; import com.android.internal.logging.UiEventLogger; import com.android.internal.logging.UiEventLoggerImpl; @@ -99,6 +100,7 @@ public class RotationButtonController { private @WindowInsetsController.Behavior int mBehavior = WindowInsetsController.BEHAVIOR_DEFAULT; private int mNavBarMode; + private boolean mTaskBarVisible = false; private boolean mSkipOverrideUserLockPrefsOnce; private final int mLightIconColor; private final int mDarkIconColor; @@ -422,6 +424,7 @@ public class RotationButtonController { } public void onTaskbarStateChange(boolean visible, boolean stashed) { + mTaskBarVisible = visible; if (getRotationButton() == null) { return; } @@ -438,9 +441,12 @@ public class RotationButtonController { * Return true when either the task bar is visible or it's in visual immersive mode. */ @SuppressLint("InlinedApi") - private boolean canShowRotationButton() { - return mIsNavigationBarShowing || mBehavior == WindowInsetsController.BEHAVIOR_DEFAULT - || isGesturalMode(mNavBarMode); + @VisibleForTesting + boolean canShowRotationButton() { + return mIsNavigationBarShowing + || mBehavior == WindowInsetsController.BEHAVIOR_DEFAULT + || isGesturalMode(mNavBarMode) + || mTaskBarVisible; } @DrawableRes @@ -624,4 +630,3 @@ public class RotationButtonController { } } } - diff --git a/packages/SystemUI/src/com/android/keyguard/logging/KeyguardUpdateMonitorLogger.kt b/packages/SystemUI/src/com/android/keyguard/logging/KeyguardUpdateMonitorLogger.kt index d718a240bbfd..6c452bd97ff6 100644 --- a/packages/SystemUI/src/com/android/keyguard/logging/KeyguardUpdateMonitorLogger.kt +++ b/packages/SystemUI/src/com/android/keyguard/logging/KeyguardUpdateMonitorLogger.kt @@ -45,7 +45,7 @@ class KeyguardUpdateMonitorLogger @Inject constructor( fun e(@CompileTimeConstant msg: String) = log(msg, ERROR) - fun v(@CompileTimeConstant msg: String) = log(msg, ERROR) + fun v(@CompileTimeConstant msg: String) = log(msg, VERBOSE) fun w(@CompileTimeConstant msg: String) = log(msg, WARNING) diff --git a/packages/SystemUI/src/com/android/keyguard/logging/KeyguardViewMediatorLogger.kt b/packages/SystemUI/src/com/android/keyguard/logging/KeyguardViewMediatorLogger.kt new file mode 100644 index 000000000000..f54bf026a686 --- /dev/null +++ b/packages/SystemUI/src/com/android/keyguard/logging/KeyguardViewMediatorLogger.kt @@ -0,0 +1,690 @@ +/* + * 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.keyguard.logging + +import android.os.RemoteException +import android.view.WindowManagerPolicyConstants +import com.android.systemui.dagger.SysUISingleton +import com.android.systemui.log.LogBuffer +import com.android.systemui.log.LogLevel.DEBUG +import com.android.systemui.log.LogLevel.ERROR +import com.android.systemui.log.LogLevel.INFO +import com.android.systemui.log.LogLevel.WARNING +import com.android.systemui.log.LogLevel.WTF +import com.android.systemui.log.dagger.KeyguardViewMediatorLog +import javax.inject.Inject + +private const val TAG = "KeyguardViewMediatorLog" + +@SysUISingleton +class KeyguardViewMediatorLogger @Inject constructor( + @KeyguardViewMediatorLog private val logBuffer: LogBuffer, +) { + + fun logFailedLoadLockSound(soundPath: String) { + logBuffer.log( + TAG, + WARNING, + { str1 = soundPath }, + { "failed to load lock sound from $str1" } + ) + } + + fun logFailedLoadUnlockSound(soundPath: String) { + logBuffer.log( + TAG, + WARNING, + { str1 = soundPath }, + { "failed to load unlock sound from $str1" } + ) + } + + fun logFailedLoadTrustedSound(soundPath: String) { + logBuffer.log( + TAG, + WARNING, + { str1 = soundPath }, + { "failed to load trusted sound from $str1" } + ) + } + + fun logOnSystemReady() { + logBuffer.log(TAG, DEBUG, "onSystemReady") + } + + fun logOnStartedGoingToSleep(offReason: Int) { + val offReasonString = WindowManagerPolicyConstants.offReasonToString(offReason) + logBuffer.log( + TAG, + DEBUG, + { str1 = offReasonString }, + { "onStartedGoingToSleep($str1)" } + ) + } + + fun logPendingExitSecureCallbackCancelled() { + logBuffer.log(TAG, DEBUG, "pending exit secure callback cancelled") + } + + fun logFailedOnKeyguardExitResultFalse(remoteException: RemoteException) { + logBuffer.log( + TAG, + WARNING, + "Failed to call onKeyguardExitResult(false)", + remoteException + ) + } + + fun logOnFinishedGoingToSleep(offReason: Int) { + val offReasonString = WindowManagerPolicyConstants.offReasonToString(offReason) + logBuffer.log( + TAG, + DEBUG, + { str1 = offReasonString }, + { "onFinishedGoingToSleep($str1)" } + ) + } + + fun logPinLockRequestedStartingKeyguard() { + logBuffer.log(TAG, INFO, "PIN lock requested, starting keyguard") + } + + fun logUserSwitching(userId: Int) { + logBuffer.log( + TAG, + DEBUG, + { int1 = userId }, + { "onUserSwitching $int1" } + ) + } + + fun logOnUserSwitchComplete(userId: Int) { + logBuffer.log( + TAG, + DEBUG, + { int1 = userId }, + { "onUserSwitchComplete $int1" } + ) + } + + fun logOnSimStateChanged(subId: Int, slotId: Int, simState: String) { + logBuffer.log( + TAG, + DEBUG, + { + int1 = subId + int2 = slotId + str1 = simState + }, + { "onSimStateChanged(subId=$int1, slotId=$int2, state=$str1)" } + ) + } + + fun logFailedToCallOnSimSecureStateChanged(remoteException: RemoteException) { + logBuffer.log( + TAG, + WARNING, + "Failed to call onSimSecureStateChanged", + remoteException + ) + } + + fun logIccAbsentIsNotShowing() { + logBuffer.log(TAG, DEBUG, "ICC_ABSENT isn't showing, we need to show the " + + "keyguard since the device isn't provisioned yet.") + } + + fun logSimMovedToAbsent() { + logBuffer.log(TAG, DEBUG, "SIM moved to ABSENT when the " + + "previous state was locked. Reset the state.") + } + + fun logIntentValueIccLocked() { + logBuffer.log(TAG, DEBUG, "INTENT_VALUE_ICC_LOCKED and keyguard isn't " + + "showing; need to show keyguard so user can enter sim pin") + } + + fun logPermDisabledKeyguardNotShowing() { + logBuffer.log(TAG, DEBUG, "PERM_DISABLED and keyguard isn't showing.") + } + + fun logPermDisabledResetStateLocked() { + logBuffer.log(TAG, DEBUG, "PERM_DISABLED, resetStateLocked to show permanently " + + "disabled message in lockscreen.") + } + + fun logReadyResetState(showing: Boolean) { + logBuffer.log( + TAG, + DEBUG, + { bool1 = showing }, + { "READY, reset state? $bool1"} + ) + } + + fun logSimMovedToReady() { + logBuffer.log(TAG, DEBUG, "SIM moved to READY when the previously was locked. " + + "Reset the state.") + } + + fun logUnspecifiedSimState(simState: Int) { + logBuffer.log( + TAG, + DEBUG, + { int1 = simState }, + { "Unspecific state: $int1" } + ) + } + + fun logOccludeLaunchAnimationCancelled(occluded: Boolean) { + logBuffer.log( + TAG, + DEBUG, + { bool1 = occluded }, + { "Occlude launch animation cancelled. Occluded state is now: $bool1"} + ) + } + + fun logActivityLaunchAnimatorLaunchContainerChanged() { + logBuffer.log(TAG, WTF, "Someone tried to change the launch container for the " + + "ActivityLaunchAnimator, which should never happen.") + } + + fun logVerifyUnlock() { + logBuffer.log(TAG, DEBUG, "verifyUnlock") + } + + fun logIgnoreUnlockDeviceNotProvisioned() { + logBuffer.log(TAG, DEBUG, "ignoring because device isn't provisioned") + } + + fun logFailedToCallOnKeyguardExitResultFalse(remoteException: RemoteException) { + logBuffer.log( + TAG, + WARNING, + "Failed to call onKeyguardExitResult(false)", + remoteException + ) + } + + fun logVerifyUnlockCalledNotExternallyDisabled() { + logBuffer.log(TAG, WARNING, "verifyUnlock called when not externally disabled") + } + + fun logSetOccluded(isOccluded: Boolean) { + logBuffer.log( + TAG, + DEBUG, + { bool1 = isOccluded }, + { "setOccluded($bool1)" } + ) + } + + fun logHandleSetOccluded(isOccluded: Boolean) { + logBuffer.log( + TAG, + DEBUG, + { bool1 = isOccluded }, + { "handleSetOccluded($bool1)" } + ) + } + + fun logIgnoreHandleShow() { + logBuffer.log(TAG, DEBUG, "ignoring handleShow because system is not ready.") + } + + fun logHandleShow() { + logBuffer.log(TAG, DEBUG, "handleShow") + } + + fun logHandleHide() { + logBuffer.log(TAG, DEBUG, "handleHide") + } + + fun logSplitSystemUserQuitUnlocking() { + logBuffer.log(TAG, DEBUG, "Split system user, quit unlocking.") + } + + fun logHandleStartKeyguardExitAnimation(startTime: Long, fadeoutDuration: Long) { + logBuffer.log( + TAG, + DEBUG, + { + long1 = startTime + long2 = fadeoutDuration + }, + { "handleStartKeyguardExitAnimation startTime=$long1 fadeoutDuration=$long2" } + ) + } + + fun logHandleVerifyUnlock() { + logBuffer.log(TAG, DEBUG, "handleVerifyUnlock") + } + + fun logHandleNotifyStartedGoingToSleep() { + logBuffer.log(TAG, DEBUG, "handleNotifyStartedGoingToSleep") + } + + fun logHandleNotifyFinishedGoingToSleep() { + logBuffer.log(TAG, DEBUG, "handleNotifyFinishedGoingToSleep") + } + + fun logHandleNotifyWakingUp() { + logBuffer.log(TAG, DEBUG, "handleNotifyWakingUp") + } + + fun logHandleReset() { + logBuffer.log(TAG, DEBUG, "handleReset") + } + + fun logKeyguardDone() { + logBuffer.log(TAG, DEBUG, "keyguardDone") + } + + fun logKeyguardDonePending() { + logBuffer.log(TAG, DEBUG, "keyguardDonePending") + } + + fun logKeyguardGone() { + logBuffer.log(TAG, DEBUG, "keyguardGone") + } + + fun logUnoccludeAnimationCancelled(isOccluded: Boolean) { + logBuffer.log( + TAG, + DEBUG, + { bool1 = isOccluded }, + { "Unocclude animation cancelled. Occluded state is now: $bool1" } + ) + } + + fun logShowLocked() { + logBuffer.log(TAG, DEBUG, "showLocked") + } + + fun logHideLocked() { + logBuffer.log(TAG, DEBUG, "hideLocked") + } + + fun logResetStateLocked() { + logBuffer.log(TAG, DEBUG, "resetStateLocked") + } + + fun logNotifyStartedGoingToSleep() { + logBuffer.log(TAG, DEBUG, "notifyStartedGoingToSleep") + } + + fun logNotifyFinishedGoingToSleep() { + logBuffer.log(TAG, DEBUG, "notifyFinishedGoingToSleep") + } + + fun logNotifyStartedWakingUp() { + logBuffer.log(TAG, DEBUG, "notifyStartedWakingUp") + } + + fun logDoKeyguardShowingLockScreen() { + logBuffer.log(TAG, DEBUG, "doKeyguard: showing the lock screen") + } + + fun logDoKeyguardNotShowingLockScreenOff() { + logBuffer.log(TAG, DEBUG, "doKeyguard: not showing because lockscreen is off") + } + + fun logDoKeyguardNotShowingDeviceNotProvisioned() { + logBuffer.log(TAG, DEBUG, "doKeyguard: not showing because device isn't " + + "provisioned and the sim is not locked or missing") + } + + fun logDoKeyguardNotShowingAlreadyShowing() { + logBuffer.log(TAG, DEBUG, "doKeyguard: not showing because it is already showing") + } + + fun logDoKeyguardNotShowingBootingCryptkeeper() { + logBuffer.log(TAG, DEBUG, "doKeyguard: not showing because booting to cryptkeeper") + } + + fun logDoKeyguardNotShowingExternallyDisabled() { + logBuffer.log(TAG, DEBUG, "doKeyguard: not showing because externally disabled") + } + + fun logFailedToCallOnDeviceProvisioned(remoteException: RemoteException) { + logBuffer.log( + TAG, + WARNING, + "Failed to call onDeviceProvisioned", + remoteException + ) + } + + fun logMaybeHandlePendingLockNotHandling() { + logBuffer.log(TAG, DEBUG, "#maybeHandlePendingLock: not handling because the " + + "screen off animation's isKeyguardShowDelayed() returned true. This should be " + + "handled soon by #onStartedWakingUp, or by the end actions of the " + + "screen off animation.") + } + + fun logMaybeHandlePendingLockKeyguardGoingAway() { + logBuffer.log(TAG, DEBUG, "#maybeHandlePendingLock: not handling because the " + + "keyguard is going away. This should be handled shortly by " + + "StatusBar#finishKeyguardFadingAway.") + } + + fun logMaybeHandlePendingLockHandling() { + logBuffer.log(TAG, DEBUG, "#maybeHandlePendingLock: handling pending lock; " + + "locking keyguard.") + } + + fun logSetAlarmToTurnOffKeyguard(delayedShowingSequence: Int) { + logBuffer.log( + TAG, + DEBUG, + { int1 = delayedShowingSequence }, + { "setting alarm to turn off keyguard, seq = $int1" } + ) + } + + fun logOnStartedWakingUp(delayedShowingSequence: Int) { + logBuffer.log( + TAG, + DEBUG, + { int1 = delayedShowingSequence }, + { "onStartedWakingUp, seq = $int1" } + ) + } + + fun logSetKeyguardEnabled(enabled: Boolean) { + logBuffer.log( + TAG, + DEBUG, + { bool1 = enabled }, + { "setKeyguardEnabled($bool1)" } + ) + } + + fun logIgnoreVerifyUnlockRequest() { + logBuffer.log(TAG, DEBUG, "in process of verifyUnlock request, ignoring") + } + + fun logRememberToReshowLater() { + logBuffer.log(TAG, DEBUG, "remembering to reshow, hiding keyguard, disabling " + + "status bar expansion") + } + + fun logPreviouslyHiddenReshow() { + logBuffer.log(TAG, DEBUG, "previously hidden, reshowing, reenabling status " + + "bar expansion") + } + + fun logOnKeyguardExitResultFalseResetting() { + logBuffer.log(TAG, DEBUG, "onKeyguardExitResult(false), resetting") + } + + fun logWaitingUntilKeyguardVisibleIsFalse() { + logBuffer.log(TAG, DEBUG, "waiting until mWaitingUntilKeyguardVisible is false") + } + + fun logDoneWaitingUntilKeyguardVisible() { + logBuffer.log(TAG, DEBUG, "done waiting for mWaitingUntilKeyguardVisible") + } + + fun logUnoccludeAnimatorOnAnimationStart() { + logBuffer.log(TAG, DEBUG, "UnoccludeAnimator#onAnimationStart. " + + "Set occluded = false.") + } + + fun logNoAppsProvidedToUnoccludeRunner() { + logBuffer.log(TAG, DEBUG, "No apps provided to unocclude runner; " + + "skipping animation and unoccluding.") + } + + fun logReceivedDelayedKeyguardAction(sequence: Int, delayedShowingSequence: Int) { + logBuffer.log( + TAG, + DEBUG, + { + int1 = sequence + int2 = delayedShowingSequence + }, + { + "received DELAYED_KEYGUARD_ACTION with seq = $int1 " + + "mDelayedShowingSequence = $int2" + } + ) + } + + fun logTimeoutWhileActivityDrawn() { + logBuffer.log(TAG, WARNING, "Timeout while waiting for activity drawn") + } + + fun logTryKeyguardDonePending( + keyguardDonePending: Boolean, + hideAnimationRun: Boolean, + hideAnimationRunning: Boolean + ) { + logBuffer.log(TAG, DEBUG, + { + bool1 = keyguardDonePending + bool2 = hideAnimationRun + bool3 = hideAnimationRunning + }, + { "tryKeyguardDone: pending - $bool1, animRan - $bool2 animRunning - $bool3" } + ) + } + + fun logTryKeyguardDonePreHideAnimation() { + logBuffer.log(TAG, DEBUG, "tryKeyguardDone: starting pre-hide animation") + } + + fun logHandleKeyguardDone() { + logBuffer.log(TAG, DEBUG, "handleKeyguardDone") + } + + fun logDeviceGoingToSleep() { + logBuffer.log(TAG, INFO, "Device is going to sleep, aborting keyguardDone") + } + + fun logFailedToCallOnKeyguardExitResultTrue(remoteException: RemoteException) { + logBuffer.log( + TAG, + WARNING, + "Failed to call onKeyguardExitResult(true)", + remoteException + ) + } + + fun logHandleKeyguardDoneDrawing() { + logBuffer.log(TAG, DEBUG, "handleKeyguardDoneDrawing") + } + + fun logHandleKeyguardDoneDrawingNotifyingKeyguardVisible() { + logBuffer.log(TAG, DEBUG, "handleKeyguardDoneDrawing: notifying " + + "mWaitingUntilKeyguardVisible") + } + + fun logUpdateActivityLockScreenState(showing: Boolean, aodShowing: Boolean) { + logBuffer.log( + TAG, + DEBUG, + { + bool1 = showing + bool2 = aodShowing + }, + { "updateActivityLockScreenState($bool1, $bool2)" } + ) + } + + fun logFailedToCallSetLockScreenShown(remoteException: RemoteException) { + logBuffer.log( + TAG, + WARNING, + "Failed to call setLockScreenShown", + remoteException + ) + } + + fun logKeyguardGoingAway() { + logBuffer.log(TAG, DEBUG, "keyguardGoingAway") + } + + fun logFailedToCallKeyguardGoingAway(keyguardFlag: Int, remoteException: RemoteException) { + logBuffer.log( + TAG, + ERROR, + { int1 = keyguardFlag }, + { "Failed to call keyguardGoingAway($int1)" }, + remoteException + ) + } + + fun logHideAnimationFinishedRunnable() { + logBuffer.log(TAG, WARNING, "mHideAnimationFinishedRunnable#run") + } + + fun logFailedToCallOnAnimationFinished(remoteException: RemoteException) { + logBuffer.log( + TAG, + WARNING, + "Failed to call onAnimationFinished", + remoteException + ) + } + + fun logFailedToCallOnAnimationStart(remoteException: RemoteException) { + logBuffer.log( + TAG, + WARNING, + "Failed to call onAnimationStart", + remoteException + ) + } + + fun logOnKeyguardExitRemoteAnimationFinished() { + logBuffer.log(TAG, DEBUG, "onKeyguardExitRemoteAnimationFinished") + } + + fun logSkipOnKeyguardExitRemoteAnimationFinished( + cancelled: Boolean, + surfaceBehindRemoteAnimationRunning: Boolean, + surfaceBehindRemoteAnimationRequested: Boolean + ) { + logBuffer.log( + TAG, + DEBUG, + { + bool1 = cancelled + bool2 = surfaceBehindRemoteAnimationRunning + bool3 = surfaceBehindRemoteAnimationRequested + }, + { + "skip onKeyguardExitRemoteAnimationFinished cancelled=$bool1 " + + "surfaceAnimationRunning=$bool2 " + + "surfaceAnimationRequested=$bool3" + } + ) + } + + fun logOnKeyguardExitRemoteAnimationFinishedHideKeyguardView() { + logBuffer.log(TAG, DEBUG, "onKeyguardExitRemoteAnimationFinished" + + "#hideKeyguardViewAfterRemoteAnimation") + } + + fun logSkipHideKeyguardViewAfterRemoteAnimation( + dismissingFromSwipe: Boolean, + wasShowing: Boolean + ) { + logBuffer.log( + TAG, + DEBUG, + { + bool1 = dismissingFromSwipe + bool2 = wasShowing + }, + { + "skip hideKeyguardViewAfterRemoteAnimation dismissFromSwipe=$bool1 " + + "wasShowing=$bool2" + } + ) + } + + fun logCouldNotGetStatusBarManager() { + logBuffer.log(TAG, WARNING, "Could not get status bar manager") + } + + fun logAdjustStatusBarLocked( + showing: Boolean, + occluded: Boolean, + secure: Boolean, + forceHideHomeRecentsButtons: Boolean, + flags: String + ) { + logBuffer.log( + TAG, + DEBUG, + { + bool1 = showing + bool2 = occluded + bool3 = secure + bool4 = forceHideHomeRecentsButtons + str3 = flags + }, + { + "adjustStatusBarLocked: mShowing=$bool1 mOccluded=$bool2 isSecure=$bool3 " + + "force=$bool4 --> flags=0x$str3" + } + ) + } + + fun logFailedToCallOnShowingStateChanged(remoteException: RemoteException) { + logBuffer.log( + TAG, + WARNING, + "Failed to call onShowingStateChanged", + remoteException + ) + } + + fun logFailedToCallNotifyTrustedChangedLocked(remoteException: RemoteException) { + logBuffer.log( + TAG, + WARNING, + "Failed to call notifyTrustedChangedLocked", + remoteException + ) + } + + fun logFailedToCallIKeyguardStateCallback(remoteException: RemoteException) { + logBuffer.log( + TAG, + WARNING, + "Failed to call to IKeyguardStateCallback", + remoteException + ) + } + + fun logOccludeAnimatorOnAnimationStart() { + logBuffer.log(TAG, DEBUG, "OccludeAnimator#onAnimationStart. Set occluded = true.") + } + + fun logOccludeAnimationCancelledByWm(isKeyguardOccluded: Boolean) { + logBuffer.log( + TAG, + DEBUG, + { bool1 = isKeyguardOccluded }, + { "Occlude animation cancelled by WM. Setting occluded state to: $bool1" } + ) + } +}
\ No newline at end of file diff --git a/packages/SystemUI/src/com/android/systemui/ActivityIntentHelper.java b/packages/SystemUI/src/com/android/systemui/ActivityIntentHelper.java index 43b3929808b3..df65bcf9c10d 100644 --- a/packages/SystemUI/src/com/android/systemui/ActivityIntentHelper.java +++ b/packages/SystemUI/src/com/android/systemui/ActivityIntentHelper.java @@ -16,6 +16,7 @@ package com.android.systemui; +import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; @@ -34,12 +35,12 @@ import javax.inject.Inject; @SysUISingleton public class ActivityIntentHelper { - private final Context mContext; + private final PackageManager mPm; @Inject public ActivityIntentHelper(Context context) { // TODO: inject a package manager, not a context. - mContext = context; + mPm = context.getPackageManager(); } /** @@ -57,6 +58,15 @@ public class ActivityIntentHelper { } /** + * @see #wouldLaunchResolverActivity(Intent, int) + */ + public boolean wouldPendingLaunchResolverActivity(PendingIntent intent, int currentUserId) { + ActivityInfo targetActivityInfo = getPendingTargetActivityInfo(intent, currentUserId, + false /* onlyDirectBootAware */); + return targetActivityInfo == null; + } + + /** * Returns info about the target Activity of a given intent, or null if the intent does not * resolve to a specific component meeting the requirements. * @@ -68,19 +78,45 @@ public class ActivityIntentHelper { */ public ActivityInfo getTargetActivityInfo(Intent intent, int currentUserId, boolean onlyDirectBootAware) { - PackageManager packageManager = mContext.getPackageManager(); - int flags = PackageManager.MATCH_DEFAULT_ONLY; + int flags = PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_META_DATA; if (!onlyDirectBootAware) { flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE; } - final List<ResolveInfo> appList = packageManager.queryIntentActivitiesAsUser( + final List<ResolveInfo> appList = mPm.queryIntentActivitiesAsUser( intent, flags, currentUserId); if (appList.size() == 0) { return null; } - ResolveInfo resolved = packageManager.resolveActivityAsUser(intent, - flags | PackageManager.GET_META_DATA, currentUserId); + if (appList.size() == 1) { + return appList.get(0).activityInfo; + } + ResolveInfo resolved = mPm.resolveActivityAsUser(intent, flags, currentUserId); + if (resolved == null || wouldLaunchResolverActivity(resolved, appList)) { + return null; + } else { + return resolved.activityInfo; + } + } + + /** + * @see #getTargetActivityInfo(Intent, int, boolean) + */ + public ActivityInfo getPendingTargetActivityInfo(PendingIntent intent, int currentUserId, + boolean onlyDirectBootAware) { + int flags = PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_META_DATA; + if (!onlyDirectBootAware) { + flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE + | PackageManager.MATCH_DIRECT_BOOT_UNAWARE; + } + final List<ResolveInfo> appList = intent.queryIntentComponents(flags); + if (appList.size() == 0) { + return null; + } + if (appList.size() == 1) { + return appList.get(0).activityInfo; + } + ResolveInfo resolved = mPm.resolveActivityAsUser(intent.getIntent(), flags, currentUserId); if (resolved == null || wouldLaunchResolverActivity(resolved, appList)) { return null; } else { @@ -104,6 +140,17 @@ public class ActivityIntentHelper { } /** + * @see #wouldShowOverLockscreen(Intent, int) + */ + public boolean wouldPendingShowOverLockscreen(PendingIntent intent, int currentUserId) { + ActivityInfo targetActivityInfo = getPendingTargetActivityInfo(intent, + currentUserId, false /* onlyDirectBootAware */); + return targetActivityInfo != null + && (targetActivityInfo.flags & (ActivityInfo.FLAG_SHOW_WHEN_LOCKED + | ActivityInfo.FLAG_SHOW_FOR_ALL_USERS)) > 0; + } + + /** * Determines if sending the given intent would result in starting an Intent resolver activity, * instead of resolving to a specific component. * diff --git a/packages/SystemUI/src/com/android/systemui/GuestSessionNotification.java b/packages/SystemUI/src/com/android/systemui/GuestSessionNotification.java index b0eaab97c5ac..fa9a83ec9913 100644 --- a/packages/SystemUI/src/com/android/systemui/GuestSessionNotification.java +++ b/packages/SystemUI/src/com/android/systemui/GuestSessionNotification.java @@ -25,7 +25,6 @@ import android.content.pm.UserInfo; import android.os.Bundle; import android.os.UserHandle; import android.provider.Settings; -import android.util.FeatureFlagUtils; import com.android.internal.messages.nano.SystemMessageProto; import com.android.systemui.util.NotificationChannels; @@ -59,10 +58,8 @@ public final class GuestSessionNotification { } void createPersistentNotification(UserInfo userInfo, boolean isGuestFirstLogin) { - if (!FeatureFlagUtils.isEnabled(mContext, - FeatureFlagUtils.SETTINGS_GUEST_MODE_UX_CHANGES) - || !userInfo.isGuest()) { - // we create a persistent notification only if enabled and only for guests + if (!userInfo.isGuest()) { + // we create a persistent notification only for guests return; } String contentText; diff --git a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java index 2dadf573fd12..e549a96079bd 100644 --- a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java +++ b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java @@ -241,7 +241,6 @@ public abstract class SystemUIModule { notifCollection, notifPipeline, sysUiState, - dumpManager, sysuiMainExecutor)); } diff --git a/packages/SystemUI/src/com/android/systemui/dreams/DreamOverlayStatusBarView.java b/packages/SystemUI/src/com/android/systemui/dreams/DreamOverlayStatusBarView.java index 7e4a108aadf1..823255c38a84 100644 --- a/packages/SystemUI/src/com/android/systemui/dreams/DreamOverlayStatusBarView.java +++ b/packages/SystemUI/src/com/android/systemui/dreams/DreamOverlayStatusBarView.java @@ -113,7 +113,7 @@ public class DreamOverlayStatusBarView extends ConstraintLayout { } void setExtraStatusBarItemViews(List<View> views) { - mSystemStatusViewGroup.removeAllViews(); + removeAllStatusBarItemViews(); views.forEach(view -> mSystemStatusViewGroup.addView(view)); } @@ -121,4 +121,8 @@ public class DreamOverlayStatusBarView extends ConstraintLayout { final View statusIcon = findViewById(resId); return Objects.requireNonNull(statusIcon); } + + void removeAllStatusBarItemViews() { + mSystemStatusViewGroup.removeAllViews(); + } } diff --git a/packages/SystemUI/src/com/android/systemui/dreams/DreamOverlayStatusBarViewController.java b/packages/SystemUI/src/com/android/systemui/dreams/DreamOverlayStatusBarViewController.java index 65cfae1ac14b..6f505504b186 100644 --- a/packages/SystemUI/src/com/android/systemui/dreams/DreamOverlayStatusBarViewController.java +++ b/packages/SystemUI/src/com/android/systemui/dreams/DreamOverlayStatusBarViewController.java @@ -192,6 +192,7 @@ public class DreamOverlayStatusBarViewController extends ViewController<DreamOve mDreamOverlayNotificationCountProvider.ifPresent( provider -> provider.removeCallback(mNotificationCountCallback)); mStatusBarItemsProvider.removeCallback(mStatusBarItemsProviderCallback); + mView.removeAllStatusBarItemViews(); mTouchInsetSession.clear(); mIsAttached = false; diff --git a/packages/SystemUI/src/com/android/systemui/dreams/complication/ComplicationTypesUpdater.java b/packages/SystemUI/src/com/android/systemui/dreams/complication/ComplicationTypesUpdater.java index 83249aa324d1..bbcab60d7ba2 100644 --- a/packages/SystemUI/src/com/android/systemui/dreams/complication/ComplicationTypesUpdater.java +++ b/packages/SystemUI/src/com/android/systemui/dreams/complication/ComplicationTypesUpdater.java @@ -69,7 +69,7 @@ public class ComplicationTypesUpdater extends CoreStartable { }; mSecureSettings.registerContentObserverForUser( - Settings.Secure.SCREENSAVER_ENABLED_COMPLICATIONS, + Settings.Secure.SCREENSAVER_COMPLICATIONS_ENABLED, settingsObserver, UserHandle.myUserId()); settingsObserver.onChange(false); diff --git a/packages/SystemUI/src/com/android/systemui/flags/Flags.java b/packages/SystemUI/src/com/android/systemui/flags/Flags.java index 1f356cb3d18c..29d67650fbd8 100644 --- a/packages/SystemUI/src/com/android/systemui/flags/Flags.java +++ b/packages/SystemUI/src/com/android/systemui/flags/Flags.java @@ -154,7 +154,11 @@ public class Flags { public static final ReleasedFlag STATUS_BAR_LETTERBOX_APPEARANCE = new ReleasedFlag(603, false); - public static final UnreleasedFlag NEW_STATUS_BAR_PIPELINE = new UnreleasedFlag(604, true); + public static final UnreleasedFlag NEW_STATUS_BAR_PIPELINE_BACKEND = + new UnreleasedFlag(604, false); + + public static final UnreleasedFlag NEW_STATUS_BAR_PIPELINE_FRONTEND = + new UnreleasedFlag(605, false); /***************************************/ // 700 - dialer/calls diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java index 4a7346ee2901..319928466d4d 100644 --- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java +++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java @@ -73,8 +73,6 @@ import android.provider.Settings; import android.telephony.SubscriptionManager; import android.telephony.TelephonyManager; import android.util.EventLog; -import android.util.Log; -import android.util.Slog; import android.util.SparseBooleanArray; import android.util.SparseIntArray; import android.view.IRemoteAnimationFinishedCallback; @@ -106,6 +104,7 @@ import com.android.keyguard.KeyguardUpdateMonitor; import com.android.keyguard.KeyguardUpdateMonitorCallback; import com.android.keyguard.KeyguardViewController; import com.android.keyguard.ViewMediatorCallback; +import com.android.keyguard.logging.KeyguardViewMediatorLogger; import com.android.keyguard.mediator.ScreenOnCoordinator; import com.android.systemui.CoreStartable; import com.android.systemui.DejankUtils; @@ -513,8 +512,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, public void onKeyguardVisibilityChanged(boolean showing) { synchronized (KeyguardViewMediator.this) { if (!showing && mPendingPinLock) { - Log.i(TAG, "PIN lock requested, starting keyguard"); - + mLogger.logPinLockRequestedStartingKeyguard(); // Bring the keyguard back in order to show the PIN lock mPendingPinLock = false; doKeyguardLocked(null); @@ -524,7 +522,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, @Override public void onUserSwitching(int userId) { - if (DEBUG) Log.d(TAG, String.format("onUserSwitching %d", userId)); + mLogger.logUserSwitching(userId); // Note that the mLockPatternUtils user has already been updated from setCurrentUser. // We need to force a reset of the views, since lockNow (called by // ActivityManagerService) will not reconstruct the keyguard if it is already showing. @@ -542,7 +540,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, @Override public void onUserSwitchComplete(int userId) { - if (DEBUG) Log.d(TAG, String.format("onUserSwitchComplete %d", userId)); + mLogger.logOnUserSwitchComplete(userId); if (userId != UserHandle.USER_SYSTEM) { UserInfo info = UserManager.get(mContext).getUserInfo(userId); // Don't try to dismiss if the user has Pin/Pattern/Password set @@ -570,8 +568,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, public void onSimStateChanged(int subId, int slotId, int simState) { if (DEBUG_SIM_STATES) { - Log.d(TAG, "onSimStateChanged(subId=" + subId + ", slotId=" + slotId - + ",state=" + simState + ")"); + mLogger.logOnSimStateChanged(subId, slotId, String.valueOf(simState)); } int size = mKeyguardStateCallbacks.size(); @@ -580,7 +577,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, try { mKeyguardStateCallbacks.get(i).onSimSecureStateChanged(simPinSecure); } catch (RemoteException e) { - Slog.w(TAG, "Failed to call onSimSecureStateChanged", e); + mLogger.logFailedToCallOnSimSecureStateChanged(e); if (e instanceof DeadObjectException) { mKeyguardStateCallbacks.remove(i); } @@ -603,9 +600,9 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, synchronized (KeyguardViewMediator.this) { if (shouldWaitForProvisioning()) { if (!mShowing) { - if (DEBUG_SIM_STATES) Log.d(TAG, "ICC_ABSENT isn't showing," - + " we need to show the keyguard since the " - + "device isn't provisioned yet."); + if (DEBUG_SIM_STATES) { + mLogger.logIccAbsentIsNotShowing(); + } doKeyguardLocked(null); } else { resetStateLocked(); @@ -615,8 +612,9 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, // MVNO SIMs can become transiently NOT_READY when switching networks, // so we should only lock when they are ABSENT. if (lastSimStateWasLocked) { - if (DEBUG_SIM_STATES) Log.d(TAG, "SIM moved to ABSENT when the " - + "previous state was locked. Reset the state."); + if (DEBUG_SIM_STATES) { + mLogger.logSimMovedToAbsent(); + } resetStateLocked(); } mSimWasLocked.append(slotId, false); @@ -629,9 +627,9 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, mSimWasLocked.append(slotId, true); mPendingPinLock = true; if (!mShowing) { - if (DEBUG_SIM_STATES) Log.d(TAG, - "INTENT_VALUE_ICC_LOCKED and keygaurd isn't " - + "showing; need to show keyguard so user can enter sim pin"); + if (DEBUG_SIM_STATES) { + mLogger.logIntentValueIccLocked(); + } doKeyguardLocked(null); } else { resetStateLocked(); @@ -641,29 +639,36 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, case TelephonyManager.SIM_STATE_PERM_DISABLED: synchronized (KeyguardViewMediator.this) { if (!mShowing) { - if (DEBUG_SIM_STATES) Log.d(TAG, "PERM_DISABLED and " - + "keygaurd isn't showing."); + if (DEBUG_SIM_STATES) { + mLogger.logPermDisabledKeyguardNotShowing(); + } doKeyguardLocked(null); } else { - if (DEBUG_SIM_STATES) Log.d(TAG, "PERM_DISABLED, resetStateLocked to" - + "show permanently disabled message in lockscreen."); + if (DEBUG_SIM_STATES) { + mLogger.logPermDisabledResetStateLocked(); + } resetStateLocked(); } } break; case TelephonyManager.SIM_STATE_READY: synchronized (KeyguardViewMediator.this) { - if (DEBUG_SIM_STATES) Log.d(TAG, "READY, reset state? " + mShowing); + if (DEBUG_SIM_STATES) { + mLogger.logReadyResetState(mShowing); + } if (mShowing && mSimWasLocked.get(slotId, false)) { - if (DEBUG_SIM_STATES) Log.d(TAG, "SIM moved to READY when the " - + "previously was locked. Reset the state."); + if (DEBUG_SIM_STATES) { + mLogger.logSimMovedToReady(); + } mSimWasLocked.append(slotId, false); resetStateLocked(); } } break; default: - if (DEBUG_SIM_STATES) Log.v(TAG, "Unspecific state: " + simState); + if (DEBUG_SIM_STATES) { + mLogger.logUnspecifiedSimState(simState); + } break; } } @@ -708,7 +713,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, if (targetUserId != ActivityManager.getCurrentUser()) { return; } - if (DEBUG) Log.d(TAG, "keyguardDone"); + mLogger.logKeyguardDone(); tryKeyguardDone(); } @@ -727,7 +732,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, @Override public void keyguardDonePending(boolean strongAuth, int targetUserId) { Trace.beginSection("KeyguardViewMediator.mViewMediatorCallback#keyguardDonePending"); - if (DEBUG) Log.d(TAG, "keyguardDonePending"); + mLogger.logKeyguardDonePending(); if (targetUserId != ActivityManager.getCurrentUser()) { Trace.endSection(); return; @@ -746,7 +751,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, @Override public void keyguardGone() { Trace.beginSection("KeyguardViewMediator.mViewMediatorCallback#keyguardGone"); - if (DEBUG) Log.d(TAG, "keyguardGone"); + mLogger.logKeyguardGone(); mKeyguardViewControllerLazy.get().setKeyguardGoingAwayState(false); mKeyguardDisplayManager.hide(); Trace.endSection(); @@ -832,8 +837,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, @Override public void onLaunchAnimationCancelled() { - Log.d(TAG, "Occlude launch animation cancelled. Occluded state is now: " - + mOccluded); + mLogger.logOccludeLaunchAnimationCancelled(mOccluded); } @Override @@ -853,8 +857,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, @Override public void setLaunchContainer(@NonNull ViewGroup launchContainer) { // No-op, launch container is always the shade. - Log.wtf(TAG, "Someone tried to change the launch container for the " - + "ActivityLaunchAnimator, which should never happen."); + mLogger.logActivityLaunchAnimatorLaunchContainerChanged(); } @NonNull @@ -905,8 +908,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, } setOccluded(isKeyguardOccluded /* isOccluded */, false /* animate */); - Log.d(TAG, "Unocclude animation cancelled. Occluded state is now: " - + mOccluded); + mLogger.logUnoccludeAnimationCancelled(mOccluded); } @Override @@ -914,12 +916,11 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, RemoteAnimationTarget[] wallpapers, RemoteAnimationTarget[] nonApps, IRemoteAnimationFinishedCallback finishedCallback) throws RemoteException { - Log.d(TAG, "UnoccludeAnimator#onAnimationStart. Set occluded = false."); + mLogger.logUnoccludeAnimatorOnAnimationStart(); setOccluded(false /* isOccluded */, true /* animate */); if (apps == null || apps.length == 0 || apps[0] == null) { - Log.d(TAG, "No apps provided to unocclude runner; " - + "skipping animation and unoccluding."); + mLogger.logNoAppsProvidedToUnoccludeRunner(); finishedCallback.onAnimationFinished(); return; } @@ -1007,6 +1008,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, private ScreenOnCoordinator mScreenOnCoordinator; private Lazy<ActivityLaunchAnimator> mActivityLaunchAnimator; + private KeyguardViewMediatorLogger mLogger; /** * Injected constructor. See {@link KeyguardModule}. @@ -1035,7 +1037,8 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, InteractionJankMonitor interactionJankMonitor, DreamOverlayStateController dreamOverlayStateController, Lazy<NotificationShadeWindowController> notificationShadeWindowControllerLazy, - Lazy<ActivityLaunchAnimator> activityLaunchAnimator) { + Lazy<ActivityLaunchAnimator> activityLaunchAnimator, + KeyguardViewMediatorLogger logger) { super(context); mFalsingCollector = falsingCollector; mLockPatternUtils = lockPatternUtils; @@ -1078,6 +1081,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, mDreamOverlayStateController = dreamOverlayStateController; mActivityLaunchAnimator = activityLaunchAnimator; + mLogger = logger; mPowerButtonY = context.getResources().getDimensionPixelSize( R.dimen.physical_power_button_center_screen_location_y); @@ -1141,21 +1145,21 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, mLockSoundId = mLockSounds.load(soundPath, 1); } if (soundPath == null || mLockSoundId == 0) { - Log.w(TAG, "failed to load lock sound from " + soundPath); + mLogger.logFailedLoadLockSound(soundPath); } soundPath = Settings.Global.getString(cr, Settings.Global.UNLOCK_SOUND); if (soundPath != null) { mUnlockSoundId = mLockSounds.load(soundPath, 1); } if (soundPath == null || mUnlockSoundId == 0) { - Log.w(TAG, "failed to load unlock sound from " + soundPath); + mLogger.logFailedLoadUnlockSound(soundPath); } soundPath = Settings.Global.getString(cr, Settings.Global.TRUSTED_SOUND); if (soundPath != null) { mTrustedSoundId = mLockSounds.load(soundPath, 1); } if (soundPath == null || mTrustedSoundId == 0) { - Log.w(TAG, "failed to load trusted sound from " + soundPath); + mLogger.logFailedLoadTrustedSound(soundPath); } int lockSoundDefaultAttenuation = mContext.getResources().getInteger( @@ -1184,7 +1188,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, private void handleSystemReady() { synchronized (this) { - if (DEBUG) Log.d(TAG, "onSystemReady"); + mLogger.logOnSystemReady(); mSystemReady = true; doKeyguardLocked(null); mUpdateMonitor.registerCallback(mUpdateCallback); @@ -1202,7 +1206,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, * {@link WindowManagerPolicyConstants#OFF_BECAUSE_OF_TIMEOUT}. */ public void onStartedGoingToSleep(@WindowManagerPolicyConstants.OffReason int offReason) { - if (DEBUG) Log.d(TAG, "onStartedGoingToSleep(" + offReason + ")"); + mLogger.logOnStartedGoingToSleep(offReason); synchronized (this) { mDeviceInteractive = false; mPowerGestureIntercepted = false; @@ -1218,11 +1222,11 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, long timeout = getLockTimeout(KeyguardUpdateMonitor.getCurrentUser()); mLockLater = false; if (mExitSecureCallback != null) { - if (DEBUG) Log.d(TAG, "pending exit secure callback cancelled"); + mLogger.logPendingExitSecureCallbackCancelled(); try { mExitSecureCallback.onKeyguardExitResult(false); } catch (RemoteException e) { - Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e); + mLogger.logFailedOnKeyguardExitResultFalse(e); } mExitSecureCallback = null; if (!mExternallyEnabled) { @@ -1267,7 +1271,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, */ public void onFinishedGoingToSleep( @WindowManagerPolicyConstants.OffReason int offReason, boolean cameraGestureTriggered) { - if (DEBUG) Log.d(TAG, "onFinishedGoingToSleep(" + offReason + ")"); + mLogger.logOnFinishedGoingToSleep(offReason); synchronized (this) { mDeviceInteractive = false; mGoingToSleep = false; @@ -1325,13 +1329,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, // - The screen off animation is cancelled by the device waking back up. We will call // maybeHandlePendingLock from KeyguardViewMediator#onStartedWakingUp. if (mScreenOffAnimationController.isKeyguardShowDelayed()) { - if (DEBUG) { - Log.d(TAG, "#maybeHandlePendingLock: not handling because the screen off " - + "animation's isKeyguardShowDelayed() returned true. This should be " - + "handled soon by #onStartedWakingUp, or by the end actions of the " - + "screen off animation."); - } - + mLogger.logMaybeHandlePendingLockNotHandling(); return; } @@ -1341,18 +1339,11 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, // StatusBar#finishKeyguardFadingAway, which is always responsible for setting // isKeyguardGoingAway to false. if (mKeyguardStateController.isKeyguardGoingAway()) { - if (DEBUG) { - Log.d(TAG, "#maybeHandlePendingLock: not handling because the keyguard is " - + "going away. This should be handled shortly by " - + "StatusBar#finishKeyguardFadingAway."); - } - + mLogger.logMaybeHandlePendingLockKeyguardGoingAway(); return; } - if (DEBUG) { - Log.d(TAG, "#maybeHandlePendingLock: handling pending lock; locking keyguard."); - } + mLogger.logMaybeHandlePendingLockHandling(); doKeyguardLocked(null); setPendingLock(false); @@ -1421,8 +1412,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, PendingIntent sender = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE); mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, when, sender); - if (DEBUG) Log.d(TAG, "setting alarm to turn off keyguard, seq = " - + mDelayedShowingSequence); + mLogger.logSetAlarmToTurnOffKeyguard(mDelayedShowingSequence); doKeyguardLaterForChildProfilesLocked(); } @@ -1482,7 +1472,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, mAnimatingScreenOff = false; cancelDoKeyguardLaterLocked(); cancelDoKeyguardForChildProfilesLocked(); - if (DEBUG) Log.d(TAG, "onStartedWakingUp, seq = " + mDelayedShowingSequence); + mLogger.logOnStartedWakingUp(mDelayedShowingSequence); notifyStartedWakingUp(); } mUpdateMonitor.dispatchStartedWakingUp(); @@ -1542,37 +1532,35 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, */ public void setKeyguardEnabled(boolean enabled) { synchronized (this) { - if (DEBUG) Log.d(TAG, "setKeyguardEnabled(" + enabled + ")"); + mLogger.logSetKeyguardEnabled(enabled); mExternallyEnabled = enabled; if (!enabled && mShowing) { if (mExitSecureCallback != null) { - if (DEBUG) Log.d(TAG, "in process of verifyUnlock request, ignoring"); + mLogger.logIgnoreVerifyUnlockRequest(); // we're in the process of handling a request to verify the user // can get past the keyguard. ignore extraneous requests to disable / re-enable return; } // hiding keyguard that is showing, remember to reshow later - if (DEBUG) Log.d(TAG, "remembering to reshow, hiding keyguard, " - + "disabling status bar expansion"); + mLogger.logRememberToReshowLater(); mNeedToReshowWhenReenabled = true; updateInputRestrictedLocked(); hideLocked(); } else if (enabled && mNeedToReshowWhenReenabled) { // re-enabled after previously hidden, reshow - if (DEBUG) Log.d(TAG, "previously hidden, reshowing, reenabling " - + "status bar expansion"); + mLogger.logPreviouslyHiddenReshow(); mNeedToReshowWhenReenabled = false; updateInputRestrictedLocked(); if (mExitSecureCallback != null) { - if (DEBUG) Log.d(TAG, "onKeyguardExitResult(false), resetting"); + mLogger.logOnKeyguardExitResultFalseResetting(); try { mExitSecureCallback.onKeyguardExitResult(false); } catch (RemoteException e) { - Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e); + mLogger.logFailedToCallOnKeyguardExitResultFalse(e); } mExitSecureCallback = null; resetStateLocked(); @@ -1584,7 +1572,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, // and causing an ANR). mWaitingUntilKeyguardVisible = true; mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_DRAWING, KEYGUARD_DONE_DRAWING_TIMEOUT_MS); - if (DEBUG) Log.d(TAG, "waiting until mWaitingUntilKeyguardVisible is false"); + mLogger.logWaitingUntilKeyguardVisibleIsFalse(); while (mWaitingUntilKeyguardVisible) { try { wait(); @@ -1592,7 +1580,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, Thread.currentThread().interrupt(); } } - if (DEBUG) Log.d(TAG, "done waiting for mWaitingUntilKeyguardVisible"); + mLogger.logDoneWaitingUntilKeyguardVisible(); } } } @@ -1604,31 +1592,31 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, public void verifyUnlock(IKeyguardExitCallback callback) { Trace.beginSection("KeyguardViewMediator#verifyUnlock"); synchronized (this) { - if (DEBUG) Log.d(TAG, "verifyUnlock"); + mLogger.logVerifyUnlock(); if (shouldWaitForProvisioning()) { // don't allow this api when the device isn't provisioned - if (DEBUG) Log.d(TAG, "ignoring because device isn't provisioned"); + mLogger.logIgnoreUnlockDeviceNotProvisioned(); try { callback.onKeyguardExitResult(false); } catch (RemoteException e) { - Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e); + mLogger.logFailedToCallOnKeyguardExitResultFalse(e); } } else if (mExternallyEnabled) { // this only applies when the user has externally disabled the // keyguard. this is unexpected and means the user is not // using the api properly. - Log.w(TAG, "verifyUnlock called when not externally disabled"); + mLogger.logVerifyUnlockCalledNotExternallyDisabled(); try { callback.onKeyguardExitResult(false); } catch (RemoteException e) { - Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e); + mLogger.logFailedToCallOnKeyguardExitResultFalse(e); } } else if (mExitSecureCallback != null) { // already in progress with someone else try { callback.onKeyguardExitResult(false); } catch (RemoteException e) { - Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e); + mLogger.logFailedToCallOnKeyguardExitResultFalse(e); } } else if (!isSecure()) { @@ -1640,7 +1628,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, try { callback.onKeyguardExitResult(true); } catch (RemoteException e) { - Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e); + mLogger.logFailedToCallOnKeyguardExitResultFalse(e); } } else { @@ -1649,7 +1637,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, try { callback.onKeyguardExitResult(false); } catch (RemoteException e) { - Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e); + mLogger.logFailedToCallOnKeyguardExitResultFalse(e); } } } @@ -1667,10 +1655,8 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, * Notify us when the keyguard is occluded by another window */ public void setOccluded(boolean isOccluded, boolean animate) { - Log.d(TAG, "setOccluded(" + isOccluded + ")"); - Trace.beginSection("KeyguardViewMediator#setOccluded"); - if (DEBUG) Log.d(TAG, "setOccluded " + isOccluded); + mLogger.logSetOccluded(isOccluded); mInteractionJankMonitor.cancel(CUJ_LOCKSCREEN_TRANSITION_FROM_AOD); mHandler.removeMessages(SET_OCCLUDED); Message msg = mHandler.obtainMessage(SET_OCCLUDED, isOccluded ? 1 : 0, animate ? 1 : 0); @@ -1699,7 +1685,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, */ private void handleSetOccluded(boolean isOccluded, boolean animate) { Trace.beginSection("KeyguardViewMediator#handleSetOccluded"); - Log.d(TAG, "handleSetOccluded(" + isOccluded + ")"); + mLogger.logHandleSetOccluded(isOccluded); synchronized (KeyguardViewMediator.this) { if (mHiding && isOccluded) { // We're in the process of going away but WindowManager wants to show a @@ -1756,7 +1742,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, try { callback.onInputRestrictedStateChanged(inputRestricted); } catch (RemoteException e) { - Slog.w(TAG, "Failed to call onDeviceProvisioned", e); + mLogger.logFailedToCallOnDeviceProvisioned(e); if (e instanceof DeadObjectException) { mKeyguardStateCallbacks.remove(callback); } @@ -1771,8 +1757,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, private void doKeyguardLocked(Bundle options) { // if another app is disabling us, don't show if (!mExternallyEnabled) { - if (DEBUG) Log.d(TAG, "doKeyguard: not showing because externally disabled"); - + mLogger.logDoKeyguardNotShowingExternallyDisabled(); mNeedToReshowWhenReenabled = true; return; } @@ -1781,7 +1766,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, // to account for the hiding animation which results in a delay and discrepancy // between flags if (mShowing && mKeyguardViewControllerLazy.get().isShowing()) { - if (DEBUG) Log.d(TAG, "doKeyguard: not showing because it is already showing"); + mLogger.logDoKeyguardNotShowingAlreadyShowing(); resetStateLocked(); return; } @@ -1800,20 +1785,19 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, || ((absent || disabled) && requireSim); if (!lockedOrMissing && shouldWaitForProvisioning()) { - if (DEBUG) Log.d(TAG, "doKeyguard: not showing because device isn't provisioned" - + " and the sim is not locked or missing"); + mLogger.logDoKeyguardNotShowingDeviceNotProvisioned(); return; } boolean forceShow = options != null && options.getBoolean(OPTION_FORCE_SHOW, false); if (mLockPatternUtils.isLockScreenDisabled(KeyguardUpdateMonitor.getCurrentUser()) && !lockedOrMissing && !forceShow) { - if (DEBUG) Log.d(TAG, "doKeyguard: not showing because lockscreen is off"); + mLogger.logDoKeyguardNotShowingLockScreenOff(); return; } } - if (DEBUG) Log.d(TAG, "doKeyguard: showing the lock screen"); + mLogger.logDoKeyguardShowingLockScreen(); showLocked(options); } @@ -1851,32 +1835,23 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, * @see #handleReset */ private void resetStateLocked() { - if (DEBUG) Log.e(TAG, "resetStateLocked"); + mLogger.logResetStateLocked(); Message msg = mHandler.obtainMessage(RESET); mHandler.sendMessage(msg); } - /** - * Send message to keyguard telling it to verify unlock - * @see #handleVerifyUnlock() - */ - private void verifyUnlockLocked() { - if (DEBUG) Log.d(TAG, "verifyUnlockLocked"); - mHandler.sendEmptyMessage(VERIFY_UNLOCK); - } - private void notifyStartedGoingToSleep() { - if (DEBUG) Log.d(TAG, "notifyStartedGoingToSleep"); + mLogger.logNotifyStartedGoingToSleep(); mHandler.sendEmptyMessage(NOTIFY_STARTED_GOING_TO_SLEEP); } private void notifyFinishedGoingToSleep() { - if (DEBUG) Log.d(TAG, "notifyFinishedGoingToSleep"); + mLogger.logNotifyFinishedGoingToSleep(); mHandler.sendEmptyMessage(NOTIFY_FINISHED_GOING_TO_SLEEP); } private void notifyStartedWakingUp() { - if (DEBUG) Log.d(TAG, "notifyStartedWakingUp"); + mLogger.logNotifyStartedWakingUp(); mHandler.sendEmptyMessage(NOTIFY_STARTED_WAKING_UP); } @@ -1886,7 +1861,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, */ private void showLocked(Bundle options) { Trace.beginSection("KeyguardViewMediator#showLocked acquiring mShowKeyguardWakeLock"); - if (DEBUG) Log.d(TAG, "showLocked"); + mLogger.logShowLocked(); // ensure we stay awake until we are finished displaying the keyguard mShowKeyguardWakeLock.acquire(); Message msg = mHandler.obtainMessage(SHOW, options); @@ -1903,7 +1878,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, */ private void hideLocked() { Trace.beginSection("KeyguardViewMediator#hideLocked"); - if (DEBUG) Log.d(TAG, "hideLocked"); + mLogger.logHideLocked(); Message msg = mHandler.obtainMessage(HIDE); mHandler.sendMessage(msg); Trace.endSection(); @@ -1982,8 +1957,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, public void onReceive(Context context, Intent intent) { if (DELAYED_KEYGUARD_ACTION.equals(intent.getAction())) { final int sequence = intent.getIntExtra("seq", 0); - if (DEBUG) Log.d(TAG, "received DELAYED_KEYGUARD_ACTION with seq = " - + sequence + ", mDelayedShowingSequence = " + mDelayedShowingSequence); + mLogger.logReceivedDelayedKeyguardAction(sequence, mDelayedShowingSequence); synchronized (KeyguardViewMediator.this) { if (mDelayedShowingSequence == sequence) { doKeyguardLocked(null); @@ -2016,7 +1990,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, private void keyguardDone() { Trace.beginSection("KeyguardViewMediator#keyguardDone"); - if (DEBUG) Log.d(TAG, "keyguardDone()"); + mLogger.logKeyguardDone(); userActivity(); EventLog.writeEvent(70000, 2); Message msg = mHandler.obtainMessage(KEYGUARD_DONE); @@ -2108,7 +2082,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, case KEYGUARD_DONE_PENDING_TIMEOUT: Trace.beginSection("KeyguardViewMediator#handleMessage" + " KEYGUARD_DONE_PENDING_TIMEOUT"); - Log.w(TAG, "Timeout while waiting for activity drawn!"); + mLogger.logTimeoutWhileActivityDrawn(); Trace.endSection(); break; case SYSTEM_READY: @@ -2119,14 +2093,15 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, }; private void tryKeyguardDone() { - if (DEBUG) { - Log.d(TAG, "tryKeyguardDone: pending - " + mKeyguardDonePending + ", animRan - " - + mHideAnimationRun + " animRunning - " + mHideAnimationRunning); - } + mLogger.logTryKeyguardDonePending( + mKeyguardDonePending, + mHideAnimationRun, + mHideAnimationRunning + ); if (!mKeyguardDonePending && mHideAnimationRun && !mHideAnimationRunning) { handleKeyguardDone(); } else if (!mHideAnimationRun) { - if (DEBUG) Log.d(TAG, "tryKeyguardDone: starting pre-hide animation"); + mLogger.logTryKeyguardDonePreHideAnimation(); mHideAnimationRun = true; mHideAnimationRunning = true; mKeyguardViewControllerLazy.get() @@ -2146,14 +2121,14 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, mLockPatternUtils.getDevicePolicyManager().reportKeyguardDismissed(currentUser); } }); - if (DEBUG) Log.d(TAG, "handleKeyguardDone"); + mLogger.logHandleKeyguardDone(); synchronized (this) { resetKeyguardDonePendingLocked(); } if (mGoingToSleep) { mUpdateMonitor.clearBiometricRecognizedWhenKeyguardDone(currentUser); - Log.i(TAG, "Device is going to sleep, aborting keyguardDone"); + mLogger.logDeviceGoingToSleep(); return; } setPendingLock(false); // user may have authenticated during the screen off animation @@ -2161,7 +2136,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, try { mExitSecureCallback.onKeyguardExitResult(true /* authenciated */); } catch (RemoteException e) { - Slog.w(TAG, "Failed to call onKeyguardExitResult()", e); + mLogger.logFailedToCallOnKeyguardExitResultTrue(e); } mExitSecureCallback = null; @@ -2204,9 +2179,9 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, private void handleKeyguardDoneDrawing() { Trace.beginSection("KeyguardViewMediator#handleKeyguardDoneDrawing"); synchronized(this) { - if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing"); + mLogger.logHandleKeyguardDoneDrawing(); if (mWaitingUntilKeyguardVisible) { - if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing: notifying mWaitingUntilKeyguardVisible"); + mLogger.logHandleKeyguardDoneDrawingNotifyingKeyguardVisible(); mWaitingUntilKeyguardVisible = false; notifyAll(); @@ -2256,12 +2231,11 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, private void updateActivityLockScreenState(boolean showing, boolean aodShowing) { mUiBgExecutor.execute(() -> { - if (DEBUG) { - Log.d(TAG, "updateActivityLockScreenState(" + showing + ", " + aodShowing + ")"); - } + mLogger.logUpdateActivityLockScreenState(showing, aodShowing); try { ActivityTaskManager.getService().setLockScreenShown(showing, aodShowing); } catch (RemoteException e) { + mLogger.logFailedToCallSetLockScreenShown(e); } }); } @@ -2278,10 +2252,10 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, } synchronized (KeyguardViewMediator.this) { if (!mSystemReady) { - if (DEBUG) Log.d(TAG, "ignoring handleShow because system is not ready."); + mLogger.logIgnoreHandleShow(); return; } else { - if (DEBUG) Log.d(TAG, "handleShow"); + mLogger.logHandleShow(); } mHiding = false; @@ -2313,7 +2287,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, @Override public void run() { Trace.beginSection("KeyguardViewMediator.mKeyGuardGoingAwayRunnable"); - if (DEBUG) Log.d(TAG, "keyguardGoingAway"); + mLogger.logKeyguardGoingAway(); mKeyguardViewControllerLazy.get().keyguardGoingAway(); int flags = 0; @@ -2357,7 +2331,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, try { ActivityTaskManager.getService().keyguardGoingAway(keyguardFlag); } catch (RemoteException e) { - Log.e(TAG, "Error while calling WindowManager", e); + mLogger.logFailedToCallKeyguardGoingAway(keyguardFlag, e); } }); Trace.endSection(); @@ -2365,7 +2339,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, }; private final Runnable mHideAnimationFinishedRunnable = () -> { - Log.e(TAG, "mHideAnimationFinishedRunnable#run"); + mLogger.logHideAnimationFinishedRunnable(); mHideAnimationRunning = false; tryKeyguardDone(); }; @@ -2385,14 +2359,14 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, } synchronized (KeyguardViewMediator.this) { - if (DEBUG) Log.d(TAG, "handleHide"); + mLogger.logHandleHide(); if (mustNotUnlockCurrentUser()) { // In split system user mode, we never unlock system user. The end user has to // switch to another user. // TODO: We should stop it early by disabling the swipe up flow. Right now swipe up // still completes and makes the screen blank. - if (DEBUG) Log.d(TAG, "Split system user, quit unlocking."); + mLogger.logSplitSystemUserQuitUnlocking(); mKeyguardExitAnimationRunner = null; return; } @@ -2424,8 +2398,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, RemoteAnimationTarget[] apps, RemoteAnimationTarget[] wallpapers, RemoteAnimationTarget[] nonApps, IRemoteAnimationFinishedCallback finishedCallback) { Trace.beginSection("KeyguardViewMediator#handleStartKeyguardExitAnimation"); - Log.d(TAG, "handleStartKeyguardExitAnimation startTime=" + startTime - + " fadeoutDuration=" + fadeoutDuration); + mLogger.logHandleStartKeyguardExitAnimation(startTime, fadeoutDuration); synchronized (KeyguardViewMediator.this) { // Tell ActivityManager that we canceled the keyguard animation if @@ -2441,7 +2414,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, try { finishedCallback.onAnimationFinished(); } catch (RemoteException e) { - Slog.w(TAG, "Failed to call onAnimationFinished", e); + mLogger.logFailedToCallOnAnimationFinished(e); } } setShowingLocked(mShowing, true /* force */); @@ -2464,7 +2437,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, try { finishedCallback.onAnimationFinished(); } catch (RemoteException e) { - Slog.w(TAG, "Failed to call onAnimationFinished", e); + mLogger.logFailedToCallOnAnimationFinished(e); } onKeyguardExitFinished(); mKeyguardViewControllerLazy.get().hide(0 /* startTime */, @@ -2483,7 +2456,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, runner.onAnimationStart(WindowManager.TRANSIT_KEYGUARD_GOING_AWAY, apps, wallpapers, nonApps, callback); } catch (RemoteException e) { - Slog.w(TAG, "Failed to call onAnimationStart", e); + mLogger.logFailedToCallOnAnimationStart(e); } // When remaining on the shade, there's no need to do a fancy remote animation, @@ -2548,7 +2521,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, try { finishedCallback.onAnimationFinished(); } catch (RemoteException e) { - Slog.e(TAG, "RemoteException"); + mLogger.logFailedToCallOnAnimationFinished(e); } finally { mInteractionJankMonitor.end(CUJ_LOCKSCREEN_UNLOCK_ANIMATION); } @@ -2559,7 +2532,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, try { finishedCallback.onAnimationFinished(); } catch (RemoteException e) { - Slog.e(TAG, "RemoteException"); + mLogger.logFailedToCallOnAnimationFinished(e); } finally { mInteractionJankMonitor.cancel(CUJ_LOCKSCREEN_UNLOCK_ANIMATION); } @@ -2628,11 +2601,9 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, * @param cancelled {@code true} if the animation was cancelled before it finishes. */ public void onKeyguardExitRemoteAnimationFinished(boolean cancelled) { - Log.d(TAG, "onKeyguardExitRemoteAnimationFinished"); + mLogger.logOnKeyguardExitRemoteAnimationFinished(); if (!mSurfaceBehindRemoteAnimationRunning && !mSurfaceBehindRemoteAnimationRequested) { - Log.d(TAG, "skip onKeyguardExitRemoteAnimationFinished cancelled=" + cancelled - + " surfaceAnimationRunning=" + mSurfaceBehindRemoteAnimationRunning - + " surfaceAnimationRequested=" + mSurfaceBehindRemoteAnimationRequested); + mLogger.logSkipOnKeyguardExitRemoteAnimationFinished(cancelled, false, false); return; } @@ -2646,13 +2617,13 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, onKeyguardExitFinished(); if (mKeyguardStateController.isDismissingFromSwipe() || wasShowing) { - Log.d(TAG, "onKeyguardExitRemoteAnimationFinished" - + "#hideKeyguardViewAfterRemoteAnimation"); + mLogger.logOnKeyguardExitRemoteAnimationFinishedHideKeyguardView(); mKeyguardUnlockAnimationControllerLazy.get().hideKeyguardViewAfterRemoteAnimation(); } else { - Log.d(TAG, "skip hideKeyguardViewAfterRemoteAnimation" - + " dismissFromSwipe=" + mKeyguardStateController.isDismissingFromSwipe() - + " wasShowing=" + wasShowing); + mLogger.logSkipHideKeyguardViewAfterRemoteAnimation( + mKeyguardStateController.isDismissingFromSwipe(), + wasShowing + ); } finishSurfaceBehindRemoteAnimation(cancelled); @@ -2749,7 +2720,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, } if (mStatusBarManager == null) { - Log.w(TAG, "Could not get status bar manager"); + mLogger.logCouldNotGetStatusBarManager(); } else { // Disable aspects of the system/status/navigation bars that must not be re-enabled by // windows that appear on top, ever @@ -2767,12 +2738,13 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, } flags |= StatusBarManager.DISABLE_RECENT; } - - if (DEBUG) { - Log.d(TAG, "adjustStatusBarLocked: mShowing=" + mShowing + " mOccluded=" + mOccluded - + " isSecure=" + isSecure() + " force=" + forceHideHomeRecentsButtons - + " --> flags=0x" + Integer.toHexString(flags)); - } + mLogger.logAdjustStatusBarLocked( + mShowing, + mOccluded, + isSecure(), + forceHideHomeRecentsButtons, + Integer.toHexString(flags) + ); mStatusBarManager.disable(flags); } @@ -2784,7 +2756,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, */ private void handleReset() { synchronized (KeyguardViewMediator.this) { - if (DEBUG) Log.d(TAG, "handleReset"); + mLogger.logHandleReset(); mKeyguardViewControllerLazy.get().reset(true /* hideBouncerWhenShowing */); } } @@ -2796,7 +2768,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, private void handleVerifyUnlock() { Trace.beginSection("KeyguardViewMediator#handleVerifyUnlock"); synchronized (KeyguardViewMediator.this) { - if (DEBUG) Log.d(TAG, "handleVerifyUnlock"); + mLogger.logHandleVerifyUnlock(); setShowingLocked(true); mKeyguardViewControllerLazy.get().dismissAndCollapse(); } @@ -2805,7 +2777,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, private void handleNotifyStartedGoingToSleep() { synchronized (KeyguardViewMediator.this) { - if (DEBUG) Log.d(TAG, "handleNotifyStartedGoingToSleep"); + mLogger.logHandleNotifyStartedGoingToSleep(); mKeyguardViewControllerLazy.get().onStartedGoingToSleep(); } } @@ -2816,7 +2788,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, */ private void handleNotifyFinishedGoingToSleep() { synchronized (KeyguardViewMediator.this) { - if (DEBUG) Log.d(TAG, "handleNotifyFinishedGoingToSleep"); + mLogger.logHandleNotifyFinishedGoingToSleep(); mKeyguardViewControllerLazy.get().onFinishedGoingToSleep(); } } @@ -2824,7 +2796,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, private void handleNotifyStartedWakingUp() { Trace.beginSection("KeyguardViewMediator#handleMotifyStartedWakingUp"); synchronized (KeyguardViewMediator.this) { - if (DEBUG) Log.d(TAG, "handleNotifyWakingUp"); + mLogger.logHandleNotifyWakingUp(); mKeyguardViewControllerLazy.get().onStartedWakingUp(); } Trace.endSection(); @@ -3090,7 +3062,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, try { callback.onShowingStateChanged(showing, KeyguardUpdateMonitor.getCurrentUser()); } catch (RemoteException e) { - Slog.w(TAG, "Failed to call onShowingStateChanged", e); + mLogger.logFailedToCallOnShowingStateChanged(e); if (e instanceof DeadObjectException) { mKeyguardStateCallbacks.remove(callback); } @@ -3109,7 +3081,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, try { mKeyguardStateCallbacks.get(i).onTrustedChanged(trusted); } catch (RemoteException e) { - Slog.w(TAG, "Failed to call notifyTrustedChangedLocked", e); + mLogger.logFailedToCallNotifyTrustedChangedLocked(e); if (e instanceof DeadObjectException) { mKeyguardStateCallbacks.remove(i); } @@ -3132,7 +3104,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, callback.onTrustedChanged(mUpdateMonitor.getUserHasTrust( KeyguardUpdateMonitor.getCurrentUser())); } catch (RemoteException e) { - Slog.w(TAG, "Failed to call to IKeyguardStateCallback", e); + mLogger.logFailedToCallIKeyguardStateCallback(e); } } } @@ -3209,7 +3181,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, // internal state to reflect that immediately, vs. waiting for the launch animator to // begin. Otherwise, calls to setShowingLocked, etc. will not know that we're about to // be occluded and might re-show the keyguard. - Log.d(TAG, "OccludeAnimator#onAnimationStart. Set occluded = true."); + mLogger.logOccludeAnimatorOnAnimationStart(); setOccluded(true /* isOccluded */, false /* animate */); } @@ -3217,8 +3189,7 @@ public class KeyguardViewMediator extends CoreStartable implements Dumpable, public void onAnimationCancelled(boolean isKeyguardOccluded) throws RemoteException { super.onAnimationCancelled(isKeyguardOccluded); - Log.d(TAG, "Occlude animation cancelled by WM. " - + "Setting occluded state to: " + isKeyguardOccluded); + mLogger.logOccludeAnimationCancelledByWm(isKeyguardOccluded); setOccluded(isKeyguardOccluded /* occluded */, false /* animate */); } diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/dagger/KeyguardModule.java b/packages/SystemUI/src/com/android/systemui/keyguard/dagger/KeyguardModule.java index 56f1ac46a875..fdea62dc0cbe 100644 --- a/packages/SystemUI/src/com/android/systemui/keyguard/dagger/KeyguardModule.java +++ b/packages/SystemUI/src/com/android/systemui/keyguard/dagger/KeyguardModule.java @@ -30,6 +30,7 @@ import com.android.keyguard.dagger.KeyguardQsUserSwitchComponent; import com.android.keyguard.dagger.KeyguardStatusBarViewComponent; import com.android.keyguard.dagger.KeyguardStatusViewComponent; import com.android.keyguard.dagger.KeyguardUserSwitcherComponent; +import com.android.keyguard.logging.KeyguardViewMediatorLogger; import com.android.keyguard.mediator.ScreenOnCoordinator; import com.android.systemui.animation.ActivityLaunchAnimator; import com.android.systemui.broadcast.BroadcastDispatcher; @@ -105,7 +106,8 @@ public class KeyguardModule { InteractionJankMonitor interactionJankMonitor, DreamOverlayStateController dreamOverlayStateController, Lazy<NotificationShadeWindowController> notificationShadeWindowController, - Lazy<ActivityLaunchAnimator> activityLaunchAnimator) { + Lazy<ActivityLaunchAnimator> activityLaunchAnimator, + KeyguardViewMediatorLogger logger) { return new KeyguardViewMediator( context, falsingCollector, @@ -132,7 +134,8 @@ public class KeyguardModule { interactionJankMonitor, dreamOverlayStateController, notificationShadeWindowController, - activityLaunchAnimator); + activityLaunchAnimator, + logger); } /** */ diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardBottomAreaViewBinder.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardBottomAreaViewBinder.kt index 19c6249a12c0..c4e3d4e4c1b5 100644 --- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardBottomAreaViewBinder.kt +++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/KeyguardBottomAreaViewBinder.kt @@ -251,9 +251,21 @@ object KeyguardBottomAreaViewBinder { Utils.getColorAttr(view.context, com.android.internal.R.attr.colorSurface) view.contentDescription = view.context.getString(viewModel.contentDescriptionResourceId) - view.setOnClickListener { + view.isClickable = viewModel.isClickable + if (viewModel.isClickable) { + view.setOnClickListener(OnClickListener(viewModel, falsingManager)) + } else { + view.setOnClickListener(null) + } + } + + private class OnClickListener( + private val viewModel: KeyguardQuickAffordanceViewModel, + private val falsingManager: FalsingManager, + ) : View.OnClickListener { + override fun onClick(view: View) { if (falsingManager.isFalseTap(FalsingManager.LOW_PENALTY)) { - return@setOnClickListener + return } if (viewModel.configKey != null) { diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardBottomAreaViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardBottomAreaViewModel.kt index 01d5e5c493ce..e3ebac60febb 100644 --- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardBottomAreaViewModel.kt +++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardBottomAreaViewModel.kt @@ -16,6 +16,7 @@ package com.android.systemui.keyguard.ui.viewmodel +import androidx.annotation.VisibleForTesting import com.android.systemui.doze.util.BurnInHelperWrapper import com.android.systemui.keyguard.domain.interactor.KeyguardBottomAreaInteractor import com.android.systemui.keyguard.domain.interactor.KeyguardInteractor @@ -37,6 +38,23 @@ constructor( private val bottomAreaInteractor: KeyguardBottomAreaInteractor, private val burnInHelperWrapper: BurnInHelperWrapper, ) { + /** + * Whether quick affordances are "opaque enough" to be considered visible to and interactive by + * the user. If they are not interactive, user input should not be allowed on them. + * + * Note that there is a margin of error, where we allow very, very slightly transparent views to + * be considered "fully opaque" for the purpose of being interactive. This is to accommodate the + * error margin of floating point arithmetic. + * + * A view that is visible but with an alpha of less than our threshold either means it's not + * fully done fading in or is fading/faded out. Either way, it should not be + * interactive/clickable unless "fully opaque" to avoid issues like in b/241830987. + */ + private val areQuickAffordancesFullyOpaque: Flow<Boolean> = + bottomAreaInteractor.alpha + .map { alpha -> alpha >= AFFORDANCE_FULLY_OPAQUE_ALPHA_THRESHOLD } + .distinctUntilChanged() + /** An observable for the view-model of the "start button" quick affordance. */ val startButton: Flow<KeyguardQuickAffordanceViewModel> = button(KeyguardQuickAffordancePosition.BOTTOM_START) @@ -77,14 +95,19 @@ constructor( return combine( quickAffordanceInteractor.quickAffordance(position), bottomAreaInteractor.animateDozingTransitions.distinctUntilChanged(), - ) { model, animateReveal -> - model.toViewModel(animateReveal) + areQuickAffordancesFullyOpaque, + ) { model, animateReveal, isFullyOpaque -> + model.toViewModel( + animateReveal = animateReveal, + isClickable = isFullyOpaque, + ) } .distinctUntilChanged() } private fun KeyguardQuickAffordanceModel.toViewModel( animateReveal: Boolean, + isClickable: Boolean, ): KeyguardQuickAffordanceViewModel { return when (this) { is KeyguardQuickAffordanceModel.Visible -> @@ -100,8 +123,20 @@ constructor( animationController = parameters.animationController, ) }, + isClickable = isClickable, ) is KeyguardQuickAffordanceModel.Hidden -> KeyguardQuickAffordanceViewModel() } } + + companion object { + // We select a value that's less than 1.0 because we want floating point math precision to + // not be a factor in determining whether the affordance UI is fully opaque. The number we + // choose needs to be close enough 1.0 such that the user can't easily tell the difference + // between the UI with an alpha at the threshold and when the alpha is 1.0. At the same + // time, we don't want the number to be too close to 1.0 such that there is a chance that we + // never treat the affordance UI as "fully opaque" as that would risk making it forever not + // clickable. + @VisibleForTesting const val AFFORDANCE_FULLY_OPAQUE_ALPHA_THRESHOLD = 0.95f + } } diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardQuickAffordanceViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardQuickAffordanceViewModel.kt index 985ab623764a..b1de27d262cf 100644 --- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardQuickAffordanceViewModel.kt +++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardQuickAffordanceViewModel.kt @@ -31,6 +31,7 @@ data class KeyguardQuickAffordanceViewModel( val icon: ContainedDrawable = ContainedDrawable.WithResource(0), @StringRes val contentDescriptionResourceId: Int = 0, val onClicked: (OnClickedParameters) -> Unit = {}, + val isClickable: Boolean = false, ) { data class OnClickedParameters( val configKey: KClass<out KeyguardQuickAffordanceConfig>, diff --git a/packages/SystemUI/src/com/android/systemui/log/LogBuffer.kt b/packages/SystemUI/src/com/android/systemui/log/LogBuffer.kt index 6124e10144f2..77ad8069f273 100644 --- a/packages/SystemUI/src/com/android/systemui/log/LogBuffer.kt +++ b/packages/SystemUI/src/com/android/systemui/log/LogBuffer.kt @@ -158,8 +158,13 @@ class LogBuffer @JvmOverloads constructor( * add more detail to every log may do more to improve overall logging than adding more logs * with this method. */ - fun log(tag: String, level: LogLevel, @CompileTimeConstant message: String) = - log(tag, level, {str1 = message}, { str1!! }) + fun log( + tag: String, + level: LogLevel, + @CompileTimeConstant message: String, + exception: Throwable? = null + ) = + log(tag, level, {str1 = message}, { str1!! }, exception) /** * You should call [log] instead of this method. diff --git a/packages/SystemUI/src/com/android/systemui/log/dagger/KeyguardUpdateMonitorLog.kt b/packages/SystemUI/src/com/android/systemui/log/dagger/KeyguardUpdateMonitorLog.kt index 323ee21953ea..684839f2b124 100644 --- a/packages/SystemUI/src/com/android/systemui/log/dagger/KeyguardUpdateMonitorLog.kt +++ b/packages/SystemUI/src/com/android/systemui/log/dagger/KeyguardUpdateMonitorLog.kt @@ -1,4 +1,7 @@ package com.android.systemui.log.dagger +import javax.inject.Qualifier + /** A [com.android.systemui.log.LogBuffer] for KeyguardUpdateMonitor. */ +@Qualifier annotation class KeyguardUpdateMonitorLog diff --git a/packages/SystemUI/src/com/android/systemui/log/dagger/KeyguardViewMediatorLog.kt b/packages/SystemUI/src/com/android/systemui/log/dagger/KeyguardViewMediatorLog.kt new file mode 100644 index 000000000000..88e227b8ae35 --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/log/dagger/KeyguardViewMediatorLog.kt @@ -0,0 +1,23 @@ +/* + * 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.systemui.log.dagger + +import javax.inject.Qualifier + +/** A [com.android.systemui.log.LogBuffer] for KeyguardViewMediator. */ +@Qualifier +annotation class KeyguardViewMediatorLog
\ No newline at end of file diff --git a/packages/SystemUI/src/com/android/systemui/log/dagger/LogModule.java b/packages/SystemUI/src/com/android/systemui/log/dagger/LogModule.java index c2a87649adef..9af42f825e00 100644 --- a/packages/SystemUI/src/com/android/systemui/log/dagger/LogModule.java +++ b/packages/SystemUI/src/com/android/systemui/log/dagger/LogModule.java @@ -305,4 +305,15 @@ public class LogModule { public static LogBuffer provideKeyguardUpdateMonitorLogBuffer(LogBufferFactory factory) { return factory.create("KeyguardUpdateMonitorLog", 200); } + + /** + * Provides a {@link LogBuffer} for use by + * {@link com.android.systemui.keyguard.KeyguardViewMediator}. + */ + @Provides + @SysUISingleton + @KeyguardViewMediatorLog + public static LogBuffer provideKeyguardViewMediatorLogBuffer(LogBufferFactory factory) { + return factory.create("KeyguardViewMediatorLog", 100); + } } diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputAdapter.java b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputAdapter.java index e360d10d9362..ee5956105b7b 100644 --- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputAdapter.java +++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputAdapter.java @@ -16,6 +16,7 @@ package com.android.systemui.media.dialog; +import android.annotation.DrawableRes; import android.content.res.ColorStateList; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; @@ -42,9 +43,6 @@ public class MediaOutputAdapter extends MediaOutputBaseAdapter { private static final String TAG = "MediaOutputAdapter"; private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG); - private ViewGroup mConnectedItem; - private boolean mIncludeDynamicGroup; - public MediaOutputAdapter(MediaOutputController controller) { super(controller); setHasStableIds(true); @@ -102,141 +100,90 @@ public class MediaOutputAdapter extends MediaOutputBaseAdapter { void onBind(MediaDevice device, boolean topMargin, boolean bottomMargin, int position) { super.onBind(device, topMargin, bottomMargin, position); boolean isMutingExpectedDeviceExist = mController.hasMutingExpectedDevice(); - final boolean currentlyConnected = !mIncludeDynamicGroup - && isCurrentlyConnected(device); + final boolean currentlyConnected = isCurrentlyConnected(device); boolean isCurrentSeekbarInvisible = mSeekBar.getVisibility() == View.GONE; - if (currentlyConnected) { - mConnectedItem = mContainerLayout; - } - mCheckBox.setVisibility(View.GONE); - mStatusIcon.setVisibility(View.GONE); - mEndTouchArea.setVisibility(View.GONE); - mEndTouchArea.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); - mContainerLayout.setOnClickListener(null); - mContainerLayout.setContentDescription(null); - mTitleText.setTextColor(mController.getColorItemContent()); - mSubTitleText.setTextColor(mController.getColorItemContent()); - mTwoLineTitleText.setTextColor(mController.getColorItemContent()); - mSeekBar.getProgressDrawable().setColorFilter( - new PorterDuffColorFilter(mController.getColorSeekbarProgress(), - PorterDuff.Mode.SRC_IN)); if (mCurrentActivePosition == position) { mCurrentActivePosition = -1; } - if (mController.isTransferring()) { + if (mController.isAnyDeviceTransferring()) { if (device.getState() == MediaDeviceState.STATE_CONNECTING && !mController.hasAdjustVolumeUserRestriction()) { setUpDeviceIcon(device); - mProgressBar.getIndeterminateDrawable().setColorFilter( - new PorterDuffColorFilter( - mController.getColorItemContent(), - PorterDuff.Mode.SRC_IN)); - setSingleLineLayout(getItemTitle(device), true /* bFocused */, - false /* showSeekBar*/, - true /* showProgressBar */, false /* showStatus */); + updateProgressBarColor(); + setSingleLineLayout(getItemTitle(device), false /* showSeekBar*/, + true /* showProgressBar */, false /* showCheckBox */, + false /* showEndTouchArea */); } else { setUpDeviceIcon(device); - setSingleLineLayout(getItemTitle(device), false /* bFocused */); + setSingleLineLayout(getItemTitle(device)); } } else { // Set different layout for each device if (device.isMutingExpectedDevice() && !mController.isCurrentConnectedDeviceRemote()) { - mTitleIcon.setImageDrawable( - mContext.getDrawable(R.drawable.media_output_icon_volume)); - mTitleIcon.setColorFilter(mController.getColorItemContent()); - mTitleText.setTextColor(mController.getColorItemContent()); - setSingleLineLayout(getItemTitle(device), true /* bFocused */, - false /* showSeekBar */, - false /* showProgressBar */, false /* showStatus */); + updateTitleIcon(R.drawable.media_output_icon_volume, + mController.getColorItemContent()); initMutingExpectedDevice(); mCurrentActivePosition = position; - mContainerLayout.setOnClickListener(v -> onItemClick(v, device)); + updateContainerClickListener(v -> onItemClick(v, device)); + setSingleLineLayout(getItemTitle(device)); } else if (device.getState() == MediaDeviceState.STATE_CONNECTING_FAILED) { setUpDeviceIcon(device); - mStatusIcon.setImageDrawable( - mContext.getDrawable(R.drawable.media_output_status_failed)); - mStatusIcon.setColorFilter(mController.getColorItemContent()); - setTwoLineLayout(device, false /* bFocused */, - false /* showSeekBar */, false /* showProgressBar */, - true /* showSubtitle */, true /* showStatus */); + updateConnectionFailedStatusIcon(); mSubTitleText.setText(R.string.media_output_dialog_connect_failed); - mContainerLayout.setOnClickListener(v -> onItemClick(v, device)); + updateContainerClickListener(v -> onItemClick(v, device)); + setTwoLineLayout(device, false /* bFocused */, false /* showSeekBar */, + false /* showProgressBar */, true /* showSubtitle */, + true /* showStatus */); } else if (device.getState() == MediaDeviceState.STATE_GROUPING) { setUpDeviceIcon(device); - mProgressBar.getIndeterminateDrawable().setColorFilter( - new PorterDuffColorFilter( - mController.getColorItemContent(), - PorterDuff.Mode.SRC_IN)); - setSingleLineLayout(getItemTitle(device), true /* bFocused */, - false /* showSeekBar*/, - true /* showProgressBar */, false /* showStatus */); + updateProgressBarColor(); + setSingleLineLayout(getItemTitle(device), false /* showSeekBar*/, + true /* showProgressBar */, false /* showCheckBox */, + false /* showEndTouchArea */); } else if (mController.getSelectedMediaDevice().size() > 1 && isDeviceIncluded(mController.getSelectedMediaDevice(), device)) { boolean isDeviceDeselectable = isDeviceIncluded( mController.getDeselectableMediaDevice(), device); - mTitleText.setTextColor(mController.getColorItemContent()); - mTitleIcon.setImageDrawable( - mContext.getDrawable(R.drawable.media_output_icon_volume)); - mTitleIcon.setColorFilter(mController.getColorItemContent()); - setSingleLineLayout(getItemTitle(device), true /* bFocused */, - true /* showSeekBar */, - false /* showProgressBar */, false /* showStatus */); + updateTitleIcon(R.drawable.media_output_icon_volume, + mController.getColorItemContent()); + updateGroupableCheckBox(true, isDeviceDeselectable, device); + updateEndClickArea(device, isDeviceDeselectable); setUpContentDescriptionForView(mContainerLayout, false, device); - mCheckBox.setOnCheckedChangeListener(null); - mCheckBox.setVisibility(View.VISIBLE); - mCheckBox.setChecked(true); - mCheckBox.setOnCheckedChangeListener(isDeviceDeselectable - ? (buttonView, isChecked) -> onGroupActionTriggered(false, device) - : null); - mCheckBox.setEnabled(isDeviceDeselectable); - setCheckBoxColor(mCheckBox, mController.getColorItemContent()); + setSingleLineLayout(getItemTitle(device), true /* showSeekBar */, + false /* showProgressBar */, true /* showCheckBox */, + true /* showEndTouchArea */); initSeekbar(device, isCurrentSeekbarInvisible); - mEndTouchArea.setVisibility(View.VISIBLE); - mEndTouchArea.setOnClickListener(null); - mEndTouchArea.setOnClickListener( - isDeviceDeselectable ? (v) -> mCheckBox.performClick() : null); - mEndTouchArea.setImportantForAccessibility( - View.IMPORTANT_FOR_ACCESSIBILITY_YES); - setUpContentDescriptionForView(mEndTouchArea, true, device); } else if (!mController.hasAdjustVolumeUserRestriction() && currentlyConnected) { if (isMutingExpectedDeviceExist && !mController.isCurrentConnectedDeviceRemote()) { // mark as disconnected and set special click listener setUpDeviceIcon(device); - setSingleLineLayout(getItemTitle(device), false /* bFocused */); - mContainerLayout.setOnClickListener(v -> cancelMuteAwaitConnection()); + updateContainerClickListener(v -> cancelMuteAwaitConnection()); + setSingleLineLayout(getItemTitle(device)); } else { - mTitleIcon.setImageDrawable( - mContext.getDrawable(R.drawable.media_output_icon_volume)); - mTitleIcon.setColorFilter(mController.getColorItemContent()); - mTitleText.setTextColor(mController.getColorItemContent()); - setSingleLineLayout(getItemTitle(device), true /* bFocused */, - true /* showSeekBar */, - false /* showProgressBar */, false /* showStatus */); - initSeekbar(device, isCurrentSeekbarInvisible); + updateTitleIcon(R.drawable.media_output_icon_volume, + mController.getColorItemContent()); setUpContentDescriptionForView(mContainerLayout, false, device); mCurrentActivePosition = position; + setSingleLineLayout(getItemTitle(device), true /* showSeekBar */, + false /* showProgressBar */, false /* showCheckBox */, + false /* showEndTouchArea */); + initSeekbar(device, isCurrentSeekbarInvisible); } } else if (isDeviceIncluded(mController.getSelectableMediaDevice(), device)) { setUpDeviceIcon(device); - mCheckBox.setOnCheckedChangeListener(null); - mCheckBox.setVisibility(View.VISIBLE); - mCheckBox.setChecked(false); - mCheckBox.setOnCheckedChangeListener( - (buttonView, isChecked) -> onGroupActionTriggered(true, device)); - mEndTouchArea.setVisibility(View.VISIBLE); - mContainerLayout.setOnClickListener(v -> onGroupActionTriggered(true, device)); - setCheckBoxColor(mCheckBox, mController.getColorItemContent()); - setSingleLineLayout(getItemTitle(device), false /* bFocused */, - false /* showSeekBar */, - false /* showProgressBar */, false /* showStatus */); + updateGroupableCheckBox(false, true, device); + updateContainerClickListener(v -> onGroupActionTriggered(true, device)); + setSingleLineLayout(getItemTitle(device), false /* showSeekBar */, + false /* showProgressBar */, true /* showCheckBox */, + true /* showEndTouchArea */); } else { setUpDeviceIcon(device); - setSingleLineLayout(getItemTitle(device), false /* bFocused */); - mContainerLayout.setOnClickListener(v -> onItemClick(v, device)); + setSingleLineLayout(getItemTitle(device)); + updateContainerClickListener(v -> onItemClick(v, device)); } } } @@ -248,15 +195,56 @@ public class MediaOutputAdapter extends MediaOutputBaseAdapter { ColorStateList(states, colors)); } + private void updateConnectionFailedStatusIcon() { + mStatusIcon.setImageDrawable( + mContext.getDrawable(R.drawable.media_output_status_failed)); + mStatusIcon.setColorFilter(mController.getColorItemContent()); + } + + private void updateProgressBarColor() { + mProgressBar.getIndeterminateDrawable().setColorFilter( + new PorterDuffColorFilter( + mController.getColorItemContent(), + PorterDuff.Mode.SRC_IN)); + } + + public void updateEndClickArea(MediaDevice device, boolean isDeviceDeselectable) { + mEndTouchArea.setOnClickListener(null); + mEndTouchArea.setOnClickListener( + isDeviceDeselectable ? (v) -> mCheckBox.performClick() : null); + mEndTouchArea.setImportantForAccessibility( + View.IMPORTANT_FOR_ACCESSIBILITY_YES); + setUpContentDescriptionForView(mEndTouchArea, true, device); + } + + private void updateGroupableCheckBox(boolean isSelected, boolean isGroupable, + MediaDevice device) { + mCheckBox.setOnCheckedChangeListener(null); + mCheckBox.setChecked(isSelected); + mCheckBox.setOnCheckedChangeListener( + isGroupable ? (buttonView, isChecked) -> onGroupActionTriggered(!isSelected, + device) : null); + mCheckBox.setEnabled(isGroupable); + setCheckBoxColor(mCheckBox, mController.getColorItemContent()); + } + + private void updateTitleIcon(@DrawableRes int id, int color) { + mTitleIcon.setImageDrawable(mContext.getDrawable(id)); + mTitleIcon.setColorFilter(color); + } + + private void updateContainerClickListener(View.OnClickListener listener) { + mContainerLayout.setOnClickListener(listener); + } + @Override void onBind(int customizedItem, boolean topMargin, boolean bottomMargin) { if (customizedItem == CUSTOMIZED_ITEM_PAIR_NEW) { mTitleText.setTextColor(mController.getColorItemContent()); mCheckBox.setVisibility(View.GONE); - setSingleLineLayout(mContext.getText(R.string.media_output_dialog_pairing_new), - false /* bFocused */); - final Drawable d = mContext.getDrawable(R.drawable.ic_add); - mTitleIcon.setImageDrawable(d); + setSingleLineLayout(mContext.getText(R.string.media_output_dialog_pairing_new)); + final Drawable addDrawable = mContext.getDrawable(R.drawable.ic_add); + mTitleIcon.setImageDrawable(addDrawable); mTitleIcon.setColorFilter(mController.getColorItemContent()); mContainerLayout.setOnClickListener(mController::launchBluetoothPairing); } @@ -273,7 +261,7 @@ public class MediaOutputAdapter extends MediaOutputBaseAdapter { } private void onItemClick(View view, MediaDevice device) { - if (mController.isTransferring()) { + if (mController.isAnyDeviceTransferring()) { return; } if (isCurrentlyConnected(device)) { diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBaseAdapter.java b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBaseAdapter.java index 43b0287c164e..3f7b2261ea52 100644 --- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBaseAdapter.java +++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBaseAdapter.java @@ -63,8 +63,6 @@ public abstract class MediaOutputBaseAdapter extends protected final MediaOutputController mController; - private int mMargin; - Context mContext; View mHolderView; boolean mIsDragging; @@ -82,8 +80,6 @@ public abstract class MediaOutputBaseAdapter extends public MediaDeviceBaseViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) { mContext = viewGroup.getContext(); - mMargin = mContext.getResources().getDimensionPixelSize( - R.dimen.media_output_dialog_list_margin); mHolderView = LayoutInflater.from(mContext).inflate(R.layout.media_output_list_item, viewGroup, false); @@ -168,16 +164,28 @@ public abstract class MediaOutputBaseAdapter extends void onBind(MediaDevice device, boolean topMargin, boolean bottomMargin, int position) { mDeviceId = device.getId(); + mCheckBox.setVisibility(View.GONE); + mStatusIcon.setVisibility(View.GONE); + mEndTouchArea.setVisibility(View.GONE); + mEndTouchArea.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); + mContainerLayout.setOnClickListener(null); + mContainerLayout.setContentDescription(null); + mTitleText.setTextColor(mController.getColorItemContent()); + mSubTitleText.setTextColor(mController.getColorItemContent()); + mTwoLineTitleText.setTextColor(mController.getColorItemContent()); + mSeekBar.getProgressDrawable().setColorFilter( + new PorterDuffColorFilter(mController.getColorSeekbarProgress(), + PorterDuff.Mode.SRC_IN)); } abstract void onBind(int customizedItem, boolean topMargin, boolean bottomMargin); - void setSingleLineLayout(CharSequence title, boolean bFocused) { - setSingleLineLayout(title, bFocused, false, false, false); + void setSingleLineLayout(CharSequence title) { + setSingleLineLayout(title, false, false, false, false); } - void setSingleLineLayout(CharSequence title, boolean bFocused, boolean showSeekBar, - boolean showProgressBar, boolean showStatus) { + void setSingleLineLayout(CharSequence title, boolean showSeekBar, + boolean showProgressBar, boolean showCheckBox, boolean showEndTouchArea) { mTwoLineLayout.setVisibility(View.GONE); boolean isActive = showSeekBar || showProgressBar; if (!mCornerAnimator.isRunning()) { @@ -188,10 +196,6 @@ public abstract class MediaOutputBaseAdapter extends .mutate() : mContext.getDrawable( R.drawable.media_output_item_background) .mutate(); - backgroundDrawable.setColorFilter(new PorterDuffColorFilter( - isActive ? mController.getColorConnectedItemBackground() - : mController.getColorItemBackground(), - PorterDuff.Mode.SRC_IN)); mItemLayout.setBackground(backgroundDrawable); if (showSeekBar) { final ClipDrawable clipDrawable = @@ -201,27 +205,21 @@ public abstract class MediaOutputBaseAdapter extends (GradientDrawable) clipDrawable.getDrawable(); progressDrawable.setCornerRadius(mController.getActiveRadius()); } - } else { - mItemLayout.getBackground().setColorFilter(new PorterDuffColorFilter( - isActive ? mController.getColorConnectedItemBackground() - : mController.getColorItemBackground(), - PorterDuff.Mode.SRC_IN)); } + mItemLayout.getBackground().setColorFilter(new PorterDuffColorFilter( + isActive ? mController.getColorConnectedItemBackground() + : mController.getColorItemBackground(), + PorterDuff.Mode.SRC_IN)); mProgressBar.setVisibility(showProgressBar ? View.VISIBLE : View.GONE); mSeekBar.setAlpha(1); mSeekBar.setVisibility(showSeekBar ? View.VISIBLE : View.GONE); if (!showSeekBar) { mSeekBar.resetVolume(); } - mStatusIcon.setVisibility(showStatus ? View.VISIBLE : View.GONE); mTitleText.setText(title); mTitleText.setVisibility(View.VISIBLE); - } - - void setTwoLineLayout(MediaDevice device, boolean bFocused, boolean showSeekBar, - boolean showProgressBar, boolean showSubtitle) { - setTwoLineLayout(device, null, bFocused, showSeekBar, showProgressBar, showSubtitle, - false); + mCheckBox.setVisibility(showCheckBox ? View.VISIBLE : View.GONE); + mEndTouchArea.setVisibility(showEndTouchArea ? View.VISIBLE : View.GONE); } void setTwoLineLayout(MediaDevice device, boolean bFocused, boolean showSeekBar, @@ -230,12 +228,6 @@ public abstract class MediaOutputBaseAdapter extends showStatus); } - void setTwoLineLayout(CharSequence title, boolean bFocused, boolean showSeekBar, - boolean showProgressBar, boolean showSubtitle) { - setTwoLineLayout(null, title, bFocused, showSeekBar, showProgressBar, showSubtitle, - false); - } - private void setTwoLineLayout(MediaDevice device, CharSequence title, boolean bFocused, boolean showSeekBar, boolean showProgressBar, boolean showSubtitle, boolean showStatus) { @@ -254,20 +246,11 @@ public abstract class MediaOutputBaseAdapter extends mProgressBar.setVisibility(showProgressBar ? View.VISIBLE : View.GONE); mSubTitleText.setVisibility(showSubtitle ? View.VISIBLE : View.GONE); mTwoLineTitleText.setTranslationY(0); - if (device == null) { - mTwoLineTitleText.setText(title); - } else { - mTwoLineTitleText.setText(getItemTitle(device)); - } - - if (bFocused) { - mTwoLineTitleText.setTypeface(Typeface.create(mContext.getString( - com.android.internal.R.string.config_headlineFontFamilyMedium), - Typeface.NORMAL)); - } else { - mTwoLineTitleText.setTypeface(Typeface.create(mContext.getString( - com.android.internal.R.string.config_headlineFontFamily), Typeface.NORMAL)); - } + mTwoLineTitleText.setText(device == null ? title : getItemTitle(device)); + mTwoLineTitleText.setTypeface(Typeface.create(mContext.getString( + bFocused ? com.android.internal.R.string.config_headlineFontFamilyMedium + : com.android.internal.R.string.config_headlineFontFamily), + Typeface.NORMAL)); } void initSeekbar(MediaDevice device, boolean isCurrentSeekbarInvisible) { @@ -327,35 +310,6 @@ public abstract class MediaOutputBaseAdapter extends mItemLayout.setBackground(backgroundDrawable); } - void initSessionSeekbar() { - disableSeekBar(); - mSeekBar.setMax(mController.getSessionVolumeMax()); - mSeekBar.setMin(0); - final int currentVolume = mController.getSessionVolume(); - if (mSeekBar.getProgress() != currentVolume) { - mSeekBar.setProgress(currentVolume, true); - } - mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (!fromUser) { - return; - } - mController.adjustSessionVolume(progress); - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - mIsDragging = true; - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - mIsDragging = false; - } - }); - } - private void animateCornerAndVolume(int fromProgress, int toProgress) { final GradientDrawable layoutBackgroundDrawable = (GradientDrawable) mItemLayout.getBackground(); diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputController.java b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputController.java index f7d80e0b1dbd..96817c9bf32d 100644 --- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputController.java +++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputController.java @@ -411,7 +411,7 @@ public class MediaOutputController implements LocalMediaManager.DeviceCallback, device.getId()); boolean isSelectedDeviceInGroup = getSelectedMediaDevice().size() > 1 && getSelectedMediaDevice().contains(device); - return (!hasAdjustVolumeUserRestriction() && isConnected && !isTransferring()) + return (!hasAdjustVolumeUserRestriction() && isConnected && !isAnyDeviceTransferring()) || isSelectedDeviceInGroup; } @@ -708,7 +708,7 @@ public class MediaOutputController implements LocalMediaManager.DeviceCallback, UserHandle.of(UserHandle.myUserId())); } - boolean isTransferring() { + boolean isAnyDeviceTransferring() { synchronized (mMediaDevicesLock) { for (MediaDevice device : mMediaDevices) { if (device.getState() == LocalMediaManager.MediaDeviceState.STATE_CONNECTING) { diff --git a/packages/SystemUI/src/com/android/systemui/media/taptotransfer/common/MediaTttChipControllerCommon.kt b/packages/SystemUI/src/com/android/systemui/media/taptotransfer/common/MediaTttChipControllerCommon.kt index 2278938c398e..3a0ac1b7d9b0 100644 --- a/packages/SystemUI/src/com/android/systemui/media/taptotransfer/common/MediaTttChipControllerCommon.kt +++ b/packages/SystemUI/src/com/android/systemui/media/taptotransfer/common/MediaTttChipControllerCommon.kt @@ -226,7 +226,7 @@ abstract class MediaTttChipControllerCommon<T : ChipInfoCommon>( appIconView.contentDescription = appNameOverride ?: iconInfo.iconName appIconView.setImageDrawable(appIconDrawableOverride ?: iconInfo.icon) - return appIconView.contentDescription.toString() + return appIconView.contentDescription } /** diff --git a/packages/SystemUI/src/com/android/systemui/media/taptotransfer/receiver/MediaTttChipControllerReceiver.kt b/packages/SystemUI/src/com/android/systemui/media/taptotransfer/receiver/MediaTttChipControllerReceiver.kt index 196ea222e50d..00a22f20e94d 100644 --- a/packages/SystemUI/src/com/android/systemui/media/taptotransfer/receiver/MediaTttChipControllerReceiver.kt +++ b/packages/SystemUI/src/com/android/systemui/media/taptotransfer/receiver/MediaTttChipControllerReceiver.kt @@ -141,12 +141,13 @@ class MediaTttChipControllerReceiver @Inject constructor( override fun updateChipView(newChipInfo: ChipReceiverInfo, currentChipView: ViewGroup) { super.updateChipView(newChipInfo, currentChipView) - setIcon( + val iconName = setIcon( currentChipView, newChipInfo.routeInfo.clientPackageName, newChipInfo.appIconDrawableOverride, newChipInfo.appNameOverride ) + currentChipView.contentDescription = iconName } override fun animateChipIn(chipView: ViewGroup) { @@ -159,6 +160,8 @@ class MediaTttChipControllerReceiver @Inject constructor( .alpha(1f) .setDuration(5.frames) .start() + // Using withEndAction{} doesn't apply a11y focus when screen is unlocked. + appIconView.postOnAnimation { chipView.requestAccessibilityFocus() } startRipple(chipView.requireViewById(R.id.ripple)) } diff --git a/packages/SystemUI/src/com/android/systemui/navigationbar/gestural/EdgeBackGestureHandler.java b/packages/SystemUI/src/com/android/systemui/navigationbar/gestural/EdgeBackGestureHandler.java index 6ac3eadb838d..7c4c64c20089 100644 --- a/packages/SystemUI/src/com/android/systemui/navigationbar/gestural/EdgeBackGestureHandler.java +++ b/packages/SystemUI/src/com/android/systemui/navigationbar/gestural/EdgeBackGestureHandler.java @@ -814,8 +814,10 @@ public class EdgeBackGestureHandler extends CurrentUserTracker } mLogGesture = false; String logPackageName = ""; + Map<String, Integer> vocab = mVocab; // Due to privacy, only top 100 most used apps by all users can be logged. - if (mUseMLModel && mVocab.containsKey(mPackageName) && mVocab.get(mPackageName) < 100) { + if (mUseMLModel && vocab != null && vocab.containsKey(mPackageName) + && vocab.get(mPackageName) < 100) { logPackageName = mPackageName; } SysUiStatsLog.write(SysUiStatsLog.BACK_GESTURE_REPORTED_REPORTED, backType, diff --git a/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeaderController.java b/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeaderController.java index eeb1010693fc..2a6cf66995ea 100644 --- a/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeaderController.java +++ b/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeaderController.java @@ -80,7 +80,8 @@ class QuickStatusBarHeaderController extends ViewController<QuickStatusBarHeader FeatureFlags featureFlags, VariableDateViewController.Factory variableDateViewControllerFactory, BatteryMeterViewController batteryMeterViewController, - StatusBarContentInsetsProvider statusBarContentInsetsProvider) { + StatusBarContentInsetsProvider statusBarContentInsetsProvider, + StatusBarIconController.TintedIconManager.Factory tintedIconManagerFactory) { super(view); mPrivacyIconsController = headerPrivacyIconsController; mStatusBarIconController = statusBarIconController; @@ -103,7 +104,7 @@ class QuickStatusBarHeaderController extends ViewController<QuickStatusBarHeader mView.requireViewById(R.id.date_clock) ); - mIconManager = new StatusBarIconController.TintedIconManager(mIconContainer, featureFlags); + mIconManager = tintedIconManagerFactory.create(mIconContainer); mDemoModeReceiver = new ClockDemoModeReceiver(mClockView); mColorExtractor = colorExtractor; mOnColorsChangedListener = (extractor, which) -> { diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java b/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java index a8993bc274e4..35f32caffe21 100644 --- a/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java +++ b/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java @@ -53,8 +53,7 @@ import android.util.Log; import android.view.WindowManager; import android.widget.Toast; -import androidx.annotation.NonNull; - +import com.android.internal.annotations.VisibleForTesting; import com.android.internal.logging.UiEventLogger; import com.android.internal.util.ScreenshotHelper; import com.android.systemui.R; @@ -70,7 +69,7 @@ import javax.inject.Inject; public class TakeScreenshotService extends Service { private static final String TAG = logTag(TakeScreenshotService.class); - private ScreenshotController mScreenshot; + private final ScreenshotController mScreenshot; private final UserManager mUserManager; private final DevicePolicyManager mDevicePolicyManager; @@ -137,7 +136,7 @@ public class TakeScreenshotService extends Service { } @Override - public IBinder onBind(@NonNull Intent intent) { + public IBinder onBind(Intent intent) { registerReceiver(mCloseSystemDialogs, new IntentFilter(ACTION_CLOSE_SYSTEM_DIALOGS), Context.RECEIVER_EXPORTED); final Messenger m = new Messenger(mHandler); @@ -152,10 +151,7 @@ public class TakeScreenshotService extends Service { if (DEBUG_SERVICE) { Log.d(TAG, "onUnbind"); } - if (mScreenshot != null) { - mScreenshot.removeWindow(); - mScreenshot = null; - } + mScreenshot.removeWindow(); unregisterReceiver(mCloseSystemDialogs); return false; } @@ -163,10 +159,7 @@ public class TakeScreenshotService extends Service { @Override public void onDestroy() { super.onDestroy(); - if (mScreenshot != null) { - mScreenshot.onDestroy(); - mScreenshot = null; - } + mScreenshot.onDestroy(); if (DEBUG_SERVICE) { Log.d(TAG, "onDestroy"); } @@ -190,13 +183,23 @@ public class TakeScreenshotService extends Service { } } - /** Respond to incoming Message via Binder (Messenger) */ @MainThread private boolean handleMessage(Message msg) { final Messenger replyTo = msg.replyTo; - final Consumer<Uri> uriConsumer = (uri) -> reportUri(replyTo, uri); - RequestCallback requestCallback = new RequestCallbackImpl(replyTo); + final Consumer<Uri> onSaved = (uri) -> reportUri(replyTo, uri); + RequestCallback callback = new RequestCallbackImpl(replyTo); + + ScreenshotHelper.ScreenshotRequest request = + (ScreenshotHelper.ScreenshotRequest) msg.obj; + + handleRequest(request, onSaved, callback); + return true; + } + @MainThread + @VisibleForTesting + void handleRequest(ScreenshotHelper.ScreenshotRequest request, Consumer<Uri> onSaved, + RequestCallback callback) { // If the storage for this user is locked, we have no place to store // the screenshot, so skip taking it instead of showing a misleading // animation and error notification. @@ -204,8 +207,8 @@ public class TakeScreenshotService extends Service { Log.w(TAG, "Skipping screenshot because storage is locked!"); mNotificationsController.notifyScreenshotError( R.string.screenshot_failed_to_save_user_locked_text); - requestCallback.reportError(); - return true; + callback.reportError(); + return; } if (mDevicePolicyManager.getScreenCaptureDisabled(null, UserHandle.USER_ALL)) { @@ -217,33 +220,26 @@ public class TakeScreenshotService extends Service { () -> mContext.getString(R.string.screenshot_blocked_by_admin)); mHandler.post(() -> Toast.makeText(mContext, blockedByAdminText, Toast.LENGTH_SHORT).show()); - requestCallback.reportError(); + callback.reportError(); }); - return true; + return; } - ScreenshotHelper.ScreenshotRequest screenshotRequest = - (ScreenshotHelper.ScreenshotRequest) msg.obj; - - ComponentName topComponent = screenshotRequest.getTopComponent(); - mUiEventLogger.log(ScreenshotEvent.getScreenshotSource(screenshotRequest.getSource()), 0, - topComponent == null ? "" : topComponent.getPackageName()); - if (mFeatureFlags.isEnabled(SCREENSHOT_REQUEST_PROCESSOR)) { Log.d(TAG, "handleMessage: Using request processor"); - mProcessor.processAsync(screenshotRequest, - (request) -> dispatchToController(request, uriConsumer, requestCallback)); - return true; + mProcessor.processAsync(request, + (r) -> dispatchToController(r, onSaved, callback)); } - dispatchToController(screenshotRequest, uriConsumer, requestCallback); - return true; + dispatchToController(request, onSaved, callback); } private void dispatchToController(ScreenshotHelper.ScreenshotRequest request, Consumer<Uri> uriConsumer, RequestCallback callback) { ComponentName topComponent = request.getTopComponent(); + mUiEventLogger.log(ScreenshotEvent.getScreenshotSource(request.getSource()), 0, + topComponent == null ? "" : topComponent.getPackageName()); switch (request.getType()) { case WindowManager.TAKE_SCREENSHOT_FULLSCREEN: diff --git a/packages/SystemUI/src/com/android/systemui/settings/UserTracker.kt b/packages/SystemUI/src/com/android/systemui/settings/UserTracker.kt index 5e908d9cd29f..1558ac533137 100644 --- a/packages/SystemUI/src/com/android/systemui/settings/UserTracker.kt +++ b/packages/SystemUI/src/com/android/systemui/settings/UserTracker.kt @@ -76,6 +76,6 @@ interface UserTracker : UserContentResolverProvider, UserContextProvider { * Notifies that the current user's profiles have changed. */ @JvmDefault - fun onProfilesChanged(profiles: List<UserInfo>) {} + fun onProfilesChanged(profiles: List<@JvmSuppressWildcards UserInfo>) {} } }
\ No newline at end of file diff --git a/packages/SystemUI/src/com/android/systemui/shade/LargeScreenShadeHeaderController.kt b/packages/SystemUI/src/com/android/systemui/shade/LargeScreenShadeHeaderController.kt index 0f9ac360cbe1..fab70fc2eebd 100644 --- a/packages/SystemUI/src/com/android/systemui/shade/LargeScreenShadeHeaderController.kt +++ b/packages/SystemUI/src/com/android/systemui/shade/LargeScreenShadeHeaderController.kt @@ -77,6 +77,7 @@ import javax.inject.Named class LargeScreenShadeHeaderController @Inject constructor( @Named(LARGE_SCREEN_SHADE_HEADER) private val header: View, private val statusBarIconController: StatusBarIconController, + private val tintedIconManagerFactory: StatusBarIconController.TintedIconManager.Factory, private val privacyIconsController: HeaderPrivacyIconsController, private val insetsProvider: StatusBarContentInsetsProvider, private val configurationController: ConfigurationController, @@ -259,7 +260,7 @@ class LargeScreenShadeHeaderController @Inject constructor( batteryMeterViewController.ignoreTunerUpdates() batteryIcon.setPercentShowMode(BatteryMeterView.MODE_ESTIMATE) - iconManager = StatusBarIconController.TintedIconManager(iconContainer, featureFlags) + iconManager = tintedIconManagerFactory.create(iconContainer) iconManager.setTint( Utils.getColorAttrDefaultColor(header.context, android.R.attr.textColorPrimary) ) diff --git a/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java b/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java index 7a4c87766114..29c7633ca93e 100644 --- a/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java +++ b/packages/SystemUI/src/com/android/systemui/shade/NotificationPanelViewController.java @@ -54,7 +54,6 @@ import android.graphics.ColorFilter; import android.graphics.Insets; import android.graphics.Paint; import android.graphics.PixelFormat; -import android.graphics.PointF; import android.graphics.Rect; import android.graphics.Region; import android.graphics.drawable.Drawable; @@ -98,6 +97,7 @@ import com.android.internal.policy.ScreenDecorationsUtils; import com.android.internal.policy.SystemBarUtils; import com.android.internal.util.LatencyTracker; import com.android.keyguard.ActiveUnlockConfig; +import com.android.keyguard.KeyguardClockSwitch.ClockSize; import com.android.keyguard.KeyguardStatusView; import com.android.keyguard.KeyguardStatusViewController; import com.android.keyguard.KeyguardUnfoldTransition; @@ -1416,19 +1416,10 @@ public final class NotificationPanelViewController extends PanelViewController { private void updateClockAppearance() { int userSwitcherPreferredY = mStatusBarHeaderHeightKeyguard; boolean bypassEnabled = mKeyguardBypassController.getBypassEnabled(); - final boolean hasVisibleNotifications = mNotificationStackScrollLayoutController - .getVisibleNotificationCount() != 0 - || mMediaDataManager.hasActiveMediaOrRecommendation(); - boolean splitShadeWithActiveMedia = - mSplitShadeEnabled && mMediaDataManager.hasActiveMediaOrRecommendation(); boolean shouldAnimateClockChange = mScreenOffAnimationController.shouldAnimateClockChange(); - if ((hasVisibleNotifications && !mSplitShadeEnabled) - || (splitShadeWithActiveMedia && !mDozing)) { - mKeyguardStatusViewController.displayClock(SMALL, shouldAnimateClockChange); - } else { - mKeyguardStatusViewController.displayClock(LARGE, shouldAnimateClockChange); - } - updateKeyguardStatusViewAlignment(true /* animate */); + mKeyguardStatusViewController.displayClock(computeDesiredClockSize(), + shouldAnimateClockChange); + updateKeyguardStatusViewAlignment(/* animate= */true); int userSwitcherHeight = mKeyguardQsUserSwitchController != null ? mKeyguardQsUserSwitchController.getUserIconHeight() : 0; if (mKeyguardUserSwitcherController != null) { @@ -1437,7 +1428,7 @@ public final class NotificationPanelViewController extends PanelViewController { float expandedFraction = mScreenOffAnimationController.shouldExpandNotifications() ? 1.0f : getExpandedFraction(); - float darkamount = + float darkAmount = mScreenOffAnimationController.shouldExpandNotifications() ? 1.0f : mInterpolatedDarkAmount; @@ -1455,7 +1446,7 @@ public final class NotificationPanelViewController extends PanelViewController { mKeyguardStatusViewController.getLockscreenHeight(), userSwitcherHeight, userSwitcherPreferredY, - darkamount, mOverStretchAmount, + darkAmount, mOverStretchAmount, bypassEnabled, getUnlockedStackScrollerPadding(), computeQsExpansionFraction(), mDisplayTopInset, @@ -1487,6 +1478,34 @@ public final class NotificationPanelViewController extends PanelViewController { updateClock(); } + @ClockSize + private int computeDesiredClockSize() { + if (mSplitShadeEnabled) { + return computeDesiredClockSizeForSplitShade(); + } + return computeDesiredClockSizeForSingleShade(); + } + + @ClockSize + private int computeDesiredClockSizeForSingleShade() { + if (hasVisibleNotifications()) { + return SMALL; + } + return LARGE; + } + + @ClockSize + private int computeDesiredClockSizeForSplitShade() { + // Media is not visible to the user on AOD. + boolean isMediaVisibleToUser = + mMediaDataManager.hasActiveMediaOrRecommendation() && !isOnAod(); + if (isMediaVisibleToUser) { + // When media is visible, it overlaps with the large clock. Use small clock instead. + return SMALL; + } + return LARGE; + } + private void updateKeyguardStatusViewAlignment(boolean animate) { boolean shouldBeCentered = shouldKeyguardStatusViewBeCentered(); if (mStatusViewCentered != shouldBeCentered) { @@ -1513,12 +1532,35 @@ public final class NotificationPanelViewController extends PanelViewController { } private boolean shouldKeyguardStatusViewBeCentered() { - boolean hasVisibleNotifications = mNotificationStackScrollLayoutController + if (mSplitShadeEnabled) { + return shouldKeyguardStatusViewBeCenteredInSplitShade(); + } + return true; + } + + private boolean shouldKeyguardStatusViewBeCenteredInSplitShade() { + if (!hasVisibleNotifications()) { + // No notifications visible. It is safe to have the clock centered as there will be no + // overlap. + return true; + } + if (hasPulsingNotifications()) { + // Pulsing notification appears on the right. Move clock left to avoid overlap. + return false; + } + // "Visible" notifications are actually not visible on AOD (unless pulsing), so it is safe + // to center the clock without overlap. + return isOnAod(); + } + + private boolean isOnAod() { + return mDozing && mDozeParameters.getAlwaysOn(); + } + + private boolean hasVisibleNotifications() { + return mNotificationStackScrollLayoutController .getVisibleNotificationCount() != 0 || mMediaDataManager.hasActiveMediaOrRecommendation(); - boolean isOnAod = mDozing && mDozeParameters.getAlwaysOn(); - return !mSplitShadeEnabled || !hasVisibleNotifications || isOnAod - || hasPulsingNotifications(); } /** @@ -3752,13 +3794,12 @@ public final class NotificationPanelViewController extends PanelViewController { * * @param dozing {@code true} when dozing. * @param animate if transition should be animated. - * @param wakeUpTouchLocation touch event location - if woken up by SLPI sensor. */ - public void setDozing(boolean dozing, boolean animate, PointF wakeUpTouchLocation) { + public void setDozing(boolean dozing, boolean animate) { if (dozing == mDozing) return; mView.setDozing(dozing); mDozing = dozing; - mNotificationStackScrollLayoutController.setDozing(mDozing, animate, wakeUpTouchLocation); + mNotificationStackScrollLayoutController.setDozing(mDozing, animate); mKeyguardBottomArea.setDozing(mDozing, animate); mKeyguardBottomAreaInteractorProvider.get().setAnimateDozingTransitions(animate); mKeyguardStatusBarViewController.setDozing(mDozing); @@ -3791,6 +3832,8 @@ public final class NotificationPanelViewController extends PanelViewController { mAnimateNextPositionUpdate = false; } mNotificationStackScrollLayoutController.setPulsing(pulsing, animatePulse); + + updateKeyguardStatusViewAlignment(/* animate= */ true); } public void setAmbientIndicationTop(int ambientIndicationTop, boolean ambientTextVisible) { @@ -4683,7 +4726,7 @@ public final class NotificationPanelViewController extends PanelViewController { * change. */ public void showAodUi() { - setDozing(true /* dozing */, false /* animate */, null); + setDozing(true /* dozing */, false /* animate */); mStatusBarStateController.setUpcomingState(KEYGUARD); mEntryManager.updateNotifications("showAodUi"); mStatusBarStateListener.onStateChanged(KEYGUARD); diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/AlertingNotificationManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/AlertingNotificationManager.java index 0898d6329f75..a72b7f167d95 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/AlertingNotificationManager.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/AlertingNotificationManager.java @@ -24,6 +24,7 @@ import android.util.ArrayMap; import android.util.ArraySet; import android.view.accessibility.AccessibilityEvent; +import com.android.internal.annotations.VisibleForTesting; import com.android.systemui.dagger.qualifiers.Main; import com.android.systemui.statusbar.notification.collection.NotificationEntry; import com.android.systemui.statusbar.notification.row.NotificationRowContentBinder.InflationFlag; @@ -49,7 +50,8 @@ public abstract class AlertingNotificationManager { protected int mMinimumDisplayTime; protected int mAutoDismissNotificationDecay; - private final Handler mHandler; + @VisibleForTesting + public Handler mHandler; /** * Called when posting a new notification that should alert the user and appear on screen. diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBarWifiView.kt b/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBarWifiView.kt new file mode 100644 index 000000000000..4d53064d047d --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBarWifiView.kt @@ -0,0 +1,34 @@ +/* + * 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.systemui.statusbar + +import android.content.Context +import android.util.AttributeSet +import android.widget.FrameLayout + +/** + * A temporary base class that's shared between our old status bar wifi view implementation + * ([StatusBarWifiView]) and our new status bar wifi view implementation + * ([ModernStatusBarWifiView]). + * + * Once our refactor is over, we should be able to delete this go-between class and the old view + * class. + */ +abstract class BaseStatusBarWifiView @JvmOverloads constructor( + context: Context, + attrs: AttributeSet? = null, + defStyleAttrs: Int = 0, +) : FrameLayout(context, attrs, defStyleAttrs), StatusIconDisplayable diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarStateControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarStateControllerImpl.java index 0280e0b729a9..c04bc8289f81 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarStateControllerImpl.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarStateControllerImpl.java @@ -303,11 +303,6 @@ public class StatusBarStateControllerImpl implements } @Override - public void setDozeAmount(float dozeAmount, boolean animated) { - setAndInstrumentDozeAmount(null, dozeAmount, animated); - } - - @Override public void setAndInstrumentDozeAmount(View view, float dozeAmount, boolean animated) { if (mDarkAnimator != null && mDarkAnimator.isRunning()) { if (animated && mDozeAmountTarget == dozeAmount) { diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarWifiView.java b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarWifiView.java index a6986d797833..5aee62e3e89f 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarWifiView.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarWifiView.java @@ -28,7 +28,6 @@ import android.util.AttributeSet; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; -import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; @@ -41,8 +40,7 @@ import java.util.ArrayList; /** * Start small: StatusBarWifiView will be able to layout from a WifiIconState */ -public class StatusBarWifiView extends FrameLayout implements DarkReceiver, - StatusIconDisplayable { +public class StatusBarWifiView extends BaseStatusBarWifiView implements DarkReceiver { private static final String TAG = "StatusBarWifiView"; /// Used to show etc dots @@ -80,11 +78,6 @@ public class StatusBarWifiView extends FrameLayout implements DarkReceiver, super(context, attrs, defStyleAttr); } - public StatusBarWifiView(Context context, AttributeSet attrs, int defStyleAttr, - int defStyleRes) { - super(context, attrs, defStyleAttr, defStyleRes); - } - public void setSlot(String slot) { mSlot = slot; } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/SysuiStatusBarStateController.java b/packages/SystemUI/src/com/android/systemui/statusbar/SysuiStatusBarStateController.java index 2b3190159ecd..2cc77384fb2a 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/SysuiStatusBarStateController.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/SysuiStatusBarStateController.java @@ -99,14 +99,6 @@ public interface SysuiStatusBarStateController extends StatusBarStateController boolean setIsDozing(boolean isDozing); /** - * Changes the current doze amount. - * - * @param dozeAmount New doze/dark amount. - * @param animated If change should be animated or not. This will cancel current animations. - */ - void setDozeAmount(float dozeAmount, boolean animated); - - /** * Changes the current doze amount, also starts the * {@link com.android.internal.jank.InteractionJankMonitor InteractionJankMonitor} as possible. * diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/WifiIcons.java b/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/WifiIcons.java index 3c449ad270ef..7097568c4adf 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/WifiIcons.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/WifiIcons.java @@ -23,7 +23,7 @@ import com.android.settingslib.SignalIcon.IconGroup; /** */ public class WifiIcons { - static final int[] WIFI_FULL_ICONS = { + public static final int[] WIFI_FULL_ICONS = { com.android.internal.R.drawable.ic_wifi_signal_0, com.android.internal.R.drawable.ic_wifi_signal_1, com.android.internal.R.drawable.ic_wifi_signal_2, diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ListAttachState.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ListAttachState.kt index 9e5dab1152ec..f8449ae8807b 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ListAttachState.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ListAttachState.kt @@ -90,6 +90,18 @@ data class ListAttachState private constructor( stableIndex = -1 } + /** + * Erases bookkeeping traces stored on an entry when it is removed from the notif list. + * This can happen if the entry is removed from a group that was broken up or if the entry was + * filtered out during any of the filtering steps. + */ + fun detach() { + parent = null + section = null + promoter = null + // stableIndex = -1 // TODO(b/241229236): Clear this once we fix the stability fragility + } + companion object { @JvmStatic fun create(): ListAttachState { diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilder.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilder.java index 14cc6bf1ea41..3eaa988e8389 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilder.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/ShadeListBuilder.java @@ -958,9 +958,7 @@ public class ShadeListBuilder implements Dumpable, PipelineDumpable { * filtered out during any of the filtering steps. */ private void annulAddition(ListEntry entry) { - entry.setParent(null); - entry.getAttachState().setSection(null); - entry.getAttachState().setPromoter(null); + entry.getAttachState().detach(); } private void assignSections() { @@ -1198,9 +1196,9 @@ public class ShadeListBuilder implements Dumpable, PipelineDumpable { o2.getSectionIndex()); if (cmp != 0) return cmp; - int index1 = canReorder(o1) ? -1 : o1.getPreviousAttachState().getStableIndex(); - int index2 = canReorder(o2) ? -1 : o2.getPreviousAttachState().getStableIndex(); - cmp = Integer.compare(index1, index2); + cmp = Integer.compare( + getStableOrderIndex(o1), + getStableOrderIndex(o2)); if (cmp != 0) return cmp; NotifComparator sectionComparator = getSectionComparator(o1, o2); @@ -1214,31 +1212,32 @@ public class ShadeListBuilder implements Dumpable, PipelineDumpable { if (cmp != 0) return cmp; } - final NotificationEntry rep1 = o1.getRepresentativeEntry(); - final NotificationEntry rep2 = o2.getRepresentativeEntry(); - cmp = rep1.getRanking().getRank() - rep2.getRanking().getRank(); + cmp = Integer.compare( + o1.getRepresentativeEntry().getRanking().getRank(), + o2.getRepresentativeEntry().getRanking().getRank()); if (cmp != 0) return cmp; - cmp = Long.compare( - rep2.getSbn().getNotification().when, - rep1.getSbn().getNotification().when); + cmp = -1 * Long.compare( + o1.getRepresentativeEntry().getSbn().getNotification().when, + o2.getRepresentativeEntry().getSbn().getNotification().when); return cmp; }; private final Comparator<NotificationEntry> mGroupChildrenComparator = (o1, o2) -> { - int index1 = canReorder(o1) ? -1 : o1.getPreviousAttachState().getStableIndex(); - int index2 = canReorder(o2) ? -1 : o2.getPreviousAttachState().getStableIndex(); - int cmp = Integer.compare(index1, index2); + int cmp = Integer.compare( + getStableOrderIndex(o1), + getStableOrderIndex(o2)); if (cmp != 0) return cmp; - cmp = o1.getRepresentativeEntry().getRanking().getRank() - - o2.getRepresentativeEntry().getRanking().getRank(); + cmp = Integer.compare( + o1.getRepresentativeEntry().getRanking().getRank(), + o2.getRepresentativeEntry().getRanking().getRank()); if (cmp != 0) return cmp; - cmp = Long.compare( - o2.getRepresentativeEntry().getSbn().getNotification().when, - o1.getRepresentativeEntry().getSbn().getNotification().when); + cmp = -1 * Long.compare( + o1.getRepresentativeEntry().getSbn().getNotification().when, + o2.getRepresentativeEntry().getSbn().getNotification().when); return cmp; }; @@ -1248,8 +1247,16 @@ public class ShadeListBuilder implements Dumpable, PipelineDumpable { */ private boolean mForceReorderable = false; - private boolean canReorder(ListEntry entry) { - return mForceReorderable || getStabilityManager().isEntryReorderingAllowed(entry); + private int getStableOrderIndex(ListEntry entry) { + if (mForceReorderable) { + // this is used to determine if the list is correctly sorted + return -1; + } + if (getStabilityManager().isEntryReorderingAllowed(entry)) { + // let the stability manager constrain or allow reordering + return -1; + } + return entry.getPreviousAttachState().getStableIndex(); } private boolean applyFilters(NotificationEntry entry, long now, List<NotifFilter> filters) { diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java index 9ad906c83e10..855390d75ff8 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java @@ -20,7 +20,6 @@ import static android.app.Notification.Action.SEMANTIC_ACTION_MARK_CONVERSATION_ import static android.service.notification.NotificationListenerService.REASON_CANCEL; import static com.android.systemui.statusbar.notification.row.NotificationContentView.VISIBLE_TYPE_HEADSUP; -import static com.android.systemui.statusbar.notification.row.NotificationRowContentBinder.FLAG_CONTENT_VIEW_PUBLIC; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; @@ -236,11 +235,6 @@ public class ExpandableNotificationRow extends ActivatableNotificationView */ private boolean mIsHeadsUp; - /** - * Whether or not the notification should be redacted on the lock screen, i.e has sensitive - * content which should be redacted on the lock screen. - */ - private boolean mNeedsRedaction; private boolean mLastChronometerRunning = true; private ViewStub mChildrenContainerStub; private GroupMembershipManager mGroupMembershipManager; @@ -1502,23 +1496,6 @@ public class ExpandableNotificationRow extends ActivatableNotificationView mUseIncreasedHeadsUpHeight = use; } - /** @deprecated TODO: Remove this when the old pipeline code is removed. */ - @Deprecated - public void setNeedsRedaction(boolean needsRedaction) { - if (mNeedsRedaction != needsRedaction) { - mNeedsRedaction = needsRedaction; - if (!isRemoved()) { - RowContentBindParams params = mRowContentBindStage.getStageParams(mEntry); - if (needsRedaction) { - params.requireContentViews(FLAG_CONTENT_VIEW_PUBLIC); - } else { - params.markContentViewsFreeable(FLAG_CONTENT_VIEW_PUBLIC); - } - mRowContentBindStage.requestRebind(mEntry, null /* callback */); - } - } - } - public interface ExpansionLogger { void logNotificationExpansion(String key, boolean userAction, boolean expanded); } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java index 952bafbe6eb3..79d883b32a98 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java @@ -42,7 +42,6 @@ import android.graphics.Color; import android.graphics.Outline; import android.graphics.Paint; import android.graphics.Path; -import android.graphics.PointF; import android.graphics.Rect; import android.os.Bundle; import android.provider.Settings; @@ -4405,8 +4404,7 @@ public class NotificationStackScrollLayout extends ViewGroup implements Dumpable * See {@link AmbientState#setDozing}. */ @ShadeViewRefactor(RefactorComponent.SHADE_VIEW) - public void setDozing(boolean dozing, boolean animate, - @Nullable PointF touchWakeUpScreenLocation) { + public void setDozing(boolean dozing, boolean animate) { if (mAmbientState.isDozing() == dozing) { return; } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java index 9998fe41b775..3f6586c37b5d 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java @@ -33,7 +33,6 @@ import static com.android.systemui.statusbar.phone.NotificationIconAreaControlle import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Point; -import android.graphics.PointF; import android.os.Trace; import android.os.UserHandle; import android.provider.Settings; @@ -1235,8 +1234,8 @@ public class NotificationStackScrollLayoutController { mView.setAnimationsEnabled(enabled); } - public void setDozing(boolean dozing, boolean animate, PointF wakeUpTouchLocation) { - mView.setDozing(dozing, animate, wakeUpTouchLocation); + public void setDozing(boolean dozing, boolean animate) { + mView.setDozing(dozing, animate); } public void setPulsing(boolean pulsing, boolean animatePulse) { diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java index b0a5adb62339..e444e0a1e2c5 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/CentralSurfacesImpl.java @@ -67,7 +67,6 @@ import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.graphics.Point; -import android.graphics.PointF; import android.hardware.devicestate.DeviceStateManager; import android.metrics.LogMaker; import android.net.Uri; @@ -446,7 +445,6 @@ public class CentralSurfacesImpl extends CoreStartable implements @VisibleForTesting DozeServiceHost mDozeServiceHost; private boolean mWakeUpComingFromTouch; - private PointF mWakeUpTouchLocation; private LightRevealScrim mLightRevealScrim; private PowerButtonReveal mPowerButtonReveal; @@ -603,8 +601,6 @@ public class CentralSurfacesImpl extends CoreStartable implements private int mLastCameraLaunchSource; protected PowerManager.WakeLock mGestureWakeLock; - private final int[] mTmpInt2 = new int[2]; - // Fingerprint (as computed by getLoggingFingerprint() of the last logged state. private int mLastLoggedStateFingerprint; private boolean mIsLaunchingActivityOverLockscreen; @@ -1430,16 +1426,6 @@ public class CentralSurfacesImpl extends CoreStartable implements mPowerManager.wakeUp( time, PowerManager.WAKE_REASON_GESTURE, "com.android.systemui:" + why); mWakeUpComingFromTouch = true; - - // NOTE, the incoming view can sometimes be the entire container... unsure if - // this location is valuable enough - if (where != null) { - where.getLocationInWindow(mTmpInt2); - mWakeUpTouchLocation = new PointF(mTmpInt2[0] + where.getWidth() / 2, - mTmpInt2[1] + where.getHeight() / 2); - } else { - mWakeUpTouchLocation = new PointF(-1, -1); - } mFalsingCollector.onScreenOnFromTouch(); } } @@ -1955,7 +1941,6 @@ public class CentralSurfacesImpl extends CoreStartable implements PowerManager.WAKE_REASON_APPLICATION, "com.android.systemui:full_screen_intent"); mWakeUpComingFromTouch = false; - mWakeUpTouchLocation = null; } } @@ -3225,7 +3210,7 @@ public class CentralSurfacesImpl extends CoreStartable implements || (mDozing && mDozeParameters.shouldControlScreenOff() && visibleNotOccludedOrWillBe); - mNotificationPanelViewController.setDozing(mDozing, animate, mWakeUpTouchLocation); + mNotificationPanelViewController.setDozing(mDozing, animate); updateQsExpansionEnabled(); Trace.endSection(); } @@ -3556,7 +3541,6 @@ public class CentralSurfacesImpl extends CoreStartable implements mLaunchCameraWhenFinishedWaking = false; mDeviceInteractive = false; mWakeUpComingFromTouch = false; - mWakeUpTouchLocation = null; updateVisibleToUser(); updateNotificationPanelTouchState(); @@ -4065,7 +4049,7 @@ public class CentralSurfacesImpl extends CoreStartable implements final PendingIntent intent, @Nullable final Runnable intentSentUiThreadCallback, @Nullable ActivityLaunchAnimator.Controller animationController) { final boolean willLaunchResolverActivity = intent.isActivity() - && mActivityIntentHelper.wouldLaunchResolverActivity(intent.getIntent(), + && mActivityIntentHelper.wouldPendingLaunchResolverActivity(intent, mLockscreenUserManager.getCurrentUserId()); boolean animate = !willLaunchResolverActivity diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/DemoStatusIcons.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/DemoStatusIcons.java index fc8e7d5f6aa2..deb6150f773b 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/DemoStatusIcons.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/DemoStatusIcons.java @@ -225,6 +225,7 @@ public class DemoStatusIcons extends StatusIconContainer implements DemoMode, Da public void addDemoWifiView(WifiIconState state) { Log.d(TAG, "addDemoWifiView: "); + // TODO(b/238425913): Migrate this view to {@code ModernStatusBarWifiView}. StatusBarWifiView view = StatusBarWifiView.fromContext(mContext, state.slot); int viewIndex = getChildCount(); diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarIconController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarIconController.java index 30b640b583e6..ed186ab6a10b 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarIconController.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarIconController.java @@ -40,6 +40,7 @@ import com.android.systemui.demomode.DemoModeCommandReceiver; import com.android.systemui.flags.FeatureFlags; import com.android.systemui.plugins.DarkIconDispatcher; import com.android.systemui.plugins.DarkIconDispatcher.DarkReceiver; +import com.android.systemui.statusbar.BaseStatusBarWifiView; import com.android.systemui.statusbar.StatusBarIconView; import com.android.systemui.statusbar.StatusBarMobileView; import com.android.systemui.statusbar.StatusBarWifiView; @@ -47,12 +48,16 @@ import com.android.systemui.statusbar.StatusIconDisplayable; import com.android.systemui.statusbar.phone.StatusBarSignalPolicy.CallIndicatorIconState; import com.android.systemui.statusbar.phone.StatusBarSignalPolicy.MobileIconState; import com.android.systemui.statusbar.phone.StatusBarSignalPolicy.WifiIconState; +import com.android.systemui.statusbar.pipeline.StatusBarPipelineFlags; +import com.android.systemui.statusbar.pipeline.wifi.ui.view.ModernStatusBarWifiView; +import com.android.systemui.statusbar.pipeline.wifi.ui.viewmodel.WifiViewModel; import com.android.systemui.util.Assert; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; +import javax.inject.Provider; public interface StatusBarIconController { @@ -128,8 +133,12 @@ public interface StatusBarIconController { private final DarkIconDispatcher mDarkIconDispatcher; private int mIconHPadding; - public DarkIconManager(LinearLayout linearLayout, FeatureFlags featureFlags) { - super(linearLayout, featureFlags); + public DarkIconManager( + LinearLayout linearLayout, + FeatureFlags featureFlags, + StatusBarPipelineFlags statusBarPipelineFlags, + Provider<WifiViewModel> wifiViewModelProvider) { + super(linearLayout, featureFlags, statusBarPipelineFlags, wifiViewModelProvider); mIconHPadding = mContext.getResources().getDimensionPixelSize( R.dimen.status_bar_icon_padding); mDarkIconDispatcher = Dependency.get(DarkIconDispatcher.class); @@ -183,14 +192,40 @@ public interface StatusBarIconController { mDarkIconDispatcher.removeDarkReceiver(mDemoStatusIcons); super.exitDemoMode(); } + + @SysUISingleton + public static class Factory { + private final FeatureFlags mFeatureFlags; + private final StatusBarPipelineFlags mStatusBarPipelineFlags; + private final Provider<WifiViewModel> mWifiViewModelProvider; + + @Inject + public Factory( + FeatureFlags featureFlags, + StatusBarPipelineFlags statusBarPipelineFlags, + Provider<WifiViewModel> wifiViewModelProvider) { + mFeatureFlags = featureFlags; + mStatusBarPipelineFlags = statusBarPipelineFlags; + mWifiViewModelProvider = wifiViewModelProvider; + } + + public DarkIconManager create(LinearLayout group) { + return new DarkIconManager( + group, mFeatureFlags, mStatusBarPipelineFlags, mWifiViewModelProvider); + } + } } /** */ class TintedIconManager extends IconManager { private int mColor; - public TintedIconManager(ViewGroup group, FeatureFlags featureFlags) { - super(group, featureFlags); + public TintedIconManager( + ViewGroup group, + FeatureFlags featureFlags, + StatusBarPipelineFlags statusBarPipelineFlags, + Provider<WifiViewModel> wifiViewModelProvider) { + super(group, featureFlags, statusBarPipelineFlags, wifiViewModelProvider); } @Override @@ -223,14 +258,22 @@ public interface StatusBarIconController { @SysUISingleton public static class Factory { private final FeatureFlags mFeatureFlags; + private final StatusBarPipelineFlags mStatusBarPipelineFlags; + private final Provider<WifiViewModel> mWifiViewModelProvider; @Inject - public Factory(FeatureFlags featureFlags) { + public Factory( + FeatureFlags featureFlags, + StatusBarPipelineFlags statusBarPipelineFlags, + Provider<WifiViewModel> wifiViewModelProvider) { mFeatureFlags = featureFlags; + mStatusBarPipelineFlags = statusBarPipelineFlags; + mWifiViewModelProvider = wifiViewModelProvider; } public TintedIconManager create(ViewGroup group) { - return new TintedIconManager(group, mFeatureFlags); + return new TintedIconManager( + group, mFeatureFlags, mStatusBarPipelineFlags, mWifiViewModelProvider); } } } @@ -239,8 +282,10 @@ public interface StatusBarIconController { * Turns info from StatusBarIconController into ImageViews in a ViewGroup. */ class IconManager implements DemoModeCommandReceiver { - private final FeatureFlags mFeatureFlags; protected final ViewGroup mGroup; + private final FeatureFlags mFeatureFlags; + private final StatusBarPipelineFlags mStatusBarPipelineFlags; + private final Provider<WifiViewModel> mWifiViewModelProvider; protected final Context mContext; protected final int mIconSize; // Whether or not these icons show up in dumpsys @@ -254,9 +299,15 @@ public interface StatusBarIconController { protected ArrayList<String> mBlockList = new ArrayList<>(); - public IconManager(ViewGroup group, FeatureFlags featureFlags) { - mFeatureFlags = featureFlags; + public IconManager( + ViewGroup group, + FeatureFlags featureFlags, + StatusBarPipelineFlags statusBarPipelineFlags, + Provider<WifiViewModel> wifiViewModelProvider) { mGroup = group; + mFeatureFlags = featureFlags; + mStatusBarPipelineFlags = statusBarPipelineFlags; + mWifiViewModelProvider = wifiViewModelProvider; mContext = group.getContext(); mIconSize = mContext.getResources().getDimensionPixelSize( com.android.internal.R.dimen.status_bar_icon_size); @@ -308,7 +359,7 @@ public interface StatusBarIconController { return addIcon(index, slot, blocked, holder.getIcon()); case TYPE_WIFI: - return addSignalIcon(index, slot, holder.getWifiState()); + return addWifiIcon(index, slot, holder.getWifiState()); case TYPE_MOBILE: return addMobileIcon(index, slot, holder.getMobileState()); @@ -327,9 +378,17 @@ public interface StatusBarIconController { } @VisibleForTesting - protected StatusBarWifiView addSignalIcon(int index, String slot, WifiIconState state) { - StatusBarWifiView view = onCreateStatusBarWifiView(slot); - view.applyWifiState(state); + protected StatusIconDisplayable addWifiIcon(int index, String slot, WifiIconState state) { + final BaseStatusBarWifiView view; + if (mStatusBarPipelineFlags.isNewPipelineFrontendEnabled()) { + view = onCreateModernStatusBarWifiView(slot); + // When [ModernStatusBarWifiView] is created, it will automatically apply the + // correct view state so we don't need to call applyWifiState. + } else { + StatusBarWifiView wifiView = onCreateStatusBarWifiView(slot); + wifiView.applyWifiState(state); + view = wifiView; + } mGroup.addView(view, index, onCreateLayoutParams()); if (mIsInDemoMode) { @@ -359,6 +418,11 @@ public interface StatusBarIconController { return view; } + private ModernStatusBarWifiView onCreateModernStatusBarWifiView(String slot) { + return ModernStatusBarWifiView.constructAndBind( + mContext, slot, mWifiViewModelProvider.get()); + } + private StatusBarMobileView onCreateStatusBarMobileView(String slot) { StatusBarMobileView view = StatusBarMobileView.fromContext(mContext, slot); return view; @@ -415,9 +479,8 @@ public interface StatusBarIconController { onSetIcon(viewIndex, holder.getIcon()); return; case TYPE_WIFI: - onSetSignalIcon(viewIndex, holder.getWifiState()); + onSetWifiIcon(viewIndex, holder.getWifiState()); return; - case TYPE_MOBILE: onSetMobileIcon(viewIndex, holder.getMobileState()); default: @@ -425,10 +488,16 @@ public interface StatusBarIconController { } } - public void onSetSignalIcon(int viewIndex, WifiIconState state) { - StatusBarWifiView wifiView = (StatusBarWifiView) mGroup.getChildAt(viewIndex); - if (wifiView != null) { - wifiView.applyWifiState(state); + public void onSetWifiIcon(int viewIndex, WifiIconState state) { + View view = mGroup.getChildAt(viewIndex); + if (view instanceof StatusBarWifiView) { + ((StatusBarWifiView) view).applyWifiState(state); + } else if (view instanceof ModernStatusBarWifiView) { + // ModernStatusBarWifiView will automatically apply state based on its callbacks, so + // we don't need to call applyWifiState. + } else { + throw new IllegalStateException("View at " + viewIndex + " must be of type " + + "StatusBarWifiView or ModernStatusBarWifiView"); } if (mIsInDemoMode) { diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java index 374f0916fb33..5cd2ba1b1cf3 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java @@ -223,12 +223,12 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte boolean isActivityIntent = intent != null && intent.isActivity() && !isBubble; final boolean willLaunchResolverActivity = isActivityIntent - && mActivityIntentHelper.wouldLaunchResolverActivity(intent.getIntent(), + && mActivityIntentHelper.wouldPendingLaunchResolverActivity(intent, mLockscreenUserManager.getCurrentUserId()); final boolean animate = !willLaunchResolverActivity && mCentralSurfaces.shouldAnimateLaunch(isActivityIntent); boolean showOverLockscreen = mKeyguardStateController.isShowing() && intent != null - && mActivityIntentHelper.wouldShowOverLockscreen(intent.getIntent(), + && mActivityIntentHelper.wouldPendingShowOverLockscreen(intent, mLockscreenUserManager.getCurrentUserId()); ActivityStarter.OnDismissAction postKeyguardAction = new ActivityStarter.OnDismissAction() { @Override diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallback.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallback.java index 40b9a152057a..70af77e1eb36 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallback.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarRemoteInputCallback.java @@ -259,8 +259,9 @@ public class StatusBarRemoteInputCallback implements Callback, Callbacks, final boolean isActivity = pendingIntent.isActivity(); if (isActivity || appRequestedAuth) { mActionClickLogger.logWaitingToCloseKeyguard(pendingIntent); - final boolean afterKeyguardGone = mActivityIntentHelper.wouldLaunchResolverActivity( - pendingIntent.getIntent(), mLockscreenUserManager.getCurrentUserId()); + final boolean afterKeyguardGone = mActivityIntentHelper + .wouldPendingLaunchResolverActivity(pendingIntent, + mLockscreenUserManager.getCurrentUserId()); mActivityStarter.dismissKeyguardThenExecute(() -> { mActionClickLogger.logKeyguardGone(pendingIntent); diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/dagger/StatusBarViewModule.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/dagger/StatusBarViewModule.java index 200f45f7f8a3..fb5b0960bb86 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/dagger/StatusBarViewModule.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/dagger/StatusBarViewModule.java @@ -286,6 +286,7 @@ public abstract class StatusBarViewModule { PanelExpansionStateManager panelExpansionStateManager, FeatureFlags featureFlags, StatusBarIconController statusBarIconController, + StatusBarIconController.DarkIconManager.Factory darkIconManagerFactory, StatusBarHideIconsForBouncerManager statusBarHideIconsForBouncerManager, KeyguardStateController keyguardStateController, NotificationPanelViewController notificationPanelViewController, @@ -306,6 +307,7 @@ public abstract class StatusBarViewModule { panelExpansionStateManager, featureFlags, statusBarIconController, + darkIconManagerFactory, statusBarHideIconsForBouncerManager, keyguardStateController, notificationPanelViewController, diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragment.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragment.java index f61b488a4fbb..5fd72b7a5247 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragment.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragment.java @@ -124,6 +124,7 @@ public class CollapsedStatusBarFragment extends Fragment implements CommandQueue private final StatusBarIconController mStatusBarIconController; private final CarrierConfigTracker mCarrierConfigTracker; private final StatusBarHideIconsForBouncerManager mStatusBarHideIconsForBouncerManager; + private final StatusBarIconController.DarkIconManager.Factory mDarkIconManagerFactory; private final SecureSettings mSecureSettings; private final Executor mMainExecutor; private final DumpManager mDumpManager; @@ -172,6 +173,7 @@ public class CollapsedStatusBarFragment extends Fragment implements CommandQueue PanelExpansionStateManager panelExpansionStateManager, FeatureFlags featureFlags, StatusBarIconController statusBarIconController, + StatusBarIconController.DarkIconManager.Factory darkIconManagerFactory, StatusBarHideIconsForBouncerManager statusBarHideIconsForBouncerManager, KeyguardStateController keyguardStateController, NotificationPanelViewController notificationPanelViewController, @@ -193,6 +195,7 @@ public class CollapsedStatusBarFragment extends Fragment implements CommandQueue mFeatureFlags = featureFlags; mStatusBarIconController = statusBarIconController; mStatusBarHideIconsForBouncerManager = statusBarHideIconsForBouncerManager; + mDarkIconManagerFactory = darkIconManagerFactory; mKeyguardStateController = keyguardStateController; mNotificationPanelViewController = notificationPanelViewController; mStatusBarStateController = statusBarStateController; @@ -232,7 +235,7 @@ public class CollapsedStatusBarFragment extends Fragment implements CommandQueue mStatusBar.restoreHierarchyState( savedInstanceState.getSparseParcelableArray(EXTRA_PANEL_STATE)); } - mDarkIconManager = new DarkIconManager(view.findViewById(R.id.statusIcons), mFeatureFlags); + mDarkIconManager = mDarkIconManagerFactory.create(view.findViewById(R.id.statusIcons)); mDarkIconManager.setShouldLog(true); updateBlockedIcons(); mStatusBarIconController.addIconGroup(mDarkIconManager); diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/ConnectivityInfoCollector.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/ConnectivityInfoCollector.kt deleted file mode 100644 index 780a02da3410..000000000000 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/ConnectivityInfoCollector.kt +++ /dev/null @@ -1,49 +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.systemui.statusbar.pipeline - -import com.android.systemui.statusbar.pipeline.wifi.data.repository.NetworkCapabilityInfo -import kotlinx.coroutines.flow.StateFlow - -/** - * Interface exposing a flow for raw connectivity information. Clients should collect on - * [rawConnectivityInfoFlow] to get updates on connectivity information. - * - * Note: [rawConnectivityInfoFlow] should be a *hot* flow, so that we only create one instance of it - * and all clients get references to the same flow. - * - * This will be used for the new status bar pipeline to compile information we need to display some - * of the icons in the RHS of the status bar. - */ -interface ConnectivityInfoCollector { - val rawConnectivityInfoFlow: StateFlow<RawConnectivityInfo> -} - -/** - * An object containing all of the raw connectivity information. - * - * Importantly, all the information in this object should not be processed at all (i.e., the data - * that we receive from callbacks should be piped straight into this object and not be filtered, - * manipulated, or processed in any way). Instead, any listeners on - * [ConnectivityInfoCollector.rawConnectivityInfoFlow] can do the processing. - * - * This allows us to keep all the processing in one place which is beneficial for logging and - * debugging purposes. - */ -data class RawConnectivityInfo( - val networkCapabilityInfo: Map<Int, NetworkCapabilityInfo> = emptyMap(), -) diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/ConnectivityInfoCollectorImpl.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/ConnectivityInfoCollectorImpl.kt deleted file mode 100644 index 99798f9b38d3..000000000000 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/ConnectivityInfoCollectorImpl.kt +++ /dev/null @@ -1,46 +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.systemui.statusbar.pipeline - -import com.android.systemui.dagger.SysUISingleton -import com.android.systemui.dagger.qualifiers.Application -import com.android.systemui.statusbar.pipeline.wifi.data.repository.NetworkCapabilitiesRepo -import javax.inject.Inject -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.flow.SharingStarted.Companion.Lazily -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.stateIn - -/** - * The real implementation of [ConnectivityInfoCollector] that will collect information from all the - * relevant connectivity callbacks and compile it into [rawConnectivityInfoFlow]. - */ -@SysUISingleton -class ConnectivityInfoCollectorImpl @Inject constructor( - networkCapabilitiesRepo: NetworkCapabilitiesRepo, - @Application scope: CoroutineScope, -) : ConnectivityInfoCollector { - override val rawConnectivityInfoFlow: StateFlow<RawConnectivityInfo> = - // TODO(b/238425913): Collect all the separate flows for individual raw information into - // this final flow. - networkCapabilitiesRepo.dataStream - .map { - RawConnectivityInfo(networkCapabilityInfo = it) - } - .stateIn(scope, started = Lazily, initialValue = RawConnectivityInfo()) -} diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/ConnectivityInfoProcessor.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/ConnectivityInfoProcessor.kt index 64c47f679142..fe846747d0c6 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/ConnectivityInfoProcessor.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/ConnectivityInfoProcessor.kt @@ -20,31 +20,21 @@ import android.content.Context import com.android.systemui.CoreStartable import com.android.systemui.dagger.SysUISingleton import com.android.systemui.dagger.qualifiers.Application -import com.android.systemui.statusbar.pipeline.wifi.data.repository.NetworkCapabilityInfo import com.android.systemui.statusbar.pipeline.wifi.ui.viewmodel.WifiViewModel import javax.inject.Inject import javax.inject.Provider import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.SharingStarted.Companion.Lazily import kotlinx.coroutines.flow.collect -import kotlinx.coroutines.flow.emptyFlow -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch /** - * A processor that transforms raw connectivity information that we get from callbacks and turns it - * into a list of displayable connectivity information. + * A temporary object that collects on [WifiViewModel] flows for debugging purposes. * - * This will be used for the new status bar pipeline to calculate the list of icons that should be - * displayed in the RHS of the status bar. - * - * Anyone can listen to [processedInfoFlow] to get updates to the processed data. + * This will eventually get migrated to a view binder that will use the flow outputs to set state on + * views. For now, this just collects on flows so that the information gets logged. */ @SysUISingleton class ConnectivityInfoProcessor @Inject constructor( - connectivityInfoCollector: ConnectivityInfoCollector, context: Context, // TODO(b/238425913): Don't use the application scope; instead, use the status bar view's // scope so we only do work when there's UI that cares about it. @@ -52,23 +42,8 @@ class ConnectivityInfoProcessor @Inject constructor( private val statusBarPipelineFlags: StatusBarPipelineFlags, private val wifiViewModelProvider: Provider<WifiViewModel>, ) : CoreStartable(context) { - // Note: This flow will not start running until a client calls `collect` on it, which means that - // [connectivityInfoCollector]'s flow will also not start anything until that `collect` call - // happens. - // TODO(b/238425913): Delete this. - val processedInfoFlow: Flow<ProcessedConnectivityInfo> = - if (!statusBarPipelineFlags.isNewPipelineEnabled()) - emptyFlow() - else connectivityInfoCollector.rawConnectivityInfoFlow - .map { it.process() } - .stateIn( - scope, - started = Lazily, - initialValue = ProcessedConnectivityInfo() - ) - override fun start() { - if (!statusBarPipelineFlags.isNewPipelineEnabled()) { + if (!statusBarPipelineFlags.isNewPipelineBackendEnabled()) { return } // TODO(b/238425913): The view binder should do this instead. For now, do it here so we can @@ -77,17 +52,4 @@ class ConnectivityInfoProcessor @Inject constructor( wifiViewModelProvider.get().isActivityInVisible.collect { } } } - - private fun RawConnectivityInfo.process(): ProcessedConnectivityInfo { - // TODO(b/238425913): Actually process the raw info into meaningful data. - return ProcessedConnectivityInfo(this.networkCapabilityInfo) - } } - -/** - * An object containing connectivity info that has been processed into data that can be directly - * used by the status bar (and potentially other SysUI areas) to display icons. - */ -data class ProcessedConnectivityInfo( - val networkCapabilityInfo: Map<Int, NetworkCapabilityInfo> = emptyMap(), -) diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/StatusBarPipelineFlags.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/StatusBarPipelineFlags.kt index 589cdb8182cb..9b8b6434827e 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/StatusBarPipelineFlags.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/StatusBarPipelineFlags.kt @@ -25,13 +25,28 @@ import javax.inject.Inject @SysUISingleton class StatusBarPipelineFlags @Inject constructor(private val featureFlags: FeatureFlags) { /** - * Returns true if we should run the new pipeline. + * Returns true if we should run the new pipeline backend. * - * TODO(b/238425913): We may want to split this out into: - * (1) isNewPipelineLoggingEnabled(), where the new pipeline runs and logs its decisions but - * doesn't change the UI at all. - * (2) isNewPipelineEnabled(), where the new pipeline runs and does change the UI (and the old - * pipeline doesn't change the UI). + * The new pipeline backend hooks up to all our external callbacks, logs those callback inputs, + * and logs the output state. */ - fun isNewPipelineEnabled(): Boolean = featureFlags.isEnabled(Flags.NEW_STATUS_BAR_PIPELINE) + fun isNewPipelineBackendEnabled(): Boolean = + featureFlags.isEnabled(Flags.NEW_STATUS_BAR_PIPELINE_BACKEND) + + /** + * Returns true if we should run the new pipeline frontend *and* backend. + * + * The new pipeline frontend will use the outputted state from the new backend and will make the + * correct changes to the UI. + */ + fun isNewPipelineFrontendEnabled(): Boolean = + isNewPipelineBackendEnabled() && + featureFlags.isEnabled(Flags.NEW_STATUS_BAR_PIPELINE_FRONTEND) + + /** + * Returns true if we should apply some coloring to icons that were rendered with the new + * pipeline to help with debugging. + */ + // For now, just always apply the debug coloring if we've enabled frontend rendering. + fun useNewPipelineDebugColoring(): Boolean = isNewPipelineFrontendEnabled() } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/dagger/StatusBarPipelineModule.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/dagger/StatusBarPipelineModule.kt index 7abe19e7bbe0..88eccb5ba47f 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/dagger/StatusBarPipelineModule.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/dagger/StatusBarPipelineModule.kt @@ -17,8 +17,6 @@ package com.android.systemui.statusbar.pipeline.dagger import com.android.systemui.CoreStartable -import com.android.systemui.statusbar.pipeline.ConnectivityInfoCollector -import com.android.systemui.statusbar.pipeline.ConnectivityInfoCollectorImpl import com.android.systemui.statusbar.pipeline.ConnectivityInfoProcessor import com.android.systemui.statusbar.pipeline.wifi.data.repository.WifiRepository import com.android.systemui.statusbar.pipeline.wifi.data.repository.WifiRepositoryImpl @@ -36,10 +34,5 @@ abstract class StatusBarPipelineModule { abstract fun bindConnectivityInfoProcessor(cip: ConnectivityInfoProcessor): CoreStartable @Binds - abstract fun provideConnectivityInfoCollector( - impl: ConnectivityInfoCollectorImpl - ): ConnectivityInfoCollector - - @Binds abstract fun wifiRepository(impl: WifiRepositoryImpl): WifiRepository } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/shared/ConnectivityPipelineLogger.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/shared/ConnectivityPipelineLogger.kt index a5fff5e65ebc..2a89309f7200 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/shared/ConnectivityPipelineLogger.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/shared/ConnectivityPipelineLogger.kt @@ -31,6 +31,9 @@ import kotlinx.coroutines.flow.onEach class ConnectivityPipelineLogger @Inject constructor( @StatusBarConnectivityLog private val buffer: LogBuffer, ) { + /** + * Logs a change in one of the **raw inputs** to the connectivity pipeline. + */ fun logInputChange(callbackName: String, changeInfo: String) { buffer.log( SB_LOGGING_TAG, @@ -45,6 +48,41 @@ class ConnectivityPipelineLogger @Inject constructor( ) } + /** + * Logs a **data transformation** that we performed within the connectivity pipeline. + */ + fun logTransformation(transformationName: String, oldValue: Any?, newValue: Any?) { + if (oldValue == newValue) { + buffer.log( + SB_LOGGING_TAG, + LogLevel.INFO, + { + str1 = transformationName + str2 = oldValue.toString() + }, + { + "Transform: $str1: $str2 (transformation didn't change it)" + } + ) + } else { + buffer.log( + SB_LOGGING_TAG, + LogLevel.INFO, + { + str1 = transformationName + str2 = oldValue.toString() + str3 = newValue.toString() + }, + { + "Transform: $str1: $str2 -> $str3" + } + ) + } + } + + /** + * Logs a change in one of the **outputs** to the connectivity pipeline. + */ fun logOutputChange(outputParamName: String, changeInfo: String) { buffer.log( SB_LOGGING_TAG, diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/model/WifiNetworkModel.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/model/WifiNetworkModel.kt new file mode 100644 index 000000000000..5566fa6b5835 --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/model/WifiNetworkModel.kt @@ -0,0 +1,46 @@ +/* + * 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.systemui.statusbar.pipeline.wifi.data.model + +/** Provides information about the current wifi network. */ +sealed class WifiNetworkModel { + /** A model representing that we have no active wifi network. */ + object Inactive : WifiNetworkModel() + + /** Provides information about an active wifi network. */ + class Active( + /** + * The [android.net.Network.netId] we received from + * [android.net.ConnectivityManager.NetworkCallback] in association with this wifi network. + * + * Importantly, **not** [android.net.wifi.WifiInfo.getNetworkId]. + */ + val networkId: Int, + + /** See [android.net.wifi.WifiInfo.ssid]. */ + val ssid: String? = null, + + /** See [android.net.wifi.WifiInfo.isPasspointAp]. */ + val isPasspointAccessPoint: Boolean = false, + + /** See [android.net.wifi.WifiInfo.isOsuAp]. */ + val isOnlineSignUpForPasspointAccessPoint: Boolean = false, + + /** See [android.net.wifi.WifiInfo.passpointProviderFriendlyName]. */ + val passpointProviderFriendlyName: String? = null, + ) : WifiNetworkModel() +} diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/NetworkCapabilitiesRepo.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/NetworkCapabilitiesRepo.kt deleted file mode 100644 index 6c0a44524e3a..000000000000 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/NetworkCapabilitiesRepo.kt +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2021 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. - */ - -@file:OptIn(ExperimentalCoroutinesApi::class) - -package com.android.systemui.statusbar.pipeline.wifi.data.repository - -import android.annotation.SuppressLint -import android.net.ConnectivityManager -import android.net.Network -import android.net.NetworkCapabilities -import android.net.NetworkRequest -import com.android.systemui.dagger.SysUISingleton -import com.android.systemui.dagger.qualifiers.Application -import com.android.systemui.statusbar.pipeline.shared.ConnectivityPipelineLogger -import javax.inject.Inject -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.channels.awaitClose -import kotlinx.coroutines.flow.SharingStarted.Companion.Lazily -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.callbackFlow -import kotlinx.coroutines.flow.stateIn - -/** - * Repository that contains all relevant [NetworkCapabilities] for the current networks. - * - * TODO(b/238425913): Figure out how to merge this with [WifiRepository]. - */ -@SysUISingleton -class NetworkCapabilitiesRepo @Inject constructor( - connectivityManager: ConnectivityManager, - @Application scope: CoroutineScope, - logger: ConnectivityPipelineLogger, -) { - @SuppressLint("MissingPermission") - val dataStream: StateFlow<Map<Int, NetworkCapabilityInfo>> = run { - var state = emptyMap<Int, NetworkCapabilityInfo>() - callbackFlow { - val networkRequest: NetworkRequest = - NetworkRequest.Builder() - .clearCapabilities() - .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) - .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) - .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) - .build() - val callback = - // TODO (b/240569788): log these using [LogBuffer] - object : ConnectivityManager.NetworkCallback(FLAG_INCLUDE_LOCATION_INFO) { - override fun onCapabilitiesChanged( - network: Network, - networkCapabilities: NetworkCapabilities - ) { - logger.logOnCapabilitiesChanged(network, networkCapabilities) - state = - state.toMutableMap().also { - it[network.getNetId()] = - NetworkCapabilityInfo(network, networkCapabilities) - } - trySend(state) - } - - override fun onLost(network: Network) { - logger.logOnLost(network) - state = state.toMutableMap().also { it.remove(network.getNetId()) } - trySend(state) - } - } - connectivityManager.registerNetworkCallback(networkRequest, callback) - - awaitClose { connectivityManager.unregisterNetworkCallback(callback) } - } - .stateIn(scope, started = Lazily, initialValue = state) - } -} - -/** contains info about network capabilities. */ -data class NetworkCapabilityInfo( - val network: Network, - val capabilities: NetworkCapabilities, -) diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepository.kt index 012dde5fb8f2..43fbabca823f 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepository.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepository.kt @@ -16,16 +16,26 @@ package com.android.systemui.statusbar.pipeline.wifi.data.repository +import android.annotation.SuppressLint +import android.net.ConnectivityManager +import android.net.Network +import android.net.NetworkCapabilities +import android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN +import android.net.NetworkCapabilities.TRANSPORT_CELLULAR +import android.net.NetworkCapabilities.TRANSPORT_WIFI +import android.net.NetworkRequest +import android.net.wifi.WifiInfo import android.net.wifi.WifiManager import android.net.wifi.WifiManager.TrafficStateCallback import android.util.Log +import com.android.settingslib.Utils import com.android.systemui.common.coroutine.ConflatedCallbackFlow.conflatedCallbackFlow import com.android.systemui.dagger.SysUISingleton import com.android.systemui.dagger.qualifiers.Main import com.android.systemui.statusbar.pipeline.shared.ConnectivityPipelineLogger import com.android.systemui.statusbar.pipeline.shared.ConnectivityPipelineLogger.Companion.SB_LOGGING_TAG import com.android.systemui.statusbar.pipeline.wifi.data.model.WifiActivityModel -import com.android.systemui.statusbar.pipeline.wifi.data.model.WifiModel +import com.android.systemui.statusbar.pipeline.wifi.data.model.WifiNetworkModel import java.util.concurrent.Executor import javax.inject.Inject import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -38,9 +48,9 @@ import kotlinx.coroutines.flow.flowOf */ interface WifiRepository { /** - * Observable for the current state of wifi; `null` when there is no active wifi. + * Observable for the current wifi network. */ - val wifiModel: Flow<WifiModel?> + val wifiNetwork: Flow<WifiNetworkModel> /** * Observable for the current wifi network activity. @@ -51,14 +61,57 @@ interface WifiRepository { /** Real implementation of [WifiRepository]. */ @OptIn(ExperimentalCoroutinesApi::class) @SysUISingleton +@SuppressLint("MissingPermission") class WifiRepositoryImpl @Inject constructor( + connectivityManager: ConnectivityManager, wifiManager: WifiManager?, @Main mainExecutor: Executor, logger: ConnectivityPipelineLogger, ) : WifiRepository { + override val wifiNetwork: Flow<WifiNetworkModel> = conflatedCallbackFlow { + var currentWifi: WifiNetworkModel = WIFI_NETWORK_DEFAULT - // TODO(b/238425913): Actually implement the wifiModel flow. - override val wifiModel: Flow<WifiModel?> = flowOf(WifiModel(ssid = "AB")) + val callback = object : ConnectivityManager.NetworkCallback(FLAG_INCLUDE_LOCATION_INFO) { + override fun onCapabilitiesChanged( + network: Network, + networkCapabilities: NetworkCapabilities + ) { + logger.logOnCapabilitiesChanged(network, networkCapabilities) + + val wifiInfo = networkCapabilitiesToWifiInfo(networkCapabilities) + if (wifiInfo?.isPrimary == true) { + val wifiNetworkModel = wifiInfoToModel(wifiInfo, network.getNetId()) + logger.logTransformation( + WIFI_NETWORK_CALLBACK_NAME, + oldValue = currentWifi, + newValue = wifiNetworkModel + ) + currentWifi = wifiNetworkModel + trySend(wifiNetworkModel) + } + } + + override fun onLost(network: Network) { + logger.logOnLost(network) + val wifi = currentWifi + if (wifi is WifiNetworkModel.Active && wifi.networkId == network.getNetId()) { + val newNetworkModel = WifiNetworkModel.Inactive + logger.logTransformation( + WIFI_NETWORK_CALLBACK_NAME, + oldValue = wifi, + newValue = newNetworkModel + ) + currentWifi = newNetworkModel + trySend(newNetworkModel) + } + } + } + + trySend(WIFI_NETWORK_DEFAULT) + connectivityManager.registerNetworkCallback(WIFI_NETWORK_CALLBACK_REQUEST, callback) + + awaitClose { connectivityManager.unregisterNetworkCallback(callback) } + } override val wifiActivity: Flow<WifiActivityModel> = if (wifiManager == null) { @@ -71,8 +124,8 @@ class WifiRepositoryImpl @Inject constructor( trySend(trafficStateToWifiActivityModel(state)) } - wifiManager.registerTrafficStateCallback(mainExecutor, callback) trySend(ACTIVITY_DEFAULT) + wifiManager.registerTrafficStateCallback(mainExecutor, callback) awaitClose { wifiManager.unregisterTrafficStateCallback(callback) } } @@ -80,6 +133,13 @@ class WifiRepositoryImpl @Inject constructor( companion object { val ACTIVITY_DEFAULT = WifiActivityModel(hasActivityIn = false, hasActivityOut = false) + // Start out with no known wifi network. + // Note: [WifiStatusTracker] (the old implementation of connectivity logic) does do an + // initial fetch to get a starting wifi network. But, it uses a deprecated API + // [WifiManager.getConnectionInfo()], and the deprecation doc indicates to just use + // [ConnectivityManager.NetworkCallback] results instead. So, for now we'll just rely on the + // NetworkCallback inside [wifiNetwork] for our wifi network information. + val WIFI_NETWORK_DEFAULT = WifiNetworkModel.Inactive private fun trafficStateToWifiActivityModel(state: Int): WifiActivityModel { return WifiActivityModel( @@ -90,6 +150,30 @@ class WifiRepositoryImpl @Inject constructor( ) } + private fun networkCapabilitiesToWifiInfo( + networkCapabilities: NetworkCapabilities + ): WifiInfo? { + return when { + networkCapabilities.hasTransport(TRANSPORT_WIFI) -> + networkCapabilities.transportInfo as WifiInfo? + networkCapabilities.hasTransport(TRANSPORT_CELLULAR) -> + // Sometimes, cellular networks can act as wifi networks (known as VCN -- + // virtual carrier network). So, see if this cellular network has wifi info. + Utils.tryGetWifiInfoForVcn(networkCapabilities) + else -> null + } + } + + private fun wifiInfoToModel(wifiInfo: WifiInfo, networkId: Int): WifiNetworkModel { + return WifiNetworkModel.Active( + networkId, + wifiInfo.ssid, + wifiInfo.isPasspointAp, + wifiInfo.isOsuAp, + wifiInfo.passpointProviderFriendlyName + ) + } + private fun prettyPrintActivity(activity: Int): String { return when (activity) { TrafficStateCallback.DATA_ACTIVITY_NONE -> "NONE" @@ -99,5 +183,15 @@ class WifiRepositoryImpl @Inject constructor( else -> "INVALID" } } + + private val WIFI_NETWORK_CALLBACK_REQUEST: NetworkRequest = + NetworkRequest.Builder() + .clearCapabilities() + .addCapability(NET_CAPABILITY_NOT_VPN) + .addTransportType(TRANSPORT_WIFI) + .addTransportType(TRANSPORT_CELLULAR) + .build() + + private const val WIFI_NETWORK_CALLBACK_NAME = "wifiNetworkModel" } } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/domain/interactor/WifiInteractor.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/domain/interactor/WifiInteractor.kt index f705399af85d..a9da63b43aa4 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/domain/interactor/WifiInteractor.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/domain/interactor/WifiInteractor.kt @@ -18,6 +18,7 @@ package com.android.systemui.statusbar.pipeline.wifi.domain.interactor import android.net.wifi.WifiManager import com.android.systemui.dagger.SysUISingleton +import com.android.systemui.statusbar.pipeline.wifi.data.model.WifiNetworkModel import com.android.systemui.statusbar.pipeline.wifi.data.repository.WifiRepository import javax.inject.Inject import kotlinx.coroutines.flow.Flow @@ -34,13 +35,15 @@ import kotlinx.coroutines.flow.map class WifiInteractor @Inject constructor( repository: WifiRepository, ) { - private val ssid: Flow<String?> = repository.wifiModel.map { info -> - when { - info == null -> null - info.isPasspointAccessPoint || info.isOnlineSignUpForPasspointAccessPoint -> - info.passpointProviderFriendlyName - info.ssid != WifiManager.UNKNOWN_SSID -> info.ssid - else -> null + private val ssid: Flow<String?> = repository.wifiNetwork.map { info -> + when (info) { + is WifiNetworkModel.Inactive -> null + is WifiNetworkModel.Active -> when { + info.isPasspointAccessPoint || info.isOnlineSignUpForPasspointAccessPoint -> + info.passpointProviderFriendlyName + info.ssid != WifiManager.UNKNOWN_SSID -> info.ssid + else -> null + } } } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/ui/binder/WifiViewBinder.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/ui/binder/WifiViewBinder.kt new file mode 100644 index 000000000000..b06aaf441f5a --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/ui/binder/WifiViewBinder.kt @@ -0,0 +1,67 @@ +/* + * 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.systemui.statusbar.pipeline.wifi.ui.binder + +import android.content.res.ColorStateList +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import androidx.core.view.isVisible +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.repeatOnLifecycle +import com.android.systemui.R +import com.android.systemui.lifecycle.repeatWhenAttached +import com.android.systemui.statusbar.connectivity.WifiIcons.WIFI_FULL_ICONS +import com.android.systemui.statusbar.pipeline.wifi.ui.viewmodel.WifiViewModel +import kotlinx.coroutines.InternalCoroutinesApi +import kotlinx.coroutines.flow.collect +import kotlinx.coroutines.launch + +/** + * Binds a wifi icon in the status bar to its view-model. + * + * To use this properly, users should maintain a one-to-one relationship between the [View] and the + * view-binding, binding each view only once. It is okay and expected for the same instance of the + * view-model to be reused for multiple view/view-binder bindings. + */ +@OptIn(InternalCoroutinesApi::class) +object WifiViewBinder { + /** Binds the view to the view-model, continuing to update the former based on the latter. */ + @JvmStatic + fun bind( + view: ViewGroup, + viewModel: WifiViewModel, + ) { + val iconView = view.requireViewById<ImageView>(R.id.wifi_signal) + + view.isVisible = true + iconView.isVisible = true + iconView.setImageDrawable(view.context.getDrawable(WIFI_FULL_ICONS[2])) + + view.repeatWhenAttached { + repeatOnLifecycle(Lifecycle.State.STARTED) { + launch { + viewModel.tint.collect { tint -> + iconView.imageTintList = ColorStateList.valueOf(tint) + } + } + } + } + + // TODO(b/238425913): Hook up to [viewModel] to render actual changes to the wifi icon. + } +} diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/ui/view/ModernStatusBarWifiView.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/ui/view/ModernStatusBarWifiView.kt new file mode 100644 index 000000000000..c14a897fffab --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/ui/view/ModernStatusBarWifiView.kt @@ -0,0 +1,93 @@ +/* + * 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.systemui.statusbar.pipeline.wifi.ui.view + +import android.content.Context +import android.graphics.Rect +import android.util.AttributeSet +import android.view.LayoutInflater +import com.android.systemui.R +import com.android.systemui.statusbar.BaseStatusBarWifiView +import com.android.systemui.statusbar.StatusBarIconView.STATE_ICON +import com.android.systemui.statusbar.pipeline.wifi.ui.binder.WifiViewBinder +import com.android.systemui.statusbar.pipeline.wifi.ui.viewmodel.WifiViewModel + +/** + * A new and more modern implementation of [com.android.systemui.statusbar.StatusBarWifiView] that + * is updated by [WifiViewBinder]. + */ +class ModernStatusBarWifiView( + context: Context, + attrs: AttributeSet? +) : BaseStatusBarWifiView(context, attrs) { + + private lateinit var slot: String + + override fun onDarkChanged(areas: ArrayList<Rect>?, darkIntensity: Float, tint: Int) { + // TODO(b/238425913) + } + + override fun getSlot() = slot + + override fun setStaticDrawableColor(color: Int) { + // TODO(b/238425913) + } + + override fun setDecorColor(color: Int) { + // TODO(b/238425913) + } + + override fun setVisibleState(state: Int, animate: Boolean) { + // TODO(b/238425913) + } + + override fun getVisibleState(): Int { + // TODO(b/238425913) + return STATE_ICON + } + + override fun isIconVisible(): Boolean { + // TODO(b/238425913) + return true + } + + /** Set the slot name for this view. */ + private fun setSlot(slotName: String) { + this.slot = slotName + } + + companion object { + /** + * Inflates a new instance of [ModernStatusBarWifiView], binds it to [viewModel], and + * returns it. + */ + @JvmStatic + fun constructAndBind( + context: Context, + slot: String, + viewModel: WifiViewModel, + ): ModernStatusBarWifiView { + return ( + LayoutInflater.from(context).inflate(R.layout.new_status_bar_wifi_group, null) + as ModernStatusBarWifiView + ).also { + it.setSlot(slot) + WifiViewBinder.bind(it, viewModel) + } + } + } +} diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/ui/viewmodel/WifiViewModel.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/ui/viewmodel/WifiViewModel.kt index b990eb7d9173..7a262605681d 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/ui/viewmodel/WifiViewModel.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/wifi/ui/viewmodel/WifiViewModel.kt @@ -16,12 +16,15 @@ package com.android.systemui.statusbar.pipeline.wifi.ui.viewmodel +import android.graphics.Color +import com.android.systemui.statusbar.pipeline.StatusBarPipelineFlags import com.android.systemui.statusbar.pipeline.shared.ConnectivityPipelineLogger import com.android.systemui.statusbar.pipeline.shared.ConnectivityPipelineLogger.Companion.logOutputChange import com.android.systemui.statusbar.pipeline.wifi.domain.interactor.WifiInteractor import com.android.systemui.statusbar.pipeline.wifi.shared.WifiConstants import javax.inject.Inject import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flowOf /** @@ -30,9 +33,10 @@ import kotlinx.coroutines.flow.flowOf * TODO(b/238425913): Hook this up to the real status bar wifi view using a view binder. */ class WifiViewModel @Inject constructor( - private val constants: WifiConstants, - private val logger: ConnectivityPipelineLogger, - private val interactor: WifiInteractor, + statusBarPipelineFlags: StatusBarPipelineFlags, + private val constants: WifiConstants, + private val logger: ConnectivityPipelineLogger, + private val interactor: WifiInteractor, ) { val isActivityInVisible: Flow<Boolean> get() = @@ -42,4 +46,11 @@ class WifiViewModel @Inject constructor( interactor.hasActivityIn } .logOutputChange(logger, "activityInVisible") + + /** The tint that should be applied to the icon. */ + val tint: Flow<Int> = if (!statusBarPipelineFlags.useNewPipelineDebugColoring()) { + emptyFlow() + } else { + flowOf(Color.CYAN) + } } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java index dfcdaefd8e03..836d57131fac 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java @@ -45,7 +45,6 @@ import android.os.UserManager; import android.provider.Settings; import android.telephony.TelephonyCallback; import android.text.TextUtils; -import android.util.FeatureFlagUtils; import android.util.Log; import android.util.SparseArray; import android.util.SparseBooleanArray; @@ -287,10 +286,6 @@ public class UserSwitcherController implements Dumpable { refreshUsers(UserHandle.USER_NULL); } - private static boolean isEnableGuestModeUxChanges(Context context) { - return FeatureFlagUtils.isEnabled(context, FeatureFlagUtils.SETTINGS_GUEST_MODE_UX_CHANGES); - } - /** * Refreshes users from UserManager. * @@ -549,17 +544,9 @@ public class UserSwitcherController implements Dumpable { } if (currUserInfo != null && currUserInfo.isGuest()) { - if (isEnableGuestModeUxChanges(mContext)) { - showExitGuestDialog(currUserId, currUserInfo.isEphemeral(), - record.resolveId(), dialogShower); - return; - } else { - if (currUserInfo.isEphemeral()) { - showExitGuestDialog(currUserId, currUserInfo.isEphemeral(), - record.resolveId(), dialogShower); - return; - } - } + showExitGuestDialog(currUserId, currUserInfo.isEphemeral(), + record.resolveId(), dialogShower); + return; } if (dialogShower != null) { @@ -1056,14 +1043,8 @@ public class UserSwitcherController implements Dumpable { public String getName(Context context, UserRecord item) { if (item.isGuest) { if (item.isCurrent) { - if (isEnableGuestModeUxChanges(context)) { - return context.getString( - com.android.settingslib.R.string.guest_exit_quick_settings_button); - } else { - return context.getString(mController.mGuestUserAutoCreated - ? com.android.settingslib.R.string.guest_reset_guest - : com.android.settingslib.R.string.guest_exit_guest); - } + return context.getString( + com.android.settingslib.R.string.guest_exit_quick_settings_button); } else { if (item.info != null) { return context.getString(com.android.internal.R.string.guest_name); @@ -1080,13 +1061,8 @@ public class UserSwitcherController implements Dumpable { ? com.android.settingslib.R.string.guest_resetting : com.android.internal.R.string.guest_name); } else { - if (isEnableGuestModeUxChanges(context)) { - // we always show "guest" as string, instead of "add guest" - return context.getString(com.android.internal.R.string.guest_name); - } else { - return context.getString( - com.android.settingslib.R.string.guest_new_guest); - } + // we always show "guest" as string, instead of "add guest" + return context.getString(com.android.internal.R.string.guest_name); } } } @@ -1108,11 +1084,7 @@ public class UserSwitcherController implements Dumpable { protected static Drawable getIconDrawable(Context context, UserRecord item) { int iconRes; if (item.isAddUser) { - if (isEnableGuestModeUxChanges(context)) { - iconRes = R.drawable.ic_add; - } else { - iconRes = R.drawable.ic_account_circle_filled; - } + iconRes = R.drawable.ic_add; } else if (item.isGuest) { iconRes = R.drawable.ic_account_circle; } else if (item.isAddSupervisedUser) { @@ -1289,46 +1261,32 @@ public class UserSwitcherController implements Dumpable { ExitGuestDialog(Context context, int guestId, boolean isGuestEphemeral, int targetId) { super(context); - if (isEnableGuestModeUxChanges(context)) { - if (isGuestEphemeral) { - setTitle(context.getString( - com.android.settingslib.R.string.guest_exit_dialog_title)); - setMessage(context.getString( - com.android.settingslib.R.string.guest_exit_dialog_message)); - setButton(DialogInterface.BUTTON_NEUTRAL, - context.getString(android.R.string.cancel), this); - setButton(DialogInterface.BUTTON_POSITIVE, - context.getString( - com.android.settingslib.R.string.guest_exit_dialog_button), this); - } else { - setTitle(context.getString( - com.android.settingslib - .R.string.guest_exit_dialog_title_non_ephemeral)); - setMessage(context.getString( - com.android.settingslib - .R.string.guest_exit_dialog_message_non_ephemeral)); - setButton(DialogInterface.BUTTON_NEUTRAL, - context.getString(android.R.string.cancel), this); - setButton(DialogInterface.BUTTON_NEGATIVE, - context.getString( - com.android.settingslib.R.string.guest_exit_clear_data_button), - this); - setButton(DialogInterface.BUTTON_POSITIVE, - context.getString( - com.android.settingslib.R.string.guest_exit_save_data_button), - this); - } + if (isGuestEphemeral) { + setTitle(context.getString( + com.android.settingslib.R.string.guest_exit_dialog_title)); + setMessage(context.getString( + com.android.settingslib.R.string.guest_exit_dialog_message)); + setButton(DialogInterface.BUTTON_NEUTRAL, + context.getString(android.R.string.cancel), this); + setButton(DialogInterface.BUTTON_POSITIVE, + context.getString( + com.android.settingslib.R.string.guest_exit_dialog_button), this); } else { - setTitle(mGuestUserAutoCreated - ? com.android.settingslib.R.string.guest_reset_guest_dialog_title - : com.android.settingslib.R.string.guest_remove_guest_dialog_title); - setMessage(context.getString(R.string.guest_exit_guest_dialog_message)); + setTitle(context.getString( + com.android.settingslib + .R.string.guest_exit_dialog_title_non_ephemeral)); + setMessage(context.getString( + com.android.settingslib + .R.string.guest_exit_dialog_message_non_ephemeral)); setButton(DialogInterface.BUTTON_NEUTRAL, context.getString(android.R.string.cancel), this); + setButton(DialogInterface.BUTTON_NEGATIVE, + context.getString( + com.android.settingslib.R.string.guest_exit_clear_data_button), + this); setButton(DialogInterface.BUTTON_POSITIVE, - context.getString(mGuestUserAutoCreated - ? com.android.settingslib.R.string.guest_reset_guest_confirm_button - : com.android.settingslib.R.string.guest_remove_guest_confirm_button), + context.getString( + com.android.settingslib.R.string.guest_exit_save_data_button), this); } SystemUIDialog.setWindowOnTop(this, mKeyguardStateController.isShowing()); @@ -1345,39 +1303,29 @@ public class UserSwitcherController implements Dumpable { if (mFalsingManager.isFalseTap(penalty)) { return; } - if (isEnableGuestModeUxChanges(getContext())) { - if (mIsGuestEphemeral) { - if (which == DialogInterface.BUTTON_POSITIVE) { - mDialogLaunchAnimator.dismissStack(this); - // Ephemeral guest: exit guest, guest is removed by the system - // on exit, since its marked ephemeral - exitGuestUser(mGuestId, mTargetId, false); - } else if (which == DialogInterface.BUTTON_NEGATIVE) { - // Cancel clicked, do nothing - cancel(); - } - } else { - if (which == DialogInterface.BUTTON_POSITIVE) { - mDialogLaunchAnimator.dismissStack(this); - // Non-ephemeral guest: exit guest, guest is not removed by the system - // on exit, since its marked non-ephemeral - exitGuestUser(mGuestId, mTargetId, false); - } else if (which == DialogInterface.BUTTON_NEGATIVE) { - mDialogLaunchAnimator.dismissStack(this); - // Non-ephemeral guest: remove guest and then exit - exitGuestUser(mGuestId, mTargetId, true); - } else if (which == DialogInterface.BUTTON_NEUTRAL) { - // Cancel clicked, do nothing - cancel(); - } + if (mIsGuestEphemeral) { + if (which == DialogInterface.BUTTON_POSITIVE) { + mDialogLaunchAnimator.dismissStack(this); + // Ephemeral guest: exit guest, guest is removed by the system + // on exit, since its marked ephemeral + exitGuestUser(mGuestId, mTargetId, false); + } else if (which == DialogInterface.BUTTON_NEGATIVE) { + // Cancel clicked, do nothing + cancel(); } } else { - if (which == BUTTON_NEUTRAL) { - cancel(); - } else { - mUiEventLogger.log(QSUserSwitcherEvent.QS_USER_GUEST_REMOVE); + if (which == DialogInterface.BUTTON_POSITIVE) { + mDialogLaunchAnimator.dismissStack(this); + // Non-ephemeral guest: exit guest, guest is not removed by the system + // on exit, since its marked non-ephemeral + exitGuestUser(mGuestId, mTargetId, false); + } else if (which == DialogInterface.BUTTON_NEGATIVE) { mDialogLaunchAnimator.dismissStack(this); - removeGuestUser(mGuestId, mTargetId); + // Non-ephemeral guest: remove guest and then exit + exitGuestUser(mGuestId, mTargetId, true); + } else if (which == DialogInterface.BUTTON_NEUTRAL) { + // Cancel clicked, do nothing + cancel(); } } } diff --git a/packages/SystemUI/src/com/android/systemui/util/SysuiLifecycle.java b/packages/SystemUI/src/com/android/systemui/util/SysuiLifecycle.java deleted file mode 100644 index d73175310802..000000000000 --- a/packages/SystemUI/src/com/android/systemui/util/SysuiLifecycle.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2018 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.systemui.util; - -import static androidx.lifecycle.Lifecycle.State.DESTROYED; -import static androidx.lifecycle.Lifecycle.State.RESUMED; - -import android.view.View; -import android.view.View.OnAttachStateChangeListener; - -import androidx.annotation.NonNull; -import androidx.lifecycle.Lifecycle; -import androidx.lifecycle.LifecycleOwner; -import androidx.lifecycle.LifecycleRegistry; - -/** - * Tools for generating lifecycle from sysui objects. - */ -public class SysuiLifecycle { - - private SysuiLifecycle() { - } - - /** - * Get a lifecycle that will be put into the resumed state when the view is attached - * and goes to the destroyed state when the view is detached. - */ - public static LifecycleOwner viewAttachLifecycle(View v) { - return new ViewLifecycle(v); - } - - private static class ViewLifecycle implements LifecycleOwner, OnAttachStateChangeListener { - private final LifecycleRegistry mLifecycle = new LifecycleRegistry(this); - - ViewLifecycle(View v) { - v.addOnAttachStateChangeListener(this); - if (v.isAttachedToWindow()) { - mLifecycle.markState(RESUMED); - } - } - - @NonNull - @Override - public Lifecycle getLifecycle() { - return mLifecycle; - } - - @Override - public void onViewAttachedToWindow(View v) { - mLifecycle.markState(RESUMED); - } - - @Override - public void onViewDetachedFromWindow(View v) { - mLifecycle.markState(DESTROYED); - } - } -} diff --git a/packages/SystemUI/src/com/android/systemui/util/kotlin/IpcSerializer.kt b/packages/SystemUI/src/com/android/systemui/util/kotlin/IpcSerializer.kt new file mode 100644 index 000000000000..c0331e6000bf --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/util/kotlin/IpcSerializer.kt @@ -0,0 +1,98 @@ +/* + * 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.systemui.util.kotlin + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Job +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.runBlocking + +/** + * A utility for handling incoming IPCs from a Binder interface in the order that they are received. + * + * This class serves as a replacement for the common [android.os.Handler] message-queue pattern, + * where IPCs can arrive on arbitrary threads and are all enqueued onto a queue and processed by the + * Handler in-order. + * + * class MyService : Service() { + * + * private val serializer = IpcSerializer() + * + * // Need to invoke process() in order to actually process IPCs sent over the serializer. + * override fun onStart(...) = lifecycleScope.launch { + * serializer.process() + * } + * + * // In your binder implementation, use runSerializedBlocking to enqueue a function onto + * // the serializer. + * override fun onBind(intent: Intent?) = object : IAidlService.Stub() { + * override fun ipcMethodFoo() = serializer.runSerializedBlocking { + * ... + * } + * + * override fun ipcMethodBar() = serializer.runSerializedBlocking { + * ... + * } + * } + * } + */ +class IpcSerializer { + + private val channel = Channel<Pair<CompletableDeferred<Unit>, Job>>() + + /** + * Runs functions enqueued via usage of [runSerialized] and [runSerializedBlocking] serially. + * This method will never complete normally, so it must be launched in its own coroutine; if + * this is not actively running, no enqueued functions will be evaluated. + */ + suspend fun process(): Nothing { + for ((start, finish) in channel) { + // Signal to the sender that serializer has reached this message + start.complete(Unit) + // Wait to hear from the sender that it has finished running it's work, before handling + // the next message + finish.join() + } + error("Unexpected end of serialization channel") + } + + /** + * Enqueues [block] for evaluation by the serializer, suspending the caller until it has + * completed. It is up to the caller to define what thread this is evaluated in, determined + * by the [kotlin.coroutines.CoroutineContext] used. + */ + suspend fun <R> runSerialized(block: suspend () -> R): R { + val start = CompletableDeferred(Unit) + val finish = CompletableDeferred(Unit) + // Enqueue our message on the channel. + channel.send(start to finish) + // Wait for the serializer to reach our message + start.await() + // Now evaluate the block + val result = block() + // Notify the serializer that we've completed evaluation + finish.complete(Unit) + return result + } + + /** + * Enqueues [block] for evaluation by the serializer, blocking the binder thread until it has + * completed. Evaluation occurs on the binder thread, so methods like + * [android.os.Binder.getCallingUid] that depend on the current thread will work as expected. + */ + fun <R> runSerializedBlocking(block: suspend () -> R): R = runBlocking { runSerialized(block) } +} diff --git a/packages/SystemUI/src/com/android/systemui/wmshell/BubblesManager.java b/packages/SystemUI/src/com/android/systemui/wmshell/BubblesManager.java index aeab2dff9421..199048ec7b2e 100644 --- a/packages/SystemUI/src/com/android/systemui/wmshell/BubblesManager.java +++ b/packages/SystemUI/src/com/android/systemui/wmshell/BubblesManager.java @@ -50,9 +50,7 @@ import androidx.annotation.Nullable; import com.android.internal.annotations.VisibleForTesting; import com.android.internal.statusbar.IStatusBarService; -import com.android.systemui.Dumpable; import com.android.systemui.dagger.SysUISingleton; -import com.android.systemui.dump.DumpManager; import com.android.systemui.model.SysUiState; import com.android.systemui.shade.ShadeController; import com.android.systemui.shared.system.QuickStepContract; @@ -77,7 +75,6 @@ import com.android.wm.shell.bubbles.Bubble; import com.android.wm.shell.bubbles.BubbleEntry; import com.android.wm.shell.bubbles.Bubbles; -import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -92,7 +89,7 @@ import java.util.function.IntConsumer; * The SysUi side bubbles manager which communicate with other SysUi components. */ @SysUISingleton -public class BubblesManager implements Dumpable { +public class BubblesManager { private static final String TAG = TAG_WITH_CLASS_NAME ? "BubblesManager" : TAG_BUBBLES; @@ -137,7 +134,6 @@ public class BubblesManager implements Dumpable { CommonNotifCollection notifCollection, NotifPipeline notifPipeline, SysUiState sysUiState, - DumpManager dumpManager, Executor sysuiMainExecutor) { if (bubblesOptional.isPresent()) { return new BubblesManager(context, @@ -156,7 +152,6 @@ public class BubblesManager implements Dumpable { notifCollection, notifPipeline, sysUiState, - dumpManager, sysuiMainExecutor); } else { return null; @@ -180,7 +175,6 @@ public class BubblesManager implements Dumpable { CommonNotifCollection notifCollection, NotifPipeline notifPipeline, SysUiState sysUiState, - DumpManager dumpManager, Executor sysuiMainExecutor) { mContext = context; mBubbles = bubbles; @@ -203,8 +197,6 @@ public class BubblesManager implements Dumpable { setupNotifPipeline(); - dumpManager.registerDumpable(TAG, this); - keyguardStateController.addCallback(new KeyguardStateController.Callback() { @Override public void onKeyguardShowingChanged() { @@ -648,11 +640,6 @@ public class BubblesManager implements Dumpable { } } - @Override - public void dump(@NonNull PrintWriter pw, @NonNull String[] args) { - mBubbles.dump(pw, args); - } - /** Checks whether bubbles are enabled for this user, handles negative userIds. */ public static boolean areBubblesEnabled(@NonNull Context context, @NonNull UserHandle user) { if (user.getIdentifier() < 0) { diff --git a/packages/SystemUI/src/com/android/systemui/wmshell/WMShell.java b/packages/SystemUI/src/com/android/systemui/wmshell/WMShell.java index eba279587629..a4a59fc9d4a7 100644 --- a/packages/SystemUI/src/com/android/systemui/wmshell/WMShell.java +++ b/packages/SystemUI/src/com/android/systemui/wmshell/WMShell.java @@ -29,14 +29,16 @@ import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_S import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING_OCCLUDED; import android.content.Context; +import android.content.pm.UserInfo; import android.content.res.Configuration; import android.graphics.Rect; -import android.graphics.drawable.Drawable; import android.inputmethodservice.InputMethodService; import android.os.IBinder; import android.os.ParcelFileDescriptor; import android.view.KeyEvent; +import androidx.annotation.NonNull; + import com.android.internal.annotations.VisibleForTesting; import com.android.keyguard.KeyguardUpdateMonitor; import com.android.keyguard.KeyguardUpdateMonitorCallback; @@ -47,11 +49,11 @@ import com.android.systemui.dagger.qualifiers.Main; import com.android.systemui.keyguard.ScreenLifecycle; import com.android.systemui.keyguard.WakefulnessLifecycle; import com.android.systemui.model.SysUiState; +import com.android.systemui.settings.UserTracker; import com.android.systemui.shared.tracing.ProtoTraceable; import com.android.systemui.statusbar.CommandQueue; import com.android.systemui.statusbar.policy.ConfigurationController; import com.android.systemui.statusbar.policy.KeyguardStateController; -import com.android.systemui.statusbar.policy.UserInfoController; import com.android.systemui.tracing.ProtoTracer; import com.android.systemui.tracing.nano.SystemUiTraceProto; import com.android.wm.shell.nano.WmShellTraceProto; @@ -66,6 +68,7 @@ import com.android.wm.shell.sysui.ShellInterface; import java.io.PrintWriter; import java.util.Arrays; +import java.util.List; import java.util.Optional; import java.util.concurrent.Executor; @@ -115,7 +118,7 @@ public final class WMShell extends CoreStartable private final SysUiState mSysUiState; private final WakefulnessLifecycle mWakefulnessLifecycle; private final ProtoTracer mProtoTracer; - private final UserInfoController mUserInfoController; + private final UserTracker mUserTracker; private final Executor mSysUiMainExecutor; // Listeners and callbacks. Note that we prefer member variable over anonymous class here to @@ -144,9 +147,20 @@ public final class WMShell extends CoreStartable mShell.onKeyguardDismissAnimationFinished(); } }; + private final UserTracker.Callback mUserChangedCallback = + new UserTracker.Callback() { + @Override + public void onUserChanged(int newUser, @NonNull Context userContext) { + mShell.onUserChanged(newUser, userContext); + } + + @Override + public void onProfilesChanged(@NonNull List<UserInfo> profiles) { + mShell.onUserProfilesChanged(profiles); + } + }; private boolean mIsSysUiStateValid; - private KeyguardUpdateMonitorCallback mOneHandedKeyguardCallback; private WakefulnessLifecycle.Observer mWakefulnessObserver; @Inject @@ -163,7 +177,7 @@ public final class WMShell extends CoreStartable SysUiState sysUiState, ProtoTracer protoTracer, WakefulnessLifecycle wakefulnessLifecycle, - UserInfoController userInfoController, + UserTracker userTracker, @Main Executor sysUiMainExecutor) { super(context); mShell = shell; @@ -178,7 +192,7 @@ public final class WMShell extends CoreStartable mOneHandedOptional = oneHandedOptional; mWakefulnessLifecycle = wakefulnessLifecycle; mProtoTracer = protoTracer; - mUserInfoController = userInfoController; + mUserTracker = userTracker; mSysUiMainExecutor = sysUiMainExecutor; } @@ -192,8 +206,9 @@ public final class WMShell extends CoreStartable mKeyguardStateController.addCallback(mKeyguardStateCallback); mKeyguardUpdateMonitor.registerCallback(mKeyguardUpdateMonitorCallback); - // TODO: Consider piping config change and other common calls to a shell component to - // delegate internally + // Subscribe to user changes + mUserTracker.addCallback(mUserChangedCallback, mContext.getMainExecutor()); + mProtoTracer.add(this); mCommandQueue.addCallback(this); mPipOptional.ifPresent(this::initPip); @@ -214,10 +229,6 @@ public final class WMShell extends CoreStartable mIsSysUiStateValid = (sysUiStateFlag & INVALID_SYSUI_STATE_MASK) == 0; pip.onSystemUiStateChanged(mIsSysUiStateValid, sysUiStateFlag); }); - - // The media session listener needs to be re-registered when switching users - mUserInfoController.addCallback((String name, Drawable picture, String userAccount) -> - pip.registerSessionListenerForCurrentUser()); } @VisibleForTesting @@ -267,15 +278,6 @@ public final class WMShell extends CoreStartable } }); - // TODO: Either move into ShellInterface or register a receiver on the Shell side directly - mOneHandedKeyguardCallback = new KeyguardUpdateMonitorCallback() { - @Override - public void onUserSwitchComplete(int userId) { - oneHanded.onUserSwitch(userId); - } - }; - mKeyguardUpdateMonitor.registerCallback(mOneHandedKeyguardCallback); - mWakefulnessObserver = new WakefulnessLifecycle.Observer() { @Override diff --git a/packages/SystemUI/tests/src/com/android/systemui/dreams/DreamOverlayStatusBarViewControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/dreams/DreamOverlayStatusBarViewControllerTest.java index 01309f86a137..7f6b79b48939 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/dreams/DreamOverlayStatusBarViewControllerTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/dreams/DreamOverlayStatusBarViewControllerTest.java @@ -308,6 +308,12 @@ public class DreamOverlayStatusBarViewControllerTest extends SysuiTestCase { } @Test + public void testOnViewDetachedRemovesViews() { + mController.onViewDetached(); + verify(mView).removeAllStatusBarItemViews(); + } + + @Test public void testWifiIconHiddenWhenWifiBecomesAvailable() { // Make sure wifi starts out unavailable when onViewAttached is called, and then returns // true on the second query. diff --git a/packages/SystemUI/tests/src/com/android/systemui/dreams/complication/ComplicationTypesUpdaterTest.java b/packages/SystemUI/tests/src/com/android/systemui/dreams/complication/ComplicationTypesUpdaterTest.java index 09976e0e6192..571dd3d1faf3 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/dreams/complication/ComplicationTypesUpdaterTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/dreams/complication/ComplicationTypesUpdaterTest.java @@ -106,7 +106,7 @@ public class ComplicationTypesUpdaterTest extends SysuiTestCase { private ContentObserver captureSettingsObserver() { verify(mSecureSettings).registerContentObserverForUser( - eq(Settings.Secure.SCREENSAVER_ENABLED_COMPLICATIONS), + eq(Settings.Secure.SCREENSAVER_COMPLICATIONS_ENABLED), mSettingsObserverCaptor.capture(), eq(UserHandle.myUserId())); return mSettingsObserverCaptor.getValue(); } diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardViewMediatorTest.java b/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardViewMediatorTest.java index 21c018a0419d..6e89bb90e558 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardViewMediatorTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/KeyguardViewMediatorTest.java @@ -48,6 +48,7 @@ import com.android.internal.widget.LockPatternUtils; import com.android.keyguard.KeyguardDisplayManager; import com.android.keyguard.KeyguardSecurityView; import com.android.keyguard.KeyguardUpdateMonitor; +import com.android.keyguard.logging.KeyguardViewMediatorLogger; import com.android.keyguard.mediator.ScreenOnCoordinator; import com.android.systemui.SysuiTestCase; import com.android.systemui.animation.ActivityLaunchAnimator; @@ -106,6 +107,7 @@ public class KeyguardViewMediatorTest extends SysuiTestCase { private @Mock Lazy<NotificationShadeWindowController> mNotificationShadeWindowControllerLazy; private @Mock DreamOverlayStateController mDreamOverlayStateController; private @Mock ActivityLaunchAnimator mActivityLaunchAnimator; + private @Mock KeyguardViewMediatorLogger mLogger; private DeviceConfigProxy mDeviceConfig = new DeviceConfigProxyFake(); private FakeExecutor mUiBgExecutor = new FakeExecutor(new FakeSystemClock()); @@ -262,7 +264,8 @@ public class KeyguardViewMediatorTest extends SysuiTestCase { mInteractionJankMonitor, mDreamOverlayStateController, mNotificationShadeWindowControllerLazy, - () -> mActivityLaunchAnimator); + () -> mActivityLaunchAnimator, + mLogger); mViewMediator.start(); } } diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardBottomAreaViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardBottomAreaViewModelTest.kt index 19491f41a0c1..14b85b8b5e56 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardBottomAreaViewModelTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardBottomAreaViewModelTest.kt @@ -37,6 +37,8 @@ import com.android.systemui.statusbar.policy.KeyguardStateController import com.android.systemui.util.mockito.any import com.android.systemui.util.mockito.mock import com.google.common.truth.Truth.assertThat +import kotlin.math.max +import kotlin.math.min import kotlin.reflect.KClass import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach @@ -127,6 +129,7 @@ class KeyguardBottomAreaViewModelTest : SysuiTestCase() { val testConfig = TestConfig( isVisible = true, + isClickable = true, icon = mock(), canShowWhileLocked = false, intent = Intent("action"), @@ -154,6 +157,7 @@ class KeyguardBottomAreaViewModelTest : SysuiTestCase() { val config = TestConfig( isVisible = true, + isClickable = true, icon = mock(), canShowWhileLocked = false, intent = null, // This will cause it to tell the system that the click was handled. @@ -201,6 +205,7 @@ class KeyguardBottomAreaViewModelTest : SysuiTestCase() { val testConfig = TestConfig( isVisible = true, + isClickable = true, icon = mock(), canShowWhileLocked = false, intent = Intent("action"), @@ -260,6 +265,7 @@ class KeyguardBottomAreaViewModelTest : SysuiTestCase() { testConfig = TestConfig( isVisible = true, + isClickable = true, icon = mock(), canShowWhileLocked = true, ) @@ -269,6 +275,7 @@ class KeyguardBottomAreaViewModelTest : SysuiTestCase() { testConfig = TestConfig( isVisible = true, + isClickable = true, icon = mock(), canShowWhileLocked = false, ) @@ -342,6 +349,129 @@ class KeyguardBottomAreaViewModelTest : SysuiTestCase() { job.cancel() } + @Test + fun `isClickable - true when alpha at threshold`() = runBlockingTest { + repository.setKeyguardShowing(true) + repository.setBottomAreaAlpha( + KeyguardBottomAreaViewModel.AFFORDANCE_FULLY_OPAQUE_ALPHA_THRESHOLD + ) + + val testConfig = + TestConfig( + isVisible = true, + isClickable = true, + icon = mock(), + canShowWhileLocked = false, + intent = Intent("action"), + ) + val configKey = + setUpQuickAffordanceModel( + position = KeyguardQuickAffordancePosition.BOTTOM_START, + testConfig = testConfig, + ) + + var latest: KeyguardQuickAffordanceViewModel? = null + val job = underTest.startButton.onEach { latest = it }.launchIn(this) + + assertQuickAffordanceViewModel( + viewModel = latest, + testConfig = testConfig, + configKey = configKey, + ) + job.cancel() + } + + @Test + fun `isClickable - true when alpha above threshold`() = runBlockingTest { + repository.setKeyguardShowing(true) + var latest: KeyguardQuickAffordanceViewModel? = null + val job = underTest.startButton.onEach { latest = it }.launchIn(this) + repository.setBottomAreaAlpha( + min(1f, KeyguardBottomAreaViewModel.AFFORDANCE_FULLY_OPAQUE_ALPHA_THRESHOLD + 0.1f), + ) + + val testConfig = + TestConfig( + isVisible = true, + isClickable = true, + icon = mock(), + canShowWhileLocked = false, + intent = Intent("action"), + ) + val configKey = + setUpQuickAffordanceModel( + position = KeyguardQuickAffordancePosition.BOTTOM_START, + testConfig = testConfig, + ) + + assertQuickAffordanceViewModel( + viewModel = latest, + testConfig = testConfig, + configKey = configKey, + ) + job.cancel() + } + + @Test + fun `isClickable - false when alpha below threshold`() = runBlockingTest { + repository.setKeyguardShowing(true) + var latest: KeyguardQuickAffordanceViewModel? = null + val job = underTest.startButton.onEach { latest = it }.launchIn(this) + repository.setBottomAreaAlpha( + max(0f, KeyguardBottomAreaViewModel.AFFORDANCE_FULLY_OPAQUE_ALPHA_THRESHOLD - 0.1f), + ) + + val testConfig = + TestConfig( + isVisible = true, + isClickable = false, + icon = mock(), + canShowWhileLocked = false, + intent = Intent("action"), + ) + val configKey = + setUpQuickAffordanceModel( + position = KeyguardQuickAffordancePosition.BOTTOM_START, + testConfig = testConfig, + ) + + assertQuickAffordanceViewModel( + viewModel = latest, + testConfig = testConfig, + configKey = configKey, + ) + job.cancel() + } + + @Test + fun `isClickable - false when alpha at zero`() = runBlockingTest { + repository.setKeyguardShowing(true) + var latest: KeyguardQuickAffordanceViewModel? = null + val job = underTest.startButton.onEach { latest = it }.launchIn(this) + repository.setBottomAreaAlpha(0f) + + val testConfig = + TestConfig( + isVisible = true, + isClickable = false, + icon = mock(), + canShowWhileLocked = false, + intent = Intent("action"), + ) + val configKey = + setUpQuickAffordanceModel( + position = KeyguardQuickAffordancePosition.BOTTOM_START, + testConfig = testConfig, + ) + + assertQuickAffordanceViewModel( + viewModel = latest, + testConfig = testConfig, + configKey = configKey, + ) + job.cancel() + } + private suspend fun setDozeAmountAndCalculateExpectedTranslationY(dozeAmount: Float): Float { repository.setDozeAmount(dozeAmount) return dozeAmount * (RETURNED_BURN_IN_OFFSET - DEFAULT_BURN_IN_OFFSET) @@ -384,6 +514,7 @@ class KeyguardBottomAreaViewModelTest : SysuiTestCase() { ) { checkNotNull(viewModel) assertThat(viewModel.isVisible).isEqualTo(testConfig.isVisible) + assertThat(viewModel.isClickable).isEqualTo(testConfig.isClickable) if (testConfig.isVisible) { assertThat(viewModel.icon).isEqualTo(testConfig.icon) viewModel.onClicked.invoke( @@ -404,6 +535,7 @@ class KeyguardBottomAreaViewModelTest : SysuiTestCase() { private data class TestConfig( val isVisible: Boolean, + val isClickable: Boolean = false, val icon: ContainedDrawable? = null, val canShowWhileLocked: Boolean = false, val intent: Intent? = null, diff --git a/packages/SystemUI/tests/src/com/android/systemui/lifecycle/InstantTaskExecutorRule.kt b/packages/SystemUI/tests/src/com/android/systemui/lifecycle/InstantTaskExecutorRule.kt new file mode 100644 index 000000000000..373af5cdf4b7 --- /dev/null +++ b/packages/SystemUI/tests/src/com/android/systemui/lifecycle/InstantTaskExecutorRule.kt @@ -0,0 +1,57 @@ +/* + * 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.systemui.lifecycle + +import androidx.arch.core.executor.ArchTaskExecutor +import androidx.arch.core.executor.TaskExecutor +import org.junit.rules.TestWatcher +import org.junit.runner.Description + +/** + * Test rule that makes ArchTaskExecutor main thread assertions pass. There is one such assert + * in LifecycleRegistry. + */ +class InstantTaskExecutorRule : TestWatcher() { + // TODO(b/240620122): This is a copy of + // androidx/arch/core/executor/testing/InstantTaskExecutorRule which should be replaced + // with a dependency on the real library once b/ is cleared. + override fun starting(description: Description) { + super.starting(description) + ArchTaskExecutor.getInstance() + .setDelegate( + object : TaskExecutor() { + override fun executeOnDiskIO(runnable: Runnable) { + runnable.run() + } + + override fun postToMainThread(runnable: Runnable) { + runnable.run() + } + + override fun isMainThread(): Boolean { + return true + } + } + ) + } + + override fun finished(description: Description) { + super.finished(description) + ArchTaskExecutor.getInstance().setDelegate(null) + } +} diff --git a/packages/SystemUI/tests/src/com/android/systemui/lifecycle/RepeatWhenAttachedTest.kt b/packages/SystemUI/tests/src/com/android/systemui/lifecycle/RepeatWhenAttachedTest.kt index 80f3e46b848f..91a6de6ae4c0 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/lifecycle/RepeatWhenAttachedTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/lifecycle/RepeatWhenAttachedTest.kt @@ -20,8 +20,6 @@ package com.android.systemui.lifecycle import android.testing.TestableLooper.RunWithLooper import android.view.View import android.view.ViewTreeObserver -import androidx.arch.core.executor.ArchTaskExecutor -import androidx.arch.core.executor.TaskExecutor import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.test.filters.SmallTest @@ -35,8 +33,6 @@ import kotlinx.coroutines.test.runBlockingTest import org.junit.Before import org.junit.Rule import org.junit.Test -import org.junit.rules.TestWatcher -import org.junit.runner.Description import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.mockito.Mock @@ -282,38 +278,4 @@ class RepeatWhenAttachedTest : SysuiTestCase() { _invocations.add(Invocation(lifecycleOwner)) } } - - /** - * Test rule that makes ArchTaskExecutor main thread assertions pass. There is one such assert - * in LifecycleRegistry. - */ - class InstantTaskExecutorRule : TestWatcher() { - // TODO(b/240620122): This is a copy of - // androidx/arch/core/executor/testing/InstantTaskExecutorRule which should be replaced - // with a dependency on the real library once b/ is cleared. - override fun starting(description: Description) { - super.starting(description) - ArchTaskExecutor.getInstance() - .setDelegate( - object : TaskExecutor() { - override fun executeOnDiskIO(runnable: Runnable) { - runnable.run() - } - - override fun postToMainThread(runnable: Runnable) { - runnable.run() - } - - override fun isMainThread(): Boolean { - return true - } - } - ) - } - - override fun finished(description: Description) { - super.finished(description) - ArchTaskExecutor.getInstance().setDelegate(null) - } - } } diff --git a/packages/SystemUI/tests/src/com/android/systemui/log/LogBufferTest.kt b/packages/SystemUI/tests/src/com/android/systemui/log/LogBufferTest.kt index 56aff3c2fc8b..7b12eb75e841 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/log/LogBufferTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/log/LogBufferTest.kt @@ -41,6 +41,18 @@ class LogBufferTest : SysuiTestCase() { } @Test + fun log_shouldSaveLogToBufferWithException() { + val exception = createTestException("Some exception test message", "SomeExceptionTestClass") + buffer.log("Test", LogLevel.INFO, "Some test message", exception) + + val dumpedString = dumpBuffer() + + assertThat(dumpedString).contains("Some test message") + assertThat(dumpedString).contains("Some exception test message") + assertThat(dumpedString).contains("SomeExceptionTestClass") + } + + @Test fun log_shouldRotateIfLogBufferIsFull() { buffer.log("Test", LogLevel.INFO, "This should be rotated") buffer.log("Test", LogLevel.INFO, "New test message") diff --git a/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputAdapterTest.java b/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputAdapterTest.java index 260bb8760f1c..22ecb4b93743 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputAdapterTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputAdapterTest.java @@ -78,7 +78,7 @@ public class MediaOutputAdapterTest extends SysuiTestCase { when(mMediaOutputController.getMediaDevices()).thenReturn(mMediaDevices); when(mMediaOutputController.hasAdjustVolumeUserRestriction()).thenReturn(false); - when(mMediaOutputController.isTransferring()).thenReturn(false); + when(mMediaOutputController.isAnyDeviceTransferring()).thenReturn(false); when(mMediaOutputController.getDeviceIconCompat(mMediaDevice1)).thenReturn(mIconCompat); when(mMediaOutputController.getDeviceIconCompat(mMediaDevice2)).thenReturn(mIconCompat); when(mMediaOutputController.getCurrentConnectedMediaDevice()).thenReturn(mMediaDevice1); @@ -208,7 +208,7 @@ public class MediaOutputAdapterTest extends SysuiTestCase { @Test public void onBindViewHolder_inTransferring_bindTransferringDevice_verifyView() { - when(mMediaOutputController.isTransferring()).thenReturn(true); + when(mMediaOutputController.isAnyDeviceTransferring()).thenReturn(true); when(mMediaDevice1.getState()).thenReturn( LocalMediaManager.MediaDeviceState.STATE_CONNECTING); mMediaOutputAdapter.onBindViewHolder(mViewHolder, 0); @@ -224,7 +224,7 @@ public class MediaOutputAdapterTest extends SysuiTestCase { @Test public void onBindViewHolder_inTransferring_bindNonTransferringDevice_verifyView() { - when(mMediaOutputController.isTransferring()).thenReturn(true); + when(mMediaOutputController.isAnyDeviceTransferring()).thenReturn(true); when(mMediaDevice2.getState()).thenReturn( LocalMediaManager.MediaDeviceState.STATE_CONNECTING); mMediaOutputAdapter.onBindViewHolder(mViewHolder, 0); diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/QuickStatusBarHeaderControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/QuickStatusBarHeaderControllerTest.kt index be14cc51ef96..cb4f08e6c552 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/qs/QuickStatusBarHeaderControllerTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/qs/QuickStatusBarHeaderControllerTest.kt @@ -93,6 +93,10 @@ class QuickStatusBarHeaderControllerTest : SysuiTestCase() { private lateinit var featureFlags: FeatureFlags @Mock private lateinit var insetsProvider: StatusBarContentInsetsProvider + @Mock + private lateinit var iconManagerFactory: StatusBarIconController.TintedIconManager.Factory + @Mock + private lateinit var iconManager: StatusBarIconController.TintedIconManager private val qsExpansionPathInterpolator = QSExpansionPathInterpolator() @@ -106,6 +110,7 @@ class QuickStatusBarHeaderControllerTest : SysuiTestCase() { `when`(qsCarrierGroupControllerBuilder.build()).thenReturn(qsCarrierGroupController) `when`(variableDateViewControllerFactory.create(any())) .thenReturn(variableDateViewController) + `when`(iconManagerFactory.create(any())).thenReturn(iconManager) `when`(view.resources).thenReturn(mContext.resources) `when`(view.isAttachedToWindow).thenReturn(true) `when`(view.context).thenReturn(context) @@ -122,7 +127,8 @@ class QuickStatusBarHeaderControllerTest : SysuiTestCase() { featureFlags, variableDateViewControllerFactory, batteryMeterViewController, - insetsProvider + insetsProvider, + iconManagerFactory, ) } diff --git a/packages/SystemUI/tests/src/com/android/systemui/screenshot/TakeScreenshotServiceTest.kt b/packages/SystemUI/tests/src/com/android/systemui/screenshot/TakeScreenshotServiceTest.kt new file mode 100644 index 000000000000..83e56daf1fbc --- /dev/null +++ b/packages/SystemUI/tests/src/com/android/systemui/screenshot/TakeScreenshotServiceTest.kt @@ -0,0 +1,237 @@ +/* + * 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.systemui.screenshot + +import android.app.Application +import android.app.admin.DevicePolicyManager +import android.app.admin.DevicePolicyResources.Strings.SystemUi.SCREENSHOT_BLOCKED_BY_ADMIN +import android.app.admin.DevicePolicyResourcesManager +import android.content.ComponentName +import android.graphics.Bitmap +import android.graphics.Bitmap.Config.HARDWARE +import android.graphics.ColorSpace +import android.graphics.Insets +import android.graphics.Rect +import android.hardware.HardwareBuffer +import android.os.UserHandle +import android.os.UserManager +import android.testing.AndroidTestingRunner +import android.view.WindowManager.ScreenshotSource.SCREENSHOT_KEY_CHORD +import android.view.WindowManager.ScreenshotSource.SCREENSHOT_OVERVIEW +import android.view.WindowManager.TAKE_SCREENSHOT_FULLSCREEN +import android.view.WindowManager.TAKE_SCREENSHOT_PROVIDED_IMAGE +import android.view.WindowManager.TAKE_SCREENSHOT_SELECTED_REGION +import com.android.internal.logging.testing.UiEventLoggerFake +import com.android.internal.util.ScreenshotHelper +import com.android.internal.util.ScreenshotHelper.ScreenshotRequest +import com.android.systemui.SysuiTestCase +import com.android.systemui.flags.FakeFeatureFlags +import com.android.systemui.flags.Flags.SCREENSHOT_REQUEST_PROCESSOR +import com.android.systemui.screenshot.ScreenshotEvent.SCREENSHOT_REQUESTED_KEY_CHORD +import com.android.systemui.screenshot.ScreenshotEvent.SCREENSHOT_REQUESTED_OVERVIEW +import com.android.systemui.screenshot.TakeScreenshotService.RequestCallback +import com.android.systemui.util.mockito.any +import com.android.systemui.util.mockito.argThat +import com.android.systemui.util.mockito.eq +import com.android.systemui.util.mockito.mock +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentMatchers.anyInt +import org.mockito.ArgumentMatchers.isNull +import org.mockito.Mockito.verify +import org.mockito.Mockito.verifyZeroInteractions +import org.mockito.Mockito.`when` as whenever + +private const val USER_ID = 1 +private const val TASK_ID = 1 + +@RunWith(AndroidTestingRunner::class) +class TakeScreenshotServiceTest : SysuiTestCase() { + + private val application = mock<Application>() + private val controller = mock<ScreenshotController>() + private val userManager = mock<UserManager>() + private val requestProcessor = mock<RequestProcessor>() + private val devicePolicyManager = mock<DevicePolicyManager>() + private val devicePolicyResourcesManager = mock<DevicePolicyResourcesManager>() + private val notificationsController = mock<ScreenshotNotificationsController>() + private val callback = mock<RequestCallback>() + + private val eventLogger = UiEventLoggerFake() + private val flags = FakeFeatureFlags() + private val topComponent = ComponentName(mContext, TakeScreenshotServiceTest::class.java) + + private val service = TakeScreenshotService( + controller, userManager, devicePolicyManager, eventLogger, + notificationsController, mContext, Runnable::run, flags, requestProcessor) + + @Before + fun setUp() { + whenever(devicePolicyManager.resources).thenReturn(devicePolicyResourcesManager) + whenever(devicePolicyManager.getScreenCaptureDisabled( + /* admin component (null: any admin) */ isNull(), eq(UserHandle.USER_ALL))) + .thenReturn(false) + whenever(userManager.isUserUnlocked).thenReturn(true) + + flags.set(SCREENSHOT_REQUEST_PROCESSOR, false) + + service.attach( + mContext, + /* thread = */ null, + /* className = */ null, + /* token = */ null, + application, + /* activityManager = */ null) + } + + @Test + fun testServiceLifecycle() { + service.onCreate() + service.onBind(null /* unused: Intent */) + + service.onUnbind(null /* unused: Intent */) + verify(controller).removeWindow() + + service.onDestroy() + verify(controller).onDestroy() + } + + @Test + fun takeScreenshotFullscreen() { + val request = ScreenshotRequest( + TAKE_SCREENSHOT_FULLSCREEN, + SCREENSHOT_KEY_CHORD, + topComponent) + + service.handleRequest(request, { /* onSaved */ }, callback) + + verify(controller).takeScreenshotFullscreen( + eq(topComponent), + /* onSavedListener = */ any(), + /* requestCallback = */ any()) + + assertEquals("Expected one UiEvent", eventLogger.numLogs(), 1) + val logEvent = eventLogger.get(0) + + assertEquals("Expected SCREENSHOT_REQUESTED UiEvent", + logEvent.eventId, SCREENSHOT_REQUESTED_KEY_CHORD.id) + assertEquals("Expected supplied package name", + topComponent.packageName, eventLogger.get(0).packageName) + } + + @Test + fun takeScreenshotPartial() { + val request = ScreenshotRequest( + TAKE_SCREENSHOT_SELECTED_REGION, + SCREENSHOT_KEY_CHORD, + /* topComponent = */ null) + + service.handleRequest(request, { /* onSaved */ }, callback) + + verify(controller).takeScreenshotPartial( + /* topComponent = */ isNull(), + /* onSavedListener = */ any(), + /* requestCallback = */ any()) + + assertEquals("Expected one UiEvent", eventLogger.numLogs(), 1) + val logEvent = eventLogger.get(0) + + assertEquals("Expected SCREENSHOT_REQUESTED UiEvent", + logEvent.eventId, SCREENSHOT_REQUESTED_KEY_CHORD.id) + assertEquals("Expected empty package name in UiEvent", "", eventLogger.get(0).packageName) + } + + @Test + fun takeScreenshotProvidedImage() { + val bounds = Rect(50, 50, 150, 150) + val bitmap = makeHardwareBitmap(100, 100) + val bitmapBundle = ScreenshotHelper.HardwareBitmapBundler.hardwareBitmapToBundle(bitmap) + + val request = ScreenshotRequest(TAKE_SCREENSHOT_PROVIDED_IMAGE, SCREENSHOT_OVERVIEW, + bitmapBundle, bounds, Insets.NONE, TASK_ID, USER_ID, topComponent) + + service.handleRequest(request, { /* onSaved */ }, callback) + + verify(controller).handleImageAsScreenshot( + argThat { b -> b.equalsHardwareBitmap(bitmap) }, + eq(bounds), + eq(Insets.NONE), eq(TASK_ID), eq(USER_ID), eq(topComponent), + /* onSavedListener = */ any(), /* requestCallback = */ any()) + + assertEquals("Expected one UiEvent", eventLogger.numLogs(), 1) + val logEvent = eventLogger.get(0) + + assertEquals("Expected SCREENSHOT_REQUESTED_* UiEvent", + logEvent.eventId, SCREENSHOT_REQUESTED_OVERVIEW.id) + assertEquals("Expected supplied package name", + topComponent.packageName, eventLogger.get(0).packageName) + } + + @Test + fun takeScreenshotFullscreen_userLocked() { + whenever(userManager.isUserUnlocked).thenReturn(false) + + val request = ScreenshotRequest( + TAKE_SCREENSHOT_FULLSCREEN, + SCREENSHOT_KEY_CHORD, + topComponent) + + service.handleRequest(request, { /* onSaved */ }, callback) + + verify(notificationsController).notifyScreenshotError(anyInt()) + verify(callback).reportError() + verifyZeroInteractions(controller) + } + + @Test + fun takeScreenshotFullscreen_screenCaptureDisabled_allUsers() { + whenever(devicePolicyManager.getScreenCaptureDisabled( + isNull(), eq(UserHandle.USER_ALL)) + ).thenReturn(true) + + whenever(devicePolicyResourcesManager.getString( + eq(SCREENSHOT_BLOCKED_BY_ADMIN), + /* Supplier<String> */ any(), + )).thenReturn("SCREENSHOT_BLOCKED_BY_ADMIN") + + val request = ScreenshotRequest( + TAKE_SCREENSHOT_FULLSCREEN, + SCREENSHOT_KEY_CHORD, + topComponent) + + service.handleRequest(request, { /* onSaved */ }, callback) + + // error shown: Toast.makeText(...).show(), untestable + verify(callback).reportError() + verifyZeroInteractions(controller) + } +} + +private fun Bitmap.equalsHardwareBitmap(other: Bitmap): Boolean { + return config == HARDWARE && + other.config == HARDWARE && + hardwareBuffer == other.hardwareBuffer && + colorSpace == other.colorSpace +} + +/** A hardware Bitmap is mandated by use of ScreenshotHelper.HardwareBitmapBundler */ +private fun makeHardwareBitmap(width: Int, height: Int): Bitmap { + val buffer = HardwareBuffer.create(width, height, HardwareBuffer.RGBA_8888, 1, + HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE) + return Bitmap.wrapHardwareBuffer(buffer, ColorSpace.get(ColorSpace.Named.SRGB))!! +} diff --git a/packages/SystemUI/tests/src/com/android/systemui/shade/LargeScreenShadeHeaderControllerCombinedTest.kt b/packages/SystemUI/tests/src/com/android/systemui/shade/LargeScreenShadeHeaderControllerCombinedTest.kt index ed1a13b36d6c..20c6d9adc300 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/shade/LargeScreenShadeHeaderControllerCombinedTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/shade/LargeScreenShadeHeaderControllerCombinedTest.kt @@ -91,6 +91,10 @@ class LargeScreenShadeHeaderControllerCombinedTest : SysuiTestCase() { @Mock private lateinit var statusBarIconController: StatusBarIconController @Mock + private lateinit var iconManagerFactory: StatusBarIconController.TintedIconManager.Factory + @Mock + private lateinit var iconManager: StatusBarIconController.TintedIconManager + @Mock private lateinit var qsCarrierGroupController: QSCarrierGroupController @Mock private lateinit var qsCarrierGroupControllerBuilder: QSCarrierGroupController.Builder @@ -169,6 +173,8 @@ class LargeScreenShadeHeaderControllerCombinedTest : SysuiTestCase() { } whenever(view.visibility).thenAnswer { _ -> viewVisibility } + whenever(iconManagerFactory.create(any())).thenReturn(iconManager) + whenever(featureFlags.isEnabled(Flags.COMBINED_QS_HEADERS)).thenReturn(true) whenever(featureFlags.isEnabled(Flags.NEW_HEADER)).thenReturn(true) @@ -178,6 +184,7 @@ class LargeScreenShadeHeaderControllerCombinedTest : SysuiTestCase() { controller = LargeScreenShadeHeaderController( view, statusBarIconController, + iconManagerFactory, privacyIconsController, insetsProvider, configurationController, diff --git a/packages/SystemUI/tests/src/com/android/systemui/shade/LargeScreenShadeHeaderControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/shade/LargeScreenShadeHeaderControllerTest.kt index 02b26dbbc32d..eeb61bc8a0f8 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/shade/LargeScreenShadeHeaderControllerTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/shade/LargeScreenShadeHeaderControllerTest.kt @@ -43,6 +43,8 @@ class LargeScreenShadeHeaderControllerTest : SysuiTestCase() { @Mock private lateinit var view: View @Mock private lateinit var statusIcons: StatusIconContainer @Mock private lateinit var statusBarIconController: StatusBarIconController + @Mock private lateinit var iconManagerFactory: StatusBarIconController.TintedIconManager.Factory + @Mock private lateinit var iconManager: StatusBarIconController.TintedIconManager @Mock private lateinit var qsCarrierGroupController: QSCarrierGroupController @Mock private lateinit var qsCarrierGroupControllerBuilder: QSCarrierGroupController.Builder @Mock private lateinit var featureFlags: FeatureFlags @@ -91,10 +93,12 @@ class LargeScreenShadeHeaderControllerTest : SysuiTestCase() { whenever(view.visibility).thenAnswer { _ -> viewVisibility } whenever(variableDateViewControllerFactory.create(any())) .thenReturn(variableDateViewController) + whenever(iconManagerFactory.create(any())).thenReturn(iconManager) whenever(featureFlags.isEnabled(Flags.COMBINED_QS_HEADERS)).thenReturn(false) mLargeScreenShadeHeaderController = LargeScreenShadeHeaderController( view, statusBarIconController, + iconManagerFactory, privacyIconsController, insetsProvider, configurationController, diff --git a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerTest.java index 95211c0c8ec8..7d28871e340c 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerTest.java @@ -47,7 +47,6 @@ import android.content.ContentResolver; import android.content.res.Configuration; import android.content.res.Resources; import android.database.ContentObserver; -import android.graphics.PointF; import android.os.Handler; import android.os.Looper; import android.os.PowerManager; @@ -764,10 +763,8 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase { @Test public void testSetDozing_notifiesNsslAndStateController() { - mNotificationPanelViewController.setDozing(true /* dozing */, false /* animate */, - null /* touch */); - verify(mNotificationStackScrollLayoutController) - .setDozing(eq(true), eq(false), eq(null)); + mNotificationPanelViewController.setDozing(true /* dozing */, false /* animate */); + verify(mNotificationStackScrollLayoutController).setDozing(eq(true), eq(false)); assertThat(mStatusBarStateController.getDozeAmount()).isEqualTo(1f); } @@ -908,7 +905,7 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase { setDozing(/* dozing= */ true, /* dozingAlwaysOn= */ true); - assertThat(isKeyguardStatusViewCentered()).isTrue(); + assertKeyguardStatusViewCentered(); } @Test @@ -919,7 +916,7 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase { setDozing(/* dozing= */ true, /* dozingAlwaysOn= */ false); - assertThat(isKeyguardStatusViewCentered()).isFalse(); + assertKeyguardStatusViewNotCentered(); } @Test @@ -930,19 +927,19 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase { setDozing(/* dozing= */ false, /* dozingAlwaysOn= */ true); - assertThat(isKeyguardStatusViewCentered()).isFalse(); + assertKeyguardStatusViewNotCentered(); } @Test - public void keyguardStatusView_splitShade_pulsing_isCentered() { + public void keyguardStatusView_splitShade_pulsing_isNotCentered() { when(mNotificationStackScrollLayoutController.getVisibleNotificationCount()).thenReturn(2); when(mNotificationListContainer.hasPulsingNotifications()).thenReturn(true); mStatusBarStateController.setState(KEYGUARD); enableSplitShade(/* enabled= */ true); - setDozing(/* dozing= */ false, /* dozingAlwaysOn= */ true); + setDozing(/* dozing= */ false, /* dozingAlwaysOn= */ false); - assertThat(isKeyguardStatusViewCentered()).isFalse(); + assertKeyguardStatusViewNotCentered(); } @Test @@ -952,9 +949,9 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase { mStatusBarStateController.setState(KEYGUARD); enableSplitShade(/* enabled= */ true); - setDozing(/* dozing= */ false, /* dozingAlwaysOn= */ true); + setDozing(/* dozing= */ false, /* dozingAlwaysOn= */ false); - assertThat(isKeyguardStatusViewCentered()).isFalse(); + assertKeyguardStatusViewNotCentered(); } @Test @@ -967,7 +964,7 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase { mStatusBarStateController.setState(KEYGUARD); setDozing(/* dozing= */ false, /* dozingAlwaysOn= */ false); - assertThat(isKeyguardStatusViewCentered()).isFalse(); + assertKeyguardStatusViewCentered(); } @Test @@ -1212,16 +1209,31 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase { } @Test - public void testSwitchesToBigClockInSplitShadeOnAod() { + public void clockSize_mediaShowing_inSplitShade_onAod_isLarge() { + when(mDozeParameters.getAlwaysOn()).thenReturn(true); mStatusBarStateController.setState(KEYGUARD); enableSplitShade(/* enabled= */ true); when(mMediaDataManager.hasActiveMediaOrRecommendation()).thenReturn(true); when(mNotificationStackScrollLayoutController.getVisibleNotificationCount()).thenReturn(2); clearInvocations(mKeyguardStatusViewController); - mNotificationPanelViewController.setDozing(true, false, null); + mNotificationPanelViewController.setDozing(/* dozing= */ true, /* animate= */ false); - verify(mKeyguardStatusViewController).displayClock(LARGE, /* animate */ true); + verify(mKeyguardStatusViewController).displayClock(LARGE, /* animate= */ true); + } + + @Test + public void clockSize_mediaShowing_inSplitShade_screenOff_notAod_isSmall() { + when(mDozeParameters.getAlwaysOn()).thenReturn(false); + mStatusBarStateController.setState(KEYGUARD); + enableSplitShade(/* enabled= */ true); + when(mMediaDataManager.hasActiveMediaOrRecommendation()).thenReturn(true); + when(mNotificationStackScrollLayoutController.getVisibleNotificationCount()).thenReturn(2); + clearInvocations(mKeyguardStatusViewController); + + mNotificationPanelViewController.setDozing(/* dozing= */ true, /* animate= */ false); + + verify(mKeyguardStatusViewController).displayClock(SMALL, /* animate= */ true); } @Test @@ -1233,7 +1245,7 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase { when(mMediaDataManager.hasActiveMedia()).thenReturn(true); when(mNotificationStackScrollLayoutController.getVisibleNotificationCount()).thenReturn(2); - mNotificationPanelViewController.setDozing(true, false, null); + mNotificationPanelViewController.setDozing(true, false); verify(mKeyguardStatusViewController).displayClock(LARGE, /* animate */ false); } @@ -1547,14 +1559,19 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase { when(mDozeParameters.getAlwaysOn()).thenReturn(dozingAlwaysOn); mNotificationPanelViewController.setDozing( /* dozing= */ dozing, - /* animate= */ false, - /* wakeUpTouchLocation= */ new PointF() + /* animate= */ false ); } - private boolean isKeyguardStatusViewCentered() { + private void assertKeyguardStatusViewCentered() { + mNotificationPanelViewController.updateResources(); + assertThat(getConstraintSetLayout(R.id.keyguard_status_view).endToEnd).isAnyOf( + ConstraintSet.PARENT_ID, ConstraintSet.UNSET); + } + + private void assertKeyguardStatusViewNotCentered() { mNotificationPanelViewController.updateResources(); - return getConstraintSetLayout(R.id.keyguard_status_view).endToEnd - == ConstraintSet.PARENT_ID; + assertThat(getConstraintSetLayout(R.id.keyguard_status_view).endToEnd).isEqualTo( + R.id.qs_edge_guideline); } } diff --git a/packages/SystemUI/tests/src/com/android/systemui/shared/rotation/RotationButtonControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/shared/rotation/RotationButtonControllerTest.kt new file mode 100644 index 000000000000..9393a4f4eead --- /dev/null +++ b/packages/SystemUI/tests/src/com/android/systemui/shared/rotation/RotationButtonControllerTest.kt @@ -0,0 +1,77 @@ +/* + * 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.systemui.shared.rotation + +import android.testing.AndroidTestingRunner +import android.testing.TestableLooper.RunWithLooper +import android.view.Display +import android.view.WindowInsetsController +import android.view.WindowManagerPolicyConstants +import androidx.test.filters.SmallTest +import com.android.systemui.SysuiTestCase +import com.google.common.truth.Truth.assertThat +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidTestingRunner::class) +@SmallTest +@RunWithLooper +class RotationButtonControllerTest : SysuiTestCase() { + + private lateinit var mController: RotationButtonController + + @Before + fun setUp() { + mController = RotationButtonController( + mContext, + /* lightIconColor = */ 0, + /* darkIconColor = */ 0, + /* iconCcwStart0ResId = */ 0, + /* iconCcwStart90ResId = */ 0, + /* iconCwStart0ResId = */ 0, + /* iconCwStart90ResId = */ 0 + ) { 0 } + } + + @Test + fun ifGestural_showRotationSuggestion() { + mController.onNavigationBarWindowVisibilityChange( /* showing = */ false) + mController.onBehaviorChanged(Display.DEFAULT_DISPLAY, + WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE) + mController.onNavigationModeChanged(WindowManagerPolicyConstants.NAV_BAR_MODE_3BUTTON) + mController.onTaskbarStateChange( /* visible = */ false, /* stashed = */ false) + assertThat(mController.canShowRotationButton()).isFalse() + + mController.onNavigationModeChanged(WindowManagerPolicyConstants.NAV_BAR_MODE_GESTURAL) + + assertThat(mController.canShowRotationButton()).isTrue() + } + + @Test + fun ifTaskbarVisible_showRotationSuggestion() { + mController.onNavigationBarWindowVisibilityChange( /* showing = */ false) + mController.onBehaviorChanged(Display.DEFAULT_DISPLAY, + WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE) + mController.onNavigationModeChanged(WindowManagerPolicyConstants.NAV_BAR_MODE_3BUTTON) + mController.onTaskbarStateChange( /* visible = */ false, /* stashed = */ false) + assertThat(mController.canShowRotationButton()).isFalse() + + mController.onTaskbarStateChange( /* visible = */ true, /* stashed = */ false) + + assertThat(mController.canShowRotationButton()).isTrue() + } +} diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/StatusBarStateControllerImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/StatusBarStateControllerImplTest.kt index be631afdd1a9..1d8e5dec5c50 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/StatusBarStateControllerImplTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/StatusBarStateControllerImplTest.kt @@ -38,8 +38,8 @@ import org.mockito.ArgumentMatchers.eq import org.mockito.Mock import org.mockito.Mockito.mock import org.mockito.Mockito.verify -import org.mockito.MockitoAnnotations import org.mockito.Mockito.`when` as whenever +import org.mockito.MockitoAnnotations @SmallTest @RunWith(AndroidTestingRunner::class) @@ -89,8 +89,8 @@ class StatusBarStateControllerImplTest : SysuiTestCase() { val listener = mock(StatusBarStateController.StateListener::class.java) controller.addCallback(listener) - controller.setDozeAmount(0.5f, false /* animated */) - controller.setDozeAmount(0.5f, false /* animated */) + controller.setAndInstrumentDozeAmount(null, 0.5f, false /* animated */) + controller.setAndInstrumentDozeAmount(null, 0.5f, false /* animated */) verify(listener).onDozeAmountChanged(eq(0.5f), anyFloat()) } @@ -135,7 +135,7 @@ class StatusBarStateControllerImplTest : SysuiTestCase() { @Test fun testSetDozeAmount_immediatelyChangesDozeAmount_lockscreenTransitionFromAod() { // Put controller in AOD state - controller.setDozeAmount(1f, false) + controller.setAndInstrumentDozeAmount(null, 1f, false) // When waking from doze, CentralSurfaces#updateDozingState will update the dozing state // before the doze amount changes diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ChannelEditorDialogControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ChannelEditorDialogControllerTest.kt index 214ba16dfc44..64d025628754 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ChannelEditorDialogControllerTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ChannelEditorDialogControllerTest.kt @@ -98,7 +98,7 @@ class ChannelEditorDialogControllerTest : SysuiTestCase() { @Test fun testPrepareDialogForApp_onlyDefaultChannel() { - group.channels = listOf(channelDefault) + group.addChannel(channelDefault) controller.prepareDialogForApp(TEST_APP_NAME, TEST_PACKAGE_NAME, TEST_UID, setOf(channelDefault), appIcon, clickListener) diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java index f8b39e8cff71..137842ef314f 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java @@ -28,7 +28,6 @@ import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; @@ -58,8 +57,8 @@ import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin; import com.android.systemui.plugins.statusbar.StatusBarStateController; import com.android.systemui.statusbar.notification.AboveShelfChangedListener; import com.android.systemui.statusbar.notification.FeedbackIcon; -import com.android.systemui.statusbar.notification.row.ExpandableView.OnHeightChangedListener; import com.android.systemui.statusbar.notification.collection.NotificationEntry; +import com.android.systemui.statusbar.notification.row.ExpandableView.OnHeightChangedListener; import com.android.systemui.statusbar.notification.stack.NotificationChildrenContainer; import org.junit.Assert; @@ -260,17 +259,6 @@ public class ExpandableNotificationRowTest extends SysuiTestCase { } @Test - public void setNeedsRedactionFreesViewWhenFalse() throws Exception { - ExpandableNotificationRow row = mNotificationTestHelper.createRow(FLAG_CONTENT_VIEW_ALL); - row.setNeedsRedaction(true); - row.getPublicLayout().setVisibility(View.GONE); - - row.setNeedsRedaction(false); - TestableLooper.get(this).processAllMessages(); - assertNull(row.getPublicLayout().getContractedChild()); - } - - @Test public void testAboveShelfChangedListenerCalled() throws Exception { ExpandableNotificationRow row = mNotificationTestHelper.createRow(); AboveShelfChangedListener listener = mock(AboveShelfChangedListener.class); diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardStatusBarViewControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardStatusBarViewControllerTest.java index 11e502fc79bf..6cf1a12d94f0 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardStatusBarViewControllerTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/KeyguardStatusBarViewControllerTest.java @@ -47,7 +47,6 @@ import com.android.keyguard.KeyguardUpdateMonitorCallback; import com.android.systemui.R; import com.android.systemui.SysuiTestCase; import com.android.systemui.battery.BatteryMeterViewController; -import com.android.systemui.flags.FeatureFlags; import com.android.systemui.plugins.statusbar.StatusBarStateController; import com.android.systemui.shade.NotificationPanelViewController; import com.android.systemui.statusbar.SysuiStatusBarStateController; @@ -89,7 +88,9 @@ public class KeyguardStatusBarViewControllerTest extends SysuiTestCase { @Mock private StatusBarIconController mStatusBarIconController; @Mock - private FeatureFlags mFeatureFlags; + private StatusBarIconController.TintedIconManager.Factory mIconManagerFactory; + @Mock + private StatusBarIconController.TintedIconManager mIconManager; @Mock private BatteryMeterViewController mBatteryMeterViewController; @Mock @@ -129,6 +130,8 @@ public class KeyguardStatusBarViewControllerTest extends SysuiTestCase { MockitoAnnotations.initMocks(this); + when(mIconManagerFactory.create(any())).thenReturn(mIconManager); + allowTestableLooperAsMainThread(); TestableLooper.get(this).runWithLooper(() -> { mKeyguardStatusBarView = @@ -148,7 +151,7 @@ public class KeyguardStatusBarViewControllerTest extends SysuiTestCase { mBatteryController, mUserInfoController, mStatusBarIconController, - new StatusBarIconController.TintedIconManager.Factory(mFeatureFlags), + mIconManagerFactory, mBatteryMeterViewController, mNotificationPanelViewStateProvider, mKeyguardStateController, diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarIconControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarIconControllerTest.java index 0f1c40bacb7b..a6b7e5103c78 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarIconControllerTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarIconControllerTest.java @@ -40,12 +40,16 @@ import com.android.systemui.statusbar.phone.StatusBarIconController.DarkIconMana import com.android.systemui.statusbar.phone.StatusBarIconController.IconManager; import com.android.systemui.statusbar.phone.StatusBarSignalPolicy.MobileIconState; import com.android.systemui.statusbar.phone.StatusBarSignalPolicy.WifiIconState; +import com.android.systemui.statusbar.pipeline.StatusBarPipelineFlags; +import com.android.systemui.statusbar.pipeline.wifi.ui.viewmodel.WifiViewModel; import com.android.systemui.utils.leaks.LeakCheckedTest; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import javax.inject.Provider; + @RunWith(AndroidTestingRunner.class) @RunWithLooper @SmallTest @@ -67,7 +71,11 @@ public class StatusBarIconControllerTest extends LeakCheckedTest { @Test public void testSetCalledOnAdd_DarkIconManager() { LinearLayout layout = new LinearLayout(mContext); - TestDarkIconManager manager = new TestDarkIconManager(layout, mock(FeatureFlags.class)); + TestDarkIconManager manager = new TestDarkIconManager( + layout, + mock(FeatureFlags.class), + mock(StatusBarPipelineFlags.class), + () -> mock(WifiViewModel.class)); testCallOnAdd_forManager(manager); } @@ -104,8 +112,12 @@ public class StatusBarIconControllerTest extends LeakCheckedTest { private static class TestDarkIconManager extends DarkIconManager implements TestableIconManager { - TestDarkIconManager(LinearLayout group, FeatureFlags featureFlags) { - super(group, featureFlags); + TestDarkIconManager( + LinearLayout group, + FeatureFlags featureFlags, + StatusBarPipelineFlags statusBarPipelineFlags, + Provider<WifiViewModel> wifiViewModelProvider) { + super(group, featureFlags, statusBarPipelineFlags, wifiViewModelProvider); } @Override @@ -123,7 +135,7 @@ public class StatusBarIconControllerTest extends LeakCheckedTest { } @Override - protected StatusBarWifiView addSignalIcon(int index, String slot, WifiIconState state) { + protected StatusBarWifiView addWifiIcon(int index, String slot, WifiIconState state) { StatusBarWifiView mock = mock(StatusBarWifiView.class); mGroup.addView(mock, index); return mock; @@ -140,7 +152,10 @@ public class StatusBarIconControllerTest extends LeakCheckedTest { private static class TestIconManager extends IconManager implements TestableIconManager { TestIconManager(ViewGroup group) { - super(group, mock(FeatureFlags.class)); + super(group, + mock(FeatureFlags.class), + mock(StatusBarPipelineFlags.class), + () -> mock(WifiViewModel.class)); } @Override @@ -158,7 +173,7 @@ public class StatusBarIconControllerTest extends LeakCheckedTest { } @Override - protected StatusBarWifiView addSignalIcon(int index, String slot, WifiIconState state) { + protected StatusBarWifiView addWifiIcon(int index, String slot, WifiIconState state) { StatusBarWifiView mock = mock(StatusBarWifiView.class); mGroup.addView(mock, index); return mock; diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java index de43a1fabab6..2b805089a430 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java @@ -37,7 +37,6 @@ import android.app.KeyguardManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; -import android.content.Intent; import android.os.Handler; import android.os.RemoteException; import android.os.UserHandle; @@ -135,8 +134,6 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase { @Mock private PendingIntent mContentIntent; @Mock - private Intent mContentIntentInner; - @Mock private OnUserInteractionCallback mOnUserInteractionCallback; @Mock private Runnable mFutureDismissalRunnable; @@ -159,7 +156,6 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase { MockitoAnnotations.initMocks(this); when(mContentIntent.isActivity()).thenReturn(true); when(mContentIntent.getCreatorUserHandle()).thenReturn(UserHandle.of(1)); - when(mContentIntent.getIntent()).thenReturn(mContentIntentInner); NotificationTestHelper notificationTestHelper = new NotificationTestHelper( mContext, @@ -374,7 +370,6 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase { eq(entry.getKey()), any(NotificationVisibility.class)); // The content intent should NOT be sent on click. - verify(mContentIntent).getIntent(); verify(mContentIntent).isActivity(); verifyNoMoreInteractions(mContentIntent); } diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java index 4c8599d99ddd..ceaceb4695b9 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragmentTest.java @@ -111,6 +111,10 @@ public class CollapsedStatusBarFragmentTest extends SysuiBaseFragmentTest { @Mock private NotificationPanelViewController mNotificationPanelViewController; @Mock + private StatusBarIconController.DarkIconManager.Factory mIconManagerFactory; + @Mock + private StatusBarIconController.DarkIconManager mIconManager; + @Mock private StatusBarHideIconsForBouncerManager mStatusBarHideIconsForBouncerManager; @Mock private DumpManager mDumpManager; @@ -424,6 +428,7 @@ public class CollapsedStatusBarFragmentTest extends SysuiBaseFragmentTest { mOperatorNameViewControllerFactory = mock(OperatorNameViewController.Factory.class); when(mOperatorNameViewControllerFactory.create(any())) .thenReturn(mOperatorNameViewController); + when(mIconManagerFactory.create(any())).thenReturn(mIconManager); mSecureSettings = mock(SecureSettings.class); setUpNotificationIconAreaController(); @@ -436,6 +441,7 @@ public class CollapsedStatusBarFragmentTest extends SysuiBaseFragmentTest { new PanelExpansionStateManager(), mock(FeatureFlags.class), mStatusBarIconController, + mIconManagerFactory, mStatusBarHideIconsForBouncerManager, mKeyguardStateController, mNotificationPanelViewController, diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/ConnectivityInfoProcessorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/ConnectivityInfoProcessorTest.kt deleted file mode 100644 index 7b492cb7ddd1..000000000000 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/ConnectivityInfoProcessorTest.kt +++ /dev/null @@ -1,88 +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.systemui.statusbar.pipeline - -import android.net.NetworkCapabilities -import android.testing.AndroidTestingRunner -import androidx.test.filters.SmallTest -import com.android.systemui.SysuiTestCase -import com.android.systemui.statusbar.pipeline.wifi.data.repository.NetworkCapabilityInfo -import com.android.systemui.util.mockito.mock -import com.google.common.truth.Truth.assertThat -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.CoroutineStart -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.InternalCoroutinesApi -import kotlinx.coroutines.cancel -import kotlinx.coroutines.flow.collect -import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.yield -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.Mockito.`when` as whenever - -@OptIn(InternalCoroutinesApi::class) -@SmallTest -@RunWith(AndroidTestingRunner::class) -class ConnectivityInfoProcessorTest : SysuiTestCase() { - - private val statusBarPipelineFlags = mock<StatusBarPipelineFlags>() - - @Before - fun setUp() { - whenever(statusBarPipelineFlags.isNewPipelineEnabled()).thenReturn(true) - } - - @Test - fun collectorInfoUpdated_processedInfoAlsoUpdated() = runBlocking { - // GIVEN a processor hooked up to a collector - val scope = CoroutineScope(Dispatchers.Unconfined) - val collector = FakeConnectivityInfoCollector() - val processor = ConnectivityInfoProcessor( - collector, - context, - scope, - statusBarPipelineFlags, - mock(), - ) - - var mostRecentValue: ProcessedConnectivityInfo? = null - val job = launch(start = CoroutineStart.UNDISPATCHED) { - processor.processedInfoFlow.collect { - mostRecentValue = it - } - } - - // WHEN the collector emits a value - val networkCapabilityInfo = mapOf( - 10 to NetworkCapabilityInfo(mock(), NetworkCapabilities.Builder().build()) - ) - collector.emitValue(RawConnectivityInfo(networkCapabilityInfo)) - // Because our job uses [CoroutineStart.UNDISPATCHED], it executes in the same thread as - // this test. So, our test needs to yield to let the job run. - // Note: Once we upgrade our Kotlin coroutines testing library, we won't need this. - yield() - - // THEN the processor receives it - assertThat(mostRecentValue?.networkCapabilityInfo).isEqualTo(networkCapabilityInfo) - - job.cancel() - scope.cancel() - } -} diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/FakeWifiRepository.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/FakeWifiRepository.kt index df389bc52664..6b8d4aa7c51f 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/FakeWifiRepository.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/FakeWifiRepository.kt @@ -17,21 +17,22 @@ package com.android.systemui.statusbar.pipeline.wifi.data.repository import com.android.systemui.statusbar.pipeline.wifi.data.model.WifiActivityModel -import com.android.systemui.statusbar.pipeline.wifi.data.model.WifiModel +import com.android.systemui.statusbar.pipeline.wifi.data.model.WifiNetworkModel import com.android.systemui.statusbar.pipeline.wifi.data.repository.WifiRepositoryImpl.Companion.ACTIVITY_DEFAULT import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow /** Fake implementation of [WifiRepository] exposing set methods for all the flows. */ class FakeWifiRepository : WifiRepository { - private val _wifiModel: MutableStateFlow<WifiModel?> = MutableStateFlow(null) - override val wifiModel: Flow<WifiModel?> = _wifiModel + private val _wifiNetwork: MutableStateFlow<WifiNetworkModel> = + MutableStateFlow(WifiNetworkModel.Inactive) + override val wifiNetwork: Flow<WifiNetworkModel> = _wifiNetwork private val _wifiActivity = MutableStateFlow(ACTIVITY_DEFAULT) override val wifiActivity: Flow<WifiActivityModel> = _wifiActivity - fun setWifiModel(wifiModel: WifiModel?) { - _wifiModel.value = wifiModel + fun setWifiNetwork(wifiNetworkModel: WifiNetworkModel) { + _wifiNetwork.value = wifiNetworkModel } fun setWifiActivity(activity: WifiActivityModel) { diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/NetworkCapabilitiesRepoTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/NetworkCapabilitiesRepoTest.kt deleted file mode 100644 index 6edf76ce77c9..000000000000 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/NetworkCapabilitiesRepoTest.kt +++ /dev/null @@ -1,252 +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.systemui.statusbar.pipeline.wifi.data.repository - -import android.net.ConnectivityManager -import android.net.ConnectivityManager.NetworkCallback -import android.net.Network -import android.net.NetworkCapabilities -import android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED -import android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED -import android.net.NetworkCapabilities.TRANSPORT_CELLULAR -import android.net.NetworkCapabilities.TRANSPORT_WIFI -import android.net.NetworkRequest -import android.test.suitebuilder.annotation.SmallTest -import android.testing.AndroidTestingRunner -import com.android.systemui.SysuiTestCase -import com.android.systemui.statusbar.pipeline.shared.ConnectivityPipelineLogger -import com.android.systemui.util.mockito.mock -import com.android.systemui.util.mockito.withArgCaptor -import com.google.common.truth.Truth.assertThat -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.CoroutineStart -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.cancel -import kotlinx.coroutines.flow.collect -import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.ArgumentMatchers.any -import org.mockito.Mock -import org.mockito.Mockito.verify -import org.mockito.Mockito.`when` as whenever -import org.mockito.MockitoAnnotations - -// TODO(b/240619365): Update this test to use `runTest` when we update the testing library -@SmallTest -@RunWith(AndroidTestingRunner::class) -class NetworkCapabilitiesRepoTest : SysuiTestCase() { - @Mock private lateinit var connectivityManager: ConnectivityManager - @Mock private lateinit var logger: ConnectivityPipelineLogger - - @Before - fun setup() { - MockitoAnnotations.initMocks(this) - } - - @Test - fun testOnCapabilitiesChanged_oneNewNetwork_networkStored() = runBlocking { - // GIVEN a repo hooked up to [ConnectivityManager] - val scope = CoroutineScope(Dispatchers.Unconfined) - val repo = NetworkCapabilitiesRepo( - connectivityManager = connectivityManager, - scope = scope, - logger = logger, - ) - - val job = launch(start = CoroutineStart.UNDISPATCHED) { - repo.dataStream.collect { - } - } - - val callback: NetworkCallback = withArgCaptor { - verify(connectivityManager) - .registerNetworkCallback(any(NetworkRequest::class.java), capture()) - } - - // WHEN a new network is added - callback.onCapabilitiesChanged(NET_1, NET_1_CAPS) - - val currentMap = repo.dataStream.value - - // THEN it is emitted from the flow - assertThat(currentMap[NET_1_ID]?.network).isEqualTo(NET_1) - assertThat(currentMap[NET_1_ID]?.capabilities).isEqualTo(NET_1_CAPS) - - job.cancel() - scope.cancel() - } - - @Test - fun testOnCapabilitiesChanged_twoNewNetworks_bothStored() = runBlocking { - // GIVEN a repo hooked up to [ConnectivityManager] - val scope = CoroutineScope(Dispatchers.Unconfined) - val repo = NetworkCapabilitiesRepo( - connectivityManager = connectivityManager, - scope = scope, - logger = logger, - ) - - val job = launch(start = CoroutineStart.UNDISPATCHED) { - repo.dataStream.collect { - } - } - - val callback: NetworkCallback = withArgCaptor { - verify(connectivityManager) - .registerNetworkCallback(any(NetworkRequest::class.java), capture()) - } - - // WHEN two new networks are added - callback.onCapabilitiesChanged(NET_1, NET_1_CAPS) - callback.onCapabilitiesChanged(NET_2, NET_2_CAPS) - - val currentMap = repo.dataStream.value - - // THEN the current state of the flow reflects 2 networks - assertThat(currentMap[NET_1_ID]?.network).isEqualTo(NET_1) - assertThat(currentMap[NET_1_ID]?.capabilities).isEqualTo(NET_1_CAPS) - assertThat(currentMap[NET_2_ID]?.network).isEqualTo(NET_2) - assertThat(currentMap[NET_2_ID]?.capabilities).isEqualTo(NET_2_CAPS) - - job.cancel() - scope.cancel() - } - - @Test - fun testOnCapabilitesChanged_newCapabilitiesForExistingNetwork_areCaptured() = runBlocking { - // GIVEN a repo hooked up to [ConnectivityManager] - val scope = CoroutineScope(Dispatchers.Unconfined) - val repo = NetworkCapabilitiesRepo( - connectivityManager = connectivityManager, - scope = scope, - logger = logger, - ) - - val job = launch(start = CoroutineStart.UNDISPATCHED) { - repo.dataStream.collect { - } - } - - val callback: NetworkCallback = withArgCaptor { - verify(connectivityManager) - .registerNetworkCallback(any(NetworkRequest::class.java), capture()) - } - - // WHEN a network is added, and then its capabilities are changed - callback.onCapabilitiesChanged(NET_1, NET_1_CAPS) - callback.onCapabilitiesChanged(NET_1, NET_2_CAPS) - - val currentMap = repo.dataStream.value - - // THEN the current state of the flow reflects the new capabilities - assertThat(currentMap[NET_1_ID]?.capabilities).isEqualTo(NET_2_CAPS) - - job.cancel() - scope.cancel() - } - - @Test - fun testOnLost_networkIsRemoved() = runBlocking { - // GIVEN a repo hooked up to [ConnectivityManager] - val scope = CoroutineScope(Dispatchers.Unconfined) - val repo = NetworkCapabilitiesRepo( - connectivityManager = connectivityManager, - scope = scope, - logger = logger, - ) - - val job = launch(start = CoroutineStart.UNDISPATCHED) { - repo.dataStream.collect { - } - } - - val callback: NetworkCallback = withArgCaptor { - verify(connectivityManager) - .registerNetworkCallback(any(NetworkRequest::class.java), capture()) - } - - // WHEN two new networks are added, and one is removed - callback.onCapabilitiesChanged(NET_1, NET_1_CAPS) - callback.onCapabilitiesChanged(NET_2, NET_2_CAPS) - callback.onLost(NET_1) - - val currentMap = repo.dataStream.value - - // THEN the current state of the flow reflects only the remaining network - assertThat(currentMap[NET_1_ID]).isNull() - assertThat(currentMap[NET_2_ID]?.network).isEqualTo(NET_2) - assertThat(currentMap[NET_2_ID]?.capabilities).isEqualTo(NET_2_CAPS) - - job.cancel() - scope.cancel() - } - - @Test - fun testOnLost_noNetworks_doesNotCrash() = runBlocking { - // GIVEN a repo hooked up to [ConnectivityManager] - val scope = CoroutineScope(Dispatchers.Unconfined) - val repo = NetworkCapabilitiesRepo( - connectivityManager = connectivityManager, - scope = scope, - logger = logger, - ) - - val job = launch(start = CoroutineStart.UNDISPATCHED) { - repo.dataStream.collect { - } - } - - val callback: NetworkCallback = withArgCaptor { - verify(connectivityManager) - .registerNetworkCallback(any(NetworkRequest::class.java), capture()) - } - - // WHEN no networks are added, and one is removed - callback.onLost(NET_1) - - val currentMap = repo.dataStream.value - - // THEN the current state of the flow shows no networks - assertThat(currentMap).isEmpty() - - job.cancel() - scope.cancel() - } - - private val NET_1_ID = 100 - private val NET_1 = mock<Network>().also { - whenever(it.getNetId()).thenReturn(NET_1_ID) - } - private val NET_2_ID = 200 - private val NET_2 = mock<Network>().also { - whenever(it.getNetId()).thenReturn(NET_2_ID) - } - - private val NET_1_CAPS = NetworkCapabilities.Builder() - .addTransportType(TRANSPORT_CELLULAR) - .addCapability(NET_CAPABILITY_VALIDATED) - .build() - - private val NET_2_CAPS = NetworkCapabilities.Builder() - .addTransportType(TRANSPORT_WIFI) - .addCapability(NET_CAPABILITY_NOT_METERED) - .addCapability(NET_CAPABILITY_VALIDATED) - .build() -} diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepositoryImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepositoryImplTest.kt index 8b61364a2ac9..d0a38084af76 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepositoryImplTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/data/repository/WifiRepositoryImplTest.kt @@ -16,16 +16,26 @@ package com.android.systemui.statusbar.pipeline.wifi.data.repository +import android.net.ConnectivityManager +import android.net.Network +import android.net.NetworkCapabilities +import android.net.NetworkCapabilities.TRANSPORT_CELLULAR +import android.net.NetworkCapabilities.TRANSPORT_WIFI +import android.net.vcn.VcnTransportInfo +import android.net.wifi.WifiInfo import android.net.wifi.WifiManager import android.net.wifi.WifiManager.TrafficStateCallback import androidx.test.filters.SmallTest import com.android.systemui.SysuiTestCase import com.android.systemui.statusbar.pipeline.shared.ConnectivityPipelineLogger import com.android.systemui.statusbar.pipeline.wifi.data.model.WifiActivityModel +import com.android.systemui.statusbar.pipeline.wifi.data.model.WifiNetworkModel import com.android.systemui.statusbar.pipeline.wifi.data.repository.WifiRepositoryImpl.Companion.ACTIVITY_DEFAULT +import com.android.systemui.statusbar.pipeline.wifi.data.repository.WifiRepositoryImpl.Companion.WIFI_NETWORK_DEFAULT import com.android.systemui.util.concurrency.FakeExecutor import com.android.systemui.util.mockito.any import com.android.systemui.util.mockito.argumentCaptor +import com.android.systemui.util.mockito.mock import com.android.systemui.util.time.FakeSystemClock import com.google.common.truth.Truth.assertThat import java.util.concurrent.Executor @@ -38,6 +48,7 @@ import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito.verify +import org.mockito.Mockito.`when` as whenever import org.mockito.MockitoAnnotations @OptIn(ExperimentalCoroutinesApi::class) @@ -47,6 +58,7 @@ class WifiRepositoryImplTest : SysuiTestCase() { private lateinit var underTest: WifiRepositoryImpl @Mock private lateinit var logger: ConnectivityPipelineLogger + @Mock private lateinit var connectivityManager: ConnectivityManager @Mock private lateinit var wifiManager: WifiManager private lateinit var executor: Executor @@ -54,11 +66,347 @@ class WifiRepositoryImplTest : SysuiTestCase() { fun setUp() { MockitoAnnotations.initMocks(this) executor = FakeExecutor(FakeSystemClock()) + + underTest = WifiRepositoryImpl( + connectivityManager, + wifiManager, + executor, + logger, + ) + } + + @Test + fun wifiNetwork_initiallyGetsDefault() = runBlocking(IMMEDIATE) { + var latest: WifiNetworkModel? = null + val job = underTest + .wifiNetwork + .onEach { latest = it } + .launchIn(this) + + assertThat(latest).isEqualTo(WIFI_NETWORK_DEFAULT) + + job.cancel() + } + + @Test + fun wifiNetwork_primaryWifiNetworkAdded_flowHasNetwork() = runBlocking(IMMEDIATE) { + var latest: WifiNetworkModel? = null + val job = underTest + .wifiNetwork + .onEach { latest = it } + .launchIn(this) + + val wifiInfo = mock<WifiInfo>().apply { + whenever(this.ssid).thenReturn(SSID) + whenever(this.isPrimary).thenReturn(true) + } + val network = mock<Network>().apply { + whenever(this.getNetId()).thenReturn(NETWORK_ID) + } + + getNetworkCallback().onCapabilitiesChanged(network, createWifiNetworkCapabilities(wifiInfo)) + + assertThat(latest is WifiNetworkModel.Active).isTrue() + val latestActive = latest as WifiNetworkModel.Active + assertThat(latestActive.networkId).isEqualTo(NETWORK_ID) + assertThat(latestActive.ssid).isEqualTo(SSID) + + job.cancel() + } + + @Test + fun wifiNetwork_nonPrimaryWifiNetworkAdded_flowHasNoNetwork() = runBlocking(IMMEDIATE) { + var latest: WifiNetworkModel? = null + val job = underTest + .wifiNetwork + .onEach { latest = it } + .launchIn(this) + + val wifiInfo = mock<WifiInfo>().apply { + whenever(this.ssid).thenReturn(SSID) + whenever(this.isPrimary).thenReturn(false) + } + + getNetworkCallback().onCapabilitiesChanged(NETWORK, createWifiNetworkCapabilities(wifiInfo)) + + assertThat(latest is WifiNetworkModel.Inactive).isTrue() + + job.cancel() + } + + @Test + fun wifiNetwork_cellularVcnNetworkAdded_flowHasNetwork() = runBlocking(IMMEDIATE) { + var latest: WifiNetworkModel? = null + val job = underTest + .wifiNetwork + .onEach { latest = it } + .launchIn(this) + + val capabilities = mock<NetworkCapabilities>().apply { + whenever(this.hasTransport(TRANSPORT_CELLULAR)).thenReturn(true) + whenever(this.transportInfo).thenReturn(VcnTransportInfo(PRIMARY_WIFI_INFO)) + } + + getNetworkCallback().onCapabilitiesChanged(NETWORK, capabilities) + + assertThat(latest is WifiNetworkModel.Active).isTrue() + val latestActive = latest as WifiNetworkModel.Active + assertThat(latestActive.networkId).isEqualTo(NETWORK_ID) + assertThat(latestActive.ssid).isEqualTo(SSID) + + job.cancel() + } + + @Test + fun wifiNetwork_nonPrimaryCellularVcnNetworkAdded_flowHasNoNetwork() = runBlocking(IMMEDIATE) { + var latest: WifiNetworkModel? = null + val job = underTest + .wifiNetwork + .onEach { latest = it } + .launchIn(this) + + val wifiInfo = mock<WifiInfo>().apply { + whenever(this.ssid).thenReturn(SSID) + whenever(this.isPrimary).thenReturn(false) + } + val capabilities = mock<NetworkCapabilities>().apply { + whenever(this.hasTransport(TRANSPORT_CELLULAR)).thenReturn(true) + whenever(this.transportInfo).thenReturn(VcnTransportInfo(wifiInfo)) + } + + getNetworkCallback().onCapabilitiesChanged(NETWORK, capabilities) + + assertThat(latest is WifiNetworkModel.Inactive).isTrue() + + job.cancel() + } + + @Test + fun wifiNetwork_cellularNotVcnNetworkAdded_flowHasNoNetwork() = runBlocking(IMMEDIATE) { + var latest: WifiNetworkModel? = null + val job = underTest + .wifiNetwork + .onEach { latest = it } + .launchIn(this) + + val capabilities = mock<NetworkCapabilities>().apply { + whenever(this.hasTransport(TRANSPORT_CELLULAR)).thenReturn(true) + whenever(this.transportInfo).thenReturn(mock()) + } + + getNetworkCallback().onCapabilitiesChanged(NETWORK, capabilities) + + assertThat(latest is WifiNetworkModel.Inactive).isTrue() + + job.cancel() + } + + @Test + fun wifiNetwork_newPrimaryWifiNetwork_flowHasNewNetwork() = runBlocking(IMMEDIATE) { + var latest: WifiNetworkModel? = null + val job = underTest + .wifiNetwork + .onEach { latest = it } + .launchIn(this) + + // Start with the original network + getNetworkCallback() + .onCapabilitiesChanged(NETWORK, createWifiNetworkCapabilities(PRIMARY_WIFI_INFO)) + + // WHEN we update to a new primary network + val newNetworkId = 456 + val newNetwork = mock<Network>().apply { + whenever(this.getNetId()).thenReturn(newNetworkId) + } + val newSsid = "CD" + val newWifiInfo = mock<WifiInfo>().apply { + whenever(this.ssid).thenReturn(newSsid) + whenever(this.isPrimary).thenReturn(true) + } + + getNetworkCallback().onCapabilitiesChanged( + newNetwork, createWifiNetworkCapabilities(newWifiInfo) + ) + + // THEN we use the new network + assertThat(latest is WifiNetworkModel.Active).isTrue() + val latestActive = latest as WifiNetworkModel.Active + assertThat(latestActive.networkId).isEqualTo(newNetworkId) + assertThat(latestActive.ssid).isEqualTo(newSsid) + + job.cancel() + } + + @Test + fun wifiNetwork_newNonPrimaryWifiNetwork_flowHasOldNetwork() = runBlocking(IMMEDIATE) { + var latest: WifiNetworkModel? = null + val job = underTest + .wifiNetwork + .onEach { latest = it } + .launchIn(this) + + // Start with the original network + getNetworkCallback() + .onCapabilitiesChanged(NETWORK, createWifiNetworkCapabilities(PRIMARY_WIFI_INFO)) + + // WHEN we notify of a new but non-primary network + val newNetworkId = 456 + val newNetwork = mock<Network>().apply { + whenever(this.getNetId()).thenReturn(newNetworkId) + } + val newSsid = "EF" + val newWifiInfo = mock<WifiInfo>().apply { + whenever(this.ssid).thenReturn(newSsid) + whenever(this.isPrimary).thenReturn(false) + } + + getNetworkCallback().onCapabilitiesChanged( + newNetwork, createWifiNetworkCapabilities(newWifiInfo) + ) + + // THEN we still use the original network + assertThat(latest is WifiNetworkModel.Active).isTrue() + val latestActive = latest as WifiNetworkModel.Active + assertThat(latestActive.networkId).isEqualTo(NETWORK_ID) + assertThat(latestActive.ssid).isEqualTo(SSID) + + job.cancel() + } + + @Test + fun wifiNetwork_newNetworkCapabilities_flowHasNewData() = runBlocking(IMMEDIATE) { + var latest: WifiNetworkModel? = null + val job = underTest + .wifiNetwork + .onEach { latest = it } + .launchIn(this) + + val wifiInfo = mock<WifiInfo>().apply { + whenever(this.ssid).thenReturn(SSID) + whenever(this.isPrimary).thenReturn(true) + } + + // Start with the original network + getNetworkCallback() + .onCapabilitiesChanged(NETWORK, createWifiNetworkCapabilities(wifiInfo)) + + // WHEN we keep the same network ID but change the SSID + val newSsid = "CD" + val newWifiInfo = mock<WifiInfo>().apply { + whenever(this.ssid).thenReturn(newSsid) + whenever(this.isPrimary).thenReturn(true) + } + + getNetworkCallback() + .onCapabilitiesChanged(NETWORK, createWifiNetworkCapabilities(newWifiInfo)) + + // THEN we've updated to the new SSID + assertThat(latest is WifiNetworkModel.Active).isTrue() + val latestActive = latest as WifiNetworkModel.Active + assertThat(latestActive.networkId).isEqualTo(NETWORK_ID) + assertThat(latestActive.ssid).isEqualTo(newSsid) + + job.cancel() + } + + @Test + fun wifiNetwork_noCurrentNetwork_networkLost_flowHasNoNetwork() = runBlocking(IMMEDIATE) { + var latest: WifiNetworkModel? = null + val job = underTest + .wifiNetwork + .onEach { latest = it } + .launchIn(this) + + // WHEN we receive #onLost without any #onCapabilitiesChanged beforehand + getNetworkCallback().onLost(NETWORK) + + // THEN there's no crash and we still have no network + assertThat(latest is WifiNetworkModel.Inactive).isTrue() + + job.cancel() + } + + @Test + fun wifiNetwork_currentNetworkLost_flowHasNoNetwork() = runBlocking(IMMEDIATE) { + var latest: WifiNetworkModel? = null + val job = underTest + .wifiNetwork + .onEach { latest = it } + .launchIn(this) + + getNetworkCallback() + .onCapabilitiesChanged(NETWORK, createWifiNetworkCapabilities(PRIMARY_WIFI_INFO)) + assertThat((latest as WifiNetworkModel.Active).networkId).isEqualTo(NETWORK_ID) + + // WHEN we lose our current network + getNetworkCallback().onLost(NETWORK) + + // THEN we update to no network + assertThat(latest is WifiNetworkModel.Inactive).isTrue() + + job.cancel() + } + + @Test + fun wifiNetwork_unknownNetworkLost_flowHasPreviousNetwork() = runBlocking(IMMEDIATE) { + var latest: WifiNetworkModel? = null + val job = underTest + .wifiNetwork + .onEach { latest = it } + .launchIn(this) + + getNetworkCallback() + .onCapabilitiesChanged(NETWORK, createWifiNetworkCapabilities(PRIMARY_WIFI_INFO)) + assertThat((latest as WifiNetworkModel.Active).networkId).isEqualTo(NETWORK_ID) + + // WHEN we lose an unknown network + val unknownNetwork = mock<Network>().apply { + whenever(this.getNetId()).thenReturn(543) + } + getNetworkCallback().onLost(unknownNetwork) + + // THEN we still have our previous network + assertThat(latest is WifiNetworkModel.Active).isTrue() + val latestActive = latest as WifiNetworkModel.Active + assertThat(latestActive.networkId).isEqualTo(NETWORK_ID) + assertThat(latestActive.ssid).isEqualTo(SSID) + + job.cancel() + } + + @Test + fun wifiNetwork_notCurrentNetworkLost_flowHasCurrentNetwork() = runBlocking(IMMEDIATE) { + var latest: WifiNetworkModel? = null + val job = underTest + .wifiNetwork + .onEach { latest = it } + .launchIn(this) + + getNetworkCallback() + .onCapabilitiesChanged(NETWORK, createWifiNetworkCapabilities(PRIMARY_WIFI_INFO)) + assertThat((latest as WifiNetworkModel.Active).networkId).isEqualTo(NETWORK_ID) + + // WHEN we update to a new network... + val newNetworkId = 89 + val newNetwork = mock<Network>().apply { + whenever(this.getNetId()).thenReturn(newNetworkId) + } + getNetworkCallback().onCapabilitiesChanged( + newNetwork, createWifiNetworkCapabilities(PRIMARY_WIFI_INFO) + ) + // ...and lose the old network + getNetworkCallback().onLost(NETWORK) + + // THEN we still have the new network + assertThat((latest as WifiNetworkModel.Active).networkId).isEqualTo(newNetworkId) + + job.cancel() } @Test fun wifiActivity_nullWifiManager_receivesDefault() = runBlocking(IMMEDIATE) { underTest = WifiRepositoryImpl( + connectivityManager, wifiManager = null, executor, logger, @@ -77,12 +425,6 @@ class WifiRepositoryImplTest : SysuiTestCase() { @Test fun wifiActivity_callbackGivesNone_activityFlowHasNone() = runBlocking(IMMEDIATE) { - underTest = WifiRepositoryImpl( - wifiManager, - executor, - logger, - ) - var latest: WifiActivityModel? = null val job = underTest .wifiActivity @@ -100,12 +442,6 @@ class WifiRepositoryImplTest : SysuiTestCase() { @Test fun wifiActivity_callbackGivesIn_activityFlowHasIn() = runBlocking(IMMEDIATE) { - underTest = WifiRepositoryImpl( - wifiManager, - executor, - logger, - ) - var latest: WifiActivityModel? = null val job = underTest .wifiActivity @@ -123,12 +459,6 @@ class WifiRepositoryImplTest : SysuiTestCase() { @Test fun wifiActivity_callbackGivesOut_activityFlowHasOut() = runBlocking(IMMEDIATE) { - underTest = WifiRepositoryImpl( - wifiManager, - executor, - logger, - ) - var latest: WifiActivityModel? = null val job = underTest .wifiActivity @@ -146,12 +476,6 @@ class WifiRepositoryImplTest : SysuiTestCase() { @Test fun wifiActivity_callbackGivesInout_activityFlowHasInAndOut() = runBlocking(IMMEDIATE) { - underTest = WifiRepositoryImpl( - wifiManager, - executor, - logger, - ) - var latest: WifiActivityModel? = null val job = underTest .wifiActivity @@ -170,6 +494,30 @@ class WifiRepositoryImplTest : SysuiTestCase() { verify(wifiManager).registerTrafficStateCallback(any(), callbackCaptor.capture()) return callbackCaptor.value!! } + + private fun getNetworkCallback(): ConnectivityManager.NetworkCallback { + val callbackCaptor = argumentCaptor<ConnectivityManager.NetworkCallback>() + verify(connectivityManager).registerNetworkCallback(any(), callbackCaptor.capture()) + return callbackCaptor.value!! + } + + private fun createWifiNetworkCapabilities(wifiInfo: WifiInfo) = + mock<NetworkCapabilities>().apply { + whenever(this.hasTransport(TRANSPORT_WIFI)).thenReturn(true) + whenever(this.transportInfo).thenReturn(wifiInfo) + } + + private companion object { + const val NETWORK_ID = 45 + val NETWORK = mock<Network>().apply { + whenever(this.getNetId()).thenReturn(NETWORK_ID) + } + const val SSID = "AB" + val PRIMARY_WIFI_INFO: WifiInfo = mock<WifiInfo>().apply { + whenever(this.ssid).thenReturn(SSID) + whenever(this.isPrimary).thenReturn(true) + } + } } private val IMMEDIATE = Dispatchers.Main.immediate diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/domain/interactor/WifiInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/domain/interactor/WifiInteractorTest.kt index c52f347a605a..5f1b1dbb19dc 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/domain/interactor/WifiInteractorTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/domain/interactor/WifiInteractorTest.kt @@ -19,7 +19,7 @@ package com.android.systemui.statusbar.pipeline.wifi.domain.interactor import androidx.test.filters.SmallTest import com.android.systemui.SysuiTestCase import com.android.systemui.statusbar.pipeline.wifi.data.model.WifiActivityModel -import com.android.systemui.statusbar.pipeline.wifi.data.model.WifiModel +import com.android.systemui.statusbar.pipeline.wifi.data.model.WifiNetworkModel import com.android.systemui.statusbar.pipeline.wifi.data.repository.FakeWifiRepository import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.Dispatchers @@ -47,7 +47,7 @@ class WifiInteractorTest : SysuiTestCase() { @Test fun hasActivityIn_noInOrOut_outputsFalse() = runBlocking(IMMEDIATE) { - repository.setWifiModel(WifiModel(ssid = "AB")) + repository.setWifiNetwork(VALID_WIFI_NETWORK_MODEL) repository.setWifiActivity(WifiActivityModel(hasActivityIn = false, hasActivityOut = false)) var latest: Boolean? = null @@ -63,7 +63,7 @@ class WifiInteractorTest : SysuiTestCase() { @Test fun hasActivityIn_onlyOut_outputsFalse() = runBlocking(IMMEDIATE) { - repository.setWifiModel(WifiModel(ssid = "AB")) + repository.setWifiNetwork(VALID_WIFI_NETWORK_MODEL) repository.setWifiActivity(WifiActivityModel(hasActivityIn = false, hasActivityOut = true)) var latest: Boolean? = null @@ -79,7 +79,7 @@ class WifiInteractorTest : SysuiTestCase() { @Test fun hasActivityIn_onlyIn_outputsTrue() = runBlocking(IMMEDIATE) { - repository.setWifiModel(WifiModel(ssid = "AB")) + repository.setWifiNetwork(VALID_WIFI_NETWORK_MODEL) repository.setWifiActivity(WifiActivityModel(hasActivityIn = true, hasActivityOut = false)) var latest: Boolean? = null @@ -95,7 +95,7 @@ class WifiInteractorTest : SysuiTestCase() { @Test fun hasActivityIn_inAndOut_outputsTrue() = runBlocking(IMMEDIATE) { - repository.setWifiModel(WifiModel(ssid = "AB")) + repository.setWifiNetwork(VALID_WIFI_NETWORK_MODEL) repository.setWifiActivity(WifiActivityModel(hasActivityIn = true, hasActivityOut = true)) var latest: Boolean? = null @@ -111,7 +111,7 @@ class WifiInteractorTest : SysuiTestCase() { @Test fun hasActivityIn_ssidNull_outputsFalse() = runBlocking(IMMEDIATE) { - repository.setWifiModel(WifiModel(ssid = null)) + repository.setWifiNetwork(WifiNetworkModel.Active(networkId = 1, ssid = null)) repository.setWifiActivity(WifiActivityModel(hasActivityIn = true, hasActivityOut = true)) var latest: Boolean? = null @@ -127,7 +127,7 @@ class WifiInteractorTest : SysuiTestCase() { @Test fun hasActivityIn_multipleChanges_multipleOutputChanges() = runBlocking(IMMEDIATE) { - repository.setWifiModel(WifiModel(ssid = "AB")) + repository.setWifiNetwork(VALID_WIFI_NETWORK_MODEL) var latest: Boolean? = null val job = underTest @@ -158,6 +158,10 @@ class WifiInteractorTest : SysuiTestCase() { job.cancel() } + + companion object { + val VALID_WIFI_NETWORK_MODEL = WifiNetworkModel.Active(networkId = 1, ssid = "AB") + } } private val IMMEDIATE = Dispatchers.Main.immediate diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/ui/view/ModernStatusBarWifiViewTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/ui/view/ModernStatusBarWifiViewTest.kt new file mode 100644 index 000000000000..3c200a5da4fa --- /dev/null +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/ui/view/ModernStatusBarWifiViewTest.kt @@ -0,0 +1,53 @@ +/* + * 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.systemui.statusbar.pipeline.wifi.ui.view + +import android.testing.TestableLooper.RunWithLooper +import androidx.test.filters.SmallTest +import com.android.systemui.SysuiTestCase +import com.android.systemui.lifecycle.InstantTaskExecutorRule +import com.android.systemui.util.Assert +import com.android.systemui.util.mockito.mock +import com.google.common.truth.Truth.assertThat +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +@SmallTest +@RunWith(JUnit4::class) +@RunWithLooper +class ModernStatusBarWifiViewTest : SysuiTestCase() { + + @JvmField @Rule + val instantTaskExecutor = InstantTaskExecutorRule() + + @Before + fun setUp() { + Assert.setTestThread(Thread.currentThread()) + } + + @Test + fun constructAndBind_hasCorrectSlot() { + val view = ModernStatusBarWifiView.constructAndBind( + context, "slotName", mock() + ) + + assertThat(view.slot).isEqualTo("slotName") + } +} diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/ui/viewmodel/WifiViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/ui/viewmodel/WifiViewModelTest.kt index e9259b071e0b..c79073409883 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/ui/viewmodel/WifiViewModelTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/wifi/ui/viewmodel/WifiViewModelTest.kt @@ -18,9 +18,10 @@ package com.android.systemui.statusbar.pipeline.wifi.ui.viewmodel import androidx.test.filters.SmallTest import com.android.systemui.SysuiTestCase +import com.android.systemui.statusbar.pipeline.StatusBarPipelineFlags import com.android.systemui.statusbar.pipeline.shared.ConnectivityPipelineLogger import com.android.systemui.statusbar.pipeline.wifi.data.model.WifiActivityModel -import com.android.systemui.statusbar.pipeline.wifi.data.model.WifiModel +import com.android.systemui.statusbar.pipeline.wifi.data.model.WifiNetworkModel import com.android.systemui.statusbar.pipeline.wifi.data.repository.FakeWifiRepository import com.android.systemui.statusbar.pipeline.wifi.domain.interactor.WifiInteractor import com.android.systemui.statusbar.pipeline.wifi.shared.WifiConstants @@ -43,6 +44,7 @@ class WifiViewModelTest : SysuiTestCase() { private lateinit var underTest: WifiViewModel + @Mock private lateinit var statusBarPipelineFlags: StatusBarPipelineFlags @Mock private lateinit var logger: ConnectivityPipelineLogger @Mock private lateinit var constants: WifiConstants private lateinit var repository: FakeWifiRepository @@ -55,13 +57,14 @@ class WifiViewModelTest : SysuiTestCase() { interactor = WifiInteractor(repository) underTest = WifiViewModel( - constants, - logger, - interactor + statusBarPipelineFlags, + constants, + logger, + interactor ) // Set up with a valid SSID - repository.setWifiModel(WifiModel(ssid = "AB")) + repository.setWifiNetwork(WifiNetworkModel.Active(networkId = 1, ssid = "AB")) } @Test diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/SysuiLifecycleTest.java b/packages/SystemUI/tests/src/com/android/systemui/util/SysuiLifecycleTest.java deleted file mode 100644 index 4f509eaaadde..000000000000 --- a/packages/SystemUI/tests/src/com/android/systemui/util/SysuiLifecycleTest.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright (C) 2018 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.systemui.util; - -import static androidx.lifecycle.Lifecycle.Event.ON_CREATE; -import static androidx.lifecycle.Lifecycle.Event.ON_DESTROY; -import static androidx.lifecycle.Lifecycle.Event.ON_PAUSE; -import static androidx.lifecycle.Lifecycle.Event.ON_RESUME; -import static androidx.lifecycle.Lifecycle.Event.ON_START; -import static androidx.lifecycle.Lifecycle.Event.ON_STOP; - -import static com.android.systemui.util.SysuiLifecycle.viewAttachLifecycle; - -import static com.google.common.truth.Truth.assertThat; - -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import android.testing.AndroidTestingRunner; -import android.testing.TestableLooper; -import android.testing.TestableLooper.RunWithLooper; -import android.testing.ViewUtils; -import android.view.View; - -import androidx.lifecycle.Lifecycle; -import androidx.lifecycle.LifecycleEventObserver; -import androidx.lifecycle.LifecycleOwner; -import androidx.test.filters.SmallTest; - -import com.android.systemui.SysuiTestCase; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -@RunWithLooper(setAsMainLooper = true) -@RunWith(AndroidTestingRunner.class) -@SmallTest -public class SysuiLifecycleTest extends SysuiTestCase { - - private View mView; - - @Before - public void setUp() { - mView = new View(mContext); - } - - @After - public void tearDown() { - if (mView.isAttachedToWindow()) { - ViewUtils.detachView(mView); - TestableLooper.get(this).processAllMessages(); - } - } - - @Test - public void testAttach() { - LifecycleEventObserver observer = mock(LifecycleEventObserver.class); - LifecycleOwner lifecycle = viewAttachLifecycle(mView); - lifecycle.getLifecycle().addObserver(observer); - - ViewUtils.attachView(mView); - TestableLooper.get(this).processAllMessages(); - - verify(observer).onStateChanged(eq(lifecycle), eq(ON_CREATE)); - verify(observer).onStateChanged(eq(lifecycle), eq(ON_START)); - verify(observer).onStateChanged(eq(lifecycle), eq(ON_RESUME)); - } - - @Test - public void testDetach() { - LifecycleEventObserver observer = mock(LifecycleEventObserver.class); - LifecycleOwner lifecycle = viewAttachLifecycle(mView); - lifecycle.getLifecycle().addObserver(observer); - - ViewUtils.attachView(mView); - TestableLooper.get(this).processAllMessages(); - - ViewUtils.detachView(mView); - TestableLooper.get(this).processAllMessages(); - - verify(observer).onStateChanged(eq(lifecycle), eq(ON_PAUSE)); - verify(observer).onStateChanged(eq(lifecycle), eq(ON_STOP)); - verify(observer).onStateChanged(eq(lifecycle), eq(ON_DESTROY)); - } - - @Test - public void testStateBeforeAttach() { - // WHEN a lifecycle is obtained from a view - LifecycleOwner lifecycle = viewAttachLifecycle(mView); - // THEN the lifecycle state should be INITIAZED - assertThat(lifecycle.getLifecycle().getCurrentState()).isEqualTo( - Lifecycle.State.INITIALIZED); - } - - @Test - public void testStateAfterAttach() { - // WHEN a lifecycle is obtained from a view - LifecycleOwner lifecycle = viewAttachLifecycle(mView); - // AND the view is attached - ViewUtils.attachView(mView); - TestableLooper.get(this).processAllMessages(); - // THEN the lifecycle state should be RESUMED - assertThat(lifecycle.getLifecycle().getCurrentState()).isEqualTo(Lifecycle.State.RESUMED); - } - - @Test - public void testStateAfterDetach() { - // WHEN a lifecycle is obtained from a view - LifecycleOwner lifecycle = viewAttachLifecycle(mView); - // AND the view is detached - ViewUtils.attachView(mView); - TestableLooper.get(this).processAllMessages(); - ViewUtils.detachView(mView); - TestableLooper.get(this).processAllMessages(); - // THEN the lifecycle state should be DESTROYED - assertThat(lifecycle.getLifecycle().getCurrentState()).isEqualTo(Lifecycle.State.DESTROYED); - } - - @Test - public void testStateAfterReattach() { - // WHEN a lifecycle is obtained from a view - LifecycleOwner lifecycle = viewAttachLifecycle(mView); - // AND the view is re-attached - ViewUtils.attachView(mView); - TestableLooper.get(this).processAllMessages(); - ViewUtils.detachView(mView); - TestableLooper.get(this).processAllMessages(); - ViewUtils.attachView(mView); - TestableLooper.get(this).processAllMessages(); - // THEN the lifecycle state should still be DESTROYED, err RESUMED? - assertThat(lifecycle.getLifecycle().getCurrentState()).isEqualTo(Lifecycle.State.RESUMED); - } - - @Test - public void testStateWhenViewAlreadyAttached() { - // GIVEN that a view is already attached - ViewUtils.attachView(mView); - TestableLooper.get(this).processAllMessages(); - // WHEN a lifecycle is obtained from a view - LifecycleOwner lifecycle = viewAttachLifecycle(mView); - // THEN the lifecycle state should be RESUMED - assertThat(lifecycle.getLifecycle().getCurrentState()).isEqualTo(Lifecycle.State.RESUMED); - } - - @Test - public void testStateWhenViewAlreadyDetached() { - // GIVEN that a view is already detached - ViewUtils.attachView(mView); - TestableLooper.get(this).processAllMessages(); - ViewUtils.detachView(mView); - TestableLooper.get(this).processAllMessages(); - // WHEN a lifecycle is obtained from a view - LifecycleOwner lifecycle = viewAttachLifecycle(mView); - // THEN the lifecycle state should be INITIALIZED - assertThat(lifecycle.getLifecycle().getCurrentState()).isEqualTo( - Lifecycle.State.INITIALIZED); - } -} diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/kotlin/IpcSerializerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/util/kotlin/IpcSerializerTest.kt new file mode 100644 index 000000000000..15ba67205034 --- /dev/null +++ b/packages/SystemUI/tests/src/com/android/systemui/util/kotlin/IpcSerializerTest.kt @@ -0,0 +1,71 @@ +/* + * 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.systemui.util.kotlin + +import android.testing.AndroidTestingRunner +import androidx.test.filters.SmallTest +import com.android.systemui.SysuiTestCase +import java.util.concurrent.atomic.AtomicLong +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withContext +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +@SmallTest +@RunWith(AndroidTestingRunner::class) +class IpcSerializerTest : SysuiTestCase() { + + private val serializer = IpcSerializer() + + @Test + fun serializeManyIncomingIpcs(): Unit = runBlocking(Dispatchers.Main.immediate) { + val processor = launch(start = CoroutineStart.LAZY) { serializer.process() } + withContext(Dispatchers.IO) { + val lastEvaluatedTime = AtomicLong(System.currentTimeMillis()) + // First, launch many serialization requests in parallel + repeat(100_000) { + launch(Dispatchers.Unconfined) { + val enqueuedTime = System.currentTimeMillis() + serializer.runSerialized { + val last = lastEvaluatedTime.getAndSet(enqueuedTime) + assertTrue( + "expected $last less than or equal to $enqueuedTime ", + last <= enqueuedTime, + ) + } + } + } + // Then, process them all in the order they came in. + processor.start() + } + // All done, stop processing + processor.cancel() + } + + @Test(timeout = 5000) + fun serializeOnOneThread_doesNotDeadlock() = runBlocking { + val job = launch { serializer.process() } + repeat(100) { + serializer.runSerializedBlocking { } + } + job.cancel() + } +} diff --git a/packages/SystemUI/tests/src/com/android/systemui/wmshell/BubblesTest.java b/packages/SystemUI/tests/src/com/android/systemui/wmshell/BubblesTest.java index 8f2b715ba051..5d63632725c2 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/wmshell/BubblesTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/wmshell/BubblesTest.java @@ -135,6 +135,7 @@ import com.android.wm.shell.common.SyncTransactionQueue; import com.android.wm.shell.common.TaskStackListenerImpl; import com.android.wm.shell.draganddrop.DragAndDropController; import com.android.wm.shell.onehanded.OneHandedController; +import com.android.wm.shell.sysui.ShellCommandHandler; import com.android.wm.shell.sysui.ShellController; import com.android.wm.shell.sysui.ShellInit; @@ -225,6 +226,8 @@ public class BubblesTest extends SysuiTestCase { @Mock private ShellInit mShellInit; @Mock + private ShellCommandHandler mShellCommandHandler; + @Mock private ShellController mShellController; @Mock private Bubbles.BubbleExpandListener mBubbleExpandListener; @@ -349,6 +352,7 @@ public class BubblesTest extends SysuiTestCase { mBubbleController = new TestableBubbleController( mContext, mShellInit, + mShellCommandHandler, mShellController, mBubbleData, mFloatingContentCoordinator, @@ -389,7 +393,6 @@ public class BubblesTest extends SysuiTestCase { mCommonNotifCollection, mNotifPipeline, mSysUiState, - mDumpManager, syncExecutor); mBubblesManager.addNotifCallback(mNotifCallback); @@ -1395,6 +1398,33 @@ public class BubblesTest extends SysuiTestCase { assertThat(stackView.getVisibility()).isEqualTo(View.VISIBLE); } + /** + * Test to verify behavior for following situation: + * <ul> + * <li>status bar shade state is set to <code>false</code></li> + * <li>there is a bubble pending to be expanded</li> + * </ul> + * Test that duplicate status bar state updates to <code>false</code> do not clear the + * pending bubble to be + * expanded. + */ + @Test + public void testOnStatusBarStateChanged_statusBarChangeDoesNotClearExpandingBubble() { + mBubbleController.updateBubble(mBubbleEntry); + mBubbleController.onStatusBarStateChanged(false); + // Set the bubble to expand once status bar state changes + mBubbleController.expandStackAndSelectBubble(mBubbleEntry); + // Check that stack is currently collapsed + assertStackCollapsed(); + // Post status bar state change update with the same value + mBubbleController.onStatusBarStateChanged(false); + // Stack should remain collapsedb + assertStackCollapsed(); + // Post status bar state change which should trigger bubble to expand + mBubbleController.onStatusBarStateChanged(true); + assertStackExpanded(); + } + @Test public void testSetShouldAutoExpand_notifiesFlagChanged() { mBubbleController.updateBubble(mBubbleEntry); diff --git a/packages/SystemUI/tests/src/com/android/systemui/wmshell/TestableBubbleController.java b/packages/SystemUI/tests/src/com/android/systemui/wmshell/TestableBubbleController.java index 880ad187f910..6357a09eb196 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/wmshell/TestableBubbleController.java +++ b/packages/SystemUI/tests/src/com/android/systemui/wmshell/TestableBubbleController.java @@ -38,6 +38,7 @@ import com.android.wm.shell.common.SyncTransactionQueue; import com.android.wm.shell.common.TaskStackListenerImpl; import com.android.wm.shell.draganddrop.DragAndDropController; import com.android.wm.shell.onehanded.OneHandedController; +import com.android.wm.shell.sysui.ShellCommandHandler; import com.android.wm.shell.sysui.ShellController; import com.android.wm.shell.sysui.ShellInit; @@ -51,6 +52,7 @@ public class TestableBubbleController extends BubbleController { // Let's assume surfaces can be synchronized immediately. TestableBubbleController(Context context, ShellInit shellInit, + ShellCommandHandler shellCommandHandler, ShellController shellController, BubbleData data, FloatingContentCoordinator floatingContentCoordinator, @@ -71,12 +73,12 @@ public class TestableBubbleController extends BubbleController { Handler shellMainHandler, TaskViewTransitions taskViewTransitions, SyncTransactionQueue syncQueue) { - super(context, shellInit, shellController, data, Runnable::run, floatingContentCoordinator, - dataRepository, statusBarService, windowManager, windowManagerShellWrapper, - userManager, launcherApps, bubbleLogger, taskStackListener, shellTaskOrganizer, - positioner, displayController, oneHandedOptional, dragAndDropController, - shellMainExecutor, shellMainHandler, new SyncExecutor(), taskViewTransitions, - syncQueue); + super(context, shellInit, shellCommandHandler, shellController, data, Runnable::run, + floatingContentCoordinator, dataRepository, statusBarService, windowManager, + windowManagerShellWrapper, userManager, launcherApps, bubbleLogger, + taskStackListener, shellTaskOrganizer, positioner, displayController, + oneHandedOptional, dragAndDropController, shellMainExecutor, shellMainHandler, + new SyncExecutor(), taskViewTransitions, syncQueue); setInflateSynchronously(true); onInit(); } diff --git a/packages/SystemUI/tests/src/com/android/systemui/wmshell/WMShellTest.java b/packages/SystemUI/tests/src/com/android/systemui/wmshell/WMShellTest.java index 9c2136675dfa..da33fa62a9ab 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/wmshell/WMShellTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/wmshell/WMShellTest.java @@ -28,10 +28,10 @@ import com.android.systemui.SysuiTestCase; import com.android.systemui.keyguard.ScreenLifecycle; import com.android.systemui.keyguard.WakefulnessLifecycle; import com.android.systemui.model.SysUiState; +import com.android.systemui.settings.UserTracker; import com.android.systemui.statusbar.CommandQueue; import com.android.systemui.statusbar.policy.ConfigurationController; import com.android.systemui.statusbar.policy.KeyguardStateController; -import com.android.systemui.statusbar.policy.UserInfoController; import com.android.systemui.tracing.ProtoTracer; import com.android.wm.shell.common.ShellExecutor; import com.android.wm.shell.onehanded.OneHanded; @@ -72,7 +72,7 @@ public class WMShellTest extends SysuiTestCase { @Mock OneHanded mOneHanded; @Mock WakefulnessLifecycle mWakefulnessLifecycle; @Mock ProtoTracer mProtoTracer; - @Mock UserInfoController mUserInfoController; + @Mock UserTracker mUserTracker; @Mock ShellExecutor mSysUiMainExecutor; @Before @@ -83,7 +83,7 @@ public class WMShellTest extends SysuiTestCase { Optional.of(mSplitScreen), Optional.of(mOneHanded), mCommandQueue, mConfigurationController, mKeyguardStateController, mKeyguardUpdateMonitor, mScreenLifecycle, mSysUiState, mProtoTracer, mWakefulnessLifecycle, - mUserInfoController, mSysUiMainExecutor); + mUserTracker, mSysUiMainExecutor); } @Test diff --git a/services/OWNERS b/services/OWNERS index 67cee5517913..495c0737e599 100644 --- a/services/OWNERS +++ b/services/OWNERS @@ -1,4 +1,4 @@ -per-file Android.bp = file:platform/build/soong:/OWNERS +per-file Android.bp = file:platform/build/soong:/OWNERS #{LAST_RESORT_SUGGESTION} # art-team@ manages the system server profile per-file art-profile* = calin@google.com, ngeoffray@google.com, vmarko@google.com diff --git a/services/api/OWNERS b/services/api/OWNERS index a6093900c635..e10440c1aed5 100644 --- a/services/api/OWNERS +++ b/services/api/OWNERS @@ -1,4 +1,4 @@ -per-file Android.bp = file:platform/build/soong:/OWNERS +per-file Android.bp = file:platform/build/soong:/OWNERS #{LAST_RESORT_SUGGESTION} # API changes are managed via Prolog rules, not OWNERS * diff --git a/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java b/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java index fa043f8e02af..265fbc510259 100644 --- a/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java +++ b/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java @@ -17,7 +17,6 @@ package com.android.server.companion; -import static android.Manifest.permission.DELIVER_COMPANION_MESSAGES; import static android.Manifest.permission.MANAGE_COMPANION_DEVICES; import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE; import static android.content.pm.PackageManager.CERT_INPUT_SHA256; @@ -88,7 +87,6 @@ import android.os.SystemProperties; import android.os.UserHandle; import android.os.UserManager; import android.util.ArraySet; -import android.util.Base64; import android.util.ExceptionUtils; import android.util.Log; import android.util.Slog; @@ -756,6 +754,11 @@ public class CompanionDeviceManagerService extends SystemService { mDevicePresenceMonitor.onSelfManagedDeviceDisconnected(associationId); } + @Override + public boolean isCompanionApplicationBound(String packageName, int userId) { + return mCompanionAppController.isCompanionApplicationBound(userId, packageName); + } + private void registerDevicePresenceListenerActive(String packageName, String deviceAddress, boolean active) throws RemoteException { if (DEBUG) { diff --git a/services/core/java/com/android/server/BootReceiver.java b/services/core/java/com/android/server/BootReceiver.java index b8815454cadb..b33d84c0f275 100644 --- a/services/core/java/com/android/server/BootReceiver.java +++ b/services/core/java/com/android/server/BootReceiver.java @@ -16,6 +16,7 @@ package com.android.server; +import static android.os.ParcelFileDescriptor.MODE_READ_WRITE; import static android.system.OsConstants.O_RDONLY; import android.content.BroadcastReceiver; @@ -26,8 +27,10 @@ import android.os.DropBoxManager; import android.os.Environment; import android.os.FileUtils; import android.os.MessageQueue.OnFileDescriptorEventListener; +import android.os.ParcelFileDescriptor; import android.os.RecoverySystem; import android.os.SystemProperties; +import android.os.TombstoneWithHeadersProto; import android.provider.Downloads; import android.system.ErrnoException; import android.system.Os; @@ -38,6 +41,7 @@ import android.util.Slog; import android.util.TypedXmlPullParser; import android.util.TypedXmlSerializer; import android.util.Xml; +import android.util.proto.ProtoOutputStream; import com.android.internal.annotations.VisibleForTesting; import com.android.internal.logging.MetricsLogger; @@ -54,6 +58,8 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.attribute.PosixFilePermissions; import java.util.HashMap; import java.util.Iterator; import java.util.regex.Matcher; @@ -78,6 +84,11 @@ public class BootReceiver extends BroadcastReceiver { private static final String TAG_TOMBSTONE = "SYSTEM_TOMBSTONE"; private static final String TAG_TOMBSTONE_PROTO = "SYSTEM_TOMBSTONE_PROTO"; + private static final String TAG_TOMBSTONE_PROTO_WITH_HEADERS = + "SYSTEM_TOMBSTONE_PROTO_WITH_HEADERS"; + + // Directory to store temporary tombstones. + private static final File TOMBSTONE_TMP_DIR = new File("/data/tombstones"); // The pre-froyo package and class of the system updater, which // ran in the system process. We need to remove its packages here @@ -329,7 +340,44 @@ public class BootReceiver extends BroadcastReceiver { try { if (proto) { if (recordFileTimestamp(tombstone, timestamps)) { - db.addFile(TAG_TOMBSTONE_PROTO, tombstone, 0); + // We need to attach the count indicating the number of dropped dropbox entries + // due to rate limiting. Do this by enclosing the proto tombsstone in a + // container proto that has the dropped entry count and the proto tombstone as + // bytes (to avoid the complexity of reading and writing nested protos). + + // Read the proto tombstone file as bytes. + final byte[] tombstoneBytes = Files.readAllBytes(tombstone.toPath()); + + final File tombstoneProtoWithHeaders = File.createTempFile( + tombstone.getName(), ".tmp", TOMBSTONE_TMP_DIR); + Files.setPosixFilePermissions( + tombstoneProtoWithHeaders.toPath(), + PosixFilePermissions.fromString("rw-rw----")); + + // Write the new proto container proto with headers. + ParcelFileDescriptor pfd; + try { + pfd = ParcelFileDescriptor.open(tombstoneProtoWithHeaders, MODE_READ_WRITE); + + ProtoOutputStream protoStream = new ProtoOutputStream( + pfd.getFileDescriptor()); + protoStream.write(TombstoneWithHeadersProto.TOMBSTONE, tombstoneBytes); + protoStream.write( + TombstoneWithHeadersProto.DROPPED_COUNT, + rateLimitResult.droppedCountSinceRateLimitActivated()); + protoStream.flush(); + + // Add the proto to dropbox. + db.addFile(TAG_TOMBSTONE_PROTO_WITH_HEADERS, tombstoneProtoWithHeaders, 0); + } catch (FileNotFoundException ex) { + Slog.e(TAG, "failed to open for write: " + tombstoneProtoWithHeaders, ex); + throw ex; + } finally { + // Remove the temporary file. + if (tombstoneProtoWithHeaders != null) { + tombstoneProtoWithHeaders.delete(); + } + } } } else { // Add the header indicating how many events have been dropped due to rate limiting. diff --git a/services/core/java/com/android/server/TelephonyRegistry.java b/services/core/java/com/android/server/TelephonyRegistry.java index 0b858cf38d44..f7833b0f36fd 100644 --- a/services/core/java/com/android/server/TelephonyRegistry.java +++ b/services/core/java/com/android/server/TelephonyRegistry.java @@ -339,7 +339,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub { private int[] mDataConnectionNetworkType; - private ArrayList<List<CellInfo>> mCellInfo = null; + private ArrayList<List<CellInfo>> mCellInfo; private Map<Integer, List<EmergencyNumber>> mEmergencyNumberList; @@ -725,7 +725,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub { mMessageWaiting[i] = false; mCallForwarding[i] = false; mCellIdentity[i] = null; - mCellInfo.add(i, null); + mCellInfo.add(i, Collections.EMPTY_LIST); mImsReasonInfo.add(i, null); mSrvccState[i] = TelephonyManager.SRVCC_STATE_HANDOVER_NONE; mCallDisconnectCause[i] = DisconnectCause.NOT_VALID; @@ -802,7 +802,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub { mCallNetworkType = new int[numPhones]; mCallAttributes = new CallAttributes[numPhones]; mPreciseDataConnectionStates = new ArrayList<>(); - mCellInfo = new ArrayList<>(); + mCellInfo = new ArrayList<>(numPhones); mImsReasonInfo = new ArrayList<>(); mEmergencyNumberList = new HashMap<>(); mOutgoingCallEmergencyNumber = new EmergencyNumber[numPhones]; @@ -832,7 +832,7 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub { mMessageWaiting[i] = false; mCallForwarding[i] = false; mCellIdentity[i] = null; - mCellInfo.add(i, null); + mCellInfo.add(i, Collections.EMPTY_LIST); mImsReasonInfo.add(i, null); mSrvccState[i] = TelephonyManager.SRVCC_STATE_HANDOVER_NONE; mCallDisconnectCause[i] = DisconnectCause.NOT_VALID; @@ -1803,10 +1803,17 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub { if (!checkNotifyPermission("notifyCellInfoForSubscriber()")) { return; } + if (VDBG) { log("notifyCellInfoForSubscriber: subId=" + subId + " cellInfo=" + cellInfo); } + + if (cellInfo == null) { + loge("notifyCellInfoForSubscriber() received a null list"); + cellInfo = Collections.EMPTY_LIST; + } + int phoneId = getPhoneIdFromSubId(subId); synchronized (mRecords) { if (validatePhoneId(phoneId)) { @@ -2987,8 +2994,8 @@ public class TelephonyRegistry extends ITelephonyRegistry.Stub { pw.println("mBarringInfo=" + mBarringInfo.get(i)); pw.println("mCarrierNetworkChangeState=" + mCarrierNetworkChangeState[i]); pw.println("mTelephonyDisplayInfo=" + mTelephonyDisplayInfos[i]); - pw.println("mIsDataEnabled=" + mIsDataEnabled); - pw.println("mDataEnabledReason=" + mDataEnabledReason); + pw.println("mIsDataEnabled=" + mIsDataEnabled[i]); + pw.println("mDataEnabledReason=" + mDataEnabledReason[i]); pw.println("mAllowedNetworkTypeReason=" + mAllowedNetworkTypeReason[i]); pw.println("mAllowedNetworkTypeValue=" + mAllowedNetworkTypeValue[i]); pw.println("mPhysicalChannelConfigs=" + mPhysicalChannelConfigs.get(i)); diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java index 297e6a2c5fc7..a0c2ad57241b 100644 --- a/services/core/java/com/android/server/am/ActivityManagerService.java +++ b/services/core/java/com/android/server/am/ActivityManagerService.java @@ -454,6 +454,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.concurrent.CopyOnWriteArrayList; @@ -2400,13 +2401,13 @@ public class ActivityManagerService extends IActivityManager.Stub mEnableOffloadQueue = SystemProperties.getBoolean( "persist.device_config.activity_manager_native_boot.offload_queue_enabled", true); - mFgBroadcastQueue = new BroadcastQueue(this, mHandler, + mFgBroadcastQueue = new BroadcastQueueImpl(this, mHandler, "foreground", foreConstants, false); - mBgBroadcastQueue = new BroadcastQueue(this, mHandler, + mBgBroadcastQueue = new BroadcastQueueImpl(this, mHandler, "background", backConstants, true); - mBgOffloadBroadcastQueue = new BroadcastQueue(this, mHandler, + mBgOffloadBroadcastQueue = new BroadcastQueueImpl(this, mHandler, "offload_bg", offloadConstants, true); - mFgOffloadBroadcastQueue = new BroadcastQueue(this, mHandler, + mFgOffloadBroadcastQueue = new BroadcastQueueImpl(this, mHandler, "offload_fg", foreConstants, true); mBroadcastQueues[0] = mFgBroadcastQueue; mBroadcastQueues[1] = mBgBroadcastQueue; @@ -5501,7 +5502,7 @@ public class ActivityManagerService extends IActivityManager.Stub IIntentSender pendingResult, int matchFlags) { enforceCallingPermission(Manifest.permission.GET_INTENT_SENDER_INTENT, "queryIntentComponentsForIntentSender()"); - Preconditions.checkNotNull(pendingResult); + Objects.requireNonNull(pendingResult); final PendingIntentRecord res; try { res = (PendingIntentRecord) pendingResult; @@ -5513,17 +5514,19 @@ public class ActivityManagerService extends IActivityManager.Stub return null; } final int userId = res.key.userId; + final int uid = res.uid; + final String resolvedType = res.key.requestResolvedType; switch (res.key.type) { case ActivityManager.INTENT_SENDER_ACTIVITY: - return new ParceledListSlice<>(mContext.getPackageManager() - .queryIntentActivitiesAsUser(intent, matchFlags, userId)); + return new ParceledListSlice<>(mPackageManagerInt.queryIntentActivities( + intent, resolvedType, matchFlags, uid, userId)); case ActivityManager.INTENT_SENDER_SERVICE: case ActivityManager.INTENT_SENDER_FOREGROUND_SERVICE: - return new ParceledListSlice<>(mContext.getPackageManager() - .queryIntentServicesAsUser(intent, matchFlags, userId)); + return new ParceledListSlice<>(mPackageManagerInt.queryIntentServices( + intent, matchFlags, uid, userId)); case ActivityManager.INTENT_SENDER_BROADCAST: - return new ParceledListSlice<>(mContext.getPackageManager() - .queryBroadcastReceiversAsUser(intent, matchFlags, userId)); + return new ParceledListSlice<>(mPackageManagerInt.queryIntentReceivers( + intent, resolvedType, matchFlags, uid, userId, false)); default: // ActivityManager.INTENT_SENDER_ACTIVITY_RESULT throw new IllegalStateException("Unsupported intent sender type: " + res.key.type); } @@ -10623,8 +10626,7 @@ public class ActivityManagerService extends IActivityManager.Stub if (!onlyHistory && !onlyReceivers && dumpAll) { pw.println(); for (BroadcastQueue queue : mBroadcastQueues) { - pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]=" - + queue.mBroadcastsScheduled); + pw.println(" Queue " + queue.toString() + ": " + queue.describeState()); } pw.println(" mHandler:"); mHandler.dump(new PrintWriterPrinter(pw), " "); @@ -13079,17 +13081,23 @@ public class ActivityManagerService extends IActivityManager.Stub } boolean isPendingBroadcastProcessLocked(int pid) { - return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid) - || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid) - || mBgOffloadBroadcastQueue.isPendingBroadcastProcessLocked(pid) - || mFgOffloadBroadcastQueue.isPendingBroadcastProcessLocked(pid); + for (BroadcastQueue queue : mBroadcastQueues) { + BroadcastRecord r = queue.getPendingBroadcastLocked(); + if (r != null && r.curApp.getPid() == pid) { + return true; + } + } + return false; } boolean isPendingBroadcastProcessLocked(ProcessRecord app) { - return mFgBroadcastQueue.isPendingBroadcastProcessLocked(app) - || mBgBroadcastQueue.isPendingBroadcastProcessLocked(app) - || mBgOffloadBroadcastQueue.isPendingBroadcastProcessLocked(app) - || mFgOffloadBroadcastQueue.isPendingBroadcastProcessLocked(app); + for (BroadcastQueue queue : mBroadcastQueues) { + BroadcastRecord r = queue.getPendingBroadcastLocked(); + if (r != null && r.curApp == app) { + return true; + } + } + return false; } void skipPendingBroadcastLocked(int pid) { @@ -13111,7 +13119,6 @@ public class ActivityManagerService extends IActivityManager.Stub void updateUidReadyForBootCompletedBroadcastLocked(int uid) { for (BroadcastQueue queue : mBroadcastQueues) { queue.updateUidReadyForBootCompletedBroadcastLocked(uid); - queue.scheduleBroadcastsLocked(); } } @@ -13361,8 +13368,7 @@ public class ActivityManagerService extends IActivityManager.Stub receivers, null, 0, null, null, false, true, true, -1, false, null, false /* only PRE_BOOT_COMPLETED should be exempt, no stickies */, null /* filterExtrasForReceiver */); - queue.enqueueParallelBroadcastLocked(r); - queue.scheduleBroadcastsLocked(); + queue.enqueueBroadcastLocked(r); } } @@ -14240,13 +14246,7 @@ public class ActivityManagerService extends IActivityManager.Stub sticky, false, userId, allowBackgroundActivityStarts, backgroundActivityStartsToken, timeoutExempt, filterExtrasForReceiver); if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing parallel broadcast " + r); - final boolean replaced = replacePending - && (queue.replaceParallelBroadcastLocked(r) != null); - // Note: We assume resultTo is null for non-ordered broadcasts. - if (!replaced) { - queue.enqueueParallelBroadcastLocked(r); - queue.scheduleBroadcastsLocked(); - } + queue.enqueueBroadcastLocked(r); registeredReceivers = null; NR = 0; } @@ -14339,31 +14339,7 @@ public class ActivityManagerService extends IActivityManager.Stub backgroundActivityStartsToken, timeoutExempt, filterExtrasForReceiver); if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing ordered broadcast " + r); - - final BroadcastRecord oldRecord = - replacePending ? queue.replaceOrderedBroadcastLocked(r) : null; - if (oldRecord != null) { - // Replaced, fire the result-to receiver. - if (oldRecord.resultTo != null) { - final BroadcastQueue oldQueue = broadcastQueueForIntent(oldRecord.intent); - try { - oldRecord.mIsReceiverAppRunning = true; - oldQueue.performReceiveLocked(oldRecord.callerApp, oldRecord.resultTo, - oldRecord.intent, - Activity.RESULT_CANCELED, null, null, - false, false, oldRecord.userId, oldRecord.callingUid, callingUid, - SystemClock.uptimeMillis() - oldRecord.enqueueTime, 0); - } catch (RemoteException e) { - Slog.w(TAG, "Failure [" - + queue.mQueueName + "] sending broadcast result of " - + intent, e); - - } - } - } else { - queue.enqueueOrderedBroadcastLocked(r); - queue.scheduleBroadcastsLocked(); - } + queue.enqueueBroadcastLocked(r); } else { // There was nobody interested in the broadcast, but we still want to record // that it happened. @@ -15183,7 +15159,7 @@ public class ActivityManagerService extends IActivityManager.Stub // It's not the current receiver, but it might be starting up to become one for (BroadcastQueue queue : mBroadcastQueues) { - final BroadcastRecord r = queue.mPendingBroadcast; + final BroadcastRecord r = queue.getPendingBroadcastLocked(); if (r != null && r.curApp == app) { // found it; report which queue it's in receivingQueues.add(queue); @@ -15298,7 +15274,7 @@ public class ActivityManagerService extends IActivityManager.Stub @GuardedBy("this") final boolean canGcNowLocked() { for (BroadcastQueue q : mBroadcastQueues) { - if (!q.mParallelBroadcasts.isEmpty() || !q.mDispatcher.isIdle()) { + if (!q.isIdle()) { return false; } } @@ -17887,7 +17863,7 @@ public class ActivityManagerService extends IActivityManager.Stub pw.flush(); } Slog.v(TAG, msg); - queue.cancelDeferrals(); + queue.flush(); idle = false; } } diff --git a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java index 5cb25d36d94b..36908ce8c7b3 100644 --- a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java +++ b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java @@ -49,10 +49,12 @@ import android.app.BroadcastOptions; import android.app.IActivityController; import android.app.IActivityManager; import android.app.IActivityTaskManager; +import android.app.IProcessObserver; import android.app.IStopUserCallback; import android.app.IUidObserver; import android.app.IUserSwitchObserver; import android.app.KeyguardManager; +import android.app.ProcessStateEnum; import android.app.ProfilerInfo; import android.app.RemoteServiceException.CrashedByAdbException; import android.app.UserSwitchObserver; @@ -359,6 +361,8 @@ final class ActivityManagerShellCommand extends ShellCommand { return runSetBgRestrictionLevel(pw); case "get-bg-restriction-level": return runGetBgRestrictionLevel(pw); + case "observe-foreground-process": + return runGetCurrentForegroundProcess(pw, mInternal, mTaskInterface); default: return handleDefaultCommands(cmd); } @@ -3230,6 +3234,82 @@ final class ActivityManagerShellCommand extends ShellCommand { return -1; } + private int runGetCurrentForegroundProcess(PrintWriter pw, + IActivityManager iam, IActivityTaskManager iatm) + throws RemoteException { + + ProcessObserver observer = new ProcessObserver(pw, iam, iatm, mInternal); + iam.registerProcessObserver(observer); + + final InputStream mInput = getRawInputStream(); + InputStreamReader converter = new InputStreamReader(mInput); + BufferedReader in = new BufferedReader(converter); + String line; + try { + while ((line = in.readLine()) != null) { + boolean addNewline = true; + if (line.length() <= 0) { + addNewline = false; + } else if ("q".equals(line) || "quit".equals(line)) { + break; + } else { + pw.println("Invalid command: " + line); + } + if (addNewline) { + pw.println(""); + } + pw.flush(); + } + } catch (IOException e) { + e.printStackTrace(); + pw.flush(); + } finally { + iam.unregisterProcessObserver(observer); + } + return 0; + } + + static final class ProcessObserver extends IProcessObserver.Stub { + + private PrintWriter mPw; + private IActivityManager mIam; + private IActivityTaskManager mIatm; + private ActivityManagerService mInternal; + + ProcessObserver(PrintWriter mPw, IActivityManager mIam, + IActivityTaskManager mIatm, ActivityManagerService ams) { + this.mPw = mPw; + this.mIam = mIam; + this.mIatm = mIatm; + this.mInternal = ams; + } + + @Override + public void onForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) { + if (foregroundActivities) { + try { + int prcState = mIam.getUidProcessState(uid, "android"); + int topPid = mInternal.getTopApp().getPid(); + if (prcState == ProcessStateEnum.TOP && topPid == pid) { + mPw.println("New foreground process: " + pid); + } + mPw.flush(); + } catch (RemoteException e) { + mPw.println("Error occurred in binder call"); + mPw.flush(); + } + } + } + + @Override + public void onForegroundServicesChanged(int pid, int uid, int serviceTypes) { + } + + @Override + public void onProcessDied(int pid, int uid) { + } + } + private int runSetMemoryFactor(PrintWriter pw) throws RemoteException { final String levelArg = getNextArgRequired(); @MemFactor int level = ADJ_MEM_FACTOR_NOTHING; diff --git a/services/core/java/com/android/server/am/BroadcastDispatcher.java b/services/core/java/com/android/server/am/BroadcastDispatcher.java index 49477ad75302..e9a36e05c6c1 100644 --- a/services/core/java/com/android/server/am/BroadcastDispatcher.java +++ b/services/core/java/com/android/server/am/BroadcastDispatcher.java @@ -162,7 +162,7 @@ public class BroadcastDispatcher { } private final Object mLock; - private final BroadcastQueue mQueue; + private final BroadcastQueueImpl mQueue; private final BroadcastConstants mConstants; private final Handler mHandler; private AlarmManagerInternal mAlarm; @@ -489,7 +489,7 @@ public class BroadcastDispatcher { /** * Constructed & sharing a lock with its associated BroadcastQueue instance */ - public BroadcastDispatcher(BroadcastQueue queue, BroadcastConstants constants, + public BroadcastDispatcher(BroadcastQueueImpl queue, BroadcastConstants constants, Handler handler, Object lock) { mQueue = queue; mConstants = constants; diff --git a/services/core/java/com/android/server/am/BroadcastQueue.java b/services/core/java/com/android/server/am/BroadcastQueue.java index 31d9f96d46e4..d0946bec730a 100644 --- a/services/core/java/com/android/server/am/BroadcastQueue.java +++ b/services/core/java/com/android/server/am/BroadcastQueue.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 The Android Open Source Project + * 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. @@ -16,236 +16,40 @@ package com.android.server.am; -import static android.app.ActivityManager.RESTRICTION_LEVEL_RESTRICTED_BUCKET; -import static android.os.Process.ZYGOTE_POLICY_FLAG_EMPTY; -import static android.os.Process.ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE; -import static android.text.TextUtils.formatSimple; - -import static com.android.internal.util.FrameworkStatsLog.BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED; -import static com.android.internal.util.FrameworkStatsLog.BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__BOOT_COMPLETED; -import static com.android.internal.util.FrameworkStatsLog.BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__LOCKED_BOOT_COMPLETED; -import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED; -import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_COLD; -import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM; -import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__MANIFEST; -import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__RUNTIME; -import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST; -import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_DEFERRAL; -import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_LIGHT; -import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU; -import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW; -import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BROADCAST; -import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU; -import static com.android.server.am.OomAdjuster.OOM_ADJ_REASON_FINISH_RECEIVER; -import static com.android.server.am.OomAdjuster.OOM_ADJ_REASON_START_RECEIVER; - - -import android.annotation.NonNull; -import android.annotation.Nullable; -import android.app.ActivityManager; -import android.app.AppGlobals; -import android.app.AppOpsManager; -import android.app.BroadcastOptions; -import android.app.IApplicationThread; -import android.app.PendingIntent; -import android.app.RemoteServiceException.CannotDeliverBroadcastException; -import android.app.usage.UsageEvents.Event; -import android.app.usage.UsageStatsManagerInternal; -import android.content.ComponentName; +import android.content.BroadcastReceiver; import android.content.ContentResolver; -import android.content.IIntentReceiver; -import android.content.IIntentSender; import android.content.Intent; -import android.content.IntentSender; -import android.content.pm.ActivityInfo; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.content.pm.PermissionInfo; -import android.content.pm.ResolveInfo; -import android.content.pm.UserInfo; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; -import android.os.Looper; -import android.os.Message; -import android.os.PowerExemptionManager.ReasonCode; -import android.os.PowerExemptionManager.TempAllowListType; -import android.os.Process; -import android.os.RemoteException; -import android.os.SystemClock; -import android.os.Trace; -import android.os.UserHandle; -import android.os.UserManager; -import android.permission.IPermissionManager; -import android.text.TextUtils; -import android.util.EventLog; -import android.util.Slog; -import android.util.SparseIntArray; -import android.util.TimeUtils; import android.util.proto.ProtoOutputStream; -import com.android.internal.os.TimeoutRecord; -import com.android.internal.util.ArrayUtils; -import com.android.internal.util.FrameworkStatsLog; -import com.android.server.LocalServices; -import com.android.server.pm.UserManagerInternal; - import java.io.FileDescriptor; import java.io.PrintWriter; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; import java.util.Set; /** - * BROADCASTS - * - * We keep three broadcast queues and associated bookkeeping, one for those at - * foreground priority, and one for normal (background-priority) broadcasts, and one to - * offload special broadcasts that we know take a long time, such as BOOT_COMPLETED. + * Queue of broadcast intents and associated bookkeeping. */ -public final class BroadcastQueue { - private static final String TAG = "BroadcastQueue"; - private static final String TAG_MU = TAG + POSTFIX_MU; - private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST; - - static final int MAX_BROADCAST_HISTORY = ActivityManager.isLowRamDeviceStatic() ? 10 : 50; - static final int MAX_BROADCAST_SUMMARY_HISTORY - = ActivityManager.isLowRamDeviceStatic() ? 25 : 300; +public abstract class BroadcastQueue { + public static final String TAG = "BroadcastQueue"; final ActivityManagerService mService; - - /** - * Behavioral parameters such as timeouts and deferral policy, tracking Settings - * for runtime configurability - */ + final Handler mHandler; final BroadcastConstants mConstants; - - /** - * Recognizable moniker for this queue - */ + final BroadcastSkipPolicy mSkipPolicy; final String mQueueName; - /** - * If true, we can delay broadcasts while waiting services to finish in the previous - * receiver's process. - */ - final boolean mDelayBehindServices; - - /** - * Lists of all active broadcasts that are to be executed immediately - * (without waiting for another broadcast to finish). Currently this only - * contains broadcasts to registered receivers, to avoid spinning up - * a bunch of processes to execute IntentReceiver components. Background- - * and foreground-priority broadcasts are queued separately. - */ - final ArrayList<BroadcastRecord> mParallelBroadcasts = new ArrayList<>(); - - /** - * Tracking of the ordered broadcast queue, including deferral policy and alarm - * prioritization. - */ - final BroadcastDispatcher mDispatcher; - - /** - * Refcounting for completion callbacks of split/deferred broadcasts. The key - * is an opaque integer token assigned lazily when a broadcast is first split - * into multiple BroadcastRecord objects. - */ - final SparseIntArray mSplitRefcounts = new SparseIntArray(); - private int mNextToken = 0; - - /** - * Historical data of past broadcasts, for debugging. This is a ring buffer - * whose last element is at mHistoryNext. - */ - final BroadcastRecord[] mBroadcastHistory = new BroadcastRecord[MAX_BROADCAST_HISTORY]; - int mHistoryNext = 0; - - /** - * Summary of historical data of past broadcasts, for debugging. This is a - * ring buffer whose last element is at mSummaryHistoryNext. - */ - final Intent[] mBroadcastSummaryHistory = new Intent[MAX_BROADCAST_SUMMARY_HISTORY]; - int mSummaryHistoryNext = 0; - - /** - * Various milestone timestamps of entries in the mBroadcastSummaryHistory ring - * buffer, also tracked via the mSummaryHistoryNext index. These are all in wall - * clock time, not elapsed. - */ - final long[] mSummaryHistoryEnqueueTime = new long[MAX_BROADCAST_SUMMARY_HISTORY]; - final long[] mSummaryHistoryDispatchTime = new long[MAX_BROADCAST_SUMMARY_HISTORY]; - final long[] mSummaryHistoryFinishTime = new long[MAX_BROADCAST_SUMMARY_HISTORY]; - - /** - * Set when we current have a BROADCAST_INTENT_MSG in flight. - */ - boolean mBroadcastsScheduled = false; - - /** - * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler. - */ - boolean mPendingBroadcastTimeoutMessage; - - /** - * Intent broadcasts that we have tried to start, but are - * waiting for the application's process to be created. We only - * need one per scheduling class (instead of a list) because we always - * process broadcasts one at a time, so no others can be started while - * waiting for this one. - */ - BroadcastRecord mPendingBroadcast = null; - - /** - * The receiver index that is pending, to restart the broadcast if needed. - */ - int mPendingBroadcastRecvIndex; - - static final int BROADCAST_INTENT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG; - static final int BROADCAST_TIMEOUT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 1; - - // log latency metrics for ordered broadcasts during BOOT_COMPLETED processing - boolean mLogLatencyMetrics = true; - - final BroadcastHandler mHandler; - - private final class BroadcastHandler extends Handler { - public BroadcastHandler(Looper looper) { - super(looper, null, true); - } - - @Override - public void handleMessage(Message msg) { - switch (msg.what) { - case BROADCAST_INTENT_MSG: { - if (DEBUG_BROADCAST) Slog.v( - TAG_BROADCAST, "Received BROADCAST_INTENT_MSG [" - + mQueueName + "]"); - processNextBroadcast(true); - } break; - case BROADCAST_TIMEOUT_MSG: { - synchronized (mService) { - broadcastTimeoutLocked(true); - } - } break; - } - } - } - BroadcastQueue(ActivityManagerService service, Handler handler, - String name, BroadcastConstants constants, boolean allowDelayBehindServices) { + String name, BroadcastConstants constants) { mService = service; - mHandler = new BroadcastHandler(handler.getLooper()); + mHandler = handler; mQueueName = name; - mDelayBehindServices = allowDelayBehindServices; - mConstants = constants; - mDispatcher = new BroadcastDispatcher(this, mConstants, mHandler, mService); + mSkipPolicy = new BroadcastSkipPolicy(service); } void start(ContentResolver resolver) { - mDispatcher.start(); mConstants.startObserving(mHandler, resolver); } @@ -254,2322 +58,78 @@ public final class BroadcastQueue { return mQueueName; } - public boolean isPendingBroadcastProcessLocked(int pid) { - return mPendingBroadcast != null && mPendingBroadcast.curApp.getPid() == pid; - } - - boolean isPendingBroadcastProcessLocked(ProcessRecord app) { - return mPendingBroadcast != null && mPendingBroadcast.curApp == app; - } - - public void enqueueParallelBroadcastLocked(BroadcastRecord r) { - r.enqueueClockTime = System.currentTimeMillis(); - r.enqueueTime = SystemClock.uptimeMillis(); - r.enqueueRealTime = SystemClock.elapsedRealtime(); - mParallelBroadcasts.add(r); - enqueueBroadcastHelper(r); - } - - public void enqueueOrderedBroadcastLocked(BroadcastRecord r) { - r.enqueueClockTime = System.currentTimeMillis(); - r.enqueueTime = SystemClock.uptimeMillis(); - r.enqueueRealTime = SystemClock.elapsedRealtime(); - mDispatcher.enqueueOrderedBroadcastLocked(r); - enqueueBroadcastHelper(r); - } + public abstract boolean isDelayBehindServices(); - /** - * Don't call this method directly; call enqueueParallelBroadcastLocked or - * enqueueOrderedBroadcastLocked. - */ - private void enqueueBroadcastHelper(BroadcastRecord r) { - if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { - Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, - createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING), - System.identityHashCode(r)); - } - } + public abstract BroadcastRecord getPendingBroadcastLocked(); - /** - * Find the same intent from queued parallel broadcast, replace with a new one and return - * the old one. - */ - public final BroadcastRecord replaceParallelBroadcastLocked(BroadcastRecord r) { - return replaceBroadcastLocked(mParallelBroadcasts, r, "PARALLEL"); - } + public abstract BroadcastRecord getActiveBroadcastLocked(); /** - * Find the same intent from queued ordered broadcast, replace with a new one and return - * the old one. + * Enqueue the given broadcast to be eventually dispatched. + * <p> + * Callers must populate {@link BroadcastRecord#receivers} with the relevant + * targets before invoking this method. + * <p> + * When {@link Intent#FLAG_RECEIVER_REPLACE_PENDING} is set, this method + * internally handles replacement of any matching broadcasts. */ - public final BroadcastRecord replaceOrderedBroadcastLocked(BroadcastRecord r) { - return mDispatcher.replaceBroadcastLocked(r, "ORDERED"); - } + public abstract void enqueueBroadcastLocked(BroadcastRecord r); - private BroadcastRecord replaceBroadcastLocked(ArrayList<BroadcastRecord> queue, - BroadcastRecord r, String typeForLogging) { - final Intent intent = r.intent; - for (int i = queue.size() - 1; i > 0; i--) { - final BroadcastRecord old = queue.get(i); - if (old.userId == r.userId && intent.filterEquals(old.intent)) { - if (DEBUG_BROADCAST) { - Slog.v(TAG_BROADCAST, "***** DROPPING " - + typeForLogging + " [" + mQueueName + "]: " + intent); - } - queue.set(i, r); - return old; - } - } - return null; - } + public abstract void updateUidReadyForBootCompletedBroadcastLocked(int uid); - private final void processCurBroadcastLocked(BroadcastRecord r, - ProcessRecord app) throws RemoteException { - if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, - "Process cur broadcast " + r + " for app " + app); - final IApplicationThread thread = app.getThread(); - if (thread == null) { - throw new RemoteException(); - } - if (app.isInFullBackup()) { - skipReceiverLocked(r); - return; - } + public abstract boolean sendPendingBroadcastsLocked(ProcessRecord app); - r.receiver = thread.asBinder(); - r.curApp = app; - final ProcessReceiverRecord prr = app.mReceivers; - prr.addCurReceiver(r); - app.mState.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER); - // Don't bump its LRU position if it's in the background restricted. - if (mService.mInternal.getRestrictionLevel(app.info.packageName, app.userId) - < RESTRICTION_LEVEL_RESTRICTED_BUCKET) { - mService.updateLruProcessLocked(app, false, null); - } - // Make sure the oom adj score is updated before delivering the broadcast. - // Force an update, even if there are other pending requests, overall it still saves time, - // because time(updateOomAdj(N apps)) <= N * time(updateOomAdj(1 app)). - mService.enqueueOomAdjTargetLocked(app); - mService.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_START_RECEIVER); + public abstract void skipPendingBroadcastLocked(int pid); - // Tell the application to launch this receiver. - maybeReportBroadcastDispatchedEventLocked(r, r.curReceiver.applicationInfo.uid); - r.intent.setComponent(r.curComponent); + public abstract void skipCurrentReceiverLocked(ProcessRecord app); - boolean started = false; - try { - if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, - "Delivering to component " + r.curComponent - + ": " + r); - mService.notifyPackageUse(r.intent.getComponent().getPackageName(), - PackageManager.NOTIFY_PACKAGE_USE_BROADCAST_RECEIVER); - thread.scheduleReceiver(prepareReceiverIntent(r.intent, r.curFilteredExtras), - r.curReceiver, null /* compatInfo (unused but need to keep method signature) */, - r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId, - app.mState.getReportedProcState()); - if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, - "Process cur broadcast " + r + " DELIVERED for app " + app); - started = true; - } finally { - if (!started) { - if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, - "Process cur broadcast " + r + ": NOT STARTED!"); - r.receiver = null; - r.curApp = null; - prr.removeCurReceiver(r); - } - } - - // if something bad happens here, launch the app and try again - if (app.isKilled()) { - throw new RemoteException("app gets killed during broadcasting"); - } - } + public abstract BroadcastRecord getMatchingOrderedReceiver(IBinder receiver); /** - * Called by ActivityManagerService to notify that the uid has process started, if there is any - * deferred BOOT_COMPLETED broadcast, the BroadcastDispatcher can dispatch the broadcast now. - * @param uid + * Signal delivered back from a {@link BroadcastReceiver} to indicate that + * it's finished processing the current broadcast being dispatched to it. + * <p> + * If this signal isn't delivered back in a timely fashion, we assume the + * receiver has somehow wedged and we trigger an ANR. */ - public void updateUidReadyForBootCompletedBroadcastLocked(int uid) { - mDispatcher.updateUidReadyForBootCompletedBroadcastLocked(uid); - } - - public boolean sendPendingBroadcastsLocked(ProcessRecord app) { - boolean didSomething = false; - final BroadcastRecord br = mPendingBroadcast; - if (br != null && br.curApp.getPid() > 0 && br.curApp.getPid() == app.getPid()) { - if (br.curApp != app) { - Slog.e(TAG, "App mismatch when sending pending broadcast to " - + app.processName + ", intended target is " + br.curApp.processName); - return false; - } - try { - mPendingBroadcast = null; - br.mIsReceiverAppRunning = false; - processCurBroadcastLocked(br, app); - didSomething = true; - } catch (Exception e) { - Slog.w(TAG, "Exception in new application when starting receiver " - + br.curComponent.flattenToShortString(), e); - logBroadcastReceiverDiscardLocked(br); - finishReceiverLocked(br, br.resultCode, br.resultData, - br.resultExtras, br.resultAbort, false); - scheduleBroadcastsLocked(); - // We need to reset the state if we failed to start the receiver. - br.state = BroadcastRecord.IDLE; - throw new RuntimeException(e.getMessage()); - } - } - return didSomething; - } - - public void skipPendingBroadcastLocked(int pid) { - final BroadcastRecord br = mPendingBroadcast; - if (br != null && br.curApp.getPid() == pid) { - br.state = BroadcastRecord.IDLE; - br.nextReceiver = mPendingBroadcastRecvIndex; - mPendingBroadcast = null; - scheduleBroadcastsLocked(); - } - } + public abstract boolean finishReceiverLocked(BroadcastRecord r, int resultCode, + String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices); - // Skip the current receiver, if any, that is in flight to the given process - public void skipCurrentReceiverLocked(ProcessRecord app) { - BroadcastRecord r = null; - final BroadcastRecord curActive = mDispatcher.getActiveBroadcastLocked(); - if (curActive != null && curActive.curApp == app) { - // confirmed: the current active broadcast is to the given app - r = curActive; - } + public abstract void backgroundServicesFinishedLocked(int userId); - // If the current active broadcast isn't this BUT we're waiting for - // mPendingBroadcast to spin up the target app, that's what we use. - if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) { - if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, - "[" + mQueueName + "] skip & discard pending app " + r); - r = mPendingBroadcast; - } - - if (r != null) { - skipReceiverLocked(r); - } - } - - private void skipReceiverLocked(BroadcastRecord r) { - logBroadcastReceiverDiscardLocked(r); - finishReceiverLocked(r, r.resultCode, r.resultData, - r.resultExtras, r.resultAbort, false); - scheduleBroadcastsLocked(); - } - - public void scheduleBroadcastsLocked() { - if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts [" - + mQueueName + "]: current=" - + mBroadcastsScheduled); - - if (mBroadcastsScheduled) { - return; - } - mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this)); - mBroadcastsScheduled = true; - } - - public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) { - BroadcastRecord br = mDispatcher.getActiveBroadcastLocked(); - if (br != null && br.receiver == receiver) { - return br; - } - return null; - } - - // > 0 only, no worry about "eventual" recycling - private int nextSplitTokenLocked() { - int next = mNextToken + 1; - if (next <= 0) { - next = 1; - } - mNextToken = next; - return next; - } - - private void postActivityStartTokenRemoval(ProcessRecord app, BroadcastRecord r) { - // the receiver had run for less than allowed bg activity start timeout, - // so allow the process to still start activities from bg for some more time - String msgToken = (app.toShortString() + r.toString()).intern(); - // first, if there exists a past scheduled request to remove this token, drop - // that request - we don't want the token to be swept from under our feet... - mHandler.removeCallbacksAndMessages(msgToken); - // ...then schedule the removal of the token after the extended timeout - mHandler.postAtTime(() -> { - synchronized (mService) { - app.removeAllowBackgroundActivityStartsToken(r); - } - }, msgToken, (r.receiverTime + mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT)); - } - - public boolean finishReceiverLocked(BroadcastRecord r, int resultCode, - String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) { - final int state = r.state; - final ActivityInfo receiver = r.curReceiver; - final long finishTime = SystemClock.uptimeMillis(); - final long elapsed = finishTime - r.receiverTime; - r.state = BroadcastRecord.IDLE; - final int curIndex = r.nextReceiver - 1; - if (curIndex >= 0 && curIndex < r.receivers.size() && r.curApp != null) { - final Object curReceiver = r.receivers.get(curIndex); - FrameworkStatsLog.write(BROADCAST_DELIVERY_EVENT_REPORTED, r.curApp.uid, - r.callingUid == -1 ? Process.SYSTEM_UID : r.callingUid, - ActivityManagerService.getShortAction(r.intent.getAction()), - curReceiver instanceof BroadcastFilter - ? BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__RUNTIME - : BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__MANIFEST, - r.mIsReceiverAppRunning - ? BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM - : BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_COLD, - r.dispatchTime - r.enqueueTime, - r.receiverTime - r.dispatchTime, - finishTime - r.receiverTime); - } - if (state == BroadcastRecord.IDLE) { - Slog.w(TAG_BROADCAST, "finishReceiver [" + mQueueName + "] called but state is IDLE"); - } - if (r.allowBackgroundActivityStarts && r.curApp != null) { - if (elapsed > mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT) { - // if the receiver has run for more than allowed bg activity start timeout, - // just remove the token for this process now and we're done - r.curApp.removeAllowBackgroundActivityStartsToken(r); - } else { - // It gets more time; post the removal to happen at the appropriate moment - postActivityStartTokenRemoval(r.curApp, r); - } - } - // If we're abandoning this broadcast before any receivers were actually spun up, - // nextReceiver is zero; in which case time-to-process bookkeeping doesn't apply. - if (r.nextReceiver > 0) { - r.duration[r.nextReceiver - 1] = elapsed; - } - - // if this receiver was slow, impose deferral policy on the app. This will kick in - // when processNextBroadcastLocked() next finds this uid as a receiver identity. - if (!r.timeoutExempt) { - // r.curApp can be null if finish has raced with process death - benign - // edge case, and we just ignore it because we're already cleaning up - // as expected. - if (r.curApp != null - && mConstants.SLOW_TIME > 0 && elapsed > mConstants.SLOW_TIME) { - // Core system packages are exempt from deferral policy - if (!UserHandle.isCore(r.curApp.uid)) { - if (DEBUG_BROADCAST_DEFERRAL) { - Slog.i(TAG_BROADCAST, "Broadcast receiver " + (r.nextReceiver - 1) - + " was slow: " + receiver + " br=" + r); - } - mDispatcher.startDeferring(r.curApp.uid); - } else { - if (DEBUG_BROADCAST_DEFERRAL) { - Slog.i(TAG_BROADCAST, "Core uid " + r.curApp.uid - + " receiver was slow but not deferring: " - + receiver + " br=" + r); - } - } - } - } else { - if (DEBUG_BROADCAST_DEFERRAL) { - Slog.i(TAG_BROADCAST, "Finished broadcast " + r.intent.getAction() - + " is exempt from deferral policy"); - } - } - - r.receiver = null; - r.intent.setComponent(null); - if (r.curApp != null && r.curApp.mReceivers.hasCurReceiver(r)) { - r.curApp.mReceivers.removeCurReceiver(r); - mService.enqueueOomAdjTargetLocked(r.curApp); - } - if (r.curFilter != null) { - r.curFilter.receiverList.curBroadcast = null; - } - r.curFilter = null; - r.curReceiver = null; - r.curApp = null; - r.curFilteredExtras = null; - mPendingBroadcast = null; - - r.resultCode = resultCode; - r.resultData = resultData; - r.resultExtras = resultExtras; - if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) { - r.resultAbort = resultAbort; - } else { - r.resultAbort = false; - } - - // If we want to wait behind services *AND* we're finishing the head/ - // active broadcast on its queue - if (waitForServices && r.curComponent != null && r.queue.mDelayBehindServices - && r.queue.mDispatcher.getActiveBroadcastLocked() == r) { - ActivityInfo nextReceiver; - if (r.nextReceiver < r.receivers.size()) { - Object obj = r.receivers.get(r.nextReceiver); - nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null; - } else { - nextReceiver = null; - } - // Don't do this if the next receive is in the same process as the current one. - if (receiver == null || nextReceiver == null - || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid - || !receiver.processName.equals(nextReceiver.processName)) { - // In this case, we are ready to process the next receiver for the current broadcast, - //Â but are on a queue that would like to wait for services to finish before moving - // on. If there are background services currently starting, then we will go into a - // special state where we hold off on continuing this broadcast until they are done. - if (mService.mServices.hasBackgroundServicesLocked(r.userId)) { - Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString()); - r.state = BroadcastRecord.WAITING_SERVICES; - return false; - } - } - } - - r.curComponent = null; - - // We will process the next receiver right now if this is finishing - // an app receiver (which is always asynchronous) or after we have - // come back from calling a receiver. - return state == BroadcastRecord.APP_RECEIVE - || state == BroadcastRecord.CALL_DONE_RECEIVE; - } - - public void backgroundServicesFinishedLocked(int userId) { - BroadcastRecord br = mDispatcher.getActiveBroadcastLocked(); - if (br != null) { - if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) { - Slog.i(TAG, "Resuming delayed broadcast"); - br.curComponent = null; - br.state = BroadcastRecord.IDLE; - processNextBroadcastLocked(false, false); - } - } - } - - void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver, - Intent intent, int resultCode, String data, Bundle extras, - boolean ordered, boolean sticky, int sendingUser, - int receiverUid, int callingUid, long dispatchDelay, - long receiveDelay) throws RemoteException { - // Send the intent to the receiver asynchronously using one-way binder calls. - if (app != null) { - final IApplicationThread thread = app.getThread(); - if (thread != null) { - // If we have an app thread, do the call through that so it is - // correctly ordered with other one-way calls. - try { - thread.scheduleRegisteredReceiver(receiver, intent, resultCode, - data, extras, ordered, sticky, sendingUser, - app.mState.getReportedProcState()); - // TODO: Uncomment this when (b/28322359) is fixed and we aren't getting - // DeadObjectException when the process isn't actually dead. - //} catch (DeadObjectException ex) { - // Failed to call into the process. It's dying so just let it die and move on. - // throw ex; - } catch (RemoteException ex) { - // Failed to call into the process. It's either dying or wedged. Kill it gently. - synchronized (mService) { - Slog.w(TAG, "Can't deliver broadcast to " + app.processName - + " (pid " + app.getPid() + "). Crashing it."); - app.scheduleCrashLocked("can't deliver broadcast", - CannotDeliverBroadcastException.TYPE_ID, /* extras=*/ null); - } - throw ex; - } - } else { - // Application has died. Receiver doesn't exist. - throw new RemoteException("app.thread must not be null"); - } - } else { - receiver.performReceive(intent, resultCode, data, extras, ordered, - sticky, sendingUser); - } - if (!ordered) { - FrameworkStatsLog.write(BROADCAST_DELIVERY_EVENT_REPORTED, - receiverUid == -1 ? Process.SYSTEM_UID : receiverUid, - callingUid == -1 ? Process.SYSTEM_UID : callingUid, - ActivityManagerService.getShortAction(intent.getAction()), - BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__RUNTIME, - BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM, - dispatchDelay, receiveDelay, 0 /* finish_delay */); - } - } - - private void deliverToRegisteredReceiverLocked(BroadcastRecord r, - BroadcastFilter filter, boolean ordered, int index) { - boolean skip = false; - if (r.options != null && !r.options.testRequireCompatChange(filter.owningUid)) { - Slog.w(TAG, "Compat change filtered: broadcasting " + r.intent.toString() - + " to uid " + filter.owningUid + " due to compat change " - + r.options.getRequireCompatChangeId()); - skip = true; - } - if (!mService.validateAssociationAllowedLocked(r.callerPackage, r.callingUid, - filter.packageName, filter.owningUid)) { - Slog.w(TAG, "Association not allowed: broadcasting " - + r.intent.toString() - + " from " + r.callerPackage + " (pid=" + r.callingPid - + ", uid=" + r.callingUid + ") to " + filter.packageName + " through " - + filter); - skip = true; - } - if (!skip && !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid, - r.callingPid, r.resolvedType, filter.receiverList.uid)) { - Slog.w(TAG, "Firewall blocked: broadcasting " - + r.intent.toString() - + " from " + r.callerPackage + " (pid=" + r.callingPid - + ", uid=" + r.callingUid + ") to " + filter.packageName + " through " - + filter); - skip = true; - } - // Check that the sender has permission to send to this receiver - if (filter.requiredPermission != null) { - int perm = mService.checkComponentPermission(filter.requiredPermission, - r.callingPid, r.callingUid, -1, true); - if (perm != PackageManager.PERMISSION_GRANTED) { - Slog.w(TAG, "Permission Denial: broadcasting " - + r.intent.toString() - + " from " + r.callerPackage + " (pid=" - + r.callingPid + ", uid=" + r.callingUid + ")" - + " requires " + filter.requiredPermission - + " due to registered receiver " + filter); - skip = true; - } else { - final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission); - if (opCode != AppOpsManager.OP_NONE - && mService.getAppOpsManager().noteOpNoThrow(opCode, r.callingUid, - r.callerPackage, r.callerFeatureId, "Broadcast sent to protected receiver") - != AppOpsManager.MODE_ALLOWED) { - Slog.w(TAG, "Appop Denial: broadcasting " - + r.intent.toString() - + " from " + r.callerPackage + " (pid=" - + r.callingPid + ", uid=" + r.callingUid + ")" - + " requires appop " + AppOpsManager.permissionToOp( - filter.requiredPermission) - + " due to registered receiver " + filter); - skip = true; - } - } - } - - if (!skip && (filter.receiverList.app == null || filter.receiverList.app.isKilled() - || filter.receiverList.app.mErrorState.isCrashing())) { - Slog.w(TAG, "Skipping deliver [" + mQueueName + "] " + r - + " to " + filter.receiverList + ": process gone or crashing"); - skip = true; - } - - // Ensure that broadcasts are only sent to other Instant Apps if they are marked as - // visible to Instant Apps. - final boolean visibleToInstantApps = - (r.intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0; - - if (!skip && !visibleToInstantApps && filter.instantApp - && filter.receiverList.uid != r.callingUid) { - Slog.w(TAG, "Instant App Denial: receiving " - + r.intent.toString() - + " to " + filter.receiverList.app - + " (pid=" + filter.receiverList.pid - + ", uid=" + filter.receiverList.uid + ")" - + " due to sender " + r.callerPackage - + " (uid " + r.callingUid + ")" - + " not specifying FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS"); - skip = true; - } - - if (!skip && !filter.visibleToInstantApp && r.callerInstantApp - && filter.receiverList.uid != r.callingUid) { - Slog.w(TAG, "Instant App Denial: receiving " - + r.intent.toString() - + " to " + filter.receiverList.app - + " (pid=" + filter.receiverList.pid - + ", uid=" + filter.receiverList.uid + ")" - + " requires receiver be visible to instant apps" - + " due to sender " + r.callerPackage - + " (uid " + r.callingUid + ")"); - skip = true; - } - - // Check that the receiver has the required permission(s) to receive this broadcast. - if (!skip && r.requiredPermissions != null && r.requiredPermissions.length > 0) { - for (int i = 0; i < r.requiredPermissions.length; i++) { - String requiredPermission = r.requiredPermissions[i]; - int perm = mService.checkComponentPermission(requiredPermission, - filter.receiverList.pid, filter.receiverList.uid, -1, true); - if (perm != PackageManager.PERMISSION_GRANTED) { - Slog.w(TAG, "Permission Denial: receiving " - + r.intent.toString() - + " to " + filter.receiverList.app - + " (pid=" + filter.receiverList.pid - + ", uid=" + filter.receiverList.uid + ")" - + " requires " + requiredPermission - + " due to sender " + r.callerPackage - + " (uid " + r.callingUid + ")"); - skip = true; - break; - } - int appOp = AppOpsManager.permissionToOpCode(requiredPermission); - if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp - && mService.getAppOpsManager().noteOpNoThrow(appOp, - filter.receiverList.uid, filter.packageName, filter.featureId, - "Broadcast delivered to registered receiver " + filter.receiverId) - != AppOpsManager.MODE_ALLOWED) { - Slog.w(TAG, "Appop Denial: receiving " - + r.intent.toString() - + " to " + filter.receiverList.app - + " (pid=" + filter.receiverList.pid - + ", uid=" + filter.receiverList.uid + ")" - + " requires appop " + AppOpsManager.permissionToOp( - requiredPermission) - + " due to sender " + r.callerPackage - + " (uid " + r.callingUid + ")"); - skip = true; - break; - } - } - } - if (!skip && (r.requiredPermissions == null || r.requiredPermissions.length == 0)) { - int perm = mService.checkComponentPermission(null, - filter.receiverList.pid, filter.receiverList.uid, -1, true); - if (perm != PackageManager.PERMISSION_GRANTED) { - Slog.w(TAG, "Permission Denial: security check failed when receiving " - + r.intent.toString() - + " to " + filter.receiverList.app - + " (pid=" + filter.receiverList.pid - + ", uid=" + filter.receiverList.uid + ")" - + " due to sender " + r.callerPackage - + " (uid " + r.callingUid + ")"); - skip = true; - } - } - // Check that the receiver does *not* have any excluded permissions - if (!skip && r.excludedPermissions != null && r.excludedPermissions.length > 0) { - for (int i = 0; i < r.excludedPermissions.length; i++) { - String excludedPermission = r.excludedPermissions[i]; - final int perm = mService.checkComponentPermission(excludedPermission, - filter.receiverList.pid, filter.receiverList.uid, -1, true); - - int appOp = AppOpsManager.permissionToOpCode(excludedPermission); - if (appOp != AppOpsManager.OP_NONE) { - // When there is an app op associated with the permission, - // skip when both the permission and the app op are - // granted. - if ((perm == PackageManager.PERMISSION_GRANTED) && ( - mService.getAppOpsManager().checkOpNoThrow(appOp, - filter.receiverList.uid, - filter.packageName) - == AppOpsManager.MODE_ALLOWED)) { - Slog.w(TAG, "Appop Denial: receiving " - + r.intent.toString() - + " to " + filter.receiverList.app - + " (pid=" + filter.receiverList.pid - + ", uid=" + filter.receiverList.uid + ")" - + " excludes appop " + AppOpsManager.permissionToOp( - excludedPermission) - + " due to sender " + r.callerPackage - + " (uid " + r.callingUid + ")"); - skip = true; - break; - } - } else { - // When there is no app op associated with the permission, - // skip when permission is granted. - if (perm == PackageManager.PERMISSION_GRANTED) { - Slog.w(TAG, "Permission Denial: receiving " - + r.intent.toString() - + " to " + filter.receiverList.app - + " (pid=" + filter.receiverList.pid - + ", uid=" + filter.receiverList.uid + ")" - + " excludes " + excludedPermission - + " due to sender " + r.callerPackage - + " (uid " + r.callingUid + ")"); - skip = true; - break; - } - } - } - } - - // Check that the receiver does *not* belong to any of the excluded packages - if (!skip && r.excludedPackages != null && r.excludedPackages.length > 0) { - if (ArrayUtils.contains(r.excludedPackages, filter.packageName)) { - Slog.w(TAG, "Skipping delivery of excluded package " - + r.intent.toString() - + " to " + filter.receiverList.app - + " (pid=" + filter.receiverList.pid - + ", uid=" + filter.receiverList.uid + ")" - + " excludes package " + filter.packageName - + " due to sender " + r.callerPackage - + " (uid " + r.callingUid + ")"); - skip = true; - } - } - - // If the broadcast also requires an app op check that as well. - if (!skip && r.appOp != AppOpsManager.OP_NONE - && mService.getAppOpsManager().noteOpNoThrow(r.appOp, - filter.receiverList.uid, filter.packageName, filter.featureId, - "Broadcast delivered to registered receiver " + filter.receiverId) - != AppOpsManager.MODE_ALLOWED) { - Slog.w(TAG, "Appop Denial: receiving " - + r.intent.toString() - + " to " + filter.receiverList.app - + " (pid=" + filter.receiverList.pid - + ", uid=" + filter.receiverList.uid + ")" - + " requires appop " + AppOpsManager.opToName(r.appOp) - + " due to sender " + r.callerPackage - + " (uid " + r.callingUid + ")"); - skip = true; - } - - // Ensure that broadcasts are only sent to other apps if they are explicitly marked as - // exported, or are System level broadcasts - if (!skip && !filter.exported && mService.checkComponentPermission(null, r.callingPid, - r.callingUid, filter.receiverList.uid, filter.exported) - != PackageManager.PERMISSION_GRANTED) { - Slog.w(TAG, "Exported Denial: sending " - + r.intent.toString() - + ", action: " + r.intent.getAction() - + " from " + r.callerPackage - + " (uid=" + r.callingUid + ")" - + " due to receiver " + filter.receiverList.app - + " (uid " + filter.receiverList.uid + ")" - + " not specifying RECEIVER_EXPORTED"); - skip = true; - } - - // Filter packages in the intent extras, skipping delivery if none of the packages is - // visible to the receiver. - Bundle filteredExtras = null; - if (!skip && r.filterExtrasForReceiver != null) { - final Bundle extras = r.intent.getExtras(); - if (extras != null) { - filteredExtras = r.filterExtrasForReceiver.apply(filter.receiverList.uid, extras); - if (filteredExtras == null) { - if (DEBUG_BROADCAST) { - Slog.v(TAG, "Skipping delivery to " - + filter.receiverList.app - + " : receiver is filtered by the package visibility"); - } - skip = true; - } - } - } - - if (skip) { - r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED; - return; - } - - // If permissions need a review before any of the app components can run, we drop - // the broadcast and if the calling app is in the foreground and the broadcast is - // explicit we launch the review UI passing it a pending intent to send the skipped - // broadcast. - if (!requestStartTargetPermissionsReviewIfNeededLocked(r, filter.packageName, - filter.owningUserId)) { - r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED; - return; - } - - r.delivery[index] = BroadcastRecord.DELIVERY_DELIVERED; - - // If this is not being sent as an ordered broadcast, then we - // don't want to touch the fields that keep track of the current - // state of ordered broadcasts. - if (ordered) { - r.receiver = filter.receiverList.receiver.asBinder(); - r.curFilter = filter; - filter.receiverList.curBroadcast = r; - r.state = BroadcastRecord.CALL_IN_RECEIVE; - if (filter.receiverList.app != null) { - // Bump hosting application to no longer be in background - // scheduling class. Note that we can't do that if there - // isn't an app... but we can only be in that case for - // things that directly call the IActivityManager API, which - // are already core system stuff so don't matter for this. - r.curApp = filter.receiverList.app; - filter.receiverList.app.mReceivers.addCurReceiver(r); - mService.enqueueOomAdjTargetLocked(r.curApp); - mService.updateOomAdjPendingTargetsLocked( - OOM_ADJ_REASON_START_RECEIVER); - } - } else if (filter.receiverList.app != null) { - mService.mOomAdjuster.mCachedAppOptimizer.unfreezeTemporarily(filter.receiverList.app, - OOM_ADJ_REASON_START_RECEIVER); - } - - try { - if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST, - "Delivering to " + filter + " : " + r); - if (filter.receiverList.app != null && filter.receiverList.app.isInFullBackup()) { - // Skip delivery if full backup in progress - // If it's an ordered broadcast, we need to continue to the next receiver. - if (ordered) { - skipReceiverLocked(r); - } - } else { - r.receiverTime = SystemClock.uptimeMillis(); - maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r); - maybeScheduleTempAllowlistLocked(filter.owningUid, r, r.options); - maybeReportBroadcastDispatchedEventLocked(r, filter.owningUid); - performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver, - prepareReceiverIntent(r.intent, filteredExtras), r.resultCode, r.resultData, - r.resultExtras, r.ordered, r.initialSticky, r.userId, - filter.receiverList.uid, r.callingUid, - r.dispatchTime - r.enqueueTime, - r.receiverTime - r.dispatchTime); - // parallel broadcasts are fire-and-forget, not bookended by a call to - // finishReceiverLocked(), so we manage their activity-start token here - if (filter.receiverList.app != null - && r.allowBackgroundActivityStarts && !r.ordered) { - postActivityStartTokenRemoval(filter.receiverList.app, r); - } - } - if (ordered) { - r.state = BroadcastRecord.CALL_DONE_RECEIVE; - } - } catch (RemoteException e) { - Slog.w(TAG, "Failure sending broadcast " + r.intent, e); - // Clean up ProcessRecord state related to this broadcast attempt - if (filter.receiverList.app != null) { - filter.receiverList.app.removeAllowBackgroundActivityStartsToken(r); - if (ordered) { - filter.receiverList.app.mReceivers.removeCurReceiver(r); - // Something wrong, its oom adj could be downgraded, but not in a hurry. - mService.enqueueOomAdjTargetLocked(r.curApp); - } - } - // And BroadcastRecord state related to ordered delivery, if appropriate - if (ordered) { - r.receiver = null; - r.curFilter = null; - filter.receiverList.curBroadcast = null; - } - } - } - - private boolean requestStartTargetPermissionsReviewIfNeededLocked( - BroadcastRecord receiverRecord, String receivingPackageName, - final int receivingUserId) { - if (!mService.getPackageManagerInternal().isPermissionsReviewRequired( - receivingPackageName, receivingUserId)) { - return true; - } - - final boolean callerForeground = receiverRecord.callerApp != null - ? receiverRecord.callerApp.mState.getSetSchedGroup() - != ProcessList.SCHED_GROUP_BACKGROUND : true; - - // Show a permission review UI only for explicit broadcast from a foreground app - if (callerForeground && receiverRecord.intent.getComponent() != null) { - IIntentSender target = mService.mPendingIntentController.getIntentSender( - ActivityManager.INTENT_SENDER_BROADCAST, receiverRecord.callerPackage, - receiverRecord.callerFeatureId, receiverRecord.callingUid, - receiverRecord.userId, null, null, 0, - new Intent[]{receiverRecord.intent}, - new String[]{receiverRecord.intent.resolveType(mService.mContext - .getContentResolver())}, - PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT - | PendingIntent.FLAG_IMMUTABLE, null); - - final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK - | Intent.FLAG_ACTIVITY_MULTIPLE_TASK - | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); - intent.putExtra(Intent.EXTRA_PACKAGE_NAME, receivingPackageName); - intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target)); - - if (DEBUG_PERMISSIONS_REVIEW) { - Slog.i(TAG, "u" + receivingUserId + " Launching permission review for package " - + receivingPackageName); - } - - mHandler.post(new Runnable() { - @Override - public void run() { - mService.mContext.startActivityAsUser(intent, new UserHandle(receivingUserId)); - } - }); - } else { - Slog.w(TAG, "u" + receivingUserId + " Receiving a broadcast in package" - + receivingPackageName + " requires a permissions review"); - } - - return false; - } - - void maybeScheduleTempAllowlistLocked(int uid, BroadcastRecord r, - @Nullable BroadcastOptions brOptions) { - if (brOptions == null || brOptions.getTemporaryAppAllowlistDuration() <= 0) { - return; - } - long duration = brOptions.getTemporaryAppAllowlistDuration(); - final @TempAllowListType int type = brOptions.getTemporaryAppAllowlistType(); - final @ReasonCode int reasonCode = brOptions.getTemporaryAppAllowlistReasonCode(); - final String reason = brOptions.getTemporaryAppAllowlistReason(); - - if (duration > Integer.MAX_VALUE) { - duration = Integer.MAX_VALUE; - } - // XXX ideally we should pause the broadcast until everything behind this is done, - // or else we will likely start dispatching the broadcast before we have opened - // access to the app (there is a lot of asynchronicity behind this). It is probably - // not that big a deal, however, because the main purpose here is to allow apps - // to hold wake locks, and they will be able to acquire their wake lock immediately - // it just won't be enabled until we get through this work. - StringBuilder b = new StringBuilder(); - b.append("broadcast:"); - UserHandle.formatUid(b, r.callingUid); - b.append(":"); - if (r.intent.getAction() != null) { - b.append(r.intent.getAction()); - } else if (r.intent.getComponent() != null) { - r.intent.getComponent().appendShortString(b); - } else if (r.intent.getData() != null) { - b.append(r.intent.getData()); - } - b.append(",reason:"); - b.append(reason); - if (DEBUG_BROADCAST) { - Slog.v(TAG, "Broadcast temp allowlist uid=" + uid + " duration=" + duration - + " type=" + type + " : " + b.toString()); - } - mService.tempAllowlistUidLocked(uid, duration, reasonCode, b.toString(), type, - r.callingUid); - } + public abstract void processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj); /** - * Return true if all given permissions are signature-only perms. + * Signal from OS internals that the given package (or some subset of that + * package) has been disabled or uninstalled, and that any pending + * broadcasts should be cleaned up. */ - final boolean isSignaturePerm(String[] perms) { - if (perms == null) { - return false; - } - IPermissionManager pm = AppGlobals.getPermissionManager(); - for (int i = perms.length-1; i >= 0; i--) { - try { - PermissionInfo pi = pm.getPermissionInfo(perms[i], "android", 0); - if (pi == null) { - // a required permission that no package has actually - // defined cannot be signature-required. - return false; - } - if ((pi.protectionLevel & (PermissionInfo.PROTECTION_MASK_BASE - | PermissionInfo.PROTECTION_FLAG_PRIVILEGED)) - != PermissionInfo.PROTECTION_SIGNATURE) { - // If this a signature permission and NOT allowed for privileged apps, it - // is okay... otherwise, nope! - return false; - } - } catch (RemoteException e) { - return false; - } - } - return true; - } - - private void processNextBroadcast(boolean fromMsg) { - synchronized (mService) { - processNextBroadcastLocked(fromMsg, false); - } - } + public abstract boolean cleanupDisabledPackageReceiversLocked( + String packageName, Set<String> filterByClasses, int userId, boolean doit); - static String broadcastDescription(BroadcastRecord r, ComponentName component) { - return r.intent.toString() - + " from " + r.callerPackage + " (pid=" + r.callingPid - + ", uid=" + r.callingUid + ") to " + component.flattenToShortString(); - } - - private static Intent prepareReceiverIntent(@NonNull Intent originalIntent, - @Nullable Bundle filteredExtras) { - final Intent intent = new Intent(originalIntent); - if (filteredExtras != null) { - intent.replaceExtras(filteredExtras); - } - return intent; - } - - final void processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj) { - BroadcastRecord r; - - if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast [" - + mQueueName + "]: " - + mParallelBroadcasts.size() + " parallel broadcasts; " - + mDispatcher.describeStateLocked()); - - mService.updateCpuStats(); - - if (fromMsg) { - mBroadcastsScheduled = false; - } - - // First, deliver any non-serialized broadcasts right away. - while (mParallelBroadcasts.size() > 0) { - r = mParallelBroadcasts.remove(0); - r.dispatchTime = SystemClock.uptimeMillis(); - r.dispatchRealTime = SystemClock.elapsedRealtime(); - r.dispatchClockTime = System.currentTimeMillis(); - r.mIsReceiverAppRunning = true; - - if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { - Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, - createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING), - System.identityHashCode(r)); - Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, - createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED), - System.identityHashCode(r)); - } - - final int N = r.receivers.size(); - if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast [" - + mQueueName + "] " + r); - for (int i=0; i<N; i++) { - Object target = r.receivers.get(i); - if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, - "Delivering non-ordered on [" + mQueueName + "] to registered " - + target + ": " + r); - deliverToRegisteredReceiverLocked(r, - (BroadcastFilter) target, false, i); - } - addBroadcastToHistoryLocked(r); - if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast [" - + mQueueName + "] " + r); - } - - // Now take care of the next serialized one... - - // If we are waiting for a process to come up to handle the next - // broadcast, then do nothing at this point. Just in case, we - // check that the process we're waiting for still exists. - if (mPendingBroadcast != null) { - if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, - "processNextBroadcast [" + mQueueName + "]: waiting for " - + mPendingBroadcast.curApp); - - boolean isDead; - if (mPendingBroadcast.curApp.getPid() > 0) { - synchronized (mService.mPidsSelfLocked) { - ProcessRecord proc = mService.mPidsSelfLocked.get( - mPendingBroadcast.curApp.getPid()); - isDead = proc == null || proc.mErrorState.isCrashing(); - } - } else { - final ProcessRecord proc = mService.mProcessList.getProcessNamesLOSP().get( - mPendingBroadcast.curApp.processName, mPendingBroadcast.curApp.uid); - isDead = proc == null || !proc.isPendingStart(); - } - if (!isDead) { - // It's still alive, so keep waiting - return; - } else { - Slog.w(TAG, "pending app [" - + mQueueName + "]" + mPendingBroadcast.curApp - + " died before responding to broadcast"); - mPendingBroadcast.state = BroadcastRecord.IDLE; - mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex; - mPendingBroadcast = null; - } - } - - boolean looped = false; - - do { - final long now = SystemClock.uptimeMillis(); - r = mDispatcher.getNextBroadcastLocked(now); - - if (r == null) { - // No more broadcasts are deliverable right now, so all done! - mDispatcher.scheduleDeferralCheckLocked(false); - synchronized (mService.mAppProfiler.mProfilerLock) { - mService.mAppProfiler.scheduleAppGcsLPf(); - } - if (looped && !skipOomAdj) { - // If we had finished the last ordered broadcast, then - // make sure all processes have correct oom and sched - // adjustments. - mService.updateOomAdjPendingTargetsLocked( - OOM_ADJ_REASON_START_RECEIVER); - } - - // when we have no more ordered broadcast on this queue, stop logging - if (mService.mUserController.mBootCompleted && mLogLatencyMetrics) { - mLogLatencyMetrics = false; - } - - return; - } - - boolean forceReceive = false; - - // Ensure that even if something goes awry with the timeout - // detection, we catch "hung" broadcasts here, discard them, - // and continue to make progress. - // - // This is only done if the system is ready so that early-stage receivers - // don't get executed with timeouts; and of course other timeout- - // exempt broadcasts are ignored. - int numReceivers = (r.receivers != null) ? r.receivers.size() : 0; - if (mService.mProcessesReady && !r.timeoutExempt && r.dispatchTime > 0) { - if ((numReceivers > 0) && - (now > r.dispatchTime + (2 * mConstants.TIMEOUT * numReceivers))) { - Slog.w(TAG, "Hung broadcast [" - + mQueueName + "] discarded after timeout failure:" - + " now=" + now - + " dispatchTime=" + r.dispatchTime - + " startTime=" + r.receiverTime - + " intent=" + r.intent - + " numReceivers=" + numReceivers - + " nextReceiver=" + r.nextReceiver - + " state=" + r.state); - broadcastTimeoutLocked(false); // forcibly finish this broadcast - forceReceive = true; - r.state = BroadcastRecord.IDLE; - } - } - - if (r.state != BroadcastRecord.IDLE) { - if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST, - "processNextBroadcast(" - + mQueueName + ") called when not idle (state=" - + r.state + ")"); - return; - } - - // Is the current broadcast is done for any reason? - if (r.receivers == null || r.nextReceiver >= numReceivers - || r.resultAbort || forceReceive) { - // Send the final result if requested - if (r.resultTo != null) { - boolean sendResult = true; - - // if this was part of a split/deferral complex, update the refcount and only - // send the completion when we clear all of them - if (r.splitToken != 0) { - int newCount = mSplitRefcounts.get(r.splitToken) - 1; - if (newCount == 0) { - // done! clear out this record's bookkeeping and deliver - if (DEBUG_BROADCAST_DEFERRAL) { - Slog.i(TAG_BROADCAST, - "Sending broadcast completion for split token " - + r.splitToken + " : " + r.intent.getAction()); - } - mSplitRefcounts.delete(r.splitToken); - } else { - // still have some split broadcast records in flight; update refcount - // and hold off on the callback - if (DEBUG_BROADCAST_DEFERRAL) { - Slog.i(TAG_BROADCAST, - "Result refcount now " + newCount + " for split token " - + r.splitToken + " : " + r.intent.getAction() - + " - not sending completion yet"); - } - sendResult = false; - mSplitRefcounts.put(r.splitToken, newCount); - } - } - if (sendResult) { - if (r.callerApp != null) { - mService.mOomAdjuster.mCachedAppOptimizer.unfreezeTemporarily( - r.callerApp, OOM_ADJ_REASON_FINISH_RECEIVER); - } - try { - if (DEBUG_BROADCAST) { - Slog.i(TAG_BROADCAST, "Finishing broadcast [" + mQueueName + "] " - + r.intent.getAction() + " app=" + r.callerApp); - } - if (r.dispatchTime == 0) { - // The dispatch time here could be 0, in case it's a parallel - // broadcast but it has a result receiver. Set it to now. - r.dispatchTime = now; - } - r.mIsReceiverAppRunning = true; - performReceiveLocked(r.callerApp, r.resultTo, - new Intent(r.intent), r.resultCode, - r.resultData, r.resultExtras, false, false, r.userId, - r.callingUid, r.callingUid, - r.dispatchTime - r.enqueueTime, - now - r.dispatchTime); - logBootCompletedBroadcastCompletionLatencyIfPossible(r); - // Set this to null so that the reference - // (local and remote) isn't kept in the mBroadcastHistory. - r.resultTo = null; - } catch (RemoteException e) { - r.resultTo = null; - Slog.w(TAG, "Failure [" - + mQueueName + "] sending broadcast result of " - + r.intent, e); - } - } - } - - if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG"); - cancelBroadcastTimeoutLocked(); - - if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, - "Finished with ordered broadcast " + r); - - // ... and on to the next... - addBroadcastToHistoryLocked(r); - if (r.intent.getComponent() == null && r.intent.getPackage() == null - && (r.intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { - // This was an implicit broadcast... let's record it for posterity. - mService.addBroadcastStatLocked(r.intent.getAction(), r.callerPackage, - r.manifestCount, r.manifestSkipCount, r.finishTime-r.dispatchTime); - } - mDispatcher.retireBroadcastLocked(r); - r = null; - looped = true; - continue; - } - - // Check whether the next receiver is under deferral policy, and handle that - // accordingly. If the current broadcast was already part of deferred-delivery - // tracking, we know that it must now be deliverable as-is without re-deferral. - if (!r.deferred) { - final int receiverUid = r.getReceiverUid(r.receivers.get(r.nextReceiver)); - if (mDispatcher.isDeferringLocked(receiverUid)) { - if (DEBUG_BROADCAST_DEFERRAL) { - Slog.i(TAG_BROADCAST, "Next receiver in " + r + " uid " + receiverUid - + " at " + r.nextReceiver + " is under deferral"); - } - // If this is the only (remaining) receiver in the broadcast, "splitting" - // doesn't make sense -- just defer it as-is and retire it as the - // currently active outgoing broadcast. - BroadcastRecord defer; - if (r.nextReceiver + 1 == numReceivers) { - if (DEBUG_BROADCAST_DEFERRAL) { - Slog.i(TAG_BROADCAST, "Sole receiver of " + r - + " is under deferral; setting aside and proceeding"); - } - defer = r; - mDispatcher.retireBroadcastLocked(r); - } else { - // Nontrivial case; split out 'uid's receivers to a new broadcast record - // and defer that, then loop and pick up continuing delivery of the current - // record (now absent those receivers). - - // The split operation is guaranteed to match at least at 'nextReceiver' - defer = r.splitRecipientsLocked(receiverUid, r.nextReceiver); - if (DEBUG_BROADCAST_DEFERRAL) { - Slog.i(TAG_BROADCAST, "Post split:"); - Slog.i(TAG_BROADCAST, "Original broadcast receivers:"); - for (int i = 0; i < r.receivers.size(); i++) { - Slog.i(TAG_BROADCAST, " " + r.receivers.get(i)); - } - Slog.i(TAG_BROADCAST, "Split receivers:"); - for (int i = 0; i < defer.receivers.size(); i++) { - Slog.i(TAG_BROADCAST, " " + defer.receivers.get(i)); - } - } - // Track completion refcount as well if relevant - if (r.resultTo != null) { - int token = r.splitToken; - if (token == 0) { - // first split of this record; refcount for 'r' and 'deferred' - r.splitToken = defer.splitToken = nextSplitTokenLocked(); - mSplitRefcounts.put(r.splitToken, 2); - if (DEBUG_BROADCAST_DEFERRAL) { - Slog.i(TAG_BROADCAST, - "Broadcast needs split refcount; using new token " - + r.splitToken); - } - } else { - // new split from an already-refcounted situation; increment count - final int curCount = mSplitRefcounts.get(token); - if (DEBUG_BROADCAST_DEFERRAL) { - if (curCount == 0) { - Slog.wtf(TAG_BROADCAST, - "Split refcount is zero with token for " + r); - } - } - mSplitRefcounts.put(token, curCount + 1); - if (DEBUG_BROADCAST_DEFERRAL) { - Slog.i(TAG_BROADCAST, "New split count for token " + token - + " is " + (curCount + 1)); - } - } - } - } - mDispatcher.addDeferredBroadcast(receiverUid, defer); - r = null; - looped = true; - continue; - } - } - } while (r == null); - - // Get the next receiver... - int recIdx = r.nextReceiver++; - - // Keep track of when this receiver started, and make sure there - // is a timeout message pending to kill it if need be. - r.receiverTime = SystemClock.uptimeMillis(); - if (recIdx == 0) { - r.dispatchTime = r.receiverTime; - r.dispatchRealTime = SystemClock.elapsedRealtime(); - r.dispatchClockTime = System.currentTimeMillis(); - - if (mLogLatencyMetrics) { - FrameworkStatsLog.write( - FrameworkStatsLog.BROADCAST_DISPATCH_LATENCY_REPORTED, - r.dispatchClockTime - r.enqueueClockTime); - } - - if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { - Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, - createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING), - System.identityHashCode(r)); - Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, - createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED), - System.identityHashCode(r)); - } - if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast [" - + mQueueName + "] " + r); - } - if (! mPendingBroadcastTimeoutMessage) { - long timeoutTime = r.receiverTime + mConstants.TIMEOUT; - if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, - "Submitting BROADCAST_TIMEOUT_MSG [" - + mQueueName + "] for " + r + " at " + timeoutTime); - setBroadcastTimeoutLocked(timeoutTime); - } - - final BroadcastOptions brOptions = r.options; - final Object nextReceiver = r.receivers.get(recIdx); - - if (nextReceiver instanceof BroadcastFilter) { - // Simple case: this is a registered receiver who gets - // a direct call. - BroadcastFilter filter = (BroadcastFilter)nextReceiver; - if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, - "Delivering ordered [" - + mQueueName + "] to registered " - + filter + ": " + r); - r.mIsReceiverAppRunning = true; - deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx); - if (r.receiver == null || !r.ordered) { - // The receiver has already finished, so schedule to - // process the next one. - if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing [" - + mQueueName + "]: ordered=" - + r.ordered + " receiver=" + r.receiver); - r.state = BroadcastRecord.IDLE; - scheduleBroadcastsLocked(); - } else { - if (filter.receiverList != null) { - maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r); - // r is guaranteed ordered at this point, so we know finishReceiverLocked() - // will get a callback and handle the activity start token lifecycle. - } - } - return; - } - - // Hard case: need to instantiate the receiver, possibly - // starting its application process to host it. - - ResolveInfo info = - (ResolveInfo)nextReceiver; - ComponentName component = new ComponentName( - info.activityInfo.applicationInfo.packageName, - info.activityInfo.name); - - boolean skip = false; - if (brOptions != null && - (info.activityInfo.applicationInfo.targetSdkVersion - < brOptions.getMinManifestReceiverApiLevel() || - info.activityInfo.applicationInfo.targetSdkVersion - > brOptions.getMaxManifestReceiverApiLevel())) { - Slog.w(TAG, "Target SDK mismatch: receiver " + info.activityInfo - + " targets " + info.activityInfo.applicationInfo.targetSdkVersion - + " but delivery restricted to [" - + brOptions.getMinManifestReceiverApiLevel() + ", " - + brOptions.getMaxManifestReceiverApiLevel() - + "] broadcasting " + broadcastDescription(r, component)); - skip = true; - } - if (brOptions != null && - !brOptions.testRequireCompatChange(info.activityInfo.applicationInfo.uid)) { - Slog.w(TAG, "Compat change filtered: broadcasting " + broadcastDescription(r, component) - + " to uid " + info.activityInfo.applicationInfo.uid + " due to compat change " - + r.options.getRequireCompatChangeId()); - skip = true; - } - if (!skip && !mService.validateAssociationAllowedLocked(r.callerPackage, r.callingUid, - component.getPackageName(), info.activityInfo.applicationInfo.uid)) { - Slog.w(TAG, "Association not allowed: broadcasting " - + broadcastDescription(r, component)); - skip = true; - } - if (!skip) { - skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid, - r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid); - if (skip) { - Slog.w(TAG, "Firewall blocked: broadcasting " - + broadcastDescription(r, component)); - } - } - int perm = mService.checkComponentPermission(info.activityInfo.permission, - r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid, - info.activityInfo.exported); - if (!skip && perm != PackageManager.PERMISSION_GRANTED) { - if (!info.activityInfo.exported) { - Slog.w(TAG, "Permission Denial: broadcasting " - + broadcastDescription(r, component) - + " is not exported from uid " + info.activityInfo.applicationInfo.uid); - } else { - Slog.w(TAG, "Permission Denial: broadcasting " - + broadcastDescription(r, component) - + " requires " + info.activityInfo.permission); - } - skip = true; - } else if (!skip && info.activityInfo.permission != null) { - final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission); - if (opCode != AppOpsManager.OP_NONE && mService.getAppOpsManager().noteOpNoThrow(opCode, - r.callingUid, r.callerPackage, r.callerFeatureId, - "Broadcast delivered to " + info.activityInfo.name) - != AppOpsManager.MODE_ALLOWED) { - Slog.w(TAG, "Appop Denial: broadcasting " - + broadcastDescription(r, component) - + " requires appop " + AppOpsManager.permissionToOp( - info.activityInfo.permission)); - skip = true; - } - } - - boolean isSingleton = false; - try { - isSingleton = mService.isSingleton(info.activityInfo.processName, - info.activityInfo.applicationInfo, - info.activityInfo.name, info.activityInfo.flags); - } catch (SecurityException e) { - Slog.w(TAG, e.getMessage()); - skip = true; - } - if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) { - if (ActivityManager.checkUidPermission( - android.Manifest.permission.INTERACT_ACROSS_USERS, - info.activityInfo.applicationInfo.uid) - != PackageManager.PERMISSION_GRANTED) { - Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString() - + " requests FLAG_SINGLE_USER, but app does not hold " - + android.Manifest.permission.INTERACT_ACROSS_USERS); - skip = true; - } - } - if (!skip && info.activityInfo.applicationInfo.isInstantApp() - && r.callingUid != info.activityInfo.applicationInfo.uid) { - Slog.w(TAG, "Instant App Denial: receiving " - + r.intent - + " to " + component.flattenToShortString() - + " due to sender " + r.callerPackage - + " (uid " + r.callingUid + ")" - + " Instant Apps do not support manifest receivers"); - skip = true; - } - if (!skip && r.callerInstantApp - && (info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0 - && r.callingUid != info.activityInfo.applicationInfo.uid) { - Slog.w(TAG, "Instant App Denial: receiving " - + r.intent - + " to " + component.flattenToShortString() - + " requires receiver have visibleToInstantApps set" - + " due to sender " + r.callerPackage - + " (uid " + r.callingUid + ")"); - skip = true; - } - if (r.curApp != null && r.curApp.mErrorState.isCrashing()) { - // If the target process is crashing, just skip it. - Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r - + " to " + r.curApp + ": process crashing"); - skip = true; - } - if (!skip) { - boolean isAvailable = false; - try { - isAvailable = AppGlobals.getPackageManager().isPackageAvailable( - info.activityInfo.packageName, - UserHandle.getUserId(info.activityInfo.applicationInfo.uid)); - } catch (Exception e) { - // all such failures mean we skip this receiver - Slog.w(TAG, "Exception getting recipient info for " - + info.activityInfo.packageName, e); - } - if (!isAvailable) { - Slog.w(TAG_BROADCAST, - "Skipping delivery to " + info.activityInfo.packageName + " / " - + info.activityInfo.applicationInfo.uid - + " : package no longer available"); - skip = true; - } - } - - // If permissions need a review before any of the app components can run, we drop - // the broadcast and if the calling app is in the foreground and the broadcast is - // explicit we launch the review UI passing it a pending intent to send the skipped - // broadcast. - if (!skip) { - if (!requestStartTargetPermissionsReviewIfNeededLocked(r, - info.activityInfo.packageName, UserHandle.getUserId( - info.activityInfo.applicationInfo.uid))) { - Slog.w(TAG_BROADCAST, - "Skipping delivery: permission review required for " - + broadcastDescription(r, component)); - skip = true; - } - } - - // This is safe to do even if we are skipping the broadcast, and we need - // this information now to evaluate whether it is going to be allowed to run. - final int receiverUid = info.activityInfo.applicationInfo.uid; - // If it's a singleton, it needs to be the same app or a special app - if (r.callingUid != Process.SYSTEM_UID && isSingleton - && mService.isValidSingletonCall(r.callingUid, receiverUid)) { - info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0); - } - String targetProcess = info.activityInfo.processName; - ProcessRecord app = mService.getProcessRecordLocked(targetProcess, - info.activityInfo.applicationInfo.uid); - - if (!skip) { - final int allowed = mService.getAppStartModeLOSP( - info.activityInfo.applicationInfo.uid, info.activityInfo.packageName, - info.activityInfo.applicationInfo.targetSdkVersion, -1, true, false, false); - if (allowed != ActivityManager.APP_START_MODE_NORMAL) { - // We won't allow this receiver to be launched if the app has been - // completely disabled from launches, or it was not explicitly sent - // to it and the app is in a state that should not receive it - // (depending on how getAppStartModeLOSP has determined that). - if (allowed == ActivityManager.APP_START_MODE_DISABLED) { - Slog.w(TAG, "Background execution disabled: receiving " - + r.intent + " to " - + component.flattenToShortString()); - skip = true; - } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0) - || (r.intent.getComponent() == null - && r.intent.getPackage() == null - && ((r.intent.getFlags() - & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0) - && !isSignaturePerm(r.requiredPermissions))) { - mService.addBackgroundCheckViolationLocked(r.intent.getAction(), - component.getPackageName()); - Slog.w(TAG, "Background execution not allowed: receiving " - + r.intent + " to " - + component.flattenToShortString()); - skip = true; - } - } - } - - if (!skip && !Intent.ACTION_SHUTDOWN.equals(r.intent.getAction()) - && !mService.mUserController - .isUserRunning(UserHandle.getUserId(info.activityInfo.applicationInfo.uid), - 0 /* flags */)) { - skip = true; - Slog.w(TAG, - "Skipping delivery to " + info.activityInfo.packageName + " / " - + info.activityInfo.applicationInfo.uid + " : user is not running"); - } - - if (!skip && r.excludedPermissions != null && r.excludedPermissions.length > 0) { - for (int i = 0; i < r.excludedPermissions.length; i++) { - String excludedPermission = r.excludedPermissions[i]; - try { - perm = AppGlobals.getPackageManager() - .checkPermission(excludedPermission, - info.activityInfo.applicationInfo.packageName, - UserHandle - .getUserId(info.activityInfo.applicationInfo.uid)); - } catch (RemoteException e) { - perm = PackageManager.PERMISSION_DENIED; - } - - int appOp = AppOpsManager.permissionToOpCode(excludedPermission); - if (appOp != AppOpsManager.OP_NONE) { - // When there is an app op associated with the permission, - // skip when both the permission and the app op are - // granted. - if ((perm == PackageManager.PERMISSION_GRANTED) && ( - mService.getAppOpsManager().checkOpNoThrow(appOp, - info.activityInfo.applicationInfo.uid, - info.activityInfo.packageName) - == AppOpsManager.MODE_ALLOWED)) { - skip = true; - break; - } - } else { - // When there is no app op associated with the permission, - // skip when permission is granted. - if (perm == PackageManager.PERMISSION_GRANTED) { - skip = true; - break; - } - } - } - } - - // Check that the receiver does *not* belong to any of the excluded packages - if (!skip && r.excludedPackages != null && r.excludedPackages.length > 0) { - if (ArrayUtils.contains(r.excludedPackages, component.getPackageName())) { - Slog.w(TAG, "Skipping delivery of excluded package " - + r.intent + " to " - + component.flattenToShortString() - + " excludes package " + component.getPackageName() - + " due to sender " + r.callerPackage - + " (uid " + r.callingUid + ")"); - skip = true; - } - } - - if (!skip && info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID && - r.requiredPermissions != null && r.requiredPermissions.length > 0) { - for (int i = 0; i < r.requiredPermissions.length; i++) { - String requiredPermission = r.requiredPermissions[i]; - try { - perm = AppGlobals.getPackageManager(). - checkPermission(requiredPermission, - info.activityInfo.applicationInfo.packageName, - UserHandle - .getUserId(info.activityInfo.applicationInfo.uid)); - } catch (RemoteException e) { - perm = PackageManager.PERMISSION_DENIED; - } - if (perm != PackageManager.PERMISSION_GRANTED) { - Slog.w(TAG, "Permission Denial: receiving " - + r.intent + " to " - + component.flattenToShortString() - + " requires " + requiredPermission - + " due to sender " + r.callerPackage - + " (uid " + r.callingUid + ")"); - skip = true; - break; - } - int appOp = AppOpsManager.permissionToOpCode(requiredPermission); - if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp) { - if (!noteOpForManifestReceiver(appOp, r, info, component)) { - skip = true; - break; - } - } - } - } - if (!skip && r.appOp != AppOpsManager.OP_NONE) { - if (!noteOpForManifestReceiver(r.appOp, r, info, component)) { - skip = true; - } - } - - // Filter packages in the intent extras, skipping delivery if none of the packages is - // visible to the receiver. - Bundle filteredExtras = null; - if (!skip && r.filterExtrasForReceiver != null) { - final Bundle extras = r.intent.getExtras(); - if (extras != null) { - filteredExtras = r.filterExtrasForReceiver.apply(receiverUid, extras); - if (filteredExtras == null) { - if (DEBUG_BROADCAST) { - Slog.v(TAG, "Skipping delivery to " - + info.activityInfo.packageName + " / " + receiverUid - + " : receiver is filtered by the package visibility"); - } - skip = true; - } - } - } - - if (skip) { - if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, - "Skipping delivery of ordered [" + mQueueName + "] " - + r + " for reason described above"); - r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED; - r.receiver = null; - r.curFilter = null; - r.state = BroadcastRecord.IDLE; - r.manifestSkipCount++; - scheduleBroadcastsLocked(); - return; - } - r.manifestCount++; - - r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED; - r.state = BroadcastRecord.APP_RECEIVE; - r.curComponent = component; - r.curReceiver = info.activityInfo; - r.curFilteredExtras = filteredExtras; - if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) { - Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, " - + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = " - + receiverUid); - } - final boolean isActivityCapable = - (brOptions != null && brOptions.getTemporaryAppAllowlistDuration() > 0); - maybeScheduleTempAllowlistLocked(receiverUid, r, brOptions); - - // Report that a component is used for explicit broadcasts. - if (r.intent.getComponent() != null && r.curComponent != null - && !TextUtils.equals(r.curComponent.getPackageName(), r.callerPackage)) { - mService.mUsageStatsService.reportEvent( - r.curComponent.getPackageName(), r.userId, Event.APP_COMPONENT_USED); - } - - // Broadcast is being executed, its package can't be stopped. - try { - AppGlobals.getPackageManager().setPackageStoppedState( - r.curComponent.getPackageName(), false, r.userId); - } catch (RemoteException e) { - } catch (IllegalArgumentException e) { - Slog.w(TAG, "Failed trying to unstop package " - + r.curComponent.getPackageName() + ": " + e); - } - - // Is this receiver's application already running? - if (app != null && app.getThread() != null && !app.isKilled()) { - try { - app.addPackage(info.activityInfo.packageName, - info.activityInfo.applicationInfo.longVersionCode, mService.mProcessStats); - maybeAddAllowBackgroundActivityStartsToken(app, r); - r.mIsReceiverAppRunning = true; - processCurBroadcastLocked(r, app); - return; - } catch (RemoteException e) { - Slog.w(TAG, "Exception when sending broadcast to " - + r.curComponent, e); - } catch (RuntimeException e) { - Slog.wtf(TAG, "Failed sending broadcast to " - + r.curComponent + " with " + r.intent, e); - // If some unexpected exception happened, just skip - // this broadcast. At this point we are not in the call - // from a client, so throwing an exception out from here - // will crash the entire system instead of just whoever - // sent the broadcast. - logBroadcastReceiverDiscardLocked(r); - finishReceiverLocked(r, r.resultCode, r.resultData, - r.resultExtras, r.resultAbort, false); - scheduleBroadcastsLocked(); - // We need to reset the state if we failed to start the receiver. - r.state = BroadcastRecord.IDLE; - return; - } - - // If a dead object exception was thrown -- fall through to - // restart the application. - } - - // Not running -- get it started, to be executed when the app comes up. - if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, - "Need to start app [" - + mQueueName + "] " + targetProcess + " for broadcast " + r); - r.curApp = mService.startProcessLocked(targetProcess, - info.activityInfo.applicationInfo, true, - r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND, - new HostingRecord(HostingRecord.HOSTING_TYPE_BROADCAST, r.curComponent, - r.intent.getAction(), getHostingRecordTriggerType(r)), - isActivityCapable ? ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE : ZYGOTE_POLICY_FLAG_EMPTY, - (r.intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false); - if (r.curApp == null) { - // Ah, this recipient is unavailable. Finish it if necessary, - // and mark the broadcast record as ready for the next. - Slog.w(TAG, "Unable to launch app " - + info.activityInfo.applicationInfo.packageName + "/" - + receiverUid + " for broadcast " - + r.intent + ": process is bad"); - logBroadcastReceiverDiscardLocked(r); - finishReceiverLocked(r, r.resultCode, r.resultData, - r.resultExtras, r.resultAbort, false); - scheduleBroadcastsLocked(); - r.state = BroadcastRecord.IDLE; - return; - } - - maybeAddAllowBackgroundActivityStartsToken(r.curApp, r); - mPendingBroadcast = r; - mPendingBroadcastRecvIndex = recIdx; - } - - private String getHostingRecordTriggerType(BroadcastRecord r) { - if (r.alarm) { - return HostingRecord.TRIGGER_TYPE_ALARM; - } else if (r.pushMessage) { - return HostingRecord.TRIGGER_TYPE_PUSH_MESSAGE; - } else if (r.pushMessageOverQuota) { - return HostingRecord.TRIGGER_TYPE_PUSH_MESSAGE_OVER_QUOTA; - } - return HostingRecord.TRIGGER_TYPE_UNKNOWN; - } - - @Nullable - private String getTargetPackage(BroadcastRecord r) { - if (r.intent == null) { - return null; - } - if (r.intent.getPackage() != null) { - return r.intent.getPackage(); - } else if (r.intent.getComponent() != null) { - return r.intent.getComponent().getPackageName(); - } - return null; - } - - private void logBootCompletedBroadcastCompletionLatencyIfPossible(BroadcastRecord r) { - // Only log after last receiver. - // In case of split BOOT_COMPLETED broadcast, make sure only call this method on the - // last BroadcastRecord of the split broadcast which has non-null resultTo. - final int numReceivers = (r.receivers != null) ? r.receivers.size() : 0; - if (r.nextReceiver < numReceivers) { - return; - } - final String action = r.intent.getAction(); - int event = 0; - if (Intent.ACTION_LOCKED_BOOT_COMPLETED.equals(action)) { - event = BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__LOCKED_BOOT_COMPLETED; - } else if (Intent.ACTION_BOOT_COMPLETED.equals(action)) { - event = BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__BOOT_COMPLETED; - } - if (event != 0) { - final int dispatchLatency = (int)(r.dispatchTime - r.enqueueTime); - final int completeLatency = (int) - (SystemClock.uptimeMillis() - r.enqueueTime); - final int dispatchRealLatency = (int)(r.dispatchRealTime - r.enqueueRealTime); - final int completeRealLatency = (int) - (SystemClock.elapsedRealtime() - r.enqueueRealTime); - int userType = FrameworkStatsLog.USER_LIFECYCLE_JOURNEY_REPORTED__USER_TYPE__TYPE_UNKNOWN; - // This method is called very infrequently, no performance issue we call - // LocalServices.getService() here. - final UserManagerInternal umInternal = LocalServices.getService( - UserManagerInternal.class); - final UserInfo userInfo = umInternal.getUserInfo(r.userId); - if (userInfo != null) { - userType = UserManager.getUserTypeForStatsd(userInfo.userType); - } - Slog.i(TAG_BROADCAST, - "BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED action:" - + action - + " dispatchLatency:" + dispatchLatency - + " completeLatency:" + completeLatency - + " dispatchRealLatency:" + dispatchRealLatency - + " completeRealLatency:" + completeRealLatency - + " receiversSize:" + numReceivers - + " userId:" + r.userId - + " userType:" + (userInfo != null? userInfo.userType : null)); - FrameworkStatsLog.write( - BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED, - event, - dispatchLatency, - completeLatency, - dispatchRealLatency, - completeRealLatency, - r.userId, - userType); - } - } - - private void maybeReportBroadcastDispatchedEventLocked(BroadcastRecord r, int targetUid) { - if (r.options == null || r.options.getIdForResponseEvent() <= 0) { - return; - } - final String targetPackage = getTargetPackage(r); - // Ignore non-explicit broadcasts - if (targetPackage == null) { - return; - } - getUsageStatsManagerInternal().reportBroadcastDispatched( - r.callingUid, targetPackage, UserHandle.of(r.userId), - r.options.getIdForResponseEvent(), SystemClock.elapsedRealtime(), - mService.getUidStateLocked(targetUid)); - } - - @NonNull - private UsageStatsManagerInternal getUsageStatsManagerInternal() { - final UsageStatsManagerInternal usageStatsManagerInternal = - LocalServices.getService(UsageStatsManagerInternal.class); - return usageStatsManagerInternal; - } - - private boolean noteOpForManifestReceiver(int appOp, BroadcastRecord r, ResolveInfo info, - ComponentName component) { - if (ArrayUtils.isEmpty(info.activityInfo.attributionTags)) { - return noteOpForManifestReceiverInner(appOp, r, info, component, null); - } else { - // Attribution tags provided, noteOp each tag - for (String tag : info.activityInfo.attributionTags) { - if (!noteOpForManifestReceiverInner(appOp, r, info, component, tag)) { - return false; - } - } - return true; - } - } - - private boolean noteOpForManifestReceiverInner(int appOp, BroadcastRecord r, ResolveInfo info, - ComponentName component, String tag) { - if (mService.getAppOpsManager().noteOpNoThrow(appOp, - info.activityInfo.applicationInfo.uid, - info.activityInfo.packageName, - tag, - "Broadcast delivered to " + info.activityInfo.name) - != AppOpsManager.MODE_ALLOWED) { - Slog.w(TAG, "Appop Denial: receiving " - + r.intent + " to " - + component.flattenToShortString() - + " requires appop " + AppOpsManager.opToName(appOp) - + " due to sender " + r.callerPackage - + " (uid " + r.callingUid + ")"); - return false; - } - return true; - } - - private void maybeAddAllowBackgroundActivityStartsToken(ProcessRecord proc, BroadcastRecord r) { - if (r == null || proc == null || !r.allowBackgroundActivityStarts) { - return; - } - String msgToken = (proc.toShortString() + r.toString()).intern(); - // first, if there exists a past scheduled request to remove this token, drop - // that request - we don't want the token to be swept from under our feet... - mHandler.removeCallbacksAndMessages(msgToken); - // ...then add the token - proc.addOrUpdateAllowBackgroundActivityStartsToken(r, r.mBackgroundActivityStartsToken); - } - - final void setBroadcastTimeoutLocked(long timeoutTime) { - if (! mPendingBroadcastTimeoutMessage) { - Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this); - mHandler.sendMessageAtTime(msg, timeoutTime); - mPendingBroadcastTimeoutMessage = true; - } - } - - final void cancelBroadcastTimeoutLocked() { - if (mPendingBroadcastTimeoutMessage) { - mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this); - mPendingBroadcastTimeoutMessage = false; - } - } - - final void broadcastTimeoutLocked(boolean fromMsg) { - if (fromMsg) { - mPendingBroadcastTimeoutMessage = false; - } - - if (mDispatcher.isEmpty() || mDispatcher.getActiveBroadcastLocked() == null) { - return; - } - - long now = SystemClock.uptimeMillis(); - BroadcastRecord r = mDispatcher.getActiveBroadcastLocked(); - if (fromMsg) { - if (!mService.mProcessesReady) { - // Only process broadcast timeouts if the system is ready; some early - // broadcasts do heavy work setting up system facilities - return; - } - - // If the broadcast is generally exempt from timeout tracking, we're done - if (r.timeoutExempt) { - if (DEBUG_BROADCAST) { - Slog.i(TAG_BROADCAST, "Broadcast timeout but it's exempt: " - + r.intent.getAction()); - } - return; - } - - long timeoutTime = r.receiverTime + mConstants.TIMEOUT; - if (timeoutTime > now) { - // We can observe premature timeouts because we do not cancel and reset the - // broadcast timeout message after each receiver finishes. Instead, we set up - // an initial timeout then kick it down the road a little further as needed - // when it expires. - if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, - "Premature timeout [" - + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for " - + timeoutTime); - setBroadcastTimeoutLocked(timeoutTime); - return; - } - } - - if (r.state == BroadcastRecord.WAITING_SERVICES) { - // In this case the broadcast had already finished, but we had decided to wait - // for started services to finish as well before going on. So if we have actually - // waited long enough time timeout the broadcast, let's give up on the whole thing - // and just move on to the next. - Slog.i(TAG, "Waited long enough for: " + (r.curComponent != null - ? r.curComponent.flattenToShortString() : "(null)")); - r.curComponent = null; - r.state = BroadcastRecord.IDLE; - processNextBroadcastLocked(false, false); - return; - } - - // If the receiver app is being debugged we quietly ignore unresponsiveness, just - // tidying up and moving on to the next broadcast without crashing or ANRing this - // app just because it's stopped at a breakpoint. - final boolean debugging = (r.curApp != null && r.curApp.isDebugging()); - - long timeoutDurationMs = now - r.receiverTime; - Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver - + ", started " + timeoutDurationMs + "ms ago"); - r.receiverTime = now; - if (!debugging) { - r.anrCount++; - } - - ProcessRecord app = null; - TimeoutRecord timeoutRecord = null; - - Object curReceiver; - if (r.nextReceiver > 0) { - curReceiver = r.receivers.get(r.nextReceiver-1); - r.delivery[r.nextReceiver-1] = BroadcastRecord.DELIVERY_TIMEOUT; - } else { - curReceiver = r.curReceiver; - } - Slog.w(TAG, "Receiver during timeout of " + r + " : " + curReceiver); - logBroadcastReceiverDiscardLocked(r); - if (curReceiver != null && curReceiver instanceof BroadcastFilter) { - BroadcastFilter bf = (BroadcastFilter)curReceiver; - if (bf.receiverList.pid != 0 - && bf.receiverList.pid != ActivityManagerService.MY_PID) { - synchronized (mService.mPidsSelfLocked) { - app = mService.mPidsSelfLocked.get( - bf.receiverList.pid); - } - } - } else { - app = r.curApp; - } - - if (app != null) { - String anrMessage = - "Broadcast of " + r.intent.toString() + ", waited " + timeoutDurationMs - + "ms"; - timeoutRecord = TimeoutRecord.forBroadcastReceiver(anrMessage); - } - - if (mPendingBroadcast == r) { - mPendingBroadcast = null; - } - - // Move on to the next receiver. - finishReceiverLocked(r, r.resultCode, r.resultData, - r.resultExtras, r.resultAbort, false); - scheduleBroadcastsLocked(); - - if (!debugging && timeoutRecord != null) { - mService.mAnrHelper.appNotResponding(app, timeoutRecord); - } - } - - private final int ringAdvance(int x, final int increment, final int ringSize) { - x += increment; - if (x < 0) return (ringSize - 1); - else if (x >= ringSize) return 0; - else return x; - } - - private final void addBroadcastToHistoryLocked(BroadcastRecord original) { - if (original.callingUid < 0) { - // This was from a registerReceiver() call; ignore it. - return; - } - original.finishTime = SystemClock.uptimeMillis(); - - if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { - Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, - createBroadcastTraceTitle(original, BroadcastRecord.DELIVERY_DELIVERED), - System.identityHashCode(original)); - } - - final ApplicationInfo info = original.callerApp != null ? original.callerApp.info : null; - final String callerPackage = info != null ? info.packageName : original.callerPackage; - if (callerPackage != null) { - mService.mHandler.obtainMessage(ActivityManagerService.DISPATCH_SENDING_BROADCAST_EVENT, - original.callingUid, 0, callerPackage).sendToTarget(); - } - - // Note sometimes (only for sticky broadcasts?) we reuse BroadcastRecords, - // So don't change the incoming record directly. - final BroadcastRecord historyRecord = original.maybeStripForHistory(); - - mBroadcastHistory[mHistoryNext] = historyRecord; - mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY); - - mBroadcastSummaryHistory[mSummaryHistoryNext] = historyRecord.intent; - mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = historyRecord.enqueueClockTime; - mSummaryHistoryDispatchTime[mSummaryHistoryNext] = historyRecord.dispatchClockTime; - mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis(); - mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY); - } - - boolean cleanupDisabledPackageReceiversLocked( - String packageName, Set<String> filterByClasses, int userId, boolean doit) { - boolean didSomething = false; - for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) { - didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked( - packageName, filterByClasses, userId, doit); - if (!doit && didSomething) { - return true; - } - } - - didSomething |= mDispatcher.cleanupDisabledPackageReceiversLocked(packageName, - filterByClasses, userId, doit); - - return didSomething; - } - - final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) { - final int logIndex = r.nextReceiver - 1; - if (logIndex >= 0 && logIndex < r.receivers.size()) { - Object curReceiver = r.receivers.get(logIndex); - if (curReceiver instanceof BroadcastFilter) { - BroadcastFilter bf = (BroadcastFilter) curReceiver; - EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER, - bf.owningUserId, System.identityHashCode(r), - r.intent.getAction(), logIndex, System.identityHashCode(bf)); - } else { - ResolveInfo ri = (ResolveInfo) curReceiver; - EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP, - UserHandle.getUserId(ri.activityInfo.applicationInfo.uid), - System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString()); - } - } else { - if (logIndex < 0) Slog.w(TAG, - "Discarding broadcast before first receiver is invoked: " + r); - EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP, - -1, System.identityHashCode(r), - r.intent.getAction(), - r.nextReceiver, - "NONE"); - } - } - - private String createBroadcastTraceTitle(BroadcastRecord record, int state) { - return formatSimple("Broadcast %s from %s (%s) %s", - state == BroadcastRecord.DELIVERY_PENDING ? "in queue" : "dispatched", - record.callerPackage == null ? "" : record.callerPackage, - record.callerApp == null ? "process unknown" : record.callerApp.toShortString(), - record.intent == null ? "" : record.intent.getAction()); - } - - boolean isIdle() { - return mParallelBroadcasts.isEmpty() && mDispatcher.isIdle() - && (mPendingBroadcast == null); - } - - // Used by wait-for-broadcast-idle : fast-forward all current deferrals to - // be immediately deliverable. - void cancelDeferrals() { - synchronized (mService) { - mDispatcher.cancelDeferralsLocked(); - scheduleBroadcastsLocked(); - } - } - - String describeState() { - synchronized (mService) { - return mParallelBroadcasts.size() + " parallel; " - + mDispatcher.describeStateLocked(); - } - } - - void dumpDebug(ProtoOutputStream proto, long fieldId) { - long token = proto.start(fieldId); - proto.write(BroadcastQueueProto.QUEUE_NAME, mQueueName); - int N; - N = mParallelBroadcasts.size(); - for (int i = N - 1; i >= 0; i--) { - mParallelBroadcasts.get(i).dumpDebug(proto, BroadcastQueueProto.PARALLEL_BROADCASTS); - } - mDispatcher.dumpDebug(proto, BroadcastQueueProto.ORDERED_BROADCASTS); - if (mPendingBroadcast != null) { - mPendingBroadcast.dumpDebug(proto, BroadcastQueueProto.PENDING_BROADCAST); - } - - int lastIndex = mHistoryNext; - int ringIndex = lastIndex; - do { - // increasing index = more recent entry, and we want to print the most - // recent first and work backwards, so we roll through the ring backwards. - ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY); - BroadcastRecord r = mBroadcastHistory[ringIndex]; - if (r != null) { - r.dumpDebug(proto, BroadcastQueueProto.HISTORICAL_BROADCASTS); - } - } while (ringIndex != lastIndex); - - lastIndex = ringIndex = mSummaryHistoryNext; - do { - ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY); - Intent intent = mBroadcastSummaryHistory[ringIndex]; - if (intent == null) { - continue; - } - long summaryToken = proto.start(BroadcastQueueProto.HISTORICAL_BROADCASTS_SUMMARY); - intent.dumpDebug(proto, BroadcastQueueProto.BroadcastSummary.INTENT, - false, true, true, false); - proto.write(BroadcastQueueProto.BroadcastSummary.ENQUEUE_CLOCK_TIME_MS, - mSummaryHistoryEnqueueTime[ringIndex]); - proto.write(BroadcastQueueProto.BroadcastSummary.DISPATCH_CLOCK_TIME_MS, - mSummaryHistoryDispatchTime[ringIndex]); - proto.write(BroadcastQueueProto.BroadcastSummary.FINISH_CLOCK_TIME_MS, - mSummaryHistoryFinishTime[ringIndex]); - proto.end(summaryToken); - } while (ringIndex != lastIndex); - proto.end(token); - } - - final boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args, - int opti, boolean dumpAll, String dumpPackage, boolean needSep) { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); - if (!mParallelBroadcasts.isEmpty() || !mDispatcher.isEmpty() - || mPendingBroadcast != null) { - boolean printed = false; - for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) { - BroadcastRecord br = mParallelBroadcasts.get(i); - if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) { - continue; - } - if (!printed) { - if (needSep) { - pw.println(); - } - needSep = true; - printed = true; - pw.println(" Active broadcasts [" + mQueueName + "]:"); - } - pw.println(" Active Broadcast " + mQueueName + " #" + i + ":"); - br.dump(pw, " ", sdf); - } - - mDispatcher.dumpLocked(pw, dumpPackage, mQueueName, sdf); - - if (dumpPackage == null || (mPendingBroadcast != null - && dumpPackage.equals(mPendingBroadcast.callerPackage))) { - pw.println(); - pw.println(" Pending broadcast [" + mQueueName + "]:"); - if (mPendingBroadcast != null) { - mPendingBroadcast.dump(pw, " ", sdf); - } else { - pw.println(" (null)"); - } - needSep = true; - } - } - - mConstants.dump(pw); - - int i; - boolean printed = false; + /** + * Quickly determine if this queue has broadcasts that are still waiting to + * be delivered at some point in the future. + * + * @see #flush() + */ + public abstract boolean isIdle(); - i = -1; - int lastIndex = mHistoryNext; - int ringIndex = lastIndex; - do { - // increasing index = more recent entry, and we want to print the most - // recent first and work backwards, so we roll through the ring backwards. - ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY); - BroadcastRecord r = mBroadcastHistory[ringIndex]; - if (r == null) { - continue; - } + /** + * Brief summary of internal state, useful for debugging purposes. + */ + public abstract String describeState(); - i++; // genuine record of some sort even if we're filtering it out - if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) { - continue; - } - if (!printed) { - if (needSep) { - pw.println(); - } - needSep = true; - pw.println(" Historical broadcasts [" + mQueueName + "]:"); - printed = true; - } - if (dumpAll) { - pw.print(" Historical Broadcast " + mQueueName + " #"); - pw.print(i); pw.println(":"); - r.dump(pw, " ", sdf); - } else { - pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r); - pw.print(" "); - pw.println(r.intent.toShortString(false, true, true, false)); - if (r.targetComp != null && r.targetComp != r.intent.getComponent()) { - pw.print(" targetComp: "); pw.println(r.targetComp.toShortString()); - } - Bundle bundle = r.intent.getExtras(); - if (bundle != null) { - pw.print(" extras: "); pw.println(bundle.toString()); - } - } - } while (ringIndex != lastIndex); + /** + * Flush any broadcasts still waiting to be delivered, causing them to be + * delivered as soon as possible. + * + * @see #isIdle() + */ + public abstract void flush(); - if (dumpPackage == null) { - lastIndex = ringIndex = mSummaryHistoryNext; - if (dumpAll) { - printed = false; - i = -1; - } else { - // roll over the 'i' full dumps that have already been issued - for (int j = i; - j > 0 && ringIndex != lastIndex;) { - ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY); - BroadcastRecord r = mBroadcastHistory[ringIndex]; - if (r == null) { - continue; - } - j--; - } - } - // done skipping; dump the remainder of the ring. 'i' is still the ordinal within - // the overall broadcast history. - do { - ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY); - Intent intent = mBroadcastSummaryHistory[ringIndex]; - if (intent == null) { - continue; - } - if (!printed) { - if (needSep) { - pw.println(); - } - needSep = true; - pw.println(" Historical broadcasts summary [" + mQueueName + "]:"); - printed = true; - } - if (!dumpAll && i >= 50) { - pw.println(" ..."); - break; - } - i++; - pw.print(" #"); pw.print(i); pw.print(": "); - pw.println(intent.toShortString(false, true, true, false)); - pw.print(" "); - TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex] - - mSummaryHistoryEnqueueTime[ringIndex], pw); - pw.print(" dispatch "); - TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex] - - mSummaryHistoryDispatchTime[ringIndex], pw); - pw.println(" finish"); - pw.print(" enq="); - pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex]))); - pw.print(" disp="); - pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex]))); - pw.print(" fin="); - pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex]))); - Bundle bundle = intent.getExtras(); - if (bundle != null) { - pw.print(" extras: "); pw.println(bundle.toString()); - } - } while (ringIndex != lastIndex); - } + public abstract void dumpDebug(ProtoOutputStream proto, long fieldId); - return needSep; - } + public abstract boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args, + int opti, boolean dumpAll, String dumpPackage, boolean needSep); } diff --git a/services/core/java/com/android/server/am/BroadcastQueueImpl.java b/services/core/java/com/android/server/am/BroadcastQueueImpl.java new file mode 100644 index 000000000000..4bffe351a379 --- /dev/null +++ b/services/core/java/com/android/server/am/BroadcastQueueImpl.java @@ -0,0 +1,1960 @@ +/* + * Copyright (C) 2012 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.server.am; + +import static android.app.ActivityManager.RESTRICTION_LEVEL_RESTRICTED_BUCKET; +import static android.os.Process.ZYGOTE_POLICY_FLAG_EMPTY; +import static android.os.Process.ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE; +import static android.text.TextUtils.formatSimple; + +import static com.android.internal.util.FrameworkStatsLog.BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED; +import static com.android.internal.util.FrameworkStatsLog.BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__BOOT_COMPLETED; +import static com.android.internal.util.FrameworkStatsLog.BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__LOCKED_BOOT_COMPLETED; +import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED; +import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_COLD; +import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM; +import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__MANIFEST; +import static com.android.internal.util.FrameworkStatsLog.BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__RUNTIME; +import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST; +import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_DEFERRAL; +import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_LIGHT; +import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU; +import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BROADCAST; +import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU; +import static com.android.server.am.OomAdjuster.OOM_ADJ_REASON_FINISH_RECEIVER; +import static com.android.server.am.OomAdjuster.OOM_ADJ_REASON_START_RECEIVER; + +import android.annotation.NonNull; +import android.annotation.Nullable; +import android.app.Activity; +import android.app.ActivityManager; +import android.app.AppGlobals; +import android.app.BroadcastOptions; +import android.app.IApplicationThread; +import android.app.RemoteServiceException.CannotDeliverBroadcastException; +import android.app.usage.UsageEvents.Event; +import android.app.usage.UsageStatsManagerInternal; +import android.content.ComponentName; +import android.content.ContentResolver; +import android.content.IIntentReceiver; +import android.content.Intent; +import android.content.pm.ActivityInfo; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; +import android.content.pm.UserInfo; +import android.os.Bundle; +import android.os.Handler; +import android.os.IBinder; +import android.os.Looper; +import android.os.Message; +import android.os.PowerExemptionManager.ReasonCode; +import android.os.PowerExemptionManager.TempAllowListType; +import android.os.Process; +import android.os.RemoteException; +import android.os.SystemClock; +import android.os.Trace; +import android.os.UserHandle; +import android.os.UserManager; +import android.text.TextUtils; +import android.util.EventLog; +import android.util.Slog; +import android.util.SparseIntArray; +import android.util.TimeUtils; +import android.util.proto.ProtoOutputStream; + +import com.android.internal.os.TimeoutRecord; +import com.android.internal.util.FrameworkStatsLog; +import com.android.server.LocalServices; +import com.android.server.pm.UserManagerInternal; + +import java.io.FileDescriptor; +import java.io.PrintWriter; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.Set; + +/** + * BROADCASTS + * + * We keep three broadcast queues and associated bookkeeping, one for those at + * foreground priority, and one for normal (background-priority) broadcasts, and one to + * offload special broadcasts that we know take a long time, such as BOOT_COMPLETED. + */ +public class BroadcastQueueImpl extends BroadcastQueue { + private static final String TAG_MU = TAG + POSTFIX_MU; + private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST; + + static final int MAX_BROADCAST_HISTORY = ActivityManager.isLowRamDeviceStatic() ? 10 : 50; + static final int MAX_BROADCAST_SUMMARY_HISTORY + = ActivityManager.isLowRamDeviceStatic() ? 25 : 300; + + /** + * If true, we can delay broadcasts while waiting services to finish in the previous + * receiver's process. + */ + final boolean mDelayBehindServices; + + /** + * Lists of all active broadcasts that are to be executed immediately + * (without waiting for another broadcast to finish). Currently this only + * contains broadcasts to registered receivers, to avoid spinning up + * a bunch of processes to execute IntentReceiver components. Background- + * and foreground-priority broadcasts are queued separately. + */ + final ArrayList<BroadcastRecord> mParallelBroadcasts = new ArrayList<>(); + + /** + * Tracking of the ordered broadcast queue, including deferral policy and alarm + * prioritization. + */ + final BroadcastDispatcher mDispatcher; + + /** + * Refcounting for completion callbacks of split/deferred broadcasts. The key + * is an opaque integer token assigned lazily when a broadcast is first split + * into multiple BroadcastRecord objects. + */ + final SparseIntArray mSplitRefcounts = new SparseIntArray(); + private int mNextToken = 0; + + /** + * Historical data of past broadcasts, for debugging. This is a ring buffer + * whose last element is at mHistoryNext. + */ + final BroadcastRecord[] mBroadcastHistory = new BroadcastRecord[MAX_BROADCAST_HISTORY]; + int mHistoryNext = 0; + + /** + * Summary of historical data of past broadcasts, for debugging. This is a + * ring buffer whose last element is at mSummaryHistoryNext. + */ + final Intent[] mBroadcastSummaryHistory = new Intent[MAX_BROADCAST_SUMMARY_HISTORY]; + int mSummaryHistoryNext = 0; + + /** + * Various milestone timestamps of entries in the mBroadcastSummaryHistory ring + * buffer, also tracked via the mSummaryHistoryNext index. These are all in wall + * clock time, not elapsed. + */ + final long[] mSummaryHistoryEnqueueTime = new long[MAX_BROADCAST_SUMMARY_HISTORY]; + final long[] mSummaryHistoryDispatchTime = new long[MAX_BROADCAST_SUMMARY_HISTORY]; + final long[] mSummaryHistoryFinishTime = new long[MAX_BROADCAST_SUMMARY_HISTORY]; + + /** + * Set when we current have a BROADCAST_INTENT_MSG in flight. + */ + boolean mBroadcastsScheduled = false; + + /** + * True if we have a pending unexpired BROADCAST_TIMEOUT_MSG posted to our handler. + */ + boolean mPendingBroadcastTimeoutMessage; + + /** + * Intent broadcasts that we have tried to start, but are + * waiting for the application's process to be created. We only + * need one per scheduling class (instead of a list) because we always + * process broadcasts one at a time, so no others can be started while + * waiting for this one. + */ + BroadcastRecord mPendingBroadcast = null; + + /** + * The receiver index that is pending, to restart the broadcast if needed. + */ + int mPendingBroadcastRecvIndex; + + static final int BROADCAST_INTENT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG; + static final int BROADCAST_TIMEOUT_MSG = ActivityManagerService.FIRST_BROADCAST_QUEUE_MSG + 1; + + // log latency metrics for ordered broadcasts during BOOT_COMPLETED processing + boolean mLogLatencyMetrics = true; + + final BroadcastHandler mHandler; + + private final class BroadcastHandler extends Handler { + public BroadcastHandler(Looper looper) { + super(looper, null, true); + } + + @Override + public void handleMessage(Message msg) { + switch (msg.what) { + case BROADCAST_INTENT_MSG: { + if (DEBUG_BROADCAST) Slog.v( + TAG_BROADCAST, "Received BROADCAST_INTENT_MSG [" + + mQueueName + "]"); + processNextBroadcast(true); + } break; + case BROADCAST_TIMEOUT_MSG: { + synchronized (mService) { + broadcastTimeoutLocked(true); + } + } break; + } + } + } + + BroadcastQueueImpl(ActivityManagerService service, Handler handler, + String name, BroadcastConstants constants, boolean allowDelayBehindServices) { + super(service, handler, name, constants); + mHandler = new BroadcastHandler(handler.getLooper()); + mDelayBehindServices = allowDelayBehindServices; + mDispatcher = new BroadcastDispatcher(this, mConstants, mHandler, mService); + } + + void start(ContentResolver resolver) { + mDispatcher.start(); + mConstants.startObserving(mHandler, resolver); + } + + public boolean isDelayBehindServices() { + return mDelayBehindServices; + } + + public BroadcastRecord getPendingBroadcastLocked() { + return mPendingBroadcast; + } + + public BroadcastRecord getActiveBroadcastLocked() { + return mDispatcher.getActiveBroadcastLocked(); + } + + public void enqueueBroadcastLocked(BroadcastRecord r) { + final boolean replacePending = (r.intent.getFlags() + & Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0; + + // Ordered broadcasts obviously need to be dispatched in serial order, + // but this implementation expects all manifest receivers to also be + // dispatched in a serial fashion + boolean serialDispatch = r.ordered; + if (!serialDispatch) { + final int N = (r.receivers != null) ? r.receivers.size() : 0; + for (int i = 0; i < N; i++) { + if (r.receivers.get(i) instanceof ResolveInfo) { + serialDispatch = true; + break; + } + } + } + + if (serialDispatch) { + final BroadcastRecord oldRecord = + replacePending ? replaceOrderedBroadcastLocked(r) : null; + if (oldRecord != null) { + // Replaced, fire the result-to receiver. + if (oldRecord.resultTo != null) { + try { + oldRecord.mIsReceiverAppRunning = true; + performReceiveLocked(oldRecord.callerApp, oldRecord.resultTo, + oldRecord.intent, + Activity.RESULT_CANCELED, null, null, + false, false, oldRecord.userId, oldRecord.callingUid, r.callingUid, + SystemClock.uptimeMillis() - oldRecord.enqueueTime, 0); + } catch (RemoteException e) { + Slog.w(TAG, "Failure [" + + mQueueName + "] sending broadcast result of " + + oldRecord.intent, e); + + } + } + } else { + enqueueOrderedBroadcastLocked(r); + scheduleBroadcastsLocked(); + } + } else { + final boolean replaced = replacePending + && (replaceParallelBroadcastLocked(r) != null); + // Note: We assume resultTo is null for non-ordered broadcasts. + if (!replaced) { + enqueueParallelBroadcastLocked(r); + scheduleBroadcastsLocked(); + } + } + } + + public void enqueueParallelBroadcastLocked(BroadcastRecord r) { + r.enqueueClockTime = System.currentTimeMillis(); + r.enqueueTime = SystemClock.uptimeMillis(); + r.enqueueRealTime = SystemClock.elapsedRealtime(); + mParallelBroadcasts.add(r); + enqueueBroadcastHelper(r); + } + + public void enqueueOrderedBroadcastLocked(BroadcastRecord r) { + r.enqueueClockTime = System.currentTimeMillis(); + r.enqueueTime = SystemClock.uptimeMillis(); + r.enqueueRealTime = SystemClock.elapsedRealtime(); + mDispatcher.enqueueOrderedBroadcastLocked(r); + enqueueBroadcastHelper(r); + } + + /** + * Don't call this method directly; call enqueueParallelBroadcastLocked or + * enqueueOrderedBroadcastLocked. + */ + private void enqueueBroadcastHelper(BroadcastRecord r) { + if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { + Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, + createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING), + System.identityHashCode(r)); + } + } + + /** + * Find the same intent from queued parallel broadcast, replace with a new one and return + * the old one. + */ + public final BroadcastRecord replaceParallelBroadcastLocked(BroadcastRecord r) { + return replaceBroadcastLocked(mParallelBroadcasts, r, "PARALLEL"); + } + + /** + * Find the same intent from queued ordered broadcast, replace with a new one and return + * the old one. + */ + public final BroadcastRecord replaceOrderedBroadcastLocked(BroadcastRecord r) { + return mDispatcher.replaceBroadcastLocked(r, "ORDERED"); + } + + private BroadcastRecord replaceBroadcastLocked(ArrayList<BroadcastRecord> queue, + BroadcastRecord r, String typeForLogging) { + final Intent intent = r.intent; + for (int i = queue.size() - 1; i > 0; i--) { + final BroadcastRecord old = queue.get(i); + if (old.userId == r.userId && intent.filterEquals(old.intent)) { + if (DEBUG_BROADCAST) { + Slog.v(TAG_BROADCAST, "***** DROPPING " + + typeForLogging + " [" + mQueueName + "]: " + intent); + } + queue.set(i, r); + return old; + } + } + return null; + } + + private final void processCurBroadcastLocked(BroadcastRecord r, + ProcessRecord app) throws RemoteException { + if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, + "Process cur broadcast " + r + " for app " + app); + final IApplicationThread thread = app.getThread(); + if (thread == null) { + throw new RemoteException(); + } + if (app.isInFullBackup()) { + skipReceiverLocked(r); + return; + } + + r.receiver = thread.asBinder(); + r.curApp = app; + final ProcessReceiverRecord prr = app.mReceivers; + prr.addCurReceiver(r); + app.mState.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER); + // Don't bump its LRU position if it's in the background restricted. + if (mService.mInternal.getRestrictionLevel(app.info.packageName, app.userId) + < RESTRICTION_LEVEL_RESTRICTED_BUCKET) { + mService.updateLruProcessLocked(app, false, null); + } + // Make sure the oom adj score is updated before delivering the broadcast. + // Force an update, even if there are other pending requests, overall it still saves time, + // because time(updateOomAdj(N apps)) <= N * time(updateOomAdj(1 app)). + mService.enqueueOomAdjTargetLocked(app); + mService.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_START_RECEIVER); + + // Tell the application to launch this receiver. + maybeReportBroadcastDispatchedEventLocked(r, r.curReceiver.applicationInfo.uid); + r.intent.setComponent(r.curComponent); + + boolean started = false; + try { + if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, + "Delivering to component " + r.curComponent + + ": " + r); + mService.notifyPackageUse(r.intent.getComponent().getPackageName(), + PackageManager.NOTIFY_PACKAGE_USE_BROADCAST_RECEIVER); + thread.scheduleReceiver(prepareReceiverIntent(r.intent, r.curFilteredExtras), + r.curReceiver, null /* compatInfo (unused but need to keep method signature) */, + r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId, + app.mState.getReportedProcState()); + if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, + "Process cur broadcast " + r + " DELIVERED for app " + app); + started = true; + } finally { + if (!started) { + if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, + "Process cur broadcast " + r + ": NOT STARTED!"); + r.receiver = null; + r.curApp = null; + prr.removeCurReceiver(r); + } + } + + // if something bad happens here, launch the app and try again + if (app.isKilled()) { + throw new RemoteException("app gets killed during broadcasting"); + } + } + + /** + * Called by ActivityManagerService to notify that the uid has process started, if there is any + * deferred BOOT_COMPLETED broadcast, the BroadcastDispatcher can dispatch the broadcast now. + * @param uid + */ + public void updateUidReadyForBootCompletedBroadcastLocked(int uid) { + mDispatcher.updateUidReadyForBootCompletedBroadcastLocked(uid); + scheduleBroadcastsLocked(); + } + + public boolean sendPendingBroadcastsLocked(ProcessRecord app) { + boolean didSomething = false; + final BroadcastRecord br = mPendingBroadcast; + if (br != null && br.curApp.getPid() > 0 && br.curApp.getPid() == app.getPid()) { + if (br.curApp != app) { + Slog.e(TAG, "App mismatch when sending pending broadcast to " + + app.processName + ", intended target is " + br.curApp.processName); + return false; + } + try { + mPendingBroadcast = null; + br.mIsReceiverAppRunning = false; + processCurBroadcastLocked(br, app); + didSomething = true; + } catch (Exception e) { + Slog.w(TAG, "Exception in new application when starting receiver " + + br.curComponent.flattenToShortString(), e); + logBroadcastReceiverDiscardLocked(br); + finishReceiverLocked(br, br.resultCode, br.resultData, + br.resultExtras, br.resultAbort, false); + scheduleBroadcastsLocked(); + // We need to reset the state if we failed to start the receiver. + br.state = BroadcastRecord.IDLE; + throw new RuntimeException(e.getMessage()); + } + } + return didSomething; + } + + public void skipPendingBroadcastLocked(int pid) { + final BroadcastRecord br = mPendingBroadcast; + if (br != null && br.curApp.getPid() == pid) { + br.state = BroadcastRecord.IDLE; + br.nextReceiver = mPendingBroadcastRecvIndex; + mPendingBroadcast = null; + scheduleBroadcastsLocked(); + } + } + + // Skip the current receiver, if any, that is in flight to the given process + public void skipCurrentReceiverLocked(ProcessRecord app) { + BroadcastRecord r = null; + final BroadcastRecord curActive = mDispatcher.getActiveBroadcastLocked(); + if (curActive != null && curActive.curApp == app) { + // confirmed: the current active broadcast is to the given app + r = curActive; + } + + // If the current active broadcast isn't this BUT we're waiting for + // mPendingBroadcast to spin up the target app, that's what we use. + if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) { + if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, + "[" + mQueueName + "] skip & discard pending app " + r); + r = mPendingBroadcast; + } + + if (r != null) { + skipReceiverLocked(r); + } + } + + private void skipReceiverLocked(BroadcastRecord r) { + logBroadcastReceiverDiscardLocked(r); + finishReceiverLocked(r, r.resultCode, r.resultData, + r.resultExtras, r.resultAbort, false); + scheduleBroadcastsLocked(); + } + + public void scheduleBroadcastsLocked() { + if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts [" + + mQueueName + "]: current=" + + mBroadcastsScheduled); + + if (mBroadcastsScheduled) { + return; + } + mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this)); + mBroadcastsScheduled = true; + } + + public BroadcastRecord getMatchingOrderedReceiver(IBinder receiver) { + BroadcastRecord br = mDispatcher.getActiveBroadcastLocked(); + if (br != null && br.receiver == receiver) { + return br; + } + return null; + } + + // > 0 only, no worry about "eventual" recycling + private int nextSplitTokenLocked() { + int next = mNextToken + 1; + if (next <= 0) { + next = 1; + } + mNextToken = next; + return next; + } + + private void postActivityStartTokenRemoval(ProcessRecord app, BroadcastRecord r) { + // the receiver had run for less than allowed bg activity start timeout, + // so allow the process to still start activities from bg for some more time + String msgToken = (app.toShortString() + r.toString()).intern(); + // first, if there exists a past scheduled request to remove this token, drop + // that request - we don't want the token to be swept from under our feet... + mHandler.removeCallbacksAndMessages(msgToken); + // ...then schedule the removal of the token after the extended timeout + mHandler.postAtTime(() -> { + synchronized (mService) { + app.removeAllowBackgroundActivityStartsToken(r); + } + }, msgToken, (r.receiverTime + mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT)); + } + + public boolean finishReceiverLocked(BroadcastRecord r, int resultCode, + String resultData, Bundle resultExtras, boolean resultAbort, boolean waitForServices) { + final int state = r.state; + final ActivityInfo receiver = r.curReceiver; + final long finishTime = SystemClock.uptimeMillis(); + final long elapsed = finishTime - r.receiverTime; + r.state = BroadcastRecord.IDLE; + final int curIndex = r.nextReceiver - 1; + if (curIndex >= 0 && curIndex < r.receivers.size() && r.curApp != null) { + final Object curReceiver = r.receivers.get(curIndex); + FrameworkStatsLog.write(BROADCAST_DELIVERY_EVENT_REPORTED, r.curApp.uid, + r.callingUid == -1 ? Process.SYSTEM_UID : r.callingUid, + ActivityManagerService.getShortAction(r.intent.getAction()), + curReceiver instanceof BroadcastFilter + ? BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__RUNTIME + : BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__MANIFEST, + r.mIsReceiverAppRunning + ? BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM + : BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_COLD, + r.dispatchTime - r.enqueueTime, + r.receiverTime - r.dispatchTime, + finishTime - r.receiverTime); + } + if (state == BroadcastRecord.IDLE) { + Slog.w(TAG_BROADCAST, "finishReceiver [" + mQueueName + "] called but state is IDLE"); + } + if (r.allowBackgroundActivityStarts && r.curApp != null) { + if (elapsed > mConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT) { + // if the receiver has run for more than allowed bg activity start timeout, + // just remove the token for this process now and we're done + r.curApp.removeAllowBackgroundActivityStartsToken(r); + } else { + // It gets more time; post the removal to happen at the appropriate moment + postActivityStartTokenRemoval(r.curApp, r); + } + } + // If we're abandoning this broadcast before any receivers were actually spun up, + // nextReceiver is zero; in which case time-to-process bookkeeping doesn't apply. + if (r.nextReceiver > 0) { + r.duration[r.nextReceiver - 1] = elapsed; + } + + // if this receiver was slow, impose deferral policy on the app. This will kick in + // when processNextBroadcastLocked() next finds this uid as a receiver identity. + if (!r.timeoutExempt) { + // r.curApp can be null if finish has raced with process death - benign + // edge case, and we just ignore it because we're already cleaning up + // as expected. + if (r.curApp != null + && mConstants.SLOW_TIME > 0 && elapsed > mConstants.SLOW_TIME) { + // Core system packages are exempt from deferral policy + if (!UserHandle.isCore(r.curApp.uid)) { + if (DEBUG_BROADCAST_DEFERRAL) { + Slog.i(TAG_BROADCAST, "Broadcast receiver " + (r.nextReceiver - 1) + + " was slow: " + receiver + " br=" + r); + } + mDispatcher.startDeferring(r.curApp.uid); + } else { + if (DEBUG_BROADCAST_DEFERRAL) { + Slog.i(TAG_BROADCAST, "Core uid " + r.curApp.uid + + " receiver was slow but not deferring: " + + receiver + " br=" + r); + } + } + } + } else { + if (DEBUG_BROADCAST_DEFERRAL) { + Slog.i(TAG_BROADCAST, "Finished broadcast " + r.intent.getAction() + + " is exempt from deferral policy"); + } + } + + r.receiver = null; + r.intent.setComponent(null); + if (r.curApp != null && r.curApp.mReceivers.hasCurReceiver(r)) { + r.curApp.mReceivers.removeCurReceiver(r); + mService.enqueueOomAdjTargetLocked(r.curApp); + } + if (r.curFilter != null) { + r.curFilter.receiverList.curBroadcast = null; + } + r.curFilter = null; + r.curReceiver = null; + r.curApp = null; + r.curFilteredExtras = null; + mPendingBroadcast = null; + + r.resultCode = resultCode; + r.resultData = resultData; + r.resultExtras = resultExtras; + if (resultAbort && (r.intent.getFlags()&Intent.FLAG_RECEIVER_NO_ABORT) == 0) { + r.resultAbort = resultAbort; + } else { + r.resultAbort = false; + } + + // If we want to wait behind services *AND* we're finishing the head/ + // active broadcast on its queue + if (waitForServices && r.curComponent != null && r.queue.isDelayBehindServices() + && r.queue.getActiveBroadcastLocked() == r) { + ActivityInfo nextReceiver; + if (r.nextReceiver < r.receivers.size()) { + Object obj = r.receivers.get(r.nextReceiver); + nextReceiver = (obj instanceof ActivityInfo) ? (ActivityInfo)obj : null; + } else { + nextReceiver = null; + } + // Don't do this if the next receive is in the same process as the current one. + if (receiver == null || nextReceiver == null + || receiver.applicationInfo.uid != nextReceiver.applicationInfo.uid + || !receiver.processName.equals(nextReceiver.processName)) { + // In this case, we are ready to process the next receiver for the current broadcast, + //Â but are on a queue that would like to wait for services to finish before moving + // on. If there are background services currently starting, then we will go into a + // special state where we hold off on continuing this broadcast until they are done. + if (mService.mServices.hasBackgroundServicesLocked(r.userId)) { + Slog.i(TAG, "Delay finish: " + r.curComponent.flattenToShortString()); + r.state = BroadcastRecord.WAITING_SERVICES; + return false; + } + } + } + + r.curComponent = null; + + // We will process the next receiver right now if this is finishing + // an app receiver (which is always asynchronous) or after we have + // come back from calling a receiver. + return state == BroadcastRecord.APP_RECEIVE + || state == BroadcastRecord.CALL_DONE_RECEIVE; + } + + public void backgroundServicesFinishedLocked(int userId) { + BroadcastRecord br = mDispatcher.getActiveBroadcastLocked(); + if (br != null) { + if (br.userId == userId && br.state == BroadcastRecord.WAITING_SERVICES) { + Slog.i(TAG, "Resuming delayed broadcast"); + br.curComponent = null; + br.state = BroadcastRecord.IDLE; + processNextBroadcastLocked(false, false); + } + } + } + + public void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver, + Intent intent, int resultCode, String data, Bundle extras, + boolean ordered, boolean sticky, int sendingUser, + int receiverUid, int callingUid, long dispatchDelay, + long receiveDelay) throws RemoteException { + // Send the intent to the receiver asynchronously using one-way binder calls. + if (app != null) { + final IApplicationThread thread = app.getThread(); + if (thread != null) { + // If we have an app thread, do the call through that so it is + // correctly ordered with other one-way calls. + try { + thread.scheduleRegisteredReceiver(receiver, intent, resultCode, + data, extras, ordered, sticky, sendingUser, + app.mState.getReportedProcState()); + // TODO: Uncomment this when (b/28322359) is fixed and we aren't getting + // DeadObjectException when the process isn't actually dead. + //} catch (DeadObjectException ex) { + // Failed to call into the process. It's dying so just let it die and move on. + // throw ex; + } catch (RemoteException ex) { + // Failed to call into the process. It's either dying or wedged. Kill it gently. + synchronized (mService) { + Slog.w(TAG, "Can't deliver broadcast to " + app.processName + + " (pid " + app.getPid() + "). Crashing it."); + app.scheduleCrashLocked("can't deliver broadcast", + CannotDeliverBroadcastException.TYPE_ID, /* extras=*/ null); + } + throw ex; + } + } else { + // Application has died. Receiver doesn't exist. + throw new RemoteException("app.thread must not be null"); + } + } else { + receiver.performReceive(intent, resultCode, data, extras, ordered, + sticky, sendingUser); + } + if (!ordered) { + FrameworkStatsLog.write(BROADCAST_DELIVERY_EVENT_REPORTED, + receiverUid == -1 ? Process.SYSTEM_UID : receiverUid, + callingUid == -1 ? Process.SYSTEM_UID : callingUid, + ActivityManagerService.getShortAction(intent.getAction()), + BROADCAST_DELIVERY_EVENT_REPORTED__RECEIVER_TYPE__RUNTIME, + BROADCAST_DELIVERY_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM, + dispatchDelay, receiveDelay, 0 /* finish_delay */); + } + } + + private void deliverToRegisteredReceiverLocked(BroadcastRecord r, + BroadcastFilter filter, boolean ordered, int index) { + boolean skip = mSkipPolicy.shouldSkip(r, filter); + + // Filter packages in the intent extras, skipping delivery if none of the packages is + // visible to the receiver. + Bundle filteredExtras = null; + if (!skip && r.filterExtrasForReceiver != null) { + final Bundle extras = r.intent.getExtras(); + if (extras != null) { + filteredExtras = r.filterExtrasForReceiver.apply(filter.receiverList.uid, extras); + if (filteredExtras == null) { + if (DEBUG_BROADCAST) { + Slog.v(TAG, "Skipping delivery to " + + filter.receiverList.app + + " : receiver is filtered by the package visibility"); + } + skip = true; + } + } + } + + if (skip) { + r.delivery[index] = BroadcastRecord.DELIVERY_SKIPPED; + return; + } + + r.delivery[index] = BroadcastRecord.DELIVERY_DELIVERED; + + // If this is not being sent as an ordered broadcast, then we + // don't want to touch the fields that keep track of the current + // state of ordered broadcasts. + if (ordered) { + r.receiver = filter.receiverList.receiver.asBinder(); + r.curFilter = filter; + filter.receiverList.curBroadcast = r; + r.state = BroadcastRecord.CALL_IN_RECEIVE; + if (filter.receiverList.app != null) { + // Bump hosting application to no longer be in background + // scheduling class. Note that we can't do that if there + // isn't an app... but we can only be in that case for + // things that directly call the IActivityManager API, which + // are already core system stuff so don't matter for this. + r.curApp = filter.receiverList.app; + filter.receiverList.app.mReceivers.addCurReceiver(r); + mService.enqueueOomAdjTargetLocked(r.curApp); + mService.updateOomAdjPendingTargetsLocked( + OOM_ADJ_REASON_START_RECEIVER); + } + } else if (filter.receiverList.app != null) { + mService.mOomAdjuster.mCachedAppOptimizer.unfreezeTemporarily(filter.receiverList.app, + OOM_ADJ_REASON_START_RECEIVER); + } + + try { + if (DEBUG_BROADCAST_LIGHT) Slog.i(TAG_BROADCAST, + "Delivering to " + filter + " : " + r); + if (filter.receiverList.app != null && filter.receiverList.app.isInFullBackup()) { + // Skip delivery if full backup in progress + // If it's an ordered broadcast, we need to continue to the next receiver. + if (ordered) { + skipReceiverLocked(r); + } + } else { + r.receiverTime = SystemClock.uptimeMillis(); + maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r); + maybeScheduleTempAllowlistLocked(filter.owningUid, r, r.options); + maybeReportBroadcastDispatchedEventLocked(r, filter.owningUid); + performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver, + prepareReceiverIntent(r.intent, filteredExtras), r.resultCode, r.resultData, + r.resultExtras, r.ordered, r.initialSticky, r.userId, + filter.receiverList.uid, r.callingUid, + r.dispatchTime - r.enqueueTime, + r.receiverTime - r.dispatchTime); + // parallel broadcasts are fire-and-forget, not bookended by a call to + // finishReceiverLocked(), so we manage their activity-start token here + if (filter.receiverList.app != null + && r.allowBackgroundActivityStarts && !r.ordered) { + postActivityStartTokenRemoval(filter.receiverList.app, r); + } + } + if (ordered) { + r.state = BroadcastRecord.CALL_DONE_RECEIVE; + } + } catch (RemoteException e) { + Slog.w(TAG, "Failure sending broadcast " + r.intent, e); + // Clean up ProcessRecord state related to this broadcast attempt + if (filter.receiverList.app != null) { + filter.receiverList.app.removeAllowBackgroundActivityStartsToken(r); + if (ordered) { + filter.receiverList.app.mReceivers.removeCurReceiver(r); + // Something wrong, its oom adj could be downgraded, but not in a hurry. + mService.enqueueOomAdjTargetLocked(r.curApp); + } + } + // And BroadcastRecord state related to ordered delivery, if appropriate + if (ordered) { + r.receiver = null; + r.curFilter = null; + filter.receiverList.curBroadcast = null; + } + } + } + + void maybeScheduleTempAllowlistLocked(int uid, BroadcastRecord r, + @Nullable BroadcastOptions brOptions) { + if (brOptions == null || brOptions.getTemporaryAppAllowlistDuration() <= 0) { + return; + } + long duration = brOptions.getTemporaryAppAllowlistDuration(); + final @TempAllowListType int type = brOptions.getTemporaryAppAllowlistType(); + final @ReasonCode int reasonCode = brOptions.getTemporaryAppAllowlistReasonCode(); + final String reason = brOptions.getTemporaryAppAllowlistReason(); + + if (duration > Integer.MAX_VALUE) { + duration = Integer.MAX_VALUE; + } + // XXX ideally we should pause the broadcast until everything behind this is done, + // or else we will likely start dispatching the broadcast before we have opened + // access to the app (there is a lot of asynchronicity behind this). It is probably + // not that big a deal, however, because the main purpose here is to allow apps + // to hold wake locks, and they will be able to acquire their wake lock immediately + // it just won't be enabled until we get through this work. + StringBuilder b = new StringBuilder(); + b.append("broadcast:"); + UserHandle.formatUid(b, r.callingUid); + b.append(":"); + if (r.intent.getAction() != null) { + b.append(r.intent.getAction()); + } else if (r.intent.getComponent() != null) { + r.intent.getComponent().appendShortString(b); + } else if (r.intent.getData() != null) { + b.append(r.intent.getData()); + } + b.append(",reason:"); + b.append(reason); + if (DEBUG_BROADCAST) { + Slog.v(TAG, "Broadcast temp allowlist uid=" + uid + " duration=" + duration + + " type=" + type + " : " + b.toString()); + } + mService.tempAllowlistUidLocked(uid, duration, reasonCode, b.toString(), type, + r.callingUid); + } + + private void processNextBroadcast(boolean fromMsg) { + synchronized (mService) { + processNextBroadcastLocked(fromMsg, false); + } + } + + private static Intent prepareReceiverIntent(@NonNull Intent originalIntent, + @Nullable Bundle filteredExtras) { + final Intent intent = new Intent(originalIntent); + if (filteredExtras != null) { + intent.replaceExtras(filteredExtras); + } + return intent; + } + + public void processNextBroadcastLocked(boolean fromMsg, boolean skipOomAdj) { + BroadcastRecord r; + + if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "processNextBroadcast [" + + mQueueName + "]: " + + mParallelBroadcasts.size() + " parallel broadcasts; " + + mDispatcher.describeStateLocked()); + + mService.updateCpuStats(); + + if (fromMsg) { + mBroadcastsScheduled = false; + } + + // First, deliver any non-serialized broadcasts right away. + while (mParallelBroadcasts.size() > 0) { + r = mParallelBroadcasts.remove(0); + r.dispatchTime = SystemClock.uptimeMillis(); + r.dispatchRealTime = SystemClock.elapsedRealtime(); + r.dispatchClockTime = System.currentTimeMillis(); + r.mIsReceiverAppRunning = true; + + if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { + Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, + createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING), + System.identityHashCode(r)); + Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, + createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED), + System.identityHashCode(r)); + } + + final int N = r.receivers.size(); + if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing parallel broadcast [" + + mQueueName + "] " + r); + for (int i=0; i<N; i++) { + Object target = r.receivers.get(i); + if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, + "Delivering non-ordered on [" + mQueueName + "] to registered " + + target + ": " + r); + deliverToRegisteredReceiverLocked(r, + (BroadcastFilter) target, false, i); + } + addBroadcastToHistoryLocked(r); + if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Done with parallel broadcast [" + + mQueueName + "] " + r); + } + + // Now take care of the next serialized one... + + // If we are waiting for a process to come up to handle the next + // broadcast, then do nothing at this point. Just in case, we + // check that the process we're waiting for still exists. + if (mPendingBroadcast != null) { + if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, + "processNextBroadcast [" + mQueueName + "]: waiting for " + + mPendingBroadcast.curApp); + + boolean isDead; + if (mPendingBroadcast.curApp.getPid() > 0) { + synchronized (mService.mPidsSelfLocked) { + ProcessRecord proc = mService.mPidsSelfLocked.get( + mPendingBroadcast.curApp.getPid()); + isDead = proc == null || proc.mErrorState.isCrashing(); + } + } else { + final ProcessRecord proc = mService.mProcessList.getProcessNamesLOSP().get( + mPendingBroadcast.curApp.processName, mPendingBroadcast.curApp.uid); + isDead = proc == null || !proc.isPendingStart(); + } + if (!isDead) { + // It's still alive, so keep waiting + return; + } else { + Slog.w(TAG, "pending app [" + + mQueueName + "]" + mPendingBroadcast.curApp + + " died before responding to broadcast"); + mPendingBroadcast.state = BroadcastRecord.IDLE; + mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex; + mPendingBroadcast = null; + } + } + + boolean looped = false; + + do { + final long now = SystemClock.uptimeMillis(); + r = mDispatcher.getNextBroadcastLocked(now); + + if (r == null) { + // No more broadcasts are deliverable right now, so all done! + mDispatcher.scheduleDeferralCheckLocked(false); + synchronized (mService.mAppProfiler.mProfilerLock) { + mService.mAppProfiler.scheduleAppGcsLPf(); + } + if (looped && !skipOomAdj) { + // If we had finished the last ordered broadcast, then + // make sure all processes have correct oom and sched + // adjustments. + mService.updateOomAdjPendingTargetsLocked( + OOM_ADJ_REASON_START_RECEIVER); + } + + // when we have no more ordered broadcast on this queue, stop logging + if (mService.mUserController.mBootCompleted && mLogLatencyMetrics) { + mLogLatencyMetrics = false; + } + + return; + } + + boolean forceReceive = false; + + // Ensure that even if something goes awry with the timeout + // detection, we catch "hung" broadcasts here, discard them, + // and continue to make progress. + // + // This is only done if the system is ready so that early-stage receivers + // don't get executed with timeouts; and of course other timeout- + // exempt broadcasts are ignored. + int numReceivers = (r.receivers != null) ? r.receivers.size() : 0; + if (mService.mProcessesReady && !r.timeoutExempt && r.dispatchTime > 0) { + if ((numReceivers > 0) && + (now > r.dispatchTime + (2 * mConstants.TIMEOUT * numReceivers))) { + Slog.w(TAG, "Hung broadcast [" + + mQueueName + "] discarded after timeout failure:" + + " now=" + now + + " dispatchTime=" + r.dispatchTime + + " startTime=" + r.receiverTime + + " intent=" + r.intent + + " numReceivers=" + numReceivers + + " nextReceiver=" + r.nextReceiver + + " state=" + r.state); + broadcastTimeoutLocked(false); // forcibly finish this broadcast + forceReceive = true; + r.state = BroadcastRecord.IDLE; + } + } + + if (r.state != BroadcastRecord.IDLE) { + if (DEBUG_BROADCAST) Slog.d(TAG_BROADCAST, + "processNextBroadcast(" + + mQueueName + ") called when not idle (state=" + + r.state + ")"); + return; + } + + // Is the current broadcast is done for any reason? + if (r.receivers == null || r.nextReceiver >= numReceivers + || r.resultAbort || forceReceive) { + // Send the final result if requested + if (r.resultTo != null) { + boolean sendResult = true; + + // if this was part of a split/deferral complex, update the refcount and only + // send the completion when we clear all of them + if (r.splitToken != 0) { + int newCount = mSplitRefcounts.get(r.splitToken) - 1; + if (newCount == 0) { + // done! clear out this record's bookkeeping and deliver + if (DEBUG_BROADCAST_DEFERRAL) { + Slog.i(TAG_BROADCAST, + "Sending broadcast completion for split token " + + r.splitToken + " : " + r.intent.getAction()); + } + mSplitRefcounts.delete(r.splitToken); + } else { + // still have some split broadcast records in flight; update refcount + // and hold off on the callback + if (DEBUG_BROADCAST_DEFERRAL) { + Slog.i(TAG_BROADCAST, + "Result refcount now " + newCount + " for split token " + + r.splitToken + " : " + r.intent.getAction() + + " - not sending completion yet"); + } + sendResult = false; + mSplitRefcounts.put(r.splitToken, newCount); + } + } + if (sendResult) { + if (r.callerApp != null) { + mService.mOomAdjuster.mCachedAppOptimizer.unfreezeTemporarily( + r.callerApp, OOM_ADJ_REASON_FINISH_RECEIVER); + } + try { + if (DEBUG_BROADCAST) { + Slog.i(TAG_BROADCAST, "Finishing broadcast [" + mQueueName + "] " + + r.intent.getAction() + " app=" + r.callerApp); + } + if (r.dispatchTime == 0) { + // The dispatch time here could be 0, in case it's a parallel + // broadcast but it has a result receiver. Set it to now. + r.dispatchTime = now; + } + r.mIsReceiverAppRunning = true; + performReceiveLocked(r.callerApp, r.resultTo, + new Intent(r.intent), r.resultCode, + r.resultData, r.resultExtras, false, false, r.userId, + r.callingUid, r.callingUid, + r.dispatchTime - r.enqueueTime, + now - r.dispatchTime); + logBootCompletedBroadcastCompletionLatencyIfPossible(r); + // Set this to null so that the reference + // (local and remote) isn't kept in the mBroadcastHistory. + r.resultTo = null; + } catch (RemoteException e) { + r.resultTo = null; + Slog.w(TAG, "Failure [" + + mQueueName + "] sending broadcast result of " + + r.intent, e); + } + } + } + + if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Cancelling BROADCAST_TIMEOUT_MSG"); + cancelBroadcastTimeoutLocked(); + + if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, + "Finished with ordered broadcast " + r); + + // ... and on to the next... + addBroadcastToHistoryLocked(r); + if (r.intent.getComponent() == null && r.intent.getPackage() == null + && (r.intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { + // This was an implicit broadcast... let's record it for posterity. + mService.addBroadcastStatLocked(r.intent.getAction(), r.callerPackage, + r.manifestCount, r.manifestSkipCount, r.finishTime-r.dispatchTime); + } + mDispatcher.retireBroadcastLocked(r); + r = null; + looped = true; + continue; + } + + // Check whether the next receiver is under deferral policy, and handle that + // accordingly. If the current broadcast was already part of deferred-delivery + // tracking, we know that it must now be deliverable as-is without re-deferral. + if (!r.deferred) { + final int receiverUid = r.getReceiverUid(r.receivers.get(r.nextReceiver)); + if (mDispatcher.isDeferringLocked(receiverUid)) { + if (DEBUG_BROADCAST_DEFERRAL) { + Slog.i(TAG_BROADCAST, "Next receiver in " + r + " uid " + receiverUid + + " at " + r.nextReceiver + " is under deferral"); + } + // If this is the only (remaining) receiver in the broadcast, "splitting" + // doesn't make sense -- just defer it as-is and retire it as the + // currently active outgoing broadcast. + BroadcastRecord defer; + if (r.nextReceiver + 1 == numReceivers) { + if (DEBUG_BROADCAST_DEFERRAL) { + Slog.i(TAG_BROADCAST, "Sole receiver of " + r + + " is under deferral; setting aside and proceeding"); + } + defer = r; + mDispatcher.retireBroadcastLocked(r); + } else { + // Nontrivial case; split out 'uid's receivers to a new broadcast record + // and defer that, then loop and pick up continuing delivery of the current + // record (now absent those receivers). + + // The split operation is guaranteed to match at least at 'nextReceiver' + defer = r.splitRecipientsLocked(receiverUid, r.nextReceiver); + if (DEBUG_BROADCAST_DEFERRAL) { + Slog.i(TAG_BROADCAST, "Post split:"); + Slog.i(TAG_BROADCAST, "Original broadcast receivers:"); + for (int i = 0; i < r.receivers.size(); i++) { + Slog.i(TAG_BROADCAST, " " + r.receivers.get(i)); + } + Slog.i(TAG_BROADCAST, "Split receivers:"); + for (int i = 0; i < defer.receivers.size(); i++) { + Slog.i(TAG_BROADCAST, " " + defer.receivers.get(i)); + } + } + // Track completion refcount as well if relevant + if (r.resultTo != null) { + int token = r.splitToken; + if (token == 0) { + // first split of this record; refcount for 'r' and 'deferred' + r.splitToken = defer.splitToken = nextSplitTokenLocked(); + mSplitRefcounts.put(r.splitToken, 2); + if (DEBUG_BROADCAST_DEFERRAL) { + Slog.i(TAG_BROADCAST, + "Broadcast needs split refcount; using new token " + + r.splitToken); + } + } else { + // new split from an already-refcounted situation; increment count + final int curCount = mSplitRefcounts.get(token); + if (DEBUG_BROADCAST_DEFERRAL) { + if (curCount == 0) { + Slog.wtf(TAG_BROADCAST, + "Split refcount is zero with token for " + r); + } + } + mSplitRefcounts.put(token, curCount + 1); + if (DEBUG_BROADCAST_DEFERRAL) { + Slog.i(TAG_BROADCAST, "New split count for token " + token + + " is " + (curCount + 1)); + } + } + } + } + mDispatcher.addDeferredBroadcast(receiverUid, defer); + r = null; + looped = true; + continue; + } + } + } while (r == null); + + // Get the next receiver... + int recIdx = r.nextReceiver++; + + // Keep track of when this receiver started, and make sure there + // is a timeout message pending to kill it if need be. + r.receiverTime = SystemClock.uptimeMillis(); + if (recIdx == 0) { + r.dispatchTime = r.receiverTime; + r.dispatchRealTime = SystemClock.elapsedRealtime(); + r.dispatchClockTime = System.currentTimeMillis(); + + if (mLogLatencyMetrics) { + FrameworkStatsLog.write( + FrameworkStatsLog.BROADCAST_DISPATCH_LATENCY_REPORTED, + r.dispatchClockTime - r.enqueueClockTime); + } + + if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { + Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, + createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_PENDING), + System.identityHashCode(r)); + Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, + createBroadcastTraceTitle(r, BroadcastRecord.DELIVERY_DELIVERED), + System.identityHashCode(r)); + } + if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, "Processing ordered broadcast [" + + mQueueName + "] " + r); + } + if (! mPendingBroadcastTimeoutMessage) { + long timeoutTime = r.receiverTime + mConstants.TIMEOUT; + if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, + "Submitting BROADCAST_TIMEOUT_MSG [" + + mQueueName + "] for " + r + " at " + timeoutTime); + setBroadcastTimeoutLocked(timeoutTime); + } + + final BroadcastOptions brOptions = r.options; + final Object nextReceiver = r.receivers.get(recIdx); + + if (nextReceiver instanceof BroadcastFilter) { + // Simple case: this is a registered receiver who gets + // a direct call. + BroadcastFilter filter = (BroadcastFilter)nextReceiver; + if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, + "Delivering ordered [" + + mQueueName + "] to registered " + + filter + ": " + r); + r.mIsReceiverAppRunning = true; + deliverToRegisteredReceiverLocked(r, filter, r.ordered, recIdx); + if (r.receiver == null || !r.ordered) { + // The receiver has already finished, so schedule to + // process the next one. + if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Quick finishing [" + + mQueueName + "]: ordered=" + + r.ordered + " receiver=" + r.receiver); + r.state = BroadcastRecord.IDLE; + scheduleBroadcastsLocked(); + } else { + if (filter.receiverList != null) { + maybeAddAllowBackgroundActivityStartsToken(filter.receiverList.app, r); + // r is guaranteed ordered at this point, so we know finishReceiverLocked() + // will get a callback and handle the activity start token lifecycle. + } + } + return; + } + + // Hard case: need to instantiate the receiver, possibly + // starting its application process to host it. + + final ResolveInfo info = + (ResolveInfo)nextReceiver; + final ComponentName component = new ComponentName( + info.activityInfo.applicationInfo.packageName, + info.activityInfo.name); + final int receiverUid = info.activityInfo.applicationInfo.uid; + + final String targetProcess = info.activityInfo.processName; + final ProcessRecord app = mService.getProcessRecordLocked(targetProcess, + info.activityInfo.applicationInfo.uid); + + boolean skip = mSkipPolicy.shouldSkip(r, info); + + // Filter packages in the intent extras, skipping delivery if none of the packages is + // visible to the receiver. + Bundle filteredExtras = null; + if (!skip && r.filterExtrasForReceiver != null) { + final Bundle extras = r.intent.getExtras(); + if (extras != null) { + filteredExtras = r.filterExtrasForReceiver.apply(receiverUid, extras); + if (filteredExtras == null) { + if (DEBUG_BROADCAST) { + Slog.v(TAG, "Skipping delivery to " + + info.activityInfo.packageName + " / " + receiverUid + + " : receiver is filtered by the package visibility"); + } + skip = true; + } + } + } + + if (skip) { + if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, + "Skipping delivery of ordered [" + mQueueName + "] " + + r + " for reason described above"); + r.delivery[recIdx] = BroadcastRecord.DELIVERY_SKIPPED; + r.receiver = null; + r.curFilter = null; + r.state = BroadcastRecord.IDLE; + r.manifestSkipCount++; + scheduleBroadcastsLocked(); + return; + } + r.manifestCount++; + + r.delivery[recIdx] = BroadcastRecord.DELIVERY_DELIVERED; + r.state = BroadcastRecord.APP_RECEIVE; + r.curComponent = component; + r.curReceiver = info.activityInfo; + r.curFilteredExtras = filteredExtras; + if (DEBUG_MU && r.callingUid > UserHandle.PER_USER_RANGE) { + Slog.v(TAG_MU, "Updated broadcast record activity info for secondary user, " + + info.activityInfo + ", callingUid = " + r.callingUid + ", uid = " + + receiverUid); + } + final boolean isActivityCapable = + (brOptions != null && brOptions.getTemporaryAppAllowlistDuration() > 0); + maybeScheduleTempAllowlistLocked(receiverUid, r, brOptions); + + // Report that a component is used for explicit broadcasts. + if (r.intent.getComponent() != null && r.curComponent != null + && !TextUtils.equals(r.curComponent.getPackageName(), r.callerPackage)) { + mService.mUsageStatsService.reportEvent( + r.curComponent.getPackageName(), r.userId, Event.APP_COMPONENT_USED); + } + + // Broadcast is being executed, its package can't be stopped. + try { + AppGlobals.getPackageManager().setPackageStoppedState( + r.curComponent.getPackageName(), false, r.userId); + } catch (RemoteException e) { + } catch (IllegalArgumentException e) { + Slog.w(TAG, "Failed trying to unstop package " + + r.curComponent.getPackageName() + ": " + e); + } + + // Is this receiver's application already running? + if (app != null && app.getThread() != null && !app.isKilled()) { + try { + app.addPackage(info.activityInfo.packageName, + info.activityInfo.applicationInfo.longVersionCode, mService.mProcessStats); + maybeAddAllowBackgroundActivityStartsToken(app, r); + r.mIsReceiverAppRunning = true; + processCurBroadcastLocked(r, app); + return; + } catch (RemoteException e) { + Slog.w(TAG, "Exception when sending broadcast to " + + r.curComponent, e); + } catch (RuntimeException e) { + Slog.wtf(TAG, "Failed sending broadcast to " + + r.curComponent + " with " + r.intent, e); + // If some unexpected exception happened, just skip + // this broadcast. At this point we are not in the call + // from a client, so throwing an exception out from here + // will crash the entire system instead of just whoever + // sent the broadcast. + logBroadcastReceiverDiscardLocked(r); + finishReceiverLocked(r, r.resultCode, r.resultData, + r.resultExtras, r.resultAbort, false); + scheduleBroadcastsLocked(); + // We need to reset the state if we failed to start the receiver. + r.state = BroadcastRecord.IDLE; + return; + } + + // If a dead object exception was thrown -- fall through to + // restart the application. + } + + // Not running -- get it started, to be executed when the app comes up. + if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, + "Need to start app [" + + mQueueName + "] " + targetProcess + " for broadcast " + r); + r.curApp = mService.startProcessLocked(targetProcess, + info.activityInfo.applicationInfo, true, + r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND, + new HostingRecord(HostingRecord.HOSTING_TYPE_BROADCAST, r.curComponent, + r.intent.getAction(), getHostingRecordTriggerType(r)), + isActivityCapable ? ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE : ZYGOTE_POLICY_FLAG_EMPTY, + (r.intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false); + if (r.curApp == null) { + // Ah, this recipient is unavailable. Finish it if necessary, + // and mark the broadcast record as ready for the next. + Slog.w(TAG, "Unable to launch app " + + info.activityInfo.applicationInfo.packageName + "/" + + receiverUid + " for broadcast " + + r.intent + ": process is bad"); + logBroadcastReceiverDiscardLocked(r); + finishReceiverLocked(r, r.resultCode, r.resultData, + r.resultExtras, r.resultAbort, false); + scheduleBroadcastsLocked(); + r.state = BroadcastRecord.IDLE; + return; + } + + maybeAddAllowBackgroundActivityStartsToken(r.curApp, r); + mPendingBroadcast = r; + mPendingBroadcastRecvIndex = recIdx; + } + + private String getHostingRecordTriggerType(BroadcastRecord r) { + if (r.alarm) { + return HostingRecord.TRIGGER_TYPE_ALARM; + } else if (r.pushMessage) { + return HostingRecord.TRIGGER_TYPE_PUSH_MESSAGE; + } else if (r.pushMessageOverQuota) { + return HostingRecord.TRIGGER_TYPE_PUSH_MESSAGE_OVER_QUOTA; + } + return HostingRecord.TRIGGER_TYPE_UNKNOWN; + } + + @Nullable + private String getTargetPackage(BroadcastRecord r) { + if (r.intent == null) { + return null; + } + if (r.intent.getPackage() != null) { + return r.intent.getPackage(); + } else if (r.intent.getComponent() != null) { + return r.intent.getComponent().getPackageName(); + } + return null; + } + + private void logBootCompletedBroadcastCompletionLatencyIfPossible(BroadcastRecord r) { + // Only log after last receiver. + // In case of split BOOT_COMPLETED broadcast, make sure only call this method on the + // last BroadcastRecord of the split broadcast which has non-null resultTo. + final int numReceivers = (r.receivers != null) ? r.receivers.size() : 0; + if (r.nextReceiver < numReceivers) { + return; + } + final String action = r.intent.getAction(); + int event = 0; + if (Intent.ACTION_LOCKED_BOOT_COMPLETED.equals(action)) { + event = BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__LOCKED_BOOT_COMPLETED; + } else if (Intent.ACTION_BOOT_COMPLETED.equals(action)) { + event = BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED__EVENT__BOOT_COMPLETED; + } + if (event != 0) { + final int dispatchLatency = (int)(r.dispatchTime - r.enqueueTime); + final int completeLatency = (int) + (SystemClock.uptimeMillis() - r.enqueueTime); + final int dispatchRealLatency = (int)(r.dispatchRealTime - r.enqueueRealTime); + final int completeRealLatency = (int) + (SystemClock.elapsedRealtime() - r.enqueueRealTime); + int userType = FrameworkStatsLog.USER_LIFECYCLE_JOURNEY_REPORTED__USER_TYPE__TYPE_UNKNOWN; + // This method is called very infrequently, no performance issue we call + // LocalServices.getService() here. + final UserManagerInternal umInternal = LocalServices.getService( + UserManagerInternal.class); + final UserInfo userInfo = umInternal.getUserInfo(r.userId); + if (userInfo != null) { + userType = UserManager.getUserTypeForStatsd(userInfo.userType); + } + Slog.i(TAG_BROADCAST, + "BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED action:" + + action + + " dispatchLatency:" + dispatchLatency + + " completeLatency:" + completeLatency + + " dispatchRealLatency:" + dispatchRealLatency + + " completeRealLatency:" + completeRealLatency + + " receiversSize:" + numReceivers + + " userId:" + r.userId + + " userType:" + (userInfo != null? userInfo.userType : null)); + FrameworkStatsLog.write( + BOOT_COMPLETED_BROADCAST_COMPLETION_LATENCY_REPORTED, + event, + dispatchLatency, + completeLatency, + dispatchRealLatency, + completeRealLatency, + r.userId, + userType); + } + } + + private void maybeReportBroadcastDispatchedEventLocked(BroadcastRecord r, int targetUid) { + if (r.options == null || r.options.getIdForResponseEvent() <= 0) { + return; + } + final String targetPackage = getTargetPackage(r); + // Ignore non-explicit broadcasts + if (targetPackage == null) { + return; + } + getUsageStatsManagerInternal().reportBroadcastDispatched( + r.callingUid, targetPackage, UserHandle.of(r.userId), + r.options.getIdForResponseEvent(), SystemClock.elapsedRealtime(), + mService.getUidStateLocked(targetUid)); + } + + @NonNull + private UsageStatsManagerInternal getUsageStatsManagerInternal() { + final UsageStatsManagerInternal usageStatsManagerInternal = + LocalServices.getService(UsageStatsManagerInternal.class); + return usageStatsManagerInternal; + } + + private void maybeAddAllowBackgroundActivityStartsToken(ProcessRecord proc, BroadcastRecord r) { + if (r == null || proc == null || !r.allowBackgroundActivityStarts) { + return; + } + String msgToken = (proc.toShortString() + r.toString()).intern(); + // first, if there exists a past scheduled request to remove this token, drop + // that request - we don't want the token to be swept from under our feet... + mHandler.removeCallbacksAndMessages(msgToken); + // ...then add the token + proc.addOrUpdateAllowBackgroundActivityStartsToken(r, r.mBackgroundActivityStartsToken); + } + + final void setBroadcastTimeoutLocked(long timeoutTime) { + if (! mPendingBroadcastTimeoutMessage) { + Message msg = mHandler.obtainMessage(BROADCAST_TIMEOUT_MSG, this); + mHandler.sendMessageAtTime(msg, timeoutTime); + mPendingBroadcastTimeoutMessage = true; + } + } + + final void cancelBroadcastTimeoutLocked() { + if (mPendingBroadcastTimeoutMessage) { + mHandler.removeMessages(BROADCAST_TIMEOUT_MSG, this); + mPendingBroadcastTimeoutMessage = false; + } + } + + final void broadcastTimeoutLocked(boolean fromMsg) { + if (fromMsg) { + mPendingBroadcastTimeoutMessage = false; + } + + if (mDispatcher.isEmpty() || mDispatcher.getActiveBroadcastLocked() == null) { + return; + } + + long now = SystemClock.uptimeMillis(); + BroadcastRecord r = mDispatcher.getActiveBroadcastLocked(); + if (fromMsg) { + if (!mService.mProcessesReady) { + // Only process broadcast timeouts if the system is ready; some early + // broadcasts do heavy work setting up system facilities + return; + } + + // If the broadcast is generally exempt from timeout tracking, we're done + if (r.timeoutExempt) { + if (DEBUG_BROADCAST) { + Slog.i(TAG_BROADCAST, "Broadcast timeout but it's exempt: " + + r.intent.getAction()); + } + return; + } + + long timeoutTime = r.receiverTime + mConstants.TIMEOUT; + if (timeoutTime > now) { + // We can observe premature timeouts because we do not cancel and reset the + // broadcast timeout message after each receiver finishes. Instead, we set up + // an initial timeout then kick it down the road a little further as needed + // when it expires. + if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, + "Premature timeout [" + + mQueueName + "] @ " + now + ": resetting BROADCAST_TIMEOUT_MSG for " + + timeoutTime); + setBroadcastTimeoutLocked(timeoutTime); + return; + } + } + + if (r.state == BroadcastRecord.WAITING_SERVICES) { + // In this case the broadcast had already finished, but we had decided to wait + // for started services to finish as well before going on. So if we have actually + // waited long enough time timeout the broadcast, let's give up on the whole thing + // and just move on to the next. + Slog.i(TAG, "Waited long enough for: " + (r.curComponent != null + ? r.curComponent.flattenToShortString() : "(null)")); + r.curComponent = null; + r.state = BroadcastRecord.IDLE; + processNextBroadcastLocked(false, false); + return; + } + + // If the receiver app is being debugged we quietly ignore unresponsiveness, just + // tidying up and moving on to the next broadcast without crashing or ANRing this + // app just because it's stopped at a breakpoint. + final boolean debugging = (r.curApp != null && r.curApp.isDebugging()); + + long timeoutDurationMs = now - r.receiverTime; + Slog.w(TAG, "Timeout of broadcast " + r + " - receiver=" + r.receiver + + ", started " + timeoutDurationMs + "ms ago"); + r.receiverTime = now; + if (!debugging) { + r.anrCount++; + } + + ProcessRecord app = null; + TimeoutRecord timeoutRecord = null; + + Object curReceiver; + if (r.nextReceiver > 0) { + curReceiver = r.receivers.get(r.nextReceiver-1); + r.delivery[r.nextReceiver-1] = BroadcastRecord.DELIVERY_TIMEOUT; + } else { + curReceiver = r.curReceiver; + } + Slog.w(TAG, "Receiver during timeout of " + r + " : " + curReceiver); + logBroadcastReceiverDiscardLocked(r); + if (curReceiver != null && curReceiver instanceof BroadcastFilter) { + BroadcastFilter bf = (BroadcastFilter)curReceiver; + if (bf.receiverList.pid != 0 + && bf.receiverList.pid != ActivityManagerService.MY_PID) { + synchronized (mService.mPidsSelfLocked) { + app = mService.mPidsSelfLocked.get( + bf.receiverList.pid); + } + } + } else { + app = r.curApp; + } + + if (app != null) { + String anrMessage = + "Broadcast of " + r.intent.toString() + ", waited " + timeoutDurationMs + + "ms"; + timeoutRecord = TimeoutRecord.forBroadcastReceiver(anrMessage); + } + + if (mPendingBroadcast == r) { + mPendingBroadcast = null; + } + + // Move on to the next receiver. + finishReceiverLocked(r, r.resultCode, r.resultData, + r.resultExtras, r.resultAbort, false); + scheduleBroadcastsLocked(); + + if (!debugging && timeoutRecord != null) { + mService.mAnrHelper.appNotResponding(app, timeoutRecord); + } + } + + private final int ringAdvance(int x, final int increment, final int ringSize) { + x += increment; + if (x < 0) return (ringSize - 1); + else if (x >= ringSize) return 0; + else return x; + } + + private final void addBroadcastToHistoryLocked(BroadcastRecord original) { + if (original.callingUid < 0) { + // This was from a registerReceiver() call; ignore it. + return; + } + original.finishTime = SystemClock.uptimeMillis(); + + if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { + Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, + createBroadcastTraceTitle(original, BroadcastRecord.DELIVERY_DELIVERED), + System.identityHashCode(original)); + } + + final ApplicationInfo info = original.callerApp != null ? original.callerApp.info : null; + final String callerPackage = info != null ? info.packageName : original.callerPackage; + if (callerPackage != null) { + mService.mHandler.obtainMessage(ActivityManagerService.DISPATCH_SENDING_BROADCAST_EVENT, + original.callingUid, 0, callerPackage).sendToTarget(); + } + + // Note sometimes (only for sticky broadcasts?) we reuse BroadcastRecords, + // So don't change the incoming record directly. + final BroadcastRecord historyRecord = original.maybeStripForHistory(); + + mBroadcastHistory[mHistoryNext] = historyRecord; + mHistoryNext = ringAdvance(mHistoryNext, 1, MAX_BROADCAST_HISTORY); + + mBroadcastSummaryHistory[mSummaryHistoryNext] = historyRecord.intent; + mSummaryHistoryEnqueueTime[mSummaryHistoryNext] = historyRecord.enqueueClockTime; + mSummaryHistoryDispatchTime[mSummaryHistoryNext] = historyRecord.dispatchClockTime; + mSummaryHistoryFinishTime[mSummaryHistoryNext] = System.currentTimeMillis(); + mSummaryHistoryNext = ringAdvance(mSummaryHistoryNext, 1, MAX_BROADCAST_SUMMARY_HISTORY); + } + + public boolean cleanupDisabledPackageReceiversLocked( + String packageName, Set<String> filterByClasses, int userId, boolean doit) { + boolean didSomething = false; + for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) { + didSomething |= mParallelBroadcasts.get(i).cleanupDisabledPackageReceiversLocked( + packageName, filterByClasses, userId, doit); + if (!doit && didSomething) { + return true; + } + } + + didSomething |= mDispatcher.cleanupDisabledPackageReceiversLocked(packageName, + filterByClasses, userId, doit); + + return didSomething; + } + + final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) { + final int logIndex = r.nextReceiver - 1; + if (logIndex >= 0 && logIndex < r.receivers.size()) { + Object curReceiver = r.receivers.get(logIndex); + if (curReceiver instanceof BroadcastFilter) { + BroadcastFilter bf = (BroadcastFilter) curReceiver; + EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER, + bf.owningUserId, System.identityHashCode(r), + r.intent.getAction(), logIndex, System.identityHashCode(bf)); + } else { + ResolveInfo ri = (ResolveInfo) curReceiver; + EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP, + UserHandle.getUserId(ri.activityInfo.applicationInfo.uid), + System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString()); + } + } else { + if (logIndex < 0) Slog.w(TAG, + "Discarding broadcast before first receiver is invoked: " + r); + EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP, + -1, System.identityHashCode(r), + r.intent.getAction(), + r.nextReceiver, + "NONE"); + } + } + + private String createBroadcastTraceTitle(BroadcastRecord record, int state) { + return formatSimple("Broadcast %s from %s (%s) %s", + state == BroadcastRecord.DELIVERY_PENDING ? "in queue" : "dispatched", + record.callerPackage == null ? "" : record.callerPackage, + record.callerApp == null ? "process unknown" : record.callerApp.toShortString(), + record.intent == null ? "" : record.intent.getAction()); + } + + public boolean isIdle() { + return mParallelBroadcasts.isEmpty() && mDispatcher.isIdle() + && (mPendingBroadcast == null); + } + + public void flush() { + cancelDeferrals(); + } + + // Used by wait-for-broadcast-idle : fast-forward all current deferrals to + // be immediately deliverable. + public void cancelDeferrals() { + synchronized (mService) { + mDispatcher.cancelDeferralsLocked(); + scheduleBroadcastsLocked(); + } + } + + public String describeState() { + synchronized (mService) { + return mParallelBroadcasts.size() + " parallel; " + + mDispatcher.describeStateLocked(); + } + } + + public void dumpDebug(ProtoOutputStream proto, long fieldId) { + long token = proto.start(fieldId); + proto.write(BroadcastQueueProto.QUEUE_NAME, mQueueName); + int N; + N = mParallelBroadcasts.size(); + for (int i = N - 1; i >= 0; i--) { + mParallelBroadcasts.get(i).dumpDebug(proto, BroadcastQueueProto.PARALLEL_BROADCASTS); + } + mDispatcher.dumpDebug(proto, BroadcastQueueProto.ORDERED_BROADCASTS); + if (mPendingBroadcast != null) { + mPendingBroadcast.dumpDebug(proto, BroadcastQueueProto.PENDING_BROADCAST); + } + + int lastIndex = mHistoryNext; + int ringIndex = lastIndex; + do { + // increasing index = more recent entry, and we want to print the most + // recent first and work backwards, so we roll through the ring backwards. + ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY); + BroadcastRecord r = mBroadcastHistory[ringIndex]; + if (r != null) { + r.dumpDebug(proto, BroadcastQueueProto.HISTORICAL_BROADCASTS); + } + } while (ringIndex != lastIndex); + + lastIndex = ringIndex = mSummaryHistoryNext; + do { + ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY); + Intent intent = mBroadcastSummaryHistory[ringIndex]; + if (intent == null) { + continue; + } + long summaryToken = proto.start(BroadcastQueueProto.HISTORICAL_BROADCASTS_SUMMARY); + intent.dumpDebug(proto, BroadcastQueueProto.BroadcastSummary.INTENT, + false, true, true, false); + proto.write(BroadcastQueueProto.BroadcastSummary.ENQUEUE_CLOCK_TIME_MS, + mSummaryHistoryEnqueueTime[ringIndex]); + proto.write(BroadcastQueueProto.BroadcastSummary.DISPATCH_CLOCK_TIME_MS, + mSummaryHistoryDispatchTime[ringIndex]); + proto.write(BroadcastQueueProto.BroadcastSummary.FINISH_CLOCK_TIME_MS, + mSummaryHistoryFinishTime[ringIndex]); + proto.end(summaryToken); + } while (ringIndex != lastIndex); + proto.end(token); + } + + public boolean dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args, + int opti, boolean dumpAll, String dumpPackage, boolean needSep) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); + if (!mParallelBroadcasts.isEmpty() || !mDispatcher.isEmpty() + || mPendingBroadcast != null) { + boolean printed = false; + for (int i = mParallelBroadcasts.size() - 1; i >= 0; i--) { + BroadcastRecord br = mParallelBroadcasts.get(i); + if (dumpPackage != null && !dumpPackage.equals(br.callerPackage)) { + continue; + } + if (!printed) { + if (needSep) { + pw.println(); + } + needSep = true; + printed = true; + pw.println(" Active broadcasts [" + mQueueName + "]:"); + } + pw.println(" Active Broadcast " + mQueueName + " #" + i + ":"); + br.dump(pw, " ", sdf); + } + + mDispatcher.dumpLocked(pw, dumpPackage, mQueueName, sdf); + + if (dumpPackage == null || (mPendingBroadcast != null + && dumpPackage.equals(mPendingBroadcast.callerPackage))) { + pw.println(); + pw.println(" Pending broadcast [" + mQueueName + "]:"); + if (mPendingBroadcast != null) { + mPendingBroadcast.dump(pw, " ", sdf); + } else { + pw.println(" (null)"); + } + needSep = true; + } + } + + mConstants.dump(pw); + + int i; + boolean printed = false; + + i = -1; + int lastIndex = mHistoryNext; + int ringIndex = lastIndex; + do { + // increasing index = more recent entry, and we want to print the most + // recent first and work backwards, so we roll through the ring backwards. + ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_HISTORY); + BroadcastRecord r = mBroadcastHistory[ringIndex]; + if (r == null) { + continue; + } + + i++; // genuine record of some sort even if we're filtering it out + if (dumpPackage != null && !dumpPackage.equals(r.callerPackage)) { + continue; + } + if (!printed) { + if (needSep) { + pw.println(); + } + needSep = true; + pw.println(" Historical broadcasts [" + mQueueName + "]:"); + printed = true; + } + if (dumpAll) { + pw.print(" Historical Broadcast " + mQueueName + " #"); + pw.print(i); pw.println(":"); + r.dump(pw, " ", sdf); + } else { + pw.print(" #"); pw.print(i); pw.print(": "); pw.println(r); + pw.print(" "); + pw.println(r.intent.toShortString(false, true, true, false)); + if (r.targetComp != null && r.targetComp != r.intent.getComponent()) { + pw.print(" targetComp: "); pw.println(r.targetComp.toShortString()); + } + Bundle bundle = r.intent.getExtras(); + if (bundle != null) { + pw.print(" extras: "); pw.println(bundle.toString()); + } + } + } while (ringIndex != lastIndex); + + if (dumpPackage == null) { + lastIndex = ringIndex = mSummaryHistoryNext; + if (dumpAll) { + printed = false; + i = -1; + } else { + // roll over the 'i' full dumps that have already been issued + for (int j = i; + j > 0 && ringIndex != lastIndex;) { + ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY); + BroadcastRecord r = mBroadcastHistory[ringIndex]; + if (r == null) { + continue; + } + j--; + } + } + // done skipping; dump the remainder of the ring. 'i' is still the ordinal within + // the overall broadcast history. + do { + ringIndex = ringAdvance(ringIndex, -1, MAX_BROADCAST_SUMMARY_HISTORY); + Intent intent = mBroadcastSummaryHistory[ringIndex]; + if (intent == null) { + continue; + } + if (!printed) { + if (needSep) { + pw.println(); + } + needSep = true; + pw.println(" Historical broadcasts summary [" + mQueueName + "]:"); + printed = true; + } + if (!dumpAll && i >= 50) { + pw.println(" ..."); + break; + } + i++; + pw.print(" #"); pw.print(i); pw.print(": "); + pw.println(intent.toShortString(false, true, true, false)); + pw.print(" "); + TimeUtils.formatDuration(mSummaryHistoryDispatchTime[ringIndex] + - mSummaryHistoryEnqueueTime[ringIndex], pw); + pw.print(" dispatch "); + TimeUtils.formatDuration(mSummaryHistoryFinishTime[ringIndex] + - mSummaryHistoryDispatchTime[ringIndex], pw); + pw.println(" finish"); + pw.print(" enq="); + pw.print(sdf.format(new Date(mSummaryHistoryEnqueueTime[ringIndex]))); + pw.print(" disp="); + pw.print(sdf.format(new Date(mSummaryHistoryDispatchTime[ringIndex]))); + pw.print(" fin="); + pw.println(sdf.format(new Date(mSummaryHistoryFinishTime[ringIndex]))); + Bundle bundle = intent.getExtras(); + if (bundle != null) { + pw.print(" extras: "); pw.println(bundle.toString()); + } + } while (ringIndex != lastIndex); + } + + return needSep; + } +} diff --git a/services/core/java/com/android/server/am/BroadcastSkipPolicy.java b/services/core/java/com/android/server/am/BroadcastSkipPolicy.java new file mode 100644 index 000000000000..9569848cbe37 --- /dev/null +++ b/services/core/java/com/android/server/am/BroadcastSkipPolicy.java @@ -0,0 +1,715 @@ +/* + * 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.server.am; + +import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST; +import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW; +import static com.android.server.am.ActivityManagerService.checkComponentPermission; +import static com.android.server.am.BroadcastQueue.TAG; + +import android.annotation.NonNull; +import android.app.ActivityManager; +import android.app.AppGlobals; +import android.app.AppOpsManager; +import android.app.BroadcastOptions; +import android.app.PendingIntent; +import android.content.ComponentName; +import android.content.IIntentSender; +import android.content.Intent; +import android.content.IntentSender; +import android.content.pm.ActivityInfo; +import android.content.pm.PackageManager; +import android.content.pm.PermissionInfo; +import android.content.pm.ResolveInfo; +import android.os.Bundle; +import android.os.Process; +import android.os.RemoteException; +import android.os.UserHandle; +import android.permission.IPermissionManager; +import android.util.Slog; + +import com.android.internal.util.ArrayUtils; + +/** + * Policy logic that decides if delivery of a particular {@link BroadcastRecord} + * should be skipped for a given {@link ResolveInfo} or {@link BroadcastFilter}. + * <p> + * This policy should be consulted as close as possible to the actual dispatch. + */ +public class BroadcastSkipPolicy { + private final ActivityManagerService mService; + + public BroadcastSkipPolicy(ActivityManagerService service) { + mService = service; + } + + /** + * Determine if the given {@link BroadcastRecord} is eligible to be sent to + * the given {@link ResolveInfo}. + */ + public boolean shouldSkip(@NonNull BroadcastRecord r, @NonNull ResolveInfo info) { + final BroadcastOptions brOptions = r.options; + final ComponentName component = new ComponentName( + info.activityInfo.applicationInfo.packageName, + info.activityInfo.name); + + if (brOptions != null && + (info.activityInfo.applicationInfo.targetSdkVersion + < brOptions.getMinManifestReceiverApiLevel() || + info.activityInfo.applicationInfo.targetSdkVersion + > brOptions.getMaxManifestReceiverApiLevel())) { + Slog.w(TAG, "Target SDK mismatch: receiver " + info.activityInfo + + " targets " + info.activityInfo.applicationInfo.targetSdkVersion + + " but delivery restricted to [" + + brOptions.getMinManifestReceiverApiLevel() + ", " + + brOptions.getMaxManifestReceiverApiLevel() + + "] broadcasting " + broadcastDescription(r, component)); + return true; + } + if (brOptions != null && + !brOptions.testRequireCompatChange(info.activityInfo.applicationInfo.uid)) { + Slog.w(TAG, "Compat change filtered: broadcasting " + broadcastDescription(r, component) + + " to uid " + info.activityInfo.applicationInfo.uid + " due to compat change " + + r.options.getRequireCompatChangeId()); + return true; + } + if (!mService.validateAssociationAllowedLocked(r.callerPackage, r.callingUid, + component.getPackageName(), info.activityInfo.applicationInfo.uid)) { + Slog.w(TAG, "Association not allowed: broadcasting " + + broadcastDescription(r, component)); + return true; + } + if (!mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid, + r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid)) { + Slog.w(TAG, "Firewall blocked: broadcasting " + + broadcastDescription(r, component)); + return true; + } + int perm = checkComponentPermission(info.activityInfo.permission, + r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid, + info.activityInfo.exported); + if (perm != PackageManager.PERMISSION_GRANTED) { + if (!info.activityInfo.exported) { + Slog.w(TAG, "Permission Denial: broadcasting " + + broadcastDescription(r, component) + + " is not exported from uid " + info.activityInfo.applicationInfo.uid); + } else { + Slog.w(TAG, "Permission Denial: broadcasting " + + broadcastDescription(r, component) + + " requires " + info.activityInfo.permission); + } + return true; + } else if (info.activityInfo.permission != null) { + final int opCode = AppOpsManager.permissionToOpCode(info.activityInfo.permission); + if (opCode != AppOpsManager.OP_NONE && mService.getAppOpsManager().noteOpNoThrow(opCode, + r.callingUid, r.callerPackage, r.callerFeatureId, + "Broadcast delivered to " + info.activityInfo.name) + != AppOpsManager.MODE_ALLOWED) { + Slog.w(TAG, "Appop Denial: broadcasting " + + broadcastDescription(r, component) + + " requires appop " + AppOpsManager.permissionToOp( + info.activityInfo.permission)); + return true; + } + } + + boolean isSingleton = false; + try { + isSingleton = mService.isSingleton(info.activityInfo.processName, + info.activityInfo.applicationInfo, + info.activityInfo.name, info.activityInfo.flags); + } catch (SecurityException e) { + Slog.w(TAG, e.getMessage()); + return true; + } + if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) { + if (ActivityManager.checkUidPermission( + android.Manifest.permission.INTERACT_ACROSS_USERS, + info.activityInfo.applicationInfo.uid) + != PackageManager.PERMISSION_GRANTED) { + Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString() + + " requests FLAG_SINGLE_USER, but app does not hold " + + android.Manifest.permission.INTERACT_ACROSS_USERS); + return true; + } + } + if (info.activityInfo.applicationInfo.isInstantApp() + && r.callingUid != info.activityInfo.applicationInfo.uid) { + Slog.w(TAG, "Instant App Denial: receiving " + + r.intent + + " to " + component.flattenToShortString() + + " due to sender " + r.callerPackage + + " (uid " + r.callingUid + ")" + + " Instant Apps do not support manifest receivers"); + return true; + } + if (r.callerInstantApp + && (info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0 + && r.callingUid != info.activityInfo.applicationInfo.uid) { + Slog.w(TAG, "Instant App Denial: receiving " + + r.intent + + " to " + component.flattenToShortString() + + " requires receiver have visibleToInstantApps set" + + " due to sender " + r.callerPackage + + " (uid " + r.callingUid + ")"); + return true; + } + if (r.curApp != null && r.curApp.mErrorState.isCrashing()) { + // If the target process is crashing, just skip it. + Slog.w(TAG, "Skipping deliver ordered [" + r.queue.toString() + "] " + r + + " to " + r.curApp + ": process crashing"); + return true; + } + + boolean isAvailable = false; + try { + isAvailable = AppGlobals.getPackageManager().isPackageAvailable( + info.activityInfo.packageName, + UserHandle.getUserId(info.activityInfo.applicationInfo.uid)); + } catch (Exception e) { + // all such failures mean we skip this receiver + Slog.w(TAG, "Exception getting recipient info for " + + info.activityInfo.packageName, e); + } + if (!isAvailable) { + Slog.w(TAG, + "Skipping delivery to " + info.activityInfo.packageName + " / " + + info.activityInfo.applicationInfo.uid + + " : package no longer available"); + return true; + } + + // If permissions need a review before any of the app components can run, we drop + // the broadcast and if the calling app is in the foreground and the broadcast is + // explicit we launch the review UI passing it a pending intent to send the skipped + // broadcast. + if (!requestStartTargetPermissionsReviewIfNeededLocked(r, + info.activityInfo.packageName, UserHandle.getUserId( + info.activityInfo.applicationInfo.uid))) { + Slog.w(TAG, + "Skipping delivery: permission review required for " + + broadcastDescription(r, component)); + return true; + } + + // This is safe to do even if we are skipping the broadcast, and we need + // this information now to evaluate whether it is going to be allowed to run. + final int receiverUid = info.activityInfo.applicationInfo.uid; + // If it's a singleton, it needs to be the same app or a special app + if (r.callingUid != Process.SYSTEM_UID && isSingleton + && mService.isValidSingletonCall(r.callingUid, receiverUid)) { + info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0); + } + + final int allowed = mService.getAppStartModeLOSP( + info.activityInfo.applicationInfo.uid, info.activityInfo.packageName, + info.activityInfo.applicationInfo.targetSdkVersion, -1, true, false, false); + if (allowed != ActivityManager.APP_START_MODE_NORMAL) { + // We won't allow this receiver to be launched if the app has been + // completely disabled from launches, or it was not explicitly sent + // to it and the app is in a state that should not receive it + // (depending on how getAppStartModeLOSP has determined that). + if (allowed == ActivityManager.APP_START_MODE_DISABLED) { + Slog.w(TAG, "Background execution disabled: receiving " + + r.intent + " to " + + component.flattenToShortString()); + return true; + } else if (((r.intent.getFlags()&Intent.FLAG_RECEIVER_EXCLUDE_BACKGROUND) != 0) + || (r.intent.getComponent() == null + && r.intent.getPackage() == null + && ((r.intent.getFlags() + & Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND) == 0) + && !isSignaturePerm(r.requiredPermissions))) { + mService.addBackgroundCheckViolationLocked(r.intent.getAction(), + component.getPackageName()); + Slog.w(TAG, "Background execution not allowed: receiving " + + r.intent + " to " + + component.flattenToShortString()); + return true; + } + } + + if (!Intent.ACTION_SHUTDOWN.equals(r.intent.getAction()) + && !mService.mUserController + .isUserRunning(UserHandle.getUserId(info.activityInfo.applicationInfo.uid), + 0 /* flags */)) { + Slog.w(TAG, + "Skipping delivery to " + info.activityInfo.packageName + " / " + + info.activityInfo.applicationInfo.uid + " : user is not running"); + return true; + } + + if (r.excludedPermissions != null && r.excludedPermissions.length > 0) { + for (int i = 0; i < r.excludedPermissions.length; i++) { + String excludedPermission = r.excludedPermissions[i]; + try { + perm = AppGlobals.getPackageManager() + .checkPermission(excludedPermission, + info.activityInfo.applicationInfo.packageName, + UserHandle + .getUserId(info.activityInfo.applicationInfo.uid)); + } catch (RemoteException e) { + perm = PackageManager.PERMISSION_DENIED; + } + + int appOp = AppOpsManager.permissionToOpCode(excludedPermission); + if (appOp != AppOpsManager.OP_NONE) { + // When there is an app op associated with the permission, + // skip when both the permission and the app op are + // granted. + if ((perm == PackageManager.PERMISSION_GRANTED) && ( + mService.getAppOpsManager().checkOpNoThrow(appOp, + info.activityInfo.applicationInfo.uid, + info.activityInfo.packageName) + == AppOpsManager.MODE_ALLOWED)) { + return true; + } + } else { + // When there is no app op associated with the permission, + // skip when permission is granted. + if (perm == PackageManager.PERMISSION_GRANTED) { + return true; + } + } + } + } + + // Check that the receiver does *not* belong to any of the excluded packages + if (r.excludedPackages != null && r.excludedPackages.length > 0) { + if (ArrayUtils.contains(r.excludedPackages, component.getPackageName())) { + Slog.w(TAG, "Skipping delivery of excluded package " + + r.intent + " to " + + component.flattenToShortString() + + " excludes package " + component.getPackageName() + + " due to sender " + r.callerPackage + + " (uid " + r.callingUid + ")"); + return true; + } + } + + if (info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID && + r.requiredPermissions != null && r.requiredPermissions.length > 0) { + for (int i = 0; i < r.requiredPermissions.length; i++) { + String requiredPermission = r.requiredPermissions[i]; + try { + perm = AppGlobals.getPackageManager(). + checkPermission(requiredPermission, + info.activityInfo.applicationInfo.packageName, + UserHandle + .getUserId(info.activityInfo.applicationInfo.uid)); + } catch (RemoteException e) { + perm = PackageManager.PERMISSION_DENIED; + } + if (perm != PackageManager.PERMISSION_GRANTED) { + Slog.w(TAG, "Permission Denial: receiving " + + r.intent + " to " + + component.flattenToShortString() + + " requires " + requiredPermission + + " due to sender " + r.callerPackage + + " (uid " + r.callingUid + ")"); + return true; + } + int appOp = AppOpsManager.permissionToOpCode(requiredPermission); + if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp) { + if (!noteOpForManifestReceiver(appOp, r, info, component)) { + return true; + } + } + } + } + if (r.appOp != AppOpsManager.OP_NONE) { + if (!noteOpForManifestReceiver(r.appOp, r, info, component)) { + return true; + } + } + + return false; + } + + /** + * Determine if the given {@link BroadcastRecord} is eligible to be sent to + * the given {@link BroadcastFilter}. + */ + public boolean shouldSkip(@NonNull BroadcastRecord r, @NonNull BroadcastFilter filter) { + if (r.options != null && !r.options.testRequireCompatChange(filter.owningUid)) { + Slog.w(TAG, "Compat change filtered: broadcasting " + r.intent.toString() + + " to uid " + filter.owningUid + " due to compat change " + + r.options.getRequireCompatChangeId()); + return true; + } + if (!mService.validateAssociationAllowedLocked(r.callerPackage, r.callingUid, + filter.packageName, filter.owningUid)) { + Slog.w(TAG, "Association not allowed: broadcasting " + + r.intent.toString() + + " from " + r.callerPackage + " (pid=" + r.callingPid + + ", uid=" + r.callingUid + ") to " + filter.packageName + " through " + + filter); + return true; + } + if (!mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid, + r.callingPid, r.resolvedType, filter.receiverList.uid)) { + Slog.w(TAG, "Firewall blocked: broadcasting " + + r.intent.toString() + + " from " + r.callerPackage + " (pid=" + r.callingPid + + ", uid=" + r.callingUid + ") to " + filter.packageName + " through " + + filter); + return true; + } + // Check that the sender has permission to send to this receiver + if (filter.requiredPermission != null) { + int perm = checkComponentPermission(filter.requiredPermission, + r.callingPid, r.callingUid, -1, true); + if (perm != PackageManager.PERMISSION_GRANTED) { + Slog.w(TAG, "Permission Denial: broadcasting " + + r.intent.toString() + + " from " + r.callerPackage + " (pid=" + + r.callingPid + ", uid=" + r.callingUid + ")" + + " requires " + filter.requiredPermission + + " due to registered receiver " + filter); + return true; + } else { + final int opCode = AppOpsManager.permissionToOpCode(filter.requiredPermission); + if (opCode != AppOpsManager.OP_NONE + && mService.getAppOpsManager().noteOpNoThrow(opCode, r.callingUid, + r.callerPackage, r.callerFeatureId, "Broadcast sent to protected receiver") + != AppOpsManager.MODE_ALLOWED) { + Slog.w(TAG, "Appop Denial: broadcasting " + + r.intent.toString() + + " from " + r.callerPackage + " (pid=" + + r.callingPid + ", uid=" + r.callingUid + ")" + + " requires appop " + AppOpsManager.permissionToOp( + filter.requiredPermission) + + " due to registered receiver " + filter); + return true; + } + } + } + + if ((filter.receiverList.app == null || filter.receiverList.app.isKilled() + || filter.receiverList.app.mErrorState.isCrashing())) { + Slog.w(TAG, "Skipping deliver [" + r.queue.toString() + "] " + r + + " to " + filter.receiverList + ": process gone or crashing"); + return true; + } + + // Ensure that broadcasts are only sent to other Instant Apps if they are marked as + // visible to Instant Apps. + final boolean visibleToInstantApps = + (r.intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0; + + if (!visibleToInstantApps && filter.instantApp + && filter.receiverList.uid != r.callingUid) { + Slog.w(TAG, "Instant App Denial: receiving " + + r.intent.toString() + + " to " + filter.receiverList.app + + " (pid=" + filter.receiverList.pid + + ", uid=" + filter.receiverList.uid + ")" + + " due to sender " + r.callerPackage + + " (uid " + r.callingUid + ")" + + " not specifying FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS"); + return true; + } + + if (!filter.visibleToInstantApp && r.callerInstantApp + && filter.receiverList.uid != r.callingUid) { + Slog.w(TAG, "Instant App Denial: receiving " + + r.intent.toString() + + " to " + filter.receiverList.app + + " (pid=" + filter.receiverList.pid + + ", uid=" + filter.receiverList.uid + ")" + + " requires receiver be visible to instant apps" + + " due to sender " + r.callerPackage + + " (uid " + r.callingUid + ")"); + return true; + } + + // Check that the receiver has the required permission(s) to receive this broadcast. + if (r.requiredPermissions != null && r.requiredPermissions.length > 0) { + for (int i = 0; i < r.requiredPermissions.length; i++) { + String requiredPermission = r.requiredPermissions[i]; + int perm = checkComponentPermission(requiredPermission, + filter.receiverList.pid, filter.receiverList.uid, -1, true); + if (perm != PackageManager.PERMISSION_GRANTED) { + Slog.w(TAG, "Permission Denial: receiving " + + r.intent.toString() + + " to " + filter.receiverList.app + + " (pid=" + filter.receiverList.pid + + ", uid=" + filter.receiverList.uid + ")" + + " requires " + requiredPermission + + " due to sender " + r.callerPackage + + " (uid " + r.callingUid + ")"); + return true; + } + int appOp = AppOpsManager.permissionToOpCode(requiredPermission); + if (appOp != AppOpsManager.OP_NONE && appOp != r.appOp + && mService.getAppOpsManager().noteOpNoThrow(appOp, + filter.receiverList.uid, filter.packageName, filter.featureId, + "Broadcast delivered to registered receiver " + filter.receiverId) + != AppOpsManager.MODE_ALLOWED) { + Slog.w(TAG, "Appop Denial: receiving " + + r.intent.toString() + + " to " + filter.receiverList.app + + " (pid=" + filter.receiverList.pid + + ", uid=" + filter.receiverList.uid + ")" + + " requires appop " + AppOpsManager.permissionToOp( + requiredPermission) + + " due to sender " + r.callerPackage + + " (uid " + r.callingUid + ")"); + return true; + } + } + } + if ((r.requiredPermissions == null || r.requiredPermissions.length == 0)) { + int perm = checkComponentPermission(null, + filter.receiverList.pid, filter.receiverList.uid, -1, true); + if (perm != PackageManager.PERMISSION_GRANTED) { + Slog.w(TAG, "Permission Denial: security check failed when receiving " + + r.intent.toString() + + " to " + filter.receiverList.app + + " (pid=" + filter.receiverList.pid + + ", uid=" + filter.receiverList.uid + ")" + + " due to sender " + r.callerPackage + + " (uid " + r.callingUid + ")"); + return true; + } + } + // Check that the receiver does *not* have any excluded permissions + if (r.excludedPermissions != null && r.excludedPermissions.length > 0) { + for (int i = 0; i < r.excludedPermissions.length; i++) { + String excludedPermission = r.excludedPermissions[i]; + final int perm = checkComponentPermission(excludedPermission, + filter.receiverList.pid, filter.receiverList.uid, -1, true); + + int appOp = AppOpsManager.permissionToOpCode(excludedPermission); + if (appOp != AppOpsManager.OP_NONE) { + // When there is an app op associated with the permission, + // skip when both the permission and the app op are + // granted. + if ((perm == PackageManager.PERMISSION_GRANTED) && ( + mService.getAppOpsManager().checkOpNoThrow(appOp, + filter.receiverList.uid, + filter.packageName) + == AppOpsManager.MODE_ALLOWED)) { + Slog.w(TAG, "Appop Denial: receiving " + + r.intent.toString() + + " to " + filter.receiverList.app + + " (pid=" + filter.receiverList.pid + + ", uid=" + filter.receiverList.uid + ")" + + " excludes appop " + AppOpsManager.permissionToOp( + excludedPermission) + + " due to sender " + r.callerPackage + + " (uid " + r.callingUid + ")"); + return true; + } + } else { + // When there is no app op associated with the permission, + // skip when permission is granted. + if (perm == PackageManager.PERMISSION_GRANTED) { + Slog.w(TAG, "Permission Denial: receiving " + + r.intent.toString() + + " to " + filter.receiverList.app + + " (pid=" + filter.receiverList.pid + + ", uid=" + filter.receiverList.uid + ")" + + " excludes " + excludedPermission + + " due to sender " + r.callerPackage + + " (uid " + r.callingUid + ")"); + return true; + } + } + } + } + + // Check that the receiver does *not* belong to any of the excluded packages + if (r.excludedPackages != null && r.excludedPackages.length > 0) { + if (ArrayUtils.contains(r.excludedPackages, filter.packageName)) { + Slog.w(TAG, "Skipping delivery of excluded package " + + r.intent.toString() + + " to " + filter.receiverList.app + + " (pid=" + filter.receiverList.pid + + ", uid=" + filter.receiverList.uid + ")" + + " excludes package " + filter.packageName + + " due to sender " + r.callerPackage + + " (uid " + r.callingUid + ")"); + return true; + } + } + + // If the broadcast also requires an app op check that as well. + if (r.appOp != AppOpsManager.OP_NONE + && mService.getAppOpsManager().noteOpNoThrow(r.appOp, + filter.receiverList.uid, filter.packageName, filter.featureId, + "Broadcast delivered to registered receiver " + filter.receiverId) + != AppOpsManager.MODE_ALLOWED) { + Slog.w(TAG, "Appop Denial: receiving " + + r.intent.toString() + + " to " + filter.receiverList.app + + " (pid=" + filter.receiverList.pid + + ", uid=" + filter.receiverList.uid + ")" + + " requires appop " + AppOpsManager.opToName(r.appOp) + + " due to sender " + r.callerPackage + + " (uid " + r.callingUid + ")"); + return true; + } + + // Ensure that broadcasts are only sent to other apps if they are explicitly marked as + // exported, or are System level broadcasts + if (!filter.exported && checkComponentPermission(null, r.callingPid, + r.callingUid, filter.receiverList.uid, filter.exported) + != PackageManager.PERMISSION_GRANTED) { + Slog.w(TAG, "Exported Denial: sending " + + r.intent.toString() + + ", action: " + r.intent.getAction() + + " from " + r.callerPackage + + " (uid=" + r.callingUid + ")" + + " due to receiver " + filter.receiverList.app + + " (uid " + filter.receiverList.uid + ")" + + " not specifying RECEIVER_EXPORTED"); + return true; + } + + // If permissions need a review before any of the app components can run, we drop + // the broadcast and if the calling app is in the foreground and the broadcast is + // explicit we launch the review UI passing it a pending intent to send the skipped + // broadcast. + if (!requestStartTargetPermissionsReviewIfNeededLocked(r, filter.packageName, + filter.owningUserId)) { + return true; + } + + return false; + } + + private static String broadcastDescription(BroadcastRecord r, ComponentName component) { + return r.intent.toString() + + " from " + r.callerPackage + " (pid=" + r.callingPid + + ", uid=" + r.callingUid + ") to " + component.flattenToShortString(); + } + + private boolean noteOpForManifestReceiver(int appOp, BroadcastRecord r, ResolveInfo info, + ComponentName component) { + if (ArrayUtils.isEmpty(info.activityInfo.attributionTags)) { + return noteOpForManifestReceiverInner(appOp, r, info, component, null); + } else { + // Attribution tags provided, noteOp each tag + for (String tag : info.activityInfo.attributionTags) { + if (!noteOpForManifestReceiverInner(appOp, r, info, component, tag)) { + return false; + } + } + return true; + } + } + + private boolean noteOpForManifestReceiverInner(int appOp, BroadcastRecord r, ResolveInfo info, + ComponentName component, String tag) { + if (mService.getAppOpsManager().noteOpNoThrow(appOp, + info.activityInfo.applicationInfo.uid, + info.activityInfo.packageName, + tag, + "Broadcast delivered to " + info.activityInfo.name) + != AppOpsManager.MODE_ALLOWED) { + Slog.w(TAG, "Appop Denial: receiving " + + r.intent + " to " + + component.flattenToShortString() + + " requires appop " + AppOpsManager.opToName(appOp) + + " due to sender " + r.callerPackage + + " (uid " + r.callingUid + ")"); + return false; + } + return true; + } + + /** + * Return true if all given permissions are signature-only perms. + */ + private boolean isSignaturePerm(String[] perms) { + if (perms == null) { + return false; + } + IPermissionManager pm = AppGlobals.getPermissionManager(); + for (int i = perms.length-1; i >= 0; i--) { + try { + PermissionInfo pi = pm.getPermissionInfo(perms[i], "android", 0); + if (pi == null) { + // a required permission that no package has actually + // defined cannot be signature-required. + return false; + } + if ((pi.protectionLevel & (PermissionInfo.PROTECTION_MASK_BASE + | PermissionInfo.PROTECTION_FLAG_PRIVILEGED)) + != PermissionInfo.PROTECTION_SIGNATURE) { + // If this a signature permission and NOT allowed for privileged apps, it + // is okay... otherwise, nope! + return false; + } + } catch (RemoteException e) { + return false; + } + } + return true; + } + + private boolean requestStartTargetPermissionsReviewIfNeededLocked( + BroadcastRecord receiverRecord, String receivingPackageName, + final int receivingUserId) { + if (!mService.getPackageManagerInternal().isPermissionsReviewRequired( + receivingPackageName, receivingUserId)) { + return true; + } + + final boolean callerForeground = receiverRecord.callerApp != null + ? receiverRecord.callerApp.mState.getSetSchedGroup() + != ProcessList.SCHED_GROUP_BACKGROUND : true; + + // Show a permission review UI only for explicit broadcast from a foreground app + if (callerForeground && receiverRecord.intent.getComponent() != null) { + IIntentSender target = mService.mPendingIntentController.getIntentSender( + ActivityManager.INTENT_SENDER_BROADCAST, receiverRecord.callerPackage, + receiverRecord.callerFeatureId, receiverRecord.callingUid, + receiverRecord.userId, null, null, 0, + new Intent[]{receiverRecord.intent}, + new String[]{receiverRecord.intent.resolveType(mService.mContext + .getContentResolver())}, + PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT + | PendingIntent.FLAG_IMMUTABLE, null); + + final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK + | Intent.FLAG_ACTIVITY_MULTIPLE_TASK + | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); + intent.putExtra(Intent.EXTRA_PACKAGE_NAME, receivingPackageName); + intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target)); + + if (DEBUG_PERMISSIONS_REVIEW) { + Slog.i(TAG, "u" + receivingUserId + " Launching permission review for package " + + receivingPackageName); + } + + mService.mHandler.post(new Runnable() { + @Override + public void run() { + mService.mContext.startActivityAsUser(intent, new UserHandle(receivingUserId)); + } + }); + } else { + Slog.w(TAG, "u" + receivingUserId + " Receiving a broadcast in package" + + receivingPackageName + " requires a permissions review"); + } + + return false; + } +} diff --git a/services/core/java/com/android/server/app/GameManagerService.java b/services/core/java/com/android/server/app/GameManagerService.java index 1302e226eba3..134e2061c090 100644 --- a/services/core/java/com/android/server/app/GameManagerService.java +++ b/services/core/java/com/android/server/app/GameManagerService.java @@ -502,6 +502,14 @@ public final class GameManagerService extends IGameManagerService.Stub { GamePackageConfiguration(PackageManager packageManager, String packageName, int userId) { mPackageName = packageName; + + // set flag default values + mPerfModeOptedIn = false; + mBatteryModeOptedIn = false; + mAllowDownscale = true; + mAllowAngle = true; + mAllowFpsOverride = true; + try { final ApplicationInfo ai = packageManager.getApplicationInfoAsUser(packageName, PackageManager.GET_META_DATA, userId); @@ -511,12 +519,6 @@ public final class GameManagerService extends IGameManagerService.Stub { mBatteryModeOptedIn = ai.metaData.getBoolean(METADATA_BATTERY_MODE_ENABLE); mAllowDownscale = ai.metaData.getBoolean(METADATA_WM_ALLOW_DOWNSCALE, true); mAllowAngle = ai.metaData.getBoolean(METADATA_ANGLE_ALLOW_ANGLE, true); - } else { - mPerfModeOptedIn = false; - mBatteryModeOptedIn = false; - mAllowDownscale = true; - mAllowAngle = true; - mAllowFpsOverride = true; } } } catch (NameNotFoundException e) { diff --git a/services/core/java/com/android/server/audio/AudioDeviceBroker.java b/services/core/java/com/android/server/audio/AudioDeviceBroker.java index eba9c7a5f14e..e97d9c22620e 100644 --- a/services/core/java/com/android/server/audio/AudioDeviceBroker.java +++ b/services/core/java/com/android/server/audio/AudioDeviceBroker.java @@ -1771,8 +1771,8 @@ import java.util.concurrent.atomic.AtomicBoolean; return; } Log.w(TAG, "Communication client died"); - removeCommunicationRouteClient(client.getBinder(), true); - onUpdateCommunicationRouteClient("onCommunicationRouteClientDied"); + setCommunicationRouteForClient(client.getBinder(), client.getPid(), null, + BtHelper.SCO_MODE_UNDEFINED, "onCommunicationRouteClientDied"); } /** diff --git a/services/core/java/com/android/server/audio/SpatializerHelper.java b/services/core/java/com/android/server/audio/SpatializerHelper.java index aedbe4eb945a..b7e817e15452 100644 --- a/services/core/java/com/android/server/audio/SpatializerHelper.java +++ b/services/core/java/com/android/server/audio/SpatializerHelper.java @@ -729,8 +729,11 @@ public class SpatializerHelper { } private boolean isDeviceCompatibleWithSpatializationModes(@NonNull AudioDeviceAttributes ada) { + // modeForDevice will be neither transaural or binaural for devices that do not support + // spatial audio. For instance mono devices like earpiece, speaker safe or sco must + // not be included. final byte modeForDevice = (byte) SPAT_MODE_FOR_DEVICE_TYPE.get(ada.getType(), - /*default when type not found*/ SpatializationMode.SPATIALIZER_BINAURAL); + /*default when type not found*/ -1); if ((modeForDevice == SpatializationMode.SPATIALIZER_BINAURAL && mBinauralSupported) || (modeForDevice == SpatializationMode.SPATIALIZER_TRANSAURAL && mTransauralSupported)) { @@ -1538,8 +1541,8 @@ public class SpatializerHelper { @Override public String toString() { - return "type:" + mDeviceType + " addr:" + mDeviceAddress + " enabled:" + mEnabled - + " HT:" + mHasHeadTracker + " HTenabled:" + mHeadTrackerEnabled; + return "type: " + mDeviceType + " addr: " + mDeviceAddress + " enabled: " + mEnabled + + " HT: " + mHasHeadTracker + " HTenabled: " + mHeadTrackerEnabled; } String toPersistableString() { diff --git a/services/core/java/com/android/server/biometrics/sensors/BiometricStateCallback.java b/services/core/java/com/android/server/biometrics/sensors/BiometricStateCallback.java index f8543162f95e..2263e80039bd 100644 --- a/services/core/java/com/android/server/biometrics/sensors/BiometricStateCallback.java +++ b/services/core/java/com/android/server/biometrics/sensors/BiometricStateCallback.java @@ -28,6 +28,7 @@ import android.content.pm.UserInfo; import android.hardware.biometrics.BiometricStateListener; import android.hardware.biometrics.IBiometricStateListener; import android.hardware.biometrics.SensorPropertiesInternal; +import android.os.IBinder; import android.os.RemoteException; import android.os.UserManager; import android.util.Slog; @@ -45,7 +46,8 @@ import java.util.concurrent.CopyOnWriteArrayList; * @param <P> internal property type */ public class BiometricStateCallback<T extends BiometricServiceProvider<P>, - P extends SensorPropertiesInternal> implements ClientMonitorCallback { + P extends SensorPropertiesInternal> + implements ClientMonitorCallback, IBinder.DeathRecipient { private static final String TAG = "BiometricStateCallback"; @@ -161,6 +163,11 @@ public class BiometricStateCallback<T extends BiometricServiceProvider<P>, @NonNull IBiometricStateListener listener) { mBiometricStateListeners.add(listener); broadcastCurrentEnrollmentState(listener); + try { + listener.asBinder().linkToDeath(this, 0 /* flags */); + } catch (RemoteException e) { + Slog.e(TAG, "Failed to link to death", e); + } } private synchronized void broadcastCurrentEnrollmentState( @@ -196,4 +203,19 @@ public class BiometricStateCallback<T extends BiometricServiceProvider<P>, Slog.e(TAG, "Remote exception", e); } } -} + + @Override + public void binderDied() { + // Do nothing, handled below + } + + @Override + public void binderDied(IBinder who) { + Slog.w(TAG, "Callback binder died: " + who); + if (mBiometricStateListeners.removeIf(listener -> listener.asBinder().equals(who))) { + Slog.w(TAG, "Removed dead listener for " + who); + } else { + Slog.w(TAG, "No dead listeners found"); + } + } +}
\ No newline at end of file diff --git a/services/core/java/com/android/server/broadcastradio/hal2/RadioEventLogger.java b/services/core/java/com/android/server/broadcastradio/hal2/RadioEventLogger.java new file mode 100644 index 000000000000..48112c452f02 --- /dev/null +++ b/services/core/java/com/android/server/broadcastradio/hal2/RadioEventLogger.java @@ -0,0 +1,44 @@ +/** + * 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.server.broadcastradio.hal2; + +import android.util.IndentingPrintWriter; +import android.util.LocalLog; +import android.util.Log; +import android.util.Slog; + +final class RadioEventLogger { + private final String mTag; + private final LocalLog mEventLogger; + + RadioEventLogger(String tag, int loggerQueueSize) { + mTag = tag; + mEventLogger = new LocalLog(loggerQueueSize); + } + + void logRadioEvent(String logFormat, Object... args) { + String log = String.format(logFormat, args); + mEventLogger.log(log); + if (Log.isLoggable(mTag, Log.DEBUG)) { + Slog.d(mTag, log); + } + } + + void dump(IndentingPrintWriter pw) { + mEventLogger.dump(pw); + } +} diff --git a/services/core/java/com/android/server/broadcastradio/hal2/RadioModule.java b/services/core/java/com/android/server/broadcastradio/hal2/RadioModule.java index 852aa66866f0..0a23e385d67a 100644 --- a/services/core/java/com/android/server/broadcastradio/hal2/RadioModule.java +++ b/services/core/java/com/android/server/broadcastradio/hal2/RadioModule.java @@ -55,12 +55,14 @@ import java.util.stream.Collectors; class RadioModule { private static final String TAG = "BcRadio2Srv.module"; + private static final int RADIO_EVENT_LOGGER_QUEUE_SIZE = 25; @NonNull private final IBroadcastRadio mService; @NonNull public final RadioManager.ModuleProperties mProperties; private final Object mLock; @NonNull private final Handler mHandler; + @NonNull private final RadioEventLogger mEventLogger; @GuardedBy("mLock") private ITunerSession mHalTunerSession; @@ -138,6 +140,7 @@ class RadioModule { mService = Objects.requireNonNull(service); mLock = Objects.requireNonNull(lock); mHandler = new Handler(Looper.getMainLooper()); + mEventLogger = new RadioEventLogger(TAG, RADIO_EVENT_LOGGER_QUEUE_SIZE); } public static @Nullable RadioModule tryLoadingModule(int idx, @NonNull String fqName, @@ -176,13 +179,14 @@ class RadioModule { public @NonNull TunerSession openSession(@NonNull android.hardware.radio.ITunerCallback userCb) throws RemoteException { - Slog.i(TAG, "Open TunerSession"); + mEventLogger.logRadioEvent("Open TunerSession"); synchronized (mLock) { if (mHalTunerSession == null) { Mutable<ITunerSession> hwSession = new Mutable<>(); mService.openSession(mHalTunerCallback, (result, session) -> { Convert.throwOnError("openSession", result); hwSession.value = session; + mEventLogger.logRadioEvent("New HIDL 2.0 tuner session is opened"); }); mHalTunerSession = Objects.requireNonNull(hwSession.value); } @@ -207,7 +211,7 @@ class RadioModule { // Copy the contents of mAidlTunerSessions into a local array because TunerSession.close() // must be called without mAidlTunerSessions locked because it can call // onTunerSessionClosed(). - Slog.i(TAG, "Close TunerSessions"); + mEventLogger.logRadioEvent("Close TunerSessions"); TunerSession[] tunerSessions; synchronized (mLock) { tunerSessions = new TunerSession[mAidlTunerSessions.size()]; @@ -320,7 +324,7 @@ class RadioModule { } onTunerSessionProgramListFilterChanged(null); if (mAidlTunerSessions.isEmpty() && mHalTunerSession != null) { - Slog.i(TAG, "Closing HAL tuner session"); + mEventLogger.logRadioEvent("Closing HAL tuner session"); try { mHalTunerSession.close(); } catch (RemoteException ex) { @@ -372,7 +376,7 @@ class RadioModule { public android.hardware.radio.ICloseHandle addAnnouncementListener(@NonNull int[] enabledTypes, @NonNull android.hardware.radio.IAnnouncementListener listener) throws RemoteException { - Slog.i(TAG, "Add AnnouncementListener"); + mEventLogger.logRadioEvent("Add AnnouncementListener"); ArrayList<Byte> enabledList = new ArrayList<>(); for (int type : enabledTypes) { enabledList.add((byte)type); @@ -409,7 +413,7 @@ class RadioModule { } Bitmap getImage(int id) { - Slog.i(TAG, "Get image for id " + id); + mEventLogger.logRadioEvent("Get image for id %d", id); if (id == 0) throw new IllegalArgumentException("Image ID is missing"); byte[] rawImage; @@ -449,6 +453,10 @@ class RadioModule { } pw.decreaseIndent(); } + pw.printf("Radio module events:\n"); + pw.increaseIndent(); + mEventLogger.dump(pw); + pw.decreaseIndent(); pw.decreaseIndent(); } } diff --git a/services/core/java/com/android/server/broadcastradio/hal2/TunerSession.java b/services/core/java/com/android/server/broadcastradio/hal2/TunerSession.java index 41f753c11216..918dc98e3a9e 100644 --- a/services/core/java/com/android/server/broadcastradio/hal2/TunerSession.java +++ b/services/core/java/com/android/server/broadcastradio/hal2/TunerSession.java @@ -28,7 +28,6 @@ import android.hardware.radio.ProgramSelector; import android.hardware.radio.RadioManager; import android.os.RemoteException; import android.util.IndentingPrintWriter; -import android.util.Log; import android.util.MutableBoolean; import android.util.MutableInt; import android.util.Slog; @@ -41,8 +40,10 @@ import java.util.Objects; class TunerSession extends ITuner.Stub { private static final String TAG = "BcRadio2Srv.session"; private static final String kAudioDeviceName = "Radio tuner source"; + private static final int TUNER_EVENT_LOGGER_QUEUE_SIZE = 25; private final Object mLock; + @NonNull private final RadioEventLogger mEventLogger; private final RadioModule mModule; private final ITunerSession mHwSession; @@ -61,15 +62,12 @@ class TunerSession extends ITuner.Stub { mHwSession = Objects.requireNonNull(hwSession); mCallback = Objects.requireNonNull(callback); mLock = Objects.requireNonNull(lock); - } - - private boolean isDebugEnabled() { - return Log.isLoggable(TAG, Log.DEBUG); + mEventLogger = new RadioEventLogger(TAG, TUNER_EVENT_LOGGER_QUEUE_SIZE); } @Override public void close() { - if (isDebugEnabled()) Slog.d(TAG, "Close"); + mEventLogger.logRadioEvent("Close"); close(null); } @@ -81,7 +79,7 @@ class TunerSession extends ITuner.Stub { * @param error Optional error to send to client before session is closed. */ public void close(@Nullable Integer error) { - if (isDebugEnabled()) Slog.d(TAG, "Close on error " + error); + mEventLogger.logRadioEvent("Close on error %d", error); synchronized (mLock) { if (mIsClosed) return; if (error != null) { @@ -145,10 +143,8 @@ class TunerSession extends ITuner.Stub { @Override public void step(boolean directionDown, boolean skipSubChannel) throws RemoteException { - if (isDebugEnabled()) { - Slog.d(TAG, "Step with directionDown " + directionDown - + " skipSubChannel " + skipSubChannel); - } + mEventLogger.logRadioEvent("Step with direction %s, skipSubChannel? %s", + directionDown ? "down" : "up", skipSubChannel ? "yes" : "no"); synchronized (mLock) { checkNotClosedLocked(); int halResult = mHwSession.step(!directionDown); @@ -158,10 +154,8 @@ class TunerSession extends ITuner.Stub { @Override public void scan(boolean directionDown, boolean skipSubChannel) throws RemoteException { - if (isDebugEnabled()) { - Slog.d(TAG, "Scan with directionDown " + directionDown - + " skipSubChannel " + skipSubChannel); - } + mEventLogger.logRadioEvent("Scan with direction %s, skipSubChannel? %s", + directionDown ? "down" : "up", skipSubChannel ? "yes" : "no"); synchronized (mLock) { checkNotClosedLocked(); int halResult = mHwSession.scan(!directionDown, skipSubChannel); @@ -171,7 +165,7 @@ class TunerSession extends ITuner.Stub { @Override public void tune(ProgramSelector selector) throws RemoteException { - if (isDebugEnabled()) Slog.d(TAG, "Tune with selector " + selector); + mEventLogger.logRadioEvent("Tune with selector %s", selector); synchronized (mLock) { checkNotClosedLocked(); int halResult = mHwSession.tune(Convert.programSelectorToHal(selector)); @@ -195,7 +189,7 @@ class TunerSession extends ITuner.Stub { @Override public Bitmap getImage(int id) { - if (isDebugEnabled()) Slog.d(TAG, "Get image for " + id); + mEventLogger.logRadioEvent("Get image for %d", id); return mModule.getImage(id); } @@ -208,7 +202,7 @@ class TunerSession extends ITuner.Stub { @Override public void startProgramListUpdates(ProgramList.Filter filter) throws RemoteException { - if (isDebugEnabled()) Slog.d(TAG, "start programList updates " + filter); + mEventLogger.logRadioEvent("start programList updates %s", filter); // If the AIDL client provides a null filter, it wants all updates, so use the most broad // filter. if (filter == null) { @@ -267,7 +261,7 @@ class TunerSession extends ITuner.Stub { @Override public void stopProgramListUpdates() throws RemoteException { - if (isDebugEnabled()) Slog.d(TAG, "Stop programList updates"); + mEventLogger.logRadioEvent("Stop programList updates"); synchronized (mLock) { checkNotClosedLocked(); mProgramInfoCache = null; @@ -291,7 +285,7 @@ class TunerSession extends ITuner.Stub { @Override public boolean isConfigFlagSet(int flag) { - if (isDebugEnabled()) Slog.d(TAG, "Is ConfigFlagSet for " + ConfigFlag.toString(flag)); + mEventLogger.logRadioEvent("Is ConfigFlagSet for %s", ConfigFlag.toString(flag)); synchronized (mLock) { checkNotClosedLocked(); @@ -313,9 +307,7 @@ class TunerSession extends ITuner.Stub { @Override public void setConfigFlag(int flag, boolean value) throws RemoteException { - if (isDebugEnabled()) { - Slog.d(TAG, "Set ConfigFlag " + ConfigFlag.toString(flag) + " = " + value); - } + mEventLogger.logRadioEvent("Set ConfigFlag %s = %b", ConfigFlag.toString(flag), value); synchronized (mLock) { checkNotClosedLocked(); int halResult = mHwSession.setConfigFlag(flag, value); @@ -351,6 +343,10 @@ class TunerSession extends ITuner.Stub { pw.printf("ProgramInfoCache: %s\n", mProgramInfoCache); pw.printf("Config: %s\n", mDummyConfig); } + pw.printf("Tuner session events:\n"); + pw.increaseIndent(); + mEventLogger.dump(pw); + pw.decreaseIndent(); pw.decreaseIndent(); } } diff --git a/services/core/java/com/android/server/camera/CameraServiceProxy.java b/services/core/java/com/android/server/camera/CameraServiceProxy.java index 66ef5e761194..11eb78277beb 100644 --- a/services/core/java/com/android/server/camera/CameraServiceProxy.java +++ b/services/core/java/com/android/server/camera/CameraServiceProxy.java @@ -582,13 +582,18 @@ public class CameraServiceProxy extends SystemService } @Override - public boolean isCameraDisabled() { + public boolean isCameraDisabled(int userId) { DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class); if (dpm == null) { Slog.e(TAG, "Failed to get the device policy manager service"); return false; } - return dpm.getCameraDisabled(null); + try { + return dpm.getCameraDisabled(null, userId); + } catch (Exception e) { + e.printStackTrace(); + return false; + } } }; diff --git a/services/core/java/com/android/server/connectivity/Vpn.java b/services/core/java/com/android/server/connectivity/Vpn.java index 931c692b5f01..b4e91b586b40 100644 --- a/services/core/java/com/android/server/connectivity/Vpn.java +++ b/services/core/java/com/android/server/connectivity/Vpn.java @@ -1110,7 +1110,7 @@ public class Vpn { // Except for Settings and VpnDialogs, the caller should be matched one of oldPackage or // newPackage. Otherwise, non VPN owner might get the VPN always-on status of the VPN owner. // See b/191382886. - if (!hasControlVpnPermission()) { + if (mContext.checkCallingOrSelfPermission(CONTROL_VPN) != PERMISSION_GRANTED) { if (oldPackage != null) { verifyCallingUidAndPackage(oldPackage); } @@ -2073,10 +2073,6 @@ public class Vpn { "Unauthorized Caller"); } - private boolean hasControlVpnPermission() { - return mContext.checkCallingOrSelfPermission(CONTROL_VPN) == PERMISSION_GRANTED; - } - private class Connection implements ServiceConnection { private IBinder mService; @@ -3901,10 +3897,8 @@ public class Vpn { Binder.restoreCallingIdentity(token); } - // If package has CONTROL_VPN, grant the ACTIVATE_PLATFORM_VPN appop. - if (hasControlVpnPermission()) { - setPackageAuthorization(packageName, VpnManager.TYPE_VPN_PLATFORM); - } + // TODO: if package has CONTROL_VPN, grant the ACTIVATE_PLATFORM_VPN appop. + // This mirrors the prepareAndAuthorize that is used by VpnService. // Return whether the app is already pre-consented return isVpnProfilePreConsented(mContext, packageName); diff --git a/services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java b/services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java index ea54b3001163..e6c2e7cae23e 100644 --- a/services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java +++ b/services/core/java/com/android/server/hdmi/HdmiCecLocalDevicePlayback.java @@ -544,6 +544,7 @@ public class HdmiCecLocalDevicePlayback extends HdmiCecLocalDeviceSource { || message.getOpcode() == Constants.MESSAGE_SET_STREAM_PATH || message.getOpcode() == Constants.MESSAGE_ACTIVE_SOURCE) { removeAction(ActiveSourceAction.class); + removeAction(OneTouchPlayAction.class); return; } } diff --git a/services/core/java/com/android/server/hdmi/HdmiControlService.java b/services/core/java/com/android/server/hdmi/HdmiControlService.java index fa8b5c1b8086..3ee35036e9fd 100644 --- a/services/core/java/com/android/server/hdmi/HdmiControlService.java +++ b/services/core/java/com/android/server/hdmi/HdmiControlService.java @@ -1051,13 +1051,13 @@ public class HdmiControlService extends SystemService { // Address allocation completed for all devices. Notify each device. if (allocatingDevices.size() == ++finished[0]) { - mAddressAllocated = true; if (initiatedBy != INITIATED_BY_HOTPLUG) { // In case of the hotplug we don't call // onInitializeCecComplete() // since we reallocate the logical address only. onInitializeCecComplete(initiatedBy); } + mAddressAllocated = true; notifyAddressAllocated(allocatedDevices, initiatedBy); // Reinvoke the saved display status callback once the local // device is ready. diff --git a/services/core/java/com/android/server/inputmethod/IInputMethodInvoker.java b/services/core/java/com/android/server/inputmethod/IInputMethodInvoker.java index eb73234549c9..3e397468aa87 100644 --- a/services/core/java/com/android/server/inputmethod/IInputMethodInvoker.java +++ b/services/core/java/com/android/server/inputmethod/IInputMethodInvoker.java @@ -109,13 +109,11 @@ final class IInputMethodInvoker { @AnyThread void initializeInternal(IBinder token, IInputMethodPrivilegedOperations privilegedOperations, - int configChanges, boolean stylusHandWritingSupported, - @InputMethodNavButtonFlags int navigationBarFlags) { + int configChanges, @InputMethodNavButtonFlags int navigationBarFlags) { final IInputMethod.InitParams params = new IInputMethod.InitParams(); params.token = token; params.privilegedOperations = privilegedOperations; params.configChanges = configChanges; - params.stylusHandWritingSupported = stylusHandWritingSupported; params.navigationBarFlags = navigationBarFlags; try { mTarget.initializeInternal(params); @@ -279,4 +277,13 @@ final class IInputMethodInvoker { logRemoteException(e); } } + + @AnyThread + void removeStylusHandwritingWindow() { + try { + mTarget.removeStylusHandwritingWindow(); + } catch (RemoteException e) { + logRemoteException(e); + } + } } diff --git a/services/core/java/com/android/server/inputmethod/InputMethodBindingController.java b/services/core/java/com/android/server/inputmethod/InputMethodBindingController.java index b63592c2fedb..23ea39a3b022 100644 --- a/services/core/java/com/android/server/inputmethod/InputMethodBindingController.java +++ b/services/core/java/com/android/server/inputmethod/InputMethodBindingController.java @@ -286,8 +286,7 @@ final class InputMethodBindingController { if (DEBUG) Slog.v(TAG, "Initiating attach with token: " + mCurToken); final InputMethodInfo info = mMethodMap.get(mSelectedMethodId); mSupportsStylusHw = info.supportsStylusHandwriting(); - mService.initializeImeLocked(mCurMethod, mCurToken, info.getConfigChanges(), - mSupportsStylusHw); + mService.initializeImeLocked(mCurMethod, mCurToken, info.getConfigChanges()); mService.scheduleNotifyImeUidToAudioService(mCurMethodUid); mService.reRequestCurrentClientSessionLocked(); mService.performOnCreateInlineSuggestionsRequestLocked(); diff --git a/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java b/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java index 23f437392d2b..7bd835c73749 100644 --- a/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java +++ b/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java @@ -246,6 +246,7 @@ public final class InputMethodManagerService extends IInputMethodManager.Stub private static final int MSG_RESET_HANDWRITING = 1090; private static final int MSG_START_HANDWRITING = 1100; private static final int MSG_FINISH_HANDWRITING = 1110; + private static final int MSG_REMOVE_HANDWRITING_WINDOW = 1120; private static final int MSG_SET_INTERACTIVE = 3030; @@ -2719,13 +2720,13 @@ public final class InputMethodManagerService extends IInputMethodManager.Stub @GuardedBy("ImfLock.class") void initializeImeLocked(@NonNull IInputMethodInvoker inputMethod, @NonNull IBinder token, - @android.content.pm.ActivityInfo.Config int configChanges, boolean supportStylusHw) { + @android.content.pm.ActivityInfo.Config int configChanges) { if (DEBUG) { Slog.v(TAG, "Sending attach of token: " + token + " for display: " + mCurTokenDisplayId); } inputMethod.initializeInternal(token, new InputMethodPrivilegedOperationsImpl(this, token), - configChanges, supportStylusHw, getInputMethodNavButtonFlagsLocked()); + configChanges, getInputMethodNavButtonFlagsLocked()); } @AnyThread @@ -2734,6 +2735,11 @@ public final class InputMethodManagerService extends IInputMethodManager.Stub } @AnyThread + void scheduleRemoveStylusHandwritingWindow() { + mHandler.obtainMessage(MSG_REMOVE_HANDWRITING_WINDOW).sendToTarget(); + } + + @AnyThread void scheduleNotifyImeUidToAudioService(int uid) { mHandler.removeMessages(MSG_NOTIFY_IME_UID_TO_AUDIO_SERVICE); mHandler.obtainMessage(MSG_NOTIFY_IME_UID_TO_AUDIO_SERVICE, uid, 0 /* unused */) @@ -4363,40 +4369,50 @@ public final class InputMethodManagerService extends IInputMethodManager.Stub private void add(int deviceId) { synchronized (ImfLock.class) { - if (mStylusIds == null) { - mStylusIds = new IntArray(); - } else if (mStylusIds.indexOf(deviceId) != -1) { - return; - } - Slog.d(TAG, "New Stylus device " + deviceId + " added."); - mStylusIds.add(deviceId); - // a new Stylus is detected. If IME supports handwriting and we don't have - // handwriting initialized, lets do it now. - if (!mHwController.getCurrentRequestId().isPresent() - && mMethodMap.get(getSelectedMethodIdLocked()) - .supportsStylusHandwriting()) { - scheduleResetStylusHandwriting(); - } + addStylusDeviceIdLocked(deviceId); } } private void remove(int deviceId) { synchronized (ImfLock.class) { - if (mStylusIds == null || mStylusIds.size() == 0) { - return; - } - if (mStylusIds.indexOf(deviceId) != -1) { - mStylusIds.remove(deviceId); - Slog.d(TAG, "Stylus device " + deviceId + " removed."); - } - if (mStylusIds.size() == 0) { - mHwController.reset(); - } + removeStylusDeviceIdLocked(deviceId); } } }, mHandler); } + private void addStylusDeviceIdLocked(int deviceId) { + if (mStylusIds == null) { + mStylusIds = new IntArray(); + } else if (mStylusIds.indexOf(deviceId) != -1) { + return; + } + Slog.d(TAG, "New Stylus deviceId" + deviceId + " added."); + mStylusIds.add(deviceId); + // a new Stylus is detected. If IME supports handwriting, and we don't have + // handwriting initialized, lets do it now. + if (!mHwController.getCurrentRequestId().isPresent() + && mBindingController.supportsStylusHandwriting()) { + scheduleResetStylusHandwriting(); + } + } + + private void removeStylusDeviceIdLocked(int deviceId) { + if (mStylusIds == null || mStylusIds.size() == 0) { + return; + } + int index; + if ((index = mStylusIds.indexOf(deviceId)) != -1) { + mStylusIds.remove(index); + Slog.d(TAG, "Stylus deviceId: " + deviceId + " removed."); + } + if (mStylusIds.size() == 0) { + // no more supported stylus(es) in system. + mHwController.reset(); + scheduleRemoveStylusHandwritingWindow(); + } + } + private static boolean isStylusDevice(InputDevice inputDevice) { return inputDevice.supportsSource(InputDevice.SOURCE_STYLUS) || inputDevice.supportsSource(InputDevice.SOURCE_BLUETOOTH_STYLUS); @@ -4422,17 +4438,8 @@ public final class InputMethodManagerService extends IInputMethodManager.Stub } final long ident = Binder.clearCallingIdentity(); try { - if (!mBindingController.supportsStylusHandwriting()) { - Slog.w(TAG, "Stylus HW unsupported by IME. Ignoring addVirtualStylusId()"); - return; - } - if (DEBUG) Slog.v(TAG, "Adding virtual stylus id for session"); - if (mStylusIds == null) { - mStylusIds = new IntArray(); - } - mStylusIds.add(VIRTUAL_STYLUS_ID_FOR_TEST); - scheduleResetStylusHandwriting(); + addStylusDeviceIdLocked(VIRTUAL_STYLUS_ID_FOR_TEST); } finally { Binder.restoreCallingIdentity(ident); } @@ -4441,10 +4448,7 @@ public final class InputMethodManagerService extends IInputMethodManager.Stub @GuardedBy("ImfLock.class") private void removeVirtualStylusIdForTestSessionLocked() { - int index; - if ((index = mStylusIds.indexOf(VIRTUAL_STYLUS_ID_FOR_TEST)) != -1) { - mStylusIds.remove(index); - } + removeStylusDeviceIdLocked(VIRTUAL_STYLUS_ID_FOR_TEST); } private static IntArray getStylusInputDeviceIds(InputManager im) { @@ -4922,6 +4926,14 @@ public final class InputMethodManagerService extends IInputMethodManager.Stub } } return true; + case MSG_REMOVE_HANDWRITING_WINDOW: + synchronized (ImfLock.class) { + IInputMethodInvoker curMethod = getCurMethodLocked(); + if (curMethod != null) { + curMethod.removeStylusHandwritingWindow(); + } + } + return true; } return false; } diff --git a/services/core/java/com/android/server/location/contexthub/ContextHubEventLogger.java b/services/core/java/com/android/server/location/contexthub/ContextHubEventLogger.java new file mode 100644 index 000000000000..e46bb74003a2 --- /dev/null +++ b/services/core/java/com/android/server/location/contexthub/ContextHubEventLogger.java @@ -0,0 +1,107 @@ +/* + * 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.server.location.contexthub; + +import android.hardware.location.NanoAppMessage; + +/** + * A class to log events and useful metrics within the Context Hub service. + * + * The class holds a queue of the last NUM_EVENTS_TO_STORE events for each + * event category: nanoapp load, nanoapp unload, message from a nanoapp, + * message to a nanoapp, and context hub restarts. The dump() function + * will be called during debug dumps, giving access to the event information + * and aggregate data since the instantiation of this class. + * + * @hide + */ +public class ContextHubEventLogger { + private static final String TAG = "ContextHubEventLogger"; + + ContextHubEventLogger() { + throw new RuntimeException("Not implemented"); + } + + /** + * Logs a nanoapp load event + * + * @param contextHubId the ID of the context hub + * @param nanoAppId the ID of the nanoapp + * @param nanoAppVersion the version of the nanoapp + * @param nanoAppSize the size in bytes of the nanoapp + * @param success whether the load was successful + */ + public void logNanoAppLoad(int contextHubId, long nanoAppId, int nanoAppVersion, + long nanoAppSize, boolean success) { + throw new RuntimeException("Not implemented"); + } + + /** + * Logs a nanoapp unload event + * + * @param contextHubId the ID of the context hub + * @param nanoAppId the ID of the nanoapp + * @param success whether the unload was successful + */ + public void logNanoAppUnload(int contextHubId, long nanoAppId, boolean success) { + throw new RuntimeException("Not implemented"); + } + + /** + * Logs the event where a nanoapp sends a message to a client + * + * @param contextHubId the ID of the context hub + * @param message the message that was sent + */ + public void logMessageFromNanoApp(int contextHubId, NanoAppMessage message) { + throw new RuntimeException("Not implemented"); + } + + /** + * Logs the event where a client sends a message to a nanoapp + * + * @param contextHubId the ID of the context hub + * @param message the message that was sent + * @param success whether the message was sent successfully + */ + public void logMessageToNanoApp(int contextHubId, NanoAppMessage message, boolean success) { + throw new RuntimeException("Not implemented"); + } + + /** + * Logs a context hub restart event + * + * @param contextHubId the ID of the context hub + */ + public void logContextHubRestarts(int contextHubId) { + throw new RuntimeException("Not implemented"); + } + + /** + * Creates a string representation of the logged events + * + * @return the dumped events + */ + public String dump() { + throw new RuntimeException("Not implemented"); + } + + @Override + public String toString() { + return dump(); + } +} diff --git a/services/core/java/com/android/server/notification/PreferencesHelper.java b/services/core/java/com/android/server/notification/PreferencesHelper.java index 729c521a4ce0..477b8da61e0f 100644 --- a/services/core/java/com/android/server/notification/PreferencesHelper.java +++ b/services/core/java/com/android/server/notification/PreferencesHelper.java @@ -86,7 +86,6 @@ import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -1328,17 +1327,16 @@ public class PreferencesHelper implements RankingConfig { return null; } NotificationChannelGroup group = r.groups.get(groupId).clone(); - ArrayList channels = new ArrayList(); + group.setChannels(new ArrayList<>()); int N = r.channels.size(); for (int i = 0; i < N; i++) { final NotificationChannel nc = r.channels.valueAt(i); if (includeDeleted || !nc.isDeleted()) { if (groupId.equals(nc.getGroup())) { - channels.add(nc); + group.addChannel(nc); } } } - group.setChannels(channels); return group; } } @@ -1351,10 +1349,7 @@ public class PreferencesHelper implements RankingConfig { if (r == null) { return null; } - if (r.groups.get(groupId) != null) { - return r.groups.get(groupId).clone(); - } - return null; + return r.groups.get(groupId); } } @@ -1362,48 +1357,44 @@ public class PreferencesHelper implements RankingConfig { public ParceledListSlice<NotificationChannelGroup> getNotificationChannelGroups(String pkg, int uid, boolean includeDeleted, boolean includeNonGrouped, boolean includeEmpty) { Objects.requireNonNull(pkg); - List<NotificationChannelGroup> groups = new ArrayList<>(); + Map<String, NotificationChannelGroup> groups = new ArrayMap<>(); synchronized (mPackagePreferences) { PackagePreferences r = getPackagePreferencesLocked(pkg, uid); if (r == null) { return ParceledListSlice.emptyList(); } - Map<String, ArrayList<NotificationChannel>> groupedChannels = new HashMap(); + NotificationChannelGroup nonGrouped = new NotificationChannelGroup(null, null); int N = r.channels.size(); for (int i = 0; i < N; i++) { final NotificationChannel nc = r.channels.valueAt(i); if (includeDeleted || !nc.isDeleted()) { if (nc.getGroup() != null) { if (r.groups.get(nc.getGroup()) != null) { - ArrayList<NotificationChannel> channels = groupedChannels.getOrDefault( - nc.getGroup(), new ArrayList<>()); - channels.add(nc); - groupedChannels.put(nc.getGroup(), channels); + NotificationChannelGroup ncg = groups.get(nc.getGroup()); + if (ncg == null) { + ncg = r.groups.get(nc.getGroup()).clone(); + ncg.setChannels(new ArrayList<>()); + groups.put(nc.getGroup(), ncg); + + } + ncg.addChannel(nc); } } else { - ArrayList<NotificationChannel> channels = groupedChannels.getOrDefault( - null, new ArrayList<>()); - channels.add(nc); - groupedChannels.put(null, channels); + nonGrouped.addChannel(nc); } } } - for (NotificationChannelGroup group : r.groups.values()) { - ArrayList<NotificationChannel> channels = - groupedChannels.getOrDefault(group.getId(), new ArrayList<>()); - if (includeEmpty || !channels.isEmpty()) { - NotificationChannelGroup clone = group.clone(); - clone.setChannels(channels); - groups.add(clone); - } + if (includeNonGrouped && nonGrouped.getChannels().size() > 0) { + groups.put(null, nonGrouped); } - - if (includeNonGrouped && groupedChannels.containsKey(null)) { - NotificationChannelGroup nonGrouped = new NotificationChannelGroup(null, null); - nonGrouped.setChannels(groupedChannels.get(null)); - groups.add(nonGrouped); + if (includeEmpty) { + for (NotificationChannelGroup group : r.groups.values()) { + if (!groups.containsKey(group.getId())) { + groups.put(group.getId(), group); + } + } } - return new ParceledListSlice<>(groups); + return new ParceledListSlice<>(new ArrayList<>(groups.values())); } } diff --git a/services/core/java/com/android/server/notification/ValidateNotificationPeople.java b/services/core/java/com/android/server/notification/ValidateNotificationPeople.java index bdc571103ffd..5e0a18039152 100644 --- a/services/core/java/com/android/server/notification/ValidateNotificationPeople.java +++ b/services/core/java/com/android/server/notification/ValidateNotificationPeople.java @@ -131,6 +131,17 @@ public class ValidateNotificationPeople implements NotificationSignalExtractor { } } + // For tests: just do the setting of various local variables without actually doing work + @VisibleForTesting + protected void initForTests(Context context, NotificationUsageStats usageStats, + LruCache peopleCache) { + mUserToContextMap = new ArrayMap<>(); + mBaseContext = context; + mUsageStats = usageStats; + mPeopleCache = peopleCache; + mEnabled = true; + } + public RankingReconsideration process(NotificationRecord record) { if (!mEnabled) { if (VERBOSE) Slog.i(TAG, "disabled"); @@ -179,7 +190,7 @@ public class ValidateNotificationPeople implements NotificationSignalExtractor { return NONE; } final PeopleRankingReconsideration prr = - validatePeople(context, key, extras, null, affinityOut); + validatePeople(context, key, extras, null, affinityOut, null); float affinity = affinityOut[0]; if (prr != null) { @@ -224,15 +235,21 @@ public class ValidateNotificationPeople implements NotificationSignalExtractor { return context; } - private RankingReconsideration validatePeople(Context context, + @VisibleForTesting + protected RankingReconsideration validatePeople(Context context, final NotificationRecord record) { final String key = record.getKey(); final Bundle extras = record.getNotification().extras; final float[] affinityOut = new float[1]; + ArraySet<String> phoneNumbersOut = new ArraySet<>(); final PeopleRankingReconsideration rr = - validatePeople(context, key, extras, record.getPeopleOverride(), affinityOut); + validatePeople(context, key, extras, record.getPeopleOverride(), affinityOut, + phoneNumbersOut); final float affinity = affinityOut[0]; record.setContactAffinity(affinity); + if (phoneNumbersOut.size() > 0) { + record.mergePhoneNumbers(phoneNumbersOut); + } if (rr == null) { mUsageStats.registerPeopleAffinity(record, affinity > NONE, affinity == STARRED_CONTACT, true /* cached */); @@ -243,7 +260,7 @@ public class ValidateNotificationPeople implements NotificationSignalExtractor { } private PeopleRankingReconsideration validatePeople(Context context, String key, Bundle extras, - List<String> peopleOverride, float[] affinityOut) { + List<String> peopleOverride, float[] affinityOut, ArraySet<String> phoneNumbersOut) { float affinity = NONE; if (extras == null) { return null; @@ -270,6 +287,15 @@ public class ValidateNotificationPeople implements NotificationSignalExtractor { } if (lookupResult != null) { affinity = Math.max(affinity, lookupResult.getAffinity()); + + // add all phone numbers associated with this lookup result, if they exist + // and if requested + if (phoneNumbersOut != null) { + ArraySet<String> phoneNumbers = lookupResult.getPhoneNumbers(); + if (phoneNumbers != null && phoneNumbers.size() > 0) { + phoneNumbersOut.addAll(phoneNumbers); + } + } } } if (++personIdx == MAX_PEOPLE) { @@ -289,7 +315,8 @@ public class ValidateNotificationPeople implements NotificationSignalExtractor { return new PeopleRankingReconsideration(context, key, pendingLookups); } - private String getCacheKey(int userId, String handle) { + @VisibleForTesting + protected static String getCacheKey(int userId, String handle) { return Integer.toString(userId) + ":" + handle; } @@ -485,7 +512,8 @@ public class ValidateNotificationPeople implements NotificationSignalExtractor { } } - private static class LookupResult { + @VisibleForTesting + protected static class LookupResult { private static final long CONTACT_REFRESH_MILLIS = 60 * 60 * 1000; // 1hr private final long mExpireMillis; @@ -574,7 +602,8 @@ public class ValidateNotificationPeople implements NotificationSignalExtractor { return mPhoneNumbers; } - private boolean isExpired() { + @VisibleForTesting + protected boolean isExpired() { return mExpireMillis < System.currentTimeMillis(); } diff --git a/services/core/java/com/android/server/om/OverlayManagerService.java b/services/core/java/com/android/server/om/OverlayManagerService.java index 51b36dd9c579..715967369ffb 100644 --- a/services/core/java/com/android/server/om/OverlayManagerService.java +++ b/services/core/java/com/android/server/om/OverlayManagerService.java @@ -39,7 +39,6 @@ import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.UserIdInt; import android.app.ActivityManager; -import android.app.ActivityManagerInternal; import android.app.IActivityManager; import android.content.BroadcastReceiver; import android.content.Context; @@ -1417,18 +1416,16 @@ public final class OverlayManagerService extends SystemService { private static void broadcastActionOverlayChanged(@NonNull final Set<String> targetPackages, final int userId) { - final PackageManagerInternal pmInternal = - LocalServices.getService(PackageManagerInternal.class); - final ActivityManagerInternal amInternal = - LocalServices.getService(ActivityManagerInternal.class); CollectionUtils.forEach(targetPackages, target -> { final Intent intent = new Intent(ACTION_OVERLAY_CHANGED, Uri.fromParts("package", target, null)); intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); - final int[] allowList = pmInternal.getVisibilityAllowList(target, userId); - amInternal.broadcastIntent(intent, null /* resultTo */, null /* requiredPermissions */, - false /* serialized */, userId, allowList, null /* filterExtrasForReceiver */, - null /* bOptions */); + try { + ActivityManager.getService().broadcastIntent(null, intent, null, null, 0, null, + null, null, android.app.AppOpsManager.OP_NONE, null, false, false, userId); + } catch (RemoteException e) { + Slog.e(TAG, "broadcastActionOverlayChanged remote exception", e); + } }); } diff --git a/services/core/java/com/android/server/om/OverlayManagerShellCommand.java b/services/core/java/com/android/server/om/OverlayManagerShellCommand.java index da76738fa025..bb918d594167 100644 --- a/services/core/java/com/android/server/om/OverlayManagerShellCommand.java +++ b/services/core/java/com/android/server/om/OverlayManagerShellCommand.java @@ -257,6 +257,7 @@ final class OverlayManagerShellCommand extends ShellCommand { String name = ""; String filename = null; String opt; + String configuration = null; while ((opt = getNextOption()) != null) { switch (opt) { case "--user": @@ -274,6 +275,9 @@ final class OverlayManagerShellCommand extends ShellCommand { case "--file": filename = getNextArgRequired(); break; + case "--config": + configuration = getNextArgRequired(); + break; default: err.println("Error: Unknown option: " + opt); return 1; @@ -307,7 +311,7 @@ final class OverlayManagerShellCommand extends ShellCommand { final String resourceName = getNextArgRequired(); final String typeStr = getNextArgRequired(); final String strData = String.join(" ", peekRemainingArgs()); - addOverlayValue(overlayBuilder, resourceName, typeStr, strData); + addOverlayValue(overlayBuilder, resourceName, typeStr, strData, configuration); } mInterface.commit(new OverlayManagerTransaction.Builder() @@ -363,8 +367,9 @@ final class OverlayManagerShellCommand extends ShellCommand { err.println("Error: value missing at line " + parser.getLineNumber()); return 1; } + String config = parser.getAttributeValue(null, "config"); addOverlayValue(overlayBuilder, targetPackage + ':' + target, - overlayType, value); + overlayType, value, config); } } } @@ -379,7 +384,7 @@ final class OverlayManagerShellCommand extends ShellCommand { } private void addOverlayValue(FabricatedOverlay.Builder overlayBuilder, - String resourceName, String typeString, String valueString) { + String resourceName, String typeString, String valueString, String configuration) { final int type; typeString = typeString.toLowerCase(Locale.getDefault()); if (TYPE_MAP.containsKey(typeString)) { @@ -392,7 +397,7 @@ final class OverlayManagerShellCommand extends ShellCommand { } } if (type == TypedValue.TYPE_STRING) { - overlayBuilder.setResourceValue(resourceName, type, valueString); + overlayBuilder.setResourceValue(resourceName, type, valueString, configuration); } else { final int intData; if (valueString.startsWith("0x")) { @@ -400,7 +405,7 @@ final class OverlayManagerShellCommand extends ShellCommand { } else { intData = Integer.parseUnsignedInt(valueString); } - overlayBuilder.setResourceValue(resourceName, type, intData); + overlayBuilder.setResourceValue(resourceName, type, intData, configuration); } } diff --git a/services/core/java/com/android/server/os/NativeTombstoneManager.java b/services/core/java/com/android/server/os/NativeTombstoneManager.java index 45192b7bcdbe..d3d1cc5d05cb 100644 --- a/services/core/java/com/android/server/os/NativeTombstoneManager.java +++ b/services/core/java/com/android/server/os/NativeTombstoneManager.java @@ -109,6 +109,13 @@ public final class NativeTombstoneManager { private void handleTombstone(File path) { final String filename = path.getName(); + + // Clean up temporary files if they made it this far (e.g. if system server crashes). + if (filename.endsWith(".tmp")) { + path.delete(); + return; + } + if (!filename.startsWith("tombstone_")) { return; } @@ -561,6 +568,10 @@ public final class NativeTombstoneManager { @Override public void onEvent(int event, @Nullable String path) { mHandler.post(() -> { + // Ignore .tmp files. + if (path.endsWith(".tmp")) { + return; + } handleTombstone(new File(TOMBSTONE_DIR, path)); }); } diff --git a/services/core/java/com/android/server/pm/Computer.java b/services/core/java/com/android/server/pm/Computer.java index b3c7cc07493b..ab998608f66d 100644 --- a/services/core/java/com/android/server/pm/Computer.java +++ b/services/core/java/com/android/server/pm/Computer.java @@ -113,6 +113,8 @@ public interface Computer extends PackageDataSnapshot { @PackageManagerInternal.PrivateResolveFlags long privateResolveFlags, int filterCallingUid, int userId, boolean resolveForStart, boolean allowDynamicSplits); @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, String resolvedType, + long flags, int filterCallingUid, int userId); + @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, String resolvedType, long flags, int userId); @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, String resolvedType, long flags, int userId, int callingUid, boolean includeInstantApps); diff --git a/services/core/java/com/android/server/pm/ComputerEngine.java b/services/core/java/com/android/server/pm/ComputerEngine.java index 7dc648c281f5..7c1777852382 100644 --- a/services/core/java/com/android/server/pm/ComputerEngine.java +++ b/services/core/java/com/android/server/pm/ComputerEngine.java @@ -608,6 +608,15 @@ public class ComputerEngine implements Computer { resolveForStart, userId, intent); } + @NonNull + @Override + public final List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, String resolvedType, + @PackageManager.ResolveInfoFlagsBits long flags, int filterCallingUid, int userId) { + return queryIntentActivitiesInternal( + intent, resolvedType, flags, 0 /*privateResolveFlags*/, filterCallingUid, + userId, false /*resolveForStart*/, true /*allowDynamicSplits*/); + } + public final @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, int userId) { return queryIntentActivitiesInternal( diff --git a/services/core/java/com/android/server/pm/InstallPackageHelper.java b/services/core/java/com/android/server/pm/InstallPackageHelper.java index 9db9837ffc45..61e2419e2d14 100644 --- a/services/core/java/com/android/server/pm/InstallPackageHelper.java +++ b/services/core/java/com/android/server/pm/InstallPackageHelper.java @@ -899,7 +899,7 @@ final class InstallPackageHelper { Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "reconcilePackages"); reconciledPackages = ReconcilePackageUtils.reconcilePackages( reconcileRequest, mSharedLibraries, - mPm.mSettings.getKeySetManagerService(), mPm.mSettings); + mPm.mSettings.getKeySetManagerService(), mPm.mSettings, mContext); } catch (ReconcileFailure e) { for (InstallRequest request : requests) { request.mInstallResult.setError("Reconciliation failed...", e); @@ -3669,7 +3669,7 @@ final class InstallPackageHelper { final Map<String, ReconciledPackage> reconcileResult = ReconcilePackageUtils.reconcilePackages(reconcileRequest, mSharedLibraries, mPm.mSettings.getKeySetManagerService(), - mPm.mSettings); + mPm.mSettings, mContext); if ((scanFlags & SCAN_AS_APEX) == 0) { appIdCreated = optimisticallyRegisterAppId(scanResult); } else { diff --git a/services/core/java/com/android/server/pm/PackageManagerInternalBase.java b/services/core/java/com/android/server/pm/PackageManagerInternalBase.java index c8db2973f1eb..e969d93465f8 100644 --- a/services/core/java/com/android/server/pm/PackageManagerInternalBase.java +++ b/services/core/java/com/android/server/pm/PackageManagerInternalBase.java @@ -309,7 +309,8 @@ abstract class PackageManagerInternalBase extends PackageManagerInternal { public final List<ResolveInfo> queryIntentActivities( Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, int filterCallingUid, int userId) { - return snapshot().queryIntentActivitiesInternal(intent, resolvedType, flags, userId); + return snapshot().queryIntentActivitiesInternal(intent, resolvedType, flags, + filterCallingUid, userId); } @Override diff --git a/services/core/java/com/android/server/pm/ReconcilePackageUtils.java b/services/core/java/com/android/server/pm/ReconcilePackageUtils.java index d6a133e43789..3c4780171ee5 100644 --- a/services/core/java/com/android/server/pm/ReconcilePackageUtils.java +++ b/services/core/java/com/android/server/pm/ReconcilePackageUtils.java @@ -16,6 +16,7 @@ package com.android.server.pm; +import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; import static android.content.pm.SigningDetails.CapabilityMergeRule.MERGE_RESTRICTED_CAPABILITY; @@ -23,25 +24,31 @@ import static android.content.pm.SigningDetails.CapabilityMergeRule.MERGE_RESTRI import static com.android.server.pm.PackageManagerService.SCAN_BOOTING; import static com.android.server.pm.PackageManagerService.SCAN_DONT_KILL_APP; +import android.content.Context; import android.content.pm.PackageManager; +import android.content.pm.PermissionInfo; import android.content.pm.SharedLibraryInfo; import android.content.pm.SigningDetails; import android.os.SystemProperties; +import android.permission.PermissionManager; import android.util.ArrayMap; import android.util.Log; import com.android.server.pm.parsing.pkg.AndroidPackage; import com.android.server.pm.parsing.pkg.ParsedPackage; +import com.android.server.pm.pkg.component.ParsedUsesPermission; import com.android.server.pm.pkg.parsing.ParsingPackageUtils; import com.android.server.utils.WatchedLongSparseArray; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Map; final class ReconcilePackageUtils { public static Map<String, ReconciledPackage> reconcilePackages( final ReconcileRequest request, SharedLibrariesImpl sharedLibraries, - KeySetManagerService ksms, Settings settings) + KeySetManagerService ksms, Settings settings, Context context) throws ReconcileFailure { final Map<String, ScanResult> scannedPackages = request.mScannedPackages; @@ -161,11 +168,43 @@ final class ReconcilePackageUtils { // over the latest parsed certs. signingDetails = parsedPackage.getSigningDetails(); - // if this is is a sharedUser, check to see if the new package is signed by a - // newer - // signing certificate than the existing one, and if so, copy over the new + // if this is a sharedUser, check to see if the new package is signed by a + // newer signing certificate than the existing one, and if so, copy over the new // details if (sharedUserSetting != null) { + if (prepareResult != null && !prepareResult.mPackageToScan.isTestOnly() + && sharedUserSetting.isPrivileged() + && !signatureCheckPs.isSystem()) { + final List<ParsedUsesPermission> usesPermissions = + parsedPackage.getUsesPermissions(); + final List<String> usesPrivilegedPermissions = new ArrayList<>(); + final PermissionManager permissionManager = context.getSystemService( + PermissionManager.class); + // Check if the app requests any privileged permissions because that + // violates the privapp-permissions allowlist check during boot. + if (permissionManager != null) { + for (int i = 0; i < usesPermissions.size(); i++) { + final String permissionName = usesPermissions.get(i).getName(); + final PermissionInfo permissionInfo = + permissionManager.getPermissionInfo(permissionName, 0); + if (permissionInfo != null + && (permissionInfo.getProtectionFlags() + & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { + usesPrivilegedPermissions.add(permissionName); + } + } + } + + if (!usesPrivilegedPermissions.isEmpty()) { + throw new ReconcileFailure(INSTALL_FAILED_INVALID_APK, + "Non-system package: " + parsedPackage.getPackageName() + + " shares signature and sharedUserId with" + + " a privileged package but requests" + + " privileged permissions that are not" + + " allowed: " + Arrays.toString( + usesPrivilegedPermissions.toArray())); + } + } // Attempt to merge the existing lineage for the shared SigningDetails with // the lineage of the new package; if the shared SigningDetails are not // returned this indicates the new package added new signers to the lineage diff --git a/services/core/java/com/android/server/pm/UserManagerService.java b/services/core/java/com/android/server/pm/UserManagerService.java index e423ea9170d7..672c13c2dbf9 100644 --- a/services/core/java/com/android/server/pm/UserManagerService.java +++ b/services/core/java/com/android/server/pm/UserManagerService.java @@ -911,7 +911,7 @@ public class UserManagerService extends IUserManager.Stub { private @NonNull List<UserInfo> getUsersInternal(boolean excludePartial, boolean excludeDying, boolean excludePreCreated) { synchronized (mUsersLock) { - ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size()); + ArrayList<UserInfo> users = new ArrayList<>(mUsers.size()); final int userSize = mUsers.size(); for (int i = 0; i < userSize; i++) { UserInfo ui = mUsers.valueAt(i).info; @@ -1767,6 +1767,32 @@ public class UserManagerService extends IUserManager.Stub { } @Override + public List<UserHandle> getVisibleUsers() { + if (!hasManageUsersOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)) { + throw new SecurityException("Caller needs MANAGE_USERS or INTERACT_ACROSS_USERS " + + "permission to get list of visible users"); + } + final long ident = Binder.clearCallingIdentity(); + try { + // TODO(b/2399825580): refactor into UserDisplayAssigner + synchronized (mUsersLock) { + int usersSize = mUsers.size(); + ArrayList<UserHandle> visibleUsers = new ArrayList<>(usersSize); + for (int i = 0; i < usersSize; i++) { + UserInfo ui = mUsers.valueAt(i).info; + if (!ui.partial && !ui.preCreated && !mRemovingUserIds.get(ui.id) + && isUserVisibleUnchecked(ui.id)) { + visibleUsers.add(UserHandle.of(ui.id)); + } + } + return visibleUsers; + } + } finally { + Binder.restoreCallingIdentity(ident); + } + } + + @Override public @NonNull String getUserName() { final int callingUid = Binder.getCallingUid(); if (!hasQueryOrCreateUsersPermission() diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java index 7dcfd8bd446b..1a1de0341aa0 100644 --- a/services/core/java/com/android/server/policy/PhoneWindowManager.java +++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java @@ -215,7 +215,6 @@ import com.android.server.wm.DisplayPolicy; import com.android.server.wm.DisplayRotation; import com.android.server.wm.WindowManagerInternal; import com.android.server.wm.WindowManagerInternal.AppTransitionListener; -import com.android.server.wm.WindowManagerService; import java.io.File; import java.io.FileNotFoundException; @@ -2082,22 +2081,19 @@ public class PhoneWindowManager implements WindowManagerPolicy { mWindowManagerInternal.registerAppTransitionListener(new AppTransitionListener() { @Override - public int onAppTransitionStartingLocked(boolean keyguardGoingAway, - boolean keyguardOccluding, long duration, long statusBarAnimationStartTime, + public int onAppTransitionStartingLocked(long statusBarAnimationStartTime, long statusBarAnimationDuration) { - // When remote animation is enabled for KEYGUARD_GOING_AWAY transition, SysUI - // receives IRemoteAnimationRunner#onAnimationStart to start animation, so we don't - // need to call IKeyguardService#keyguardGoingAway here. - return handleStartTransitionForKeyguardLw(keyguardGoingAway - && !WindowManagerService.sEnableRemoteKeyguardGoingAwayAnimation, - keyguardOccluding, duration); + return handleTransitionForKeyguardLw(false /* startKeyguardExitAnimation */, + false /* notifyOccluded */); } @Override - public void onAppTransitionCancelledLocked(boolean keyguardGoingAway) { - handleStartTransitionForKeyguardLw( - keyguardGoingAway, false /* keyguardOccludingStarted */, - 0 /* duration */); + public void onAppTransitionCancelledLocked(boolean keyguardGoingAwayCancelled) { + // When KEYGUARD_GOING_AWAY app transition is canceled, we need to trigger relevant + // IKeyguardService calls to sync keyguard status in WindowManagerService and SysUI. + handleTransitionForKeyguardLw( + keyguardGoingAwayCancelled /* startKeyguardExitAnimation */, + true /* notifyOccluded */); } }); @@ -3258,36 +3254,43 @@ public class PhoneWindowManager implements WindowManagerPolicy { @Override public void onKeyguardOccludedChangedLw(boolean occluded) { - if (mKeyguardDelegate != null && mKeyguardDelegate.isShowing() - && !WindowManagerService.sEnableShellTransitions) { + if (mKeyguardDelegate != null && mKeyguardDelegate.isShowing()) { mPendingKeyguardOccluded = occluded; mKeyguardOccludedChanged = true; } else { - setKeyguardOccludedLw(occluded, false /* force */, - false /* transitionStarted */); + setKeyguardOccludedLw(occluded, true /* notify */); } } @Override - public int applyKeyguardOcclusionChange(boolean transitionStarted) { + public int applyKeyguardOcclusionChange(boolean notify) { if (mKeyguardOccludedChanged) { if (DEBUG_KEYGUARD) Slog.d(TAG, "transition/occluded changed occluded=" + mPendingKeyguardOccluded); - if (setKeyguardOccludedLw(mPendingKeyguardOccluded, false /* force */, - transitionStarted)) { + if (setKeyguardOccludedLw(mPendingKeyguardOccluded, notify)) { return FINISH_LAYOUT_REDO_LAYOUT | FINISH_LAYOUT_REDO_WALLPAPER; } } return 0; } - private int handleStartTransitionForKeyguardLw(boolean keyguardGoingAway, - boolean keyguardOccluding, long duration) { - final int redoLayout = applyKeyguardOcclusionChange(keyguardOccluding); + /** + * Called when keyguard related app transition starts, or cancelled. + * + * @param startKeyguardExitAnimation Trigger IKeyguardService#startKeyguardExitAnimation to + * start keyguard exit animation. + * @param notifyOccluded Trigger IKeyguardService#setOccluded binder call to notify whether + * the top activity can occlude the keyguard or not. + * + * @return Whether the flags have changed and we have to redo the layout. + */ + private int handleTransitionForKeyguardLw(boolean startKeyguardExitAnimation, + boolean notifyOccluded) { + final int redoLayout = applyKeyguardOcclusionChange(notifyOccluded); if (redoLayout != 0) return redoLayout; - if (keyguardGoingAway) { + if (startKeyguardExitAnimation) { if (DEBUG_KEYGUARD) Slog.d(TAG, "Starting keyguard exit animation"); - startKeyguardExitAnimation(SystemClock.uptimeMillis(), duration); + startKeyguardExitAnimation(SystemClock.uptimeMillis()); } return 0; } @@ -3519,28 +3522,18 @@ public class PhoneWindowManager implements WindowManagerPolicy { * Updates the occluded state of the Keyguard. * * @param isOccluded Whether the Keyguard is occluded by another window. - * @param force notify the occluded status to KeyguardService and update flags even though - * occlude status doesn't change. - * @param transitionStarted {@code true} if keyguard (un)occluded transition started. + * @param notify Notify keyguard occlude status change immediately via + * {@link com.android.internal.policy.IKeyguardService}. * @return Whether the flags have changed and we have to redo the layout. */ - private boolean setKeyguardOccludedLw(boolean isOccluded, boolean force, - boolean transitionStarted) { + private boolean setKeyguardOccludedLw(boolean isOccluded, boolean notify) { if (DEBUG_KEYGUARD) Slog.d(TAG, "setKeyguardOccluded occluded=" + isOccluded); mKeyguardOccludedChanged = false; - if (isKeyguardOccluded() == isOccluded && !force) { + if (isKeyguardOccluded() == isOccluded) { return false; } - - final boolean showing = mKeyguardDelegate.isShowing(); - final boolean animate = showing && !isOccluded; - // When remote animation is enabled for keyguard (un)occlude transition, KeyguardService - // uses remote animation start as a signal to update its occlusion status ,so we don't need - // to notify here. - final boolean notify = !WindowManagerService.sEnableRemoteKeyguardOccludeAnimation - || !transitionStarted; - mKeyguardDelegate.setOccluded(isOccluded, animate, notify); - return showing; + mKeyguardDelegate.setOccluded(isOccluded, notify); + return mKeyguardDelegate.isShowing(); } /** {@inheritDoc} */ @@ -4936,10 +4929,10 @@ public class PhoneWindowManager implements WindowManagerPolicy { } @Override - public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) { + public void startKeyguardExitAnimation(long startTime) { if (mKeyguardDelegate != null) { if (DEBUG_KEYGUARD) Slog.d(TAG, "PWM.startKeyguardExitAnimation"); - mKeyguardDelegate.startKeyguardExitAnimation(startTime, fadeoutDuration); + mKeyguardDelegate.startKeyguardExitAnimation(startTime); } } diff --git a/services/core/java/com/android/server/policy/SingleKeyGestureDetector.java b/services/core/java/com/android/server/policy/SingleKeyGestureDetector.java index 9ad15c8b538d..f00edf3a76c5 100644 --- a/services/core/java/com/android/server/policy/SingleKeyGestureDetector.java +++ b/services/core/java/com/android/server/policy/SingleKeyGestureDetector.java @@ -49,7 +49,7 @@ public final class SingleKeyGestureDetector { // Key code of current key down event, reset when key up. private int mDownKeyCode = KeyEvent.KEYCODE_UNKNOWN; - private volatile boolean mHandledByLongPress = false; + private boolean mHandledByLongPress = false; private final Handler mHandler; private long mLastDownTime = 0; @@ -194,8 +194,8 @@ public final class SingleKeyGestureDetector { mHandledByLongPress = true; mHandler.removeMessages(MSG_KEY_LONG_PRESS); mHandler.removeMessages(MSG_KEY_VERY_LONG_PRESS); - final Message msg = mHandler.obtainMessage(MSG_KEY_LONG_PRESS, mActiveRule.mKeyCode, - 0, mActiveRule); + final Message msg = mHandler.obtainMessage(MSG_KEY_LONG_PRESS, keyCode, 0, + mActiveRule); msg.setAsynchronous(true); mHandler.sendMessage(msg); } @@ -274,13 +274,26 @@ public final class SingleKeyGestureDetector { } private boolean interceptKeyUp(KeyEvent event) { - mHandler.removeMessages(MSG_KEY_LONG_PRESS); - mHandler.removeMessages(MSG_KEY_VERY_LONG_PRESS); mDownKeyCode = KeyEvent.KEYCODE_UNKNOWN; if (mActiveRule == null) { return false; } + if (!mHandledByLongPress) { + final long eventTime = event.getEventTime(); + if (eventTime < mLastDownTime + mActiveRule.getLongPressTimeoutMs()) { + mHandler.removeMessages(MSG_KEY_LONG_PRESS); + } else { + mHandledByLongPress = mActiveRule.supportLongPress(); + } + + if (eventTime < mLastDownTime + mActiveRule.getVeryLongPressTimeoutMs()) { + mHandler.removeMessages(MSG_KEY_VERY_LONG_PRESS); + } else { + mHandledByLongPress = mActiveRule.supportVeryLongPress(); + } + } + if (mHandledByLongPress) { mHandledByLongPress = false; mKeyPressCounter = 0; @@ -376,7 +389,6 @@ public final class SingleKeyGestureDetector { if (DEBUG) { Log.i(TAG, "Detect long press " + KeyEvent.keyCodeToString(keyCode)); } - mHandledByLongPress = true; rule.onLongPress(mLastDownTime); break; case MSG_KEY_VERY_LONG_PRESS: @@ -384,7 +396,6 @@ public final class SingleKeyGestureDetector { Log.i(TAG, "Detect very long press " + KeyEvent.keyCodeToString(keyCode)); } - mHandledByLongPress = true; rule.onVeryLongPress(mLastDownTime); break; case MSG_KEY_DELAYED_PRESS: diff --git a/services/core/java/com/android/server/policy/WindowManagerPolicy.java b/services/core/java/com/android/server/policy/WindowManagerPolicy.java index 4f00992c713e..2b0405073323 100644 --- a/services/core/java/com/android/server/policy/WindowManagerPolicy.java +++ b/services/core/java/com/android/server/policy/WindowManagerPolicy.java @@ -171,10 +171,10 @@ public interface WindowManagerPolicy extends WindowManagerPolicyConstants { void onKeyguardOccludedChangedLw(boolean occluded); /** - * Applies a keyguard occlusion change if one happened. - * @param transitionStarted Whether keyguard (un)occlude transition is starting or not. + * @param notify {@code true} if the status change should be immediately notified via + * {@link com.android.internal.policy.IKeyguardService} */ - int applyKeyguardOcclusionChange(boolean transitionStarted); + int applyKeyguardOcclusionChange(boolean notify); /** * Interface to the Window Manager state associated with a particular @@ -1129,11 +1129,10 @@ public interface WindowManagerPolicy extends WindowManagerPolicyConstants { /** * Notifies the keyguard to start fading out. + * @param startTime the start time of the animation in uptime milliseconds * - * @param startTime the start time of the animation in uptime milliseconds - * @param fadeoutDuration the duration of the exit animation, in milliseconds */ - void startKeyguardExitAnimation(long startTime, long fadeoutDuration); + void startKeyguardExitAnimation(long startTime); /** * Called when System UI has been started. diff --git a/services/core/java/com/android/server/policy/keyguard/KeyguardServiceDelegate.java b/services/core/java/com/android/server/policy/keyguard/KeyguardServiceDelegate.java index b79ac6f68be2..7737421654ee 100644 --- a/services/core/java/com/android/server/policy/keyguard/KeyguardServiceDelegate.java +++ b/services/core/java/com/android/server/policy/keyguard/KeyguardServiceDelegate.java @@ -249,10 +249,10 @@ public class KeyguardServiceDelegate { } } - public void setOccluded(boolean isOccluded, boolean animate, boolean notify) { + public void setOccluded(boolean isOccluded, boolean notify) { if (mKeyguardService != null && notify) { - if (DEBUG) Log.v(TAG, "setOccluded(" + isOccluded + ") animate=" + animate); - mKeyguardService.setOccluded(isOccluded, animate); + if (DEBUG) Log.v(TAG, "setOccluded(" + isOccluded + ")"); + mKeyguardService.setOccluded(isOccluded, false /* animate */); } mKeyguardState.occluded = isOccluded; } @@ -394,9 +394,9 @@ public class KeyguardServiceDelegate { } } - public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) { + public void startKeyguardExitAnimation(long startTime) { if (mKeyguardService != null) { - mKeyguardService.startKeyguardExitAnimation(startTime, fadeoutDuration); + mKeyguardService.startKeyguardExitAnimation(startTime, 0); } } diff --git a/services/core/java/com/android/server/power/Notifier.java b/services/core/java/com/android/server/power/Notifier.java index dad9584c6722..5a2fb18673ac 100644 --- a/services/core/java/com/android/server/power/Notifier.java +++ b/services/core/java/com/android/server/power/Notifier.java @@ -571,8 +571,7 @@ public class Notifier { /** * Called when there has been user activity. */ - public void onUserActivity(int displayGroupId, @PowerManager.UserActivityEvent int event, - int uid) { + public void onUserActivity(int displayGroupId, int event, int uid) { if (DEBUG) { Slog.d(TAG, "onUserActivity: event=" + event + ", uid=" + uid); } diff --git a/services/core/java/com/android/server/power/PowerGroup.java b/services/core/java/com/android/server/power/PowerGroup.java index 9fe53fbfaf25..fec61ac8f2cf 100644 --- a/services/core/java/com/android/server/power/PowerGroup.java +++ b/services/core/java/com/android/server/power/PowerGroup.java @@ -74,8 +74,6 @@ public class PowerGroup { private long mLastPowerOnTime; private long mLastUserActivityTime; private long mLastUserActivityTimeNoChangeLights; - @PowerManager.UserActivityEvent - private int mLastUserActivityEvent; /** Timestamp (milliseconds since boot) of the last time the power group was awoken.*/ private long mLastWakeTime; /** Timestamp (milliseconds since boot) of the last time the power group was put to sleep. */ @@ -246,7 +244,7 @@ public class PowerGroup { return true; } - boolean dozeLocked(long eventTime, int uid, @PowerManager.GoToSleepReason int reason) { + boolean dozeLocked(long eventTime, int uid, int reason) { if (eventTime < getLastWakeTimeLocked() || !isInteractive(mWakefulness)) { return false; } @@ -255,14 +253,9 @@ public class PowerGroup { try { reason = Math.min(PowerManager.GO_TO_SLEEP_REASON_MAX, Math.max(reason, PowerManager.GO_TO_SLEEP_REASON_MIN)); - long millisSinceLastUserActivity = eventTime - Math.max( - mLastUserActivityTimeNoChangeLights, mLastUserActivityTime); Slog.i(TAG, "Powering off display group due to " - + PowerManager.sleepReasonToString(reason) - + " (groupId= " + getGroupId() + ", uid= " + uid - + ", millisSinceLastUserActivity=" + millisSinceLastUserActivity - + ", lastUserActivityEvent=" + PowerManager.userActivityEventToString( - mLastUserActivityEvent) + ")..."); + + PowerManager.sleepReasonToString(reason) + " (groupId= " + getGroupId() + + ", uid= " + uid + ")..."); setSandmanSummonedLocked(/* isSandmanSummoned= */ true); setWakefulnessLocked(WAKEFULNESS_DOZING, eventTime, uid, reason, /* opUid= */ 0, @@ -273,16 +266,14 @@ public class PowerGroup { return true; } - boolean sleepLocked(long eventTime, int uid, @PowerManager.GoToSleepReason int reason) { + boolean sleepLocked(long eventTime, int uid, int reason) { if (eventTime < mLastWakeTime || getWakefulnessLocked() == WAKEFULNESS_ASLEEP) { return false; } Trace.traceBegin(Trace.TRACE_TAG_POWER, "sleepPowerGroup"); try { - Slog.i(TAG, - "Sleeping power group (groupId=" + getGroupId() + ", uid=" + uid + ", reason=" - + PowerManager.sleepReasonToString(reason) + ")..."); + Slog.i(TAG, "Sleeping power group (groupId=" + getGroupId() + ", uid=" + uid + ")..."); setSandmanSummonedLocked(/* isSandmanSummoned= */ true); setWakefulnessLocked(WAKEFULNESS_ASLEEP, eventTime, uid, reason, /* opUid= */0, /* opPackageName= */ null, /* details= */ null); @@ -296,20 +287,16 @@ public class PowerGroup { return mLastUserActivityTime; } - void setLastUserActivityTimeLocked(long lastUserActivityTime, - @PowerManager.UserActivityEvent int event) { + void setLastUserActivityTimeLocked(long lastUserActivityTime) { mLastUserActivityTime = lastUserActivityTime; - mLastUserActivityEvent = event; } public long getLastUserActivityTimeNoChangeLightsLocked() { return mLastUserActivityTimeNoChangeLights; } - public void setLastUserActivityTimeNoChangeLightsLocked(long time, - @PowerManager.UserActivityEvent int event) { + public void setLastUserActivityTimeNoChangeLightsLocked(long time) { mLastUserActivityTimeNoChangeLights = time; - mLastUserActivityEvent = event; } public int getUserActivitySummaryLocked() { diff --git a/services/core/java/com/android/server/power/PowerManagerService.java b/services/core/java/com/android/server/power/PowerManagerService.java index ca3599ca7fa0..2a1748c441dc 100644 --- a/services/core/java/com/android/server/power/PowerManagerService.java +++ b/services/core/java/com/android/server/power/PowerManagerService.java @@ -1216,7 +1216,6 @@ public final class PowerManagerService extends SystemService return; } - Slog.i(TAG, "onFlip(): Face " + (isFaceDown ? "down." : "up.")); mIsFaceDown = isFaceDown; if (isFaceDown) { final long currentTime = mClock.uptimeMillis(); @@ -1938,13 +1937,12 @@ public final class PowerManagerService extends SystemService // Called from native code. @SuppressWarnings("unused") - private void userActivityFromNative(long eventTime, @PowerManager.UserActivityEvent int event, - int displayId, int flags) { + private void userActivityFromNative(long eventTime, int event, int displayId, int flags) { userActivityInternal(displayId, eventTime, event, flags, Process.SYSTEM_UID); } - private void userActivityInternal(int displayId, long eventTime, - @PowerManager.UserActivityEvent int event, int flags, int uid) { + private void userActivityInternal(int displayId, long eventTime, int event, int flags, + int uid) { synchronized (mLock) { if (displayId == Display.INVALID_DISPLAY) { if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) { @@ -1995,12 +1993,11 @@ public final class PowerManagerService extends SystemService @GuardedBy("mLock") private boolean userActivityNoUpdateLocked(final PowerGroup powerGroup, long eventTime, - @PowerManager.UserActivityEvent int event, int flags, int uid) { + int event, int flags, int uid) { final int groupId = powerGroup.getGroupId(); if (DEBUG_SPEW) { Slog.d(TAG, "userActivityNoUpdateLocked: groupId=" + groupId - + ", eventTime=" + eventTime - + ", event=" + PowerManager.userActivityEventToString(event) + + ", eventTime=" + eventTime + ", event=" + event + ", flags=0x" + Integer.toHexString(flags) + ", uid=" + uid); } @@ -2035,7 +2032,7 @@ public final class PowerManagerService extends SystemService if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) { if (eventTime > powerGroup.getLastUserActivityTimeNoChangeLightsLocked() && eventTime > powerGroup.getLastUserActivityTimeLocked()) { - powerGroup.setLastUserActivityTimeNoChangeLightsLocked(eventTime, event); + powerGroup.setLastUserActivityTimeNoChangeLightsLocked(eventTime); mDirty |= DIRTY_USER_ACTIVITY; if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) { mDirty |= DIRTY_QUIESCENT; @@ -2045,7 +2042,7 @@ public final class PowerManagerService extends SystemService } } else { if (eventTime > powerGroup.getLastUserActivityTimeLocked()) { - powerGroup.setLastUserActivityTimeLocked(eventTime, event); + powerGroup.setLastUserActivityTimeLocked(eventTime); mDirty |= DIRTY_USER_ACTIVITY; if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) { mDirty |= DIRTY_QUIESCENT; @@ -2072,8 +2069,7 @@ public final class PowerManagerService extends SystemService @WakeReason int reason, String details, int uid, String opPackageName, int opUid) { if (DEBUG_SPEW) { Slog.d(TAG, "wakePowerGroupLocked: eventTime=" + eventTime - + ", groupId=" + powerGroup.getGroupId() - + ", reason=" + PowerManager.wakeReasonToString(reason) + ", uid=" + uid); + + ", groupId=" + powerGroup.getGroupId() + ", uid=" + uid); } if (mForceSuspendActive || !mSystemReady) { return; @@ -2096,11 +2092,11 @@ public final class PowerManagerService extends SystemService @GuardedBy("mLock") private boolean dozePowerGroupLocked(final PowerGroup powerGroup, long eventTime, - @GoToSleepReason int reason, int uid) { + int reason, int uid) { if (DEBUG_SPEW) { Slog.d(TAG, "dozePowerGroup: eventTime=" + eventTime - + ", groupId=" + powerGroup.getGroupId() - + ", reason=" + PowerManager.sleepReasonToString(reason) + ", uid=" + uid); + + ", groupId=" + powerGroup.getGroupId() + ", reason=" + reason + + ", uid=" + uid); } if (!mSystemReady || !mBootCompleted) { @@ -2111,12 +2107,10 @@ public final class PowerManagerService extends SystemService } @GuardedBy("mLock") - private boolean sleepPowerGroupLocked(final PowerGroup powerGroup, long eventTime, - @GoToSleepReason int reason, int uid) { + private boolean sleepPowerGroupLocked(final PowerGroup powerGroup, long eventTime, int reason, + int uid) { if (DEBUG_SPEW) { - Slog.d(TAG, "sleepPowerGroup: eventTime=" + eventTime - + ", groupId=" + powerGroup.getGroupId() - + ", reason=" + PowerManager.sleepReasonToString(reason) + ", uid=" + uid); + Slog.d(TAG, "sleepPowerGroup: eventTime=" + eventTime + ", uid=" + uid); } if (!mBootCompleted || !mSystemReady) { return false; @@ -2178,11 +2172,7 @@ public final class PowerManagerService extends SystemService case WAKEFULNESS_DOZING: traceMethodName = "goToSleep"; Slog.i(TAG, "Going to sleep due to " + PowerManager.sleepReasonToString(reason) - + " (uid " + uid + ", screenOffTimeout=" + mScreenOffTimeoutSetting - + ", activityTimeoutWM=" + mUserActivityTimeoutOverrideFromWindowManager - + ", maxDimRatio=" + mMaximumScreenDimRatioConfig - + ", maxDimDur=" + mMaximumScreenDimDurationConfig + ")..."); - + + " (uid " + uid + ")..."); mLastGlobalSleepTime = eventTime; mLastGlobalSleepReason = reason; mLastGlobalSleepTimeRealtime = mClock.elapsedRealtime(); @@ -4267,7 +4257,7 @@ public final class PowerManagerService extends SystemService void onUserActivity() { synchronized (mLock) { mPowerGroups.get(Display.DEFAULT_DISPLAY_GROUP).setLastUserActivityTimeLocked( - mClock.uptimeMillis(), PowerManager.USER_ACTIVITY_EVENT_OTHER); + mClock.uptimeMillis()); } } @@ -5655,8 +5645,7 @@ public final class PowerManagerService extends SystemService } @Override // Binder call - public void userActivity(int displayId, long eventTime, - @PowerManager.UserActivityEvent int event, int flags) { + public void userActivity(int displayId, long eventTime, int event, int flags) { final long now = mClock.uptimeMillis(); if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER) != PackageManager.PERMISSION_GRANTED diff --git a/services/core/java/com/android/server/power/stats/BatteryStatsImpl.java b/services/core/java/com/android/server/power/stats/BatteryStatsImpl.java index 202beb377b2c..0c9ada8fa6db 100644 --- a/services/core/java/com/android/server/power/stats/BatteryStatsImpl.java +++ b/services/core/java/com/android/server/power/stats/BatteryStatsImpl.java @@ -5911,8 +5911,7 @@ public class BatteryStatsImpl extends BatteryStats { } @GuardedBy("this") - public void noteUserActivityLocked(int uid, @PowerManager.UserActivityEvent int event, - long elapsedRealtimeMs, long uptimeMs) { + public void noteUserActivityLocked(int uid, int event, long elapsedRealtimeMs, long uptimeMs) { if (mOnBatteryInternal) { uid = mapUid(uid); getUidStatsLocked(uid, elapsedRealtimeMs, uptimeMs).noteUserActivityLocked(event); @@ -9417,14 +9416,14 @@ public class BatteryStatsImpl extends BatteryStats { } @Override - public void noteUserActivityLocked(@PowerManager.UserActivityEvent int event) { + public void noteUserActivityLocked(int type) { if (mUserActivityCounters == null) { initUserActivityLocked(); } - if (event >= 0 && event < NUM_USER_ACTIVITY_TYPES) { - mUserActivityCounters[event].stepAtomic(); + if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) { + mUserActivityCounters[type].stepAtomic(); } else { - Slog.w(TAG, "Unknown user activity event " + event + " was specified.", + Slog.w(TAG, "Unknown user activity type " + type + " was specified.", new Throwable()); } } diff --git a/services/core/java/com/android/server/vibrator/AbstractVibratorStep.java b/services/core/java/com/android/server/vibrator/AbstractVibratorStep.java index eebd046b2601..be9053055fe3 100644 --- a/services/core/java/com/android/server/vibrator/AbstractVibratorStep.java +++ b/services/core/java/com/android/server/vibrator/AbstractVibratorStep.java @@ -31,9 +31,9 @@ abstract class AbstractVibratorStep extends Step { public final VibratorController controller; public final VibrationEffect.Composed effect; public final int segmentIndex; - public final long previousStepVibratorOffTimeout; long mVibratorOnResult; + long mPendingVibratorOffDeadline; boolean mVibratorCompleteCallbackReceived; /** @@ -43,19 +43,19 @@ abstract class AbstractVibratorStep extends Step { * @param controller The vibrator that is playing the effect. * @param effect The effect being played in this step. * @param index The index of the next segment to be played by this step - * @param previousStepVibratorOffTimeout The time the vibrator is expected to complete any + * @param pendingVibratorOffDeadline The time the vibrator is expected to complete any * previous vibration and turn off. This is used to allow this step to * be triggered when the completion callback is received, and can * be used to play effects back-to-back. */ AbstractVibratorStep(VibrationStepConductor conductor, long startTime, VibratorController controller, VibrationEffect.Composed effect, int index, - long previousStepVibratorOffTimeout) { + long pendingVibratorOffDeadline) { super(conductor, startTime); this.controller = controller; this.effect = effect; this.segmentIndex = index; - this.previousStepVibratorOffTimeout = previousStepVibratorOffTimeout; + mPendingVibratorOffDeadline = pendingVibratorOffDeadline; } public int getVibratorId() { @@ -69,27 +69,57 @@ abstract class AbstractVibratorStep extends Step { @Override public boolean acceptVibratorCompleteCallback(int vibratorId) { - boolean isSameVibrator = controller.getVibratorInfo().getId() == vibratorId; - mVibratorCompleteCallbackReceived |= isSameVibrator; + if (getVibratorId() != vibratorId) { + return false; + } + // Only activate this step if a timeout was set to wait for the vibration to complete, // otherwise we are waiting for the correct time to play the next step. - return isSameVibrator && (previousStepVibratorOffTimeout > SystemClock.uptimeMillis()); + boolean shouldAcceptCallback = mPendingVibratorOffDeadline > SystemClock.uptimeMillis(); + if (VibrationThread.DEBUG) { + Slog.d(VibrationThread.TAG, + "Received completion callback from " + vibratorId + + ", accepted = " + shouldAcceptCallback); + } + + // The callback indicates this vibrator has stopped, reset the timeout. + mPendingVibratorOffDeadline = 0; + mVibratorCompleteCallbackReceived = true; + return shouldAcceptCallback; } @Override public List<Step> cancel() { return Arrays.asList(new CompleteEffectVibratorStep(conductor, SystemClock.uptimeMillis(), - /* cancelled= */ true, controller, previousStepVibratorOffTimeout)); + /* cancelled= */ true, controller, mPendingVibratorOffDeadline)); } @Override public void cancelImmediately() { - if (previousStepVibratorOffTimeout > SystemClock.uptimeMillis()) { + if (mPendingVibratorOffDeadline > SystemClock.uptimeMillis()) { // Vibrator might be running from previous steps, so turn it off while canceling. stopVibrating(); } } + protected long handleVibratorOnResult(long vibratorOnResult) { + mVibratorOnResult = vibratorOnResult; + if (VibrationThread.DEBUG) { + Slog.d(VibrationThread.TAG, + "Turned on vibrator " + getVibratorId() + ", result = " + mVibratorOnResult); + } + if (mVibratorOnResult > 0) { + // Vibrator was turned on by this step, with vibratorOnResult as the duration. + // Set an extra timeout to wait for the vibrator completion callback. + mPendingVibratorOffDeadline = SystemClock.uptimeMillis() + mVibratorOnResult + + VibrationStepConductor.CALLBACKS_EXTRA_TIMEOUT; + } else { + // Vibrator does not support the request or failed to turn on, reset callback deadline. + mPendingVibratorOffDeadline = 0; + } + return mVibratorOnResult; + } + protected void stopVibrating() { if (VibrationThread.DEBUG) { Slog.d(VibrationThread.TAG, @@ -97,6 +127,7 @@ abstract class AbstractVibratorStep extends Step { } controller.off(); getVibration().stats().reportVibratorOff(); + mPendingVibratorOffDeadline = 0; } protected void changeAmplitude(float amplitude) { @@ -109,40 +140,29 @@ abstract class AbstractVibratorStep extends Step { } /** - * Return the {@link VibrationStepConductor#nextVibrateStep} with same timings, only jumping - * the segments. - */ - protected List<Step> skipToNextSteps(int segmentsSkipped) { - return nextSteps(startTime, previousStepVibratorOffTimeout, segmentsSkipped); - } - - /** - * Return the {@link VibrationStepConductor#nextVibrateStep} with same start and off timings - * calculated from {@link #getVibratorOnDuration()}, jumping all played segments. - * - * <p>This method has same behavior as {@link #skipToNextSteps(int)} when the vibrator - * result is non-positive, meaning the vibrator has either ignored or failed to turn on. + * Return the {@link VibrationStepConductor#nextVibrateStep} with start and off timings + * calculated from {@link #getVibratorOnDuration()} based on the current + * {@link SystemClock#uptimeMillis()} and jumping all played segments from the effect. */ protected List<Step> nextSteps(int segmentsPlayed) { - if (mVibratorOnResult <= 0) { - // Vibration was not started, so just skip the played segments and keep timings. - return skipToNextSteps(segmentsPlayed); + // Schedule next steps to run right away. + long nextStartTime = SystemClock.uptimeMillis(); + if (mVibratorOnResult > 0) { + // Vibrator was turned on by this step, with mVibratorOnResult as the duration. + // Schedule next steps for right after the vibration finishes. + nextStartTime += mVibratorOnResult; } - long nextStartTime = SystemClock.uptimeMillis() + mVibratorOnResult; - long nextVibratorOffTimeout = - nextStartTime + VibrationStepConductor.CALLBACKS_EXTRA_TIMEOUT; - return nextSteps(nextStartTime, nextVibratorOffTimeout, segmentsPlayed); + return nextSteps(nextStartTime, segmentsPlayed); } /** - * Return the {@link VibrationStepConductor#nextVibrateStep} with given start and off timings, - * which might be calculated independently, jumping all played segments. + * Return the {@link VibrationStepConductor#nextVibrateStep} with given start time, + * which might be calculated independently, and jumping all played segments from the effect. * - * <p>This should be used when the vibrator on/off state is not responsible for the steps - * execution timings, e.g. while playing the vibrator amplitudes. + * <p>This should be used when the vibrator on/off state is not responsible for the step + * execution timing, e.g. while playing the vibrator amplitudes. */ - protected List<Step> nextSteps(long nextStartTime, long vibratorOffTimeout, - int segmentsPlayed) { + protected List<Step> nextSteps(long nextStartTime, int segmentsPlayed) { int nextSegmentIndex = segmentIndex + segmentsPlayed; int effectSize = effect.getSegments().size(); int repeatIndex = effect.getRepeatIndex(); @@ -154,7 +174,7 @@ abstract class AbstractVibratorStep extends Step { nextSegmentIndex = repeatIndex + ((nextSegmentIndex - effectSize) % loopSize); } Step nextStep = conductor.nextVibrateStep(nextStartTime, controller, effect, - nextSegmentIndex, vibratorOffTimeout); + nextSegmentIndex, mPendingVibratorOffDeadline); return nextStep == null ? VibrationStepConductor.EMPTY_STEP_LIST : Arrays.asList(nextStep); } } diff --git a/services/core/java/com/android/server/vibrator/CompleteEffectVibratorStep.java b/services/core/java/com/android/server/vibrator/CompleteEffectVibratorStep.java index 8585e3473ef3..fb5140d862b7 100644 --- a/services/core/java/com/android/server/vibrator/CompleteEffectVibratorStep.java +++ b/services/core/java/com/android/server/vibrator/CompleteEffectVibratorStep.java @@ -34,9 +34,9 @@ final class CompleteEffectVibratorStep extends AbstractVibratorStep { private final boolean mCancelled; CompleteEffectVibratorStep(VibrationStepConductor conductor, long startTime, boolean cancelled, - VibratorController controller, long previousStepVibratorOffTimeout) { + VibratorController controller, long pendingVibratorOffDeadline) { super(conductor, startTime, controller, /* effect= */ null, /* index= */ -1, - previousStepVibratorOffTimeout); + pendingVibratorOffDeadline); mCancelled = cancelled; } @@ -73,10 +73,11 @@ final class CompleteEffectVibratorStep extends AbstractVibratorStep { return VibrationStepConductor.EMPTY_STEP_LIST; } + long now = SystemClock.uptimeMillis(); float currentAmplitude = controller.getCurrentAmplitude(); long remainingOnDuration = - previousStepVibratorOffTimeout - VibrationStepConductor.CALLBACKS_EXTRA_TIMEOUT - - SystemClock.uptimeMillis(); + mPendingVibratorOffDeadline - now + - VibrationStepConductor.CALLBACKS_EXTRA_TIMEOUT; long rampDownDuration = Math.min(remainingOnDuration, conductor.vibrationSettings.getRampDownDuration()); @@ -89,8 +90,10 @@ final class CompleteEffectVibratorStep extends AbstractVibratorStep { stopVibrating(); return VibrationStepConductor.EMPTY_STEP_LIST; } else { + // Vibration is completing normally, turn off after the deadline in case we + // don't receive the callback in time (callback also triggers it right away). return Arrays.asList(new TurnOffVibratorStep( - conductor, previousStepVibratorOffTimeout, controller)); + conductor, mPendingVibratorOffDeadline, controller)); } } @@ -100,13 +103,18 @@ final class CompleteEffectVibratorStep extends AbstractVibratorStep { + " from amplitude " + currentAmplitude + " for " + rampDownDuration + "ms"); } + + // If we are cancelling this vibration then make sure the vibrator will be turned off + // immediately after the ramp off duration. Otherwise, this is a planned ramp off for + // the remaining ON duration, then just propagate the mPendingVibratorOffDeadline so the + // turn off step will wait for the vibration completion callback and end gracefully. + long rampOffVibratorOffDeadline = + mCancelled ? (now + rampDownDuration) : mPendingVibratorOffDeadline; float amplitudeDelta = currentAmplitude / (rampDownDuration / stepDownDuration); float amplitudeTarget = currentAmplitude - amplitudeDelta; - long newVibratorOffTimeout = - mCancelled ? rampDownDuration : previousStepVibratorOffTimeout; return Arrays.asList( new RampOffVibratorStep(conductor, startTime, amplitudeTarget, amplitudeDelta, - controller, newVibratorOffTimeout)); + controller, rampOffVibratorOffDeadline)); } finally { Trace.traceEnd(Trace.TRACE_TAG_VIBRATOR); } diff --git a/services/core/java/com/android/server/vibrator/ComposePrimitivesVibratorStep.java b/services/core/java/com/android/server/vibrator/ComposePrimitivesVibratorStep.java index f8b99265246a..545ec5bcff03 100644 --- a/services/core/java/com/android/server/vibrator/ComposePrimitivesVibratorStep.java +++ b/services/core/java/com/android/server/vibrator/ComposePrimitivesVibratorStep.java @@ -40,11 +40,11 @@ final class ComposePrimitivesVibratorStep extends AbstractVibratorStep { ComposePrimitivesVibratorStep(VibrationStepConductor conductor, long startTime, VibratorController controller, VibrationEffect.Composed effect, int index, - long previousStepVibratorOffTimeout) { + long pendingVibratorOffDeadline) { // This step should wait for the last vibration to finish (with the timeout) and for the // intended step start time (to respect the effect delays). - super(conductor, Math.max(startTime, previousStepVibratorOffTimeout), controller, effect, - index, previousStepVibratorOffTimeout); + super(conductor, Math.max(startTime, pendingVibratorOffDeadline), controller, effect, + index, pendingVibratorOffDeadline); } @Override @@ -60,18 +60,22 @@ final class ComposePrimitivesVibratorStep extends AbstractVibratorStep { if (primitives.isEmpty()) { Slog.w(VibrationThread.TAG, "Ignoring wrong segment for a ComposePrimitivesStep: " + effect.getSegments().get(segmentIndex)); - return skipToNextSteps(/* segmentsSkipped= */ 1); + // Skip this step and play the next one right away. + return nextSteps(/* segmentsPlayed= */ 1); } if (VibrationThread.DEBUG) { Slog.d(VibrationThread.TAG, "Compose " + primitives + " primitives on vibrator " - + controller.getVibratorInfo().getId()); + + getVibratorId()); } + PrimitiveSegment[] primitivesArray = primitives.toArray(new PrimitiveSegment[primitives.size()]); - mVibratorOnResult = controller.on(primitivesArray, getVibration().id); - getVibration().stats().reportComposePrimitives(mVibratorOnResult, primitivesArray); + long vibratorOnResult = controller.on(primitivesArray, getVibration().id); + handleVibratorOnResult(vibratorOnResult); + getVibration().stats().reportComposePrimitives(vibratorOnResult, primitivesArray); + // The next start and off times will be calculated from mVibratorOnResult. return nextSteps(/* segmentsPlayed= */ primitives.size()); } finally { Trace.traceEnd(Trace.TRACE_TAG_VIBRATOR); diff --git a/services/core/java/com/android/server/vibrator/ComposePwleVibratorStep.java b/services/core/java/com/android/server/vibrator/ComposePwleVibratorStep.java index 81f52c912f28..8bfa2c3cd082 100644 --- a/services/core/java/com/android/server/vibrator/ComposePwleVibratorStep.java +++ b/services/core/java/com/android/server/vibrator/ComposePwleVibratorStep.java @@ -41,11 +41,11 @@ final class ComposePwleVibratorStep extends AbstractVibratorStep { ComposePwleVibratorStep(VibrationStepConductor conductor, long startTime, VibratorController controller, VibrationEffect.Composed effect, int index, - long previousStepVibratorOffTimeout) { + long pendingVibratorOffDeadline) { // This step should wait for the last vibration to finish (with the timeout) and for the // intended step start time (to respect the effect delays). - super(conductor, Math.max(startTime, previousStepVibratorOffTimeout), controller, effect, - index, previousStepVibratorOffTimeout); + super(conductor, Math.max(startTime, pendingVibratorOffDeadline), controller, effect, + index, pendingVibratorOffDeadline); } @Override @@ -61,7 +61,8 @@ final class ComposePwleVibratorStep extends AbstractVibratorStep { if (pwles.isEmpty()) { Slog.w(VibrationThread.TAG, "Ignoring wrong segment for a ComposePwleStep: " + effect.getSegments().get(segmentIndex)); - return skipToNextSteps(/* segmentsSkipped= */ 1); + // Skip this step and play the next one right away. + return nextSteps(/* segmentsPlayed= */ 1); } if (VibrationThread.DEBUG) { @@ -69,9 +70,11 @@ final class ComposePwleVibratorStep extends AbstractVibratorStep { + controller.getVibratorInfo().getId()); } RampSegment[] pwlesArray = pwles.toArray(new RampSegment[pwles.size()]); - mVibratorOnResult = controller.on(pwlesArray, getVibration().id); - getVibration().stats().reportComposePwle(mVibratorOnResult, pwlesArray); + long vibratorOnResult = controller.on(pwlesArray, getVibration().id); + handleVibratorOnResult(vibratorOnResult); + getVibration().stats().reportComposePwle(vibratorOnResult, pwlesArray); + // The next start and off times will be calculated from mVibratorOnResult. return nextSteps(/* segmentsPlayed= */ pwles.size()); } finally { Trace.traceEnd(Trace.TRACE_TAG_VIBRATOR); diff --git a/services/core/java/com/android/server/vibrator/PerformPrebakedVibratorStep.java b/services/core/java/com/android/server/vibrator/PerformPrebakedVibratorStep.java index 41902147838d..d91bafa7c8c2 100644 --- a/services/core/java/com/android/server/vibrator/PerformPrebakedVibratorStep.java +++ b/services/core/java/com/android/server/vibrator/PerformPrebakedVibratorStep.java @@ -35,11 +35,11 @@ final class PerformPrebakedVibratorStep extends AbstractVibratorStep { PerformPrebakedVibratorStep(VibrationStepConductor conductor, long startTime, VibratorController controller, VibrationEffect.Composed effect, int index, - long previousStepVibratorOffTimeout) { + long pendingVibratorOffDeadline) { // This step should wait for the last vibration to finish (with the timeout) and for the // intended step start time (to respect the effect delays). - super(conductor, Math.max(startTime, previousStepVibratorOffTimeout), controller, effect, - index, previousStepVibratorOffTimeout); + super(conductor, Math.max(startTime, pendingVibratorOffDeadline), controller, effect, + index, pendingVibratorOffDeadline); } @Override @@ -50,7 +50,8 @@ final class PerformPrebakedVibratorStep extends AbstractVibratorStep { if (!(segment instanceof PrebakedSegment)) { Slog.w(VibrationThread.TAG, "Ignoring wrong segment for a " + "PerformPrebakedVibratorStep: " + segment); - return skipToNextSteps(/* segmentsSkipped= */ 1); + // Skip this step and play the next one right away. + return nextSteps(/* segmentsPlayed= */ 1); } PrebakedSegment prebaked = (PrebakedSegment) segment; @@ -61,10 +62,11 @@ final class PerformPrebakedVibratorStep extends AbstractVibratorStep { } VibrationEffect fallback = getVibration().getFallback(prebaked.getEffectId()); - mVibratorOnResult = controller.on(prebaked, getVibration().id); - getVibration().stats().reportPerformEffect(mVibratorOnResult, prebaked); + long vibratorOnResult = controller.on(prebaked, getVibration().id); + handleVibratorOnResult(vibratorOnResult); + getVibration().stats().reportPerformEffect(vibratorOnResult, prebaked); - if (mVibratorOnResult == 0 && prebaked.shouldFallback() + if (vibratorOnResult == 0 && prebaked.shouldFallback() && (fallback instanceof VibrationEffect.Composed)) { if (VibrationThread.DEBUG) { Slog.d(VibrationThread.TAG, "Playing fallback for effect " @@ -72,14 +74,15 @@ final class PerformPrebakedVibratorStep extends AbstractVibratorStep { } AbstractVibratorStep fallbackStep = conductor.nextVibrateStep(startTime, controller, replaceCurrentSegment((VibrationEffect.Composed) fallback), - segmentIndex, previousStepVibratorOffTimeout); + segmentIndex, mPendingVibratorOffDeadline); List<Step> fallbackResult = fallbackStep.play(); // Update the result with the fallback result so this step is seamlessly // replaced by the fallback to any outer application of this. - mVibratorOnResult = fallbackStep.getVibratorOnDuration(); + handleVibratorOnResult(fallbackStep.getVibratorOnDuration()); return fallbackResult; } + // The next start and off times will be calculated from mVibratorOnResult. return nextSteps(/* segmentsPlayed= */ 1); } finally { Trace.traceEnd(Trace.TRACE_TAG_VIBRATOR); diff --git a/services/core/java/com/android/server/vibrator/RampOffVibratorStep.java b/services/core/java/com/android/server/vibrator/RampOffVibratorStep.java index 8cf5fb394d9d..84da9f2c58ec 100644 --- a/services/core/java/com/android/server/vibrator/RampOffVibratorStep.java +++ b/services/core/java/com/android/server/vibrator/RampOffVibratorStep.java @@ -30,9 +30,9 @@ final class RampOffVibratorStep extends AbstractVibratorStep { RampOffVibratorStep(VibrationStepConductor conductor, long startTime, float amplitudeTarget, float amplitudeDelta, VibratorController controller, - long previousStepVibratorOffTimeout) { + long pendingVibratorOffDeadline) { super(conductor, startTime, controller, /* effect= */ null, /* index= */ -1, - previousStepVibratorOffTimeout); + pendingVibratorOffDeadline); mAmplitudeTarget = amplitudeTarget; mAmplitudeDelta = amplitudeDelta; } @@ -68,15 +68,17 @@ final class RampOffVibratorStep extends AbstractVibratorStep { float newAmplitudeTarget = mAmplitudeTarget - mAmplitudeDelta; if (newAmplitudeTarget < VibrationStepConductor.RAMP_OFF_AMPLITUDE_MIN) { - // Vibrator amplitude cannot go further down, just turn it off. + // Vibrator amplitude cannot go further down, just turn it off with the configured + // deadline that has been adjusted for the scenario when this was triggered by a + // cancelled vibration. return Arrays.asList(new TurnOffVibratorStep( - conductor, previousStepVibratorOffTimeout, controller)); + conductor, mPendingVibratorOffDeadline, controller)); } return Arrays.asList(new RampOffVibratorStep( conductor, startTime + conductor.vibrationSettings.getRampStepDuration(), newAmplitudeTarget, mAmplitudeDelta, controller, - previousStepVibratorOffTimeout)); + mPendingVibratorOffDeadline)); } finally { Trace.traceEnd(Trace.TRACE_TAG_VIBRATOR); } diff --git a/services/core/java/com/android/server/vibrator/SetAmplitudeVibratorStep.java b/services/core/java/com/android/server/vibrator/SetAmplitudeVibratorStep.java index 6fb9111793ea..1672470f1f1a 100644 --- a/services/core/java/com/android/server/vibrator/SetAmplitudeVibratorStep.java +++ b/services/core/java/com/android/server/vibrator/SetAmplitudeVibratorStep.java @@ -39,26 +39,34 @@ final class SetAmplitudeVibratorStep extends AbstractVibratorStep { */ private static final int REPEATING_EFFECT_ON_DURATION = 5000; // 5s - private long mNextOffTime; - SetAmplitudeVibratorStep(VibrationStepConductor conductor, long startTime, VibratorController controller, VibrationEffect.Composed effect, int index, - long previousStepVibratorOffTimeout) { + long pendingVibratorOffDeadline) { // This step has a fixed startTime coming from the timings of the waveform it's playing. - super(conductor, startTime, controller, effect, index, previousStepVibratorOffTimeout); - mNextOffTime = previousStepVibratorOffTimeout; + super(conductor, startTime, controller, effect, index, pendingVibratorOffDeadline); } @Override public boolean acceptVibratorCompleteCallback(int vibratorId) { - if (controller.getVibratorInfo().getId() == vibratorId) { - mVibratorCompleteCallbackReceived = true; - mNextOffTime = SystemClock.uptimeMillis(); + // Ensure the super method is called and will reset the off timeout and boolean flag. + // This is true if the vibrator was ON and this callback has the same vibratorId. + if (!super.acceptVibratorCompleteCallback(vibratorId)) { + return false; } + // Timings are tightly controlled here, so only trigger this step if the vibrator was // supposed to be ON but has completed prematurely, to turn it back on as soon as - // possible. - return mNextOffTime < startTime && controller.getCurrentAmplitude() > 0; + // possible. If the vibrator turned off during a zero-amplitude step, just wait for + // the correct start time of this step before playing it. + boolean shouldAcceptCallback = + (SystemClock.uptimeMillis() < startTime) && (controller.getCurrentAmplitude() > 0); + + if (VibrationThread.DEBUG) { + Slog.d(VibrationThread.TAG, + "Amplitude step received completion callback from " + vibratorId + + ", accepted = " + shouldAcceptCallback); + } + return shouldAcceptCallback; } @Override @@ -78,40 +86,38 @@ final class SetAmplitudeVibratorStep extends AbstractVibratorStep { if (mVibratorCompleteCallbackReceived && latency < 0) { // This step was run early because the vibrator turned off prematurely. // Turn it back on and return this same step to run at the exact right time. - mNextOffTime = turnVibratorBackOn(/* remainingDuration= */ -latency); + turnVibratorBackOn(/* remainingDuration= */ -latency); return Arrays.asList(new SetAmplitudeVibratorStep(conductor, startTime, controller, - effect, segmentIndex, mNextOffTime)); + effect, segmentIndex, mPendingVibratorOffDeadline)); } VibrationEffectSegment segment = effect.getSegments().get(segmentIndex); if (!(segment instanceof StepSegment)) { Slog.w(VibrationThread.TAG, "Ignoring wrong segment for a SetAmplitudeVibratorStep: " + segment); - return skipToNextSteps(/* segmentsSkipped= */ 1); + // Use original startTime to avoid propagating latencies to the waveform. + return nextSteps(startTime, /* segmentsPlayed= */ 1); } StepSegment stepSegment = (StepSegment) segment; if (stepSegment.getDuration() == 0) { - // Skip waveform entries with zero timing. - return skipToNextSteps(/* segmentsSkipped= */ 1); + // Use original startTime to avoid propagating latencies to the waveform. + return nextSteps(startTime, /* segmentsPlayed= */ 1); } float amplitude = stepSegment.getAmplitude(); if (amplitude == 0) { - if (previousStepVibratorOffTimeout > now) { + if (mPendingVibratorOffDeadline > now) { // Amplitude cannot be set to zero, so stop the vibrator. stopVibrating(); - mNextOffTime = now; } } else { - if (startTime >= mNextOffTime) { + if (startTime >= mPendingVibratorOffDeadline) { // Vibrator is OFF. Turn vibrator back on for the duration of another // cycle before setting the amplitude. long onDuration = getVibratorOnDuration(effect, segmentIndex); if (onDuration > 0) { - mVibratorOnResult = startVibrating(onDuration); - mNextOffTime = now + onDuration - + VibrationStepConductor.CALLBACKS_EXTRA_TIMEOUT; + startVibrating(onDuration); } } changeAmplitude(amplitude); @@ -119,27 +125,32 @@ final class SetAmplitudeVibratorStep extends AbstractVibratorStep { // Use original startTime to avoid propagating latencies to the waveform. long nextStartTime = startTime + segment.getDuration(); - return nextSteps(nextStartTime, mNextOffTime, /* segmentsPlayed= */ 1); + return nextSteps(nextStartTime, /* segmentsPlayed= */ 1); } finally { Trace.traceEnd(Trace.TRACE_TAG_VIBRATOR); } } - private long turnVibratorBackOn(long remainingDuration) { + private void turnVibratorBackOn(long remainingDuration) { long onDuration = getVibratorOnDuration(effect, segmentIndex); if (onDuration <= 0) { // Vibrator is supposed to go back off when this step starts, so just leave it off. - return previousStepVibratorOffTimeout; + return; } onDuration += remainingDuration; + + if (VibrationThread.DEBUG) { + Slog.d(VibrationThread.TAG, + "Turning the vibrator back ON using the remaining duration of " + + remainingDuration + "ms, for a total of " + onDuration + "ms"); + } + float expectedAmplitude = controller.getCurrentAmplitude(); - mVibratorOnResult = startVibrating(onDuration); - if (mVibratorOnResult > 0) { + long vibratorOnResult = startVibrating(onDuration); + if (vibratorOnResult > 0) { // Set the amplitude back to the value it was supposed to be playing at. changeAmplitude(expectedAmplitude); } - return SystemClock.uptimeMillis() + onDuration - + VibrationStepConductor.CALLBACKS_EXTRA_TIMEOUT; } private long startVibrating(long duration) { @@ -149,6 +160,7 @@ final class SetAmplitudeVibratorStep extends AbstractVibratorStep { + duration + "ms"); } long vibratorOnResult = controller.on(duration, getVibration().id); + handleVibratorOnResult(vibratorOnResult); getVibration().stats().reportVibratorOn(vibratorOnResult); return vibratorOnResult; } diff --git a/services/core/java/com/android/server/vibrator/VibrationStepConductor.java b/services/core/java/com/android/server/vibrator/VibrationStepConductor.java index 0799b955b6f1..0af171871792 100644 --- a/services/core/java/com/android/server/vibrator/VibrationStepConductor.java +++ b/services/core/java/com/android/server/vibrator/VibrationStepConductor.java @@ -112,8 +112,7 @@ final class VibrationStepConductor implements IBinder.DeathRecipient { @Nullable AbstractVibratorStep nextVibrateStep(long startTime, VibratorController controller, - VibrationEffect.Composed effect, int segmentIndex, - long previousStepVibratorOffTimeout) { + VibrationEffect.Composed effect, int segmentIndex, long pendingVibratorOffDeadline) { if (Build.IS_DEBUGGABLE) { expectIsVibrationThread(true); } @@ -123,24 +122,24 @@ final class VibrationStepConductor implements IBinder.DeathRecipient { if (segmentIndex < 0) { // No more segments to play, last step is to complete the vibration on this vibrator. return new CompleteEffectVibratorStep(this, startTime, /* cancelled= */ false, - controller, previousStepVibratorOffTimeout); + controller, pendingVibratorOffDeadline); } VibrationEffectSegment segment = effect.getSegments().get(segmentIndex); if (segment instanceof PrebakedSegment) { return new PerformPrebakedVibratorStep(this, startTime, controller, effect, - segmentIndex, previousStepVibratorOffTimeout); + segmentIndex, pendingVibratorOffDeadline); } if (segment instanceof PrimitiveSegment) { return new ComposePrimitivesVibratorStep(this, startTime, controller, effect, - segmentIndex, previousStepVibratorOffTimeout); + segmentIndex, pendingVibratorOffDeadline); } if (segment instanceof RampSegment) { return new ComposePwleVibratorStep(this, startTime, controller, effect, segmentIndex, - previousStepVibratorOffTimeout); + pendingVibratorOffDeadline); } return new SetAmplitudeVibratorStep(this, startTime, controller, effect, segmentIndex, - previousStepVibratorOffTimeout); + pendingVibratorOffDeadline); } /** Called when this conductor is going to be started running by the VibrationThread. */ diff --git a/services/core/java/com/android/server/vibrator/VibratorManagerService.java b/services/core/java/com/android/server/vibrator/VibratorManagerService.java index 2f12a820eb81..d1cde602b391 100644 --- a/services/core/java/com/android/server/vibrator/VibratorManagerService.java +++ b/services/core/java/com/android/server/vibrator/VibratorManagerService.java @@ -387,8 +387,8 @@ public class VibratorManagerService extends IVibratorManagerService.Stub { * An internal-only version of vibrate that allows the caller access to the {@link Vibration}. * The Vibration is only returned if it is ongoing after this method returns. */ - @Nullable @VisibleForTesting + @Nullable Vibration vibrateInternal(int uid, String opPkg, @NonNull CombinedVibration effect, @Nullable VibrationAttributes attrs, String reason, IBinder token) { Trace.traceBegin(Trace.TRACE_TAG_VIBRATOR, "vibrate, reason = " + reason); @@ -1844,6 +1844,8 @@ public class VibratorManagerService extends IVibratorManagerService.Stub { attrs, commonOptions.description, deathBinder); if (vib != null && !commonOptions.background) { try { + // Waits for the client vibration to finish, but the VibrationThread may still + // do cleanup after this. vib.waitForEnd(); } catch (InterruptedException e) { } diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java index 7e9474395f0c..f8f94f655a16 100644 --- a/services/core/java/com/android/server/wm/ActivityRecord.java +++ b/services/core/java/com/android/server/wm/ActivityRecord.java @@ -312,7 +312,6 @@ import android.util.TypedXmlPullParser; import android.util.TypedXmlSerializer; import android.util.proto.ProtoOutputStream; import android.view.AppTransitionAnimationSpec; -import android.view.DisplayCutout; import android.view.DisplayInfo; import android.view.IAppTransitionAnimationSpecsFuture; import android.view.InputApplicationHandle; @@ -357,6 +356,7 @@ import com.android.server.wm.ActivityMetricsLogger.TransitionInfoSnapshot; import com.android.server.wm.SurfaceAnimator.AnimationType; import com.android.server.wm.WindowManagerService.H; import com.android.server.wm.utils.InsetUtils; +import com.android.server.wm.utils.WmDisplayCutout; import dalvik.annotation.optimization.NeverCompile; @@ -3245,7 +3245,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A rootTask.moveToFront(reason, task); // Report top activity change to tracking services and WM if (mRootWindowContainer.getTopResumedActivity() == this) { - mAtmService.setResumedActivityUncheckLocked(this, reason); + mAtmService.setLastResumedActivityUncheckLocked(this, reason); } return true; } @@ -5887,7 +5887,8 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A try { mAtmService.getLifecycleManager().scheduleTransaction(app.getThread(), token, PauseActivityItem.obtain(finishing, false /* userLeaving */, - configChangeFlags, false /* dontReport */)); + configChangeFlags, false /* dontReport */, + false /* autoEnteringPip */)); } catch (Exception e) { Slog.w(TAG, "Exception thrown sending pause: " + intent.getComponent(), e); } @@ -9683,9 +9684,8 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A final boolean rotated = (rotation == ROTATION_90 || rotation == ROTATION_270); final int dw = rotated ? display.mBaseDisplayHeight : display.mBaseDisplayWidth; final int dh = rotated ? display.mBaseDisplayWidth : display.mBaseDisplayHeight; - final DisplayCutout cutout = display.calculateDisplayCutoutForRotation(rotation) - .getDisplayCutout(); - policy.getNonDecorInsetsLw(rotation, cutout, mNonDecorInsets[rotation]); + final WmDisplayCutout cutout = display.calculateDisplayCutoutForRotation(rotation); + policy.getNonDecorInsetsLw(rotation, dw, dh, cutout, mNonDecorInsets[rotation]); mStableInsets[rotation].set(mNonDecorInsets[rotation]); policy.convertNonDecorInsetsToStableInsets(mStableInsets[rotation], rotation); diff --git a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java index de3b2a686dde..4003eeb61abe 100644 --- a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java +++ b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java @@ -3563,7 +3563,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { // Continue the pausing process after entering pip. if (r.isState(PAUSING)) { r.getTask().schedulePauseActivity(r, false /* userLeaving */, - false /* pauseImmediately */, "auto-pip"); + false /* pauseImmediately */, true /* autoEnteringPip */, "auto-pip"); } } }; @@ -4624,7 +4624,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { } /** Update AMS states when an activity is resumed. */ - void setResumedActivityUncheckLocked(ActivityRecord r, String reason) { + void setLastResumedActivityUncheckLocked(ActivityRecord r, String reason) { final Task task = r.getTask(); if (task.isActivityTypeStandard()) { if (mCurAppTimeTracker != r.appTimeTracker) { diff --git a/services/core/java/com/android/server/wm/ActivityTaskSupervisor.java b/services/core/java/com/android/server/wm/ActivityTaskSupervisor.java index 20032d668344..dc91c1597128 100644 --- a/services/core/java/com/android/server/wm/ActivityTaskSupervisor.java +++ b/services/core/java/com/android/server/wm/ActivityTaskSupervisor.java @@ -2083,7 +2083,7 @@ public class ActivityTaskSupervisor implements RecentTasks.Callbacks { * activity releases the top state and reports back, message about acquiring top state will be * sent to the new top resumed activity. */ - void updateTopResumedActivityIfNeeded() { + void updateTopResumedActivityIfNeeded(String reason) { final ActivityRecord prevTopActivity = mTopResumedActivity; final Task topRootTask = mRootWindowContainer.getTopDisplayFocusedRootTask(); if (topRootTask == null || topRootTask.getTopResumedActivity() == prevTopActivity) { @@ -2119,6 +2119,12 @@ public class ActivityTaskSupervisor implements RecentTasks.Callbacks { } mService.updateOomAdj(); } + // Update the last resumed activity and focused app when the top resumed activity changed + // because the new top resumed activity might be already resumed and thus won't have + // activity state change to update the records to AMS. + if (mTopResumedActivity != null) { + mService.setLastResumedActivityUncheckLocked(mTopResumedActivity, reason); + } scheduleTopResumedActivityStateIfNeeded(); mService.updateTopApp(mTopResumedActivity); diff --git a/services/core/java/com/android/server/wm/AppTransition.java b/services/core/java/com/android/server/wm/AppTransition.java index 55d6b2fe8226..c940a658015d 100644 --- a/services/core/java/com/android/server/wm/AppTransition.java +++ b/services/core/java/com/android/server/wm/AppTransition.java @@ -375,9 +375,6 @@ public class AppTransition implements Dump { final AnimationAdapter topOpeningAnim = wc != null ? wc.getAnimation() : null; int redoLayout = notifyAppTransitionStartingLocked( - AppTransition.isKeyguardGoingAwayTransitOld(transit), - AppTransition.isKeyguardOccludeTransitOld(transit), - topOpeningAnim != null ? topOpeningAnim.getDurationHint() : 0, topOpeningAnim != null ? topOpeningAnim.getStatusBarTransitionsStartTime() : SystemClock.uptimeMillis(), @@ -416,7 +413,7 @@ public class AppTransition implements Dump { } void freeze() { - final boolean keyguardGoingAway = mNextAppTransitionRequests.contains( + final boolean keyguardGoingAwayCancelled = mNextAppTransitionRequests.contains( TRANSIT_KEYGUARD_GOING_AWAY); // The RemoteAnimationControl didn't register AppTransitionListener and @@ -429,7 +426,7 @@ public class AppTransition implements Dump { mNextAppTransitionRequests.clear(); clear(); setReady(); - notifyAppTransitionCancelledLocked(keyguardGoingAway); + notifyAppTransitionCancelledLocked(keyguardGoingAwayCancelled); } private void setAppTransitionState(int state) { @@ -479,9 +476,9 @@ public class AppTransition implements Dump { } } - private void notifyAppTransitionCancelledLocked(boolean keyguardGoingAway) { + private void notifyAppTransitionCancelledLocked(boolean keyguardGoingAwayCancelled) { for (int i = 0; i < mListeners.size(); i++) { - mListeners.get(i).onAppTransitionCancelledLocked(keyguardGoingAway); + mListeners.get(i).onAppTransitionCancelledLocked(keyguardGoingAwayCancelled); } } @@ -491,14 +488,12 @@ public class AppTransition implements Dump { } } - private int notifyAppTransitionStartingLocked(boolean keyguardGoingAway, - boolean keyguardOcclude, long duration, long statusBarAnimationStartTime, + private int notifyAppTransitionStartingLocked(long statusBarAnimationStartTime, long statusBarAnimationDuration) { int redoLayout = 0; for (int i = 0; i < mListeners.size(); i++) { - redoLayout |= mListeners.get(i).onAppTransitionStartingLocked(keyguardGoingAway, - keyguardOcclude, duration, statusBarAnimationStartTime, - statusBarAnimationDuration); + redoLayout |= mListeners.get(i).onAppTransitionStartingLocked( + statusBarAnimationStartTime, statusBarAnimationDuration); } return redoLayout; } diff --git a/services/core/java/com/android/server/wm/AppTransitionController.java b/services/core/java/com/android/server/wm/AppTransitionController.java index 44f388b6ed39..4b0005d77e40 100644 --- a/services/core/java/com/android/server/wm/AppTransitionController.java +++ b/services/core/java/com/android/server/wm/AppTransitionController.java @@ -20,10 +20,6 @@ import static android.app.WindowConfiguration.ACTIVITY_TYPE_DREAM; import static android.view.WindowManager.TRANSIT_CHANGE; import static android.view.WindowManager.TRANSIT_CLOSE; import static android.view.WindowManager.TRANSIT_FLAG_APP_CRASHED; -import static android.view.WindowManager.TRANSIT_FLAG_KEYGUARD_GOING_AWAY_NO_ANIMATION; -import static android.view.WindowManager.TRANSIT_FLAG_KEYGUARD_GOING_AWAY_SUBTLE_ANIMATION; -import static android.view.WindowManager.TRANSIT_FLAG_KEYGUARD_GOING_AWAY_TO_SHADE; -import static android.view.WindowManager.TRANSIT_FLAG_KEYGUARD_GOING_AWAY_WITH_WALLPAPER; import static android.view.WindowManager.TRANSIT_FLAG_OPEN_BEHIND; import static android.view.WindowManager.TRANSIT_KEYGUARD_GOING_AWAY; import static android.view.WindowManager.TRANSIT_KEYGUARD_OCCLUDE; @@ -95,7 +91,6 @@ import android.view.WindowManager.LayoutParams; import android.view.WindowManager.TransitionFlags; import android.view.WindowManager.TransitionOldType; import android.view.WindowManager.TransitionType; -import android.view.animation.Animation; import android.window.ITaskFragmentOrganizer; import com.android.internal.annotations.VisibleForTesting; @@ -297,7 +292,6 @@ public class AppTransitionController { final int flags = appTransition.getTransitFlags(); layoutRedo = appTransition.goodToGo(transit, topOpeningApp); - handleNonAppWindowsInTransition(transit, flags); appTransition.postAnimationCallback(); appTransition.clear(); } finally { @@ -1171,30 +1165,6 @@ public class AppTransitionController { } } - private void handleNonAppWindowsInTransition(@TransitionOldType int transit, int flags) { - if (transit == TRANSIT_OLD_KEYGUARD_GOING_AWAY - && !WindowManagerService.sEnableRemoteKeyguardGoingAwayAnimation) { - if ((flags & TRANSIT_FLAG_KEYGUARD_GOING_AWAY_WITH_WALLPAPER) != 0 - && (flags & TRANSIT_FLAG_KEYGUARD_GOING_AWAY_NO_ANIMATION) == 0 - && (flags & TRANSIT_FLAG_KEYGUARD_GOING_AWAY_SUBTLE_ANIMATION) == 0) { - Animation anim = mService.mPolicy.createKeyguardWallpaperExit( - (flags & TRANSIT_FLAG_KEYGUARD_GOING_AWAY_TO_SHADE) != 0); - if (anim != null) { - anim.scaleCurrentDuration(mService.getTransitionAnimationScaleLocked()); - mDisplayContent.mWallpaperController.startWallpaperAnimation(anim); - } - } - } - if ((transit == TRANSIT_OLD_KEYGUARD_GOING_AWAY - || transit == TRANSIT_OLD_KEYGUARD_GOING_AWAY_ON_WALLPAPER) - && !WindowManagerService.sEnableRemoteKeyguardGoingAwayAnimation) { - mDisplayContent.startKeyguardExitOnNonAppWindows( - transit == TRANSIT_OLD_KEYGUARD_GOING_AWAY_ON_WALLPAPER, - (flags & TRANSIT_FLAG_KEYGUARD_GOING_AWAY_TO_SHADE) != 0, - (flags & TRANSIT_FLAG_KEYGUARD_GOING_AWAY_SUBTLE_ANIMATION) != 0); - } - } - private boolean transitionGoodToGo(ArraySet<? extends WindowContainer> apps, ArrayMap<WindowContainer, Integer> outReasons) { ProtoLog.v(WM_DEBUG_APP_TRANSITIONS, diff --git a/services/core/java/com/android/server/wm/BLASTSyncEngine.java b/services/core/java/com/android/server/wm/BLASTSyncEngine.java index 9a94a4f54b61..d3452277a29f 100644 --- a/services/core/java/com/android/server/wm/BLASTSyncEngine.java +++ b/services/core/java/com/android/server/wm/BLASTSyncEngine.java @@ -22,6 +22,7 @@ import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_SYNC_ENGINE; import static com.android.server.wm.WindowState.BLAST_TIMEOUT_DURATION; import android.annotation.NonNull; +import android.annotation.Nullable; import android.os.Trace; import android.util.ArraySet; import android.util.Slog; @@ -63,6 +64,15 @@ import java.util.ArrayList; class BLASTSyncEngine { private static final String TAG = "BLASTSyncEngine"; + /** No specific method. Used by override specifiers. */ + public static final int METHOD_UNDEFINED = -1; + + /** No sync method. Apps will draw/present internally and just report. */ + public static final int METHOD_NONE = 0; + + /** Sync with BLAST. Apps will draw and then send the buffer to be applied in sync. */ + public static final int METHOD_BLAST = 1; + interface TransactionReadyListener { void onTransactionReady(int mSyncId, SurfaceControl.Transaction transaction); } @@ -85,6 +95,7 @@ class BLASTSyncEngine { */ class SyncGroup { final int mSyncId; + final int mSyncMethod; final TransactionReadyListener mListener; final Runnable mOnTimeout; boolean mReady = false; @@ -92,8 +103,9 @@ class BLASTSyncEngine { private SurfaceControl.Transaction mOrphanTransaction = null; private String mTraceName; - private SyncGroup(TransactionReadyListener listener, int id, String name) { + private SyncGroup(TransactionReadyListener listener, int id, String name, int method) { mSyncId = id; + mSyncMethod = method; mListener = listener; mOnTimeout = () -> { Slog.w(TAG, "Sync group " + mSyncId + " timeout"); @@ -271,16 +283,13 @@ class BLASTSyncEngine { * Prepares a {@link SyncGroup} that is not active yet. Caller must call {@link #startSyncSet} * before calling {@link #addToSyncSet(int, WindowContainer)} on any {@link WindowContainer}. */ - SyncGroup prepareSyncSet(TransactionReadyListener listener, String name) { - return new SyncGroup(listener, mNextSyncId++, name); + SyncGroup prepareSyncSet(TransactionReadyListener listener, String name, int method) { + return new SyncGroup(listener, mNextSyncId++, name, method); } - int startSyncSet(TransactionReadyListener listener) { - return startSyncSet(listener, BLAST_TIMEOUT_DURATION, ""); - } - - int startSyncSet(TransactionReadyListener listener, long timeoutMs, String name) { - final SyncGroup s = prepareSyncSet(listener, name); + int startSyncSet(TransactionReadyListener listener, long timeoutMs, String name, + int method) { + final SyncGroup s = prepareSyncSet(listener, name, method); startSyncSet(s, timeoutMs); return s.mSyncId; } @@ -302,6 +311,11 @@ class BLASTSyncEngine { scheduleTimeout(s, timeoutMs); } + @Nullable + SyncGroup getSyncSet(int id) { + return mActiveSyncs.get(id); + } + boolean hasActiveSync() { return mActiveSyncs.size() != 0; } diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java index 8a34af3b0107..1c90bbae79ec 100644 --- a/services/core/java/com/android/server/wm/DisplayContent.java +++ b/services/core/java/com/android/server/wm/DisplayContent.java @@ -441,7 +441,7 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp */ final DisplayMetrics mRealDisplayMetrics = new DisplayMetrics(); - /** @see #computeCompatSmallestWidth(boolean, int, int, int) */ + /** @see #computeCompatSmallestWidth(boolean, int, int) */ private final DisplayMetrics mTmpDisplayMetrics = new DisplayMetrics(); /** @@ -2017,7 +2017,7 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp // the top of the method, the caller is obligated to call computeNewConfigurationLocked(). // By updating the Display info here it will be available to // #computeScreenConfiguration() later. - updateDisplayAndOrientation(getConfiguration().uiMode, null /* outConfig */); + updateDisplayAndOrientation(null /* outConfig */); // NOTE: We disable the rotation in the emulator because // it doesn't support hardware OpenGL emulation yet. @@ -2067,7 +2067,7 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp * changed. * Do not call if {@link WindowManagerService#mDisplayReady} == false. */ - private DisplayInfo updateDisplayAndOrientation(int uiMode, Configuration outConfig) { + private DisplayInfo updateDisplayAndOrientation(Configuration outConfig) { // Use the effective "visual" dimensions based on current rotation final int rotation = getRotation(); final boolean rotated = (rotation == ROTATION_90 || rotation == ROTATION_270); @@ -2079,18 +2079,16 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp final DisplayCutout displayCutout = wmDisplayCutout.getDisplayCutout(); final RoundedCorners roundedCorners = calculateRoundedCornersForRotation(rotation); - final int appWidth = mDisplayPolicy.getNonDecorDisplayWidth(dw, dh, rotation, uiMode, - displayCutout); - final int appHeight = mDisplayPolicy.getNonDecorDisplayHeight(dh, rotation, - displayCutout); + final Rect appFrame = mDisplayPolicy.getNonDecorDisplayFrame(dw, dh, rotation, + wmDisplayCutout); mDisplayInfo.rotation = rotation; mDisplayInfo.logicalWidth = dw; mDisplayInfo.logicalHeight = dh; mDisplayInfo.logicalDensityDpi = mBaseDisplayDensity; mDisplayInfo.physicalXDpi = mBaseDisplayPhysicalXDpi; mDisplayInfo.physicalYDpi = mBaseDisplayPhysicalYDpi; - mDisplayInfo.appWidth = appWidth; - mDisplayInfo.appHeight = appHeight; + mDisplayInfo.appWidth = appFrame.width(); + mDisplayInfo.appHeight = appFrame.height(); if (isDefaultDisplay) { mDisplayInfo.getLogicalMetrics(mRealDisplayMetrics, CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO, null); @@ -2104,7 +2102,7 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp mDisplayInfo.flags &= ~Display.FLAG_SCALING_DISABLED; } - computeSizeRangesAndScreenLayout(mDisplayInfo, rotated, uiMode, dw, dh, + computeSizeRangesAndScreenLayout(mDisplayInfo, rotated, dw, dh, mDisplayMetrics.density, outConfig); mWmService.mDisplayManagerInternal.setDisplayInfoOverrideFromWindowManager(mDisplayId, @@ -2194,10 +2192,8 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp outConfig.windowConfiguration.setMaxBounds(0, 0, dw, dh); outConfig.windowConfiguration.setBounds(outConfig.windowConfiguration.getMaxBounds()); - final int uiMode = getConfiguration().uiMode; - final DisplayCutout displayCutout = - calculateDisplayCutoutForRotation(rotation).getDisplayCutout(); - computeScreenAppConfiguration(outConfig, dw, dh, rotation, uiMode, displayCutout); + final WmDisplayCutout wmDisplayCutout = calculateDisplayCutoutForRotation(rotation); + computeScreenAppConfiguration(outConfig, dw, dh, rotation, wmDisplayCutout); final DisplayInfo displayInfo = new DisplayInfo(mDisplayInfo); displayInfo.rotation = rotation; @@ -2206,38 +2202,35 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp final Rect appBounds = outConfig.windowConfiguration.getAppBounds(); displayInfo.appWidth = appBounds.width(); displayInfo.appHeight = appBounds.height(); + final DisplayCutout displayCutout = wmDisplayCutout.getDisplayCutout(); displayInfo.displayCutout = displayCutout.isEmpty() ? null : displayCutout; - computeSizeRangesAndScreenLayout(displayInfo, rotated, uiMode, dw, dh, + computeSizeRangesAndScreenLayout(displayInfo, rotated, dw, dh, mDisplayMetrics.density, outConfig); return displayInfo; } /** Compute configuration related to application without changing current display. */ private void computeScreenAppConfiguration(Configuration outConfig, int dw, int dh, - int rotation, int uiMode, DisplayCutout displayCutout) { - final int appWidth = mDisplayPolicy.getNonDecorDisplayWidth(dw, dh, rotation, uiMode, - displayCutout); - final int appHeight = mDisplayPolicy.getNonDecorDisplayHeight(dh, rotation, - displayCutout); - mDisplayPolicy.getNonDecorInsetsLw(rotation, displayCutout, mTmpRect); - final int leftInset = mTmpRect.left; - final int topInset = mTmpRect.top; + int rotation, WmDisplayCutout wmDisplayCutout) { + final DisplayFrames displayFrames = + mDisplayPolicy.getSimulatedDisplayFrames(rotation, dw, dh, wmDisplayCutout); + final Rect appFrame = + mDisplayPolicy.getNonDecorDisplayFrameWithSimulatedFrame(displayFrames); // AppBounds at the root level should mirror the app screen size. - outConfig.windowConfiguration.setAppBounds(leftInset /* left */, topInset /* top */, - leftInset + appWidth /* right */, topInset + appHeight /* bottom */); + outConfig.windowConfiguration.setAppBounds(appFrame); outConfig.windowConfiguration.setRotation(rotation); outConfig.orientation = (dw <= dh) ? ORIENTATION_PORTRAIT : ORIENTATION_LANDSCAPE; final float density = mDisplayMetrics.density; - outConfig.screenWidthDp = (int) (mDisplayPolicy.getConfigDisplayWidth(dw, dh, rotation, - uiMode, displayCutout) / density + 0.5f); - outConfig.screenHeightDp = (int) (mDisplayPolicy.getConfigDisplayHeight(dw, dh, rotation, - uiMode, displayCutout) / density + 0.5f); + final Point configSize = + mDisplayPolicy.getConfigDisplaySizeWithSimulatedFrame(displayFrames); + outConfig.screenWidthDp = (int) (configSize.x / density + 0.5f); + outConfig.screenHeightDp = (int) (configSize.y / density + 0.5f); outConfig.compatScreenWidthDp = (int) (outConfig.screenWidthDp / mCompatibleScreenScale); outConfig.compatScreenHeightDp = (int) (outConfig.screenHeightDp / mCompatibleScreenScale); final boolean rotated = (rotation == ROTATION_90 || rotation == ROTATION_270); - outConfig.compatSmallestScreenWidthDp = computeCompatSmallestWidth(rotated, uiMode, dw, dh); + outConfig.compatSmallestScreenWidthDp = computeCompatSmallestWidth(rotated, dw, dh); outConfig.windowConfiguration.setDisplayRotation(rotation); } @@ -2246,7 +2239,7 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp * Do not call if mDisplayReady == false. */ void computeScreenConfiguration(Configuration config) { - final DisplayInfo displayInfo = updateDisplayAndOrientation(config.uiMode, config); + final DisplayInfo displayInfo = updateDisplayAndOrientation(config); final int dw = displayInfo.logicalWidth; final int dh = displayInfo.logicalHeight; mTmpRect.set(0, 0, dw, dh); @@ -2255,8 +2248,8 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp config.windowConfiguration.setWindowingMode(getWindowingMode()); config.windowConfiguration.setDisplayWindowingMode(getWindowingMode()); - computeScreenAppConfiguration(config, dw, dh, displayInfo.rotation, config.uiMode, - displayInfo.displayCutout); + computeScreenAppConfiguration(config, dw, dh, displayInfo.rotation, + calculateDisplayCutoutForRotation(getRotation())); config.screenLayout = (config.screenLayout & ~Configuration.SCREENLAYOUT_ROUND_MASK) | ((displayInfo.flags & Display.FLAG_ROUND) != 0 @@ -2345,7 +2338,7 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp mWmService.mPolicy.adjustConfigurationLw(config, keyboardPresence, navigationPresence); } - private int computeCompatSmallestWidth(boolean rotated, int uiMode, int dw, int dh) { + private int computeCompatSmallestWidth(boolean rotated, int dw, int dh) { mTmpDisplayMetrics.setTo(mDisplayMetrics); final DisplayMetrics tmpDm = mTmpDisplayMetrics; final int unrotDw, unrotDh; @@ -2356,25 +2349,20 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp unrotDw = dw; unrotDh = dh; } - int sw = reduceCompatConfigWidthSize(0, Surface.ROTATION_0, uiMode, tmpDm, unrotDw, - unrotDh); - sw = reduceCompatConfigWidthSize(sw, Surface.ROTATION_90, uiMode, tmpDm, unrotDh, - unrotDw); - sw = reduceCompatConfigWidthSize(sw, Surface.ROTATION_180, uiMode, tmpDm, unrotDw, - unrotDh); - sw = reduceCompatConfigWidthSize(sw, Surface.ROTATION_270, uiMode, tmpDm, unrotDh, - unrotDw); + int sw = reduceCompatConfigWidthSize(0, Surface.ROTATION_0, tmpDm, unrotDw, unrotDh); + sw = reduceCompatConfigWidthSize(sw, Surface.ROTATION_90, tmpDm, unrotDh, unrotDw); + sw = reduceCompatConfigWidthSize(sw, Surface.ROTATION_180, tmpDm, unrotDw, unrotDh); + sw = reduceCompatConfigWidthSize(sw, Surface.ROTATION_270, tmpDm, unrotDh, unrotDw); return sw; } - private int reduceCompatConfigWidthSize(int curSize, int rotation, int uiMode, + private int reduceCompatConfigWidthSize(int curSize, int rotation, DisplayMetrics dm, int dw, int dh) { - final DisplayCutout displayCutout = calculateDisplayCutoutForRotation( - rotation).getDisplayCutout(); - dm.noncompatWidthPixels = mDisplayPolicy.getNonDecorDisplayWidth(dw, dh, rotation, uiMode, - displayCutout); - dm.noncompatHeightPixels = mDisplayPolicy.getNonDecorDisplayHeight(dh, rotation, - displayCutout); + final WmDisplayCutout wmDisplayCutout = calculateDisplayCutoutForRotation(rotation); + final Rect nonDecorSize = mDisplayPolicy.getNonDecorDisplayFrame(dw, dh, rotation, + wmDisplayCutout); + dm.noncompatWidthPixels = nonDecorSize.width(); + dm.noncompatHeightPixels = nonDecorSize.height(); float scale = CompatibilityInfo.computeCompatibleScaling(dm, null); int size = (int)(((dm.noncompatWidthPixels / scale) / dm.density) + .5f); if (curSize == 0 || size < curSize) { @@ -2384,7 +2372,7 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp } private void computeSizeRangesAndScreenLayout(DisplayInfo displayInfo, boolean rotated, - int uiMode, int dw, int dh, float density, Configuration outConfig) { + int dw, int dh, float density, Configuration outConfig) { // We need to determine the smallest width that will occur under normal // operation. To this, start with the base screen size and compute the @@ -2402,37 +2390,34 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp displayInfo.smallestNominalAppHeight = 1<<30; displayInfo.largestNominalAppWidth = 0; displayInfo.largestNominalAppHeight = 0; - adjustDisplaySizeRanges(displayInfo, Surface.ROTATION_0, uiMode, unrotDw, unrotDh); - adjustDisplaySizeRanges(displayInfo, Surface.ROTATION_90, uiMode, unrotDh, unrotDw); - adjustDisplaySizeRanges(displayInfo, Surface.ROTATION_180, uiMode, unrotDw, unrotDh); - adjustDisplaySizeRanges(displayInfo, Surface.ROTATION_270, uiMode, unrotDh, unrotDw); + adjustDisplaySizeRanges(displayInfo, Surface.ROTATION_0, unrotDw, unrotDh); + adjustDisplaySizeRanges(displayInfo, Surface.ROTATION_90, unrotDh, unrotDw); + adjustDisplaySizeRanges(displayInfo, Surface.ROTATION_180, unrotDw, unrotDh); + adjustDisplaySizeRanges(displayInfo, Surface.ROTATION_270, unrotDh, unrotDw); if (outConfig == null) { return; } int sl = Configuration.resetScreenLayout(outConfig.screenLayout); - sl = reduceConfigLayout(sl, Surface.ROTATION_0, density, unrotDw, unrotDh, uiMode); - sl = reduceConfigLayout(sl, Surface.ROTATION_90, density, unrotDh, unrotDw, uiMode); - sl = reduceConfigLayout(sl, Surface.ROTATION_180, density, unrotDw, unrotDh, uiMode); - sl = reduceConfigLayout(sl, Surface.ROTATION_270, density, unrotDh, unrotDw, uiMode); + sl = reduceConfigLayout(sl, Surface.ROTATION_0, density, unrotDw, unrotDh); + sl = reduceConfigLayout(sl, Surface.ROTATION_90, density, unrotDh, unrotDw); + sl = reduceConfigLayout(sl, Surface.ROTATION_180, density, unrotDw, unrotDh); + sl = reduceConfigLayout(sl, Surface.ROTATION_270, density, unrotDh, unrotDw); outConfig.smallestScreenWidthDp = (int) (displayInfo.smallestNominalAppWidth / density + 0.5f); outConfig.screenLayout = sl; } - private int reduceConfigLayout(int curLayout, int rotation, float density, int dw, int dh, - int uiMode) { + private int reduceConfigLayout(int curLayout, int rotation, float density, int dw, int dh) { // Get the display cutout at this rotation. - final DisplayCutout displayCutout = calculateDisplayCutoutForRotation( - rotation).getDisplayCutout(); + final WmDisplayCutout wmDisplayCutout = calculateDisplayCutoutForRotation(rotation); // Get the app screen size at this rotation. - int w = mDisplayPolicy.getNonDecorDisplayWidth(dw, dh, rotation, uiMode, displayCutout); - int h = mDisplayPolicy.getNonDecorDisplayHeight(dh, rotation, displayCutout); + final Rect size = mDisplayPolicy.getNonDecorDisplayFrame(dw, dh, rotation, wmDisplayCutout); // Compute the screen layout size class for this rotation. - int longSize = w; - int shortSize = h; + int longSize = size.width(); + int shortSize = size.height(); if (longSize < shortSize) { int tmp = longSize; longSize = shortSize; @@ -2443,25 +2428,20 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp return Configuration.reduceScreenLayout(curLayout, longSize, shortSize); } - private void adjustDisplaySizeRanges(DisplayInfo displayInfo, int rotation, - int uiMode, int dw, int dh) { - final DisplayCutout displayCutout = calculateDisplayCutoutForRotation( - rotation).getDisplayCutout(); - final int width = mDisplayPolicy.getConfigDisplayWidth(dw, dh, rotation, uiMode, - displayCutout); - if (width < displayInfo.smallestNominalAppWidth) { - displayInfo.smallestNominalAppWidth = width; + private void adjustDisplaySizeRanges(DisplayInfo displayInfo, int rotation, int dw, int dh) { + final WmDisplayCutout wmDisplayCutout = calculateDisplayCutoutForRotation(rotation); + final Point size = mDisplayPolicy.getConfigDisplaySize(dw, dh, rotation, wmDisplayCutout); + if (size.x < displayInfo.smallestNominalAppWidth) { + displayInfo.smallestNominalAppWidth = size.x; } - if (width > displayInfo.largestNominalAppWidth) { - displayInfo.largestNominalAppWidth = width; + if (size.x > displayInfo.largestNominalAppWidth) { + displayInfo.largestNominalAppWidth = size.x; } - final int height = mDisplayPolicy.getConfigDisplayHeight(dw, dh, rotation, uiMode, - displayCutout); - if (height < displayInfo.smallestNominalAppHeight) { - displayInfo.smallestNominalAppHeight = height; + if (size.y < displayInfo.smallestNominalAppHeight) { + displayInfo.smallestNominalAppHeight = size.y; } - if (height > displayInfo.largestNominalAppHeight) { - displayInfo.largestNominalAppHeight = height; + if (size.y > displayInfo.largestNominalAppHeight) { + displayInfo.largestNominalAppHeight = size.y; } } @@ -3316,6 +3296,14 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp mAsyncRotationController.keepAppearanceInPreviousRotation(); } } else if (isRotationChanging()) { + if (displayChange != null) { + final boolean seamless = mDisplayRotation.shouldRotateSeamlessly( + displayChange.getStartRotation(), displayChange.getEndRotation(), + false /* forceUpdate */); + if (seamless) { + t.onSeamlessRotating(this); + } + } mWmService.mLatencyTracker.onActionStart(ACTION_ROTATE_SCREEN); controller.mTransitionMetricsReporter.associate(t, startTime -> mWmService.mLatencyTracker.onActionEnd(ACTION_ROTATE_SCREEN)); @@ -6598,7 +6586,7 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp } @Override - public void onAppTransitionCancelledLocked(boolean keyguardGoingAway) { + public void onAppTransitionCancelledLocked(boolean keyguardGoingAwayCancelled) { // It is only needed when freezing display in legacy transition. if (mTransitionController.isShellTransitionsEnabled()) return; continueUpdateOrientationForDiffOrienLaunchingApp(); diff --git a/services/core/java/com/android/server/wm/DisplayPolicy.java b/services/core/java/com/android/server/wm/DisplayPolicy.java index 1a34c93f2ad6..508e6dc77a61 100644 --- a/services/core/java/com/android/server/wm/DisplayPolicy.java +++ b/services/core/java/com/android/server/wm/DisplayPolicy.java @@ -19,15 +19,19 @@ package com.android.server.wm; import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM; import static android.app.WindowConfiguration.WINDOWING_MODE_MULTI_WINDOW; import static android.view.Display.TYPE_INTERNAL; +import static android.view.InsetsState.ITYPE_BOTTOM_DISPLAY_CUTOUT; import static android.view.InsetsState.ITYPE_BOTTOM_MANDATORY_GESTURES; import static android.view.InsetsState.ITYPE_BOTTOM_TAPPABLE_ELEMENT; import static android.view.InsetsState.ITYPE_CAPTION_BAR; import static android.view.InsetsState.ITYPE_CLIMATE_BAR; import static android.view.InsetsState.ITYPE_EXTRA_NAVIGATION_BAR; +import static android.view.InsetsState.ITYPE_LEFT_DISPLAY_CUTOUT; import static android.view.InsetsState.ITYPE_LEFT_GESTURES; import static android.view.InsetsState.ITYPE_NAVIGATION_BAR; +import static android.view.InsetsState.ITYPE_RIGHT_DISPLAY_CUTOUT; import static android.view.InsetsState.ITYPE_RIGHT_GESTURES; import static android.view.InsetsState.ITYPE_STATUS_BAR; +import static android.view.InsetsState.ITYPE_TOP_DISPLAY_CUTOUT; import static android.view.InsetsState.ITYPE_TOP_MANDATORY_GESTURES; import static android.view.InsetsState.ITYPE_TOP_TAPPABLE_ELEMENT; import static android.view.WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS; @@ -103,6 +107,7 @@ import android.content.Intent; import android.content.res.Resources; import android.graphics.Insets; import android.graphics.PixelFormat; +import android.graphics.Point; import android.graphics.Rect; import android.graphics.Region; import android.gui.DropInputMode; @@ -127,6 +132,8 @@ import android.view.InsetsSource; import android.view.InsetsState; import android.view.InsetsState.InternalInsetsType; import android.view.InsetsVisibilities; +import android.view.PrivacyIndicatorBounds; +import android.view.RoundedCorners; import android.view.Surface; import android.view.View; import android.view.ViewDebug; @@ -136,7 +143,6 @@ import android.view.WindowLayout; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.view.WindowManagerGlobal; -import android.view.WindowManagerPolicyConstants; import android.view.accessibility.AccessibilityManager; import android.window.ClientWindowFrames; @@ -160,6 +166,7 @@ import com.android.server.policy.WindowManagerPolicy.ScreenOnListener; import com.android.server.policy.WindowManagerPolicy.WindowManagerFuncs; import com.android.server.statusbar.StatusBarManagerInternal; import com.android.server.wallpaper.WallpaperManagerInternal; +import com.android.server.wm.utils.WmDisplayCutout; import java.io.PrintWriter; import java.util.ArrayList; @@ -383,6 +390,16 @@ public class DisplayPolicy { private static final int MSG_REQUEST_TRANSIENT_BARS_ARG_STATUS = 0; private static final int MSG_REQUEST_TRANSIENT_BARS_ARG_NAVIGATION = 1; + // TODO (b/235842600): Use public type once we can treat task bar as navigation bar. + private static final int[] STABLE_TYPES = new int[]{ + ITYPE_TOP_DISPLAY_CUTOUT, ITYPE_RIGHT_DISPLAY_CUTOUT, ITYPE_BOTTOM_DISPLAY_CUTOUT, + ITYPE_LEFT_DISPLAY_CUTOUT, ITYPE_NAVIGATION_BAR, ITYPE_STATUS_BAR, ITYPE_CLIMATE_BAR + }; + private static final int[] NON_DECOR_TYPES = new int[]{ + ITYPE_TOP_DISPLAY_CUTOUT, ITYPE_RIGHT_DISPLAY_CUTOUT, ITYPE_BOTTOM_DISPLAY_CUTOUT, + ITYPE_LEFT_DISPLAY_CUTOUT, ITYPE_NAVIGATION_BAR + }; + private final GestureNavigationSettingsObserver mGestureNavigationSettingsObserver; private final WindowManagerInternal.AppTransitionListener mAppTransitionListener; @@ -602,9 +619,8 @@ public class DisplayPolicy { } @Override - public int onAppTransitionStartingLocked(boolean keyguardGoingAway, - boolean keyguardOccluding, long duration, - long statusBarAnimationStartTime, long statusBarAnimationDuration) { + public int onAppTransitionStartingLocked(long statusBarAnimationStartTime, + long statusBarAnimationDuration) { mHandler.post(() -> { StatusBarManagerInternal statusBar = getStatusBarManagerInternal(); if (statusBar != null) { @@ -616,7 +632,7 @@ public class DisplayPolicy { } @Override - public void onAppTransitionCancelledLocked(boolean keyguardGoingAway) { + public void onAppTransitionCancelledLocked(boolean keyguardGoingAwayCancelled) { mHandler.post(mAppTransitionCancelled); } @@ -2007,35 +2023,6 @@ public class DisplayPolicy { return mUiContext; } - private int getNavigationBarWidth(int rotation, int uiMode, int position) { - if (mNavigationBar == null) { - return 0; - } - LayoutParams lp = mNavigationBar.mAttrs; - if (lp.paramsForRotation != null - && lp.paramsForRotation.length == 4 - && lp.paramsForRotation[rotation] != null) { - lp = lp.paramsForRotation[rotation]; - } - Insets providedInsetsSize = null; - if (lp.providedInsets != null) { - for (InsetsFrameProvider provider : lp.providedInsets) { - if (provider.type != ITYPE_NAVIGATION_BAR) { - continue; - } - providedInsetsSize = provider.insetsSize; - } - } - if (providedInsetsSize != null) { - if (position == NAV_BAR_LEFT) { - return providedInsetsSize.left; - } else if (position == NAV_BAR_RIGHT) { - return providedInsetsSize.right; - } - } - return lp.width; - } - @VisibleForTesting void setCanSystemBarsBeShownByUser(boolean canBeShown) { mCanSystemBarsBeShownByUser = canBeShown; @@ -2057,45 +2044,24 @@ public class DisplayPolicy { } /** - * Return the display width available after excluding any screen - * decorations that could never be removed in Honeycomb. That is, system bar or - * button bar. + * Return the display frame available after excluding any screen decorations that could never be + * removed in Honeycomb. That is, system bar or button bar. + * + * @return display frame excluding all non-decor insets. */ - public int getNonDecorDisplayWidth(int fullWidth, int fullHeight, int rotation, int uiMode, - DisplayCutout displayCutout) { - int width = fullWidth; - if (hasNavigationBar()) { - final int navBarPosition = navigationBarPosition(rotation); - if (navBarPosition == NAV_BAR_LEFT || navBarPosition == NAV_BAR_RIGHT) { - width -= getNavigationBarWidth(rotation, uiMode, navBarPosition); - } - } - if (displayCutout != null) { - width -= displayCutout.getSafeInsetLeft() + displayCutout.getSafeInsetRight(); - } - return width; + Rect getNonDecorDisplayFrame(int fullWidth, int fullHeight, int rotation, + WmDisplayCutout cutout) { + final DisplayFrames displayFrames = + getSimulatedDisplayFrames(rotation, fullWidth, fullHeight, cutout); + return getNonDecorDisplayFrameWithSimulatedFrame(displayFrames); } - @VisibleForTesting - int getNavigationBarHeight(int rotation) { - if (mNavigationBar == null) { - return 0; - } - LayoutParams lp = mNavigationBar.mAttrs.forRotation(rotation); - Insets providedInsetsSize = null; - if (lp.providedInsets != null) { - for (InsetsFrameProvider provider : lp.providedInsets) { - if (provider.type != ITYPE_NAVIGATION_BAR) { - continue; - } - providedInsetsSize = provider.insetsSize; - if (providedInsetsSize != null) { - return providedInsetsSize.bottom; - } - break; - } - } - return lp.height; + Rect getNonDecorDisplayFrameWithSimulatedFrame(DisplayFrames displayFrames) { + final Rect nonDecorInsets = + getInsetsWithInternalTypes(displayFrames, NON_DECOR_TYPES).toRect(); + final Rect displayFrame = new Rect(displayFrames.mInsetsState.getDisplayFrame()); + displayFrame.inset(nonDecorInsets); + return displayFrame; } /** @@ -2117,53 +2083,23 @@ public class DisplayPolicy { } /** - * Return the display height available after excluding any screen - * decorations that could never be removed in Honeycomb. That is, system bar or - * button bar. - */ - public int getNonDecorDisplayHeight(int fullHeight, int rotation, DisplayCutout displayCutout) { - int height = fullHeight; - final int navBarPosition = navigationBarPosition(rotation); - if (navBarPosition == NAV_BAR_BOTTOM) { - height -= getNavigationBarHeight(rotation); - } - if (displayCutout != null) { - height -= displayCutout.getSafeInsetTop() + displayCutout.getSafeInsetBottom(); - } - return height; - } - - /** - * Return the available screen width that we should report for the + * Return the available screen size that we should report for the * configuration. This must be no larger than - * {@link #getNonDecorDisplayWidth(int, int, int, int, DisplayCutout)}; it may be smaller + * {@link #getNonDecorDisplayFrame(int, int, int, DisplayCutout)}; it may be smaller * than that to account for more transient decoration like a status bar. */ - public int getConfigDisplayWidth(int fullWidth, int fullHeight, int rotation, int uiMode, - DisplayCutout displayCutout) { - return getNonDecorDisplayWidth(fullWidth, fullHeight, rotation, uiMode, displayCutout); + public Point getConfigDisplaySize(int fullWidth, int fullHeight, int rotation, + WmDisplayCutout wmDisplayCutout) { + final DisplayFrames displayFrames = getSimulatedDisplayFrames(rotation, fullWidth, + fullHeight, wmDisplayCutout); + return getConfigDisplaySizeWithSimulatedFrame(displayFrames); } - /** - * Return the available screen height that we should report for the - * configuration. This must be no larger than - * {@link #getNonDecorDisplayHeight(int, int, DisplayCutout)}; it may be smaller - * than that to account for more transient decoration like a status bar. - */ - public int getConfigDisplayHeight(int fullWidth, int fullHeight, int rotation, int uiMode, - DisplayCutout displayCutout) { - // There is a separate status bar at the top of the display. We don't count that as part - // of the fixed decor, since it can hide; however, for purposes of configurations, - // we do want to exclude it since applications can't generally use that part - // of the screen. - int statusBarHeight = mStatusBarHeightForRotation[rotation]; - if (displayCutout != null) { - // If there is a cutout, it may already have accounted for some part of the status - // bar height. - statusBarHeight = Math.max(0, statusBarHeight - displayCutout.getSafeInsetTop()); - } - return getNonDecorDisplayHeight(fullHeight, rotation, displayCutout) - - statusBarHeight; + Point getConfigDisplaySizeWithSimulatedFrame(DisplayFrames displayFrames) { + final Insets insets = getInsetsWithInternalTypes(displayFrames, STABLE_TYPES); + Rect configFrame = new Rect(displayFrames.mInsetsState.getDisplayFrame()); + configFrame.inset(insets); + return new Point(configFrame.width(), configFrame.height()); } /** @@ -2195,48 +2131,75 @@ public class DisplayPolicy { * Calculates the stable insets without running a layout. * * @param displayRotation the current display rotation + * @param displayWidth full display width + * @param displayHeight full display height * @param displayCutout the current display cutout * @param outInsets the insets to return */ - public void getStableInsetsLw(int displayRotation, DisplayCutout displayCutout, - Rect outInsets) { - outInsets.setEmpty(); + public void getStableInsetsLw(int displayRotation, int displayWidth, int displayHeight, + WmDisplayCutout displayCutout, Rect outInsets) { + final DisplayFrames displayFrames = getSimulatedDisplayFrames(displayRotation, + displayWidth, displayHeight, displayCutout); + getStableInsetsWithSimulatedFrame(displayFrames, outInsets); + } - // Navigation bar and status bar. - getNonDecorInsetsLw(displayRotation, displayCutout, outInsets); - convertNonDecorInsetsToStableInsets(outInsets, displayRotation); + void getStableInsetsWithSimulatedFrame(DisplayFrames displayFrames, Rect outInsets) { + // Navigation bar, status bar, and cutout. + outInsets.set(getInsetsWithInternalTypes(displayFrames, STABLE_TYPES).toRect()); } /** * Calculates the insets for the areas that could never be removed in Honeycomb, i.e. system - * bar or button bar. See {@link #getNonDecorDisplayWidth}. - * @param displayRotation the current display rotation - * @param displayCutout the current display cutout + * bar or button bar. See {@link #getNonDecorDisplayFrame}. + * + * @param displayRotation the current display rotation + * @param fullWidth the width of the display, including all insets + * @param fullHeight the height of the display, including all insets + * @param cutout the current display cutout * @param outInsets the insets to return */ - public void getNonDecorInsetsLw(int displayRotation, DisplayCutout displayCutout, - Rect outInsets) { - outInsets.setEmpty(); - - // Only navigation bar - if (hasNavigationBar()) { - final int uiMode = mService.mPolicy.getUiMode(); - int position = navigationBarPosition(displayRotation); - if (position == NAV_BAR_BOTTOM) { - outInsets.bottom = getNavigationBarHeight(displayRotation); - } else if (position == NAV_BAR_RIGHT) { - outInsets.right = getNavigationBarWidth(displayRotation, uiMode, position); - } else if (position == NAV_BAR_LEFT) { - outInsets.left = getNavigationBarWidth(displayRotation, uiMode, position); - } - } + public void getNonDecorInsetsLw(int displayRotation, int fullWidth, int fullHeight, + WmDisplayCutout cutout, Rect outInsets) { + final DisplayFrames displayFrames = + getSimulatedDisplayFrames(displayRotation, fullWidth, fullHeight, cutout); + getNonDecorInsetsWithSimulatedFrame(displayFrames, outInsets); + } + + void getNonDecorInsetsWithSimulatedFrame(DisplayFrames displayFrames, Rect outInsets) { + outInsets.set(getInsetsWithInternalTypes(displayFrames, NON_DECOR_TYPES).toRect()); + } + + DisplayFrames getSimulatedDisplayFrames(int displayRotation, int fullWidth, + int fullHeight, WmDisplayCutout cutout) { + final DisplayInfo info = new DisplayInfo(mDisplayContent.getDisplayInfo()); + info.rotation = displayRotation; + info.logicalWidth = fullWidth; + info.logicalHeight = fullHeight; + info.displayCutout = cutout.getDisplayCutout(); + final RoundedCorners roundedCorners = + mDisplayContent.calculateRoundedCornersForRotation(displayRotation); + final PrivacyIndicatorBounds indicatorBounds = + mDisplayContent.calculatePrivacyIndicatorBoundsForRotation(displayRotation); + final DisplayFrames displayFrames = new DisplayFrames(getDisplayId(), new InsetsState(), + info, cutout, roundedCorners, indicatorBounds); + simulateLayoutDisplay(displayFrames); + return displayFrames; + } - if (displayCutout != null) { - outInsets.left += displayCutout.getSafeInsetLeft(); - outInsets.top += displayCutout.getSafeInsetTop(); - outInsets.right += displayCutout.getSafeInsetRight(); - outInsets.bottom += displayCutout.getSafeInsetBottom(); - } + @VisibleForTesting + Insets getInsets(DisplayFrames displayFrames, @InsetsType int type) { + final InsetsState state = displayFrames.mInsetsState; + final Insets insets = state.calculateInsets(state.getDisplayFrame(), type, + true /* ignoreVisibility */); + return insets; + } + + Insets getInsetsWithInternalTypes(DisplayFrames displayFrames, + @InternalInsetsType int[] types) { + final InsetsState state = displayFrames.mInsetsState; + final Insets insets = state.calculateInsetsWithInternalTypes(state.getDisplayFrame(), types, + true /* ignoreVisibility */); + return insets; } @NavigationBarPosition @@ -2256,17 +2219,6 @@ public class DisplayPolicy { } /** - * @return The side of the screen where navigation bar is positioned. - * @see WindowManagerPolicyConstants#NAV_BAR_LEFT - * @see WindowManagerPolicyConstants#NAV_BAR_RIGHT - * @see WindowManagerPolicyConstants#NAV_BAR_BOTTOM - */ - @NavigationBarPosition - public int getNavBarPosition() { - return mNavigationBarPosition; - } - - /** * A new window has been focused. */ public void focusChangedLw(WindowState lastFocus, WindowState newFocus) { diff --git a/services/core/java/com/android/server/wm/RecentsAnimationController.java b/services/core/java/com/android/server/wm/RecentsAnimationController.java index 5b702eac7059..7bb57d827a43 100644 --- a/services/core/java/com/android/server/wm/RecentsAnimationController.java +++ b/services/core/java/com/android/server/wm/RecentsAnimationController.java @@ -161,15 +161,14 @@ public class RecentsAnimationController implements DeathRecipient { */ final AppTransitionListener mAppTransitionListener = new AppTransitionListener() { @Override - public int onAppTransitionStartingLocked(boolean keyguardGoingAway, - boolean keyguardOccluding, long duration, long statusBarAnimationStartTime, + public int onAppTransitionStartingLocked(long statusBarAnimationStartTime, long statusBarAnimationDuration) { continueDeferredCancel(); return 0; } @Override - public void onAppTransitionCancelledLocked(boolean keyguardGoingAway) { + public void onAppTransitionCancelledLocked(boolean keyguardGoingAwayCancelled) { continueDeferredCancel(); } diff --git a/services/core/java/com/android/server/wm/RootWindowContainer.java b/services/core/java/com/android/server/wm/RootWindowContainer.java index 552c6a530544..077f8b55e5e6 100644 --- a/services/core/java/com/android/server/wm/RootWindowContainer.java +++ b/services/core/java/com/android/server/wm/RootWindowContainer.java @@ -512,7 +512,7 @@ class RootWindowContainer extends WindowContainer<DisplayContent> void onChildPositionChanged(WindowContainer child) { mWmService.updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL, !mWmService.mPerDisplayFocusEnabled /* updateInputWindows */); - mTaskSupervisor.updateTopResumedActivityIfNeeded(); + mTaskSupervisor.updateTopResumedActivityIfNeeded("onChildPositionChanged"); } @Override diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java index 0332935348e9..e38f5fe61888 100644 --- a/services/core/java/com/android/server/wm/Task.java +++ b/services/core/java/com/android/server/wm/Task.java @@ -920,7 +920,7 @@ class Task extends TaskFragment { // If the original state is resumed, there is no state change to update focused app. // So here makes sure the activity focus is set if it is the top. if (r.isState(RESUMED) && r == mRootWindowContainer.getTopResumedActivity()) { - mAtmService.setResumedActivityUncheckLocked(r, reason); + mAtmService.setLastResumedActivityUncheckLocked(r, reason); } } if (!animate) { @@ -1883,8 +1883,7 @@ class Task extends TaskFragment { } final int newWinMode = getWindowingMode(); - if ((prevWinMode != newWinMode) && (mDisplayContent != null) - && shouldStartChangeTransition(prevWinMode, newWinMode)) { + if (shouldStartChangeTransition(prevWinMode, mTmpPrevBounds)) { initializeChangeTransition(mTmpPrevBounds); } @@ -2135,10 +2134,16 @@ class Task extends TaskFragment { bounds.offset(horizontalDiff, verticalDiff); } - private boolean shouldStartChangeTransition(int prevWinMode, int newWinMode) { + private boolean shouldStartChangeTransition(int prevWinMode, @NonNull Rect prevBounds) { if (!isLeafTask() || !canStartChangeTransition()) { return false; } + final int newWinMode = getWindowingMode(); + if (mTransitionController.inTransition(this)) { + final Rect newBounds = getConfiguration().windowConfiguration.getBounds(); + return prevWinMode != newWinMode || prevBounds.width() != newBounds.width() + || prevBounds.height() != newBounds.height(); + } // Only do an animation into and out-of freeform mode for now. Other mode // transition animations are currently handled by system-ui. return (prevWinMode == WINDOWING_MODE_FREEFORM) != (newWinMode == WINDOWING_MODE_FREEFORM); @@ -2433,11 +2438,7 @@ class Task extends TaskFragment { focusableTask.moveToFront(myReason); // Top display focused root task is changed, update top resumed activity if needed. if (rootTask.getTopResumedActivity() != null) { - mTaskSupervisor.updateTopResumedActivityIfNeeded(); - // Set focused app directly because if the next focused activity is already resumed - // (e.g. the next top activity is on a different display), there won't have activity - // state change to update it. - mAtmService.setResumedActivityUncheckLocked(rootTask.getTopResumedActivity(), reason); + mTaskSupervisor.updateTopResumedActivityIfNeeded(reason); } return rootTask; } diff --git a/services/core/java/com/android/server/wm/TaskDisplayArea.java b/services/core/java/com/android/server/wm/TaskDisplayArea.java index 52bf220a647a..4063cae42b6b 100644 --- a/services/core/java/com/android/server/wm/TaskDisplayArea.java +++ b/services/core/java/com/android/server/wm/TaskDisplayArea.java @@ -323,6 +323,10 @@ final class TaskDisplayArea extends DisplayArea<WindowContainer> { // Clear preferred top because the adding focusable task has a higher z-order. mPreferredTopFocusableRootTask = null; } + + // Update the top resumed activity because the preferred top focusable task may be changed. + mAtmService.mTaskSupervisor.updateTopResumedActivityIfNeeded("addChildTask"); + mAtmService.updateSleepIfNeededLocked(); onRootTaskOrderChanged(task); } @@ -416,12 +420,7 @@ final class TaskDisplayArea extends DisplayArea<WindowContainer> { } // Update the top resumed activity because the preferred top focusable task may be changed. - mAtmService.mTaskSupervisor.updateTopResumedActivityIfNeeded(); - - final ActivityRecord r = child.getTopResumedActivity(); - if (r != null && r == mRootWindowContainer.getTopResumedActivity()) { - mAtmService.setResumedActivityUncheckLocked(r, "positionChildAt"); - } + mAtmService.mTaskSupervisor.updateTopResumedActivityIfNeeded("positionChildTaskAt"); if (mChildren.indexOf(child) != oldPosition) { onRootTaskOrderChanged(child); diff --git a/services/core/java/com/android/server/wm/TaskFragment.java b/services/core/java/com/android/server/wm/TaskFragment.java index 44b5b886a5f6..8872b3526e8c 100644 --- a/services/core/java/com/android/server/wm/TaskFragment.java +++ b/services/core/java/com/android/server/wm/TaskFragment.java @@ -98,6 +98,7 @@ import com.android.internal.util.function.pooled.PooledLambda; import com.android.internal.util.function.pooled.PooledPredicate; import com.android.server.am.HostingRecord; import com.android.server.pm.parsing.pkg.AndroidPackage; +import com.android.server.wm.utils.WmDisplayCutout; import java.io.FileDescriptor; import java.io.PrintWriter; @@ -460,7 +461,7 @@ class TaskFragment extends WindowContainer<WindowContainer> { final ActivityRecord prevR = mResumedActivity; mResumedActivity = r; - mTaskSupervisor.updateTopResumedActivityIfNeeded(); + mTaskSupervisor.updateTopResumedActivityIfNeeded(reason); if (r == null && prevR.mDisplayContent != null && prevR.mDisplayContent.getFocusedRootTask() == null) { // Only need to notify DWPC when no activity will resume. @@ -773,9 +774,6 @@ class TaskFragment extends WindowContainer<WindowContainer> { Slog.v(TAG, "set resumed activity to:" + record + " reason:" + reason); } setResumedActivity(record, reason + " - onActivityStateChanged"); - if (record == mRootWindowContainer.getTopResumedActivity()) { - mAtmService.setResumedActivityUncheckLocked(record, reason); - } mTaskSupervisor.mRecentTasks.add(record.getTask()); } } @@ -1621,7 +1619,8 @@ class TaskFragment extends WindowContainer<WindowContainer> { ProtoLog.d(WM_DEBUG_STATES, "Auto-PIP allowed, entering PIP mode " + "directly: %s, didAutoPip: %b", prev, didAutoPip); } else { - schedulePauseActivity(prev, userLeaving, pauseImmediately, reason); + schedulePauseActivity(prev, userLeaving, pauseImmediately, + false /* autoEnteringPip */, reason); } } else { mPausingActivity = null; @@ -1675,7 +1674,7 @@ class TaskFragment extends WindowContainer<WindowContainer> { } void schedulePauseActivity(ActivityRecord prev, boolean userLeaving, - boolean pauseImmediately, String reason) { + boolean pauseImmediately, boolean autoEnteringPip, String reason) { ProtoLog.v(WM_DEBUG_STATES, "Enqueueing pending pause: %s", prev); try { EventLogTags.writeWmPauseActivity(prev.mUserId, System.identityHashCode(prev), @@ -1683,7 +1682,7 @@ class TaskFragment extends WindowContainer<WindowContainer> { mAtmService.getLifecycleManager().scheduleTransaction(prev.app.getThread(), prev.token, PauseActivityItem.obtain(prev.finishing, userLeaving, - prev.configChangeFlags, pauseImmediately)); + prev.configChangeFlags, pauseImmediately, autoEnteringPip)); } catch (Exception e) { // Ignore exception, if process died other code will cleanup. Slog.w(TAG, "Exception thrown during pause", e); @@ -2210,11 +2209,13 @@ class TaskFragment extends WindowContainer<WindowContainer> { mTmpBounds.set(0, 0, displayInfo.logicalWidth, displayInfo.logicalHeight); final DisplayPolicy policy = rootTask.mDisplayContent.getDisplayPolicy(); - policy.getNonDecorInsetsLw(displayInfo.rotation, - displayInfo.displayCutout, mTmpInsets); + final WmDisplayCutout cutout = + rootTask.mDisplayContent.calculateDisplayCutoutForRotation(displayInfo.rotation); + final DisplayFrames displayFrames = policy.getSimulatedDisplayFrames(displayInfo.rotation, + displayInfo.logicalWidth, displayInfo.logicalHeight, cutout); + policy.getNonDecorInsetsWithSimulatedFrame(displayFrames, mTmpInsets); intersectWithInsetsIfFits(outNonDecorBounds, mTmpBounds, mTmpInsets); - - policy.convertNonDecorInsetsToStableInsets(mTmpInsets, displayInfo.rotation); + policy.getStableInsetsWithSimulatedFrame(displayFrames, mTmpInsets); intersectWithInsetsIfFits(outStableBounds, mTmpBounds, mTmpInsets); } diff --git a/services/core/java/com/android/server/wm/TaskFragmentOrganizerController.java b/services/core/java/com/android/server/wm/TaskFragmentOrganizerController.java index 88059e1a0d04..d615583f4d7f 100644 --- a/services/core/java/com/android/server/wm/TaskFragmentOrganizerController.java +++ b/services/core/java/com/android/server/wm/TaskFragmentOrganizerController.java @@ -49,7 +49,9 @@ import android.window.ITaskFragmentOrganizer; import android.window.ITaskFragmentOrganizerController; import android.window.TaskFragmentInfo; import android.window.TaskFragmentTransaction; +import android.window.WindowContainerTransaction; +import com.android.internal.protolog.ProtoLogGroup; import com.android.internal.protolog.common.ProtoLog; import java.lang.annotation.Retention; @@ -68,6 +70,8 @@ public class TaskFragmentOrganizerController extends ITaskFragmentOrganizerContr private final ActivityTaskManagerService mAtmService; private final WindowManagerGlobalLock mGlobalLock; + private final WindowOrganizerController mWindowOrganizerController; + /** * A Map which manages the relationship between * {@link ITaskFragmentOrganizer} and {@link TaskFragmentOrganizerState} @@ -82,9 +86,11 @@ public class TaskFragmentOrganizerController extends ITaskFragmentOrganizerContr private final ArraySet<Task> mTmpTaskSet = new ArraySet<>(); - TaskFragmentOrganizerController(ActivityTaskManagerService atm) { - mAtmService = atm; + TaskFragmentOrganizerController(@NonNull ActivityTaskManagerService atm, + @NonNull WindowOrganizerController windowOrganizerController) { + mAtmService = requireNonNull(atm); mGlobalLock = atm.mGlobalLock; + mWindowOrganizerController = requireNonNull(windowOrganizerController); } /** @@ -131,6 +137,14 @@ public class TaskFragmentOrganizerController extends ITaskFragmentOrganizerContr private final SparseArray<RemoteAnimationDefinition> mRemoteAnimationDefinitions = new SparseArray<>(); + /** + * List of {@link TaskFragmentTransaction#getTransactionToken()} that have been sent to the + * organizer. If the transaction is sent during a transition, the + * {@link TransitionController} will wait until the transaction is finished. + * @see #onTransactionFinished(IBinder) + */ + private final List<IBinder> mRunningTransactions = new ArrayList<>(); + TaskFragmentOrganizerState(ITaskFragmentOrganizer organizer, int pid, int uid) { mOrganizer = organizer; mOrganizerPid = pid; @@ -176,6 +190,10 @@ public class TaskFragmentOrganizerController extends ITaskFragmentOrganizerContr taskFragment.removeImmediately(); mOrganizedTaskFragments.remove(taskFragment); } + for (int i = mRunningTransactions.size() - 1; i >= 0; i--) { + // Cleanup any running transaction to unblock the current transition. + onTransactionFinished(mRunningTransactions.get(i)); + } mOrganizer.asBinder().unlinkToDeath(this, 0 /*flags*/); } @@ -320,6 +338,40 @@ public class TaskFragmentOrganizerController extends ITaskFragmentOrganizerContr .setActivityIntent(activity.intent) .setActivityToken(activityToken); } + + void dispatchTransaction(@NonNull TaskFragmentTransaction transaction) { + if (transaction.isEmpty()) { + return; + } + try { + mOrganizer.onTransactionReady(transaction); + } catch (RemoteException e) { + Slog.d(TAG, "Exception sending TaskFragmentTransaction", e); + return; + } + onTransactionStarted(transaction.getTransactionToken()); + } + + /** Called when the transaction is sent to the organizer. */ + void onTransactionStarted(@NonNull IBinder transactionToken) { + if (!mWindowOrganizerController.getTransitionController().isCollecting()) { + return; + } + ProtoLog.v(ProtoLogGroup.WM_DEBUG_WINDOW_TRANSITIONS, + "Defer transition ready for TaskFragmentTransaction=%s", transactionToken); + mRunningTransactions.add(transactionToken); + mWindowOrganizerController.getTransitionController().deferTransitionReady(); + } + + /** Called when the transaction is finished. */ + void onTransactionFinished(@NonNull IBinder transactionToken) { + if (!mRunningTransactions.remove(transactionToken)) { + return; + } + ProtoLog.v(ProtoLogGroup.WM_DEBUG_WINDOW_TRANSITIONS, + "Continue transition ready for TaskFragmentTransaction=%s", transactionToken); + mWindowOrganizerController.getTransitionController().continueTransitionReady(); + } } @Nullable @@ -336,7 +388,7 @@ public class TaskFragmentOrganizerController extends ITaskFragmentOrganizerContr } @Override - public void registerOrganizer(ITaskFragmentOrganizer organizer) { + public void registerOrganizer(@NonNull ITaskFragmentOrganizer organizer) { final int pid = Binder.getCallingPid(); final int uid = Binder.getCallingUid(); synchronized (mGlobalLock) { @@ -354,7 +406,7 @@ public class TaskFragmentOrganizerController extends ITaskFragmentOrganizerContr } @Override - public void unregisterOrganizer(ITaskFragmentOrganizer organizer) { + public void unregisterOrganizer(@NonNull ITaskFragmentOrganizer organizer) { validateAndGetState(organizer); final int pid = Binder.getCallingPid(); final long uid = Binder.getCallingUid(); @@ -372,8 +424,8 @@ public class TaskFragmentOrganizerController extends ITaskFragmentOrganizerContr } @Override - public void registerRemoteAnimations(ITaskFragmentOrganizer organizer, int taskId, - RemoteAnimationDefinition definition) { + public void registerRemoteAnimations(@NonNull ITaskFragmentOrganizer organizer, int taskId, + @NonNull RemoteAnimationDefinition definition) { final int pid = Binder.getCallingPid(); final int uid = Binder.getCallingUid(); synchronized (mGlobalLock) { @@ -398,7 +450,7 @@ public class TaskFragmentOrganizerController extends ITaskFragmentOrganizerContr } @Override - public void unregisterRemoteAnimations(ITaskFragmentOrganizer organizer, int taskId) { + public void unregisterRemoteAnimations(@NonNull ITaskFragmentOrganizer organizer, int taskId) { final int pid = Binder.getCallingPid(); final long uid = Binder.getCallingUid(); synchronized (mGlobalLock) { @@ -416,6 +468,17 @@ public class TaskFragmentOrganizerController extends ITaskFragmentOrganizerContr } } + @Override + public void onTransactionHandled(@NonNull ITaskFragmentOrganizer organizer, + @NonNull IBinder transactionToken, @NonNull WindowContainerTransaction wct) { + synchronized (mGlobalLock) { + // Keep the calling identity to avoid unsecure change. + mWindowOrganizerController.applyTransaction(wct); + final TaskFragmentOrganizerState state = validateAndGetState(organizer); + state.onTransactionFinished(transactionToken); + } + } + /** * Gets the {@link RemoteAnimationDefinition} set on the given organizer if exists. Returns * {@code null} if it doesn't, or if the organizer has activity(ies) embedded in untrusted mode. @@ -775,13 +838,13 @@ public class TaskFragmentOrganizerController extends ITaskFragmentOrganizerContr } final int organizerNum = mPendingTaskFragmentEvents.size(); for (int i = 0; i < organizerNum; i++) { - final ITaskFragmentOrganizer organizer = mTaskFragmentOrganizerState.get( - mPendingTaskFragmentEvents.keyAt(i)).mOrganizer; - dispatchPendingEvents(organizer, mPendingTaskFragmentEvents.valueAt(i)); + final TaskFragmentOrganizerState state = + mTaskFragmentOrganizerState.get(mPendingTaskFragmentEvents.keyAt(i)); + dispatchPendingEvents(state, mPendingTaskFragmentEvents.valueAt(i)); } } - void dispatchPendingEvents(@NonNull ITaskFragmentOrganizer organizer, + void dispatchPendingEvents(@NonNull TaskFragmentOrganizerState state, @NonNull List<PendingTaskFragmentEvent> pendingEvents) { if (pendingEvents.isEmpty()) { return; @@ -817,7 +880,7 @@ public class TaskFragmentOrganizerController extends ITaskFragmentOrganizerContr if (mTmpTaskSet.add(task)) { // Make sure the organizer know about the Task config. transaction.addChange(prepareChange(new PendingTaskFragmentEvent.Builder( - PendingTaskFragmentEvent.EVENT_PARENT_INFO_CHANGED, organizer) + PendingTaskFragmentEvent.EVENT_PARENT_INFO_CHANGED, state.mOrganizer) .setTask(task) .build())); } @@ -825,7 +888,7 @@ public class TaskFragmentOrganizerController extends ITaskFragmentOrganizerContr transaction.addChange(prepareChange(event)); } mTmpTaskSet.clear(); - dispatchTransactionInfo(organizer, transaction); + state.dispatchTransaction(transaction); pendingEvents.removeAll(candidateEvents); } @@ -855,6 +918,7 @@ public class TaskFragmentOrganizerController extends ITaskFragmentOrganizerContr } final ITaskFragmentOrganizer organizer = taskFragment.getTaskFragmentOrganizer(); + final TaskFragmentOrganizerState state = validateAndGetState(organizer); final TaskFragmentTransaction transaction = new TaskFragmentTransaction(); // Make sure the organizer know about the Task config. transaction.addChange(prepareChange(new PendingTaskFragmentEvent.Builder( @@ -862,22 +926,10 @@ public class TaskFragmentOrganizerController extends ITaskFragmentOrganizerContr .setTask(taskFragment.getTask()) .build())); transaction.addChange(prepareChange(event)); - dispatchTransactionInfo(event.mTaskFragmentOrg, transaction); + state.dispatchTransaction(transaction); mPendingTaskFragmentEvents.get(organizer.asBinder()).remove(event); } - private void dispatchTransactionInfo(@NonNull ITaskFragmentOrganizer organizer, - @NonNull TaskFragmentTransaction transaction) { - if (transaction.isEmpty()) { - return; - } - try { - organizer.onTransactionReady(transaction); - } catch (RemoteException e) { - Slog.d(TAG, "Exception sending TaskFragmentTransaction", e); - } - } - @Nullable private TaskFragmentTransaction.Change prepareChange( @NonNull PendingTaskFragmentEvent event) { diff --git a/services/core/java/com/android/server/wm/Transition.java b/services/core/java/com/android/server/wm/Transition.java index 803890b4032d..c586b155a222 100644 --- a/services/core/java/com/android/server/wm/Transition.java +++ b/services/core/java/com/android/server/wm/Transition.java @@ -16,6 +16,7 @@ package com.android.server.wm; +import static android.app.ActivityOptions.ANIM_OPEN_CROSS_PROFILE_APPS; import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME; import static android.app.WindowConfiguration.ACTIVITY_TYPE_RECENTS; import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD; @@ -31,13 +32,7 @@ import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD; import static android.view.WindowManager.TRANSIT_CHANGE; import static android.view.WindowManager.TRANSIT_CLOSE; import static android.view.WindowManager.TRANSIT_FLAG_IS_RECENTS; -import static android.view.WindowManager.TRANSIT_FLAG_KEYGUARD_GOING_AWAY; -import static android.view.WindowManager.TRANSIT_FLAG_KEYGUARD_GOING_AWAY_NO_ANIMATION; -import static android.view.WindowManager.TRANSIT_FLAG_KEYGUARD_GOING_AWAY_SUBTLE_ANIMATION; -import static android.view.WindowManager.TRANSIT_FLAG_KEYGUARD_GOING_AWAY_TO_SHADE; -import static android.view.WindowManager.TRANSIT_FLAG_KEYGUARD_GOING_AWAY_WITH_WALLPAPER; import static android.view.WindowManager.TRANSIT_FLAG_KEYGUARD_LOCKED; -import static android.view.WindowManager.TRANSIT_KEYGUARD_GOING_AWAY; import static android.view.WindowManager.TRANSIT_OPEN; import static android.view.WindowManager.TRANSIT_TO_BACK; import static android.view.WindowManager.TRANSIT_TO_FRONT; @@ -68,11 +63,11 @@ import android.app.ActivityManager; import android.content.pm.ActivityInfo; import android.graphics.Point; import android.graphics.Rect; +import android.hardware.HardwareBuffer; import android.os.Binder; import android.os.IBinder; import android.os.IRemoteCallback; import android.os.RemoteException; -import android.os.SystemClock; import android.os.Trace; import android.util.ArrayMap; import android.util.ArraySet; @@ -80,7 +75,6 @@ import android.util.Slog; import android.util.SparseArray; import android.view.SurfaceControl; import android.view.WindowManager; -import android.view.animation.Animation; import android.window.RemoteTransition; import android.window.TransitionInfo; @@ -205,6 +199,9 @@ class Transition extends Binder implements BLASTSyncEngine.TransactionReadyListe /** @see #setCanPipOnFinish */ private boolean mCanPipOnFinish = true; + private boolean mIsSeamlessRotation = false; + private IContainerFreezer mContainerFreezer = null; + Transition(@TransitionType int type, @TransitionFlags int flags, TransitionController controller, BLASTSyncEngine syncEngine) { mType = type; @@ -265,10 +262,31 @@ class Transition extends Binder implements BLASTSyncEngine.TransactionReadyListe return mTargetDisplays.contains(dc); } + /** Set a transition to be a seamless-rotation. */ void setSeamlessRotation(@NonNull WindowContainer wc) { final ChangeInfo info = mChanges.get(wc); if (info == null) return; info.mFlags = info.mFlags | ChangeInfo.FLAG_SEAMLESS_ROTATION; + onSeamlessRotating(wc.getDisplayContent()); + } + + /** + * Called when it's been determined that this is transition is a seamless rotation. This should + * be called before any WM changes have happened. + */ + void onSeamlessRotating(@NonNull DisplayContent dc) { + // Don't need to do anything special if everything is using BLAST sync already. + if (mSyncEngine.getSyncSet(mSyncId).mSyncMethod == BLASTSyncEngine.METHOD_BLAST) return; + if (mContainerFreezer == null) { + mContainerFreezer = new ScreenshotFreezer(); + } + mIsSeamlessRotation = true; + final WindowState top = dc.getDisplayPolicy().getTopFullscreenOpaqueWindow(); + if (top != null) { + top.mSyncMethodOverride = BLASTSyncEngine.METHOD_BLAST; + ProtoLog.v(ProtoLogGroup.WM_DEBUG_WINDOW_TRANSITIONS, "Override sync-method for %s " + + "because seamless rotating", top.getName()); + } } /** @@ -285,6 +303,11 @@ class Transition extends Binder implements BLASTSyncEngine.TransactionReadyListe } } + /** Only for testing. */ + void setContainerFreezer(IContainerFreezer freezer) { + mContainerFreezer = freezer; + } + @TransitionState int getState() { return mState; @@ -314,13 +337,18 @@ class Transition extends Binder implements BLASTSyncEngine.TransactionReadyListe return mState == STATE_COLLECTING || mState == STATE_STARTED; } - /** Starts collecting phase. Once this starts, all relevant surface operations are sync. */ + @VisibleForTesting void startCollecting(long timeoutMs) { + startCollecting(timeoutMs, TransitionController.SYNC_METHOD); + } + + /** Starts collecting phase. Once this starts, all relevant surface operations are sync. */ + void startCollecting(long timeoutMs, int method) { if (mState != STATE_PENDING) { throw new IllegalStateException("Attempting to re-use a transition"); } mState = STATE_COLLECTING; - mSyncId = mSyncEngine.startSyncSet(this, timeoutMs, TAG); + mSyncId = mSyncEngine.startSyncSet(this, timeoutMs, TAG, method); mController.mTransitionTracer.logState(this); } @@ -415,6 +443,37 @@ class Transition extends Binder implements BLASTSyncEngine.TransactionReadyListe } /** + * Records that a particular container is changing visibly (ie. something about it is changing + * while it remains visible). This only effects windows that are already in the collecting + * transition. + */ + void collectVisibleChange(WindowContainer wc) { + if (mSyncEngine.getSyncSet(mSyncId).mSyncMethod == BLASTSyncEngine.METHOD_BLAST) { + // All windows are synced already. + return; + } + if (!isInTransition(wc)) return; + + if (mContainerFreezer == null) { + mContainerFreezer = new ScreenshotFreezer(); + } + Transition.ChangeInfo change = mChanges.get(wc); + if (change == null || !change.mVisible || !wc.isVisibleRequested()) return; + // Note: many more tests have already been done by caller. + mContainerFreezer.freeze(wc, change.mAbsoluteBounds); + } + + /** + * @return {@code true} if `wc` is a participant or is a descendant of one. + */ + boolean isInTransition(WindowContainer wc) { + for (WindowContainer p = wc; p != null; p = p.getParent()) { + if (mParticipants.contains(p)) return true; + } + return false; + } + + /** * Specifies configuration change explicitly for the window container, so it can be chosen as * transition target. This is usually used with transition mode * {@link android.view.WindowManager#TRANSIT_CHANGE}. @@ -531,6 +590,10 @@ class Transition extends Binder implements BLASTSyncEngine.TransactionReadyListe displays.add(target.getDisplayContent()); } } + // Remove screenshot layers if necessary + if (mContainerFreezer != null) { + mContainerFreezer.cleanUp(t); + } // Need to update layers on involved displays since they were all paused while // the animation played. This puts the layers back into the correct order. mController.mBuildingFinishLayers = true; @@ -817,6 +880,19 @@ class Transition extends Binder implements BLASTSyncEngine.TransactionReadyListe transaction); if (mOverrideOptions != null) { info.setAnimationOptions(mOverrideOptions); + if (mOverrideOptions.getType() == ANIM_OPEN_CROSS_PROFILE_APPS) { + for (int i = 0; i < mTargets.size(); ++i) { + final TransitionInfo.Change c = info.getChanges().get(i); + final ActivityRecord ar = mTargets.get(i).asActivityRecord(); + if (ar == null || c.getMode() != TRANSIT_OPEN) continue; + int flags = c.getFlags(); + flags |= ar.mUserId == ar.mWmService.mCurrentUserId + ? TransitionInfo.FLAG_CROSS_PROFILE_OWNER_THUMBNAIL + : TransitionInfo.FLAG_CROSS_PROFILE_WORK_THUMBNAIL; + c.setFlags(flags); + break; + } + } } // TODO(b/188669821): Move to animation impl in shell. @@ -1066,36 +1142,9 @@ class Transition extends Binder implements BLASTSyncEngine.TransactionReadyListe private void handleNonAppWindowsInTransition(@NonNull DisplayContent dc, @TransitionType int transit, @TransitionFlags int flags) { - if ((transit == TRANSIT_KEYGUARD_GOING_AWAY - || (flags & TRANSIT_FLAG_KEYGUARD_GOING_AWAY) != 0) - && !WindowManagerService.sEnableRemoteKeyguardGoingAwayAnimation) { - if ((flags & TRANSIT_FLAG_KEYGUARD_GOING_AWAY_WITH_WALLPAPER) != 0 - && (flags & TRANSIT_FLAG_KEYGUARD_GOING_AWAY_NO_ANIMATION) == 0 - && (flags & TRANSIT_FLAG_KEYGUARD_GOING_AWAY_SUBTLE_ANIMATION) == 0) { - Animation anim = mController.mAtm.mWindowManager.mPolicy - .createKeyguardWallpaperExit( - (flags & TRANSIT_FLAG_KEYGUARD_GOING_AWAY_TO_SHADE) != 0); - if (anim != null) { - anim.scaleCurrentDuration( - mController.mAtm.mWindowManager.getTransitionAnimationScaleLocked()); - dc.mWallpaperController.startWallpaperAnimation(anim); - } - } - dc.startKeyguardExitOnNonAppWindows( - (flags & TRANSIT_FLAG_KEYGUARD_GOING_AWAY_WITH_WALLPAPER) != 0, - (flags & TRANSIT_FLAG_KEYGUARD_GOING_AWAY_TO_SHADE) != 0, - (flags & TRANSIT_FLAG_KEYGUARD_GOING_AWAY_SUBTLE_ANIMATION) != 0); - if (!WindowManagerService.sEnableRemoteKeyguardGoingAwayAnimation) { - // When remote animation is enabled for KEYGUARD_GOING_AWAY transition, SysUI - // receives IRemoteAnimationRunner#onAnimationStart to start animation, so we don't - // need to call IKeyguardService#keyguardGoingAway here. - mController.mAtm.mWindowManager.mPolicy.startKeyguardExitAnimation( - SystemClock.uptimeMillis(), 0 /* duration */); - } - } if ((flags & TRANSIT_FLAG_KEYGUARD_LOCKED) != 0) { mController.mAtm.mWindowManager.mPolicy.applyKeyguardOcclusionChange( - true /* keyguardOccludingStarted */); + false /* notify */); } } @@ -1815,6 +1864,8 @@ class Transition extends Binder implements BLASTSyncEngine.TransactionReadyListe /** This undoes one call to {@link #deferTransitionReady}. */ void continueTransitionReady() { --mReadyTracker.mDeferReadyDepth; + // Apply ready in case it is waiting for the previous defer call. + applyReady(); } /** @@ -1980,4 +2031,111 @@ class Transition extends Binder implements BLASTSyncEngine.TransactionReadyListe return sortedTargets; } } + + /** + * Interface for freezing a container's content during sync preparation. Really just one impl + * but broken into an interface for testing (since you can't take screenshots in unit tests). + */ + interface IContainerFreezer { + /** + * Makes sure a particular window is "frozen" for the remainder of a sync. + * + * @return whether the freeze was successful. It fails if `wc` is already in a frozen window + * or is not visible/ready. + */ + boolean freeze(@NonNull WindowContainer wc, @NonNull Rect bounds); + + /** Populates `t` with operations that clean-up any state created to set-up the freeze. */ + void cleanUp(SurfaceControl.Transaction t); + } + + /** + * Freezes container content by taking a screenshot. Because screenshots are heavy, usage of + * any container "freeze" is currently explicit. WM code needs to be prudent about which + * containers to freeze. + */ + @VisibleForTesting + private class ScreenshotFreezer implements IContainerFreezer { + /** Values are the screenshot "surfaces" or null if it was frozen via BLAST override. */ + private final ArrayMap<WindowContainer, SurfaceControl> mSnapshots = new ArrayMap<>(); + + /** Takes a screenshot and puts it at the top of the container's surface. */ + @Override + public boolean freeze(@NonNull WindowContainer wc, @NonNull Rect bounds) { + if (!wc.isVisibleRequested()) return false; + + // Check if any parents have already been "frozen". If so, `wc` is already part of that + // snapshot, so just skip it. + for (WindowContainer p = wc; p != null; p = p.getParent()) { + if (mSnapshots.containsKey(p)) return false; + } + + if (mIsSeamlessRotation) { + WindowState top = wc.getDisplayContent() == null ? null + : wc.getDisplayContent().getDisplayPolicy().getTopFullscreenOpaqueWindow(); + if (top != null && (top == wc || top.isDescendantOf(wc))) { + // Don't use screenshots for seamless windows: these will use BLAST even if not + // BLAST mode. + mSnapshots.put(wc, null); + return true; + } + } + + ProtoLog.v(ProtoLogGroup.WM_DEBUG_WINDOW_TRANSITIONS, "Screenshotting %s [%s]", + wc.toString(), bounds.toString()); + + Rect cropBounds = new Rect(bounds); + cropBounds.offsetTo(0, 0); + SurfaceControl.LayerCaptureArgs captureArgs = + new SurfaceControl.LayerCaptureArgs.Builder(wc.getSurfaceControl()) + .setSourceCrop(cropBounds) + .setCaptureSecureLayers(true) + .setAllowProtected(true) + .build(); + SurfaceControl.ScreenshotHardwareBuffer screenshotBuffer = + SurfaceControl.captureLayers(captureArgs); + final HardwareBuffer buffer = screenshotBuffer == null ? null + : screenshotBuffer.getHardwareBuffer(); + if (buffer == null || buffer.getWidth() <= 1 || buffer.getHeight() <= 1) { + // This can happen when display is not ready. + Slog.w(TAG, "Failed to capture screenshot for " + wc); + return false; + } + SurfaceControl snapshotSurface = wc.makeAnimationLeash() + .setName("transition snapshot: " + wc.toString()) + .setOpaque(true) + .setParent(wc.getSurfaceControl()) + .setSecure(screenshotBuffer.containsSecureLayers()) + .setCallsite("Transition.ScreenshotSync") + .setBLASTLayer() + .build(); + mSnapshots.put(wc, snapshotSurface); + SurfaceControl.Transaction t = wc.mWmService.mTransactionFactory.get(); + + t.setBuffer(snapshotSurface, buffer); + t.setDataSpace(snapshotSurface, screenshotBuffer.getColorSpace().getDataSpace()); + t.show(snapshotSurface); + + // Place it on top of anything else in the container. + t.setLayer(snapshotSurface, Integer.MAX_VALUE); + t.apply(); + t.close(); + + // Detach the screenshot on the sync transaction (the screenshot is just meant to + // freeze the window until the sync transaction is applied (with all its other + // corresponding changes), so this is how we unfreeze it. + wc.getSyncTransaction().reparent(snapshotSurface, null /* newParent */); + return true; + } + + @Override + public void cleanUp(SurfaceControl.Transaction t) { + for (int i = 0; i < mSnapshots.size(); ++i) { + SurfaceControl snap = mSnapshots.valueAt(i); + // May be null if it was frozen via BLAST override. + if (snap == null) continue; + t.remove(snap); + } + } + } } diff --git a/services/core/java/com/android/server/wm/TransitionController.java b/services/core/java/com/android/server/wm/TransitionController.java index 846aa3e3739a..e2438097bce4 100644 --- a/services/core/java/com/android/server/wm/TransitionController.java +++ b/services/core/java/com/android/server/wm/TransitionController.java @@ -46,6 +46,7 @@ import android.window.TransitionInfo; import android.window.TransitionRequestInfo; import com.android.internal.annotations.GuardedBy; +import com.android.internal.annotations.VisibleForTesting; import com.android.internal.protolog.ProtoLogGroup; import com.android.internal.protolog.common.ProtoLog; import com.android.server.LocalServices; @@ -64,6 +65,11 @@ class TransitionController { private static final boolean SHELL_TRANSITIONS_ROTATION = SystemProperties.getBoolean("persist.wm.debug.shell_transit_rotate", false); + /** Which sync method to use for transition syncs. */ + static final int SYNC_METHOD = + android.os.SystemProperties.getBoolean("persist.wm.debug.shell_transit_blast", true) + ? BLASTSyncEngine.METHOD_BLAST : BLASTSyncEngine.METHOD_NONE; + /** The same as legacy APP_TRANSITION_TIMEOUT_MS. */ private static final int DEFAULT_TIMEOUT_MS = 5000; /** Less duration for CHANGE type because it does not involve app startup. */ @@ -160,6 +166,12 @@ class TransitionController { /** Starts Collecting */ void moveToCollecting(@NonNull Transition transition) { + moveToCollecting(transition, SYNC_METHOD); + } + + /** Starts Collecting */ + @VisibleForTesting + void moveToCollecting(@NonNull Transition transition, int method) { if (mCollectingTransition != null) { throw new IllegalStateException("Simultaneous transition collection not supported."); } @@ -167,7 +179,7 @@ class TransitionController { // Distinguish change type because the response time is usually expected to be not too long. final long timeoutMs = transition.mType == TRANSIT_CHANGE ? CHANGE_TIMEOUT_MS : DEFAULT_TIMEOUT_MS; - mCollectingTransition.startCollecting(timeoutMs); + mCollectingTransition.startCollecting(timeoutMs, method); ProtoLog.v(ProtoLogGroup.WM_DEBUG_WINDOW_TRANSITIONS, "Start collecting in Transition: %s", mCollectingTransition); dispatchLegacyAppTransitionPending(); @@ -228,10 +240,7 @@ class TransitionController { */ boolean inCollectingTransition(@NonNull WindowContainer wc) { if (!isCollecting()) return false; - for (WindowContainer p = wc; p != null; p = p.getParent()) { - if (mCollectingTransition.mParticipants.contains(p)) return true; - } - return false; + return mCollectingTransition.isInTransition(wc); } /** @@ -247,9 +256,7 @@ class TransitionController { */ boolean inPlayingTransition(@NonNull WindowContainer wc) { for (int i = mPlayingTransitions.size() - 1; i >= 0; --i) { - for (WindowContainer p = wc; p != null; p = p.getParent()) { - if (mPlayingTransitions.get(i).mParticipants.contains(p)) return true; - } + if (mPlayingTransitions.get(i).isInTransition(wc)) return true; } return false; } @@ -469,6 +476,7 @@ class TransitionController { void collectForDisplayAreaChange(@NonNull DisplayArea<?> wc) { final Transition transition = mCollectingTransition; if (transition == null || !transition.mParticipants.contains(wc)) return; + transition.collectVisibleChange(wc); // Collect all visible tasks. wc.forAllLeafTasks(task -> { if (task.isVisible()) { @@ -488,6 +496,16 @@ class TransitionController { } } + /** + * Records that a particular container is changing visibly (ie. something about it is changing + * while it remains visible). This only effects windows that are already in the collecting + * transition. + */ + void collectVisibleChange(WindowContainer wc) { + if (!isCollecting()) return; + mCollectingTransition.collectVisibleChange(wc); + } + /** @see Transition#mStatusBarTransitionDelay */ void setStatusBarTransitionDelay(long delay) { if (mCollectingTransition == null) return; @@ -637,11 +655,9 @@ class TransitionController { } void dispatchLegacyAppTransitionStarting(TransitionInfo info, long statusBarTransitionDelay) { - final boolean keyguardGoingAway = info.isKeyguardGoingAway(); for (int i = 0; i < mLegacyListeners.size(); ++i) { // TODO(shell-transitions): handle (un)occlude transition. - mLegacyListeners.get(i).onAppTransitionStartingLocked(keyguardGoingAway, - false /* keyguardOcclude */, 0 /* durationHint */, + mLegacyListeners.get(i).onAppTransitionStartingLocked( SystemClock.uptimeMillis() + statusBarTransitionDelay, AnimationAdapter.STATUS_BAR_TRANSITION_DURATION); } @@ -656,7 +672,7 @@ class TransitionController { void dispatchLegacyAppTransitionCancelled() { for (int i = 0; i < mLegacyListeners.size(); ++i) { mLegacyListeners.get(i).onAppTransitionCancelledLocked( - false /* keyguardGoingAway */); + false /* keyguardGoingAwayCancelled */); } } diff --git a/services/core/java/com/android/server/wm/WindowContainer.java b/services/core/java/com/android/server/wm/WindowContainer.java index 73658b2dc301..d820ec44ebf6 100644 --- a/services/core/java/com/android/server/wm/WindowContainer.java +++ b/services/core/java/com/android/server/wm/WindowContainer.java @@ -343,6 +343,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer< BLASTSyncEngine.SyncGroup mSyncGroup = null; final SurfaceControl.Transaction mSyncTransaction; @SyncState int mSyncState = SYNC_STATE_NONE; + int mSyncMethodOverride = BLASTSyncEngine.METHOD_UNDEFINED; private final List<WindowContainerListener> mListeners = new ArrayList<>(); @@ -2829,6 +2830,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer< */ void initializeChangeTransition(Rect startBounds, @Nullable SurfaceControl freezeTarget) { if (mDisplayContent.mTransitionController.isShellTransitionsEnabled()) { + mDisplayContent.mTransitionController.collectVisibleChange(this); // TODO(b/207070762): request shell transition for activityEmbedding change. return; } @@ -3662,6 +3664,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer< boolean onSyncFinishedDrawing() { if (mSyncState == SYNC_STATE_NONE) return false; mSyncState = SYNC_STATE_READY; + mSyncMethodOverride = BLASTSyncEngine.METHOD_UNDEFINED; mWmService.mWindowPlacerLocked.requestTraversal(); ProtoLog.v(WM_DEBUG_SYNC_ENGINE, "onSyncFinishedDrawing %s", this); return true; @@ -3680,6 +3683,13 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer< mSyncGroup = group; } + @Nullable + BLASTSyncEngine.SyncGroup getSyncGroup() { + if (mSyncGroup != null) return mSyncGroup; + if (mParent != null) return mParent.getSyncGroup(); + return null; + } + /** * Prepares this container for participation in a sync-group. This includes preparing all its * children. @@ -3719,6 +3729,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer< } if (cancel && mSyncGroup != null) mSyncGroup.onCancelSync(this); mSyncState = SYNC_STATE_NONE; + mSyncMethodOverride = BLASTSyncEngine.METHOD_UNDEFINED; mSyncGroup = null; } @@ -3821,6 +3832,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer< // disable this when shell transitions is disabled. if (mTransitionController.isShellTransitionsEnabled()) { mSyncState = SYNC_STATE_NONE; + mSyncMethodOverride = BLASTSyncEngine.METHOD_UNDEFINED; } prepareSync(); } diff --git a/services/core/java/com/android/server/wm/WindowManagerInternal.java b/services/core/java/com/android/server/wm/WindowManagerInternal.java index a71c3866ba38..11475ac6150b 100644 --- a/services/core/java/com/android/server/wm/WindowManagerInternal.java +++ b/services/core/java/com/android/server/wm/WindowManagerInternal.java @@ -220,9 +220,10 @@ public abstract class WindowManagerInternal { /** * Called when a pending app transition gets cancelled. * - * @param keyguardGoingAway true if keyguard going away transition got cancelled. + * @param keyguardGoingAwayCancelled {@code true} if keyguard going away transition was + * cancelled. */ - public void onAppTransitionCancelledLocked(boolean keyguardGoingAway) {} + public void onAppTransitionCancelledLocked(boolean keyguardGoingAwayCancelled) {} /** * Called when an app transition is timed out. @@ -232,9 +233,6 @@ public abstract class WindowManagerInternal { /** * Called when an app transition gets started * - * @param keyguardGoingAway true if keyguard going away transition is started. - * @param keyguardOccluding true if keyguard (un)occlude transition is started. - * @param duration the total duration of the transition * @param statusBarAnimationStartTime the desired start time for all visual animations in * the status bar caused by this app transition in uptime millis * @param statusBarAnimationDuration the duration for all visual animations in the status @@ -245,8 +243,7 @@ public abstract class WindowManagerInternal { * {@link WindowManagerPolicy#FINISH_LAYOUT_REDO_WALLPAPER}, * or {@link WindowManagerPolicy#FINISH_LAYOUT_REDO_ANIM}. */ - public int onAppTransitionStartingLocked(boolean keyguardGoingAway, - boolean keyguardOccluding, long duration, long statusBarAnimationStartTime, + public int onAppTransitionStartingLocked(long statusBarAnimationStartTime, long statusBarAnimationDuration) { return 0; } diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java index 22411bb068a0..8025cb296b32 100644 --- a/services/core/java/com/android/server/wm/WindowManagerService.java +++ b/services/core/java/com/android/server/wm/WindowManagerService.java @@ -92,7 +92,6 @@ import static android.view.WindowManager.fixScale; import static android.view.WindowManagerGlobal.ADD_OKAY; import static android.view.WindowManagerGlobal.RELAYOUT_RES_CANCEL_AND_REDRAW; import static android.view.WindowManagerGlobal.RELAYOUT_RES_SURFACE_CHANGED; -import static android.view.WindowManagerPolicyConstants.NAV_BAR_INVALID; import static android.view.WindowManagerPolicyConstants.TYPE_LAYER_MULTIPLIER; import static android.view.displayhash.DisplayHashResultCallback.DISPLAY_HASH_ERROR_MISSING_WINDOW; import static android.view.displayhash.DisplayHashResultCallback.DISPLAY_HASH_ERROR_NOT_VISIBLE_ON_SCREEN; @@ -321,6 +320,7 @@ import com.android.server.policy.WindowManagerPolicy; import com.android.server.policy.WindowManagerPolicy.ScreenOffListener; import com.android.server.power.ShutdownThread; import com.android.server.utils.PriorityDump; +import com.android.server.wm.utils.WmDisplayCutout; import dalvik.annotation.optimization.NeverCompile; @@ -425,32 +425,6 @@ public class WindowManagerService extends IWindowManager.Stub SystemProperties.getBoolean(ENABLE_SHELL_TRANSITIONS, false); /** - * Run Keyguard animation as remote animation in System UI instead of local animation in - * the server process. - * - * 0: Runs all keyguard animation as local animation - * 1: Only runs keyguard going away animation as remote animation - * 2: Runs all keyguard animation as remote animation - */ - private static final String ENABLE_REMOTE_KEYGUARD_ANIMATION_PROPERTY = - "persist.wm.enable_remote_keyguard_animation"; - - private static final int sEnableRemoteKeyguardAnimation = - SystemProperties.getInt(ENABLE_REMOTE_KEYGUARD_ANIMATION_PROPERTY, 2); - - /** - * @see #ENABLE_REMOTE_KEYGUARD_ANIMATION_PROPERTY - */ - public static final boolean sEnableRemoteKeyguardGoingAwayAnimation = - sEnableRemoteKeyguardAnimation >= 1; - - /** - * @see #ENABLE_REMOTE_KEYGUARD_ANIMATION_PROPERTY - */ - public static final boolean sEnableRemoteKeyguardOccludeAnimation = - sEnableRemoteKeyguardAnimation >= 2; - - /** * Allows a fullscreen windowing mode activity to launch in its desired orientation directly * when the display has different orientation. */ @@ -1118,7 +1092,7 @@ public class WindowManagerService extends IWindowManager.Stub = new WindowManagerInternal.AppTransitionListener() { @Override - public void onAppTransitionCancelledLocked(boolean keyguardGoingAway) { + public void onAppTransitionCancelledLocked(boolean keyguardGoingAwayCancelled) { } @Override @@ -1873,7 +1847,8 @@ public class WindowManagerService extends IWindowManager.Stub ProtoLog.v(WM_DEBUG_ADD_REMOVE, "addWindow: New client %s" + ": window=%s Callers=%s", client.asBinder(), win, Debug.getCallers(5)); - if (win.isVisibleRequestedOrAdding() && displayContent.updateOrientation()) { + if ((win.isVisibleRequestedOrAdding() && displayContent.updateOrientation()) + || win.providesNonDecorInsets()) { displayContent.sendNewConfiguration(); } @@ -2583,7 +2558,7 @@ public class WindowManagerService extends IWindowManager.Stub final int maybeSyncSeqId; if (USE_BLAST_SYNC && win.useBLASTSync() && viewVisibility != View.GONE && win.mSyncSeqId > lastSyncSeqId) { - maybeSyncSeqId = win.mSyncSeqId; + maybeSyncSeqId = win.shouldSyncWithBuffers() ? win.mSyncSeqId : -1; win.markRedrawForSyncReported(); } else { maybeSyncSeqId = -1; @@ -6384,27 +6359,6 @@ public class WindowManagerService extends IWindowManager.Stub } } - /** - * Used by ActivityManager to determine where to position an app with aspect ratio shorter then - * the screen is. - * @see DisplayPolicy#getNavBarPosition() - */ - @Override - @WindowManagerPolicy.NavigationBarPosition - public int getNavBarPosition(int displayId) { - synchronized (mGlobalLock) { - // Perform layout if it was scheduled before to make sure that we get correct nav bar - // position when doing rotations. - final DisplayContent displayContent = mRoot.getDisplayContent(displayId); - if (displayContent == null) { - Slog.w(TAG, "getNavBarPosition with invalid displayId=" + displayId - + " callers=" + Debug.getCallers(3)); - return NAV_BAR_INVALID; - } - return displayContent.getDisplayPolicy().getNavBarPosition(); - } - } - @Override public void createInputConsumer(IBinder token, String name, int displayId, InputChannel inputChannel) { @@ -7242,7 +7196,9 @@ public class WindowManagerService extends IWindowManager.Stub final DisplayContent dc = mRoot.getDisplayContent(displayId); if (dc != null) { final DisplayInfo di = dc.getDisplayInfo(); - dc.getDisplayPolicy().getStableInsetsLw(di.rotation, di.displayCutout, outInsets); + final WmDisplayCutout cutout = dc.calculateDisplayCutoutForRotation(di.rotation); + dc.getDisplayPolicy().getStableInsetsLw(di.rotation, di.logicalWidth, di.logicalHeight, + cutout, outInsets); } } diff --git a/services/core/java/com/android/server/wm/WindowOrganizerController.java b/services/core/java/com/android/server/wm/WindowOrganizerController.java index 4f03264b1556..f83925507512 100644 --- a/services/core/java/com/android/server/wm/WindowOrganizerController.java +++ b/services/core/java/com/android/server/wm/WindowOrganizerController.java @@ -147,7 +147,7 @@ class WindowOrganizerController extends IWindowOrganizerController.Stub mGlobalLock = atm.mGlobalLock; mTaskOrganizerController = new TaskOrganizerController(mService); mDisplayAreaOrganizerController = new DisplayAreaOrganizerController(mService); - mTaskFragmentOrganizerController = new TaskFragmentOrganizerController(atm); + mTaskFragmentOrganizerController = new TaskFragmentOrganizerController(atm, this); } void setWindowManager(WindowManagerService wms) { @@ -1405,7 +1405,7 @@ class WindowOrganizerController extends IWindowOrganizerController.Stub private BLASTSyncEngine.SyncGroup prepareSyncWithOrganizer( IWindowContainerTransactionCallback callback) { final BLASTSyncEngine.SyncGroup s = mService.mWindowManager.mSyncEngine - .prepareSyncSet(this, ""); + .prepareSyncSet(this, "", BLASTSyncEngine.METHOD_BLAST); mTransactionCallbacksByPendingSyncId.put(s.mSyncId, callback); return s; } diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java index d2b9bda7d742..346930311068 100644 --- a/services/core/java/com/android/server/wm/WindowState.java +++ b/services/core/java/com/android/server/wm/WindowState.java @@ -242,6 +242,7 @@ import android.view.View; import android.view.ViewDebug; import android.view.ViewTreeObserver; import android.view.WindowInfo; +import android.view.WindowInsets; import android.view.WindowInsets.Type.InsetsType; import android.view.WindowManager; import android.view.animation.Animation; @@ -390,7 +391,7 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP */ int mSyncSeqId = 0; - /** The last syncId associated with a prepareSync or 0 when no sync is active. */ + /** The last syncId associated with a BLAST prepareSync or 0 when no BLAST sync is active. */ int mPrepareSyncSeqId = 0; /** @@ -1896,6 +1897,19 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP return (mPolicyVisibility & POLICY_VISIBILITY_ALL) == POLICY_VISIBILITY_ALL; } + boolean providesNonDecorInsets() { + if (mProvidedInsetsSources == null) { + return false; + } + for (int i = mProvidedInsetsSources.size() - 1; i >= 0; i--) { + final int type = mProvidedInsetsSources.keyAt(i); + if ((InsetsState.toPublicType(type) & WindowInsets.Type.navigationBars()) != 0) { + return true; + } + } + return false; + } + void clearPolicyVisibilityFlag(int policyVisibilityFlag) { mPolicyVisibility &= ~policyVisibilityFlag; mWmService.scheduleAnimationLocked(); @@ -2608,14 +2622,19 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP } removeImmediately(); - // Removing a visible window will effect the computed orientation - // So just update orientation if needed. + boolean sentNewConfig = false; if (wasVisible) { + // Removing a visible window will effect the computed orientation + // So just update orientation if needed. final DisplayContent displayContent = getDisplayContent(); if (displayContent.updateOrientation()) { displayContent.sendNewConfiguration(); + sentNewConfig = true; } } + if (!sentNewConfig && providesNonDecorInsets()) { + getDisplayContent().sendNewConfiguration(); + } mWmService.updateFocusedWindowLocked(isFocused() ? UPDATE_FOCUS_REMOVING_FOCUS : UPDATE_FOCUS_NORMAL, @@ -3892,9 +3911,10 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP fillClientWindowFramesAndConfiguration(mClientWindowFrames, mLastReportedConfiguration, true /* useLatestConfig */, false /* relayoutVisible */); final boolean syncRedraw = shouldSendRedrawForSync(); + final boolean syncWithBuffers = syncRedraw && shouldSyncWithBuffers(); final boolean reportDraw = syncRedraw || drawPending; final boolean isDragResizeChanged = isDragResizeChanged(); - final boolean forceRelayout = syncRedraw || isDragResizeChanged; + final boolean forceRelayout = syncWithBuffers || isDragResizeChanged; final DisplayContent displayContent = getDisplayContent(); final boolean alwaysConsumeSystemBars = displayContent.getDisplayPolicy().areSystemBarsForcedShownLw(); @@ -3920,7 +3940,7 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP try { mClient.resized(mClientWindowFrames, reportDraw, mLastReportedConfiguration, getCompatInsetsState(), forceRelayout, alwaysConsumeSystemBars, displayId, - mSyncSeqId, resizeMode); + syncWithBuffers ? mSyncSeqId : -1, resizeMode); if (drawPending && prevRotation >= 0 && prevRotation != mLastReportedConfiguration .getMergedConfiguration().windowConfiguration.getRotation()) { mOrientationChangeRedrawRequestTime = SystemClock.elapsedRealtime(); @@ -5924,7 +5944,9 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP } mSyncSeqId++; - mPrepareSyncSeqId = mSyncSeqId; + if (getSyncMethod() == BLASTSyncEngine.METHOD_BLAST) { + mPrepareSyncSeqId = mSyncSeqId; + } requestRedrawForSync(); return true; } @@ -5997,6 +6019,7 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP postDrawTransaction = null; skipLayout = true; } else if (syncActive) { + // Currently in a Sync that is using BLAST. if (!syncStillPending) { onSyncFinishedDrawing(); } @@ -6005,6 +6028,9 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP // Consume the transaction because the sync group will merge it. postDrawTransaction = null; } + } else if (useBLASTSync()) { + // Sync that is not using BLAST + onSyncFinishedDrawing(); } final boolean layoutNeeded = @@ -6063,6 +6089,18 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP return useBLASTSync(); } + int getSyncMethod() { + final BLASTSyncEngine.SyncGroup syncGroup = getSyncGroup(); + if (syncGroup == null) return BLASTSyncEngine.METHOD_NONE; + if (mSyncMethodOverride != BLASTSyncEngine.METHOD_UNDEFINED) return mSyncMethodOverride; + return syncGroup.mSyncMethod; + } + + boolean shouldSyncWithBuffers() { + if (!mDrawHandlers.isEmpty()) return true; + return getSyncMethod() == BLASTSyncEngine.METHOD_BLAST; + } + void requestRedrawForSync() { mRedrawForSyncReported = false; } diff --git a/services/core/jni/OWNERS b/services/core/jni/OWNERS index 85671105ec25..9abf107c780a 100644 --- a/services/core/jni/OWNERS +++ b/services/core/jni/OWNERS @@ -11,7 +11,7 @@ per-file com_android_server_power_PowerManagerService.* = michaelwr@google.com, # BatteryStats per-file com_android_server_am_BatteryStatsService.cpp = file:/BATTERY_STATS_OWNERS -per-file Android.bp = file:platform/build/soong:/OWNERS +per-file Android.bp = file:platform/build/soong:/OWNERS #{LAST_RESORT_SUGGESTION} per-file com_android_server_Usb* = file:/services/usb/OWNERS per-file com_android_server_Vibrator* = file:/services/core/java/com/android/server/vibrator/OWNERS per-file com_android_server_hdmi_* = file:/core/java/android/hardware/hdmi/OWNERS diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyData.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyData.java index 054181dfa728..0305c35b1828 100644 --- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyData.java +++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyData.java @@ -671,6 +671,21 @@ class DevicePolicyData { if (mFactoryResetReason != null) { pw.print("mFactoryResetReason="); pw.println(mFactoryResetReason); } + if (mDelegationMap.size() != 0) { + pw.println("mDelegationMap="); + pw.increaseIndent(); + for (int i = 0; i < mDelegationMap.size(); i++) { + List<String> delegationScopes = mDelegationMap.valueAt(i); + pw.println(mDelegationMap.keyAt(i) + "[size=" + delegationScopes.size() + + "]"); + pw.increaseIndent(); + for (int j = 0; j < delegationScopes.size(); j++) { + pw.println(j + ": " + delegationScopes.get(j)); + } + pw.decreaseIndent(); + } + pw.decreaseIndent(); + } pw.decreaseIndent(); } diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java index 0018a523a34a..fbaf1ce25b85 100644 --- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java +++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java @@ -5786,29 +5786,8 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager { @VisibleForTesting public void enforceCallerCanRequestDeviceIdAttestation(CallerIdentity caller) throws SecurityException { - /** - * First check if there's a profile owner because the device could be in COMP mode (where - * there's a device owner and profile owner on the same device). - * If the caller is from the work profile, then it must be the PO or the delegate, and - * it must have the right permission to access device identifiers. - */ - int callerUserId = caller.getUserId(); - if (hasProfileOwner(callerUserId)) { - // Make sure that the caller is the profile owner or delegate. - Preconditions.checkCallAuthorization(canInstallCertificates(caller)); - // Verify that the managed profile is on an organization-owned device (or is affiliated - // with the device owner user) and as such the profile owner can access Device IDs. - if (isProfileOwnerOfOrganizationOwnedDevice(callerUserId) - || isUserAffiliatedWithDevice(callerUserId)) { - return; - } - throw new SecurityException( - "Profile Owner is not allowed to access Device IDs."); - } - - // If not, fall back to the device owner check. - Preconditions.checkCallAuthorization( - isDefaultDeviceOwner(caller) || isCallerDelegate(caller, DELEGATION_CERT_INSTALL)); + Preconditions.checkCallAuthorization(hasDeviceIdAccessUnchecked(caller.getPackageName(), + caller.getUid())); } @VisibleForTesting @@ -5856,7 +5835,6 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager { final boolean deviceIdAttestationRequired = attestationUtilsFlags != null; KeyGenParameterSpec keySpec = parcelableKeySpec.getSpec(); final String alias = keySpec.getKeystoreAlias(); - Preconditions.checkStringNotEmpty(alias, "Empty alias provided"); Preconditions.checkArgument( !deviceIdAttestationRequired || keySpec.getAttestationChallenge() != null, @@ -8166,7 +8144,8 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager { } final CallerIdentity caller = getCallerIdentity(who); - Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)); + Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle) + || isCameraServerUid(caller)); if (parent) { Preconditions.checkCallAuthorization( @@ -9393,26 +9372,33 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager { if (!hasPermission(permission.READ_PHONE_STATE, pid, uid)) { return false; } + return hasDeviceIdAccessUnchecked(packageName, uid); + } - // Allow access to the device owner or delegate cert installer or profile owner of an - // affiliated user + /** + * Check if caller is device owner, delegate cert installer or profile owner of + * affiliated user. Or if caller is profile owner for a specified user or delegate cert + * installer on an organization-owned device. + */ + private boolean hasDeviceIdAccessUnchecked(String packageName, int uid) { + // Is the caller a device owner, delegate cert installer or profile owner of an + // affiliated user. ComponentName deviceOwner = getDeviceOwnerComponent(true); if (deviceOwner != null && (deviceOwner.getPackageName().equals(packageName) || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL))) { return true; } final int userId = UserHandle.getUserId(uid); - // Allow access to the profile owner for the specified user, or delegate cert installer - // But only if this is an organization-owned device. + // Is the caller the profile owner for the specified user, or delegate cert installer on an + // organization-owned device. ComponentName profileOwner = getProfileOwnerAsUser(userId); final boolean isCallerProfileOwnerOrDelegate = profileOwner != null && (profileOwner.getPackageName().equals(packageName) - || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL)); + || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL)); if (isCallerProfileOwnerOrDelegate && (isProfileOwnerOfOrganizationOwnedDevice(userId) || isUserAffiliatedWithDevice(userId))) { return true; } - return false; } @@ -9681,6 +9667,10 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager { return UserHandle.isSameApp(caller.getUid(), Process.SHELL_UID); } + private boolean isCameraServerUid(CallerIdentity caller) { + return UserHandle.isSameApp(caller.getUid(), Process.CAMERASERVER_UID); + } + private @UserIdInt int getCurrentForegroundUserId() { try { UserInfo currentUser = mInjector.getIActivityManager().getCurrentUser(); diff --git a/services/tests/mockingservicestests/src/com/android/server/job/controllers/BatteryControllerTest.java b/services/tests/mockingservicestests/src/com/android/server/job/controllers/BatteryControllerTest.java index 4a631a1251d5..59cb43f16ef6 100644 --- a/services/tests/mockingservicestests/src/com/android/server/job/controllers/BatteryControllerTest.java +++ b/services/tests/mockingservicestests/src/com/android/server/job/controllers/BatteryControllerTest.java @@ -33,6 +33,7 @@ import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; +import android.content.pm.PackageManager; import android.content.pm.PackageManagerInternal; import android.os.BatteryManagerInternal; import android.os.RemoteException; @@ -75,6 +76,8 @@ public class BatteryControllerTest { private JobSchedulerService mJobSchedulerService; @Mock private PackageManagerInternal mPackageManagerInternal; + @Mock + private PackageManager mPackageManager; @Before public void setUp() { @@ -100,6 +103,9 @@ public class BatteryControllerTest { ArgumentCaptor<BroadcastReceiver> receiverCaptor = ArgumentCaptor.forClass(BroadcastReceiver.class); + when(mContext.getPackageManager()).thenReturn(mPackageManager); + when(mPackageManager.hasSystemFeature( + PackageManager.FEATURE_AUTOMOTIVE)).thenReturn(false); mFlexibilityController = new FlexibilityController(mJobSchedulerService, mock(PrefetchController.class)); mBatteryController = new BatteryController(mJobSchedulerService, mFlexibilityController); diff --git a/services/tests/mockingservicestests/src/com/android/server/job/controllers/ConnectivityControllerTest.java b/services/tests/mockingservicestests/src/com/android/server/job/controllers/ConnectivityControllerTest.java index 953a72d5085c..1f85f2c2c46e 100644 --- a/services/tests/mockingservicestests/src/com/android/server/job/controllers/ConnectivityControllerTest.java +++ b/services/tests/mockingservicestests/src/com/android/server/job/controllers/ConnectivityControllerTest.java @@ -51,6 +51,7 @@ import android.annotation.Nullable; import android.app.job.JobInfo; import android.content.ComponentName; import android.content.Context; +import android.content.pm.PackageManager; import android.content.pm.PackageManagerInternal; import android.net.ConnectivityManager; import android.net.ConnectivityManager.NetworkCallback; @@ -96,6 +97,8 @@ public class ConnectivityControllerTest { private NetworkPolicyManagerInternal mNetPolicyManagerInternal; @Mock private JobSchedulerService mService; + @Mock + private PackageManager mPackageManager; private Constants mConstants; @@ -115,10 +118,6 @@ public class ConnectivityControllerTest { LocalServices.removeServiceForTest(NetworkPolicyManagerInternal.class); LocalServices.addService(NetworkPolicyManagerInternal.class, mNetPolicyManagerInternal); - when(mContext.getMainLooper()).thenReturn(Looper.getMainLooper()); - mFlexibilityController = - new FlexibilityController(mService, mock(PrefetchController.class)); - // Freeze the clocks at this moment in time JobSchedulerService.sSystemClock = Clock.fixed(Clock.systemUTC().instant(), ZoneOffset.UTC); @@ -142,6 +141,13 @@ public class ConnectivityControllerTest { when(mService.getTestableContext()).thenReturn(mContext); when(mService.getLock()).thenReturn(mService); when(mService.getConstants()).thenReturn(mConstants); + // Instantiate Flexibility Controller + when(mContext.getMainLooper()).thenReturn(Looper.getMainLooper()); + when(mContext.getPackageManager()).thenReturn(mPackageManager); + when(mPackageManager.hasSystemFeature( + PackageManager.FEATURE_AUTOMOTIVE)).thenReturn(false); + mFlexibilityController = + new FlexibilityController(mService, mock(PrefetchController.class)); } @Test diff --git a/services/tests/mockingservicestests/src/com/android/server/job/controllers/FlexibilityControllerTest.java b/services/tests/mockingservicestests/src/com/android/server/job/controllers/FlexibilityControllerTest.java index 9d039bd09a2f..0eb0a002fe6e 100644 --- a/services/tests/mockingservicestests/src/com/android/server/job/controllers/FlexibilityControllerTest.java +++ b/services/tests/mockingservicestests/src/com/android/server/job/controllers/FlexibilityControllerTest.java @@ -29,10 +29,12 @@ import static com.android.server.job.controllers.FlexibilityController.FcConfig. import static com.android.server.job.controllers.FlexibilityController.FcConfig.KEY_FALLBACK_FLEXIBILITY_DEADLINE; import static com.android.server.job.controllers.FlexibilityController.FcConfig.KEY_FLEXIBILITY_ENABLED; import static com.android.server.job.controllers.FlexibilityController.FcConfig.KEY_PERCENTS_TO_DROP_NUM_FLEXIBLE_CONSTRAINTS; +import static com.android.server.job.controllers.FlexibilityController.NUM_FLEXIBLE_CONSTRAINTS; import static com.android.server.job.controllers.JobStatus.CONSTRAINT_BATTERY_NOT_LOW; import static com.android.server.job.controllers.JobStatus.CONSTRAINT_CHARGING; import static com.android.server.job.controllers.JobStatus.CONSTRAINT_FLEXIBLE; import static com.android.server.job.controllers.JobStatus.CONSTRAINT_IDLE; +import static com.android.server.job.controllers.JobStatus.NO_LATEST_RUNTIME; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -48,6 +50,7 @@ import android.app.AlarmManager; import android.app.job.JobInfo; import android.content.ComponentName; import android.content.Context; +import android.content.pm.PackageManager; import android.content.pm.PackageManagerInternal; import android.os.Looper; import android.provider.DeviceConfig; @@ -90,6 +93,8 @@ public class FlexibilityControllerTest { private JobSchedulerService mJobSchedulerService; @Mock private PrefetchController mPrefetchController; + @Mock + private PackageManager mPackageManager; @Before public void setup() { @@ -107,6 +112,9 @@ public class FlexibilityControllerTest { // Called in FlexibilityController constructor. when(mContext.getMainLooper()).thenReturn(Looper.getMainLooper()); when(mContext.getSystemService(Context.ALARM_SERVICE)).thenReturn(mAlarmManager); + when(mContext.getPackageManager()).thenReturn(mPackageManager); + when(mPackageManager.hasSystemFeature( + PackageManager.FEATURE_AUTOMOTIVE)).thenReturn(false); // Used in FlexibilityController.FcConstants. doAnswer((Answer<Void>) invocationOnMock -> null) .when(() -> DeviceConfig.addOnPropertiesChangedListener( @@ -190,7 +198,7 @@ public class FlexibilityControllerTest { */ @Test public void testDefaultVariableValues() { - assertEquals(FlexibilityController.NUM_FLEXIBLE_CONSTRAINTS, + assertEquals(NUM_FLEXIBLE_CONSTRAINTS, mFlexibilityController.mFcConfig.DEFAULT_PERCENT_TO_DROP_FLEXIBLE_CONSTRAINTS.length ); } @@ -390,7 +398,7 @@ public class FlexibilityControllerTest { } @Test - public void testGetLifeCycleBeginningElapsedLocked_prefetch() { + public void testGetLifeCycleBeginningElapsedLocked_Prefetch() { // prefetch with lifecycle when(mPrefetchController.getLaunchTimeThresholdMs()).thenReturn(700L); JobInfo.Builder jb = createJob(0).setPrefetch(true); @@ -417,7 +425,7 @@ public class FlexibilityControllerTest { } @Test - public void testGetLifeCycleBeginningElapsedLocked_nonPrefetch() { + public void testGetLifeCycleBeginningElapsedLocked_NonPrefetch() { // delay long delay = 100; JobInfo.Builder jb = createJob(0).setMinimumLatency(delay); @@ -432,7 +440,7 @@ public class FlexibilityControllerTest { } @Test - public void testGetLifeCycleEndElapsedLocked_prefetch() { + public void testGetLifeCycleEndElapsedLocked_Prefetch() { // prefetch no estimate JobInfo.Builder jb = createJob(0).setPrefetch(true); JobStatus js = createJobStatus("time", jb); @@ -444,8 +452,9 @@ public class FlexibilityControllerTest { when(mPrefetchController.getNextEstimatedLaunchTimeLocked(js)).thenReturn(1000L); assertEquals(1000L, mFlexibilityController.getLifeCycleEndElapsedLocked(js, 0)); } + @Test - public void testGetLifeCycleEndElapsedLocked_nonPrefetch() { + public void testGetLifeCycleEndElapsedLocked_NonPrefetch() { // deadline JobInfo.Builder jb = createJob(0).setOverrideDeadline(1000L); JobStatus js = createJobStatus("time", jb); @@ -459,6 +468,28 @@ public class FlexibilityControllerTest { } @Test + public void testGetLifeCycleEndElapsedLocked_Rescheduled() { + JobInfo.Builder jb = createJob(0).setOverrideDeadline(1000L); + JobStatus js = createJobStatus("time", jb); + js = new JobStatus( + js, FROZEN_TIME, NO_LATEST_RUNTIME, /* numFailures */ 2, FROZEN_TIME, FROZEN_TIME); + + assertEquals(mFcConfig.RESCHEDULED_JOB_DEADLINE_MS, + mFlexibilityController.getLifeCycleEndElapsedLocked(js, 0)); + + js = new JobStatus( + js, FROZEN_TIME, NO_LATEST_RUNTIME, /* numFailures */ 3, FROZEN_TIME, FROZEN_TIME); + + assertEquals(2 * mFcConfig.RESCHEDULED_JOB_DEADLINE_MS, + mFlexibilityController.getLifeCycleEndElapsedLocked(js, 0)); + + js = new JobStatus( + js, FROZEN_TIME, NO_LATEST_RUNTIME, /* numFailures */ 10, FROZEN_TIME, FROZEN_TIME); + assertEquals(mFcConfig.MAX_RESCHEDULED_DEADLINE_MS, + mFlexibilityController.getLifeCycleEndElapsedLocked(js, 0)); + } + + @Test public void testWontStopJobFromRunning() { JobStatus js = createJobStatus("testWontStopJobFromRunning", createJob(101)); // Stop satisfied constraints from causing a false positive. @@ -473,9 +504,9 @@ public class FlexibilityControllerTest { public void testFlexibilityTracker() { FlexibilityController.FlexibilityTracker flexTracker = mFlexibilityController.new - FlexibilityTracker(FlexibilityController.NUM_FLEXIBLE_CONSTRAINTS); - - assertEquals(4, flexTracker.size()); + FlexibilityTracker(NUM_FLEXIBLE_CONSTRAINTS); + // Plus one for jobs with 0 required constraint. + assertEquals(NUM_FLEXIBLE_CONSTRAINTS + 1, flexTracker.size()); JobStatus[] jobs = new JobStatus[4]; JobInfo.Builder jb; for (int i = 0; i < jobs.length; i++) { @@ -495,47 +526,53 @@ public class FlexibilityControllerTest { synchronized (mFlexibilityController.mLock) { ArrayList<ArraySet<JobStatus>> trackedJobs = flexTracker.getArrayList(); - assertEquals(0, trackedJobs.get(0).size()); + assertEquals(1, trackedJobs.get(0).size()); assertEquals(0, trackedJobs.get(1).size()); - assertEquals(3, trackedJobs.get(2).size()); - assertEquals(0, trackedJobs.get(3).size()); + assertEquals(0, trackedJobs.get(2).size()); + assertEquals(3, trackedJobs.get(3).size()); + assertEquals(0, trackedJobs.get(4).size()); flexTracker.adjustJobsRequiredConstraints(jobs[0], -1, FROZEN_TIME); - assertEquals(0, trackedJobs.get(0).size()); - assertEquals(1, trackedJobs.get(1).size()); - assertEquals(2, trackedJobs.get(2).size()); - assertEquals(0, trackedJobs.get(3).size()); + assertEquals(1, trackedJobs.get(0).size()); + assertEquals(0, trackedJobs.get(1).size()); + assertEquals(1, trackedJobs.get(2).size()); + assertEquals(2, trackedJobs.get(3).size()); + assertEquals(0, trackedJobs.get(4).size()); flexTracker.adjustJobsRequiredConstraints(jobs[0], -1, FROZEN_TIME); assertEquals(1, trackedJobs.get(0).size()); - assertEquals(0, trackedJobs.get(1).size()); - assertEquals(2, trackedJobs.get(2).size()); - assertEquals(0, trackedJobs.get(3).size()); + assertEquals(1, trackedJobs.get(1).size()); + assertEquals(0, trackedJobs.get(2).size()); + assertEquals(2, trackedJobs.get(3).size()); + assertEquals(0, trackedJobs.get(4).size()); flexTracker.adjustJobsRequiredConstraints(jobs[0], -1, FROZEN_TIME); - assertEquals(0, trackedJobs.get(0).size()); + assertEquals(2, trackedJobs.get(0).size()); assertEquals(0, trackedJobs.get(1).size()); - assertEquals(2, trackedJobs.get(2).size()); - assertEquals(0, trackedJobs.get(3).size()); + assertEquals(0, trackedJobs.get(2).size()); + assertEquals(2, trackedJobs.get(3).size()); + assertEquals(0, trackedJobs.get(4).size()); flexTracker.remove(jobs[1]); - assertEquals(0, trackedJobs.get(0).size()); + assertEquals(2, trackedJobs.get(0).size()); assertEquals(0, trackedJobs.get(1).size()); - assertEquals(1, trackedJobs.get(2).size()); - assertEquals(0, trackedJobs.get(3).size()); + assertEquals(0, trackedJobs.get(2).size()); + assertEquals(1, trackedJobs.get(3).size()); + assertEquals(0, trackedJobs.get(4).size()); flexTracker.resetJobNumDroppedConstraints(jobs[0], FROZEN_TIME); - assertEquals(0, trackedJobs.get(0).size()); + assertEquals(2, trackedJobs.get(0).size()); assertEquals(0, trackedJobs.get(1).size()); - assertEquals(2, trackedJobs.get(2).size()); - assertEquals(0, trackedJobs.get(3).size()); + assertEquals(0, trackedJobs.get(2).size()); + assertEquals(2, trackedJobs.get(3).size()); + assertEquals(0, trackedJobs.get(4).size()); flexTracker.adjustJobsRequiredConstraints(jobs[0], -2, FROZEN_TIME); - - assertEquals(1, trackedJobs.get(0).size()); - assertEquals(0, trackedJobs.get(1).size()); - assertEquals(1, trackedJobs.get(2).size()); - assertEquals(0, trackedJobs.get(3).size()); + assertEquals(2, trackedJobs.get(0).size()); + assertEquals(1, trackedJobs.get(1).size()); + assertEquals(0, trackedJobs.get(2).size()); + assertEquals(1, trackedJobs.get(3).size()); + assertEquals(0, trackedJobs.get(4).size()); final long nowElapsed = ((DEFAULT_FALLBACK_FLEXIBILITY_DEADLINE_MS / 2) + HOUR_IN_MILLIS); @@ -543,10 +580,11 @@ public class FlexibilityControllerTest { Clock.fixed(Instant.ofEpochMilli(nowElapsed), ZoneOffset.UTC); flexTracker.resetJobNumDroppedConstraints(jobs[0], nowElapsed); - assertEquals(0, trackedJobs.get(0).size()); - assertEquals(1, trackedJobs.get(1).size()); + assertEquals(2, trackedJobs.get(0).size()); + assertEquals(0, trackedJobs.get(1).size()); assertEquals(1, trackedJobs.get(2).size()); - assertEquals(0, trackedJobs.get(3).size()); + assertEquals(1, trackedJobs.get(3).size()); + assertEquals(0, trackedJobs.get(4).size()); } } @@ -578,6 +616,15 @@ public class FlexibilityControllerTest { } @Test + public void testExceptions_RescheduledOnce() { + JobInfo.Builder jb = createJob(0); + JobStatus js = createJobStatus("time", jb); + js = new JobStatus( + js, FROZEN_TIME, NO_LATEST_RUNTIME, /* numFailures */ 1, FROZEN_TIME, FROZEN_TIME); + assertFalse(js.hasFlexibilityConstraint()); + } + + @Test public void testExceptions_None() { JobInfo.Builder jb = createJob(0); JobStatus js = createJobStatus("testExceptions_None", jb); @@ -818,6 +865,29 @@ public class FlexibilityControllerTest { } + @Test + public void testDeviceDisabledFlexibility_Auto() { + when(mPackageManager.hasSystemFeature( + PackageManager.FEATURE_AUTOMOTIVE)).thenReturn(true); + mFlexibilityController = + new FlexibilityController(mJobSchedulerService, mPrefetchController); + assertFalse(mFlexibilityController.mFlexibilityEnabled); + + JobStatus js = createJobStatus("testIsAuto", createJob(0)); + + mFlexibilityController.maybeStartTrackingJobLocked(js, null); + assertTrue(js.isConstraintSatisfied(CONSTRAINT_FLEXIBLE)); + + setDeviceConfigBoolean(KEY_FLEXIBILITY_ENABLED, true); + assertFalse(mFlexibilityController.mFlexibilityEnabled); + + ArrayList<ArraySet<JobStatus>> jobs = + mFlexibilityController.mFlexibilityTracker.getArrayList(); + for (int i = 0; i < jobs.size(); i++) { + assertEquals(0, jobs.get(i).size()); + } + } + private void setUidBias(int uid, int bias) { int prevBias = mJobSchedulerService.getUidBias(uid); doReturn(bias).when(mJobSchedulerService).getUidBias(uid); diff --git a/services/tests/servicestests/src/com/android/server/backup/BackupManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/backup/BackupManagerServiceTest.java index 3de006cea15f..81e06649ebc4 100644 --- a/services/tests/servicestests/src/com/android/server/backup/BackupManagerServiceTest.java +++ b/services/tests/servicestests/src/com/android/server/backup/BackupManagerServiceTest.java @@ -507,7 +507,7 @@ public class BackupManagerServiceTest { } @Test - public void dump_callerDoesNotHavePermission_ignored() { + public void dump_callerDoesNotHaveDumpPermission_ignored() { when(mContextMock.checkCallingOrSelfPermission( android.Manifest.permission.DUMP)).thenReturn( PackageManager.PERMISSION_DENIED); @@ -518,6 +518,18 @@ public class BackupManagerServiceTest { verifyNoMoreInteractions(mNonSystemUserBackupManagerService); } + @Test + public void dump_callerDoesNotHavePackageUsageStatsPermission_ignored() { + when(mContextMock.checkCallingOrSelfPermission( + Manifest.permission.PACKAGE_USAGE_STATS)).thenReturn( + PackageManager.PERMISSION_DENIED); + + mService.dump(mFileDescriptorStub, mPrintWriterMock, new String[0]); + + verifyNoMoreInteractions(mUserBackupManagerService); + verifyNoMoreInteractions(mNonSystemUserBackupManagerService); + } + /** * Test that {@link BackupManagerService#dump()} dumps system user information before non-system * user information. diff --git a/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/BiometricStateCallbackTest.java b/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/BiometricStateCallbackTest.java index 0e30782eaece..3b66eaba6129 100644 --- a/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/BiometricStateCallbackTest.java +++ b/services/tests/servicestests/src/com/android/server/biometrics/sensors/fingerprint/BiometricStateCallbackTest.java @@ -80,6 +80,8 @@ public class BiometricStateCallbackTest { when(mFakeProvider.hasEnrollments(eq(SENSOR_ID), eq(USER_ID))).thenReturn(true); when(mUserManager.getAliveUsers()).thenReturn( List.of(new UserInfo(USER_ID, "name", 0))); + when(mBiometricStateListener.asBinder()).thenReturn(mBiometricStateListener); + mCallback = new BiometricStateCallback<>(mUserManager); mCallback.registerBiometricStateListener(mBiometricStateListener); @@ -110,6 +112,14 @@ public class BiometricStateCallbackTest { false /* expectCallback */, false /* expectedCallbackValue */); } + @Test + public void testBinderDeath() { + mCallback.binderDied(mBiometricStateListener.asBinder()); + + testEnrollmentCallback(true /* changed */, false /* isNowEnrolled */, + false /* expectCallback */, false /* expectedCallbackValue */); + } + private void testEnrollmentCallback(boolean changed, boolean isNowEnrolled, boolean expectCallback, boolean expectedCallbackValue) { EnrollClient<?> client = mock(EnrollClient.class); diff --git a/services/tests/servicestests/src/com/android/server/vibrator/VibrationThreadTest.java b/services/tests/servicestests/src/com/android/server/vibrator/VibrationThreadTest.java index ca162efe0f6e..efc240d3f172 100644 --- a/services/tests/servicestests/src/com/android/server/vibrator/VibrationThreadTest.java +++ b/services/tests/servicestests/src/com/android/server/vibrator/VibrationThreadTest.java @@ -574,7 +574,7 @@ public class VibrationThreadTest { } @Test - public void vibrate_singleVibratorComposedAndNoCapability_ignoresVibration() throws Exception { + public void vibrate_singleVibratorComposedAndNoCapability_ignoresVibration() { long vibrationId = 1; VibrationEffect effect = VibrationEffect.startComposition() .addPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 1f) @@ -666,6 +666,47 @@ public class VibrationThreadTest { } @Test + public void vibrate_singleVibratorComposedWithFallback_replacedInTheMiddleOfComposition() { + FakeVibratorControllerProvider fakeVibrator = mVibratorProviders.get(VIBRATOR_ID); + fakeVibrator.setSupportedEffects(VibrationEffect.EFFECT_CLICK); + fakeVibrator.setSupportedPrimitives( + VibrationEffect.Composition.PRIMITIVE_CLICK, + VibrationEffect.Composition.PRIMITIVE_TICK); + fakeVibrator.setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS); + + long vibrationId = 1; + VibrationEffect fallback = VibrationEffect.createOneShot(10, 100); + VibrationEffect effect = VibrationEffect.startComposition() + .addEffect(VibrationEffect.get(VibrationEffect.EFFECT_CLICK)) + .addPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 1f) + .addEffect(VibrationEffect.get(VibrationEffect.EFFECT_TICK)) + .addPrimitive(VibrationEffect.Composition.PRIMITIVE_TICK, 0.5f) + .compose(); + Vibration vib = createVibration(vibrationId, CombinedVibration.createParallel(effect)); + vib.addFallback(VibrationEffect.EFFECT_TICK, fallback); + startThreadAndDispatcher(vib); + waitForCompletion(); + + // Use first duration the vibrator is turned on since we cannot estimate the clicks. + verify(mManagerHooks).noteVibratorOn(eq(UID), anyLong()); + verify(mManagerHooks).noteVibratorOff(eq(UID)); + verify(mControllerCallbacks, times(4)).onComplete(eq(VIBRATOR_ID), eq(vibrationId)); + verifyCallbacksTriggered(vibrationId, Vibration.Status.FINISHED); + assertFalse(mControllers.get(VIBRATOR_ID).isVibrating()); + + List<VibrationEffectSegment> segments = + mVibratorProviders.get(VIBRATOR_ID).getEffectSegments(vibrationId); + assertTrue("Wrong segments: " + segments, segments.size() >= 4); + assertTrue(segments.get(0) instanceof PrebakedSegment); + assertTrue(segments.get(1) instanceof PrimitiveSegment); + for (int i = 2; i < segments.size() - 1; i++) { + // One or more step segments as fallback for the EFFECT_TICK. + assertTrue(segments.get(i) instanceof StepSegment); + } + assertTrue(segments.get(segments.size() - 1) instanceof PrimitiveSegment); + } + + @Test public void vibrate_singleVibratorPwle_runsComposePwle() throws Exception { FakeVibratorControllerProvider fakeVibrator = mVibratorProviders.get(VIBRATOR_ID); fakeVibrator.setCapabilities(IVibrator.CAP_COMPOSE_PWLE_EFFECTS); diff --git a/services/tests/servicestests/src/com/android/server/vibrator/VibratorManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/vibrator/VibratorManagerServiceTest.java index 36bec750e3bc..b8e1612049f0 100644 --- a/services/tests/servicestests/src/com/android/server/vibrator/VibratorManagerServiceTest.java +++ b/services/tests/servicestests/src/com/android/server/vibrator/VibratorManagerServiceTest.java @@ -72,6 +72,7 @@ import android.os.VibratorInfo; import android.os.test.TestLooper; import android.os.vibrator.PrebakedSegment; import android.os.vibrator.PrimitiveSegment; +import android.os.vibrator.StepSegment; import android.os.vibrator.VibrationConfig; import android.os.vibrator.VibrationEffectSegment; import android.platform.test.annotations.Presubmit; @@ -99,6 +100,7 @@ import org.mockito.junit.MockitoRule; import java.util.Arrays; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -391,22 +393,22 @@ public class VibratorManagerServiceTest { IVibratorStateListener listenerMock = mockVibratorStateListener(); service.registerVibratorStateListener(1, listenerMock); - vibrate(service, VibrationEffect.createOneShot(40, 100), ALARM_ATTRS); - // Wait until service knows vibrator is on. - assertTrue(waitUntil(s -> s.isVibrating(1), service, TEST_TIMEOUT_MILLIS)); - // Wait until effect ends. - assertTrue(waitUntil(s -> !s.isVibrating(1), service, TEST_TIMEOUT_MILLIS)); + long oneShotDuration = 20; + vibrateAndWaitUntilFinished(service, + VibrationEffect.createOneShot(oneShotDuration, VibrationEffect.DEFAULT_AMPLITUDE), + ALARM_ATTRS); InOrder inOrderVerifier = inOrder(listenerMock); // First notification done when listener is registered. inOrderVerifier.verify(listenerMock).onVibrating(eq(false)); inOrderVerifier.verify(listenerMock).onVibrating(eq(true)); - inOrderVerifier.verify(listenerMock).onVibrating(eq(false)); + // The last notification is after the vibration has completed. + inOrderVerifier.verify(listenerMock, timeout(TEST_TIMEOUT_MILLIS)).onVibrating(eq(false)); inOrderVerifier.verifyNoMoreInteractions(); InOrder batteryVerifier = inOrder(mBatteryStatsMock); batteryVerifier.verify(mBatteryStatsMock) - .noteVibratorOn(UID, 40 + mVibrationConfig.getRampDownDurationMs()); + .noteVibratorOn(UID, oneShotDuration + mVibrationConfig.getRampDownDurationMs()); batteryVerifier.verify(mBatteryStatsMock).noteVibratorOff(UID); } @@ -577,22 +579,18 @@ public class VibratorManagerServiceTest { setRingerMode(AudioManager.RINGER_MODE_SILENT); VibratorManagerService service = createSystemReadyService(); - vibrate(service, VibrationEffect.get(VibrationEffect.EFFECT_CLICK), RINGTONE_ATTRS); - // Wait before checking it never played. - assertFalse(waitUntil(s -> !fakeVibrator.getAllEffectSegments().isEmpty(), - service, /* timeout= */ 50)); + vibrateAndWaitUntilFinished(service, VibrationEffect.get(VibrationEffect.EFFECT_CLICK), + RINGTONE_ATTRS); setRingerMode(AudioManager.RINGER_MODE_NORMAL); service = createSystemReadyService(); - vibrate(service, VibrationEffect.get(VibrationEffect.EFFECT_HEAVY_CLICK), RINGTONE_ATTRS); - assertTrue(waitUntil(s -> fakeVibrator.getAllEffectSegments().size() == 1, - service, TEST_TIMEOUT_MILLIS)); + vibrateAndWaitUntilFinished( + service, VibrationEffect.get(VibrationEffect.EFFECT_HEAVY_CLICK), RINGTONE_ATTRS); setRingerMode(AudioManager.RINGER_MODE_VIBRATE); service = createSystemReadyService(); - vibrate(service, VibrationEffect.get(VibrationEffect.EFFECT_DOUBLE_CLICK), RINGTONE_ATTRS); - assertTrue(waitUntil(s -> fakeVibrator.getAllEffectSegments().size() == 2, - service, TEST_TIMEOUT_MILLIS)); + vibrateAndWaitUntilFinished( + service, VibrationEffect.get(VibrationEffect.EFFECT_DOUBLE_CLICK), RINGTONE_ATTRS); assertEquals( Arrays.asList(expectedPrebaked(VibrationEffect.EFFECT_HEAVY_CLICK), @@ -607,27 +605,18 @@ public class VibratorManagerServiceTest { fakeVibrator.setSupportedEffects(VibrationEffect.EFFECT_TICK, VibrationEffect.EFFECT_CLICK, VibrationEffect.EFFECT_HEAVY_CLICK, VibrationEffect.EFFECT_DOUBLE_CLICK); VibratorManagerService service = createSystemReadyService(); - mRegisteredPowerModeListener.onLowPowerModeChanged(LOW_POWER_STATE); - // The haptic feedback should be ignored in low power, but not the ringtone. The end - // of the test asserts which actual effects ended up playing. - vibrate(service, VibrationEffect.get(VibrationEffect.EFFECT_TICK), HAPTIC_FEEDBACK_ATTRS); - vibrate(service, VibrationEffect.get(VibrationEffect.EFFECT_CLICK), RINGTONE_ATTRS); - assertTrue(waitUntil(s -> fakeVibrator.getAllEffectSegments().size() == 1, - service, TEST_TIMEOUT_MILLIS)); - // Allow the ringtone to complete, as the other vibrations won't cancel it. - assertTrue(waitUntil(s -> !s.isVibrating(1), service, TEST_TIMEOUT_MILLIS)); + mRegisteredPowerModeListener.onLowPowerModeChanged(LOW_POWER_STATE); + vibrateAndWaitUntilFinished(service, VibrationEffect.get(VibrationEffect.EFFECT_TICK), + HAPTIC_FEEDBACK_ATTRS); + vibrateAndWaitUntilFinished(service, VibrationEffect.get(VibrationEffect.EFFECT_CLICK), + RINGTONE_ATTRS); mRegisteredPowerModeListener.onLowPowerModeChanged(NORMAL_POWER_STATE); - vibrate(service, VibrationEffect.get(VibrationEffect.EFFECT_HEAVY_CLICK), - /* attrs= */ null); - assertTrue(waitUntil(s -> fakeVibrator.getAllEffectSegments().size() == 2, - service, TEST_TIMEOUT_MILLIS)); - - vibrate(service, VibrationEffect.get(VibrationEffect.EFFECT_DOUBLE_CLICK), - NOTIFICATION_ATTRS); - assertTrue(waitUntil(s -> fakeVibrator.getAllEffectSegments().size() == 3, - service, TEST_TIMEOUT_MILLIS)); + vibrateAndWaitUntilFinished(service, + VibrationEffect.get(VibrationEffect.EFFECT_HEAVY_CLICK), /* attrs= */ null); + vibrateAndWaitUntilFinished(service, + VibrationEffect.get(VibrationEffect.EFFECT_DOUBLE_CLICK), NOTIFICATION_ATTRS); assertEquals( Arrays.asList(expectedPrebaked(VibrationEffect.EFFECT_CLICK), @@ -693,22 +682,17 @@ public class VibratorManagerServiceTest { Vibrator.VIBRATION_INTENSITY_HIGH); VibratorManagerService service = createSystemReadyService(); - VibrationAttributes enforceFreshAttrs = new VibrationAttributes.Builder() + VibrationAttributes notificationWithFreshAttrs = new VibrationAttributes.Builder() .setUsage(VibrationAttributes.USAGE_NOTIFICATION) .setFlags(VibrationAttributes.FLAG_INVALIDATE_SETTINGS_CACHE) .build(); setUserSetting(Settings.System.NOTIFICATION_VIBRATION_INTENSITY, Vibrator.VIBRATION_INTENSITY_LOW); - vibrate(service, VibrationEffect.get(VibrationEffect.EFFECT_CLICK), NOTIFICATION_ATTRS); - // VibrationThread will start this vibration async, so wait before vibrating a second time. - assertTrue(waitUntil(s -> mVibratorProviders.get(0).getAllEffectSegments().size() > 0, - service, TEST_TIMEOUT_MILLIS)); - - vibrate(service, VibrationEffect.get(VibrationEffect.EFFECT_TICK), enforceFreshAttrs); - // VibrationThread will start this vibration async, so wait before checking. - assertTrue(waitUntil(s -> mVibratorProviders.get(0).getAllEffectSegments().size() > 1, - service, TEST_TIMEOUT_MILLIS)); + vibrateAndWaitUntilFinished(service, VibrationEffect.get(VibrationEffect.EFFECT_CLICK), + NOTIFICATION_ATTRS); + vibrateAndWaitUntilFinished(service, VibrationEffect.get(VibrationEffect.EFFECT_TICK), + notificationWithFreshAttrs); assertEquals( Arrays.asList( @@ -784,21 +768,22 @@ public class VibratorManagerServiceTest { vibrate(service, repeatingEffect, new VibrationAttributes.Builder().setUsage( VibrationAttributes.USAGE_UNKNOWN).build()); - // VibrationThread will start this vibration async, so wait before checking it started. + // VibrationThread will start this vibration async, wait until it has started. assertTrue(waitUntil(s -> !mVibratorProviders.get(1).getAllEffectSegments().isEmpty(), service, TEST_TIMEOUT_MILLIS)); - vibrate(service, VibrationEffect.get(VibrationEffect.EFFECT_CLICK), HAPTIC_FEEDBACK_ATTRS); - - // Wait before checking it never played a second effect. - assertFalse(waitUntil(s -> mVibratorProviders.get(1).getAllEffectSegments().size() > 1, - service, /* timeout= */ 50)); + vibrateAndWaitUntilFinished(service, VibrationEffect.get(VibrationEffect.EFFECT_CLICK), + HAPTIC_FEEDBACK_ATTRS); // The time estimate is recorded when the vibration starts, repeating vibrations // are capped at BATTERY_STATS_REPEATING_VIBRATION_DURATION (=5000). verify(mBatteryStatsMock).noteVibratorOn(UID, 5000); // The second vibration shouldn't have recorded that the vibrators were turned on. verify(mBatteryStatsMock, times(1)).noteVibratorOn(anyInt(), anyLong()); + // No segment played is the prebaked CLICK from the second vibration. + assertFalse( + mVibratorProviders.get(1).getAllEffectSegments().stream() + .anyMatch(segment -> segment instanceof PrebakedSegment)); } @Test @@ -811,7 +796,7 @@ public class VibratorManagerServiceTest { new long[]{10_000, 10_000}, new int[]{128, 255}, -1); vibrate(service, alarmEffect, ALARM_ATTRS); - // VibrationThread will start this vibration async, so wait before checking it started. + // VibrationThread will start this vibration async, wait until it has started. assertTrue(waitUntil(s -> !mVibratorProviders.get(1).getAllEffectSegments().isEmpty(), service, TEST_TIMEOUT_MILLIS)); @@ -841,14 +826,15 @@ public class VibratorManagerServiceTest { assertTrue(waitUntil(s -> !mVibratorProviders.get(1).getAllEffectSegments().isEmpty(), service, TEST_TIMEOUT_MILLIS)); - vibrate(service, effect, HAPTIC_FEEDBACK_ATTRS); - - // Wait before checking it never played a second effect. - assertFalse(waitUntil(s -> mVibratorProviders.get(1).getAllEffectSegments().size() > 1, - service, /* timeout= */ 50)); + vibrateAndWaitUntilFinished(service, VibrationEffect.get(VibrationEffect.EFFECT_CLICK), + HAPTIC_FEEDBACK_ATTRS); // The second vibration shouldn't have recorded that the vibrators were turned on. verify(mBatteryStatsMock, times(1)).noteVibratorOn(anyInt(), anyLong()); + // The second vibration shouldn't have played any prebaked segment. + assertFalse( + mVibratorProviders.get(1).getAllEffectSegments().stream() + .anyMatch(segment -> segment instanceof PrebakedSegment)); } @Test @@ -856,6 +842,7 @@ public class VibratorManagerServiceTest { throws Exception { mockVibrators(1); mVibratorProviders.get(1).setCapabilities(IVibrator.CAP_AMPLITUDE_CONTROL); + mVibratorProviders.get(1).setSupportedEffects(VibrationEffect.EFFECT_CLICK); VibratorManagerService service = createSystemReadyService(); VibrationEffect effect = VibrationEffect.createWaveform( @@ -866,14 +853,16 @@ public class VibratorManagerServiceTest { assertTrue(waitUntil(s -> !mVibratorProviders.get(1).getAllEffectSegments().isEmpty(), service, TEST_TIMEOUT_MILLIS)); - vibrate(service, effect, RINGTONE_ATTRS); - - // VibrationThread will start this vibration async, so wait before checking it started. - assertTrue(waitUntil(s -> mVibratorProviders.get(1).getAllEffectSegments().size() > 1, - service, TEST_TIMEOUT_MILLIS)); + vibrateAndWaitUntilFinished(service, VibrationEffect.get(VibrationEffect.EFFECT_CLICK), + RINGTONE_ATTRS); // The second vibration should have recorded that the vibrators were turned on. verify(mBatteryStatsMock, times(2)).noteVibratorOn(anyInt(), anyLong()); + // One segment played is the prebaked CLICK from the second vibration. + assertEquals(1, + mVibratorProviders.get(1).getAllEffectSegments().stream() + .filter(PrebakedSegment.class::isInstance) + .count()); } @Test @@ -892,12 +881,10 @@ public class VibratorManagerServiceTest { CombinedVibration effect = CombinedVibration.createParallel( VibrationEffect.createOneShot(10, 10)); - vibrate(service, effect, ALARM_ATTRS); - verify(mIInputManagerMock).vibrateCombined(eq(1), eq(effect), any()); + vibrateAndWaitUntilFinished(service, effect, ALARM_ATTRS); - // VibrationThread will start this vibration async, so wait before checking it never played. - assertFalse(waitUntil(s -> !mVibratorProviders.get(1).getAllEffectSegments().isEmpty(), - service, /* timeout= */ 50)); + verify(mIInputManagerMock).vibrateCombined(eq(1), eq(effect), any()); + assertTrue(mVibratorProviders.get(1).getAllEffectSegments().isEmpty()); } @Test @@ -992,9 +979,7 @@ public class VibratorManagerServiceTest { .addPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK) .compose()) .combine(); - vibrate(service, effect, ALARM_ATTRS); - assertTrue(waitUntil(s -> !fakeVibrator1.getAllEffectSegments().isEmpty(), service, - TEST_TIMEOUT_MILLIS)); + vibrateAndWaitUntilFinished(service, effect, ALARM_ATTRS); verify(mNativeWrapperMock).prepareSynced(eq(new int[]{1, 2})); verify(mNativeWrapperMock).triggerSynced(anyLong()); @@ -1016,9 +1001,7 @@ public class VibratorManagerServiceTest { .addVibrator(1, VibrationEffect.get(VibrationEffect.EFFECT_CLICK)) .addVibrator(2, VibrationEffect.createOneShot(10, 100)) .combine(); - vibrate(service, effect, ALARM_ATTRS); - assertTrue(waitUntil(s -> !fakeVibrator1.getAllEffectSegments().isEmpty(), service, - TEST_TIMEOUT_MILLIS)); + vibrateAndWaitUntilFinished(service, effect, ALARM_ATTRS); verify(mNativeWrapperMock, never()).prepareSynced(any()); verify(mNativeWrapperMock, never()).triggerSynced(anyLong()); @@ -1036,9 +1019,7 @@ public class VibratorManagerServiceTest { .addVibrator(1, VibrationEffect.createOneShot(10, 50)) .addVibrator(2, VibrationEffect.createOneShot(10, 100)) .combine(); - vibrate(service, effect, ALARM_ATTRS); - assertTrue(waitUntil(s -> !mVibratorProviders.get(1).getAllEffectSegments().isEmpty(), - service, TEST_TIMEOUT_MILLIS)); + vibrateAndWaitUntilFinished(service, effect, ALARM_ATTRS); verify(mNativeWrapperMock).prepareSynced(eq(new int[]{1, 2})); verify(mNativeWrapperMock, never()).triggerSynced(anyLong()); @@ -1057,9 +1038,7 @@ public class VibratorManagerServiceTest { .addVibrator(1, VibrationEffect.createOneShot(10, 50)) .addVibrator(2, VibrationEffect.createOneShot(10, 100)) .combine(); - vibrate(service, effect, ALARM_ATTRS); - assertTrue(waitUntil(s -> !mVibratorProviders.get(1).getAllEffectSegments().isEmpty(), - service, TEST_TIMEOUT_MILLIS)); + vibrateAndWaitUntilFinished(service, effect, ALARM_ATTRS); verify(mNativeWrapperMock).prepareSynced(eq(new int[]{1, 2})); verify(mNativeWrapperMock).triggerSynced(anyLong()); @@ -1096,28 +1075,21 @@ public class VibratorManagerServiceTest { VibrationEffect.Composition.PRIMITIVE_TICK); VibratorManagerService service = createSystemReadyService(); - vibrate(service, VibrationEffect.startComposition() + vibrateAndWaitUntilFinished(service, VibrationEffect.startComposition() .addPrimitive(VibrationEffect.Composition.PRIMITIVE_TICK, 0.5f) .compose(), HAPTIC_FEEDBACK_ATTRS); - assertTrue(waitUntil(s -> fakeVibrator.getAllEffectSegments().size() == 1, - service, TEST_TIMEOUT_MILLIS)); - vibrate(service, CombinedVibration.startSequential() + vibrateAndWaitUntilFinished(service, CombinedVibration.startSequential() .addNext(1, VibrationEffect.createOneShot(100, 125)) .combine(), NOTIFICATION_ATTRS); - assertTrue(waitUntil(s -> fakeVibrator.getAllEffectSegments().size() == 2, - service, TEST_TIMEOUT_MILLIS)); - vibrate(service, VibrationEffect.startComposition() + vibrateAndWaitUntilFinished(service, VibrationEffect.startComposition() .addPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK, 1f) .compose(), ALARM_ATTRS); - assertTrue(waitUntil(s -> fakeVibrator.getAllEffectSegments().size() == 3, - service, TEST_TIMEOUT_MILLIS)); // Ring vibrations have intensity OFF and are not played. - vibrate(service, VibrationEffect.createOneShot(100, 125), RINGTONE_ATTRS); - assertFalse(waitUntil(s -> fakeVibrator.getAllEffectSegments().size() > 3, - service, /* timeout= */ 50)); + vibrateAndWaitUntilFinished(service, VibrationEffect.createOneShot(100, 125), + RINGTONE_ATTRS); // Only 3 effects played successfully. assertEquals(3, fakeVibrator.getAllEffectSegments().size()); @@ -1145,6 +1117,7 @@ public class VibratorManagerServiceTest { .combine(), HAPTIC_FEEDBACK_ATTRS); + // VibrationThread will start this vibration async, so wait until vibration is triggered. assertTrue(waitUntil(s -> s.isVibrating(1), service, TEST_TIMEOUT_MILLIS)); mRegisteredPowerModeListener.onLowPowerModeChanged(LOW_POWER_STATE); @@ -1159,14 +1132,50 @@ public class VibratorManagerServiceTest { VibratorManagerService service = createSystemReadyService(); vibrate(service, VibrationEffect.createOneShot(1000, 100), HAPTIC_FEEDBACK_ATTRS); + + // VibrationThread will start this vibration async, so wait until vibration is triggered. assertTrue(waitUntil(s -> s.isVibrating(1), service, TEST_TIMEOUT_MILLIS)); service.updateServiceState(); + // Vibration is not stopped nearly after updating service. assertFalse(waitUntil(s -> !s.isVibrating(1), service, 50)); } @Test + public void vibrate_prebakedAndComposedVibrationsWithFallbacks_playsFallbackOnlyForPredefined() + throws Exception { + mockVibrators(1); + mVibratorProviders.get(1).setCapabilities(IVibrator.CAP_COMPOSE_EFFECTS); + mVibratorProviders.get(1).setSupportedEffects(VibrationEffect.EFFECT_CLICK); + mVibratorProviders.get(1).setSupportedPrimitives( + VibrationEffect.Composition.PRIMITIVE_CLICK); + + VibratorManagerService service = createSystemReadyService(); + vibrateAndWaitUntilFinished(service, + VibrationEffect.startComposition() + .addEffect(VibrationEffect.createPredefined(VibrationEffect.EFFECT_CLICK)) + .addPrimitive(VibrationEffect.Composition.PRIMITIVE_TICK) + .addEffect(VibrationEffect.createPredefined(VibrationEffect.EFFECT_TICK)) + .addPrimitive(VibrationEffect.Composition.PRIMITIVE_CLICK) + .compose(), + ALARM_ATTRS); + + List<VibrationEffectSegment> segments = mVibratorProviders.get(1).getAllEffectSegments(); + // At least one step segment played as fallback for unusupported vibration effect + assertTrue(segments.size() > 2); + // 0: Supported effect played + assertTrue(segments.get(0) instanceof PrebakedSegment); + // 1: No segment for unsupported primitive + // 2: One or more intermediate step segments as fallback for unsupported effect + for (int i = 1; i < segments.size() - 1; i++) { + assertTrue(segments.get(i) instanceof StepSegment); + } + // 3: Supported primitive played + assertTrue(segments.get(segments.size() - 1) instanceof PrimitiveSegment); + } + + @Test public void cancelVibrate_withoutUsageFilter_stopsVibrating() throws Exception { mockVibrators(1); VibratorManagerService service = createSystemReadyService(); @@ -1175,9 +1184,13 @@ public class VibratorManagerServiceTest { assertFalse(service.isVibrating(1)); vibrate(service, VibrationEffect.createOneShot(10 * TEST_TIMEOUT_MILLIS, 100), ALARM_ATTRS); + + // VibrationThread will start this vibration async, so wait until vibration is triggered. assertTrue(waitUntil(s -> s.isVibrating(1), service, TEST_TIMEOUT_MILLIS)); service.cancelVibrate(VibrationAttributes.USAGE_FILTER_MATCH_ALL, service); + + // Alarm cancelled on filter match all. assertTrue(waitUntil(s -> !s.isVibrating(1), service, TEST_TIMEOUT_MILLIS)); } @@ -1187,6 +1200,8 @@ public class VibratorManagerServiceTest { VibratorManagerService service = createSystemReadyService(); vibrate(service, VibrationEffect.createOneShot(10 * TEST_TIMEOUT_MILLIS, 100), ALARM_ATTRS); + + // VibrationThread will start this vibration async, so wait until vibration is triggered. assertTrue(waitUntil(s -> s.isVibrating(1), service, TEST_TIMEOUT_MILLIS)); // Vibration is not cancelled with a different usage. @@ -1216,6 +1231,8 @@ public class VibratorManagerServiceTest { VibratorManagerService service = createSystemReadyService(); vibrate(service, VibrationEffect.createOneShot(10 * TEST_TIMEOUT_MILLIS, 100), attrs); + + // VibrationThread will start this vibration async, so wait until vibration is triggered. assertTrue(waitUntil(s -> s.isVibrating(1), service, TEST_TIMEOUT_MILLIS)); // Do not cancel UNKNOWN vibration when filter is being applied for other usages. @@ -1232,6 +1249,8 @@ public class VibratorManagerServiceTest { assertTrue(waitUntil(s -> !s.isVibrating(1), service, TEST_TIMEOUT_MILLIS)); vibrate(service, VibrationEffect.createOneShot(10 * TEST_TIMEOUT_MILLIS, 100), attrs); + + // VibrationThread will start this vibration async, so wait until vibration is triggered. assertTrue(waitUntil(s -> s.isVibrating(1), service, TEST_TIMEOUT_MILLIS)); // Cancel UNKNOWN vibration when all vibrations are being cancelled. @@ -1312,6 +1331,8 @@ public class VibratorManagerServiceTest { VibrationEffect effect = VibrationEffect.createOneShot(10 * TEST_TIMEOUT_MILLIS, 100); vibrate(service, effect, HAPTIC_FEEDBACK_ATTRS); + + // VibrationThread will start this vibration async, so wait until vibration is triggered. assertTrue(waitUntil(s -> s.isVibrating(1), service, TEST_TIMEOUT_MILLIS)); ExternalVibration externalVibration = new ExternalVibration(UID, PACKAGE_NAME, AUDIO_ATTRS, diff --git a/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java index d62ac99e530b..598a22bbde39 100644 --- a/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java +++ b/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java @@ -93,7 +93,6 @@ import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; -import android.os.Parcel; import android.os.RemoteCallback; import android.os.RemoteException; import android.os.UserHandle; @@ -2448,35 +2447,6 @@ public class PreferencesHelperTest extends UiServiceTestCase { } @Test - public void testGetNotificationChannelGroup() throws Exception { - NotificationChannelGroup notDeleted = new NotificationChannelGroup("not", "deleted"); - NotificationChannel base = - new NotificationChannel("not deleted", "belongs to notDeleted", IMPORTANCE_DEFAULT); - base.setGroup("not"); - NotificationChannel convo = - new NotificationChannel("convo", "belongs to notDeleted", IMPORTANCE_DEFAULT); - convo.setGroup("not"); - convo.setConversationId("not deleted", "banana"); - - mHelper.createNotificationChannelGroup(PKG_N_MR1, UID_N_MR1, notDeleted, true); - mHelper.createNotificationChannel(PKG_N_MR1, UID_N_MR1, base, true, false); - mHelper.createNotificationChannel(PKG_N_MR1, UID_N_MR1, convo, true, false); - mHelper.createNotificationChannelGroup(PKG_N_MR1, UID_N_MR1, notDeleted, true); - - NotificationChannelGroup g - = mHelper.getNotificationChannelGroup(notDeleted.getId(), PKG_N_MR1, UID_N_MR1); - Parcel parcel = Parcel.obtain(); - g.writeToParcel(parcel, 0); - parcel.setDataPosition(0); - - NotificationChannelGroup g2 - = mHelper.getNotificationChannelGroup(notDeleted.getId(), PKG_N_MR1, UID_N_MR1); - Parcel parcel2 = Parcel.obtain(); - g2.writeToParcel(parcel2, 0); - parcel2.setDataPosition(0); - } - - @Test public void testOnUserRemoved() throws Exception { int[] user0Uids = {98, 235, 16, 3782}; int[] user1Uids = new int[user0Uids.length]; diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ValidateNotificationPeopleTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ValidateNotificationPeopleTest.java index c12f0a965146..d72cfc70fc02 100644 --- a/services/tests/uiservicestests/src/com/android/server/notification/ValidateNotificationPeopleTest.java +++ b/services/tests/uiservicestests/src/com/android/server/notification/ValidateNotificationPeopleTest.java @@ -17,7 +17,9 @@ package com.android.server.notification; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.contains; import static org.mockito.ArgumentMatchers.eq; @@ -30,6 +32,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.app.Notification; +import android.app.NotificationChannel; import android.app.Person; import android.content.ContentProvider; import android.content.ContentResolver; @@ -39,8 +42,11 @@ import android.net.Uri; import android.os.Bundle; import android.os.UserManager; import android.provider.ContactsContract; +import android.service.notification.StatusBarNotification; import android.test.suitebuilder.annotation.SmallTest; import android.text.SpannableString; +import android.util.ArraySet; +import android.util.LruCache; import androidx.test.runner.AndroidJUnit4; @@ -323,6 +329,69 @@ public class ValidateNotificationPeopleTest extends UiServiceTestCase { isNull()); // sort order } + @Test + public void testValidatePeople_needsLookupWhenNoCache() { + final Context mockContext = mock(Context.class); + final ContentResolver mockContentResolver = mock(ContentResolver.class); + when(mockContext.getContentResolver()).thenReturn(mockContentResolver); + final NotificationUsageStats mockNotificationUsageStats = + mock(NotificationUsageStats.class); + + // Create validator with empty cache + ValidateNotificationPeople vnp = new ValidateNotificationPeople(); + LruCache cache = new LruCache<String, ValidateNotificationPeople.LookupResult>(5); + vnp.initForTests(mockContext, mockNotificationUsageStats, cache); + + NotificationRecord record = getNotificationRecord(); + String[] callNumber = new String[]{"tel:12345678910"}; + setNotificationPeople(record, callNumber); + + // Returned ranking reconsideration not null indicates that there is a lookup to be done + RankingReconsideration rr = vnp.validatePeople(mockContext, record); + assertNotNull(rr); + } + + @Test + public void testValidatePeople_noLookupWhenCached_andPopulatesContactInfo() { + final Context mockContext = mock(Context.class); + final ContentResolver mockContentResolver = mock(ContentResolver.class); + when(mockContext.getContentResolver()).thenReturn(mockContentResolver); + when(mockContext.getUserId()).thenReturn(1); + final NotificationUsageStats mockNotificationUsageStats = + mock(NotificationUsageStats.class); + + // Information to be passed in & returned from the lookup result + String lookup = "lookup:contactinfohere"; + String lookupTel = "16175551234"; + float affinity = 0.7f; + + // Create a fake LookupResult for the data we'll pass in + LruCache cache = new LruCache<String, ValidateNotificationPeople.LookupResult>(5); + ValidateNotificationPeople.LookupResult lr = + mock(ValidateNotificationPeople.LookupResult.class); + when(lr.getAffinity()).thenReturn(affinity); + when(lr.getPhoneNumbers()).thenReturn(new ArraySet<>(new String[]{lookupTel})); + when(lr.isExpired()).thenReturn(false); + cache.put(ValidateNotificationPeople.getCacheKey(1, lookup), lr); + + // Create validator with the established cache + ValidateNotificationPeople vnp = new ValidateNotificationPeople(); + vnp.initForTests(mockContext, mockNotificationUsageStats, cache); + + NotificationRecord record = getNotificationRecord(); + String[] peopleInfo = new String[]{lookup}; + setNotificationPeople(record, peopleInfo); + + // Returned ranking reconsideration null indicates that there is no pending work to be done + RankingReconsideration rr = vnp.validatePeople(mockContext, record); + assertNull(rr); + + // Confirm that the affinity & phone number made it into our record + assertEquals(affinity, record.getContactAffinity(), 1e-8); + assertNotNull(record.getPhoneNumbers()); + assertTrue(record.getPhoneNumbers().contains(lookupTel)); + } + // Creates a cursor that points to one item of Contacts data with the specified // columns. private Cursor makeMockCursor(int id, String lookupKey, int starred, int hasPhone) { @@ -365,4 +434,17 @@ public class ValidateNotificationPeopleTest extends UiServiceTestCase { String resultString = Arrays.toString(result); assertEquals(message + ": arrays differ", expectedString, resultString); } + + private NotificationRecord getNotificationRecord() { + StatusBarNotification sbn = mock(StatusBarNotification.class); + Notification notification = mock(Notification.class); + when(sbn.getNotification()).thenReturn(notification); + return new NotificationRecord(mContext, sbn, mock(NotificationChannel.class)); + } + + private void setNotificationPeople(NotificationRecord r, String[] people) { + Bundle extras = new Bundle(); + extras.putObject(Notification.EXTRA_PEOPLE_LIST, people); + r.getSbn().getNotification().extras = extras; + } } diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java index 15d1a3c48ccd..44494831eb68 100644 --- a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java @@ -158,6 +158,7 @@ import androidx.test.filters.MediumTest; import com.android.internal.R; import com.android.server.wm.ActivityRecord.State; +import com.android.server.wm.utils.WmDisplayCutout; import org.junit.Assert; import org.junit.Before; @@ -551,7 +552,8 @@ public class ActivityRecordTests extends WindowTestsBase { final Rect insets = new Rect(); final DisplayInfo displayInfo = task.mDisplayContent.getDisplayInfo(); final DisplayPolicy policy = task.mDisplayContent.getDisplayPolicy(); - policy.getNonDecorInsetsLw(displayInfo.rotation, displayInfo.displayCutout, insets); + policy.getNonDecorInsetsLw(displayInfo.rotation, displayInfo.logicalWidth, + displayInfo.logicalHeight, WmDisplayCutout.NO_CUTOUT, insets); policy.convertNonDecorInsetsToStableInsets(insets, displayInfo.rotation); Task.intersectWithInsetsIfFits(stableRect, stableRect, insets); @@ -592,7 +594,8 @@ public class ActivityRecordTests extends WindowTestsBase { final Rect insets = new Rect(); final DisplayInfo displayInfo = rootTask.mDisplayContent.getDisplayInfo(); final DisplayPolicy policy = rootTask.mDisplayContent.getDisplayPolicy(); - policy.getNonDecorInsetsLw(displayInfo.rotation, displayInfo.displayCutout, insets); + policy.getNonDecorInsetsLw(displayInfo.rotation, displayInfo.logicalWidth, + displayInfo.logicalHeight, WmDisplayCutout.NO_CUTOUT, insets); policy.convertNonDecorInsetsToStableInsets(insets, displayInfo.rotation); Task.intersectWithInsetsIfFits(stableRect, stableRect, insets); diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityTaskSupervisorTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityTaskSupervisorTests.java index 75ecfd870eb2..d5e336b1cf2f 100644 --- a/services/tests/wmtests/src/com/android/server/wm/ActivityTaskSupervisorTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/ActivityTaskSupervisorTests.java @@ -228,7 +228,7 @@ public class ActivityTaskSupervisorTests extends WindowTestsBase { mAtm.getTaskChangeNotificationController(); spyOn(taskChangeNotifier); - mAtm.setResumedActivityUncheckLocked(fullScreenActivityA, "resumeA"); + mAtm.setLastResumedActivityUncheckLocked(fullScreenActivityA, "resumeA"); verify(taskChangeNotifier).notifyTaskFocusChanged(eq(taskA.mTaskId) /* taskId */, eq(true) /* focused */); reset(taskChangeNotifier); @@ -237,7 +237,7 @@ public class ActivityTaskSupervisorTests extends WindowTestsBase { .build(); final Task taskB = fullScreenActivityB.getTask(); - mAtm.setResumedActivityUncheckLocked(fullScreenActivityB, "resumeB"); + mAtm.setLastResumedActivityUncheckLocked(fullScreenActivityB, "resumeB"); verify(taskChangeNotifier).notifyTaskFocusChanged(eq(taskA.mTaskId) /* taskId */, eq(false) /* focused */); verify(taskChangeNotifier).notifyTaskFocusChanged(eq(taskB.mTaskId) /* taskId */, @@ -295,6 +295,7 @@ public class ActivityTaskSupervisorTests extends WindowTestsBase { activity1.moveFocusableActivityToTop("test"); assertEquals(activity1.getUid(), pendingTopUid[0]); verify(mAtm).updateOomAdj(); + verify(mAtm).setLastResumedActivityUncheckLocked(any(), eq("test")); } /** diff --git a/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyInsetsTests.java b/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyInsetsTests.java index 2158cafbb64a..aa5a74e962e6 100644 --- a/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyInsetsTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/DisplayPolicyInsetsTests.java @@ -25,10 +25,13 @@ import static org.hamcrest.Matchers.equalTo; import android.graphics.Rect; import android.platform.test.annotations.Presubmit; +import android.util.Pair; import android.view.DisplayInfo; import androidx.test.filters.SmallTest; +import com.android.server.wm.utils.WmDisplayCutout; + import org.junit.Rule; import org.junit.Test; import org.junit.rules.ErrorCollector; @@ -46,7 +49,8 @@ public class DisplayPolicyInsetsTests extends DisplayPolicyTestsBase { @Test public void portrait() { - final DisplayInfo di = displayInfoForRotation(ROTATION_0, false /* withCutout */); + final Pair<DisplayInfo, WmDisplayCutout> di = + displayInfoForRotation(ROTATION_0, false /* withCutout */); verifyStableInsets(di, 0, STATUS_BAR_HEIGHT, 0, NAV_BAR_HEIGHT); verifyNonDecorInsets(di, 0, 0, 0, NAV_BAR_HEIGHT); @@ -55,7 +59,8 @@ public class DisplayPolicyInsetsTests extends DisplayPolicyTestsBase { @Test public void portrait_withCutout() { - final DisplayInfo di = displayInfoForRotation(ROTATION_0, true /* withCutout */); + final Pair<DisplayInfo, WmDisplayCutout> di = + displayInfoForRotation(ROTATION_0, true /* withCutout */); verifyStableInsets(di, 0, STATUS_BAR_HEIGHT, 0, NAV_BAR_HEIGHT); verifyNonDecorInsets(di, 0, DISPLAY_CUTOUT_HEIGHT, 0, NAV_BAR_HEIGHT); @@ -64,7 +69,8 @@ public class DisplayPolicyInsetsTests extends DisplayPolicyTestsBase { @Test public void landscape() { - final DisplayInfo di = displayInfoForRotation(ROTATION_90, false /* withCutout */); + final Pair<DisplayInfo, WmDisplayCutout> di = + displayInfoForRotation(ROTATION_90, false /* withCutout */); if (mDisplayPolicy.navigationBarCanMove()) { verifyStableInsets(di, 0, STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT, 0); @@ -79,7 +85,8 @@ public class DisplayPolicyInsetsTests extends DisplayPolicyTestsBase { @Test public void landscape_withCutout() { - final DisplayInfo di = displayInfoForRotation(ROTATION_90, true /* withCutout */); + final Pair<DisplayInfo, WmDisplayCutout> di = + displayInfoForRotation(ROTATION_90, true /* withCutout */); if (mDisplayPolicy.navigationBarCanMove()) { verifyStableInsets(di, DISPLAY_CUTOUT_HEIGHT, STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT, 0); @@ -94,7 +101,8 @@ public class DisplayPolicyInsetsTests extends DisplayPolicyTestsBase { @Test public void seascape() { - final DisplayInfo di = displayInfoForRotation(ROTATION_270, false /* withCutout */); + final Pair<DisplayInfo, WmDisplayCutout> di = + displayInfoForRotation(ROTATION_270, false /* withCutout */); if (mDisplayPolicy.navigationBarCanMove()) { verifyStableInsets(di, NAV_BAR_HEIGHT, STATUS_BAR_HEIGHT, 0, 0); @@ -109,7 +117,8 @@ public class DisplayPolicyInsetsTests extends DisplayPolicyTestsBase { @Test public void seascape_withCutout() { - final DisplayInfo di = displayInfoForRotation(ROTATION_270, true /* withCutout */); + final Pair<DisplayInfo, WmDisplayCutout> di = + displayInfoForRotation(ROTATION_270, true /* withCutout */); if (mDisplayPolicy.navigationBarCanMove()) { verifyStableInsets(di, NAV_BAR_HEIGHT, STATUS_BAR_HEIGHT, DISPLAY_CUTOUT_HEIGHT, 0); @@ -124,7 +133,8 @@ public class DisplayPolicyInsetsTests extends DisplayPolicyTestsBase { @Test public void upsideDown() { - final DisplayInfo di = displayInfoForRotation(ROTATION_180, false /* withCutout */); + final Pair<DisplayInfo, WmDisplayCutout> di = + displayInfoForRotation(ROTATION_180, false /* withCutout */); verifyStableInsets(di, 0, STATUS_BAR_HEIGHT, 0, NAV_BAR_HEIGHT); verifyNonDecorInsets(di, 0, 0, 0, NAV_BAR_HEIGHT); @@ -133,28 +143,34 @@ public class DisplayPolicyInsetsTests extends DisplayPolicyTestsBase { @Test public void upsideDown_withCutout() { - final DisplayInfo di = displayInfoForRotation(ROTATION_180, true /* withCutout */); + final Pair<DisplayInfo, WmDisplayCutout> di = + displayInfoForRotation(ROTATION_180, true /* withCutout */); verifyStableInsets(di, 0, STATUS_BAR_HEIGHT, 0, NAV_BAR_HEIGHT + DISPLAY_CUTOUT_HEIGHT); verifyNonDecorInsets(di, 0, 0, 0, NAV_BAR_HEIGHT + DISPLAY_CUTOUT_HEIGHT); verifyConsistency(di); } - private void verifyStableInsets(DisplayInfo di, int left, int top, int right, int bottom) { - mErrorCollector.checkThat("stableInsets", getStableInsetsLw(di), equalTo(new Rect( - left, top, right, bottom))); + private void verifyStableInsets(Pair<DisplayInfo, WmDisplayCutout> diPair, int left, int top, + int right, int bottom) { + mErrorCollector.checkThat("stableInsets", getStableInsetsLw(diPair.first, diPair.second), + equalTo(new Rect(left, top, right, bottom))); } - private void verifyNonDecorInsets(DisplayInfo di, int left, int top, int right, int bottom) { - mErrorCollector.checkThat("nonDecorInsets", getNonDecorInsetsLw(di), equalTo(new Rect( + private void verifyNonDecorInsets(Pair<DisplayInfo, WmDisplayCutout> diPair, int left, int top, + int right, int bottom) { + mErrorCollector.checkThat("nonDecorInsets", + getNonDecorInsetsLw(diPair.first, diPair.second), equalTo(new Rect( left, top, right, bottom))); } - private void verifyConsistency(DisplayInfo di) { - verifyConsistency("configDisplay", di, getStableInsetsLw(di), - getConfigDisplayWidth(di), getConfigDisplayHeight(di)); - verifyConsistency("nonDecorDisplay", di, getNonDecorInsetsLw(di), - getNonDecorDisplayWidth(di), getNonDecorDisplayHeight(di)); + private void verifyConsistency(Pair<DisplayInfo, WmDisplayCutout> diPair) { + final DisplayInfo di = diPair.first; + final WmDisplayCutout cutout = diPair.second; + verifyConsistency("configDisplay", di, getStableInsetsLw(di, cutout), + getConfigDisplayWidth(di, cutout), getConfigDisplayHeight(di, cutout)); + verifyConsistency("nonDecorDisplay", di, getNonDecorInsetsLw(di, cutout), + getNonDecorDisplayWidth(di, cutout), getNonDecorDisplayHeight(di, cutout)); } private void verifyConsistency(String what, DisplayInfo di, Rect insets, int width, @@ -165,39 +181,42 @@ public class DisplayPolicyInsetsTests extends DisplayPolicyTestsBase { equalTo(di.logicalHeight - insets.top - insets.bottom)); } - private Rect getStableInsetsLw(DisplayInfo di) { + private Rect getStableInsetsLw(DisplayInfo di, WmDisplayCutout cutout) { Rect result = new Rect(); - mDisplayPolicy.getStableInsetsLw(di.rotation, di.displayCutout, result); + mDisplayPolicy.getStableInsetsLw(di.rotation, di.logicalWidth, di.logicalHeight, + cutout, result); return result; } - private Rect getNonDecorInsetsLw(DisplayInfo di) { + private Rect getNonDecorInsetsLw(DisplayInfo di, WmDisplayCutout cutout) { Rect result = new Rect(); - mDisplayPolicy.getNonDecorInsetsLw(di.rotation, di.displayCutout, result); + mDisplayPolicy.getNonDecorInsetsLw(di.rotation, di.logicalWidth, di.logicalHeight, + cutout, result); return result; } - private int getNonDecorDisplayWidth(DisplayInfo di) { - return mDisplayPolicy.getNonDecorDisplayWidth(di.logicalWidth, di.logicalHeight, - di.rotation, 0 /* ui */, di.displayCutout); + private int getNonDecorDisplayWidth(DisplayInfo di, WmDisplayCutout cutout) { + return mDisplayPolicy.getNonDecorDisplayFrame(di.logicalWidth, di.logicalHeight, + di.rotation, cutout).width(); } - private int getNonDecorDisplayHeight(DisplayInfo di) { - return mDisplayPolicy.getNonDecorDisplayHeight(di.logicalHeight, di.rotation, - di.displayCutout); + private int getNonDecorDisplayHeight(DisplayInfo di, WmDisplayCutout cutout) { + return mDisplayPolicy.getNonDecorDisplayFrame(di.logicalWidth, di.logicalHeight, + di.rotation, cutout).height(); } - private int getConfigDisplayWidth(DisplayInfo di) { - return mDisplayPolicy.getConfigDisplayWidth(di.logicalWidth, di.logicalHeight, - di.rotation, 0 /* ui */, di.displayCutout); + private int getConfigDisplayWidth(DisplayInfo di, WmDisplayCutout cutout) { + return mDisplayPolicy.getConfigDisplaySize(di.logicalWidth, di.logicalHeight, + di.rotation, cutout).x; } - private int getConfigDisplayHeight(DisplayInfo di) { - return mDisplayPolicy.getConfigDisplayHeight(di.logicalWidth, di.logicalHeight, - di.rotation, 0 /* ui */, di.displayCutout); + private int getConfigDisplayHeight(DisplayInfo di, WmDisplayCutout cutout) { + return mDisplayPolicy.getConfigDisplaySize(di.logicalWidth, di.logicalHeight, + di.rotation, cutout).y; } - private static DisplayInfo displayInfoForRotation(int rotation, boolean withDisplayCutout) { - return displayInfoAndCutoutForRotation(rotation, withDisplayCutout, false).first; + private static Pair<DisplayInfo, WmDisplayCutout> displayInfoForRotation(int rotation, + boolean withDisplayCutout) { + return displayInfoAndCutoutForRotation(rotation, withDisplayCutout, false); } } diff --git a/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java index 8546763aebec..88e58eab58aa 100644 --- a/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java +++ b/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationControllerTest.java @@ -281,7 +281,7 @@ public class RecentsAnimationControllerTest extends WindowTestsBase { verify(mMockRunner).onAnimationCanceled(null /* taskIds */, null /* taskSnapshots */); // Simulate the app transition finishing - mController.mAppTransitionListener.onAppTransitionStartingLocked(false, false, 0, 0, 0); + mController.mAppTransitionListener.onAppTransitionStartingLocked(0, 0); verify(mAnimationCallbacks).onAnimationFinished(REORDER_KEEP_IN_PLACE, false); } diff --git a/services/tests/wmtests/src/com/android/server/wm/SyncEngineTests.java b/services/tests/wmtests/src/com/android/server/wm/SyncEngineTests.java index 420ea8e63562..d3aa073c84d8 100644 --- a/services/tests/wmtests/src/com/android/server/wm/SyncEngineTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/SyncEngineTests.java @@ -16,13 +16,18 @@ package com.android.server.wm; +import static android.view.WindowManager.LayoutParams.TYPE_BASE_APPLICATION; + import static com.android.dx.mockito.inline.extended.ExtendedMockito.mock; import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn; import static com.android.dx.mockito.inline.extended.ExtendedMockito.times; import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify; +import static com.android.server.wm.BLASTSyncEngine.METHOD_BLAST; +import static com.android.server.wm.BLASTSyncEngine.METHOD_NONE; import static com.android.server.wm.WindowContainer.POSITION_BOTTOM; import static com.android.server.wm.WindowContainer.POSITION_TOP; import static com.android.server.wm.WindowContainer.SYNC_STATE_NONE; +import static com.android.server.wm.WindowState.BLAST_TIMEOUT_DURATION; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -67,7 +72,7 @@ public class SyncEngineTests extends WindowTestsBase { BLASTSyncEngine.TransactionReadyListener listener = mock( BLASTSyncEngine.TransactionReadyListener.class); - int id = bse.startSyncSet(listener); + int id = startSyncSet(bse, listener); bse.addToSyncSet(id, mockWC); // Make sure a traversal is requested verify(mWm.mWindowPlacerLocked, times(1)).requestTraversal(); @@ -95,7 +100,7 @@ public class SyncEngineTests extends WindowTestsBase { BLASTSyncEngine.TransactionReadyListener listener = mock( BLASTSyncEngine.TransactionReadyListener.class); - int id = bse.startSyncSet(listener); + int id = startSyncSet(bse, listener); bse.addToSyncSet(id, mockWC); bse.setReady(id); // Make sure traversals requested (one for add and another for setReady) @@ -119,7 +124,7 @@ public class SyncEngineTests extends WindowTestsBase { BLASTSyncEngine.TransactionReadyListener listener = mock( BLASTSyncEngine.TransactionReadyListener.class); - int id = bse.startSyncSet(listener); + int id = startSyncSet(bse, listener); bse.addToSyncSet(id, mockWC); bse.setReady(id); // Make sure traversals requested (one for add and another for setReady) @@ -147,7 +152,7 @@ public class SyncEngineTests extends WindowTestsBase { BLASTSyncEngine.TransactionReadyListener listener = mock( BLASTSyncEngine.TransactionReadyListener.class); - int id = bse.startSyncSet(listener); + int id = startSyncSet(bse, listener); bse.addToSyncSet(id, parentWC); bse.setReady(id); bse.onSurfacePlacement(); @@ -180,7 +185,7 @@ public class SyncEngineTests extends WindowTestsBase { BLASTSyncEngine.TransactionReadyListener listener = mock( BLASTSyncEngine.TransactionReadyListener.class); - int id = bse.startSyncSet(listener); + int id = startSyncSet(bse, listener); bse.addToSyncSet(id, parentWC); bse.setReady(id); bse.onSurfacePlacement(); @@ -211,7 +216,7 @@ public class SyncEngineTests extends WindowTestsBase { BLASTSyncEngine.TransactionReadyListener listener = mock( BLASTSyncEngine.TransactionReadyListener.class); - int id = bse.startSyncSet(listener); + int id = startSyncSet(bse, listener); bse.addToSyncSet(id, parentWC); bse.setReady(id); bse.onSurfacePlacement(); @@ -243,7 +248,7 @@ public class SyncEngineTests extends WindowTestsBase { BLASTSyncEngine.TransactionReadyListener listener = mock( BLASTSyncEngine.TransactionReadyListener.class); - int id = bse.startSyncSet(listener); + int id = startSyncSet(bse, listener); bse.addToSyncSet(id, parentWC); bse.setReady(id); bse.onSurfacePlacement(); @@ -278,7 +283,7 @@ public class SyncEngineTests extends WindowTestsBase { BLASTSyncEngine.TransactionReadyListener listener = mock( BLASTSyncEngine.TransactionReadyListener.class); - int id = bse.startSyncSet(listener); + int id = startSyncSet(bse, listener); bse.addToSyncSet(id, parentWC); bse.setReady(id); bse.onSurfacePlacement(); @@ -317,7 +322,7 @@ public class SyncEngineTests extends WindowTestsBase { BLASTSyncEngine.TransactionReadyListener listener = mock( BLASTSyncEngine.TransactionReadyListener.class); - int id = bse.startSyncSet(listener); + int id = startSyncSet(bse, listener); bse.addToSyncSet(id, parentWC); final BLASTSyncEngine.SyncGroup syncGroup = parentWC.mSyncGroup; bse.setReady(id); @@ -350,6 +355,33 @@ public class SyncEngineTests extends WindowTestsBase { assertEquals(SYNC_STATE_NONE, botChildWC.mSyncState); } + @Test + public void testNonBlastMethod() { + mAppWindow = createWindow(null, TYPE_BASE_APPLICATION, "mAppWindow"); + + final BLASTSyncEngine bse = createTestBLASTSyncEngine(); + + BLASTSyncEngine.TransactionReadyListener listener = mock( + BLASTSyncEngine.TransactionReadyListener.class); + + int id = startSyncSet(bse, listener, METHOD_NONE); + bse.addToSyncSet(id, mAppWindow.mToken); + mAppWindow.prepareSync(); + assertFalse(mAppWindow.shouldSyncWithBuffers()); + + mAppWindow.removeImmediately(); + } + + static int startSyncSet(BLASTSyncEngine engine, + BLASTSyncEngine.TransactionReadyListener listener) { + return startSyncSet(engine, listener, METHOD_BLAST); + } + + static int startSyncSet(BLASTSyncEngine engine, + BLASTSyncEngine.TransactionReadyListener listener, int method) { + return engine.startSyncSet(listener, BLAST_TIMEOUT_DURATION, "", method); + } + static class TestWindowContainer extends WindowContainer { final boolean mWaiter; boolean mVisibleRequested = true; diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskFragmentOrganizerControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/TaskFragmentOrganizerControllerTest.java index da72030b313d..9274eb3f1490 100644 --- a/services/tests/wmtests/src/com/android/server/wm/TaskFragmentOrganizerControllerTest.java +++ b/services/tests/wmtests/src/com/android/server/wm/TaskFragmentOrganizerControllerTest.java @@ -25,6 +25,7 @@ import static android.window.WindowContainerTransaction.HierarchyOp.HIERARCHY_OP import static android.window.WindowContainerTransaction.HierarchyOp.HIERARCHY_OP_TYPE_SET_ADJACENT_TASK_FRAGMENTS; import static android.window.WindowContainerTransaction.HierarchyOp.HIERARCHY_OP_TYPE_START_ACTIVITY_IN_TASK_FRAGMENT; +import static com.android.dx.mockito.inline.extended.ExtendedMockito.doNothing; import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn; import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn; import static com.android.server.wm.TaskFragment.EMBEDDING_ALLOWED; @@ -46,7 +47,6 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; -import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -65,6 +65,7 @@ import android.window.TaskFragmentCreationParams; import android.window.TaskFragmentInfo; import android.window.TaskFragmentOrganizer; import android.window.TaskFragmentOrganizerToken; +import android.window.TaskFragmentTransaction; import android.window.WindowContainerToken; import android.window.WindowContainerTransaction; import android.window.WindowContainerTransactionCallback; @@ -90,6 +91,7 @@ public class TaskFragmentOrganizerControllerTest extends WindowTestsBase { private TaskFragmentOrganizerController mController; private WindowOrganizerController mWindowOrganizerController; + private TransitionController mTransitionController; private TaskFragmentOrganizer mOrganizer; private TaskFragmentOrganizerToken mOrganizerToken; private ITaskFragmentOrganizer mIOrganizer; @@ -107,9 +109,10 @@ public class TaskFragmentOrganizerControllerTest extends WindowTestsBase { private Task mTask; @Before - public void setup() { + public void setup() throws RemoteException { MockitoAnnotations.initMocks(this); mWindowOrganizerController = mAtm.mWindowOrganizerController; + mTransitionController = mWindowOrganizerController.mTransitionController; mController = mWindowOrganizerController.mTaskFragmentOrganizerController; mOrganizer = new TaskFragmentOrganizer(Runnable::run); mOrganizerToken = mOrganizer.getOrganizerToken(); @@ -128,11 +131,16 @@ public class TaskFragmentOrganizerControllerTest extends WindowTestsBase { spyOn(mController); spyOn(mOrganizer); spyOn(mTaskFragment); + spyOn(mWindowOrganizerController); + spyOn(mTransitionController); doReturn(mIOrganizer).when(mTaskFragment).getTaskFragmentOrganizer(); doReturn(mTaskFragmentInfo).when(mTaskFragment).getTaskFragmentInfo(); doReturn(new SurfaceControl()).when(mTaskFragment).getSurfaceControl(); doReturn(mFragmentToken).when(mTaskFragment).getFragmentToken(); doReturn(new Configuration()).when(mTaskFragmentInfo).getConfiguration(); + + // To prevent it from calling the real server. + doNothing().when(mOrganizer).onTransactionHandled(any(), any()); } @Test @@ -866,7 +874,7 @@ public class TaskFragmentOrganizerControllerTest extends WindowTestsBase { assertFalse(parentTask.shouldBeVisible(null)); // Verify the info changed callback still occurred despite the task being invisible - reset(mOrganizer); + clearInvocations(mOrganizer); mController.onTaskFragmentInfoChanged(mIOrganizer, taskFragment); mController.dispatchPendingEvents(); verify(mOrganizer).onTaskFragmentInfoChanged(any(), any()); @@ -899,7 +907,7 @@ public class TaskFragmentOrganizerControllerTest extends WindowTestsBase { verify(mOrganizer).onTaskFragmentInfoChanged(any(), any()); // Verify the info changed callback is not called when the task is invisible - reset(mOrganizer); + clearInvocations(mOrganizer); doReturn(false).when(task).shouldBeVisible(any()); mController.onTaskFragmentInfoChanged(mIOrganizer, taskFragment); mController.dispatchPendingEvents(); @@ -1092,6 +1100,40 @@ public class TaskFragmentOrganizerControllerTest extends WindowTestsBase { .that(mTaskFragment.getBounds()).isEqualTo(task.getBounds()); } + @Test + public void testOnTransactionReady_invokeOnTransactionHandled() { + mController.registerOrganizer(mIOrganizer); + final TaskFragmentTransaction transaction = new TaskFragmentTransaction(); + mOrganizer.onTransactionReady(transaction); + + // Organizer should always trigger #onTransactionHandled when receives #onTransactionReady + verify(mOrganizer).onTransactionHandled(eq(transaction.getTransactionToken()), any()); + verify(mOrganizer, never()).applyTransaction(any()); + } + + @Test + public void testDispatchTransaction_deferTransitionReady() { + mController.registerOrganizer(mIOrganizer); + setupMockParent(mTaskFragment, mTask); + final ArgumentCaptor<IBinder> tokenCaptor = ArgumentCaptor.forClass(IBinder.class); + final ArgumentCaptor<WindowContainerTransaction> wctCaptor = + ArgumentCaptor.forClass(WindowContainerTransaction.class); + doReturn(true).when(mTransitionController).isCollecting(); + + mController.onTaskFragmentAppeared(mTaskFragment.getTaskFragmentOrganizer(), mTaskFragment); + mController.dispatchPendingEvents(); + + // Defer transition when send TaskFragment transaction during transition collection. + verify(mTransitionController).deferTransitionReady(); + verify(mOrganizer).onTransactionHandled(tokenCaptor.capture(), wctCaptor.capture()); + + mController.onTransactionHandled(mIOrganizer, tokenCaptor.getValue(), wctCaptor.getValue()); + + // Apply the organizer change and continue transition. + verify(mWindowOrganizerController).applyTransaction(wctCaptor.getValue()); + verify(mTransitionController).continueTransitionReady(); + } + /** * Creates a {@link TaskFragment} with the {@link WindowContainerTransaction}. Calls * {@link WindowOrganizerController#applyTransaction} to apply the transaction, diff --git a/services/tests/wmtests/src/com/android/server/wm/TestDisplayContent.java b/services/tests/wmtests/src/com/android/server/wm/TestDisplayContent.java index 1e64e469fe7f..f5304d00faab 100644 --- a/services/tests/wmtests/src/com/android/server/wm/TestDisplayContent.java +++ b/services/tests/wmtests/src/com/android/server/wm/TestDisplayContent.java @@ -18,6 +18,13 @@ package com.android.server.wm; import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN; import static android.view.DisplayAdjustments.DEFAULT_DISPLAY_ADJUSTMENTS; +import static android.view.InsetsState.ITYPE_BOTTOM_DISPLAY_CUTOUT; +import static android.view.InsetsState.ITYPE_CLIMATE_BAR; +import static android.view.InsetsState.ITYPE_LEFT_DISPLAY_CUTOUT; +import static android.view.InsetsState.ITYPE_NAVIGATION_BAR; +import static android.view.InsetsState.ITYPE_RIGHT_DISPLAY_CUTOUT; +import static android.view.InsetsState.ITYPE_STATUS_BAR; +import static android.view.InsetsState.ITYPE_TOP_DISPLAY_CUTOUT; import static android.view.WindowManagerPolicyConstants.NAV_BAR_BOTTOM; import static com.android.dx.mockito.inline.extended.ExtendedMockito.any; @@ -26,12 +33,9 @@ import static com.android.dx.mockito.inline.extended.ExtendedMockito.anyInt; import static com.android.dx.mockito.inline.extended.ExtendedMockito.doAnswer; import static com.android.dx.mockito.inline.extended.ExtendedMockito.doNothing; import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn; +import static com.android.dx.mockito.inline.extended.ExtendedMockito.eq; import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.Mockito.doReturn; - import android.annotation.Nullable; import android.content.Context; import android.content.res.Configuration; @@ -43,6 +47,7 @@ import android.util.DisplayMetrics; import android.view.Display; import android.view.DisplayCutout; import android.view.DisplayInfo; +import android.view.WindowInsets; import com.android.server.wm.DisplayWindowSettings.SettingsProvider.SettingsEntry; @@ -204,7 +209,26 @@ class TestDisplayContent extends DisplayContent { doReturn(true).when(newDisplay).supportsSystemDecorations(); doReturn(true).when(displayPolicy).hasNavigationBar(); doReturn(NAV_BAR_BOTTOM).when(displayPolicy).navigationBarPosition(anyInt()); - doReturn(20).when(displayPolicy).getNavigationBarHeight(anyInt()); + doReturn(Insets.of(0, 0, 0, 20)).when(displayPolicy).getInsets(any(), + eq(WindowInsets.Type.displayCutout() | WindowInsets.Type.navigationBars())); + doReturn(Insets.of(0, 20, 0, 20)).when(displayPolicy).getInsets(any(), + eq(WindowInsets.Type.displayCutout() | WindowInsets.Type.navigationBars() + | WindowInsets.Type.statusBars())); + final int[] nonDecorTypes = new int[]{ + ITYPE_TOP_DISPLAY_CUTOUT, ITYPE_RIGHT_DISPLAY_CUTOUT, + ITYPE_BOTTOM_DISPLAY_CUTOUT, ITYPE_LEFT_DISPLAY_CUTOUT, ITYPE_NAVIGATION_BAR + }; + doReturn(Insets.of(0, 0, 0, 20)).when(displayPolicy).getInsetsWithInternalTypes( + any(), + eq(nonDecorTypes)); + final int[] stableTypes = new int[]{ + ITYPE_TOP_DISPLAY_CUTOUT, ITYPE_RIGHT_DISPLAY_CUTOUT, + ITYPE_BOTTOM_DISPLAY_CUTOUT, ITYPE_LEFT_DISPLAY_CUTOUT, + ITYPE_NAVIGATION_BAR, ITYPE_STATUS_BAR, ITYPE_CLIMATE_BAR + }; + doReturn(Insets.of(0, 20, 0, 20)).when(displayPolicy).getInsetsWithInternalTypes( + any(), + eq(stableTypes)); } else { doReturn(false).when(displayPolicy).hasNavigationBar(); doReturn(false).when(displayPolicy).hasStatusBar(); diff --git a/services/tests/wmtests/src/com/android/server/wm/TestWindowManagerPolicy.java b/services/tests/wmtests/src/com/android/server/wm/TestWindowManagerPolicy.java index d2cb7ba5d311..13da1543cfb8 100644 --- a/services/tests/wmtests/src/com/android/server/wm/TestWindowManagerPolicy.java +++ b/services/tests/wmtests/src/com/android/server/wm/TestWindowManagerPolicy.java @@ -310,11 +310,11 @@ class TestWindowManagerPolicy implements WindowManagerPolicy { } @Override - public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) { + public void startKeyguardExitAnimation(long startTime) { } @Override - public int applyKeyguardOcclusionChange(boolean keyguardOccludingStarted) { + public int applyKeyguardOcclusionChange(boolean notify) { return 0; } diff --git a/services/tests/wmtests/src/com/android/server/wm/TransitionTests.java b/services/tests/wmtests/src/com/android/server/wm/TransitionTests.java index 85ac7bd96854..55ca5fa65fce 100644 --- a/services/tests/wmtests/src/com/android/server/wm/TransitionTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/TransitionTests.java @@ -57,6 +57,7 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import android.content.res.Configuration; import android.graphics.Point; import android.graphics.Rect; import android.os.IBinder; @@ -73,6 +74,7 @@ import android.window.RemoteTransition; import android.window.TaskFragmentOrganizer; import android.window.TransitionInfo; +import androidx.annotation.NonNull; import androidx.test.filters.SmallTest; import org.junit.Test; @@ -1117,6 +1119,36 @@ public class TransitionTests extends WindowTestsBase { assertTrue(targets.contains(activity)); } + @Test + public void testTransitionVisibleChange() { + registerTestTransitionPlayer(); + final ActivityRecord app = createActivityRecord(mDisplayContent); + final Transition transition = new Transition(TRANSIT_OPEN, 0 /* flags */, + app.mTransitionController, mWm.mSyncEngine); + app.mTransitionController.moveToCollecting(transition, BLASTSyncEngine.METHOD_NONE); + final ArrayList<WindowContainer> freezeCalls = new ArrayList<>(); + transition.setContainerFreezer(new Transition.IContainerFreezer() { + @Override + public boolean freeze(@NonNull WindowContainer wc, @NonNull Rect bounds) { + freezeCalls.add(wc); + return true; + } + + @Override + public void cleanUp(SurfaceControl.Transaction t) { + } + }); + final Task task = app.getTask(); + transition.collect(task); + final Rect bounds = new Rect(task.getBounds()); + Configuration c = new Configuration(task.getRequestedOverrideConfiguration()); + bounds.inset(10, 10); + c.windowConfiguration.setBounds(bounds); + task.onRequestedOverrideConfigurationChanged(c); + assertTrue(freezeCalls.contains(task)); + transition.abort(); + } + private static void makeTaskOrganized(Task... tasks) { final ITaskOrganizer organizer = mock(ITaskOrganizer.class); for (Task t : tasks) { diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowOrganizerTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowOrganizerTests.java index a62625cea46c..3b64c512ca8f 100644 --- a/services/tests/wmtests/src/com/android/server/wm/WindowOrganizerTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/WindowOrganizerTests.java @@ -42,8 +42,10 @@ import static com.android.dx.mockito.inline.extended.ExtendedMockito.times; import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify; import static com.android.dx.mockito.inline.extended.ExtendedMockito.when; import static com.android.server.wm.ActivityRecord.State.RESUMED; +import static com.android.server.wm.BLASTSyncEngine.METHOD_BLAST; import static com.android.server.wm.WindowContainer.POSITION_TOP; import static com.android.server.wm.WindowContainer.SYNC_STATE_READY; +import static com.android.server.wm.WindowState.BLAST_TIMEOUT_DURATION; import static com.google.common.truth.Truth.assertThat; @@ -997,7 +999,7 @@ public class WindowOrganizerTests extends WindowTestsBase { BLASTSyncEngine.TransactionReadyListener transactionListener = mock(BLASTSyncEngine.TransactionReadyListener.class); - int id = bse.startSyncSet(transactionListener); + int id = bse.startSyncSet(transactionListener, BLAST_TIMEOUT_DURATION, "", METHOD_BLAST); bse.addToSyncSet(id, task); bse.setReady(id); bse.onSurfacePlacement(); diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java b/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java index 564d3ca2a1c9..6785979e2065 100644 --- a/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java +++ b/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java @@ -331,6 +331,10 @@ class WindowTestsBase extends SystemServiceTestsBase { mNavBarWindow.mAttrs.gravity = Gravity.BOTTOM; mNavBarWindow.mAttrs.paramsForRotation = new WindowManager.LayoutParams[4]; mNavBarWindow.mAttrs.setFitInsetsTypes(0); + mNavBarWindow.mAttrs.layoutInDisplayCutoutMode = + LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS; + mNavBarWindow.mAttrs.privateFlags |= + WindowManager.LayoutParams.PRIVATE_FLAG_LAYOUT_SIZE_EXTENDED_BY_CUTOUT; for (int rot = Surface.ROTATION_0; rot <= Surface.ROTATION_270; rot++) { mNavBarWindow.mAttrs.paramsForRotation[rot] = getNavBarLayoutParamsForRotation(rot); @@ -381,6 +385,9 @@ class WindowTestsBase extends SystemServiceTestsBase { lp.height = height; lp.gravity = gravity; lp.setFitInsetsTypes(0); + lp.privateFlags |= + WindowManager.LayoutParams.PRIVATE_FLAG_LAYOUT_SIZE_EXTENDED_BY_CUTOUT; + lp.layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS; return lp; } diff --git a/tests/testables/tests/AndroidManifest.xml b/tests/testables/tests/AndroidManifest.xml index 2bfb04fdb765..1731f6be4bf2 100644 --- a/tests/testables/tests/AndroidManifest.xml +++ b/tests/testables/tests/AndroidManifest.xml @@ -21,7 +21,7 @@ <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" /> <uses-permission android:name="android.permission.MANAGE_USERS" /> - <application android:debuggable="true"> + <application android:debuggable="true" android:testOnly="true"> <uses-library android:name="android.test.runner" /> </application> diff --git a/tests/testables/tests/AndroidTest.xml b/tests/testables/tests/AndroidTest.xml new file mode 100644 index 000000000000..de1165fca1a2 --- /dev/null +++ b/tests/testables/tests/AndroidTest.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + ~ 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. + --> +<configuration description="Runs Testable Tests."> + <option name="test-tag" value="TestablesTests" /> + <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller"> + <option name="cleanup-apks" value="true" /> + <option name="install-arg" value="-t" /> + <option name="test-file-name" value="TestablesTests.apk" /> + </target_preparer> + <test class="com.android.tradefed.testtype.AndroidJUnitTest"> + <option name="package" value="com.android.testables"/> + </test> +</configuration>
\ No newline at end of file diff --git a/tools/aapt2/dump/DumpManifest.cpp b/tools/aapt2/dump/DumpManifest.cpp index 39ac24b29f35..b3165d320e9b 100644 --- a/tools/aapt2/dump/DumpManifest.cpp +++ b/tools/aapt2/dump/DumpManifest.cpp @@ -1981,10 +1981,11 @@ class Action : public ManifestExtractor::Element { if (ElementCast<Activity>(parent_stack[1])) { // Detects the presence of a particular type of activity. Activity* activity = ElementCast<Activity>(parent_stack[1]); - auto map = std::map<std::string, std::string>({ - { "android.intent.action.MAIN" , "main" }, - { "android.intent.action.VIDEO_CAMERA" , "camera" }, - { "android.intent.action.STILL_IMAGE_CAMERA_SECURE" , "camera-secure" }, + static const auto map = std::map<std::string, std::string>({ + {"android.intent.action.MAIN", "main"}, + {"android.media.action.VIDEO_CAMERA", "camera"}, + {"android.media.action.STILL_IMAGE_CAMERA", "camera"}, + {"android.media.action.STILL_IMAGE_CAMERA_SECURE", "camera-secure"}, }); auto entry = map.find(action); @@ -2735,10 +2736,9 @@ bool ManifestExtractor::Extract(android::IDiagnostics* diag) { auto it = apk_->GetFileCollection()->Iterator(); while (it->HasNext()) { auto file_path = it->Next()->GetSource().path; - size_t pos = file_path.find("lib/"); - if (pos != std::string::npos) { - file_path = file_path.substr(pos + 4); - pos = file_path.find('/'); + if (file_path.starts_with("lib/")) { + file_path = file_path.substr(4); + size_t pos = file_path.find('/'); if (pos != std::string::npos) { file_path = file_path.substr(0, pos); } diff --git a/tools/aapt2/integration-tests/DumpTest/components.apk b/tools/aapt2/integration-tests/DumpTest/components.apk Binary files differindex deb55ea6fda3..a34ec83f3dae 100644 --- a/tools/aapt2/integration-tests/DumpTest/components.apk +++ b/tools/aapt2/integration-tests/DumpTest/components.apk diff --git a/tools/aapt2/integration-tests/DumpTest/components_full_proto.txt b/tools/aapt2/integration-tests/DumpTest/components_full_proto.txt index bd7673616ddc..8e733a5db034 100644 --- a/tools/aapt2/integration-tests/DumpTest/components_full_proto.txt +++ b/tools/aapt2/integration-tests/DumpTest/components_full_proto.txt @@ -1677,7 +1677,7 @@ xml_files { attribute { namespace_uri: "http://schemas.android.com/apk/res/android" name: "name" - value: "android.intent.action.VIDEO_CAMERA" + value: "android.media.action.VIDEO_CAMERA" resource_id: 16842755 } } @@ -1691,7 +1691,7 @@ xml_files { attribute { namespace_uri: "http://schemas.android.com/apk/res/android" name: "name" - value: "android.intent.action.STILL_IMAGE_CAMERA_SECURE" + value: "android.media.action.STILL_IMAGE_CAMERA_SECURE" resource_id: 16842755 } } diff --git a/tools/lint/OWNERS b/tools/lint/OWNERS index 7c0451900e32..2c526a1e239e 100644 --- a/tools/lint/OWNERS +++ b/tools/lint/OWNERS @@ -2,4 +2,5 @@ brufino@google.com jsharkey@google.com per-file *CallingSettingsNonUserGetterMethods* = file:/packages/SettingsProvider/OWNERS +per-file *RegisterReceiverFlagDetector* = jacobhobbie@google.com |