diff options
791 files changed, 25313 insertions, 12588 deletions
diff --git a/Android.bp b/Android.bp index 3d0188a3918d..2740ccc9a803 100644 --- a/Android.bp +++ b/Android.bp @@ -102,6 +102,7 @@ filegroup { ":android.hardware.keymaster-V4-java-source", ":android.hardware.security.keymint-V3-java-source", ":android.hardware.security.secureclock-V1-java-source", + ":android.hardware.thermal-V1-java-source", ":android.hardware.tv.tuner-V2-java-source", ":android.security.apc-java-source", ":android.security.authorization-java-source", @@ -404,6 +405,7 @@ java_defaults { "framework-permission-aidl-java", "spatializer-aidl-java", "audiopolicy-types-aidl-java", + "sounddose-aidl-java", ], } diff --git a/apct-tests/perftests/settingsprovider/OWNERS b/apct-tests/perftests/settingsprovider/OWNERS new file mode 100644 index 000000000000..86ae5818e91c --- /dev/null +++ b/apct-tests/perftests/settingsprovider/OWNERS @@ -0,0 +1 @@ +include /PACKAGE_MANAGER_OWNERS diff --git a/apex/jobscheduler/framework/java/android/app/AlarmManager.java b/apex/jobscheduler/framework/java/android/app/AlarmManager.java index dade7c3d84a8..53e81c789d2b 100644 --- a/apex/jobscheduler/framework/java/android/app/AlarmManager.java +++ b/apex/jobscheduler/framework/java/android/app/AlarmManager.java @@ -27,7 +27,6 @@ import android.annotation.SystemApi; import android.annotation.SystemService; import android.annotation.TestApi; import android.compat.annotation.ChangeId; -import android.compat.annotation.Disabled; import android.compat.annotation.EnabledSince; import android.compat.annotation.UnsupportedAppUsage; import android.content.Context; @@ -285,11 +284,10 @@ public class AlarmManager { * The permission {@link Manifest.permission#SCHEDULE_EXACT_ALARM} will be denied, unless the * user explicitly allows it from Settings. * - * TODO (b/226439802): Either enable it in the next SDK or replace it with a better alternative. * @hide */ @ChangeId - @Disabled + @EnabledSince(targetSdkVersion = Build.VERSION_CODES.TIRAMISU) public static final long SCHEDULE_EXACT_ALARM_DENIED_BY_DEFAULT = 226439802L; @UnsupportedAppUsage diff --git a/apex/jobscheduler/framework/java/android/app/job/JobService.java b/apex/jobscheduler/framework/java/android/app/job/JobService.java index e88e979460b8..62799598cf6a 100644 --- a/apex/jobscheduler/framework/java/android/app/job/JobService.java +++ b/apex/jobscheduler/framework/java/android/app/job/JobService.java @@ -416,6 +416,11 @@ public abstract class JobService extends Service { * JobScheduler will not remember this notification after the job has finished running, * so apps must call this every time the job is started (if required or desired). * + * <p> + * If separate jobs use the same notification ID with this API, the most recently provided + * notification will be shown to the user, and the + * {@code jobEndNotificationPolicy} of the last job to stop will be applied. + * * @param params The parameters identifying this job, as supplied to * the job in the {@link #onStartJob(JobParameters)} callback. * @param notificationId The ID for this notification, as per diff --git a/apex/jobscheduler/service/java/com/android/server/job/JobConcurrencyManager.java b/apex/jobscheduler/service/java/com/android/server/job/JobConcurrencyManager.java index 16201b29571e..30986dde6b91 100644 --- a/apex/jobscheduler/service/java/com/android/server/job/JobConcurrencyManager.java +++ b/apex/jobscheduler/service/java/com/android/server/job/JobConcurrencyManager.java @@ -193,6 +193,7 @@ class JobConcurrencyManager { } private final Object mLock; + private final JobNotificationCoordinator mNotificationCoordinator; private final JobSchedulerService mService; private final Context mContext; private final Handler mHandler; @@ -418,6 +419,7 @@ class JobConcurrencyManager { mLock = mService.getLock(); mContext = service.getTestableContext(); mInjector = injector; + mNotificationCoordinator = new JobNotificationCoordinator(); mHandler = JobSchedulerBackgroundThread.getHandler(); @@ -451,7 +453,8 @@ class JobConcurrencyManager { ServiceManager.getService(BatteryStats.SERVICE_NAME)); for (int i = 0; i < STANDARD_CONCURRENCY_LIMIT; i++) { mIdleContexts.add( - mInjector.createJobServiceContext(mService, this, batteryStats, + mInjector.createJobServiceContext(mService, this, + mNotificationCoordinator, batteryStats, mService.mJobPackageTracker, mContext.getMainLooper())); } } @@ -1687,7 +1690,7 @@ class JobConcurrencyManager { @NonNull private JobServiceContext createNewJobServiceContext() { - return mInjector.createJobServiceContext(mService, this, + return mInjector.createJobServiceContext(mService, this, mNotificationCoordinator, IBatteryStats.Stub.asInterface( ServiceManager.getService(BatteryStats.SERVICE_NAME)), mService.mJobPackageTracker, mContext.getMainLooper()); @@ -2612,10 +2615,11 @@ class JobConcurrencyManager { static class Injector { @NonNull JobServiceContext createJobServiceContext(JobSchedulerService service, - JobConcurrencyManager concurrencyManager, IBatteryStats batteryStats, + JobConcurrencyManager concurrencyManager, + JobNotificationCoordinator notificationCoordinator, IBatteryStats batteryStats, JobPackageTracker tracker, Looper looper) { - return new JobServiceContext(service, concurrencyManager, batteryStats, - tracker, looper); + return new JobServiceContext(service, concurrencyManager, notificationCoordinator, + batteryStats, tracker, looper); } } } diff --git a/apex/jobscheduler/service/java/com/android/server/job/JobNotificationCoordinator.java b/apex/jobscheduler/service/java/com/android/server/job/JobNotificationCoordinator.java new file mode 100644 index 000000000000..ce5ade5531ec --- /dev/null +++ b/apex/jobscheduler/service/java/com/android/server/job/JobNotificationCoordinator.java @@ -0,0 +1,144 @@ +/* + * 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.job; + +import static android.app.job.JobService.JOB_END_NOTIFICATION_POLICY_DETACH; +import static android.app.job.JobService.JOB_END_NOTIFICATION_POLICY_REMOVE; + +import android.annotation.NonNull; +import android.app.Notification; +import android.app.job.JobService; +import android.content.pm.UserPackage; +import android.os.UserHandle; +import android.util.ArrayMap; +import android.util.ArraySet; +import android.util.Slog; +import android.util.SparseSetArray; + +import com.android.server.LocalServices; +import com.android.server.notification.NotificationManagerInternal; + +class JobNotificationCoordinator { + private static final String TAG = "JobNotificationCoordinator"; + + /** + * Mapping of UserPackage -> {notificationId -> List<JobServiceContext>} to track which jobs + * are associated with each app's notifications. + */ + private final ArrayMap<UserPackage, SparseSetArray<JobServiceContext>> mCurrentAssociations = + new ArrayMap<>(); + /** + * Set of NotificationDetails for each running job. + */ + private final ArrayMap<JobServiceContext, NotificationDetails> mNotificationDetails = + new ArrayMap<>(); + + private static final class NotificationDetails { + @NonNull + public final UserPackage userPackage; + public final int notificationId; + public final int appPid; + public final int appUid; + @JobService.JobEndNotificationPolicy + public final int jobEndNotificationPolicy; + + NotificationDetails(@NonNull UserPackage userPackage, int appPid, int appUid, + int notificationId, + @JobService.JobEndNotificationPolicy int jobEndNotificationPolicy) { + this.userPackage = userPackage; + this.notificationId = notificationId; + this.appPid = appPid; + this.appUid = appUid; + this.jobEndNotificationPolicy = jobEndNotificationPolicy; + } + } + + private final NotificationManagerInternal mNotificationManagerInternal; + + JobNotificationCoordinator() { + mNotificationManagerInternal = LocalServices.getService(NotificationManagerInternal.class); + } + + void enqueueNotification(@NonNull JobServiceContext hostingContext, @NonNull String packageName, + int callingPid, int callingUid, int notificationId, @NonNull Notification notification, + @JobService.JobEndNotificationPolicy int jobEndNotificationPolicy) { + validateNotification(packageName, callingUid, notification, jobEndNotificationPolicy); + final NotificationDetails oldDetails = mNotificationDetails.get(hostingContext); + if (oldDetails != null && oldDetails.notificationId != notificationId) { + // App is switching notification IDs. Remove association with the old one. + removeNotificationAssociation(hostingContext); + } + final int userId = UserHandle.getUserId(callingUid); + // TODO(260848384): ensure apps can't cancel the notification for user-initiated job + // eg., by calling NotificationManager.cancel/All or deleting the notification channel + mNotificationManagerInternal.enqueueNotification( + packageName, packageName, callingUid, callingPid, /* tag */ null, + notificationId, notification, userId); + final UserPackage userPackage = UserPackage.of(userId, packageName); + final NotificationDetails details = new NotificationDetails( + userPackage, callingPid, callingUid, notificationId, jobEndNotificationPolicy); + SparseSetArray<JobServiceContext> appNotifications = mCurrentAssociations.get(userPackage); + if (appNotifications == null) { + appNotifications = new SparseSetArray<>(); + mCurrentAssociations.put(userPackage, appNotifications); + } + appNotifications.add(notificationId, hostingContext); + mNotificationDetails.put(hostingContext, details); + } + + void removeNotificationAssociation(@NonNull JobServiceContext hostingContext) { + final NotificationDetails details = mNotificationDetails.remove(hostingContext); + if (details == null) { + return; + } + final SparseSetArray<JobServiceContext> associations = + mCurrentAssociations.get(details.userPackage); + if (associations == null || !associations.remove(details.notificationId, hostingContext)) { + Slog.wtf(TAG, "Association data structures not in sync"); + return; + } + ArraySet<JobServiceContext> associatedContexts = associations.get(details.notificationId); + if (associatedContexts == null || associatedContexts.isEmpty()) { + // No more jobs using this notification. Apply the final job stop policy. + if (details.jobEndNotificationPolicy == JOB_END_NOTIFICATION_POLICY_REMOVE) { + final String packageName = details.userPackage.packageName; + mNotificationManagerInternal.cancelNotification( + packageName, packageName, details.appUid, details.appPid, /* tag */ null, + details.notificationId, UserHandle.getUserId(details.appUid)); + } + } + } + + private void validateNotification(@NonNull String packageName, int callingUid, + @NonNull Notification notification, + @JobService.JobEndNotificationPolicy int jobEndNotificationPolicy) { + if (notification == null) { + throw new NullPointerException("notification"); + } + if (notification.getSmallIcon() == null) { + throw new IllegalArgumentException("small icon required"); + } + if (null == mNotificationManagerInternal.getNotificationChannel( + packageName, callingUid, notification.getChannelId())) { + throw new IllegalArgumentException("invalid notification channel"); + } + if (jobEndNotificationPolicy != JOB_END_NOTIFICATION_POLICY_DETACH + && jobEndNotificationPolicy != JOB_END_NOTIFICATION_POLICY_REMOVE) { + throw new IllegalArgumentException("invalid job end notification policy"); + } + } +} diff --git a/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java b/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java index ad6eff07b977..6f58c7ce626c 100644 --- a/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java +++ b/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java @@ -266,6 +266,8 @@ public class JobSchedulerService extends com.android.server.SystemService private final List<RestrictingController> mRestrictiveControllers; /** Need direct access to this for testing. */ private final StorageController mStorageController; + /** Needed to get estimated transfer time. */ + private final ConnectivityController mConnectivityController; /** Need directly for sending uid state changes */ private final DeviceIdleJobsController mDeviceIdleJobsController; /** Needed to get next estimated launch time. */ @@ -464,6 +466,13 @@ public class JobSchedulerService extends com.android.server.SystemService case Constants.KEY_RUNTIME_MIN_GUARANTEE_MS: case Constants.KEY_RUNTIME_MIN_EJ_GUARANTEE_MS: case Constants.KEY_RUNTIME_MIN_HIGH_PRIORITY_GUARANTEE_MS: + case Constants.KEY_RUNTIME_MIN_DATA_TRANSFER_GUARANTEE_MS: + case Constants.KEY_RUNTIME_DATA_TRANSFER_LIMIT_MS: + case Constants.KEY_RUNTIME_MIN_USER_INITIATED_GUARANTEE_MS: + case Constants.KEY_RUNTIME_USER_INITIATED_LIMIT_MS: + case Constants.KEY_RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_BUFFER_FACTOR: + case Constants.KEY_RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_MS: + case Constants.KEY_RUNTIME_USER_INITIATED_DATA_TRANSFER_LIMIT_MS: if (!runtimeUpdated) { mConstants.updateRuntimeConstantsLocked(); runtimeUpdated = true; @@ -555,6 +564,21 @@ public class JobSchedulerService extends com.android.server.SystemService private static final String KEY_RUNTIME_MIN_EJ_GUARANTEE_MS = "runtime_min_ej_guarantee_ms"; private static final String KEY_RUNTIME_MIN_HIGH_PRIORITY_GUARANTEE_MS = "runtime_min_high_priority_guarantee_ms"; + private static final String KEY_RUNTIME_MIN_DATA_TRANSFER_GUARANTEE_MS = + "runtime_min_data_transfer_guarantee_ms"; + private static final String KEY_RUNTIME_DATA_TRANSFER_LIMIT_MS = + "runtime_data_transfer_limit_ms"; + private static final String KEY_RUNTIME_MIN_USER_INITIATED_GUARANTEE_MS = + "runtime_min_user_initiated_guarantee_ms"; + private static final String KEY_RUNTIME_USER_INITIATED_LIMIT_MS = + "runtime_user_initiated_limit_ms"; + private static final String + KEY_RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_BUFFER_FACTOR = + "runtime_min_user_initiated_data_transfer_guarantee_buffer_factor"; + private static final String KEY_RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_MS = + "runtime_min_user_initiated_data_transfer_guarantee_ms"; + private static final String KEY_RUNTIME_USER_INITIATED_DATA_TRANSFER_LIMIT_MS = + "runtime_user_initiated_data_transfer_limit_ms"; private static final String KEY_PERSIST_IN_SPLIT_FILES = "persist_in_split_files"; @@ -584,6 +608,20 @@ public class JobSchedulerService extends com.android.server.SystemService public static final long DEFAULT_RUNTIME_MIN_EJ_GUARANTEE_MS = 3 * MINUTE_IN_MILLIS; @VisibleForTesting static final long DEFAULT_RUNTIME_MIN_HIGH_PRIORITY_GUARANTEE_MS = 5 * MINUTE_IN_MILLIS; + public static final long DEFAULT_RUNTIME_MIN_DATA_TRANSFER_GUARANTEE_MS = + DEFAULT_RUNTIME_MIN_GUARANTEE_MS; + public static final long DEFAULT_RUNTIME_DATA_TRANSFER_LIMIT_MS = + DEFAULT_RUNTIME_FREE_QUOTA_MAX_LIMIT_MS; + public static final long DEFAULT_RUNTIME_MIN_USER_INITIATED_GUARANTEE_MS = + Math.max(10 * MINUTE_IN_MILLIS, DEFAULT_RUNTIME_MIN_GUARANTEE_MS); + public static final long DEFAULT_RUNTIME_USER_INITIATED_LIMIT_MS = + Math.max(60 * MINUTE_IN_MILLIS, DEFAULT_RUNTIME_FREE_QUOTA_MAX_LIMIT_MS); + public static final float + DEFAULT_RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_BUFFER_FACTOR = 1.35f; + public static final long DEFAULT_RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_MS = + Math.max(10 * MINUTE_IN_MILLIS, DEFAULT_RUNTIME_MIN_USER_INITIATED_GUARANTEE_MS); + public static final long DEFAULT_RUNTIME_USER_INITIATED_DATA_TRANSFER_LIMIT_MS = + Math.max(Long.MAX_VALUE, DEFAULT_RUNTIME_USER_INITIATED_LIMIT_MS); static final boolean DEFAULT_PERSIST_IN_SPLIT_FILES = true; private static final boolean DEFAULT_USE_TARE_POLICY = false; @@ -700,6 +738,49 @@ public class JobSchedulerService extends com.android.server.SystemService DEFAULT_RUNTIME_MIN_HIGH_PRIORITY_GUARANTEE_MS; /** + * The minimum amount of time we try to guarantee normal data transfer jobs will run for. + */ + public long RUNTIME_MIN_DATA_TRANSFER_GUARANTEE_MS = + DEFAULT_RUNTIME_MIN_DATA_TRANSFER_GUARANTEE_MS; + + /** + * The maximum amount of time we will let a normal data transfer job run for. This will only + * apply if there are no other limits that apply to the specific data transfer job. + */ + public long RUNTIME_DATA_TRANSFER_LIMIT_MS = DEFAULT_RUNTIME_DATA_TRANSFER_LIMIT_MS; + + /** + * The minimum amount of time we try to guarantee normal user-initiated jobs will run for. + */ + public long RUNTIME_MIN_USER_INITIATED_GUARANTEE_MS = + DEFAULT_RUNTIME_MIN_USER_INITIATED_GUARANTEE_MS; + + /** + * The maximum amount of time we will let a user-initiated job run for. This will only + * apply if there are no other limits that apply to the specific user-initiated job. + */ + public long RUNTIME_USER_INITIATED_LIMIT_MS = DEFAULT_RUNTIME_USER_INITIATED_LIMIT_MS; + + /** + * A factor to apply to estimated transfer durations for user-initiated data transfer jobs + * so that we give some extra time for unexpected situations. This will be at least 1 and + * so can just be multiplied with the original value to get the final value. + */ + public float RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_BUFFER_FACTOR = + DEFAULT_RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_BUFFER_FACTOR; + + /** + * The minimum amount of time we try to guarantee user-initiated data transfer jobs + * will run for. + */ + public long RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_MS = + DEFAULT_RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_MS; + + /** The maximum amount of time we will let a user-initiated data transfer job run for. */ + public long RUNTIME_USER_INITIATED_DATA_TRANSFER_LIMIT_MS = + DEFAULT_RUNTIME_USER_INITIATED_DATA_TRANSFER_LIMIT_MS; + + /** * Whether to persist jobs in split files (by UID). If false, all persisted jobs will be * saved in a single file. */ @@ -801,7 +882,14 @@ public class JobSchedulerService extends com.android.server.SystemService DeviceConfig.NAMESPACE_JOB_SCHEDULER, KEY_RUNTIME_FREE_QUOTA_MAX_LIMIT_MS, KEY_RUNTIME_MIN_GUARANTEE_MS, KEY_RUNTIME_MIN_EJ_GUARANTEE_MS, - KEY_RUNTIME_MIN_HIGH_PRIORITY_GUARANTEE_MS); + KEY_RUNTIME_MIN_HIGH_PRIORITY_GUARANTEE_MS, + KEY_RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_BUFFER_FACTOR, + KEY_RUNTIME_MIN_DATA_TRANSFER_GUARANTEE_MS, + KEY_RUNTIME_DATA_TRANSFER_LIMIT_MS, + KEY_RUNTIME_MIN_USER_INITIATED_GUARANTEE_MS, + KEY_RUNTIME_USER_INITIATED_LIMIT_MS, + KEY_RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_MS, + KEY_RUNTIME_USER_INITIATED_DATA_TRANSFER_LIMIT_MS); // Make sure min runtime for regular jobs is at least 10 minutes. RUNTIME_MIN_GUARANTEE_MS = Math.max(10 * MINUTE_IN_MILLIS, @@ -819,6 +907,49 @@ public class JobSchedulerService extends com.android.server.SystemService RUNTIME_FREE_QUOTA_MAX_LIMIT_MS = Math.max(RUNTIME_MIN_GUARANTEE_MS, properties.getLong(KEY_RUNTIME_FREE_QUOTA_MAX_LIMIT_MS, DEFAULT_RUNTIME_FREE_QUOTA_MAX_LIMIT_MS)); + // Make sure min runtime is at least as long as regular jobs. + RUNTIME_MIN_DATA_TRANSFER_GUARANTEE_MS = Math.max(RUNTIME_MIN_GUARANTEE_MS, + properties.getLong( + KEY_RUNTIME_MIN_DATA_TRANSFER_GUARANTEE_MS, + DEFAULT_RUNTIME_MIN_DATA_TRANSFER_GUARANTEE_MS)); + // Max limit should be at least the min guarantee AND the free quota. + RUNTIME_DATA_TRANSFER_LIMIT_MS = Math.max(RUNTIME_FREE_QUOTA_MAX_LIMIT_MS, + Math.max(RUNTIME_MIN_DATA_TRANSFER_GUARANTEE_MS, + properties.getLong( + KEY_RUNTIME_DATA_TRANSFER_LIMIT_MS, + DEFAULT_RUNTIME_DATA_TRANSFER_LIMIT_MS))); + // Make sure min runtime is at least as long as regular jobs. + RUNTIME_MIN_USER_INITIATED_GUARANTEE_MS = Math.max(RUNTIME_MIN_GUARANTEE_MS, + properties.getLong( + KEY_RUNTIME_MIN_USER_INITIATED_GUARANTEE_MS, + DEFAULT_RUNTIME_MIN_USER_INITIATED_GUARANTEE_MS)); + // Max limit should be at least the min guarantee AND the free quota. + RUNTIME_USER_INITIATED_LIMIT_MS = Math.max(RUNTIME_FREE_QUOTA_MAX_LIMIT_MS, + Math.max(RUNTIME_MIN_USER_INITIATED_GUARANTEE_MS, + properties.getLong( + KEY_RUNTIME_USER_INITIATED_LIMIT_MS, + DEFAULT_RUNTIME_USER_INITIATED_LIMIT_MS))); + // The buffer factor should be at least 1 (so we don't decrease the time). + RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_BUFFER_FACTOR = Math.max(1, + properties.getFloat( + KEY_RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_BUFFER_FACTOR, + DEFAULT_RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_BUFFER_FACTOR + )); + // Make sure min runtime is at least as long as other user-initiated jobs. + RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_MS = Math.max( + RUNTIME_MIN_USER_INITIATED_GUARANTEE_MS, + properties.getLong( + KEY_RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_MS, + DEFAULT_RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_MS)); + // Data transfer requires RUN_LONG_JOBS permission, so the upper limit will be higher + // than other jobs. + // Max limit should be the min guarantee and the max of other user-initiated jobs. + RUNTIME_USER_INITIATED_DATA_TRANSFER_LIMIT_MS = Math.max( + RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_MS, + Math.max(RUNTIME_USER_INITIATED_LIMIT_MS, + properties.getLong( + KEY_RUNTIME_USER_INITIATED_DATA_TRANSFER_LIMIT_MS, + DEFAULT_RUNTIME_USER_INITIATED_DATA_TRANSFER_LIMIT_MS))); } private boolean updateTareSettingsLocked(boolean isTareEnabled) { @@ -867,6 +998,20 @@ public class JobSchedulerService extends com.android.server.SystemService RUNTIME_MIN_HIGH_PRIORITY_GUARANTEE_MS).println(); pw.print(KEY_RUNTIME_FREE_QUOTA_MAX_LIMIT_MS, RUNTIME_FREE_QUOTA_MAX_LIMIT_MS) .println(); + pw.print(KEY_RUNTIME_MIN_DATA_TRANSFER_GUARANTEE_MS, + RUNTIME_MIN_DATA_TRANSFER_GUARANTEE_MS).println(); + pw.print(KEY_RUNTIME_DATA_TRANSFER_LIMIT_MS, + RUNTIME_DATA_TRANSFER_LIMIT_MS).println(); + pw.print(KEY_RUNTIME_MIN_USER_INITIATED_GUARANTEE_MS, + RUNTIME_MIN_USER_INITIATED_GUARANTEE_MS).println(); + pw.print(KEY_RUNTIME_USER_INITIATED_LIMIT_MS, + RUNTIME_USER_INITIATED_LIMIT_MS).println(); + pw.print(KEY_RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_BUFFER_FACTOR, + RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_BUFFER_FACTOR).println(); + pw.print(KEY_RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_MS, + RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_MS).println(); + pw.print(KEY_RUNTIME_USER_INITIATED_DATA_TRANSFER_LIMIT_MS, + RUNTIME_USER_INITIATED_DATA_TRANSFER_LIMIT_MS).println(); pw.print(KEY_PERSIST_IN_SPLIT_FILES, PERSIST_IN_SPLIT_FILES).println(); @@ -1858,9 +2003,9 @@ public class JobSchedulerService extends com.android.server.SystemService final FlexibilityController flexibilityController = new FlexibilityController(this, mPrefetchController); mControllers.add(flexibilityController); - final ConnectivityController connectivityController = + mConnectivityController = new ConnectivityController(this, flexibilityController); - mControllers.add(connectivityController); + mControllers.add(mConnectivityController); mControllers.add(new TimeController(this)); final IdleController idleController = new IdleController(this, flexibilityController); mControllers.add(idleController); @@ -1876,16 +2021,16 @@ public class JobSchedulerService extends com.android.server.SystemService mDeviceIdleJobsController = new DeviceIdleJobsController(this); mControllers.add(mDeviceIdleJobsController); mQuotaController = - new QuotaController(this, backgroundJobsController, connectivityController); + new QuotaController(this, backgroundJobsController, mConnectivityController); mControllers.add(mQuotaController); mControllers.add(new ComponentController(this)); mTareController = - new TareController(this, backgroundJobsController, connectivityController); + new TareController(this, backgroundJobsController, mConnectivityController); mControllers.add(mTareController); mRestrictiveControllers = new ArrayList<>(); mRestrictiveControllers.add(batteryController); - mRestrictiveControllers.add(connectivityController); + mRestrictiveControllers.add(mConnectivityController); mRestrictiveControllers.add(idleController); // Create restrictions @@ -3028,7 +3173,30 @@ public class JobSchedulerService extends com.android.server.SystemService /** Returns the minimum amount of time we should let this job run before timing out. */ public long getMinJobExecutionGuaranteeMs(JobStatus job) { synchronized (mLock) { - if (job.shouldTreatAsExpeditedJob()) { + final boolean shouldTreatAsDataTransfer = job.getJob().isDataTransfer() + && checkRunLongJobsPermission(job.getSourceUid(), job.getSourcePackageName()); + if (job.shouldTreatAsUserInitiated()) { + if (shouldTreatAsDataTransfer) { + final long estimatedTransferTimeMs = + mConnectivityController.getEstimatedTransferTimeMs(job); + if (estimatedTransferTimeMs == ConnectivityController.UNKNOWN_TIME) { + return mConstants.RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_MS; + } + // Try to give the job at least as much time as we think the transfer will take, + // but cap it at the maximum limit + final long factoredTransferTimeMs = (long) (estimatedTransferTimeMs + * mConstants + .RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_BUFFER_FACTOR); + return Math.min(mConstants.RUNTIME_USER_INITIATED_DATA_TRANSFER_LIMIT_MS, + Math.max(factoredTransferTimeMs, + mConstants.RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_MS + )); + } + return mConstants.RUNTIME_MIN_USER_INITIATED_GUARANTEE_MS; + } else if (shouldTreatAsDataTransfer) { + // For now, don't increase a bg data transfer's minimum guarantee. + return mConstants.RUNTIME_MIN_DATA_TRANSFER_GUARANTEE_MS; + } else if (job.shouldTreatAsExpeditedJob()) { // Don't guarantee RESTRICTED jobs more than 5 minutes. return job.getEffectiveStandbyBucket() != RESTRICTED_INDEX ? mConstants.RUNTIME_MIN_EJ_GUARANTEE_MS @@ -3044,6 +3212,16 @@ public class JobSchedulerService extends com.android.server.SystemService /** Returns the maximum amount of time this job could run for. */ public long getMaxJobExecutionTimeMs(JobStatus job) { synchronized (mLock) { + final boolean shouldTreatAsDataTransfer = job.getJob().isDataTransfer() + && checkRunLongJobsPermission(job.getSourceUid(), job.getSourcePackageName()); + if (job.shouldTreatAsUserInitiated()) { + if (shouldTreatAsDataTransfer) { + return mConstants.RUNTIME_USER_INITIATED_DATA_TRANSFER_LIMIT_MS; + } + return mConstants.RUNTIME_USER_INITIATED_LIMIT_MS; + } else if (shouldTreatAsDataTransfer) { + return mConstants.RUNTIME_DATA_TRANSFER_LIMIT_MS; + } return Math.min(mConstants.RUNTIME_FREE_QUOTA_MAX_LIMIT_MS, mConstants.USE_TARE_POLICY ? mTareController.getMaxJobExecutionTimeMsLocked(job) @@ -3703,13 +3881,6 @@ public class JobSchedulerService extends com.android.server.SystemService return checkRunLongJobsPermission(uid, packageName); } - private boolean checkRunLongJobsPermission(int packageUid, String packageName) { - // Returns true if both the appop and permission are granted. - return PermissionChecker.checkPermissionForPreflight(getContext(), - android.Manifest.permission.RUN_LONG_JOBS, PermissionChecker.PID_UNKNOWN, - packageUid, packageName) == PermissionChecker.PERMISSION_GRANTED; - } - /** * "dumpsys" infrastructure */ @@ -3824,6 +3995,7 @@ public class JobSchedulerService extends com.android.server.SystemService @Override @EnforcePermission(allOf = {MANAGE_ACTIVITY_TASKS, INTERACT_ACROSS_USERS_FULL}) public void registerUserVisibleJobObserver(@NonNull IUserVisibleJobObserver observer) { + super.registerUserVisibleJobObserver_enforcePermission(); if (observer == null) { throw new NullPointerException("observer"); } @@ -3835,6 +4007,7 @@ public class JobSchedulerService extends com.android.server.SystemService @Override @EnforcePermission(allOf = {MANAGE_ACTIVITY_TASKS, INTERACT_ACROSS_USERS_FULL}) public void unregisterUserVisibleJobObserver(@NonNull IUserVisibleJobObserver observer) { + super.unregisterUserVisibleJobObserver_enforcePermission(); if (observer == null) { throw new NullPointerException("observer"); } @@ -3842,8 +4015,9 @@ public class JobSchedulerService extends com.android.server.SystemService } @Override - @EnforcePermission(allOf = {"MANAGE_ACTIVITY_TASKS", "INTERACT_ACROSS_USERS_FULL"}) + @EnforcePermission(allOf = {MANAGE_ACTIVITY_TASKS, INTERACT_ACROSS_USERS_FULL}) public void stopUserVisibleJobsForUser(@NonNull String packageName, int userId) { + super.stopUserVisibleJobsForUser_enforcePermission(); if (packageName == null) { throw new NullPointerException("packageName"); } @@ -3985,13 +4159,27 @@ public class JobSchedulerService extends com.android.server.SystemService } } + private boolean checkRunLongJobsPermission(int packageUid, String packageName) { + // Returns true if both the appop and permission are granted. + return PermissionChecker.checkPermissionForPreflight(getTestableContext(), + android.Manifest.permission.RUN_LONG_JOBS, PermissionChecker.PID_UNKNOWN, + packageUid, packageName) == PermissionChecker.PERMISSION_GRANTED; + } + + @VisibleForTesting + protected ConnectivityController getConnectivityController() { + return mConnectivityController; + } + // Shell command infrastructure int getJobState(PrintWriter pw, String pkgName, int userId, int jobId) { try { final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0, userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM); if (uid < 0) { - pw.print("unknown("); pw.print(pkgName); pw.println(")"); + pw.print("unknown("); + pw.print(pkgName); + pw.println(")"); return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE; } diff --git a/apex/jobscheduler/service/java/com/android/server/job/JobServiceContext.java b/apex/jobscheduler/service/java/com/android/server/job/JobServiceContext.java index fead68e021db..df47f1787fdc 100644 --- a/apex/jobscheduler/service/java/com/android/server/job/JobServiceContext.java +++ b/apex/jobscheduler/service/java/com/android/server/job/JobServiceContext.java @@ -17,8 +17,6 @@ package com.android.server.job; import static android.app.job.JobInfo.getPriorityString; -import static android.app.job.JobService.JOB_END_NOTIFICATION_POLICY_DETACH; -import static android.app.job.JobService.JOB_END_NOTIFICATION_POLICY_REMOVE; import static com.android.server.job.JobConcurrencyManager.WORK_TYPE_NONE; import static com.android.server.job.JobSchedulerService.sElapsedRealtimeClock; @@ -61,7 +59,6 @@ import com.android.internal.util.FrameworkStatsLog; import com.android.server.EventLogTags; import com.android.server.LocalServices; import com.android.server.job.controllers.JobStatus; -import com.android.server.notification.NotificationManagerInternal; import com.android.server.tare.EconomicPolicy; import com.android.server.tare.EconomyManagerInternal; import com.android.server.tare.JobSchedulerEconomicPolicy; @@ -113,6 +110,7 @@ public final class JobServiceContext implements ServiceConnection { /** Make callbacks to {@link JobSchedulerService} to inform on job completion status. */ private final JobCompletedListener mCompletedListener; private final JobConcurrencyManager mJobConcurrencyManager; + private final JobNotificationCoordinator mNotificationCoordinator; private final JobSchedulerService mService; /** Used for service binding, etc. */ private final Context mContext; @@ -121,7 +119,6 @@ public final class JobServiceContext implements ServiceConnection { private final EconomyManagerInternal mEconomyManagerInternal; private final JobPackageTracker mJobPackageTracker; private final PowerManager mPowerManager; - private final NotificationManagerInternal mNotificationManagerInternal; private PowerManager.WakeLock mWakeLock; // Execution state. @@ -174,11 +171,6 @@ public final class JobServiceContext implements ServiceConnection { /** The absolute maximum amount of time the job can run */ private long mMaxExecutionTimeMillis; - private int mNotificationId; - private Notification mNotification; - private int mNotificationPid; - private int mNotificationJobStopPolicy; - /** * The stop reason for a pending cancel. If there's not pending cancel, then the value should be * {@link JobParameters#STOP_REASON_UNDEFINED}. @@ -254,16 +246,17 @@ public final class JobServiceContext implements ServiceConnection { } JobServiceContext(JobSchedulerService service, JobConcurrencyManager concurrencyManager, + JobNotificationCoordinator notificationCoordinator, IBatteryStats batteryStats, JobPackageTracker tracker, Looper looper) { mContext = service.getContext(); mLock = service.getLock(); mService = service; mBatteryStats = batteryStats; mEconomyManagerInternal = LocalServices.getService(EconomyManagerInternal.class); - mNotificationManagerInternal = LocalServices.getService(NotificationManagerInternal.class); mJobPackageTracker = tracker; mCallbackHandler = new JobServiceHandler(looper); mJobConcurrencyManager = concurrencyManager; + mNotificationCoordinator = notificationCoordinator; mCompletedListener = service; mPowerManager = mContext.getSystemService(PowerManager.class); mAvailable = true; @@ -624,29 +617,10 @@ public final class JobServiceContext implements ServiceConnection { Slog.wtfStack(TAG, "Calling UID isn't the same as running job's UID..."); throw new SecurityException("Can't post notification on behalf of another app"); } - if (notification == null) { - throw new NullPointerException("notification"); - } - if (notification.getSmallIcon() == null) { - throw new IllegalArgumentException("small icon required"); - } final String callingPkgName = mRunningJob.getServiceComponent().getPackageName(); - if (null == mNotificationManagerInternal.getNotificationChannel( - callingPkgName, callingUid, notification.getChannelId())) { - throw new IllegalArgumentException("invalid notification channel"); - } - if (jobEndNotificationPolicy != JOB_END_NOTIFICATION_POLICY_DETACH - && jobEndNotificationPolicy != JOB_END_NOTIFICATION_POLICY_REMOVE) { - throw new IllegalArgumentException("invalid job end notification policy"); - } - // TODO(260848384): ensure apps can't cancel the notification for user-initiated job - mNotificationManagerInternal.enqueueNotification( - callingPkgName, callingPkgName, callingUid, callingPid, /* tag */ null, - notificationId, notification, UserHandle.getUserId(callingUid)); - mNotificationId = notificationId; - mNotification = notification; - mNotificationPid = callingPid; - mNotificationJobStopPolicy = jobEndNotificationPolicy; + mNotificationCoordinator.enqueueNotification(this, callingPkgName, + callingPid, callingUid, notificationId, + notification, jobEndNotificationPolicy); } } finally { Binder.restoreCallingIdentity(ident); @@ -1179,13 +1153,7 @@ public final class JobServiceContext implements ServiceConnection { JobSchedulerEconomicPolicy.ACTION_JOB_TIMEOUT, String.valueOf(mRunningJob.getJobId())); } - if (mNotification != null - && mNotificationJobStopPolicy == JOB_END_NOTIFICATION_POLICY_REMOVE) { - final String callingPkgName = completedJob.getServiceComponent().getPackageName(); - mNotificationManagerInternal.cancelNotification( - callingPkgName, callingPkgName, completedJob.getUid(), mNotificationPid, - /* tag */ null, mNotificationId, UserHandle.getUserId(completedJob.getUid())); - } + mNotificationCoordinator.removeNotificationAssociation(this); if (mWakeLock != null) { mWakeLock.release(); } @@ -1203,7 +1171,6 @@ public final class JobServiceContext implements ServiceConnection { mPendingStopReason = JobParameters.STOP_REASON_UNDEFINED; mPendingInternalStopReason = 0; mPendingDebugStopReason = null; - mNotification = null; removeOpTimeOutLocked(); if (completedJob.isUserVisibleJob()) { mService.informObserversOfUserVisibleJobChange(this, completedJob, false); diff --git a/apex/jobscheduler/service/java/com/android/server/job/controllers/ConnectivityController.java b/apex/jobscheduler/service/java/com/android/server/job/controllers/ConnectivityController.java index 16dd16727fa6..6166921d64b2 100644 --- a/apex/jobscheduler/service/java/com/android/server/job/controllers/ConnectivityController.java +++ b/apex/jobscheduler/service/java/com/android/server/job/controllers/ConnectivityController.java @@ -42,7 +42,6 @@ import android.telephony.TelephonyManager; import android.text.format.DateUtils; import android.util.ArrayMap; import android.util.ArraySet; -import android.util.DataUnit; import android.util.IndentingPrintWriter; import android.util.Log; import android.util.Pools; @@ -82,6 +81,8 @@ public final class ConnectivityController extends RestrictingController implemen private static final boolean DEBUG = JobSchedulerService.DEBUG || Log.isLoggable(TAG, Log.DEBUG); + public static final long UNKNOWN_TIME = -1L; + // The networking stack has a hard limit so we can't make this configurable. private static final int MAX_NETWORK_CALLBACKS = 125; /** @@ -570,9 +571,8 @@ public final class ConnectivityController extends RestrictingController implemen // If we don't know the bandwidth, all we can do is hope the job finishes the minimum // chunk in time. if (bandwidthDown > 0) { - // Divide by 8 to convert bits to bytes. - final long estimatedMillis = ((minimumChunkBytes * DateUtils.SECOND_IN_MILLIS) - / (DataUnit.KIBIBYTES.toBytes(bandwidthDown) / 8)); + final long estimatedMillis = + calculateTransferTimeMs(minimumChunkBytes, bandwidthDown); if (estimatedMillis > maxJobExecutionTimeMs) { // If we'd never finish the minimum chunk before the timeout, we'd be insane! Slog.w(TAG, "Minimum chunk " + minimumChunkBytes + " bytes over " @@ -585,9 +585,8 @@ public final class ConnectivityController extends RestrictingController implemen final long bandwidthUp = capabilities.getLinkUpstreamBandwidthKbps(); // If we don't know the bandwidth, all we can do is hope the job finishes in time. if (bandwidthUp > 0) { - // Divide by 8 to convert bits to bytes. - final long estimatedMillis = ((minimumChunkBytes * DateUtils.SECOND_IN_MILLIS) - / (DataUnit.KIBIBYTES.toBytes(bandwidthUp) / 8)); + final long estimatedMillis = + calculateTransferTimeMs(minimumChunkBytes, bandwidthUp); if (estimatedMillis > maxJobExecutionTimeMs) { // If we'd never finish the minimum chunk before the timeout, we'd be insane! Slog.w(TAG, "Minimum chunk " + minimumChunkBytes + " bytes over " + bandwidthUp @@ -615,9 +614,7 @@ public final class ConnectivityController extends RestrictingController implemen final long bandwidth = capabilities.getLinkDownstreamBandwidthKbps(); // If we don't know the bandwidth, all we can do is hope the job finishes in time. if (bandwidth > 0) { - // Divide by 8 to convert bits to bytes. - final long estimatedMillis = ((downloadBytes * DateUtils.SECOND_IN_MILLIS) - / (DataUnit.KIBIBYTES.toBytes(bandwidth) / 8)); + final long estimatedMillis = calculateTransferTimeMs(downloadBytes, bandwidth); if (estimatedMillis > maxJobExecutionTimeMs) { // If we'd never finish before the timeout, we'd be insane! Slog.w(TAG, "Estimated " + downloadBytes + " download bytes over " + bandwidth @@ -633,9 +630,7 @@ public final class ConnectivityController extends RestrictingController implemen final long bandwidth = capabilities.getLinkUpstreamBandwidthKbps(); // If we don't know the bandwidth, all we can do is hope the job finishes in time. if (bandwidth > 0) { - // Divide by 8 to convert bits to bytes. - final long estimatedMillis = ((uploadBytes * DateUtils.SECOND_IN_MILLIS) - / (DataUnit.KIBIBYTES.toBytes(bandwidth) / 8)); + final long estimatedMillis = calculateTransferTimeMs(uploadBytes, bandwidth); if (estimatedMillis > maxJobExecutionTimeMs) { // If we'd never finish before the timeout, we'd be insane! Slog.w(TAG, "Estimated " + uploadBytes + " upload bytes over " + bandwidth @@ -649,6 +644,48 @@ public final class ConnectivityController extends RestrictingController implemen return false; } + /** + * Return the estimated amount of time this job will be transferring data, + * based on the current network speed. + */ + public long getEstimatedTransferTimeMs(JobStatus jobStatus) { + final long downloadBytes = jobStatus.getEstimatedNetworkDownloadBytes(); + final long uploadBytes = jobStatus.getEstimatedNetworkUploadBytes(); + if (downloadBytes == JobInfo.NETWORK_BYTES_UNKNOWN + && uploadBytes == JobInfo.NETWORK_BYTES_UNKNOWN) { + return UNKNOWN_TIME; + } + if (jobStatus.network == null) { + // This job doesn't have a network assigned. + return UNKNOWN_TIME; + } + NetworkCapabilities capabilities = getNetworkCapabilities(jobStatus.network); + if (capabilities == null) { + return UNKNOWN_TIME; + } + final long estimatedDownloadTimeMs = calculateTransferTimeMs(downloadBytes, + capabilities.getLinkDownstreamBandwidthKbps()); + final long estimatedUploadTimeMs = calculateTransferTimeMs(uploadBytes, + capabilities.getLinkUpstreamBandwidthKbps()); + if (estimatedDownloadTimeMs == UNKNOWN_TIME) { + return estimatedUploadTimeMs; + } else if (estimatedUploadTimeMs == UNKNOWN_TIME) { + return estimatedDownloadTimeMs; + } + return estimatedDownloadTimeMs + estimatedUploadTimeMs; + } + + @VisibleForTesting + static long calculateTransferTimeMs(long transferBytes, long bandwidthKbps) { + if (transferBytes == JobInfo.NETWORK_BYTES_UNKNOWN || bandwidthKbps <= 0) { + return UNKNOWN_TIME; + } + return (transferBytes * DateUtils.SECOND_IN_MILLIS) + // Multiply by 1000 to convert kilobits to bits. + // Divide by 8 to convert bits to bytes. + / (bandwidthKbps * 1000 / 8); + } + private static boolean isCongestionDelayed(JobStatus jobStatus, Network network, NetworkCapabilities capabilities, Constants constants) { // If network is congested, and job is less than 50% through the 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 83b6a8ea3916..419127e6c6a9 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 @@ -1345,6 +1345,15 @@ public final class JobStatus { } /** + * @return true if the job was scheduled as a user-initiated job and it hasn't been downgraded + * for any reason. + */ + public boolean shouldTreatAsUserInitiated() { + // TODO(248386641): implement + return false; + } + + /** * Return a summary that uniquely identifies the underlying job. */ @NonNull diff --git a/apex/jobscheduler/service/java/com/android/server/job/restrictions/ThermalStatusRestriction.java b/apex/jobscheduler/service/java/com/android/server/job/restrictions/ThermalStatusRestriction.java index 830031e2f442..85b762d1e524 100644 --- a/apex/jobscheduler/service/java/com/android/server/job/restrictions/ThermalStatusRestriction.java +++ b/apex/jobscheduler/service/java/com/android/server/job/restrictions/ThermalStatusRestriction.java @@ -91,12 +91,23 @@ public class ThermalStatusRestriction extends JobRestriction { } final int priority = job.getEffectivePriority(); if (mThermalStatus >= HIGHER_PRIORITY_THRESHOLD) { - // For moderate throttling, only let expedited jobs and high priority regular jobs that - // haven't been running for a long time run. - return !job.shouldTreatAsExpeditedJob() - && !(priority == JobInfo.PRIORITY_HIGH - && mService.isCurrentlyRunningLocked(job) - && !mService.isJobInOvertimeLocked(job)); + // For moderate throttling: + // Only let expedited & user-initiated jobs run if: + // 1. They haven't previously run + // 2. They're already running and aren't yet in overtime + // Only let high priority jobs run if: + // They are already running and aren't yet in overtime + // Don't let any other job run. + if (job.shouldTreatAsExpeditedJob() || job.shouldTreatAsUserInitiated()) { + return job.getNumPreviousAttempts() > 0 + || (mService.isCurrentlyRunningLocked(job) + && mService.isJobInOvertimeLocked(job)); + } + if (priority == JobInfo.PRIORITY_HIGH) { + return !mService.isCurrentlyRunningLocked(job) + || mService.isJobInOvertimeLocked(job); + } + return true; } if (mThermalStatus >= LOW_PRIORITY_THRESHOLD) { // For light throttling, throttle all min priority jobs and all low priority jobs that diff --git a/apex/jobscheduler/service/java/com/android/server/usage/AppStandbyController.java b/apex/jobscheduler/service/java/com/android/server/usage/AppStandbyController.java index b1c8b511ac25..1a775b4e1d49 100644 --- a/apex/jobscheduler/service/java/com/android/server/usage/AppStandbyController.java +++ b/apex/jobscheduler/service/java/com/android/server/usage/AppStandbyController.java @@ -111,6 +111,7 @@ import android.util.SparseArray; import android.util.SparseBooleanArray; import android.util.SparseIntArray; import android.util.SparseLongArray; +import android.util.SparseSetArray; import android.util.TimeUtils; import android.view.Display; import android.widget.Toast; @@ -463,6 +464,12 @@ public class AppStandbyController private final Map<String, String> mAppStandbyProperties = new ArrayMap<>(); /** + * Set of apps that were restored via backup & restore, per user, that need their + * standby buckets to be adjusted when installed. + */ + private final SparseSetArray<String> mAppsToRestoreToRare = new SparseSetArray<>(); + + /** * List of app-ids of system packages, populated on boot, when system services are ready. */ private final ArrayList<Integer> mSystemPackagesAppIds = new ArrayList<>(); @@ -1663,18 +1670,29 @@ public class AppStandbyController final int reason = REASON_MAIN_DEFAULT | REASON_SUB_DEFAULT_APP_RESTORED; final long nowElapsed = mInjector.elapsedRealtime(); for (String packageName : restoredApps) { - // If the package is not installed, don't allow the bucket to be set. + // If the package is not installed, don't allow the bucket to be set. Instead, add it + // to a list of all packages whose buckets need to be adjusted when installed. if (!mInjector.isPackageInstalled(packageName, 0, userId)) { - Slog.e(TAG, "Tried to restore bucket for uninstalled app: " + packageName); + Slog.i(TAG, "Tried to restore bucket for uninstalled app: " + packageName); + mAppsToRestoreToRare.add(userId, packageName); continue; } - final int standbyBucket = getAppStandbyBucket(packageName, userId, nowElapsed, false); - // Only update the standby bucket to RARE if the app is still in the NEVER bucket. - if (standbyBucket == STANDBY_BUCKET_NEVER) { - setAppStandbyBucket(packageName, userId, STANDBY_BUCKET_RARE, reason, - nowElapsed, false); - } + restoreAppToRare(packageName, userId, nowElapsed, reason); + } + // Clear out the list of restored apps that need to have their standby buckets adjusted + // if they still haven't been installed eight hours after restore. + // Note: if the device reboots within these first 8 hours, this list will be lost since it's + // not persisted - this is the expected behavior for now and may be updated in the future. + mHandler.postDelayed(() -> mAppsToRestoreToRare.remove(userId), 8 * ONE_HOUR); + } + + /** Adjust the standby bucket of the given package for the user to RARE. */ + private void restoreAppToRare(String pkgName, int userId, long nowElapsed, int reason) { + final int standbyBucket = getAppStandbyBucket(pkgName, userId, nowElapsed, false); + // Only update the standby bucket to RARE if the app is still in the NEVER bucket. + if (standbyBucket == STANDBY_BUCKET_NEVER) { + setAppStandbyBucket(pkgName, userId, STANDBY_BUCKET_RARE, reason, nowElapsed, false); } } @@ -2176,8 +2194,15 @@ public class AppStandbyController Intent.ACTION_PACKAGE_ADDED.equals(action))) { if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) { maybeUnrestrictBuggyApp(pkgName, userId); - } else { + } else if (!Intent.ACTION_PACKAGE_ADDED.equals(action)) { clearAppIdleForPackage(pkgName, userId); + } else { + // Package was just added and it's not being replaced. + if (mAppsToRestoreToRare.contains(userId, pkgName)) { + restoreAppToRare(pkgName, userId, mInjector.elapsedRealtime(), + REASON_MAIN_DEFAULT | REASON_SUB_DEFAULT_APP_RESTORED); + mAppsToRestoreToRare.remove(userId, pkgName); + } } } synchronized (mSystemExemptionAppOpMode) { diff --git a/api/Android.bp b/api/Android.bp index b0ce9afe147b..318748e20808 100644 --- a/api/Android.bp +++ b/api/Android.bp @@ -118,9 +118,11 @@ combined_apis { ], system_server_classpath: [ "service-art", + "service-configinfrastructure", "service-healthconnect", "service-media-s", "service-permission", + "service-rkp", "service-sdksandbox", ], } diff --git a/cmds/bootanimation/BootAnimation.cpp b/cmds/bootanimation/BootAnimation.cpp index c4d90c6295aa..80512f7b3187 100644 --- a/cmds/bootanimation/BootAnimation.cpp +++ b/cmds/bootanimation/BootAnimation.cpp @@ -1112,6 +1112,11 @@ bool BootAnimation::parseAnimationDesc(Animation& animation) { int nextReadPos; + if (strlen(l) == 0) { + s = ++endl; + continue; + } + int topLineNumbers = sscanf(l, "%d %d %d %d", &width, &height, &fps, &progress); if (topLineNumbers == 3 || topLineNumbers == 4) { // SLOGD("> w=%d, h=%d, fps=%d, progress=%d", width, height, fps, progress); diff --git a/core/api/current.txt b/core/api/current.txt index 434b60dd144a..b31fdc79184c 100644 --- a/core/api/current.txt +++ b/core/api/current.txt @@ -1042,7 +1042,6 @@ package android { field public static final int max = 16843062; // 0x1010136 field public static final int maxAspectRatio = 16844128; // 0x1010560 field public static final int maxButtonHeight = 16844029; // 0x10104fd - field public static final int maxConcurrentSessionsCount; field public static final int maxDate = 16843584; // 0x1010340 field public static final int maxEms = 16843095; // 0x1010157 field public static final int maxHeight = 16843040; // 0x1010120 @@ -7283,8 +7282,10 @@ package android.app { method public android.content.Intent getCropAndSetWallpaperIntent(android.net.Uri); method public int getDesiredMinimumHeight(); method public int getDesiredMinimumWidth(); - method @RequiresPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) public android.graphics.drawable.Drawable getDrawable(); - method @RequiresPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) public android.graphics.drawable.Drawable getFastDrawable(); + method @Nullable @RequiresPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) public android.graphics.drawable.Drawable getDrawable(); + method @Nullable @RequiresPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) public android.graphics.drawable.Drawable getDrawable(int); + method @Nullable @RequiresPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) public android.graphics.drawable.Drawable getFastDrawable(); + method @Nullable @RequiresPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) public android.graphics.drawable.Drawable getFastDrawable(int); method public static android.app.WallpaperManager getInstance(android.content.Context); method @Nullable public android.app.WallpaperColors getWallpaperColors(int); method @RequiresPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) public android.os.ParcelFileDescriptor getWallpaperFile(int); @@ -7294,8 +7295,10 @@ package android.app { method public boolean hasResourceWallpaper(@RawRes int); method public boolean isSetWallpaperAllowed(); method public boolean isWallpaperSupported(); - method public android.graphics.drawable.Drawable peekDrawable(); - method @RequiresPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) public android.graphics.drawable.Drawable peekFastDrawable(); + method @Nullable public android.graphics.drawable.Drawable peekDrawable(); + method @Nullable public android.graphics.drawable.Drawable peekDrawable(int); + method @Nullable @RequiresPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) public android.graphics.drawable.Drawable peekFastDrawable(); + method @Nullable @RequiresPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) public android.graphics.drawable.Drawable peekFastDrawable(int); method public void removeOnColorsChangedListener(@NonNull android.app.WallpaperManager.OnColorsChangedListener); method public void sendWallpaperCommand(android.os.IBinder, String, int, int, int, android.os.Bundle); method @RequiresPermission(android.Manifest.permission.SET_WALLPAPER) public void setBitmap(android.graphics.Bitmap) throws java.io.IOException; @@ -7475,7 +7478,7 @@ package android.app.admin { method public boolean getBluetoothContactSharingDisabled(@NonNull android.content.ComponentName); method public boolean getCameraDisabled(@Nullable android.content.ComponentName); method @Deprecated @Nullable public String getCertInstallerPackage(@NonNull android.content.ComponentName) throws java.lang.SecurityException; - method @Nullable public java.util.Set<java.lang.String> getCrossProfileCalendarPackages(@NonNull android.content.ComponentName); + method @Deprecated @Nullable public java.util.Set<java.lang.String> getCrossProfileCalendarPackages(@NonNull android.content.ComponentName); method public boolean getCrossProfileCallerIdDisabled(@NonNull android.content.ComponentName); method public boolean getCrossProfileContactsSearchDisabled(@NonNull android.content.ComponentName); method @NonNull public java.util.Set<java.lang.String> getCrossProfilePackages(@NonNull android.content.ComponentName); @@ -7624,7 +7627,7 @@ package android.app.admin { method @Deprecated public void setCertInstallerPackage(@NonNull android.content.ComponentName, @Nullable String) throws java.lang.SecurityException; method public void setCommonCriteriaModeEnabled(@NonNull android.content.ComponentName, boolean); method public void setConfiguredNetworksLockdownState(@NonNull android.content.ComponentName, boolean); - method public void setCrossProfileCalendarPackages(@NonNull android.content.ComponentName, @Nullable java.util.Set<java.lang.String>); + method @Deprecated public void setCrossProfileCalendarPackages(@NonNull android.content.ComponentName, @Nullable java.util.Set<java.lang.String>); method public void setCrossProfileCallerIdDisabled(@NonNull android.content.ComponentName, boolean); method public void setCrossProfileContactsSearchDisabled(@NonNull android.content.ComponentName, boolean); method public void setCrossProfilePackages(@NonNull android.content.ComponentName, @NonNull java.util.Set<java.lang.String>); @@ -8014,6 +8017,9 @@ package android.app.admin { field public static final int TAG_MEDIA_UNMOUNT = 210014; // 0x3345e field public static final int TAG_OS_SHUTDOWN = 210010; // 0x3345a field public static final int TAG_OS_STARTUP = 210009; // 0x33459 + field public static final int TAG_PACKAGE_INSTALLED = 210041; // 0x33479 + field public static final int TAG_PACKAGE_UNINSTALLED = 210043; // 0x3347b + field public static final int TAG_PACKAGE_UPDATED = 210042; // 0x3347a field public static final int TAG_PASSWORD_CHANGED = 210036; // 0x33474 field public static final int TAG_PASSWORD_COMPLEXITY_REQUIRED = 210035; // 0x33473 field public static final int TAG_PASSWORD_COMPLEXITY_SET = 210017; // 0x33461 @@ -13044,6 +13050,14 @@ package android.content.res.loader { package android.credentials { + public class ClearCredentialStateException extends java.lang.Exception { + ctor public ClearCredentialStateException(@NonNull String, @Nullable String); + ctor public ClearCredentialStateException(@NonNull String, @Nullable String, @Nullable Throwable); + ctor public ClearCredentialStateException(@NonNull String, @Nullable Throwable); + ctor public ClearCredentialStateException(@NonNull String); + field @NonNull public final String errorType; + } + public final class ClearCredentialStateRequest implements android.os.Parcelable { ctor public ClearCredentialStateRequest(@NonNull android.os.Bundle); method public int describeContents(); @@ -13052,6 +13066,14 @@ package android.credentials { field @NonNull public static final android.os.Parcelable.Creator<android.credentials.ClearCredentialStateRequest> CREATOR; } + public class CreateCredentialException extends java.lang.Exception { + ctor public CreateCredentialException(@NonNull String, @Nullable String); + ctor public CreateCredentialException(@NonNull String, @Nullable String, @Nullable Throwable); + ctor public CreateCredentialException(@NonNull String, @Nullable Throwable); + ctor public CreateCredentialException(@NonNull String); + field @NonNull public final String errorType; + } + public final class CreateCredentialRequest implements android.os.Parcelable { ctor public CreateCredentialRequest(@NonNull String, @NonNull android.os.Bundle, @NonNull android.os.Bundle, boolean); method public int describeContents(); @@ -13081,24 +13103,24 @@ package android.credentials { } public final class CredentialManager { - method public void clearCredentialState(@NonNull android.credentials.ClearCredentialStateRequest, @Nullable android.os.CancellationSignal, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<java.lang.Void,android.credentials.CredentialManagerException>); - method public void executeCreateCredential(@NonNull android.credentials.CreateCredentialRequest, @NonNull android.app.Activity, @Nullable android.os.CancellationSignal, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<android.credentials.CreateCredentialResponse,android.credentials.CredentialManagerException>); - method public void executeGetCredential(@NonNull android.credentials.GetCredentialRequest, @NonNull android.app.Activity, @Nullable android.os.CancellationSignal, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<android.credentials.GetCredentialResponse,android.credentials.CredentialManagerException>); + method public void clearCredentialState(@NonNull android.credentials.ClearCredentialStateRequest, @Nullable android.os.CancellationSignal, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<java.lang.Void,android.credentials.ClearCredentialStateException>); + method public void executeCreateCredential(@NonNull android.credentials.CreateCredentialRequest, @NonNull android.app.Activity, @Nullable android.os.CancellationSignal, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<android.credentials.CreateCredentialResponse,android.credentials.CreateCredentialException>); + method public void executeGetCredential(@NonNull android.credentials.GetCredentialRequest, @NonNull android.app.Activity, @Nullable android.os.CancellationSignal, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<android.credentials.GetCredentialResponse,android.credentials.GetCredentialException>); } - public class CredentialManagerException extends java.lang.Exception { - ctor public CredentialManagerException(int, @Nullable String); - ctor public CredentialManagerException(int, @Nullable String, @Nullable Throwable); - ctor public CredentialManagerException(int, @Nullable Throwable); - ctor public CredentialManagerException(int); - field public static final int ERROR_UNKNOWN = 0; // 0x0 - field public final int errorCode; + public class GetCredentialException extends java.lang.Exception { + ctor public GetCredentialException(@NonNull String, @Nullable String); + ctor public GetCredentialException(@NonNull String, @Nullable String, @Nullable Throwable); + ctor public GetCredentialException(@NonNull String, @Nullable Throwable); + ctor public GetCredentialException(@NonNull String); + field @NonNull public final String errorType; } public final class GetCredentialOption implements android.os.Parcelable { - ctor public GetCredentialOption(@NonNull String, @NonNull android.os.Bundle, boolean); + ctor public GetCredentialOption(@NonNull String, @NonNull android.os.Bundle, @NonNull android.os.Bundle, boolean); method public int describeContents(); - method @NonNull public android.os.Bundle getData(); + method @NonNull public android.os.Bundle getCandidateQueryData(); + method @NonNull public android.os.Bundle getCredentialRetrievalData(); method @NonNull public String getType(); method public boolean requireSystemProvider(); method public void writeToParcel(@NonNull android.os.Parcel, int); @@ -17826,6 +17848,7 @@ package android.hardware.camera2 { field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> SENSOR_MAX_ANALOG_SENSITIVITY; field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<android.graphics.Rect[]> SENSOR_OPTICAL_BLACK_REGIONS; field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> SENSOR_ORIENTATION; + field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> SENSOR_READOUT_TIMESTAMP; field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Integer> SENSOR_REFERENCE_ILLUMINANT1; field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<java.lang.Byte> SENSOR_REFERENCE_ILLUMINANT2; field @NonNull public static final android.hardware.camera2.CameraCharacteristics.Key<int[]> SHADING_AVAILABLE_MODES; @@ -18194,6 +18217,8 @@ package android.hardware.camera2 { field public static final int SENSOR_INFO_TIMESTAMP_SOURCE_UNKNOWN = 0; // 0x0 field public static final int SENSOR_PIXEL_MODE_DEFAULT = 0; // 0x0 field public static final int SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION = 1; // 0x1 + field public static final int SENSOR_READOUT_TIMESTAMP_HARDWARE = 1; // 0x1 + field public static final int SENSOR_READOUT_TIMESTAMP_NOT_SUPPORTED = 0; // 0x0 field public static final int SENSOR_REFERENCE_ILLUMINANT1_CLOUDY_WEATHER = 10; // 0xa field public static final int SENSOR_REFERENCE_ILLUMINANT1_COOL_WHITE_FLUORESCENT = 14; // 0xe field public static final int SENSOR_REFERENCE_ILLUMINANT1_D50 = 23; // 0x17 @@ -18307,6 +18332,7 @@ package android.hardware.camera2 { field @NonNull public static final android.os.Parcelable.Creator<android.hardware.camera2.CaptureRequest> CREATOR; field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> DISTORTION_CORRECTION_MODE; field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> EDGE_MODE; + field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> EXTENSION_STRENGTH; field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> FLASH_MODE; field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<java.lang.Integer> HOT_PIXEL_MODE; field @NonNull public static final android.hardware.camera2.CaptureRequest.Key<android.location.Location> JPEG_GPS_LOCATION; @@ -18399,6 +18425,8 @@ package android.hardware.camera2 { field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Float> CONTROL_ZOOM_RATIO; field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> DISTORTION_CORRECTION_MODE; field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> EDGE_MODE; + field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> EXTENSION_CURRENT_TYPE; + field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> EXTENSION_STRENGTH; field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> FLASH_MODE; field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> FLASH_STATE; field @NonNull public static final android.hardware.camera2.CaptureResult.Key<java.lang.Integer> HOT_PIXEL_MODE; @@ -20206,7 +20234,7 @@ package android.location.altitude { public final class AltitudeConverter { ctor public AltitudeConverter(); - method @WorkerThread public void addMslAltitude(@NonNull android.content.Context, @NonNull android.location.Location) throws java.io.IOException; + method @WorkerThread public void addMslAltitudeToLocation(@NonNull android.content.Context, @NonNull android.location.Location) throws java.io.IOException; } } @@ -20525,10 +20553,12 @@ package android.media { method public int abandonAudioFocusRequest(@NonNull android.media.AudioFocusRequest); method public void addOnCommunicationDeviceChangedListener(@NonNull java.util.concurrent.Executor, @NonNull android.media.AudioManager.OnCommunicationDeviceChangedListener); method public void addOnModeChangedListener(@NonNull java.util.concurrent.Executor, @NonNull android.media.AudioManager.OnModeChangedListener); + method public void addOnPreferredMixerAttributesChangedListener(@NonNull java.util.concurrent.Executor, @NonNull android.media.AudioManager.OnPreferredMixerAttributesChangedListener); method public void adjustStreamVolume(int, int, int); method public void adjustSuggestedStreamVolume(int, int, int); method public void adjustVolume(int, int); method public void clearCommunicationDevice(); + method @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_SETTINGS) public boolean clearPreferredMixerAttributes(@NonNull android.media.AudioAttributes, @NonNull android.media.AudioDeviceInfo); method public void dispatchMediaKeyEvent(android.view.KeyEvent); method public int generateAudioSessionId(); method @NonNull public java.util.List<android.media.AudioPlaybackConfiguration> getActivePlaybackConfigurations(); @@ -20546,6 +20576,7 @@ package android.media { method public int getMode(); method public String getParameters(String); method @Deprecated public static int getPlaybackOffloadSupport(@NonNull android.media.AudioFormat, @NonNull android.media.AudioAttributes); + method @Nullable public android.media.AudioMixerAttributes getPreferredMixerAttributes(@NonNull android.media.AudioAttributes, @NonNull android.media.AudioDeviceInfo); method public String getProperty(String); method public int getRingerMode(); method @Deprecated public int getRouting(int); @@ -20554,6 +20585,7 @@ package android.media { method public int getStreamMinVolume(int); method public int getStreamVolume(int); method public float getStreamVolumeDb(int, int, int); + method @NonNull public java.util.List<android.media.AudioMixerAttributes> getSupportedMixerAttributes(@NonNull android.media.AudioDeviceInfo); method @Deprecated public int getVibrateSetting(int); method @Deprecated public boolean isBluetoothA2dpOn(); method public boolean isBluetoothScoAvailableOffCall(); @@ -20581,6 +20613,7 @@ package android.media { method @Deprecated public boolean registerRemoteController(android.media.RemoteController); method public void removeOnCommunicationDeviceChangedListener(@NonNull android.media.AudioManager.OnCommunicationDeviceChangedListener); method public void removeOnModeChangedListener(@NonNull android.media.AudioManager.OnModeChangedListener); + method public void removeOnPreferredMixerAttributesChangedListener(@NonNull android.media.AudioManager.OnPreferredMixerAttributesChangedListener); method @Deprecated public int requestAudioFocus(android.media.AudioManager.OnAudioFocusChangeListener, int, int); method public int requestAudioFocus(@NonNull android.media.AudioFocusRequest); method public void setAllowedCapturePolicy(int); @@ -20591,6 +20624,7 @@ package android.media { method public void setMicrophoneMute(boolean); method public void setMode(int); method public void setParameters(String); + method @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_SETTINGS) public boolean setPreferredMixerAttributes(@NonNull android.media.AudioAttributes, @NonNull android.media.AudioDeviceInfo, @NonNull android.media.AudioMixerAttributes); method public void setRingerMode(int); method @Deprecated public void setRouting(int, int, int); method @Deprecated public void setSpeakerphoneOn(boolean); @@ -20746,6 +20780,10 @@ package android.media { method public void onModeChanged(int); } + public static interface AudioManager.OnPreferredMixerAttributesChangedListener { + method public void onPreferredMixerAttributesChanged(@NonNull android.media.AudioAttributes, @NonNull android.media.AudioDeviceInfo, @Nullable android.media.AudioMixerAttributes); + } + public final class AudioMetadata { method @NonNull public static android.media.AudioMetadataMap createMap(); } @@ -20781,6 +20819,21 @@ package android.media { method @IntRange(from=0) public int size(); } + public final class AudioMixerAttributes implements android.os.Parcelable { + method public int describeContents(); + method @NonNull public android.media.AudioFormat getFormat(); + method public int getMixerBehavior(); + method public void writeToParcel(@NonNull android.os.Parcel, int); + field @NonNull public static final android.os.Parcelable.Creator<android.media.AudioMixerAttributes> CREATOR; + field public static final int MIXER_BEHAVIOR_DEFAULT = 0; // 0x0 + } + + public static final class AudioMixerAttributes.Builder { + ctor public AudioMixerAttributes.Builder(@NonNull android.media.AudioFormat); + method @NonNull public android.media.AudioMixerAttributes build(); + method @NonNull public android.media.AudioMixerAttributes.Builder setMixerBehavior(int); + } + public final class AudioPlaybackCaptureConfiguration { method @NonNull public int[] getExcludeUids(); method @NonNull public int[] getExcludeUsages(); @@ -39448,6 +39501,40 @@ package android.service.credentials { method @NonNull public android.service.credentials.BeginCreateCredentialResponse.Builder setRemoteCreateEntry(@Nullable android.service.credentials.CreateEntry); } + public final class BeginGetCredentialOption implements android.os.Parcelable { + ctor public BeginGetCredentialOption(@NonNull String, @NonNull android.os.Bundle); + method public int describeContents(); + method @NonNull public android.os.Bundle getCandidateQueryData(); + method @NonNull public String getType(); + method public void writeToParcel(@NonNull android.os.Parcel, int); + field @NonNull public static final android.os.Parcelable.Creator<android.service.credentials.BeginGetCredentialOption> CREATOR; + } + + public final class BeginGetCredentialsRequest implements android.os.Parcelable { + method public int describeContents(); + method @NonNull public java.util.List<android.service.credentials.BeginGetCredentialOption> getBeginGetCredentialOptions(); + method @NonNull public String getCallingPackage(); + method public void writeToParcel(@NonNull android.os.Parcel, int); + field @NonNull public static final android.os.Parcelable.Creator<android.service.credentials.BeginGetCredentialsRequest> CREATOR; + } + + public static final class BeginGetCredentialsRequest.Builder { + ctor public BeginGetCredentialsRequest.Builder(@NonNull String); + method @NonNull public android.service.credentials.BeginGetCredentialsRequest.Builder addBeginGetCredentialOption(@NonNull android.service.credentials.BeginGetCredentialOption); + method @NonNull public android.service.credentials.BeginGetCredentialsRequest build(); + method @NonNull public android.service.credentials.BeginGetCredentialsRequest.Builder setBeginGetCredentialOptions(@NonNull java.util.List<android.service.credentials.BeginGetCredentialOption>); + } + + public final class BeginGetCredentialsResponse implements android.os.Parcelable { + method @NonNull public static android.service.credentials.BeginGetCredentialsResponse createWithAuthentication(@NonNull android.service.credentials.Action); + method @NonNull public static android.service.credentials.BeginGetCredentialsResponse createWithResponseContent(@NonNull android.service.credentials.CredentialsResponseContent); + method public int describeContents(); + method @Nullable public android.service.credentials.Action getAuthenticationAction(); + method @Nullable public android.service.credentials.CredentialsResponseContent getCredentialsResponseContent(); + method public void writeToParcel(@NonNull android.os.Parcel, int); + field @NonNull public static final android.os.Parcelable.Creator<android.service.credentials.BeginGetCredentialsResponse> CREATOR; + } + public final class CreateCredentialRequest implements android.os.Parcelable { ctor public CreateCredentialRequest(@NonNull String, @NonNull String, @NonNull android.os.Bundle); method public int describeContents(); @@ -39469,8 +39556,7 @@ package android.service.credentials { public final class CredentialEntry implements android.os.Parcelable { method public int describeContents(); - method @Nullable public android.credentials.Credential getCredential(); - method @Nullable public android.app.PendingIntent getPendingIntent(); + method @NonNull public android.app.PendingIntent getPendingIntent(); method @NonNull public android.app.slice.Slice getSlice(); method @NonNull public String getType(); method public boolean isAutoSelectAllowed(); @@ -39480,7 +39566,6 @@ package android.service.credentials { public static final class CredentialEntry.Builder { ctor public CredentialEntry.Builder(@NonNull String, @NonNull android.app.slice.Slice, @NonNull android.app.PendingIntent); - ctor public CredentialEntry.Builder(@NonNull String, @NonNull android.app.slice.Slice, @NonNull android.credentials.Credential); method @NonNull public android.service.credentials.CredentialEntry build(); method @NonNull public android.service.credentials.CredentialEntry.Builder setAutoSelectAllowed(@NonNull boolean); } @@ -39497,14 +39582,16 @@ package android.service.credentials { public abstract class CredentialProviderService extends android.app.Service { ctor public CredentialProviderService(); method public abstract void onBeginCreateCredential(@NonNull android.service.credentials.BeginCreateCredentialRequest, @NonNull android.os.CancellationSignal, @NonNull android.os.OutcomeReceiver<android.service.credentials.BeginCreateCredentialResponse,android.service.credentials.CredentialProviderException>); + method public abstract void onBeginGetCredentials(@NonNull android.service.credentials.BeginGetCredentialsRequest, @NonNull android.os.CancellationSignal, @NonNull android.os.OutcomeReceiver<android.service.credentials.BeginGetCredentialsResponse,android.service.credentials.CredentialProviderException>); method @NonNull public final android.os.IBinder onBind(@NonNull android.content.Intent); - method public abstract void onGetCredentials(@NonNull android.service.credentials.GetCredentialsRequest, @NonNull android.os.CancellationSignal, @NonNull android.os.OutcomeReceiver<android.service.credentials.GetCredentialsResponse,android.service.credentials.CredentialProviderException>); field public static final String CAPABILITY_META_DATA_KEY = "android.credentials.capabilities"; + field public static final String EXTRA_CREATE_CREDENTIAL_EXCEPTION = "android.service.credentials.extra.CREATE_CREDENTIAL_EXCEPTION"; field public static final String EXTRA_CREATE_CREDENTIAL_REQUEST = "android.service.credentials.extra.CREATE_CREDENTIAL_REQUEST"; - field public static final String EXTRA_CREATE_CREDENTIAL_RESULT = "android.service.credentials.extra.CREATE_CREDENTIAL_RESULT"; - field public static final String EXTRA_CREDENTIAL_RESULT = "android.service.credentials.extra.CREDENTIAL_RESULT"; - field public static final String EXTRA_ERROR = "android.service.credentials.extra.ERROR"; - field public static final String EXTRA_GET_CREDENTIALS_CONTENT_RESULT = "android.service.credentials.extra.GET_CREDENTIALS_CONTENT_RESULT"; + field public static final String EXTRA_CREATE_CREDENTIAL_RESPONSE = "android.service.credentials.extra.CREATE_CREDENTIAL_RESPONSE"; + field public static final String EXTRA_CREDENTIALS_RESPONSE_CONTENT = "android.service.credentials.extra.CREDENTIALS_RESPONSE_CONTENT"; + field public static final String EXTRA_GET_CREDENTIAL_EXCEPTION = "android.service.credentials.extra.GET_CREDENTIAL_EXCEPTION"; + field public static final String EXTRA_GET_CREDENTIAL_REQUEST = "android.service.credentials.extra.GET_CREDENTIAL_REQUEST"; + field public static final String EXTRA_GET_CREDENTIAL_RESPONSE = "android.service.credentials.extra.GET_CREDENTIAL_RESPONSE"; field public static final String SERVICE_INTERFACE = "android.service.credentials.CredentialProviderService"; } @@ -39527,29 +39614,19 @@ package android.service.credentials { method @NonNull public android.service.credentials.CredentialsResponseContent.Builder setRemoteCredentialEntry(@Nullable android.service.credentials.CredentialEntry); } - public final class GetCredentialsRequest implements android.os.Parcelable { + public final class GetCredentialRequest implements android.os.Parcelable { method public int describeContents(); method @NonNull public String getCallingPackage(); method @NonNull public java.util.List<android.credentials.GetCredentialOption> getGetCredentialOptions(); method public void writeToParcel(@NonNull android.os.Parcel, int); - field @NonNull public static final android.os.Parcelable.Creator<android.service.credentials.GetCredentialsRequest> CREATOR; - } - - public static final class GetCredentialsRequest.Builder { - ctor public GetCredentialsRequest.Builder(@NonNull String); - method @NonNull public android.service.credentials.GetCredentialsRequest.Builder addGetCredentialOption(@NonNull android.credentials.GetCredentialOption); - method @NonNull public android.service.credentials.GetCredentialsRequest build(); - method @NonNull public android.service.credentials.GetCredentialsRequest.Builder setGetCredentialOptions(@NonNull java.util.List<android.credentials.GetCredentialOption>); + field @NonNull public static final android.os.Parcelable.Creator<android.service.credentials.GetCredentialRequest> CREATOR; } - public final class GetCredentialsResponse implements android.os.Parcelable { - method @NonNull public static android.service.credentials.GetCredentialsResponse createWithAuthentication(@NonNull android.service.credentials.Action); - method @NonNull public static android.service.credentials.GetCredentialsResponse createWithResponseContent(@NonNull android.service.credentials.CredentialsResponseContent); - method public int describeContents(); - method @Nullable public android.service.credentials.Action getAuthenticationAction(); - method @Nullable public android.service.credentials.CredentialsResponseContent getCredentialsResponseContent(); - method public void writeToParcel(@NonNull android.os.Parcel, int); - field @NonNull public static final android.os.Parcelable.Creator<android.service.credentials.GetCredentialsResponse> CREATOR; + public static final class GetCredentialRequest.Builder { + ctor public GetCredentialRequest.Builder(@NonNull String); + method @NonNull public android.service.credentials.GetCredentialRequest.Builder addGetCredentialOption(@NonNull android.credentials.GetCredentialOption); + method @NonNull public android.service.credentials.GetCredentialRequest build(); + method @NonNull public android.service.credentials.GetCredentialRequest.Builder setGetCredentialOptions(@NonNull java.util.List<android.credentials.GetCredentialOption>); } } @@ -42813,6 +42890,7 @@ package android.telephony { method public int getSsRsrp(); method public int getSsRsrq(); method public int getSsSinr(); + method @IntRange(from=0, to=1282) public int getTimingAdvanceMicros(); method public void writeToParcel(android.os.Parcel, int); field @NonNull public static final android.os.Parcelable.Creator<android.telephony.CellSignalStrengthNr> CREATOR; } diff --git a/core/api/module-lib-current.txt b/core/api/module-lib-current.txt index 3efb0c6ee20a..98c78fefcc60 100644 --- a/core/api/module-lib-current.txt +++ b/core/api/module-lib-current.txt @@ -418,41 +418,6 @@ package android.provider { method @NonNull @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS) public static java.util.Map<java.lang.String,java.util.List<android.content.ContentValues>> queryRawContactEntity(@NonNull android.content.ContentResolver, long); } - public final class DeviceConfig { - field public static final String NAMESPACE_ACTIVITY_MANAGER_COMPONENT_ALIAS = "activity_manager_ca"; - field public static final String NAMESPACE_ALARM_MANAGER = "alarm_manager"; - field public static final String NAMESPACE_APP_CLONING = "app_cloning"; - field public static final String NAMESPACE_APP_STANDBY = "app_standby"; - field public static final String NAMESPACE_ARC_APP_COMPAT = "arc_app_compat"; - field public static final String NAMESPACE_CONFIGURATION = "configuration"; - field public static final String NAMESPACE_CONNECTIVITY_THERMAL_POWER_MANAGER = "connectivity_thermal_power_manager"; - field public static final String NAMESPACE_CONTACTS_PROVIDER = "contacts_provider"; - field public static final String NAMESPACE_DEVICE_IDLE = "device_idle"; - field public static final String NAMESPACE_DEVICE_POLICY_MANAGER = "device_policy_manager"; - field public static final String NAMESPACE_GAME_OVERLAY = "game_overlay"; - field public static final String NAMESPACE_INTELLIGENCE_CONTENT_SUGGESTIONS = "intelligence_content_suggestions"; - field public static final String NAMESPACE_INTERACTION_JANK_MONITOR = "interaction_jank_monitor"; - field public static final String NAMESPACE_LATENCY_TRACKER = "latency_tracker"; - field public static final String NAMESPACE_MEMORY_SAFETY_NATIVE = "memory_safety_native"; - field public static final String NAMESPACE_MGLRU_NATIVE = "mglru_native"; - field public static final String NAMESPACE_REMOTE_KEY_PROVISIONING_NATIVE = "remote_key_provisioning_native"; - field public static final String NAMESPACE_ROTATION_RESOLVER = "rotation_resolver"; - field public static final String NAMESPACE_SETTINGS_STATS = "settings_stats"; - field public static final String NAMESPACE_SETTINGS_UI = "settings_ui"; - field public static final String NAMESPACE_TARE = "tare"; - field public static final String NAMESPACE_VENDOR_SYSTEM_NATIVE = "vendor_system_native"; - field public static final String NAMESPACE_VENDOR_SYSTEM_NATIVE_BOOT = "vendor_system_native_boot"; - field public static final String NAMESPACE_VIRTUALIZATION_FRAMEWORK_NATIVE = "virtualization_framework_native"; - field public static final String NAMESPACE_VOICE_INTERACTION = "voice_interaction"; - field public static final String NAMESPACE_WEAR = "wear"; - field public static final String NAMESPACE_WIDGET = "widget"; - field public static final String NAMESPACE_WINDOW_MANAGER = "window_manager"; - } - - public static class DeviceConfig.Properties { - ctor public DeviceConfig.Properties(@NonNull String, @Nullable java.util.Map<java.lang.String,java.lang.String>); - } - public final class Settings { field public static final int RESET_MODE_PACKAGE_DEFAULTS = 1; // 0x1 field public static final int RESET_MODE_TRUSTED_DEFAULTS = 4; // 0x4 diff --git a/core/api/system-current.txt b/core/api/system-current.txt index eb2d2ca89588..992e524d7edf 100644 --- a/core/api/system-current.txt +++ b/core/api/system-current.txt @@ -826,7 +826,6 @@ package android.app { method public int describeContents(); method public int getFpsOverride(); method public float getScalingFactor(); - method @NonNull public android.app.GameModeConfiguration.Builder toBuilder(); method public void writeToParcel(@NonNull android.os.Parcel, int); field @NonNull public static final android.os.Parcelable.Creator<android.app.GameModeConfiguration> CREATOR; field public static final int FPS_OVERRIDE_NONE = 0; // 0x0 @@ -834,6 +833,7 @@ package android.app { public static final class GameModeConfiguration.Builder { ctor public GameModeConfiguration.Builder(); + ctor public GameModeConfiguration.Builder(@NonNull android.app.GameModeConfiguration); method @NonNull public android.app.GameModeConfiguration build(); method @NonNull public android.app.GameModeConfiguration.Builder setFpsOverride(int); method @NonNull public android.app.GameModeConfiguration.Builder setScalingFactor(float); @@ -845,7 +845,7 @@ package android.app { method public int getActiveGameMode(); method @NonNull public int[] getAvailableGameModes(); method @Nullable public android.app.GameModeConfiguration getGameModeConfiguration(int); - method @NonNull public int[] getOptedInGameModes(); + method @NonNull public int[] getOverriddenGameModes(); method public boolean isDownscalingAllowed(); method public boolean isFpsOverrideAllowed(); method public void writeToParcel(@NonNull android.os.Parcel, int); @@ -860,7 +860,7 @@ package android.app { method @NonNull public android.app.GameModeInfo.Builder setDownscalingAllowed(boolean); method @NonNull public android.app.GameModeInfo.Builder setFpsOverrideAllowed(boolean); method @NonNull public android.app.GameModeInfo.Builder setGameModeConfiguration(int, @NonNull android.app.GameModeConfiguration); - method @NonNull public android.app.GameModeInfo.Builder setOptedInGameModes(@NonNull int[]); + method @NonNull public android.app.GameModeInfo.Builder setOverriddenGameModes(@NonNull int[]); } public abstract class InstantAppResolverService extends android.app.Service { @@ -3772,6 +3772,7 @@ package android.content.pm { field @Deprecated public static final int PROTECTION_FLAG_DOCUMENTER = 262144; // 0x40000 field public static final int PROTECTION_FLAG_INCIDENT_REPORT_APPROVER = 1048576; // 0x100000 field public static final int PROTECTION_FLAG_KNOWN_SIGNER = 134217728; // 0x8000000 + field public static final int PROTECTION_FLAG_MODULE = 4194304; // 0x400000 field public static final int PROTECTION_FLAG_OEM = 16384; // 0x4000 field public static final int PROTECTION_FLAG_RECENTS = 33554432; // 0x2000000 field public static final int PROTECTION_FLAG_RETAIL_DEMO = 16777216; // 0x1000000 @@ -5803,8 +5804,9 @@ package android.location { } public final class Country implements android.os.Parcelable { + ctor public Country(@NonNull String, int); method public int describeContents(); - method @NonNull public String getCountryIso(); + method @NonNull public String getCountryCode(); method public int getSource(); method public void writeToParcel(@NonNull android.os.Parcel, int); field public static final int COUNTRY_SOURCE_LOCALE = 3; // 0x3 @@ -5815,13 +5817,8 @@ package android.location { } public class CountryDetector { - method public void addCountryListener(@NonNull android.location.CountryListener, @Nullable android.os.Looper); - method @Nullable public android.location.Country detectCountry(); - method public void removeCountryListener(@NonNull android.location.CountryListener); - } - - public interface CountryListener { - method public void onCountryDetected(@NonNull android.location.Country); + method public void registerCountryDetectorCallback(@NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<android.location.Country>); + method public void unregisterCountryDetectorCallback(@NonNull java.util.function.Consumer<android.location.Country>); } public final class GnssCapabilities implements android.os.Parcelable { @@ -10224,7 +10221,7 @@ package android.os { method @Nullable @RequiresPermission(anyOf={android.Manifest.permission.MANAGE_USERS, android.Manifest.permission.GET_ACCOUNTS_PRIVILEGED}) public android.graphics.Bitmap getUserIcon(); method @Deprecated @android.os.UserManager.UserRestrictionSource @RequiresPermission(anyOf={android.Manifest.permission.MANAGE_USERS, android.Manifest.permission.QUERY_USERS}) public int getUserRestrictionSource(String, android.os.UserHandle); method @RequiresPermission(anyOf={android.Manifest.permission.MANAGE_USERS, android.Manifest.permission.QUERY_USERS}) public java.util.List<android.os.UserManager.EnforcingUser> getUserRestrictionSources(String, android.os.UserHandle); - method @RequiresPermission(allOf={android.Manifest.permission.READ_PHONE_STATE, android.Manifest.permission.MANAGE_USERS, android.Manifest.permission.INTERACT_ACROSS_USERS}, conditional=true) public int getUserSwitchability(); + method @RequiresPermission(anyOf={android.Manifest.permission.MANAGE_USERS, android.Manifest.permission.INTERACT_ACROSS_USERS}) public int getUserSwitchability(); method @NonNull @RequiresPermission(anyOf={"android.permission.INTERACT_ACROSS_USERS", "android.permission.MANAGE_USERS"}) public java.util.Set<android.os.UserHandle> getVisibleUsers(); method @RequiresPermission(android.Manifest.permission.MANAGE_USERS) public boolean hasRestrictedProfiles(); method @RequiresPermission(anyOf={android.Manifest.permission.MANAGE_USERS, android.Manifest.permission.INTERACT_ACROSS_USERS}, conditional=true) public boolean hasUserRestrictionForUser(@NonNull String, @NonNull android.os.UserHandle); @@ -10706,121 +10703,6 @@ package android.provider { method @RequiresPermission("android.contacts.permission.MANAGE_SIM_ACCOUNTS") public static void removeSimAccounts(@NonNull android.content.ContentResolver, int); } - public final class DeviceConfig { - method public static void addOnPropertiesChangedListener(@NonNull String, @NonNull java.util.concurrent.Executor, @NonNull android.provider.DeviceConfig.OnPropertiesChangedListener); - method @RequiresPermission(android.Manifest.permission.WRITE_DEVICE_CONFIG) public static boolean deleteProperty(@NonNull String, @NonNull String); - method @RequiresPermission(android.Manifest.permission.READ_DEVICE_CONFIG) public static boolean getBoolean(@NonNull String, @NonNull String, boolean); - method @RequiresPermission(android.Manifest.permission.READ_DEVICE_CONFIG) public static float getFloat(@NonNull String, @NonNull String, float); - method @RequiresPermission(android.Manifest.permission.READ_DEVICE_CONFIG) public static int getInt(@NonNull String, @NonNull String, int); - method @RequiresPermission(android.Manifest.permission.READ_DEVICE_CONFIG) public static long getLong(@NonNull String, @NonNull String, long); - method @NonNull @RequiresPermission(android.Manifest.permission.READ_DEVICE_CONFIG) public static android.provider.DeviceConfig.Properties getProperties(@NonNull String, @NonNull java.lang.String...); - method @RequiresPermission(android.Manifest.permission.READ_DEVICE_CONFIG) public static String getProperty(@NonNull String, @NonNull String); - method @NonNull public static java.util.List<java.lang.String> getPublicNamespaces(); - method @RequiresPermission(android.Manifest.permission.READ_DEVICE_CONFIG) public static String getString(@NonNull String, @NonNull String, @Nullable String); - method @RequiresPermission(android.Manifest.permission.WRITE_DEVICE_CONFIG) public static int getSyncDisabledMode(); - method public static void removeOnPropertiesChangedListener(@NonNull android.provider.DeviceConfig.OnPropertiesChangedListener); - method @RequiresPermission(android.Manifest.permission.WRITE_DEVICE_CONFIG) public static void resetToDefaults(int, @Nullable String); - method @RequiresPermission(android.Manifest.permission.WRITE_DEVICE_CONFIG) public static boolean setProperties(@NonNull android.provider.DeviceConfig.Properties) throws android.provider.DeviceConfig.BadConfigException; - method @RequiresPermission(android.Manifest.permission.WRITE_DEVICE_CONFIG) public static boolean setProperty(@NonNull String, @NonNull String, @Nullable String, boolean); - method @RequiresPermission(android.Manifest.permission.WRITE_DEVICE_CONFIG) public static void setSyncDisabledMode(int); - field public static final String NAMESPACE_ACTIVITY_MANAGER = "activity_manager"; - field public static final String NAMESPACE_ACTIVITY_MANAGER_NATIVE_BOOT = "activity_manager_native_boot"; - field public static final String NAMESPACE_ADSERVICES = "adservices"; - field public static final String NAMESPACE_AMBIENT_CONTEXT_MANAGER_SERVICE = "ambient_context_manager_service"; - field public static final String NAMESPACE_ANDROID = "android"; - field public static final String NAMESPACE_APPSEARCH = "appsearch"; - field public static final String NAMESPACE_APP_COMPAT = "app_compat"; - field public static final String NAMESPACE_APP_COMPAT_OVERRIDES = "app_compat_overrides"; - field public static final String NAMESPACE_APP_HIBERNATION = "app_hibernation"; - field public static final String NAMESPACE_ATTENTION_MANAGER_SERVICE = "attention_manager_service"; - field public static final String NAMESPACE_AUTOFILL = "autofill"; - field public static final String NAMESPACE_BACKUP_AND_RESTORE = "backup_and_restore"; - field public static final String NAMESPACE_BATTERY_SAVER = "battery_saver"; - field public static final String NAMESPACE_BIOMETRICS = "biometrics"; - field public static final String NAMESPACE_BLOBSTORE = "blobstore"; - field public static final String NAMESPACE_BLUETOOTH = "bluetooth"; - field public static final String NAMESPACE_CAPTIVEPORTALLOGIN = "captive_portal_login"; - field public static final String NAMESPACE_CLIPBOARD = "clipboard"; - field public static final String NAMESPACE_CONNECTIVITY = "connectivity"; - field public static final String NAMESPACE_CONSTRAIN_DISPLAY_APIS = "constrain_display_apis"; - field public static final String NAMESPACE_CONTENT_CAPTURE = "content_capture"; - field @Deprecated public static final String NAMESPACE_DEX_BOOT = "dex_boot"; - field public static final String NAMESPACE_DISPLAY_MANAGER = "display_manager"; - field public static final String NAMESPACE_GAME_DRIVER = "game_driver"; - field public static final String NAMESPACE_HDMI_CONTROL = "hdmi_control"; - field public static final String NAMESPACE_INPUT_METHOD_MANAGER = "input_method_manager"; - field public static final String NAMESPACE_INPUT_NATIVE_BOOT = "input_native_boot"; - field public static final String NAMESPACE_INTELLIGENCE_ATTENTION = "intelligence_attention"; - field public static final String NAMESPACE_JOB_SCHEDULER = "jobscheduler"; - field public static final String NAMESPACE_LMKD_NATIVE = "lmkd_native"; - field public static final String NAMESPACE_LOCATION = "location"; - field public static final String NAMESPACE_MEDIA = "media"; - field public static final String NAMESPACE_MEDIA_NATIVE = "media_native"; - field public static final String NAMESPACE_NEARBY = "nearby"; - field public static final String NAMESPACE_NETD_NATIVE = "netd_native"; - field public static final String NAMESPACE_NNAPI_NATIVE = "nnapi_native"; - field public static final String NAMESPACE_ON_DEVICE_PERSONALIZATION = "on_device_personalization"; - field public static final String NAMESPACE_OTA = "ota"; - field public static final String NAMESPACE_PACKAGE_MANAGER_SERVICE = "package_manager_service"; - field public static final String NAMESPACE_PERMISSIONS = "permissions"; - field public static final String NAMESPACE_PRIVACY = "privacy"; - field public static final String NAMESPACE_PROFCOLLECT_NATIVE_BOOT = "profcollect_native_boot"; - field public static final String NAMESPACE_REBOOT_READINESS = "reboot_readiness"; - field public static final String NAMESPACE_ROLLBACK = "rollback"; - field public static final String NAMESPACE_ROLLBACK_BOOT = "rollback_boot"; - field public static final String NAMESPACE_RUNTIME = "runtime"; - field public static final String NAMESPACE_RUNTIME_NATIVE = "runtime_native"; - field public static final String NAMESPACE_RUNTIME_NATIVE_BOOT = "runtime_native_boot"; - field public static final String NAMESPACE_SCHEDULER = "scheduler"; - field public static final String NAMESPACE_SDK_SANDBOX = "sdk_sandbox"; - field public static final String NAMESPACE_SELECTION_TOOLBAR = "selection_toolbar"; - field public static final String NAMESPACE_STATSD_JAVA = "statsd_java"; - field public static final String NAMESPACE_STATSD_JAVA_BOOT = "statsd_java_boot"; - field public static final String NAMESPACE_STATSD_NATIVE = "statsd_native"; - field public static final String NAMESPACE_STATSD_NATIVE_BOOT = "statsd_native_boot"; - field @Deprecated public static final String NAMESPACE_STORAGE = "storage"; - field public static final String NAMESPACE_STORAGE_NATIVE_BOOT = "storage_native_boot"; - field public static final String NAMESPACE_SURFACE_FLINGER_NATIVE_BOOT = "surface_flinger_native_boot"; - field public static final String NAMESPACE_SWCODEC_NATIVE = "swcodec_native"; - field public static final String NAMESPACE_SYSTEMUI = "systemui"; - field public static final String NAMESPACE_SYSTEM_TIME = "system_time"; - field public static final String NAMESPACE_TELEPHONY = "telephony"; - field public static final String NAMESPACE_TETHERING = "tethering"; - field public static final String NAMESPACE_TEXTCLASSIFIER = "textclassifier"; - field public static final String NAMESPACE_TRANSPARENCY_METADATA = "transparency_metadata"; - field public static final String NAMESPACE_UWB = "uwb"; - field public static final String NAMESPACE_WEARABLE_SENSING = "wearable_sensing"; - field public static final String NAMESPACE_WINDOW_MANAGER_NATIVE_BOOT = "window_manager_native_boot"; - } - - public static class DeviceConfig.BadConfigException extends java.lang.Exception { - ctor public DeviceConfig.BadConfigException(); - } - - public static interface DeviceConfig.OnPropertiesChangedListener { - method public void onPropertiesChanged(@NonNull android.provider.DeviceConfig.Properties); - } - - public static class DeviceConfig.Properties { - method public boolean getBoolean(@NonNull String, boolean); - method public float getFloat(@NonNull String, float); - method public int getInt(@NonNull String, int); - method @NonNull public java.util.Set<java.lang.String> getKeyset(); - method public long getLong(@NonNull String, long); - method @NonNull public String getNamespace(); - method @Nullable public String getString(@NonNull String, @Nullable String); - } - - public static final class DeviceConfig.Properties.Builder { - ctor public DeviceConfig.Properties.Builder(@NonNull String); - method @NonNull public android.provider.DeviceConfig.Properties build(); - method @NonNull public android.provider.DeviceConfig.Properties.Builder setBoolean(@NonNull String, boolean); - method @NonNull public android.provider.DeviceConfig.Properties.Builder setFloat(@NonNull String, float); - method @NonNull public android.provider.DeviceConfig.Properties.Builder setInt(@NonNull String, int); - method @NonNull public android.provider.DeviceConfig.Properties.Builder setLong(@NonNull String, long); - method @NonNull public android.provider.DeviceConfig.Properties.Builder setString(@NonNull String, @Nullable String); - } - public final class DocumentsContract { method @NonNull public static android.net.Uri buildDocumentUriAsUser(@NonNull String, @NonNull String, @NonNull android.os.UserHandle); method public static boolean isManageMode(@NonNull android.net.Uri); diff --git a/core/api/system-lint-baseline.txt b/core/api/system-lint-baseline.txt index 47588d97fdbf..025e8629fc20 100644 --- a/core/api/system-lint-baseline.txt +++ b/core/api/system-lint-baseline.txt @@ -3,10 +3,6 @@ ArrayReturn: android.view.contentcapture.ViewNode#getAutofillOptions(): Method should return Collection<CharSequence> (or subclass) instead of raw array; was `java.lang.CharSequence[]` -ExecutorRegistration: android.location.CountryDetector#addCountryListener(android.location.CountryListener, android.os.Looper): - Registration methods should have overload that accepts delivery Executor: `addCountryListener` - - GenericException: android.app.prediction.AppPredictor#finalize(): Methods must not throw generic exceptions (`java.lang.Throwable`) GenericException: android.hardware.location.ContextHubClient#finalize(): @@ -131,8 +127,6 @@ SamShouldBeLast: android.content.pm.PackageItemInfo#dumpFront(android.util.Print SAM-compatible parameters (such as parameter 1, "pw", in android.content.pm.PackageItemInfo.dumpFront) should be last to improve Kotlin interoperability; see https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions SamShouldBeLast: android.content.pm.ResolveInfo#dump(android.util.Printer, String): SAM-compatible parameters (such as parameter 1, "pw", in android.content.pm.ResolveInfo.dump) should be last to improve Kotlin interoperability; see https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions -SamShouldBeLast: android.location.CountryDetector#addCountryListener(android.location.CountryListener, android.os.Looper): - SAM-compatible parameters (such as parameter 1, "listener", in android.location.CountryDetector.addCountryListener) should be last to improve Kotlin interoperability; see https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions SamShouldBeLast: android.location.Location#dump(android.util.Printer, String): SAM-compatible parameters (such as parameter 1, "pw", in android.location.Location.dump) should be last to improve Kotlin interoperability; see https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions SamShouldBeLast: android.location.LocationManager#addNmeaListener(android.location.OnNmeaMessageListener, android.os.Handler): diff --git a/core/api/test-current.txt b/core/api/test-current.txt index 43d4530cbf1d..e14902f59ccc 100644 --- a/core/api/test-current.txt +++ b/core/api/test-current.txt @@ -38,6 +38,7 @@ package android { field public static final String READ_CELL_BROADCASTS = "android.permission.READ_CELL_BROADCASTS"; field public static final String READ_PRIVILEGED_PHONE_STATE = "android.permission.READ_PRIVILEGED_PHONE_STATE"; field public static final String RECORD_BACKGROUND_AUDIO = "android.permission.RECORD_BACKGROUND_AUDIO"; + field public static final String REMAP_MODIFIER_KEYS = "android.permission.REMAP_MODIFIER_KEYS"; field public static final String REMOVE_TASKS = "android.permission.REMOVE_TASKS"; field public static final String REQUEST_UNIQUE_ID_ATTESTATION = "android.permission.REQUEST_UNIQUE_ID_ATTESTATION"; field public static final String RESET_APP_ERRORS = "android.permission.RESET_APP_ERRORS"; @@ -1294,8 +1295,11 @@ package android.hardware.input { public final class InputManager { method public void addUniqueIdAssociation(@NonNull String, @NonNull String); + method @RequiresPermission(android.Manifest.permission.REMAP_MODIFIER_KEYS) public void clearAllModifierKeyRemappings(); method @Nullable public String getCurrentKeyboardLayoutForInputDevice(@NonNull android.hardware.input.InputDeviceIdentifier); method @NonNull public java.util.List<java.lang.String> getKeyboardLayoutDescriptorsForInputDevice(@NonNull android.view.InputDevice); + method @NonNull @RequiresPermission(android.Manifest.permission.REMAP_MODIFIER_KEYS) public java.util.Map<java.lang.Integer,java.lang.Integer> getModifierKeyRemapping(); + method @RequiresPermission(android.Manifest.permission.REMAP_MODIFIER_KEYS) public void remapModifierKey(int, int); method @RequiresPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT) public void removeKeyboardLayoutForInputDevice(@NonNull android.hardware.input.InputDeviceIdentifier, @NonNull String); method public void removeUniqueIdAssociation(@NonNull String); method @RequiresPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT) public void setCurrentKeyboardLayoutForInputDevice(@NonNull android.hardware.input.InputDeviceIdentifier, @NonNull String); @@ -3429,14 +3433,20 @@ package android.window { public class TaskFragmentOrganizer extends android.window.WindowOrganizer { ctor public TaskFragmentOrganizer(@NonNull java.util.concurrent.Executor); + method public void applyTransaction(@NonNull android.window.WindowContainerTransaction, int, boolean); method @NonNull public java.util.concurrent.Executor getExecutor(); method @NonNull public android.window.TaskFragmentOrganizerToken getOrganizerToken(); + method public void onTransactionHandled(@NonNull android.os.IBinder, @NonNull android.window.WindowContainerTransaction, int, boolean); method public void onTransactionReady(@NonNull android.window.TaskFragmentTransaction); method @CallSuper public void registerOrganizer(); method @CallSuper public void unregisterOrganizer(); field public static final String KEY_ERROR_CALLBACK_OP_TYPE = "operation_type"; field public static final String KEY_ERROR_CALLBACK_TASK_FRAGMENT_INFO = "task_fragment_info"; field public static final String KEY_ERROR_CALLBACK_THROWABLE = "fragment_throwable"; + field public static final int TASK_FRAGMENT_TRANSIT_CHANGE = 6; // 0x6 + field public static final int TASK_FRAGMENT_TRANSIT_CLOSE = 2; // 0x2 + field public static final int TASK_FRAGMENT_TRANSIT_NONE = 0; // 0x0 + field public static final int TASK_FRAGMENT_TRANSIT_OPEN = 1; // 0x1 } public final class TaskFragmentOrganizerToken implements android.os.Parcelable { @@ -3558,8 +3568,8 @@ package android.window { public class WindowOrganizer { ctor public WindowOrganizer(); - method @RequiresPermission(value=android.Manifest.permission.MANAGE_ACTIVITY_TASKS, conditional=true) public int applySyncTransaction(@NonNull android.window.WindowContainerTransaction, @NonNull android.window.WindowContainerTransactionCallback); - method @RequiresPermission(value=android.Manifest.permission.MANAGE_ACTIVITY_TASKS, conditional=true) public void applyTransaction(@NonNull android.window.WindowContainerTransaction); + method @RequiresPermission(android.Manifest.permission.MANAGE_ACTIVITY_TASKS) public int applySyncTransaction(@NonNull android.window.WindowContainerTransaction, @NonNull android.window.WindowContainerTransactionCallback); + method @RequiresPermission(android.Manifest.permission.MANAGE_ACTIVITY_TASKS) public void applyTransaction(@NonNull android.window.WindowContainerTransaction); } @UiContext public abstract class WindowProviderService extends android.app.Service { diff --git a/core/java/Android.bp b/core/java/Android.bp index 128e3de49fbf..738e2de7d44b 100644 --- a/core/java/Android.bp +++ b/core/java/Android.bp @@ -368,6 +368,20 @@ aidl_interface { }, } +// Build Rust bindings for remote provisioning. Needed by keystore2. +aidl_interface { + name: "android.security.rkp_aidl", + unstable: true, + srcs: [ + "android/security/rkp/*.aidl", + ], + backend: { + rust: { + enabled: true, + }, + }, +} + aidl_interface { name: "android.debug_aidl", unstable: true, diff --git a/core/java/android/animation/Animator.java b/core/java/android/animation/Animator.java index a9d14df8bcf4..8142ee5806ca 100644 --- a/core/java/android/animation/Animator.java +++ b/core/java/android/animation/Animator.java @@ -23,6 +23,7 @@ import android.compat.annotation.UnsupportedAppUsage; import android.content.pm.ActivityInfo.Config; import android.content.res.ConstantState; import android.os.Build; +import android.util.LongArray; import java.util.ArrayList; @@ -559,9 +560,36 @@ public abstract class Animator implements Cloneable { } /** - * Internal use only. + * Internal use only. Changes the value of the animator as if currentPlayTime has passed since + * the start of the animation. Therefore, currentPlayTime includes the start delay, and any + * repetition. lastPlayTime is similar and is used to calculate how many repeats have been + * done between the two times. + */ + void animateValuesInRange(long currentPlayTime, long lastPlayTime) {} + + /** + * Internal use only. This animates any animation that has ended since lastPlayTime. + * If an animation hasn't been finished, no change will be made. */ - void animateBasedOnPlayTime(long currentPlayTime, long lastPlayTime, boolean inReverse) {} + void animateSkipToEnds(long currentPlayTime, long lastPlayTime) {} + + /** + * Internal use only. Adds all start times (after delay) to and end times to times. + * The value must include offset. + */ + void getStartAndEndTimes(LongArray times, long offset) { + long startTime = offset + getStartDelay(); + if (times.indexOf(startTime) < 0) { + times.add(startTime); + } + long duration = getTotalDuration(); + if (duration != DURATION_INFINITE) { + long endTime = duration + offset; + if (times.indexOf(endTime) < 0) { + times.add(endTime); + } + } + } /** * <p>An animation listener receives notifications from an animation. diff --git a/core/java/android/animation/AnimatorSet.java b/core/java/android/animation/AnimatorSet.java index bc8db029e06d..54aaafc6c30a 100644 --- a/core/java/android/animation/AnimatorSet.java +++ b/core/java/android/animation/AnimatorSet.java @@ -23,9 +23,11 @@ import android.os.Looper; import android.util.AndroidRuntimeException; import android.util.ArrayMap; import android.util.Log; +import android.util.LongArray; import android.view.animation.Animation; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; @@ -181,6 +183,11 @@ public final class AnimatorSet extends Animator implements AnimationHandler.Anim */ private long mPauseTime = -1; + /** + * The start and stop times of all descendant animators. + */ + private long[] mChildStartAndStopTimes; + // This is to work around a bug in b/34736819. This needs to be removed once app team // fixes their side. private AnimatorListenerAdapter mAnimationEndListener = new AnimatorListenerAdapter() { @@ -779,26 +786,25 @@ public final class AnimatorSet extends Animator implements AnimationHandler.Anim @Override void skipToEndValue(boolean inReverse) { - if (!isInitialized()) { - throw new UnsupportedOperationException("Children must be initialized."); - } - // This makes sure the animation events are sorted an up to date. initAnimation(); + initChildren(); // Calling skip to the end in the sequence that they would be called in a forward/reverse // run, such that the sequential animations modifying the same property would have // the right value in the end. if (inReverse) { for (int i = mEvents.size() - 1; i >= 0; i--) { - if (mEvents.get(i).mEvent == AnimationEvent.ANIMATION_DELAY_ENDED) { - mEvents.get(i).mNode.mAnimation.skipToEndValue(true); + AnimationEvent event = mEvents.get(i); + if (event.mEvent == AnimationEvent.ANIMATION_DELAY_ENDED) { + event.mNode.mAnimation.skipToEndValue(true); } } } else { for (int i = 0; i < mEvents.size(); i++) { - if (mEvents.get(i).mEvent == AnimationEvent.ANIMATION_END) { - mEvents.get(i).mNode.mAnimation.skipToEndValue(false); + AnimationEvent event = mEvents.get(i); + if (event.mEvent == AnimationEvent.ANIMATION_END) { + event.mNode.mAnimation.skipToEndValue(false); } } } @@ -814,72 +820,181 @@ public final class AnimatorSet extends Animator implements AnimationHandler.Anim * {@link android.view.animation.Animation.AnimationListener#onAnimationRepeat(Animation)}, * as needed, based on the last play time and current play time. */ - @Override - void animateBasedOnPlayTime(long currentPlayTime, long lastPlayTime, boolean inReverse) { - if (currentPlayTime < 0 || lastPlayTime < 0) { + private void animateBasedOnPlayTime( + long currentPlayTime, + long lastPlayTime, + boolean inReverse + ) { + if (currentPlayTime < 0 || lastPlayTime < -1) { throw new UnsupportedOperationException("Error: Play time should never be negative."); } // TODO: take into account repeat counts and repeat callback when repeat is implemented. - // Clamp currentPlayTime and lastPlayTime - - // TODO: Make this more efficient - // Convert the play times to the forward direction. if (inReverse) { - if (getTotalDuration() == DURATION_INFINITE) { - throw new UnsupportedOperationException("Cannot reverse AnimatorSet with infinite" - + " duration"); + long duration = getTotalDuration(); + if (duration == DURATION_INFINITE) { + throw new UnsupportedOperationException( + "Cannot reverse AnimatorSet with infinite duration" + ); } - long duration = getTotalDuration() - mStartDelay; + // Convert the play times to the forward direction. currentPlayTime = Math.min(currentPlayTime, duration); currentPlayTime = duration - currentPlayTime; lastPlayTime = duration - lastPlayTime; - inReverse = false; } - ArrayList<Node> unfinishedNodes = new ArrayList<>(); - // Assumes forward playing from here on. - for (int i = 0; i < mEvents.size(); i++) { - AnimationEvent event = mEvents.get(i); - if (event.getTime() > currentPlayTime || event.getTime() == DURATION_INFINITE) { - break; + long[] startEndTimes = ensureChildStartAndEndTimes(); + int index = findNextIndex(lastPlayTime, startEndTimes); + int endIndex = findNextIndex(currentPlayTime, startEndTimes); + + // Change values at the start/end times so that values are set in the right order. + // We don't want an animator that would finish before another to override the value + // set by another animator that finishes earlier. + if (currentPlayTime >= lastPlayTime) { + while (index < endIndex) { + long playTime = startEndTimes[index]; + if (lastPlayTime != playTime) { + animateSkipToEnds(playTime, lastPlayTime); + animateValuesInRange(playTime, lastPlayTime); + lastPlayTime = playTime; + } + index++; } + } else { + while (index > endIndex) { + index--; + long playTime = startEndTimes[index]; + if (lastPlayTime != playTime) { + animateSkipToEnds(playTime, lastPlayTime); + animateValuesInRange(playTime, lastPlayTime); + lastPlayTime = playTime; + } + } + } + if (currentPlayTime != lastPlayTime) { + animateSkipToEnds(currentPlayTime, lastPlayTime); + animateValuesInRange(currentPlayTime, lastPlayTime); + } + } - // This animation started prior to the current play time, and won't finish before the - // play time, add to the unfinished list. - if (event.mEvent == AnimationEvent.ANIMATION_DELAY_ENDED) { - if (event.mNode.mEndTime == DURATION_INFINITE - || event.mNode.mEndTime > currentPlayTime) { - unfinishedNodes.add(event.mNode); + /** + * Looks through startEndTimes for playTime. If it is in startEndTimes, the index after + * is returned. Otherwise, it returns the index at which it would be placed if it were + * to be inserted. + */ + private int findNextIndex(long playTime, long[] startEndTimes) { + int index = Arrays.binarySearch(startEndTimes, playTime); + if (index < 0) { + index = -index - 1; + } else { + index++; + } + return index; + } + + @Override + void animateSkipToEnds(long currentPlayTime, long lastPlayTime) { + initAnimation(); + + if (lastPlayTime > currentPlayTime) { + for (int i = mEvents.size() - 1; i >= 0; i--) { + AnimationEvent event = mEvents.get(i); + Node node = event.mNode; + if (event.mEvent == AnimationEvent.ANIMATION_END + && node.mStartTime != DURATION_INFINITE + ) { + Animator animator = node.mAnimation; + long start = node.mStartTime + animator.getStartDelay(); + long end = node.mTotalDuration == DURATION_INFINITE + ? Long.MAX_VALUE : node.mEndTime; + if (currentPlayTime <= start && start < lastPlayTime) { + animator.animateSkipToEnds( + start - node.mStartTime, + lastPlayTime - node.mStartTime + ); + } else if (start <= currentPlayTime && currentPlayTime <= end) { + animator.animateSkipToEnds( + currentPlayTime - node.mStartTime, + lastPlayTime - node.mStartTime + ); + } } } - // For animations that do finish before the play time, end them in the sequence that - // they would in a normal run. - if (event.mEvent == AnimationEvent.ANIMATION_END) { - // Skip to the end of the animation. - event.mNode.mAnimation.skipToEndValue(false); + } else { + int eventsSize = mEvents.size(); + for (int i = 0; i < eventsSize; i++) { + AnimationEvent event = mEvents.get(i); + Node node = event.mNode; + if (event.mEvent == AnimationEvent.ANIMATION_DELAY_ENDED + && node.mStartTime != DURATION_INFINITE + ) { + Animator animator = node.mAnimation; + long start = node.mStartTime + animator.getStartDelay(); + long end = node.mTotalDuration == DURATION_INFINITE + ? Long.MAX_VALUE : node.mEndTime; + if (lastPlayTime < end && end <= currentPlayTime) { + animator.animateSkipToEnds( + end - node.mStartTime, + lastPlayTime - node.mStartTime + ); + } else if (start <= currentPlayTime && currentPlayTime <= end) { + animator.animateSkipToEnds( + currentPlayTime - node.mStartTime, + lastPlayTime - node.mStartTime + ); + } + } } } + } - // Seek unfinished animation to the right time. - for (int i = 0; i < unfinishedNodes.size(); i++) { - Node node = unfinishedNodes.get(i); - long playTime = getPlayTimeForNode(currentPlayTime, node, inReverse); - if (!inReverse) { - playTime -= node.mAnimation.getStartDelay(); + @Override + void animateValuesInRange(long currentPlayTime, long lastPlayTime) { + initAnimation(); + + int eventsSize = mEvents.size(); + for (int i = 0; i < eventsSize; i++) { + AnimationEvent event = mEvents.get(i); + Node node = event.mNode; + if (event.mEvent == AnimationEvent.ANIMATION_DELAY_ENDED + && node.mStartTime != DURATION_INFINITE + ) { + Animator animator = node.mAnimation; + long start = node.mStartTime + animator.getStartDelay(); + long end = node.mTotalDuration == DURATION_INFINITE + ? Long.MAX_VALUE : node.mEndTime; + if (start < currentPlayTime && currentPlayTime < end) { + animator.animateValuesInRange( + currentPlayTime - node.mStartTime, + Math.max(-1, lastPlayTime - node.mStartTime) + ); + } } - node.mAnimation.animateBasedOnPlayTime(playTime, lastPlayTime, inReverse); } + } + + private long[] ensureChildStartAndEndTimes() { + if (mChildStartAndStopTimes == null) { + LongArray startAndEndTimes = new LongArray(); + getStartAndEndTimes(startAndEndTimes, 0); + long[] times = startAndEndTimes.toArray(); + Arrays.sort(times); + mChildStartAndStopTimes = times; + } + return mChildStartAndStopTimes; + } - // Seek not yet started animations. - for (int i = 0; i < mEvents.size(); i++) { + @Override + void getStartAndEndTimes(LongArray times, long offset) { + int eventsSize = mEvents.size(); + for (int i = 0; i < eventsSize; i++) { AnimationEvent event = mEvents.get(i); - if (event.getTime() > currentPlayTime - && event.mEvent == AnimationEvent.ANIMATION_DELAY_ENDED) { - event.mNode.mAnimation.skipToEndValue(true); + if (event.mEvent == AnimationEvent.ANIMATION_DELAY_ENDED + && event.mNode.mStartTime != DURATION_INFINITE + ) { + event.mNode.mAnimation.getStartAndEndTimes(times, offset + event.mNode.mStartTime); } } - } @Override @@ -899,10 +1014,6 @@ public final class AnimatorSet extends Animator implements AnimationHandler.Anim return mChildrenInitialized; } - private void skipToStartValue(boolean inReverse) { - skipToEndValue(!inReverse); - } - /** * Sets the position of the animation to the specified point in time. This time should * be between 0 and the total duration of the animation, including any repetition. If @@ -926,23 +1037,25 @@ public final class AnimatorSet extends Animator implements AnimationHandler.Anim if ((getTotalDuration() != DURATION_INFINITE && playTime > getTotalDuration() - mStartDelay) || playTime < 0) { throw new UnsupportedOperationException("Error: Play time should always be in between" - + "0 and duration."); + + " 0 and duration."); } initAnimation(); if (!isStarted() || isPaused()) { - if (mReversing) { + if (mReversing && !isStarted()) { throw new UnsupportedOperationException("Error: Something went wrong. mReversing" + " should not be set when AnimatorSet is not started."); } + long lastPlayTime = mSeekState.getPlayTime(); if (!mSeekState.isActive()) { findLatestEventIdForTime(0); - // Set all the values to start values. initChildren(); + // Set all the values to start values. + skipToEndValue(!mReversing); mSeekState.setPlayTime(0, mReversing); } - animateBasedOnPlayTime(playTime, 0, mReversing); + animateBasedOnPlayTime(playTime, lastPlayTime, mReversing); mSeekState.setPlayTime(playTime, mReversing); } else { // If the animation is running, just set the seek time and wait until the next frame @@ -981,10 +1094,16 @@ public final class AnimatorSet extends Animator implements AnimationHandler.Anim private void initChildren() { if (!isInitialized()) { mChildrenInitialized = true; - // Forcefully initialize all children based on their end time, so that if the start - // value of a child is dependent on a previous animation, the animation will be - // initialized after the the previous animations have been advanced to the end. - skipToEndValue(false); + + // We have to initialize all the start values so that they are based on the previous + // values. + long[] times = ensureChildStartAndEndTimes(); + + long previousTime = -1; + for (long time : times) { + animateBasedOnPlayTime(time, previousTime, false); + previousTime = time; + } } } @@ -1058,7 +1177,7 @@ public final class AnimatorSet extends Animator implements AnimationHandler.Anim for (int i = 0; i < mPlayingSet.size(); i++) { Node node = mPlayingSet.get(i); if (!node.mEnded) { - pulseFrame(node, getPlayTimeForNode(unscaledPlayTime, node)); + pulseFrame(node, getPlayTimeForNodeIncludingDelay(unscaledPlayTime, node)); } } @@ -1129,7 +1248,7 @@ public final class AnimatorSet extends Animator implements AnimationHandler.Anim pulseFrame(node, 0); } else if (event.mEvent == AnimationEvent.ANIMATION_DELAY_ENDED && !node.mEnded) { // end event: - pulseFrame(node, getPlayTimeForNode(playTime, node)); + pulseFrame(node, getPlayTimeForNodeIncludingDelay(playTime, node)); } } } else { @@ -1150,7 +1269,7 @@ public final class AnimatorSet extends Animator implements AnimationHandler.Anim pulseFrame(node, 0); } else if (event.mEvent == AnimationEvent.ANIMATION_END && !node.mEnded) { // start event: - pulseFrame(node, getPlayTimeForNode(playTime, node)); + pulseFrame(node, getPlayTimeForNodeIncludingDelay(playTime, node)); } } } @@ -1172,11 +1291,15 @@ public final class AnimatorSet extends Animator implements AnimationHandler.Anim } } - private long getPlayTimeForNode(long overallPlayTime, Node node) { - return getPlayTimeForNode(overallPlayTime, node, mReversing); + private long getPlayTimeForNodeIncludingDelay(long overallPlayTime, Node node) { + return getPlayTimeForNodeIncludingDelay(overallPlayTime, node, mReversing); } - private long getPlayTimeForNode(long overallPlayTime, Node node, boolean inReverse) { + private long getPlayTimeForNodeIncludingDelay( + long overallPlayTime, + Node node, + boolean inReverse + ) { if (inReverse) { overallPlayTime = getTotalDuration() - overallPlayTime; return node.mEndTime - overallPlayTime; @@ -1198,26 +1321,8 @@ public final class AnimatorSet extends Animator implements AnimationHandler.Anim } // Set the child animators to the right end: if (mShouldResetValuesAtStart) { - if (isInitialized()) { - skipToEndValue(!mReversing); - } else if (mReversing) { - // Reversing but haven't initialized all the children yet. - initChildren(); - skipToEndValue(!mReversing); - } else { - // If not all children are initialized and play direction is forward - for (int i = mEvents.size() - 1; i >= 0; i--) { - if (mEvents.get(i).mEvent == AnimationEvent.ANIMATION_DELAY_ENDED) { - Animator anim = mEvents.get(i).mNode.mAnimation; - // Only reset the animations that have been initialized to start value, - // so that if they are defined without a start value, they will get the - // values set at the right time (i.e. the next animation run) - if (anim.isInitialized()) { - anim.skipToEndValue(true); - } - } - } - } + initChildren(); + skipToEndValue(!mReversing); } if (mReversing || mStartDelay == 0 || mSeekState.isActive()) { @@ -1922,11 +2027,11 @@ public final class AnimatorSet extends Animator implements AnimationHandler.Anim } void setPlayTime(long playTime, boolean inReverse) { - // TODO: This can be simplified. - // Clamp the play time if (getTotalDuration() != DURATION_INFINITE) { mPlayTime = Math.min(playTime, getTotalDuration() - mStartDelay); + } else { + mPlayTime = playTime; } mPlayTime = Math.max(0, mPlayTime); mSeekingInReverse = inReverse; diff --git a/core/java/android/animation/ValueAnimator.java b/core/java/android/animation/ValueAnimator.java index 6ab7ae6d0cee..d41c03d9ab82 100644 --- a/core/java/android/animation/ValueAnimator.java +++ b/core/java/android/animation/ValueAnimator.java @@ -324,8 +324,9 @@ public class ValueAnimator extends Animator implements AnimationHandler.Animatio listenerCopy = new ArrayList<>(sDurationScaleChangeListeners); } - for (WeakReference<DurationScaleChangeListener> listenerRef : listenerCopy) { - final DurationScaleChangeListener listener = listenerRef.get(); + int listenersSize = listenerCopy.size(); + for (int i = 0; i < listenersSize; i++) { + final DurationScaleChangeListener listener = listenerCopy.get(i).get(); if (listener != null) { listener.onChanged(durationScale); } @@ -624,7 +625,7 @@ public class ValueAnimator extends Animator implements AnimationHandler.Animatio public void setValues(PropertyValuesHolder... values) { int numValues = values.length; mValues = values; - mValuesMap = new HashMap<String, PropertyValuesHolder>(numValues); + mValuesMap = new HashMap<>(numValues); for (int i = 0; i < numValues; ++i) { PropertyValuesHolder valuesHolder = values[i]; mValuesMap.put(valuesHolder.getPropertyName(), valuesHolder); @@ -658,9 +659,11 @@ public class ValueAnimator extends Animator implements AnimationHandler.Animatio @CallSuper void initAnimation() { if (!mInitialized) { - int numValues = mValues.length; - for (int i = 0; i < numValues; ++i) { - mValues[i].init(); + if (mValues != null) { + int numValues = mValues.length; + for (int i = 0; i < numValues; ++i) { + mValues[i].init(); + } } mInitialized = true; } @@ -1209,10 +1212,14 @@ public class ValueAnimator extends Animator implements AnimationHandler.Animatio // If it's not yet running, then start listeners weren't called. Call them now. notifyStartListeners(); } - ArrayList<AnimatorListener> tmpListeners = - (ArrayList<AnimatorListener>) mListeners.clone(); - for (AnimatorListener listener : tmpListeners) { - listener.onAnimationCancel(this); + int listenersSize = mListeners.size(); + if (listenersSize > 0) { + ArrayList<AnimatorListener> tmpListeners = + (ArrayList<AnimatorListener>) mListeners.clone(); + for (int i = 0; i < listenersSize; i++) { + AnimatorListener listener = tmpListeners.get(i); + listener.onAnimationCancel(this); + } } } endAnimation(); @@ -1452,12 +1459,19 @@ public class ValueAnimator extends Animator implements AnimationHandler.Animatio * will be called. */ @Override - void animateBasedOnPlayTime(long currentPlayTime, long lastPlayTime, boolean inReverse) { - if (currentPlayTime < 0 || lastPlayTime < 0) { + void animateValuesInRange(long currentPlayTime, long lastPlayTime) { + if (currentPlayTime < mStartDelay || lastPlayTime < -1) { throw new UnsupportedOperationException("Error: Play time should never be negative."); } initAnimation(); + long duration = getTotalDuration(); + if (duration >= 0) { + lastPlayTime = Math.min(duration, lastPlayTime); + } + lastPlayTime -= mStartDelay; + currentPlayTime -= mStartDelay; + // Check whether repeat callback is needed only when repeat count is non-zero if (mRepeatCount > 0) { int iteration = (int) (currentPlayTime / mDuration); @@ -1478,15 +1492,27 @@ public class ValueAnimator extends Animator implements AnimationHandler.Animatio } if (mRepeatCount != INFINITE && currentPlayTime >= (mRepeatCount + 1) * mDuration) { - skipToEndValue(inReverse); + throw new IllegalStateException("Can't animate a value outside of the duration"); } else { // Find the current fraction: float fraction = currentPlayTime / (float) mDuration; - fraction = getCurrentIterationFraction(fraction, inReverse); + fraction = getCurrentIterationFraction(fraction, false); animateValue(fraction); } } + @Override + void animateSkipToEnds(long currentPlayTime, long lastPlayTime) { + if (currentPlayTime <= mStartDelay && lastPlayTime > mStartDelay) { + skipToEndValue(true); + } else { + long duration = getTotalDuration(); + if (duration >= 0 && currentPlayTime >= duration && lastPlayTime < duration) { + skipToEndValue(false); + } + } + } + /** * Internal use only. * Skips the animation value to end/start, depending on whether the play direction is forward @@ -1641,6 +1667,9 @@ public class ValueAnimator extends Animator implements AnimationHandler.Animatio Trace.traceCounter(Trace.TRACE_TAG_VIEW, getNameForTrace() + hashCode(), (int) (fraction * 1000)); } + if (mValues == null) { + return; + } fraction = mInterpolator.getInterpolation(fraction); mCurrentFraction = fraction; int numValues = mValues.length; diff --git a/core/java/android/app/ActivityManagerInternal.java b/core/java/android/app/ActivityManagerInternal.java index f62190a7e6ca..c51e8aee61f0 100644 --- a/core/java/android/app/ActivityManagerInternal.java +++ b/core/java/android/app/ActivityManagerInternal.java @@ -902,4 +902,9 @@ public abstract class ActivityManagerInternal { */ public abstract void registerNetworkPolicyUidObserver(@NonNull IUidObserver observer, int which, int cutpoint, @NonNull String callingPackage); + + /** + * Return all client package names of a service. + */ + public abstract ArraySet<String> getClientPackages(String servicePackageName); } diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java index 31cbe28334f9..a4c9f8c88eda 100644 --- a/core/java/android/app/ActivityThread.java +++ b/core/java/android/app/ActivityThread.java @@ -1020,6 +1020,12 @@ public final class ActivityThread extends ClientTransactionHandler int flags; } + // A list of receivers and an index into the receiver to be processed next. + static final class ReceiverList { + List<ReceiverInfo> receivers; + int index; + } + private class ApplicationThread extends IApplicationThread.Stub { private static final String DB_CONNECTION_INFO_HEADER = " %8s %8s %14s %5s %5s %5s %s"; private static final String DB_CONNECTION_INFO_FORMAT = " %8s %8s %14s %5d %5d %5d %s"; @@ -1036,6 +1042,21 @@ public final class ActivityThread extends ClientTransactionHandler sendMessage(H.RECEIVER, r); } + public final void scheduleReceiverList(List<ReceiverInfo> info) throws RemoteException { + for (int i = 0; i < info.size(); i++) { + ReceiverInfo r = info.get(i); + if (r.registered) { + scheduleRegisteredReceiver(r.receiver, r.intent, + r.resultCode, r.data, r.extras, r.ordered, r.sticky, + r.sendingUser, r.processState); + } else { + scheduleReceiver(r.intent, r.activityInfo, r.compatInfo, + r.resultCode, r.data, r.extras, r.sync, + r.sendingUser, r.processState); + } + } + } + public final void scheduleCreateBackupAgent(ApplicationInfo app, int backupMode, int userId, @BackupDestination int backupDestination) { CreateBackupAgentData d = new CreateBackupAgentData(); diff --git a/core/java/android/app/Dialog.java b/core/java/android/app/Dialog.java index de0f7522f36d..411d157fa927 100644 --- a/core/java/android/app/Dialog.java +++ b/core/java/android/app/Dialog.java @@ -458,8 +458,7 @@ public class Dialog implements DialogInterface, Window.Callback, && WindowOnBackInvokedDispatcher.isOnBackInvokedCallbackEnabled(mContext)) { // Add onBackPressed as default back behavior. mDefaultBackCallback = this::onBackPressed; - getOnBackInvokedDispatcher().registerOnBackInvokedCallback( - OnBackInvokedDispatcher.PRIORITY_DEFAULT, mDefaultBackCallback); + getOnBackInvokedDispatcher().registerSystemOnBackInvokedCallback(mDefaultBackCallback); mDefaultBackCallback = null; } } diff --git a/core/java/android/app/GameManager.java b/core/java/android/app/GameManager.java index 2f51b174113c..c6fa064a6b0f 100644 --- a/core/java/android/app/GameManager.java +++ b/core/java/android/app/GameManager.java @@ -287,6 +287,7 @@ public final class GameManager { * <p> * The caller must have {@link android.Manifest.permission#MANAGE_GAME_MODE}. * + * @param packageName The package name of the game to update * @param gameModeConfig The configuration to use for game mode interventions * @hide */ diff --git a/core/java/android/app/GameModeConfiguration.java b/core/java/android/app/GameModeConfiguration.java index b081e82e19b0..d8be814374ff 100644 --- a/core/java/android/app/GameModeConfiguration.java +++ b/core/java/android/app/GameModeConfiguration.java @@ -62,10 +62,16 @@ public final class GameModeConfiguration implements Parcelable { */ @SystemApi public static final class Builder { - /** Constructs a new Builder for a game mode’s configuration */ + /** Constructs a new Builder for a game mode’s configuration. */ public Builder() { } + /** Constructs a new builder by copying from an existing game mode configuration. */ + public Builder(@NonNull GameModeConfiguration configuration) { + mFpsOverride = configuration.mFpsOverride; + mScalingFactor = configuration.mScalingFactor; + } + /** * Sets the scaling factor used for game resolution downscaling. * <br> @@ -156,16 +162,6 @@ public final class GameModeConfiguration implements Parcelable { return mFpsOverride; } - /** - * Converts and returns the game mode config as a new builder. - */ - @NonNull - public GameModeConfiguration.Builder toBuilder() { - return new GameModeConfiguration.Builder() - .setFpsOverride(mFpsOverride) - .setScalingFactor(mScalingFactor); - } - @Override public boolean equals(Object obj) { if (obj == this) { diff --git a/core/java/android/app/GameModeInfo.java b/core/java/android/app/GameModeInfo.java index 31255c2e381f..7dcb3909f0b9 100644 --- a/core/java/android/app/GameModeInfo.java +++ b/core/java/android/app/GameModeInfo.java @@ -87,12 +87,12 @@ public final class GameModeInfo implements Parcelable { } /** - * Sets the opted-in game modes. + * Sets the overridden game modes. */ @NonNull - public GameModeInfo.Builder setOptedInGameModes( - @NonNull @GameManager.GameMode int[] optedInGameModes) { - mOptedInGameModes = optedInGameModes; + public GameModeInfo.Builder setOverriddenGameModes( + @NonNull @GameManager.GameMode int[] overriddenGameModes) { + mOverriddenGameModes = overriddenGameModes; return this; } @@ -140,12 +140,12 @@ public final class GameModeInfo implements Parcelable { */ @NonNull public GameModeInfo build() { - return new GameModeInfo(mActiveGameMode, mAvailableGameModes, mOptedInGameModes, + return new GameModeInfo(mActiveGameMode, mAvailableGameModes, mOverriddenGameModes, mIsDownscalingAllowed, mIsFpsOverrideAllowed, mConfigMap); } private @GameManager.GameMode int[] mAvailableGameModes = new int[]{}; - private @GameManager.GameMode int[] mOptedInGameModes = new int[]{}; + private @GameManager.GameMode int[] mOverriddenGameModes = new int[]{}; private @GameManager.GameMode int mActiveGameMode; private boolean mIsDownscalingAllowed; private boolean mIsFpsOverrideAllowed; @@ -164,11 +164,11 @@ public final class GameModeInfo implements Parcelable { private GameModeInfo(@GameManager.GameMode int activeGameMode, @NonNull @GameManager.GameMode int[] availableGameModes, - @NonNull @GameManager.GameMode int[] optedInGameModes, boolean isDownscalingAllowed, + @NonNull @GameManager.GameMode int[] overriddenGameModes, boolean isDownscalingAllowed, boolean isFpsOverrideAllowed, @NonNull Map<Integer, GameModeConfiguration> configMap) { mActiveGameMode = activeGameMode; mAvailableGameModes = Arrays.copyOf(availableGameModes, availableGameModes.length); - mOptedInGameModes = Arrays.copyOf(optedInGameModes, optedInGameModes.length); + mOverriddenGameModes = Arrays.copyOf(overriddenGameModes, overriddenGameModes.length); mIsDownscalingAllowed = isDownscalingAllowed; mIsFpsOverrideAllowed = isFpsOverrideAllowed; mConfigMap = configMap; @@ -179,7 +179,7 @@ public final class GameModeInfo implements Parcelable { public GameModeInfo(Parcel in) { mActiveGameMode = in.readInt(); mAvailableGameModes = in.createIntArray(); - mOptedInGameModes = in.createIntArray(); + mOverriddenGameModes = in.createIntArray(); mIsDownscalingAllowed = in.readBoolean(); mIsFpsOverrideAllowed = in.readBoolean(); mConfigMap = new ArrayMap<>(); @@ -198,8 +198,8 @@ public final class GameModeInfo implements Parcelable { * Gets the collection of {@link GameManager.GameMode} that can be applied to the game. * <p> * Available games include all game modes that are either supported by the OEM in device - * config, or opted in by the game developers in game mode config XML, plus the default enabled - * modes for any game including {@link GameManager#GAME_MODE_STANDARD} and + * config, or overridden by the game developers in game mode config XML, plus the default + * enabled modes for any game including {@link GameManager#GAME_MODE_STANDARD} and * {@link GameManager#GAME_MODE_CUSTOM}. * <p> * Also see {@link GameModeInfo}. @@ -210,19 +210,19 @@ public final class GameModeInfo implements Parcelable { } /** - * Gets the collection of {@link GameManager.GameMode} that are opted in by the game. + * Gets the collection of {@link GameManager.GameMode} that are overridden by the game. * <p> * Also see {@link GameModeInfo}. */ @NonNull - public @GameManager.GameMode int[] getOptedInGameModes() { - return Arrays.copyOf(mOptedInGameModes, mOptedInGameModes.length); + public @GameManager.GameMode int[] getOverriddenGameModes() { + return Arrays.copyOf(mOverriddenGameModes, mOverriddenGameModes.length); } /** * Gets the current game mode configuration of a game mode. * <p> - * The game mode can be null if it's opted in by the game itself, or not configured in device + * The game mode can be null if it's overridden by the game itself, or not configured in device * config nor set by the user as custom game mode configuration. */ public @Nullable GameModeConfiguration getGameModeConfiguration( @@ -250,7 +250,7 @@ public final class GameModeInfo implements Parcelable { private final @GameManager.GameMode int[] mAvailableGameModes; - private final @GameManager.GameMode int[] mOptedInGameModes; + private final @GameManager.GameMode int[] mOverriddenGameModes; private final @GameManager.GameMode int mActiveGameMode; private final boolean mIsDownscalingAllowed; private final boolean mIsFpsOverrideAllowed; @@ -265,7 +265,7 @@ public final class GameModeInfo implements Parcelable { public void writeToParcel(@NonNull Parcel dest, int flags) { dest.writeInt(mActiveGameMode); dest.writeIntArray(mAvailableGameModes); - dest.writeIntArray(mOptedInGameModes); + dest.writeIntArray(mOverriddenGameModes); dest.writeBoolean(mIsDownscalingAllowed); dest.writeBoolean(mIsFpsOverrideAllowed); dest.writeMap(mConfigMap); diff --git a/core/java/android/app/IApplicationThread.aidl b/core/java/android/app/IApplicationThread.aidl index 595c7f7ab008..3984fee19203 100644 --- a/core/java/android/app/IApplicationThread.aidl +++ b/core/java/android/app/IApplicationThread.aidl @@ -20,6 +20,7 @@ import android.app.ContentProviderHolder; import android.app.IInstrumentationWatcher; import android.app.IUiAutomationConnection; import android.app.ProfilerInfo; +import android.app.ReceiverInfo; import android.app.ResultInfo; import android.app.servertransaction.ClientTransaction; import android.content.AutofillOptions; @@ -66,6 +67,9 @@ oneway interface IApplicationThread { in CompatibilityInfo compatInfo, int resultCode, in String data, in Bundle extras, boolean sync, int sendingUser, int processState); + + void scheduleReceiverList(in List<ReceiverInfo> info); + @UnsupportedAppUsage void scheduleCreateService(IBinder token, in ServiceInfo info, in CompatibilityInfo compatInfo, int processState); diff --git a/core/java/android/app/ReceiverInfo.aidl b/core/java/android/app/ReceiverInfo.aidl new file mode 100644 index 000000000000..d90eee704a7e --- /dev/null +++ b/core/java/android/app/ReceiverInfo.aidl @@ -0,0 +1,60 @@ +/** + * 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.app; + +import android.content.IIntentReceiver; +import android.content.Intent; +import android.content.pm.ActivityInfo; +import android.content.res.CompatibilityInfo; +import android.os.Bundle; + +/** + * Collect the information needed for manifest and registered receivers into a single structure + * that can be the element of a list. All fields are already parcelable. + * @hide + */ +parcelable ReceiverInfo { + /** + * Fields common to registered and manifest receivers. + */ + Intent intent; + String data; + Bundle extras; + int sendingUser; + int processState; + int resultCode; + + /** + * True if this instance represents a registered receiver and false if this instance + * represents a manifest receiver. + */ + boolean registered; + + /** + * Fields used only for registered receivers. + */ + IIntentReceiver receiver; + boolean ordered; + boolean sticky; + + /** + * Fields used only for manifest receivers. + */ + ActivityInfo activityInfo; + CompatibilityInfo compatInfo; + boolean sync; +} diff --git a/core/java/android/app/ResourcesManager.java b/core/java/android/app/ResourcesManager.java index 322176100e92..7e6386e47494 100644 --- a/core/java/android/app/ResourcesManager.java +++ b/core/java/android/app/ResourcesManager.java @@ -41,6 +41,7 @@ import android.os.Trace; import android.util.ArrayMap; import android.util.ArraySet; import android.util.DisplayMetrics; +import android.util.IndentingPrintWriter; import android.util.Log; import android.util.Pair; import android.util.Slog; @@ -51,7 +52,6 @@ import android.window.WindowContext; import com.android.internal.annotations.VisibleForTesting; import com.android.internal.util.ArrayUtils; -import com.android.internal.util.IndentingPrintWriter; import java.io.IOException; import java.io.PrintWriter; @@ -173,6 +173,7 @@ public class ResourcesManager { /** * The ApkAssets that are being referenced in the wild that we can reuse. + * Used as a lock for itself as well. */ private final ArrayMap<ApkKey, WeakReference<ApkAssets>> mCachedApkAssets = new ArrayMap<>(); @@ -286,42 +287,43 @@ public class ResourcesManager { * try as hard as possible to release any open FDs. */ public void invalidatePath(String path) { + final List<ResourcesImpl> implsToFlush = new ArrayList<>(); synchronized (mLock) { - int count = 0; - for (int i = mResourceImpls.size() - 1; i >= 0; i--) { final ResourcesKey key = mResourceImpls.keyAt(i); if (key.isPathReferenced(path)) { - ResourcesImpl impl = mResourceImpls.removeAt(i).get(); - if (impl != null) { - impl.flushLayoutCache(); + ResourcesImpl resImpl = mResourceImpls.removeAt(i).get(); + if (resImpl != null) { + implsToFlush.add(resImpl); } - count++; } } - - Log.i(TAG, "Invalidated " + count + " asset managers that referenced " + path); - + } + for (int i = 0; i < implsToFlush.size(); i++) { + implsToFlush.get(i).flushLayoutCache(); + } + final List<ApkAssets> assetsToClose = new ArrayList<>(); + synchronized (mCachedApkAssets) { for (int i = mCachedApkAssets.size() - 1; i >= 0; i--) { final ApkKey key = mCachedApkAssets.keyAt(i); if (key.path.equals(path)) { final WeakReference<ApkAssets> apkAssetsRef = mCachedApkAssets.removeAt(i); - if (apkAssetsRef == null) { - continue; - } - final ApkAssets apkAssets = apkAssetsRef.get(); + final ApkAssets apkAssets = apkAssetsRef != null ? apkAssetsRef.get() : null; if (apkAssets != null) { - apkAssets.close(); + assetsToClose.add(apkAssets); } } } } + for (int i = 0; i < assetsToClose.size(); i++) { + assetsToClose.get(i).close(); + } + Log.i(TAG, + "Invalidated " + implsToFlush.size() + " asset managers that referenced " + path); } public Configuration getConfiguration() { - synchronized (mLock) { - return mResConfiguration; - } + return mResConfiguration; } @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE) @@ -406,14 +408,12 @@ public class ResourcesManager { * @param resources The {@link Resources} backing the display adjustments. */ public Display getAdjustedDisplay(final int displayId, Resources resources) { - synchronized (mLock) { - final DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance(); - if (dm == null) { - // may be null early in system startup - return null; - } - return dm.getCompatibleDisplay(displayId, resources); + final DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance(); + if (dm == null) { + // may be null early in system startup + return null; } + return dm.getCompatibleDisplay(displayId, resources); } /** @@ -451,7 +451,7 @@ public class ResourcesManager { // Optimistically check if this ApkAssets exists somewhere else. final WeakReference<ApkAssets> apkAssetsRef; - synchronized (mLock) { + synchronized (mCachedApkAssets) { apkAssetsRef = mCachedApkAssets.get(key); } if (apkAssetsRef != null) { @@ -474,7 +474,7 @@ public class ResourcesManager { apkAssets = ApkAssets.loadFromPath(key.path, flags); } - synchronized (mLock) { + synchronized (mCachedApkAssets) { mCachedApkAssets.put(key, new WeakReference<>(apkAssets)); } @@ -586,28 +586,33 @@ public class ResourcesManager { * @hide */ public void dump(String prefix, PrintWriter printWriter) { + final int references; + final int resImpls; synchronized (mLock) { - IndentingPrintWriter pw = new IndentingPrintWriter(printWriter, " "); - for (int i = 0; i < prefix.length() / 2; i++) { - pw.increaseIndent(); - } - - pw.println("ResourcesManager:"); - pw.increaseIndent(); - pw.print("total apks: "); - pw.println(countLiveReferences(mCachedApkAssets.values())); - - pw.print("resources: "); - - int references = countLiveReferences(mResourceReferences); + int refs = countLiveReferences(mResourceReferences); for (ActivityResources activityResources : mActivityResourceReferences.values()) { - references += activityResources.countLiveReferences(); + refs += activityResources.countLiveReferences(); } - pw.println(references); + references = refs; + resImpls = countLiveReferences(mResourceImpls.values()); + } + final int liveAssets; + synchronized (mCachedApkAssets) { + liveAssets = countLiveReferences(mCachedApkAssets.values()); + } - pw.print("resource impls: "); - pw.println(countLiveReferences(mResourceImpls.values())); + final var pw = new IndentingPrintWriter(printWriter, " "); + for (int i = 0; i < prefix.length() / 2; i++) { + pw.increaseIndent(); } + pw.println("ResourcesManager:"); + pw.increaseIndent(); + pw.print("total apks: "); + pw.println(liveAssets); + pw.print("resources: "); + pw.println(references); + pw.print("resource impls: "); + pw.println(resImpls); } private Configuration generateConfig(@NonNull ResourcesKey key) { diff --git a/core/java/android/app/StatusBarManager.java b/core/java/android/app/StatusBarManager.java index a035375f2f82..f63f406f847d 100644 --- a/core/java/android/app/StatusBarManager.java +++ b/core/java/android/app/StatusBarManager.java @@ -234,7 +234,10 @@ public class StatusBarManager { /** * Session flag for {@link #registerSessionListener} indicating the listener - * is interested in sessions on the keygaurd + * is interested in sessions on the keygaurd. + * Keyguard Session Boundaries: + * START_SESSION: device starts going to sleep OR the keyguard is newly shown + * END_SESSION: device starts going to sleep OR keyguard is no longer showing * @hide */ public static final int SESSION_KEYGUARD = 1 << 0; diff --git a/core/java/android/app/WallpaperManager.java b/core/java/android/app/WallpaperManager.java index f5d657c4b388..84b404de9860 100644 --- a/core/java/android/app/WallpaperManager.java +++ b/core/java/android/app/WallpaperManager.java @@ -807,9 +807,33 @@ public class WallpaperManager { * is not able to access the wallpaper. */ @RequiresPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) + @Nullable public Drawable getDrawable() { + return getDrawable(FLAG_SYSTEM); + } + + /** + * Retrieve the requested wallpaper; if + * no wallpaper is set, the requested built-in static wallpaper is returned. + * This is returned as an + * abstract Drawable that you can install in a View to display whatever + * wallpaper the user has currently set. + * <p> + * This method can return null if the requested wallpaper is not available, if + * wallpapers are not supported in the current user, or if the calling app is not + * permitted to access the requested wallpaper. + * + * @param which The {@code FLAG_*} identifier of a valid wallpaper type. Throws + * IllegalArgumentException if an invalid wallpaper is requested. + * @return Returns a Drawable object that will draw the requested wallpaper, + * or {@code null} if the requested wallpaper does not exist or if the calling application + * is not able to access the wallpaper. + */ + @RequiresPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) + @Nullable + public Drawable getDrawable(@SetWallpaperFlags int which) { final ColorManagementProxy cmProxy = getColorManagementProxy(); - Bitmap bm = sGlobals.peekWallpaperBitmap(mContext, true, FLAG_SYSTEM, cmProxy); + Bitmap bm = sGlobals.peekWallpaperBitmap(mContext, true, which, cmProxy); if (bm != null) { Drawable dr = new BitmapDrawable(mContext.getResources(), bm); dr.setDither(false); @@ -1035,11 +1059,28 @@ public class WallpaperManager { * wallpaper the user has currently set. * * @return Returns a Drawable object that will draw the wallpaper or a - * null pointer if these is none. + * null pointer if wallpaper is unset. */ + @Nullable public Drawable peekDrawable() { + return peekDrawable(FLAG_SYSTEM); + } + + /** + * Retrieve the requested wallpaper; if there is no wallpaper set, + * a null pointer is returned. This is returned as an + * abstract Drawable that you can install in a View to display whatever + * wallpaper the user has currently set. + * + * @param which The {@code FLAG_*} identifier of a valid wallpaper type. Throws + * IllegalArgumentException if an invalid wallpaper is requested. + * @return Returns a Drawable object that will draw the wallpaper or a null pointer if + * wallpaper is unset. + */ + @Nullable + public Drawable peekDrawable(@SetWallpaperFlags int which) { final ColorManagementProxy cmProxy = getColorManagementProxy(); - Bitmap bm = sGlobals.peekWallpaperBitmap(mContext, false, FLAG_SYSTEM, cmProxy); + Bitmap bm = sGlobals.peekWallpaperBitmap(mContext, false, which, cmProxy); if (bm != null) { Drawable dr = new BitmapDrawable(mContext.getResources(), bm); dr.setDither(false); @@ -1062,9 +1103,31 @@ public class WallpaperManager { * @return Returns a Drawable object that will draw the wallpaper. */ @RequiresPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) + @Nullable public Drawable getFastDrawable() { + return getFastDrawable(FLAG_SYSTEM); + } + + /** + * Like {@link #getFastDrawable(int)}, but the returned Drawable has a number + * of limitations to reduce its overhead as much as possible. It will + * never scale the wallpaper (only centering it if the requested bounds + * do match the bitmap bounds, which should not be typical), doesn't + * allow setting an alpha, color filter, or other attributes, etc. The + * bounds of the returned drawable will be initialized to the same bounds + * as the wallpaper, so normally you will not need to touch it. The + * drawable also assumes that it will be used in a context running in + * the same density as the screen (not in density compatibility mode). + * + * @param which The {@code FLAG_*} identifier of a valid wallpaper type. Throws + * IllegalArgumentException if an invalid wallpaper is requested. + * @return Returns a Drawable object that will draw the wallpaper. + */ + @RequiresPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) + @Nullable + public Drawable getFastDrawable(@SetWallpaperFlags int which) { final ColorManagementProxy cmProxy = getColorManagementProxy(); - Bitmap bm = sGlobals.peekWallpaperBitmap(mContext, true, FLAG_SYSTEM, cmProxy); + Bitmap bm = sGlobals.peekWallpaperBitmap(mContext, true, which, cmProxy); if (bm != null) { return new FastBitmapDrawable(bm); } @@ -1079,9 +1142,25 @@ public class WallpaperManager { * wallpaper or a null pointer if these is none. */ @RequiresPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) + @Nullable public Drawable peekFastDrawable() { + return peekFastDrawable(FLAG_SYSTEM); + } + + /** + * Like {@link #getFastDrawable()}, but if there is no wallpaper set, + * a null pointer is returned. + * + * @param which The {@code FLAG_*} identifier of a valid wallpaper type. Throws + * IllegalArgumentException if an invalid wallpaper is requested. + * @return Returns an optimized Drawable object that will draw the + * wallpaper or a null pointer if these is none. + */ + @RequiresPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) + @Nullable + public Drawable peekFastDrawable(@SetWallpaperFlags int which) { final ColorManagementProxy cmProxy = getColorManagementProxy(); - Bitmap bm = sGlobals.peekWallpaperBitmap(mContext, false, FLAG_SYSTEM, cmProxy); + Bitmap bm = sGlobals.peekWallpaperBitmap(mContext, false, which, cmProxy); if (bm != null) { return new FastBitmapDrawable(bm); } diff --git a/core/java/android/app/admin/DevicePolicyCache.java b/core/java/android/app/admin/DevicePolicyCache.java index da6237513562..4a329a9c4891 100644 --- a/core/java/android/app/admin/DevicePolicyCache.java +++ b/core/java/android/app/admin/DevicePolicyCache.java @@ -61,7 +61,6 @@ public abstract class DevicePolicyCache { */ public abstract boolean canAdminGrantSensorsPermissionsForUser(@UserIdInt int userHandle); - /** * Empty implementation. */ diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java index ecea1bb9ac8e..dd82bc1bc916 100644 --- a/core/java/android/app/admin/DevicePolicyManager.java +++ b/core/java/android/app/admin/DevicePolicyManager.java @@ -165,6 +165,12 @@ import java.util.function.Consumer; @SuppressLint("UseIcu") public class DevicePolicyManager { + /** @hide */ + public static final String DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_FLAG = + "deprecate_usermanagerinternal_devicepolicy"; + /** @hide */ + public static final boolean DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_DEFAULT = false; + private static String TAG = "DevicePolicyManager"; private final Context mContext; @@ -14449,7 +14455,9 @@ public class DevicePolicyManager { * @throws SecurityException if {@code admin} is not a profile owner * * @see #getCrossProfileCalendarPackages(ComponentName) + * @deprecated Use {@link #setCrossProfilePackages(ComponentName, Set)}. */ + @Deprecated public void setCrossProfileCalendarPackages(@NonNull ComponentName admin, @Nullable Set<String> packageNames) { throwIfParentInstance("setCrossProfileCalendarPackages"); @@ -14475,7 +14483,9 @@ public class DevicePolicyManager { * @throws SecurityException if {@code admin} is not a profile owner * * @see #setCrossProfileCalendarPackages(ComponentName, Set) + * @deprecated Use {@link #setCrossProfilePackages(ComponentName, Set)}. */ + @Deprecated public @Nullable Set<String> getCrossProfileCalendarPackages(@NonNull ComponentName admin) { throwIfParentInstance("getCrossProfileCalendarPackages"); if (mService != null) { diff --git a/core/java/android/app/admin/DevicePolicyManagerInternal.java b/core/java/android/app/admin/DevicePolicyManagerInternal.java index b6f09167580f..840f3a3c6bb8 100644 --- a/core/java/android/app/admin/DevicePolicyManagerInternal.java +++ b/core/java/android/app/admin/DevicePolicyManagerInternal.java @@ -269,4 +269,14 @@ public abstract class DevicePolicyManagerInternal { * {@link #supportsResetOp(int)} is true. */ public abstract void resetOp(int op, String packageName, @UserIdInt int userId); + + /** + * Returns whether new "turn off work" behavior is enabled via feature flag. + */ + public abstract boolean isKeepProfilesRunningEnabled(); + + /** + * True if either the entire device or the user is organization managed. + */ + public abstract boolean isUserOrganizationManaged(@UserIdInt int userId); } diff --git a/core/java/android/app/admin/DeviceStateCache.java b/core/java/android/app/admin/DeviceStateCache.java index 7619aa2b7473..d1d130d88a39 100644 --- a/core/java/android/app/admin/DeviceStateCache.java +++ b/core/java/android/app/admin/DeviceStateCache.java @@ -15,6 +15,8 @@ */ package android.app.admin; +import android.annotation.UserIdInt; + import com.android.server.LocalServices; /** @@ -43,6 +45,11 @@ public abstract class DeviceStateCache { public abstract boolean isDeviceProvisioned(); /** + * True if either the entire device or the user is organization managed. + */ + public abstract boolean isUserOrganizationManaged(@UserIdInt int userHandle); + + /** * Empty implementation. */ private static class EmptyDeviceStateCache extends DeviceStateCache { @@ -52,5 +59,10 @@ public abstract class DeviceStateCache { public boolean isDeviceProvisioned() { return false; } + + @Override + public boolean isUserOrganizationManaged(int userHandle) { + return false; + } } } diff --git a/core/java/android/app/admin/SecurityLog.java b/core/java/android/app/admin/SecurityLog.java index 904db5f86c02..ca2e97edc432 100644 --- a/core/java/android/app/admin/SecurityLog.java +++ b/core/java/android/app/admin/SecurityLog.java @@ -96,6 +96,9 @@ public class SecurityLog { TAG_WIFI_DISCONNECTION, TAG_BLUETOOTH_CONNECTION, TAG_BLUETOOTH_DISCONNECTION, + TAG_PACKAGE_INSTALLED, + TAG_PACKAGE_UPDATED, + TAG_PACKAGE_UNINSTALLED, }) public @interface SecurityLogTag {} @@ -563,6 +566,39 @@ public class SecurityLog { SecurityLogTags.SECURITY_BLUETOOTH_DISCONNECTION; /** + * Indicates that a package is installed. + * The log entry contains the following information about the + * event, encapsulated in an {@link Object} array and accessible via + * {@link SecurityEvent#getData()}: + * <li> [0] Name of the package being installed ({@code String}) + * <li> [1] Package version code ({@code Long}) + * <li> [2] UserId of the user that installed this package ({@code Integer}) + */ + public static final int TAG_PACKAGE_INSTALLED = SecurityLogTags.SECURITY_PACKAGE_INSTALLED; + + /** + * Indicates that a package is updated. + * The log entry contains the following information about the + * event, encapsulated in an {@link Object} array and accessible via + * {@link SecurityEvent#getData()}: + * <li> [0] Name of the package being updated ({@code String}) + * <li> [1] Package version code ({@code Long}) + * <li> [2] UserId of the user that updated this package ({@code Integer}) + */ + public static final int TAG_PACKAGE_UPDATED = SecurityLogTags.SECURITY_PACKAGE_UPDATED; + + /** + * Indicates that a package is uninstalled. + * The log entry contains the following information about the + * event, encapsulated in an {@link Object} array and accessible via + * {@link SecurityEvent#getData()}: + * <li> [0] Name of the package being uninstalled ({@code String}) + * <li> [1] Package version code ({@code Long}) + * <li> [2] UserId of the user that uninstalled this package ({@code Integer}) + */ + public static final int TAG_PACKAGE_UNINSTALLED = SecurityLogTags.SECURITY_PACKAGE_UNINSTALLED; + + /** * Event severity level indicating that the event corresponds to normal workflow. */ public static final int LEVEL_INFO = 1; @@ -772,6 +808,9 @@ public class SecurityLog { break; case SecurityLog.TAG_CERT_AUTHORITY_INSTALLED: case SecurityLog.TAG_CERT_AUTHORITY_REMOVED: + case SecurityLog.TAG_PACKAGE_INSTALLED: + case SecurityLog.TAG_PACKAGE_UPDATED: + case SecurityLog.TAG_PACKAGE_UNINSTALLED: try { userId = getIntegerData(2); } catch (Exception e) { diff --git a/core/java/android/app/admin/SecurityLogTags.logtags b/core/java/android/app/admin/SecurityLogTags.logtags index b06e5a5849fd..e4af8dd91583 100644 --- a/core/java/android/app/admin/SecurityLogTags.logtags +++ b/core/java/android/app/admin/SecurityLogTags.logtags @@ -44,4 +44,7 @@ option java_package android.app.admin 210037 security_wifi_connection (bssid|3),(event_type|3),(reason|3) 210038 security_wifi_disconnection (bssid|3),(reason|3) 210039 security_bluetooth_connection (addr|3),(success|1),(reason|3) -210040 security_bluetooth_disconnection (addr|3),(reason|3)
\ No newline at end of file +210040 security_bluetooth_disconnection (addr|3),(reason|3) +210041 security_package_installed (package_name|3),(version_code|1),(user_id|1) +210042 security_package_updated (package_name|3),(version_code|1),(user_id|1) +210043 security_package_uninstalled (package_name|3),(version_code|1),(user_id|1)
\ No newline at end of file diff --git a/core/java/android/app/time/TimeState.java b/core/java/android/app/time/TimeState.java index c209cde2cf49..1d9add2c715f 100644 --- a/core/java/android/app/time/TimeState.java +++ b/core/java/android/app/time/TimeState.java @@ -29,11 +29,13 @@ import java.util.Objects; /** * A snapshot of the system time state. * - * <p>{@code mUnixEpochTime} contains a snapshot of the system clock time and elapsed realtime clock + * <p>{@code unixEpochTime} contains a snapshot of the system clock time and elapsed realtime clock * time. * - * <p>{@code mUserShouldConfirmTime} is {@code true} if the system has low confidence in the system - * clock time. + * <p>{@code userShouldConfirmTime} is {@code true} if the system automatic time detection logic + * suggests that the user be asked to confirm the {@code unixEpochTime} value is correct via {@link + * TimeManager#confirmTime}. If it is not correct, the value can usually be changed via {@link + * TimeManager#setManualTime}. * * @hide */ diff --git a/core/java/android/app/time/TimeZoneState.java b/core/java/android/app/time/TimeZoneState.java index beb6dc6d1dfb..0febc34f1c37 100644 --- a/core/java/android/app/time/TimeZoneState.java +++ b/core/java/android/app/time/TimeZoneState.java @@ -32,8 +32,10 @@ import java.util.Objects; * <p>{@code id} contains the system's time zone ID setting, e.g. "America/Los_Angeles". This * will usually agree with {@code TimeZone.getDefault().getID()} but it can be empty in rare cases. * - * <p>{@code userShouldConfirmId} is {@code true} if the system has low confidence in the current - * time zone. + * <p>{@code userShouldConfirmId} is {@code true} if the system automatic time zone detection logic + * suggests that the user be asked to confirm the {@code id} value is correct via {@link + * TimeManager#confirmTimeZone}. If it is not correct, the value can usually be changed via {@link + * TimeManager#setManualTimeZone}. * * @hide */ diff --git a/core/java/android/app/time/UnixEpochTime.java b/core/java/android/app/time/UnixEpochTime.java index 3a35f3cd1acb..61cbc5ed7977 100644 --- a/core/java/android/app/time/UnixEpochTime.java +++ b/core/java/android/app/time/UnixEpochTime.java @@ -16,6 +16,7 @@ package android.app.time; +import android.annotation.CurrentTimeMillisLong; import android.annotation.ElapsedRealtimeLong; import android.annotation.NonNull; import android.annotation.Nullable; @@ -42,7 +43,7 @@ import java.util.Objects; @SystemApi public final class UnixEpochTime implements Parcelable { @ElapsedRealtimeLong private final long mElapsedRealtimeMillis; - private final long mUnixEpochTimeMillis; + @CurrentTimeMillisLong private final long mUnixEpochTimeMillis; public UnixEpochTime(@ElapsedRealtimeLong long elapsedRealtimeMillis, long unixEpochTimeMillis) { @@ -91,11 +92,13 @@ public final class UnixEpochTime implements Parcelable { } /** Returns the elapsed realtime clock value. See {@link UnixEpochTime} for more information. */ - public @ElapsedRealtimeLong long getElapsedRealtimeMillis() { + @ElapsedRealtimeLong + public long getElapsedRealtimeMillis() { return mElapsedRealtimeMillis; } /** Returns the unix epoch time value. See {@link UnixEpochTime} for more information. */ + @CurrentTimeMillisLong public long getUnixEpochTimeMillis() { return mUnixEpochTimeMillis; } diff --git a/core/java/android/companion/virtual/IVirtualDeviceManager.aidl b/core/java/android/companion/virtual/IVirtualDeviceManager.aidl index 7d6336a225bd..6e784b2e607d 100644 --- a/core/java/android/companion/virtual/IVirtualDeviceManager.aidl +++ b/core/java/android/companion/virtual/IVirtualDeviceManager.aidl @@ -51,6 +51,11 @@ interface IVirtualDeviceManager { */ List<VirtualDevice> getVirtualDevices(); + /** + * Returns the ID of the device which owns the display with the given ID. + */ + int getDeviceIdForDisplayId(int displayId); + /** * Returns the device policy for the given virtual device and policy type. */ diff --git a/core/java/android/companion/virtual/VirtualDeviceManager.java b/core/java/android/companion/virtual/VirtualDeviceManager.java index 0e6cfb1df9de..109f4b1931f9 100644 --- a/core/java/android/companion/virtual/VirtualDeviceManager.java +++ b/core/java/android/companion/virtual/VirtualDeviceManager.java @@ -231,6 +231,23 @@ public final class VirtualDeviceManager { } /** + * Returns the ID of the device which owns the display with the given ID. + * + * @hide + */ + public int getDeviceIdForDisplayId(int displayId) { + if (mService == null) { + Log.w(TAG, "Failed to retrieve virtual devices; no virtual device manager service."); + return DEFAULT_DEVICE_ID; + } + try { + return mService.getDeviceIdForDisplayId(displayId); + } catch (RemoteException e) { + throw e.rethrowFromSystemServer(); + } + } + + /** * A virtual device has its own virtual display, audio output, microphone, and camera etc. The * creator of a virtual device can take the output from the virtual display and stream it over * to another device, and inject input events that are received from the remote device. diff --git a/core/java/android/content/ContentProvider.java b/core/java/android/content/ContentProvider.java index da486eebf9d1..5a153ce71a42 100644 --- a/core/java/android/content/ContentProvider.java +++ b/core/java/android/content/ContentProvider.java @@ -21,6 +21,11 @@ import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL; import static android.os.Process.myUserHandle; import static android.os.Trace.TRACE_TAG_DATABASE; +import static com.android.internal.util.FrameworkStatsLog.GET_TYPE_ACCESSED_WITHOUT_PERMISSION; +import static com.android.internal.util.FrameworkStatsLog.GET_TYPE_ACCESSED_WITHOUT_PERMISSION__LOCATION__PROVIDER_CHECK_URI_PERMISSION; +import static com.android.internal.util.FrameworkStatsLog.GET_TYPE_ACCESSED_WITHOUT_PERMISSION__LOCATION__PROVIDER_ERROR; +import static com.android.internal.util.FrameworkStatsLog.GET_TYPE_ACCESSED_WITHOUT_PERMISSION__LOCATION__PROVIDER_FRAMEWORK_PERMISSION; + import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.SystemApi; @@ -58,6 +63,7 @@ import android.util.Log; import android.util.SparseBooleanArray; import com.android.internal.annotations.VisibleForTesting; +import com.android.internal.util.FrameworkStatsLog; import java.io.File; import java.io.FileDescriptor; @@ -300,7 +306,11 @@ public abstract class ContentProvider implements ContentInterface, ComponentCall uri = maybeGetUriWithoutUserId(uri); traceBegin(TRACE_TAG_DATABASE, "getType: ", uri.getAuthority()); try { - return mInterface.getType(uri); + final String type = mInterface.getType(uri); + if (type != null) { + logGetTypeData(Binder.getCallingUid(), uri, type); + } + return type; } catch (RemoteException e) { throw e.rethrowAsRuntimeException(); } finally { @@ -308,6 +318,48 @@ public abstract class ContentProvider implements ContentInterface, ComponentCall } } + // Utility function to log the getTypeData calls + private void logGetTypeData(int callingUid, Uri uri, String type) { + final int enumFrameworkPermission = + GET_TYPE_ACCESSED_WITHOUT_PERMISSION__LOCATION__PROVIDER_FRAMEWORK_PERMISSION; + final int enumCheckUriPermission = + GET_TYPE_ACCESSED_WITHOUT_PERMISSION__LOCATION__PROVIDER_CHECK_URI_PERMISSION; + final int enumError = GET_TYPE_ACCESSED_WITHOUT_PERMISSION__LOCATION__PROVIDER_ERROR; + + try { + final AttributionSource attributionSource = new AttributionSource.Builder( + callingUid).build(); + try { + if (enforceReadPermission(attributionSource, uri) + != PermissionChecker.PERMISSION_GRANTED) { + FrameworkStatsLog.write(GET_TYPE_ACCESSED_WITHOUT_PERMISSION, + enumFrameworkPermission, + callingUid, uri.getAuthority(), type); + } else { + final ProviderInfo cpi = mContext.getPackageManager() + .resolveContentProvider(uri.getAuthority(), + PackageManager.ComponentInfoFlags.of(PackageManager.GET_META_DATA)); + if (cpi.forceUriPermissions + && mInterface.checkUriPermission(uri, + callingUid, Intent.FLAG_GRANT_READ_URI_PERMISSION) + != PermissionChecker.PERMISSION_GRANTED) { + FrameworkStatsLog.write(GET_TYPE_ACCESSED_WITHOUT_PERMISSION, + enumCheckUriPermission, + callingUid, uri.getAuthority(), type); + } + } + } catch (SecurityException e) { + FrameworkStatsLog.write(GET_TYPE_ACCESSED_WITHOUT_PERMISSION, + enumFrameworkPermission, + callingUid, uri.getAuthority(), type); + } + } catch (Exception e) { + FrameworkStatsLog.write(GET_TYPE_ACCESSED_WITHOUT_PERMISSION, + enumError, + callingUid, uri.getAuthority(), type); + } + } + @Override public void getTypeAsync(Uri uri, RemoteCallback callback) { final Bundle result = new Bundle(); diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java index 9f9fd3ceb5f7..df5a1ed661cd 100644 --- a/core/java/android/content/Context.java +++ b/core/java/android/content/Context.java @@ -5937,6 +5937,14 @@ public abstract class Context { public static final String FILE_INTEGRITY_SERVICE = "file_integrity"; /** + * Binder service for remote key provisioning. + * + * @see android.frameworks.rkp.IRemoteProvisioning + * @hide + */ + public static final String REMOTE_PROVISIONING_SERVICE = "remote_provisioning"; + + /** * Use with {@link #getSystemService(String)} to retrieve a * {@link android.hardware.lights.LightsManager} for controlling device lights. * diff --git a/core/java/android/content/om/TEST_MAPPING b/core/java/android/content/om/TEST_MAPPING index 6185cf64ad12..a9aaf1a89504 100644 --- a/core/java/android/content/om/TEST_MAPPING +++ b/core/java/android/content/om/TEST_MAPPING @@ -12,6 +12,9 @@ "name": "OverlayDeviceTests" }, { + "name": "SelfTargetingOverlayDeviceTests" + }, + { "name": "OverlayHostTests" }, { @@ -35,6 +38,9 @@ }, { "include-filter": "android.content.om.cts" + }, + { + "include-filter": "android.content.res.loader.cts" } ] } diff --git a/core/java/android/content/pm/PermissionInfo.java b/core/java/android/content/pm/PermissionInfo.java index 61fc6f6775c1..4fa80d7d7f40 100644 --- a/core/java/android/content/pm/PermissionInfo.java +++ b/core/java/android/content/pm/PermissionInfo.java @@ -250,6 +250,16 @@ public class PermissionInfo extends PackageItemInfo implements Parcelable { /** * Additional flag for {@link #protectionLevel}, corresponding + * to the <code>module</code> value of + * {@link android.R.attr#protectionLevel}. + * + * @hide + */ + @SystemApi + public static final int PROTECTION_FLAG_MODULE = 0x400000; + + /** + * Additional flag for {@link #protectionLevel}, corresponding * to the <code>companion</code> value of * {@link android.R.attr#protectionLevel}. * @@ -320,6 +330,7 @@ public class PermissionInfo extends PackageItemInfo implements Parcelable { PROTECTION_FLAG_RECENTS, PROTECTION_FLAG_ROLE, PROTECTION_FLAG_KNOWN_SIGNER, + PROTECTION_FLAG_MODULE, }) @Retention(RetentionPolicy.SOURCE) public @interface ProtectionFlags {} @@ -593,6 +604,9 @@ public class PermissionInfo extends PackageItemInfo implements Parcelable { if ((level & PermissionInfo.PROTECTION_FLAG_KNOWN_SIGNER) != 0) { protLevel.append("|knownSigner"); } + if ((level & PermissionInfo.PROTECTION_FLAG_MODULE) != 0) { + protLevel.append(("|module")); + } return protLevel.toString(); } diff --git a/core/java/android/credentials/ClearCredentialStateException.java b/core/java/android/credentials/ClearCredentialStateException.java new file mode 100644 index 000000000000..a6b76a783fc4 --- /dev/null +++ b/core/java/android/credentials/ClearCredentialStateException.java @@ -0,0 +1,76 @@ +/* + * 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. + */ + +package android.credentials; + +import android.annotation.NonNull; +import android.annotation.Nullable; +import android.os.CancellationSignal; +import android.os.OutcomeReceiver; + +import com.android.internal.util.Preconditions; + +import java.util.concurrent.Executor; + +/** + * Represents an error encountered during the + * {@link CredentialManager#clearCredentialState(ClearCredentialStateRequest, + * CancellationSignal, Executor, OutcomeReceiver)} operation. + */ +public class ClearCredentialStateException extends Exception { + + @NonNull + public final String errorType; + + /** + * Constructs a {@link ClearCredentialStateException}. + * + * @throws IllegalArgumentException If errorType is empty. + */ + public ClearCredentialStateException(@NonNull String errorType, @Nullable String message) { + this(errorType, message, null); + } + + /** + * Constructs a {@link ClearCredentialStateException}. + * + * @throws IllegalArgumentException If errorType is empty. + */ + public ClearCredentialStateException( + @NonNull String errorType, @Nullable String message, @Nullable Throwable cause) { + super(message, cause); + this.errorType = Preconditions.checkStringNotEmpty(errorType, + "errorType must not be empty"); + } + + /** + * Constructs a {@link ClearCredentialStateException}. + * + * @throws IllegalArgumentException If errorType is empty. + */ + public ClearCredentialStateException(@NonNull String errorType, @Nullable Throwable cause) { + this(errorType, null, cause); + } + + /** + * Constructs a {@link ClearCredentialStateException}. + * + * @throws IllegalArgumentException If errorType is empty. + */ + public ClearCredentialStateException(@NonNull String errorType) { + this(errorType, null, null); + } +} diff --git a/core/java/android/credentials/CreateCredentialException.java b/core/java/android/credentials/CreateCredentialException.java new file mode 100644 index 000000000000..87af20883091 --- /dev/null +++ b/core/java/android/credentials/CreateCredentialException.java @@ -0,0 +1,77 @@ +/* + * 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. + */ + +package android.credentials; + +import android.annotation.NonNull; +import android.annotation.Nullable; +import android.app.Activity; +import android.os.CancellationSignal; +import android.os.OutcomeReceiver; + +import com.android.internal.util.Preconditions; + +import java.util.concurrent.Executor; + +/** + * Represents an error encountered during the + * {@link CredentialManager#executeCreateCredential(CreateCredentialRequest, + * Activity, CancellationSignal, Executor, OutcomeReceiver)} operation. + */ +public class CreateCredentialException extends Exception { + + @NonNull + public final String errorType; + + /** + * Constructs a {@link CreateCredentialException}. + * + * @throws IllegalArgumentException If errorType is empty. + */ + public CreateCredentialException(@NonNull String errorType, @Nullable String message) { + this(errorType, message, null); + } + + /** + * Constructs a {@link CreateCredentialException}. + * + * @throws IllegalArgumentException If errorType is empty. + */ + public CreateCredentialException( + @NonNull String errorType, @Nullable String message, @Nullable Throwable cause) { + super(message, cause); + this.errorType = Preconditions.checkStringNotEmpty(errorType, + "errorType must not be empty"); + } + + /** + * Constructs a {@link CreateCredentialException}. + * + * @throws IllegalArgumentException If errorType is empty. + */ + public CreateCredentialException(@NonNull String errorType, @Nullable Throwable cause) { + this(errorType, null, cause); + } + + /** + * Constructs a {@link CreateCredentialException}. + * + * @throws IllegalArgumentException If errorType is empty. + */ + public CreateCredentialException(@NonNull String errorType) { + this(errorType, null, null); + } +} diff --git a/core/java/android/credentials/CreateCredentialRequest.java b/core/java/android/credentials/CreateCredentialRequest.java index 45890392bed7..be887a513e3f 100644 --- a/core/java/android/credentials/CreateCredentialRequest.java +++ b/core/java/android/credentials/CreateCredentialRequest.java @@ -52,7 +52,7 @@ public final class CreateCredentialRequest implements Parcelable { private final Bundle mCandidateQueryData; /** - * Determines whether or not the request must only be fulfilled by a system provider. + * Determines whether the request must only be fulfilled by a system provider. */ private final boolean mRequireSystemProvider; diff --git a/core/java/android/credentials/CredentialManager.java b/core/java/android/credentials/CredentialManager.java index 1efac6c2f332..c011949ec6d4 100644 --- a/core/java/android/credentials/CredentialManager.java +++ b/core/java/android/credentials/CredentialManager.java @@ -77,7 +77,7 @@ public final class CredentialManager { @Nullable CancellationSignal cancellationSignal, @CallbackExecutor @NonNull Executor executor, @NonNull OutcomeReceiver< - GetCredentialResponse, CredentialManagerException> callback) { + GetCredentialResponse, GetCredentialException> callback) { requireNonNull(request, "request must not be null"); requireNonNull(activity, "activity must not be null"); requireNonNull(executor, "executor must not be null"); @@ -121,7 +121,7 @@ public final class CredentialManager { @Nullable CancellationSignal cancellationSignal, @CallbackExecutor @NonNull Executor executor, @NonNull OutcomeReceiver< - CreateCredentialResponse, CredentialManagerException> callback) { + CreateCredentialResponse, CreateCredentialException> callback) { requireNonNull(request, "request must not be null"); requireNonNull(activity, "activity must not be null"); requireNonNull(executor, "executor must not be null"); @@ -167,7 +167,7 @@ public final class CredentialManager { @NonNull ClearCredentialStateRequest request, @Nullable CancellationSignal cancellationSignal, @CallbackExecutor @NonNull Executor executor, - @NonNull OutcomeReceiver<Void, CredentialManagerException> callback) { + @NonNull OutcomeReceiver<Void, ClearCredentialStateException> callback) { requireNonNull(executor, "executor must not be null"); requireNonNull(callback, "callback must not be null"); @@ -196,10 +196,10 @@ public final class CredentialManager { private final Activity mActivity; private final Executor mExecutor; private final OutcomeReceiver< - GetCredentialResponse, CredentialManagerException> mCallback; + GetCredentialResponse, GetCredentialException> mCallback; private GetCredentialTransport(Activity activity, Executor executor, - OutcomeReceiver<GetCredentialResponse, CredentialManagerException> callback) { + OutcomeReceiver<GetCredentialResponse, GetCredentialException> callback) { mActivity = activity; mExecutor = executor; mCallback = callback; @@ -222,9 +222,9 @@ public final class CredentialManager { } @Override - public void onError(int errorCode, String message) { + public void onError(String errorType, String message) { mExecutor.execute( - () -> mCallback.onError(new CredentialManagerException(errorCode, message))); + () -> mCallback.onError(new GetCredentialException(errorType, message))); } } @@ -234,10 +234,10 @@ public final class CredentialManager { private final Activity mActivity; private final Executor mExecutor; private final OutcomeReceiver< - CreateCredentialResponse, CredentialManagerException> mCallback; + CreateCredentialResponse, CreateCredentialException> mCallback; private CreateCredentialTransport(Activity activity, Executor executor, - OutcomeReceiver<CreateCredentialResponse, CredentialManagerException> callback) { + OutcomeReceiver<CreateCredentialResponse, CreateCredentialException> callback) { mActivity = activity; mExecutor = executor; mCallback = callback; @@ -260,9 +260,9 @@ public final class CredentialManager { } @Override - public void onError(int errorCode, String message) { + public void onError(String errorType, String message) { mExecutor.execute( - () -> mCallback.onError(new CredentialManagerException(errorCode, message))); + () -> mCallback.onError(new CreateCredentialException(errorType, message))); } } @@ -271,10 +271,10 @@ public final class CredentialManager { // TODO: listen for cancellation to release callback. private final Executor mExecutor; - private final OutcomeReceiver<Void, CredentialManagerException> mCallback; + private final OutcomeReceiver<Void, ClearCredentialStateException> mCallback; private ClearCredentialStateTransport(Executor executor, - OutcomeReceiver<Void, CredentialManagerException> callback) { + OutcomeReceiver<Void, ClearCredentialStateException> callback) { mExecutor = executor; mCallback = callback; } @@ -285,9 +285,9 @@ public final class CredentialManager { } @Override - public void onError(int errorCode, String message) { + public void onError(String errorType, String message) { mExecutor.execute( - () -> mCallback.onError(new CredentialManagerException(errorCode, message))); + () -> mCallback.onError(new ClearCredentialStateException(errorType, message))); } } } diff --git a/core/java/android/credentials/CredentialManagerException.java b/core/java/android/credentials/CredentialManagerException.java deleted file mode 100644 index 8369649fe686..000000000000 --- a/core/java/android/credentials/CredentialManagerException.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * 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. - */ - -package android.credentials; - -import android.annotation.Nullable; - -/** Exception class for CredentialManager operations. */ -public class CredentialManagerException extends Exception { - /** Indicates that an unknown error was encountered. */ - public static final int ERROR_UNKNOWN = 0; - - /** - * The given CredentialManager operation is cancelled by the user. - * - * @hide - */ - public static final int ERROR_USER_CANCELLED = 1; - - /** - * No appropriate provider is found to support the target credential type(s). - * - * @hide - */ - public static final int ERROR_PROVIDER_NOT_FOUND = 2; - - public final int errorCode; - - public CredentialManagerException(int errorCode, @Nullable String message) { - super(message); - this.errorCode = errorCode; - } - - public CredentialManagerException( - int errorCode, @Nullable String message, @Nullable Throwable cause) { - super(message, cause); - this.errorCode = errorCode; - } - - public CredentialManagerException(int errorCode, @Nullable Throwable cause) { - super(cause); - this.errorCode = errorCode; - } - - public CredentialManagerException(int errorCode) { - super(); - this.errorCode = errorCode; - } -} diff --git a/core/java/android/credentials/GetCredentialException.java b/core/java/android/credentials/GetCredentialException.java new file mode 100644 index 000000000000..4d80237b006a --- /dev/null +++ b/core/java/android/credentials/GetCredentialException.java @@ -0,0 +1,77 @@ +/* + * 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. + */ + +package android.credentials; + +import android.annotation.NonNull; +import android.annotation.Nullable; +import android.app.Activity; +import android.os.CancellationSignal; +import android.os.OutcomeReceiver; + +import com.android.internal.util.Preconditions; + +import java.util.concurrent.Executor; + +/** + * Represents an error encountered during the + * {@link CredentialManager#executeGetCredential(GetCredentialRequest, + * Activity, CancellationSignal, Executor, OutcomeReceiver)} operation. + */ +public class GetCredentialException extends Exception { + + @NonNull + public final String errorType; + + /** + * Constructs a {@link GetCredentialException}. + * + * @throws IllegalArgumentException If errorType is empty. + */ + public GetCredentialException(@NonNull String errorType, @Nullable String message) { + this(errorType, message, null); + } + + /** + * Constructs a {@link GetCredentialException}. + * + * @throws IllegalArgumentException If errorType is empty. + */ + public GetCredentialException( + @NonNull String errorType, @Nullable String message, @Nullable Throwable cause) { + super(message, cause); + this.errorType = Preconditions.checkStringNotEmpty(errorType, + "errorType must not be empty"); + } + + /** + * Constructs a {@link GetCredentialException}. + * + * @throws IllegalArgumentException If errorType is empty. + */ + public GetCredentialException(@NonNull String errorType, @Nullable Throwable cause) { + this(errorType, null, cause); + } + + /** + * Constructs a {@link GetCredentialException}. + * + * @throws IllegalArgumentException If errorType is empty. + */ + public GetCredentialException(@NonNull String errorType) { + this(errorType, null, null); + } +} diff --git a/core/java/android/credentials/GetCredentialOption.java b/core/java/android/credentials/GetCredentialOption.java index ed93daef20d3..47731dd7b517 100644 --- a/core/java/android/credentials/GetCredentialOption.java +++ b/core/java/android/credentials/GetCredentialOption.java @@ -38,13 +38,20 @@ public final class GetCredentialOption implements Parcelable { private final String mType; /** - * The request data. + * The full request data. */ @NonNull - private final Bundle mData; + private final Bundle mCredentialRetrievalData; /** - * Determines whether or not the request must only be fulfilled by a system provider. + * The partial request data that will be sent to the provider during the initial credential + * candidate query stage. + */ + @NonNull + private final Bundle mCandidateQueryData; + + /** + * Determines whether the request must only be fulfilled by a system provider. */ private final boolean mRequireSystemProvider; @@ -57,11 +64,27 @@ public final class GetCredentialOption implements Parcelable { } /** - * Returns the request data. + * Returns the full request data. */ @NonNull - public Bundle getData() { - return mData; + public Bundle getCredentialRetrievalData() { + return mCredentialRetrievalData; + } + + /** + * Returns the partial request data that will be sent to the provider during the initial + * credential candidate query stage. + * + * For security reason, a provider will receive the request data in two stages. First it gets + * this partial request that do not contain sensitive user information; it uses this + * information to provide credential candidates that the [@code CredentialManager] will show to + * the user. Next, the full request data, {@link #getCredentialRetrievalData()}, will be sent to + * a provider only if the user further grants the consent by choosing a candidate from the + * provider. + */ + @NonNull + public Bundle getCandidateQueryData() { + return mCandidateQueryData; } /** @@ -75,7 +98,8 @@ public final class GetCredentialOption implements Parcelable { @Override public void writeToParcel(@NonNull Parcel dest, int flags) { dest.writeString8(mType); - dest.writeBundle(mData); + dest.writeBundle(mCredentialRetrievalData); + dest.writeBundle(mCandidateQueryData); dest.writeBoolean(mRequireSystemProvider); } @@ -88,7 +112,8 @@ public final class GetCredentialOption implements Parcelable { public String toString() { return "GetCredentialOption {" + "type=" + mType - + ", data=" + mData + + ", requestData=" + mCredentialRetrievalData + + ", candidateQueryData=" + mCandidateQueryData + ", requireSystemProvider=" + mRequireSystemProvider + "}"; } @@ -96,44 +121,52 @@ public final class GetCredentialOption implements Parcelable { /** * Constructs a {@link GetCredentialOption}. * - * @param type the requested credential type - * @param data the request data - * @param requireSystemProvider whether or not the request must only be fulfilled by a system - * provider - * + * @param type the requested credential type + * @param credentialRetrievalData the request data + * @param candidateQueryData the partial request data that will be sent to the provider + * during the initial credential candidate query stage + * @param requireSystemProvider whether the request must only be fulfilled by a system + * provider * @throws IllegalArgumentException If type is empty. */ public GetCredentialOption( @NonNull String type, - @NonNull Bundle data, + @NonNull Bundle credentialRetrievalData, + @NonNull Bundle candidateQueryData, boolean requireSystemProvider) { mType = Preconditions.checkStringNotEmpty(type, "type must not be empty"); - mData = requireNonNull(data, "data must not be null"); + mCredentialRetrievalData = requireNonNull(credentialRetrievalData, + "requestData must not be null"); + mCandidateQueryData = requireNonNull(candidateQueryData, + "candidateQueryData must not be null"); mRequireSystemProvider = requireSystemProvider; } private GetCredentialOption(@NonNull Parcel in) { String type = in.readString8(); Bundle data = in.readBundle(); + Bundle candidateQueryData = in.readBundle(); boolean requireSystemProvider = in.readBoolean(); mType = type; AnnotationValidations.validate(NonNull.class, null, mType); - mData = data; - AnnotationValidations.validate(NonNull.class, null, mData); + mCredentialRetrievalData = data; + AnnotationValidations.validate(NonNull.class, null, mCredentialRetrievalData); + mCandidateQueryData = candidateQueryData; + AnnotationValidations.validate(NonNull.class, null, mCandidateQueryData); mRequireSystemProvider = requireSystemProvider; } public static final @NonNull Parcelable.Creator<GetCredentialOption> CREATOR = new Parcelable.Creator<GetCredentialOption>() { - @Override - public GetCredentialOption[] newArray(int size) { - return new GetCredentialOption[size]; - } - - @Override - public GetCredentialOption createFromParcel(@NonNull Parcel in) { - return new GetCredentialOption(in); - } - }; + @Override + public GetCredentialOption[] newArray(int size) { + return new GetCredentialOption[size]; + } + + @Override + public GetCredentialOption createFromParcel(@NonNull Parcel in) { + return new GetCredentialOption(in); + } + }; } diff --git a/core/java/android/credentials/IClearCredentialStateCallback.aidl b/core/java/android/credentials/IClearCredentialStateCallback.aidl index f8b7ae440680..e18e08716729 100644 --- a/core/java/android/credentials/IClearCredentialStateCallback.aidl +++ b/core/java/android/credentials/IClearCredentialStateCallback.aidl @@ -23,5 +23,5 @@ package android.credentials; */ interface IClearCredentialStateCallback { oneway void onSuccess(); - oneway void onError(int errorCode, String message); + oneway void onError(String errorType, String message); }
\ No newline at end of file diff --git a/core/java/android/credentials/ICreateCredentialCallback.aidl b/core/java/android/credentials/ICreateCredentialCallback.aidl index 87fd36fe78f4..f6890a94bc19 100644 --- a/core/java/android/credentials/ICreateCredentialCallback.aidl +++ b/core/java/android/credentials/ICreateCredentialCallback.aidl @@ -27,5 +27,5 @@ import android.credentials.CreateCredentialResponse; interface ICreateCredentialCallback { oneway void onPendingIntent(in PendingIntent pendingIntent); oneway void onResponse(in CreateCredentialResponse response); - oneway void onError(int errorCode, String message); + oneway void onError(String errorType, String message); }
\ No newline at end of file diff --git a/core/java/android/credentials/IGetCredentialCallback.aidl b/core/java/android/credentials/IGetCredentialCallback.aidl index da152bad2da9..6d1182aec7bf 100644 --- a/core/java/android/credentials/IGetCredentialCallback.aidl +++ b/core/java/android/credentials/IGetCredentialCallback.aidl @@ -27,5 +27,5 @@ import android.credentials.GetCredentialResponse; interface IGetCredentialCallback { oneway void onPendingIntent(in PendingIntent pendingIntent); oneway void onResponse(in GetCredentialResponse response); - oneway void onError(int errorCode, String message); + oneway void onError(String errorType, String message); }
\ No newline at end of file diff --git a/core/java/android/hardware/SystemSensorManager.java b/core/java/android/hardware/SystemSensorManager.java index 18118f5bfe29..161b1b71121e 100644 --- a/core/java/android/hardware/SystemSensorManager.java +++ b/core/java/android/hardware/SystemSensorManager.java @@ -135,7 +135,7 @@ public class SystemSensorManager extends SensorManager { private final boolean mIsPackageDebuggable; private final Context mContext; private final long mNativeInstance; - private final VirtualDeviceManager mVdm; + private VirtualDeviceManager mVdm; private Optional<Boolean> mHasHighSamplingRateSensorsPermission = Optional.empty(); @@ -154,7 +154,6 @@ public class SystemSensorManager extends SensorManager { mContext = context; mNativeInstance = nativeCreate(context.getOpPackageName()); mIsPackageDebuggable = (0 != (appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE)); - mVdm = mContext.getSystemService(VirtualDeviceManager.class); // initialize the sensor list for (int index = 0;; ++index) { @@ -170,8 +169,7 @@ public class SystemSensorManager extends SensorManager { @Override public List<Sensor> getSensorList(int type) { final int deviceId = mContext.getDeviceId(); - if (deviceId == DEFAULT_DEVICE_ID || mVdm == null - || mVdm.getDevicePolicy(deviceId, POLICY_TYPE_SENSORS) == DEVICE_POLICY_DEFAULT) { + if (isDeviceSensorPolicyDefault(deviceId)) { return super.getSensorList(type); } @@ -207,8 +205,7 @@ public class SystemSensorManager extends SensorManager { @Override protected List<Sensor> getFullSensorList() { final int deviceId = mContext.getDeviceId(); - if (deviceId == DEFAULT_DEVICE_ID || mVdm == null - || mVdm.getDevicePolicy(deviceId, POLICY_TYPE_SENSORS) == DEVICE_POLICY_DEFAULT) { + if (isDeviceSensorPolicyDefault(deviceId)) { return mFullSensorsList; } @@ -1136,6 +1133,17 @@ public class SystemSensorManager extends SensorManager { parameter.type, parameter.floatValues, parameter.intValues) == 0; } + private boolean isDeviceSensorPolicyDefault(int deviceId) { + if (deviceId == DEFAULT_DEVICE_ID) { + return true; + } + if (mVdm == null) { + mVdm = mContext.getSystemService(VirtualDeviceManager.class); + } + return mVdm == null + || mVdm.getDevicePolicy(deviceId, POLICY_TYPE_SENSORS) == DEVICE_POLICY_DEFAULT; + } + /** * Checks if a sensor should be capped according to HIGH_SAMPLING_RATE_SENSORS * permission. diff --git a/core/java/android/hardware/camera2/CameraCharacteristics.java b/core/java/android/hardware/camera2/CameraCharacteristics.java index 1ee2423e62fd..6e72b5f291f0 100644 --- a/core/java/android/hardware/camera2/CameraCharacteristics.java +++ b/core/java/android/hardware/camera2/CameraCharacteristics.java @@ -4613,7 +4613,6 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri * <p>This key is available on all devices.</p> * @see #SENSOR_READOUT_TIMESTAMP_NOT_SUPPORTED * @see #SENSOR_READOUT_TIMESTAMP_HARDWARE - * @hide */ @PublicKey @NonNull @@ -5572,4 +5571,6 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri + + } diff --git a/core/java/android/hardware/camera2/CameraMetadata.java b/core/java/android/hardware/camera2/CameraMetadata.java index 44f8b1bfda07..b2428b1d80a3 100644 --- a/core/java/android/hardware/camera2/CameraMetadata.java +++ b/core/java/android/hardware/camera2/CameraMetadata.java @@ -1695,7 +1695,6 @@ public abstract class CameraMetadata<TKey> { * <p>This camera device doesn't support readout timestamp and onReadoutStarted * callback.</p> * @see CameraCharacteristics#SENSOR_READOUT_TIMESTAMP - * @hide */ public static final int SENSOR_READOUT_TIMESTAMP_NOT_SUPPORTED = 0; @@ -1705,7 +1704,6 @@ public abstract class CameraMetadata<TKey> { * readout timestamp is generated by the camera hardware and it has the same accuracy * and timing characteristics of the start-of-exposure time.</p> * @see CameraCharacteristics#SENSOR_READOUT_TIMESTAMP - * @hide */ public static final int SENSOR_READOUT_TIMESTAMP_HARDWARE = 1; diff --git a/core/java/android/hardware/camera2/CaptureRequest.java b/core/java/android/hardware/camera2/CaptureRequest.java index ea3e4a807baf..43bfdcc8d898 100644 --- a/core/java/android/hardware/camera2/CaptureRequest.java +++ b/core/java/android/hardware/camera2/CaptureRequest.java @@ -4154,6 +4154,38 @@ public final class CaptureRequest extends CameraMetadata<CaptureRequest.Key<?>> public static final Key<Integer> DISTORTION_CORRECTION_MODE = new Key<Integer>("android.distortionCorrection.mode", int.class); + /** + * <p>Strength of the extension post-processing effect</p> + * <p>This control allows Camera extension clients to configure the strength of the applied + * extension effect. Strength equal to 0 means that the extension must not apply any + * post-processing and return a regular captured frame. Strength equal to 100 is the + * default level of post-processing applied when the control is not supported or not set + * by the client. Values between 0 and 100 will have different effect depending on the + * extension type as described below:</p> + * <ul> + * <li>{@link android.hardware.camera2.CameraExtensionCharacteristics#EXTENSION_BOKEH BOKEH} - + * the strength is expected to control the amount of blur.</li> + * <li>{@link android.hardware.camera2.CameraExtensionCharacteristics#EXTENSION_HDR HDR} and + * {@link android.hardware.camera2.CameraExtensionCharacteristics#EXTENSION_NIGHT NIGHT} - + * the strength can control the amount of images fused and the brightness of the final image.</li> + * <li>{@link android.hardware.camera2.CameraExtensionCharacteristics#EXTENSION_FACE_RETOUCH FACE_RETOUCH} - + * the strength value will control the amount of cosmetic enhancement and skin + * smoothing.</li> + * </ul> + * <p>The control will be supported if the capture request key is part of the list generated by + * {@link android.hardware.camera2.CameraExtensionCharacteristics#getAvailableCaptureRequestKeys }. + * The control is only defined and available to clients sending capture requests via + * {@link android.hardware.camera2.CameraExtensionSession }. + * The default value is 100.</p> + * <p><b>Range of valid values:</b><br> + * 0 - 100</p> + * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p> + */ + @PublicKey + @NonNull + public static final Key<Integer> EXTENSION_STRENGTH = + new Key<Integer>("android.extension.strength", int.class); + /*~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~ * End generated code *~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~O@*/ @@ -4163,4 +4195,6 @@ public final class CaptureRequest extends CameraMetadata<CaptureRequest.Key<?>> + + } diff --git a/core/java/android/hardware/camera2/CaptureResult.java b/core/java/android/hardware/camera2/CaptureResult.java index 285c9331fd4a..fb52cc6a0196 100644 --- a/core/java/android/hardware/camera2/CaptureResult.java +++ b/core/java/android/hardware/camera2/CaptureResult.java @@ -5576,6 +5576,62 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> { public static final Key<Integer> DISTORTION_CORRECTION_MODE = new Key<Integer>("android.distortionCorrection.mode", int.class); + /** + * <p>Contains the extension type of the currently active extension</p> + * <p>The capture result will only be supported and included by camera extension + * {@link android.hardware.camera2.CameraExtensionSession sessions}. + * In case the extension session was configured to use + * {@link android.hardware.camera2.CameraExtensionCharacteristics#EXTENSION_AUTOMATIC AUTO}, + * then the extension type value will indicate the currently active extension like + * {@link android.hardware.camera2.CameraExtensionCharacteristics#EXTENSION_HDR HDR}, + * {@link android.hardware.camera2.CameraExtensionCharacteristics#EXTENSION_NIGHT NIGHT} etc. + * , and will never return + * {@link android.hardware.camera2.CameraExtensionCharacteristics#EXTENSION_AUTOMATIC AUTO}. + * In case the extension session was configured to use an extension different from + * {@link android.hardware.camera2.CameraExtensionCharacteristics#EXTENSION_AUTOMATIC AUTO}, + * then the result type will always match with the configured extension type.</p> + * <p><b>Range of valid values:</b><br> + * Extension type value listed in + * {@link android.hardware.camera2.CameraExtensionCharacteristics }</p> + * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p> + */ + @PublicKey + @NonNull + public static final Key<Integer> EXTENSION_CURRENT_TYPE = + new Key<Integer>("android.extension.currentType", int.class); + + /** + * <p>Strength of the extension post-processing effect</p> + * <p>This control allows Camera extension clients to configure the strength of the applied + * extension effect. Strength equal to 0 means that the extension must not apply any + * post-processing and return a regular captured frame. Strength equal to 100 is the + * default level of post-processing applied when the control is not supported or not set + * by the client. Values between 0 and 100 will have different effect depending on the + * extension type as described below:</p> + * <ul> + * <li>{@link android.hardware.camera2.CameraExtensionCharacteristics#EXTENSION_BOKEH BOKEH} - + * the strength is expected to control the amount of blur.</li> + * <li>{@link android.hardware.camera2.CameraExtensionCharacteristics#EXTENSION_HDR HDR} and + * {@link android.hardware.camera2.CameraExtensionCharacteristics#EXTENSION_NIGHT NIGHT} - + * the strength can control the amount of images fused and the brightness of the final image.</li> + * <li>{@link android.hardware.camera2.CameraExtensionCharacteristics#EXTENSION_FACE_RETOUCH FACE_RETOUCH} - + * the strength value will control the amount of cosmetic enhancement and skin + * smoothing.</li> + * </ul> + * <p>The control will be supported if the capture request key is part of the list generated by + * {@link android.hardware.camera2.CameraExtensionCharacteristics#getAvailableCaptureRequestKeys }. + * The control is only defined and available to clients sending capture requests via + * {@link android.hardware.camera2.CameraExtensionSession }. + * The default value is 100.</p> + * <p><b>Range of valid values:</b><br> + * 0 - 100</p> + * <p><b>Optional</b> - The value for this key may be {@code null} on some devices.</p> + */ + @PublicKey + @NonNull + public static final Key<Integer> EXTENSION_STRENGTH = + new Key<Integer>("android.extension.strength", int.class); + /*~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~ * End generated code *~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~@~O@*/ @@ -5585,4 +5641,6 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> { + + } diff --git a/core/java/android/hardware/display/AmbientDisplayConfiguration.java b/core/java/android/hardware/display/AmbientDisplayConfiguration.java index 8c71b363eb7b..47541ca16cda 100644 --- a/core/java/android/hardware/display/AmbientDisplayConfiguration.java +++ b/core/java/android/hardware/display/AmbientDisplayConfiguration.java @@ -40,6 +40,7 @@ public class AmbientDisplayConfiguration { private static final String TAG = "AmbientDisplayConfig"; private final Context mContext; private final boolean mAlwaysOnByDefault; + private final boolean mPickupGestureEnabledByDefault; /** Copied from android.provider.Settings.Secure since these keys are hidden. */ private static final String[] DOZE_SETTINGS = { @@ -65,6 +66,8 @@ public class AmbientDisplayConfiguration { public AmbientDisplayConfiguration(Context context) { mContext = context; mAlwaysOnByDefault = mContext.getResources().getBoolean(R.bool.config_dozeAlwaysOnEnabled); + mPickupGestureEnabledByDefault = + mContext.getResources().getBoolean(R.bool.config_dozePickupGestureEnabled); } /** @hide */ @@ -95,7 +98,8 @@ public class AmbientDisplayConfiguration { /** @hide */ public boolean pickupGestureEnabled(int user) { - return boolSettingDefaultOn(Settings.Secure.DOZE_PICK_UP_GESTURE, user) + return boolSetting(Settings.Secure.DOZE_PICK_UP_GESTURE, user, + mPickupGestureEnabledByDefault ? 1 : 0) && dozePickupSensorAvailable(); } diff --git a/core/java/android/hardware/input/IInputManager.aidl b/core/java/android/hardware/input/IInputManager.aidl index b26c0a289c21..eef0f421d29f 100644 --- a/core/java/android/hardware/input/IInputManager.aidl +++ b/core/java/android/hardware/input/IInputManager.aidl @@ -123,6 +123,22 @@ interface IInputManager { String[] getKeyboardLayoutListForInputDevice(in InputDeviceIdentifier identifier, int userId, in InputMethodInfo imeInfo, in InputMethodSubtype imeSubtype); + // Modifier key remapping APIs. + @EnforcePermission("REMAP_MODIFIER_KEYS") + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(value = " + + "android.Manifest.permission.REMAP_MODIFIER_KEYS)") + void remapModifierKey(int fromKey, int toKey); + + @EnforcePermission("REMAP_MODIFIER_KEYS") + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(value = " + + "android.Manifest.permission.REMAP_MODIFIER_KEYS)") + void clearAllModifierKeyRemappings(); + + @EnforcePermission("REMAP_MODIFIER_KEYS") + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(value = " + + "android.Manifest.permission.REMAP_MODIFIER_KEYS)") + Map getModifierKeyRemapping(); + // Registers an input devices changed listener. void registerInputDevicesChangedListener(IInputDevicesChangedListener listener); diff --git a/core/java/android/hardware/input/InputManager.java b/core/java/android/hardware/input/InputManager.java index cea3fa1a7fb0..a616014b1b84 100644 --- a/core/java/android/hardware/input/InputManager.java +++ b/core/java/android/hardware/input/InputManager.java @@ -78,6 +78,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.concurrent.Executor; @@ -253,6 +254,31 @@ public final class InputManager { }) public @interface SwitchState {} + /** @hide */ + @Retention(RetentionPolicy.SOURCE) + @IntDef(prefix = { "REMAPPABLE_MODIFIER_KEY_" }, value = { + RemappableModifierKey.REMAPPABLE_MODIFIER_KEY_CTRL_LEFT, + RemappableModifierKey.REMAPPABLE_MODIFIER_KEY_CTRL_RIGHT, + RemappableModifierKey.REMAPPABLE_MODIFIER_KEY_META_LEFT, + RemappableModifierKey.REMAPPABLE_MODIFIER_KEY_META_RIGHT, + RemappableModifierKey.REMAPPABLE_MODIFIER_KEY_ALT_LEFT, + RemappableModifierKey.REMAPPABLE_MODIFIER_KEY_ALT_RIGHT, + RemappableModifierKey.REMAPPABLE_MODIFIER_KEY_SHIFT_LEFT, + RemappableModifierKey.REMAPPABLE_MODIFIER_KEY_SHIFT_RIGHT, + RemappableModifierKey.REMAPPABLE_MODIFIER_KEY_CAPS_LOCK, + }) + public @interface RemappableModifierKey { + int REMAPPABLE_MODIFIER_KEY_CTRL_LEFT = KeyEvent.KEYCODE_CTRL_LEFT; + int REMAPPABLE_MODIFIER_KEY_CTRL_RIGHT = KeyEvent.KEYCODE_CTRL_RIGHT; + int REMAPPABLE_MODIFIER_KEY_META_LEFT = KeyEvent.KEYCODE_META_LEFT; + int REMAPPABLE_MODIFIER_KEY_META_RIGHT = KeyEvent.KEYCODE_META_RIGHT; + int REMAPPABLE_MODIFIER_KEY_ALT_LEFT = KeyEvent.KEYCODE_ALT_LEFT; + int REMAPPABLE_MODIFIER_KEY_ALT_RIGHT = KeyEvent.KEYCODE_ALT_RIGHT; + int REMAPPABLE_MODIFIER_KEY_SHIFT_LEFT = KeyEvent.KEYCODE_SHIFT_LEFT; + int REMAPPABLE_MODIFIER_KEY_SHIFT_RIGHT = KeyEvent.KEYCODE_SHIFT_RIGHT; + int REMAPPABLE_MODIFIER_KEY_CAPS_LOCK = KeyEvent.KEYCODE_CAPS_LOCK; + } + /** * Switch State: Unknown. * @@ -854,6 +880,60 @@ public final class InputManager { } /** + * Remaps modifier keys. Remapping a modifier key to itself will clear any previous remappings + * for that key. + * + * @param fromKey The modifier key getting remapped. + * @param toKey The modifier key that it is remapped to. + * + * @hide + */ + @TestApi + @RequiresPermission(Manifest.permission.REMAP_MODIFIER_KEYS) + public void remapModifierKey(@RemappableModifierKey int fromKey, + @RemappableModifierKey int toKey) { + try { + mIm.remapModifierKey(fromKey, toKey); + } catch (RemoteException ex) { + throw ex.rethrowFromSystemServer(); + } + } + + /** + * Clears all existing modifier key remappings + * + * @hide + */ + @TestApi + @RequiresPermission(Manifest.permission.REMAP_MODIFIER_KEYS) + public void clearAllModifierKeyRemappings() { + try { + mIm.clearAllModifierKeyRemappings(); + } catch (RemoteException ex) { + throw ex.rethrowFromSystemServer(); + } + } + + /** + * Provides the current modifier key remapping + * + * @return a {fromKey, toKey} map that contains the existing modifier key remappings.. + * {@link RemappableModifierKey} + * + * @hide + */ + @TestApi + @NonNull + @RequiresPermission(Manifest.permission.REMAP_MODIFIER_KEYS) + public Map<Integer, Integer> getModifierKeyRemapping() { + try { + return mIm.getModifierKeyRemapping(); + } catch (RemoteException ex) { + throw ex.rethrowFromSystemServer(); + } + } + + /** * Gets the TouchCalibration applied to the specified input device's coordinates. * * @param inputDeviceDescriptor The input device descriptor. @@ -1964,6 +2044,217 @@ public final class InputManager { } /** + * Whether there is a gesture-compatible touchpad connected to the device. + * @hide + */ + public boolean areTouchpadGesturesAvailable(@NonNull Context context) { + // TODO: implement the right logic + return true; + } + + /** + * Gets the touchpad pointer speed. + * + * The returned value only applies to gesture-compatible touchpads. + * + * @param context The application context. + * @return The pointer speed as a value between {@link #MIN_POINTER_SPEED} and + * {@link #MAX_POINTER_SPEED}, or the default value {@link #DEFAULT_POINTER_SPEED}. + * + * @hide + */ + public int getTouchpadPointerSpeed(@NonNull Context context) { + int speed = DEFAULT_POINTER_SPEED; + // TODO: obtain the actual speed from the settings + return speed; + } + + /** + * Sets the touchpad pointer speed, and saves it in the settings. + * + * The new speed will only apply to gesture-compatible touchpads. + * + * @param context The application context. + * @param speed The pointer speed as a value between {@link #MIN_POINTER_SPEED} and + * {@link #MAX_POINTER_SPEED}, or the default value {@link #DEFAULT_POINTER_SPEED}. + * + * @hide + */ + public void setTouchpadPointerSpeed(@NonNull Context context, int speed) { + if (speed < MIN_POINTER_SPEED || speed > MAX_POINTER_SPEED) { + throw new IllegalArgumentException("speed out of range"); + } + + // TODO: set the right setting + } + + /** + * Changes the touchpad pointer speed temporarily, but does not save the setting. + * + * The new speed will only apply to gesture-compatible touchpads. + * Requires {@link android.Manifest.permission.SET_POINTER_SPEED}. + * + * @param speed The pointer speed as a value between {@link #MIN_POINTER_SPEED} and + * {@link #MAX_POINTER_SPEED}, or the default value {@link #DEFAULT_POINTER_SPEED}. + * + * @hide + */ + public void tryTouchpadPointerSpeed(int speed) { + if (speed < MIN_POINTER_SPEED || speed > MAX_POINTER_SPEED) { + throw new IllegalArgumentException("speed out of range"); + } + + // TODO: set the touchpad pointer speed on the gesture library + } + + /** + * Returns true if the touchpad should use pointer acceleration. + * + * The returned value only applies to gesture-compatible touchpads. + * + * @param context The application context. + * @return Whether the touchpad should use pointer acceleration. + * + * @hide + */ + public boolean useTouchpadPointerAcceleration(@NonNull Context context) { + // TODO: obtain the actual behavior from the settings + return true; + } + + /** + * Sets the pointer acceleration behavior for the touchpad. + * + * The new behavior is only applied to gesture-compatible touchpads. + * + * @param context The application context. + * @param enabled Will enable pointer acceleration if true, disable it if false + * + * @hide + */ + public void setTouchpadPointerAcceleration(@NonNull Context context, boolean enabled) { + // TODO: set the right setting + } + + /** + * Returns true if moving two fingers upwards on the touchpad should + * scroll down, which is known as natural scrolling. + * + * The returned value only applies to gesture-compatible touchpads. + * + * @param context The application context. + * @return Whether the touchpad should use natural scrolling. + * + * @hide + */ + public boolean useTouchpadNaturalScrolling(@NonNull Context context) { + // TODO: obtain the actual behavior from the settings + return true; + } + + /** + * Sets the natural scroll behavior for the touchpad. + * + * If natural scrolling is enabled, moving two fingers upwards on the + * touchpad will scroll down. + * + * @param context The application context. + * @param enabled Will enable natural scroll if true, disable it if false + * + * @hide + */ + public void setTouchpadNaturalScrolling(@NonNull Context context, boolean enabled) { + // TODO: set the right setting + } + + /** + * Returns true if the touchpad should use tap to click. + * + * The returned value only applies to gesture-compatible touchpads. + * + * @param context The application context. + * @return Whether the touchpad should use tap to click. + * + * @hide + */ + public boolean useTouchpadTapToClick(@NonNull Context context) { + // TODO: obtain the actual behavior from the settings + return true; + } + + /** + * Sets the tap to click behavior for the touchpad. + * + * The new behavior is only applied to gesture-compatible touchpads. + * + * @param context The application context. + * @param enabled Will enable tap to click if true, disable it if false + * + * @hide + */ + public void setTouchpadTapToClick(@NonNull Context context, boolean enabled) { + // TODO: set the right setting + } + + /** + * Returns true if the touchpad should use tap dragging. + * + * The returned value only applies to gesture-compatible touchpads. + * + * @param context The application context. + * @return Whether the touchpad should use tap dragging. + * + * @hide + */ + public boolean useTouchpadTapDragging(@NonNull Context context) { + // TODO: obtain the actual behavior from the settings + return true; + } + + /** + * Sets the tap dragging behavior for the touchpad. + * + * The new behavior is only applied to gesture-compatible touchpads. + * + * @param context The application context. + * @param enabled Will enable tap dragging if true, disable it if false + * + * @hide + */ + public void setTouchpadTapDragging(@NonNull Context context, boolean enabled) { + // TODO: set the right setting + } + + /** + * Returns true if the touchpad should use the right click zone. + * + * The returned value only applies to gesture-compatible touchpads. + * + * @param context The application context. + * @return Whether the touchpad should use the right click zone. + * + * @hide + */ + public boolean useTouchpadRightClickZone(@NonNull Context context) { + // TODO: obtain the actual behavior from the settings + return true; + } + + /** + * Sets the right click zone behavior for the touchpad. + * + * The new behavior is only applied to gesture-compatible touchpads. + * + * @param context The application context. + * @param enabled Will enable the right click zone if true, disable it if false + * + * @hide + */ + public void setTouchpadRightClickZone(@NonNull Context context, boolean enabled) { + // TODO: set the right setting + } + + /** * A callback used to be notified about battery state changes for an input device. The * {@link #onBatteryStateChanged(int, long, BatteryState)} method will be called once after the * listener is successfully registered to provide the initial battery state of the device. diff --git a/core/java/android/os/BatteryStats.java b/core/java/android/os/BatteryStats.java index 7a55a5c4ef72..e915d98722cf 100644 --- a/core/java/android/os/BatteryStats.java +++ b/core/java/android/os/BatteryStats.java @@ -650,8 +650,11 @@ public abstract class BatteryStats { return Uid.PROCESS_STATE_NONEXISTENT; } else if (procState == ActivityManager.PROCESS_STATE_TOP) { return Uid.PROCESS_STATE_TOP; - } else if (ActivityManager.isForegroundService(procState)) { - // State when app has put itself in the foreground. + } else if (procState == ActivityManager.PROCESS_STATE_BOUND_TOP) { + return Uid.PROCESS_STATE_BACKGROUND; + } else if (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) { + return Uid.PROCESS_STATE_FOREGROUND_SERVICE; + } else if (procState == ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) { return Uid.PROCESS_STATE_FOREGROUND_SERVICE; } else if (procState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) { // Persistent and other foreground states go here. diff --git a/core/java/android/os/CoolingDevice.java b/core/java/android/os/CoolingDevice.java index 4babd4b524c9..4ddcd9d4ff8b 100644 --- a/core/java/android/os/CoolingDevice.java +++ b/core/java/android/os/CoolingDevice.java @@ -19,7 +19,7 @@ package android.os; import android.annotation.IntDef; import android.annotation.NonNull; import android.annotation.Nullable; -import android.hardware.thermal.V2_0.CoolingType; +import android.hardware.thermal.CoolingType; import com.android.internal.util.Preconditions; @@ -52,11 +52,16 @@ public final class CoolingDevice implements Parcelable { TYPE_MODEM, TYPE_NPU, TYPE_COMPONENT, + TYPE_TPU, + TYPE_POWER_AMPLIFIER, + TYPE_DISPLAY, + TYPE_SPEAKER }) @Retention(RetentionPolicy.SOURCE) public @interface Type {} - /** Keep in sync with hardware/interfaces/thermal/2.0/types.hal */ + /** Keep in sync with hardware/interfaces/thermal/aidl/android/hardware/thermal + * /ThrottlingSeverity.aidl */ /** Fan for active cooling */ public static final int TYPE_FAN = CoolingType.FAN; /** Battery charging cooling deivice */ @@ -67,10 +72,18 @@ public final class CoolingDevice implements Parcelable { public static final int TYPE_GPU = CoolingType.GPU; /** Modem cooling deivice */ public static final int TYPE_MODEM = CoolingType.MODEM; - /** NPU/TPU cooling deivice */ + /** NPU cooling deivice */ public static final int TYPE_NPU = CoolingType.NPU; /** Generic passive cooling deivice */ public static final int TYPE_COMPONENT = CoolingType.COMPONENT; + /** TPU cooling deivice */ + public static final int TYPE_TPU = CoolingType.TPU; + /** Power amplifier cooling device */ + public static final int TYPE_POWER_AMPLIFIER = CoolingType.POWER_AMPLIFIER; + /** Display cooling device */ + public static final int TYPE_DISPLAY = CoolingType.DISPLAY; + /** Speaker cooling device */ + public static final int TYPE_SPEAKER = CoolingType.SPEAKER; /** * Verify a valid cooling device type. @@ -78,7 +91,7 @@ public final class CoolingDevice implements Parcelable { * @return true if a cooling device type is valid otherwise false. */ public static boolean isValidType(@Type int type) { - return type >= TYPE_FAN && type <= TYPE_COMPONENT; + return type >= TYPE_FAN && type <= TYPE_SPEAKER; } public CoolingDevice(long value, @Type int type, @NonNull String name) { diff --git a/core/java/android/os/IUserManager.aidl b/core/java/android/os/IUserManager.aidl index d31540a65f2f..c2ddf4535d91 100644 --- a/core/java/android/os/IUserManager.aidl +++ b/core/java/android/os/IUserManager.aidl @@ -79,6 +79,7 @@ interface IUserManager { String getUserAccount(int userId); void setUserAccount(int userId, String accountName); long getUserCreationTime(int userId); + int getUserSwitchability(int userId); boolean isUserSwitcherEnabled(boolean showEvenIfNotActionable, int mUserId); boolean isRestricted(int userId); boolean canHaveRestrictedProfile(int userId); diff --git a/core/java/android/os/OWNERS b/core/java/android/os/OWNERS index 5c5af2a26a53..e9a32544e58e 100644 --- a/core/java/android/os/OWNERS +++ b/core/java/android/os/OWNERS @@ -71,6 +71,9 @@ per-file Vintf* = file:/platform/system/libvintf:/OWNERS # Tracing per-file Trace.java = file:/TRACE_OWNERS +# PatternMatcher +per-file PatternMatcher* = file:/PACKAGE_MANAGER_OWNERS + # PermissionEnforcer per-file PermissionEnforcer.java = tweek@google.com, brufino@google.com diff --git a/core/java/android/os/PowerManager.java b/core/java/android/os/PowerManager.java index 9bc7ffdef26e..dc62f8c9add7 100644 --- a/core/java/android/os/PowerManager.java +++ b/core/java/android/os/PowerManager.java @@ -533,10 +533,7 @@ public final class PowerManager { BRIGHTNESS_CONSTRAINT_TYPE_MAXIMUM, BRIGHTNESS_CONSTRAINT_TYPE_DEFAULT, BRIGHTNESS_CONSTRAINT_TYPE_DIM, - BRIGHTNESS_CONSTRAINT_TYPE_DOZE, - BRIGHTNESS_CONSTRAINT_TYPE_MINIMUM_VR, - BRIGHTNESS_CONSTRAINT_TYPE_MAXIMUM_VR, - BRIGHTNESS_CONSTRAINT_TYPE_DEFAULT_VR + BRIGHTNESS_CONSTRAINT_TYPE_DOZE }) @Retention(RetentionPolicy.SOURCE) public @interface BrightnessConstraint{} @@ -571,24 +568,6 @@ public final class PowerManager { public static final int BRIGHTNESS_CONSTRAINT_TYPE_DOZE = 4; /** - * Brightness constraint type: minimum allowed value. - * @hide - */ - public static final int BRIGHTNESS_CONSTRAINT_TYPE_MINIMUM_VR = 5; - - /** - * Brightness constraint type: minimum allowed value. - * @hide - */ - public static final int BRIGHTNESS_CONSTRAINT_TYPE_MAXIMUM_VR = 6; - - /** - * Brightness constraint type: minimum allowed value. - * @hide - */ - public static final int BRIGHTNESS_CONSTRAINT_TYPE_DEFAULT_VR = 7; - - /** * @hide */ @IntDef(prefix = { "WAKE_REASON_" }, value = { @@ -1211,35 +1190,6 @@ public final class PowerManager { } /** - * Gets the minimum supported screen brightness setting for VR Mode. - * @hide - */ - public int getMinimumScreenBrightnessForVrSetting() { - return mContext.getResources().getInteger( - com.android.internal.R.integer.config_screenBrightnessForVrSettingMinimum); - } - - /** - * Gets the maximum supported screen brightness setting for VR Mode. - * The screen may be allowed to become dimmer than this value but - * this is the maximum value that can be set by the user. - * @hide - */ - public int getMaximumScreenBrightnessForVrSetting() { - return mContext.getResources().getInteger( - com.android.internal.R.integer.config_screenBrightnessForVrSettingMaximum); - } - - /** - * Gets the default screen brightness for VR setting. - * @hide - */ - public int getDefaultScreenBrightnessForVrSetting() { - return mContext.getResources().getInteger( - com.android.internal.R.integer.config_screenBrightnessForVrSettingDefault); - } - - /** * Gets a float screen brightness setting. * @hide */ diff --git a/core/java/android/os/Temperature.java b/core/java/android/os/Temperature.java index 55785f3bdba9..a138431f745a 100644 --- a/core/java/android/os/Temperature.java +++ b/core/java/android/os/Temperature.java @@ -19,8 +19,8 @@ package android.os; import android.annotation.IntDef; import android.annotation.NonNull; import android.annotation.Nullable; -import android.hardware.thermal.V2_0.TemperatureType; -import android.hardware.thermal.V2_0.ThrottlingSeverity; +import android.hardware.thermal.TemperatureType; +import android.hardware.thermal.ThrottlingSeverity; import com.android.internal.util.Preconditions; @@ -54,7 +54,8 @@ public final class Temperature implements Parcelable { @Retention(RetentionPolicy.SOURCE) public @interface ThrottlingStatus {} - /** Keep in sync with hardware/interfaces/thermal/2.0/types.hal */ + /** Keep in sync with hardware/interfaces/thermal/aidl/android/hardware/thermal + * /ThrottlingSeverity.aidl */ public static final int THROTTLING_NONE = ThrottlingSeverity.NONE; public static final int THROTTLING_LIGHT = ThrottlingSeverity.LIGHT; public static final int THROTTLING_MODERATE = ThrottlingSeverity.MODERATE; @@ -75,11 +76,16 @@ public final class Temperature implements Parcelable { TYPE_BCL_CURRENT, TYPE_BCL_PERCENTAGE, TYPE_NPU, + TYPE_TPU, + TYPE_DISPLAY, + TYPE_MODEM, + TYPE_SOC }) @Retention(RetentionPolicy.SOURCE) public @interface Type {} - /** Keep in sync with hardware/interfaces/thermal/2.0/types.hal */ + /** Keep in sync with hardware/interfaces/thermal/aidl/android/hardware/thermal + * /TemperatureType.aidl */ public static final int TYPE_UNKNOWN = TemperatureType.UNKNOWN; public static final int TYPE_CPU = TemperatureType.CPU; public static final int TYPE_GPU = TemperatureType.GPU; @@ -91,6 +97,10 @@ public final class Temperature implements Parcelable { public static final int TYPE_BCL_CURRENT = TemperatureType.BCL_CURRENT; public static final int TYPE_BCL_PERCENTAGE = TemperatureType.BCL_PERCENTAGE; public static final int TYPE_NPU = TemperatureType.NPU; + public static final int TYPE_TPU = TemperatureType.TPU; + public static final int TYPE_DISPLAY = TemperatureType.DISPLAY; + public static final int TYPE_MODEM = TemperatureType.MODEM; + public static final int TYPE_SOC = TemperatureType.SOC; /** * Verify a valid Temperature type. @@ -98,7 +108,7 @@ public final class Temperature implements Parcelable { * @return true if a Temperature type is valid otherwise false. */ public static boolean isValidType(@Type int type) { - return type >= TYPE_UNKNOWN && type <= TYPE_NPU; + return type >= TYPE_UNKNOWN && type <= TYPE_SOC; } /** diff --git a/core/java/android/os/UidBatteryConsumer.java b/core/java/android/os/UidBatteryConsumer.java index 4a6772dcccd6..103452d255a7 100644 --- a/core/java/android/os/UidBatteryConsumer.java +++ b/core/java/android/os/UidBatteryConsumer.java @@ -50,8 +50,7 @@ public final class UidBatteryConsumer extends BatteryConsumer { } /** - * The state of an application when it is either running a foreground (top) activity - * or a foreground service. + * The state of an application when it is either running a foreground (top) activity. */ public static final int STATE_FOREGROUND = 0; @@ -63,7 +62,8 @@ public final class UidBatteryConsumer extends BatteryConsumer { * {@link android.app.ActivityManager#PROCESS_STATE_TRANSIENT_BACKGROUND}, * {@link android.app.ActivityManager#PROCESS_STATE_BACKUP}, * {@link android.app.ActivityManager#PROCESS_STATE_SERVICE}, - * {@link android.app.ActivityManager#PROCESS_STATE_RECEIVER}. + * {@link android.app.ActivityManager#PROCESS_STATE_RECEIVER}, + * {@link android.app.ActivityManager#PROCESS_STATE_FOREGROUND_SERVICE}. */ public static final int STATE_BACKGROUND = 1; diff --git a/core/java/android/os/UserManager.java b/core/java/android/os/UserManager.java index 07c4b441655e..5f2f710e3c01 100644 --- a/core/java/android/os/UserManager.java +++ b/core/java/android/os/UserManager.java @@ -59,7 +59,6 @@ import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.location.LocationManager; import android.provider.Settings; -import android.telecom.TelecomManager; import android.util.AndroidException; import android.util.ArraySet; import android.util.Log; @@ -1748,7 +1747,7 @@ public class UserManager { public static final int SWITCHABILITY_STATUS_SYSTEM_USER_LOCKED = 1 << 2; /** - * Result returned in {@link #getUserSwitchability()} indicating user swichability. + * Result returned in {@link #getUserSwitchability()} indicating user switchability. * @hide */ @Retention(RetentionPolicy.SOURCE) @@ -2128,20 +2127,16 @@ public class UserManager { * @hide */ @Deprecated - @RequiresPermission(allOf = { - Manifest.permission.READ_PHONE_STATE, - Manifest.permission.MANAGE_USERS}, // Can be INTERACT_ACROSS_USERS instead. - conditional = true) + @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS, + android.Manifest.permission.INTERACT_ACROSS_USERS}) @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) @UserHandleAware public boolean canSwitchUsers() { - boolean allowUserSwitchingWhenSystemUserLocked = Settings.Global.getInt( - mContext.getContentResolver(), - Settings.Global.ALLOW_USER_SWITCHING_WHEN_SYSTEM_USER_LOCKED, 0) != 0; - boolean isSystemUserUnlocked = isUserUnlocked(UserHandle.SYSTEM); - boolean isUserSwitchDisallowed = hasUserRestrictionForUser(DISALLOW_USER_SWITCH, mUserId); - return (allowUserSwitchingWhenSystemUserLocked || isSystemUserUnlocked) && !inCall() - && !isUserSwitchDisallowed; + try { + return mService.getUserSwitchability(mUserId) == SWITCHABILITY_STATUS_OK; + } catch (RemoteException re) { + throw re.rethrowFromSystemServer(); + } } /** @@ -2156,9 +2151,8 @@ public class UserManager { * @hide */ @SystemApi - @RequiresPermission(allOf = {Manifest.permission.READ_PHONE_STATE, - android.Manifest.permission.MANAGE_USERS, - android.Manifest.permission.INTERACT_ACROSS_USERS}, conditional = true) + @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS, + android.Manifest.permission.INTERACT_ACROSS_USERS}) @UserHandleAware(enabledSinceTargetSdkVersion = Build.VERSION_CODES.TIRAMISU) public @UserSwitchabilityResult int getUserSwitchability() { return getUserSwitchability(UserHandle.of(getContextUserIfAppropriate())); @@ -2175,31 +2169,14 @@ public class UserManager { * @return A {@link UserSwitchabilityResult} flag indicating if the user is switchable. * @hide */ - @RequiresPermission(allOf = {Manifest.permission.READ_PHONE_STATE, - android.Manifest.permission.MANAGE_USERS, - android.Manifest.permission.INTERACT_ACROSS_USERS}, conditional = true) + @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS, + android.Manifest.permission.INTERACT_ACROSS_USERS}) public @UserSwitchabilityResult int getUserSwitchability(UserHandle userHandle) { - int flags = SWITCHABILITY_STATUS_OK; - if (inCall()) { - flags |= SWITCHABILITY_STATUS_USER_IN_CALL; - } - if (hasUserRestrictionForUser(DISALLOW_USER_SWITCH, userHandle)) { - flags |= SWITCHABILITY_STATUS_USER_SWITCH_DISALLOWED; - } - - // System User is always unlocked in Headless System User Mode, so ignore this flag - if (!isHeadlessSystemUserMode()) { - final boolean allowUserSwitchingWhenSystemUserLocked = Settings.Global.getInt( - mContext.getContentResolver(), - Settings.Global.ALLOW_USER_SWITCHING_WHEN_SYSTEM_USER_LOCKED, 0) != 0; - final boolean systemUserUnlocked = isUserUnlocked(UserHandle.SYSTEM); - - if (!allowUserSwitchingWhenSystemUserLocked && !systemUserUnlocked) { - flags |= SWITCHABILITY_STATUS_SYSTEM_USER_LOCKED; - } + try { + return mService.getUserSwitchability(userHandle.getIdentifier()); + } catch (RemoteException re) { + throw re.rethrowFromSystemServer(); } - - return flags; } /** @@ -5614,11 +5591,6 @@ public class UserManager { } } - private boolean inCall() { - final TelecomManager telecomManager = mContext.getSystemService(TelecomManager.class); - return telecomManager != null && telecomManager.isInCall(); - } - /* Cache key for anything that assumes that userIds cannot be re-used without rebooting. */ private static final String CACHE_KEY_STATIC_USER_PROPERTIES = "cache_key.static_user_props"; diff --git a/core/java/android/provider/DeviceConfig.java b/core/java/android/provider/DeviceConfig.java deleted file mode 100644 index 7df9290274ce..000000000000 --- a/core/java/android/provider/DeviceConfig.java +++ /dev/null @@ -1,1566 +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 android.provider; - -import static android.Manifest.permission.READ_DEVICE_CONFIG; -import static android.Manifest.permission.WRITE_DEVICE_CONFIG; - -import android.annotation.CallbackExecutor; -import android.annotation.NonNull; -import android.annotation.Nullable; -import android.annotation.RequiresPermission; -import android.annotation.SuppressLint; -import android.annotation.SystemApi; -import android.database.ContentObserver; -import android.net.Uri; -import android.provider.Settings.Config.SyncDisabledMode; -import android.provider.Settings.ResetMode; -import android.util.ArrayMap; -import android.util.Log; -import android.util.Pair; - -import com.android.internal.annotations.GuardedBy; -import com.android.internal.util.Preconditions; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.Executor; - -/** - * Device level configuration parameters which can be tuned by a separate configuration service. - * Namespaces that end in "_native" such as {@link #NAMESPACE_NETD_NATIVE} are intended to be used - * by native code and should be pushed to system properties to make them accessible. - * - * @hide - */ -@SystemApi -public final class DeviceConfig { - /** - * Namespace for activity manager related features. These features will be applied - * immediately upon change. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_ACTIVITY_MANAGER = "activity_manager"; - - /** - * Namespace for activity manager, specific to the "component alias" feature. We needed a - * different namespace in order to avoid phonetype from resetting it. - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_ACTIVITY_MANAGER_COMPONENT_ALIAS = "activity_manager_ca"; - - /** - * Namespace for all activity manager related features that are used at the native level. - * These features are applied at reboot. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_ACTIVITY_MANAGER_NATIVE_BOOT = - "activity_manager_native_boot"; - - /** - * Namespace for AlarmManager configurations. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_ALARM_MANAGER = "alarm_manager"; - - /** - * Namespace for all app compat related features. These features will be applied - * immediately upon change. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_APP_COMPAT = "app_compat"; - - /** - * Namespace for all app hibernation related features. - * @hide - */ - @SystemApi - public static final String NAMESPACE_APP_HIBERNATION = "app_hibernation"; - - /** - * Namespace for all AppSearch related features. - * @hide - */ - @SystemApi - public static final String NAMESPACE_APPSEARCH = "appsearch"; - - /** - * Namespace for app standby configurations. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_APP_STANDBY = "app_standby"; - - /** - * Namespace for all App Cloning related features. - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_APP_CLONING = "app_cloning"; - - /** - * Namespace for AttentionManagerService related features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_ATTENTION_MANAGER_SERVICE = "attention_manager_service"; - - /** - * Namespace for autofill feature that provides suggestions across all apps when - * the user interacts with input fields. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_AUTOFILL = "autofill"; - - /** - * Namespace for battery saver feature. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_BATTERY_SAVER = "battery_saver"; - - /** - * Namespace for blobstore feature that allows apps to share data blobs. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_BLOBSTORE = "blobstore"; - - /** - * Namespace for all Bluetooth related features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_BLUETOOTH = "bluetooth"; - - /** - * Namespace for features relating to clipboard. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_CLIPBOARD = "clipboard"; - - /** - * Namespace for all networking connectivity related features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_CONNECTIVITY = "connectivity"; - - /** - * Namespace for CaptivePortalLogin module. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_CAPTIVEPORTALLOGIN = "captive_portal_login"; - - /** - * Namespace for Tethering module. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_TETHERING = "tethering"; - - - /** - * Namespace for Nearby module. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_NEARBY = "nearby"; - - /** - * Namespace for content capture feature used by on-device machine intelligence - * to provide suggestions in a privacy-safe manner. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_CONTENT_CAPTURE = "content_capture"; - - /** - * Namespace for device idle configurations. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_DEVICE_IDLE = "device_idle"; - - /** - * Namespace for how dex runs. The feature requires a reboot to reach a clean state. - * - * @deprecated No longer used - * @hide - */ - @Deprecated - @SystemApi - public static final String NAMESPACE_DEX_BOOT = "dex_boot"; - - /** - * Namespace for display manager related features. The names to access the properties in this - * namespace should be defined in {@link android.hardware.display.DisplayManager}. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_DISPLAY_MANAGER = "display_manager"; - - /** - * Namespace for all Game Driver features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_GAME_DRIVER = "game_driver"; - - /** - * Namespace for all HDMI Control features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_HDMI_CONTROL = "hdmi_control"; - - /** - * Namespace for all input-related features that are used at the native level. - * These features are applied at reboot. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_INPUT_NATIVE_BOOT = "input_native_boot"; - - /** - * Namespace for attention-based features provided by on-device machine intelligence. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_INTELLIGENCE_ATTENTION = "intelligence_attention"; - - /** - * Definitions for properties related to Content Suggestions. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_INTELLIGENCE_CONTENT_SUGGESTIONS = - "intelligence_content_suggestions"; - - /** - * Namespace for JobScheduler configurations. - * @hide - */ - @SystemApi - public static final String NAMESPACE_JOB_SCHEDULER = "jobscheduler"; - - /** - * Namespace for all lmkd related features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_LMKD_NATIVE = "lmkd_native"; - - /** - * Namespace for all location related features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_LOCATION = "location"; - - /** - * Namespace for all media related features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_MEDIA = "media"; - - /** - * Namespace for all media native related features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_MEDIA_NATIVE = "media_native"; - - /** - * Namespace for all Kernel Multi-Gen LRU feature. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_MGLRU_NATIVE = "mglru_native"; - - /** - * Namespace for all netd related features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_NETD_NATIVE = "netd_native"; - - /** - * Namespace for all Android NNAPI related features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_NNAPI_NATIVE = "nnapi_native"; - - /** - * Namespace for all OnDevicePersonalization related feature. - * @hide - */ - @SystemApi - public static final String NAMESPACE_ON_DEVICE_PERSONALIZATION = "on_device_personalization"; - - /** - * Namespace for features related to the Package Manager Service. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_PACKAGE_MANAGER_SERVICE = "package_manager_service"; - - /** - * Namespace for features related to the Profcollect native Service. - * These features are applied at reboot. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_PROFCOLLECT_NATIVE_BOOT = "profcollect_native_boot"; - - /** - * Namespace for features related to Reboot Readiness detection. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_REBOOT_READINESS = "reboot_readiness"; - - /** - * Namespace for Remote Key Provisioning related features. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_REMOTE_KEY_PROVISIONING_NATIVE = - "remote_key_provisioning_native"; - - /** - * Namespace for Rollback flags that are applied immediately. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_ROLLBACK = "rollback"; - - /** - * Namespace for Rollback flags that are applied after a reboot. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_ROLLBACK_BOOT = "rollback_boot"; - - /** - * Namespace for Rotation Resolver Manager Service. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_ROTATION_RESOLVER = "rotation_resolver"; - - /** - * Namespace for all runtime related features that don't require a reboot to become active. - * There are no feature flags using NAMESPACE_RUNTIME. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_RUNTIME = "runtime"; - - /** - * Namespace for all runtime related features that require system properties for accessing - * the feature flags from C++ or Java language code. One example is the app image startup - * cache feature use_app_image_startup_cache. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_RUNTIME_NATIVE = "runtime_native"; - - /** - * Namespace for all runtime native boot related features. Boot in this case refers to the - * fact that the properties only take affect after rebooting the device. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_RUNTIME_NATIVE_BOOT = "runtime_native_boot"; - - /** - * Namespace for system scheduler related features. These features will be applied - * immediately upon change. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_SCHEDULER = "scheduler"; - - /** - * Namespace for all SdkSandbox related features. - * @hide - */ - @SystemApi - public static final String NAMESPACE_SDK_SANDBOX = "sdk_sandbox"; - - /** - * Namespace for settings statistics features. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_SETTINGS_STATS = "settings_stats"; - - /** - * Namespace for all statsd java features that can be applied immediately. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_STATSD_JAVA = "statsd_java"; - - /** - * Namespace for all statsd java features that are applied on boot. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_STATSD_JAVA_BOOT = "statsd_java_boot"; - - /** - * Namespace for all statsd native features that can be applied immediately. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_STATSD_NATIVE = "statsd_native"; - - /** - * Namespace for all statsd native features that are applied on boot. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_STATSD_NATIVE_BOOT = "statsd_native_boot"; - - /** - * Namespace for storage-related features. - * - * @deprecated Replace storage namespace with storage_native_boot. - * @hide - */ - @Deprecated - @SystemApi - public static final String NAMESPACE_STORAGE = "storage"; - - /** - * Namespace for storage-related features, including native and boot. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_STORAGE_NATIVE_BOOT = "storage_native_boot"; - - /** - * Namespace for all AdServices related features. - * @hide - */ - @SystemApi - public static final String NAMESPACE_ADSERVICES = "adservices"; - - /** - * Namespace for all SurfaceFlinger features that are used at the native level. - * These features are applied on boot or after reboot. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_SURFACE_FLINGER_NATIVE_BOOT = - "surface_flinger_native_boot"; - - /** - * Namespace for swcodec native related features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_SWCODEC_NATIVE = "swcodec_native"; - - - /** - * Namespace for System UI related features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_SYSTEMUI = "systemui"; - - /** - * Namespace for system time and time zone detection related features / behavior. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_SYSTEM_TIME = "system_time"; - - /** - * Namespace for TARE configurations. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_TARE = "tare"; - - /** - * Telephony related properties. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_TELEPHONY = "telephony"; - - /** - * Namespace for TextClassifier related features. - * - * @hide - * @see android.provider.Settings.Global.TEXT_CLASSIFIER_CONSTANTS - */ - @SystemApi - public static final String NAMESPACE_TEXTCLASSIFIER = "textclassifier"; - - /** - * Namespace for contacts provider related features. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_CONTACTS_PROVIDER = "contacts_provider"; - - /** - * Namespace for settings ui related features - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_SETTINGS_UI = "settings_ui"; - - /** - * Namespace for android related features, i.e. for flags that affect not just a single - * component, but the entire system. - * - * The keys for this namespace are defined in {@link AndroidDeviceConfig}. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_ANDROID = "android"; - - /** - * Namespace for window manager related features. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_WINDOW_MANAGER = "window_manager"; - - /** - * Namespace for window manager features accessible by native code and - * loaded once per boot. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_WINDOW_MANAGER_NATIVE_BOOT = "window_manager_native_boot"; - - /** - * Definitions for selection toolbar related functions. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_SELECTION_TOOLBAR = "selection_toolbar"; - - /** - * Definitions for voice interaction related functions. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_VOICE_INTERACTION = "voice_interaction"; - - /** - * Namespace for DevicePolicyManager related features. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_DEVICE_POLICY_MANAGER = - "device_policy_manager"; - - /** - * List of namespaces which can be read without READ_DEVICE_CONFIG permission - * - * @hide - */ - @NonNull - private static final List<String> PUBLIC_NAMESPACES = - Arrays.asList(NAMESPACE_TEXTCLASSIFIER, NAMESPACE_RUNTIME, NAMESPACE_STATSD_JAVA, - NAMESPACE_STATSD_JAVA_BOOT, NAMESPACE_SELECTION_TOOLBAR, NAMESPACE_AUTOFILL, - NAMESPACE_DEVICE_POLICY_MANAGER, NAMESPACE_CONTENT_CAPTURE); - /** - * Privacy related properties definitions. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_PRIVACY = "privacy"; - - /** - * Namespace for biometrics related features - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_BIOMETRICS = "biometrics"; - - /** - * Permission related properties definitions. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_PERMISSIONS = "permissions"; - - /** - * Namespace for ota related features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_OTA = "ota"; - - /** - * Namespace for all widget related features. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_WIDGET = "widget"; - - /** - * Namespace for connectivity thermal power manager features. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_CONNECTIVITY_THERMAL_POWER_MANAGER = - "connectivity_thermal_power_manager"; - - /** - * Namespace for configuration related features. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_CONFIGURATION = "configuration"; - - /** - * LatencyTracker properties definitions. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_LATENCY_TRACKER = "latency_tracker"; - - /** - * InteractionJankMonitor properties definitions. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - @SuppressLint("IntentName") - public static final String NAMESPACE_INTERACTION_JANK_MONITOR = "interaction_jank_monitor"; - - /** - * Namespace for game overlay related features. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_GAME_OVERLAY = "game_overlay"; - - /** - * Namespace for Android Virtualization Framework related features accessible by native code. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_VIRTUALIZATION_FRAMEWORK_NATIVE = - "virtualization_framework_native"; - - /** - * Namespace for Constrain Display APIs related features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_CONSTRAIN_DISPLAY_APIS = "constrain_display_apis"; - - /** - * Namespace for App Compat Overrides related features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_APP_COMPAT_OVERRIDES = "app_compat_overrides"; - - /** - * Namespace for all ultra wideband (uwb) related features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_UWB = "uwb"; - - /** - * Namespace for AmbientContextEventManagerService related features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_AMBIENT_CONTEXT_MANAGER_SERVICE = - "ambient_context_manager_service"; - - /** - * Namespace for WearableSensingManagerService related features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_WEARABLE_SENSING = - "wearable_sensing"; - - /** - * Namespace for Vendor System Native related features. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_VENDOR_SYSTEM_NATIVE = "vendor_system_native"; - - /** - * Namespace for Vendor System Native Boot related features. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_VENDOR_SYSTEM_NATIVE_BOOT = "vendor_system_native_boot"; - - /** - * Namespace for memory safety related features (e.g. MTE) - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_MEMORY_SAFETY_NATIVE = "memory_safety_native"; - - /** - * Namespace for wear OS platform features. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_WEAR = "wear"; - - /** - * Namespace for features relating to MBA transparency metadata. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_TRANSPARENCY_METADATA = "transparency_metadata"; - - /** - * Namespace for the input method manager platform features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_INPUT_METHOD_MANAGER = "input_method_manager"; - - /** - * Namespace for backup and restore service related features. - * - * @hide - */ - @SystemApi - public static final String NAMESPACE_BACKUP_AND_RESTORE = "backup_and_restore"; - - /** - * Namespace for ARC App Compat related features. - * - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public static final String NAMESPACE_ARC_APP_COMPAT = "arc_app_compat"; - - private static final Object sLock = new Object(); - @GuardedBy("sLock") - private static ArrayMap<OnPropertiesChangedListener, Pair<String, Executor>> sListeners = - new ArrayMap<>(); - @GuardedBy("sLock") - private static Map<String, Pair<ContentObserver, Integer>> sNamespaces = new HashMap<>(); - private static final String TAG = "DeviceConfig"; - - // Should never be invoked - private DeviceConfig() { - } - - /** - * Look up the value of a property for a particular namespace. - * - * @param namespace The namespace containing the property to look up. - * @param name The name of the property to look up. - * @return the corresponding value, or null if not present. - * @hide - */ - @SystemApi - @RequiresPermission(READ_DEVICE_CONFIG) - public static String getProperty(@NonNull String namespace, @NonNull String name) { - // Fetch all properties for the namespace at once and cache them in the local process, so we - // incur the cost of the IPC less often. Lookups happen much more frequently than updates, - // and we want to optimize the former. - return getProperties(namespace, name).getString(name, null); - } - - /** - * Look up the values of multiple properties for a particular namespace. The lookup is atomic, - * such that the values of these properties cannot change between the time when the first is - * fetched and the time when the last is fetched. - * <p> - * Each call to {@link #setProperties(Properties)} is also atomic and ensures that either none - * or all of the change is picked up here, but never only part of it. - * - * @param namespace The namespace containing the properties to look up. - * @param names The names of properties to look up, or empty to fetch all properties for the - * given namespace. - * @return {@link Properties} object containing the requested properties. This reflects the - * state of these properties at the time of the lookup, and is not updated to reflect any - * future changes. The keyset of this Properties object will contain only the intersection - * of properties already set and properties requested via the names parameter. Properties - * that are already set but were not requested will not be contained here. Properties that - * are not set, but were requested will not be contained here either. - * @hide - */ - @SystemApi - @NonNull - @RequiresPermission(READ_DEVICE_CONFIG) - public static Properties getProperties(@NonNull String namespace, @NonNull String ... names) { - return new Properties(namespace, - Settings.Config.getStrings(namespace, Arrays.asList(names))); - } - - /** - * Look up the String value of a property for a particular namespace. - * - * @param namespace The namespace containing the property to look up. - * @param name The name of the property to look up. - * @param defaultValue The value to return if the property does not exist or has no non-null - * value. - * @return the corresponding value, or defaultValue if none exists. - * @hide - */ - @SystemApi - @RequiresPermission(READ_DEVICE_CONFIG) - public static String getString(@NonNull String namespace, @NonNull String name, - @Nullable String defaultValue) { - String value = getProperty(namespace, name); - return value != null ? value : defaultValue; - } - - /** - * Look up the boolean value of a property for a particular namespace. - * - * @param namespace The namespace containing the property to look up. - * @param name The name of the property to look up. - * @param defaultValue The value to return if the property does not exist or has no non-null - * value. - * @return the corresponding value, or defaultValue if none exists. - * @hide - */ - @SystemApi - @RequiresPermission(READ_DEVICE_CONFIG) - public static boolean getBoolean(@NonNull String namespace, @NonNull String name, - boolean defaultValue) { - String value = getProperty(namespace, name); - return value != null ? Boolean.parseBoolean(value) : defaultValue; - } - - /** - * Look up the int value of a property for a particular namespace. - * - * @param namespace The namespace containing the property to look up. - * @param name The name of the property to look up. - * @param defaultValue The value to return if the property does not exist, has no non-null - * value, or fails to parse into an int. - * @return the corresponding value, or defaultValue if either none exists or it does not parse. - * @hide - */ - @SystemApi - @RequiresPermission(READ_DEVICE_CONFIG) - public static int getInt(@NonNull String namespace, @NonNull String name, int defaultValue) { - String value = getProperty(namespace, name); - if (value == null) { - return defaultValue; - } - try { - return Integer.parseInt(value); - } catch (NumberFormatException e) { - Log.e(TAG, "Parsing integer failed for " + namespace + ":" + name); - return defaultValue; - } - } - - /** - * Look up the long value of a property for a particular namespace. - * - * @param namespace The namespace containing the property to look up. - * @param name The name of the property to look up. - * @param defaultValue The value to return if the property does not exist, has no non-null - * value, or fails to parse into a long. - * @return the corresponding value, or defaultValue if either none exists or it does not parse. - * @hide - */ - @SystemApi - @RequiresPermission(READ_DEVICE_CONFIG) - public static long getLong(@NonNull String namespace, @NonNull String name, long defaultValue) { - String value = getProperty(namespace, name); - if (value == null) { - return defaultValue; - } - try { - return Long.parseLong(value); - } catch (NumberFormatException e) { - Log.e(TAG, "Parsing long failed for " + namespace + ":" + name); - return defaultValue; - } - } - - /** - * Look up the float value of a property for a particular namespace. - * - * @param namespace The namespace containing the property to look up. - * @param name The name of the property to look up. - * @param defaultValue The value to return if the property does not exist, has no non-null - * value, or fails to parse into a float. - * @return the corresponding value, or defaultValue if either none exists or it does not parse. - * @hide - */ - @SystemApi - @RequiresPermission(READ_DEVICE_CONFIG) - public static float getFloat(@NonNull String namespace, @NonNull String name, - float defaultValue) { - String value = getProperty(namespace, name); - if (value == null) { - return defaultValue; - } - try { - return Float.parseFloat(value); - } catch (NumberFormatException e) { - Log.e(TAG, "Parsing float failed for " + namespace + ":" + name); - return defaultValue; - } - } - - /** - * Create a new property with the provided name and value in the provided namespace, or - * update the value of such a property if it already exists. The same name can exist in multiple - * namespaces and might have different values in any or all namespaces. - * <p> - * The method takes an argument indicating whether to make the value the default for this - * property. - * <p> - * All properties stored for a particular scope can be reverted to their default values - * by passing the namespace to {@link #resetToDefaults(int, String)}. - * - * @param namespace The namespace containing the property to create or update. - * @param name The name of the property to create or update. - * @param value The value to store for the property. - * @param makeDefault Whether to make the new value the default one. - * @return {@code true} if the value was set, {@code false} if the storage implementation throws - * errors. - * @hide - * @see #resetToDefaults(int, String). - */ - @SystemApi - @RequiresPermission(WRITE_DEVICE_CONFIG) - public static boolean setProperty(@NonNull String namespace, @NonNull String name, - @Nullable String value, boolean makeDefault) { - return Settings.Config.putString(namespace, name, value, makeDefault); - } - - /** - * Set all of the properties for a specific namespace. Pre-existing properties will be updated - * and new properties will be added if necessary. Any pre-existing properties for the specific - * namespace which are not part of the provided {@link Properties} object will be deleted from - * the namespace. These changes are all applied atomically, such that no calls to read or reset - * these properties can happen in the middle of this update. - * <p> - * Each call to {@link #getProperties(String, String...)} is also atomic and ensures that either - * none or all of this update is picked up, but never only part of it. - * - * @param properties the complete set of properties to set for a specific namespace. - * @throws BadConfigException if the provided properties are banned by RescueParty. - * @return {@code true} if the values were set, {@code false} otherwise. - * @hide - */ - @SystemApi - @RequiresPermission(WRITE_DEVICE_CONFIG) - public static boolean setProperties(@NonNull Properties properties) throws BadConfigException { - return Settings.Config.setStrings(properties.getNamespace(), - properties.mMap); - } - - /** - * Delete a property with the provided name and value in the provided namespace - * - * @param namespace The namespace containing the property to delete. - * @param name The name of the property to delete. - * @return {@code true} if the property was deleted or it did not exist in the first place. - * Return {@code false} if the storage implementation throws errors. - * @hide - */ - @SystemApi - @RequiresPermission(WRITE_DEVICE_CONFIG) - public static boolean deleteProperty(@NonNull String namespace, @NonNull String name) { - return Settings.Config.deleteString(namespace, name); - } - - /** - * Reset properties to their default values by removing the underlying values. - * <p> - * The method accepts an optional namespace parameter. If provided, only properties set within - * that namespace will be reset. Otherwise, all properties will be reset. - * <p> - * Note: This method should only be used by {@link com.android.server.RescueParty}. It was - * designed to be used in the event of boot or crash loops caused by flag changes. It does not - * revert flag values to defaults - instead it removes the property entirely which causes the - * consumer of the flag to use hardcoded defaults upon retrieval. - * <p> - * To clear values for a namespace without removing the underlying properties, construct a - * {@link Properties} object with the caller's namespace and either an empty flag map, or some - * snapshot of flag values. Then use {@link #setProperties(Properties)} to remove all flags - * under the namespace, or set them to the values in the snapshot. - * <p> - * To revert values for testing, one should mock DeviceConfig using - * {@link com.android.server.testables.TestableDeviceConfig} where possible. Otherwise, fallback - * to using {@link #setProperties(Properties)} as outlined above. - * - * @param resetMode The reset mode to use. - * @param namespace Optionally, the specific namespace which resets will be limited to. - * @hide - * @see #setProperty(String, String, String, boolean) - */ - @SystemApi - @RequiresPermission(WRITE_DEVICE_CONFIG) - public static void resetToDefaults(@ResetMode int resetMode, @Nullable String namespace) { - Settings.Config.resetToDefaults(resetMode, namespace); - } - - /** - * Disables or re-enables bulk modifications ({@link #setProperties(Properties)}) to device - * config values. This is intended for use during tests to prevent a sync operation clearing - * config values which could influence the outcome of the tests, i.e. by changing behavior. - * - * @param syncDisabledMode the mode to use, see {@link Settings.Config#SYNC_DISABLED_MODE_NONE}, - * {@link Settings.Config#SYNC_DISABLED_MODE_PERSISTENT} and {@link - * Settings.Config#SYNC_DISABLED_MODE_UNTIL_REBOOT} - * - * @see #getSyncDisabledMode() - * @hide - */ - @SystemApi - @RequiresPermission(WRITE_DEVICE_CONFIG) - public static void setSyncDisabledMode(@SyncDisabledMode int syncDisabledMode) { - Settings.Config.setSyncDisabledMode(syncDisabledMode); - } - - /** - * Returns the current mode of sync disabling. - * - * @see #setSyncDisabledMode(int) - * @hide - */ - @SystemApi - @RequiresPermission(WRITE_DEVICE_CONFIG) - public static @SyncDisabledMode int getSyncDisabledMode() { - return Settings.Config.getSyncDisabledMode(); - } - - /** - * Add a listener for property changes. - * <p> - * This listener will be called whenever properties in the specified namespace change. Callbacks - * will be made on the specified executor. Future calls to this method with the same listener - * will replace the old namespace and executor. Remove the listener entirely by calling - * {@link #removeOnPropertiesChangedListener(OnPropertiesChangedListener)}. - * - * @param namespace The namespace containing properties to monitor. - * @param executor The executor which will be used to run callbacks. - * @param onPropertiesChangedListener The listener to add. - * @hide - * @see #removeOnPropertiesChangedListener(OnPropertiesChangedListener) - */ - @SystemApi - public static void addOnPropertiesChangedListener( - @NonNull String namespace, - @NonNull @CallbackExecutor Executor executor, - @NonNull OnPropertiesChangedListener onPropertiesChangedListener) { - synchronized (sLock) { - Pair<String, Executor> oldNamespace = sListeners.get(onPropertiesChangedListener); - if (oldNamespace == null) { - // Brand new listener, add it to the list. - sListeners.put(onPropertiesChangedListener, new Pair<>(namespace, executor)); - incrementNamespace(namespace); - } else if (namespace.equals(oldNamespace.first)) { - // Listener is already registered for this namespace, update executor just in case. - sListeners.put(onPropertiesChangedListener, new Pair<>(namespace, executor)); - } else { - // Update this listener from an old namespace to the new one. - decrementNamespace(sListeners.get(onPropertiesChangedListener).first); - sListeners.put(onPropertiesChangedListener, new Pair<>(namespace, executor)); - incrementNamespace(namespace); - } - } - } - - /** - * Remove a listener for property changes. The listener will receive no further notification of - * property changes. - * - * @param onPropertiesChangedListener The listener to remove. - * @hide - * @see #addOnPropertiesChangedListener(String, Executor, OnPropertiesChangedListener) - */ - @SystemApi - public static void removeOnPropertiesChangedListener( - @NonNull OnPropertiesChangedListener onPropertiesChangedListener) { - Preconditions.checkNotNull(onPropertiesChangedListener); - synchronized (sLock) { - if (sListeners.containsKey(onPropertiesChangedListener)) { - decrementNamespace(sListeners.get(onPropertiesChangedListener).first); - sListeners.remove(onPropertiesChangedListener); - } - } - } - - /** - * Increment the count used to represent the number of listeners subscribed to the given - * namespace. If this is the first (i.e. incrementing from 0 to 1) for the given namespace, a - * ContentObserver is registered. - * - * @param namespace The namespace to increment the count for. - */ - @GuardedBy("sLock") - private static void incrementNamespace(@NonNull String namespace) { - Preconditions.checkNotNull(namespace); - Pair<ContentObserver, Integer> namespaceCount = sNamespaces.get(namespace); - if (namespaceCount != null) { - sNamespaces.put(namespace, new Pair<>(namespaceCount.first, namespaceCount.second + 1)); - } else { - // This is a new namespace, register a ContentObserver for it. - ContentObserver contentObserver = new ContentObserver(null) { - @Override - public void onChange(boolean selfChange, Uri uri) { - if (uri != null) { - handleChange(uri); - } - } - }; - Settings.Config - .registerContentObserver(namespace, true, contentObserver); - sNamespaces.put(namespace, new Pair<>(contentObserver, 1)); - } - } - - /** - * Decrement the count used to represent the number of listeners subscribed to the given - * namespace. If this is the final decrement call (i.e. decrementing from 1 to 0) for the given - * namespace, the ContentObserver that had been tracking it will be removed. - * - * @param namespace The namespace to decrement the count for. - */ - @GuardedBy("sLock") - private static void decrementNamespace(@NonNull String namespace) { - Preconditions.checkNotNull(namespace); - Pair<ContentObserver, Integer> namespaceCount = sNamespaces.get(namespace); - if (namespaceCount == null) { - // This namespace is not registered and does not need to be decremented - return; - } else if (namespaceCount.second > 1) { - sNamespaces.put(namespace, new Pair<>(namespaceCount.first, namespaceCount.second - 1)); - } else { - // Decrementing a namespace to zero means we no longer need its ContentObserver. - Settings.Config.unregisterContentObserver(namespaceCount.first); - sNamespaces.remove(namespace); - } - } - - private static void handleChange(@NonNull Uri uri) { - Preconditions.checkNotNull(uri); - List<String> pathSegments = uri.getPathSegments(); - // pathSegments(0) is "config" - final String namespace = pathSegments.get(1); - Properties.Builder propBuilder = new Properties.Builder(namespace); - try { - Properties allProperties = getProperties(namespace); - for (int i = 2; i < pathSegments.size(); ++i) { - String key = pathSegments.get(i); - propBuilder.setString(key, allProperties.getString(key, null)); - } - } catch (SecurityException e) { - // Silently failing to not crash binder or listener threads. - Log.e(TAG, "OnPropertyChangedListener update failed: permission violation."); - return; - } - Properties properties = propBuilder.build(); - - synchronized (sLock) { - for (int i = 0; i < sListeners.size(); i++) { - if (namespace.equals(sListeners.valueAt(i).first)) { - final OnPropertiesChangedListener listener = sListeners.keyAt(i); - sListeners.valueAt(i).second.execute(() -> { - listener.onPropertiesChanged(properties); - }); - } - } - } - } - - /** - * Returns list of namespaces that can be read without READ_DEVICE_CONFIG_PERMISSION; - * @hide - */ - @SystemApi - public static @NonNull List<String> getPublicNamespaces() { - return PUBLIC_NAMESPACES; - } - - /** - * Interface for monitoring changes to properties. Implementations will receive callbacks when - * properties change, including a {@link Properties} object which contains a single namespace - * and all of the properties which changed for that namespace. This includes properties which - * were added, updated, or deleted. This is not necessarily a complete list of all properties - * belonging to the namespace, as properties which don't change are omitted. - * <p> - * Override {@link #onPropertiesChanged(Properties)} to handle callbacks for changes. - * - * @hide - */ - @SystemApi - public interface OnPropertiesChangedListener { - /** - * Called when one or more properties have changed, providing a Properties object with all - * of the changed properties. This object will contain only properties which have changed, - * not the complete set of all properties belonging to the namespace. - * - * @param properties Contains the complete collection of properties which have changed for a - * single namespace. This includes only those which were added, updated, - * or deleted. - */ - void onPropertiesChanged(@NonNull Properties properties); - } - - /** - * Thrown by {@link #setProperties(Properties)} when a configuration is rejected. This - * happens if RescueParty has identified a bad configuration and reset the namespace. - * - * @hide - */ - @SystemApi - public static class BadConfigException extends Exception {} - - /** - * A mapping of properties to values, as well as a single namespace which they all belong to. - * - * @hide - */ - @SystemApi - public static class Properties { - private final String mNamespace; - private final HashMap<String, String> mMap; - private Set<String> mKeyset; - - /** - * Create a mapping of properties to values and the namespace they belong to. - * - * @param namespace The namespace these properties belong to. - * @param keyValueMap A map between property names and property values. - * @hide - */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) - public Properties(@NonNull String namespace, @Nullable Map<String, String> keyValueMap) { - Preconditions.checkNotNull(namespace); - mNamespace = namespace; - mMap = new HashMap(); - if (keyValueMap != null) { - mMap.putAll(keyValueMap); - } - } - - /** - * @return the namespace all properties within this instance belong to. - */ - @NonNull - public String getNamespace() { - return mNamespace; - } - - /** - * @return the non-null set of property names. - */ - @NonNull - public Set<String> getKeyset() { - if (mKeyset == null) { - mKeyset = Collections.unmodifiableSet(mMap.keySet()); - } - return mKeyset; - } - - /** - * Look up the String value of a property. - * - * @param name The name of the property to look up. - * @param defaultValue The value to return if the property has not been defined. - * @return the corresponding value, or defaultValue if none exists. - */ - @Nullable - public String getString(@NonNull String name, @Nullable String defaultValue) { - Preconditions.checkNotNull(name); - String value = mMap.get(name); - return value != null ? value : defaultValue; - } - - /** - * Look up the boolean value of a property. - * - * @param name The name of the property to look up. - * @param defaultValue The value to return if the property has not been defined. - * @return the corresponding value, or defaultValue if none exists. - */ - public boolean getBoolean(@NonNull String name, boolean defaultValue) { - Preconditions.checkNotNull(name); - String value = mMap.get(name); - return value != null ? Boolean.parseBoolean(value) : defaultValue; - } - - /** - * Look up the int value of a property. - * - * @param name The name of the property to look up. - * @param defaultValue The value to return if the property has not been defined or fails to - * parse into an int. - * @return the corresponding value, or defaultValue if no valid int is available. - */ - public int getInt(@NonNull String name, int defaultValue) { - Preconditions.checkNotNull(name); - String value = mMap.get(name); - if (value == null) { - return defaultValue; - } - try { - return Integer.parseInt(value); - } catch (NumberFormatException e) { - Log.e(TAG, "Parsing int failed for " + name); - return defaultValue; - } - } - - /** - * Look up the long value of a property. - * - * @param name The name of the property to look up. - * @param defaultValue The value to return if the property has not been defined. or fails to - * parse into a long. - * @return the corresponding value, or defaultValue if no valid long is available. - */ - public long getLong(@NonNull String name, long defaultValue) { - Preconditions.checkNotNull(name); - String value = mMap.get(name); - if (value == null) { - return defaultValue; - } - try { - return Long.parseLong(value); - } catch (NumberFormatException e) { - Log.e(TAG, "Parsing long failed for " + name); - return defaultValue; - } - } - - /** - * Look up the int value of a property. - * - * @param name The name of the property to look up. - * @param defaultValue The value to return if the property has not been defined. or fails to - * parse into a float. - * @return the corresponding value, or defaultValue if no valid float is available. - */ - public float getFloat(@NonNull String name, float defaultValue) { - Preconditions.checkNotNull(name); - String value = mMap.get(name); - if (value == null) { - return defaultValue; - } - try { - return Float.parseFloat(value); - } catch (NumberFormatException e) { - Log.e(TAG, "Parsing float failed for " + name); - return defaultValue; - } - } - - /** - * Builder class for the construction of {@link Properties} objects. - */ - public static final class Builder { - @NonNull - private final String mNamespace; - @NonNull - private final Map<String, String> mKeyValues = new HashMap<>(); - - /** - * Create a new Builders for the specified namespace. - * @param namespace non null namespace. - */ - public Builder(@NonNull String namespace) { - mNamespace = namespace; - } - - /** - * Add a new property with the specified key and value. - * @param name non null name of the property. - * @param value nullable string value of the property. - * @return this Builder object - */ - @NonNull - public Builder setString(@NonNull String name, @Nullable String value) { - mKeyValues.put(name, value); - return this; - } - - /** - * Add a new property with the specified key and value. - * @param name non null name of the property. - * @param value nullable string value of the property. - * @return this Builder object - */ - @NonNull - public Builder setBoolean(@NonNull String name, boolean value) { - mKeyValues.put(name, Boolean.toString(value)); - return this; - } - - /** - * Add a new property with the specified key and value. - * @param name non null name of the property. - * @param value int value of the property. - * @return this Builder object - */ - @NonNull - public Builder setInt(@NonNull String name, int value) { - mKeyValues.put(name, Integer.toString(value)); - return this; - } - - /** - * Add a new property with the specified key and value. - * @param name non null name of the property. - * @param value long value of the property. - * @return this Builder object - */ - @NonNull - public Builder setLong(@NonNull String name, long value) { - mKeyValues.put(name, Long.toString(value)); - return this; - } - - /** - * Add a new property with the specified key and value. - * @param name non null name of the property. - * @param value float value of the property. - * @return this Builder object - */ - @NonNull - public Builder setFloat(@NonNull String name, float value) { - mKeyValues.put(name, Float.toString(value)); - return this; - } - - /** - * Create a new {@link Properties} object. - * @return non null Properties. - */ - @NonNull - public Properties build() { - return new Properties(mNamespace, mKeyValues); - } - } - } - -} diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java index 03846dbcfb68..e90ba6e42c6d 100644 --- a/core/java/android/provider/Settings.java +++ b/core/java/android/provider/Settings.java @@ -4638,21 +4638,6 @@ public final class Settings { public static final String SCREEN_BRIGHTNESS = "screen_brightness"; /** - * The screen backlight brightness between 0 and 255. - * @hide - */ - @Readable - public static final String SCREEN_BRIGHTNESS_FOR_VR = "screen_brightness_for_vr"; - - /** - * The screen backlight brightness between 0.0f and 1.0f. - * @hide - */ - @Readable - public static final String SCREEN_BRIGHTNESS_FOR_VR_FLOAT = - "screen_brightness_for_vr_float"; - - /** * The screen backlight brightness between 0.0f and 1.0f. * @hide */ @@ -5637,8 +5622,6 @@ public final class Settings { PUBLIC_SETTINGS.add(SCREEN_OFF_TIMEOUT); PUBLIC_SETTINGS.add(SCREEN_BRIGHTNESS); PUBLIC_SETTINGS.add(SCREEN_BRIGHTNESS_FLOAT); - PUBLIC_SETTINGS.add(SCREEN_BRIGHTNESS_FOR_VR); - PUBLIC_SETTINGS.add(SCREEN_BRIGHTNESS_FOR_VR_FLOAT); PUBLIC_SETTINGS.add(SCREEN_BRIGHTNESS_MODE); PUBLIC_SETTINGS.add(MODE_RINGER_STREAMS_AFFECTED); PUBLIC_SETTINGS.add(MUTE_STREAMS_AFFECTED); @@ -9370,6 +9353,14 @@ public final class Settings { public static final int DOCK_SETUP_PAUSED = 2; /** + * Indicates that the user has been prompted to start dock setup. + * One of the possible states for {@link #DOCK_SETUP_STATE}. + * + * @hide + */ + public static final int DOCK_SETUP_PROMPTED = 3; + + /** * Indicates that the user has completed dock setup. * One of the possible states for {@link #DOCK_SETUP_STATE}. * @@ -9383,6 +9374,7 @@ public final class Settings { DOCK_SETUP_NOT_STARTED, DOCK_SETUP_STARTED, DOCK_SETUP_PAUSED, + DOCK_SETUP_PROMPTED, DOCK_SETUP_COMPLETED }) public @interface DockSetupState { diff --git a/core/java/android/security/rkp/IGetKeyCallback.aidl b/core/java/android/security/rkp/IGetKeyCallback.aidl new file mode 100644 index 000000000000..85ceae62aadc --- /dev/null +++ b/core/java/android/security/rkp/IGetKeyCallback.aidl @@ -0,0 +1,49 @@ +/* + * 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.security.rkp; + +import android.security.rkp.RemotelyProvisionedKey; + +/** + * Callback interface for receiving remotely provisioned keys from a + * {@link IRegistration}. + * + * @hide + */ +oneway interface IGetKeyCallback { + /** + * Called in response to {@link IRegistration.getKey}, indicating + * a remotely-provisioned key is available. + * + * @param key The key that was received from the remote provisioning service. + */ + void onSuccess(in RemotelyProvisionedKey key); + + /** + * Called when the key request has been successfully cancelled. + * @see IRegistration.cancelGetKey + */ + void onCancel(); + + /** + * Called when an error has occurred while trying to get a remotely provisioned key. + * + * @param error A description of what failed, suitable for logging. + */ + void onError(String error); +} + diff --git a/core/java/android/security/rkp/IGetRegistrationCallback.aidl b/core/java/android/security/rkp/IGetRegistrationCallback.aidl new file mode 100644 index 000000000000..e375a6f97b31 --- /dev/null +++ b/core/java/android/security/rkp/IGetRegistrationCallback.aidl @@ -0,0 +1,49 @@ +/* + * 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.security.rkp; + +import android.security.rkp.IRegistration; + +/** + * Callback interface for receiving a remote provisioning registration. + * {@link IRegistration}. + * + * @hide + */ +oneway interface IGetRegistrationCallback { + /** + * Called in response to {@link IRemoteProvisioning.getRegistration}. + * + * @param registration an IRegistration that is used to fetch remotely + * provisioned keys for the given IRemotelyProvisionedComponent. + */ + void onSuccess(in IRegistration registration); + + /** + * Called when the get registration request has been successfully cancelled. + * @see IRemoteProvisioning.cancelGetRegistration + */ + void onCancel(); + + /** + * Called when an error has occurred while trying to get a registration. + * + * @param error A description of what failed, suitable for logging. + */ + void onError(String error); +} + diff --git a/core/java/android/security/rkp/IRegistration.aidl b/core/java/android/security/rkp/IRegistration.aidl new file mode 100644 index 000000000000..6522a458de4e --- /dev/null +++ b/core/java/android/security/rkp/IRegistration.aidl @@ -0,0 +1,85 @@ +/* + * 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.security.rkp; + +import android.security.rkp.IGetKeyCallback; + +/** + * This interface is associated with the registration of an + * IRemotelyProvisionedComponent. Each component has a unique set of keys + * and certificates that are provisioned to the device for attestation. An + * IRegistration binder is created by calling + * {@link IRemoteProvisioning#getRegistration()}. + * + * This interface is used to query for available keys and certificates for the + * registered component. + * + * @hide + */ +oneway interface IRegistration { + /** + * Fetch a remotely provisioned key for the given keyId. Keys are unique + * per caller/keyId/registration tuple. This ensures that no two + * applications are able to correlate keys to uniquely identify a + * device/user. Callers receive their key via {@code callback}. + * + * If a key is available, this call immediately invokes {@code callback}. + * + * If no keys are immediately available, then this function contacts the + * remote provisioning server to provision a key. After provisioning is + * completed, the key is passed to {@code callback}. + * + * @param keyId This is a client-chosen key identifier, used to + * differentiate between keys for varying client-specific use-cases. For + * example, keystore2 passes the UID of the applications that call it as + * the keyId value here, so that each of keystore2's clients gets a unique + * key. + * @param callback Receives the result of the call. A callback must only + * be used with one {@code getKey} call at a time. + */ + void getKey(int keyId, IGetKeyCallback callback); + + /** + * Cancel an active request for a remotely provisioned key, as initiated via + * {@link getKey}. Upon cancellation, {@code callback.onCancel} will be invoked. + */ + void cancelGetKey(IGetKeyCallback callback); + + /** + * Replace an obsolete key blob with an upgraded key blob. + * In certain cases, such as security patch level upgrade, keys become "old". + * In these cases, the component which supports operations with the remotely + * provisioned key blobs must support upgrading the blobs to make them "new" + * and usable on the updated system. + * + * For an example of a remotely provisioned component that has an upgrade + * mechanism, see the documentation for IKeyMintDevice.upgradeKey. + * + * Once a key has been upgraded, the IRegistration where the key is stored + * needs to be told about the new blob. After calling storeUpgradedKey, + * getKey will return the new key blob instead of the old one. + * + * Note that this function does NOT extend the lifetime of key blobs. The + * certificate for the key is unchanged, and the key will still expire at + * the same time it would have if storeUpgradedKey had never been called. + * + * @param oldKeyBlob The old key blob to be replaced by {@code newKeyBlob}. + * + * @param newKeyblob The new blob to replace {@code oldKeyBlob}. + */ + void storeUpgradedKey(in byte[] oldKeyBlob, in byte[] newKeyBlob); +} diff --git a/core/java/android/security/rkp/IRemoteProvisioning.aidl b/core/java/android/security/rkp/IRemoteProvisioning.aidl new file mode 100644 index 000000000000..23d8159f7b28 --- /dev/null +++ b/core/java/android/security/rkp/IRemoteProvisioning.aidl @@ -0,0 +1,68 @@ +/* + * 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.security.rkp; + +import android.security.rkp.IRegistration; +import android.security.rkp.IGetRegistrationCallback; + +/** + * {@link IRemoteProvisioning} is the interface provided to use the remote key + * provisioning functionality from the Remote Key Provisioning Daemon (RKPD). + * This would be the first service that RKPD clients would interact with. The + * intent is for the clients to get the {@link IRegistration} object from this + * interface and use it for actual remote provisioning work. + * + * @hide + */ +oneway interface IRemoteProvisioning { + /** + * Takes a remotely provisioned component service name and gets a + * registration bound to that service and the caller's UID. + * + * @param irpcName The name of the {@code IRemotelyProvisionedComponent} + * for which remotely provisioned keys should be managed. + * @param callback Receives the result of the call. A callback must only + * be used with one {@code getRegistration} call at a time. + * + * Notes: + * - This function will attempt to get the service named by irpcName. This + * implies that a lazy/dynamic aidl service will be instantiated, and this + * function blocks until the service is up. Upon return, any binder tokens + * are dropped, allowing the lazy/dynamic service to shutdown. + * - The created registration object is unique per caller. If two different + * UIDs call getRegistration with the same irpcName, they will receive + * different registrations. This prevents two different applications from + * being able to see the same keys. + * - This function is idempotent per calling UID. Additional calls to + * getRegistration with the same parameters, from the same caller, will have + * no side effects. + * - A callback may only be associated with one getRegistration call at a time. + * If the callback is used multiple times, this API will return an error. + * + * @see IRegistration#getKey() + * @see IRemotelyProvisionedComponent + * + */ + void getRegistration(String irpcName, IGetRegistrationCallback callback); + + /** + * Cancel any active {@link getRegistration} call associated with the given + * callback. If no getRegistration call is currently active, this function is + * a noop. + */ + void cancelGetRegistration(IGetRegistrationCallback callback); +} diff --git a/core/java/android/security/rkp/OWNERS b/core/java/android/security/rkp/OWNERS new file mode 100644 index 000000000000..fd430899fc5f --- /dev/null +++ b/core/java/android/security/rkp/OWNERS @@ -0,0 +1,5 @@ +# Bug component: 1084908 + +jbires@google.com +sethmo@google.com +vikramgaur@google.com diff --git a/core/java/android/security/rkp/RemotelyProvisionedKey.aidl b/core/java/android/security/rkp/RemotelyProvisionedKey.aidl new file mode 100644 index 000000000000..207f18f2f947 --- /dev/null +++ b/core/java/android/security/rkp/RemotelyProvisionedKey.aidl @@ -0,0 +1,44 @@ +/* + * 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. + */ + +package android.security.rkp; + +/** + * A {@link RemotelyProvisionedKey} holds an attestation key and the + * corresponding remotely provisioned certificate chain. + * + * @hide + */ +@RustDerive(Eq=true, PartialEq=true) +parcelable RemotelyProvisionedKey { + /** + * The remotely-provisioned key that may be used to sign attestations. The + * format of this key is opaque, and need only be understood by the + * IRemotelyProvisionedComponent that generated it. + * + * Any private key material contained within this blob must be encrypted. + * + * @see IRemotelyProvisionedComponent + */ + byte[] keyBlob; + + /** + * Sequence of DER-encoded X.509 certificates that make up the attestation + * key's certificate chain. This is the binary encoding for a chain that is + * supported by Java's CertificateFactory.generateCertificates API. + */ + byte[] encodedCertChain; +} diff --git a/core/java/android/service/credentials/Action.java b/core/java/android/service/credentials/Action.java index 77570813e6c3..42dd52840575 100644 --- a/core/java/android/service/credentials/Action.java +++ b/core/java/android/service/credentials/Action.java @@ -42,7 +42,7 @@ public final class Action implements Parcelable { * level authentication before displaying any content etc. * * <p> See details on usage of {@code Action} for various actionable entries in - * {@link BeginCreateCredentialResponse} and {@link GetCredentialsResponse}. + * {@link BeginCreateCredentialResponse} and {@link BeginGetCredentialsResponse}. * * @param slice the display content to be displayed on the UI, along with this action * @param pendingIntent the intent to be invoked when the user selects this action diff --git a/core/java/android/service/credentials/BeginCreateCredentialResponse.java b/core/java/android/service/credentials/BeginCreateCredentialResponse.java index 022678ea49bd..8ca3a1a2ec99 100644 --- a/core/java/android/service/credentials/BeginCreateCredentialResponse.java +++ b/core/java/android/service/credentials/BeginCreateCredentialResponse.java @@ -127,7 +127,7 @@ public final class BeginCreateCredentialResponse implements Parcelable { * * <p> Once the remote credential flow is complete, the {@link android.app.Activity} * result should be set to {@link android.app.Activity#RESULT_OK} and an extra with the - * {@link CredentialProviderService#EXTRA_CREATE_CREDENTIAL_RESULT} key should be populated + * {@link CredentialProviderService#EXTRA_CREATE_CREDENTIAL_RESPONSE} key should be populated * with a {@link android.credentials.CreateCredentialResponse} object. */ public @NonNull Builder setRemoteCreateEntry(@Nullable CreateEntry remoteCreateEntry) { diff --git a/core/java/android/service/credentials/BeginGetCredentialOption.java b/core/java/android/service/credentials/BeginGetCredentialOption.java new file mode 100644 index 000000000000..c82b445d19e0 --- /dev/null +++ b/core/java/android/service/credentials/BeginGetCredentialOption.java @@ -0,0 +1,129 @@ +/* + * 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. + */ + +package android.service.credentials; + +import static java.util.Objects.requireNonNull; + +import android.annotation.NonNull; +import android.os.Bundle; +import android.os.Parcel; +import android.os.Parcelable; + +import com.android.internal.util.AnnotationValidations; +import com.android.internal.util.Preconditions; + +/** + * A specific type of credential request to be sent to the provider during the query phase of + * a get flow. This request contains limited parameters needed to populate a list of + * {@link CredentialEntry} on the {@link BeginGetCredentialsResponse}. + */ +public final class BeginGetCredentialOption implements Parcelable { + + /** + * The requested credential type. + */ + @NonNull + private final String mType; + + /** + * The request candidateQueryData. + */ + @NonNull + private final Bundle mCandidateQueryData; + + /** + * Returns the requested credential type. + */ + @NonNull + public String getType() { + return mType; + } + + /** + * Returns the request candidate query data, denoting a set of parameters + * that can be used to populate a candidate list of credentials, as + * {@link CredentialEntry} on {@link BeginGetCredentialsResponse}. This list + * of entries is then presented to the user on a selector. + * + * <p>This data does not contain any sensitive parameters, and will be sent + * to all eligible providers. + * The complete set of parameters will only be set on the {@link android.app.PendingIntent} + * set on the {@link CredentialEntry} that is selected by the user. + */ + @NonNull + public Bundle getCandidateQueryData() { + return mCandidateQueryData; + } + + @Override + public void writeToParcel(@NonNull Parcel dest, int flags) { + dest.writeString8(mType); + dest.writeBundle(mCandidateQueryData); + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public String toString() { + return "GetCredentialOption {" + + "type=" + mType + + ", candidateQueryData=" + mCandidateQueryData + + "}"; + } + + /** + * Constructs a {@link BeginGetCredentialOption}. + * + * @param type the requested credential type + * @param candidateQueryData the request candidateQueryData + * + * @throws IllegalArgumentException If type is empty. + */ + public BeginGetCredentialOption( + @NonNull String type, + @NonNull Bundle candidateQueryData) { + mType = Preconditions.checkStringNotEmpty(type, "type must not be empty"); + mCandidateQueryData = requireNonNull( + candidateQueryData, "candidateQueryData must not be null"); + } + + private BeginGetCredentialOption(@NonNull Parcel in) { + String type = in.readString8(); + Bundle candidateQueryData = in.readBundle(); + + mType = type; + AnnotationValidations.validate(NonNull.class, null, mType); + mCandidateQueryData = candidateQueryData; + AnnotationValidations.validate(NonNull.class, null, mCandidateQueryData); + } + + public static final @NonNull Creator<BeginGetCredentialOption> CREATOR = + new Creator<BeginGetCredentialOption>() { + @Override + public BeginGetCredentialOption[] newArray(int size) { + return new BeginGetCredentialOption[size]; + } + + @Override + public BeginGetCredentialOption createFromParcel(@NonNull Parcel in) { + return new BeginGetCredentialOption(in); + } + }; +} diff --git a/core/java/android/service/credentials/GetCredentialsResponse.aidl b/core/java/android/service/credentials/BeginGetCredentialsRequest.aidl index 0d8c6357a715..5e1fe8abc2aa 100644 --- a/core/java/android/service/credentials/GetCredentialsResponse.aidl +++ b/core/java/android/service/credentials/BeginGetCredentialsRequest.aidl @@ -1,3 +1,3 @@ package android.service.credentials; -parcelable GetCredentialsResponse;
\ No newline at end of file +parcelable BeginGetCredentialsRequest;
\ No newline at end of file diff --git a/core/java/android/service/credentials/BeginGetCredentialsRequest.java b/core/java/android/service/credentials/BeginGetCredentialsRequest.java new file mode 100644 index 000000000000..795840b42f2a --- /dev/null +++ b/core/java/android/service/credentials/BeginGetCredentialsRequest.java @@ -0,0 +1,175 @@ +/* + * 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.service.credentials; + +import android.annotation.NonNull; +import android.app.PendingIntent; +import android.content.Intent; +import android.credentials.GetCredentialOption; +import android.os.Parcel; +import android.os.Parcelable; + +import com.android.internal.util.AnnotationValidations; +import com.android.internal.util.Preconditions; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * Query stage request for getting user's credentials from a given credential provider. + * + * <p>This request contains a list of {@link GetCredentialOption} that have parameters + * to be used to query credentials, and return a list of {@link CredentialEntry} to be set + * on the {@link BeginGetCredentialsResponse}. This list is then shown to the user on a selector. + * + * If a {@link PendingIntent} is set on a {@link CredentialEntry}, and the user selects that + * entry, a {@link GetCredentialRequest} with all parameters needed to get the actual + * {@link android.credentials.Credential} will be sent as part of the {@link Intent} fired + * through the {@link PendingIntent}. + */ +public final class BeginGetCredentialsRequest implements Parcelable { + /** Calling package of the app requesting for credentials. */ + @NonNull private final String mCallingPackage; + + /** + * List of credential options. Each {@link BeginGetCredentialOption} object holds parameters to + * be used for populating a list of {@link CredentialEntry} for a specific type of credential. + * + * This request does not reveal sensitive parameters. Complete list of parameters + * is retrieved through the {@link PendingIntent} set on each {@link CredentialEntry} + * on {@link CredentialsResponseContent} set on {@link BeginGetCredentialsResponse}, + * when the user selects one of these entries. + */ + @NonNull private final List<BeginGetCredentialOption> mBeginGetCredentialOptions; + + private BeginGetCredentialsRequest(@NonNull String callingPackage, + @NonNull List<BeginGetCredentialOption> getBeginCredentialOptions) { + this.mCallingPackage = callingPackage; + this.mBeginGetCredentialOptions = getBeginCredentialOptions; + } + + private BeginGetCredentialsRequest(@NonNull Parcel in) { + mCallingPackage = in.readString8(); + List<BeginGetCredentialOption> getBeginCredentialOptions = new ArrayList<>(); + in.readTypedList(getBeginCredentialOptions, BeginGetCredentialOption.CREATOR); + mBeginGetCredentialOptions = getBeginCredentialOptions; + AnnotationValidations.validate(NonNull.class, null, mBeginGetCredentialOptions); + } + + public static final @NonNull Creator<BeginGetCredentialsRequest> CREATOR = + new Creator<BeginGetCredentialsRequest>() { + @Override + public BeginGetCredentialsRequest createFromParcel(Parcel in) { + return new BeginGetCredentialsRequest(in); + } + + @Override + public BeginGetCredentialsRequest[] newArray(int size) { + return new BeginGetCredentialsRequest[size]; + } + }; + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(@NonNull Parcel dest, int flags) { + dest.writeString8(mCallingPackage); + dest.writeTypedList(mBeginGetCredentialOptions); + } + + /** + * Returns the calling package of the app requesting credentials. + */ + public @NonNull String getCallingPackage() { + return mCallingPackage; + } + + /** + * Returns the list of type specific credential options to list credentials for in + * {@link BeginGetCredentialsResponse}. + */ + public @NonNull List<BeginGetCredentialOption> getBeginGetCredentialOptions() { + return mBeginGetCredentialOptions; + } + + /** + * Builder for {@link BeginGetCredentialsRequest}. + */ + public static final class Builder { + private String mCallingPackage; + private List<BeginGetCredentialOption> mBeginGetCredentialOptions = new ArrayList<>(); + + /** + * Creates a new builder. + * @param callingPackage the calling package of the app requesting credentials + * + * @throws IllegalArgumentException If {@code callingPackage} is null or empty. + */ + public Builder(@NonNull String callingPackage) { + mCallingPackage = Preconditions.checkStringNotEmpty(callingPackage); + } + + /** + * Sets the list of credential options. + * + * @throws NullPointerException If {@code getBeginCredentialOptions} itself or any of its + * elements is null. + * @throws IllegalArgumentException If {@code getBeginCredentialOptions} is empty. + */ + public @NonNull Builder setBeginGetCredentialOptions( + @NonNull List<BeginGetCredentialOption> getBeginCredentialOptions) { + Preconditions.checkCollectionNotEmpty(getBeginCredentialOptions, + "getBeginCredentialOptions"); + Preconditions.checkCollectionElementsNotNull(getBeginCredentialOptions, + "getBeginCredentialOptions"); + mBeginGetCredentialOptions = getBeginCredentialOptions; + return this; + } + + /** + * Adds a single {@link BeginGetCredentialOption} object to the list of credential options. + * + * @throws NullPointerException If {@code beginGetCredentialOption} is null. + */ + public @NonNull Builder addBeginGetCredentialOption( + @NonNull BeginGetCredentialOption beginGetCredentialOption) { + Objects.requireNonNull(beginGetCredentialOption, + "beginGetCredentialOption must not be null"); + mBeginGetCredentialOptions.add(beginGetCredentialOption); + return this; + } + + /** + * Builds a new {@link BeginGetCredentialsRequest} instance. + * + * @throws NullPointerException If {@code beginGetCredentialOptions} is null. + * @throws IllegalArgumentException If {@code beginGetCredentialOptions} is empty, or if + * {@code callingPackage} is null or empty. + */ + public @NonNull BeginGetCredentialsRequest build() { + Preconditions.checkStringNotEmpty(mCallingPackage, + "Must set the calling package"); + Preconditions.checkCollectionNotEmpty(mBeginGetCredentialOptions, + "beginGetCredentialOptions"); + return new BeginGetCredentialsRequest(mCallingPackage, mBeginGetCredentialOptions); + } + } +} diff --git a/core/java/android/service/credentials/BeginGetCredentialsResponse.aidl b/core/java/android/service/credentials/BeginGetCredentialsResponse.aidl new file mode 100644 index 000000000000..ca69bcaa866b --- /dev/null +++ b/core/java/android/service/credentials/BeginGetCredentialsResponse.aidl @@ -0,0 +1,3 @@ +package android.service.credentials; + +parcelable BeginGetCredentialsResponse;
\ No newline at end of file diff --git a/core/java/android/service/credentials/GetCredentialsResponse.java b/core/java/android/service/credentials/BeginGetCredentialsResponse.java index 5263141f982a..2cda56067ba8 100644 --- a/core/java/android/service/credentials/GetCredentialsResponse.java +++ b/core/java/android/service/credentials/BeginGetCredentialsResponse.java @@ -27,7 +27,7 @@ import java.util.Objects; * Response from a credential provider, containing credential entries and other associated * data to be shown on the account selector UI. */ -public final class GetCredentialsResponse implements Parcelable { +public final class BeginGetCredentialsResponse implements Parcelable { /** Content to be used for the UI. */ private final @Nullable CredentialsResponseContent mCredentialsResponseContent; @@ -38,14 +38,15 @@ public final class GetCredentialsResponse implements Parcelable { private final @Nullable Action mAuthenticationAction; /** - * Creates a {@link GetCredentialsResponse} instance with an authentication {@link Action} set. - * Providers must use this method when no content can be shown before authentication. + * Creates a {@link BeginGetCredentialsResponse} instance with an authentication + * {@link Action} set. Providers must use this method when no content can be shown + * before authentication. * * <p> When the user selects this {@code authenticationAction}, the system invokes the * corresponding {@code pendingIntent}. Once the authentication flow is complete, * the {@link android.app.Activity} result should be set * to {@link android.app.Activity#RESULT_OK} and the - * {@link CredentialProviderService#EXTRA_GET_CREDENTIALS_CONTENT_RESULT} extra should be set + * {@link CredentialProviderService#EXTRA_CREDENTIALS_RESPONSE_CONTENT} extra should be set * with a fully populated {@link CredentialsResponseContent} object. * the authentication action activity is launched, and the user is authenticated, providers * should create another response with {@link CredentialsResponseContent} using @@ -54,48 +55,49 @@ public final class GetCredentialsResponse implements Parcelable { * * @throws NullPointerException If {@code authenticationAction} is null. */ - public static @NonNull GetCredentialsResponse createWithAuthentication( + public static @NonNull BeginGetCredentialsResponse createWithAuthentication( @NonNull Action authenticationAction) { Objects.requireNonNull(authenticationAction, "authenticationAction must not be null"); - return new GetCredentialsResponse(null, authenticationAction); + return new BeginGetCredentialsResponse(null, authenticationAction); } /** - * Creates a {@link GetCredentialsRequest} instance with content to be shown on the UI. + * Creates a {@link BeginGetCredentialsRequest} instance with content to be shown on the UI. * Providers must use this method when there is content to be shown without top level * authentication required, including credential entries, action entries or a remote entry, * * @throws NullPointerException If {@code credentialsResponseContent} is null. */ - public static @NonNull GetCredentialsResponse createWithResponseContent( + public static @NonNull BeginGetCredentialsResponse createWithResponseContent( @NonNull CredentialsResponseContent credentialsResponseContent) { Objects.requireNonNull(credentialsResponseContent, "credentialsResponseContent must not be null"); - return new GetCredentialsResponse(credentialsResponseContent, null); + return new BeginGetCredentialsResponse(credentialsResponseContent, null); } - private GetCredentialsResponse(@Nullable CredentialsResponseContent credentialsResponseContent, + private BeginGetCredentialsResponse(@Nullable CredentialsResponseContent + credentialsResponseContent, @Nullable Action authenticationAction) { mCredentialsResponseContent = credentialsResponseContent; mAuthenticationAction = authenticationAction; } - private GetCredentialsResponse(@NonNull Parcel in) { + private BeginGetCredentialsResponse(@NonNull Parcel in) { mCredentialsResponseContent = in.readTypedObject(CredentialsResponseContent.CREATOR); mAuthenticationAction = in.readTypedObject(Action.CREATOR); } - public static final @NonNull Creator<GetCredentialsResponse> CREATOR = - new Creator<GetCredentialsResponse>() { + public static final @NonNull Creator<BeginGetCredentialsResponse> CREATOR = + new Creator<BeginGetCredentialsResponse>() { @Override - public GetCredentialsResponse createFromParcel(Parcel in) { - return new GetCredentialsResponse(in); + public BeginGetCredentialsResponse createFromParcel(Parcel in) { + return new BeginGetCredentialsResponse(in); } @Override - public GetCredentialsResponse[] newArray(int size) { - return new GetCredentialsResponse[size]; + public BeginGetCredentialsResponse[] newArray(int size) { + return new BeginGetCredentialsResponse[size]; } }; diff --git a/core/java/android/service/credentials/CredentialEntry.java b/core/java/android/service/credentials/CredentialEntry.java index 941db02be8d1..3c399d26c2fb 100644 --- a/core/java/android/service/credentials/CredentialEntry.java +++ b/core/java/android/service/credentials/CredentialEntry.java @@ -17,10 +17,9 @@ package android.service.credentials; import android.annotation.NonNull; -import android.annotation.Nullable; import android.app.PendingIntent; import android.app.slice.Slice; -import android.credentials.Credential; +import android.credentials.GetCredentialResponse; import android.os.Parcel; import android.os.Parcelable; @@ -41,32 +40,23 @@ public final class CredentialEntry implements Parcelable { private final @NonNull Slice mSlice; /** The pending intent to be invoked when this credential entry is selected. */ - private final @Nullable PendingIntent mPendingIntent; - - /** - * The underlying credential to be returned to the app when the user selects - * this credential entry. - */ - private final @Nullable Credential mCredential; + private final @NonNull PendingIntent mPendingIntent; /** A flag denoting whether auto-select is enabled for this entry. */ private final @NonNull boolean mAutoSelectAllowed; private CredentialEntry(@NonNull String type, @NonNull Slice slice, - @Nullable PendingIntent pendingIntent, @Nullable Credential credential, - @NonNull boolean autoSeletAllowed) { + @NonNull PendingIntent pendingIntent, @NonNull boolean autoSelectAllowed) { mType = type; mSlice = slice; mPendingIntent = pendingIntent; - mCredential = credential; - mAutoSelectAllowed = autoSeletAllowed; + mAutoSelectAllowed = autoSelectAllowed; } private CredentialEntry(@NonNull Parcel in) { mType = in.readString8(); mSlice = in.readTypedObject(Slice.CREATOR); mPendingIntent = in.readTypedObject(PendingIntent.CREATOR); - mCredential = in.readTypedObject(Credential.CREATOR); mAutoSelectAllowed = in.readBoolean(); } @@ -93,7 +83,6 @@ public final class CredentialEntry implements Parcelable { dest.writeString8(mType); dest.writeTypedObject(mSlice, flags); dest.writeTypedObject(mPendingIntent, flags); - dest.writeTypedObject(mCredential, flags); dest.writeBoolean(mAutoSelectAllowed); } @@ -114,18 +103,11 @@ public final class CredentialEntry implements Parcelable { /** * Returns the pending intent to be invoked if the user selects this entry. */ - public @Nullable PendingIntent getPendingIntent() { + public @NonNull PendingIntent getPendingIntent() { return mPendingIntent; } /** - * Returns the credential associated with this entry. - */ - public @Nullable Credential getCredential() { - return mCredential; - } - - /** * Returns whether this entry can be auto selected if it is the only option for the user. */ public boolean isAutoSelectAllowed() { @@ -138,8 +120,7 @@ public final class CredentialEntry implements Parcelable { public static final class Builder { private String mType; private Slice mSlice; - private PendingIntent mPendingIntent = null; - private Credential mCredential = null; + private PendingIntent mPendingIntent; private boolean mAutoSelectAllowed = false; /** @@ -152,8 +133,8 @@ public final class CredentialEntry implements Parcelable { * Once the activity fulfills the required user engagement, the * {@link android.app.Activity} result should be set to * {@link android.app.Activity#RESULT_OK}, and the - * {@link CredentialProviderService#EXTRA_CREDENTIAL_RESULT} must be set with a - * {@link Credential} object. + * {@link CredentialProviderService#EXTRA_GET_CREDENTIAL_RESPONSE} must be set with a + * {@link GetCredentialResponse} object. * * @param type the type of credential underlying this credential entry * @param slice the content to be displayed with this entry on the UI @@ -179,26 +160,6 @@ public final class CredentialEntry implements Parcelable { } /** - * Creates a builder for a {@link CredentialEntry} that contains a {@link Credential}, - * and does not require further action. - * @param type the type of credential underlying this credential entry - * @param slice the content to be displayed with this entry on the UI - * @param credential the credential to be returned to the client app, when this entry is - * selected by the user - * - * @throws IllegalArgumentException If {@code type} is null or empty. - * @throws NullPointerException If {@code slice}, or {@code credential} is null. - */ - public Builder(@NonNull String type, @NonNull Slice slice, @NonNull Credential credential) { - mType = Preconditions.checkStringNotEmpty(type, "type must not be " - + "null, or empty"); - mSlice = Objects.requireNonNull(slice, - "slice must not be null"); - mCredential = Objects.requireNonNull(credential, - "credential must not be null"); - } - - /** * Sets whether the entry is allowed to be auto selected by the framework. * The default value is set to false. * @@ -219,12 +180,9 @@ public final class CredentialEntry implements Parcelable { * is set, or if both are set. */ public @NonNull CredentialEntry build() { - Preconditions.checkState(((mPendingIntent != null && mCredential == null) - || (mPendingIntent == null && mCredential != null)), - "Either pendingIntent or credential must be set, and both cannot" - + "be set at the same time"); - return new CredentialEntry(mType, mSlice, mPendingIntent, - mCredential, mAutoSelectAllowed); + Preconditions.checkState(mPendingIntent != null, + "pendingIntent must not be null"); + return new CredentialEntry(mType, mSlice, mPendingIntent, mAutoSelectAllowed); } } } diff --git a/core/java/android/service/credentials/CredentialProviderService.java b/core/java/android/service/credentials/CredentialProviderService.java index 32646e6fd289..416ddf172616 100644 --- a/core/java/android/service/credentials/CredentialProviderService.java +++ b/core/java/android/service/credentials/CredentialProviderService.java @@ -21,6 +21,7 @@ import static com.android.internal.util.function.pooled.PooledLambda.obtainMessa import android.annotation.CallSuper; import android.annotation.NonNull; import android.annotation.SdkConstant; +import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.CancellationSignal; @@ -45,12 +46,23 @@ public abstract class CredentialProviderService extends Service { * returned as part of the {@link BeginCreateCredentialResponse} * * <p> - * Type: {@link android.credentials.CreateCredentialRequest} + * Type: {@link android.service.credentials.CreateCredentialRequest} */ public static final String EXTRA_CREATE_CREDENTIAL_REQUEST = "android.service.credentials.extra.CREATE_CREDENTIAL_REQUEST"; /** + * Intent extra: The {@link GetCredentialRequest} attached with + * the {@code pendingIntent} that is invoked when the user selects a {@link CredentialEntry} + * returned as part of the {@link BeginGetCredentialsResponse} + * + * <p> + * Type: {@link GetCredentialRequest} + */ + public static final String EXTRA_GET_CREDENTIAL_REQUEST = + "android.service.credentials.extra.GET_CREDENTIAL_REQUEST"; + + /** * Intent extra: The result of a create flow operation, to be set on finish of the * {@link android.app.Activity} invoked through the {@code pendingIntent} set on * a {@link CreateEntry}. @@ -58,8 +70,8 @@ public abstract class CredentialProviderService extends Service { * <p> * Type: {@link android.credentials.CreateCredentialResponse} */ - public static final String EXTRA_CREATE_CREDENTIAL_RESULT = - "android.service.credentials.extra.CREATE_CREDENTIAL_RESULT"; + public static final String EXTRA_CREATE_CREDENTIAL_RESPONSE = + "android.service.credentials.extra.CREATE_CREDENTIAL_RESPONSE"; /** * Intent extra: The result of a get credential flow operation, to be set on finish of the @@ -67,33 +79,48 @@ public abstract class CredentialProviderService extends Service { * a {@link CredentialEntry}. * * <p> - * Type: {@link android.credentials.Credential} + * Type: {@link android.credentials.GetCredentialResponse} */ - public static final String EXTRA_CREDENTIAL_RESULT = - "android.service.credentials.extra.CREDENTIAL_RESULT"; + public static final String EXTRA_GET_CREDENTIAL_RESPONSE = + "android.service.credentials.extra.GET_CREDENTIAL_RESPONSE"; /** * Intent extra: The result of an authentication flow, to be set on finish of the * {@link android.app.Activity} invoked through the {@link android.app.PendingIntent} set on - * a {@link GetCredentialsResponse}. This result should contain the actual content, including - * credential entries and action entries, to be shown on the selector. + * a {@link BeginGetCredentialsResponse}. This result should contain the actual content, + * including credential entries and action entries, to be shown on the selector. * * <p> * Type: {@link CredentialsResponseContent} */ - public static final String EXTRA_GET_CREDENTIALS_CONTENT_RESULT = - "android.service.credentials.extra.GET_CREDENTIALS_CONTENT_RESULT"; + public static final String EXTRA_CREDENTIALS_RESPONSE_CONTENT = + "android.service.credentials.extra.CREDENTIALS_RESPONSE_CONTENT"; /** - * Intent extra: The error result of any {@link android.app.PendingIntent} flow, to be set - * on finish of the corresponding {@link android.app.Activity}. This result should contain an - * error code, representing the error encountered by the provider. + * Intent extra: The failure exception set at the final stage of a get flow. + * This exception is set at the finishing result of the {@link android.app.Activity} + * invoked by the {@link PendingIntent} , when a user selects the {@link CredentialEntry} + * that contained the {@link PendingIntent} in question. + * + * <p>The result must be set through {@link android.app.Activity#setResult} as an intent extra * * <p> - * Type: {@link String} + * Type: {@link android.credentials.GetCredentialException} */ - public static final String EXTRA_ERROR = - "android.service.credentials.extra.ERROR"; + public static final String EXTRA_GET_CREDENTIAL_EXCEPTION = + "android.service.credentials.extra.GET_CREDENTIAL_EXCEPTION"; + + /** + * Intent extra: The failure exception set at the final stage of a create flow. + * This exception is set at the finishing result of the {@link android.app.Activity} + * invoked by the {@link PendingIntent} , when a user selects the {@link CreateEntry} + * that contained the {@link PendingIntent} in question. + * + * <p> + * Type: {@link android.credentials.CreateCredentialException} + */ + public static final String EXTRA_CREATE_CREDENTIAL_EXCEPTION = + "android.service.credentials.extra.CREATE_CREDENTIAL_EXCEPTION"; private static final String TAG = "CredProviderService"; @@ -128,20 +155,21 @@ public abstract class CredentialProviderService extends Service { private final ICredentialProviderService mInterface = new ICredentialProviderService.Stub() { @Override - public ICancellationSignal onGetCredentials(GetCredentialsRequest request, - IGetCredentialsCallback callback) { + public ICancellationSignal onBeginGetCredentials(BeginGetCredentialsRequest request, + IBeginGetCredentialsCallback callback) { Objects.requireNonNull(request); Objects.requireNonNull(callback); ICancellationSignal transport = CancellationSignal.createTransport(); mHandler.sendMessage(obtainMessage( - CredentialProviderService::onGetCredentials, + CredentialProviderService::onBeginGetCredentials, CredentialProviderService.this, request, CancellationSignal.fromTransport(transport), - new OutcomeReceiver<GetCredentialsResponse, CredentialProviderException>() { + new OutcomeReceiver<BeginGetCredentialsResponse, + CredentialProviderException>() { @Override - public void onResult(GetCredentialsResponse result) { + public void onResult(BeginGetCredentialsResponse result) { try { callback.onSuccess(result); } catch (RemoteException e) { @@ -200,14 +228,29 @@ public abstract class CredentialProviderService extends Service { /** * Called by the android system to retrieve user credentials from the connected provider * service. - * @param request the credential request for the provider to handle + * + * + * + * <p>This API denotes a query stage request for getting user's credentials from a given + * credential provider. The request contains a list of + * {@link android.credentials.GetCredentialOption} that have parameters to be used for + * populating candidate credentials, as a list of {@link CredentialEntry} to be set + * on the {@link BeginGetCredentialsResponse}. This list is then shown to the user on a + * selector. + * + * <p>If a {@link PendingIntent} is set on a {@link CredentialEntry}, and the user selects that + * entry, a {@link GetCredentialRequest} with all parameters needed to get the actual + * {@link android.credentials.Credential} will be sent as part of the {@link Intent} fired + * through the {@link PendingIntent}. + * @param request the request for the provider to handle * @param cancellationSignal signal for providers to listen to any cancellation requests from * the android system * @param callback object used to relay the response of the credentials request */ - public abstract void onGetCredentials(@NonNull GetCredentialsRequest request, + public abstract void onBeginGetCredentials(@NonNull BeginGetCredentialsRequest request, @NonNull CancellationSignal cancellationSignal, - @NonNull OutcomeReceiver<GetCredentialsResponse, CredentialProviderException> callback); + @NonNull OutcomeReceiver< + BeginGetCredentialsResponse, CredentialProviderException> callback); /** * Called by the android system to create a credential. diff --git a/core/java/android/service/credentials/CredentialsResponseContent.java b/core/java/android/service/credentials/CredentialsResponseContent.java index 32cab5004ac0..c2f28cb1204c 100644 --- a/core/java/android/service/credentials/CredentialsResponseContent.java +++ b/core/java/android/service/credentials/CredentialsResponseContent.java @@ -29,7 +29,7 @@ import java.util.Objects; /** * The content to be displayed on the account selector UI, including credential entries, - * actions etc. Returned as part of {@link GetCredentialsResponse} + * actions etc. Returned as part of {@link BeginGetCredentialsResponse} */ public final class CredentialsResponseContent implements Parcelable { /** List of credential entries to be displayed on the UI. */ @@ -124,7 +124,7 @@ public final class CredentialsResponseContent implements Parcelable { * * <p> Once the remote credential flow is complete, the {@link android.app.Activity} * result should be set to {@link android.app.Activity#RESULT_OK} and an extra with the - * {@link CredentialProviderService#EXTRA_CREDENTIAL_RESULT} key should be populated + * {@link CredentialProviderService#EXTRA_GET_CREDENTIAL_RESPONSE} key should be populated * with a {@link android.credentials.Credential} object. */ public @NonNull Builder setRemoteCredentialEntry(@Nullable CredentialEntry @@ -188,7 +188,7 @@ public final class CredentialsResponseContent implements Parcelable { } /** - * Builds a {@link GetCredentialsResponse} instance. + * Builds a {@link CredentialsResponseContent} instance. * * @throws IllegalStateException if {@code credentialEntries}, {@code actions} * and {@code remoteCredentialEntry} are all null or empty. diff --git a/core/java/android/service/credentials/GetCredentialsRequest.java b/core/java/android/service/credentials/GetCredentialRequest.java index 9052b54c8291..1d6c83be0db1 100644 --- a/core/java/android/service/credentials/GetCredentialsRequest.java +++ b/core/java/android/service/credentials/GetCredentialRequest.java @@ -21,6 +21,7 @@ import android.credentials.GetCredentialOption; import android.os.Parcel; import android.os.Parcelable; +import com.android.internal.util.AnnotationValidations; import com.android.internal.util.Preconditions; import java.util.ArrayList; @@ -30,7 +31,7 @@ import java.util.Objects; /** * Request for getting user's credentials from a given credential provider. */ -public final class GetCredentialsRequest implements Parcelable { +public final class GetCredentialRequest implements Parcelable { /** Calling package of the app requesting for credentials. */ private final @NonNull String mCallingPackage; @@ -40,29 +41,30 @@ public final class GetCredentialsRequest implements Parcelable { */ private final @NonNull List<GetCredentialOption> mGetCredentialOptions; - private GetCredentialsRequest(@NonNull String callingPackage, + private GetCredentialRequest(@NonNull String callingPackage, @NonNull List<GetCredentialOption> getCredentialOptions) { this.mCallingPackage = callingPackage; this.mGetCredentialOptions = getCredentialOptions; } - private GetCredentialsRequest(@NonNull Parcel in) { + private GetCredentialRequest(@NonNull Parcel in) { mCallingPackage = in.readString8(); List<GetCredentialOption> getCredentialOptions = new ArrayList<>(); in.readTypedList(getCredentialOptions, GetCredentialOption.CREATOR); mGetCredentialOptions = getCredentialOptions; + AnnotationValidations.validate(NonNull.class, null, mGetCredentialOptions); } - public static final @NonNull Creator<GetCredentialsRequest> CREATOR = - new Creator<GetCredentialsRequest>() { + public static final @NonNull Creator<GetCredentialRequest> CREATOR = + new Creator<GetCredentialRequest>() { @Override - public GetCredentialsRequest createFromParcel(Parcel in) { - return new GetCredentialsRequest(in); + public GetCredentialRequest createFromParcel(Parcel in) { + return new GetCredentialRequest(in); } @Override - public GetCredentialsRequest[] newArray(int size) { - return new GetCredentialsRequest[size]; + public GetCredentialRequest[] newArray(int size) { + return new GetCredentialRequest[size]; } }; @@ -92,7 +94,7 @@ public final class GetCredentialsRequest implements Parcelable { } /** - * Builder for {@link GetCredentialsRequest}. + * Builder for {@link GetCredentialRequest}. */ public static final class Builder { private String mCallingPackage; @@ -139,18 +141,18 @@ public final class GetCredentialsRequest implements Parcelable { } /** - * Builds a new {@link GetCredentialsRequest} instance. + * Builds a new {@link GetCredentialRequest} instance. * * @throws NullPointerException If {@code getCredentialOptions} is null. * @throws IllegalArgumentException If {@code getCredentialOptions} is empty, or if * {@code callingPackage} is null or empty. */ - public @NonNull GetCredentialsRequest build() { + public @NonNull GetCredentialRequest build() { Preconditions.checkStringNotEmpty(mCallingPackage, "Must set the calling package"); Preconditions.checkCollectionNotEmpty(mGetCredentialOptions, "getCredentialOptions"); - return new GetCredentialsRequest(mCallingPackage, mGetCredentialOptions); + return new GetCredentialRequest(mCallingPackage, mGetCredentialOptions); } } } diff --git a/core/java/android/service/credentials/GetCredentialsRequest.aidl b/core/java/android/service/credentials/GetCredentialsRequest.aidl deleted file mode 100644 index b309d698e7de..000000000000 --- a/core/java/android/service/credentials/GetCredentialsRequest.aidl +++ /dev/null @@ -1,3 +0,0 @@ -package android.service.credentials; - -parcelable GetCredentialsRequest;
\ No newline at end of file diff --git a/core/java/android/service/credentials/IGetCredentialsCallback.aidl b/core/java/android/service/credentials/IBeginGetCredentialsCallback.aidl index 6e20c555af60..9ac28f26059b 100644 --- a/core/java/android/service/credentials/IGetCredentialsCallback.aidl +++ b/core/java/android/service/credentials/IBeginGetCredentialsCallback.aidl @@ -1,13 +1,13 @@ package android.service.credentials; -import android.service.credentials.GetCredentialsResponse; +import android.service.credentials.BeginGetCredentialsResponse; /** * Interface from the system to a credential provider service. * * @hide */ -oneway interface IGetCredentialsCallback { - void onSuccess(in GetCredentialsResponse response); +oneway interface IBeginGetCredentialsCallback { + void onSuccess(in BeginGetCredentialsResponse response); void onFailure(int errorCode, in CharSequence message); }
\ No newline at end of file diff --git a/core/java/android/service/credentials/ICredentialProviderService.aidl b/core/java/android/service/credentials/ICredentialProviderService.aidl index b9eb3ed9571a..130688291795 100644 --- a/core/java/android/service/credentials/ICredentialProviderService.aidl +++ b/core/java/android/service/credentials/ICredentialProviderService.aidl @@ -17,9 +17,9 @@ package android.service.credentials; import android.os.ICancellationSignal; -import android.service.credentials.GetCredentialsRequest; +import android.service.credentials.BeginGetCredentialsRequest; import android.service.credentials.BeginCreateCredentialRequest; -import android.service.credentials.IGetCredentialsCallback; +import android.service.credentials.IBeginGetCredentialsCallback; import android.service.credentials.IBeginCreateCredentialCallback; import android.os.ICancellationSignal; @@ -29,6 +29,6 @@ import android.os.ICancellationSignal; * @hide */ interface ICredentialProviderService { - ICancellationSignal onGetCredentials(in GetCredentialsRequest request, in IGetCredentialsCallback callback); + ICancellationSignal onBeginGetCredentials(in BeginGetCredentialsRequest request, in IBeginGetCredentialsCallback callback); ICancellationSignal onBeginCreateCredential(in BeginCreateCredentialRequest request, in IBeginCreateCredentialCallback callback); } diff --git a/core/java/android/service/notification/NotificationListenerService.java b/core/java/android/service/notification/NotificationListenerService.java index e821af1ab313..d113a3cc0c4b 100644 --- a/core/java/android/service/notification/NotificationListenerService.java +++ b/core/java/android/service/notification/NotificationListenerService.java @@ -267,6 +267,8 @@ public abstract class NotificationListenerService extends Service { * will be restored via NotificationListeners#notifyPostedLocked() */ public static final int REASON_LOCKDOWN = 23; + // If adding a new notification cancellation reason, you must also add handling for it in + // NotificationCancelledEvent.fromCancelReason. /** * @hide diff --git a/core/java/android/service/voice/AbstractHotwordDetector.java b/core/java/android/service/voice/AbstractHotwordDetector.java index 5d3852b8e81e..28357efeafd0 100644 --- a/core/java/android/service/voice/AbstractHotwordDetector.java +++ b/core/java/android/service/voice/AbstractHotwordDetector.java @@ -75,7 +75,7 @@ abstract class AbstractHotwordDetector implements HotwordDetector { /** * Detect hotword from an externally supplied stream of data. * - * @return true if the request to start recognition succeeded + * @return {@code true} if the request to start recognition succeeded */ @Override public boolean startRecognition( @@ -102,23 +102,7 @@ abstract class AbstractHotwordDetector implements HotwordDetector { return true; } - /** - * Set configuration and pass read-only data to hotword detection service. - * - * @param options Application configuration data to provide to the - * {@link HotwordDetectionService}. PersistableBundle does not allow any remotable - * objects or other contents that can be used to communicate with other processes. - * @param sharedMemory The unrestricted data blob to provide to the - * {@link HotwordDetectionService}. Use this to provide the hotword models data or other - * such data to the trusted process. - * @throws IllegalDetectorStateException Thrown when a caller has a target SDK of - * Android Tiramisu or above and attempts to start a recognition when the detector is - * not able based on the state. Because the caller receives updates via an asynchronous - * callback and the state of the detector can change without caller's knowledge, a - * checked exception is thrown. - * @throws IllegalStateException if this HotwordDetector wasn't specified to use a - * {@link HotwordDetectionService} when it was created. - */ + /** {@inheritDoc} */ @Override public void updateState(@Nullable PersistableBundle options, @Nullable SharedMemory sharedMemory) throws IllegalDetectorStateException { diff --git a/core/java/android/service/voice/AlwaysOnHotwordDetector.java b/core/java/android/service/voice/AlwaysOnHotwordDetector.java index d58f6d35981f..320280b9e68b 100644 --- a/core/java/android/service/voice/AlwaysOnHotwordDetector.java +++ b/core/java/android/service/voice/AlwaysOnHotwordDetector.java @@ -728,53 +728,24 @@ public class AlwaysOnHotwordDetector extends AbstractHotwordDetector { */ public abstract void onDetected(@NonNull EventPayload eventPayload); - /** - * Called when the detection fails due to an error. - */ + /** {@inheritDoc} */ public abstract void onError(); - /** - * Called when the recognition is paused temporarily for some reason. - * This is an informational callback, and the clients shouldn't be doing anything here - * except showing an indication on their UI if they have to. - */ + /** {@inheritDoc} */ public abstract void onRecognitionPaused(); - /** - * Called when the recognition is resumed after it was temporarily paused. - * This is an informational callback, and the clients shouldn't be doing anything here - * except showing an indication on their UI if they have to. - */ + /** {@inheritDoc} */ public abstract void onRecognitionResumed(); - /** - * Called when the {@link HotwordDetectionService second stage detection} did not detect the - * keyphrase. - * - * @param result Info about the second stage detection result, provided by the - * {@link HotwordDetectionService}. - */ + /** {@inheritDoc} */ public void onRejected(@NonNull HotwordRejectedResult result) { } - /** - * Called when the {@link HotwordDetectionService} is created by the system and given a - * short amount of time to report it's initialization state. - * - * @param status Info about initialization state of {@link HotwordDetectionService}; the - * allowed values are {@link HotwordDetectionService#INITIALIZATION_STATUS_SUCCESS}, - * 1<->{@link HotwordDetectionService#getMaxCustomInitializationStatus()}, - * {@link HotwordDetectionService#INITIALIZATION_STATUS_UNKNOWN}. - */ + /** {@inheritDoc} */ public void onHotwordDetectionServiceInitialized(int status) { } - /** - * Called with the {@link HotwordDetectionService} is restarted. - * - * Clients are expected to call {@link HotwordDetector#updateState} to share the state with - * the newly created service. - */ + /** {@inheritDoc} */ public void onHotwordDetectionServiceRestarted() { } } @@ -785,14 +756,8 @@ public class AlwaysOnHotwordDetector extends AbstractHotwordDetector { * @param callback A non-null Callback for receiving the recognition events. * @param modelManagementService A service that allows management of sound models. * @param targetSdkVersion The target SDK version. - * @param supportHotwordDetectionService {@code true} if hotword detection service should be + * @param supportHotwordDetectionService {@code true} if HotwordDetectionService should be * triggered, otherwise {@code false}. - * @param options Application configuration data provided by the - * {@link VoiceInteractionService}. PersistableBundle does not allow any remotable objects or - * other contents that can be used to communicate with other processes. - * @param sharedMemory The unrestricted data blob provided by the - * {@link VoiceInteractionService}. Use this to provide the hotword models data or other - * such data to the trusted process. * * @hide */ @@ -1422,10 +1387,7 @@ public class AlwaysOnHotwordDetector extends AbstractHotwordDetector { return mKeyphraseEnrollmentInfo.getManageKeyphraseIntent(action, mText, mLocale); } - /** - * Invalidates this hotword detector so that any future calls to this result - * in an IllegalStateException. - */ + /** {@inheritDoc} */ @Override public void destroy() { synchronized (mLock) { diff --git a/core/java/android/service/voice/HotwordDetector.java b/core/java/android/service/voice/HotwordDetector.java index 1a0dc8945b63..7112dc666509 100644 --- a/core/java/android/service/voice/HotwordDetector.java +++ b/core/java/android/service/voice/HotwordDetector.java @@ -96,7 +96,7 @@ public interface HotwordDetector { * <p> * Calling this again while recognition is active does nothing. * - * @return true if the request to start recognition succeeded + * @return {@code true} if the request to start recognition succeeded * @throws IllegalDetectorStateException Thrown when a caller has a target SDK of API level 33 * or above and attempts to start a recognition when the detector is not able based on * the state. This can be thrown even if the state has been checked before calling this @@ -109,7 +109,7 @@ public interface HotwordDetector { /** * Stops hotword recognition. * - * @return true if the request to stop recognition succeeded + * @return {@code true} if the request to stop recognition succeeded * @throws IllegalDetectorStateException Thrown when a caller has a target SDK of API level 33 * or above and attempts to stop a recognition when the detector is not able based on * the state. This can be thrown even if the state has been checked before calling this @@ -129,7 +129,7 @@ public interface HotwordDetector { * source of the audio. This will be provided to the {@link HotwordDetectionService}. * PersistableBundle does not allow any remotable objects or other contents that can be * used to communicate with other processes. - * @return true if the request to start recognition succeeded + * @return {@code true} if the request to start recognition succeeded * @throws IllegalDetectorStateException Thrown when a caller has a target SDK of API level 33 * or above and attempts to start a recognition when the detector is not able based on * the state. This can be thrown even if the state has been checked before calling this @@ -164,7 +164,9 @@ public interface HotwordDetector { /** * Invalidates this hotword detector so that any future calls to this result - * in an {@link IllegalStateException}. + * in an {@link IllegalStateException} when a caller has a target SDK below API level 33 + * or an {@link IllegalDetectorStateException} when a caller has a target SDK of API level 33 + * or above. * * <p>If there are no other {@link HotwordDetector} instances linked to the * {@link HotwordDetectionService}, the service will be shutdown. @@ -234,7 +236,7 @@ public interface HotwordDetector { void onRecognitionResumed(); /** - * Called when the {@link HotwordDetectionService second stage detection} did not detect the + * Called when the {@link HotwordDetectionService} second stage detection did not detect the * keyphrase. * * @param result Info about the second stage detection result, provided by the @@ -244,7 +246,7 @@ public interface HotwordDetector { /** * Called when the {@link HotwordDetectionService} is created by the system and given a - * short amount of time to report it's initialization state. + * short amount of time to report its initialization state. * * @param status Info about initialization state of {@link HotwordDetectionService}; the * allowed values are {@link HotwordDetectionService#INITIALIZATION_STATUS_SUCCESS}, diff --git a/core/java/android/view/KeyCharacterMap.java b/core/java/android/view/KeyCharacterMap.java index a6f88a7410c2..ea5d9a684ba4 100644 --- a/core/java/android/view/KeyCharacterMap.java +++ b/core/java/android/view/KeyCharacterMap.java @@ -177,6 +177,8 @@ public class KeyCharacterMap implements Parcelable { private static final int ACCENT_UMLAUT = '\u00A8'; private static final int ACCENT_VERTICAL_LINE_ABOVE = '\u02C8'; private static final int ACCENT_VERTICAL_LINE_BELOW = '\u02CC'; + private static final int ACCENT_APOSTROPHE = '\''; + private static final int ACCENT_QUOTATION_MARK = '"'; /* Legacy dead key display characters used in previous versions of the API. * We still support these characters by mapping them to their non-legacy version. */ @@ -204,8 +206,6 @@ public class KeyCharacterMap implements Parcelable { addCombining('\u030A', ACCENT_RING_ABOVE); addCombining('\u030B', ACCENT_DOUBLE_ACUTE); addCombining('\u030C', ACCENT_CARON); - addCombining('\u030D', ACCENT_VERTICAL_LINE_ABOVE); - //addCombining('\u030E', ACCENT_DOUBLE_VERTICAL_LINE_ABOVE); //addCombining('\u030F', ACCENT_DOUBLE_GRAVE); //addCombining('\u0310', ACCENT_CANDRABINDU); //addCombining('\u0311', ACCENT_INVERTED_BREVE); @@ -229,11 +229,17 @@ public class KeyCharacterMap implements Parcelable { sCombiningToAccent.append('\u0340', ACCENT_GRAVE); sCombiningToAccent.append('\u0341', ACCENT_ACUTE); sCombiningToAccent.append('\u0343', ACCENT_COMMA_ABOVE); + sCombiningToAccent.append('\u030D', ACCENT_APOSTROPHE); + sCombiningToAccent.append('\u030E', ACCENT_QUOTATION_MARK); // One-way legacy mappings to preserve compatibility with older applications. sAccentToCombining.append(ACCENT_GRAVE_LEGACY, '\u0300'); sAccentToCombining.append(ACCENT_CIRCUMFLEX_LEGACY, '\u0302'); sAccentToCombining.append(ACCENT_TILDE_LEGACY, '\u0303'); + + // One-way mappings to use the preferred accent + sAccentToCombining.append(ACCENT_APOSTROPHE, '\u0301'); + sAccentToCombining.append(ACCENT_QUOTATION_MARK, '\u0308'); } private static void addCombining(int combining, int accent) { diff --git a/core/java/android/view/SurfaceControl.java b/core/java/android/view/SurfaceControl.java index 89a0c05e0e3f..277b90cc04bc 100644 --- a/core/java/android/view/SurfaceControl.java +++ b/core/java/android/view/SurfaceControl.java @@ -187,8 +187,8 @@ public final class SurfaceControl implements Parcelable { int L, int T, int R, int B); private static native void nativeSetDisplaySize(long transactionObj, IBinder displayToken, int width, int height); - private static native StaticDisplayInfo nativeGetStaticDisplayInfo(IBinder displayToken); - private static native DynamicDisplayInfo nativeGetDynamicDisplayInfo(IBinder displayToken); + private static native StaticDisplayInfo nativeGetStaticDisplayInfo(long displayId); + private static native DynamicDisplayInfo nativeGetDynamicDisplayInfo(long displayId); private static native DisplayedContentSamplingAttributes nativeGetDisplayedContentSamplingAttributes(IBinder displayToken); private static native boolean nativeSetDisplayedContentSamplingEnabled(IBinder displayToken, @@ -1627,21 +1627,15 @@ public final class SurfaceControl implements Parcelable { /** * @hide */ - public static StaticDisplayInfo getStaticDisplayInfo(IBinder displayToken) { - if (displayToken == null) { - throw new IllegalArgumentException("displayToken must not be null"); - } - return nativeGetStaticDisplayInfo(displayToken); + public static StaticDisplayInfo getStaticDisplayInfo(long displayId) { + return nativeGetStaticDisplayInfo(displayId); } /** * @hide */ - public static DynamicDisplayInfo getDynamicDisplayInfo(IBinder displayToken) { - if (displayToken == null) { - throw new IllegalArgumentException("displayToken must not be null"); - } - return nativeGetDynamicDisplayInfo(displayToken); + public static DynamicDisplayInfo getDynamicDisplayInfo(long displayId) { + return nativeGetDynamicDisplayInfo(displayId); } /** diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java index bfb489ea46dc..727011c5a94f 100644 --- a/core/java/android/view/ViewRootImpl.java +++ b/core/java/android/view/ViewRootImpl.java @@ -471,16 +471,6 @@ public final class ViewRootImpl implements ViewParent, private boolean mAppVisibilityChanged; int mOrigWindowType = -1; - /** Whether the window had focus during the most recent traversal. */ - boolean mHadWindowFocus; - - /** - * Whether the window lost focus during a previous traversal and has not - * yet gained it back. Used to determine whether a WINDOW_STATE_CHANGE - * accessibility events should be sent during traversal. - */ - boolean mLostWindowFocus; - // Set to true if the owner of this window is in the stopped state, // so the window should no longer be active. @UnsupportedAppUsage @@ -3630,20 +3620,8 @@ public final class ViewRootImpl implements ViewParent, } final boolean changedVisibility = (viewVisibilityChanged || mFirst) && isViewVisible; - final boolean hasWindowFocus = mAttachInfo.mHasWindowFocus && isViewVisible; - final boolean regainedFocus = hasWindowFocus && mLostWindowFocus; - if (regainedFocus) { - mLostWindowFocus = false; - } else if (!hasWindowFocus && mHadWindowFocus) { - mLostWindowFocus = true; - } - - if (changedVisibility || regainedFocus) { - // Toasts are presented as notifications - don't present them as windows as well - boolean isToast = mWindowAttributes.type == TYPE_TOAST; - if (!isToast) { - host.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); - } + if (changedVisibility) { + maybeFireAccessibilityWindowStateChangedEvent(); } mFirst = false; @@ -3651,8 +3629,8 @@ public final class ViewRootImpl implements ViewParent, mNewSurfaceNeeded = false; mActivityRelaunched = false; mViewVisibility = viewVisibility; - mHadWindowFocus = hasWindowFocus; + final boolean hasWindowFocus = mAttachInfo.mHasWindowFocus && isViewVisible; mImeFocusController.onTraversal(hasWindowFocus, mWindowAttributes); if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) { @@ -3895,6 +3873,8 @@ public final class ViewRootImpl implements ViewParent, ~WindowManager.LayoutParams .SOFT_INPUT_IS_FORWARD_NAVIGATION; + maybeFireAccessibilityWindowStateChangedEvent(); + // Refocusing a window that has a focused view should fire a // focus event for the view since the global focused view changed. fireAccessibilityFocusEventIfHasFocusedNode(); @@ -3922,6 +3902,14 @@ public final class ViewRootImpl implements ViewParent, ensureTouchModeLocally(inTouchMode); } + private void maybeFireAccessibilityWindowStateChangedEvent() { + // Toasts are presented as notifications - don't present them as windows as well. + boolean isToast = mWindowAttributes != null && (mWindowAttributes.type == TYPE_TOAST); + if (!isToast && mView != null) { + mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); + } + } + private void fireAccessibilityFocusEventIfHasFocusedNode() { if (!AccessibilityManager.getInstance(mContext).isEnabled()) { return; diff --git a/core/java/android/window/TaskFragmentCreationParams.java b/core/java/android/window/TaskFragmentCreationParams.java index 81ab7836435d..c9ddf92d3740 100644 --- a/core/java/android/window/TaskFragmentCreationParams.java +++ b/core/java/android/window/TaskFragmentCreationParams.java @@ -20,6 +20,7 @@ import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED; import static android.app.WindowConfiguration.WindowingMode; import android.annotation.NonNull; +import android.annotation.Nullable; import android.annotation.TestApi; import android.graphics.Rect; import android.os.IBinder; @@ -57,14 +58,33 @@ public final class TaskFragmentCreationParams implements Parcelable { /** The initial windowing mode of the TaskFragment. Inherits from parent if not set. */ @WindowingMode - private int mWindowingMode = WINDOWING_MODE_UNDEFINED; + private final int mWindowingMode; + + /** + * The fragment token of the paired primary TaskFragment. + * When it is set, the new TaskFragment will be positioned right above the paired TaskFragment. + * Otherwise, the new TaskFragment will be positioned on the top of the Task by default. + * + * This is different from {@link WindowContainerTransaction#setAdjacentTaskFragments} as we may + * set this when the pair of TaskFragments are stacked, while adjacent is only set on the pair + * of TaskFragments that are in split. + * + * This is needed in case we need to launch a placeholder Activity to split below a transparent + * always-expand Activity. + */ + @Nullable + private final IBinder mPairedPrimaryFragmentToken; private TaskFragmentCreationParams( - @NonNull TaskFragmentOrganizerToken organizer, - @NonNull IBinder fragmentToken, @NonNull IBinder ownerToken) { + @NonNull TaskFragmentOrganizerToken organizer, @NonNull IBinder fragmentToken, + @NonNull IBinder ownerToken, @NonNull Rect initialBounds, + @WindowingMode int windowingMode, @Nullable IBinder pairedPrimaryFragmentToken) { mOrganizer = organizer; mFragmentToken = fragmentToken; mOwnerToken = ownerToken; + mInitialBounds.set(initialBounds); + mWindowingMode = windowingMode; + mPairedPrimaryFragmentToken = pairedPrimaryFragmentToken; } @NonNull @@ -92,12 +112,22 @@ public final class TaskFragmentCreationParams implements Parcelable { return mWindowingMode; } + /** + * TODO(b/232476698): remove the hide with adding CTS for this in next release. + * @hide + */ + @Nullable + public IBinder getPairedPrimaryFragmentToken() { + return mPairedPrimaryFragmentToken; + } + private TaskFragmentCreationParams(Parcel in) { mOrganizer = TaskFragmentOrganizerToken.CREATOR.createFromParcel(in); mFragmentToken = in.readStrongBinder(); mOwnerToken = in.readStrongBinder(); mInitialBounds.readFromParcel(in); mWindowingMode = in.readInt(); + mPairedPrimaryFragmentToken = in.readStrongBinder(); } /** @hide */ @@ -108,6 +138,7 @@ public final class TaskFragmentCreationParams implements Parcelable { dest.writeStrongBinder(mOwnerToken); mInitialBounds.writeToParcel(dest, flags); dest.writeInt(mWindowingMode); + dest.writeStrongBinder(mPairedPrimaryFragmentToken); } @NonNull @@ -132,6 +163,7 @@ public final class TaskFragmentCreationParams implements Parcelable { + " ownerToken=" + mOwnerToken + " initialBounds=" + mInitialBounds + " windowingMode=" + mWindowingMode + + " pairedFragmentToken=" + mPairedPrimaryFragmentToken + "}"; } @@ -159,6 +191,9 @@ public final class TaskFragmentCreationParams implements Parcelable { @WindowingMode private int mWindowingMode = WINDOWING_MODE_UNDEFINED; + @Nullable + private IBinder mPairedPrimaryFragmentToken; + public Builder(@NonNull TaskFragmentOrganizerToken organizer, @NonNull IBinder fragmentToken, @NonNull IBinder ownerToken) { mOrganizer = organizer; @@ -180,14 +215,29 @@ public final class TaskFragmentCreationParams implements Parcelable { return this; } + /** + * Sets the fragment token of the paired primary TaskFragment. + * When it is set, the new TaskFragment will be positioned right above the paired + * TaskFragment. Otherwise, the new TaskFragment will be positioned on the top of the Task + * by default. + * + * This is needed in case we need to launch a placeholder Activity to split below a + * transparent always-expand Activity. + * + * TODO(b/232476698): remove the hide with adding CTS for this in next release. + * @hide + */ + @NonNull + public Builder setPairedPrimaryFragmentToken(@Nullable IBinder fragmentToken) { + mPairedPrimaryFragmentToken = fragmentToken; + return this; + } + /** Constructs the options to create TaskFragment with. */ @NonNull public TaskFragmentCreationParams build() { - final TaskFragmentCreationParams result = new TaskFragmentCreationParams( - mOrganizer, mFragmentToken, mOwnerToken); - result.mInitialBounds.set(mInitialBounds); - result.mWindowingMode = mWindowingMode; - return result; + return new TaskFragmentCreationParams(mOrganizer, mFragmentToken, mOwnerToken, + mInitialBounds, mWindowingMode, mPairedPrimaryFragmentToken); } } } diff --git a/core/java/android/window/TaskFragmentOrganizer.java b/core/java/android/window/TaskFragmentOrganizer.java index ef19c55019dc..283df7608806 100644 --- a/core/java/android/window/TaskFragmentOrganizer.java +++ b/core/java/android/window/TaskFragmentOrganizer.java @@ -20,22 +20,20 @@ import static android.view.WindowManager.TRANSIT_CHANGE; import static android.view.WindowManager.TRANSIT_CLOSE; import static android.view.WindowManager.TRANSIT_NONE; import static android.view.WindowManager.TRANSIT_OPEN; -import static android.window.WindowContainerTransaction.HierarchyOp.HIERARCHY_OP_TYPE_CREATE_TASK_FRAGMENT; -import static android.window.WindowContainerTransaction.HierarchyOp.HIERARCHY_OP_TYPE_DELETE_TASK_FRAGMENT; -import static android.window.WindowContainerTransaction.HierarchyOp.HIERARCHY_OP_TYPE_REPARENT_ACTIVITY_TO_TASK_FRAGMENT; import android.annotation.CallSuper; +import android.annotation.IntDef; import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.TestApi; -import android.app.WindowConfiguration; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.view.RemoteAnimationDefinition; import android.view.WindowManager; -import java.util.List; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; import java.util.concurrent.Executor; /** @@ -63,6 +61,52 @@ public class TaskFragmentOrganizer extends WindowOrganizer { public static final String KEY_ERROR_CALLBACK_OP_TYPE = "operation_type"; /** + * No change set. + */ + @WindowManager.TransitionType + @TaskFragmentTransitionType + public static final int TASK_FRAGMENT_TRANSIT_NONE = TRANSIT_NONE; + + /** + * A window that didn't exist before has been created and made visible. + */ + @WindowManager.TransitionType + @TaskFragmentTransitionType + public static final int TASK_FRAGMENT_TRANSIT_OPEN = TRANSIT_OPEN; + + /** + * A window that was visible no-longer exists (was finished or destroyed). + */ + @WindowManager.TransitionType + @TaskFragmentTransitionType + public static final int TASK_FRAGMENT_TRANSIT_CLOSE = TRANSIT_CLOSE; + + /** + * A window is visible before and after but changes in some way (eg. it resizes or changes + * windowing-mode). + */ + @WindowManager.TransitionType + @TaskFragmentTransitionType + public static final int TASK_FRAGMENT_TRANSIT_CHANGE = TRANSIT_CHANGE; + + /** + * Introduced a sub set of {@link WindowManager.TransitionType} for the types that are used for + * TaskFragment transition. + * + * Doing this instead of exposing {@link WindowManager.TransitionType} because we want to keep + * the Shell transition API hidden until it comes fully stable. + * @hide + */ + @IntDef(prefix = { "TASK_FRAGMENT_TRANSIT_" }, value = { + TASK_FRAGMENT_TRANSIT_NONE, + TASK_FRAGMENT_TRANSIT_OPEN, + TASK_FRAGMENT_TRANSIT_CLOSE, + TASK_FRAGMENT_TRANSIT_CHANGE, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface TaskFragmentTransitionType {} + + /** * Creates a {@link Bundle} with an exception, operation type and TaskFragmentInfo (if any) * that can be passed to {@link ITaskFragmentOrganizer#onTaskFragmentError}. * @hide @@ -155,7 +199,7 @@ public class TaskFragmentOrganizer extends WindowOrganizer { * {@link #onTransactionReady(TaskFragmentTransaction)} * @param wct {@link WindowContainerTransaction} that the server should apply for * update of the transaction. - * @param transitionType {@link WindowManager.TransitionType} if it needs to start a + * @param transitionType {@link TaskFragmentTransitionType} if it needs to start a * transition. * @param shouldApplyIndependently If {@code true}, the {@code wct} will request a new * transition, which will be queued until the sync engine is @@ -163,11 +207,10 @@ public class TaskFragmentOrganizer extends WindowOrganizer { * the {@code wct} will be directly applied to the active sync. * @see com.android.server.wm.WindowOrganizerController#enforceTaskFragmentOrganizerPermission * for permission enforcement. - * @hide */ public void onTransactionHandled(@NonNull IBinder transactionToken, @NonNull WindowContainerTransaction wct, - @WindowManager.TransitionType int transitionType, boolean shouldApplyIndependently) { + @TaskFragmentTransitionType int transitionType, boolean shouldApplyIndependently) { wct.setTaskFragmentOrganizer(mInterface); try { getController().onTransactionHandled(transactionToken, wct, transitionType, @@ -178,22 +221,19 @@ public class TaskFragmentOrganizer extends WindowOrganizer { } /** - * Routes to {@link ITaskFragmentOrganizerController#applyTransaction} instead of - * {@link IWindowOrganizerController#applyTransaction} for the different transition options. - * + * Must use {@link #applyTransaction(WindowContainerTransaction, int, boolean)} instead. * @see #applyTransaction(WindowContainerTransaction, int, boolean) */ @Override public void applyTransaction(@NonNull WindowContainerTransaction wct) { - // TODO(b/207070762) doing so to keep CTS compatibility. Remove in the next release. - applyTransaction(wct, getTransitionType(wct), false /* shouldApplyIndependently */); + throw new RuntimeException("Not allowed!"); } /** * Requests the server to apply the given {@link WindowContainerTransaction}. * * @param wct {@link WindowContainerTransaction} to apply. - * @param transitionType {@link WindowManager.TransitionType} if it needs to start a + * @param transitionType {@link TaskFragmentTransitionType} if it needs to start a * transition. * @param shouldApplyIndependently If {@code true}, the {@code wct} will request a new * transition, which will be queued until the sync engine is @@ -201,10 +241,9 @@ public class TaskFragmentOrganizer extends WindowOrganizer { * the {@code wct} will be directly applied to the active sync. * @see com.android.server.wm.WindowOrganizerController#enforceTaskFragmentOrganizerPermission * for permission enforcement. - * @hide */ public void applyTransaction(@NonNull WindowContainerTransaction wct, - @WindowManager.TransitionType int transitionType, boolean shouldApplyIndependently) { + @TaskFragmentTransitionType int transitionType, boolean shouldApplyIndependently) { if (wct.isEmpty()) { return; } @@ -217,56 +256,13 @@ public class TaskFragmentOrganizer extends WindowOrganizer { } /** - * Gets the default {@link WindowManager.TransitionType} based on the requested - * {@link WindowContainerTransaction}. - * @hide - */ - // TODO(b/207070762): let Extensions to set the transition type instead. - @WindowManager.TransitionType - public static int getTransitionType(@NonNull WindowContainerTransaction wct) { - if (wct.isEmpty()) { - return TRANSIT_NONE; - } - for (WindowContainerTransaction.Change change : wct.getChanges().values()) { - if ((change.getWindowSetMask() & WindowConfiguration.WINDOW_CONFIG_BOUNDS) != 0) { - // Treat as TRANSIT_CHANGE when there is TaskFragment resizing. - return TRANSIT_CHANGE; - } - } - boolean containsCreatingTaskFragment = false; - boolean containsDeleteTaskFragment = false; - final List<WindowContainerTransaction.HierarchyOp> ops = wct.getHierarchyOps(); - for (int i = ops.size() - 1; i >= 0; i--) { - final int type = ops.get(i).getType(); - if (type == HIERARCHY_OP_TYPE_REPARENT_ACTIVITY_TO_TASK_FRAGMENT) { - // Treat as TRANSIT_CHANGE when there is activity reparent. - return TRANSIT_CHANGE; - } - if (type == HIERARCHY_OP_TYPE_CREATE_TASK_FRAGMENT) { - containsCreatingTaskFragment = true; - } else if (type == HIERARCHY_OP_TYPE_DELETE_TASK_FRAGMENT) { - containsDeleteTaskFragment = true; - } - } - if (containsCreatingTaskFragment) { - return TRANSIT_OPEN; - } - if (containsDeleteTaskFragment) { - return TRANSIT_CLOSE; - } - - // Use TRANSIT_CHANGE as default. - return TRANSIT_CHANGE; - } - - /** * Called when the transaction is ready so that the organizer can update the TaskFragments based * on the changes in transaction. */ public void onTransactionReady(@NonNull TaskFragmentTransaction transaction) { // Notify the server to finish the transaction. onTransactionHandled(transaction.getTransactionToken(), new WindowContainerTransaction(), - TRANSIT_NONE, false /* shouldApplyIndependently */); + TASK_FRAGMENT_TRANSIT_NONE, false /* shouldApplyIndependently */); } private final ITaskFragmentOrganizer mInterface = new ITaskFragmentOrganizer.Stub() { diff --git a/core/java/android/window/WindowOrganizer.java b/core/java/android/window/WindowOrganizer.java index 930aaa2b291b..695d01e92316 100644 --- a/core/java/android/window/WindowOrganizer.java +++ b/core/java/android/window/WindowOrganizer.java @@ -40,14 +40,11 @@ public class WindowOrganizer { * Apply multiple WindowContainer operations at once. * * Note that using this API requires the caller to hold - * {@link android.Manifest.permission#MANAGE_ACTIVITY_TASKS}, unless the caller is using - * {@link TaskFragmentOrganizer}, in which case it is allowed to change TaskFragment that is - * created by itself. + * {@link android.Manifest.permission#MANAGE_ACTIVITY_TASKS}. * * @param t The transaction to apply. */ - @RequiresPermission(value = android.Manifest.permission.MANAGE_ACTIVITY_TASKS, - conditional = true) + @RequiresPermission(value = android.Manifest.permission.MANAGE_ACTIVITY_TASKS) public void applyTransaction(@NonNull WindowContainerTransaction t) { try { if (!t.isEmpty()) { @@ -62,9 +59,7 @@ public class WindowOrganizer { * Apply multiple WindowContainer operations at once. * * Note that using this API requires the caller to hold - * {@link android.Manifest.permission#MANAGE_ACTIVITY_TASKS}, unless the caller is using - * {@link TaskFragmentOrganizer}, in which case it is allowed to change TaskFragment that is - * created by itself. + * {@link android.Manifest.permission#MANAGE_ACTIVITY_TASKS}. * * @param t The transaction to apply. * @param callback This transaction will use the synchronization scheme described in @@ -73,8 +68,7 @@ public class WindowOrganizer { * @return An ID for the sync operation which will later be passed to transactionReady callback. * This lets the caller differentiate overlapping sync operations. */ - @RequiresPermission(value = android.Manifest.permission.MANAGE_ACTIVITY_TASKS, - conditional = true) + @RequiresPermission(value = android.Manifest.permission.MANAGE_ACTIVITY_TASKS) public int applySyncTransaction(@NonNull WindowContainerTransaction t, @NonNull WindowContainerTransactionCallback callback) { try { diff --git a/core/java/com/android/internal/accessibility/AccessibilityShortcutController.java b/core/java/com/android/internal/accessibility/AccessibilityShortcutController.java index 43be0312245e..e0b01103ae73 100644 --- a/core/java/com/android/internal/accessibility/AccessibilityShortcutController.java +++ b/core/java/com/android/internal/accessibility/AccessibilityShortcutController.java @@ -226,9 +226,7 @@ public class AccessibilityShortcutController { Slog.d(TAG, "Accessibility shortcut activated"); final ContentResolver cr = mContext.getContentResolver(); final int userId = ActivityManager.getCurrentUser(); - final int dialogAlreadyShown = Settings.Secure.getIntForUser( - cr, Settings.Secure.ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN, DialogStatus.NOT_SHOWN, - userId); + // Play a notification vibration Vibrator vibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE); if ((vibrator != null) && vibrator.hasVibrator()) { @@ -239,7 +237,7 @@ public class AccessibilityShortcutController { vibrator.vibrate(vibePattern, -1, VIBRATION_ATTRIBUTES); } - if (dialogAlreadyShown == DialogStatus.NOT_SHOWN) { + if (shouldShowDialog()) { // The first time, we show a warning rather than toggle the service to give the user a // chance to turn off this feature before stuff gets enabled. mAlertDialog = createShortcutWarningDialog(userId); @@ -269,6 +267,20 @@ public class AccessibilityShortcutController { } } + /** Whether the warning dialog should be shown instead of performing the shortcut. */ + private boolean shouldShowDialog() { + if (hasFeatureLeanback()) { + // Never show the dialog on TV, instead always perform the shortcut directly. + return false; + } + final ContentResolver cr = mContext.getContentResolver(); + final int userId = ActivityManager.getCurrentUser(); + final int dialogAlreadyShown = Settings.Secure.getIntForUser(cr, + Settings.Secure.ACCESSIBILITY_SHORTCUT_DIALOG_SHOWN, DialogStatus.NOT_SHOWN, + userId); + return dialogAlreadyShown == DialogStatus.NOT_SHOWN; + } + /** * Show toast to alert the user that the accessibility shortcut turned on or off an * accessibility service. diff --git a/core/java/com/android/internal/content/om/TEST_MAPPING b/core/java/com/android/internal/content/om/TEST_MAPPING index 4cb595b01681..98dadce7359a 100644 --- a/core/java/com/android/internal/content/om/TEST_MAPPING +++ b/core/java/com/android/internal/content/om/TEST_MAPPING @@ -7,6 +7,28 @@ "include-filter": "com.android.internal.content." } ] + }, + { + "name": "SelfTargetingOverlayDeviceTests" + } + ], + "presubmit-large": [ + { + "name": "CtsContentTestCases", + "options": [ + { + "exclude-annotation": "androidx.test.filters.FlakyTest" + }, + { + "exclude-annotation": "org.junit.Ignore" + }, + { + "include-filter": "android.content.om.cts" + }, + { + "include-filter": "android.content.res.loader.cts" + } + ] } ] -}
\ No newline at end of file +} diff --git a/core/java/com/android/internal/inputmethod/InputBindResult.java b/core/java/com/android/internal/inputmethod/InputBindResult.java index f101497125e9..7dbbffda49ba 100644 --- a/core/java/com/android/internal/inputmethod/InputBindResult.java +++ b/core/java/com/android/internal/inputmethod/InputBindResult.java @@ -170,6 +170,9 @@ public final class InputBindResult implements Parcelable { * display. */ int ERROR_INVALID_DISPLAY_ID = 15; + /** + * Indicates that a valid session is created and result is ready for accessibility. + */ int SUCCESS_WITH_ACCESSIBILITY_SESSION = 16; } @@ -389,6 +392,8 @@ public final class InputBindResult implements Parcelable { return "ERROR_DISPLAY_ID_MISMATCH"; case ResultCode.ERROR_INVALID_DISPLAY_ID: return "ERROR_INVALID_DISPLAY_ID"; + case ResultCode.SUCCESS_WITH_ACCESSIBILITY_SESSION: + return "SUCCESS_WITH_ACCESSIBILITY_SESSION"; default: return "Unknown(" + result + ")"; } diff --git a/core/java/com/android/internal/os/BatteryStatsHistory.java b/core/java/com/android/internal/os/BatteryStatsHistory.java index 556e1467c7df..c3361a2bb583 100644 --- a/core/java/com/android/internal/os/BatteryStatsHistory.java +++ b/core/java/com/android/internal/os/BatteryStatsHistory.java @@ -1047,6 +1047,17 @@ public class BatteryStatsHistory { } /** + * Records a wakelock release event. + */ + public void recordWakelockStopEvent(long elapsedRealtimeMs, long uptimeMs, String historyName, + int uid) { + mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag; + mHistoryCur.wakelockTag.string = historyName != null ? historyName : ""; + mHistoryCur.wakelockTag.uid = uid; + recordStateStopEvent(elapsedRealtimeMs, uptimeMs, HistoryItem.STATE_WAKE_LOCK_FLAG); + } + + /** * Records an event when some state flag changes to true. */ public void recordStateStartEvent(long elapsedRealtimeMs, long uptimeMs, int stateFlags) { diff --git a/core/jni/TEST_MAPPING b/core/jni/TEST_MAPPING index 004c30ee5113..28448561e135 100644 --- a/core/jni/TEST_MAPPING +++ b/core/jni/TEST_MAPPING @@ -11,6 +11,29 @@ } ], "file_patterns": ["CharsetUtils|FastData"] + }, + { + "name": "SelfTargetingOverlayDeviceTests", + "file_patterns": ["Overlay"] + } + ], + "presubmit-large": [ + { + "name": "CtsContentTestCases", + "options": [ + { + "exclude-annotation": "androidx.test.filters.FlakyTest" + }, + { + "exclude-annotation": "org.junit.Ignore" + }, + { + "include-filter": "android.content.om.cts" + }, + { + "include-filter": "android.content.res.loader.cts" + } + ] } ] } diff --git a/core/jni/android_media_AudioMixerAttributes.h b/core/jni/android_media_AudioMixerAttributes.h new file mode 100644 index 000000000000..61adb27bdc7f --- /dev/null +++ b/core/jni/android_media_AudioMixerAttributes.h @@ -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. + */ + +#ifndef ANDROID_MEDIA_AUDIOMIXERATTRIBUTES_H +#define ANDROID_MEDIA_AUDIOMIXERATTRIBUTES_H + +#include <system/audio.h> + +// Keep sync with AudioMixerAttributes.java +#define MIXER_BEHAVIOR_DEFAULT 0 +// Invalid value is not added in JAVA API, but keep sync with native value +#define MIXER_BEHAVIOR_INVALID -1 + +static inline audio_mixer_behavior_t audioMixerBehaviorToNative(int mixerBehavior) { + switch (mixerBehavior) { + case MIXER_BEHAVIOR_DEFAULT: + return AUDIO_MIXER_BEHAVIOR_DEFAULT; + default: + return AUDIO_MIXER_BEHAVIOR_INVALID; + } +} + +static inline jint audioMixerBehaviorFromNative(audio_mixer_behavior_t mixerBehavior) { + switch (mixerBehavior) { + case AUDIO_MIXER_BEHAVIOR_DEFAULT: + return MIXER_BEHAVIOR_DEFAULT; + case AUDIO_MIXER_BEHAVIOR_INVALID: + default: + return MIXER_BEHAVIOR_INVALID; + } +} + +#endif diff --git a/core/jni/android_media_AudioSystem.cpp b/core/jni/android_media_AudioSystem.cpp index 2433a05a4e9b..28ac464bdf72 100644 --- a/core/jni/android_media_AudioSystem.cpp +++ b/core/jni/android_media_AudioSystem.cpp @@ -21,6 +21,7 @@ #include <android/media/AudioVibratorInfo.h> #include <android/media/INativeSpatializerCallback.h> #include <android/media/ISpatializer.h> +#include <android/media/audio/common/AudioConfigBase.h> #include <android_os_Parcel.h> #include <audiomanager/AudioManager.h> #include <jni.h> @@ -34,6 +35,7 @@ #include <system/audio_policy.h> #include <utils/Log.h> +#include <optional> #include <sstream> #include <vector> @@ -43,6 +45,7 @@ #include "android_media_AudioEffectDescriptor.h" #include "android_media_AudioErrors.h" #include "android_media_AudioFormat.h" +#include "android_media_AudioMixerAttributes.h" #include "android_media_AudioProfile.h" #include "android_media_MicrophoneInfo.h" #include "android_util_Binder.h" @@ -51,6 +54,7 @@ // ---------------------------------------------------------------------------- using namespace android; +using media::audio::common::AudioConfigBase; static const char* const kClassPathName = "android/media/AudioSystem"; @@ -145,10 +149,12 @@ static struct { } gAudioMixFields; static jclass gAudioFormatClass; +static jmethodID gAudioFormatCstor; static struct { jfieldID mEncoding; jfieldID mSampleRate; jfieldID mChannelMask; + jfieldID mChannelIndexMask; // other fields unused by JNI } gAudioFormatFields; @@ -211,6 +217,7 @@ static struct { jfieldID mChannelMasks; jfieldID mChannelIndexMasks; jfieldID mEncapsulationType; + jfieldID mMixerBehaviors; } gAudioProfileFields; jclass gVibratorClass; @@ -221,6 +228,13 @@ static struct { jmethodID getMaxAmplitude; } gVibratorMethods; +jclass gAudioMixerAttributesClass; +jmethodID gAudioMixerAttributesCstor; +static struct { + jfieldID mFormat; + jfieldID mMixerBehavior; +} gAudioMixerAttributesField; + static Mutex gLock; enum AudioError { @@ -237,6 +251,12 @@ enum { #define MAX_PORT_GENERATION_SYNC_ATTEMPTS 5 +// Keep sync with AudioFormat.java +#define AUDIO_FORMAT_HAS_PROPERTY_ENCODING 0x1 +#define AUDIO_FORMAT_HAS_PROPERTY_SAMPLE_RATE 0x2 +#define AUDIO_FORMAT_HAS_PROPERTY_CHANNEL_MASK 0x4 +#define AUDIO_FORMAT_HAS_PROPERTY_CHANNEL_INDEX_MASK 0x8 + // ---------------------------------------------------------------------------- // ref-counted object for audio port callbacks class JNIAudioPortCallback: public AudioSystem::AudioPortCallback @@ -2105,6 +2125,80 @@ void javaAudioFormatToNativeAudioConfig(JNIEnv *env, audio_config_t *nConfig, } } +void javaAudioFormatToNativeAudioConfigBase(JNIEnv *env, const jobject jFormat, + audio_config_base_t *nConfigBase, bool isInput) { + *nConfigBase = AUDIO_CONFIG_BASE_INITIALIZER; + nConfigBase->format = + audioFormatToNative(env->GetIntField(jFormat, gAudioFormatFields.mEncoding)); + nConfigBase->sample_rate = env->GetIntField(jFormat, gAudioFormatFields.mSampleRate); + jint jChannelMask = env->GetIntField(jFormat, gAudioFormatFields.mChannelMask); + jint jChannelIndexMask = env->GetIntField(jFormat, gAudioFormatFields.mChannelIndexMask); + nConfigBase->channel_mask = jChannelIndexMask != 0 + ? audio_channel_mask_from_representation_and_bits(AUDIO_CHANNEL_REPRESENTATION_INDEX, + jChannelIndexMask) + : isInput ? inChannelMaskToNative(jChannelMask) + : outChannelMaskToNative(jChannelMask); +} + +jobject nativeAudioConfigBaseToJavaAudioFormat(JNIEnv *env, const audio_config_base_t *nConfigBase, + bool isInput) { + if (nConfigBase == nullptr) { + return nullptr; + } + int propertyMask = AUDIO_FORMAT_HAS_PROPERTY_ENCODING | AUDIO_FORMAT_HAS_PROPERTY_SAMPLE_RATE; + int channelMask = 0; + int channelIndexMask = 0; + switch (audio_channel_mask_get_representation(nConfigBase->channel_mask)) { + case AUDIO_CHANNEL_REPRESENTATION_POSITION: + channelMask = isInput ? inChannelMaskFromNative(nConfigBase->channel_mask) + : outChannelMaskFromNative(nConfigBase->channel_mask); + propertyMask |= AUDIO_FORMAT_HAS_PROPERTY_CHANNEL_MASK; + break; + case AUDIO_CHANNEL_REPRESENTATION_INDEX: + channelIndexMask = audio_channel_mask_get_bits(nConfigBase->channel_mask); + propertyMask |= AUDIO_FORMAT_HAS_PROPERTY_CHANNEL_INDEX_MASK; + break; + default: + // This must not happen + break; + } + return env->NewObject(gAudioFormatClass, gAudioFormatCstor, propertyMask, + audioFormatFromNative(nConfigBase->format), nConfigBase->sample_rate, + channelMask, channelIndexMask); +} + +jint convertAudioMixerAttributesToNative(JNIEnv *env, const jobject jAudioMixerAttributes, + audio_mixer_attributes_t *nMixerAttributes) { + ScopedLocalRef<jobject> jFormat(env, + env->GetObjectField(jAudioMixerAttributes, + gAudioMixerAttributesField.mFormat)); + javaAudioFormatToNativeAudioConfigBase(env, jFormat.get(), &nMixerAttributes->config, + false /*isInput*/); + nMixerAttributes->mixer_behavior = audioMixerBehaviorToNative( + env->GetIntField(jAudioMixerAttributes, gAudioMixerAttributesField.mMixerBehavior)); + if (nMixerAttributes->mixer_behavior == AUDIO_MIXER_BEHAVIOR_INVALID) { + return (jint)AUDIO_JAVA_BAD_VALUE; + } + return (jint)AUDIO_JAVA_SUCCESS; +} + +jobject convertAudioMixerAttributesFromNative(JNIEnv *env, + const audio_mixer_attributes_t *nMixerAttributes) { + if (nMixerAttributes == nullptr) { + return nullptr; + } + jint mixerBehavior = audioMixerBehaviorFromNative(nMixerAttributes->mixer_behavior); + if (mixerBehavior == MIXER_BEHAVIOR_INVALID) { + return nullptr; + } + ScopedLocalRef<jobject> + jFormat(env, + nativeAudioConfigBaseToJavaAudioFormat(env, &nMixerAttributes->config, + false /*isInput*/)); + return env->NewObject(gAudioMixerAttributesClass, gAudioMixerAttributesCstor, jFormat.get(), + mixerBehavior); +} + static jint convertAudioMixToNative(JNIEnv *env, AudioMix *nAudioMix, const jobject jAudioMix) @@ -2868,6 +2962,20 @@ static jboolean android_media_AudioSystem_canBeSpatialized(JNIEnv *env, jobject return canBeSpatialized; } +static jobject android_media_AudioSystem_nativeGetSoundDose(JNIEnv *env, jobject thiz, + jobject jISoundDoseCallback) { + sp<media::ISoundDoseCallback> nISoundDoseCallback = interface_cast<media::ISoundDoseCallback>( + ibinderForJavaObject(env, jISoundDoseCallback)); + + sp<media::ISoundDose> nSoundDose; + status_t status = AudioSystem::getSoundDoseInterface(nISoundDoseCallback, &nSoundDose); + + if (status != NO_ERROR) { + return nullptr; + } + return javaObjectForIBinder(env, IInterface::asBinder(nSoundDose)); +} + // keep these values in sync with AudioSystem.java #define DIRECT_NOT_SUPPORTED 0 #define DIRECT_OFFLOAD_SUPPORTED 1 @@ -2957,6 +3065,142 @@ static jint android_media_AudioSystem_getDirectProfilesForAttributes(JNIEnv *env return jStatus; } +static jint android_media_AudioSystem_getSupportedMixerAttributes(JNIEnv *env, jobject thiz, + jint jDeviceId, + jobject jAudioMixerAttributes) { + ALOGV("%s", __func__); + if (jAudioMixerAttributes == NULL) { + ALOGE("getSupportedMixerAttributes NULL AudioMixerAttributes list"); + return (jint)AUDIO_JAVA_BAD_VALUE; + } + if (!env->IsInstanceOf(jAudioMixerAttributes, gListClass)) { + ALOGE("getSupportedMixerAttributes not a list"); + return (jint)AUDIO_JAVA_BAD_VALUE; + } + + std::vector<audio_mixer_attributes_t> nMixerAttributes; + status_t status = AudioSystem::getSupportedMixerAttributes((audio_port_handle_t)jDeviceId, + &nMixerAttributes); + if (status != NO_ERROR) { + return nativeToJavaStatus(status); + } + for (const auto &mixerAttr : nMixerAttributes) { + ScopedLocalRef<jobject> jMixerAttributes(env, + convertAudioMixerAttributesFromNative(env, + &mixerAttr)); + if (jMixerAttributes.get() == nullptr) { + return (jint)AUDIO_JAVA_ERROR; + } + + env->CallBooleanMethod(jAudioMixerAttributes, gListMethods.add, jMixerAttributes.get()); + } + + return (jint)AUDIO_JAVA_SUCCESS; +} + +static jint android_media_AudioSystem_setPreferredMixerAttributes(JNIEnv *env, jobject thiz, + jobject jAudioAttributes, + jint portId, jint uid, + jobject jAudioMixerAttributes) { + ALOGV("%s", __func__); + + if (jAudioAttributes == nullptr) { + ALOGE("jAudioAttributes is NULL"); + return (jint)AUDIO_JAVA_BAD_VALUE; + } + if (jAudioMixerAttributes == nullptr) { + ALOGE("jAudioMixerAttributes is NULL"); + return (jint)AUDIO_JAVA_BAD_VALUE; + } + + JNIAudioAttributeHelper::UniqueAaPtr paa = JNIAudioAttributeHelper::makeUnique(); + jint jStatus = JNIAudioAttributeHelper::nativeFromJava(env, jAudioAttributes, paa.get()); + if (jStatus != (jint)AUDIO_JAVA_SUCCESS) { + return jStatus; + } + + audio_mixer_attributes_t mixerAttributes = AUDIO_MIXER_ATTRIBUTES_INITIALIZER; + jStatus = convertAudioMixerAttributesToNative(env, jAudioMixerAttributes, &mixerAttributes); + if (jStatus != (jint)AUDIO_JAVA_SUCCESS) { + return jStatus; + } + + status_t status = + AudioSystem::setPreferredMixerAttributes(paa.get(), (audio_port_handle_t)portId, + (uid_t)uid, &mixerAttributes); + return nativeToJavaStatus(status); +} + +static jint android_media_AudioSystem_getPreferredMixerAttributes(JNIEnv *env, jobject thiz, + jobject jAudioAttributes, + jint portId, + jobject jAudioMixerAttributes) { + ALOGV("%s", __func__); + + if (jAudioAttributes == nullptr) { + ALOGE("getPreferredMixerAttributes jAudioAttributes is NULL"); + return (jint)AUDIO_JAVA_BAD_VALUE; + } + if (jAudioMixerAttributes == NULL) { + ALOGE("getPreferredMixerAttributes NULL AudioMixerAttributes list"); + return (jint)AUDIO_JAVA_BAD_VALUE; + } + if (!env->IsInstanceOf(jAudioMixerAttributes, gListClass)) { + ALOGE("getPreferredMixerAttributes not a list"); + return (jint)AUDIO_JAVA_BAD_VALUE; + } + + JNIAudioAttributeHelper::UniqueAaPtr paa = JNIAudioAttributeHelper::makeUnique(); + jint jStatus = JNIAudioAttributeHelper::nativeFromJava(env, jAudioAttributes, paa.get()); + if (jStatus != (jint)AUDIO_JAVA_SUCCESS) { + return jStatus; + } + + std::optional<audio_mixer_attributes_t> nMixerAttributes; + status_t status = + AudioSystem::getPreferredMixerAttributes(paa.get(), (audio_port_handle_t)portId, + &nMixerAttributes); + if (status != NO_ERROR) { + return nativeToJavaStatus(status); + } + + ScopedLocalRef<jobject> + jMixerAttributes(env, + convertAudioMixerAttributesFromNative(env, + nMixerAttributes.has_value() + ? &nMixerAttributes + .value() + : nullptr)); + if (jMixerAttributes.get() == nullptr) { + return (jint)AUDIO_JAVA_ERROR; + } + + env->CallBooleanMethod(jAudioMixerAttributes, gListMethods.add, jMixerAttributes.get()); + return AUDIO_JAVA_SUCCESS; +} + +static jint android_media_AudioSystem_clearPreferredMixerAttributes(JNIEnv *env, jobject thiz, + jobject jAudioAttributes, + jint portId, jint uid) { + ALOGV("%s", __func__); + + if (jAudioAttributes == nullptr) { + ALOGE("jAudioAttributes is NULL"); + return (jint)AUDIO_JAVA_BAD_VALUE; + } + + JNIAudioAttributeHelper::UniqueAaPtr paa = JNIAudioAttributeHelper::makeUnique(); + jint jStatus = JNIAudioAttributeHelper::nativeFromJava(env, jAudioAttributes, paa.get()); + if (jStatus != (jint)AUDIO_JAVA_SUCCESS) { + return jStatus; + } + + status_t status = + AudioSystem::clearPreferredMixerAttributes(paa.get(), (audio_port_handle_t)portId, + (uid_t)uid); + return nativeToJavaStatus(status); +} + // ---------------------------------------------------------------------------- static const JNINativeMethod gMethods[] = @@ -3104,12 +3348,23 @@ static const JNINativeMethod gMethods[] = "(Landroid/media/AudioAttributes;Landroid/media/AudioFormat;" "[Landroid/media/AudioDeviceAttributes;)Z", (void *)android_media_AudioSystem_canBeSpatialized}, + {"nativeGetSoundDose", "(Landroid/media/ISoundDoseCallback;)Landroid/os/IBinder;", + (void *)android_media_AudioSystem_nativeGetSoundDose}, {"getDirectPlaybackSupport", "(Landroid/media/AudioFormat;Landroid/media/AudioAttributes;)I", (void *)android_media_AudioSystem_getDirectPlaybackSupport}, {"getDirectProfilesForAttributes", "(Landroid/media/AudioAttributes;Ljava/util/ArrayList;)I", - (void *)android_media_AudioSystem_getDirectProfilesForAttributes}}; + (void *)android_media_AudioSystem_getDirectProfilesForAttributes}, + {"getSupportedMixerAttributes", "(ILjava/util/List;)I", + (void *)android_media_AudioSystem_getSupportedMixerAttributes}, + {"setPreferredMixerAttributes", + "(Landroid/media/AudioAttributes;IILandroid/media/AudioMixerAttributes;)I", + (void *)android_media_AudioSystem_setPreferredMixerAttributes}, + {"getPreferredMixerAttributes", "(Landroid/media/AudioAttributes;ILjava/util/List;)I", + (void *)android_media_AudioSystem_getPreferredMixerAttributes}, + {"clearPreferredMixerAttributes", "(Landroid/media/AudioAttributes;II)I", + (void *)android_media_AudioSystem_clearPreferredMixerAttributes}}; static const JNINativeMethod gEventHandlerMethods[] = { {"native_setup", @@ -3272,9 +3527,12 @@ int register_android_media_AudioSystem(JNIEnv *env) jclass audioFormatClass = FindClassOrDie(env, "android/media/AudioFormat"); gAudioFormatClass = MakeGlobalRefOrDie(env, audioFormatClass); + gAudioFormatCstor = GetMethodIDOrDie(env, audioFormatClass, "<init>", "(IIIII)V"); gAudioFormatFields.mEncoding = GetFieldIDOrDie(env, audioFormatClass, "mEncoding", "I"); gAudioFormatFields.mSampleRate = GetFieldIDOrDie(env, audioFormatClass, "mSampleRate", "I"); gAudioFormatFields.mChannelMask = GetFieldIDOrDie(env, audioFormatClass, "mChannelMask", "I"); + gAudioFormatFields.mChannelIndexMask = + GetFieldIDOrDie(env, audioFormatClass, "mChannelIndexMask", "I"); jclass audioMixingRuleClass = FindClassOrDie(env, "android/media/audiopolicy/AudioMixingRule"); gAudioMixingRuleClass = MakeGlobalRefOrDie(env, audioMixingRuleClass); @@ -3348,6 +3606,15 @@ int register_android_media_AudioSystem(JNIEnv *env) gVibratorMethods.getMaxAmplitude = GetMethodIDOrDie(env, vibratorClass, "getHapticChannelMaximumAmplitude", "()F"); + jclass audioMixerAttributesClass = FindClassOrDie(env, "android/media/AudioMixerAttributes"); + gAudioMixerAttributesClass = MakeGlobalRefOrDie(env, audioMixerAttributesClass); + gAudioMixerAttributesCstor = GetMethodIDOrDie(env, audioMixerAttributesClass, "<init>", + "(Landroid/media/AudioFormat;I)V"); + gAudioMixerAttributesField.mFormat = GetFieldIDOrDie(env, audioMixerAttributesClass, "mFormat", + "Landroid/media/AudioFormat;"); + gAudioMixerAttributesField.mMixerBehavior = + GetFieldIDOrDie(env, audioMixerAttributesClass, "mMixerBehavior", "I"); + AudioSystem::addErrorCallback(android_media_AudioSystem_error_callback); RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods)); diff --git a/core/jni/android_view_SurfaceControl.cpp b/core/jni/android_view_SurfaceControl.cpp index 1ed355577a3f..593482c9deac 100644 --- a/core/jni/android_view_SurfaceControl.cpp +++ b/core/jni/android_view_SurfaceControl.cpp @@ -1099,10 +1099,9 @@ static jobject convertDeviceProductInfoToJavaObject( connectionToSinkType); } -static jobject nativeGetStaticDisplayInfo(JNIEnv* env, jclass clazz, jobject tokenObj) { +static jobject nativeGetStaticDisplayInfo(JNIEnv* env, jclass clazz, jlong id) { ui::StaticDisplayInfo info; - if (const auto token = ibinderForJavaObject(env, tokenObj); - !token || SurfaceComposerClient::getStaticDisplayInfo(token, &info) != NO_ERROR) { + if (SurfaceComposerClient::getStaticDisplayInfo(id, &info) != NO_ERROR) { return nullptr; } @@ -1160,10 +1159,9 @@ jobject convertHdrCapabilitiesToJavaObject(JNIEnv* env, const HdrCapabilities& c capabilities.getDesiredMinLuminance()); } -static jobject nativeGetDynamicDisplayInfo(JNIEnv* env, jclass clazz, jobject tokenObj) { +static jobject nativeGetDynamicDisplayInfo(JNIEnv* env, jclass clazz, jlong displayId) { ui::DynamicDisplayInfo info; - if (const auto token = ibinderForJavaObject(env, tokenObj); - !token || SurfaceComposerClient::getDynamicDisplayInfo(token, &info) != NO_ERROR) { + if (SurfaceComposerClient::getDynamicDisplayInfoFromId(displayId, &info) != NO_ERROR) { return nullptr; } @@ -2020,10 +2018,10 @@ static const JNINativeMethod sSurfaceControlMethods[] = { {"nativeSetDisplaySize", "(JLandroid/os/IBinder;II)V", (void*)nativeSetDisplaySize }, {"nativeGetStaticDisplayInfo", - "(Landroid/os/IBinder;)Landroid/view/SurfaceControl$StaticDisplayInfo;", + "(J)Landroid/view/SurfaceControl$StaticDisplayInfo;", (void*)nativeGetStaticDisplayInfo }, {"nativeGetDynamicDisplayInfo", - "(Landroid/os/IBinder;)Landroid/view/SurfaceControl$DynamicDisplayInfo;", + "(J)Landroid/view/SurfaceControl$DynamicDisplayInfo;", (void*)nativeGetDynamicDisplayInfo }, {"nativeSetDesiredDisplayModeSpecs", "(Landroid/os/IBinder;Landroid/view/SurfaceControl$DesiredDisplayModeSpecs;)Z", diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml index fb451ddabd04..09672c2db47f 100644 --- a/core/res/AndroidManifest.xml +++ b/core/res/AndroidManifest.xml @@ -4025,7 +4025,7 @@ @hide --> <permission android:name="android.permission.INTERNAL_SYSTEM_WINDOW" - android:protectionLevel="signature" /> + android:protectionLevel="signature|module" /> <!-- Allows an application to avoid all toast rate limiting restrictions. <p>Not for use by third-party applications. @@ -4629,6 +4629,8 @@ <p>Protection level: appop --> <permission android:name="android.permission.SCHEDULE_EXACT_ALARM" + android:label="@string/permlab_schedule_exact_alarm" + android:description="@string/permdesc_schedule_exact_alarm" android:protectionLevel="normal|appop"/> <!-- Allows apps to use exact alarms just like with {@link @@ -4654,6 +4656,8 @@ lower standby bucket. --> <permission android:name="android.permission.USE_EXACT_ALARM" + android:label="@string/permlab_use_exact_alarm" + android:description="@string/permdesc_use_exact_alarm" android:protectionLevel="normal"/> <!-- Allows an application to query tablet mode state and monitor changes @@ -6772,6 +6776,14 @@ @hide --> <permission android:name="android.permission.HANDLE_QUERY_PACKAGE_RESTART" android:protectionLevel="signature" /> + + <!-- Allows low-level access to re-mapping modifier keys. + <p>Not for use by third-party applications. + @hide + @TestApi --> + <permission android:name="android.permission.REMAP_MODIFIER_KEYS" + android:protectionLevel="signature" /> + <uses-permission android:name="android.permission.HANDLE_QUERY_PACKAGE_RESTART" /> <!-- Allows financed device kiosk apps to perform actions on the Device Lock service @@ -7346,6 +7358,10 @@ android:permission="android.permission.BIND_JOB_SERVICE" > </service> + <service android:name="com.android.server.healthconnect.storage.AutoDeleteService" + android:permission="android.permission.BIND_JOB_SERVICE" > + </service> + <service android:name="com.android.server.pm.PackageManagerShellCommandDataLoader" android:exported="false"> <intent-filter> diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml index 79464937ff30..2d832bc71684 100644 --- a/core/res/res/values/attrs.xml +++ b/core/res/res/values/attrs.xml @@ -8955,9 +8955,6 @@ <!-- Flag indicating whether a recognition service can be selected as default. The default value of this flag is true. --> <attr name="selectableAsDefault" format="boolean" /> - <!-- The maximal number of recognition sessions ongoing at the same time. - The default value is 1, meaning no concurrency. --> - <attr name="maxConcurrentSessionsCount" format="integer" /> </declare-styleable> <!-- Use <code>voice-interaction-service</code> as the root tag of the XML resource that diff --git a/core/res/res/values/attrs_manifest.xml b/core/res/res/values/attrs_manifest.xml index c8a65a744de7..d4644c59fa52 100644 --- a/core/res/res/values/attrs_manifest.xml +++ b/core/res/res/values/attrs_manifest.xml @@ -294,6 +294,9 @@ <!-- Additional flag from base permission type: this permission can be automatically granted to the system app predictor --> <flag name="appPredictor" value="0x200000" /> + <!-- Additional flag from base permission type: this permission can also be granted if the + requesting application is included in the mainline module}. --> + <flag name="module" value="0x400000" /> <!-- Additional flag from base permission type: this permission can be automatically granted to the system companion device manager service --> <flag name="companion" value="0x800000" /> diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml index 9a585a194ed1..cead34b6231c 100644 --- a/core/res/res/values/config.xml +++ b/core/res/res/values/config.xml @@ -1371,30 +1371,6 @@ Must be in the range specified by minimum and maximum. --> <item name="config_screenBrightnessSettingDefaultFloat" format="float" type="dimen">-2</item> - <!-- Note: This setting is deprecated, please use - config_screenBrightnessSettingForVrDefaultFloat instead --> - <integer name="config_screenBrightnessForVrSettingDefault">86</integer> - - <!-- Note: This setting is deprecated, please use - config_screenBrightnessSettingForVrMinimumFloat instead --> - <integer name="config_screenBrightnessForVrSettingMinimum">79</integer> - - <!-- Note: This setting is deprecated, please use - config_screenBrightnessSettingForVrMaximumFloat instead --> - <integer name="config_screenBrightnessForVrSettingMaximum">255</integer> - - <!-- Default screen brightness for VR setting as a float. - Equivalent to 86/255--> - <item name="config_screenBrightnessSettingForVrDefaultFloat" format="float" type="dimen">0.33464</item> - - <!-- Minimum screen brightness setting allowed for VR. Device panels start increasing pulse - width as brightness decreases below this threshold as float. - Equivalent to 79/255 --> - <item name="config_screenBrightnessSettingForVrMinimumFloat" format="float" type="dimen">0.307087</item> - - <!-- Maximum screen brightness setting allowed for VR as float. --> - <item name="config_screenBrightnessSettingForVrMaximumFloat" format="float" type="dimen">1.0</item> - <!-- Screen brightness used to dim the screen while dozing in a very low power state. May be less than the minimum allowed brightness setting that can be set by the user. --> @@ -2507,6 +2483,10 @@ states. --> <bool name="config_dozeAlwaysOnDisplayAvailable">false</bool> + <!-- Control whether the pickup gesture is enabled by default. This value will be used + during initialization when the setting is still null. --> + <bool name="config_dozePickupGestureEnabled">true</bool> + <!-- Control whether the always on display mode is enabled by default. This value will be used during initialization when the setting is still null. --> <bool name="config_dozeAlwaysOnEnabled">true</bool> diff --git a/core/res/res/values/public-staging.xml b/core/res/res/values/public-staging.xml index a9bec7a9fe28..90141e57ce8d 100644 --- a/core/res/res/values/public-staging.xml +++ b/core/res/res/values/public-staging.xml @@ -117,7 +117,7 @@ <public name="accessibilityDataPrivate" /> <public name="enableTextStylingShortcuts" /> <public name="requiredDisplayCategory"/> - <public name="maxConcurrentSessionsCount" /> + <public name="removed_maxConcurrentSessionsCount" /> </staging-public-group> <staging-public-group type="id" first-id="0x01cd0000"> diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml index 39012ae20e0a..18a5c72b0892 100644 --- a/core/res/res/values/strings.xml +++ b/core/res/res/values/strings.xml @@ -1133,6 +1133,16 @@ <string name="permdesc_useDataInBackground">This app can use data in the background. This may increase data usage.</string> <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. --> + <string name="permlab_schedule_exact_alarm">Schedule precisely timed actions</string> + <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. --> + <string name="permdesc_schedule_exact_alarm">This app can schedule work to happen at a desired time in the future. This also means that the app can run when you\u2019re not actively using the device.</string> + + <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. --> + <string name="permlab_use_exact_alarm">Schedule alarms or event reminders</string> + <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. --> + <string name="permdesc_use_exact_alarm">This app can schedule actions like alarms and reminders to notify you at a desired time in the future.</string> + + <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. --> <string name="permlab_persistentActivity">make app always run</string> <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. --> <string name="permdesc_persistentActivity" product="tablet">Allows the app to make parts of itself persistent in memory. This can limit memory available to other apps slowing down the tablet.</string> diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml index ace7e4c31b4a..cd0024feae7e 100644 --- a/core/res/res/values/symbols.xml +++ b/core/res/res/values/symbols.xml @@ -2062,12 +2062,6 @@ <java-symbol type="integer" name="config_screenBrightnessSettingMinimum" /> <java-symbol type="integer" name="config_screenBrightnessSettingMaximum" /> <java-symbol type="integer" name="config_screenBrightnessSettingDefault" /> - <java-symbol type="integer" name="config_screenBrightnessForVrSettingDefault" /> - <java-symbol type="integer" name="config_screenBrightnessForVrSettingMaximum" /> - <java-symbol type="integer" name="config_screenBrightnessForVrSettingMinimum" /> - <java-symbol type="dimen" name="config_screenBrightnessSettingForVrMinimumFloat" /> - <java-symbol type="dimen" name="config_screenBrightnessSettingForVrMaximumFloat" /> - <java-symbol type="dimen" name="config_screenBrightnessSettingForVrDefaultFloat" /> <java-symbol type="dimen" name="config_screenBrightnessSettingMinimumFloat" /> <java-symbol type="dimen" name="config_screenBrightnessSettingMaximumFloat" /> <java-symbol type="dimen" name="config_screenBrightnessSettingDefaultFloat" /> @@ -3826,6 +3820,7 @@ <java-symbol type="string" name="config_cameraShutterSound" /> <java-symbol type="integer" name="config_autoGroupAtCount" /> <java-symbol type="bool" name="config_dozeAlwaysOnDisplayAvailable" /> + <java-symbol type="bool" name="config_dozePickupGestureEnabled" /> <java-symbol type="bool" name="config_dozeAlwaysOnEnabled" /> <java-symbol type="bool" name="config_dozeSupportsAodWallpaper" /> <java-symbol type="bool" name="config_displayBlanksAfterDoze" /> diff --git a/core/res/res/xml/bookmarks.xml b/core/res/res/xml/bookmarks.xml index 454f4562a239..3087aaaefd41 100644 --- a/core/res/res/xml/bookmarks.xml +++ b/core/res/res/xml/bookmarks.xml @@ -19,23 +19,20 @@ Bookmarks for vendor apps should be added to a bookmarks resource overlay; not here. Typical shortcuts (not necessarily defined here): - 'a': Calculator 'b': Browser 'c': Contacts 'e': Email 'g': GMail - 'l': Calendar + 'k': Calendar 'm': Maps 'p': Music 's': SMS 't': Talk + 'u': Calculator 'y': YouTube --> <bookmarks> <bookmark - category="android.intent.category.APP_CALCULATOR" - shortcut="a" /> - <bookmark category="android.intent.category.APP_BROWSER" shortcut="b" /> <bookmark @@ -46,7 +43,7 @@ shortcut="e" /> <bookmark category="android.intent.category.APP_CALENDAR" - shortcut="l" /> + shortcut="k" /> <bookmark category="android.intent.category.APP_MAPS" shortcut="m" /> @@ -56,4 +53,7 @@ <bookmark category="android.intent.category.APP_MESSAGING" shortcut="s" /> + <bookmark + category="android.intent.category.APP_CALCULATOR" + shortcut="u" /> </bookmarks> diff --git a/core/tests/GameManagerTests/src/android/app/GameModeConfigurationTest.java b/core/tests/GameManagerTests/src/android/app/GameModeConfigurationTest.java index 7462bcf67480..b3e74d3f553a 100644 --- a/core/tests/GameManagerTests/src/android/app/GameModeConfigurationTest.java +++ b/core/tests/GameManagerTests/src/android/app/GameModeConfigurationTest.java @@ -77,10 +77,10 @@ public class GameModeConfigurationTest { } @Test - public void testToBuilder() { + public void testBuilderConstructor() { GameModeConfiguration config = new GameModeConfiguration .Builder().setFpsOverride(40).setScalingFactor(0.5f).build(); - GameModeConfiguration newConfig = config.toBuilder().build(); + GameModeConfiguration newConfig = new GameModeConfiguration.Builder(config).build(); assertEquals(config, newConfig); } diff --git a/core/tests/GameManagerTests/src/android/app/GameModeInfoTest.java b/core/tests/GameManagerTests/src/android/app/GameModeInfoTest.java index ecd9b6b8143a..5fa60849dbfc 100644 --- a/core/tests/GameManagerTests/src/android/app/GameModeInfoTest.java +++ b/core/tests/GameManagerTests/src/android/app/GameModeInfoTest.java @@ -43,7 +43,7 @@ public class GameModeInfoTest { int[] availableGameModes = new int[]{GameManager.GAME_MODE_STANDARD, GameManager.GAME_MODE_PERFORMANCE, GameManager.GAME_MODE_BATTERY, GameManager.GAME_MODE_CUSTOM}; - int[] optedInGameModes = new int[]{GameManager.GAME_MODE_PERFORMANCE}; + int[] overriddenGameModes = new int[]{GameManager.GAME_MODE_PERFORMANCE}; GameModeConfiguration batteryConfig = new GameModeConfiguration .Builder().setFpsOverride(40).setScalingFactor(0.5f).build(); GameModeConfiguration performanceConfig = new GameModeConfiguration @@ -51,7 +51,7 @@ public class GameModeInfoTest { GameModeInfo gameModeInfo = new GameModeInfo.Builder() .setActiveGameMode(activeGameMode) .setAvailableGameModes(availableGameModes) - .setOptedInGameModes(optedInGameModes) + .setOverriddenGameModes(overriddenGameModes) .setDownscalingAllowed(true) .setFpsOverrideAllowed(false) .setGameModeConfiguration(GameManager.GAME_MODE_BATTERY, batteryConfig) @@ -59,7 +59,7 @@ public class GameModeInfoTest { .build(); assertArrayEquals(availableGameModes, gameModeInfo.getAvailableGameModes()); - assertArrayEquals(optedInGameModes, gameModeInfo.getOptedInGameModes()); + assertArrayEquals(overriddenGameModes, gameModeInfo.getOverriddenGameModes()); assertEquals(activeGameMode, gameModeInfo.getActiveGameMode()); assertTrue(gameModeInfo.isDownscalingAllowed()); assertFalse(gameModeInfo.isFpsOverrideAllowed()); @@ -75,8 +75,8 @@ public class GameModeInfoTest { assertEquals(gameModeInfo.getActiveGameMode(), newGameModeInfo.getActiveGameMode()); assertArrayEquals(gameModeInfo.getAvailableGameModes(), newGameModeInfo.getAvailableGameModes()); - assertArrayEquals(gameModeInfo.getOptedInGameModes(), - newGameModeInfo.getOptedInGameModes()); + assertArrayEquals(gameModeInfo.getOverriddenGameModes(), + newGameModeInfo.getOverriddenGameModes()); assertTrue(newGameModeInfo.isDownscalingAllowed()); assertFalse(newGameModeInfo.isFpsOverrideAllowed()); assertEquals(performanceConfig, diff --git a/data/etc/privapp-permissions-platform.xml b/data/etc/privapp-permissions-platform.xml index 3e2b71f18b75..e0b2e8a0aa29 100644 --- a/data/etc/privapp-permissions-platform.xml +++ b/data/etc/privapp-permissions-platform.xml @@ -232,6 +232,7 @@ applications that come with the platform <privapp-permissions package="com.android.shell"> <!-- Needed for test only --> + <permission name="android.permission.MANAGE_HEALTH_DATA"/> <permission name="android.permission.LAUNCH_DEVICE_MANAGER_SETUP"/> <permission name="android.permission.MODIFY_DAY_NIGHT_MODE"/> <permission name="android.permission.ACCESS_LOWPAN_STATE"/> diff --git a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/JetpackTaskFragmentOrganizer.java b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/JetpackTaskFragmentOrganizer.java index d7d43aa19757..b910287aa535 100644 --- a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/JetpackTaskFragmentOrganizer.java +++ b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/JetpackTaskFragmentOrganizer.java @@ -133,8 +133,18 @@ class JetpackTaskFragmentOrganizer extends TaskFragmentOrganizer { } // Create a TaskFragment for the secondary activity. - createTaskFragmentAndStartActivity(wct, secondaryFragmentToken, ownerToken, - secondaryFragmentBounds, windowingMode, activityIntent, + final TaskFragmentCreationParams fragmentOptions = new TaskFragmentCreationParams.Builder( + getOrganizerToken(), secondaryFragmentToken, ownerToken) + .setInitialBounds(secondaryFragmentBounds) + .setWindowingMode(windowingMode) + // Make sure to set the paired fragment token so that the new TaskFragment will be + // positioned right above the paired TaskFragment. + // This is needed in case we need to launch a placeholder Activity to split below a + // transparent always-expand Activity. + .setPairedPrimaryFragmentToken(launchingFragmentToken) + .build(); + createTaskFragment(wct, fragmentOptions); + wct.startActivityInTaskFragment(secondaryFragmentToken, ownerToken, activityIntent, activityOptions); // Set adjacent to each other so that the containers below will be invisible. @@ -173,8 +183,21 @@ class JetpackTaskFragmentOrganizer extends TaskFragmentOrganizer { */ void createTaskFragment(@NonNull WindowContainerTransaction wct, @NonNull IBinder fragmentToken, @NonNull IBinder ownerToken, @NonNull Rect bounds, @WindowingMode int windowingMode) { - final TaskFragmentCreationParams fragmentOptions = - createFragmentOptions(fragmentToken, ownerToken, bounds, windowingMode); + final TaskFragmentCreationParams fragmentOptions = new TaskFragmentCreationParams.Builder( + getOrganizerToken(), fragmentToken, ownerToken) + .setInitialBounds(bounds) + .setWindowingMode(windowingMode) + .build(); + createTaskFragment(wct, fragmentOptions); + } + + void createTaskFragment(@NonNull WindowContainerTransaction wct, + @NonNull TaskFragmentCreationParams fragmentOptions) { + if (mFragmentInfos.containsKey(fragmentOptions.getFragmentToken())) { + throw new IllegalArgumentException( + "There is an existing TaskFragment with fragmentToken=" + + fragmentOptions.getFragmentToken()); + } wct.createTaskFragment(fragmentOptions); } @@ -189,18 +212,6 @@ class JetpackTaskFragmentOrganizer extends TaskFragmentOrganizer { wct.reparentActivityToTaskFragment(fragmentToken, activity.getActivityToken()); } - /** - * @param ownerToken The token of the activity that creates this task fragment. It does not - * have to be a child of this task fragment, but must belong to the same task. - */ - private void createTaskFragmentAndStartActivity(@NonNull WindowContainerTransaction wct, - @NonNull IBinder fragmentToken, @NonNull IBinder ownerToken, @NonNull Rect bounds, - @WindowingMode int windowingMode, @NonNull Intent activityIntent, - @Nullable Bundle activityOptions) { - createTaskFragment(wct, fragmentToken, ownerToken, bounds, windowingMode); - wct.startActivityInTaskFragment(fragmentToken, ownerToken, activityIntent, activityOptions); - } - void setAdjacentTaskFragments(@NonNull WindowContainerTransaction wct, @NonNull IBinder primary, @Nullable IBinder secondary, @Nullable SplitRule splitRule) { WindowContainerTransaction.TaskFragmentAdjacentParams adjacentParams = null; @@ -238,22 +249,6 @@ class JetpackTaskFragmentOrganizer extends TaskFragmentOrganizer { wct.setCompanionTaskFragment(secondary, finishSecondaryWithPrimary ? primary : null); } - TaskFragmentCreationParams createFragmentOptions(@NonNull IBinder fragmentToken, - @NonNull IBinder ownerToken, @NonNull Rect bounds, @WindowingMode int windowingMode) { - if (mFragmentInfos.containsKey(fragmentToken)) { - throw new IllegalArgumentException( - "There is an existing TaskFragment with fragmentToken=" + fragmentToken); - } - - return new TaskFragmentCreationParams.Builder( - getOrganizerToken(), - fragmentToken, - ownerToken) - .setInitialBounds(bounds) - .setWindowingMode(windowingMode) - .build(); - } - void resizeTaskFragment(@NonNull WindowContainerTransaction wct, @NonNull IBinder fragmentToken, @Nullable Rect bounds) { if (!mFragmentInfos.containsKey(fragmentToken)) { diff --git a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitController.java b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitController.java index 6f9a4ff8188a..5afb1d11ad45 100644 --- a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitController.java +++ b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitController.java @@ -20,11 +20,11 @@ import static android.app.ActivityManager.START_SUCCESS; import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED; import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED; import static android.view.Display.DEFAULT_DISPLAY; -import static android.view.WindowManager.TRANSIT_CLOSE; -import static android.view.WindowManager.TRANSIT_OPEN; import static android.window.TaskFragmentOrganizer.KEY_ERROR_CALLBACK_OP_TYPE; import static android.window.TaskFragmentOrganizer.KEY_ERROR_CALLBACK_TASK_FRAGMENT_INFO; import static android.window.TaskFragmentOrganizer.KEY_ERROR_CALLBACK_THROWABLE; +import static android.window.TaskFragmentOrganizer.TASK_FRAGMENT_TRANSIT_CLOSE; +import static android.window.TaskFragmentOrganizer.TASK_FRAGMENT_TRANSIT_OPEN; import static android.window.TaskFragmentTransaction.TYPE_ACTIVITY_REPARENTED_TO_TASK; import static android.window.TaskFragmentTransaction.TYPE_TASK_FRAGMENT_APPEARED; import static android.window.TaskFragmentTransaction.TYPE_TASK_FRAGMENT_ERROR; @@ -340,7 +340,8 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen container.setInfo(wct, taskFragmentInfo); if (container.isFinished()) { - mTransactionManager.getCurrentTransactionRecord().setOriginType(TRANSIT_CLOSE); + mTransactionManager.getCurrentTransactionRecord() + .setOriginType(TASK_FRAGMENT_TRANSIT_CLOSE); mPresenter.cleanupContainer(wct, container, false /* shouldFinishDependent */); } else { // Update with the latest Task configuration. @@ -376,22 +377,27 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen // Do not finish the dependents if the last activity is reparented to PiP. // Instead, the original split should be cleanup, and the dependent may be // expanded to fullscreen. - mTransactionManager.getCurrentTransactionRecord().setOriginType(TRANSIT_CLOSE); + mTransactionManager.getCurrentTransactionRecord() + .setOriginType(TASK_FRAGMENT_TRANSIT_CLOSE); cleanupForEnterPip(wct, container); mPresenter.cleanupContainer(wct, container, false /* shouldFinishDependent */); } else if (taskFragmentInfo.isTaskClearedForReuse()) { // Do not finish the dependents if this TaskFragment was cleared due to // launching activity in the Task. - mTransactionManager.getCurrentTransactionRecord().setOriginType(TRANSIT_CLOSE); + mTransactionManager.getCurrentTransactionRecord() + .setOriginType(TASK_FRAGMENT_TRANSIT_CLOSE); mPresenter.cleanupContainer(wct, container, false /* shouldFinishDependent */); } else if (taskFragmentInfo.isClearedForReorderActivityToFront()) { // Do not finish the dependents if this TaskFragment was cleared to reorder // the launching Activity to front of the Task. + mTransactionManager.getCurrentTransactionRecord() + .setOriginType(TASK_FRAGMENT_TRANSIT_CLOSE); mPresenter.cleanupContainer(wct, container, false /* shouldFinishDependent */); } else if (!container.isWaitingActivityAppear()) { // Do not finish the container before the expected activity appear until // timeout. - mTransactionManager.getCurrentTransactionRecord().setOriginType(TRANSIT_CLOSE); + mTransactionManager.getCurrentTransactionRecord() + .setOriginType(TASK_FRAGMENT_TRANSIT_CLOSE); mPresenter.cleanupContainer(wct, container, true /* shouldFinishDependent */); } } else if (wasInPip && isInPip) { @@ -585,7 +591,8 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen container.setInfo(wct, taskFragmentInfo); container.clearPendingAppearedActivities(); if (container.isEmpty()) { - mTransactionManager.getCurrentTransactionRecord().setOriginType(TRANSIT_CLOSE); + mTransactionManager.getCurrentTransactionRecord() + .setOriginType(TASK_FRAGMENT_TRANSIT_CLOSE); mPresenter.cleanupContainer(wct, container, false /* shouldFinishDependent */); } break; @@ -1000,7 +1007,8 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen @GuardedBy("mLock") void onTaskFragmentAppearEmptyTimeout(@NonNull WindowContainerTransaction wct, @NonNull TaskFragmentContainer container) { - mTransactionManager.getCurrentTransactionRecord().setOriginType(TRANSIT_CLOSE); + mTransactionManager.getCurrentTransactionRecord() + .setOriginType(TASK_FRAGMENT_TRANSIT_CLOSE); mPresenter.cleanupContainer(wct, container, false /* shouldFinishDependent */); } @@ -1218,14 +1226,14 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen TaskFragmentContainer newContainer(@NonNull Activity pendingAppearedActivity, @NonNull Activity activityInTask, int taskId) { return newContainer(pendingAppearedActivity, null /* pendingAppearedIntent */, - activityInTask, taskId); + activityInTask, taskId, null /* pairedPrimaryContainer */); } @GuardedBy("mLock") TaskFragmentContainer newContainer(@NonNull Intent pendingAppearedIntent, @NonNull Activity activityInTask, int taskId) { return newContainer(null /* pendingAppearedActivity */, pendingAppearedIntent, - activityInTask, taskId); + activityInTask, taskId, null /* pairedPrimaryContainer */); } /** @@ -1237,10 +1245,13 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen * @param activityInTask activity in the same Task so that we can get the Task bounds * if needed. * @param taskId parent Task of the new TaskFragment. + * @param pairedPrimaryContainer the paired primary {@link TaskFragmentContainer}. When it is + * set, the new container will be added right above it. */ @GuardedBy("mLock") TaskFragmentContainer newContainer(@Nullable Activity pendingAppearedActivity, - @Nullable Intent pendingAppearedIntent, @NonNull Activity activityInTask, int taskId) { + @Nullable Intent pendingAppearedIntent, @NonNull Activity activityInTask, int taskId, + @Nullable TaskFragmentContainer pairedPrimaryContainer) { if (activityInTask == null) { throw new IllegalArgumentException("activityInTask must not be null,"); } @@ -1249,7 +1260,7 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen } final TaskContainer taskContainer = mTaskContainers.get(taskId); final TaskFragmentContainer container = new TaskFragmentContainer(pendingAppearedActivity, - pendingAppearedIntent, taskContainer, this); + pendingAppearedIntent, taskContainer, this, pairedPrimaryContainer); return container; } @@ -1563,7 +1574,8 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen // (not resumed yet). if (isOnCreated || primaryActivity.isResumed()) { // Only set trigger type if the launch happens in foreground. - mTransactionManager.getCurrentTransactionRecord().setOriginType(TRANSIT_OPEN); + mTransactionManager.getCurrentTransactionRecord() + .setOriginType(TASK_FRAGMENT_TRANSIT_OPEN); return null; } final ActivityOptions options = ActivityOptions.makeBasic(); @@ -1591,7 +1603,8 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen return false; } - mTransactionManager.getCurrentTransactionRecord().setOriginType(TRANSIT_CLOSE); + mTransactionManager.getCurrentTransactionRecord() + .setOriginType(TASK_FRAGMENT_TRANSIT_CLOSE); mPresenter.cleanupContainer(wct, splitContainer.getSecondaryContainer(), false /* shouldFinishDependent */); return true; @@ -1891,7 +1904,7 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen synchronized (mLock) { final TransactionRecord transactionRecord = mTransactionManager .startNewTransaction(); - transactionRecord.setOriginType(TRANSIT_OPEN); + transactionRecord.setOriginType(TASK_FRAGMENT_TRANSIT_OPEN); SplitController.this.onActivityCreated(transactionRecord.getTransaction(), activity); // The WCT should be applied and merged to the activity launch transition. @@ -1980,7 +1993,7 @@ public class SplitController implements JetpackTaskFragmentOrganizer.TaskFragmen synchronized (mLock) { final TransactionRecord transactionRecord = mTransactionManager .startNewTransaction(); - transactionRecord.setOriginType(TRANSIT_OPEN); + transactionRecord.setOriginType(TASK_FRAGMENT_TRANSIT_OPEN); final WindowContainerTransaction wct = transactionRecord.getTransaction(); final TaskFragmentContainer launchedInTaskFragment; if (launchingActivity != null) { diff --git a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitPresenter.java b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitPresenter.java index 5395fb2ef5ed..47253d388f0d 100644 --- a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitPresenter.java +++ b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/SplitPresenter.java @@ -36,6 +36,7 @@ import android.util.Size; import android.view.View; import android.view.WindowInsets; import android.view.WindowMetrics; +import android.window.TaskFragmentCreationParams; import android.window.WindowContainerTransaction; import androidx.annotation.GuardedBy; @@ -307,10 +308,13 @@ class SplitPresenter extends JetpackTaskFragmentOrganizer { } final int taskId = primaryContainer.getTaskId(); - final TaskFragmentContainer secondaryContainer = mController.newContainer(activityIntent, - launchingActivity, taskId); - final int windowingMode = mController.getTaskContainer(taskId) - .getWindowingModeForSplitTaskFragment(primaryRectBounds); + final TaskFragmentContainer secondaryContainer = mController.newContainer( + null /* pendingAppearedActivity */, activityIntent, launchingActivity, taskId, + // Pass in the primary container to make sure it is added right above the primary. + primaryContainer); + final TaskContainer taskContainer = mController.getTaskContainer(taskId); + final int windowingMode = taskContainer.getWindowingModeForSplitTaskFragment( + primaryRectBounds); mController.registerSplit(wct, primaryContainer, launchingActivity, secondaryContainer, rule, splitAttributes); startActivityToSide(wct, primaryContainer.getTaskFragmentToken(), primaryRectBounds, @@ -412,17 +416,18 @@ class SplitPresenter extends JetpackTaskFragmentOrganizer { } @Override - void createTaskFragment(@NonNull WindowContainerTransaction wct, @NonNull IBinder fragmentToken, - @NonNull IBinder ownerToken, @NonNull Rect bounds, @WindowingMode int windowingMode) { - final TaskFragmentContainer container = mController.getContainer(fragmentToken); + void createTaskFragment(@NonNull WindowContainerTransaction wct, + @NonNull TaskFragmentCreationParams fragmentOptions) { + final TaskFragmentContainer container = mController.getContainer( + fragmentOptions.getFragmentToken()); if (container == null) { throw new IllegalStateException( "Creating a task fragment that is not registered with controller."); } - container.setLastRequestedBounds(bounds); - container.setLastRequestedWindowingMode(windowingMode); - super.createTaskFragment(wct, fragmentToken, ownerToken, bounds, windowingMode); + container.setLastRequestedBounds(fragmentOptions.getInitialBounds()); + container.setLastRequestedWindowingMode(fragmentOptions.getWindowingMode()); + super.createTaskFragment(wct, fragmentOptions); } @Override diff --git a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentAnimationRunner.java b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentAnimationRunner.java index 322f85449450..dcc12ac07589 100644 --- a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentAnimationRunner.java +++ b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentAnimationRunner.java @@ -19,6 +19,7 @@ package androidx.window.extensions.embedding; import static android.os.Process.THREAD_PRIORITY_DISPLAY; import static android.view.RemoteAnimationTarget.MODE_CHANGING; import static android.view.RemoteAnimationTarget.MODE_CLOSING; +import static android.view.RemoteAnimationTarget.MODE_OPENING; import static android.view.WindowManager.TRANSIT_OLD_ACTIVITY_CLOSE; import static android.view.WindowManager.TRANSIT_OLD_ACTIVITY_OPEN; import static android.view.WindowManager.TRANSIT_OLD_TASK_FRAGMENT_CHANGE; @@ -253,6 +254,10 @@ class TaskFragmentAnimationRunner extends IRemoteAnimationRunner.Stub { @NonNull private List<TaskFragmentAnimationAdapter> createChangeAnimationAdapters( @NonNull RemoteAnimationTarget[] targets) { + if (shouldUseJumpCutForChangeAnimation(targets)) { + return new ArrayList<>(); + } + final List<TaskFragmentAnimationAdapter> adapters = new ArrayList<>(); for (RemoteAnimationTarget target : targets) { if (target.mode == MODE_CHANGING) { @@ -282,4 +287,24 @@ class TaskFragmentAnimationRunner extends IRemoteAnimationRunner.Stub { } return adapters; } + + /** + * Whether we should use jump cut for the change transition. + * This normally happens when opening a new secondary with the existing primary using a + * different split layout. This can be complicated, like from horizontal to vertical split with + * new split pairs. + * Uses a jump cut animation to simplify. + */ + private boolean shouldUseJumpCutForChangeAnimation(@NonNull RemoteAnimationTarget[] targets) { + boolean hasOpeningWindow = false; + boolean hasClosingWindow = false; + for (RemoteAnimationTarget target : targets) { + if (target.hasAnimatingParent) { + continue; + } + hasOpeningWindow |= target.mode == MODE_OPENING; + hasClosingWindow |= target.mode == MODE_CLOSING; + } + return hasOpeningWindow && hasClosingWindow; + } } diff --git a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentContainer.java b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentContainer.java index e31792ad718f..fcf0ac78af38 100644 --- a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentContainer.java +++ b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TaskFragmentContainer.java @@ -118,10 +118,12 @@ class TaskFragmentContainer { /** * Creates a container with an existing activity that will be re-parented to it in a window * container transaction. + * @param pairedPrimaryContainer when it is set, the new container will be add right above it */ TaskFragmentContainer(@Nullable Activity pendingAppearedActivity, @Nullable Intent pendingAppearedIntent, @NonNull TaskContainer taskContainer, - @NonNull SplitController controller) { + @NonNull SplitController controller, + @Nullable TaskFragmentContainer pairedPrimaryContainer) { if ((pendingAppearedActivity == null && pendingAppearedIntent == null) || (pendingAppearedActivity != null && pendingAppearedIntent != null)) { throw new IllegalArgumentException( @@ -130,7 +132,16 @@ class TaskFragmentContainer { mController = controller; mToken = new Binder("TaskFragmentContainer"); mTaskContainer = taskContainer; - taskContainer.mContainers.add(this); + if (pairedPrimaryContainer != null) { + if (pairedPrimaryContainer.getTaskContainer() != taskContainer) { + throw new IllegalArgumentException( + "pairedPrimaryContainer must be in the same Task"); + } + final int primaryIndex = taskContainer.mContainers.indexOf(pairedPrimaryContainer); + taskContainer.mContainers.add(primaryIndex + 1, this); + } else { + taskContainer.mContainers.add(this); + } if (pendingAppearedActivity != null) { addPendingAppearedActivity(pendingAppearedActivity); } diff --git a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TransactionManager.java b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TransactionManager.java index 0071fea41aa8..396956e56bb5 100644 --- a/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TransactionManager.java +++ b/libs/WindowManager/Jetpack/src/androidx/window/extensions/embedding/TransactionManager.java @@ -16,12 +16,12 @@ package androidx.window.extensions.embedding; -import static android.view.WindowManager.TRANSIT_CHANGE; -import static android.view.WindowManager.TRANSIT_NONE; +import static android.window.TaskFragmentOrganizer.TASK_FRAGMENT_TRANSIT_CHANGE; +import static android.window.TaskFragmentOrganizer.TASK_FRAGMENT_TRANSIT_NONE; import android.os.IBinder; -import android.view.WindowManager.TransitionType; import android.window.TaskFragmentOrganizer; +import android.window.TaskFragmentOrganizer.TaskFragmentTransitionType; import android.window.WindowContainerTransaction; import androidx.annotation.NonNull; @@ -122,8 +122,8 @@ class TransactionManager { * @see #setOriginType(int) * @see #getTransactionTransitionType() */ - @TransitionType - private int mOriginType = TRANSIT_NONE; + @TaskFragmentTransitionType + private int mOriginType = TASK_FRAGMENT_TRANSIT_NONE; TransactionRecord(@Nullable IBinder taskFragmentTransactionToken) { mTaskFragmentTransactionToken = taskFragmentTransactionToken; @@ -136,12 +136,12 @@ class TransactionManager { } /** - * Sets the {@link TransitionType} that triggers this transaction. If there are multiple - * calls, only the first call will be respected as the "origin" type. + * Sets the {@link TaskFragmentTransitionType} that triggers this transaction. If there are + * multiple calls, only the first call will be respected as the "origin" type. */ - void setOriginType(@TransitionType int type) { + void setOriginType(@TaskFragmentTransitionType int type) { ensureCurrentTransaction(); - if (mOriginType != TRANSIT_NONE) { + if (mOriginType != TASK_FRAGMENT_TRANSIT_NONE) { // Skip if the origin type has already been set. return; } @@ -188,14 +188,16 @@ class TransactionManager { } /** - * Gets the {@link TransitionType} that we will request transition with for the + * Gets the {@link TaskFragmentTransitionType} that we will request transition with for the * current {@link WindowContainerTransaction}. */ @VisibleForTesting - @TransitionType + @TaskFragmentTransitionType int getTransactionTransitionType() { - // Use TRANSIT_CHANGE as default if there is not opening/closing window. - return mOriginType != TRANSIT_NONE ? mOriginType : TRANSIT_CHANGE; + // Use TASK_FRAGMENT_TRANSIT_CHANGE as default if there is not opening/closing window. + return mOriginType != TASK_FRAGMENT_TRANSIT_NONE + ? mOriginType + : TASK_FRAGMENT_TRANSIT_CHANGE; } } } diff --git a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/JetpackTaskFragmentOrganizerTest.java b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/JetpackTaskFragmentOrganizerTest.java index 31aa09c902b1..bbb454d31c38 100644 --- a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/JetpackTaskFragmentOrganizerTest.java +++ b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/JetpackTaskFragmentOrganizerTest.java @@ -102,7 +102,7 @@ public class JetpackTaskFragmentOrganizerTest { public void testExpandTaskFragment() { final TaskContainer taskContainer = createTestTaskContainer(); final TaskFragmentContainer container = new TaskFragmentContainer(null /* activity */, - new Intent(), taskContainer, mSplitController); + new Intent(), taskContainer, mSplitController, null /* pairedPrimaryContainer */); final TaskFragmentInfo info = createMockInfo(container); mOrganizer.mFragmentInfos.put(container.getTaskFragmentToken(), info); container.setInfo(mTransaction, info); diff --git a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/SplitControllerTest.java b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/SplitControllerTest.java index 221c7640ef0b..6725dfdb94e8 100644 --- a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/SplitControllerTest.java +++ b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/SplitControllerTest.java @@ -169,7 +169,7 @@ public class SplitControllerTest { final TaskContainer taskContainer = createTestTaskContainer(); // tf1 has no running activity so is not active. final TaskFragmentContainer tf1 = new TaskFragmentContainer(null /* activity */, - new Intent(), taskContainer, mSplitController); + new Intent(), taskContainer, mSplitController, null /* pairedPrimaryContainer */); // tf2 has running activity so is active. final TaskFragmentContainer tf2 = mock(TaskFragmentContainer.class); doReturn(1).when(tf2).getRunningActivityCount(); @@ -375,7 +375,7 @@ public class SplitControllerTest { final Intent intent = new Intent(); final TaskContainer taskContainer = createTestTaskContainer(); final TaskFragmentContainer container = new TaskFragmentContainer(null /* activity */, - intent, taskContainer, mSplitController); + intent, taskContainer, mSplitController, null /* pairedPrimaryContainer */); final SplitController.ActivityStartMonitor monitor = mSplitController.getActivityStartMonitor(); @@ -609,7 +609,7 @@ public class SplitControllerTest { false /* isOnReparent */); assertFalse(result); - verify(mSplitController, never()).newContainer(any(), any(), any(), anyInt()); + verify(mSplitController, never()).newContainer(any(), any(), any(), anyInt(), any()); } @Test @@ -771,7 +771,7 @@ public class SplitControllerTest { false /* isOnReparent */); assertTrue(result); - verify(mSplitController, never()).newContainer(any(), any(), any(), anyInt()); + verify(mSplitController, never()).newContainer(any(), any(), any(), anyInt(), any()); verify(mSplitController, never()).registerSplit(any(), any(), any(), any(), any(), any()); } @@ -813,7 +813,7 @@ public class SplitControllerTest { false /* isOnReparent */); assertTrue(result); - verify(mSplitController, never()).newContainer(any(), any(), any(), anyInt()); + verify(mSplitController, never()).newContainer(any(), any(), any(), anyInt(), any()); verify(mSplitController, never()).registerSplit(any(), any(), any(), any(), any(), any()); } diff --git a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskContainerTest.java b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskContainerTest.java index 95328ce700e3..13e709271221 100644 --- a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskContainerTest.java +++ b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskContainerTest.java @@ -122,7 +122,7 @@ public class TaskContainerTest { assertTrue(taskContainer.isEmpty()); final TaskFragmentContainer tf = new TaskFragmentContainer(null /* activity */, - new Intent(), taskContainer, mController); + new Intent(), taskContainer, mController, null /* pairedPrimaryContainer */); assertFalse(taskContainer.isEmpty()); @@ -138,11 +138,11 @@ public class TaskContainerTest { assertNull(taskContainer.getTopTaskFragmentContainer()); final TaskFragmentContainer tf0 = new TaskFragmentContainer(null /* activity */, - new Intent(), taskContainer, mController); + new Intent(), taskContainer, mController, null /* pairedPrimaryContainer */); assertEquals(tf0, taskContainer.getTopTaskFragmentContainer()); final TaskFragmentContainer tf1 = new TaskFragmentContainer(null /* activity */, - new Intent(), taskContainer, mController); + new Intent(), taskContainer, mController, null /* pairedPrimaryContainer */); assertEquals(tf1, taskContainer.getTopTaskFragmentContainer()); } diff --git a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskFragmentContainerTest.java b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskFragmentContainerTest.java index 99f56b4ceb17..5c3ba72e2361 100644 --- a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskFragmentContainerTest.java +++ b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TaskFragmentContainerTest.java @@ -94,18 +94,21 @@ public class TaskFragmentContainerTest { // One of the activity and the intent must be non-null assertThrows(IllegalArgumentException.class, - () -> new TaskFragmentContainer(null, null, taskContainer, mController)); + () -> new TaskFragmentContainer(null, null, taskContainer, mController, + null /* pairedPrimaryContainer */)); // One of the activity and the intent must be null. assertThrows(IllegalArgumentException.class, - () -> new TaskFragmentContainer(mActivity, mIntent, taskContainer, mController)); + () -> new TaskFragmentContainer(mActivity, mIntent, taskContainer, mController, + null /* pairedPrimaryContainer */)); } @Test public void testFinish() { final TaskContainer taskContainer = createTestTaskContainer(); final TaskFragmentContainer container = new TaskFragmentContainer(mActivity, - null /* pendingAppearedIntent */, taskContainer, mController); + null /* pendingAppearedIntent */, taskContainer, mController, + null /* pairedPrimaryContainer */); doReturn(container).when(mController).getContainerWithActivity(mActivity); // Only remove the activity, but not clear the reference until appeared. @@ -137,12 +140,14 @@ public class TaskFragmentContainerTest { public void testFinish_notFinishActivityThatIsReparenting() { final TaskContainer taskContainer = createTestTaskContainer(); final TaskFragmentContainer container0 = new TaskFragmentContainer(mActivity, - null /* pendingAppearedIntent */, taskContainer, mController); + null /* pendingAppearedIntent */, taskContainer, mController, + null /* pairedPrimaryContainer */); final TaskFragmentInfo info = createMockTaskFragmentInfo(container0, mActivity); container0.setInfo(mTransaction, info); // Request to reparent the activity to a new TaskFragment. final TaskFragmentContainer container1 = new TaskFragmentContainer(mActivity, - null /* pendingAppearedIntent */, taskContainer, mController); + null /* pendingAppearedIntent */, taskContainer, mController, + null /* pairedPrimaryContainer */); doReturn(container1).when(mController).getContainerWithActivity(mActivity); final WindowContainerTransaction wct = new WindowContainerTransaction(); @@ -159,7 +164,8 @@ public class TaskFragmentContainerTest { final TaskContainer taskContainer = createTestTaskContainer(); // Pending activity should be cleared when it has appeared on server side. final TaskFragmentContainer pendingActivityContainer = new TaskFragmentContainer(mActivity, - null /* pendingAppearedIntent */, taskContainer, mController); + null /* pendingAppearedIntent */, taskContainer, mController, + null /* pairedPrimaryContainer */); assertTrue(pendingActivityContainer.mPendingAppearedActivities.contains( mActivity.getActivityToken())); @@ -172,7 +178,8 @@ public class TaskFragmentContainerTest { // Pending intent should be cleared when the container becomes non-empty. final TaskFragmentContainer pendingIntentContainer = new TaskFragmentContainer( - null /* pendingAppearedActivity */, mIntent, taskContainer, mController); + null /* pendingAppearedActivity */, mIntent, taskContainer, mController, + null /* pairedPrimaryContainer */); assertEquals(mIntent, pendingIntentContainer.getPendingAppearedIntent()); @@ -187,7 +194,7 @@ public class TaskFragmentContainerTest { public void testIsWaitingActivityAppear() { final TaskContainer taskContainer = createTestTaskContainer(); final TaskFragmentContainer container = new TaskFragmentContainer(null /* activity */, - mIntent, taskContainer, mController); + mIntent, taskContainer, mController, null /* pairedPrimaryContainer */); assertTrue(container.isWaitingActivityAppear()); @@ -209,7 +216,7 @@ public class TaskFragmentContainerTest { doNothing().when(mController).onTaskFragmentAppearEmptyTimeout(any(), any()); final TaskContainer taskContainer = createTestTaskContainer(); final TaskFragmentContainer container = new TaskFragmentContainer(null /* activity */, - mIntent, taskContainer, mController); + mIntent, taskContainer, mController, null /* pairedPrimaryContainer */); assertNull(container.mAppearEmptyTimeout); @@ -249,7 +256,7 @@ public class TaskFragmentContainerTest { public void testCollectNonFinishingActivities() { final TaskContainer taskContainer = createTestTaskContainer(); final TaskFragmentContainer container = new TaskFragmentContainer(null /* activity */, - mIntent, taskContainer, mController); + mIntent, taskContainer, mController, null /* pairedPrimaryContainer */); List<Activity> activities = container.collectNonFinishingActivities(); assertTrue(activities.isEmpty()); @@ -277,7 +284,7 @@ public class TaskFragmentContainerTest { public void testAddPendingActivity() { final TaskContainer taskContainer = createTestTaskContainer(); final TaskFragmentContainer container = new TaskFragmentContainer(null /* activity */, - mIntent, taskContainer, mController); + mIntent, taskContainer, mController, null /* pairedPrimaryContainer */); container.addPendingAppearedActivity(mActivity); assertEquals(1, container.collectNonFinishingActivities().size()); @@ -291,9 +298,9 @@ public class TaskFragmentContainerTest { public void testIsAbove() { final TaskContainer taskContainer = createTestTaskContainer(); final TaskFragmentContainer container0 = new TaskFragmentContainer(null /* activity */, - mIntent, taskContainer, mController); + mIntent, taskContainer, mController, null /* pairedPrimaryContainer */); final TaskFragmentContainer container1 = new TaskFragmentContainer(null /* activity */, - mIntent, taskContainer, mController); + mIntent, taskContainer, mController, null /* pairedPrimaryContainer */); assertTrue(container1.isAbove(container0)); assertFalse(container0.isAbove(container1)); @@ -303,7 +310,7 @@ public class TaskFragmentContainerTest { public void testGetBottomMostActivity() { final TaskContainer taskContainer = createTestTaskContainer(); final TaskFragmentContainer container = new TaskFragmentContainer(null /* activity */, - mIntent, taskContainer, mController); + mIntent, taskContainer, mController, null /* pairedPrimaryContainer */); container.addPendingAppearedActivity(mActivity); assertEquals(mActivity, container.getBottomMostActivity()); @@ -320,7 +327,7 @@ public class TaskFragmentContainerTest { public void testOnActivityDestroyed() { final TaskContainer taskContainer = createTestTaskContainer(mController); final TaskFragmentContainer container = new TaskFragmentContainer(null /* activity */, - mIntent, taskContainer, mController); + mIntent, taskContainer, mController, null /* pairedPrimaryContainer */); container.addPendingAppearedActivity(mActivity); final List<IBinder> activities = new ArrayList<>(); activities.add(mActivity.getActivityToken()); @@ -340,7 +347,7 @@ public class TaskFragmentContainerTest { // True if no info set. final TaskContainer taskContainer = createTestTaskContainer(); final TaskFragmentContainer container = new TaskFragmentContainer(null /* activity */, - mIntent, taskContainer, mController); + mIntent, taskContainer, mController, null /* pairedPrimaryContainer */); spyOn(taskContainer); doReturn(true).when(taskContainer).isVisible(); @@ -403,7 +410,7 @@ public class TaskFragmentContainerTest { public void testHasAppearedActivity() { final TaskContainer taskContainer = createTestTaskContainer(); final TaskFragmentContainer container = new TaskFragmentContainer(null /* activity */, - mIntent, taskContainer, mController); + mIntent, taskContainer, mController, null /* pairedPrimaryContainer */); container.addPendingAppearedActivity(mActivity); assertFalse(container.hasAppearedActivity(mActivity.getActivityToken())); @@ -420,7 +427,7 @@ public class TaskFragmentContainerTest { public void testHasPendingAppearedActivity() { final TaskContainer taskContainer = createTestTaskContainer(); final TaskFragmentContainer container = new TaskFragmentContainer(null /* activity */, - mIntent, taskContainer, mController); + mIntent, taskContainer, mController, null /* pairedPrimaryContainer */); container.addPendingAppearedActivity(mActivity); assertTrue(container.hasPendingAppearedActivity(mActivity.getActivityToken())); @@ -437,9 +444,9 @@ public class TaskFragmentContainerTest { public void testHasActivity() { final TaskContainer taskContainer = createTestTaskContainer(mController); final TaskFragmentContainer container1 = new TaskFragmentContainer(null /* activity */, - mIntent, taskContainer, mController); + mIntent, taskContainer, mController, null /* pairedPrimaryContainer */); final TaskFragmentContainer container2 = new TaskFragmentContainer(null /* activity */, - mIntent, taskContainer, mController); + mIntent, taskContainer, mController, null /* pairedPrimaryContainer */); // Activity is pending appeared on container2. container2.addPendingAppearedActivity(mActivity); @@ -472,6 +479,27 @@ public class TaskFragmentContainerTest { assertTrue(container2.hasActivity(mActivity.getActivityToken())); } + @Test + public void testNewContainerWithPairedPrimaryContainer() { + final TaskContainer taskContainer = createTestTaskContainer(); + final TaskFragmentContainer tf0 = new TaskFragmentContainer( + null /* pendingAppearedActivity */, new Intent(), taskContainer, mController, + null /* pairedPrimaryTaskFragment */); + final TaskFragmentContainer tf1 = new TaskFragmentContainer( + null /* pendingAppearedActivity */, new Intent(), taskContainer, mController, + null /* pairedPrimaryTaskFragment */); + taskContainer.mContainers.add(tf0); + taskContainer.mContainers.add(tf1); + + // When tf2 is created with using tf0 as pairedPrimaryContainer, tf2 should be inserted + // right above tf0. + final TaskFragmentContainer tf2 = new TaskFragmentContainer( + null /* pendingAppearedActivity */, new Intent(), taskContainer, mController, tf0); + assertEquals(0, taskContainer.indexOf(tf0)); + assertEquals(1, taskContainer.indexOf(tf2)); + assertEquals(2, taskContainer.indexOf(tf1)); + } + /** Creates a mock activity in the organizer process. */ private Activity createMockActivity() { final Activity activity = mock(Activity.class); diff --git a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TransactionManagerTest.java b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TransactionManagerTest.java index 62006bd51399..459b6d2c31f9 100644 --- a/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TransactionManagerTest.java +++ b/libs/WindowManager/Jetpack/tests/unittest/src/androidx/window/extensions/embedding/TransactionManagerTest.java @@ -16,9 +16,9 @@ package androidx.window.extensions.embedding; -import static android.view.WindowManager.TRANSIT_CHANGE; -import static android.view.WindowManager.TRANSIT_CLOSE; -import static android.view.WindowManager.TRANSIT_OPEN; +import static android.window.TaskFragmentOrganizer.TASK_FRAGMENT_TRANSIT_CHANGE; +import static android.window.TaskFragmentOrganizer.TASK_FRAGMENT_TRANSIT_CLOSE; +import static android.window.TaskFragmentOrganizer.TASK_FRAGMENT_TRANSIT_OPEN; import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify; import static com.android.dx.mockito.inline.extended.ExtendedMockito.verifyNoMoreInteractions; @@ -86,27 +86,29 @@ public class TransactionManagerTest { @Test public void testSetTransactionOriginType() { - // Return TRANSIT_CHANGE if there is no trigger type set. + // Return TASK_FRAGMENT_TRANSIT_CHANGE if there is no trigger type set. TransactionRecord transactionRecord = mTransactionManager.startNewTransaction(); - assertEquals(TRANSIT_CHANGE, transactionRecord.getTransactionTransitionType()); + assertEquals(TASK_FRAGMENT_TRANSIT_CHANGE, + transactionRecord.getTransactionTransitionType()); // Return the first set type. mTransactionManager.getCurrentTransactionRecord().abort(); transactionRecord = mTransactionManager.startNewTransaction(); - transactionRecord.setOriginType(TRANSIT_OPEN); + transactionRecord.setOriginType(TASK_FRAGMENT_TRANSIT_OPEN); - assertEquals(TRANSIT_OPEN, transactionRecord.getTransactionTransitionType()); + assertEquals(TASK_FRAGMENT_TRANSIT_OPEN, transactionRecord.getTransactionTransitionType()); - transactionRecord.setOriginType(TRANSIT_CLOSE); + transactionRecord.setOriginType(TASK_FRAGMENT_TRANSIT_CLOSE); - assertEquals(TRANSIT_OPEN, transactionRecord.getTransactionTransitionType()); + assertEquals(TASK_FRAGMENT_TRANSIT_OPEN, transactionRecord.getTransactionTransitionType()); // Reset when #startNewTransaction(). transactionRecord.abort(); transactionRecord = mTransactionManager.startNewTransaction(); - assertEquals(TRANSIT_CHANGE, transactionRecord.getTransactionTransitionType()); + assertEquals(TASK_FRAGMENT_TRANSIT_CHANGE, + transactionRecord.getTransactionTransitionType()); } @Test diff --git a/libs/WindowManager/Shell/res/values-am/strings.xml b/libs/WindowManager/Shell/res/values-am/strings.xml index 51de2e57b6b0..8b467041ed5f 100644 --- a/libs/WindowManager/Shell/res/values-am/strings.xml +++ b/libs/WindowManager/Shell/res/values-am/strings.xml @@ -22,8 +22,8 @@ <string name="pip_phone_settings" msgid="5468987116750491918">"ቅንብሮች"</string> <string name="pip_phone_enter_split" msgid="7042877263880641911">"የተከፈለ ማያ ገጽን አስገባ"</string> <string name="pip_menu_title" msgid="5393619322111827096">"ምናሌ"</string> - <string name="pip_menu_accessibility_title" msgid="8129016817688656249">"የስዕል-ላይ-ስዕል ምናሌ"</string> - <string name="pip_notification_title" msgid="1347104727641353453">"<xliff:g id="NAME">%s</xliff:g> በስዕል-ላይ-ስዕል ውስጥ ነው"</string> + <string name="pip_menu_accessibility_title" msgid="8129016817688656249">"የሥዕል-ላይ-ሥዕል ምናሌ"</string> + <string name="pip_notification_title" msgid="1347104727641353453">"<xliff:g id="NAME">%s</xliff:g> በሥዕል-ላይ-ሥዕል ውስጥ ነው"</string> <string name="pip_notification_message" msgid="8854051911700302620">"<xliff:g id="NAME">%s</xliff:g> ይህን ባህሪ እንዲጠቀም ካልፈለጉ ቅንብሮችን ለመክፈት መታ ያድርጉና ያጥፉት።"</string> <string name="pip_play" msgid="3496151081459417097">"አጫውት"</string> <string name="pip_pause" msgid="690688849510295232">"ባለበት አቁም"</string> diff --git a/libs/WindowManager/Shell/res/values-am/strings_tv.xml b/libs/WindowManager/Shell/res/values-am/strings_tv.xml index d64c051ecd23..a6be57889a4e 100644 --- a/libs/WindowManager/Shell/res/values-am/strings_tv.xml +++ b/libs/WindowManager/Shell/res/values-am/strings_tv.xml @@ -17,7 +17,7 @@ <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <string name="notification_channel_tv_pip" msgid="2576686079160402435">"ስዕል-ላይ-ስዕል"</string> + <string name="notification_channel_tv_pip" msgid="2576686079160402435">"ሥዕል-ላይ-ሥዕል"</string> <string name="pip_notification_unknown_title" msgid="2729870284350772311">"(ርዕስ የሌለው ፕሮግራም)"</string> <string name="pip_close" msgid="2955969519031223530">"ዝጋ"</string> <string name="pip_fullscreen" msgid="7278047353591302554">"ሙሉ ማያ ገጽ"</string> @@ -25,7 +25,7 @@ <string name="pip_expand" msgid="1051966011679297308">"ዘርጋ"</string> <string name="pip_collapse" msgid="3903295106641385962">"ሰብስብ"</string> <string name="pip_edu_text" msgid="7930546669915337998">"ለመቆጣጠሪያዎች "<annotation icon="home_icon">"መነሻ"</annotation>"ን ሁለቴ ይጫኑ"</string> - <string name="a11y_pip_menu_entered" msgid="5106343214776801614">"የስዕል-ላይ-ስዕል ምናሌ።"</string> + <string name="a11y_pip_menu_entered" msgid="5106343214776801614">"የሥዕል-ላይ-ሥዕል ምናሌ።"</string> <string name="a11y_action_pip_move_left" msgid="6612980937817141583">"ወደ ግራ ውሰድ"</string> <string name="a11y_action_pip_move_right" msgid="1119409122645529936">"ወደ ቀኝ ውሰድ"</string> <string name="a11y_action_pip_move_up" msgid="98502616918621959">"ወደ ላይ ውሰድ"</string> diff --git a/libs/WindowManager/Shell/res/values-ml/strings.xml b/libs/WindowManager/Shell/res/values-ml/strings.xml index 1f2ee77079bc..092331284f61 100644 --- a/libs/WindowManager/Shell/res/values-ml/strings.xml +++ b/libs/WindowManager/Shell/res/values-ml/strings.xml @@ -34,8 +34,7 @@ <string name="accessibility_action_pip_unstash" msgid="7467499339610437646">"അൺസ്റ്റാഷ് ചെയ്യൽ"</string> <string name="dock_forced_resizable" msgid="1749750436092293116">"സ്ക്രീൻ വിഭജന മോഡിൽ ആപ്പ് പ്രവർത്തിച്ചേക്കില്ല."</string> <string name="dock_non_resizeble_failed_to_dock_text" msgid="7408396418008948957">"സ്പ്ലിറ്റ്-സ്ക്രീനിനെ ആപ്പ് പിന്തുണയ്ക്കുന്നില്ല."</string> - <!-- no translation found for dock_multi_instances_not_supported_text (5242868470666346929) --> - <skip /> + <string name="dock_multi_instances_not_supported_text" msgid="5242868470666346929">"ഈ ആപ്പ് ഒരു വിൻഡോയിൽ മാത്രമേ തുറക്കാനാകൂ."</string> <string name="forced_resizable_secondary_display" msgid="1768046938673582671">"രണ്ടാം ഡിസ്പ്ലേയിൽ ആപ്പ് പ്രവർത്തിച്ചേക്കില്ല."</string> <string name="activity_launch_on_secondary_display_failed_text" msgid="4226485344988071769">"രണ്ടാം ഡിസ്പ്ലേകളിൽ സമാരംഭിക്കുന്നതിനെ ആപ്പ് അനുവദിക്കുന്നില്ല."</string> <string name="accessibility_divider" msgid="703810061635792791">"സ്പ്ലിറ്റ്-സ്ക്രീൻ ഡിവൈഡർ"</string> diff --git a/libs/WindowManager/Shell/res/values-ta/strings.xml b/libs/WindowManager/Shell/res/values-ta/strings.xml index 2039685ecc53..525f2ea043fc 100644 --- a/libs/WindowManager/Shell/res/values-ta/strings.xml +++ b/libs/WindowManager/Shell/res/values-ta/strings.xml @@ -34,8 +34,7 @@ <string name="accessibility_action_pip_unstash" msgid="7467499339610437646">"Unstash"</string> <string name="dock_forced_resizable" msgid="1749750436092293116">"திரைப் பிரிப்பு அம்சத்தில் ஆப்ஸ் செயல்படாமல் போகக்கூடும்."</string> <string name="dock_non_resizeble_failed_to_dock_text" msgid="7408396418008948957">"திரையைப் பிரிப்பதைப் ஆப்ஸ் ஆதரிக்கவில்லை."</string> - <!-- no translation found for dock_multi_instances_not_supported_text (5242868470666346929) --> - <skip /> + <string name="dock_multi_instances_not_supported_text" msgid="5242868470666346929">"இந்த ஆப்ஸை 1 சாளரத்தில் மட்டுமே திறக்க முடியும்."</string> <string name="forced_resizable_secondary_display" msgid="1768046938673582671">"இரண்டாம்நிலைத் திரையில் ஆப்ஸ் வேலை செய்யாமல் போகக்கூடும்."</string> <string name="activity_launch_on_secondary_display_failed_text" msgid="4226485344988071769">"இரண்டாம்நிலைத் திரைகளில் பயன்பாட்டைத் தொடங்க முடியாது."</string> <string name="accessibility_divider" msgid="703810061635792791">"திரையைப் பிரிக்கும் பிரிப்பான்"</string> 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 index c0a6456a2df0..164d2f149931 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationRunner.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/activityembedding/ActivityEmbeddingAnimationRunner.java @@ -17,6 +17,7 @@ package com.android.wm.shell.activityembedding; import static android.view.WindowManager.TRANSIT_CHANGE; +import static android.view.WindowManager.TRANSIT_CLOSE; import static android.view.WindowManagerPolicyConstants.TYPE_LAYER_OFFSET; import static android.window.TransitionInfo.FLAG_IS_BEHIND_STARTING_WINDOW; @@ -112,23 +113,30 @@ class ActivityEmbeddingAnimationRunner { @NonNull List<Consumer<SurfaceControl.Transaction>> postStartTransactionCallbacks) { final List<ActivityEmbeddingAnimationAdapter> adapters = createAnimationAdapters(info, startTransaction); - addEdgeExtensionIfNeeded(startTransaction, finishTransaction, postStartTransactionCallbacks, - adapters); - addBackgroundColorIfNeeded(info, startTransaction, finishTransaction, adapters); - 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(); + long duration = 0; + if (adapters.isEmpty()) { + // Jump cut + // No need to modify the animator, but to update the startTransaction with the changes' + // ending states. + prepareForJumpCut(info, startTransaction); + } else { + addEdgeExtensionIfNeeded(startTransaction, finishTransaction, + postStartTransactionCallbacks, adapters); + addBackgroundColorIfNeeded(info, startTransaction, finishTransaction, adapters); for (ActivityEmbeddingAnimationAdapter adapter : adapters) { - adapter.onAnimationUpdate(t, animator.getCurrentPlayTime()); + duration = Math.max(duration, adapter.getDurationHint()); } - t.apply(); - }); + 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.setDuration(duration); animator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) {} @@ -292,6 +300,10 @@ class ActivityEmbeddingAnimationRunner { @NonNull private List<ActivityEmbeddingAnimationAdapter> createChangeAnimationAdapters( @NonNull TransitionInfo info, @NonNull SurfaceControl.Transaction startTransaction) { + if (shouldUseJumpCutForChangeTransition(info)) { + return new ArrayList<>(); + } + final List<ActivityEmbeddingAnimationAdapter> adapters = new ArrayList<>(); final Set<TransitionInfo.Change> handledChanges = new ArraySet<>(); @@ -374,9 +386,11 @@ class ActivityEmbeddingAnimationRunner { } final Animation animation; - if (change.getParent() != null - && handledChanges.contains(info.getChange(change.getParent()))) { - // No-op if it will be covered by the changing parent window. + if ((change.getParent() != null + && handledChanges.contains(info.getChange(change.getParent()))) + || change.getMode() == TRANSIT_CHANGE) { + // No-op if it will be covered by the changing parent window, or it is a changing + // window without bounds change. animation = ActivityEmbeddingAnimationSpec.createNoopAnimation(change); } else if (Transitions.isClosingType(change.getMode())) { animation = mAnimationSpec.createChangeBoundsCloseAnimation(change, parentBounds); @@ -421,6 +435,74 @@ class ActivityEmbeddingAnimationRunner { animationChange.getLeash(), cropBounds, Integer.MAX_VALUE); } + /** + * Whether we should use jump cut for the change transition. + * This normally happens when opening a new secondary with the existing primary using a + * different split layout. This can be complicated, like from horizontal to vertical split with + * new split pairs. + * Uses a jump cut animation to simplify. + */ + private boolean shouldUseJumpCutForChangeTransition(@NonNull TransitionInfo info) { + // There can be reparenting of changing Activity to new open TaskFragment, so we need to + // exclude both in the first iteration. + final List<TransitionInfo.Change> changingChanges = new ArrayList<>(); + for (TransitionInfo.Change change : info.getChanges()) { + if (change.getMode() != TRANSIT_CHANGE + || change.getStartAbsBounds().equals(change.getEndAbsBounds())) { + continue; + } + changingChanges.add(change); + final WindowContainerToken parentToken = change.getParent(); + if (parentToken != null) { + // When the parent window is also included in the transition as an opening window, + // we would like to animate the parent window instead. + final TransitionInfo.Change parentChange = info.getChange(parentToken); + if (parentChange != null && Transitions.isOpeningType(parentChange.getMode())) { + changingChanges.add(parentChange); + } + } + } + if (changingChanges.isEmpty()) { + // No changing target found. + return true; + } + + // Check if the transition contains both opening and closing windows. + boolean hasOpeningWindow = false; + boolean hasClosingWindow = false; + for (TransitionInfo.Change change : info.getChanges()) { + if (changingChanges.contains(change)) { + continue; + } + if (change.getParent() != null + && changingChanges.contains(info.getChange(change.getParent()))) { + // No-op if it will be covered by the changing parent window. + continue; + } + hasOpeningWindow |= Transitions.isOpeningType(change.getMode()); + hasClosingWindow |= Transitions.isClosingType(change.getMode()); + } + return hasOpeningWindow && hasClosingWindow; + } + + /** Updates the changes to end states in {@code startTransaction} for jump cut animation. */ + private void prepareForJumpCut(@NonNull TransitionInfo info, + @NonNull SurfaceControl.Transaction startTransaction) { + for (TransitionInfo.Change change : info.getChanges()) { + final SurfaceControl leash = change.getLeash(); + startTransaction.setPosition(leash, + change.getEndRelOffset().x, change.getEndRelOffset().y); + startTransaction.setWindowCrop(leash, + change.getEndAbsBounds().width(), change.getEndAbsBounds().height()); + if (change.getMode() == TRANSIT_CLOSE) { + startTransaction.hide(leash); + } else { + startTransaction.show(leash); + startTransaction.setAlpha(leash, 1f); + } + } + } + /** To provide an {@link Animation} based on the transition infos. */ private interface AnimationProvider { Animation get(@NonNull TransitionInfo info, @NonNull TransitionInfo.Change change, diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleBadgeIconFactory.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleBadgeIconFactory.java index d3a9a672ec76..56b13b8dcd46 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleBadgeIconFactory.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleBadgeIconFactory.java @@ -19,7 +19,6 @@ package com.android.wm.shell.bubbles; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; -import android.graphics.Color; import android.graphics.Path; import android.graphics.Rect; import android.graphics.drawable.AdaptiveIconDrawable; @@ -59,7 +58,8 @@ public class BubbleBadgeIconFactory extends BaseIconFactory { private class CircularRingDrawable extends CircularAdaptiveIcon { final int mImportantConversationColor; - final Rect mTempBounds = new Rect(); + final int mRingWidth; + final Rect mInnerBounds = new Rect(); final Drawable mDr; @@ -68,6 +68,8 @@ public class BubbleBadgeIconFactory extends BaseIconFactory { mDr = dr; mImportantConversationColor = mContext.getResources().getColor( R.color.important_conversation, null); + mRingWidth = mContext.getResources().getDimensionPixelSize( + com.android.internal.R.dimen.importance_ring_stroke_width); } @Override @@ -75,11 +77,10 @@ public class BubbleBadgeIconFactory extends BaseIconFactory { int save = canvas.save(); canvas.clipPath(getIconMask()); canvas.drawColor(mImportantConversationColor); - int ringStrokeWidth = mContext.getResources().getDimensionPixelSize( - com.android.internal.R.dimen.importance_ring_stroke_width); - mTempBounds.set(getBounds()); - mTempBounds.inset(ringStrokeWidth, ringStrokeWidth); - mDr.setBounds(mTempBounds); + mInnerBounds.set(getBounds()); + mInnerBounds.inset(mRingWidth, mRingWidth); + canvas.translate(mInnerBounds.left, mInnerBounds.top); + mDr.setBounds(0, 0, mInnerBounds.width(), mInnerBounds.height()); mDr.draw(canvas); canvas.restoreToCount(save); } @@ -106,7 +107,6 @@ public class BubbleBadgeIconFactory extends BaseIconFactory { int save = canvas.save(); canvas.clipPath(getIconMask()); - canvas.drawColor(Color.BLACK); Drawable d; if ((d = getBackground()) != null) { d.draw(canvas); 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 dc1634a0cf09..661c08b18f46 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 @@ -702,7 +702,7 @@ public abstract class WMShellBaseModule { // Use optional-of-lazy for the dependency that this provider relies on. // Lazy ensures that this provider will not be the cause the dependency is created // when it will not be returned due to the condition below. - if (DesktopModeStatus.IS_SUPPORTED) { + if (DesktopModeStatus.isProto1Enabled()) { return desktopModeController.map(Lazy::get); } return Optional.empty(); @@ -719,7 +719,7 @@ public abstract class WMShellBaseModule { // Use optional-of-lazy for the dependency that this provider relies on. // Lazy ensures that this provider will not be the cause the dependency is created // when it will not be returned due to the condition below. - if (DesktopModeStatus.IS_SUPPORTED) { + if (DesktopModeStatus.isAnyEnabled()) { return desktopModeTaskRepository.map(Lazy::get); } return Optional.empty(); diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeController.java index 5824f51a1d33..7eb01a79f14f 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeController.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeController.java @@ -100,7 +100,7 @@ public class DesktopModeController implements RemoteCallable<DesktopModeControll mDesktopModeTaskRepository = desktopModeTaskRepository; mMainExecutor = mainExecutor; mSettingsObserver = new SettingsObserver(mContext, mainHandler); - if (DesktopModeStatus.isSupported()) { + if (DesktopModeStatus.isProto1Enabled()) { shellInit.addInitCallback(this::onInit, this); } } diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeStatus.java b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeStatus.java index e3eb2b746969..67f4a1914c49 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeStatus.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeStatus.java @@ -33,17 +33,38 @@ public class DesktopModeStatus { /** * Flag to indicate whether desktop mode is available on the device */ - public static final boolean IS_SUPPORTED = SystemProperties.getBoolean( + private static final boolean IS_SUPPORTED = SystemProperties.getBoolean( "persist.wm.debug.desktop_mode", false); /** + * Flag to indicate whether desktop mode proto 2 is available on the device + */ + private static final boolean IS_PROTO2_ENABLED = SystemProperties.getBoolean( + "persist.wm.debug.desktop_mode_2", false); + + /** * Return {@code true} if desktop mode support is enabled */ - public static boolean isSupported() { + public static boolean isProto1Enabled() { return IS_SUPPORTED; } /** + * Return {@code true} is desktop windowing proto 2 is enabled + */ + public static boolean isProto2Enabled() { + return IS_PROTO2_ENABLED; + } + + /** + * Return {@code true} if proto 1 or 2 is enabled. + * Can be used to guard logic that is common for both prototypes. + */ + public static boolean isAnyEnabled() { + return isProto1Enabled() || isProto2Enabled(); + } + + /** * Check if desktop mode is active * * @return {@code true} if active @@ -61,5 +82,4 @@ public class DesktopModeStatus { return false; } } - } 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 8a9b74fd72b1..793bad86d873 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 @@ -68,7 +68,7 @@ public class FreeformTaskListener implements ShellTaskOrganizer.TaskListener, private void onInit() { mShellTaskOrganizer.addListenerForType(this, TASK_LISTENER_TYPE_FREEFORM); - if (DesktopModeStatus.IS_SUPPORTED) { + if (DesktopModeStatus.isAnyEnabled()) { mShellTaskOrganizer.addFocusListener(this); } } @@ -90,7 +90,7 @@ public class FreeformTaskListener implements ShellTaskOrganizer.TaskListener, t.apply(); } - if (DesktopModeStatus.IS_SUPPORTED) { + if (DesktopModeStatus.isAnyEnabled()) { mDesktopModeTaskRepository.ifPresent(repository -> { repository.addOrMoveFreeformTaskToTop(taskInfo.taskId); if (taskInfo.isVisible) { @@ -110,7 +110,7 @@ public class FreeformTaskListener implements ShellTaskOrganizer.TaskListener, taskInfo.taskId); mTasks.remove(taskInfo.taskId); - if (DesktopModeStatus.IS_SUPPORTED) { + if (DesktopModeStatus.isAnyEnabled()) { mDesktopModeTaskRepository.ifPresent(repository -> { repository.removeFreeformTask(taskInfo.taskId); if (repository.removeActiveTask(taskInfo.taskId)) { @@ -134,7 +134,7 @@ public class FreeformTaskListener implements ShellTaskOrganizer.TaskListener, taskInfo.taskId); mWindowDecorationViewModel.onTaskInfoChanged(state.mTaskInfo); - if (DesktopModeStatus.IS_SUPPORTED) { + if (DesktopModeStatus.isAnyEnabled()) { mDesktopModeTaskRepository.ifPresent(repository -> { if (taskInfo.isVisible) { if (repository.addActiveTask(taskInfo.taskId)) { @@ -152,7 +152,7 @@ public class FreeformTaskListener implements ShellTaskOrganizer.TaskListener, ProtoLog.v(ShellProtoLogGroup.WM_SHELL_TASK_ORG, "Freeform Task Focus Changed: #%d focused=%b", taskInfo.taskId, taskInfo.isFocused); - if (DesktopModeStatus.IS_SUPPORTED && taskInfo.isFocused) { + if (DesktopModeStatus.isAnyEnabled() && taskInfo.isFocused) { mDesktopModeTaskRepository.ifPresent(repository -> { repository.addOrMoveFreeformTaskToTop(taskInfo.taskId); }); diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTransition.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTransition.java index 85bad174194c..e6c7e101d078 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTransition.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTransition.java @@ -358,8 +358,10 @@ public class PipTransition extends PipTransitionController { WindowContainerTransaction wct = null; if (isOutPipDirection(direction)) { // Only need to reset surface properties. The server-side operations were already - // done at the start. - if (tx != null) { + // done at the start. But if it is running fixed rotation, there will be a seamless + // display transition later. So the last rotation transform needs to be kept to + // avoid flickering, and then the display transition will reset the transform. + if (tx != null && !mInFixedRotation) { mFinishTransaction.merge(tx); } } else { diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CaptionWindowDecorViewModel.java b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CaptionWindowDecorViewModel.java index 56554020f3cc..afefd5dc6344 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CaptionWindowDecorViewModel.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CaptionWindowDecorViewModel.java @@ -517,7 +517,7 @@ public class CaptionWindowDecorViewModel implements WindowDecorViewModel { private boolean shouldShowWindowDecor(RunningTaskInfo taskInfo) { if (taskInfo.getWindowingMode() == WINDOWING_MODE_FREEFORM) return true; - return DesktopModeStatus.IS_SUPPORTED + return DesktopModeStatus.isAnyEnabled() && taskInfo.getActivityType() == ACTIVITY_TYPE_STANDARD && mDisplayController.getDisplayContext(taskInfo.displayId) .getResources().getConfiguration().smallestScreenWidthDp >= 600; diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopModeControllerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopModeControllerTest.java index dad913300711..b3c9e238a614 100644 --- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopModeControllerTest.java +++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopModeControllerTest.java @@ -100,7 +100,7 @@ public class DesktopModeControllerTest extends ShellTestCase { @Before public void setUp() { mMockitoSession = mockitoSession().mockStatic(DesktopModeStatus.class).startMocking(); - when(DesktopModeStatus.isSupported()).thenReturn(true); + when(DesktopModeStatus.isProto1Enabled()).thenReturn(true); when(DesktopModeStatus.isActive(any())).thenReturn(true); mShellInit = Mockito.spy(new ShellInit(mTestExecutor)); @@ -129,7 +129,7 @@ public class DesktopModeControllerTest extends ShellTestCase { @Test public void instantiate_flagOff_doNotAddInitCallback() { - when(DesktopModeStatus.isSupported()).thenReturn(false); + when(DesktopModeStatus.isProto1Enabled()).thenReturn(false); clearInvocations(mShellInit); createController(); diff --git a/libs/hwui/Properties.cpp b/libs/hwui/Properties.cpp index 277955e88dfe..6affc6a81685 100644 --- a/libs/hwui/Properties.cpp +++ b/libs/hwui/Properties.cpp @@ -82,7 +82,7 @@ bool Properties::isolatedProcess = false; int Properties::contextPriority = 0; float Properties::defaultSdrWhitePoint = 200.f; -bool Properties::useHintManager = true; +bool Properties::useHintManager = false; int Properties::targetCpuTimePercentage = 70; bool Properties::enableWebViewOverlays = true; @@ -142,7 +142,7 @@ bool Properties::load() { runningInEmulator = base::GetBoolProperty(PROPERTY_IS_EMULATOR, false); - useHintManager = base::GetBoolProperty(PROPERTY_USE_HINT_MANAGER, true); + useHintManager = base::GetBoolProperty(PROPERTY_USE_HINT_MANAGER, false); targetCpuTimePercentage = base::GetIntProperty(PROPERTY_TARGET_CPU_TIME_PERCENTAGE, 70); if (targetCpuTimePercentage <= 0 || targetCpuTimePercentage > 100) targetCpuTimePercentage = 70; diff --git a/libs/hwui/jni/Mesh.cpp b/libs/hwui/jni/Mesh.cpp index 109aac321b6e..7c732d7fdcf2 100644 --- a/libs/hwui/jni/Mesh.cpp +++ b/libs/hwui/jni/Mesh.cpp @@ -37,6 +37,16 @@ sk_sp<SkMesh::IndexBuffer> genIndexBuffer(JNIEnv* env, jobject buffer, int size, return indexBuffer; } +// TODO(b/260252882): undefine SK_LEGACY_MESH_MAKE and remove this. +template <typename T> +SkMesh get_mesh_from_result(T&& result) { +#ifdef SK_LEGACY_MESH_MAKE + return result; +#else + return result.mesh; +#endif +} + static jlong make(JNIEnv* env, jobject, jlong meshSpec, jint mode, jobject vertexBuffer, jboolean isDirect, jint vertexCount, jint vertexOffset, jint left, jint top, jint right, jint bottom) { @@ -44,8 +54,8 @@ static jlong make(JNIEnv* env, jobject, jlong meshSpec, jint mode, jobject verte sk_sp<SkMesh::VertexBuffer> skVertexBuffer = genVertexBuffer(env, vertexBuffer, vertexCount * skMeshSpec->stride(), isDirect); auto skRect = SkRect::MakeLTRB(left, top, right, bottom); - auto mesh = SkMesh::Make(skMeshSpec, SkMesh::Mode(mode), skVertexBuffer, vertexCount, - vertexOffset, nullptr, skRect); + auto mesh = get_mesh_from_result(SkMesh::Make(skMeshSpec, SkMesh::Mode(mode), skVertexBuffer, + vertexCount, vertexOffset, nullptr, skRect)); auto meshPtr = std::make_unique<MeshWrapper>(MeshWrapper{mesh, MeshUniformBuilder(skMeshSpec)}); return reinterpret_cast<jlong>(meshPtr.release()); } @@ -60,9 +70,9 @@ static jlong makeIndexed(JNIEnv* env, jobject, jlong meshSpec, jint mode, jobjec sk_sp<SkMesh::IndexBuffer> skIndexBuffer = genIndexBuffer(env, indexBuffer, indexCount * gIndexByteSize, isIndexDirect); auto skRect = SkRect::MakeLTRB(left, top, right, bottom); - auto mesh = SkMesh::MakeIndexed(skMeshSpec, SkMesh::Mode(mode), skVertexBuffer, vertexCount, - vertexOffset, skIndexBuffer, indexCount, indexOffset, nullptr, - skRect); + auto mesh = get_mesh_from_result(SkMesh::MakeIndexed( + skMeshSpec, SkMesh::Mode(mode), skVertexBuffer, vertexCount, vertexOffset, + skIndexBuffer, indexCount, indexOffset, nullptr, skRect)); auto meshPtr = std::make_unique<MeshWrapper>(MeshWrapper{mesh, MeshUniformBuilder(skMeshSpec)}); return reinterpret_cast<jlong>(meshPtr.release()); } @@ -71,14 +81,15 @@ static void updateMesh(JNIEnv* env, jobject, jlong meshWrapper, jboolean indexed auto wrapper = reinterpret_cast<MeshWrapper*>(meshWrapper); auto mesh = wrapper->mesh; if (indexed) { - wrapper->mesh = SkMesh::MakeIndexed( + wrapper->mesh = get_mesh_from_result(SkMesh::MakeIndexed( sk_ref_sp(mesh.spec()), mesh.mode(), sk_ref_sp(mesh.vertexBuffer()), mesh.vertexCount(), mesh.vertexOffset(), sk_ref_sp(mesh.indexBuffer()), - mesh.indexCount(), mesh.indexOffset(), wrapper->builder.fUniforms, mesh.bounds()); + mesh.indexCount(), mesh.indexOffset(), wrapper->builder.fUniforms, mesh.bounds())); } else { - wrapper->mesh = SkMesh::Make( - sk_ref_sp(mesh.spec()), mesh.mode(), sk_ref_sp(mesh.vertexBuffer()), - mesh.vertexCount(), mesh.vertexOffset(), wrapper->builder.fUniforms, mesh.bounds()); + wrapper->mesh = get_mesh_from_result( + SkMesh::Make(sk_ref_sp(mesh.spec()), mesh.mode(), sk_ref_sp(mesh.vertexBuffer()), + mesh.vertexCount(), mesh.vertexOffset(), wrapper->builder.fUniforms, + mesh.bounds())); } } diff --git a/libs/hwui/tests/common/TestContext.cpp b/libs/hwui/tests/common/TestContext.cpp index 0faa8f4f6cc9..fd596d998dfd 100644 --- a/libs/hwui/tests/common/TestContext.cpp +++ b/libs/hwui/tests/common/TestContext.cpp @@ -31,10 +31,8 @@ const ui::StaticDisplayInfo& getDisplayInfo() { const std::vector<PhysicalDisplayId> ids = SurfaceComposerClient::getPhysicalDisplayIds(); LOG_ALWAYS_FATAL_IF(ids.empty(), "%s: No displays", __FUNCTION__); - const sp<IBinder> token = SurfaceComposerClient::getPhysicalDisplayToken(ids.front()); - LOG_ALWAYS_FATAL_IF(!token, "%s: No internal display", __FUNCTION__); - - const status_t status = SurfaceComposerClient::getStaticDisplayInfo(token, &info); + const status_t status = + SurfaceComposerClient::getStaticDisplayInfo(ids.front().value, &info); LOG_ALWAYS_FATAL_IF(status, "%s: Failed to get display info", __FUNCTION__); #endif return info; diff --git a/location/java/android/location/Country.java b/location/java/android/location/Country.java index 8e1bb1f0a9b3..53cc943a7237 100644 --- a/location/java/android/location/Country.java +++ b/location/java/android/location/Country.java @@ -16,6 +16,7 @@ package android.location; +import android.annotation.IntDef; import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.SystemApi; @@ -24,6 +25,8 @@ import android.os.Parcel; import android.os.Parcelable; import android.os.SystemClock; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; import java.util.Locale; /** @@ -54,8 +57,22 @@ public final class Country implements Parcelable { public static final int COUNTRY_SOURCE_LOCALE = 3; /** - * The ISO 3166-1 two letters country code. + * Country source type + * + * @hide */ + @IntDef( + prefix = {"COUNTRY_SOURCE_"}, + value = { + COUNTRY_SOURCE_NETWORK, + COUNTRY_SOURCE_LOCATION, + COUNTRY_SOURCE_SIM, + COUNTRY_SOURCE_LOCALE + }) + @Retention(RetentionPolicy.SOURCE) + public @interface CountrySource {} + + /** The ISO 3166-1 two letters country code. */ private final String mCountryIso; /** @@ -73,21 +90,18 @@ public final class Country implements Parcelable { /** * @param countryIso the ISO 3166-1 two letters country code. - * @param source where the countryIso came from, could be one of below - * values - * <p> - * <ul> - * <li>{@link #COUNTRY_SOURCE_NETWORK}</li> - * <li>{@link #COUNTRY_SOURCE_LOCATION}</li> - * <li>{@link #COUNTRY_SOURCE_SIM}</li> - * <li>{@link #COUNTRY_SOURCE_LOCALE}</li> - * </ul> - * - * @hide + * @param source where the countryIso came from, could be one of below values + * <p> + * <ul> + * <li>{@link #COUNTRY_SOURCE_NETWORK} + * <li>{@link #COUNTRY_SOURCE_LOCATION} + * <li>{@link #COUNTRY_SOURCE_SIM} + * <li>{@link #COUNTRY_SOURCE_LOCALE} + * </ul> */ - @UnsupportedAppUsage - public Country(final String countryIso, final int source) { - if (countryIso == null || source < COUNTRY_SOURCE_NETWORK + public Country(@NonNull final String countryIso, @CountrySource final int source) { + if (countryIso == null + || source < COUNTRY_SOURCE_NETWORK || source > COUNTRY_SOURCE_LOCALE) { throw new IllegalArgumentException(); } @@ -115,13 +129,28 @@ public final class Country implements Parcelable { /** * @return the ISO 3166-1 two letters country code + * + * @hide + * + * @deprecated clients using getCountryIso should use the {@link #getCountryCode()} API instead. */ - @NonNull + @UnsupportedAppUsage + @Deprecated public String getCountryIso() { return mCountryIso; } /** + * Retrieves country code. + * + * @return country code in ISO 3166-1:alpha2 + */ + @NonNull + public String getCountryCode() { + return mCountryIso; + } + + /** * @return where the country code came from, could be one of below values * <p> * <ul> @@ -131,6 +160,7 @@ public final class Country implements Parcelable { * <li>{@link #COUNTRY_SOURCE_LOCALE}</li> * </ul> */ + @CountrySource public int getSource() { return mSource; } diff --git a/location/java/android/location/CountryDetector.java b/location/java/android/location/CountryDetector.java index 3a0edfc57193..6abb35020a35 100644 --- a/location/java/android/location/CountryDetector.java +++ b/location/java/android/location/CountryDetector.java @@ -24,28 +24,32 @@ import android.compat.annotation.UnsupportedAppUsage; import android.content.Context; import android.os.Build; import android.os.Handler; +import android.os.HandlerExecutor; import android.os.Looper; import android.os.RemoteException; import android.util.Log; import java.util.HashMap; +import java.util.concurrent.Executor; +import java.util.function.Consumer; /** - * This class provides access to the system country detector service. This - * service allows applications to obtain the country that the user is in. - * <p> - * The country will be detected in order of reliability, like + * This class provides access to the system country detector service. This service allows + * applications to obtain the country that the user is in. + * + * <p>The country will be detected in order of reliability, like + * * <ul> - * <li>Mobile network</li> - * <li>Location</li> - * <li>SIM's country</li> - * <li>Phone's locale</li> + * <li>Mobile network + * <li>Location + * <li>SIM's country + * <li>Phone's locale * </ul> - * <p> - * Call the {@link #detectCountry()} to get the available country immediately. - * <p> - * To be notified of the future country change, use the - * {@link #addCountryListener} + * + * <p>Call the {@link #detectCountry()} to get the available country immediately. + * + * <p>To be notified of the future country change, use the {@link #addCountryListener} + * * <p> * * @hide @@ -55,57 +59,52 @@ import java.util.HashMap; public class CountryDetector { /** - * The class to wrap the ICountryListener.Stub and CountryListener objects - * together. The CountryListener will be notified through the specific - * looper once the country changed and detected. + * The class to wrap the ICountryListener.Stub , CountryListener & {@code Consumer<Country>} + * objects together. + * + * <p>The CountryListener will be notified through the Handler Executor once the country changed + * and detected. + * + * <p>{@code Consumer<Country>} callback interface is notified through the specific executor + * once the country changed and detected. */ - private final static class ListenerTransport extends ICountryListener.Stub { + private static final class ListenerTransport extends ICountryListener.Stub { - private final CountryListener mListener; + private final Consumer<Country> mListener; + private final Executor mExecutor; - private final Handler mHandler; - - public ListenerTransport(CountryListener listener, Looper looper) { - mListener = listener; - if (looper != null) { - mHandler = new Handler(looper); - } else { - mHandler = new Handler(); - } + ListenerTransport(Consumer<Country> consumer, Executor executor) { + mListener = consumer; + mExecutor = executor; } public void onCountryDetected(final Country country) { - mHandler.post(new Runnable() { - public void run() { - mListener.onCountryDetected(country); - } - }); + mExecutor.execute(() -> mListener.accept(country)); } } - private final static String TAG = "CountryDetector"; + private static final String TAG = "CountryDetector"; private final ICountryDetector mService; - private final HashMap<CountryListener, ListenerTransport> mListeners; + private final HashMap<Consumer<Country>, ListenerTransport> mListeners; /** - * @hide - hide this constructor because it has a parameter of type - * ICountryDetector, which is a system private class. The right way to - * create an instance of this class is using the factory - * Context.getSystemService. + * @hide - hide this constructor because it has a parameter of type ICountryDetector, which is a + * system private class. The right way to create an instance of this class is using the + * factory Context.getSystemService. */ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) public CountryDetector(ICountryDetector service) { mService = service; - mListeners = new HashMap<CountryListener, ListenerTransport>(); + mListeners = new HashMap<>(); } /** * Start detecting the country that the user is in. * - * @return the country if it is available immediately, otherwise null will - * be returned. + * @return the country if it is available immediately, otherwise null will be returned. + * @hide */ - @Nullable + @UnsupportedAppUsage public Country detectCountry() { try { return mService.detectCountry(); @@ -116,40 +115,64 @@ public class CountryDetector { } /** - * Add a listener to receive the notification when the country is detected - * or changed. + * Add a listener to receive the notification when the country is detected or changed. * * @param listener will be called when the country is detected or changed. - * @param looper a Looper object whose message queue will be used to - * implement the callback mechanism. If looper is null then the - * callbacks will be called on the main thread. + * @param looper a Looper object whose message queue will be used to implement the callback + * mechanism. If looper is null then the callbacks will be called on the main thread. + * @hide + * @deprecated client using this api should use {@link + * #registerCountryDetectorCallback(Executor, Consumer)} } */ + @UnsupportedAppUsage + @Deprecated public void addCountryListener(@NonNull CountryListener listener, @Nullable Looper looper) { - synchronized (mListeners) { - if (!mListeners.containsKey(listener)) { - ListenerTransport transport = new ListenerTransport(listener, looper); - try { - mService.addCountryListener(transport); - mListeners.put(listener, transport); - } catch (RemoteException e) { - Log.e(TAG, "addCountryListener: RemoteException", e); - } - } - } + Handler handler = looper != null ? new Handler(looper) : new Handler(); + registerCountryDetectorCallback(new HandlerExecutor(handler), listener); } /** * Remove the listener + * + * @hide + * @deprecated client using this api should use {@link + * #unregisterCountryDetectorCallback(Consumer)} */ - public void removeCountryListener(@NonNull CountryListener listener) { + @UnsupportedAppUsage + @Deprecated + public void removeCountryListener(CountryListener listener) { + unregisterCountryDetectorCallback(listener); + } + + /** + * Add a callback interface, to be notified when country code is added or changes. + * + * @param executor The callback executor for the response. + * @param consumer {@link Consumer} callback to receive the country code when changed/detected + */ + public void registerCountryDetectorCallback( + @NonNull Executor executor, @NonNull Consumer<Country> consumer) { + synchronized (mListeners) { + unregisterCountryDetectorCallback(consumer); + ListenerTransport transport = new ListenerTransport(consumer, executor); + try { + mService.addCountryListener(transport); + mListeners.put(consumer, transport); + } catch (RemoteException e) { + throw e.rethrowFromSystemServer(); + } + } + } + + /** Remove the callback subscribed to Update country code */ + public void unregisterCountryDetectorCallback(@NonNull Consumer<Country> consumer) { synchronized (mListeners) { - ListenerTransport transport = mListeners.get(listener); + ListenerTransport transport = mListeners.remove(consumer); if (transport != null) { try { - mListeners.remove(listener); mService.removeCountryListener(transport); } catch (RemoteException e) { - Log.e(TAG, "removeCountryListener: RemoteException", e); + throw e.rethrowFromSystemServer(); } } } diff --git a/location/java/android/location/CountryListener.java b/location/java/android/location/CountryListener.java index 5c06d8239c23..0ca6962460f8 100644 --- a/location/java/android/location/CountryListener.java +++ b/location/java/android/location/CountryListener.java @@ -16,8 +16,9 @@ package android.location; -import android.annotation.NonNull; -import android.annotation.SystemApi; +import android.compat.annotation.UnsupportedAppUsage; + +import java.util.function.Consumer; /** * The listener for receiving the notification when the country is detected or @@ -25,11 +26,17 @@ import android.annotation.SystemApi; * * @hide */ -@SystemApi(client = SystemApi.Client.PRIVILEGED_APPS) -public interface CountryListener { +public interface CountryListener extends Consumer<Country> { + /** + * @param country the changed or detected country. + */ + @UnsupportedAppUsage + void onCountryDetected(Country country); + /** * @param country the changed or detected country. - * */ - void onCountryDetected(@NonNull Country country); + default void accept(Country country) { + onCountryDetected(country); + } } diff --git a/location/java/android/location/altitude/AltitudeConverter.java b/location/java/android/location/altitude/AltitudeConverter.java index 506128e17740..d46b4d2c3be3 100644 --- a/location/java/android/location/altitude/AltitudeConverter.java +++ b/location/java/android/location/altitude/AltitudeConverter.java @@ -151,20 +151,17 @@ public final class AltitudeConverter { * altitude accuracy if the {@code location} has a finite and non-negative vertical accuracy; * otherwise, does not add a corresponding accuracy. * - * <p>Must be called off the main thread as data may be loaded from raw assets. Throws an - * {@link IOException} if an I/O error occurs when loading data. + * <p>Must be called off the main thread as data may be loaded from raw assets. * - * <p>Throws an {@link IllegalArgumentException} if the {@code location} has an invalid - * latitude, longitude, or altitude above WGS84. Specifically: - * - * <ul> - * <li>The latitude must be between -90 and 90, both inclusive. - * <li>The longitude must be between -180 and 180, both inclusive. - * <li>The altitude above WGS84 must be finite. - * </ul> + * @throws IOException if an I/O error occurs when loading data from raw assets. + * @throws IllegalArgumentException if the {@code location} has an invalid latitude, longitude, + * or altitude above WGS84. Specifically, the latitude must be + * between -90 and 90 (both inclusive), the longitude must be + * between -180 and 180 (both inclusive), and the altitude + * above WGS84 must be finite. */ @WorkerThread - public void addMslAltitude(@NonNull Context context, @NonNull Location location) + public void addMslAltitudeToLocation(@NonNull Context context, @NonNull Location location) throws IOException { validate(location); MapParamsProto params = GeoidHeightMap.getParams(context); diff --git a/media/java/android/media/AudioDeviceInfo.java b/media/java/android/media/AudioDeviceInfo.java index 3b30b1d89268..5a72b0be3405 100644 --- a/media/java/android/media/AudioDeviceInfo.java +++ b/media/java/android/media/AudioDeviceInfo.java @@ -89,6 +89,8 @@ public final class AudioDeviceInfo { public static final int TYPE_USB_ACCESSORY = 12; /** * A device type describing the audio device associated with a dock. + * Starting at API 34, this device type only represents digital docks, while docks with an + * analog connection are represented with {@link #TYPE_DOCK_ANALOG}. * @see #TYPE_DOCK_ANALOG */ public static final int TYPE_DOCK = 13; diff --git a/media/java/android/media/AudioManager.java b/media/java/android/media/AudioManager.java index ae0d45ffca24..3ed2c4b6ebc7 100644 --- a/media/java/android/media/AudioManager.java +++ b/media/java/android/media/AudioManager.java @@ -8518,6 +8518,221 @@ public class AudioManager { } } + //==================================================================== + // Preferred mixer attributes + + /** + * Returns the {@link AudioMixerAttributes} that can be used to set as preferred mixe + * attributes via {@link #setPreferredMixerAttributes( + * AudioAttributes, AudioDeviceInfo, AudioMixerAttributes)}. + * <p>Note that only USB devices are guaranteed to expose configurable mixer attributes, the + * returned list may be empty when devices do not allow dynamic configuration. + * + * @param device the device to query + * @return a list of {@link AudioMixerAttributes} that can be used as preferred mixer attributes + * for the given device. + * @see #setPreferredMixerAttributes(AudioAttributes, AudioDeviceInfo, AudioMixerAttributes) + */ + @NonNull + public List<AudioMixerAttributes> getSupportedMixerAttributes(@NonNull AudioDeviceInfo device) { + Objects.requireNonNull(device); + List<AudioMixerAttributes> mixerAttrs = new ArrayList<>(); + return (AudioSystem.getSupportedMixerAttributes(device.getId(), mixerAttrs) + == AudioSystem.SUCCESS) ? mixerAttrs : new ArrayList<>(); + } + + /** + * Configures the mixer attributes for a particular {@link AudioAttributes} over a given + * {@link AudioDeviceInfo}. + * <p>When constructing an {@link AudioMixerAttributes} for setting preferred mixer attributes, + * the mixer format must be constructed from an {@link AudioProfile} that can be used to set + * preferred mixer attributes. + * <p>The ownership of preferred mixer attributes is recognized by uid. When a playback from the + * same uid is routed to the given audio device when calling this API, the output mixer/stream + * will be configured with the values previously set via this API. + * <p>Use {@link #clearPreferredMixerAttributes(AudioAttributes, AudioDeviceInfo)} + * to cancel setting mixer attributes for this {@link AudioAttributes}. + * + * @param attributes the {@link AudioAttributes} whose mixer attributes should be set. + * Currently, only {@link AudioAttributes#USAGE_MEDIA} is supported. When + * playing audio targeted at the given device, use the same attributes for + * playback. + * @param device the device to be routed. Currently, only USB device will be allowed. + * @param mixerAttributes the preferred mixer attributes. When playing audio targeted at the + * given device, use the same {@link AudioFormat} for both playback + * and the mixer attributes. + * @return true only if the preferred mixer attributes are set successfully. + * @see #getPreferredMixerAttributes(AudioAttributes, AudioDeviceInfo) + * @see #clearPreferredMixerAttributes(AudioAttributes, AudioDeviceInfo) + */ + @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_SETTINGS) + public boolean setPreferredMixerAttributes(@NonNull AudioAttributes attributes, + @NonNull AudioDeviceInfo device, + @NonNull AudioMixerAttributes mixerAttributes) { + Objects.requireNonNull(attributes); + Objects.requireNonNull(device); + Objects.requireNonNull(mixerAttributes); + try { + final int status = getService().setPreferredMixerAttributes( + attributes, device.getId(), mixerAttributes); + return status == AudioSystem.SUCCESS; + } catch (RemoteException e) { + throw e.rethrowFromSystemServer(); + } + } + + /** + * Returns current preferred mixer attributes that is set via + * {@link #setPreferredMixerAttributes(AudioAttributes, AudioDeviceInfo, AudioMixerAttributes)} + * + * @param attributes the {@link AudioAttributes} whose mixer attributes should be set. + * @param device the expected routing device + * @return the preferred mixer attributes, which will be null when no preferred mixer attributes + * have been set, or when they have been cleared. + * @see #setPreferredMixerAttributes(AudioAttributes, AudioDeviceInfo, AudioMixerAttributes) + * @see #clearPreferredMixerAttributes(AudioAttributes, AudioDeviceInfo) + */ + @Nullable + public AudioMixerAttributes getPreferredMixerAttributes( + @NonNull AudioAttributes attributes, + @NonNull AudioDeviceInfo device) { + Objects.requireNonNull(attributes); + Objects.requireNonNull(device); + List<AudioMixerAttributes> mixerAttrList = new ArrayList<>(); + int ret = AudioSystem.getPreferredMixerAttributes( + attributes, device.getId(), mixerAttrList); + if (ret == AudioSystem.SUCCESS) { + return mixerAttrList.isEmpty() ? null : mixerAttrList.get(0); + } else { + Log.e(TAG, "Failed calling getPreferredMixerAttributes, ret=" + ret); + return null; + } + } + + /** + * Clears the current preferred mixer attributes that were previously set via + * {@link #setPreferredMixerAttributes(AudioAttributes, AudioDeviceInfo, AudioMixerAttributes)} + * + * @param attributes the {@link AudioAttributes} whose mixer attributes should be cleared. + * @param device the expected routing device + * @return true only if the preferred mixer attributes are removed successfully. + * @see #setPreferredMixerAttributes(AudioAttributes, AudioDeviceInfo, AudioMixerAttributes) + * @see #getPreferredMixerAttributes(AudioAttributes, AudioDeviceInfo) + */ + @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_SETTINGS) + public boolean clearPreferredMixerAttributes( + @NonNull AudioAttributes attributes, + @NonNull AudioDeviceInfo device) { + Objects.requireNonNull(attributes); + Objects.requireNonNull(device); + try { + final int status = getService().clearPreferredMixerAttributes( + attributes, device.getId()); + return status == AudioSystem.SUCCESS; + } catch (RemoteException e) { + throw e.rethrowFromSystemServer(); + } + } + + /** + * Interface to be notified of changes in the preferred mixer attributes. + * <p>Note that this listener will only be invoked whenever + * {@link #setPreferredMixerAttributes(AudioAttributes, AudioDeviceInfo, AudioMixerAttributes)} + * or {@link #clearPreferredMixerAttributes(AudioAttributes, AudioDeviceInfo)} or device + * disconnection causes a change in preferred mixer attributes. + * @see #setPreferredMixerAttributes(AudioAttributes, AudioDeviceInfo, AudioMixerAttributes) + * @see #clearPreferredMixerAttributes(AudioAttributes, AudioDeviceInfo) + */ + public interface OnPreferredMixerAttributesChangedListener { + /** + * Called on the listener to indicate that the preferred mixer attributes for the audio + * attributes over the given device has changed. + * + * @param attributes the audio attributes for playback + * @param device the targeted device + * @param mixerAttributes the {@link AudioMixerAttributes} that contains information for + * preferred mixer attributes or null if preferred mixer attributes + * is cleared + */ + void onPreferredMixerAttributesChanged( + @NonNull AudioAttributes attributes, + @NonNull AudioDeviceInfo device, + @Nullable AudioMixerAttributes mixerAttributes); + } + + /** + * Manage the {@link OnPreferredMixerAttributesChangedListener} listeners and the + * {@link PreferredMixerAttributesDispatcherStub}. + */ + private final CallbackUtil.LazyListenerManager<OnPreferredMixerAttributesChangedListener> + mPrefMixerAttributesListenerMgr = new CallbackUtil.LazyListenerManager(); + + /** + * Adds a listener for being notified of changes to the preferred mixer attributes. + * @param executor the executor to execute the callback + * @param listener the listener to be notified of changes in the preferred mixer attributes. + */ + public void addOnPreferredMixerAttributesChangedListener( + @NonNull @CallbackExecutor Executor executor, + @NonNull OnPreferredMixerAttributesChangedListener listener) { + Objects.requireNonNull(executor); + Objects.requireNonNull(listener); + mPrefMixerAttributesListenerMgr.addListener(executor, listener, + "addOnPreferredMixerAttributesChangedListener", + () -> new PreferredMixerAttributesDispatcherStub()); + } + + /** + * Removes a previously added listener of changes to the preferred mixer attributes. + * @param listener the listener to be notified of changes in the preferred mixer attributes, + * which were added via {@link #addOnPreferredMixerAttributesChangedListener( + * Executor, OnPreferredMixerAttributesChangedListener)}. + */ + public void removeOnPreferredMixerAttributesChangedListener( + @NonNull OnPreferredMixerAttributesChangedListener listener) { + Objects.requireNonNull(listener); + mPrefMixerAttributesListenerMgr.removeListener(listener, + "removeOnPreferredMixerAttributesChangedListener"); + } + + private final class PreferredMixerAttributesDispatcherStub + extends IPreferredMixerAttributesDispatcher.Stub + implements CallbackUtil.DispatcherStub { + + @Override + public void register(boolean register) { + try { + if (register) { + getService().registerPreferredMixerAttributesDispatcher(this); + } else { + getService().unregisterPreferredMixerAttributesDispatcher(this); + } + } catch (RemoteException e) { + e.rethrowFromSystemServer(); + } + } + + @Override + public void dispatchPrefMixerAttributesChanged(@NonNull AudioAttributes attr, + int deviceId, + @Nullable AudioMixerAttributes mixerAttr) { + // TODO: If the device is disconnected, we may not be able to find the device with + // given device id. We need a better to carry the device information via binder. + AudioDeviceInfo device = getDeviceForPortId(deviceId, GET_DEVICES_OUTPUTS); + if (device == null) { + Log.d(TAG, "Drop preferred mixer attributes changed as the device(" + + deviceId + ") is disconnected"); + return; + } + mPrefMixerAttributesListenerMgr.callListeners( + (listener) -> listener.onPreferredMixerAttributesChanged( + attr, device, mixerAttr)); + } + } + + //==================================================================== + // Mute await connection + private final Object mMuteAwaitConnectionListenerLock = new Object(); @GuardedBy("mMuteAwaitConnectionListenerLock") diff --git a/media/java/android/media/AudioMixerAttributes.aidl b/media/java/android/media/AudioMixerAttributes.aidl new file mode 100644 index 000000000000..0d9badde8d25 --- /dev/null +++ b/media/java/android/media/AudioMixerAttributes.aidl @@ -0,0 +1,18 @@ +/* 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. +*/ + +package android.media; + +parcelable AudioMixerAttributes; diff --git a/media/java/android/media/AudioMixerAttributes.java b/media/java/android/media/AudioMixerAttributes.java new file mode 100644 index 000000000000..320d6bdbf227 --- /dev/null +++ b/media/java/android/media/AudioMixerAttributes.java @@ -0,0 +1,183 @@ +/* + * 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.media; + +import android.annotation.IntDef; +import android.annotation.NonNull; +import android.os.Parcel; +import android.os.Parcelable; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.util.Objects; + +/** + * Class to represent the attributes of the audio mixer: its format, which represents by an + * {@link AudioFormat} object and mixer behavior. + */ +public final class AudioMixerAttributes implements Parcelable { + + /** + * Constant indicating the audio mixer behavior will follow the default platform behavior, which + * is mixing all audio sources in the mixer. + */ + public static final int MIXER_BEHAVIOR_DEFAULT = 0; + + /** @hide */ + @IntDef(flag = false, prefix = "MIXER_BEHAVIOR_", value = { + MIXER_BEHAVIOR_DEFAULT } + ) + @Retention(RetentionPolicy.SOURCE) + public @interface MixerBehavior {} + + private final AudioFormat mFormat; + private final @MixerBehavior int mMixerBehavior; + + /** + * Constructor from {@link AudioFormat} and mixer behavior + */ + AudioMixerAttributes(AudioFormat format, @MixerBehavior int mixerBehavior) { + mFormat = format; + mMixerBehavior = mixerBehavior; + } + + /** + * Return the format of the audio mixer. The format is an {@link AudioFormat} object, which + * includes encoding format, sample rate and channel mask or channel index mask. + * @return the format of the audio mixer. + */ + @NonNull + public AudioFormat getFormat() { + return mFormat; + } + + /** + * Returns the mixer behavior for this set of mixer attributes. + * + * @return the mixer behavior + */ + public @MixerBehavior int getMixerBehavior() { + return mMixerBehavior; + } + + /** + * Builder class for {@link AudioMixerAttributes} objects. + */ + public static final class Builder { + private final AudioFormat mFormat; + private int mMixerBehavior = MIXER_BEHAVIOR_DEFAULT; + + /** + * Constructs a new Builder with the defaults. + * + * @param format the {@link AudioFormat} for the audio mixer. + */ + public Builder(@NonNull AudioFormat format) { + Objects.requireNonNull(format); + mFormat = format; + } + + /** + * Combines all attributes that have been set and returns a new {@link AudioMixerAttributes} + * object. + * @return a new {@link AudioMixerAttributes} object + */ + public @NonNull AudioMixerAttributes build() { + AudioMixerAttributes ama = new AudioMixerAttributes(mFormat, mMixerBehavior); + return ama; + } + + /** + * Sets the mixer behavior for the audio mixer + * @param mixerBehavior must be {@link #MIXER_BEHAVIOR_DEFAULT}. + * @return the same Builder instance. + */ + public @NonNull Builder setMixerBehavior(@MixerBehavior int mixerBehavior) { + switch (mixerBehavior) { + case MIXER_BEHAVIOR_DEFAULT: + mMixerBehavior = mixerBehavior; + break; + default: + throw new IllegalArgumentException("Invalid mixer behavior " + mixerBehavior); + } + return this; + } + } + + @Override + public int hashCode() { + return Objects.hash(mFormat, mMixerBehavior); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + AudioMixerAttributes that = (AudioMixerAttributes) o; + return (mFormat.equals(that.mFormat) + && (mMixerBehavior == that.mMixerBehavior)); + } + + private String mixerBehaviorToString(@MixerBehavior int mixerBehavior) { + switch (mixerBehavior) { + case MIXER_BEHAVIOR_DEFAULT: + return "default"; + default: + return "unknown"; + } + } + + @Override + public String toString() { + return new String("AudioMixerAttributes:" + + " format:" + mFormat.toString() + + " mixer behavior:" + mixerBehaviorToString(mMixerBehavior)); + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(@NonNull Parcel dest, int flags) { + dest.writeParcelable(mFormat, flags); + dest.writeInt(mMixerBehavior); + } + + private AudioMixerAttributes(@NonNull Parcel in) { + mFormat = in.readParcelable(AudioFormat.class.getClassLoader(), AudioFormat.class); + mMixerBehavior = in.readInt(); + } + + public static final @NonNull Parcelable.Creator<AudioMixerAttributes> CREATOR = + new Parcelable.Creator<AudioMixerAttributes>() { + /** + * Rebuilds an AudioMixerAttributes previously stored with writeToParcel(). + * @param p Parcel object to read the AudioMixerAttributes from + * @return a new AudioMixerAttributes created from the data in the parcel + */ + public AudioMixerAttributes createFromParcel(Parcel p) { + return new AudioMixerAttributes(p); + } + + public AudioMixerAttributes[] newArray(int size) { + return new AudioMixerAttributes[size]; + } + }; +} diff --git a/media/java/android/media/AudioSystem.java b/media/java/android/media/AudioSystem.java index a48edac8e080..3e0d657588e5 100644 --- a/media/java/android/media/AudioSystem.java +++ b/media/java/android/media/AudioSystem.java @@ -2260,6 +2260,20 @@ public class AudioSystem /** * @hide + * Register the sound dose callback with the audio server and returns the binder to the + * ISoundDose interface. + * + * @return ISoundDose interface with registered callback. + */ + @Nullable + public static ISoundDose getSoundDoseInterface(ISoundDoseCallback callback) { + return ISoundDose.Stub.asInterface(nativeGetSoundDose(callback)); + } + + private static native IBinder nativeGetSoundDose(ISoundDoseCallback callback); + + /** + * @hide * @param attributes audio attributes describing the playback use case * @param audioProfilesList the list of AudioProfiles that can be played as direct output * @return {@link #SUCCESS} if the list of AudioProfiles was successfully created (can be empty) @@ -2426,4 +2440,40 @@ public class AudioSystem * Keep in sync with core/jni/android_media_DeviceCallback.h. */ final static int NATIVE_EVENT_ROUTING_CHANGE = 1000; + + /** + * @hide + * Query the mixer attributes that can be set as preferred mixer attributes for the given + * device. + */ + public static native int getSupportedMixerAttributes( + int deviceId, @NonNull List<AudioMixerAttributes> mixerAttrs); + + /** + * @hide + * Set preferred mixer attributes for a given device when playing particular + * audio attributes. + */ + public static native int setPreferredMixerAttributes( + @NonNull AudioAttributes attributes, + int portId, + int uid, + @NonNull AudioMixerAttributes mixerAttributes); + + /** + * @hide + * Get preferred mixer attributes that is previously set via + * {link #setPreferredMixerAttributes}. + */ + public static native int getPreferredMixerAttributes( + @NonNull AudioAttributes attributes, int portId, + List<AudioMixerAttributes> mixerAttributesList); + + /** + * @hide + * Clear preferred mixer attributes that is previously set via + * {@link #setPreferredMixerAttributes} + */ + public static native int clearPreferredMixerAttributes( + @NonNull AudioAttributes attributes, int portId, int uid); } diff --git a/media/java/android/media/IAudioService.aidl b/media/java/android/media/IAudioService.aidl index ee453a4541c2..5502db2da4c6 100644 --- a/media/java/android/media/IAudioService.aidl +++ b/media/java/android/media/IAudioService.aidl @@ -23,6 +23,7 @@ import android.media.AudioDeviceAttributes; import android.media.AudioFormat; import android.media.AudioFocusInfo; import android.media.AudioHalVersionInfo; +import android.media.AudioMixerAttributes; import android.media.AudioPlaybackConfiguration; import android.media.AudioRecordingConfiguration; import android.media.AudioRoutesInfo; @@ -37,6 +38,7 @@ import android.media.ICommunicationDeviceDispatcher; import android.media.IDeviceVolumeBehaviorDispatcher; import android.media.IMuteAwaitConnectionCallback; import android.media.IPlaybackConfigDispatcher; +import android.media.IPreferredMixerAttributesDispatcher; import android.media.IRecordingConfigDispatcher; import android.media.IRingtonePlayer; import android.media.IStrategyPreferredDevicesDispatcher; @@ -573,4 +575,14 @@ interface IAudioService { boolean handlesvolumeAdjustment); AudioHalVersionInfo getHalVersion(); + + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_SETTINGS)") + int setPreferredMixerAttributes( + in AudioAttributes aa, int portId, in AudioMixerAttributes mixerAttributes); + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_SETTINGS)") + int clearPreferredMixerAttributes(in AudioAttributes aa, int portId); + void registerPreferredMixerAttributesDispatcher( + IPreferredMixerAttributesDispatcher dispatcher); + oneway void unregisterPreferredMixerAttributesDispatcher( + IPreferredMixerAttributesDispatcher dispatcher); } diff --git a/packages/SystemUI/src/com/android/systemui/qs/NewFooterActionsController.kt b/media/java/android/media/IPreferredMixerAttributesDispatcher.aidl index 7c67d9f42b55..9138fa74eccc 100644 --- a/packages/SystemUI/src/com/android/systemui/qs/NewFooterActionsController.kt +++ b/media/java/android/media/IPreferredMixerAttributesDispatcher.aidl @@ -14,20 +14,21 @@ * limitations under the License. */ -package com.android.systemui.qs +package android.media; -import com.android.systemui.dagger.SysUISingleton -import javax.inject.Inject +import android.media.AudioAttributes; +import android.media.AudioMixerAttributes; + +/** + * AIDL for AudioService to signal preferred mixer attributes update. + * + * {@hide} + */ +oneway interface IPreferredMixerAttributesDispatcher { + + void dispatchPrefMixerAttributesChanged( + in AudioAttributes attributes, + int deviceId, + in @nullable AudioMixerAttributes mixerAttributes); -/** Controller for the footer actions. This manages the initialization of its dependencies. */ -@SysUISingleton -class NewFooterActionsController -@Inject -// TODO(b/242040009): Rename this to FooterActionsController. -constructor( - private val fgsManagerController: FgsManagerController, -) { - fun init() { - fgsManagerController.init() - } } diff --git a/media/java/android/media/MediaMetrics.java b/media/java/android/media/MediaMetrics.java index a4a8cc44984f..5509782e2988 100644 --- a/media/java/android/media/MediaMetrics.java +++ b/media/java/android/media/MediaMetrics.java @@ -49,10 +49,11 @@ public class MediaMetrics { public static final String AUDIO_FOCUS = AUDIO + SEPARATOR + "focus"; public static final String AUDIO_FORCE_USE = AUDIO + SEPARATOR + "forceUse"; public static final String AUDIO_MIC = AUDIO + SEPARATOR + "mic"; + public static final String AUDIO_MIDI = AUDIO + SEPARATOR + "midi"; + public static final String AUDIO_MODE = AUDIO + SEPARATOR + "mode"; public static final String AUDIO_SERVICE = AUDIO + SEPARATOR + "service"; public static final String AUDIO_VOLUME = AUDIO + SEPARATOR + "volume"; public static final String AUDIO_VOLUME_EVENT = AUDIO_VOLUME + SEPARATOR + "event"; - public static final String AUDIO_MODE = AUDIO + SEPARATOR + "mode"; public static final String METRICS_MANAGER = "metrics" + SEPARATOR + "manager"; } @@ -90,15 +91,27 @@ public class MediaMetrics { // The client name public static final Key<String> CLIENT_NAME = createKey("clientName", String.class); + public static final Key<Integer> CLOSED_COUNT = + createKey("closedCount", Integer.class); // MIDI + // The device type public static final Key<Integer> DELAY_MS = createKey("delayMs", Integer.class); // The device type public static final Key<String> DEVICE = createKey("device", String.class); + // Whether the device is disconnected. This is either "true" or "false" + public static final Key<String> DEVICE_DISCONNECTED = + createKey("deviceDisconnected", String.class); // MIDI + + // The ID of the device + public static final Key<Integer> DEVICE_ID = + createKey("deviceId", Integer.class); // MIDI + // For volume changes, up or down public static final Key<String> DIRECTION = createKey("direction", String.class); - + public static final Key<Long> DURATION_NS = + createKey("durationNs", Long.class); // MIDI // A reason for early return or error public static final Key<String> EARLY_RETURN = createKey("earlyReturn", String.class); @@ -128,11 +141,17 @@ public class MediaMetrics { // Generally string "true" or "false" public static final Key<String> HAS_HEAD_TRACKER = createKey("hasHeadTracker", String.class); // spatializer + public static final Key<Integer> HARDWARE_TYPE = + createKey("hardwareType", Integer.class); // MIDI // Generally string "true" or "false" public static final Key<String> HEAD_TRACKER_ENABLED = createKey("headTrackerEnabled", String.class); // spatializer public static final Key<Integer> INDEX = createKey("index", Integer.class); // volume + public static final Key<Integer> INPUT_PORT_COUNT = + createKey("inputPortCount", Integer.class); // MIDI + // Either "true" or "false" + public static final Key<String> IS_SHARED = createKey("isShared", String.class); // MIDI public static final Key<String> LOG_SESSION_ID = createKey("logSessionId", String.class); public static final Key<Integer> MAX_INDEX = createKey("maxIndex", Integer.class); // vol public static final Key<Integer> MIN_INDEX = createKey("minIndex", Integer.class); // vol @@ -149,6 +168,11 @@ public class MediaMetrics { public static final Key<Integer> OBSERVERS = createKey("observers", Integer.class); + public static final Key<Integer> OPENED_COUNT = + createKey("openedCount", Integer.class); // MIDI + public static final Key<Integer> OUTPUT_PORT_COUNT = + createKey("outputPortCount", Integer.class); // MIDI + public static final Key<String> REQUEST = createKey("request", String.class); @@ -163,6 +187,18 @@ public class MediaMetrics { public static final Key<String> STATE = createKey("state", String.class); public static final Key<Integer> STATUS = createKey("status", Integer.class); public static final Key<String> STREAM_TYPE = createKey("streamType", String.class); + + // The following MIDI string is generally either "true" or "false" + public static final Key<String> SUPPORTS_MIDI_UMP = + createKey("supportsMidiUmp", String.class); // Universal MIDI Packets + + public static final Key<Integer> TOTAL_INPUT_BYTES = + createKey("totalInputBytes", Integer.class); // MIDI + public static final Key<Integer> TOTAL_OUTPUT_BYTES = + createKey("totalOutputBytes", Integer.class); // MIDI + + // The following MIDI string is generally either "true" or "false" + public static final Key<String> USING_ALSA = createKey("usingAlsa", String.class); } /** diff --git a/media/java/android/media/MediaRouter2Manager.java b/media/java/android/media/MediaRouter2Manager.java index 7786f619840a..aea6bcb8f89f 100644 --- a/media/java/android/media/MediaRouter2Manager.java +++ b/media/java/android/media/MediaRouter2Manager.java @@ -76,13 +76,7 @@ public final class MediaRouter2Manager { private static MediaRouter2Manager sInstance; private final MediaSessionManager mMediaSessionManager; - - final String mPackageName; - - private final Context mContext; - private final Client mClient; - private final IMediaRouterService mMediaRouterService; private final AtomicInteger mScanRequestCount = new AtomicInteger(/* initialValue= */ 0); final Handler mHandler; @@ -120,16 +114,14 @@ public final class MediaRouter2Manager { } private MediaRouter2Manager(Context context) { - mContext = context.getApplicationContext(); mMediaRouterService = IMediaRouterService.Stub.asInterface( ServiceManager.getService(Context.MEDIA_ROUTER_SERVICE)); mMediaSessionManager = (MediaSessionManager) context .getSystemService(Context.MEDIA_SESSION_SERVICE); - mPackageName = mContext.getPackageName(); mHandler = new Handler(context.getMainLooper()); mClient = new Client(); try { - mMediaRouterService.registerManager(mClient, mPackageName); + mMediaRouterService.registerManager(mClient, context.getPackageName()); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } diff --git a/media/java/android/media/audiopolicy/AudioVolumeGroup.java b/media/java/android/media/audiopolicy/AudioVolumeGroup.java index d58111d1e9a7..1a9ebbc56d68 100644 --- a/media/java/android/media/audiopolicy/AudioVolumeGroup.java +++ b/media/java/android/media/audiopolicy/AudioVolumeGroup.java @@ -51,7 +51,7 @@ public final class AudioVolumeGroup implements Parcelable { /** * human-readable name of this volume group. */ - private final String mName; + private final @NonNull String mName; private final AudioAttributes[] mAudioAttributes; private int[] mLegacyStreamTypes; @@ -113,7 +113,7 @@ public final class AudioVolumeGroup implements Parcelable { AudioVolumeGroup thatAvg = (AudioVolumeGroup) o; - return mName == thatAvg.mName && mId == thatAvg.mId + return mName.equals(thatAvg.mName) && mId == thatAvg.mId && Arrays.equals(mAudioAttributes, thatAvg.mAudioAttributes); } diff --git a/media/java/android/media/midi/IMidiManager.aidl b/media/java/android/media/midi/IMidiManager.aidl index b03f78504635..bd678a5e3197 100644 --- a/media/java/android/media/midi/IMidiManager.aidl +++ b/media/java/android/media/midi/IMidiManager.aidl @@ -60,4 +60,7 @@ interface IMidiManager // used by MIDI devices to report their status // the token is used by MidiService for death notification void setDeviceStatus(in IMidiDeviceServer server, in MidiDeviceStatus status); + + // Updates the number of bytes sent and received + void updateTotalBytes(in IMidiDeviceServer server, int inputBytes, int outputBytes); } diff --git a/media/java/android/media/midi/MidiDeviceServer.java b/media/java/android/media/midi/MidiDeviceServer.java index d5916b9bd6ab..fc33cef9e733 100644 --- a/media/java/android/media/midi/MidiDeviceServer.java +++ b/media/java/android/media/midi/MidiDeviceServer.java @@ -36,6 +36,7 @@ import java.io.FileDescriptor; import java.io.IOException; import java.util.HashMap; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; /** * Internal class used for providing an implementation for a MIDI device. @@ -79,6 +80,9 @@ public final class MidiDeviceServer implements Closeable { private final HashMap<MidiInputPort, PortClient> mInputPortClients = new HashMap<MidiInputPort, PortClient>(); + private AtomicInteger mTotalInputBytes = new AtomicInteger(); + private AtomicInteger mTotalOutputBytes = new AtomicInteger(); + public interface Callback { /** * Called to notify when an our device status has changed @@ -133,6 +137,8 @@ public final class MidiDeviceServer implements Closeable { int portNumber = mOutputPort.getPortNumber(); mInputPortOutputPorts[portNumber] = null; mInputPortOpen[portNumber] = false; + mTotalOutputBytes.addAndGet(mOutputPort.pullTotalBytesCount()); + updateTotalBytes(); updateDeviceStatus(); } IoUtils.closeQuietly(mOutputPort); @@ -156,6 +162,8 @@ public final class MidiDeviceServer implements Closeable { dispatcher.getSender().disconnect(mInputPort); int openCount = dispatcher.getReceiverCount(); mOutputPortOpenCount[portNumber] = openCount; + mTotalInputBytes.addAndGet(mInputPort.pullTotalBytesCount()); + updateTotalBytes(); updateDeviceStatus(); } @@ -405,18 +413,20 @@ public final class MidiDeviceServer implements Closeable { synchronized (mGuard) { if (mIsClosed) return; mGuard.close(); - for (int i = 0; i < mInputPortCount; i++) { MidiOutputPort outputPort = mInputPortOutputPorts[i]; if (outputPort != null) { + mTotalOutputBytes.addAndGet(outputPort.pullTotalBytesCount()); IoUtils.closeQuietly(outputPort); mInputPortOutputPorts[i] = null; } } for (MidiInputPort inputPort : mInputPorts) { + mTotalInputBytes.addAndGet(inputPort.pullTotalBytesCount()); IoUtils.closeQuietly(inputPort); } mInputPorts.clear(); + updateTotalBytes(); try { mMidiManager.unregisterDeviceServer(mServer); } catch (RemoteException e) { @@ -449,4 +459,12 @@ public final class MidiDeviceServer implements Closeable { System.arraycopy(mOutputPortDispatchers, 0, receivers, 0, mOutputPortCount); return receivers; } + + private void updateTotalBytes() { + try { + mMidiManager.updateTotalBytes(mServer, mTotalInputBytes.get(), mTotalOutputBytes.get()); + } catch (RemoteException e) { + Log.e(TAG, "RemoteException in updateTotalBytes"); + } + } } diff --git a/media/java/android/media/midi/MidiInputPort.java b/media/java/android/media/midi/MidiInputPort.java index a300886ea7c1..fe42b58bf315 100644 --- a/media/java/android/media/midi/MidiInputPort.java +++ b/media/java/android/media/midi/MidiInputPort.java @@ -28,6 +28,7 @@ import java.io.Closeable; import java.io.FileDescriptor; import java.io.FileOutputStream; import java.io.IOException; +import java.util.concurrent.atomic.AtomicInteger; /** * This class is used for sending data to a port on a MIDI device @@ -43,6 +44,7 @@ public final class MidiInputPort extends MidiReceiver implements Closeable { private final CloseGuard mGuard = CloseGuard.get(); private boolean mIsClosed; + private AtomicInteger mTotalBytes = new AtomicInteger(); // buffer to use for sending data out our output stream private final byte[] mBuffer = new byte[MidiPortImpl.MAX_PACKET_SIZE]; @@ -87,6 +89,7 @@ public final class MidiInputPort extends MidiReceiver implements Closeable { } int length = MidiPortImpl.packData(msg, offset, count, timestamp, mBuffer); mOutputStream.write(mBuffer, 0, length); + mTotalBytes.addAndGet(length); } } @@ -170,4 +173,12 @@ public final class MidiInputPort extends MidiReceiver implements Closeable { super.finalize(); } } + + /** + * Pulls total number of bytes and sets to zero. This allows multiple callers. + * @hide + */ + public int pullTotalBytesCount() { + return mTotalBytes.getAndSet(0); + } } diff --git a/media/java/android/media/midi/MidiOutputPort.java b/media/java/android/media/midi/MidiOutputPort.java index 5411e669f14d..d9484779055d 100644 --- a/media/java/android/media/midi/MidiOutputPort.java +++ b/media/java/android/media/midi/MidiOutputPort.java @@ -31,6 +31,7 @@ import java.io.Closeable; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.IOException; +import java.util.concurrent.atomic.AtomicInteger; /** * This class is used for receiving data from a port on a MIDI device @@ -46,6 +47,7 @@ public final class MidiOutputPort extends MidiSender implements Closeable { private final CloseGuard mGuard = CloseGuard.get(); private boolean mIsClosed; + private AtomicInteger mTotalBytes = new AtomicInteger(); // This thread reads MIDI events from a socket and distributes them to the list of // MidiReceivers attached to this device. @@ -83,6 +85,7 @@ public final class MidiOutputPort extends MidiSender implements Closeable { Log.e(TAG, "Unknown packet type " + packetType); break; } + mTotalBytes.addAndGet(count); } // while (true) } catch (IOException e) { // FIXME report I/O failure? @@ -163,4 +166,12 @@ public final class MidiOutputPort extends MidiSender implements Closeable { super.finalize(); } } + + /** + * Pulls total number of bytes and sets to zero. This allows multiple callers. + * @hide + */ + public int pullTotalBytesCount() { + return mTotalBytes.getAndSet(0); + } } diff --git a/media/java/android/media/projection/OWNERS b/media/java/android/media/projection/OWNERS index 9ca391013aa3..96532d00831b 100644 --- a/media/java/android/media/projection/OWNERS +++ b/media/java/android/media/projection/OWNERS @@ -1,2 +1,3 @@ michaelwr@google.com santoscordon@google.com +chaviw@google.com diff --git a/media/tests/AudioPolicyTest/AndroidManifest.xml b/media/tests/AudioPolicyTest/AndroidManifest.xml index f696735eb62d..5c911b135a5d 100644 --- a/media/tests/AudioPolicyTest/AndroidManifest.xml +++ b/media/tests/AudioPolicyTest/AndroidManifest.xml @@ -24,13 +24,22 @@ <application> <uses-library android:name="android.test.runner" /> - <activity android:label="@string/app_name" android:name="AudioPolicyTestActivity" + <activity android:label="@string/app_name" android:name="AudioVolumeTestActivity" android:screenOrientation="landscape" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> + <activity android:label="@string/app_name" android:name="AudioPolicyDeathTestActivity" + android:screenOrientation="landscape" + android:process=":AudioPolicyDeathTestActivityProcess" + android:exported="true"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER"/> + </intent-filter> + </activity> </application> <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner" diff --git a/media/tests/AudioPolicyTest/src/com/android/audiopolicytest/AudioPolicyDeathTest.java b/media/tests/AudioPolicyTest/src/com/android/audiopolicytest/AudioPolicyDeathTest.java new file mode 100644 index 000000000000..841804b02354 --- /dev/null +++ b/media/tests/AudioPolicyTest/src/com/android/audiopolicytest/AudioPolicyDeathTest.java @@ -0,0 +1,132 @@ +/* + * 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.audiopolicytest; + +import static androidx.test.core.app.ApplicationProvider.getApplicationContext; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.pm.PackageManager; +import android.media.AudioAttributes; +import android.media.AudioFormat; +import android.media.AudioManager; +import android.media.AudioTrack; +import android.platform.test.annotations.Presubmit; +import android.util.Log; + +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +@Presubmit +@RunWith(AndroidJUnit4.class) +public class AudioPolicyDeathTest { + private static final String TAG = "AudioPolicyDeathTest"; + + private static final int SAMPLE_RATE = 48000; + private static final int PLAYBACK_TIME_MS = 2000; + + private static final IntentFilter AUDIO_NOISY_INTENT_FILTER = + new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY); + + private class MyBroadcastReceiver extends BroadcastReceiver { + private boolean mReceived = false; + @Override + public void onReceive(Context context, Intent intent) { + if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) { + synchronized (this) { + mReceived = true; + notify(); + } + } + } + + public synchronized boolean received() { + return mReceived; + } + } + private final MyBroadcastReceiver mReceiver = new MyBroadcastReceiver(); + + private Context mContext; + + @Before + public void setUp() { + mContext = getApplicationContext(); + assertEquals(PackageManager.PERMISSION_GRANTED, + mContext.checkSelfPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)); + } + + //----------------------------------------------------------------- + // Tests that an AUDIO_BECOMING_NOISY intent is broadcast when an app having registered + // a dynamic audio policy that intercepts an active media playback dies + //----------------------------------------------------------------- + @Test + public void testPolicyClientDeathSendBecomingNoisyIntent() { + mContext.registerReceiver(mReceiver, AUDIO_NOISY_INTENT_FILTER); + + // Launch process registering a dynamic auido policy and dying after PLAYBACK_TIME_MS/2 ms + Intent intent = new Intent(mContext, AudioPolicyDeathTestActivity.class); + intent.putExtra("captureDurationMs", PLAYBACK_TIME_MS / 2); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); + mContext.startActivity(intent); + + AudioTrack track = createAudioTrack(); + track.play(); + synchronized (mReceiver) { + long startTimeMs = System.currentTimeMillis(); + long elapsedTimeMs = 0; + while (elapsedTimeMs < PLAYBACK_TIME_MS && !mReceiver.received()) { + try { + mReceiver.wait(PLAYBACK_TIME_MS - elapsedTimeMs); + } catch (InterruptedException e) { + Log.w(TAG, "wait interrupted"); + } + elapsedTimeMs = System.currentTimeMillis() - startTimeMs; + } + } + + track.stop(); + track.release(); + + assertTrue(mReceiver.received()); + } + + private AudioTrack createAudioTrack() { + AudioFormat format = new AudioFormat.Builder() + .setChannelMask(AudioFormat.CHANNEL_OUT_STEREO) + .setEncoding(AudioFormat.ENCODING_PCM_16BIT) + .setSampleRate(SAMPLE_RATE) + .build(); + + short[] data = new short[PLAYBACK_TIME_MS * SAMPLE_RATE * format.getChannelCount() / 1000]; + AudioAttributes attributes = + new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).build(); + + AudioTrack track = new AudioTrack(attributes, format, data.length, + AudioTrack.MODE_STATIC, AudioManager.AUDIO_SESSION_ID_GENERATE); + track.write(data, 0, data.length); + + return track; + } +} diff --git a/media/tests/AudioPolicyTest/src/com/android/audiopolicytest/AudioPolicyDeathTestActivity.java b/media/tests/AudioPolicyTest/src/com/android/audiopolicytest/AudioPolicyDeathTestActivity.java new file mode 100644 index 000000000000..957e719ab71f --- /dev/null +++ b/media/tests/AudioPolicyTest/src/com/android/audiopolicytest/AudioPolicyDeathTestActivity.java @@ -0,0 +1,132 @@ +/* + * 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.audiopolicytest; + +import android.app.Activity; +import android.media.AudioAttributes; +import android.media.AudioFormat; +import android.media.AudioManager; +import android.media.AudioRecord; +import android.media.audiopolicy.AudioMix; +import android.media.audiopolicy.AudioMixingRule; +import android.media.audiopolicy.AudioPolicy; +import android.os.Bundle; +import android.os.Looper; +import android.util.Log; + +// This activity will register a dynamic audio policy to intercept media playback and launch +// a thread that will capture audio from the policy mix and crash after the time indicated by +// intent extra "captureDurationMs" has elapsed +public class AudioPolicyDeathTestActivity extends Activity { + private static final String TAG = "AudioPolicyDeathTestActivity"; + + private static final int SAMPLE_RATE = 48000; + private static final int RECORD_TIME_MS = 1000; + + private AudioManager mAudioManager = null; + private AudioPolicy mAudioPolicy = null; + + public AudioPolicyDeathTestActivity() { + } + + @Override + public void onCreate(Bundle icicle) { + super.onCreate(icicle); + + mAudioManager = getApplicationContext().getSystemService(AudioManager.class); + + AudioAttributes attributes = new AudioAttributes.Builder() + .setUsage(AudioAttributes.USAGE_MEDIA).build(); + AudioMixingRule.Builder audioMixingRuleBuilder = new AudioMixingRule.Builder() + .addRule(attributes, AudioMixingRule.RULE_MATCH_ATTRIBUTE_USAGE); + + AudioFormat audioFormat = new AudioFormat.Builder() + .setEncoding(AudioFormat.ENCODING_PCM_16BIT) + .setChannelMask(AudioFormat.CHANNEL_OUT_STEREO) + .setSampleRate(SAMPLE_RATE) + .build(); + + AudioMix audioMix = new AudioMix.Builder(audioMixingRuleBuilder.build()) + .setFormat(audioFormat) + .setRouteFlags(AudioMix.ROUTE_FLAG_LOOP_BACK) + .build(); + + AudioPolicy.Builder audioPolicyBuilder = new AudioPolicy.Builder(getApplicationContext()); + audioPolicyBuilder.addMix(audioMix) + .setLooper(Looper.getMainLooper()); + mAudioPolicy = audioPolicyBuilder.build(); + + int result = mAudioManager.registerAudioPolicy(mAudioPolicy); + if (result != AudioManager.SUCCESS) { + Log.w(TAG, "registerAudioPolicy failed, status: " + result); + return; + } + AudioRecord audioRecord = mAudioPolicy.createAudioRecordSink(audioMix); + if (audioRecord == null) { + Log.w(TAG, "AudioRecord creation failed"); + return; + } + + int captureDurationMs = getIntent().getIntExtra("captureDurationMs", RECORD_TIME_MS); + AudioCapturingThread thread = new AudioCapturingThread(audioRecord, captureDurationMs); + thread.start(); + } + + @Override + public void onDestroy() { + super.onDestroy(); + if (mAudioManager != null && mAudioPolicy != null) { + mAudioManager.unregisterAudioPolicy(mAudioPolicy); + } + } + + // A thread that captures audio from the supplied AudioRecord and crashes after the supplied + // duration has elapsed + private static class AudioCapturingThread extends Thread { + private final AudioRecord mAudioRecord; + private final int mDurationMs; + + AudioCapturingThread(AudioRecord record, int durationMs) { + super(); + mAudioRecord = record; + mDurationMs = durationMs; + } + + @Override + @SuppressWarnings("ConstantOverflow") + public void run() { + int samplesLeft = mDurationMs * SAMPLE_RATE * mAudioRecord.getChannelCount() / 1000; + short[] readBuffer = new short[samplesLeft / 10]; + mAudioRecord.startRecording(); + long startTimeMs = System.currentTimeMillis(); + long elapsedTimeMs = 0; + do { + int read = readBuffer.length < samplesLeft ? readBuffer.length : samplesLeft; + read = mAudioRecord.read(readBuffer, 0, read); + elapsedTimeMs = System.currentTimeMillis() - startTimeMs; + if (read < 0) { + Log.w(TAG, "read error: " + read); + break; + } + samplesLeft -= read; + } while (elapsedTimeMs < mDurationMs && samplesLeft > 0); + + // force process to crash + int i = 1 / 0; + } + } +} diff --git a/media/tests/AudioPolicyTest/src/com/android/audiopolicytest/AudioPolicyTestActivity.java b/media/tests/AudioPolicyTest/src/com/android/audiopolicytest/AudioVolumeTestActivity.java index e31c01aae31e..8f61815fe5e6 100644 --- a/media/tests/AudioPolicyTest/src/com/android/audiopolicytest/AudioPolicyTestActivity.java +++ b/media/tests/AudioPolicyTest/src/com/android/audiopolicytest/AudioVolumeTestActivity.java @@ -19,9 +19,9 @@ package com.android.audiopolicytest; import android.app.Activity; import android.os.Bundle; -public class AudioPolicyTestActivity extends Activity { +public class AudioVolumeTestActivity extends Activity { - public AudioPolicyTestActivity() { + public AudioVolumeTestActivity() { } /** Called when the activity is first created. */ diff --git a/media/tests/AudioPolicyTest/src/com/android/audiopolicytest/AudioVolumesTestRule.java b/media/tests/AudioPolicyTest/src/com/android/audiopolicytest/AudioVolumesTestRule.java index fc3b198c4cad..c6ec7a615933 100644 --- a/media/tests/AudioPolicyTest/src/com/android/audiopolicytest/AudioVolumesTestRule.java +++ b/media/tests/AudioPolicyTest/src/com/android/audiopolicytest/AudioVolumesTestRule.java @@ -100,7 +100,7 @@ final class AudioVolumesTestRule extends ExternalResource { @Before public void setUp() throws Exception { - ActivityScenario.launch(AudioPolicyTestActivity.class); + ActivityScenario.launch(AudioVolumeTestActivity.class); mContext = getApplicationContext(); mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); diff --git a/media/tests/projection/OWNERS b/media/tests/projection/OWNERS new file mode 100644 index 000000000000..832bcd9d70e6 --- /dev/null +++ b/media/tests/projection/OWNERS @@ -0,0 +1 @@ +include /media/java/android/media/projection/OWNERS diff --git a/packages/CarrierDefaultApp/res/values-af/strings.xml b/packages/CarrierDefaultApp/res/values-af/strings.xml index 3bc18ce1335e..f3ea488b8938 100644 --- a/packages/CarrierDefaultApp/res/values-af/strings.xml +++ b/packages/CarrierDefaultApp/res/values-af/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Die netwerk waarby jy probeer aansluit, het sekuriteitkwessies."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Byvoorbeeld, die aanmeldbladsy behoort dalk nie aan die organisasie wat gewys word nie."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Gaan in elk geval deur blaaier voort"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Netwerkhupstoot"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s beveel ’n datahupstoot aan"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Koop ’n netwerkhupstoot vir beter werkverrigting"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Nie nou nie"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Bestuur"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Koop ’n netwerkhupstoot."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-ar/strings.xml b/packages/CarrierDefaultApp/res/values-ar/strings.xml index cd979b2fd223..f5ae9f221e35 100644 --- a/packages/CarrierDefaultApp/res/values-ar/strings.xml +++ b/packages/CarrierDefaultApp/res/values-ar/strings.xml @@ -16,16 +16,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"الشبكة التي تحاول الانضمام إليها بها مشاكل أمنية."</string> <string name="ssl_error_example" msgid="6188711843183058764">"على سبيل المثال، قد لا تنتمي صفحة تسجيل الدخول إلى المؤسسة المعروضة."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"المتابعة على أي حال عبر المتصفح"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"خطة معزَّزة للشبكة"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"هناك اقتراح من %s بخطة معزَّزة للبيانات"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"من خلال شراء خطة معزَّزة للشبكة، يمكنك الاستفادة من أداء أفضل."</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"لاحقًا"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"إدارة"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"شراء خطة معزَّزة للشبكة"</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-as/strings.xml b/packages/CarrierDefaultApp/res/values-as/strings.xml index fdafe2b41bf8..b983fd1df1ff 100644 --- a/packages/CarrierDefaultApp/res/values-as/strings.xml +++ b/packages/CarrierDefaultApp/res/values-as/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"আপুনি সংযোগ কৰিবলৈ বিচৰা নেটৱৰ্কটোত সুৰক্ষাজনিত সমস্যা আছে।"</string> <string name="ssl_error_example" msgid="6188711843183058764">"উদাহৰণস্বৰূপে, আপোনাক দেখুওৱা লগ ইনৰ পৃষ্ঠাটো প্ৰতিষ্ঠানটোৰ নিজা নহ\'বও পাৰে।"</string> <string name="ssl_error_continue" msgid="1138548463994095584">"তথাপিও ব্ৰাউজাৰৰ জৰিয়তে অব্যাহত ৰাখক"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"নেটৱৰ্ক পৰিৱৰ্ধন"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%sএ এটা ডেটা পৰিৱৰ্ধনৰ চুপাৰিছ কৰিছে"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"উন্নত পাৰদৰ্শিতা পাবলৈ এটা নেটৱৰ্ক পৰিৱৰ্ধন ক্ৰয় কৰক"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"এতিয়া নহয়"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"পৰিচালনা কৰক"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"এটা নেটৱৰ্ক পৰিৱৰ্ধন ক্ৰয় কৰক।"</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-az/strings.xml b/packages/CarrierDefaultApp/res/values-az/strings.xml index 32c3c1ce2b95..3e6e1a80b13c 100644 --- a/packages/CarrierDefaultApp/res/values-az/strings.xml +++ b/packages/CarrierDefaultApp/res/values-az/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Qoşulmaq istədiyiniz şəbəkənin təhlükəsizlik problemləri var."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Məsələn, giriş səhifəsi göstərilən təşkilata aid olmaya bilər."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Hər bir halda brazuer ilə davam edin"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Əlavə trafik"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s əlavə data trafiki almağı tövsiyə edir"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Daha yaxşı performans üçün əlavə şəbəkə trafiki alın"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"İndi yox"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"İdarə edin"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Əlavə trafik alın."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-b+sr+Latn/strings.xml b/packages/CarrierDefaultApp/res/values-b+sr+Latn/strings.xml index 932fc03a3178..a1974f0da1aa 100644 --- a/packages/CarrierDefaultApp/res/values-b+sr+Latn/strings.xml +++ b/packages/CarrierDefaultApp/res/values-b+sr+Latn/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Mreža kojoj pokušavate da se pridružite ima bezbednosnih problema."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Na primer, stranica za prijavljivanje možda ne pripada prikazanoj organizaciji."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Ipak nastavi preko pregledača"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Pojačanje mreže"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s preporučuje povećanje podataka"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Kupite pojačanje mreže za bolji učinak"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Ne sada"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Upravljajte"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Kupite pojačanje mreže."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-be/strings.xml b/packages/CarrierDefaultApp/res/values-be/strings.xml index 20606f6bd71a..1cb013b5b24f 100644 --- a/packages/CarrierDefaultApp/res/values-be/strings.xml +++ b/packages/CarrierDefaultApp/res/values-be/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"У сеткі, да якой вы спрабуеце далучыцца, ёсць праблемы з бяспекай."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Напрыклад, старонка ўваходу можа не належаць указанай арганізацыі."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Усё роўна працягнуць праз браўзер"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Паскарэнне сеткі"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s рэкамендуе паскарэнне перадачы даных"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Купіце паскарэнне сеткі, каб павысіць прадукцыйнасць"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Не цяпер"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Кіраваць"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Купіць паскарэнне сеткі."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-bg/strings.xml b/packages/CarrierDefaultApp/res/values-bg/strings.xml index 46a9db519af4..aee67d73cb9a 100644 --- a/packages/CarrierDefaultApp/res/values-bg/strings.xml +++ b/packages/CarrierDefaultApp/res/values-bg/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Мрежата, към която опитвате да се присъедините, има проблеми със сигурността."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Например страницата за вход може да не принадлежи на показаната организация."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Продължаване през браузър въпреки това"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Подсилване на мрежата"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s препоръчва увеличаване на данните"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Купете подсилване на мрежата за по-висока ефективност"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Не сега"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Управление"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Купете подсилване на мрежата."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-bn/strings.xml b/packages/CarrierDefaultApp/res/values-bn/strings.xml index 0826ae1dc14f..7f93175961c3 100644 --- a/packages/CarrierDefaultApp/res/values-bn/strings.xml +++ b/packages/CarrierDefaultApp/res/values-bn/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"আপনি যে নেটওয়ার্কে যোগ দেওয়ার চেষ্টা করছেন সেটিতে নিরাপত্তাজনিত সমস্যা আছে।"</string> <string name="ssl_error_example" msgid="6188711843183058764">"যেমন, লগ-ইন পৃষ্ঠাটি যে প্রতিষ্ঠানের পৃষ্ঠা বলে দেখানো আছে, আসলে তা নাও হতে পারে৷"</string> <string name="ssl_error_continue" msgid="1138548463994095584">"যাই হোক, ব্রাউজারের মাধ্যমে চালিয়ে যান"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"নেটওয়ার্ক বুস্ট"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s ডেটা বুস্ট করার জন্য সাজেস্ট করে"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"আরও ভাল পারফর্ম্যান্সের জন্য নেটওয়ার্ক বুস্ট কিনুন"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"এখন নয়"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"ম্যানেজ করুন"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"নেটওয়ার্ক বুস্ট কিনুন।"</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-bs/strings.xml b/packages/CarrierDefaultApp/res/values-bs/strings.xml index e2bc342a41b5..093f03fc4502 100644 --- a/packages/CarrierDefaultApp/res/values-bs/strings.xml +++ b/packages/CarrierDefaultApp/res/values-bs/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Mreža kojoj pokušavate pristupiti ima sigurnosnih problema."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Naprimjer, stranica za prijavljivanje možda ne pripada prikazanoj organizaciji."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Ipak nastavi preko preglednika"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Pojačanje mreže"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s preporučuje povećanje podataka"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Kupite pojačanje mreže za bolju izvedbu"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Ne sad"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Upravljajte"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Kupite pojačanje mreže."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-ca/strings.xml b/packages/CarrierDefaultApp/res/values-ca/strings.xml index bdde56704f9a..63b243ac4a75 100644 --- a/packages/CarrierDefaultApp/res/values-ca/strings.xml +++ b/packages/CarrierDefaultApp/res/values-ca/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"La xarxa a què et vols connectar té problemes de seguretat."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Per exemple, la pàgina d\'inici de sessió podria no pertànyer a l\'organització que es mostra."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Continua igualment mitjançant el navegador"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Optimització de xarxa"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s recomana optimitzar les dades"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Compra una optimització de xarxa per millorar-ne el rendiment"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Ara no"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Gestiona"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Compra una optimització de xarxa."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-cs/strings.xml b/packages/CarrierDefaultApp/res/values-cs/strings.xml index d5fdac963112..3cff883631c3 100644 --- a/packages/CarrierDefaultApp/res/values-cs/strings.xml +++ b/packages/CarrierDefaultApp/res/values-cs/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Síť, ke které se pokoušíte připojit, má bezpečnostní problémy."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Přihlašovací stránka například nemusí patřit zobrazované organizaci."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Přesto pokračovat prostřednictvím prohlížeče"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Zesilovač sítě"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s doporučuje zesílení datového připojení"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Pořiďte si zesilovač, který zvýší výkon sítě"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Teď ne"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Spravovat"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Kupte si zesilovač sítě."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-da/strings.xml b/packages/CarrierDefaultApp/res/values-da/strings.xml index 8b2bb7c164e2..487f62caf001 100644 --- a/packages/CarrierDefaultApp/res/values-da/strings.xml +++ b/packages/CarrierDefaultApp/res/values-da/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Der er sikkerhedsproblemer på det netværk, du forsøger at logge ind på."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Det er f.eks. ikke sikkert, at loginsiden tilhører den anførte organisation."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Fortsæt alligevel via browseren"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Netværksboost"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s anbefaler et databoost"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Køb et netværksboost for at få en bedre ydeevne"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Ikke nu"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Administrer"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Køb et netværksboost."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-de/strings.xml b/packages/CarrierDefaultApp/res/values-de/strings.xml index 21af41cc5a59..1394d107ef55 100644 --- a/packages/CarrierDefaultApp/res/values-de/strings.xml +++ b/packages/CarrierDefaultApp/res/values-de/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Im Netzwerk, zu dem du eine Verbindung herstellen möchtest, liegen Sicherheitsprobleme vor."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Beispiel: Die Log-in-Seite gehört eventuell nicht zur angezeigten Organisation."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Trotzdem in einem Browser fortfahren"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Netzwerk-Boost"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s empfiehlt einen Daten-Boost"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Netzwerk-Boost für bessere Leistung kaufen"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Nicht jetzt"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Verwalten"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Jetzt Netzwerk-Boost kaufen."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-el/strings.xml b/packages/CarrierDefaultApp/res/values-el/strings.xml index 75143143d497..3551401996fa 100644 --- a/packages/CarrierDefaultApp/res/values-el/strings.xml +++ b/packages/CarrierDefaultApp/res/values-el/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Παρουσιάζονται προβλήματα ασφάλειας στο δίκτυο στο οποίο προσπαθείτε να συνδεθείτε."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Για παράδειγμα, η σελίδα σύνδεσης ενδέχεται να μην ανήκει στον οργανισμό που εμφανίζεται."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Συνέχεια ούτως ή άλλως μέσω του προγράμματος περιήγησης"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Ενίσχυση δικτύου"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"Η %s συνιστά ενίσχυση δεδομένων"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Αγοράστε ενίσχυση δικτύου για καλύτερη απόδοση"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Όχι τώρα"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Διαχείριση"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Αγορά ενίσχυσης δικτύου."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-es-rUS/strings.xml b/packages/CarrierDefaultApp/res/values-es-rUS/strings.xml index bddae48eb2d0..5fa83471816d 100644 --- a/packages/CarrierDefaultApp/res/values-es-rUS/strings.xml +++ b/packages/CarrierDefaultApp/res/values-es-rUS/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"La red a la que intentas conectarte tiene problemas de seguridad."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Por ejemplo, es posible que la página de acceso no pertenezca a la organización que aparece."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Continuar de todos modos desde el navegador"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Potenciación de red"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s recomienda un potenciador de datos"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Compra un potenciador de red para obtener un mejor rendimiento"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Ahora no"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Administrar"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Compra un potenciador de red."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-es/strings.xml b/packages/CarrierDefaultApp/res/values-es/strings.xml index dd56770857e3..e65bc9b06589 100644 --- a/packages/CarrierDefaultApp/res/values-es/strings.xml +++ b/packages/CarrierDefaultApp/res/values-es/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"La red a la que intentas unirte tiene problemas de seguridad."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Por ejemplo, es posible que la página de inicio de sesión no pertenezca a la organización mostrada."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Continuar de todos modos a través del navegador"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Mejora de red"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s recomienda una mejora de datos"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Compra una mejora de red para impulsar el rendimiento"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Ahora no"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Gestionar"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Compra una mejora de red."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-et/strings.xml b/packages/CarrierDefaultApp/res/values-et/strings.xml index 8cdc2919e027..a951e7fee145 100644 --- a/packages/CarrierDefaultApp/res/values-et/strings.xml +++ b/packages/CarrierDefaultApp/res/values-et/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Võrgul, millega üritate ühenduse luua, on turvaprobleeme."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Näiteks ei pruugi sisselogimisleht kuuluda kuvatavale organisatsioonile."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Jätka siiski brauseris"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Võrgu võimendus"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s soovitab andmeside võimendust"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Ostke võrgu võimendus, et toimivust parandada"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Mitte praegu"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Haldamine"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Ostke võrgu võimendus."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-eu/strings.xml b/packages/CarrierDefaultApp/res/values-eu/strings.xml index 22565dca4cf6..ad80cc91ae61 100644 --- a/packages/CarrierDefaultApp/res/values-eu/strings.xml +++ b/packages/CarrierDefaultApp/res/values-eu/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Erabili nahi duzun sareak segurtasun-arazoak ditu."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Adibidez, baliteke saioa hasteko orria adierazitako erakundearena ez izatea."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Jarraitu arakatzailearen bidez, halere"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Sarearen hobekuntza"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s zerbitzuak datuak hobetzeko gomendatzen du"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Errendimendua areagotzeko, erosi sarearen hobekuntza bat"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Orain ez"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Kudeatu"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Erosi sarearen hobekuntza bat."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-fa/strings.xml b/packages/CarrierDefaultApp/res/values-fa/strings.xml index ecb9930be98a..4f55d7678fe5 100644 --- a/packages/CarrierDefaultApp/res/values-fa/strings.xml +++ b/packages/CarrierDefaultApp/res/values-fa/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"شبکهای که میخواهید به آن بپیوندید مشکلات امنیتی دارد."</string> <string name="ssl_error_example" msgid="6188711843183058764">"به عنوان مثال، صفحه ورود به سیستم ممکن است متعلق به سازمان نشان داده شده نباشد."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"درهر صورت ازطریق مرورگر ادامه یابد"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"تقویتکننده شبکه"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s توصیه میکند از تقویتکننده داده استفاده کنید"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"برای بهبود عملکرد، تقویتکننده شبکه خریداری کنید"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"اکنون نه"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"مدیریت"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"تقویتکننده شبکه بخرید."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-fi/strings.xml b/packages/CarrierDefaultApp/res/values-fi/strings.xml index 850f9db2a438..5ceddfb71f11 100644 --- a/packages/CarrierDefaultApp/res/values-fi/strings.xml +++ b/packages/CarrierDefaultApp/res/values-fi/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Verkossa, johon yrität muodostaa yhteyttä, havaittiin turvallisuusongelmia."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Kirjautumissivu ei välttämättä kuulu näytetylle organisaatiolle."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Jatka selaimen kautta"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Tehokkaampi verkko"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s suosittelee tehokkaampaa verkkoa"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Osta tehokkaampi verkko, jotta saat parempia tuloksia"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Ei nyt"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Muokkaa"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Osta tehokkaampi verkko."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-fr-rCA/strings.xml b/packages/CarrierDefaultApp/res/values-fr-rCA/strings.xml index 61fc2e4e1780..d7dc3ac2e03b 100644 --- a/packages/CarrierDefaultApp/res/values-fr-rCA/strings.xml +++ b/packages/CarrierDefaultApp/res/values-fr-rCA/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Le réseau que vous essayez de joindre présente des problèmes de sécurité."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Par exemple, la page de connexion pourrait ne pas appartenir à l\'organisation représentée."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Continuer quand même dans un navigateur"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Amplification de réseau"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s recommande une augmentation des données"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Acheter une amplification de réseau pour de meilleures performances"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Plus tard"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Gérer"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Acheter une amplification de réseau."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-fr/strings.xml b/packages/CarrierDefaultApp/res/values-fr/strings.xml index ef1857d925d0..2067e7bd2577 100644 --- a/packages/CarrierDefaultApp/res/values-fr/strings.xml +++ b/packages/CarrierDefaultApp/res/values-fr/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Le réseau auquel vous essayez de vous connecter présente des problèmes de sécurité."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Par exemple, la page de connexion peut ne pas appartenir à l\'organisation représentée."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Continuer quand même dans le navigateur"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Boost réseau"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s recommande de booster les données"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Achetez un boost réseau pour améliorer les performances"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Pas maintenant"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Gérer"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Acheter un boost réseau."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-gl/strings.xml b/packages/CarrierDefaultApp/res/values-gl/strings.xml index 6dde8a87d3ea..a01941f471f6 100644 --- a/packages/CarrierDefaultApp/res/values-gl/strings.xml +++ b/packages/CarrierDefaultApp/res/values-gl/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"A rede á que tentas unirte ten problemas de seguranza."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Por exemplo, é posible que a páxina de inicio de sesión non pertenza á organización que se mostra."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Continuar igualmente co navegador"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Optimizador de rede"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s recomenda un optimizador de datos"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Compra un optimizador de rede para obter un mellor rendemento"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Agora non"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Xestionar"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Compra un optimizador de rede."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-gu/strings.xml b/packages/CarrierDefaultApp/res/values-gu/strings.xml index 473a0357f9af..28f9ecb84395 100644 --- a/packages/CarrierDefaultApp/res/values-gu/strings.xml +++ b/packages/CarrierDefaultApp/res/values-gu/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"તમે જોડાવાનો પ્રયાસ કરી રહ્યા છો તે નેટવર્કમાં સુરક્ષા સંબંધી સમસ્યાઓ છે."</string> <string name="ssl_error_example" msgid="6188711843183058764">"ઉદાહરણ તરીકે, લોગિન પૃષ્ઠ બતાવવામાં આવેલી સંસ્થાનું ન પણ હોય."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"તો પણ બ્રાઉઝર મારફતે ચાલુ રાખો"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"નેટવર્ક બૂસ્ટ"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"ડેટા બૂસ્ટનો સુઝાવ %s દ્વારા આપવામાં આવે છે"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"બહેતર પર્ફોર્મન્સ માટે, કોઈ નેટવર્ક બૂસ્ટ ખરીદો"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"હમણાં નહીં"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"મેનેજ કરો"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"કોઈ નેટવર્ક બૂસ્ટ ખરીદો."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-hi/strings.xml b/packages/CarrierDefaultApp/res/values-hi/strings.xml index d878c1c55996..75206b78efd1 100644 --- a/packages/CarrierDefaultApp/res/values-hi/strings.xml +++ b/packages/CarrierDefaultApp/res/values-hi/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"आप जिस नेटवर्क में शामिल होने की कोशिश कर रहे हैं उसमें सुरक्षा से जुड़ी समस्याएं हैं."</string> <string name="ssl_error_example" msgid="6188711843183058764">"उदाहरण के लिए, हो सकता है कि लॉगिन पेज दिखाए गए संगठन का ना हो."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"ब्राउज़र के ज़रिए किसी भी तरह जारी रखें"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"नेटवर्क बूस्ट"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s, डेटा बूस्ट इस्तेमाल करने का सुझाव देता है"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"बेहतर परफ़ॉर्मेंस के लिए, नेटवर्क बूस्ट खरीदें"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"अभी नहीं"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"मैनेज करें"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"नेटवर्क बूस्ट खरीदें."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-hr/strings.xml b/packages/CarrierDefaultApp/res/values-hr/strings.xml index 0da2280ba1a3..d31f4f8bacbd 100644 --- a/packages/CarrierDefaultApp/res/values-hr/strings.xml +++ b/packages/CarrierDefaultApp/res/values-hr/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Mreža kojoj se pokušavate pridružiti ima sigurnosne poteškoće."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Na primjer, stranica za prijavu možda ne pripada prikazanoj organizaciji."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Ipak nastavi putem preglednika"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Pojačanje mreže"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s preporučuje povećanje podataka"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Kupite pojačanje mreže za bolju izvedbu"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Ne sad"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Upravljajte"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Kupite pojačanje mreže."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-hu/strings.xml b/packages/CarrierDefaultApp/res/values-hu/strings.xml index 95c1db86fc23..afd67422d38e 100644 --- a/packages/CarrierDefaultApp/res/values-hu/strings.xml +++ b/packages/CarrierDefaultApp/res/values-hu/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Biztonsági problémák vannak azzal a hálózattal, amelyhez csatlakozni szeretne."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Például lehetséges, hogy a bejelentkezési oldal nem a megjelenített szervezethez tartozik."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Folytatás ennek ellenére böngészőn keresztül"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Teljesítménynövelés"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s a teljesítménynövelést javasol"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Vásároljon teljesítménynövelési lehetőséget a jobb teljesítmény érdekében"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Most nem"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Kezelés"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Vásároljon teljesítménynövelést."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-hy/strings.xml b/packages/CarrierDefaultApp/res/values-hy/strings.xml index a846e044e7a4..1effc3db80f7 100644 --- a/packages/CarrierDefaultApp/res/values-hy/strings.xml +++ b/packages/CarrierDefaultApp/res/values-hy/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Ցանցը, որին փորձում եք միանալ, անվտանգության խնդիրներ ունի:"</string> <string name="ssl_error_example" msgid="6188711843183058764">"Օրինակ՝ մուտքի էջը կարող է ցուցադրված կազմակերպության էջը չլինել:"</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Շարունակել դիտարկիչի միջոցով"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Բջջային ինտերնետի փաթեթ"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s-ը խորհուրդ է տալիս գնել բջջային ինտերնետի փաթեթ"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Գնեք բջջային ինտերնետի փաթեթ՝ աշխատանքի արդյունավետությունը լավացնելու համար"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Ոչ հիմա"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Կառավարել"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Գնել ցանցի բջջային ինտերնետի փաթեթ։"</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-in/strings.xml b/packages/CarrierDefaultApp/res/values-in/strings.xml index 488ad09a0d32..ed7385ad9309 100644 --- a/packages/CarrierDefaultApp/res/values-in/strings.xml +++ b/packages/CarrierDefaultApp/res/values-in/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Jaringan yang ingin Anda masuki memiliki masalah keamanan."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Misalnya, halaman login mungkin bukan milik organisasi yang ditampilkan."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Tetap lanjutkan melalui browser"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Penguat sinyal"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s merekomendasikan penguat sinyal data seluler"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Beli penguat sinyal untuk performa yang lebih baik"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Lain kali"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Kelola"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Beli penguat sinyal."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-is/strings.xml b/packages/CarrierDefaultApp/res/values-is/strings.xml index ab4981d19579..df8c01b49d8a 100644 --- a/packages/CarrierDefaultApp/res/values-is/strings.xml +++ b/packages/CarrierDefaultApp/res/values-is/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Öryggisvandamál eru á netinu sem þú ert að reyna að tengjast."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Til dæmis getur verið að innskráningarsíðan tilheyri ekki fyrirtækinu sem birtist."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Halda samt áfram í vafra"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Nethröðun"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s mælir með auknu gagnamagni"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Kauptu nethröðun til að bæta afköstin"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Ekki núna"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Stjórna"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Kaupa nethröðun."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-it/strings.xml b/packages/CarrierDefaultApp/res/values-it/strings.xml index 95ea06084240..3c76f21175aa 100644 --- a/packages/CarrierDefaultApp/res/values-it/strings.xml +++ b/packages/CarrierDefaultApp/res/values-it/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"La rete a cui stai tentando di accedere presenta problemi di sicurezza."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Ad esempio, la pagina di accesso potrebbe non appartenere all\'organizzazione indicata."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Continua comunque dal browser"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Potenziamento di rete"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s consiglia un aumento dei dati"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Acquista un potenziamento di rete per migliorare le prestazioni"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Non ora"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Gestisci"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Acquista un potenziamento di rete."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-iw/strings.xml b/packages/CarrierDefaultApp/res/values-iw/strings.xml index 263ed1ab4c3e..9f7cc8e72a1e 100644 --- a/packages/CarrierDefaultApp/res/values-iw/strings.xml +++ b/packages/CarrierDefaultApp/res/values-iw/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"יש בעיות אבטחה ברשת שאליה אתה מנסה להתחבר."</string> <string name="ssl_error_example" msgid="6188711843183058764">"לדוגמה, ייתכן שדף ההתחברות אינו שייך לארגון המוצג."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"המשך בכל זאת באמצעות דפדפן"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"מגבר לרשת"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"יש המלצה של %s להגברת הרשת"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"קניית מגבר לרשת לשיפור הביצועים"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"לא עכשיו"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"ניהול"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"קניית מגבר לרשת."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-ja/strings.xml b/packages/CarrierDefaultApp/res/values-ja/strings.xml index 3b22ae186196..4b709afc8f6f 100644 --- a/packages/CarrierDefaultApp/res/values-ja/strings.xml +++ b/packages/CarrierDefaultApp/res/values-ja/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"接続しようとしているネットワークにセキュリティの問題があります。"</string> <string name="ssl_error_example" msgid="6188711843183058764">"たとえば、ログインページが表示されている組織に属していない可能性があります。"</string> <string name="ssl_error_continue" msgid="1138548463994095584">"ブラウザから続行"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"ネットワーク ブースト"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s ではデータブーストが推奨されます"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"ネットワーク ブーストを購入してパフォーマンスを改善しましょう"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"後で"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"管理"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"ネットワーク ブーストを購入できます。"</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-ka/strings.xml b/packages/CarrierDefaultApp/res/values-ka/strings.xml index 4b9cd387f0a1..713c48831dfa 100644 --- a/packages/CarrierDefaultApp/res/values-ka/strings.xml +++ b/packages/CarrierDefaultApp/res/values-ka/strings.xml @@ -14,16 +14,12 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"ქსელს, რომელთან დაკავშრებასაც ცდილობთ, უსაფრთხოების პრობლემები აქვს."</string> <string name="ssl_error_example" msgid="6188711843183058764">"მაგალითად, სისტემაში შესვლის გვერდი შეიძლება არ ეკუთვნოდეს ნაჩვენებ ორგანიზაციას."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"მაინც ბრაუზერში გაგრძელება"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"ქსელის გაძლიერება"</string> + <!-- String.format failed for translation --> <!-- no translation found for network_boost_notification_title (8226368121348880044) --> <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"შეიძინეთ ქსელის გაძლიერება უკეთესი მუშაობისთვის"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"ახლა არა"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"მართვა"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"შეიძინეთ ქსელის გაძლიერება."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-kk/strings.xml b/packages/CarrierDefaultApp/res/values-kk/strings.xml index fce8dd24a036..13fdc0a1e4b7 100644 --- a/packages/CarrierDefaultApp/res/values-kk/strings.xml +++ b/packages/CarrierDefaultApp/res/values-kk/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Қосылайын деп жатқан желіңізде қауіпсіздік мәселелері бар."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Мысалы, кіру беті көрсетілген ұйымға тиесілі болмауы мүмкін."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Бәрібір браузер арқылы жалғастыру"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Күшейтілген желі"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s күшейтілген желі пакетін ұсынады"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Өнімділікті арттыру үшін күшейтілген желі пакетін сатып алыңыз."</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Қазір емес"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Басқару"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Күшейтілген желіні сатып алыңыз."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-km/strings.xml b/packages/CarrierDefaultApp/res/values-km/strings.xml index 983f09e74111..7993f6fd4552 100644 --- a/packages/CarrierDefaultApp/res/values-km/strings.xml +++ b/packages/CarrierDefaultApp/res/values-km/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"បណ្តាញដែលអ្នកកំពុងព្យាយាមចូលមានបញ្ហាសុវត្ថិភាព។"</string> <string name="ssl_error_example" msgid="6188711843183058764">"ឧទាហរណ៍៖ ទំព័រចូលនេះអាចនឹងមិនមែនជាកម្មសិទ្ធិរបស់ស្ថាប័នដែលបានបង្ហាញនេះទេ។"</string> <string name="ssl_error_continue" msgid="1138548463994095584">"យ៉ាងណាក៏ដោយនៅតែបន្តតាមរយៈកម្មវិធីរុករកតាមអ៊ីនធឺណិត"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"ការបង្កើនល្បឿនបណ្ដាញ"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s ណែនាំឱ្យបង្កើនទិន្នន័យ"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"ទិញការបង្កើនល្បឿនបណ្ដាញ ដើម្បីឱ្យប្រតិបត្តិការប្រសើរជាងមុន"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"កុំទាន់"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"គ្រប់គ្រង"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"ទិញការបង្កើនល្បឿនបណ្ដាញ។"</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-kn/strings.xml b/packages/CarrierDefaultApp/res/values-kn/strings.xml index 86b29cece868..323885e1a431 100644 --- a/packages/CarrierDefaultApp/res/values-kn/strings.xml +++ b/packages/CarrierDefaultApp/res/values-kn/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"ನೀವು ಸೇರಬೇಕೆಂದಿರುವ ನೆಟ್ವರ್ಕ್, ಭದ್ರತೆ ಸಮಸ್ಯೆಗಳನ್ನು ಹೊಂದಿದೆ."</string> <string name="ssl_error_example" msgid="6188711843183058764">"ಉದಾಹರಣೆಗೆ, ಲಾಗಿನ್ ಪುಟವು ತೋರಿಸಲಾಗಿರುವ ಸಂಸ್ಥೆಗೆ ಸಂಬಂಧಿಸಿಲ್ಲದಿರಬಹುದು."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"ಪರವಾಗಿಲ್ಲ, ಬ್ರೌಸರ್ ಮೂಲಕ ಮುಂದುವರಿಸಿ"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"ನೆಟ್ವರ್ಕ್ ಬೂಸ್ಟ್"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s ಡೇಟಾ ಬೂಸ್ಟ್ ಅನ್ನು ಶಿಫಾರಸು ಮಾಡುತ್ತದೆ"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"ಉತ್ತಮ ಕಾರ್ಯಕ್ಷಮತೆಗಾಗಿ ನೆಟ್ವರ್ಕ್ ಬೂಸ್ಟ್ ಅನ್ನು ಖರೀದಿಸಿ"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"ಸದ್ಯಕ್ಕೆ ಬೇಡ"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"ನಿರ್ವಹಿಸಿ"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"ನೆಟ್ವರ್ಕ್ ಬೂಸ್ಟ್ ಖರೀದಿಸಿ."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-ko/strings.xml b/packages/CarrierDefaultApp/res/values-ko/strings.xml index 3c6f4a67228f..8ce69a33a45f 100644 --- a/packages/CarrierDefaultApp/res/values-ko/strings.xml +++ b/packages/CarrierDefaultApp/res/values-ko/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"가입하려는 네트워크에 보안 문제가 있습니다."</string> <string name="ssl_error_example" msgid="6188711843183058764">"예를 들어 로그인 페이지가 표시된 조직에 속하지 않을 수 있습니다."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"브라우저를 통해 계속하기"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"성능 향상"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s에서 성능 향상을 권장합니다"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"성능 향상을 구매하여 성능을 개선하세요."</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"나중에"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"관리"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"성능 향상을 구매하세요."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-ky/strings.xml b/packages/CarrierDefaultApp/res/values-ky/strings.xml index 3cece7de3a18..637620c22dd4 100644 --- a/packages/CarrierDefaultApp/res/values-ky/strings.xml +++ b/packages/CarrierDefaultApp/res/values-ky/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Кошулайын деген тармагыңызда коопсуздук көйгөйлөрү бар."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Мисалы, аккаунтка кирүү баракчасы көрсөтүлгөн уюмга таандык эмес болушу мүмкүн."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Баары бир серепчи аркылуу улантуу"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Тармакты оптималдаштыруу"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s тармак оптималдаштыруусун сунуштайт"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Иштин майнаптуулугун жогорулатуу үчүн тармакты оптималдаштыруу мүмкүнчүлүгүн сатып алыңыз"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Азыр эмес"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Тескөө"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Тармакты оптималдаштырууну сатып алыңыз."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-lo/strings.xml b/packages/CarrierDefaultApp/res/values-lo/strings.xml index c6c0533b09e1..124e5cc79c5e 100644 --- a/packages/CarrierDefaultApp/res/values-lo/strings.xml +++ b/packages/CarrierDefaultApp/res/values-lo/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"ເຄືອຂ່າຍທີ່ທ່ານກຳລັງເຂົ້າຮ່ວມມີບັນຫາຄວາມປອດໄພ."</string> <string name="ssl_error_example" msgid="6188711843183058764">"ຕົວຢ່າງ, ໜ້າເຂົ້າສູ່ລະບົບອາດຈະບໍ່ແມ່ນຂອງອົງກອນທີ່ປາກົດ."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"ດຳເນີນການຕໍ່ຜ່ານໂປຣແກຣມທ່ອງເວັບ"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"ການເພີ່ມປະສິດທິພາບເຄືອຂ່າຍ"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s ແນະນຳໃຫ້ເພີ່ມປະສິດທິພາບຂໍ້ມູນ"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"ຊື້ການເພີ່ມປະສິດທິພາບເຄືອຂ່າຍເພື່ອປະສິດທິພາບການເຮັດວຽກທີ່ດີຂຶ້ນ"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"ບໍ່ຟ້າວເທື່ອ"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"ຈັດການ"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"ຊື້ການເພີ່ມປະສິດທິພາບເຄືອຂ່າຍ."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-lt/strings.xml b/packages/CarrierDefaultApp/res/values-lt/strings.xml index fe33b1de6c75..61e159325cb3 100644 --- a/packages/CarrierDefaultApp/res/values-lt/strings.xml +++ b/packages/CarrierDefaultApp/res/values-lt/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Kilo tinklo, prie kurio bandote prisijungti, saugos problemų."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Pavyzdžiui, prisijungimo puslapis gali nepriklausyti rodomai organizacijai."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Vis tiek tęsti naudojant naršyklę"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Papildomi duomenys"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s rekomenduoja įsigyti papildomų duomenų"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Įsigykite papildomų duomenų, kad pagerintumėte našumą"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Ne dabar"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Tvarkyti"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Įsigykite papildomų duomenų."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-lv/strings.xml b/packages/CarrierDefaultApp/res/values-lv/strings.xml index f8864e2a0e52..3472b4c4050f 100644 --- a/packages/CarrierDefaultApp/res/values-lv/strings.xml +++ b/packages/CarrierDefaultApp/res/values-lv/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Tīklā, kuram mēģināt pievienoties, ir drošības problēmas."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Piemēram, pieteikšanās lapa, iespējams, nepieder norādītajai organizācijai."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Tomēr turpināt, izmantojot pārlūkprogrammu"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Tīkla veiktspējas uzlabojums"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s iesaka veiktspējas uzlabojumu"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Iegādājieties tīkla veiktspējas uzlabojumu."</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Vēlāk"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Pārvaldīt"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Iegādājieties tīkla veiktspējas uzlabojumu."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-mk/strings.xml b/packages/CarrierDefaultApp/res/values-mk/strings.xml index 0b8daafe8d41..759c58adc3b4 100644 --- a/packages/CarrierDefaultApp/res/values-mk/strings.xml +++ b/packages/CarrierDefaultApp/res/values-mk/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Мрежата на која се обидувате да се придружите има проблеми со безбедноста."</string> <string name="ssl_error_example" msgid="6188711843183058764">"На пример, страницата за најавување може да не припаѓа на прикажаната организација."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Сепак продолжи преку прелистувач"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Засилување за мрежата"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s препорачува засилување за мрежата"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Купете засилување за мрежата за подобра изведба"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Не сега"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Управувајте"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Купете засилување за мрежата."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-ml/strings.xml b/packages/CarrierDefaultApp/res/values-ml/strings.xml index f27d4d864a3b..08a04e374a7f 100644 --- a/packages/CarrierDefaultApp/res/values-ml/strings.xml +++ b/packages/CarrierDefaultApp/res/values-ml/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"നിങ്ങൾ ചേരാൻ ശ്രമിക്കുന്ന നെറ്റ്വർക്കിൽ സുരക്ഷാ പ്രശ്നങ്ങളുണ്ടായിരിക്കാം."</string> <string name="ssl_error_example" msgid="6188711843183058764">"ഉദാഹരണത്തിന്, കാണിച്ചിരിക്കുന്ന ഓർഗനൈസേഷന്റേതായിരിക്കില്ല ലോഗിൻ പേജ്."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"എന്തായാലും ബ്രൗസർ വഴി തുടരുക"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"നെറ്റ്വർക്ക് ബൂസ്റ്റ്"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s ഡാറ്റാ ബൂസ്റ്റ് നിർദ്ദേശിക്കുന്നു"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"മികച്ച പ്രകടനത്തിന് നെറ്റ്വർക്ക് ബൂസ്റ്റ് വാങ്ങുക"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"ഇപ്പോൾ വേണ്ട"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"മാനേജ് ചെയ്യുക"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"ഒരു നെറ്റ്വർക്ക് ബൂസ്റ്റ് വാങ്ങുക."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-mn/strings.xml b/packages/CarrierDefaultApp/res/values-mn/strings.xml index 354bd349ac41..5ef4243a1254 100644 --- a/packages/CarrierDefaultApp/res/values-mn/strings.xml +++ b/packages/CarrierDefaultApp/res/values-mn/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Таны холбогдох гэж буй сүлжээ аюулгүй байдлын асуудалтай байна."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Жишээлбэл нэвтрэх хуудас нь харагдаж буй байгууллагынх биш байж болно."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Ямар ч тохиолдолд хөтчөөр үргэлжлүүлэх"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Сүлжээний идэвхжүүлэлт"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s дата идэвхжүүлэлтийг санал болгодог"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Илүү сайн гүйцэтгэл авах бол сүлжээний идэвхжүүлэлтийг худалдаж авна уу"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Одоо биш"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Удирдах"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Сүлжээний идэвхжүүлэлтийг худалдан авна уу."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-mr/strings.xml b/packages/CarrierDefaultApp/res/values-mr/strings.xml index c61d3c8e2eea..930ed8cdbfdc 100644 --- a/packages/CarrierDefaultApp/res/values-mr/strings.xml +++ b/packages/CarrierDefaultApp/res/values-mr/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"तुम्ही ज्या नेटवर्कमध्ये सामील होण्याचा प्रयत्न करत आहात त्यात सुरक्षितता समस्या आहेत."</string> <string name="ssl_error_example" msgid="6188711843183058764">"उदाहरणार्थ, लॉग इन पृष्ठ दर्शवलेल्या संस्थेच्या मालकीचे नसू शकते."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"तरीही ब्राउझरद्वारे सुरू ठेवा"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"नेटवर्क बूस्ट"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s डेटा बूस्टची शिफारस करते"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"आणखी चांगल्या परफॉर्मन्ससाठी नेटवर्क बूस्ट खरेदी करा"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"आता नको"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"व्यवस्थापित करा"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"नेटवर्क बूस्ट खरेदी करा."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-ms/strings.xml b/packages/CarrierDefaultApp/res/values-ms/strings.xml index 366463ff90ce..2f959154c88a 100644 --- a/packages/CarrierDefaultApp/res/values-ms/strings.xml +++ b/packages/CarrierDefaultApp/res/values-ms/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Rangkaian yang cuba anda sertai mempunyai isu keselamatan."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Contohnya, halaman log masuk mungkin bukan milik organisasi yang ditunjukkan."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Teruskan juga melalui penyemak imbas"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Perangsang rangkaian"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s mengesyorkan peningkatan data"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Beli perangsang rangkaian untuk mendapatkan prestasi yang lebih baik"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Bukan sekarang"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Urus"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Beli perangsang rangkaian."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-my/strings.xml b/packages/CarrierDefaultApp/res/values-my/strings.xml index 2fa618829f51..1ca4317970f5 100644 --- a/packages/CarrierDefaultApp/res/values-my/strings.xml +++ b/packages/CarrierDefaultApp/res/values-my/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"သင်ချိတ်ဆက်ရန် ကြိုးစားနေသည့် ကွန်ရက်တွင် လုံခြုံရေးပြဿနာများ ရှိနေသည်။"</string> <string name="ssl_error_example" msgid="6188711843183058764">"ဥပမာ− ဝင်ရောက်ရန် စာမျက်နှာသည် ပြသထားသည့် အဖွဲ့အစည်းနှင့် သက်ဆိုင်မှုမရှိခြင်း ဖြစ်နိုင်ပါသည်။"</string> <string name="ssl_error_continue" msgid="1138548463994095584">"မည်သို့ပင်ဖြစ်စေ ဘရောက်ဇာမှတစ်ဆင့် ရှေ့ဆက်ရန်"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"ကွန်ရက်မြှင့်တင်အက်ပ်"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s က ဒေတာမြှင့်တင်ရန် အကြံပြုသည်"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"စွမ်းဆောင်ရည် ပိုကောင်းစေရန် ကွန်ရက်မြှင့်တင်အက်ပ် ဝယ်ပါ"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"ယခုမလုပ်ပါ"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"စီမံရန်"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"ကွန်ရက်မြှင့်တင်အက်ပ် ဝယ်ယူရန်။"</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-nb/strings.xml b/packages/CarrierDefaultApp/res/values-nb/strings.xml index 16f8eaadcb0a..86602072604c 100644 --- a/packages/CarrierDefaultApp/res/values-nb/strings.xml +++ b/packages/CarrierDefaultApp/res/values-nb/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Nettverket du prøver å logge på, har sikkerhetsproblemer."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Det er for eksempel mulig at påloggingssiden ikke tilhører organisasjonen som vises."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Fortsett likevel via nettleseren"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Nettverksboost"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s anbefaler en databoost"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Kjøp en nettverksboost for å få bedre ytelse"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Ikke nå"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Administrer"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Kjøp en nettverksboost."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-ne/strings.xml b/packages/CarrierDefaultApp/res/values-ne/strings.xml index cb175df24a12..c92237cb4136 100644 --- a/packages/CarrierDefaultApp/res/values-ne/strings.xml +++ b/packages/CarrierDefaultApp/res/values-ne/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"तपाईंले सामेल हुने प्रयास गरिरहनु भएको नेटवर्कमा सुरक्षा सम्बन्धी समस्याहरू छन्।"</string> <string name="ssl_error_example" msgid="6188711843183058764">"उदाहरणका लागि, लग इन पृष्ठ देखाइएको संस्थाको नहुन सक्छ।"</string> <string name="ssl_error_continue" msgid="1138548463994095584">"जे भए पनि ब्राउजर मार्फत जारी राख्नुहोस्"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"नेटवर्क बुस्ट"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s ले डेटा बुस्ट किन्न सिफारिस गर्छ"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"अझ राम्रो पर्फर्मेन्सका लागि नेटवर्क बुस्ट किन्नुहोस्"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"अहिले होइन"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"व्यवस्थापन गर्नुहोस्"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"नेटवर्क बुस्ट किन्नुहोस्।"</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-nl/strings.xml b/packages/CarrierDefaultApp/res/values-nl/strings.xml index 8511ff5e9ab3..1cd929ee23bd 100644 --- a/packages/CarrierDefaultApp/res/values-nl/strings.xml +++ b/packages/CarrierDefaultApp/res/values-nl/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Het netwerk waarmee je verbinding probeert te maken, heeft beveiligingsproblemen."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Zo hoort de weergegeven inlogpagina misschien niet bij de weergegeven organisatie."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Toch doorgaan via browser"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Netwerkboost"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s raadt een databoost aan"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Koop een netwerkboost voor betere prestaties"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Niet nu"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Beheren"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Koop een netwerkboost."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-or/strings.xml b/packages/CarrierDefaultApp/res/values-or/strings.xml index 65fd7bb687b5..4a01c1278fad 100644 --- a/packages/CarrierDefaultApp/res/values-or/strings.xml +++ b/packages/CarrierDefaultApp/res/values-or/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"ଆପଣ ଯୋଗ ଦେବାକୁ ଚେଷ୍ଟା କରୁଥିବା ନେଟୱର୍କର ସୁରକ୍ଷା ସମସ୍ୟା ଅଛି।"</string> <string name="ssl_error_example" msgid="6188711843183058764">"ଉଦାହରଣସ୍ୱରୂପ, ଲଗଇନ୍ ପୃଷ୍ଠା ଦେଖାଯାଇଥିବା ସଂସ୍ଥାର ହୋଇନଥାଇପାରେ।"</string> <string name="ssl_error_continue" msgid="1138548463994095584">"ବ୍ରାଉଜର୍ ଜରିଆରେ ଯେମିତିବି ହେଉ ଜାରି ରଖନ୍ତୁ"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"ନେଟୱାର୍କ ବୁଷ୍ଟ"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s ଏକ ଡାଟା ବୁଷ୍ଟ ପାଇଁ ସୁପାରିଶ କରେ"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"ଆହୁରି ଭଲ ପରଫରମାନ୍ସ ପାଇଁ ଏକ ନେଟୱାର୍କ ବୁଷ୍ଟ କିଣନ୍ତୁ"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"ବର୍ତ୍ତମାନ ନୁହେଁ"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"ପରିଚାଳନା କରନ୍ତୁ"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"ଏକ ନେଟୱାର୍କ ବୁଷ୍ଟ କିଣନ୍ତୁ।"</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-pa/strings.xml b/packages/CarrierDefaultApp/res/values-pa/strings.xml index 0f096ab1914d..6b15c1e6844d 100644 --- a/packages/CarrierDefaultApp/res/values-pa/strings.xml +++ b/packages/CarrierDefaultApp/res/values-pa/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"ਤੁਸੀਂ ਜਿਸ ਨੈੱਟਵਰਕ ਵਿੱਚ ਸ਼ਾਮਲ ਹੋਣ ਦੀ ਕੋਸ਼ਿਸ਼ ਕਰ ਰਹੇ ਹੋ ਉਸ ਵਿੱਚ ਸੁਰੱਖਿਆ ਸਬੰਧੀ ਸਮੱਸਿਆਵਾਂ ਹਨ।"</string> <string name="ssl_error_example" msgid="6188711843183058764">"ਉਦਾਹਰਣ ਵੱਜੋਂ, ਲੌਗ-ਇਨ ਪੰਨਾ ਦਿਖਾਈ ਗਈ ਸੰਸਥਾ ਨਾਲ ਸੰਬੰਧਿਤ ਨਹੀਂ ਹੋ ਸਕਦਾ ਹੈ।"</string> <string name="ssl_error_continue" msgid="1138548463994095584">"ਬ੍ਰਾਊਜ਼ਰ ਰਾਹੀਂ ਫਿਰ ਵੀ ਜਾਰੀ ਰੱਖੋ"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"ਨੈੱਟਵਰਕ ਬੂਸਟ"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s ਵੱਲੋਂ ਡਾਟਾ ਬੂਸਟ ਦੀ ਸਿਫ਼ਾਰਸ਼ ਕੀਤੀ ਜਾਂਦੀ ਹੈ"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"ਬਿਹਤਰ ਕਾਰਗੁਜ਼ਾਰੀ ਲਈ ਨੈੱਟਵਰਕ ਬੂਸਟ ਖਰੀਦੋ"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"ਹੁਣੇ ਨਹੀਂ"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"ਪ੍ਰਬੰਧਨ ਕਰੋ"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"ਨੈੱਟਵਰਕ ਬੂਸਟ ਖਰੀਦੋ।"</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-pl/strings.xml b/packages/CarrierDefaultApp/res/values-pl/strings.xml index 08bc76731a43..86306a29b4a3 100644 --- a/packages/CarrierDefaultApp/res/values-pl/strings.xml +++ b/packages/CarrierDefaultApp/res/values-pl/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"W sieci, z którą próbujesz się połączyć, występują problemy z zabezpieczeniami."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Na przykład strona logowania może nie należeć do wyświetlanej organizacji."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Kontynuuj mimo to w przeglądarce"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Wzmocnienie sygnału"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s zaleca wzmocnienie transmisji danych"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Kup wzmocnienie sygnału, aby zwiększyć skuteczność sieci"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Nie teraz"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Zarządzaj"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Kup wzmocnienie sygnału"</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-pt-rBR/strings.xml b/packages/CarrierDefaultApp/res/values-pt-rBR/strings.xml index 23b4152b231d..1138a8bf59d9 100644 --- a/packages/CarrierDefaultApp/res/values-pt-rBR/strings.xml +++ b/packages/CarrierDefaultApp/res/values-pt-rBR/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"A rede à qual você está tentando se conectar tem problemas de segurança."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Por exemplo, a página de login pode não pertencer à organização mostrada."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Continuar mesmo assim pelo navegador"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Aumento de rede"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s recomenda um aumento de dados"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Aumente a rede para ter um desempenho melhor"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Agora não"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Gerenciar"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Comprar um aumento de rede."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-pt/strings.xml b/packages/CarrierDefaultApp/res/values-pt/strings.xml index 23b4152b231d..1138a8bf59d9 100644 --- a/packages/CarrierDefaultApp/res/values-pt/strings.xml +++ b/packages/CarrierDefaultApp/res/values-pt/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"A rede à qual você está tentando se conectar tem problemas de segurança."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Por exemplo, a página de login pode não pertencer à organização mostrada."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Continuar mesmo assim pelo navegador"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Aumento de rede"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s recomenda um aumento de dados"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Aumente a rede para ter um desempenho melhor"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Agora não"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Gerenciar"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Comprar um aumento de rede."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-ro/strings.xml b/packages/CarrierDefaultApp/res/values-ro/strings.xml index 165952cb7e4c..4a9d57c2bbe5 100644 --- a/packages/CarrierDefaultApp/res/values-ro/strings.xml +++ b/packages/CarrierDefaultApp/res/values-ro/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Rețeaua la care încercați să vă conectați are probleme de securitate."</string> <string name="ssl_error_example" msgid="6188711843183058764">"De exemplu, este posibil ca pagina de conectare să nu aparțină organizației afișate."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Continuă oricum prin browser"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Pachet de date"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s recomandă un pachet de date"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Cumpără un pachet de date pentru o performanță mai bună"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Nu acum"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Gestionează"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Cumpără un pachet de date."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-ru/strings.xml b/packages/CarrierDefaultApp/res/values-ru/strings.xml index 77ce91fecd4b..4fd6ffbaacf8 100644 --- a/packages/CarrierDefaultApp/res/values-ru/strings.xml +++ b/packages/CarrierDefaultApp/res/values-ru/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Сеть, к которой вы хотите подключиться, небезопасна."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Например, страница входа в аккаунт может быть фиктивной."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Продолжить в браузере"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Ускорение сети"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s рекомендует использовать дополнительные данные"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Приобретите ускорение сети, чтобы повысить ее производительность"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Не сейчас"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Настроить"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Покупка ускорения сети."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-si/strings.xml b/packages/CarrierDefaultApp/res/values-si/strings.xml index fe981ca7cbce..7dad968eb12d 100644 --- a/packages/CarrierDefaultApp/res/values-si/strings.xml +++ b/packages/CarrierDefaultApp/res/values-si/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"ඔබ සම්බන්ධ වීමට උත්සහ කරන ජාලයේ ආරක්ෂක ගැටළු ඇත."</string> <string name="ssl_error_example" msgid="6188711843183058764">"උදාහරණයක් ලෙස, පුරනය වන පිටුව පෙන්වා ඇති සංවිධානයට අයිති නැති විය හැක."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"කෙසේ වුවත් බ්රවුසරය හරහා ඉදිරියට යන්න"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"ජාල වැඩි කිරීම"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s දත්ත වැඩි කිරීමක් නිර්දේශ කරයි"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"වඩා හොඳ කාර්ය සාධනයක් සඳහා ජාල වැඩි වීමක් මිල දී ගන්න"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"දැන් නොවේ"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"කළමනාකරණය කරන්න"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"ජාල වැඩි වීමක් මිල දී ගන්න."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-sl/strings.xml b/packages/CarrierDefaultApp/res/values-sl/strings.xml index 1a0f74b931d6..66dec186e034 100644 --- a/packages/CarrierDefaultApp/res/values-sl/strings.xml +++ b/packages/CarrierDefaultApp/res/values-sl/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Omrežje, ki se mu poskušate pridružiti, ima varnostne težave."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Stran za prijavo na primer morda ne pripada prikazani organizaciji."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Vseeno nadaljuj v brskalniku"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Izboljšanje omrežja"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s priporoča izboljšanje prenosa podatkov"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Za boljše delovanje si zagotovite izboljšanje omrežja."</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Ne zdaj"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Upravljanje"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Nakup izboljšanja omrežja"</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-sq/strings.xml b/packages/CarrierDefaultApp/res/values-sq/strings.xml index f6e19355ac8a..c0d430e17aee 100644 --- a/packages/CarrierDefaultApp/res/values-sq/strings.xml +++ b/packages/CarrierDefaultApp/res/values-sq/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Rrjeti në të cilin po përpiqesh të bashkohesh ka probleme sigurie."</string> <string name="ssl_error_example" msgid="6188711843183058764">"për shembull, faqja e identifikimit mund të mos i përkasë organizatës së shfaqur."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Vazhdo gjithsesi nëpërmjet shfletuesit"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Paketa e përforcimit të rrjetit"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s rekomandon një paketë përforcimi të të dhënave"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Bli një paketë përforcimi të rrjetit për një performancë më të mirë"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Jo tani"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Menaxho"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Bli një paketë përforcimi të rrjetit."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-sr/strings.xml b/packages/CarrierDefaultApp/res/values-sr/strings.xml index e615eadba6da..84db181b1af5 100644 --- a/packages/CarrierDefaultApp/res/values-sr/strings.xml +++ b/packages/CarrierDefaultApp/res/values-sr/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Мрежа којој покушавате да се придружите има безбедносних проблема."</string> <string name="ssl_error_example" msgid="6188711843183058764">"На пример, страница за пријављивање можда не припада приказаној организацији."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Ипак настави преко прегледача"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Појачање мреже"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s препоручује повећање података"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Купите појачање мреже за бољи учинак"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Не сада"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Управљајте"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Купите појачање мреже."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-sv/strings.xml b/packages/CarrierDefaultApp/res/values-sv/strings.xml index 778663b66d76..5e8853a941f8 100644 --- a/packages/CarrierDefaultApp/res/values-sv/strings.xml +++ b/packages/CarrierDefaultApp/res/values-sv/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Nätverket du försöker ansluta till har säkerhetsproblem."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Det kan t.ex. hända att inloggningssidan inte tillhör den organisation som visas."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Fortsätt ändå via webbläsaren"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Nätverksboost"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s rekommenderar en databoost"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Köp en nätverksboost för bättre resultat"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Inte nu"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Hantera"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Köp en nätverksboost."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-sw/strings.xml b/packages/CarrierDefaultApp/res/values-sw/strings.xml index 4f0745cec6b7..c99eb138c067 100644 --- a/packages/CarrierDefaultApp/res/values-sw/strings.xml +++ b/packages/CarrierDefaultApp/res/values-sw/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Mtandao unaojaribu kujiunga nao una matatizo ya usalama."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Kwa mfano, ukurasa wa kuingia katika akaunti unaweza usiwe unamilikiwa na shirika lililoonyeshwa."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Endelea hata hivyo kupitia kivinjari"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Kuimarisha mtandao"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s inapendekeza kuimarisha data"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Nunua kifaa cha kuimarisha mtandao kwa utendaji bora zaidi"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Si sasa"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Dhibiti"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Nunua kifaa cha kuimarisha mtandao."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-ta/strings.xml b/packages/CarrierDefaultApp/res/values-ta/strings.xml index a1d29286d060..6f7f4800ae79 100644 --- a/packages/CarrierDefaultApp/res/values-ta/strings.xml +++ b/packages/CarrierDefaultApp/res/values-ta/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"நீங்கள் சேர முயலும் நெட்வொர்க்கில் பாதுகாப்புச் சிக்கல்கள் உள்ளன."</string> <string name="ssl_error_example" msgid="6188711843183058764">"எடுத்துக்காட்டாக, உள்நுழைவுப் பக்கமானது காட்டப்படும் அமைப்பிற்குச் சொந்தமானதாக இல்லாமல் இருக்கலாம்."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"பரவாயில்லை, உலாவி வழியாகத் தொடர்க"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"நெட்வொர்க் பூஸ்ட்"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"டேட்டா பூஸ்ட்டை %s பரிந்துரைக்கிறது"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"சிறப்பான செயல்திறனுக்கு நெட்வொர்க் பூஸ்ட்டை வாங்கவும்"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"இப்போது வேண்டாம்"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"நிர்வகியுங்கள்"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"நெட்வொர்க் பூஸ்ட்டை வாங்குங்கள்."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-te/strings.xml b/packages/CarrierDefaultApp/res/values-te/strings.xml index 71399030c4b1..d1e49ca40b7c 100644 --- a/packages/CarrierDefaultApp/res/values-te/strings.xml +++ b/packages/CarrierDefaultApp/res/values-te/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"మీరు చేరడానికి ప్రయత్నిస్తున్న నెట్వర్క్ భద్రతా సమస్యలను కలిగి ఉంది."</string> <string name="ssl_error_example" msgid="6188711843183058764">"ఉదాహరణకు, లాగిన్ పేజీ చూపిన సంస్థకు చెందినది కాకపోవచ్చు."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"ఏదేమైనా బ్రౌజర్ ద్వారా కొనసాగించు"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"నెట్వర్క్ బూస్ట్"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"డేటా బూస్ట్ను %s సిఫార్సు చేస్తోంది"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"మెరుగైన పనితీరు కోసం నెట్వర్క్ బూస్ట్ను కొనుగోలు చేయండి"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"ఇప్పుడు కాదు"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"మేనేజ్ చేయండి"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"నెట్వర్క్ బూస్ట్ను కొనుగోలు చేయండి."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-th/strings.xml b/packages/CarrierDefaultApp/res/values-th/strings.xml index 5c63bb1bbecd..39889959728b 100644 --- a/packages/CarrierDefaultApp/res/values-th/strings.xml +++ b/packages/CarrierDefaultApp/res/values-th/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"เครือข่ายที่คุณพยายามเข้าร่วมมีปัญหาด้านความปลอดภัย"</string> <string name="ssl_error_example" msgid="6188711843183058764">"ตัวอย่างเช่น หน้าเข้าสู่ระบบอาจไม่ใช่ขององค์กรที่แสดงไว้"</string> <string name="ssl_error_continue" msgid="1138548463994095584">"ดำเนินการต่อผ่านเบราว์เซอร์"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"เพิ่มประสิทธิภาพเครือข่าย"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s แนะนำให้เพิ่มอินเทอร์เน็ตมือถือ"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"ซื้อการเพิ่มประสิทธิภาพเครือข่ายเพื่อการทำงานที่ดียิ่งขึ้น"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"ไว้ทีหลัง"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"จัดการ"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"ซื้อการเพิ่มประสิทธิภาพเครือข่าย"</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-tl/strings.xml b/packages/CarrierDefaultApp/res/values-tl/strings.xml index 9e320c88e9eb..6375a9332d28 100644 --- a/packages/CarrierDefaultApp/res/values-tl/strings.xml +++ b/packages/CarrierDefaultApp/res/values-tl/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"May mga isyu sa seguridad ang network na sinusubukan mong salihan."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Halimbawa, maaaring hindi pag-aari ng ipinapakitang organisasyon ang page ng login."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Magpatuloy pa rin sa pamamagitan ng browser"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Network boost"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"Nagrerekomenda ng data boost ang %s"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Bumili ng network boost para sa mas mahusay na performance"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Huwag muna"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Pamahalaan"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Bumili ng network boost."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-tr/strings.xml b/packages/CarrierDefaultApp/res/values-tr/strings.xml index 63616ccab453..72808e681bcc 100644 --- a/packages/CarrierDefaultApp/res/values-tr/strings.xml +++ b/packages/CarrierDefaultApp/res/values-tr/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Katılmaya çalıştığınız ağda güvenlik sorunları var."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Örneğin, giriş sayfası, gösterilen kuruluşa ait olmayabilir."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Yine de tarayıcıyla devam et"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Ağ güçlendirme"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s veri güçlendirme öneriyor"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Daha iyi performans için ağ güçlendirme satın alın"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Şimdi değil"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Yönet"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Ağ güçlendirme satın alın."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-uk/strings.xml b/packages/CarrierDefaultApp/res/values-uk/strings.xml index bd4432711ddd..2b301649c228 100644 --- a/packages/CarrierDefaultApp/res/values-uk/strings.xml +++ b/packages/CarrierDefaultApp/res/values-uk/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"У мережі, до якої ви намагаєтеся під’єднатись, є проблеми з безпекою."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Наприклад, сторінка входу може не належати вказаній організації."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Усе одно продовжити у веб-переглядачі"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Покращення характеристик мережі"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s рекомендує придбати покращення характеристик мережі"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Придбайте покращення характеристик мережі, щоб підвищити продуктивність"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Не зараз"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Керувати"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Придбайте покращення характеристик мережі."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-ur/strings.xml b/packages/CarrierDefaultApp/res/values-ur/strings.xml index 3294cf5723c5..104f8068f9a5 100644 --- a/packages/CarrierDefaultApp/res/values-ur/strings.xml +++ b/packages/CarrierDefaultApp/res/values-ur/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"آپ جس نیٹ ورک میں شامل ہونے کی کوشش کر رہے ہیں، اس میں سیکیورٹی کے مسائل ہیں۔"</string> <string name="ssl_error_example" msgid="6188711843183058764">"مثال کے طور پر ہو سکتا ہے کہ لاگ ان صفحہ دکھائی گئی تنظیم سے تعلق نہ رکھتا ہو۔"</string> <string name="ssl_error_continue" msgid="1138548463994095584">"براؤزر کے ذریعے بہرحال جاری رکھیں"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"نیٹ ورک بوسٹ"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s ڈیٹا بوسٹ کی تجویز کرتا ہے"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"بہتر کارکردگی کے لیے نیٹ ورک بوسٹ خریدیں"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"ابھی نہیں"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"نظم کریں"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"نیٹ ورک بوسٹ خریدیں۔"</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-uz/strings.xml b/packages/CarrierDefaultApp/res/values-uz/strings.xml index 4eca545ffd87..a4eb37713dae 100644 --- a/packages/CarrierDefaultApp/res/values-uz/strings.xml +++ b/packages/CarrierDefaultApp/res/values-uz/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Siz ulanmoqchi bo‘lgan tarmoqda xavfsizlik bilan bog‘liq muammolar mavjud."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Masalan, tizimga kirish sahifasi ko‘rsatilgan tashkilotga tegishli bo‘lmasligi mumkin."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Brauzerda davom ettirish"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Tarmoq kuchaytirgichi"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s maʼlumotlarni kuchaytirishni tavsiya qiladi"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Yaxshiroq ishlash uchun tarmoq kuchaytirgichini sotib oling"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Hozir emas"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Boshqarish"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Tarmoq kuchaytirgichini sotib oling."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-vi/strings.xml b/packages/CarrierDefaultApp/res/values-vi/strings.xml index d8f15e864818..6f6a314735b2 100644 --- a/packages/CarrierDefaultApp/res/values-vi/strings.xml +++ b/packages/CarrierDefaultApp/res/values-vi/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"Mạng mà bạn đang cố gắng tham gia có vấn đề về bảo mật."</string> <string name="ssl_error_example" msgid="6188711843183058764">"Ví dụ: trang đăng nhập có thể không thuộc về tổ chức được hiển thị."</string> <string name="ssl_error_continue" msgid="1138548463994095584">"Vẫn tiếp tục qua trình duyệt"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"Tăng tốc độ mạng"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s đề xuất tăng tốc độ dữ liệu"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"Mua gói tăng tốc độ mạng để cải thiện hiệu suất"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"Để sau"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"Quản lý"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"Mua gói tăng tốc độ mạng."</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-zh-rCN/strings.xml b/packages/CarrierDefaultApp/res/values-zh-rCN/strings.xml index 4ce19f5d644c..a92278d80493 100644 --- a/packages/CarrierDefaultApp/res/values-zh-rCN/strings.xml +++ b/packages/CarrierDefaultApp/res/values-zh-rCN/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"您尝试加入的网络存在安全问题。"</string> <string name="ssl_error_example" msgid="6188711843183058764">"例如,登录页面可能并不属于页面上显示的单位。"</string> <string name="ssl_error_continue" msgid="1138548463994095584">"仍然通过浏览器继续操作"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"网络加速"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"%s建议提升移动网络速度"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"购买网络加速服务,以获得更好的效果"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"以后再说"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"管理"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"购买网络加速服务。"</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-zh-rHK/strings.xml b/packages/CarrierDefaultApp/res/values-zh-rHK/strings.xml index f019beb06a6c..959b497d20e9 100644 --- a/packages/CarrierDefaultApp/res/values-zh-rHK/strings.xml +++ b/packages/CarrierDefaultApp/res/values-zh-rHK/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"您正在嘗試加入的網絡有安全性問題。"</string> <string name="ssl_error_example" msgid="6188711843183058764">"例如,登入頁面可能並不屬於所顯示的機構。"</string> <string name="ssl_error_continue" msgid="1138548463994095584">"仍要透過瀏覽器繼續操作"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"網絡強化"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"「%s」建議購買流動數據強化"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"購買網絡強化以提升效能"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"暫時不要"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"管理"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"購買網絡強化。"</string> </resources> diff --git a/packages/CarrierDefaultApp/res/values-zh-rTW/strings.xml b/packages/CarrierDefaultApp/res/values-zh-rTW/strings.xml index 32724b5ae772..29acabfba862 100644 --- a/packages/CarrierDefaultApp/res/values-zh-rTW/strings.xml +++ b/packages/CarrierDefaultApp/res/values-zh-rTW/strings.xml @@ -14,16 +14,10 @@ <string name="ssl_error_warning" msgid="3127935140338254180">"你嘗試加入的網路有安全性問題。"</string> <string name="ssl_error_example" msgid="6188711843183058764">"例如,登入網頁中顯示的機構可能並非該網頁實際隸屬的機構。"</string> <string name="ssl_error_continue" msgid="1138548463994095584">"仍要透過瀏覽器繼續操作"</string> - <!-- no translation found for network_boost_notification_channel (5430986172506159199) --> - <skip /> - <!-- no translation found for network_boost_notification_title (8226368121348880044) --> - <skip /> - <!-- no translation found for network_boost_notification_detail (3812434025544196192) --> - <skip /> - <!-- no translation found for network_boost_notification_button_not_now (4129218252146702688) --> - <skip /> - <!-- no translation found for network_boost_notification_button_manage (1511552684142641182) --> - <skip /> - <!-- no translation found for slice_purchase_app_label (915654761797446390) --> - <skip /> + <string name="network_boost_notification_channel" msgid="5430986172506159199">"網路增強"</string> + <string name="network_boost_notification_title" msgid="8226368121348880044">"「%s」建議購買行動數據增強"</string> + <string name="network_boost_notification_detail" msgid="3812434025544196192">"購買網路增強以提升效能"</string> + <string name="network_boost_notification_button_not_now" msgid="4129218252146702688">"暫時不要"</string> + <string name="network_boost_notification_button_manage" msgid="1511552684142641182">"管理"</string> + <string name="slice_purchase_app_label" msgid="915654761797446390">"購買網路增強。"</string> </resources> diff --git a/packages/CredentialManager/res/drawable/ic_face.xml b/packages/CredentialManager/res/drawable/ic_face.xml deleted file mode 100644 index 16fe14495e9d..000000000000 --- a/packages/CredentialManager/res/drawable/ic_face.xml +++ /dev/null @@ -1,30 +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. - --> - -<!--TODO: Testing only icon. Remove later. --> - -<vector xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:tools="http://schemas.android.com/tools" - tools:ignore="VectorPath" - android:width="24dp" - android:height="24dp" - android:viewportWidth="24" - android:viewportHeight="24" - android:tint="?attr/colorControlNormal"> - <path - android:fillColor="#808080" - android:pathData="M9.025,14.275Q8.5,14.275 8.125,13.9Q7.75,13.525 7.75,13Q7.75,12.475 8.125,12.1Q8.5,11.725 9.025,11.725Q9.575,11.725 9.938,12.1Q10.3,12.475 10.3,13Q10.3,13.525 9.938,13.9Q9.575,14.275 9.025,14.275ZM14.975,14.275Q14.425,14.275 14.062,13.9Q13.7,13.525 13.7,13Q13.7,12.475 14.062,12.1Q14.425,11.725 14.975,11.725Q15.5,11.725 15.875,12.1Q16.25,12.475 16.25,13Q16.25,13.525 15.875,13.9Q15.5,14.275 14.975,14.275ZM12,19.925Q15.325,19.925 17.625,17.625Q19.925,15.325 19.925,12Q19.925,11.4 19.85,10.85Q19.775,10.3 19.575,9.775Q19.05,9.9 18.538,9.962Q18.025,10.025 17.45,10.025Q15.2,10.025 13.188,9.062Q11.175,8.1 9.775,6.375Q8.975,8.3 7.5,9.712Q6.025,11.125 4.075,11.85Q4.075,11.9 4.075,11.925Q4.075,11.95 4.075,12Q4.075,15.325 6.375,17.625Q8.675,19.925 12,19.925ZM12,22.2Q9.9,22.2 8.038,21.4Q6.175,20.6 4.788,19.225Q3.4,17.85 2.6,15.988Q1.8,14.125 1.8,12Q1.8,9.875 2.6,8.012Q3.4,6.15 4.788,4.775Q6.175,3.4 8.038,2.6Q9.9,1.8 12,1.8Q14.125,1.8 15.988,2.6Q17.85,3.4 19.225,4.775Q20.6,6.15 21.4,8.012Q22.2,9.875 22.2,12Q22.2,14.125 21.4,15.988Q20.6,17.85 19.225,19.225Q17.85,20.6 15.988,21.4Q14.125,22.2 12,22.2Z"/> -</vector>
\ No newline at end of file diff --git a/packages/CredentialManager/res/drawable/ic_manage_accounts.xml b/packages/CredentialManager/res/drawable/ic_manage_accounts.xml deleted file mode 100644 index adad2f105d55..000000000000 --- a/packages/CredentialManager/res/drawable/ic_manage_accounts.xml +++ /dev/null @@ -1,30 +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. - --> - -<!--TODO: Testing only icon. Remove later. --> - -<vector xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:tools="http://schemas.android.com/tools" - tools:ignore="VectorPath" - android:width="24dp" - android:height="24dp" - android:viewportWidth="24" - android:viewportHeight="24" - android:tint="?attr/colorControlNormal"> - <path - android:fillColor="#808080" - android:pathData="M16.1,21.2 L15.775,19.675Q15.5,19.55 15.25,19.425Q15,19.3 14.75,19.1L13.275,19.575L12.2,17.75L13.375,16.725Q13.325,16.4 13.325,16.112Q13.325,15.825 13.375,15.5L12.2,14.475L13.275,12.65L14.75,13.1Q15,12.925 15.25,12.787Q15.5,12.65 15.775,12.55L16.1,11.025H18.25L18.55,12.55Q18.825,12.65 19.075,12.8Q19.325,12.95 19.575,13.15L21.05,12.65L22.125,14.525L20.95,15.55Q21.025,15.825 21.013,16.137Q21,16.45 20.95,16.725L22.125,17.75L21.05,19.575L19.575,19.1Q19.325,19.3 19.075,19.425Q18.825,19.55 18.55,19.675L18.25,21.2ZM1.8,20.3V17.3Q1.8,16.375 2.275,15.613Q2.75,14.85 3.5,14.475Q4.775,13.825 6.425,13.362Q8.075,12.9 10,12.9Q10.2,12.9 10.4,12.9Q10.6,12.9 10.775,12.95Q9.925,14.85 10.062,16.738Q10.2,18.625 11.4,20.3ZM17.175,18.075Q17.975,18.075 18.55,17.487Q19.125,16.9 19.125,16.1Q19.125,15.3 18.55,14.725Q17.975,14.15 17.175,14.15Q16.375,14.15 15.788,14.725Q15.2,15.3 15.2,16.1Q15.2,16.9 15.788,17.487Q16.375,18.075 17.175,18.075ZM10,11.9Q8.25,11.9 7.025,10.662Q5.8,9.425 5.8,7.7Q5.8,5.95 7.025,4.725Q8.25,3.5 10,3.5Q11.75,3.5 12.975,4.725Q14.2,5.95 14.2,7.7Q14.2,9.425 12.975,10.662Q11.75,11.9 10,11.9Z"/> -</vector>
\ No newline at end of file diff --git a/packages/CredentialManager/res/values-af/strings.xml b/packages/CredentialManager/res/values-af/strings.xml index 377c13fb7881..a5482198a1f3 100644 --- a/packages/CredentialManager/res/values-af/strings.xml +++ b/packages/CredentialManager/res/values-af/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Stoor in ’n ander plek"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Gebruik ’n ander toestel"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Stoor op ’n ander toestel"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"’n Maklike manier om veilig aan te meld"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Gebruik jou vingerafdruk, gesig of skermslot om aan te meld met ’n unieke wagwoordsleutel wat nie vergeet of gesteel kan word nie. Kom meer te wete"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Kies waar om <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Kies waar om <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"skep jou wagwoordsleutels"</string> <string name="save_your_password" msgid="6597736507991704307">"stoor jou wagwoord"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"stoor jou aanmeldinligting"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Stel ’n verstekwagwoordbestuurder om jou wagwoorde en wagwoordsleutels te stoor, en meld volgende keer vinniger aan."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Skep ’n wagwoordsleutel in <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Stoor jou wagwoord in <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Stoor jou aanmeldinligting in <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"wagwoordsleutel"</string> <string name="password" msgid="6738570945182936667">"wagwoord"</string> <string name="sign_ins" msgid="4710739369149469208">"aanmeldings"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Skep wagwoordsleutel in"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Stoor wagwoord in"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Stoor aanmelding in"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Skep ’n wagwoordsleutel op ’n ander toestel?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Gebruik <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> vir al jou aanmeldings?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Hierdie wagwoordbestuurder sal jou wagwoorde en wagwoordsleutels berg om jou te help om maklik aan te meld."</string> <string name="set_as_default" msgid="4415328591568654603">"Stel as verstek"</string> <string name="use_once" msgid="9027366575315399714">"Gebruik een keer"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> wagwoorde, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> wagwoordsleutels"</string> diff --git a/packages/CredentialManager/res/values-am/strings.xml b/packages/CredentialManager/res/values-am/strings.xml index b80fe2cee53a..6fdc696bcfb2 100644 --- a/packages/CredentialManager/res/values-am/strings.xml +++ b/packages/CredentialManager/res/values-am/strings.xml @@ -3,45 +3,34 @@ xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <!-- no translation found for app_name (4539824758261855508) --> <skip /> - <!-- no translation found for string_cancel (6369133483981306063) --> - <skip /> - <!-- no translation found for string_continue (1346732695941131882) --> - <skip /> - <!-- no translation found for string_create_in_another_place (1033635365843437603) --> - <skip /> - <!-- no translation found for string_save_to_another_place (7590325934591079193) --> - <skip /> - <!-- no translation found for string_use_another_device (8754514926121520445) --> - <skip /> + <string name="string_cancel" msgid="6369133483981306063">"ይቅር"</string> + <string name="string_continue" msgid="1346732695941131882">"ቀጥል"</string> + <string name="string_create_in_another_place" msgid="1033635365843437603">"በሌላ ቦታ ውስጥ ይፍጠሩ"</string> + <string name="string_save_to_another_place" msgid="7590325934591079193">"ወደ ሌላ ቦታ ያስቀምጡ"</string> + <string name="string_use_another_device" msgid="8754514926121520445">"ሌላ መሣሪያ ይጠቀሙ"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"ወደ ሌላ መሣሪያ ያስቀምጡ"</string> - <!-- no translation found for passkey_creation_intro_title (402553911484409884) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> <skip /> - <!-- no translation found for passkey_creation_intro_body (7493320456005579290) --> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> <skip /> - <!-- no translation found for choose_provider_title (7245243990139698508) --> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> - <skip /> - <!-- no translation found for save_your_password (6597736507991704307) --> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> <skip /> - <!-- no translation found for save_your_sign_in_info (7213978049817076882) --> + <string name="choose_provider_title" msgid="7245243990139698508">"የት <xliff:g id="CREATETYPES">%1$s</xliff:g> እንደሚሆን ይምረጡ"</string> + <!-- no translation found for create_your_passkeys (8901224153607590596) --> <skip /> + <string name="save_your_password" msgid="6597736507991704307">"የይለፍ ቃልዎን ያስቀምጡ"</string> + <string name="save_your_sign_in_info" msgid="7213978049817076882">"የመግቢያ መረጃዎን ያስቀምጡ"</string> <!-- no translation found for choose_provider_body (8045759834416308059) --> <skip /> - <!-- no translation found for choose_create_option_passkey_title (4146408187146573131) --> - <skip /> - <!-- no translation found for choose_create_option_password_title (8812546498357380545) --> - <skip /> - <!-- no translation found for choose_create_option_sign_in_title (6318246378475961834) --> - <skip /> - <!-- no translation found for choose_create_option_description (4419171903963100257) --> - <skip /> - <!-- no translation found for passkey (632353688396759522) --> - <skip /> - <!-- no translation found for password (6738570945182936667) --> - <skip /> - <!-- no translation found for sign_ins (4710739369149469208) --> - <skip /> + <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"በ<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ውስጥ የይለፍ ቁልፍ ይፈጠር?"</string> + <string name="choose_create_option_password_title" msgid="8812546498357380545">"የይለፍ ቃልዎ ወደ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ይቀመጥ?"</string> + <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"የመግቢያ መረጃዎ ወደ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ይቀመጥ?"</string> + <string name="choose_create_option_description" msgid="4419171903963100257">"የእርስዎን <xliff:g id="APPDOMAINNAME">%1$s</xliff:g> <xliff:g id="TYPE">%2$s</xliff:g> በማንኛውም መሣሪያ ላይ መጠቀም ይችላሉ። ለ<xliff:g id="CREATEINFODISPLAYNAME">%4$s</xliff:g> ወደ <xliff:g id="PROVIDERINFODISPLAYNAME">%3$s</xliff:g> ተቀምጧል"</string> + <string name="passkey" msgid="632353688396759522">"የይለፍ ቁልፍ"</string> + <string name="password" msgid="6738570945182936667">"የይለፍ ቃል"</string> + <string name="sign_ins" msgid="4710739369149469208">"መግቢያዎች"</string> <!-- no translation found for create_passkey_in_title (2714306562710897785) --> <skip /> <!-- no translation found for save_password_to_title (3450480045270186421) --> @@ -50,54 +39,31 @@ <skip /> <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> <skip /> - <!-- no translation found for use_provider_for_all_title (4201020195058980757) --> - <skip /> + <string name="use_provider_for_all_title" msgid="4201020195058980757">"ለሁሉም መግቢያዎችዎ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>ን ይጠቀሙ?"</string> <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> <skip /> - <!-- no translation found for set_as_default (4415328591568654603) --> - <skip /> - <!-- no translation found for use_once (9027366575315399714) --> - <skip /> - <!-- no translation found for more_options_usage_passwords_passkeys (4794903978126339473) --> - <skip /> - <!-- no translation found for more_options_usage_passwords (1632047277723187813) --> - <skip /> - <!-- no translation found for more_options_usage_passkeys (5390320437243042237) --> - <skip /> + <string name="set_as_default" msgid="4415328591568654603">"እንደ ነባሪ ያዋቅሩ"</string> + <string name="use_once" msgid="9027366575315399714">"አንዴ ይጠቀሙ"</string> + <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> የይለፍ ቃሎች፣ <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> የይለፍ ቁልፎች"</string> + <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> የይለፍ ቃሎች"</string> + <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> የይለፍ ቁልፎች"</string> <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> <skip /> - <!-- no translation found for another_device (5147276802037801217) --> - <skip /> - <!-- no translation found for other_password_manager (565790221427004141) --> - <skip /> - <!-- no translation found for close_sheet (1393792015338908262) --> - <skip /> - <!-- no translation found for accessibility_back_arrow_button (3233198183497842492) --> - <skip /> - <!-- no translation found for get_dialog_title_use_passkey_for (6236608872708021767) --> - <skip /> - <!-- no translation found for get_dialog_title_use_sign_in_for (5283099528915572980) --> - <skip /> - <!-- no translation found for get_dialog_title_choose_sign_in_for (1361715440877613701) --> - <skip /> - <!-- no translation found for get_dialog_use_saved_passkey_for (4618100798664888512) --> - <skip /> - <!-- no translation found for get_dialog_button_label_no_thanks (8114363019023838533) --> - <skip /> - <!-- no translation found for get_dialog_button_label_continue (6446201694794283870) --> - <skip /> - <!-- no translation found for get_dialog_title_sign_in_options (2092876443114893618) --> - <skip /> - <!-- no translation found for get_dialog_heading_for_username (3456868514554204776) --> - <skip /> - <!-- no translation found for get_dialog_heading_locked_password_managers (8911514851762862180) --> - <skip /> - <!-- no translation found for locked_credential_entry_label_subtext (9213450912991988691) --> - <skip /> - <!-- no translation found for get_dialog_heading_manage_sign_ins (3522556476480676782) --> - <skip /> - <!-- no translation found for get_dialog_heading_from_another_device (1166697017046724072) --> - <skip /> - <!-- no translation found for get_dialog_option_headline_use_a_different_device (8201578814988047549) --> - <skip /> + <string name="another_device" msgid="5147276802037801217">"ሌላ መሣሪያ"</string> + <string name="other_password_manager" msgid="565790221427004141">"ሌሎች የይለፍ ቃል አስተዳዳሪዎች"</string> + <string name="close_sheet" msgid="1393792015338908262">"ሉህን ዝጋ"</string> + <string name="accessibility_back_arrow_button" msgid="3233198183497842492">"ወደ ቀዳሚው ገፅ ይመለሱ"</string> + <string name="get_dialog_title_use_passkey_for" msgid="6236608872708021767">"የተቀመጠ የይለፍ ቁልፍዎን ለ<xliff:g id="APP_NAME">%1$s</xliff:g> ይጠቀሙ?"</string> + <string name="get_dialog_title_use_sign_in_for" msgid="5283099528915572980">"የተቀመጠ መግቢያዎን ለ<xliff:g id="APP_NAME">%1$s</xliff:g> ይጠቀሙ?"</string> + <string name="get_dialog_title_choose_sign_in_for" msgid="1361715440877613701">"ለ<xliff:g id="APP_NAME">%1$s</xliff:g> የተቀመጠ መግቢያ ይጠቀሙ"</string> + <string name="get_dialog_use_saved_passkey_for" msgid="4618100798664888512">"በሌላ መንገድ ይግቡ"</string> + <string name="get_dialog_button_label_no_thanks" msgid="8114363019023838533">"አይ አመሰግናለሁ"</string> + <string name="get_dialog_button_label_continue" msgid="6446201694794283870">"ቀጥል"</string> + <string name="get_dialog_title_sign_in_options" msgid="2092876443114893618">"የመግቢያ አማራጮች"</string> + <string name="get_dialog_heading_for_username" msgid="3456868514554204776">"ለ<xliff:g id="USERNAME">%1$s</xliff:g>"</string> + <string name="get_dialog_heading_locked_password_managers" msgid="8911514851762862180">"የተቆለፉ የሚስጥር ቁልፍ አስተዳዳሪዎች"</string> + <string name="locked_credential_entry_label_subtext" msgid="9213450912991988691">"ለመክፈት መታ ያድርጉ"</string> + <string name="get_dialog_heading_manage_sign_ins" msgid="3522556476480676782">"መግቢያዎችን ያስተዳድሩ"</string> + <string name="get_dialog_heading_from_another_device" msgid="1166697017046724072">"ከሌላ መሣሪያ"</string> + <string name="get_dialog_option_headline_use_a_different_device" msgid="8201578814988047549">"የተለየ መሣሪያ ይጠቀሙ"</string> </resources> diff --git a/packages/CredentialManager/res/values-ar/strings.xml b/packages/CredentialManager/res/values-ar/strings.xml index a5c85c5281b2..6a2c9a157313 100644 --- a/packages/CredentialManager/res/values-ar/strings.xml +++ b/packages/CredentialManager/res/values-ar/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"مدير بيانات الاعتماد"</string> <string name="string_cancel" msgid="6369133483981306063">"إلغاء"</string> <string name="string_continue" msgid="1346732695941131882">"متابعة"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"الإنشاء في مكان آخر"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"الحفظ في مكان آخر"</string> <string name="string_use_another_device" msgid="8754514926121520445">"استخدام جهاز آخر"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"الحفظ على جهاز آخر"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"طريقة بسيطة لتسجيل الدخول بأمان"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"استخدِم بصمة إصبعك أو وجهك أو قفل الشاشة لتسجيل الدخول باستخدام مفتاح مرور فريد لا يمكن نسيانه أو سرقته. مزيد من المعلومات"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"اختيار مكان <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"اختيار مكان <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"إنشاء مفاتيح مرورك"</string> <string name="save_your_password" msgid="6597736507991704307">"حفظ كلمة المرور"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"حفظ معلومات تسجيل الدخول"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"يمكنك ضبط خدمة تلقائية لـ \"مدير كلمات المرور\" من أجل حفظ كلمات المرور ومفاتيح المرور وتسجيل الدخول بشكل أسرع في المرة القادمة."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"هل تريد إنشاء مفتاح مرور في \"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>\"؟"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"هل تريد حفظ كلمة مرورك في \"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>\"؟"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"هل تريد حفظ معلومات تسجيل الدخول في \"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>\"؟"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"مفتاح مرور"</string> <string name="password" msgid="6738570945182936667">"كلمة المرور"</string> <string name="sign_ins" msgid="4710739369149469208">"عمليات تسجيل الدخول"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"إنشاء مفتاح مرور في"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"حفظ كلمة المرور في"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"حفظ معلومات تسجيل الدخول في"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"هل تريد إنشاء مفتاح مرور في جهاز آخر؟"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"هل تريد استخدام \"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>\" لكل عمليات تسجيل الدخول؟"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"سيخزِّن \"مدير كلمات المرور\" هذا كلمات المرور ومفاتيح المرور لمساعدتك في تسجيل الدخول بسهولة."</string> <string name="set_as_default" msgid="4415328591568654603">"ضبط الخيار كتلقائي"</string> <string name="use_once" msgid="9027366575315399714">"الاستخدام مرة واحدة"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"عدد كلمات المرور هو <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>، و عدد مفاتيح المرور هو <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g>"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"عدد كلمات المرور: <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"عدد مفاتيح المرور: <xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g>"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"مفتاح مرور"</string> <string name="another_device" msgid="5147276802037801217">"جهاز آخر"</string> <string name="other_password_manager" msgid="565790221427004141">"خدمات مدراء كلمات المرور الأخرى"</string> <string name="close_sheet" msgid="1393792015338908262">"إغلاق ورقة البيانات"</string> diff --git a/packages/CredentialManager/res/values-as/strings.xml b/packages/CredentialManager/res/values-as/strings.xml index 4d0ba6815947..7d3b5f84d147 100644 --- a/packages/CredentialManager/res/values-as/strings.xml +++ b/packages/CredentialManager/res/values-as/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"অন্য ঠাইত ছেভ কৰক"</string> <string name="string_use_another_device" msgid="8754514926121520445">"অন্য ডিভাইচ ব্যৱহাৰ কৰক"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"অন্য এটা ডিভাইচত ছেভ কৰক"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"সুৰক্ষিতভাৱে ছাইন ইন কৰাৰ এক সৰল উপায়"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"পাহৰি নোযোৱা অথবা চুৰি কৰিব নোৱৰা এটা অদ্বিতীয় পাছকী ব্যৱহাৰ কৰি ছাইন ইন কৰিবলৈ আপোনাৰ ফিংগাৰপ্ৰিণ্ট, মুখাৱয়ব অথবা স্ক্ৰীন লক ব্যৱহাৰ কৰক। অধিক জানক"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"ক’ত <xliff:g id="CREATETYPES">%1$s</xliff:g> সেয়া বাছনি কৰক"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"ক’ত <xliff:g id="CREATETYPES">%1$s</xliff:g> সেয়া বাছনি কৰক"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"আপোনাৰ পাছকী সৃষ্টি কৰক"</string> <string name="save_your_password" msgid="6597736507991704307">"আপোনাৰ পাছৱৰ্ড ছেভ কৰক"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"আপোনাৰ ছাইন ইন কৰাৰ তথ্য ছেভ কৰক"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"আপোনাৰ পাছৱৰ্ড আৰু পাছকী ছেভ কৰিবলৈ এটা ডিফ’ল্ট পাছৱৰ্ড পৰিচালক ছেট কৰক আৰু পৰৱৰ্তী বাৰ দ্ৰুতভাৱে ছাইন ইন কৰক।"</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>ত পাছকী সৃষ্টি কৰিবনে?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>ত আপোনাৰ পাছৱৰ্ড ছেভ কৰিবনে?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>ত আপোনাৰ ছাইন ইন কৰাৰ তথ্য ছেভ কৰিবনে?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"পাছকী"</string> <string name="password" msgid="6738570945182936667">"পাছৱৰ্ড"</string> <string name="sign_ins" msgid="4710739369149469208">"ছাইন-ইন"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"ইয়াত পাছকী সৃষ্টি কৰক"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"ইয়াত পাছৱৰ্ড ছেভ কৰক"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"ইয়াত ছাইন ইন কৰাৰ তথ্য ছেভ কৰক"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"অন্য এটা ডিভাইচত এটা পাছকী সৃষ্টি কৰিবনে?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"আপোনাৰ আটাইবোৰ ছাইন ইনৰ বাবে <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ব্যৱহাৰ কৰিবনে?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"আপোনাক সহজে ছাইন ইন কৰাত সহায় কৰিবলৈ এই পাছৱৰ্ড পৰিচালকটোৱে আপোনাৰ পাছৱৰ্ড আৰু পাছকী ষ্ট’ৰ কৰিব।"</string> <string name="set_as_default" msgid="4415328591568654603">"ডিফ’ল্ট হিচাপে ছেট কৰক"</string> <string name="use_once" msgid="9027366575315399714">"এবাৰ ব্যৱহাৰ কৰক"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> টা পাছৱৰ্ড, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> টা পাছকী"</string> diff --git a/packages/CredentialManager/res/values-az/strings.xml b/packages/CredentialManager/res/values-az/strings.xml index 14313f759b48..45af67bbdfbc 100644 --- a/packages/CredentialManager/res/values-az/strings.xml +++ b/packages/CredentialManager/res/values-az/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Başqa yerdə yadda saxlayın"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Digər cihaz istifadə edin"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Başqa cihazda yadda saxlayın"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Təhlükəsiz daxil olmağın sadə yolu"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Unutmaq və ya oğurlamaq mümkün olmayan unikal giriş açarı ilə daxil olmaq üçün barmaq izi, üz və ya ekran kilidindən istifadə edin. Ətraflı məlumat"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> üçün yer seçin"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> üçün yer seçin"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"giriş açarları yaradın"</string> <string name="save_your_password" msgid="6597736507991704307">"parolunuzu yadda saxlayın"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"giriş məlumatınızı yadda saxlayın"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Parollarınızı və giriş açarlarınızı saxlamaq və növbəti dəfə daha sürətli daxil olmaq üçün defolt parol meneceri ayarlayın."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> xidmətində giriş açarı yaradılsın?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Parol <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> xidmətində saxlanılsın?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Giriş məlumatınız <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> xidmətində saxlanılsın?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"giriş açarı"</string> <string name="password" msgid="6738570945182936667">"parol"</string> <string name="sign_ins" msgid="4710739369149469208">"girişlər"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Burada giriş açarı yaradın:"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Parolu burada yadda saxlayın:"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Girişi burada yadda saxlayın:"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Başqa cihazda giriş açarı yaradılsın?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Bütün girişlər üçün <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> istifadə edilsin?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Bu parol meneceri asanlıqla daxil olmanıza kömək etmək üçün parollarınızı və giriş açarlarınızı saxlayacaq."</string> <string name="set_as_default" msgid="4415328591568654603">"Defolt olaraq seçin"</string> <string name="use_once" msgid="9027366575315399714">"Bir dəfə istifadə edin"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> parol, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> giriş açarı"</string> diff --git a/packages/CredentialManager/res/values-b+sr+Latn/strings.xml b/packages/CredentialManager/res/values-b+sr+Latn/strings.xml index c58ec141f01b..7a8e40d8633e 100644 --- a/packages/CredentialManager/res/values-b+sr+Latn/strings.xml +++ b/packages/CredentialManager/res/values-b+sr+Latn/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Menadžer akreditiva"</string> <string name="string_cancel" msgid="6369133483981306063">"Otkaži"</string> <string name="string_continue" msgid="1346732695941131882">"Nastavi"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Napravi na drugom mestu"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Sačuvaj na drugom mestu"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Koristi drugi uređaj"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Sačuvaj na drugi uređaj"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Jednostavan način da se bezbedno prijavljujete"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Koristite otisak prsta, zaključavanje licem ili zaključavanje ekrana da biste se prijavili pomoću jedinstvenog pristupnog koda koji ne može da se zaboravi ili ukrade. Saznajte više"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Odaberite lokaciju za: <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Odaberite lokaciju za: <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"napravite pristupne kodove"</string> <string name="save_your_password" msgid="6597736507991704307">"sačuvajte lozinku"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"sačuvajte podatke o prijavljivanju"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Podesite podrazumevani menadžer lozinki da biste sačuvali lozinke i pristupne kodove i sledeći put se prijavili brže."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Želite da napravite pristupni kôd kod korisnika <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Želite da sačuvate lozinku kod korisnika <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Želite da sačuvate podatke o prijavljivanju kod korisnika <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"pristupni kôd"</string> <string name="password" msgid="6738570945182936667">"lozinka"</string> <string name="sign_ins" msgid="4710739369149469208">"prijavljivanja"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Napravite pristupni kôd u:"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Sačuvajte lozinku na:"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Sačuvajte podatke o prijavljivanju na:"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Želite da napravite pristupni kôd na drugom uređaju?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Želite da za sva prijavljivanja koristite: <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Ovaj menadžer lozinki će čuvati lozinke i pristupne kodove da biste se lako prijavljivali."</string> <string name="set_as_default" msgid="4415328591568654603">"Podesi kao podrazumevano"</string> <string name="use_once" msgid="9027366575315399714">"Koristi jednom"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"Lozinki: <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>, pristupnih kodova:<xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g>"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"Lozinki: <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"Pristupnih kodova: <xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g>"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Pristupni kôd"</string> <string name="another_device" msgid="5147276802037801217">"Drugi uređaj"</string> <string name="other_password_manager" msgid="565790221427004141">"Drugi menadžeri lozinki"</string> <string name="close_sheet" msgid="1393792015338908262">"Zatvorite tabelu"</string> diff --git a/packages/CredentialManager/res/values-be/strings.xml b/packages/CredentialManager/res/values-be/strings.xml index 3c23afd5101b..4b602444d100 100644 --- a/packages/CredentialManager/res/values-be/strings.xml +++ b/packages/CredentialManager/res/values-be/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Менеджар уліковых даных"</string> <string name="string_cancel" msgid="6369133483981306063">"Скасаваць"</string> <string name="string_continue" msgid="1346732695941131882">"Далей"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Стварыць у іншым месцы"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Захаваць у іншым месцы"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Скарыстаць іншую прыладу"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Захаваць на іншую прыладу"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Просты спосаб бяспечнага ўваходу"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Для ўваходу з унікальным ключом доступу, які нельга згубіць ці ўкрасці, можна скарыстаць адбітак пальца, распазнаванне твару ці разблакіроўку экрана. Даведацца больш"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Выберыце, дзе <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Выберыце, дзе <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"стварыць ключы доступу"</string> <string name="save_your_password" msgid="6597736507991704307">"захаваць пароль"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"захаваць інфармацыю пра спосаб уваходу"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Каб у далейшым хутка выконваць уваход, наладзьце стандартны менеджар пароляў для захавання вашых пароляў і ключоў доступу."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Стварыць ключ доступу ў папцы \"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>\"?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Захаваць пароль у папку \"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>\"?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Захаваць інфармацыю пра спосаб уваходу ў папку \"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>\"?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"ключ доступу"</string> <string name="password" msgid="6738570945182936667">"пароль"</string> <string name="sign_ins" msgid="4710739369149469208">"спосабы ўваходу"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Дзе стварыць ключ доступу:"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Куды захаваць пароль:"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Куды захаваць спосаб уваходу:"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Стварыць ключ доступу на іншай прыладзе?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Выкарыстоўваць папку \"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>\" для ўсіх спосабаў уваходу?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Каб вам было прасцей уваходзіць у сістэму, вашы паролі і ключы доступу будуць захоўвацца ў менеджары пароляў."</string> <string name="set_as_default" msgid="4415328591568654603">"Выкарыстоўваць стандартна"</string> <string name="use_once" msgid="9027366575315399714">"Скарыстаць адзін раз"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"Пароляў: <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>, ключоў доступу: <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g>"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"Пароляў: <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"Ключоў доступу: <xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g>"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Ключ доступу"</string> <string name="another_device" msgid="5147276802037801217">"Іншая прылада"</string> <string name="other_password_manager" msgid="565790221427004141">"Іншыя спосабы ўваходу"</string> <string name="close_sheet" msgid="1393792015338908262">"Закрыць аркуш"</string> diff --git a/packages/CredentialManager/res/values-bg/strings.xml b/packages/CredentialManager/res/values-bg/strings.xml index af7eb172810a..302cc3a010bb 100644 --- a/packages/CredentialManager/res/values-bg/strings.xml +++ b/packages/CredentialManager/res/values-bg/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Мениджър на идентификационни данни"</string> <string name="string_cancel" msgid="6369133483981306063">"Отказ"</string> <string name="string_continue" msgid="1346732695941131882">"Напред"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Създаване другаде"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Запазване на друго място"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Използване на друго устройство"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Запазване на друго устройство"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Лесен начин за безопасно влизане в профил"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Използвайте отпечатъка, лицето или опцията си за заключване на екрана, за да влизате в профила си с помощта на уникален код за достъп, който не може да бъде забравен или откраднат. Научете повече"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Изберете място за <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Изберете място за <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"създаване на кодовете ви за достъп"</string> <string name="save_your_password" msgid="6597736507991704307">"запазване на паролата ви"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"запазване на данните ви за вход"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Задайте основен мениджър на пароли, за да запазвате своите пароли и кодове за достъп, така че следващия път да влезете по-бързо в профила си."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Да се създаде ли код за достъп в(ъв) <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Искате ли да запазите паролата си в(ъв) <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Искате ли да запазите данните си за вход в(ъв) <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"код за достъп"</string> <string name="password" msgid="6738570945182936667">"парола"</string> <string name="sign_ins" msgid="4710739369149469208">"данни за вход"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Създаване на код за достъп в(ъв)"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Запазване на паролата в(ъв)"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Запазване на данните за вход в(ъв)"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Да се създаде ли код за достъп на друго устройство?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Да се използва ли <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> за всичките ви данни за вход?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Този мениджър на пароли ще съхранява вашите пароли и кодове за достъп, за да влизате лесно в профила си."</string> <string name="set_as_default" msgid="4415328591568654603">"Задаване като основно"</string> <string name="use_once" msgid="9027366575315399714">"Еднократно използване"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> пароли, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> кода за достъп"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> пароли"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> кода за достъп"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Код за достъп"</string> <string name="another_device" msgid="5147276802037801217">"Друго устройство"</string> <string name="other_password_manager" msgid="565790221427004141">"Други мениджъри на пароли"</string> <string name="close_sheet" msgid="1393792015338908262">"Затваряне на таблицата"</string> diff --git a/packages/CredentialManager/res/values-bn/strings.xml b/packages/CredentialManager/res/values-bn/strings.xml index 152e5bd8e852..ad0bdeac8b7e 100644 --- a/packages/CredentialManager/res/values-bn/strings.xml +++ b/packages/CredentialManager/res/values-bn/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"CredentialManager"</string> <string name="string_cancel" msgid="6369133483981306063">"বাতিল করুন"</string> <string name="string_continue" msgid="1346732695941131882">"চালিয়ে যান"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"অন্য জায়গায় তৈরি করুন"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"অন্য জায়গায় সেভ করুন"</string> <string name="string_use_another_device" msgid="8754514926121520445">"অন্য ডিভাইস ব্যবহার করুন"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"অন্য ডিভাইসে সেভ করুন"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"নিরাপদে সাইন-ইন করার একটি সহজ উপায়"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"একটি অনন্য পাসকী ব্যবহার করে সাইন-ইন করতে আপনার ফিঙ্গারপ্রিন্ট, মুখ বা স্ক্রিন লক ব্যবহার করুন যেটি ভুলে যাবেন না বা হারিয়ে যাবেন না। আরও জানুন"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> কোথায় সেভ করবেন তা বেছে নিন"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> কোথায় সেভ করবেন তা বেছে নিন"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"আপনার পাসকী তৈরি করা"</string> <string name="save_your_password" msgid="6597736507991704307">"আপনার পাসওয়ার্ড সেভ করুন"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"আপনার সাইন-ইন করা সম্পর্কিত তথ্য সেভ করুন"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"আপনার পাসওয়ার্ড ও পাসকী সেভ করার জন্য একটি ডিফল্ট Password Manager সেট করুন এবং পরবর্তী সময়ে আরও ঝটপট সাইন-ইন করুন।"</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>-এ পাসকী তৈরি করবেন?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"আপনার পাসওয়ার্ড <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>-এ সেভ করবেন?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"আপনার সাইন-ইন করা সম্পর্কিত তথ্য <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>-এ সেভ করবেন?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"পাসকী"</string> <string name="password" msgid="6738570945182936667">"পাসওয়ার্ড"</string> <string name="sign_ins" msgid="4710739369149469208">"সাইন-ইন"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"এখানে পাসকী তৈরি করুন"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"এখানে পাসওয়ার্ড সেভ করা"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"এখানে সাইন-ইন করা সম্পর্কিত ক্রেডেনশিয়াল সেভ করা"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"অন্য একটি ডিভাইসে পাসকী তৈরি করবেন?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"আপনার সব সাইন-ইনের জন্য <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ব্যবহার করবেন?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"এই Password Manager আপনার পাসওয়ার্ড ও পাসকী সেভ করবে, যাতে সহজেই সাইন-ইন করতে পারেন।"</string> <string name="set_as_default" msgid="4415328591568654603">"ডিফল্ট হিসেবে সেট করুন"</string> <string name="use_once" msgid="9027366575315399714">"একবার ব্যবহার করুন"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>টি পাসওয়ার্ড, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g>টি পাসকী"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>টি পাসওয়ার্ড"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g>টি পাসকী"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"পাসকী"</string> <string name="another_device" msgid="5147276802037801217">"অন্য ডিভাইস"</string> <string name="other_password_manager" msgid="565790221427004141">"অন্যান্য Password Manager"</string> <string name="close_sheet" msgid="1393792015338908262">"শিট বন্ধ করুন"</string> diff --git a/packages/CredentialManager/res/values-bs/strings.xml b/packages/CredentialManager/res/values-bs/strings.xml index d774b8810f21..2a96102c65bf 100644 --- a/packages/CredentialManager/res/values-bs/strings.xml +++ b/packages/CredentialManager/res/values-bs/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Sačuvajte na drugom mjestu"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Koristite drugi uređaj"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Sačuvajte na drugom uređaju"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Jednostavan način za sigurnu prijavu"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Koristite otisak prsta, lice ili zaključavanje ekrana da se prijavite jedinstvenim pristupnim ključem koji se ne može zaboraviti niti ukrasti. Saznajte više"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Odaberite gdje <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Odaberite gdje <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"izradite pristupne ključeve"</string> <string name="save_your_password" msgid="6597736507991704307">"sačuvajte lozinku"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"sačuvajte informacije za prijavu"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Postavite zadani upravitelj zaporki da biste spremili zaporke i pristupne ključeve i sljedeći put se brže prijavili."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Kreirati pristupni ključ na usluzi <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Sačuvati lozinku na usluzi <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Sačuvati informacije za prijavu na usluzi <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"pristupni ključ"</string> <string name="password" msgid="6738570945182936667">"lozinka"</string> <string name="sign_ins" msgid="4710739369149469208">"prijave"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Izradite pristupni ključ u"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Spremite zaporku na"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Spremite podatke za prijavu na"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Želite li izraditi pristupni ključ na nekom drugom uređaju?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Koristiti uslugu <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> za sve vaše prijave?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Upravitelj zaporki pohranit će vaše zaporke i pristupne ključeve radi jednostavnije prijave."</string> <string name="set_as_default" msgid="4415328591568654603">"Postavi kao zadano"</string> <string name="use_once" msgid="9027366575315399714">"Koristi jednom"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"Broj lozinki: <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>; broj pristupnih ključeva: <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g>"</string> diff --git a/packages/CredentialManager/res/values-ca/strings.xml b/packages/CredentialManager/res/values-ca/strings.xml index bfd91647bd9c..8b1e395280c4 100644 --- a/packages/CredentialManager/res/values-ca/strings.xml +++ b/packages/CredentialManager/res/values-ca/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Gestor de credencials"</string> <string name="string_cancel" msgid="6369133483981306063">"Cancel·la"</string> <string name="string_continue" msgid="1346732695941131882">"Continua"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Crea en un altre lloc"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Desa en un altre lloc"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Utilitza un altre dispositiu"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Desa en un altre dispositiu"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Una manera senzilla i segura d\'iniciar la sessió"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Utilitza l\'empremta digital, la cara o el bloqueig de pantalla per iniciar la sessió amb una clau d\'accés única que no es pot oblidar ni robar. Més informació"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Tria on vols <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Tria on vols <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"crea les teves claus d\'accés"</string> <string name="save_your_password" msgid="6597736507991704307">"desar la contrasenya"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"desar la teva informació d\'inici de sessió"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Defineix un gestor de contrasenyes predeterminat per desar les teves contrasenyes i claus d\'accés d\'una manera més ràpida la pròxima vegada."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Vols crear una clau d\'accés a <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Vols desar la contrasenya a <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Vols desar la teva informació d\'inici de sessió a <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"clau d\'accés"</string> <string name="password" msgid="6738570945182936667">"contrasenya"</string> <string name="sign_ins" msgid="4710739369149469208">"inicis de sessió"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Crea una clau d\'accés a"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Desa la contrasenya a"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Desa l\'inici de sessió a"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Vols crear una clau d\'accés en un altre dispositiu?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Vols utilitzar <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> per a tots els teus inicis de sessió?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Aquest gestor de contrasenyes emmagatzemarà les teves contrasenyes i claus d\'accés per ajudar-te a iniciar la sessió fàcilment."</string> <string name="set_as_default" msgid="4415328591568654603">"Estableix com a predeterminada"</string> <string name="use_once" msgid="9027366575315399714">"Utilitza un cop"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> contrasenyes, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> claus d\'accés"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> contrasenyes"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> claus d\'accés"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Clau d\'accés"</string> <string name="another_device" msgid="5147276802037801217">"Un altre dispositiu"</string> <string name="other_password_manager" msgid="565790221427004141">"Altres gestors de contrasenyes"</string> <string name="close_sheet" msgid="1393792015338908262">"Tanca el full"</string> diff --git a/packages/CredentialManager/res/values-cs/strings.xml b/packages/CredentialManager/res/values-cs/strings.xml index 72a5f98e9ad4..b03203304d6d 100644 --- a/packages/CredentialManager/res/values-cs/strings.xml +++ b/packages/CredentialManager/res/values-cs/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Správce oprávnění"</string> <string name="string_cancel" msgid="6369133483981306063">"Zrušit"</string> <string name="string_continue" msgid="1346732695941131882">"Pokračovat"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Vytvořit na jiném místě"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Uložit na jiné místo"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Použít jiné zařízení"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Uložit do jiného zařízení"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Jednoduchý způsob, jak se bezpečně přihlásit"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Použijte svůj otisk prstu, obličej nebo zámek obrazovky k přihlášení pomocí jedinečného přístupového klíče, který nemůžete zapomenout a který vám nikdo nemůže odcizit. Další informace"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Zvolte, kde <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Zvolte, kde <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"vytvářet přístupové klíče"</string> <string name="save_your_password" msgid="6597736507991704307">"uložte si heslo"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"uložte své přihlašovací údaje"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Nastavte si výchozího správce hesel, do kterého si budete ukládat hesla a přístupové klíče za účelem rychlejšího přihlašování."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Vytvořit přístupový klíč v <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Uložit heslo do <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Uložit přihlašovací údaje do <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"přístupový klíč"</string> <string name="password" msgid="6738570945182936667">"heslo"</string> <string name="sign_ins" msgid="4710739369149469208">"přihlášení"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Vytvořit přístupový klíč v"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Uložit heslo do účtu"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Uložit přihlášení do"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Vytvořit přístupový klíč v jiném zařízení?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Používat <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> pro všechna přihlášení?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Tento správce hesel bude ukládat vaše hesla a přístupové klíče, abyste se mohli snadno přihlásit."</string> <string name="set_as_default" msgid="4415328591568654603">"Nastavit jako výchozí"</string> <string name="use_once" msgid="9027366575315399714">"Použít jednou"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"Počet hesel: <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>, počet přístupových klíčů: <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g>"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"Počet hesel: <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"Počet přístupových klíčů: <xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g>"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Přístupový klíč"</string> <string name="another_device" msgid="5147276802037801217">"Jiné zařízení"</string> <string name="other_password_manager" msgid="565790221427004141">"Další správci hesel"</string> <string name="close_sheet" msgid="1393792015338908262">"Zavřít list"</string> diff --git a/packages/CredentialManager/res/values-da/strings.xml b/packages/CredentialManager/res/values-da/strings.xml index a05137e1401f..0c63af5273dc 100644 --- a/packages/CredentialManager/res/values-da/strings.xml +++ b/packages/CredentialManager/res/values-da/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Loginstyring"</string> <string name="string_cancel" msgid="6369133483981306063">"Annuller"</string> <string name="string_continue" msgid="1346732695941131882">"Fortsæt"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Opret et andet sted"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Gem et andet sted"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Brug en anden enhed"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Gem på en anden enhed"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"En nemmere og mere sikker måde at logge ind på"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Brug dit fingeraftryk, dit ansigt eller din skærmlås for at logge ind med en unik adgangsnøgle, der hverken kan glemmes eller stjæles. Få flere oplysninger"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Vælg, hvor du vil <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Vælg, hvor du vil <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"oprette dine adgangsnøgler"</string> <string name="save_your_password" msgid="6597736507991704307">"gem din adgangskode"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"gem dine loginoplysninger"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Angiv en standardadgangskodeadministrator for at gemme dine adgangskoder og adgangsnøgler og logge hurtigere ind næste gang."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Vil du oprette en adgangsnøgle i <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Vil du gemme din adgangskode i <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Vil du gemme dine loginoplysninger i <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"adgangsnøgle"</string> <string name="password" msgid="6738570945182936667">"adgangskode"</string> <string name="sign_ins" msgid="4710739369149469208">"loginmetoder"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Opret adgangsnøgle i"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Gem adgangskode i"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Gem loginmetode i"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Vil du oprette en adgangsnøgle i en anden enhed?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Vil du bruge <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> til alle dine loginmetoder?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Denne adgangskodeadministrator gemmer dine adgangskoder og adgangsnøgler for at hjælpe dig med nemt at logge ind."</string> <string name="set_as_default" msgid="4415328591568654603">"Angiv som standard"</string> <string name="use_once" msgid="9027366575315399714">"Brug én gang"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> adgangskoder, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> adgangsnøgler"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> adgangskoder"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> adgangsnøgler"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Adgangsnøgle"</string> <string name="another_device" msgid="5147276802037801217">"En anden enhed"</string> <string name="other_password_manager" msgid="565790221427004141">"Andre adgangskodeadministratorer"</string> <string name="close_sheet" msgid="1393792015338908262">"Luk arket"</string> diff --git a/packages/CredentialManager/res/values-de/strings.xml b/packages/CredentialManager/res/values-de/strings.xml index fa1e8f10f87a..7d50aed3056f 100644 --- a/packages/CredentialManager/res/values-de/strings.xml +++ b/packages/CredentialManager/res/values-de/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"An anderem Ort speichern"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Anderes Gerät verwenden"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Auf einem anderen Gerät speichern"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Einfach und sicher anmelden"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Verwende deinen Fingerabdruck oder deine Gesichts- bzw. Displaysperre, um dich mit einem eindeutigen Passkey anzumelden, der nicht vergessen oder gestohlen werden kann. Weitere Informationen"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Ort auswählen für: <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Ort auswählen für: <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"Passkeys erstellen"</string> <string name="save_your_password" msgid="6597736507991704307">"Passwort speichern"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"Anmeldedaten speichern"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Du kannst einen Passwortmanager festlegen, der standardmäßig zum Speichern deiner Passwörter und Passkeys verwendet wird, damit du dich das nächste Mal schneller anmelden kannst."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Passkey hier erstellen: <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Passwort hier speichern: <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Anmeldedaten hier speichern: <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"Passkey"</string> <string name="password" msgid="6738570945182936667">"Passwort"</string> <string name="sign_ins" msgid="4710739369149469208">"Anmeldungen"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Passkey hier erstellen:"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Passwort hier speichern:"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Anmeldedaten hier speichern:"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Passkey auf anderem Gerät erstellen?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> für alle Anmeldungen verwenden?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Mit diesem Passwortmanager werden deine Passwörter und Passkeys gespeichert, damit du dich problemlos anmelden kannst."</string> <string name="set_as_default" msgid="4415328591568654603">"Als Standard festlegen"</string> <string name="use_once" msgid="9027366575315399714">"Einmal verwenden"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> Passwörter, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> Passkeys"</string> diff --git a/packages/CredentialManager/res/values-el/strings.xml b/packages/CredentialManager/res/values-el/strings.xml index 706d9f3c4c7a..a088d1deb3d0 100644 --- a/packages/CredentialManager/res/values-el/strings.xml +++ b/packages/CredentialManager/res/values-el/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Αποθήκευση σε άλλη θέση"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Χρήση άλλης συσκευής"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Αποθήκευση σε άλλη συσκευή"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Ένας απλός τρόπος για ασφαλή σύνδεση"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Χρησιμοποιήστε το δακτυλικό αποτύπωμα, το πρόσωπο ή το κλείδωμα οθόνης σας για να συνδεθείτε με ένα μοναδικό κλειδί πρόσβασης που δεν είναι δυνατό να ξεχάσετε ή να κλαπεί. Μάθετε περισσότερα"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Επιλέξτε θέση για <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Επιλέξτε θέση για <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"δημιουργήστε τα κλειδιά πρόσβασής σας"</string> <string name="save_your_password" msgid="6597736507991704307">"αποθήκευση του κωδικού πρόσβασής σας"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"αποθήκευση των στοιχείων σύνδεσής σας"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Για να συνδέεστε πιο γρήγορα, ορίστε ένα προεπιλεγμένο πρόγραμμα διαχείρισης κωδικών πρόσβασης για να αποθηκεύετε τους κωδικούς και τα κλειδιά πρόσβασής σας."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Να δημιουργηθει κλειδί πρόσβασης στο <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>;"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Να αποθηκευτεί ο κωδικός πρόσβασής σας στο <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>;"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Να αποθηκευτούν τα στοιχεία σύνδεσής σας στο <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>;"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"κλειδί πρόσβασης"</string> <string name="password" msgid="6738570945182936667">"κωδικός πρόσβασης"</string> <string name="sign_ins" msgid="4710739369149469208">"στοιχεία σύνδεσης"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Δημιουργία κλειδιού πρόσβασης σε"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Αποθήκευση κωδικού πρόσβασης σε"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Αποθήκευση στοιχείων σύνδεσης σε"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Δημιουργία κλειδιού πρόσβασης σε άλλη συσκευή;"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Να χρησιμοποιηθεί το <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> για όλες τις συνδέσεις σας;"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Αυτός ο διαχειριστής κωδικών πρόσβασης θα αποθηκεύει τους κωδικούς πρόσβασης και τα κλειδιά πρόσβασης, για να συνδέεστε εύκολα."</string> <string name="set_as_default" msgid="4415328591568654603">"Ορισμός ως προεπιλογής"</string> <string name="use_once" msgid="9027366575315399714">"Χρήση μία φορά"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> κωδικοί πρόσβασης, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> κλειδιά πρόσβασης"</string> diff --git a/packages/CredentialManager/res/values-en-rAU/strings.xml b/packages/CredentialManager/res/values-en-rAU/strings.xml index 7adeded11424..a9a6f02909b2 100644 --- a/packages/CredentialManager/res/values-en-rAU/strings.xml +++ b/packages/CredentialManager/res/values-en-rAU/strings.xml @@ -8,8 +8,14 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Save to another place"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Use another device"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Save to another device"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"A simple way to sign in safely"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Use your fingerprint, face or screen lock to sign in with a unique passkey that can’t be forgotten or stolen. Learn more"</string> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> <string name="choose_provider_title" msgid="7245243990139698508">"Choose where to <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> <string name="create_your_passkeys" msgid="8901224153607590596">"create your passkeys"</string> <string name="save_your_password" msgid="6597736507991704307">"save your password"</string> diff --git a/packages/CredentialManager/res/values-en-rCA/strings.xml b/packages/CredentialManager/res/values-en-rCA/strings.xml index 8a8b8845f4cf..c895a41ce132 100644 --- a/packages/CredentialManager/res/values-en-rCA/strings.xml +++ b/packages/CredentialManager/res/values-en-rCA/strings.xml @@ -8,8 +8,10 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Save to another place"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Use another device"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Save to another device"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"A simple way to sign in safely"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Use your fingerprint, face or screen lock to sign in with a unique passkey that can’t be forgotten or stolen. Learn more"</string> + <string name="passkey_creation_intro_title" msgid="4251037543787718844">"Safer with passkeys"</string> + <string name="passkey_creation_intro_body_password" msgid="312712407571126228">"No need to create or remember complex passwords"</string> + <string name="passkey_creation_intro_body_fingerprint" msgid="691816235541508203">"Use your fingerprint, face, or screen lock to create a unique passkey"</string> + <string name="passkey_creation_intro_body_device" msgid="477121861162321129">"Passkeys are saved to a password manager, so you can sign in on other devices"</string> <string name="choose_provider_title" msgid="7245243990139698508">"Choose where to <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> <string name="create_your_passkeys" msgid="8901224153607590596">"create your passkeys"</string> <string name="save_your_password" msgid="6597736507991704307">"save your password"</string> diff --git a/packages/CredentialManager/res/values-en-rGB/strings.xml b/packages/CredentialManager/res/values-en-rGB/strings.xml index 7adeded11424..a9a6f02909b2 100644 --- a/packages/CredentialManager/res/values-en-rGB/strings.xml +++ b/packages/CredentialManager/res/values-en-rGB/strings.xml @@ -8,8 +8,14 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Save to another place"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Use another device"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Save to another device"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"A simple way to sign in safely"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Use your fingerprint, face or screen lock to sign in with a unique passkey that can’t be forgotten or stolen. Learn more"</string> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> <string name="choose_provider_title" msgid="7245243990139698508">"Choose where to <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> <string name="create_your_passkeys" msgid="8901224153607590596">"create your passkeys"</string> <string name="save_your_password" msgid="6597736507991704307">"save your password"</string> diff --git a/packages/CredentialManager/res/values-en-rIN/strings.xml b/packages/CredentialManager/res/values-en-rIN/strings.xml index 7adeded11424..a9a6f02909b2 100644 --- a/packages/CredentialManager/res/values-en-rIN/strings.xml +++ b/packages/CredentialManager/res/values-en-rIN/strings.xml @@ -8,8 +8,14 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Save to another place"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Use another device"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Save to another device"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"A simple way to sign in safely"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Use your fingerprint, face or screen lock to sign in with a unique passkey that can’t be forgotten or stolen. Learn more"</string> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> <string name="choose_provider_title" msgid="7245243990139698508">"Choose where to <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> <string name="create_your_passkeys" msgid="8901224153607590596">"create your passkeys"</string> <string name="save_your_password" msgid="6597736507991704307">"save your password"</string> diff --git a/packages/CredentialManager/res/values-en-rXC/strings.xml b/packages/CredentialManager/res/values-en-rXC/strings.xml index 85e94dfb60a8..efa0633c6cf9 100644 --- a/packages/CredentialManager/res/values-en-rXC/strings.xml +++ b/packages/CredentialManager/res/values-en-rXC/strings.xml @@ -8,8 +8,10 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Save to another place"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Use another device"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Save to another device"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"A simple way to sign in safely"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Use your fingerprint, face or screen lock to sign in with a unique passkey that can’t be forgotten or stolen. Learn more"</string> + <string name="passkey_creation_intro_title" msgid="4251037543787718844">"Safer with passkeys"</string> + <string name="passkey_creation_intro_body_password" msgid="312712407571126228">"No need to create or remember complex passwords"</string> + <string name="passkey_creation_intro_body_fingerprint" msgid="691816235541508203">"Use your fingerprint, face, or screen lock to create a unique passkey"</string> + <string name="passkey_creation_intro_body_device" msgid="477121861162321129">"Passkeys are saved to a password manager, so you can sign in on other devices"</string> <string name="choose_provider_title" msgid="7245243990139698508">"Choose where to <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> <string name="create_your_passkeys" msgid="8901224153607590596">"create your passkeys"</string> <string name="save_your_password" msgid="6597736507991704307">"save your password"</string> diff --git a/packages/CredentialManager/res/values-es-rUS/strings.xml b/packages/CredentialManager/res/values-es-rUS/strings.xml index 5b8e4429ed94..21f072014a31 100644 --- a/packages/CredentialManager/res/values-es-rUS/strings.xml +++ b/packages/CredentialManager/res/values-es-rUS/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Guardar en otra ubicación"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Usar otro dispositivo"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Guardar en otro dispositivo"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Un modo simple y seguro de ingresar"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Usa tu huella dactilar, tu rostro o el bloqueo de pantalla para acceder con una llave de acceso única que no olvidarás ni podrán robarte. Más información"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Elige dónde <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Elige dónde <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"crea tus llaves de acceso"</string> <string name="save_your_password" msgid="6597736507991704307">"guardar tu contraseña"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"guardar tu información de acceso"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Configura un administrador de contraseñas predeterminado para guardar tus contraseñas y llaves de acceso, y acceder más rápido la próxima vez."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"¿Quieres crear una llave de acceso en <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"¿Quieres guardar tu contraseña de <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"¿Quieres guardar tu información de acceso a <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"llave de acceso"</string> <string name="password" msgid="6738570945182936667">"contraseña"</string> <string name="sign_ins" msgid="4710739369149469208">"accesos"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Crear llave de acceso en"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Guardar contraseña en"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Guardar acceso en"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"¿Quieres crear una llave de acceso en otro dispositivo?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"¿Quieres usar <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> para todos tus accesos?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Este administrador de contraseñas almacenará tus contraseñas y llaves de acceso para ayudarte a acceder fácilmente."</string> <string name="set_as_default" msgid="4415328591568654603">"Establecer como predeterminado"</string> <string name="use_once" msgid="9027366575315399714">"Usar una vez"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> llaves de acceso, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> contraseñas"</string> diff --git a/packages/CredentialManager/res/values-es/strings.xml b/packages/CredentialManager/res/values-es/strings.xml index 19fde728ac0e..409bdacae966 100644 --- a/packages/CredentialManager/res/values-es/strings.xml +++ b/packages/CredentialManager/res/values-es/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Gestor de credenciales"</string> <string name="string_cancel" msgid="6369133483981306063">"Cancelar"</string> <string name="string_continue" msgid="1346732695941131882">"Continuar"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Crear en otro lugar"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Guardar en otro lugar"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Usar otro dispositivo"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Guardar en otro dispositivo"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Una forma sencilla y segura de iniciar sesión"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Usa la huella digital, la cara o el bloqueo de pantalla para iniciar sesión con una llave de acceso única que no se puede olvidar ni robar. Más información"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Elige dónde <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Elige dónde <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"crea tus llaves de acceso"</string> <string name="save_your_password" msgid="6597736507991704307">"guardar tu contraseña"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"guardar tu información de inicio de sesión"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Define un gestor de contraseñas predeterminado para guardar tus contraseñas y llaves de acceso e iniciar sesión más rápido la próxima vez."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"¿Crear una llave de acceso en <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"¿Guardar tu contraseña en <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"¿Guardar tu información de inicio de sesión en <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"llave de acceso"</string> <string name="password" msgid="6738570945182936667">"contraseña"</string> <string name="sign_ins" msgid="4710739369149469208">"inicios de sesión"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Crear llave de acceso en"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Guardar contraseña en"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Guardar inicio de sesión en"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"¿Crear una llave de acceso en otro dispositivo?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"¿Usar <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> para todos tus inicios de sesión?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Este gestor de contraseñas almacenará tus contraseñas y llaves de acceso para que puedas iniciar sesión fácilmente."</string> <string name="set_as_default" msgid="4415328591568654603">"Fijar como predeterminado"</string> <string name="use_once" msgid="9027366575315399714">"Usar una vez"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> contraseñas, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> llaves de acceso"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> contraseñas"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> llaves de acceso"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Llave de acceso"</string> <string name="another_device" msgid="5147276802037801217">"Otro dispositivo"</string> <string name="other_password_manager" msgid="565790221427004141">"Otros gestores de contraseñas"</string> <string name="close_sheet" msgid="1393792015338908262">"Cerrar hoja"</string> diff --git a/packages/CredentialManager/res/values-et/strings.xml b/packages/CredentialManager/res/values-et/strings.xml index 5b1b0705c053..bfaec7814258 100644 --- a/packages/CredentialManager/res/values-et/strings.xml +++ b/packages/CredentialManager/res/values-et/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Mandaatide haldur"</string> <string name="string_cancel" msgid="6369133483981306063">"Tühista"</string> <string name="string_continue" msgid="1346732695941131882">"Jätka"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Loo teises kohas"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Salvesta teise kohta"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Kasuta teist seadet"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Salvesta teise seadmesse"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Lihtne viis turvaliselt sisselogimiseks"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Kasutage sõrmejälge, nägu või ekraanilukku, et logida sisse unikaalse pääsuvõtmega, mida ei saa unustada ega varastada. Lisateave"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Valige, kus <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Valige, kus <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"looge oma pääsuvõtmed"</string> <string name="save_your_password" msgid="6597736507991704307">"parool salvestada"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"sisselogimisandmed salvestada"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Määrake vaikeparoolihaldur, et oma paroolid ja pääsuvõtmed salvestada ning järgmisel korral kiiremini sisse logida."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Kas luua teenuses <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> pääsuvõti?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Kas salvestada parool teenusesse <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Kas salvestada sisselogimisteave teenusesse <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"pääsukood"</string> <string name="password" msgid="6738570945182936667">"parool"</string> <string name="sign_ins" msgid="4710739369149469208">"sisselogimisandmed"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Loo pääsuvõti:"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Salvesta parool:"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Salvesta sisselogimisandmed:"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Kas luua pääsuvõti teises seadmes?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Kas kasutada teenust <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> kõigi teie sisselogimisandmete puhul?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"See paroolihaldur salvestab teie paroolid ja pääsuvõtmed, et aidata teil hõlpsalt sisse logida."</string> <string name="set_as_default" msgid="4415328591568654603">"Määra vaikeseadeks"</string> <string name="use_once" msgid="9027366575315399714">"Kasuta ühe korra"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> parooli, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> pääsuvõtit"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> parooli"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> pääsuvõtit"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Pääsukood"</string> <string name="another_device" msgid="5147276802037801217">"Teine seade"</string> <string name="other_password_manager" msgid="565790221427004141">"Muud paroolihaldurid"</string> <string name="close_sheet" msgid="1393792015338908262">"Sule leht"</string> diff --git a/packages/CredentialManager/res/values-eu/strings.xml b/packages/CredentialManager/res/values-eu/strings.xml index b2c1fe5252dd..5a1494b52247 100644 --- a/packages/CredentialManager/res/values-eu/strings.xml +++ b/packages/CredentialManager/res/values-eu/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Kredentzialen kudeatzailea"</string> <string name="string_cancel" msgid="6369133483981306063">"Utzi"</string> <string name="string_continue" msgid="1346732695941131882">"Egin aurrera"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Sortu beste toki batean"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Gorde beste toki batean"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Erabili beste gailu bat"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Gorde beste gailu batean"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Segurtasun osoz saioa hasteko modu erraza"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Erabili hatz-marka, aurpegia edo pantailaren blokeoa ahaztu edo lapurtu ezin den sarbide-gako baten bidez saioa hasteko. Lortu informazio gehiago"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Aukeratu non <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Aukeratu non <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"sortu sarbide-gakoak"</string> <string name="save_your_password" msgid="6597736507991704307">"gorde pasahitza"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"gorde kredentzialei buruzko informazioa"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Ezarri pasahitz-kudeatzaile lehenetsia pasahitzak eta sarbide-gakoak gordetzeko, eta hurrengoan saioa bizkorrago hasteko."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Sarbide-gako bat sortu nahi duzu <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> aplikazioan?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Pasahitza <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> aplikazioan gorde nahi duzu?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Kredentzialei buruzko informazioa <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> aplikazioan gorde nahi duzu?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"sarbide-gakoa"</string> <string name="password" msgid="6738570945182936667">"pasahitza"</string> <string name="sign_ins" msgid="4710739369149469208">"kredentzialak"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Sortu sarbide-gako bat hemen:"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Gorde pasahitza hemen:"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Gorde kredentzialak hemen:"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Sarbide-gako bat sortu nahi duzu beste gailu batean?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> erabili nahi duzu kredentzial guztietarako?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Pasahitz-kudeatzaile honek pasahitzak eta sarbide-gakoak gordeko ditu saioa erraz has dezazun."</string> <string name="set_as_default" msgid="4415328591568654603">"Ezarri lehenetsi gisa"</string> <string name="use_once" msgid="9027366575315399714">"Erabili behin"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> pasahitz eta <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> sarbide-gako"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> pasahitz"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> sarbide-gako"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Sarbide-gakoa"</string> <string name="another_device" msgid="5147276802037801217">"Beste gailu bat"</string> <string name="other_password_manager" msgid="565790221427004141">"Beste pasahitz-kudeatzaile batzuk"</string> <string name="close_sheet" msgid="1393792015338908262">"Itxi orria"</string> diff --git a/packages/CredentialManager/res/values-fa/strings.xml b/packages/CredentialManager/res/values-fa/strings.xml index 98b487caf026..065bde4825b0 100644 --- a/packages/CredentialManager/res/values-fa/strings.xml +++ b/packages/CredentialManager/res/values-fa/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"مدیر اعتبارنامه"</string> <string name="string_cancel" msgid="6369133483981306063">"لغو"</string> <string name="string_continue" msgid="1346732695941131882">"ادامه"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"ایجاد در مکانی دیگر"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"ذخیره در مکانی دیگر"</string> <string name="string_use_another_device" msgid="8754514926121520445">"استفاده از دستگاهی دیگر"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"ذخیره در دستگاهی دیگر"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"روشی ساده برای ورود به سیستم ایمن"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"برای ورود به سیستم با گذرکلیدی یکتا که غیرقابل فراموش شدن یا دزدیده شدن باشد، از اثر انگشت، چهره، یا قفل صفحه استفاده کنید. بیشتر بدانید"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"انتخاب محل <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"انتخاب محل <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"ایجاد گذرکلید"</string> <string name="save_your_password" msgid="6597736507991704307">"ذخیره گذرواژه"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"ذخیره اطلاعات ورود به سیستم"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"برای ذخیره کردن گذرواژهها و گذرکلیدهایتان، مدیر گذرواژه پیشفرض تنظیم کنید تا دفعه بعدی سریعتر به سیستم وارد شوید."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"گذرکلید در <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ایجاد شود؟"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"گذرواژه در <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ذخیره شود؟"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"اطلاعات ورود به سیستم در <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ذخیره شود؟"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"گذرکلید"</string> <string name="password" msgid="6738570945182936667">"گذرواژه"</string> <string name="sign_ins" msgid="4710739369149469208">"ورود به سیستمها"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"ایجاد گذرکلید در"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"ذخیره گذرواژه در"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"ذخیره ورود به سیستم در"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"گذرکلید در دستگاهی دیگر ایجاد شود؟"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"از <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> برای همه ورود به سیستمها استفاده شود؟"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"این مدیر گذرواژه گذرکلیدها و گذرواژههای شما را ذخیره خواهد کرد تا بهراحتی بتوانید به سیستم وارد شوید."</string> <string name="set_as_default" msgid="4415328591568654603">"تنظیم بهعنوان پیشفرض"</string> <string name="use_once" msgid="9027366575315399714">"یکبار استفاده"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> گذرواژه، <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> گذرکلید"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> گذرواژه"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> گذرکلید"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"گذرکلید"</string> <string name="another_device" msgid="5147276802037801217">"دستگاهی دیگر"</string> <string name="other_password_manager" msgid="565790221427004141">"دیگر مدیران گذرواژه"</string> <string name="close_sheet" msgid="1393792015338908262">"بستن برگ"</string> diff --git a/packages/CredentialManager/res/values-fi/strings.xml b/packages/CredentialManager/res/values-fi/strings.xml index 9ad178a456bf..cbea24bea2b6 100644 --- a/packages/CredentialManager/res/values-fi/strings.xml +++ b/packages/CredentialManager/res/values-fi/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Kirjautumistietojen hallinta"</string> <string name="string_cancel" msgid="6369133483981306063">"Peru"</string> <string name="string_continue" msgid="1346732695941131882">"Jatka"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Luo muualla"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Tallenna muualle"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Käytä toista laitetta"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Tallenna toiselle laitteelle"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Helppo tapa kirjautua turvallisesti sisään"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Käytä sormenjälkeä, kasvoja tai näytön lukitusta, niin voit kirjautua sisään yksilöllisellä avainkoodilla, jota ei voi unohtaa tai varastaa. Lue lisää"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Valitse paikka: <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Valitse paikka: <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"luo avainkoodeja"</string> <string name="save_your_password" msgid="6597736507991704307">"tallenna salasanasi"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"tallenna kirjautumistiedot"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Aseta salasanojen ylläpidolle oletustyökalu, niin voit tallentaa salasanat ja avainkoodit sekä kirjautua sisään nopeammin ensi kerralla."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Luodaanko avainkoodi (<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>)?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Tallennetaanko salasanasi tänne: <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Tallennetaanko kirjautumistietosi tänne: <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"avainkoodi"</string> <string name="password" msgid="6738570945182936667">"salasana"</string> <string name="sign_ins" msgid="4710739369149469208">"sisäänkirjautumiset"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Luo avainkoodi tänne:"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Tallenna salasana tänne:"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Tallenna kirjautumistiedot tänne:"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Luodaanko avainkoodi toisella laitteella?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Otetaanko <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> käyttöön kaikissa sisäänkirjautumisissa?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Tämä salasanojen ylläpitotyökalu tallentaa salasanat ja avainkoodit, jotta voit kirjautua helposti sisään."</string> <string name="set_as_default" msgid="4415328591568654603">"Aseta oletukseksi"</string> <string name="use_once" msgid="9027366575315399714">"Käytä kerran"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> salasanaa, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> avainkoodia"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> salasanaa"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> avainkoodia"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Avainkoodi"</string> <string name="another_device" msgid="5147276802037801217">"Toinen laite"</string> <string name="other_password_manager" msgid="565790221427004141">"Muut salasanojen ylläpitotyökalut"</string> <string name="close_sheet" msgid="1393792015338908262">"Sulje taulukko"</string> diff --git a/packages/CredentialManager/res/values-fr-rCA/strings.xml b/packages/CredentialManager/res/values-fr-rCA/strings.xml index a2e758173770..b122fd24b00f 100644 --- a/packages/CredentialManager/res/values-fr-rCA/strings.xml +++ b/packages/CredentialManager/res/values-fr-rCA/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Enregistrer à un autre emplacement"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Utiliser un autre appareil"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Enregistrer sur un autre appareil"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Une manière simple de se connecter en toute sécurité"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Utilisez vos empreintes digitales, votre visage ou un écran de verrouillage pour vous connecter avec une clé d\'accès unique qui ne peut pas être oubliée ou volée. En savoir plus"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Choisir où <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Choisir où <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"créer vos clés d\'accès"</string> <string name="save_your_password" msgid="6597736507991704307">"enregistrer votre mot de passe"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"enregistrer vos données de connexion"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Sélectionnez un gestionnaire de mots de passe par défaut où seront enregistrés vos mots de passe et vos clés d\'accès, et connectez-vous plus rapidement la prochaine fois."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Créer une clé d\'accès dans <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Enregistrer votre mot de passe dans <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Enregistrer vos données de connexion dans <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"clé d\'accès"</string> <string name="password" msgid="6738570945182936667">"mot de passe"</string> <string name="sign_ins" msgid="4710739369149469208">"connexions"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Créer une clé d\'accès dans"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Enregistrer le mot de passe dans"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Enregistrer la connexion dans"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Créer une clé d\'accès dans un autre appareil?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Utiliser <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> pour toutes vos connexions?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Ce gestionnaire de mots de passe va enregistrer vos mots de passe et vos clés d\'accès pour vous aider à vous connecter facilement."</string> <string name="set_as_default" msgid="4415328591568654603">"Définir par défaut"</string> <string name="use_once" msgid="9027366575315399714">"Utiliser une fois"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> mots de passe, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> clés d\'accès"</string> diff --git a/packages/CredentialManager/res/values-fr/strings.xml b/packages/CredentialManager/res/values-fr/strings.xml index 2b280fb7a2a1..cf69329e6bec 100644 --- a/packages/CredentialManager/res/values-fr/strings.xml +++ b/packages/CredentialManager/res/values-fr/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Enregistrer ailleurs"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Utiliser un autre appareil"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Enregistrer sur un autre appareil"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Une façon simple et sécurisée de vous connecter"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Utilisez votre empreinte digitale, votre visage ou le verrouillage de l\'écran pour vous connecter avec une clé d\'accès unique que vous ne pourrez pas oublier ni vous faire voler. En savoir plus"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Choisir où <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Choisir où <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"créer vos clés d\'accès"</string> <string name="save_your_password" msgid="6597736507991704307">"enregistrer votre mot de passe"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"enregistrer vos informations de connexion"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Définissez un gestionnaire de mots de passe par défaut pour enregistrer vos mots de passe et clés d\'accès et vous connecter plus rapidement la prochaine fois."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Créer une clé d\'accès dans <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Enregistrer votre mot de passe dans <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Enregistrer vos informations de connexion dans <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"clé d\'accès"</string> <string name="password" msgid="6738570945182936667">"mot de passe"</string> <string name="sign_ins" msgid="4710739369149469208">"connexions"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Créer une clé d\'accès dans"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Enregistrer le mot de passe dans"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Enregistrer les informations de connexion dans"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Créer une clé d\'accès dans un autre appareil ?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Utiliser <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> pour toutes vos connexions ?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Ce gestionnaire de mots de passe stockera vos mots de passe et clés d\'accès pour vous permettre de vous connecter facilement."</string> <string name="set_as_default" msgid="4415328591568654603">"Définir par défaut"</string> <string name="use_once" msgid="9027366575315399714">"Utiliser une fois"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> mots de passe, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> clés d\'accès"</string> diff --git a/packages/CredentialManager/res/values-gl/strings.xml b/packages/CredentialManager/res/values-gl/strings.xml index cc03ca4ac3a0..c41dca0fbb27 100644 --- a/packages/CredentialManager/res/values-gl/strings.xml +++ b/packages/CredentialManager/res/values-gl/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Gardar noutro lugar"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Usar outro dispositivo"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Gardar noutro dispositivo"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Un xeito fácil de iniciar sesión de forma segura"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Usa a impresión dixital, a cara ou o bloqueo de pantalla para iniciar sesión cunha clave de acceso única que non podes esquecer nin cha poden roubar. Máis información"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Escolle onde <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Escolle onde <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"crear as túas claves de acceso"</string> <string name="save_your_password" msgid="6597736507991704307">"gardar o contrasinal"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"gardar a información de inicio de sesión"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Configura un xestor de contrasinais como predefinido para gardar os teus contrasinais e as túas claves de acceso, e iniciar sesión máis rápido a próxima vez."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Queres crear unha clave de acceso en <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Queres gardar o contrasinal en <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Queres gardar a información de inicio de sesión en <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"clave de acceso"</string> <string name="password" msgid="6738570945182936667">"contrasinal"</string> <string name="sign_ins" msgid="4710739369149469208">"métodos de inicio de sesión"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Crear clave de acceso en"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Gardar contrasinal en"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Gardar método de inicio de sesión en"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Queres crear unha clave de acceso noutro dispositivo?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Queres usar <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> cada vez que inicies sesión?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Este xestor de contrasinais almacenará os contrasinais e as claves de acceso para axudarche a iniciar sesión facilmente."</string> <string name="set_as_default" msgid="4415328591568654603">"Establecer como predeterminado"</string> <string name="use_once" msgid="9027366575315399714">"Usar unha vez"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> contrasinais, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> claves de acceso"</string> diff --git a/packages/CredentialManager/res/values-gu/strings.xml b/packages/CredentialManager/res/values-gu/strings.xml index f796d207823e..17df19ef95fc 100644 --- a/packages/CredentialManager/res/values-gu/strings.xml +++ b/packages/CredentialManager/res/values-gu/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"કોઈ અન્ય સ્થાન પર સાચવો"</string> <string name="string_use_another_device" msgid="8754514926121520445">"કોઈ અન્ય ડિવાઇસનો ઉપયોગ કરો"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"અન્ય ડિવાઇસ પર સાચવો"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"સલામત રીતે સાઇન ઇન કરવાની સરળ રીત"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"ભૂલી ન શકાય કે ચોરાઈ ન જાય, તેવી કોઈ વિશિષ્ટ પાસકી વડે સાઇન ઇન કરવા માટે, તમારી ફિંગરપ્રિન્ટ, ચહેરો અથવા સ્ક્રીન લૉકનો ઉપયોગ કરો. વધુ જાણો"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> ક્યાં સાચવવી છે, તે પસંદ કરો"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> ક્યાં સાચવવી છે, તે પસંદ કરો"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"તમારી પાસકી બનાવો"</string> <string name="save_your_password" msgid="6597736507991704307">"તમારો પાસવર્ડ સાચવો"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"તમારી સાઇન-ઇનની માહિતી સાચવો"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"તમારા પાસવર્ડ અને પાસકી સાચવવા માટે કોઈ ડિફૉલ્ટ પાસવર્ડ મેનેજર સેટ કરો અને આગલી વખતે વધુ ઝડપથી સાઇન ઇન કરો."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"શું <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>માં કોઈ પાસકી બનાવીએ?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"શું તમારો પાસવર્ડ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>માં સાચવીએ?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"શું તમારી સાઇન-ઇનની માહિતી <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>માં સાચવીએ?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"પાસકી"</string> <string name="password" msgid="6738570945182936667">"પાસવર્ડ"</string> <string name="sign_ins" msgid="4710739369149469208">"સાઇન-ઇન"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"આમાં પાસકી બનાવો"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"પાસવર્ડ અહીં સાચવો"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"સાઇન-ઇનની માહિતી અહીં સાચવો"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"શું અન્ય ડિવાઇસમાં પાસકી બનાવવા માગો છો?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"શું તમારા બધા સાઇન-ઇન માટે <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>નો ઉપયોગ કરીએ?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"આ પાસવર્ડ મેનેજર તમને સરળતાથી સાઇન ઇન કરવામાં સહાય કરવા માટે, તમારા પાસવર્ડ અને પાસકીને સ્ટોર કરશે."</string> <string name="set_as_default" msgid="4415328591568654603">"ડિફૉલ્ટ તરીકે સેટ કરો"</string> <string name="use_once" msgid="9027366575315399714">"એકવાર ઉપયોગ કરો"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> પાસવર્ડ, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> પાસકી"</string> diff --git a/packages/CredentialManager/res/values-hi/strings.xml b/packages/CredentialManager/res/values-hi/strings.xml index fbf1c0214aac..014713953d33 100644 --- a/packages/CredentialManager/res/values-hi/strings.xml +++ b/packages/CredentialManager/res/values-hi/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"CredentialManager"</string> <string name="string_cancel" msgid="6369133483981306063">"रद्द करें"</string> <string name="string_continue" msgid="1346732695941131882">"जारी रखें"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"दूसरी जगह पर बनाएं"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"दूसरी जगह पर सेव करें"</string> <string name="string_use_another_device" msgid="8754514926121520445">"दूसरे डिवाइस का इस्तेमाल करें"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"दूसरे डिवाइस पर सेव करें"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"सुरक्षित तरीके से साइन इन करने का आसान तरीका"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"साइन इन करने के लिए फ़िंगरप्रिंट, फ़ेस या स्क्रीन लॉक जैसी यूनीक पासकी का इस्तेमाल करें. इन्हें, न तो भुलाया जा सकता है न ही चुराया जा सकता है. ज़्यादा जानें"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"चुनें कि <xliff:g id="CREATETYPES">%1$s</xliff:g> कहां पर सेव करना है"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"चुनें कि <xliff:g id="CREATETYPES">%1$s</xliff:g> कहां पर सेव करना है"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"अपनी पासकी बनाएं"</string> <string name="save_your_password" msgid="6597736507991704307">"अपना पासवर्ड सेव करें"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"साइन इन से जुड़ी अपनी जानकारी सेव करें"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"डिफ़ॉल्ट पासवर्ड मैनेजर सेट करें, ताकि आपके पासवर्ड और पासकी सेव की जा सकें और अगली बार आप तेज़ी से साइन इन कर सकें."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"क्या आपको <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> में पासकी बनानी है?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"क्या आपको अपना पासवर्ड <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> में सेव करना है?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"क्या आपको साइन इन करने से जुड़ी जानकारी <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> में सेव करनी है?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"पासकी"</string> <string name="password" msgid="6738570945182936667">"पासवर्ड"</string> <string name="sign_ins" msgid="4710739369149469208">"साइन इन"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"पासकी इसमें बनाएं"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"पासवर्ड इसमें सेव करें"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"साइन इन से जुड़ी जानकारी इसमें सेव करें"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"क्या आपको किसी दूसरे डिवाइस में पासकी बनानी है?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"क्या आपको साइन इन से जुड़ी सारी जानकारी सेव करने के लिए, <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> का इस्तेमाल करना है?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"पासवर्ड और पासकी को इस पासवर्ड मैनेजर में सेव करके, आसानी से साइन इन किया जा सकता है."</string> <string name="set_as_default" msgid="4415328591568654603">"डिफ़ॉल्ट के तौर पर सेट करें"</string> <string name="use_once" msgid="9027366575315399714">"इसका इस्तेमाल एक बार किया जा सकता है"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> पासवर्ड और <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> पासकी"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> पासवर्ड"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> पासकी"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"पासकी"</string> <string name="another_device" msgid="5147276802037801217">"दूसरा डिवाइस"</string> <string name="other_password_manager" msgid="565790221427004141">"दूसरे पासवर्ड मैनेजर"</string> <string name="close_sheet" msgid="1393792015338908262">"शीट बंद करें"</string> diff --git a/packages/CredentialManager/res/values-hr/strings.xml b/packages/CredentialManager/res/values-hr/strings.xml index 6c1952f38da3..a5bd3ba8269e 100644 --- a/packages/CredentialManager/res/values-hr/strings.xml +++ b/packages/CredentialManager/res/values-hr/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Upravitelj vjerodajnicama"</string> <string name="string_cancel" msgid="6369133483981306063">"Odustani"</string> <string name="string_continue" msgid="1346732695941131882">"Nastavi"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Izradi na drugom mjestu"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Spremi na drugom mjestu"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Upotrijebite neki drugi uređaj"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Spremi na drugi uređaj"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Jednostavan način za sigurnu prijavu"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Prijavite se otiskom prsta, licem ili zaključavanjem zaslona kao jedinstvenim pristupnim ključem koji je nemoguće zaboraviti ili ukrasti. Saznajte više"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Odaberite mjesto za sljedeće: <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Odaberite mjesto za sljedeće: <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"izradite pristupne ključeve"</string> <string name="save_your_password" msgid="6597736507991704307">"spremi zaporku"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"spremi podatke za prijavu"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Postavite zadani upravitelj zaporki da biste spremili zaporke i pristupne ključeve i sljedeći put se brže prijavili."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Želite li izraditi pristupni ključ na usluzi <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Želite li spremiti zaporku na usluzi <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Želite li spremiti podatke o prijavi na usluzi <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"pristupni ključ"</string> <string name="password" msgid="6738570945182936667">"zaporka"</string> <string name="sign_ins" msgid="4710739369149469208">"prijave"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Izradite pristupni ključ u"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Spremite zaporku na"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Spremite podatke za prijavu na"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Želite li izraditi pristupni ključ na nekom drugom uređaju?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Želite li upotrebljavati uslugu <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> za sve prijave?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Upravitelj zaporki pohranit će vaše zaporke i pristupne ključeve radi jednostavnije prijave."</string> <string name="set_as_default" msgid="4415328591568654603">"Postavi kao zadano"</string> <string name="use_once" msgid="9027366575315399714">"Upotrijebi jednom"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"Broj zaporki: <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>, broj pristupnih ključeva: <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g>"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"Broj zaporki: <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"Broj pristupnih ključeva: <xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g>"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Pristupni ključ"</string> <string name="another_device" msgid="5147276802037801217">"Drugi uređaj"</string> <string name="other_password_manager" msgid="565790221427004141">"Drugi upravitelji zaporki"</string> <string name="close_sheet" msgid="1393792015338908262">"Zatvaranje lista"</string> diff --git a/packages/CredentialManager/res/values-hu/strings.xml b/packages/CredentialManager/res/values-hu/strings.xml index 0efa3e8ec537..4c7703854eeb 100644 --- a/packages/CredentialManager/res/values-hu/strings.xml +++ b/packages/CredentialManager/res/values-hu/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Mentés másik helyre"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Másik eszköz használata"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Mentés másik eszközre"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"A biztonságos bejelentkezés egyszerű módja"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Ujjlenyomatát, arcát vagy képernyőzárát használva egyedi azonosítókulccsal jelentkezhet be, amelyet nem lehet elfelejteni vagy ellopni. További információ."</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Válassza ki a(z) <xliff:g id="CREATETYPES">%1$s</xliff:g> helyét"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Válassza ki a(z) <xliff:g id="CREATETYPES">%1$s</xliff:g> helyét"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"azonosítókulcsok létrehozása"</string> <string name="save_your_password" msgid="6597736507991704307">"jelszó mentése"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"bejelentkezési adatok mentése"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Állítson be alapértelmezett jelszókezelőt jelszavai és azonosítókulcsai mentéséhez és a gyorsabb bejelentkezéshez."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Létrehoz azonosítókulcsot a(z) <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> szolgáltatásban?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Menti jelszavát a(z) <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> szolgáltatásba?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Menti bejelentkezési adatait a(z) <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> szolgáltatásba?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"azonosítókulcs"</string> <string name="password" msgid="6738570945182936667">"jelszó"</string> <string name="sign_ins" msgid="4710739369149469208">"bejelentkezési adatok"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Azonosítókulcs létrehozása itt:"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Jelszó mentése ide:"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Bejelentkezési adatok mentése ide:"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Létrehoz azonosítókulcsot egy másik eszközön?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Szeretné a következőt használni az összes bejelentkezési adatához: <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Ez a jelszókezelő a bejelentkezés megkönnyítése érdekében tárolja jelszavait és azonosítókulcsait."</string> <string name="set_as_default" msgid="4415328591568654603">"Beállítás alapértelmezettként"</string> <string name="use_once" msgid="9027366575315399714">"Egyszeri használat"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> jelszó, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> azonosítókulcs"</string> diff --git a/packages/CredentialManager/res/values-hy/strings.xml b/packages/CredentialManager/res/values-hy/strings.xml index de47e9f5858c..afa529a6ed7d 100644 --- a/packages/CredentialManager/res/values-hy/strings.xml +++ b/packages/CredentialManager/res/values-hy/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Մուտքի տվյալների կառավարիչ"</string> <string name="string_cancel" msgid="6369133483981306063">"Չեղարկել"</string> <string name="string_continue" msgid="1346732695941131882">"Շարունակել"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Ստեղծել այլ տեղում"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Պահել այլ տեղում"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Օգտագործել այլ սարք"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Պահել մեկ այլ սարքում"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Մուտք գործելու անվտանգ և պարզ եղանակ"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Օգտագործեք ձեր մատնահետքը, դեմքը կամ էկրանի կողպումը՝ մուտք գործելու հաշիվ եզակի անցաբառի միջոցով, որը հնարավոր չէ կոտրել կամ մոռանալ։ Իմանալ ավելին"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Ընտրեք, թե որտեղ <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Ընտրեք, թե որտեղ <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"ստեղծել ձեր անցաբառերը"</string> <string name="save_your_password" msgid="6597736507991704307">"պահել գաղտնաբառը"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"պահել մուտքի տվյալները"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Սահմանեք գաղտնաբառերի կանխադրված կառավարիչ՝ ձեր գաղտնաբառերն ու անցաբառերը պահելու և հաջորդ անգամ ավելի արագ մուտք գործելու համար։"</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Ստեղծե՞լ անցաբառ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> հավելվածում"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Պահե՞լ ձեր գաղտնաբառը <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> հավելվածում"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Պահե՞լ ձեր մուտքի տվյալները <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> հավելվածում"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"անցաբառ"</string> <string name="password" msgid="6738570945182936667">"գաղտնաբառ"</string> <string name="sign_ins" msgid="4710739369149469208">"մուտք"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Ստեղծել անցաբառ…"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Պահել գաղտնաբառը…"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Պահել մուտքի տվյալները…"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Ստեղծե՞լ անցաբառ մեկ այլ սարքում"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Միշտ մուտք գործե՞լ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> հավելվածի միջոցով"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Գաղտնաբառերի այս կառավարիչը կպահի ձեր գաղտնաբառերն ու անցաբառերը՝ օգնելու ձեզ հեշտությամբ մուտք գործել հաշիվ։"</string> <string name="set_as_default" msgid="4415328591568654603">"Նշել որպես կանխադրված"</string> <string name="use_once" msgid="9027366575315399714">"Օգտագործել մեկ անգամ"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> գաղտնաբառ, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> անցաբառ"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> գաղտնաբառ"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> անցաբառ"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Անցաբառ"</string> <string name="another_device" msgid="5147276802037801217">"Այլ սարք"</string> <string name="other_password_manager" msgid="565790221427004141">"Գաղտնաբառերի այլ կառավարիչներ"</string> <string name="close_sheet" msgid="1393792015338908262">"Փակել թերթը"</string> diff --git a/packages/CredentialManager/res/values-in/strings.xml b/packages/CredentialManager/res/values-in/strings.xml index d980d44c7f32..5cad3f39ccc1 100644 --- a/packages/CredentialManager/res/values-in/strings.xml +++ b/packages/CredentialManager/res/values-in/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Simpan ke tempat lain"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Gunakan perangkat lain"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Simpan ke perangkat lain"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Cara mudah untuk login dengan aman"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Gunakan sidik jari, wajah, atau kunci layar untuk login dengan kunci sandi unik yang mudah diingat dan tidak dapat dicuri. Pelajari lebih lanjut"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Pilih tempat untuk <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Pilih tempat untuk <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"membuat kunci sandi Anda"</string> <string name="save_your_password" msgid="6597736507991704307">"menyimpan sandi Anda"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"menyimpan info login Anda"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Setel pengelola sandi default untuk menyimpan sandi dan kunci sandi sehingga nantinya Anda dapat login lebih cepat."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Buat kunci sandi di <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Simpan sandi ke <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Simpan info login ke <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"kunci sandi"</string> <string name="password" msgid="6738570945182936667">"sandi"</string> <string name="sign_ins" msgid="4710739369149469208">"login"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Buat kunci sandi di"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Simpan sandi ke"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Simpan info login ke"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Buat kunci sandi di perangkat lain?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Gunakan <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> untuk semua info login Anda?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Pengelola sandi ini akan menyimpan sandi dan kunci sandi untuk membantu Anda login dengan mudah."</string> <string name="set_as_default" msgid="4415328591568654603">"Setel sebagai default"</string> <string name="use_once" msgid="9027366575315399714">"Gunakan sekali"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> sandi, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> kunci sandi"</string> diff --git a/packages/CredentialManager/res/values-is/strings.xml b/packages/CredentialManager/res/values-is/strings.xml index 3fd6af2456b9..f34dd69e7bfe 100644 --- a/packages/CredentialManager/res/values-is/strings.xml +++ b/packages/CredentialManager/res/values-is/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Skilríkjastjórnun"</string> <string name="string_cancel" msgid="6369133483981306063">"Hætta við"</string> <string name="string_continue" msgid="1346732695941131882">"Áfram"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Búa til annarsstaðar"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Vista annarsstaðar"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Nota annað tæki"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Vista í öðru tæki"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Einföld leið við örugga innskráningu"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Notaðu fingrafar, andlit eða skjálás til að skrá þig inn með einkvæmum aðgangslykli sem ekki er hægt að gleyma eða stela. Nánar"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Veldu hvar á að <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Veldu hvar á að <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"búa til aðgangslykla"</string> <string name="save_your_password" msgid="6597736507991704307">"vistaðu aðgangsorðið"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"vistaðu innskráningarupplýsingarnar"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Stilltu sjálfgefna aðgangsorðastjórnun til að vista aðgangsorð og aðgangslykla og skrá þig hraðar inn næst."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Búa til aðgangslykil í <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Vista aðgangsorð í <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Vista innskráningarupplýsingar í <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"aðgangslykill"</string> <string name="password" msgid="6738570945182936667">"aðgangsorð"</string> <string name="sign_ins" msgid="4710739369149469208">"innskráningar"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Búa til aðgangslykil í"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Vista aðgangsorð á"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Vista innskráningu á"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Viltu búa til aðgangslykil í öðru tæki?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Nota <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> fyrir allar innskráningar?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Þessi aðgangsorðastjórnun vistar aðgangsorð og aðgangslykla til að auðvelda þér að skrá þig inn."</string> <string name="set_as_default" msgid="4415328591568654603">"Stilla sem sjálfgefið"</string> <string name="use_once" msgid="9027366575315399714">"Nota einu sinni"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> aðgangsorð, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> aðgangslyklar"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> aðgangsorð"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> aðgangslyklar"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Aðgangslykill"</string> <string name="another_device" msgid="5147276802037801217">"Annað tæki"</string> <string name="other_password_manager" msgid="565790221427004141">"Önnur aðgangsorðastjórnun"</string> <string name="close_sheet" msgid="1393792015338908262">"Loka blaði"</string> diff --git a/packages/CredentialManager/res/values-it/strings.xml b/packages/CredentialManager/res/values-it/strings.xml index 3a7b0fb1ec3a..ddb2f3aa2efb 100644 --- a/packages/CredentialManager/res/values-it/strings.xml +++ b/packages/CredentialManager/res/values-it/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Salva in un altro luogo"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Usa un altro dispositivo"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Salva su un altro dispositivo"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Un modo semplice per accedere in sicurezza"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Usa l\'impronta digitale, il volto o il blocco schermo per accedere con una passkey unica che non può essere dimenticata o rubata. Scopri di più"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Scegli dove <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Scegli dove <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"Crea le tue passkey"</string> <string name="save_your_password" msgid="6597736507991704307">"salva la password"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"salva le tue informazioni di accesso"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Imposta un gestore delle password predefinito per salvare le tue password e passkey in modo da poter accedere più velocemente la prossima volta."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Vuoi creare una passkey su <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Vuoi salvare la password su <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Vuoi salvare le informazioni di accesso su <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"passkey"</string> <string name="password" msgid="6738570945182936667">"password"</string> <string name="sign_ins" msgid="4710739369149469208">"accessi"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Crea passkey su"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Salva password su"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Salva accesso su"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Vuoi creare una passkey su un altro dispositivo?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Vuoi usare <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> per tutti gli accessi?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Questo gestore delle password archivierà le password e le passkey per aiutarti ad accedere facilmente."</string> <string name="set_as_default" msgid="4415328591568654603">"Imposta come valore predefinito"</string> <string name="use_once" msgid="9027366575315399714">"Usa una volta"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> password, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> passkey"</string> diff --git a/packages/CredentialManager/res/values-iw/strings.xml b/packages/CredentialManager/res/values-iw/strings.xml index 397ad60e79f7..50752eb3e3bd 100644 --- a/packages/CredentialManager/res/values-iw/strings.xml +++ b/packages/CredentialManager/res/values-iw/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"שמירה במקום אחר"</string> <string name="string_use_another_device" msgid="8754514926121520445">"שימוש במכשיר אחר"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"שמירה במכשיר אחר"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"דרך פשוטה להיכנס לחשבון בבטחה"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"אפשר להשתמש בטביעת אצבע, בזיהוי פנים או בנעילת מסך כדי להיכנס לחשבון עם מפתח גישה ייחודי שאי אפשר לשכוח או לגנוב אותו. מידע נוסף"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"צריך לבחור לאן <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"צריך לבחור לאן <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"יצירת מפתחות גישה"</string> <string name="save_your_password" msgid="6597736507991704307">"שמירת הסיסמה שלך"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"שמירת פרטי הכניסה שלך"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"יש לקבוע את מנהל הסיסמאות שיוגדר כברירת מחדל כדי לשמור את הסיסמאות ומפתחות הגישה, ולהיכנס לחשבון מהר יותר בפעם הבאה."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"ליצור מפתח גישה ב-<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"לשמור את הסיסמה ב-<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"לשמור את פרטי הכניסה ב-<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"מפתח גישה"</string> <string name="password" msgid="6738570945182936667">"סיסמה"</string> <string name="sign_ins" msgid="4710739369149469208">"פרטי כניסה"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"יצירת מפתח גישה ב"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"שמירת הסיסמה של"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"שמירת פרטי הכניסה של"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"ליצור מפתח גישה במכשיר אחר?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"להשתמש ב-<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> בכל הכניסות?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"במנהל הסיסמאות הזה יאוחסנו הסיסמאות ומפתחות הגישה שלך, כדי לעזור לך להיכנס לחשבון בקלות."</string> <string name="set_as_default" msgid="4415328591568654603">"הגדרה כברירת מחדל"</string> <string name="use_once" msgid="9027366575315399714">"שימוש פעם אחת"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> סיסמאות, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> מפתחות גישה"</string> diff --git a/packages/CredentialManager/res/values-ja/strings.xml b/packages/CredentialManager/res/values-ja/strings.xml index 0340b6698645..783a444b8a97 100644 --- a/packages/CredentialManager/res/values-ja/strings.xml +++ b/packages/CredentialManager/res/values-ja/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"別の場所に保存"</string> <string name="string_use_another_device" msgid="8754514926121520445">"別のデバイスを使用"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"他のデバイスに保存"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"安全にログインする簡単な方法"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"忘れたり盗まれたりする可能性がある一意のパスキーと合わせて、ログインに指紋認証、顔認証、画面ロックを使用できます。詳細"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> の保存場所の選択"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> の保存場所の選択"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"パスキーの作成"</string> <string name="save_your_password" msgid="6597736507991704307">"パスワードを保存"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"ログイン情報を保存"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"デフォルトのパスワード マネージャーを設定すると、パスワードやパスキーを保存して、次回から素早くログインできるようになります。"</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> でパスキーを作成しますか?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> にパスワードを保存しますか?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> にログイン情報を保存しますか?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"パスキー"</string> <string name="password" msgid="6738570945182936667">"パスワード"</string> <string name="sign_ins" msgid="4710739369149469208">"ログイン"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"パスキーの作成先"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"パスワードの保存先"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"ログイン情報の保存先"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"他のデバイスでパスキーを作成しますか?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"ログインのたびに <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> を使用しますか?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"このパスワード マネージャーに、パスワードやパスキーが保存され、簡単にログインできるようになります。"</string> <string name="set_as_default" msgid="4415328591568654603">"デフォルトに設定"</string> <string name="use_once" msgid="9027366575315399714">"1 回使用"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> 件のパスワード、<xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> 件のパスキー"</string> diff --git a/packages/CredentialManager/res/values-ka/strings.xml b/packages/CredentialManager/res/values-ka/strings.xml index 3da7ea394c60..eba01d4c0a86 100644 --- a/packages/CredentialManager/res/values-ka/strings.xml +++ b/packages/CredentialManager/res/values-ka/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"სხვა სივრცეში შენახვა"</string> <string name="string_use_another_device" msgid="8754514926121520445">"სხვა მოწყობილობის გამოყენება"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"სხვა მოწყობილობაზე შენახვა"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"უსაფრთხოდ შესვლის მარტივი გზა"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"გამოიყენეთ თქვენი თითის ანაბეჭდი, სახის ამოცნობა და ეკრანის დაბლოკვა სისტემაში უნიკალური წვდომის გასაღებით შესასვლელად, რომლის დავიწყება ან მოპარვა შეუძლებელია. შეიტყვეთ მეტი"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"აირჩიეთ, სად უნდა <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"აირჩიეთ, სად უნდა <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"შექმენით თქვენი პაროლი"</string> <string name="save_your_password" msgid="6597736507991704307">"შეინახეთ თქვენი პაროლი"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"შეინახეთ თქვენი სისტემაში შესვლის ინფორმაცია"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"დააყენეთ პაროლის ნაგულისხმევი მენეჯერი, რათა შეინახოთ თქვენი პაროლები და გასაღებები და შეხვიდეთ უფრო სწრაფად შემდეგ ჯერზე."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"გსურთ წვდომის გასაღების შექმნა <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>-ში?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"გსურთ თქვენი პაროლის შენახვა <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>-ში?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"გსურთ თქვენი სისტემაში შესვლის მონაცემების შენახვა <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>-ში?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"წვდომის გასაღები"</string> <string name="password" msgid="6738570945182936667">"პაროლი"</string> <string name="sign_ins" msgid="4710739369149469208">"სისტემაში შესვლა"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"წვდომის გასაღების შექმნა"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"პაროლის შენახვა"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"შესვლის შენახვა"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"გსურთ პაროლის შექმნა სხვა მოწყობილობაში?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"გსურთ, გამოიყენოთ<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> სისტემაში ყველა შესვლისთვის?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"მოცემული პაროლების მმართველი შეინახავს თქვენს პაროლებს და წვდომის გასაღებს, რომლებიც დაგეხმარებათ სისტემაში მარტივად შესვლაში."</string> <string name="set_as_default" msgid="4415328591568654603">"ნაგულისხმევად დაყენება"</string> <string name="use_once" msgid="9027366575315399714">"ერთხელ გამოყენება"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> პაროლი, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> წვდომის გასაღები"</string> diff --git a/packages/CredentialManager/res/values-kk/strings.xml b/packages/CredentialManager/res/values-kk/strings.xml index 9491f8e83d6b..d7d255b63c07 100644 --- a/packages/CredentialManager/res/values-kk/strings.xml +++ b/packages/CredentialManager/res/values-kk/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Тіркелу деректері менеджері"</string> <string name="string_cancel" msgid="6369133483981306063">"Бас тарту"</string> <string name="string_continue" msgid="1346732695941131882">"Жалғастыру"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Басқа орында жасау"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Басқа орынға сақтау"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Басқа құрылғыны пайдалану"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Басқа құрылғыға сақтау"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Қауіпсіз кірудің оңай жолы"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Ұмытылмайтын немесе ұрланбайтын бірегей кіру кілтінің көмегімен кіру үшін саусақ ізін, бетті анықтау функциясын немесе экран құлпын пайдаланыңыз. Толық ақпарат"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> таңдау"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> таңдау"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"кіру кілттерін жасаңыз"</string> <string name="save_your_password" msgid="6597736507991704307">"құпия сөзді сақтау"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"тіркелу деректерін сақтау"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Құпия сөздер мен кіру кілттерін сақтап, келесі рет жылдам кіру үшін әдепкі құпия сөз менеджерін орнатыңыз."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> қолданбасында кіру кілті жасалсын ба?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> қолданбасына құпия сөз сақталсын ба?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> қолданбасына тіркелу деректері сақталсын ба?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"кіру кілті"</string> <string name="password" msgid="6738570945182936667">"құпия сөз"</string> <string name="sign_ins" msgid="4710739369149469208">"кіру әрекеттері"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Кіру кілтін жасау"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Құпия сөзді келесіге сақтау:"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Кіру деректерін келесіге сақтау:"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Кіру кілті басқа құрылғыда жасалсын ба?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Барлық кіру әрекеті үшін <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> пайдаланылсын ба?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Аккаунтқа оңай кіру үшін құпия сөз менеджері құпия сөздер мен кіру кілттерін сақтайды."</string> <string name="set_as_default" msgid="4415328591568654603">"Әдепкі етіп орнату"</string> <string name="use_once" msgid="9027366575315399714">"Бір рет пайдалану"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> құпия сөз, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> кіру кілті"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> құпия сөз"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> кіру кілті"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Кіру кілті"</string> <string name="another_device" msgid="5147276802037801217">"Басқа құрылғы"</string> <string name="other_password_manager" msgid="565790221427004141">"Басқа құпия сөз менеджерлері"</string> <string name="close_sheet" msgid="1393792015338908262">"Парақты жабу"</string> diff --git a/packages/CredentialManager/res/values-km/strings.xml b/packages/CredentialManager/res/values-km/strings.xml index 80167fc36e35..b10466149c57 100644 --- a/packages/CredentialManager/res/values-km/strings.xml +++ b/packages/CredentialManager/res/values-km/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"កម្មវិធីគ្រប់គ្រងព័ត៌មានផ្ទៀងផ្ទាត់"</string> <string name="string_cancel" msgid="6369133483981306063">"បោះបង់"</string> <string name="string_continue" msgid="1346732695941131882">"បន្ត"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"បង្កើតនៅកន្លែងផ្សេងទៀត"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"រក្សាទុកក្នុងកន្លែងផ្សេងទៀត"</string> <string name="string_use_another_device" msgid="8754514926121520445">"ប្រើឧបករណ៍ផ្សេងទៀត"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"រក្សាទុកទៅក្នុងឧបករណ៍ផ្សេង"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"វិធីដ៏សាមញ្ញ ដើម្បីចូលគណនីដោយសុវត្ថិភាព"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"ប្រើស្នាមម្រាមដៃ មុខ ឬការចាក់សោអេក្រង់របស់អ្នក ដើម្បីចូលគណនីដោយប្រើកូដសម្ងាត់ខុសប្លែកពីគេដែលមិនអាចភ្លេច ឬត្រូវគេលួច។ ស្វែងយល់បន្ថែម"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"ជ្រើសរើសកន្លែងដែលត្រូវ <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"ជ្រើសរើសកន្លែងដែលត្រូវ <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"បង្កើតកូដសម្ងាត់របស់អ្នក"</string> <string name="save_your_password" msgid="6597736507991704307">"រក្សាទុកពាក្យសម្ងាត់របស់អ្នក"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"រក្សាទុកព័ត៌មានចូលគណនីរបស់អ្នក"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"កំណត់កម្មវិធីគ្រប់គ្រងពាក្យសម្ងាត់លំនាំដើម ដើម្បីរក្សាទុកពាក្យសម្ងាត់និងកូដសម្ងាត់របស់អ្នក និងចូលគណនីកាន់តែរហ័សនៅពេលលើកក្រោយ។"</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"បង្កើតកូដសម្ងាត់នៅក្នុង <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ឬ?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"រក្សាទុកពាក្យសម្ងាត់របស់អ្នកក្នុង <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ឬ?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"រក្សាទុកព័ត៌មានចូលគណនីរបស់អ្នកក្នុង <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ឬ?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"កូដសម្ងាត់"</string> <string name="password" msgid="6738570945182936667">"ពាក្យសម្ងាត់"</string> <string name="sign_ins" msgid="4710739369149469208">"ការចូលគណនី"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"បង្កើតកូដសម្ងាត់នៅក្នុង"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"រក្សាទុកពាក្យសម្ងាត់ទៅ"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"រក្សាទុកការចូលគណនីទៅ"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"បង្កើតកូដសម្ងាត់នៅក្នុងឧបករណ៍ផ្សេងទៀតឬ?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"ប្រើ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> សម្រាប់ការចូលគណនីទាំងអស់របស់អ្នកឬ?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"កម្មវិធីគ្រប់គ្រងពាក្យសម្ងាត់នេះនឹងរក្សាទុកពាក្យសម្ងាត់ និងកូដសម្ងាត់របស់អ្នក ដើម្បីជួយឱ្យអ្នកចូលគណនីបានយ៉ាងងាយស្រួល។"</string> <string name="set_as_default" msgid="4415328591568654603">"កំណត់ជាលំនាំដើម"</string> <string name="use_once" msgid="9027366575315399714">"ប្រើម្ដង"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"ពាក្យសម្ងាត់ <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> កូដសម្ងាត់ <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g>"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"ពាក្យសម្ងាត់ <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"កូដសម្ងាត់ <xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g>"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"កូដសម្ងាត់"</string> <string name="another_device" msgid="5147276802037801217">"ឧបករណ៍ផ្សេងទៀត"</string> <string name="other_password_manager" msgid="565790221427004141">"កម្មវិធីគ្រប់គ្រងពាក្យសម្ងាត់ផ្សេងទៀត"</string> <string name="close_sheet" msgid="1393792015338908262">"បិទសន្លឹក"</string> diff --git a/packages/CredentialManager/res/values-kn/strings.xml b/packages/CredentialManager/res/values-kn/strings.xml index 96304ac96d3b..033eec1df02c 100644 --- a/packages/CredentialManager/res/values-kn/strings.xml +++ b/packages/CredentialManager/res/values-kn/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"ಮತ್ತೊಂದು ಸ್ಥಳದಲ್ಲಿ ಉಳಿಸಿ"</string> <string name="string_use_another_device" msgid="8754514926121520445">"ಬೇರೊಂದು ಸಾಧನವನ್ನು ಬಳಸಿ"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"ಬೇರೊಂದು ಸಾಧನದಲ್ಲಿ ಉಳಿಸಿ"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"ಸುರಕ್ಷಿತವಾಗಿ ಸೈನ್ ಇನ್ ಮಾಡುವ ಸುಲಭ ವಿಧಾನ"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"ಮರೆಯಲಾಗದ ಅಥವಾ ಕದಿಯಲಾಗದ ಅನನ್ಯ ಪಾಸ್ಕೀ ಮೂಲಕ ಸೈನ್ ಇನ್ ಮಾಡಲು ನಿಮ್ಮ ಫಿಂಗರ್ಪ್ರಿಂಟ್, ಫೇಸ್ ಲಾಕ್ ಅಥವಾ ಸ್ಕ್ರೀನ್ ಲಾಕ್ ಬಳಸಿ. ಇನ್ನಷ್ಟು ತಿಳಿಯಿರಿ"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> ಅನ್ನು ಎಲ್ಲಿ ಉಳಿಸಬೇಕು ಎಂದು ಆಯ್ಕೆಮಾಡಿ"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> ಅನ್ನು ಎಲ್ಲಿ ಉಳಿಸಬೇಕು ಎಂದು ಆಯ್ಕೆಮಾಡಿ"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"ನಿಮ್ಮ ಪಾಸ್ಕೀಗಳನ್ನು ರಚಿಸಿ"</string> <string name="save_your_password" msgid="6597736507991704307">"ನಿಮ್ಮ ಪಾಸ್ವರ್ಡ್ ಉಳಿಸಿ"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"ನಿಮ್ಮ ಸೈನ್-ಇನ್ ಮಾಹಿತಿ ಉಳಿಸಿ"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"ನಿಮ್ಮ ಪಾಸ್ವರ್ಡ್ಗಳು ಮತ್ತು ಪಾಸ್ಕೀಗಳನ್ನು ಉಳಿಸಲು ಡೀಫಾಲ್ಟ್ ಪಾಸ್ವರ್ಡ್ ನಿರ್ವಾಹಕವನ್ನು ಸೆಟ್ ಮಾಡಿ ಹಾಗೂ ಮುಂದಿನ ಬಾರಿ ವೇಗವಾಗಿ ಸೈನ್ ಇನ್ ಮಾಡಿ."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ನಲ್ಲಿ ಪಾಸ್ಕೀ ರಚಿಸಬೇಕೆ?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"ನಿಮ್ಮ ಪಾಸ್ವರ್ಡ್ ಅನ್ನು <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ಗೆ ಉಳಿಸಬೇಕೆ?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"ನಿಮ್ಮ ಸೈನ್ ಇನ್ ಮಾಹಿತಿಯನ್ನು <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ಗೆ ಉಳಿಸಬೇಕೆ?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"ಪಾಸ್ಕೀ"</string> <string name="password" msgid="6738570945182936667">"ಪಾಸ್ವರ್ಡ್"</string> <string name="sign_ins" msgid="4710739369149469208">"ಸೈನ್-ಇನ್ಗಳು"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"ಇಲ್ಲಿ ಪಾಸ್ಕೀ ರಚಿಸಿ"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"ಇಲ್ಲಿಗೆ ಪಾಸ್ವರ್ಡ್ ಉಳಿಸಿ"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"ಇಲ್ಲಿಗೆ ಸೈನ್-ಇನ್ ಮಾಹಿತಿ ಉಳಿಸಿ"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"ಮತ್ತೊಂದು ಸಾಧನದಲ್ಲಿ ಪಾಸ್ಕೀ ರಚಿಸಬೇಕೆ?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"ನಿಮ್ಮ ಎಲ್ಲಾ ಸೈನ್-ಇನ್ಗಳಿಗಾಗಿ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ಅನ್ನು ಬಳಸುವುದೇ?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"ಈ ಪಾಸ್ವರ್ಡ್ ನಿರ್ವಾಹಕವು ನಿಮಗೆ ಸುಲಭವಾಗಿ ಸೈನ್ ಇನ್ ಮಾಡುವುದಕ್ಕೆ ಸಹಾಯ ಮಾಡಲು ನಿಮ್ಮ ಪಾಸ್ವರ್ಡ್ಗಳು ಮತ್ತು ಪಾಸ್ಕೀಗಳನ್ನು ಸಂಗ್ರಹಿಸುತ್ತದೆ."</string> <string name="set_as_default" msgid="4415328591568654603">"ಡೀಫಾಲ್ಟ್ ಆಗಿ ಸೆಟ್ ಮಾಡಿ"</string> <string name="use_once" msgid="9027366575315399714">"ಒಂದು ಬಾರಿ ಬಳಸಿ"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> ಪಾಸ್ವರ್ಡ್ಗಳು, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> ಪಾಸ್ಕೀಗಳು"</string> diff --git a/packages/CredentialManager/res/values-ko/strings.xml b/packages/CredentialManager/res/values-ko/strings.xml index 58518c16ace4..44f22d76a546 100644 --- a/packages/CredentialManager/res/values-ko/strings.xml +++ b/packages/CredentialManager/res/values-ko/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"인증서 관리자"</string> <string name="string_cancel" msgid="6369133483981306063">"취소"</string> <string name="string_continue" msgid="1346732695941131882">"계속"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"다른 위치에 만들기"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"다른 위치에 저장"</string> <string name="string_use_another_device" msgid="8754514926121520445">"다른 기기 사용"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"다른 기기에 저장"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"안전하게 로그인하는 간단한 방법"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"지문, 얼굴 인식 또는 화면 잠금을 통해 잊어버리거나 분실할 염려가 없는 고유한 패스키로 로그인하세요. 자세히 알아보기"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> 작업을 위한 위치 선택"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> 작업을 위한 위치 선택"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"패스키 만들기"</string> <string name="save_your_password" msgid="6597736507991704307">"비밀번호 저장"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"로그인 정보 저장"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"기본 비밀번호 관리자를 설정하여 비밀번호와 패스키를 저장하고 다음에 더 빠르게 로그인하세요."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>에 패스키를 만드시겠습니까?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>에 비밀번호를 저장하시겠습니까?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>에 로그인 정보를 저장하시겠습니까?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"패스키"</string> <string name="password" msgid="6738570945182936667">"비밀번호"</string> <string name="sign_ins" msgid="4710739369149469208">"로그인 정보"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"다음 위치에 패스키 만들기"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"비밀번호를 다음에 저장"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"로그인 정보를 다음에 저장"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"다른 기기에서 패스키를 만들까요?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"모든 로그인에 <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>을(를) 사용하시겠습니까?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"이 비밀번호 관리자는 비밀번호와 패스키를 저장하여 사용자가 간편하게 로그인하도록 돕습니다."</string> <string name="set_as_default" msgid="4415328591568654603">"기본값으로 설정"</string> <string name="use_once" msgid="9027366575315399714">"한 번 사용"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"비밀번호 <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>개, 패스키 <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g>개"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"비밀번호 <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>개"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"패스키 <xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g>개"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"패스키"</string> <string name="another_device" msgid="5147276802037801217">"다른 기기"</string> <string name="other_password_manager" msgid="565790221427004141">"기타 비밀번호 관리자"</string> <string name="close_sheet" msgid="1393792015338908262">"시트 닫기"</string> diff --git a/packages/CredentialManager/res/values-ky/strings.xml b/packages/CredentialManager/res/values-ky/strings.xml index 298657eb8eaa..c4621cfde407 100644 --- a/packages/CredentialManager/res/values-ky/strings.xml +++ b/packages/CredentialManager/res/values-ky/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Credential Manager"</string> <string name="string_cancel" msgid="6369133483981306063">"Жок"</string> <string name="string_continue" msgid="1346732695941131882">"Улантуу"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Башка жерде түзүү"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Башка жерге сактоо"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Башка түзмөк колдонуу"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Башка түзмөккө сактоо"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Коопсуз кирүүнүн жөнөкөй жолу"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Унутуп калууга же уурдатууга мүмкүн эмес болгон уникалдуу ачкыч менен манжа изин, жүзүнөн таанып ачуу же экранды кулпулоо функцияларын колдонуп өзүңүздү ырастай аласыз. Кененирээк"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> үчүн жер тандаңыз"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> үчүн жер тандаңыз"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"мүмкүндүк алуу ачкычтарын түзүү"</string> <string name="save_your_password" msgid="6597736507991704307">"сырсөзүңүздү сактаңыз"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"кирүү маалыматын сактаңыз"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Сырсөздөр менен мүмкүндүк алуу ачкычтары сактала турган демейки сырсөздөрдү башкаргычты тандап, кийинки жолу аккаунтуңузга тезирээк кириңиз."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> колдонмосунда мүмкүндүк алуу ачкычын түзөсүзбү?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Сырсөзүңүздү <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> колдонмосунда сактайсызбы?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Кирүү маалыматын <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> колдонмосунда сактайсызбы?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"мүмкүндүк алуу ачкычы"</string> <string name="password" msgid="6738570945182936667">"сырсөз"</string> <string name="sign_ins" msgid="4710739369149469208">"кирүүлөр"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Мүмкүндүк алуу ачкычын бул жерден түзүү:"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Сырсөздү каякка сактайсыз:"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Аккаунтка кирүү маалыматын каякка сактайсыз:"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Мүмкүндүк алуу ачкычы башка түзмөктө түзүлсүнбү?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> бардык аккаунттарга кирүү үчүн колдонулсунбу?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Сырсөздөрүңүздү жана ачкычтарыңызды Сырсөздөрдү башкаргычка сактап коюп, каалаган убакта колдоно берсеңиз болот."</string> <string name="set_as_default" msgid="4415328591568654603">"Демейки катары коюу"</string> <string name="use_once" msgid="9027366575315399714">"Бир жолу колдонуу"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> сырсөз, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> мүмкүндүк алуу ачкычы"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> сырсөз"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> мүмкүндүк алуу ачкычы"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Мүмкүндүк алуу ачкычы"</string> <string name="another_device" msgid="5147276802037801217">"Башка түзмөк"</string> <string name="other_password_manager" msgid="565790221427004141">"Башка сырсөздөрдү башкаргычтар"</string> <string name="close_sheet" msgid="1393792015338908262">"Баракты жабуу"</string> diff --git a/packages/CredentialManager/res/values-lo/strings.xml b/packages/CredentialManager/res/values-lo/strings.xml index 215262bc4943..7429389fac0a 100644 --- a/packages/CredentialManager/res/values-lo/strings.xml +++ b/packages/CredentialManager/res/values-lo/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"ຕົວຈັດການຂໍ້ມູນການເຂົ້າສູ່ລະບົບ"</string> <string name="string_cancel" msgid="6369133483981306063">"ຍົກເລີກ"</string> <string name="string_continue" msgid="1346732695941131882">"ສືບຕໍ່"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"ສ້າງໃນບ່ອນອື່ນ"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"ບັນທຶກໃສ່ບ່ອນອື່ນ"</string> <string name="string_use_another_device" msgid="8754514926121520445">"ໃຊ້ອຸປະກອນອື່ນ"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"ບັນທຶກໃສ່ອຸປະກອນອື່ນ"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"ວິທີງ່າຍໆໃນການເຂົ້າສູ່ລະບົບຢ່າງປອດໄພ"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"ໃຊ້ລາຍນິ້ວມື, ໃບໜ້າ ຫຼື ລັອກໜ້າຈໍຂອງທ່ານເພື່ອເຂົ້າສູ່ລະບົບດ້ວຍກະແຈຜ່ານທີ່ບໍ່ຊ້ຳກັນເພື່ອບໍ່ໃຫ້ລືມ ຫຼື ຖືກລັກໄດ້. ສຶກສາເພີ່ມເຕີມ"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"ເລືອກບ່ອນທີ່ຈະ <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"ເລືອກບ່ອນທີ່ຈະ <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"ສ້າງກະແຈຜ່ານຂອງທ່ານ"</string> <string name="save_your_password" msgid="6597736507991704307">"ບັນທຶກລະຫັດຜ່ານຂອງທ່ານ"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"ບັນທຶກຂໍ້ມູນການເຂົ້າສູ່ລະບົບຂອງທ່ານ"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"ຕັ້ງຄ່າເລີ່ມຕົ້ນຂອງຕົວຈັດການລະຫັດຜ່ານເພື່ອບັນທຶກລະຫັດຜ່ານ ແລະ ກະແຈຜ່ານຂອງທ່ານ ແລະ ເຂົ້າສູ່ລະບົບໄດ້ໄວຂຶ້ນໃນເທື່ອຕໍ່ໄປ."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"ສ້າງກະແຈຜ່ານໃນ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ບໍ?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"ບັນທຶກລະຫັດຜ່ານຂອງທ່ານໃສ່ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ບໍ?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"ບັນທຶກຂໍ້ມູນການເຂົ້າສູ່ລະບົບຂອງທ່ານໃສ່ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ບໍ?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"ກະແຈຜ່ານ"</string> <string name="password" msgid="6738570945182936667">"ລະຫັດຜ່ານ"</string> <string name="sign_ins" msgid="4710739369149469208">"ການເຂົ້າສູ່ລະບົບ"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"ສ້າງກະແຈຜ່ານໃນ"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"ບັນທຶກລະຫັດຜ່ານໃສ່"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"ບັນທຶກການເຂົ້າສູ່ລະບົບໃສ່"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"ສ້າງກະແຈຜ່ານໃນອຸປະກອນອື່ນບໍ?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"ໃຊ້ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ສຳລັບການເຂົ້າສູ່ລະບົບທັງໝົດຂອງທ່ານບໍ?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"ຕົວຈັດການລະຫັດຜ່ານນີ້ຈະຈັດເກັບລະຫັດຜ່ານ ແລະ ກະແຈຜ່ານຂອງທ່ານໄວ້ເພື່ອຊ່ວຍໃຫ້ທ່ານເຂົ້າສູ່ລະບົບໄດ້ໂດຍງ່າຍ."</string> <string name="set_as_default" msgid="4415328591568654603">"ຕັ້ງເປັນຄ່າເລີ່ມຕົ້ນ"</string> <string name="use_once" msgid="9027366575315399714">"ໃຊ້ເທື່ອດຽວ"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> ລະຫັດຜ່ານ, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> ກະແຈຜ່ານ"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> ລະຫັດຜ່ານ"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> ກະແຈຜ່ານ"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"ກະແຈຜ່ານ"</string> <string name="another_device" msgid="5147276802037801217">"ອຸປະກອນອື່ນ"</string> <string name="other_password_manager" msgid="565790221427004141">"ຕົວຈັດການລະຫັດຜ່ານອື່ນໆ"</string> <string name="close_sheet" msgid="1393792015338908262">"ປິດຊີດ"</string> diff --git a/packages/CredentialManager/res/values-lt/strings.xml b/packages/CredentialManager/res/values-lt/strings.xml index 6125fe3f2b7b..aa5d97a6e87b 100644 --- a/packages/CredentialManager/res/values-lt/strings.xml +++ b/packages/CredentialManager/res/values-lt/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Išsaugoti kitoje vietoje"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Naudoti kitą įrenginį"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Išsaugoti kitame įrenginyje"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Paprastas saugaus prisijungimo metodas"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Naudodami piršto atspaudą, veidą ar ekrano užraktą prisijunkite su unikaliu „passkey“, kurio neįmanoma pamiršti ar pavogti. Sužinokite daugiau"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Pasirinkite, kur <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Pasirinkite, kur <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"kurkite slaptažodžius"</string> <string name="save_your_password" msgid="6597736507991704307">"išsaugoti slaptažodį"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"išsaugoti prisijungimo informaciją"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Nustatykite numatytąją slaptažodžių tvarkyklę, kad išsaugotumėte slaptažodžius ir kitą kartą galėtumėte sparčiau prisijungti."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Sukurti „passkey“ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Išsaugoti slaptažodį <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Išsaugoti prisijungimo informaciją <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"„passkey“"</string> <string name="password" msgid="6738570945182936667">"slaptažodis"</string> <string name="sign_ins" msgid="4710739369149469208">"prisijungimo informacija"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Slaptažodžio kūrimas"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Išsaugoti slaptažodį"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Išsaugoti prisijungimo informaciją"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Sukurti slaptažodį kitame įrenginyje?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Naudoti <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> visada prisijungiant?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Šioje slaptažodžių tvarkyklėje bus saugomi jūsų slaptažodžiai, kad galėtumėte lengvai prisijungti."</string> <string name="set_as_default" msgid="4415328591568654603">"Nustatyti kaip numatytąjį"</string> <string name="use_once" msgid="9027366575315399714">"Naudoti vieną kartą"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"slaptažodžių: <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>, „passkey“: <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g>"</string> diff --git a/packages/CredentialManager/res/values-lv/strings.xml b/packages/CredentialManager/res/values-lv/strings.xml index 43c036fde4bb..06446ab91b85 100644 --- a/packages/CredentialManager/res/values-lv/strings.xml +++ b/packages/CredentialManager/res/values-lv/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Saglabāt citur"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Izmantot citu ierīci"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Saglabāt citā ierīcē"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Vienkāršs veids, kā droši pierakstīties"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Izmantojiet pirksta nospiedumu, autorizāciju pēc sejas vai ekrāna bloķēšanu, lai pierakstītos ar unikālu piekļuves atslēgu, ko nevar aizmirst vai nozagt. Uzziniet vairāk."</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Izvēlieties, kur: <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Izvēlieties, kur: <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"veidot piekļuves atslēgas"</string> <string name="save_your_password" msgid="6597736507991704307">"saglabāt paroli"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"saglabāt pierakstīšanās informāciju"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Iestatiet noklusējuma paroļu pārvaldnieku, lai saglabātu paroles un piekļuves atslēgas un nākamajā reizē pierakstītos ātrāk."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Vai izveidot piekļuves atslēgu šeit: <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Vai saglabāt paroli šeit: <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Vai saglabāt pierakstīšanās informāciju šeit: <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"piekļuves atslēga"</string> <string name="password" msgid="6738570945182936667">"parole"</string> <string name="sign_ins" msgid="4710739369149469208">"pierakstīšanās informācija"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Izveidot piekļuves atslēgu šeit:"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Saglabāt paroli šeit:"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Saglabāt pierakstīšanās informāciju šeit:"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Vai izveidot piekļuves atslēgu citā ierīcē?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Vai vienmēr izmantot <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>, lai pierakstītos?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Šis paroļu pārvaldnieks glabās jūsu paroles un piekļuves atslēgas, lai atvieglotu pierakstīšanos."</string> <string name="set_as_default" msgid="4415328591568654603">"Iestatīt kā noklusējumu"</string> <string name="use_once" msgid="9027366575315399714">"Izmantot vienreiz"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> paroles, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> piekļuves atslēgas"</string> diff --git a/packages/CredentialManager/res/values-mk/strings.xml b/packages/CredentialManager/res/values-mk/strings.xml index 059f04207958..8093d7444b49 100644 --- a/packages/CredentialManager/res/values-mk/strings.xml +++ b/packages/CredentialManager/res/values-mk/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Зачувајте на друго место"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Употребете друг уред"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Зачувајте на друг уред"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Едноставен начин за безбедно најавување"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Користете го отпечатокот, заклучувањето со лик или заклучувањето екран за да се најавите со единствен криптографски клуч што не може да се заборави или украде. Дознајте повеќе"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Изберете каде да <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Изберете каде да <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"создајте криптографски клучеви"</string> <string name="save_your_password" msgid="6597736507991704307">"се зачува лозинката"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"се зачуваат податоците за најавување"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Поставете стандарден управник со лозинки за да ги складира вашите лозинки и криптографски клучеви и најавете се побрзо следниот пат."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Да се создаде криптографски клуч во <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Да се зачува вашата лозинка во <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Да се зачуваат вашите податоци за најавување во <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"криптографски клуч"</string> <string name="password" msgid="6738570945182936667">"лозинка"</string> <string name="sign_ins" msgid="4710739369149469208">"најавувања"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Создајте криптографски клуч во"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Зачувајте ја лозинката во"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Зачувајте го најавувањето во"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Да се создаде криптографски клуч во друг уред?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Да се користи <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> за сите ваши најавувања?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Овој управник со лозинки ќе ги складира вашите лозинки и криптографски клучеви за да ви помогне лесно да се најавите."</string> <string name="set_as_default" msgid="4415328591568654603">"Постави како стандардна опција"</string> <string name="use_once" msgid="9027366575315399714">"Употребете еднаш"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> лозинки, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> криптографски клучеви"</string> diff --git a/packages/CredentialManager/res/values-ml/strings.xml b/packages/CredentialManager/res/values-ml/strings.xml index e4f6d6972698..68a641984e4a 100644 --- a/packages/CredentialManager/res/values-ml/strings.xml +++ b/packages/CredentialManager/res/values-ml/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"മറ്റൊരു സ്ഥലത്തേക്ക് സംരക്ഷിക്കുക"</string> <string name="string_use_another_device" msgid="8754514926121520445">"മറ്റൊരു ഉപകരണം ഉപയോഗിക്കുക"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"മറ്റൊരു ഉപകരണത്തിലേക്ക് സംരക്ഷിക്കുക"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"സുരക്ഷിതമായി സൈൻ ഇൻ ചെയ്യാനുള്ള ലളിതമായ മാർഗ്ഗം"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"മറന്നുപോകാനും മോഷ്ടിക്കാനും സാധ്യതയില്ലാത്ത തനത് പാസ്കീ ഉപയോഗിച്ച് സൈൻ ഇൻ ചെയ്യാൻ നിങ്ങളുടെ ഫിംഗർപ്രിന്റോ മുഖമോ സ്ക്രീൻ ലോക്കോ ഉപയോഗിക്കുക. കൂടുതലറിയുക"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"എവിടെ <xliff:g id="CREATETYPES">%1$s</xliff:g> എന്ന് തിരഞ്ഞെടുക്കുക"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"എവിടെ <xliff:g id="CREATETYPES">%1$s</xliff:g> എന്ന് തിരഞ്ഞെടുക്കുക"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"നിങ്ങളുടെ പാസ്കീകൾ സൃഷ്ടിക്കുക"</string> <string name="save_your_password" msgid="6597736507991704307">"നിങ്ങളുടെ പാസ്വേഡ് സംരക്ഷിക്കുക"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"നിങ്ങളുടെ സൈൻ ഇൻ വിവരങ്ങൾ സംരക്ഷിക്കുക"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"നിങ്ങളുടെ പാസ്വേഡുകളും പാസ്കീകളും സംരക്ഷിക്കാനും അടുത്ത തവണ വേഗത്തിൽ സൈൻ ഇൻ ചെയ്യാനും ഒരു ഡിഫോൾട്ട് പാസ്വേഡ് മാനേജർ സജ്ജീകരിക്കുക."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> എന്നതിൽ ഒരു പാസ്കീ സൃഷ്ടിക്കണോ?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"പാസ്വേഡ് <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> എന്നതിലേക്ക് സംരക്ഷിക്കണോ?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"സൈൻ ഇൻ വിവരങ്ങൾ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> എന്നതിലേക്ക് സംരക്ഷിക്കണോ?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"പാസ്കീ"</string> <string name="password" msgid="6738570945182936667">"പാസ്വേഡ്"</string> <string name="sign_ins" msgid="4710739369149469208">"സൈൻ ഇന്നുകൾ"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"ഇനിപ്പറയുന്നതിൽ പാസ്കീ സൃഷ്ടിക്കുക"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"പാസ്വേഡ് ഇനിപ്പറയുന്നതിൽ സംരക്ഷിക്കുക"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"ഇനിപ്പറയുന്നതിലേക്ക് സൈൻ ഇൻ സംരക്ഷിക്കുക"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"മറ്റൊരു ഉപകരണത്തിൽ പാസ്കീ സൃഷ്ടിക്കണോ?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"നിങ്ങളുടെ എല്ലാ സൈൻ ഇന്നുകൾക്കും <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ഉപയോഗിക്കണോ?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"എളുപ്പത്തിൽ സൈൻ ഇൻ ചെയ്യാൻ സഹായിക്കുന്നതിന് ഈ പാസ്വേഡ് മാനേജർ നിങ്ങളുടെ പാസ്വേഡുകളും പാസ്കീകളും സംഭരിക്കും."</string> <string name="set_as_default" msgid="4415328591568654603">"ഡിഫോൾട്ടായി സജ്ജീകരിക്കുക"</string> <string name="use_once" msgid="9027366575315399714">"ഒരു തവണ ഉപയോഗിക്കുക"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> പാസ്വേഡുകൾ, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> പാസ്കീകൾ"</string> diff --git a/packages/CredentialManager/res/values-mn/strings.xml b/packages/CredentialManager/res/values-mn/strings.xml index 3f8d4caafafe..40ef5e55fffa 100644 --- a/packages/CredentialManager/res/values-mn/strings.xml +++ b/packages/CredentialManager/res/values-mn/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Өөр газар хадгалах"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Өөр төхөөрөмж ашиглах"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Өөр төхөөрөмжид хадгалах"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Аюулгүй нэвтрэх энгийн арга"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Мартах эсвэл хулгайд алдах боломжгүй өвөрмөц passkey-н хамт нэвтрэх хурууны хээ, царай эсвэл дэлгэцийн түгжээгээ ашиглана уу. Нэмэлт мэдээлэл авах"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Хаана <xliff:g id="CREATETYPES">%1$s</xliff:g>-г сонгоно уу"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Хаана <xliff:g id="CREATETYPES">%1$s</xliff:g>-г сонгоно уу"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"passkey-үүдээ үүсгэнэ үү"</string> <string name="save_your_password" msgid="6597736507991704307">"нууц үгээ хадгалах"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"нэвтрэх мэдээллээ хадгалах"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Нууц үгнүүд болон passkey-г хадгалах болон дараагийн удаа илүү хурдан нэвтрэхийн тулд өгөгдмөл нууц үгний менежерийг тохируулна уу"</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>-д passkey үүсгэх үү?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Нууц үгээ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>-д хадгалах уу?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Нэвтрэх мэдээллээ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>-д хадгалах уу?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"passkey"</string> <string name="password" msgid="6738570945182936667">"нууц үг"</string> <string name="sign_ins" msgid="4710739369149469208">"нэвтрэлт"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Дараахад passkey үүсгэх"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Нууц үгийг дараахад хадгалах"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Нэвтрэх мэдээллийг дараахад хадгалах"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Өөр төхөөрөмжид passkey үүсгэх үү?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>-г бүх нэвтрэлтдээ ашиглах уу?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Танд хялбархан нэвтрэхэд туслахын тулд энэ нууц үгний менежер таны нууц үг болон passkey-г хадгална."</string> <string name="set_as_default" msgid="4415328591568654603">"Өгөгдмөлөөр тохируулах"</string> <string name="use_once" msgid="9027366575315399714">"Нэг удаа ашиглах"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> нууц үг, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> passkey"</string> diff --git a/packages/CredentialManager/res/values-mr/strings.xml b/packages/CredentialManager/res/values-mr/strings.xml index aa6f2537842a..60c969d9832e 100644 --- a/packages/CredentialManager/res/values-mr/strings.xml +++ b/packages/CredentialManager/res/values-mr/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"क्रेडेंशियल व्यवस्थापक"</string> <string name="string_cancel" msgid="6369133483981306063">"रद्द करा"</string> <string name="string_continue" msgid="1346732695941131882">"पुढे सुरू ठेवा"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"दुसऱ्या ठिकाणी तयार करा"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"दुसऱ्या ठिकाणी सेव्ह करा"</string> <string name="string_use_another_device" msgid="8754514926121520445">"दुसरे डिव्हाइस वापरा"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"दुसऱ्या डिव्हाइसवर सेव्ह करा"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"सुरक्षितपणे साइन इन करण्याचा सोपा मार्ग"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"युनिक पासकीसह साइन इन करण्यासाठी तुमचे फिंगरप्रिंट, फेस किंवा स्क्रीन लॉक वापरा, जे विसरता येणार नाही किंवा चोरीला जाणार नाही. अधिक जाणून घ्या"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> कुठे करायचे ते निवडा"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> कुठे करायचे ते निवडा"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"तुमच्या पासकी तयार करा"</string> <string name="save_your_password" msgid="6597736507991704307">"तुमचा पासवर्ड सेव्ह करा"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"तुमची साइन-इन माहिती सेव्ह करा"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"तुमचे पासवर्ड आणि पासकी सेव्ह करण्यासाठी डीफॉल्ट पासवर्ड मॅनेजर सेट करा व पुढच्या वेळी आणखी जलद साइन इन करा."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> मध्ये पासकी तयार करायची का?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"तुमचा पासवर्ड <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> वर सेव्ह करायचा का?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"तुमची साइन-इन माहिती <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> वर सेव्ह करायची का?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"पासकी"</string> <string name="password" msgid="6738570945182936667">"पासवर्ड"</string> <string name="sign_ins" msgid="4710739369149469208">"साइन-इन"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"यामध्ये पासकी तयार करा"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"यावर पासवर्ड सेव्ह करा"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"यावर साइन-इन सेव्ह करा"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"दुसऱ्या डिव्हाइसमध्ये पासकी तयार करायची आहे का?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"तुमच्या सर्व साइन-इन साठी <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>वापरायचे का?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"तुम्हाला सहजरीत्या साइन इन करण्यात मदत करण्यासाठी हा पासवर्ड व्यवस्थापक तुमचे पासवर्ड आणि पासकी स्टोअर करेल."</string> <string name="set_as_default" msgid="4415328591568654603">"डिफॉल्ट म्हणून सेट करा"</string> <string name="use_once" msgid="9027366575315399714">"एकदा वापरा"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> पासवर्ड, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> पासकी"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> पासवर्ड"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> पासकी"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"पासकी"</string> <string name="another_device" msgid="5147276802037801217">"इतर डिव्हाइस"</string> <string name="other_password_manager" msgid="565790221427004141">"इतर पासवर्ड व्यवस्थापक"</string> <string name="close_sheet" msgid="1393792015338908262">"शीट बंद करा"</string> diff --git a/packages/CredentialManager/res/values-ms/strings.xml b/packages/CredentialManager/res/values-ms/strings.xml index d5f8c0e59bca..a590e9598d74 100644 --- a/packages/CredentialManager/res/values-ms/strings.xml +++ b/packages/CredentialManager/res/values-ms/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Simpan di tempat lain"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Gunakan peranti lain"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Simpan kepada peranti lain"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Cara mudah untuk log masuk dengan selamat"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Gunakan cap jari, wajah atau kunci skrin anda untuk log masuk menggunakan kunci laluan unik yang tidak boleh dilupakan atau dicuri. Ketahui lebih lanjut"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Pilih tempat untuk <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Pilih tempat untuk <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"buat kunci laluan anda"</string> <string name="save_your_password" msgid="6597736507991704307">"simpan kata laluan anda"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"simpan maklumat log masuk anda"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Tetapkan pengurus kata laluan lalai untuk menyimpan kata laluan dan kunci laluan dan log masuk dengan lebih pantas pada masa akan datang."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Buat kunci laluan dalam <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Simpan kata laluan anda pada <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Simpan maklumat log masuk anda pada <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"kunci laluan"</string> <string name="password" msgid="6738570945182936667">"kata laluan"</string> <string name="sign_ins" msgid="4710739369149469208">"log masuk"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Buat kunci laluan dalam"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Simpan kata laluan pada"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Simpan maklumat log masuk pada"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Buat kunci laluan dalam peranti lain?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Gunakan <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> untuk semua log masuk anda?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Pengurus kata laluan ini akan menyimpan kata laluan dan kunci laluan anda untuk membantu anda log masuk dengan mudah."</string> <string name="set_as_default" msgid="4415328591568654603">"Tetapkan sebagai lalai"</string> <string name="use_once" msgid="9027366575315399714">"Gunakan sekali"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"Kata laluan <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>, kunci laluan <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g>"</string> diff --git a/packages/CredentialManager/res/values-my/strings.xml b/packages/CredentialManager/res/values-my/strings.xml index eda2f741eda7..c7c88a7f60cf 100644 --- a/packages/CredentialManager/res/values-my/strings.xml +++ b/packages/CredentialManager/res/values-my/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"အထောက်အထားမန်နေဂျာ"</string> <string name="string_cancel" msgid="6369133483981306063">"မလုပ်တော့"</string> <string name="string_continue" msgid="1346732695941131882">"ရှေ့ဆက်ရန်"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"နောက်တစ်နေရာတွင် ပြုလုပ်ရန်"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"နောက်တစ်နေရာတွင် သိမ်းရန်"</string> <string name="string_use_another_device" msgid="8754514926121520445">"စက်နောက်တစ်ခု သုံးရန်"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"စက်နောက်တစ်ခုတွင် သိမ်းရန်"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"လုံခြုံစွာလက်မှတ်ထိုးဝင်ရန် ရိုးရှင်းသောနည်း"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"မေ့မသွား (သို့) ခိုးမသွားနိုင်သော သီးခြားလျှို့ဝှက်ကီးဖြင့် လက်မှတ်ထိုးဝင်ရန် သင့်လက်ဗွေ၊ မျက်နှာ (သို့) ဖန်သားပြင်လော့ခ် သုံးနိုင်သည်။ ပိုမိုလေ့လာရန်"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> ရန် နေရာရွေးပါ"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> ရန် နေရာရွေးပါ"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"သင့်လျှို့ဝှက်ကီး ပြုလုပ်ခြင်း"</string> <string name="save_your_password" msgid="6597736507991704307">"သင့်စကားဝှက် သိမ်းရန်"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"သင်၏ လက်မှတ်ထိုးဝင်သည့်အချက်အလက်ကို သိမ်းရန်"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"သင့်စကားဝှက်၊ လျှို့ဝှက်ကီးများ သိမ်းဆည်းရန်နှင့် နောက်တစ်ကြိမ်တွင် မြန်ဆန်စွာ လက်မှတ်ထိုးဝင်ရောက်ရန် မူရင်းစကားဝှက်မန်နေဂျာကို သတ်မှတ်ပါ။"</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> တွင် လျှို့ဝှက်ကီး ပြုလုပ်မလား။"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"သင့်စကားဝှက်ကို <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> တွင် သိမ်းမလား။"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"သင်၏ လက်မှတ်ထိုးဝင်သည့်အချက်အလက်ကို <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> တွင် သိမ်းမလား။"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"လျှို့ဝှက်ကီး"</string> <string name="password" msgid="6738570945182936667">"စကားဝှက်"</string> <string name="sign_ins" msgid="4710739369149469208">"လက်မှတ်ထိုးဝင်မှုများ"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"ဤနေရာတွင် လျှို့ဝှက်ကီးပြုလုပ်ရန်"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"စကားဝှက်ကို ဤနေရာတွင် သိမ်းရန်"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"လက်မှတ်ထိုးဝင်မှုကို ဤနေရာတွင် သိမ်းရန်"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"အခြားစက်တွင် လျှို့ဝှက်ကီးပြုလုပ်မလား။"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"သင်၏လက်မှတ်ထိုးဝင်မှု အားလုံးအတွက် <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> သုံးမလား။"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"သင်အလွယ်တကူ လက်မှတ်ထိုးဝင်နိုင်ရန် ဤစကားဝှက်မန်နေဂျာက စကားဝှက်နှင့် လျှို့ဝှက်ကီးများကို သိမ်းပါမည်။"</string> <string name="set_as_default" msgid="4415328591568654603">"မူရင်းအဖြစ် သတ်မှတ်ရန်"</string> <string name="use_once" msgid="9027366575315399714">"တစ်ကြိမ်သုံးရန်"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"စကားဝှက် <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> ခု၊ လျှို့ဝှက်ကီး <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> ခု"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"စကားဝှက် <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> ခု"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"လျှို့ဝှက်ကီး <xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> ခု"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"လျှို့ဝှက်ကီး"</string> <string name="another_device" msgid="5147276802037801217">"စက်နောက်တစ်ခု"</string> <string name="other_password_manager" msgid="565790221427004141">"အခြားစကားဝှက်မန်နေဂျာများ"</string> <string name="close_sheet" msgid="1393792015338908262">"စာမျက်နှာ ပိတ်ရန်"</string> diff --git a/packages/CredentialManager/res/values-nb/strings.xml b/packages/CredentialManager/res/values-nb/strings.xml index 82854b82e555..f113f7291b93 100644 --- a/packages/CredentialManager/res/values-nb/strings.xml +++ b/packages/CredentialManager/res/values-nb/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Legitimasjonslagring"</string> <string name="string_cancel" msgid="6369133483981306063">"Avbryt"</string> <string name="string_continue" msgid="1346732695941131882">"Fortsett"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Opprett på et annet sted"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Lagre på et annet sted"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Bruk en annen enhet"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Lagre på en annen enhet"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"En enkel og trygg påloggingsmåte"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Bruk fingeravtrykk, ansiktet eller en skjermlås til å logge på med en unik tilgangsnøkkel du verken kan glemme eller miste. Finn ut mer"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Velg hvor <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Velg hvor <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"opprette tilgangsnøklene dine"</string> <string name="save_your_password" msgid="6597736507991704307">"lagre passordet ditt"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"lagre påloggingsinformasjonen din"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Angi et standardverktøy for passordlagring for å lagre passordene og tilgangsnøklene dine og logge på raskere neste gang."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Vil du opprette en tilgangsnøkkel i <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Vil du lagre passordet i <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Vil du lagre påloggingsinformasjonen i <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"tilgangsnøkkel"</string> <string name="password" msgid="6738570945182936667">"passord"</string> <string name="sign_ins" msgid="4710739369149469208">"pålogginger"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Opprett en tilgangsnøkkel på"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Lagre passordet i"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Lagre påloggingen i"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Vil du opprette en tilgangsnøkkel på en annen enhet?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Vil du bruke <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> for alle pålogginger?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Dette verktøyet for passordlagring lagrer passord og tilgangsnøkler, så det blir lett å logge på."</string> <string name="set_as_default" msgid="4415328591568654603">"Angi som standard"</string> <string name="use_once" msgid="9027366575315399714">"Bruk én gang"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> passord, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> tilgangsnøkler"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> passord"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> tilgangsnøkler"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Tilgangsnøkkel"</string> <string name="another_device" msgid="5147276802037801217">"En annen enhet"</string> <string name="other_password_manager" msgid="565790221427004141">"Andre løsninger for passordlagring"</string> <string name="close_sheet" msgid="1393792015338908262">"Lukk arket"</string> diff --git a/packages/CredentialManager/res/values-ne/strings.xml b/packages/CredentialManager/res/values-ne/strings.xml index 23f4f430a799..cc8a38afb8bf 100644 --- a/packages/CredentialManager/res/values-ne/strings.xml +++ b/packages/CredentialManager/res/values-ne/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"क्रिडेन्सियल म्यानेजर"</string> <string name="string_cancel" msgid="6369133483981306063">"रद्द गर्नुहोस्"</string> <string name="string_continue" msgid="1346732695941131882">"जारी राख्नुहोस्"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"अर्को ठाउँमा बनाउनुहोस्"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"अर्को ठाउँमा सेभ गर्नुहोस्"</string> <string name="string_use_another_device" msgid="8754514926121520445">"अर्को डिभाइस प्रयोग गर्नुहोस्"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"अर्को डिभाइसमा सेभ गर्नुहोस्"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"सुरक्षित तरिकाले साइन इन गर्ने सरल तरिका"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"नभुलिने वा चोरी नहुने खालको अद्वितीय पासकीका साथै आफ्ना फिंगरप्रिन्ट, अनुहार वा स्क्रिन लक प्रयोग गरी साइन इन गर्नुहोस्। थप जान्नुहोस्"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> सेभ गर्ने ठाउँ छनौट गर्नुहोस्"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> सेभ गर्ने ठाउँ छनौट गर्नुहोस्"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"आफ्ना पासकीहरू बाउनुहोस्"</string> <string name="save_your_password" msgid="6597736507991704307">"आफ्नो पासवर्ड सेभ गर्नुहोस्"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"आफ्नो साइन इनसम्बन्धी जानकारी सेभ गर्नुहोस्"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"आफ्ना पासवर्ड तथा पासकीहरू सेभ गर्न र अर्को पटक अझ छिटो साइन इन गर्न डिफल्ट पासवर्ड म्यानेजर सेट गर्नुहोस्।"</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> मा पासकी बनाउने हो?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"तपाईंको पासवर्ड <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> मा सेभ गर्ने हो?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"तपाईंको साइन इनसम्बन्धी जानकारी <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> मा सेभ गर्ने हो?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"पासकी"</string> <string name="password" msgid="6738570945182936667">"पासवर्ड"</string> <string name="sign_ins" msgid="4710739369149469208">"साइन इनसम्बन्धी जानकारी"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"यसमा पासकी बनाउनुहोस्:"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"यसमा पासवर्ड सेभ गर्नुहोस्:"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"यसमा साइन इनसम्बन्धी जानकारी सेभ गर्नुहोस्:"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"अर्को डिभाइसमा पासकी बनाउने हो?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"तपाईंले साइन इन गर्ने सबै डिभाइसहरूमा <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> प्रयोग गर्ने हो?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"तपाईं सजिलै साइन इन गर्न सक्नुहोस् भन्नाका लागि यो पासवर्ड म्यानेजरले तपाईंका पासवर्ड तथा पासकीहरू सेभ गर्ने छ।"</string> <string name="set_as_default" msgid="4415328591568654603">"डिफल्ट जानकारीका रूपमा सेट गर्नुहोस्"</string> <string name="use_once" msgid="9027366575315399714">"एक पटक प्रयोग गर्नुहोस्"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> वटा पासवर्ड, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> वटा पासकी"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> वटा पासवर्ड"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> वटा पासकी"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"पासकी"</string> <string name="another_device" msgid="5147276802037801217">"अर्को डिभाइस"</string> <string name="other_password_manager" msgid="565790221427004141">"अन्य पासवर्ड म्यानेजरहरू"</string> <string name="close_sheet" msgid="1393792015338908262">"पाना बन्द गर्नुहोस्"</string> diff --git a/packages/CredentialManager/res/values-nl/strings.xml b/packages/CredentialManager/res/values-nl/strings.xml index c91a318e2073..72dff7370dc6 100644 --- a/packages/CredentialManager/res/values-nl/strings.xml +++ b/packages/CredentialManager/res/values-nl/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Op een andere locatie opslaan"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Een ander apparaat gebruiken"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Opslaan op een ander apparaat"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Een makkelijke manier om beveiligd in te loggen"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Gebruik je vingerafdruk, gezichtsvergrendeling of schermvergrendeling om in te loggen met een unieke toegangssleutel die je niet kunt vergeten en die anderen niet kunnen stelen. Meer informatie"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Een locatie kiezen voor <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Een locatie kiezen voor <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"je toegangssleutels maken"</string> <string name="save_your_password" msgid="6597736507991704307">"je wachtwoord opslaan"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"je inloggegevens opslaan"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Stel een standaard wachtwoordmanager in om je wachtwoorden en toegangssleutels op te slaan zodat je de volgende keer sneller kunt inloggen."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Een toegangssleutel maken in <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Je wachtwoord opslaan in <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Je inloggegevens opslaan in <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"toegangssleutel"</string> <string name="password" msgid="6738570945182936667">"wachtwoord"</string> <string name="sign_ins" msgid="4710739369149469208">"inloggegevens"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Toegangssleutel maken in"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Wachtwoord opslaan in"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Inloggegevens opslaan in"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Toegangssleutel maken op een ander apparaat?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> elke keer gebruiken als je inlogt?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Deze wachtwoordmanager slaat je wachtwoorden en toegangssleutels op zodat je makkelijk kunt inloggen."</string> <string name="set_as_default" msgid="4415328591568654603">"Instellen als standaard"</string> <string name="use_once" msgid="9027366575315399714">"Eén keer gebruiken"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> wachtwoorden, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> toegangssleutels"</string> diff --git a/packages/CredentialManager/res/values-or/strings.xml b/packages/CredentialManager/res/values-or/strings.xml index 838ddfe64a50..a1bbf1c2e9fb 100644 --- a/packages/CredentialManager/res/values-or/strings.xml +++ b/packages/CredentialManager/res/values-or/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"କ୍ରେଡେନସିଆଲ ମେନେଜର"</string> <string name="string_cancel" msgid="6369133483981306063">"ବାତିଲ କରନ୍ତୁ"</string> <string name="string_continue" msgid="1346732695941131882">"ଜାରି ରଖନ୍ତୁ"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"ଅନ୍ୟ ଏକ ସ୍ଥାନରେ ତିଆରି କରନ୍ତୁ"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"ଅନ୍ୟ ଏକ ସ୍ଥାନରେ ସେଭ କରନ୍ତୁ"</string> <string name="string_use_another_device" msgid="8754514926121520445">"ଅନ୍ୟ ଏହି ଡିଭାଇସ ବ୍ୟବହାର କରନ୍ତୁ"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"ଅନ୍ୟ ଏକ ଡିଭାଇସରେ ସେଭ କରନ୍ତୁ"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"ସୁରକ୍ଷିତ ଭାବେ ସାଇନ ଇନ କରିବାର ଏକ ସରଳ ଉପାୟ"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"ଏକ ସ୍ୱତନ୍ତ୍ର ପାସକୀ ମାଧ୍ୟମରେ ସାଇନ ଇନ କରିବା ପାଇଁ ଆପଣଙ୍କ ଟିପଚିହ୍ନ, ଫେସ କିମ୍ବା ସ୍କ୍ରିନ ଲକ ବ୍ୟବହାର କରନ୍ତୁ ଯାହାକୁ ଭୁଲି ପାରିବେ ନାହିଁ କିମ୍ବା ଚୋରି ହୋଇପାରିବ ନାହିଁ। ଅଧିକ ଜାଣନ୍ତୁ"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"କେଉଁଠି <xliff:g id="CREATETYPES">%1$s</xliff:g> କରିବେ, ତାହା ବାଛନ୍ତୁ"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"କେଉଁଠି <xliff:g id="CREATETYPES">%1$s</xliff:g> କରିବେ, ତାହା ବାଛନ୍ତୁ"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"ଆପଣଙ୍କ ପାସକୀଗୁଡ଼ିକ ତିଆରି କରନ୍ତୁ"</string> <string name="save_your_password" msgid="6597736507991704307">"ଆପଣଙ୍କ ପାସୱାର୍ଡ ସେଭ କରନ୍ତୁ"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"ଆପଣଙ୍କ ସାଇନ-ଇନ ସୂଚନା ସେଭ କରନ୍ତୁ"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"ଆପଣଙ୍କ ପାସୱାର୍ଡ ଓ ପାସକୀଗୁଡ଼ିକୁ ସେଭ କରିବା ପାଇଁ ଏକ ଡିଫଲ୍ଟ Password Manager ସେଟ କରନ୍ତୁ ଏବଂ ପରବର୍ତ୍ତୀ ଥର ଶୀଘ୍ର ସାଇନ ଇନ କରନ୍ତୁ।"</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>ରେ ଏକ ପାସକୀ ତିଆରି କରିବେ?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"ଆପଣଙ୍କ ପାସୱାର୍ଡକୁ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>ରେ ସେଭ କରିବେ?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"ଆପଣଙ୍କ ସାଇନ-ଇନ ସୂଚନାକୁ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>ରେ ସେଭ କରିବେ?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"ପାସକୀ"</string> <string name="password" msgid="6738570945182936667">"ପାସୱାର୍ଡ"</string> <string name="sign_ins" msgid="4710739369149469208">"ସାଇନ-ଇନ"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"ଏଥିରେ ପାସକୀ ତିଆରି କରନ୍ତୁ"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"ଏଥିରେ ପାସୱାର୍ଡ ସେଭ କରନ୍ତୁ"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"ଏଥିରେ ସାଇନ-ଇନ ସେଭ କରନ୍ତୁ"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"ଅନ୍ୟ ଏକ ଡିଭାଇସରେ ପାସକୀ ତିଆରି କରିବେ?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"ଆପଣଙ୍କ ସମସ୍ତ ସାଇନ-ଇନ ପାଇଁ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ବ୍ୟବହାର କରିବେ?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"ଏହି Password Manager ସହଜରେ ସାଇନ ଇନ କରିବାରେ ଆପଣଙ୍କୁ ସାହାଯ୍ୟ କରିବା ପାଇଁ ଆପଣଙ୍କ ପାସୱାର୍ଡ ଏବଂ ପାସକୀଗୁଡ଼ିକୁ ଷ୍ଟୋର କରିବ।"</string> <string name="set_as_default" msgid="4415328591568654603">"ଡିଫଲ୍ଟ ଭାବେ ସେଟ କରନ୍ତୁ"</string> <string name="use_once" msgid="9027366575315399714">"ଥରେ ବ୍ୟବହାର କରନ୍ତୁ"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>ଟି ପାସୱାର୍ଡ, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g>ଟି ପାସକୀ"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>ଟି ପାସୱାର୍ଡ"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g>ଟି ପାସକୀ"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"ପାସକୀ"</string> <string name="another_device" msgid="5147276802037801217">"ଅନ୍ୟ ଏକ ଡିଭାଇସ"</string> <string name="other_password_manager" msgid="565790221427004141">"ଅନ୍ୟ Password Manager"</string> <string name="close_sheet" msgid="1393792015338908262">"ସିଟ ବନ୍ଦ କରନ୍ତୁ"</string> diff --git a/packages/CredentialManager/res/values-pa/strings.xml b/packages/CredentialManager/res/values-pa/strings.xml index 74b2ab123ec0..36989c670bfe 100644 --- a/packages/CredentialManager/res/values-pa/strings.xml +++ b/packages/CredentialManager/res/values-pa/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"ਕ੍ਰੀਡੈਂਸ਼ੀਅਲ ਪ੍ਰਬੰਧਕ"</string> <string name="string_cancel" msgid="6369133483981306063">"ਰੱਦ ਕਰੋ"</string> <string name="string_continue" msgid="1346732695941131882">"ਜਾਰੀ ਰੱਖੋ"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"ਕਿਸੇ ਹੋਰ ਥਾਂ \'ਤੇ ਬਣਾਓ"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"ਕਿਸੇ ਹੋਰ ਥਾਂ \'ਤੇ ਰੱਖਿਅਤ ਕਰੋ"</string> <string name="string_use_another_device" msgid="8754514926121520445">"ਕੋਈ ਹੋਰ ਡੀਵਾਈਸ ਦੀ ਵਰਤੋਂ ਕਰੋ"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"ਕਿਸੇ ਹੋਰ ਡੀਵਾਈਸ \'ਤੇ ਰੱਖਿਅਤ ਕਰੋ"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"ਸੁਰੱਖਿਅਤ ਢੰਗ ਨਾਲ ਸਾਈਨ-ਇਨ ਕਰਨ ਦਾ ਆਸਾਨ ਤਰੀਕਾ"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"ਵਿਲੱਖਣ ਪਾਸਕੀ ਨਾਲ ਸਾਈਨ-ਇਨ ਕਰਨ ਵਾਸਤੇ ਆਪਣੇ ਫਿੰਗਰਪ੍ਰਿੰਟ, ਚਿਹਰੇ ਜਾਂ ਸਕ੍ਰੀਨ ਲਾਕ ਦੀ ਵਰਤੋਂ ਕਰੋ ਜਿਸਨੂੰ ਭੁੱਲਿਆ ਜਾਂ ਚੋਰੀ ਨਹੀਂ ਕੀਤਾ ਜਾ ਸਕਦਾ। ਹੋਰ ਜਾਣੋ"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> ਲਈ ਕੋਈ ਥਾਂ ਚੁਣੋ"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> ਲਈ ਕੋਈ ਥਾਂ ਚੁਣੋ"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"ਆਪਣੀਆਂ ਪਾਸਕੀਆਂ ਬਣਾਓ"</string> <string name="save_your_password" msgid="6597736507991704307">"ਆਪਣਾ ਪਾਸਵਰਡ ਰੱਖਿਅਤ ਕਰੋ"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"ਆਪਣੀ ਸਾਈਨ-ਇਨ ਜਾਣਕਾਰੀ ਰੱਖਿਅਤ ਕਰੋ"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"ਆਪਣੇ ਪਾਸਵਰਡਾਂ ਅਤੇ ਪਾਸਕੀਆਂ ਨੂੰ ਰੱਖਿਅਤ ਕਰਨ ਲਈ ਕੋਈ ਪੂਰਵ-ਨਿਰਧਾਰਿਤ ਪਾਸਵਰਡ ਪ੍ਰਬੰਧਕ ਸੈੱਟ ਕਰੋ ਅਤੇ ਅਗਲੀ ਵਾਰ ਤੇਜ਼ੀ ਨਾਲ ਸਾਈਨ-ਇਨ ਕਰੋ।"</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"ਕੀ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ਵਿੱਚ ਪਾਸਕੀ ਨੂੰ ਬਣਾਉਣਾ ਹੈ?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"ਕੀ ਆਪਣੇ ਪਾਸਵਰਡ ਨੂੰ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ਵਿੱਚ ਰੱਖਿਅਤ ਕਰਨਾ ਹੈ?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"ਕੀ ਆਪਣੀ ਸਾਈਨ-ਇਨ ਜਾਣਕਾਰੀ ਨੂੰ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ਵਿੱਚ ਰੱਖਿਅਤ ਕਰਨਾ ਹੈ?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"ਪਾਸਕੀ"</string> <string name="password" msgid="6738570945182936667">"ਪਾਸਵਰਡ"</string> <string name="sign_ins" msgid="4710739369149469208">"ਸਾਈਨ-ਇਨਾਂ ਦੀ ਜਾਣਕਾਰੀ"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"ਇਸ ਵਿੱਚ ਪਾਸਕੀ ਬਣਾਓ"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"ਇਸ \'ਤੇ ਪਾਸਵਰਡ ਰੱਖਿਅਤ ਕਰੋ"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"ਇਸ \'ਤੇ ਸਾਈਨ-ਇਨ ਜਾਣਕਾਰੀ ਰੱਖਿਅਤ ਕਰੋ"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"ਕੀ ਕਿਸੇ ਹੋਰ ਡੀਵਾਈਸ ਵਿੱਚ ਕੋਈ ਪਾਸਕੀ ਬਣਾਉਣੀ ਹੈ?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"ਕੀ ਆਪਣੇ ਸਾਰੇ ਸਾਈਨ-ਇਨਾਂ ਲਈ<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ਦੀ ਵਰਤੋਂ ਕਰਨੀ ਹੈ?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"ਇਹ ਪਾਸਵਰਡ ਪ੍ਰਬੰਧਕ ਤੁਹਾਡੀ ਆਸਾਨੀ ਨਾਲ ਸਾਈਨ-ਇਨ ਕਰਨ ਵਿੱਚ ਮਦਦ ਕਰਨ ਲਈ ਤੁਹਾਡੇ ਪਾਸਵਰਡਾਂ ਅਤੇ ਪਾਸਕੀਆਂ ਨੂੰ ਸਟੋਰ ਕਰੇਗਾ।"</string> <string name="set_as_default" msgid="4415328591568654603">"ਪੂਰਵ-ਨਿਰਧਾਰਿਤ ਵਜੋਂ ਸੈੱਟ ਕਰੋ"</string> <string name="use_once" msgid="9027366575315399714">"ਇੱਕ ਵਾਰ ਵਰਤੋ"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> ਪਾਸਵਰਡ, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> ਪਾਸਕੀਆਂ"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> ਪਾਸਵਰਡ"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> ਪਾਸਕੀਆਂ"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"ਪਾਸਕੀ"</string> <string name="another_device" msgid="5147276802037801217">"ਹੋਰ ਡੀਵਾਈਸ"</string> <string name="other_password_manager" msgid="565790221427004141">"ਹੋਰ ਪਾਸਵਰਡ ਪ੍ਰਬੰਧਕ"</string> <string name="close_sheet" msgid="1393792015338908262">"ਸ਼ੀਟ ਬੰਦ ਕਰੋ"</string> diff --git a/packages/CredentialManager/res/values-pl/strings.xml b/packages/CredentialManager/res/values-pl/strings.xml index af6bc9d22fa8..462ded06e825 100644 --- a/packages/CredentialManager/res/values-pl/strings.xml +++ b/packages/CredentialManager/res/values-pl/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Menedżer danych logowania"</string> <string name="string_cancel" msgid="6369133483981306063">"Anuluj"</string> <string name="string_continue" msgid="1346732695941131882">"Dalej"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Utwórz w innym miejscu"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Zapisz w innym miejscu"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Użyj innego urządzenia"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Zapisz na innym urządzeniu"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Prosty sposób na bezpieczne logowanie"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Używaj odcisku palca, rozpoznawania twarzy lub blokady ekranu, aby logować się z wykorzystaniem unikalnego klucza, którego nie można zapomnieć ani utracić w wyniku kradzieży. Więcej informacji"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Wybierz, gdzie chcesz <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Wybierz, gdzie chcesz <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"tworzyć klucze"</string> <string name="save_your_password" msgid="6597736507991704307">"zapisać hasło"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"zapisać dane logowania"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Ustaw domyślny menedżer haseł, aby zapisywać swoje hasła oraz klucze dostępu i aby logować się szybciej w przyszłości."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Utworzyć klucz w usłudze <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Zapisać hasło w usłudze <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Zapisać dane logowania w usłudze <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"klucz"</string> <string name="password" msgid="6738570945182936667">"hasło"</string> <string name="sign_ins" msgid="4710739369149469208">"dane logowania"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Utwórz klucz w usłudze"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Zapisz hasło w usłudze"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Zapisz dane logowania w usłudze"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Utworzyć klucz na innym urządzeniu?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Używać usługi <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> w przypadku wszystkich danych logowania?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Menedżer haseł będzie zapisywał Twoje hasła i klucze, aby ułatwić Ci logowanie."</string> <string name="set_as_default" msgid="4415328591568654603">"Ustaw jako domyślną"</string> <string name="use_once" msgid="9027366575315399714">"Użyj raz"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"Hasła: <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>, klucze: <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g>"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"Hasła: <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"Klucze: <xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g>"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Klucz"</string> <string name="another_device" msgid="5147276802037801217">"Inne urządzenie"</string> <string name="other_password_manager" msgid="565790221427004141">"Inne menedżery haseł"</string> <string name="close_sheet" msgid="1393792015338908262">"Zamknij arkusz"</string> diff --git a/packages/CredentialManager/res/values-pt-rBR/strings.xml b/packages/CredentialManager/res/values-pt-rBR/strings.xml index d950bb45366e..945adc2986ee 100644 --- a/packages/CredentialManager/res/values-pt-rBR/strings.xml +++ b/packages/CredentialManager/res/values-pt-rBR/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Salvar em outro lugar"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Usar outro dispositivo"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Salvar em outro dispositivo"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Uma maneira simples de fazer login com segurança"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Use a impressão digital, o reconhecimento facial ou um bloqueio de tela para fazer login com uma única chave de acesso que não pode ser esquecida ou perdida. Saiba mais"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Escolha onde <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Escolha onde <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"crie suas chaves de acesso"</string> <string name="save_your_password" msgid="6597736507991704307">"salvar sua senha"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"salvar suas informações de login"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Defina um gerenciador de senhas padrão para salvar suas senhas e chaves de acesso e fazer login mais rápido na próxima vez."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Criar uma chave de acesso em <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Salvar sua senha em <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Salvar suas informações de login em <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"chave de acesso"</string> <string name="password" msgid="6738570945182936667">"senha"</string> <string name="sign_ins" msgid="4710739369149469208">"logins"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Criar chave de acesso em"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Salvar senha em"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Salvar informações de login em"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Criar uma chave de acesso em outro dispositivo?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Usar <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> para todos os seus logins?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Este gerenciador de senhas vai armazenar suas senhas e chaves de acesso para facilitar o processo de login."</string> <string name="set_as_default" msgid="4415328591568654603">"Definir como padrão"</string> <string name="use_once" msgid="9027366575315399714">"Usar uma vez"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> senhas, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> chaves de acesso"</string> diff --git a/packages/CredentialManager/res/values-pt-rPT/strings.xml b/packages/CredentialManager/res/values-pt-rPT/strings.xml index c46143cbae51..93a7a5f22ad3 100644 --- a/packages/CredentialManager/res/values-pt-rPT/strings.xml +++ b/packages/CredentialManager/res/values-pt-rPT/strings.xml @@ -8,8 +8,14 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Guardar noutro lugar"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Usar outro dispositivo"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Guardar noutro dispositivo"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Uma forma simples de iniciar sessão em segurança"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Use a sua impressão digital, rosto ou bloqueio de ecrã para iniciar sessão com uma chave de acesso única que não pode ser esquecida nem perdida. Saiba mais"</string> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> <string name="choose_provider_title" msgid="7245243990139698508">"Escolha onde quer guardar <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> <string name="create_your_passkeys" msgid="8901224153607590596">"criar as suas chaves de acesso"</string> <string name="save_your_password" msgid="6597736507991704307">"guardar a sua palavra-passe"</string> diff --git a/packages/CredentialManager/res/values-pt/strings.xml b/packages/CredentialManager/res/values-pt/strings.xml index d950bb45366e..945adc2986ee 100644 --- a/packages/CredentialManager/res/values-pt/strings.xml +++ b/packages/CredentialManager/res/values-pt/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Salvar em outro lugar"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Usar outro dispositivo"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Salvar em outro dispositivo"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Uma maneira simples de fazer login com segurança"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Use a impressão digital, o reconhecimento facial ou um bloqueio de tela para fazer login com uma única chave de acesso que não pode ser esquecida ou perdida. Saiba mais"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Escolha onde <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Escolha onde <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"crie suas chaves de acesso"</string> <string name="save_your_password" msgid="6597736507991704307">"salvar sua senha"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"salvar suas informações de login"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Defina um gerenciador de senhas padrão para salvar suas senhas e chaves de acesso e fazer login mais rápido na próxima vez."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Criar uma chave de acesso em <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Salvar sua senha em <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Salvar suas informações de login em <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"chave de acesso"</string> <string name="password" msgid="6738570945182936667">"senha"</string> <string name="sign_ins" msgid="4710739369149469208">"logins"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Criar chave de acesso em"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Salvar senha em"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Salvar informações de login em"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Criar uma chave de acesso em outro dispositivo?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Usar <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> para todos os seus logins?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Este gerenciador de senhas vai armazenar suas senhas e chaves de acesso para facilitar o processo de login."</string> <string name="set_as_default" msgid="4415328591568654603">"Definir como padrão"</string> <string name="use_once" msgid="9027366575315399714">"Usar uma vez"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> senhas, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> chaves de acesso"</string> diff --git a/packages/CredentialManager/res/values-ro/strings.xml b/packages/CredentialManager/res/values-ro/strings.xml index 6947281390f0..da7ec1a98b6d 100644 --- a/packages/CredentialManager/res/values-ro/strings.xml +++ b/packages/CredentialManager/res/values-ro/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Manager de date de conectare"</string> <string name="string_cancel" msgid="6369133483981306063">"Anulează"</string> <string name="string_continue" msgid="1346732695941131882">"Continuă"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Creează în alt loc"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Salvează în alt loc"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Folosește alt dispozitiv"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Salvează pe alt dispozitiv"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Un mod simplu de a te conecta în siguranță"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Folosește-ți amprenta, fața sau blocarea ecranului ca să te conectezi cu o cheie de acces unică, pe care nu o poți uita și care nu poate fi furată. Află mai multe"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Alege unde <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Alege unde <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"creează cheile de acces"</string> <string name="save_your_password" msgid="6597736507991704307">"salvează parola"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"salvează informațiile de conectare"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Setează un manager de parole implicit pentru a salva parolele și cheile de acces și a te conecta mai rapid data viitoare."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Creezi o cheie de acces în <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Salvezi parola în <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Salvezi informațiile de conectare în <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"cheie de acces"</string> <string name="password" msgid="6738570945182936667">"parolă"</string> <string name="sign_ins" msgid="4710739369149469208">"date de conectare"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Creează o cheie de acces în"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Salvează parola în"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Salvează datele de conectare în"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Creezi o cheie de acces în alt dispozitiv?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Folosești <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> pentru toate conectările?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Managerul de parole îți va stoca parolele și cheile de acces, pentru a te ajuta să te conectezi cu ușurință."</string> <string name="set_as_default" msgid="4415328591568654603">"Setează ca prestabilite"</string> <string name="use_once" msgid="9027366575315399714">"Folosește o dată"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> parole, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> chei de acces"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> parole"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> chei de acces"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Cheie de acces"</string> <string name="another_device" msgid="5147276802037801217">"Alt dispozitiv"</string> <string name="other_password_manager" msgid="565790221427004141">"Alți manageri de parole"</string> <string name="close_sheet" msgid="1393792015338908262">"Închide foaia"</string> diff --git a/packages/CredentialManager/res/values-ru/strings.xml b/packages/CredentialManager/res/values-ru/strings.xml index dcc643eee7cd..7dc51a2d1a7a 100644 --- a/packages/CredentialManager/res/values-ru/strings.xml +++ b/packages/CredentialManager/res/values-ru/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Сохранить в другом месте"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Использовать другое устройство"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Сохранить на другом устройстве"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Простой и безопасный способ входа"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"С уникальным ключом доступа, который невозможно украсть или забыть, вы можете подтверждать свою личность по отпечатку пальца, с помощью фейсконтроля или блокировки экрана. Подробнее…"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Выберите, где <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Выберите, где <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"создать ключи доступа"</string> <string name="save_your_password" msgid="6597736507991704307">"сохранить пароль"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"сохранить данные для входа"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Задайте менеджер паролей по умолчанию, чтобы сохранять пароли и ключи доступа и быстро выполнять вход."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Создать ключ доступа в приложении \"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>\"?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Сохранить пароль в приложении \"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>\"?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Сохранить учетные данные в приложении \"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>\"?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"ключ доступа"</string> <string name="password" msgid="6738570945182936667">"пароль"</string> <string name="sign_ins" msgid="4710739369149469208">"входы"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Выберите, где создать ключ доступа"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Выберите, где сохранить пароль"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Выберите, где сохранить учетные данные"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Создать ключ доступа на другом устройстве?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Всегда входить с помощью приложения \"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>\"?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"В этом менеджере паролей можно сохранять учетные данные, например ключи доступа, чтобы потом использовать их."</string> <string name="set_as_default" msgid="4415328591568654603">"Использовать по умолчанию"</string> <string name="use_once" msgid="9027366575315399714">"Использовать один раз"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"Пароли (<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>) и ключи доступа (<xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g>)"</string> diff --git a/packages/CredentialManager/res/values-si/strings.xml b/packages/CredentialManager/res/values-si/strings.xml index bf885a987cba..fd94e5a3f9ea 100644 --- a/packages/CredentialManager/res/values-si/strings.xml +++ b/packages/CredentialManager/res/values-si/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"අක්තපත්ර කළමනාකරු"</string> <string name="string_cancel" msgid="6369133483981306063">"අවලංගු කරන්න"</string> <string name="string_continue" msgid="1346732695941131882">"ඉදිරියට යන්න"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"වෙනත් ස්ථානයක තනන්න"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"වෙනත් ස්ථානයකට සුරකින්න"</string> <string name="string_use_another_device" msgid="8754514926121520445">"වෙනත් උපාංගයක් භාවිතා කරන්න"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"වෙනත් උපාංගයකට සුරකින්න"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"සුරක්ෂිතව පුරනය වීමට සරල ක්රමයක්"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"අමතක කළ නොහැකි හෝ සොරකම් කළ නොහැකි අනන්ය මුරයතුරක් සමග පුරනය වීමට ඔබේ ඇඟිලි සලකුණ, මුහුණ හෝ තිර අගුල භාවිතා කරන්න. තව දැන ගන්න"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> කොතැනක ද යන්න තෝරා ගන්න"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> කොතැනක ද යන්න තෝරා ගන්න"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"ඔබේ මුරයතුරු තනන්න"</string> <string name="save_your_password" msgid="6597736507991704307">"ඔබේ මුරපදය සුරකින්න"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"ඔබේ පුරනය වීමේ තතු සුරකින්න"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"ඔබේ මුරපද සහ මුරයතුරු සුරැකීමට පෙරනිමි මුරපද කළමනාකරු සකසන්න සහ මීළඟ වතාවේ වේගයෙන් පුරනය වන්න."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> තුළ මුරයතුරක් තනන්න ද?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"ඔබේ මුරපදය <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> වෙත සුරකින්න ද?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"ඔබේ පුරනය වීමේ තතු <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> වෙත සුරකින්න ද?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"මුරයතුර"</string> <string name="password" msgid="6738570945182936667">"මුරපදය"</string> <string name="sign_ins" msgid="4710739369149469208">"පුරනය වීම්"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"මුරයතුර තනන්නේ"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"මෙයට මුරපදය සුරකින්න"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"පුරනය වීම සුරකින්නේ"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"වෙනත් උපාංගයක මුරයතුරක් තනන්න ද?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"ඔබේ සියලු පුරනය වීම් සඳහා <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> භාවිතා කරන්න ද?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"මෙම මුරපද කළමනාකරු ඔබට පහසුවෙන් පුරනය වීමට උදවු කිරීම සඳහා ඔබේ මුරපද සහ මුරයතුරු ගබඩා කරනු ඇත."</string> <string name="set_as_default" msgid="4415328591568654603">"පෙරනිමි ලෙස සකසන්න"</string> <string name="use_once" msgid="9027366575315399714">"වරක් භාවිතා කරන්න"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"මුරපද <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>ක්, මුරයතුරු <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g>ක්"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"මුරපද <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>ක්"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"මුරයතුරු <xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g>ක්"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"මුරයතුර"</string> <string name="another_device" msgid="5147276802037801217">"වෙනත් උපාංගයක්"</string> <string name="other_password_manager" msgid="565790221427004141">"වෙනත් මුරපද කළමනාකරුවන්"</string> <string name="close_sheet" msgid="1393792015338908262">"පත්රය වසන්න"</string> diff --git a/packages/CredentialManager/res/values-sk/strings.xml b/packages/CredentialManager/res/values-sk/strings.xml index 1c73c57d0421..cd8136139089 100644 --- a/packages/CredentialManager/res/values-sk/strings.xml +++ b/packages/CredentialManager/res/values-sk/strings.xml @@ -8,8 +8,14 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Uložiť inde"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Použiť iné zariadenie"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Uložiť do iného zariadenia"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Jednoduchý spôsob bezpečného prihlasovania"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Použite odtlačok prsta, tvár alebo zámku obrazovky a prihláste sa jedinečným prístupovým kľúčom, ktorý sa nedá zabudnúť ani ukradnúť. Ďalšie informácie"</string> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> <string name="choose_provider_title" msgid="7245243990139698508">"Vyberte, kam <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> <string name="create_your_passkeys" msgid="8901224153607590596">"vytvoriť prístupové kľúče"</string> <string name="save_your_password" msgid="6597736507991704307">"uložiť heslo"</string> diff --git a/packages/CredentialManager/res/values-sl/strings.xml b/packages/CredentialManager/res/values-sl/strings.xml index 969f29032837..c769e19b3692 100644 --- a/packages/CredentialManager/res/values-sl/strings.xml +++ b/packages/CredentialManager/res/values-sl/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Shranjevanje na drugo mesto"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Uporabi drugo napravo"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Shrani v drugo napravo"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Preprost način za varno prijavo"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Če se želite prijaviti z enoličnim ključem za dostop, ki ga ni mogoče pozabiti ali ukrasti, uporabite prstni odtis, obraz ali nastavljeni način za odklepanje zaslona. Več o tem"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Izberite mesto za <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Izberite mesto za <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"ustvarjanje ključev za dostop"</string> <string name="save_your_password" msgid="6597736507991704307">"shranjevanje gesla"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"shranjevanje podatkov za prijavo"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Nastavite privzetega upravitelja gesel za shranjevanje gesel in ključev za dostop, da se boste naslednjič lahko hitreje prijavili."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Želite ustvariti ključ za dostop pod »<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>«?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Želite shraniti geslo pod »<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>«?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Želite shraniti podatke za prijavo pod »<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>«?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"ključ za dostop"</string> <string name="password" msgid="6738570945182936667">"geslo"</string> <string name="sign_ins" msgid="4710739369149469208">"prijave"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Ustvarjanje ključa za dostop v"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Shranjevanje gesla v"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Shranjevanje podatkov za prijavo v"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Želite ustvariti ključ za dostop v drugi napravi?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Želite za vse prijave uporabiti »<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>«?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"V tem upravitelju gesel bodo shranjeni gesla in ključi za dostop, kar vam bo olajšalo prijavo."</string> <string name="set_as_default" msgid="4415328591568654603">"Nastavi kot privzeto"</string> <string name="use_once" msgid="9027366575315399714">"Uporabi enkrat"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"Št. gesel: <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>, št. ključev za dostop: <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g>"</string> diff --git a/packages/CredentialManager/res/values-sq/strings.xml b/packages/CredentialManager/res/values-sq/strings.xml index bce068309839..7e656d638386 100644 --- a/packages/CredentialManager/res/values-sq/strings.xml +++ b/packages/CredentialManager/res/values-sq/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Menaxheri i kredencialeve"</string> <string name="string_cancel" msgid="6369133483981306063">"Anulo"</string> <string name="string_continue" msgid="1346732695941131882">"Vazhdo"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Krijo në një vend tjetër"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Ruaj në një vend tjetër"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Përdor një pajisje tjetër"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Ruaj në një pajisje tjetër"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Një mënyrë e thjeshtë për t\'u identifikuar në mënyrë të sigurt"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Përdor gjurmën e gishtit, fytyrën ose kyçjen e ekranit për t\'u identifikuar me një çelës unik kalimi i cili nuk mund të harrohet ose të vidhet. Mëso më shumë"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Zgjidh se ku të <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Zgjidh se ku të <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"do t\'i krijosh çelësat e tu të kalimit"</string> <string name="save_your_password" msgid="6597736507991704307">"ruaj fjalëkalimin"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"ruaj informacionet e tua të identifikimit"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Cakto një menaxher të parazgjedhur të fjalëkalimeve për të ruajtur fjalëkalimet dhe çelësat e kalimit dhe për t\'u identifikuar më shpejt herën tjetër."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Të krijohet një çelës kalimi në <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Të ruhet fjalëkalimi në <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Të ruhen informacionet e tua të identifikimit në <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"çelësi i kalimit"</string> <string name="password" msgid="6738570945182936667">"fjalëkalimi"</string> <string name="sign_ins" msgid="4710739369149469208">"identifikimet"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Krijo çelësin e kalimit te"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Ruaj fjalëkalimin në"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Ruaj identifikimin në"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Të krijohet një çelës kalimi në një pajisje tjetër?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Të përdoret <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> për të gjitha identifikimet?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Ky menaxher i fjalëkalimeve do të ruajë fjalëkalimet dhe çelësat e kalimit për të të ndihmuar të identifikohesh me lehtësi."</string> <string name="set_as_default" msgid="4415328591568654603">"Cakto si parazgjedhje"</string> <string name="use_once" msgid="9027366575315399714">"Përdor një herë"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> fjalëkalime, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> çelësa kalimi"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> fjalëkalime"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> çelësa kalimi"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Çelësi i kalimit"</string> <string name="another_device" msgid="5147276802037801217">"Një pajisje tjetër"</string> <string name="other_password_manager" msgid="565790221427004141">"Menaxherët e tjerë të fjalëkalimeve"</string> <string name="close_sheet" msgid="1393792015338908262">"Mbyll fletën"</string> diff --git a/packages/CredentialManager/res/values-sr/strings.xml b/packages/CredentialManager/res/values-sr/strings.xml index 6a5235c79d56..cfb6c055e0c1 100644 --- a/packages/CredentialManager/res/values-sr/strings.xml +++ b/packages/CredentialManager/res/values-sr/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Менаџер акредитива"</string> <string name="string_cancel" msgid="6369133483981306063">"Откажи"</string> <string name="string_continue" msgid="1346732695941131882">"Настави"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Направи на другом месту"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Сачувај на другом месту"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Користи други уређај"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Сачувај на други уређај"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Једноставан начин да се безбедно пријављујете"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Користите отисак прста, закључавање лицем или закључавање екрана да бисте се пријавили помоћу јединственог приступног кода који не може да се заборави или украде. Сазнајте више"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Одаберите локацију за: <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Одаберите локацију за: <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"направите приступне кодове"</string> <string name="save_your_password" msgid="6597736507991704307">"сачувајте лозинку"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"сачувајте податке о пријављивању"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Подесите подразумевани менаџер лозинки да бисте сачували лозинке и приступне кодове и следећи пут се пријавили брже."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Желите да направите приступни кôд код корисника <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Желите да сачувате лозинку код корисника <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Желите да сачувате податке о пријављивању код корисника <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"приступни кôд"</string> <string name="password" msgid="6738570945182936667">"лозинка"</string> <string name="sign_ins" msgid="4710739369149469208">"пријављивања"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Направите приступни кôд у:"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Сачувајте лозинку на:"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Сачувајте податке о пријављивању на:"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Желите да направите приступни кôд на другом уређају?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Желите да за сва пријављивања користите: <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Овај менаџер лозинки ће чувати лозинке и приступне кодове да бисте се лако пријављивали."</string> <string name="set_as_default" msgid="4415328591568654603">"Подеси као подразумевано"</string> <string name="use_once" msgid="9027366575315399714">"Користи једном"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"Лозинки: <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>, приступних кодова:<xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g>"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"Лозинки: <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"Приступних кодова: <xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g>"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Приступни кôд"</string> <string name="another_device" msgid="5147276802037801217">"Други уређај"</string> <string name="other_password_manager" msgid="565790221427004141">"Други менаџери лозинки"</string> <string name="close_sheet" msgid="1393792015338908262">"Затворите табелу"</string> diff --git a/packages/CredentialManager/res/values-sv/strings.xml b/packages/CredentialManager/res/values-sv/strings.xml index a4fffb979b8f..842d7876f5da 100644 --- a/packages/CredentialManager/res/values-sv/strings.xml +++ b/packages/CredentialManager/res/values-sv/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"Spara på en annan plats"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Använd en annan enhet"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Spara på en annan enhet"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Ett enkelt sätt att logga in säkert på"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Använd ditt fingeravtryck, ansikte eller skärmlås om du vill logga in med en unik nyckel som inte kan glömmas bort eller bli stulen. Läs mer"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Välj var du <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Välj var du <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"skapa nycklar"</string> <string name="save_your_password" msgid="6597736507991704307">"spara lösenordet"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"spara inloggningsuppgifterna"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Ställ in vilken lösenordshanterare som ska användas som standard om du vill spara lösenord, nycklar och inloggningsuppgifter snabbare nästa gång."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Vill du skapa en nyckel i <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Vill du spara ditt lösenord i <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Vill du spara dina inloggningsuppgifter i <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"nyckel"</string> <string name="password" msgid="6738570945182936667">"lösenord"</string> <string name="sign_ins" msgid="4710739369149469208">"inloggningar"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Skapa nyckel i"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Spara lösenordet i"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Spara inloggningen i"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Vill du skapa en nyckel på en annan enhet?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Vill du använda <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> för alla dina inloggningar?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Den här lösenordshanteraren sparar dina lösenord och nycklar för att underlätta inloggning."</string> <string name="set_as_default" msgid="4415328591568654603">"Ange som standard"</string> <string name="use_once" msgid="9027366575315399714">"Använd en gång"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> lösenord, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> nycklar"</string> diff --git a/packages/CredentialManager/res/values-sw/strings.xml b/packages/CredentialManager/res/values-sw/strings.xml index bfd10747554c..3eb74328b639 100644 --- a/packages/CredentialManager/res/values-sw/strings.xml +++ b/packages/CredentialManager/res/values-sw/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Kidhibiti cha Vitambulisho"</string> <string name="string_cancel" msgid="6369133483981306063">"Ghairi"</string> <string name="string_continue" msgid="1346732695941131882">"Endelea"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Unda katika sehemu nyingine"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Hifadhi sehemu nyingine"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Tumia kifaa kingine"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Hifadhi kwenye kifaa kingine"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Njia rahisi ya kuingia katika akaunti kwa usalama"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Tumia alama ya vidole, uso au kipengele cha kufunga skrini ili uingie katika kaunti kwa kutumia nenosiri la kipekee ambalo haliwezi kusahaulika au kuibiwa. Pata maelezo zaidi"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Chagua mahali pa <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Chagua mahali pa <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"unda funguo zako za siri"</string> <string name="save_your_password" msgid="6597736507991704307">"hifadhi nenosiri lako"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"hifadhi maelezo yako ya kuingia katika akaunti"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Weka kidhibiti chaguomsingi cha manenosiri ili uhifadhi manenosiri na funguo zako za siri na uingie katika akaunti kwa haraka wakati mwingine."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Ungependa kuunda ufunguo wa siri katika <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Ungependa kuhifadhi nenosiri lako kwenye <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Ungependa kuhifadhi maelezo yako ya kuingia katika akaunti kwenye <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"ufunguo wa siri"</string> <string name="password" msgid="6738570945182936667">"nenosiri"</string> <string name="sign_ins" msgid="4710739369149469208">"michakato ya kuingia katika akaunti"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Unda ufunguo wa siri kwenye"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Hifadhi nenosiri kwenye"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Hifadhi kitambulisho cha kuingia katika akaunti kwenye"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Ungependa kuunda ufunguo wa siri kwenye kifaa kingine?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Ungependa kutumia <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> kwa ajili ya michakato yako yote ya kuingia katika akaunti?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Kidhibiti hiki cha manenosiri kitahifadhi manenosiri na funguo zako za siri ili kukusaidia uingie katika akaunti kwa urahisi."</string> <string name="set_as_default" msgid="4415328591568654603">"Weka iwe chaguomsingi"</string> <string name="use_once" msgid="9027366575315399714">"Tumia mara moja"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"Manenosiri <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>, funguo <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> za siri"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"Manenosiri <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"Funguo <xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> za siri"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Ufunguo wa siri"</string> <string name="another_device" msgid="5147276802037801217">"Kifaa kingine"</string> <string name="other_password_manager" msgid="565790221427004141">"Vidhibiti vinginevyo vya manenosiri"</string> <string name="close_sheet" msgid="1393792015338908262">"Funga laha"</string> diff --git a/packages/CredentialManager/res/values-ta/strings.xml b/packages/CredentialManager/res/values-ta/strings.xml index 10c52594c7d3..2d7d84ef9e54 100644 --- a/packages/CredentialManager/res/values-ta/strings.xml +++ b/packages/CredentialManager/res/values-ta/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"அனுமதிச் சான்று நிர்வாகி"</string> <string name="string_cancel" msgid="6369133483981306063">"ரத்துசெய்"</string> <string name="string_continue" msgid="1346732695941131882">"தொடர்க"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"மற்றொரு இடத்தில் உருவாக்கவும்"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"மற்றொரு இடத்தில் சேமிக்கவும்"</string> <string name="string_use_another_device" msgid="8754514926121520445">"மற்றொரு சாதனத்தைப் பயன்படுத்தவும்"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"வேறொரு சாதனத்தில் சேமியுங்கள்"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"பாதுகாப்பாக உள்நுழைவதற்கான எளிய வழி"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"தனித்துவமான கடவுக்குறியீடு (மறக்காதவை அல்லது திருடமுடியாதவை) மூலம் உள்நுழைய, உங்கள் கைரேகை, முகம் அல்லது திரைப்பூட்டைப் பயன்படுத்தி உள்நுழையவும். மேலும் அறிக"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> எங்கே காட்டப்பட வேண்டும் என்பதைத் தேர்வுசெய்தல்"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> எங்கே காட்டப்பட வேண்டும் என்பதைத் தேர்வுசெய்தல்"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"உங்கள் கடவுச்சாவிகளை உருவாக்குங்கள்"</string> <string name="save_your_password" msgid="6597736507991704307">"உங்கள் கடவுச்சொல்லைச் சேமிக்கவும்"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"உங்கள் உள்நுழைவு தகவலைச் சேமிக்கவும்"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"கடவுச்சொற்கள் & கடவுச்சாவிகளைச் சேமிக்கவும் அடுத்தமுறை விரைவாக உள்நுழையவும் ஓர் இயல்பான Password Managerரை அமையுங்கள்."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>ல் கடவுக்குறியீட்டை உருவாக்க வேண்டுமா?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"உங்கள் கடவுச்சொல்லை <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>ல் சேமிக்க வேண்டுமா?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"உங்கள் உள்நுழைவுத் தகவலை <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>ல் சேமிக்க வேண்டுமா?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"கடவுக்குறியீடு"</string> <string name="password" msgid="6738570945182936667">"கடவுச்சொல்"</string> <string name="sign_ins" msgid="4710739369149469208">"உள்நுழைவுகள்"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"இதில் கடவுச்சாவியை உருவாக்குங்கள்:"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"கடவுச்சொல்லை இதில் சேமியுங்கள்:"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"உள்நுழைவுத் தகவலை இதில் சேமியுங்கள்:"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"வேறொரு சாதனத்தில் கடவுச்சாவியை உருவாக்கவா?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"உங்கள் அனைத்து உள்நுழைவுகளுக்கும் <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>ஐப் பயன்படுத்தவா?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"எளிதில் உள்நுழைவதற்கு உதவும் வகையில் இந்த Password Manager உங்கள் கடவுச்சொற்களையும் கடவுச்சாவிகளையும் சேமிக்கும்."</string> <string name="set_as_default" msgid="4415328591568654603">"இயல்பானதாக அமை"</string> <string name="use_once" msgid="9027366575315399714">"ஒருமுறை பயன்படுத்தவும்"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> கடவுச்சொற்கள், <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> கடவுக்குறியீடுகள்"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> கடவுச்சொற்கள்"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> கடவுக்குறியீடுகள்"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"கடவுக்குறியீடு"</string> <string name="another_device" msgid="5147276802037801217">"மற்றொரு சாதனம்"</string> <string name="other_password_manager" msgid="565790221427004141">"பிற கடவுச்சொல் நிர்வாகிகள்"</string> <string name="close_sheet" msgid="1393792015338908262">"ஷீட்டை மூடும்"</string> diff --git a/packages/CredentialManager/res/values-te/strings.xml b/packages/CredentialManager/res/values-te/strings.xml index f7617b3e34dd..664252d5a576 100644 --- a/packages/CredentialManager/res/values-te/strings.xml +++ b/packages/CredentialManager/res/values-te/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"డాక్యుమెంట్ ప్రూఫ్ మేనేజర్"</string> <string name="string_cancel" msgid="6369133483981306063">"రద్దు చేయండి"</string> <string name="string_continue" msgid="1346732695941131882">"కొనసాగించండి"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"మరొక స్థలంలో క్రియేట్ చేయండి"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"మరొక స్థలంలో సేవ్ చేయండి"</string> <string name="string_use_another_device" msgid="8754514926121520445">"మరొక పరికరాన్ని ఉపయోగించండి"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"మరొక పరికరంలో సేవ్ చేయండి"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"సురక్షితంగా సైన్ ఇన్ చేయడానికి సులభమైన మార్గం"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"మర్చిపోలేని లేదా దొంగిలించలేని ప్రత్యేకమైన పాస్-కీతో సైన్ ఇన్ చేయడానికి మీ వేలిముద్ర, ముఖం లేదా స్క్రీన్ లాక్ను ఉపయోగించండి. మరింత తెలుసుకోండి"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"ఎక్కడ <xliff:g id="CREATETYPES">%1$s</xliff:g> చేయాలో ఎంచుకోండి"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"ఎక్కడ <xliff:g id="CREATETYPES">%1$s</xliff:g> చేయాలో ఎంచుకోండి"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"మీ పాస్-కీలను క్రియేట్ చేయండి"</string> <string name="save_your_password" msgid="6597736507991704307">"మీ పాస్వర్డ్ను సేవ్ చేయండి"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"మీ సైన్ ఇన్ సమాచారాన్ని సేవ్ చేయండి"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"మీ పాస్వర్డ్లు, పాస్కీలను సేవ్ చేయడానికి ఆటోమేటిక్ సెట్టింగ్ పాస్వర్డ్ మేనేజర్ను సెట్ చేయండి, తదుపరిసారి వేగంగా సైన్ ఇన్ చేయండి."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>లో పాస్-కీని క్రియేట్ చేయాలా?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"మీ పాస్వర్డ్ను <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>కు సేవ్ చేయాలా?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"మీ సైన్ ఇన్ సమాచారాన్ని <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>కు సేవ్ చేయాలా?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"పాస్-కీ"</string> <string name="password" msgid="6738570945182936667">"పాస్వర్డ్"</string> <string name="sign_ins" msgid="4710739369149469208">"సైన్ ఇన్లు"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"వీటిలో పాస్-కీని క్రియేట్ చేయండి"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"పాస్వర్డ్ను దీనికి సేవ్ చేయండి"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"సైన్ ఇన్ను దీనికి సేవ్ చేయండి"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"మరొక పరికరంలో పాస్-కీని క్రియేట్ చేయాలా?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"మీ అన్ని సైన్-ఇన్ వివరాల కోసం <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>ను ఉపయోగించాలా?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"మీరు సులభంగా సైన్ ఇన్ చేయడంలో సహాయపడటానికి ఈ పాస్వర్డ్ మేనేజర్ మీ పాస్వర్డ్లు, పాస్-కీలను స్టోర్ చేస్తుంది."</string> <string name="set_as_default" msgid="4415328591568654603">"ఆటోమేటిక్ సెట్టింగ్గా సెట్ చేయండి"</string> <string name="use_once" msgid="9027366575315399714">"ఒకసారి ఉపయోగించండి"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> పాస్వర్డ్లు, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> పాస్-కీలు"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> పాస్వర్డ్లు"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> పాస్-కీలు"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"పాస్-కీ"</string> <string name="another_device" msgid="5147276802037801217">"మరొక పరికరం"</string> <string name="other_password_manager" msgid="565790221427004141">"ఇతర పాస్వర్డ్ మేనేజర్లు"</string> <string name="close_sheet" msgid="1393792015338908262">"షీట్ను మూసివేయండి"</string> diff --git a/packages/CredentialManager/res/values-th/strings.xml b/packages/CredentialManager/res/values-th/strings.xml index d70e94ad0425..106c456ab650 100644 --- a/packages/CredentialManager/res/values-th/strings.xml +++ b/packages/CredentialManager/res/values-th/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"บันทึกลงในตำแหน่งอื่น"</string> <string name="string_use_another_device" msgid="8754514926121520445">"ใช้อุปกรณ์อื่น"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"ย้ายไปยังอุปกรณ์อื่น"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"วิธีง่ายๆ ในการลงชื่อเข้าใช้อย่างปลอดภัย"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"ใช้ลายนิ้วมือ ใบหน้า หรือล็อกหน้าจอในการลงชื่อเข้าใช้ด้วยพาสคีย์ที่ไม่ซ้ำกันเพื่อไม่ให้ลืมหรือถูกขโมยได้ ดูข้อมูลเพิ่มเติม"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"เลือกตำแหน่งที่จะ <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"เลือกตำแหน่งที่จะ <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"สร้างพาสคีย์"</string> <string name="save_your_password" msgid="6597736507991704307">"บันทึกรหัสผ่าน"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"บันทึกข้อมูลการลงชื่อเข้าใช้"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"ตั้งค่าเครื่องมือจัดการรหัสผ่านเริ่มต้นเพื่อบันทึกรหัสผ่านและพาสคีย์ของคุณ และลงชื่อเข้าใช้ได้เร็วขึ้นในครั้งถัดไป"</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"สร้างพาสคีย์ใน <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ใช่ไหม"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"บันทึกรหัสผ่านลงใน <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ใช่ไหม"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"บันทึกข้อมูลการลงชื่อเข้าใช้ลงใน <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ใช่ไหม"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"พาสคีย์"</string> <string name="password" msgid="6738570945182936667">"รหัสผ่าน"</string> <string name="sign_ins" msgid="4710739369149469208">"การลงชื่อเข้าใช้"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"สร้างพาสคีย์ใน"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"บันทึกรหัสผ่านลงใน"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"บันทึกการลงชื่อเข้าใช้ไปยัง"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"สร้างพาสคีย์ในอุปกรณ์อื่นไหม"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"ใช้ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> สำหรับการลงชื่อเข้าใช้ทั้งหมดใช่ไหม"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"เครื่องมือจัดการรหัสผ่านนี้จะจัดเก็บรหัสผ่านและพาสคีย์ไว้เพื่อช่วยให้คุณลงชื่อเข้าใช้ได้โดยง่าย"</string> <string name="set_as_default" msgid="4415328591568654603">"ตั้งเป็นค่าเริ่มต้น"</string> <string name="use_once" msgid="9027366575315399714">"ใช้ครั้งเดียว"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"รหัสผ่าน <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> รายการ พาสคีย์ <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> รายการ"</string> diff --git a/packages/CredentialManager/res/values-tl/strings.xml b/packages/CredentialManager/res/values-tl/strings.xml index 01fd2f02063d..d5501908aa13 100644 --- a/packages/CredentialManager/res/values-tl/strings.xml +++ b/packages/CredentialManager/res/values-tl/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"I-save sa ibang lugar"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Gumamit ng ibang device"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"I-save sa ibang device"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Simpleng paraan para mag-sign in lang ligtas"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Gamitin ang iyong fingerprint, mukha, o lock ng screen para mag-sign in gamit ang natatanging passkey na hindi makakalimutan o mananakaw. Matuto pa"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Piliin kung saan <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Piliin kung saan <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"gawin ang iyong mga passkey"</string> <string name="save_your_password" msgid="6597736507991704307">"i-save ang iyong password"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"i-save ang iyong impormasyon sa pag-sign in"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Magtakda ng default na password manager para i-save ang iyong mga password at passkey at mag-sign in nang mas mabilis sa susunod."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Gumawa ng passkey sa <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"I-save ang iyong password sa <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"I-save ang iyong impormasyon sa pag-sign in sa <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"passkey"</string> <string name="password" msgid="6738570945182936667">"password"</string> <string name="sign_ins" msgid="4710739369149469208">"mga sign-in"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Gumawa ng passkey sa"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"I-save ang password sa"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"I-save ang sign-in sa"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Gumawa ng passkey sa ibang device?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Gamitin ang <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> para sa lahat ng iyong pag-sign in?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Iso-store ng password manager na ito ang iyong mga password at passkey para madali kang makapag-sign in."</string> <string name="set_as_default" msgid="4415328591568654603">"Itakda bilang default"</string> <string name="use_once" msgid="9027366575315399714">"Gamitin nang isang beses"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> (na) password, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> (na) passkey"</string> diff --git a/packages/CredentialManager/res/values-tr/strings.xml b/packages/CredentialManager/res/values-tr/strings.xml index 30ed43e6ed19..09c659027bb3 100644 --- a/packages/CredentialManager/res/values-tr/strings.xml +++ b/packages/CredentialManager/res/values-tr/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Kimlik Bilgisi Yöneticisi"</string> <string name="string_cancel" msgid="6369133483981306063">"İptal"</string> <string name="string_continue" msgid="1346732695941131882">"Devam"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Başka bir yerde oluşturun"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Başka bir yere kaydedin"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Başka bir cihaz kullan"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Başka bir cihaza kaydet"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Güvenli bir şekilde oturum açmanın basit yolu"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Parmak iziniz, yüzünüz ya da ekran kilidinizi kullanarak unutması veya çalınması mümkün olmayan benzersiz bir şifre anahtarıyla oturum açın. Daha fazla bilgi"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> yerini seçin"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> yerini seçin"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"şifre anahtarlarınızı oluşturun"</string> <string name="save_your_password" msgid="6597736507991704307">"şifrenizi kaydedin"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"oturum açma bilgilerinizi kaydedin"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Şifrelerinizi ve şifre anahtarlarınızı kaydedip bir dahaki sefere daha hızlı oturum açmak için varsayılan bir şifre yöneticisi belirleyin."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> içinde şifre anahtarı oluşturulsun mu?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Şifreniz <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> içine kaydedilsin mi?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Oturum açma bilgileriniz <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> içine kaydedilsin mi?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"şifre anahtarı"</string> <string name="password" msgid="6738570945182936667">"şifre"</string> <string name="sign_ins" msgid="4710739369149469208">"oturum aç"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Şifre anahtarının oluşturulacağı yer:"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Şifreyi şuraya kaydet:"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Oturum açma bilgilerinin kaydedileceği yer:"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Başka bir cihazda şifre anahtarı oluşturulsun mu?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Tüm oturum açma işlemlerinizde <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> kullanılsın mı?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Bu şifre yöneticisi, şifrelerinizi ve şifre anahtarlarınızı saklayarak kolayca oturum açmanıza yardımcı olur."</string> <string name="set_as_default" msgid="4415328591568654603">"Varsayılan olarak ayarla"</string> <string name="use_once" msgid="9027366575315399714">"Bir kez kullanın"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> şifre, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> şifre anahtarı"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> şifre"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> şifre anahtarı"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Şifre anahtarı"</string> <string name="another_device" msgid="5147276802037801217">"Başka bir cihaz"</string> <string name="other_password_manager" msgid="565790221427004141">"Diğer şifre yöneticileri"</string> <string name="close_sheet" msgid="1393792015338908262">"Sayfayı kapat"</string> diff --git a/packages/CredentialManager/res/values-uk/strings.xml b/packages/CredentialManager/res/values-uk/strings.xml index 69d4612eb594..9a12e331dff2 100644 --- a/packages/CredentialManager/res/values-uk/strings.xml +++ b/packages/CredentialManager/res/values-uk/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Диспетчер облікових даних"</string> <string name="string_cancel" msgid="6369133483981306063">"Скасувати"</string> <string name="string_continue" msgid="1346732695941131882">"Продовжити"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Створити в іншому місці"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Зберегти в іншому місці"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Скористатись іншим пристроєм"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Зберегти на іншому пристрої"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Зручний спосіб для безпечного входу"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Користуйтеся відбитком пальця, фейсконтролем або іншим способом розблокування екрана, щоб входити в обліковий запис за допомогою унікального ключа доступу, який неможливо забути чи викрасти. Докладніше"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Виберіть, де <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Виберіть, де <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"створювати ключі доступу"</string> <string name="save_your_password" msgid="6597736507991704307">"зберегти пароль"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"зберегти дані для входу"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Налаштуйте менеджер паролів за умовчанням, щоб зберігати свої паролі та ключі доступу й надалі входити в облікові записи швидше."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Створити ключ доступу в сервісі <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Зберегти ваш пароль у сервісі <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Зберегти ваші дані для входу в сервіс <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"ключ доступу"</string> <string name="password" msgid="6738570945182936667">"пароль"</string> <string name="sign_ins" msgid="4710739369149469208">"дані для входу"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Створити ключ доступу в"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Зберегти пароль в обліковому записі"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Зберегти дані для входу в обліковий запис"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Створити ключ доступу на іншому пристрої?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Використовувати сервіс <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> в усіх випадках входу?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Цей менеджер паролів зберігатиме ваші паролі та ключі доступу, щоб ви могли легко входити в облікові записи."</string> <string name="set_as_default" msgid="4415328591568654603">"Вибрати за умовчанням"</string> <string name="use_once" msgid="9027366575315399714">"Скористатися раз"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"Кількість паролів: <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>; кількість ключів доступу: <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g>"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"Кількість паролів: <xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"Кількість ключів доступу: <xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g>"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Ключ доступу"</string> <string name="another_device" msgid="5147276802037801217">"Інший пристрій"</string> <string name="other_password_manager" msgid="565790221427004141">"Інші менеджери паролів"</string> <string name="close_sheet" msgid="1393792015338908262">"Закрити аркуш"</string> diff --git a/packages/CredentialManager/res/values-ur/strings.xml b/packages/CredentialManager/res/values-ur/strings.xml index 2d6607934bc0..50fbb8d53fcb 100644 --- a/packages/CredentialManager/res/values-ur/strings.xml +++ b/packages/CredentialManager/res/values-ur/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"دوسرے مقام میں محفوظ کریں"</string> <string name="string_use_another_device" msgid="8754514926121520445">"کوئی دوسرا آلہ استعمال کریں"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"دوسرے آلے میں محفوظ کریں"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"محفوظ طریقے سے سائن ان کرنے کا آسان طریقہ"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"اپنے فنگر پرنٹ، چہرے یا اسکرین لاک کا استعمال کریں تاکہ ایک ایسی منفرد پاس کی سے سائن ان کیا جا سکے جسے بھولا یا چوری نہیں کیا جا سکتا۔ مزید جانیں"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> کی جگہ منتخب کریں"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> کی جگہ منتخب کریں"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"اپنی پاس کیز تخلیق کریں"</string> <string name="save_your_password" msgid="6597736507991704307">"اپنا پاس ورڈ محفوظ کریں"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"اپنے سائن ان کی معلومات محفوظ کریں"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"اپنے پاس ورڈز اور پاس کیز کو محفوظ کرنے اور اگلی بار تیزی سے سائن ان کرنے کے لیے ایک ڈیفالٹ پاس ورڈ مینیجر سیٹ کریں۔"</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> میں پاس کی تخلیق کریں؟"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"اپنا پاس ورڈ <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> میں محفوظ کریں؟"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"اپنے سائن ان کی معلومات کو <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> میں محفوظ کریں؟"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"پاس کی"</string> <string name="password" msgid="6738570945182936667">"پاس ورڈ"</string> <string name="sign_ins" msgid="4710739369149469208">"سائن انز"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"اس میں پاس کی تخلیق کریں"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"میں پاس ورڈ محفوظ کریں"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"میں سائن ان محفوظ کریں"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"کسی اور آلے میں پاس کی تخلیق کریں؟"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"اپنے سبھی سائن انز کے لیے <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> کا استعمال کریں؟"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"یہ پاس ورڈ مینیجر آپ کے پاس ورڈز اور پاس کیز کو آسانی سے سائن ان کرنے میں آپ کی مدد کرنے کے لیے اسٹور کرے گا۔"</string> <string name="set_as_default" msgid="4415328591568654603">"بطور ڈیفالٹ سیٹ کریں"</string> <string name="use_once" msgid="9027366575315399714">"ایک بار استعمال کریں"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> پاس ورڈز، <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> پاس کیز"</string> diff --git a/packages/CredentialManager/res/values-uz/strings.xml b/packages/CredentialManager/res/values-uz/strings.xml index 4ac35b2e6f7d..b46979aef749 100644 --- a/packages/CredentialManager/res/values-uz/strings.xml +++ b/packages/CredentialManager/res/values-uz/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Hisob maʼlumotlari menejeri"</string> <string name="string_cancel" msgid="6369133483981306063">"Bekor qilish"</string> <string name="string_continue" msgid="1346732695941131882">"Davom etish"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Boshqa joyda yaratish"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Boshqa joyga saqlash"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Boshqa qurilmadan foydalaning"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Boshqa qurilmaga saqlash"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Xavfsiz kirishning oddiy usuli"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Esda qoladigan maxsus kalit bilan kirishda barmoq izi, yuz axboroti yoki ekran qulfidan foydalaning. Batafsil"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> joyini tanlang"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"<xliff:g id="CREATETYPES">%1$s</xliff:g> joyini tanlang"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"kodlar yaratish"</string> <string name="save_your_password" msgid="6597736507991704307">"Parolni saqlash"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"kirish axborotini saqlang"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Parol va kodlarni saqlash va keyingi safar tezroq kirish uchun standart parollar menejerini sozlang."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Kalit <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> xizmatida yaratilsinmi?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Parol <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> xizmatida saqlansinmi?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Hisob maʼlumotlari <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> xizmatida saqlansinmi?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"kalit"</string> <string name="password" msgid="6738570945182936667">"parol"</string> <string name="sign_ins" msgid="4710739369149469208">"kirishlar"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Kod yaratish vositasi"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Parolni bu hisobga saqlash"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Kirish axborotini saqlash"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Boshqa qurilmada kod yaratilsinmi?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Hamma kirishlarda <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> ishlatilsinmi?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Bu parollar menejerida hisobga oson kirishga yordam beruvchi parol va kalitlar saqlanadi."</string> <string name="set_as_default" msgid="4415328591568654603">"Birlamchi deb belgilash"</string> <string name="use_once" msgid="9027366575315399714">"Bir marta ishlatish"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> ta parol, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> ta kalit"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> ta parol"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> ta kalit"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Kod"</string> <string name="another_device" msgid="5147276802037801217">"Boshqa qurilma"</string> <string name="other_password_manager" msgid="565790221427004141">"Boshqa parol menejerlari"</string> <string name="close_sheet" msgid="1393792015338908262">"Varaqni yopish"</string> diff --git a/packages/CredentialManager/res/values-vi/strings.xml b/packages/CredentialManager/res/values-vi/strings.xml index fd5b986c574b..6c3022ec3b60 100644 --- a/packages/CredentialManager/res/values-vi/strings.xml +++ b/packages/CredentialManager/res/values-vi/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Trình quản lý thông tin xác thực"</string> <string name="string_cancel" msgid="6369133483981306063">"Huỷ"</string> <string name="string_continue" msgid="1346732695941131882">"Tiếp tục"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Tạo ở vị trí khác"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Lưu vào vị trí khác"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Dùng thiết bị khác"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Lưu vào thiết bị khác"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Cách đơn giản để đăng nhập an toàn"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Dùng vân tay, khuôn mặt hoặc phương thức khoá màn hình để đăng nhập bằng một mã xác thực duy nhất mà bạn không lo sẽ quên hay bị đánh cắp. Tìm hiểu thêm"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"Chọn vị trí <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"Chọn vị trí <xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"tạo mã xác thực"</string> <string name="save_your_password" msgid="6597736507991704307">"lưu mật khẩu của bạn"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"lưu thông tin đăng nhập của bạn"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"Đặt một trình quản lý mật khẩu mặc định để lưu mật khẩu và mã xác thực của bạn, nhờ đó, bạn sẽ đăng nhập nhanh hơn vào lần sau."</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"Tạo một mã xác thực trong <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"Lưu mật khẩu của bạn vào <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"Lưu thông tin đăng nhập của bạn vào <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"mã xác thực"</string> <string name="password" msgid="6738570945182936667">"mật khẩu"</string> <string name="sign_ins" msgid="4710739369149469208">"thông tin đăng nhập"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"Tạo mã xác thực trong"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"Lưu mật khẩu vào"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"Lưu thông tin đăng nhập vào"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"Tạo mã xác thực trong một thiết bị khác?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"Dùng <xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g> cho mọi thông tin đăng nhập của bạn?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"Trình quản lý mật khẩu này sẽ lưu trữ mật khẩu và mã xác thực của bạn để bạn dễ dàng đăng nhập."</string> <string name="set_as_default" msgid="4415328591568654603">"Đặt làm mặc định"</string> <string name="use_once" msgid="9027366575315399714">"Dùng một lần"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> mật khẩu, <xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> mã xác thực"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> mật khẩu"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> mã xác thực"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Mã xác thực"</string> <string name="another_device" msgid="5147276802037801217">"Thiết bị khác"</string> <string name="other_password_manager" msgid="565790221427004141">"Trình quản lý mật khẩu khác"</string> <string name="close_sheet" msgid="1393792015338908262">"Đóng trang tính"</string> diff --git a/packages/CredentialManager/res/values-zh-rCN/strings.xml b/packages/CredentialManager/res/values-zh-rCN/strings.xml index a14dd2f6fe20..9e6c514bd83e 100644 --- a/packages/CredentialManager/res/values-zh-rCN/strings.xml +++ b/packages/CredentialManager/res/values-zh-rCN/strings.xml @@ -1,23 +1,26 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Credential Manager"</string> <string name="string_cancel" msgid="6369133483981306063">"取消"</string> <string name="string_continue" msgid="1346732695941131882">"继续"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"在另一位置创建"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"保存到另一位置"</string> <string name="string_use_another_device" msgid="8754514926121520445">"使用另一台设备"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"保存到其他设备"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"简单又安全的登录方式"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"借助指纹、人脸识别或屏幕锁定功能,使用不会被忘记或被盗且具有唯一性的通行密钥登录。了解详情"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"选择<xliff:g id="CREATETYPES">%1$s</xliff:g>的位置"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"选择<xliff:g id="CREATETYPES">%1$s</xliff:g>的位置"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"创建通行密钥"</string> <string name="save_your_password" msgid="6597736507991704307">"保存您的密码"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"保存您的登录信息"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"设置默认密码管理工具,以便保存您的密码和通行密钥,从而提高下次的登录速度。"</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"在“<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>”中创建通行密钥?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"将您的密码保存至“<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>”?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"将您的登录信息保存至“<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>”?"</string> @@ -25,24 +28,18 @@ <string name="passkey" msgid="632353688396759522">"通行密钥"</string> <string name="password" msgid="6738570945182936667">"密码"</string> <string name="sign_ins" msgid="4710739369149469208">"登录"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"在以下位置创建通行密钥"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"将密码保存到"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"将登录信息保存到"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"在其他设备上创建通行密钥?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"将“<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>”用于您的所有登录信息?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"此密码管理工具将会存储您的密码和通行密钥,以帮助您轻松登录。"</string> <string name="set_as_default" msgid="4415328591568654603">"设为默认项"</string> <string name="use_once" msgid="9027366575315399714">"使用一次"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> 个密码,<xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> 个通行密钥"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> 个密码"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> 个通行密钥"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"通行密钥"</string> <string name="another_device" msgid="5147276802037801217">"另一台设备"</string> <string name="other_password_manager" msgid="565790221427004141">"其他密码管理工具"</string> <string name="close_sheet" msgid="1393792015338908262">"关闭工作表"</string> diff --git a/packages/CredentialManager/res/values-zh-rHK/strings.xml b/packages/CredentialManager/res/values-zh-rHK/strings.xml index 71dfa1affb72..cc596d702da9 100644 --- a/packages/CredentialManager/res/values-zh-rHK/strings.xml +++ b/packages/CredentialManager/res/values-zh-rHK/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"儲存至其他位置"</string> <string name="string_use_another_device" msgid="8754514926121520445">"改用其他裝置"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"儲存至其他裝置"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"安全又簡便的登入方式"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"使用指紋、面孔或螢幕鎖定配合密鑰登入。密鑰獨一無二,您不用擔心忘記密鑰或密鑰被盜。瞭解詳情"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"選擇「<xliff:g id="CREATETYPES">%1$s</xliff:g>」的位置"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"選擇「<xliff:g id="CREATETYPES">%1$s</xliff:g>」的位置"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"建立密鑰"</string> <string name="save_your_password" msgid="6597736507991704307">"儲存密碼"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"儲存登入資料"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"設定預設的密碼管理工具以儲存密碼和密碼密鑰,下次就能更快速登入。"</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"要在「<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>」建立密鑰嗎?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"要將密碼儲存至「<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>」嗎?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"要將登入資料儲存至「<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>」嗎?"</string> @@ -24,23 +28,18 @@ <string name="passkey" msgid="632353688396759522">"密鑰"</string> <string name="password" msgid="6738570945182936667">"密碼"</string> <string name="sign_ins" msgid="4710739369149469208">"登入資料"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"在此裝置建立密鑰:"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"將密碼儲存至以下位置:"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"將登入資料儲存至以下位置:"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"要在另一部裝置上建立密鑰嗎?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"要將「<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>」用於所有的登入資料嗎?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"此密碼管理工具將儲存您的密碼和密鑰,協助您輕鬆登入。"</string> <string name="set_as_default" msgid="4415328591568654603">"設定為預設"</string> <string name="use_once" msgid="9027366575315399714">"單次使用"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> 個密碼,<xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> 個密鑰"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> 個密碼"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g> 個密鑰"</string> - <string name="passkey_before_subtitle" msgid="2448119456208647444">"密碼金鑰"</string> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"密鑰"</string> <string name="another_device" msgid="5147276802037801217">"其他裝置"</string> <string name="other_password_manager" msgid="565790221427004141">"其他密碼管理工具"</string> <string name="close_sheet" msgid="1393792015338908262">"閂工作表"</string> diff --git a/packages/CredentialManager/res/values-zh-rTW/strings.xml b/packages/CredentialManager/res/values-zh-rTW/strings.xml index 0d636c24cca2..1fa1bd677a8d 100644 --- a/packages/CredentialManager/res/values-zh-rTW/strings.xml +++ b/packages/CredentialManager/res/values-zh-rTW/strings.xml @@ -8,15 +8,19 @@ <string name="string_save_to_another_place" msgid="7590325934591079193">"儲存至其他位置"</string> <string name="string_use_another_device" msgid="8754514926121520445">"改用其他裝置"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"儲存至其他裝置"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"安全又簡單的登入方式"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"登入帳戶時,你可以使用指紋、人臉或螢幕鎖定功能搭配不重複的密碼金鑰,不必擔心忘記密碼金鑰或遭人竊取。瞭解詳情"</string> - <string name="choose_provider_title" msgid="7245243990139698508">"選擇「<xliff:g id="CREATETYPES">%1$s</xliff:g>」的位置"</string> - <!-- no translation found for create_your_passkeys (8901224153607590596) --> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> + <string name="choose_provider_title" msgid="7245243990139698508">"選擇「<xliff:g id="CREATETYPES">%1$s</xliff:g>」的位置"</string> + <string name="create_your_passkeys" msgid="8901224153607590596">"建立金鑰密碼"</string> <string name="save_your_password" msgid="6597736507991704307">"儲存密碼"</string> <string name="save_your_sign_in_info" msgid="7213978049817076882">"儲存登入資訊"</string> - <!-- no translation found for choose_provider_body (8045759834416308059) --> - <skip /> + <string name="choose_provider_body" msgid="8045759834416308059">"你可以設定預設的密碼管理工具以儲存密碼和密碼金鑰,下次就能更快速登入。"</string> <string name="choose_create_option_passkey_title" msgid="4146408187146573131">"要在「<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>」建立密碼金鑰嗎?"</string> <string name="choose_create_option_password_title" msgid="8812546498357380545">"要將密碼儲存至「<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>」嗎?"</string> <string name="choose_create_option_sign_in_title" msgid="6318246378475961834">"要將登入資訊儲存至「<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>」嗎?"</string> @@ -24,17 +28,12 @@ <string name="passkey" msgid="632353688396759522">"密碼金鑰"</string> <string name="password" msgid="6738570945182936667">"密碼"</string> <string name="sign_ins" msgid="4710739369149469208">"登入資訊"</string> - <!-- no translation found for create_passkey_in_title (2714306562710897785) --> - <skip /> - <!-- no translation found for save_password_to_title (3450480045270186421) --> - <skip /> - <!-- no translation found for save_sign_in_to_title (8328143607671760232) --> - <skip /> - <!-- no translation found for create_passkey_in_other_device_title (6372952459932674632) --> - <skip /> + <string name="create_passkey_in_title" msgid="2714306562710897785">"在以下位置建立密碼金鑰:"</string> + <string name="save_password_to_title" msgid="3450480045270186421">"將密碼儲存到以下位置:"</string> + <string name="save_sign_in_to_title" msgid="8328143607671760232">"將登入資訊儲存到以下位置:"</string> + <string name="create_passkey_in_other_device_title" msgid="6372952459932674632">"要在另一部裝置上建立密碼金鑰嗎?"</string> <string name="use_provider_for_all_title" msgid="4201020195058980757">"要將「<xliff:g id="PROVIDERINFODISPLAYNAME">%1$s</xliff:g>」用於所有的登入資訊嗎?"</string> - <!-- no translation found for use_provider_for_all_description (6560593199974037820) --> - <skip /> + <string name="use_provider_for_all_description" msgid="6560593199974037820">"這個密碼管理工具會儲存你的密碼和密碼金鑰,協助你輕鬆登入。"</string> <string name="set_as_default" msgid="4415328591568654603">"設為預設"</string> <string name="use_once" msgid="9027366575315399714">"單次使用"</string> <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g> 個密碼,<xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g> 個密碼金鑰"</string> diff --git a/packages/CredentialManager/res/values-zu/strings.xml b/packages/CredentialManager/res/values-zu/strings.xml index a35c6d2af737..772104dfbb0c 100644 --- a/packages/CredentialManager/res/values-zu/strings.xml +++ b/packages/CredentialManager/res/values-zu/strings.xml @@ -1,16 +1,21 @@ <?xml version="1.0" encoding="UTF-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <!-- no translation found for app_name (4539824758261855508) --> - <skip /> + <string name="app_name" msgid="4539824758261855508">"Umphathi Wezimfanelo"</string> <string name="string_cancel" msgid="6369133483981306063">"Khansela"</string> <string name="string_continue" msgid="1346732695941131882">"Qhubeka"</string> <string name="string_create_in_another_place" msgid="1033635365843437603">"Sungula kwenye indawo"</string> <string name="string_save_to_another_place" msgid="7590325934591079193">"Londoloza kwenye indawo"</string> <string name="string_use_another_device" msgid="8754514926121520445">"Sebenzisa enye idivayisi"</string> <string name="string_save_to_another_device" msgid="1959562542075194458">"Londoloza kwenye idivayisi"</string> - <string name="passkey_creation_intro_title" msgid="402553911484409884">"Indlela elula yokungena ngemvume ngokuphephile"</string> - <string name="passkey_creation_intro_body" msgid="7493320456005579290">"Sebenzisa isigxivizo somunwe, ubuso noma ukukhiya isikrini ukuze ungene ngemvume ngokhiye wokudlula oyingqayizivele ongenakulibaleka noma owebiwe. Funda kabanzi"</string> + <!-- no translation found for passkey_creation_intro_title (4251037543787718844) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_password (312712407571126228) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_fingerprint (691816235541508203) --> + <skip /> + <!-- no translation found for passkey_creation_intro_body_device (477121861162321129) --> + <skip /> <string name="choose_provider_title" msgid="7245243990139698508">"Khetha lapho onga-<xliff:g id="CREATETYPES">%1$s</xliff:g>"</string> <!-- no translation found for create_your_passkeys (8901224153607590596) --> <skip /> @@ -41,8 +46,7 @@ <string name="more_options_usage_passwords_passkeys" msgid="4794903978126339473">"Amaphasiwedi angu-<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>, okhiye bokudlula abangu-<xliff:g id="PASSKEYSNUMBER">%2$s</xliff:g>"</string> <string name="more_options_usage_passwords" msgid="1632047277723187813">"Amaphasiwedi angu-<xliff:g id="PASSWORDSNUMBER">%1$s</xliff:g>"</string> <string name="more_options_usage_passkeys" msgid="5390320437243042237">"Okhiye bokudlula abangu-<xliff:g id="PASSKEYSNUMBER">%1$s</xliff:g>"</string> - <!-- no translation found for passkey_before_subtitle (2448119456208647444) --> - <skip /> + <string name="passkey_before_subtitle" msgid="2448119456208647444">"Ukhiye wokudlula"</string> <string name="another_device" msgid="5147276802037801217">"Enye idivayisi"</string> <string name="other_password_manager" msgid="565790221427004141">"Abanye abaphathi bephasiwedi"</string> <string name="close_sheet" msgid="1393792015338908262">"Vala ishidi"</string> diff --git a/packages/CredentialManager/res/values/strings.xml b/packages/CredentialManager/res/values/strings.xml index 870d9832ca0b..a3ebf1efbb51 100644 --- a/packages/CredentialManager/res/values/strings.xml +++ b/packages/CredentialManager/res/values/strings.xml @@ -80,6 +80,8 @@ <string name="close_sheet">"Close sheet"</string> <!-- Spoken content description of the back arrow button. --> <string name="accessibility_back_arrow_button">"Go back to the previous page"</string> + <!-- Spoken content description of the close button. --> + <string name="accessibility_close_button">"Close the Credential Manager action suggestion appearing at the bottom of the screen"</string> <!-- Strings for the get flow. --> <!-- This appears as the title of the modal bottom sheet asking for user confirmation to use the single previously saved passkey to sign in to the app. [CHAR LIMIT=200] --> diff --git a/packages/CredentialManager/src/com/android/credentialmanager/CredentialManagerRepo.kt b/packages/CredentialManager/src/com/android/credentialmanager/CredentialManagerRepo.kt index 2780c3cdca79..4faf00c43d34 100644 --- a/packages/CredentialManager/src/com/android/credentialmanager/CredentialManagerRepo.kt +++ b/packages/CredentialManager/src/com/android/credentialmanager/CredentialManagerRepo.kt @@ -44,7 +44,6 @@ import com.android.credentialmanager.createflow.CreateCredentialUiState import com.android.credentialmanager.createflow.EnabledProviderInfo import com.android.credentialmanager.createflow.RemoteInfo import com.android.credentialmanager.getflow.GetCredentialUiState -import com.android.credentialmanager.getflow.GetScreenState import com.android.credentialmanager.jetpack.developer.CreatePasswordRequest.Companion.toBundle import com.android.credentialmanager.jetpack.developer.CreatePublicKeyCredentialRequest import com.android.credentialmanager.jetpack.developer.PublicKeyCredential.Companion.TYPE_PUBLIC_KEY_CREDENTIAL @@ -64,7 +63,7 @@ class CredentialManagerRepo( requestInfo = intent.extras?.getParcelable( RequestInfo.EXTRA_REQUEST_INFO, RequestInfo::class.java - ) ?: testCreatePasskeyRequestInfo() + ) ?: testGetRequestInfo() providerEnabledList = when (requestInfo.type) { RequestInfo.TYPE_CREATE -> @@ -124,11 +123,9 @@ class CredentialManagerRepo( val providerEnabledList = GetFlowUtils.toProviderList( // TODO: handle runtime cast error providerEnabledList as List<GetCredentialProviderData>, context) - // TODO: covert from real requestInfo - val requestDisplayInfo = com.android.credentialmanager.getflow.RequestDisplayInfo("the app") + val requestDisplayInfo = GetFlowUtils.toRequestDisplayInfo(requestInfo) return GetCredentialUiState( providerEnabledList, - GetScreenState.PRIMARY_SELECTION, requestDisplayInfo, ) } @@ -248,12 +245,10 @@ class CredentialManagerRepo( listOf( newActionEntry( "key3", "subkey-1", TYPE_PASSWORD_CREDENTIAL, - Icon.createWithResource(context, R.drawable.ic_manage_accounts), "Open Google Password Manager", "elisa.beckett@gmail.com" ), newActionEntry( "key3", "subkey-2", TYPE_PASSWORD_CREDENTIAL, - Icon.createWithResource(context, R.drawable.ic_manage_accounts), "Open Google Password Manager", "beckett-family@gmail.com" ), ) @@ -278,7 +273,6 @@ class CredentialManagerRepo( listOf( newActionEntry( "key3", "subkey-1", TYPE_PASSWORD_CREDENTIAL, - Icon.createWithResource(context, R.drawable.ic_face), "Open Enpass" ), ) @@ -290,7 +284,6 @@ class CredentialManagerRepo( key: String, subkey: String, credentialType: String, - icon: Icon, text: String, subtext: String? = null, ): Entry { @@ -298,7 +291,7 @@ class CredentialManagerRepo( Entry.CREDENTIAL_MANAGER_ENTRY_URI, SliceSpec(credentialType, 1) ).addText( text, null, listOf(Entry.HINT_ACTION_TITLE) - ).addIcon(icon, null, listOf(Entry.HINT_ACTION_ICON)) + ) if (subtext != null) { slice.addText(subtext, null, listOf(Entry.HINT_ACTION_SUBTEXT)) } @@ -518,7 +511,7 @@ class CredentialManagerRepo( GetCredentialRequest.Builder() .addGetCredentialOption( GetCredentialOption( - TYPE_PUBLIC_KEY_CREDENTIAL, Bundle(), /*requireSystemProvider=*/ false) + TYPE_PUBLIC_KEY_CREDENTIAL, Bundle(), Bundle(), /*requireSystemProvider=*/ false) ) .build(), /*isFirstUsage=*/false, diff --git a/packages/CredentialManager/src/com/android/credentialmanager/DataConverter.kt b/packages/CredentialManager/src/com/android/credentialmanager/DataConverter.kt index 0d7e81984ead..56fbf6632dc5 100644 --- a/packages/CredentialManager/src/com/android/credentialmanager/DataConverter.kt +++ b/packages/CredentialManager/src/com/android/credentialmanager/DataConverter.kt @@ -67,7 +67,8 @@ class GetFlowUtils { .getPackageInfo(packageName!!, PackageManager.PackageInfoFlags.of(0)) val providerDisplayName = pkgInfo.applicationInfo.loadLabel(packageManager).toString() - // TODO: decide what to do when failed to load a provider icon + // TODO: get the provider icon from the service + // and decide what to do when failed to load a provider icon val providerIcon = pkgInfo.applicationInfo.loadIcon(packageManager)!! ProviderInfo( id = it.providerFlattenedComponentName, @@ -83,11 +84,19 @@ class GetFlowUtils { it.authenticationEntry), remoteEntry = getRemoteEntry(it.providerFlattenedComponentName, it.remoteEntry), actionEntryList = getActionEntryList( - it.providerFlattenedComponentName, it.actionChips, context), + it.providerFlattenedComponentName, it.actionChips, providerIcon), ) } } + fun toRequestDisplayInfo( + requestInfo: RequestInfo, + ): com.android.credentialmanager.getflow.RequestDisplayInfo { + return com.android.credentialmanager.getflow.RequestDisplayInfo( + appDomainName = requestInfo.appPackageName + ) + } + /* From service data structure to UI credential entry list representation. */ private fun getCredentialOptionInfoList( @@ -111,7 +120,7 @@ class GetFlowUtils { displayName = credentialEntryUi.userDisplayName?.toString(), // TODO: proper fallback icon = credentialEntryUi.entryIcon?.loadDrawable(context) - ?: context.getDrawable(R.drawable.ic_passkey)!!, + ?: context.getDrawable(R.drawable.ic_other_sign_in)!!, lastUsedTimeMillis = credentialEntryUi.lastUsedTimeMillis, ) } @@ -156,7 +165,7 @@ class GetFlowUtils { private fun getActionEntryList( providerId: String, actionEntries: List<Entry>, - context: Context, + providerIcon: Drawable, ): List<ActionEntryInfo> { return actionEntries.map { val actionEntryUi = ActionUi.fromSlice(it.slice) @@ -169,7 +178,7 @@ class GetFlowUtils { fillInIntent = it.frameworkExtrasIntent, title = actionEntryUi.text.toString(), // TODO: gracefully fail - icon = actionEntryUi.icon.loadDrawable(context)!!, + icon = providerIcon, subTitle = actionEntryUi.subtext?.toString(), ) } diff --git a/packages/CredentialManager/src/com/android/credentialmanager/createflow/CreateCredentialComponents.kt b/packages/CredentialManager/src/com/android/credentialmanager/createflow/CreateCredentialComponents.kt index b417b385ada7..c26fac8895ab 100644 --- a/packages/CredentialManager/src/com/android/credentialmanager/createflow/CreateCredentialComponents.kt +++ b/packages/CredentialManager/src/com/android/credentialmanager/createflow/CreateCredentialComponents.kt @@ -313,7 +313,7 @@ fun ProviderSelectionCard( } } } - if (disabledProviderList != null) { + if (disabledProviderList != null && disabledProviderList.isNotEmpty()) { item { MoreOptionsDisabledProvidersRow( disabledProviders = disabledProviderList, @@ -431,14 +431,12 @@ fun MoreOptionsSelectionCard( } } } - if (disabledProviderList != null) { - item { - MoreOptionsDisabledProvidersRow( - disabledProviders = disabledProviderList, - onDisabledPasswordManagerSelected = - onDisabledPasswordManagerSelected, - ) - } + item { + MoreOptionsDisabledProvidersRow( + disabledProviders = disabledProviderList, + onDisabledPasswordManagerSelected = + onDisabledPasswordManagerSelected, + ) } // TODO: handle the error situation that if multiple remoteInfos exists enabledProviderList.forEach { @@ -748,7 +746,7 @@ fun PrimaryCreateOptionRow( }, contentDescription = null, tint = LocalAndroidColorScheme.current.colorAccentPrimaryVariant, - modifier = Modifier.padding(horizontal = 18.dp).size(32.dp) + modifier = Modifier.padding(start = 10.dp).size(32.dp) ) }, label = { @@ -759,7 +757,7 @@ fun PrimaryCreateOptionRow( TextOnSurfaceVariant( text = requestDisplayInfo.title, style = MaterialTheme.typography.titleLarge, - modifier = Modifier.padding(top = 16.dp), + modifier = Modifier.padding(top = 16.dp, start = 5.dp), ) TextSecondary( text = if (requestDisplayInfo.subtitle != null) { @@ -770,27 +768,27 @@ fun PrimaryCreateOptionRow( stringResource(R.string.passkey_before_subtitle) }, style = MaterialTheme.typography.bodyMedium, - modifier = Modifier.padding(bottom = 16.dp), + modifier = Modifier.padding(bottom = 16.dp, start = 5.dp), ) } TYPE_PASSWORD_CREDENTIAL -> { TextOnSurfaceVariant( text = requestDisplayInfo.title, style = MaterialTheme.typography.titleLarge, - modifier = Modifier.padding(top = 16.dp), + modifier = Modifier.padding(top = 16.dp, start = 5.dp), ) TextSecondary( // This subtitle would never be null for create password text = requestDisplayInfo.subtitle ?: "", style = MaterialTheme.typography.bodyMedium, - modifier = Modifier.padding(bottom = 16.dp), + modifier = Modifier.padding(bottom = 16.dp, start = 5.dp), ) } else -> { TextOnSurfaceVariant( text = requestDisplayInfo.title, style = MaterialTheme.typography.titleLarge, - modifier = Modifier.padding(top = 16.dp, bottom = 16.dp), + modifier = Modifier.padding(top = 16.dp, bottom = 16.dp, start = 5.dp), ) } } @@ -810,7 +808,7 @@ fun MoreOptionsInfoRow( onClick = onOptionSelected, icon = { Image( - modifier = Modifier.padding(horizontal = 16.dp).size(32.dp), + modifier = Modifier.padding(start = 10.dp).size(32.dp), bitmap = providerInfo.icon.toBitmap().asImageBitmap(), contentDescription = null ) @@ -820,12 +818,18 @@ fun MoreOptionsInfoRow( TextOnSurfaceVariant( text = providerInfo.displayName, style = MaterialTheme.typography.titleLarge, - modifier = Modifier.padding(top = 16.dp), + modifier = Modifier.padding(top = 16.dp, start = 5.dp), ) if (createOptionInfo.userProviderDisplayName != null) { TextSecondary( text = createOptionInfo.userProviderDisplayName, style = MaterialTheme.typography.bodyMedium, + // TODO: update the logic here for the case there is only total count + modifier = if ( + createOptionInfo.passwordCount != null || + createOptionInfo.passkeyCount != null + ) Modifier.padding(start = 5.dp) else Modifier + .padding(bottom = 16.dp, start = 5.dp), ) } if (createOptionInfo.passwordCount != null && @@ -839,7 +843,7 @@ fun MoreOptionsInfoRow( createOptionInfo.passkeyCount ), style = MaterialTheme.typography.bodyMedium, - modifier = Modifier.padding(bottom = 16.dp), + modifier = Modifier.padding(bottom = 16.dp, start = 5.dp), ) } else if (createOptionInfo.passwordCount != null) { TextSecondary( @@ -849,7 +853,7 @@ fun MoreOptionsInfoRow( createOptionInfo.passwordCount ), style = MaterialTheme.typography.bodyMedium, - modifier = Modifier.padding(bottom = 16.dp), + modifier = Modifier.padding(bottom = 16.dp, start = 5.dp), ) } else if (createOptionInfo.passkeyCount != null) { TextSecondary( @@ -859,7 +863,7 @@ fun MoreOptionsInfoRow( createOptionInfo.passkeyCount ), style = MaterialTheme.typography.bodyMedium, - modifier = Modifier.padding(bottom = 16.dp), + modifier = Modifier.padding(bottom = 16.dp, start = 5.dp), ) } else if (createOptionInfo.totalCredentialCount != null) { // TODO: Handle the case when there is total count @@ -873,34 +877,36 @@ fun MoreOptionsInfoRow( @OptIn(ExperimentalMaterial3Api::class) @Composable fun MoreOptionsDisabledProvidersRow( - disabledProviders: List<ProviderInfo>, + disabledProviders: List<ProviderInfo>?, onDisabledPasswordManagerSelected: () -> Unit, ) { - Entry( - onClick = onDisabledPasswordManagerSelected, - icon = { - Icon( - Icons.Filled.Add, - contentDescription = null, - modifier = Modifier.padding(start = 16.dp) - ) - }, - label = { - Column() { - TextOnSurfaceVariant( - text = stringResource(R.string.other_password_manager), - style = MaterialTheme.typography.titleLarge, - modifier = Modifier.padding(top = 16.dp, start = 16.dp), - ) - // TODO: Update the subtitle once design is confirmed - TextSecondary( - text = disabledProviders.joinToString(separator = ", ") { it.displayName }, - style = MaterialTheme.typography.bodyMedium, - modifier = Modifier.padding(bottom = 16.dp, start = 16.dp), + if (disabledProviders != null && disabledProviders.isNotEmpty()) { + Entry( + onClick = onDisabledPasswordManagerSelected, + icon = { + Icon( + Icons.Filled.Add, + contentDescription = null, + modifier = Modifier.padding(start = 16.dp) ) + }, + label = { + Column() { + TextOnSurfaceVariant( + text = stringResource(R.string.other_password_manager), + style = MaterialTheme.typography.titleLarge, + modifier = Modifier.padding(top = 16.dp, start = 5.dp), + ) + // TODO: Update the subtitle once design is confirmed + TextSecondary( + text = disabledProviders.joinToString(separator = ", ") { it.displayName }, + style = MaterialTheme.typography.bodyMedium, + modifier = Modifier.padding(bottom = 16.dp, start = 5.dp), + ) + } } - } - ) + ) + } } @OptIn(ExperimentalMaterial3Api::class) diff --git a/packages/CredentialManager/src/com/android/credentialmanager/getflow/GetCredentialComponents.kt b/packages/CredentialManager/src/com/android/credentialmanager/getflow/GetCredentialComponents.kt index d6d71220e943..619f5a37d45b 100644 --- a/packages/CredentialManager/src/com/android/credentialmanager/getflow/GetCredentialComponents.kt +++ b/packages/CredentialManager/src/com/android/credentialmanager/getflow/GetCredentialComponents.kt @@ -16,6 +16,7 @@ package com.android.credentialmanager.getflow +import android.credentials.Credential import android.text.TextUtils import androidx.activity.compose.ManagedActivityResultLauncher import androidx.activity.result.ActivityResult @@ -32,15 +33,20 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ArrowBack +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.outlined.Lock import androidx.compose.material3.Divider import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Snackbar +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment @@ -65,6 +71,7 @@ import com.android.credentialmanager.common.ui.ContainerCard import com.android.credentialmanager.common.ui.TransparentBackgroundEntry import com.android.credentialmanager.jetpack.developer.PublicKeyCredential import com.android.credentialmanager.ui.theme.EntryShape +import com.android.credentialmanager.ui.theme.LocalAndroidColorScheme @Composable fun GetCredentialScreen( @@ -75,39 +82,50 @@ fun GetCredentialScreen( initialValue = ModalBottomSheetValue.Expanded, skipHalfExpanded = true ) - ModalBottomSheetLayout( - sheetBackgroundColor = MaterialTheme.colorScheme.surface, - modifier = Modifier.background(Color.Transparent), - sheetState = state, - sheetContent = { - val uiState = viewModel.uiState - if (!uiState.hidden) { - when (uiState.currentScreenState) { - GetScreenState.PRIMARY_SELECTION -> PrimarySelectionCard( - requestDisplayInfo = uiState.requestDisplayInfo, - providerDisplayInfo = uiState.providerDisplayInfo, - onEntrySelected = viewModel::onEntrySelected, - onCancel = viewModel::onCancel, - onMoreOptionSelected = viewModel::onMoreOptionSelected, - ) - GetScreenState.ALL_SIGN_IN_OPTIONS -> AllSignInOptionCard( - providerInfoList = uiState.providerInfoList, - providerDisplayInfo = uiState.providerDisplayInfo, - onEntrySelected = viewModel::onEntrySelected, - onBackButtonClicked = viewModel::onBackToPrimarySelectionScreen, - ) + val uiState = viewModel.uiState + if (uiState.currentScreenState != GetScreenState.REMOTE_ONLY) { + ModalBottomSheetLayout( + sheetBackgroundColor = MaterialTheme.colorScheme.surface, + modifier = Modifier.background(Color.Transparent), + sheetState = state, + sheetContent = { + // TODO: hide UI at top level + if (!uiState.hidden) { + if (uiState.currentScreenState == GetScreenState.PRIMARY_SELECTION) { + PrimarySelectionCard( + requestDisplayInfo = uiState.requestDisplayInfo, + providerDisplayInfo = uiState.providerDisplayInfo, + onEntrySelected = viewModel::onEntrySelected, + onCancel = viewModel::onCancel, + onMoreOptionSelected = viewModel::onMoreOptionSelected, + ) + } else { + AllSignInOptionCard( + providerInfoList = uiState.providerInfoList, + providerDisplayInfo = uiState.providerDisplayInfo, + onEntrySelected = viewModel::onEntrySelected, + onBackButtonClicked = viewModel::onBackToPrimarySelectionScreen, + onCancel = viewModel::onCancel, + isNoAccount = uiState.isNoAccount, + ) + } + } else if (uiState.selectedEntry != null && !uiState.providerActivityPending) { + viewModel.launchProviderUi(providerActivityLauncher) } - } else if (uiState.selectedEntry != null && !uiState.providerActivityPending) { - viewModel.launchProviderUi(providerActivityLauncher) + }, + scrimColor = MaterialTheme.colorScheme.scrim.copy(alpha = 0.8f), + sheetShape = EntryShape.TopRoundedCorner, + ) {} + LaunchedEffect(state.currentValue) { + if (state.currentValue == ModalBottomSheetValue.Hidden) { + viewModel.onCancel() } - }, - scrimColor = MaterialTheme.colorScheme.scrim.copy(alpha = 0.8f), - sheetShape = EntryShape.TopRoundedCorner, - ) {} - LaunchedEffect(state.currentValue) { - if (state.currentValue == ModalBottomSheetValue.Hidden) { - viewModel.onCancel() } + } else { + SnackBarScreen( + onClick = viewModel::onMoreOptionOnSnackBarSelected, + onCancel = viewModel::onCancel, + ) } } @@ -173,7 +191,7 @@ fun PrimarySelectionCard( color = Color.Transparent ) Row( - horizontalArrangement = Arrangement.Start, + horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp) ) { CancelButton(stringResource(R.string.get_dialog_button_label_no_thanks), onCancel) @@ -195,6 +213,8 @@ fun AllSignInOptionCard( providerDisplayInfo: ProviderDisplayInfo, onEntrySelected: (EntryInfo) -> Unit, onBackButtonClicked: () -> Unit, + onCancel: () -> Unit, + isNoAccount: Boolean, ) { val sortedUserNameToCredentialEntryList = providerDisplayInfo.sortedUserNameToCredentialEntryList @@ -212,7 +232,7 @@ fun AllSignInOptionCard( ) }, navigationIcon = { - IconButton(onClick = onBackButtonClicked) { + IconButton(onClick = if (isNoAccount) onCancel else onBackButtonClicked) { Icon( Icons.Filled.ArrowBack, contentDescription = stringResource( @@ -405,11 +425,12 @@ fun CredentialEntryRow( Entry( onClick = { onEntrySelected(credentialEntryInfo) }, icon = { - Image( + Icon( modifier = Modifier.padding(start = 10.dp).size(32.dp), bitmap = credentialEntryInfo.icon.toBitmap().asImageBitmap(), // TODO: add description. - contentDescription = "" + contentDescription = "", + tint = LocalAndroidColorScheme.current.colorAccentPrimaryVariant, ) }, label = { @@ -418,19 +439,24 @@ fun CredentialEntryRow( TextOnSurfaceVariant( text = credentialEntryInfo.userName, style = MaterialTheme.typography.titleLarge, - modifier = Modifier.padding(top = 16.dp) + modifier = Modifier.padding(top = 16.dp, start = 5.dp) ) TextSecondary( - text = - if (TextUtils.isEmpty(credentialEntryInfo.displayName)) - credentialEntryInfo.credentialTypeDisplayName - else - credentialEntryInfo.credentialTypeDisplayName + - stringResource( - R.string.get_dialog_sign_in_type_username_separator) + - credentialEntryInfo.displayName, + text = if ( + credentialEntryInfo.credentialType == Credential.TYPE_PASSWORD_CREDENTIAL) { + "••••••••••••" + } else { + if (TextUtils.isEmpty(credentialEntryInfo.displayName)) + credentialEntryInfo.credentialTypeDisplayName + else + credentialEntryInfo.credentialTypeDisplayName + + stringResource( + R.string.get_dialog_sign_in_type_username_separator + ) + + credentialEntryInfo.displayName + }, style = MaterialTheme.typography.bodyMedium, - modifier = Modifier.padding(bottom = 16.dp) + modifier = Modifier.padding(bottom = 16.dp, start = 5.dp) ) } } @@ -454,17 +480,27 @@ fun AuthenticationEntryRow( ) }, label = { - Column() { - // TODO: fix the text values. - TextOnSurfaceVariant( - text = authenticationEntryInfo.title, - style = MaterialTheme.typography.titleLarge, - modifier = Modifier.padding(top = 16.dp) - ) - TextSecondary( - text = stringResource(R.string.locked_credential_entry_label_subtext), - style = MaterialTheme.typography.bodyMedium, - modifier = Modifier.padding(bottom = 16.dp) + Row( + horizontalArrangement = Arrangement.SpaceBetween, + modifier = Modifier.fillMaxWidth().padding(horizontal = 5.dp), + ) { + Column() { + // TODO: fix the text values. + TextOnSurfaceVariant( + text = authenticationEntryInfo.title, + style = MaterialTheme.typography.titleLarge, + modifier = Modifier.padding(top = 16.dp) + ) + TextSecondary( + text = stringResource(R.string.locked_credential_entry_label_subtext), + style = MaterialTheme.typography.bodyMedium, + modifier = Modifier.padding(bottom = 16.dp) + ) + } + Icon( + Icons.Outlined.Lock, + null, + Modifier.align(alignment = Alignment.CenterVertically).padding(end = 10.dp), ) } } @@ -491,11 +527,13 @@ fun ActionEntryRow( TextOnSurfaceVariant( text = actionEntryInfo.title, style = MaterialTheme.typography.titleLarge, + modifier = Modifier.padding(start = 5.dp), ) if (actionEntryInfo.subTitle != null) { TextSecondary( text = actionEntryInfo.subTitle, style = MaterialTheme.typography.bodyMedium, + modifier = Modifier.padding(start = 5.dp), ) } } @@ -518,3 +556,37 @@ fun SignInAnotherWayRow(onSelect: () -> Unit) { } ) } + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun SnackBarScreen( + onClick: (Boolean) -> Unit, + onCancel: () -> Unit, +) { + // TODO: Change the height, width and position according to the design + Snackbar ( + modifier = Modifier.padding(horizontal = 80.dp).padding(top = 700.dp), + shape = EntryShape.FullMediumRoundedCorner, + containerColor = LocalAndroidColorScheme.current.colorBackground, + contentColor = LocalAndroidColorScheme.current.colorAccentPrimaryVariant, + ) { + Row( + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + TextButton( + onClick = {onClick(true)}, + ) { + Text(text = stringResource(R.string.get_dialog_use_saved_passkey_for)) + } + IconButton(onClick = onCancel) { + Icon( + Icons.Filled.Close, + contentDescription = stringResource( + R.string.accessibility_close_button + ) + ) + } + } + } +}
\ No newline at end of file diff --git a/packages/CredentialManager/src/com/android/credentialmanager/getflow/GetCredentialViewModel.kt b/packages/CredentialManager/src/com/android/credentialmanager/getflow/GetCredentialViewModel.kt index 7b80124d618c..c182397b8aec 100644 --- a/packages/CredentialManager/src/com/android/credentialmanager/getflow/GetCredentialViewModel.kt +++ b/packages/CredentialManager/src/com/android/credentialmanager/getflow/GetCredentialViewModel.kt @@ -36,12 +36,13 @@ import com.android.internal.util.Preconditions data class GetCredentialUiState( val providerInfoList: List<ProviderInfo>, - val currentScreenState: GetScreenState, val requestDisplayInfo: RequestDisplayInfo, + val currentScreenState: GetScreenState = toGetScreenState(providerInfoList), val providerDisplayInfo: ProviderDisplayInfo = toProviderDisplayInfo(providerInfoList), val selectedEntry: EntryInfo? = null, val hidden: Boolean = false, val providerActivityPending: Boolean = false, + val isNoAccount: Boolean = false, ) class GetCredentialViewModel( @@ -127,6 +128,14 @@ class GetCredentialViewModel( ) } + fun onMoreOptionOnSnackBarSelected(isNoAccount: Boolean) { + Log.d("Account Selector", "More Option on snackBar selected") + uiState = uiState.copy( + currentScreenState = GetScreenState.ALL_SIGN_IN_OPTIONS, + isNoAccount = isNoAccount, + ) + } + fun onBackToPrimarySelectionScreen() { uiState = uiState.copy( currentScreenState = GetScreenState.PRIMARY_SELECTION @@ -192,9 +201,36 @@ private fun toProviderDisplayInfo( ) } +private fun toGetScreenState( + providerInfoList: List<ProviderInfo> +): GetScreenState { + var noLocalAccount = true + var remoteInfo: RemoteEntryInfo? = null + providerInfoList.forEach{providerInfo -> if ( + providerInfo.credentialEntryList.isNotEmpty() || providerInfo.authenticationEntry != null + ) { noLocalAccount = false } + // TODO: handle the error situation that if multiple remoteInfos exists + if (providerInfo.remoteEntry != null) { + remoteInfo = providerInfo.remoteEntry + } + } + + return if (noLocalAccount && remoteInfo != null) + GetScreenState.REMOTE_ONLY else GetScreenState.PRIMARY_SELECTION +} + internal class CredentialEntryInfoComparator : Comparator<CredentialEntryInfo> { override fun compare(p0: CredentialEntryInfo, p1: CredentialEntryInfo): Int { - // First order by last used timestamp + // First prefer passkey type for its security benefits + if (p0.credentialType != p1.credentialType) { + if (PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL == p0.credentialType) { + return -1 + } else if (PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL == p1.credentialType) { + return 1 + } + } + + // Then order by last used timestamp if (p0.lastUsedTimeMillis != null && p1.lastUsedTimeMillis != null) { if (p0.lastUsedTimeMillis < p1.lastUsedTimeMillis) { return 1 @@ -206,15 +242,6 @@ internal class CredentialEntryInfoComparator : Comparator<CredentialEntryInfo> { } else if (p1.lastUsedTimeMillis != null && p1.lastUsedTimeMillis > 0) { return 1 } - - // Then prefer passkey type for its security benefits - if (p0.credentialType != p1.credentialType) { - if (PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL == p0.credentialType) { - return -1 - } else if (PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL == p1.credentialType) { - return 1 - } - } return 0 } }
\ No newline at end of file diff --git a/packages/CredentialManager/src/com/android/credentialmanager/getflow/GetModel.kt b/packages/CredentialManager/src/com/android/credentialmanager/getflow/GetModel.kt index 0c3baffd8864..3a2a73801d8e 100644 --- a/packages/CredentialManager/src/com/android/credentialmanager/getflow/GetModel.kt +++ b/packages/CredentialManager/src/com/android/credentialmanager/getflow/GetModel.kt @@ -120,4 +120,6 @@ enum class GetScreenState { PRIMARY_SELECTION, /** The secondary credential selection page, where all sign-in options are listed. */ ALL_SIGN_IN_OPTIONS, + /** The snackbar only page when there's no account but only a remoteEntry. */ + REMOTE_ONLY, } diff --git a/packages/CredentialManager/src/com/android/credentialmanager/jetpack/developer/GetCredentialOption.kt b/packages/CredentialManager/src/com/android/credentialmanager/jetpack/developer/GetCredentialOption.kt index eb65241ed4df..ef48a778a007 100644 --- a/packages/CredentialManager/src/com/android/credentialmanager/jetpack/developer/GetCredentialOption.kt +++ b/packages/CredentialManager/src/com/android/credentialmanager/jetpack/developer/GetCredentialOption.kt @@ -28,9 +28,9 @@ import android.os.Bundle * otherwise */ open class GetCredentialOption( - val type: String, - val data: Bundle, - val requireSystemProvider: Boolean, + val type: String, + val data: Bundle, + val requireSystemProvider: Boolean, ) { companion object { @JvmStatic @@ -38,14 +38,20 @@ open class GetCredentialOption( return try { when (from.type) { Credential.TYPE_PASSWORD_CREDENTIAL -> - GetPasswordOption.createFrom(from.data) + GetPasswordOption.createFrom(from.credentialRetrievalData) PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL -> - GetPublicKeyCredentialBaseOption.createFrom(from.data) + GetPublicKeyCredentialBaseOption.createFrom(from.credentialRetrievalData) else -> - GetCredentialOption(from.type, from.data, from.requireSystemProvider()) + GetCredentialOption( + from.type, from.credentialRetrievalData, from.requireSystemProvider() + ) } } catch (e: FrameworkClassParsingException) { - GetCredentialOption(from.type, from.data, from.requireSystemProvider()) + GetCredentialOption( + from.type, + from.credentialRetrievalData, + from.requireSystemProvider() + ) } } } diff --git a/packages/CredentialManager/src/com/android/credentialmanager/jetpack/provider/ActionUi.kt b/packages/CredentialManager/src/com/android/credentialmanager/jetpack/provider/ActionUi.kt index 1e639fe6bd55..19c5c2dfa4fe 100644 --- a/packages/CredentialManager/src/com/android/credentialmanager/jetpack/provider/ActionUi.kt +++ b/packages/CredentialManager/src/com/android/credentialmanager/jetpack/provider/ActionUi.kt @@ -18,7 +18,6 @@ package com.android.credentialmanager.jetpack.provider import android.app.slice.Slice import android.credentials.ui.Entry -import android.graphics.drawable.Icon /** * UI representation for a credential entry used during the get credential flow. @@ -26,28 +25,24 @@ import android.graphics.drawable.Icon * TODO: move to jetpack. */ class ActionUi( - val icon: Icon, val text: CharSequence, val subtext: CharSequence?, ) { companion object { fun fromSlice(slice: Slice): ActionUi { - var icon: Icon? = null var text: CharSequence? = null var subtext: CharSequence? = null val items = slice.items items.forEach { - if (it.hasHint(Entry.HINT_ACTION_ICON)) { - icon = it.icon - } else if (it.hasHint(Entry.HINT_ACTION_TITLE)) { + if (it.hasHint(Entry.HINT_ACTION_TITLE)) { text = it.text } else if (it.hasHint(Entry.HINT_ACTION_SUBTEXT)) { subtext = it.text } } // TODO: fail NPE more elegantly. - return ActionUi(icon!!, text!!, subtext) + return ActionUi(text!!, subtext) } } } diff --git a/packages/InputDevices/res/raw/keyboard_layout_english_us_intl.kcm b/packages/InputDevices/res/raw/keyboard_layout_english_us_intl.kcm index 66c1c9878fc6..aa31493e9a02 100644 --- a/packages/InputDevices/res/raw/keyboard_layout_english_us_intl.kcm +++ b/packages/InputDevices/res/raw/keyboard_layout_english_us_intl.kcm @@ -292,10 +292,10 @@ key SEMICOLON { key APOSTROPHE { label: '\'' - base: '\'' - shift: '"' - ralt: '\u0301' - shift+ralt: '\u0308' + base: '\u030D' + shift: '\u030E' + ralt: '\u00B4' + shift+ralt: '\u00A8' } ### ROW 4 diff --git a/packages/PrintSpooler/res/values-ca/strings.xml b/packages/PrintSpooler/res/values-ca/strings.xml index a346cb2c1b2d..4ee4323daebd 100644 --- a/packages/PrintSpooler/res/values-ca/strings.xml +++ b/packages/PrintSpooler/res/values-ca/strings.xml @@ -56,6 +56,7 @@ <string name="print_select_printer" msgid="7388760939873368698">"Selecciona una impressora"</string> <string name="print_forget_printer" msgid="5035287497291910766">"Oblida la impressora"</string> <plurals name="print_search_result_count_utterance" formatted="false" msgid="6997663738361080868"> + <item quantity="many"><xliff:g id="COUNT_1">%1$s</xliff:g> printers found</item> <item quantity="other">S\'han trobat <xliff:g id="COUNT_1">%1$s</xliff:g> impressores</item> <item quantity="one">S\'ha trobat <xliff:g id="COUNT_0">%1$s</xliff:g> impressora</item> </plurals> @@ -76,6 +77,7 @@ <string name="disabled_services_title" msgid="7313253167968363211">"Serveis desactivats"</string> <string name="all_services_title" msgid="5578662754874906455">"Tots els serveis"</string> <plurals name="print_services_recommendation_subtitle" formatted="false" msgid="5678487708807185138"> + <item quantity="many">Install to discover <xliff:g id="COUNT_1">%1$s</xliff:g> printers</item> <item quantity="other">Instal·la\'l per detectar <xliff:g id="COUNT_1">%1$s</xliff:g> impressores</item> <item quantity="one">Instal·la\'l per detectar <xliff:g id="COUNT_0">%1$s</xliff:g> impressora</item> </plurals> diff --git a/packages/PrintSpooler/res/values-iw/strings.xml b/packages/PrintSpooler/res/values-iw/strings.xml index 2ed8b7f1b0c5..4c93df72edb9 100644 --- a/packages/PrintSpooler/res/values-iw/strings.xml +++ b/packages/PrintSpooler/res/values-iw/strings.xml @@ -56,10 +56,9 @@ <string name="print_select_printer" msgid="7388760939873368698">"בחירת מדפסת"</string> <string name="print_forget_printer" msgid="5035287497291910766">"לשכוח את המדפסת"</string> <plurals name="print_search_result_count_utterance" formatted="false" msgid="6997663738361080868"> + <item quantity="one">נמצאו <xliff:g id="COUNT_1">%1$s</xliff:g> מדפסות</item> <item quantity="two">נמצאו <xliff:g id="COUNT_1">%1$s</xliff:g> מדפסות</item> - <item quantity="many">נמצאו <xliff:g id="COUNT_1">%1$s</xliff:g> מדפסות</item> <item quantity="other">נמצאו <xliff:g id="COUNT_1">%1$s</xliff:g> מדפסות</item> - <item quantity="one">נמצאה מדפסת <xliff:g id="COUNT_0">%1$s</xliff:g></item> </plurals> <string name="printer_extended_description_template" msgid="1366699227703381874">"<xliff:g id="PRINT_SERVICE_LABEL">%1$s</xliff:g> - <xliff:g id="PRINTER_DESCRIPTION">%2$s</xliff:g>"</string> <string name="printer_info_desc" msgid="7181988788991581654">"מידע נוסף על המדפסת הזו"</string> @@ -78,10 +77,9 @@ <string name="disabled_services_title" msgid="7313253167968363211">"שירותים מושבתים"</string> <string name="all_services_title" msgid="5578662754874906455">"כל השירותים"</string> <plurals name="print_services_recommendation_subtitle" formatted="false" msgid="5678487708807185138"> + <item quantity="one">יש להתקין כדי לגלות <xliff:g id="COUNT_1">%1$s</xliff:g> מדפסות</item> <item quantity="two">יש להתקין כדי לגלות <xliff:g id="COUNT_1">%1$s</xliff:g> מדפסות</item> - <item quantity="many">יש להתקין כדי לגלות <xliff:g id="COUNT_1">%1$s</xliff:g> מדפסות</item> <item quantity="other">יש להתקין כדי לגלות <xliff:g id="COUNT_1">%1$s</xliff:g> מדפסות</item> - <item quantity="one">יש להתקין כדי לגלות מדפסת אחת (<xliff:g id="COUNT_0">%1$s</xliff:g>)</item> </plurals> <string name="printing_notification_title_template" msgid="295903957762447362">"בתהליך הדפסה של <xliff:g id="PRINT_JOB_NAME">%1$s</xliff:g>"</string> <string name="cancelling_notification_title_template" msgid="1821759594704703197">"המערכת מבטלת את <xliff:g id="PRINT_JOB_NAME">%1$s</xliff:g>"</string> diff --git a/packages/SettingsLib/Spa/gallery/AndroidManifest.xml b/packages/SettingsLib/Spa/gallery/AndroidManifest.xml index 37d6b426c337..d32d65906efb 100644 --- a/packages/SettingsLib/Spa/gallery/AndroidManifest.xml +++ b/packages/SettingsLib/Spa/gallery/AndroidManifest.xml @@ -38,7 +38,6 @@ <provider android:name="com.android.settingslib.spa.search.SpaSearchProvider" android:authorities="com.android.spa.gallery.search.provider" - android:enabled="true" android:exported="false"> </provider> @@ -67,7 +66,6 @@ <provider android:name="com.android.settingslib.spa.debug.DebugProvider" android:authorities="com.android.spa.gallery.debug.provider" - android:enabled="true" android:exported="false"> </provider> diff --git a/packages/SettingsLib/Spa/gallery/src/com/android/settingslib/spa/gallery/GallerySpaEnvironment.kt b/packages/SettingsLib/Spa/gallery/src/com/android/settingslib/spa/gallery/GallerySpaEnvironment.kt index db4990974e23..e54e2764bb40 100644 --- a/packages/SettingsLib/Spa/gallery/src/com/android/settingslib/spa/gallery/GallerySpaEnvironment.kt +++ b/packages/SettingsLib/Spa/gallery/src/com/android/settingslib/spa/gallery/GallerySpaEnvironment.kt @@ -17,7 +17,7 @@ package com.android.settingslib.spa.gallery import android.content.Context -import com.android.settingslib.spa.framework.common.LocalLogger +import com.android.settingslib.spa.debug.DebugLogger import com.android.settingslib.spa.framework.common.SettingsPageProviderRepository import com.android.settingslib.spa.framework.common.SpaEnvironment import com.android.settingslib.spa.framework.common.createSettingsPage @@ -83,7 +83,7 @@ class GallerySpaEnvironment(context: Context) : SpaEnvironment(context) { ) } - override val logger = LocalLogger() + override val logger = DebugLogger() override val browseActivityClass = GalleryMainActivity::class.java override val sliceBroadcastReceiverClass = SpaSliceBroadcastReceiver::class.java diff --git a/packages/SettingsLib/Spa/screenshot/Android.bp b/packages/SettingsLib/Spa/screenshot/Android.bp new file mode 100644 index 000000000000..4e6b646da819 --- /dev/null +++ b/packages/SettingsLib/Spa/screenshot/Android.bp @@ -0,0 +1,41 @@ +// +// 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 { + default_applicable_licenses: ["frameworks_base_license"], +} + +android_test { + name: "SpaScreenshotTests", + test_suites: ["device-tests"], + + asset_dirs: ["assets"], + + srcs: ["src/**/*.kt"], + + certificate: "platform", + + static_libs: [ + "SpaLib", + "SpaLibTestUtils", + "androidx.compose.runtime_runtime", + "androidx.test.ext.junit", + "androidx.test.runner", + "mockito-target-minus-junit4", + "platform-screenshot-diff-core", + ], + kotlincflags: ["-Xjvm-default=all"], +} diff --git a/packages/SettingsLib/Spa/screenshot/AndroidManifest.xml b/packages/SettingsLib/Spa/screenshot/AndroidManifest.xml new file mode 100644 index 000000000000..d59a1542498d --- /dev/null +++ b/packages/SettingsLib/Spa/screenshot/AndroidManifest.xml @@ -0,0 +1,32 @@ +<?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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.settingslib.spa.screenshot"> + + <uses-sdk android:minSdkVersion="21"/> + + <application> + <uses-library android:name="android.test.runner" /> + <activity android:name=".DebugActivity" android:exported="true" /> + </application> + + <instrumentation + android:name="androidx.test.runner.AndroidJUnitRunner" + android:label="Screenshot tests for SpaLib" + android:targetPackage="com.android.settingslib.spa.screenshot"> + </instrumentation> +</manifest> diff --git a/packages/SettingsLib/Spa/screenshot/AndroidTest.xml b/packages/SettingsLib/Spa/screenshot/AndroidTest.xml new file mode 100644 index 000000000000..e0c08e811c46 --- /dev/null +++ b/packages/SettingsLib/Spa/screenshot/AndroidTest.xml @@ -0,0 +1,36 @@ +<!-- + 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 screendiff tests."> + <option name="test-suite-tag" value="apct-instrumentation" /> + <option name="test-suite-tag" value="apct" /> + <target_preparer class="com.android.tradefed.targetprep.DeviceSetup"> + <option name="optimized-property-setting" value="true" /> + </target_preparer> + <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller"> + <option name="cleanup-apks" value="true" /> + <option name="test-file-name" value="SpaScreenshotTests.apk" /> + </target_preparer> + <metrics_collector class="com.android.tradefed.device.metric.FilePullerLogCollector"> + <option name="directory-keys" + value="/data/user/0/com.android.settingslib.spa.screenshot/files/settings_screenshots" /> + <option name="collect-on-run-ended-only" value="true" /> + </metrics_collector> + <test class="com.android.tradefed.testtype.AndroidJUnitTest"> + <option name="package" value="com.android.settingslib.spa.screenshot" /> + <option name="runner" value="androidx.test.runner.AndroidJUnitRunner" /> + </test> +</configuration> diff --git a/packages/SettingsLib/Spa/screenshot/assets/phone/dark_landscape_preference.png b/packages/SettingsLib/Spa/screenshot/assets/phone/dark_landscape_preference.png Binary files differnew file mode 100644 index 000000000000..6086e2d15dd2 --- /dev/null +++ b/packages/SettingsLib/Spa/screenshot/assets/phone/dark_landscape_preference.png diff --git a/packages/SettingsLib/Spa/screenshot/assets/phone/dark_portrait_preference.png b/packages/SettingsLib/Spa/screenshot/assets/phone/dark_portrait_preference.png Binary files differnew file mode 100644 index 000000000000..aa6c5b7cd131 --- /dev/null +++ b/packages/SettingsLib/Spa/screenshot/assets/phone/dark_portrait_preference.png diff --git a/packages/SettingsLib/Spa/screenshot/assets/phone/light_landscape_preference.png b/packages/SettingsLib/Spa/screenshot/assets/phone/light_landscape_preference.png Binary files differnew file mode 100644 index 000000000000..cac990caad63 --- /dev/null +++ b/packages/SettingsLib/Spa/screenshot/assets/phone/light_landscape_preference.png diff --git a/packages/SettingsLib/Spa/screenshot/assets/phone/light_portrait_preference.png b/packages/SettingsLib/Spa/screenshot/assets/phone/light_portrait_preference.png Binary files differnew file mode 100644 index 000000000000..f6298c0b62c4 --- /dev/null +++ b/packages/SettingsLib/Spa/screenshot/assets/phone/light_portrait_preference.png diff --git a/packages/SettingsLib/Spa/screenshot/assets/tablet/dark_landscape_preference.png b/packages/SettingsLib/Spa/screenshot/assets/tablet/dark_landscape_preference.png Binary files differnew file mode 100644 index 000000000000..9391eeb01e74 --- /dev/null +++ b/packages/SettingsLib/Spa/screenshot/assets/tablet/dark_landscape_preference.png diff --git a/packages/SettingsLib/Spa/screenshot/assets/tablet/dark_portrait_preference.png b/packages/SettingsLib/Spa/screenshot/assets/tablet/dark_portrait_preference.png Binary files differnew file mode 100644 index 000000000000..94e28437c04e --- /dev/null +++ b/packages/SettingsLib/Spa/screenshot/assets/tablet/dark_portrait_preference.png diff --git a/packages/SettingsLib/Spa/screenshot/assets/tablet/light_landscape_preference.png b/packages/SettingsLib/Spa/screenshot/assets/tablet/light_landscape_preference.png Binary files differnew file mode 100644 index 000000000000..b1d03c31362e --- /dev/null +++ b/packages/SettingsLib/Spa/screenshot/assets/tablet/light_landscape_preference.png diff --git a/packages/SettingsLib/Spa/screenshot/assets/tablet/light_portrait_preference.png b/packages/SettingsLib/Spa/screenshot/assets/tablet/light_portrait_preference.png Binary files differnew file mode 100644 index 000000000000..95f19da3c52c --- /dev/null +++ b/packages/SettingsLib/Spa/screenshot/assets/tablet/light_portrait_preference.png diff --git a/packages/SettingsLib/Spa/screenshot/src/com/android/settingslib/spa/screenshot/util/Bitmap.kt b/packages/SettingsLib/Spa/screenshot/src/com/android/settingslib/spa/screenshot/util/Bitmap.kt new file mode 100644 index 000000000000..814d4a1d1ede --- /dev/null +++ b/packages/SettingsLib/Spa/screenshot/src/com/android/settingslib/spa/screenshot/util/Bitmap.kt @@ -0,0 +1,66 @@ +/* + * 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.screenshot + +import android.graphics.Bitmap +import android.graphics.Canvas +import android.os.Build +import android.view.View +import platform.test.screenshot.matchers.MSSIMMatcher +import platform.test.screenshot.matchers.PixelPerfectMatcher + +/** Draw this [View] into a [Bitmap]. */ +// TODO(b/195673633): Remove this once Compose screenshot tests use hardware rendering for their +// tests. +fun View.drawIntoBitmap(): Bitmap { + val bitmap = + Bitmap.createBitmap( + measuredWidth, + measuredHeight, + Bitmap.Config.ARGB_8888, + ) + val canvas = Canvas(bitmap) + draw(canvas) + return bitmap +} + +/** + * The [BitmapMatcher][platform.test.screenshot.matchers.BitmapMatcher] that should be used for + * screenshot *unit* tests. + */ +val UnitTestBitmapMatcher = + if (Build.CPU_ABI == "x86_64") { + // Different CPU architectures can sometimes end up rendering differently, so we can't do + // pixel-perfect matching on different architectures using the same golden. Given that our + // presubmits are run on cf_x86_64_phone, our goldens should be perfectly matched on the + // x86_64 architecture and use the Structural Similarity Index on others. + // TODO(b/237511747): Run our screenshot presubmit tests on arm64 instead so that we can + // do pixel perfect matching both at presubmit time and at development time with actual + // devices. + PixelPerfectMatcher() + } else { + MSSIMMatcher() + } + +/** + * The [BitmapMatcher][platform.test.screenshot.matchers.BitmapMatcher] that should be used for + * screenshot *unit* tests. + * + * We use the Structural Similarity Index for integration tests because they usually contain + * additional information and noise that shouldn't break the test. + */ +val IntegrationTestBitmapMatcher = MSSIMMatcher() diff --git a/packages/SettingsLib/Spa/screenshot/src/com/android/settingslib/spa/screenshot/util/DefaultDeviceEmulationSpec.kt b/packages/SettingsLib/Spa/screenshot/src/com/android/settingslib/spa/screenshot/util/DefaultDeviceEmulationSpec.kt new file mode 100644 index 000000000000..d7f42b3d1be3 --- /dev/null +++ b/packages/SettingsLib/Spa/screenshot/src/com/android/settingslib/spa/screenshot/util/DefaultDeviceEmulationSpec.kt @@ -0,0 +1,66 @@ +/* + * 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.screenshot + +import platform.test.screenshot.DeviceEmulationSpec +import platform.test.screenshot.DisplaySpec + +/** + * The emulations specs for all 8 permutations of: + * - phone or tablet. + * - dark of light mode. + * - portrait or landscape. + */ +val DeviceEmulationSpec.Companion.PhoneAndTabletFull + get() = PhoneAndTabletFullSpec + +private val PhoneAndTabletFullSpec = + DeviceEmulationSpec.forDisplays(Displays.Phone, Displays.Tablet) + +/** + * The emulations specs of: + * - phone + light mode + portrait. + * - phone + light mode + landscape. + * - tablet + dark mode + portrait. + * + * This allows to test the most important permutations of a screen/layout with only 3 + * configurations. + */ +val DeviceEmulationSpec.Companion.PhoneAndTabletMinimal + get() = PhoneAndTabletMinimalSpec + +private val PhoneAndTabletMinimalSpec = + DeviceEmulationSpec.forDisplays(Displays.Phone, isDarkTheme = false) + + DeviceEmulationSpec.forDisplays(Displays.Tablet, isDarkTheme = true, isLandscape = false) + +object Displays { + val Phone = + DisplaySpec( + "phone", + width = 1440, + height = 3120, + densityDpi = 560, + ) + + val Tablet = + DisplaySpec( + "tablet", + width = 2560, + height = 1600, + densityDpi = 320, + ) +} diff --git a/packages/SettingsLib/Spa/screenshot/src/com/android/settingslib/spa/screenshot/util/SettingsGoldenImagePathManager.kt b/packages/SettingsLib/Spa/screenshot/src/com/android/settingslib/spa/screenshot/util/SettingsGoldenImagePathManager.kt new file mode 100644 index 000000000000..25bc098b29b7 --- /dev/null +++ b/packages/SettingsLib/Spa/screenshot/src/com/android/settingslib/spa/screenshot/util/SettingsGoldenImagePathManager.kt @@ -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.settingslib.spa.screenshot + +import androidx.test.platform.app.InstrumentationRegistry +import platform.test.screenshot.GoldenImagePathManager +import platform.test.screenshot.PathConfig + +/** A [GoldenImagePathManager] that should be used for all Settings screenshot tests. */ +class SettingsGoldenImagePathManager( + pathConfig: PathConfig, + assetsPathRelativeToBuildRoot: String +) : + GoldenImagePathManager( + appContext = InstrumentationRegistry.getInstrumentation().context, + assetsPathRelativeToBuildRoot = assetsPathRelativeToBuildRoot, + deviceLocalPath = + InstrumentationRegistry.getInstrumentation() + .targetContext + .filesDir + .absolutePath + .toString() + "/settings_screenshots", + pathConfig = pathConfig, + ) { + override fun toString(): String { + // This string is appended to all actual/expected screenshots on the device, so make sure + // it is a static value. + return "SettingsGoldenImagePathManager" + } +} diff --git a/packages/SettingsLib/Spa/screenshot/src/com/android/settingslib/spa/screenshot/util/SettingsScreenshotTestRule.kt b/packages/SettingsLib/Spa/screenshot/src/com/android/settingslib/spa/screenshot/util/SettingsScreenshotTestRule.kt new file mode 100644 index 000000000000..7a7cf318fb4f --- /dev/null +++ b/packages/SettingsLib/Spa/screenshot/src/com/android/settingslib/spa/screenshot/util/SettingsScreenshotTestRule.kt @@ -0,0 +1,91 @@ +/* + * 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.screenshot + +import androidx.activity.ComponentActivity +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.runtime.Composable +import androidx.compose.ui.platform.ViewRootForTest +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.compose.ui.test.onRoot +import com.android.settingslib.spa.framework.theme.SettingsTheme +import org.junit.rules.RuleChain +import org.junit.rules.TestRule +import org.junit.runner.Description +import org.junit.runners.model.Statement +import platform.test.screenshot.DeviceEmulationRule +import platform.test.screenshot.DeviceEmulationSpec +import platform.test.screenshot.MaterialYouColorsRule +import platform.test.screenshot.ScreenshotTestRule +import platform.test.screenshot.getEmulatedDevicePathConfig + +/** A rule for Settings screenshot diff tests. */ +class SettingsScreenshotTestRule( + emulationSpec: DeviceEmulationSpec, + assetsPathRelativeToBuildRoot: String +) : TestRule { + private val colorsRule = MaterialYouColorsRule() + private val deviceEmulationRule = DeviceEmulationRule(emulationSpec) + private val screenshotRule = + ScreenshotTestRule( + SettingsGoldenImagePathManager( + getEmulatedDevicePathConfig(emulationSpec), + assetsPathRelativeToBuildRoot + ) + ) + private val composeRule = createAndroidComposeRule<ComponentActivity>() + private val delegateRule = + RuleChain.outerRule(colorsRule) + .around(deviceEmulationRule) + .around(screenshotRule) + .around(composeRule) + private val matcher = UnitTestBitmapMatcher + + override fun apply(base: Statement, description: Description): Statement { + return delegateRule.apply(base, description) + } + + /** + * Compare [content] with the golden image identified by [goldenIdentifier] in the context of + * [testSpec]. + */ + fun screenshotTest( + goldenIdentifier: String, + content: @Composable () -> Unit, + ) { + // Make sure that the activity draws full screen and fits the whole display. + val activity = composeRule.activity + activity.mainExecutor.execute { activity.window.setDecorFitsSystemWindows(false) } + + // Set the content using the AndroidComposeRule to make sure that the Activity is set up + // correctly. + composeRule.setContent { + SettingsTheme { + Surface( + color = MaterialTheme.colorScheme.background, + ) { + content() + } + } + } + composeRule.waitForIdle() + + val view = (composeRule.onRoot().fetchSemanticsNode().root as ViewRootForTest).view + screenshotRule.assertBitmapAgainstGolden(view.drawIntoBitmap(), goldenIdentifier, matcher) + } +} diff --git a/packages/SettingsLib/Spa/screenshot/src/com/android/settingslib/spa/screenshot/widget/PreferenceScreenshotTest.kt b/packages/SettingsLib/Spa/screenshot/src/com/android/settingslib/spa/screenshot/widget/PreferenceScreenshotTest.kt new file mode 100644 index 000000000000..963182638293 --- /dev/null +++ b/packages/SettingsLib/Spa/screenshot/src/com/android/settingslib/spa/screenshot/widget/PreferenceScreenshotTest.kt @@ -0,0 +1,91 @@ +/* + * 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.screenshot + +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Autorenew +import androidx.compose.material.icons.outlined.DisabledByDefault +import androidx.compose.runtime.Composable +import com.android.settingslib.spa.framework.compose.toState +import com.android.settingslib.spa.widget.preference.Preference +import com.android.settingslib.spa.widget.preference.PreferenceModel +import com.android.settingslib.spa.widget.scaffold.RegularScaffold +import com.android.settingslib.spa.widget.ui.SettingsIcon +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.Parameterized +import platform.test.screenshot.DeviceEmulationSpec + +/** A screenshot test for ExampleFeature. */ +@RunWith(Parameterized::class) +class PreferenceScreenshotTest(emulationSpec: DeviceEmulationSpec) { + companion object { + @Parameterized.Parameters(name = "{0}") + @JvmStatic + fun getTestSpecs() = DeviceEmulationSpec.PhoneAndTabletFull + private const val TITLE = "Title" + private const val SUMMARY = "Summary" + private const val LONG_SUMMARY = + "Long long long long long long long long long long long long long long long summary" + } + + @get:Rule + val screenshotRule = + SettingsScreenshotTestRule( + emulationSpec, + "frameworks/base/packages/SettingsLib/Spa/screenshot/assets" + ) + + @Test + fun testPreference() { + screenshotRule.screenshotTest("preference") { + RegularScaffold(title = "Preference") { + Preference(object : PreferenceModel { + override val title = TITLE + }) + + Preference(object : PreferenceModel { + override val title = TITLE + override val summary = SUMMARY.toState() + }) + + Preference(object : PreferenceModel { + override val title = TITLE + override val summary = LONG_SUMMARY.toState() + }) + + Preference(object : PreferenceModel { + override val title = TITLE + override val summary = SUMMARY.toState() + override val enabled = false.toState() + override val icon = @Composable { + SettingsIcon(imageVector = Icons.Outlined.DisabledByDefault) + } + }) + + Preference(object : PreferenceModel { + override val title = TITLE + override val summary = SUMMARY.toState() + override val icon = @Composable { + SettingsIcon(imageVector = Icons.Outlined.Autorenew) + } + }) + } + } + } +}
\ No newline at end of file diff --git a/packages/SettingsLib/Spa/spa/Android.bp b/packages/SettingsLib/Spa/spa/Android.bp index 3ea3b5ccc4f5..40613ceaaf5f 100644 --- a/packages/SettingsLib/Spa/spa/Android.bp +++ b/packages/SettingsLib/Spa/spa/Android.bp @@ -44,3 +44,9 @@ android_library { ], min_sdk_version: "31", } + +// Expose the srcs to tests, so the tests can access the internal classes. +filegroup { + name: "SpaLib_srcs", + srcs: ["src/**/*.kt"], +} diff --git a/packages/SettingsLib/Spa/spa/build.gradle b/packages/SettingsLib/Spa/spa/build.gradle index 19963fbeed82..85ac8ec8e00d 100644 --- a/packages/SettingsLib/Spa/spa/build.gradle +++ b/packages/SettingsLib/Spa/spa/build.gradle @@ -108,6 +108,17 @@ task coverageReport(type: JacocoReport, dependsOn: "connectedDebugAndroidTest") // Excludes files forked from Accompanist. "com/android/settingslib/spa/framework/compose/DrawablePainter*", "com/android/settingslib/spa/framework/compose/Pager*", + + // Excludes inline functions, which is not covered in Jacoco reports. + "com/android/settingslib/spa/framework/util/Collections*", + "com/android/settingslib/spa/framework/util/Flows*", + + // Excludes debug functions + "com/android/settingslib/spa/framework/compose/TimeMeasurer*", + + // Excludes slice demo presenter & provider + "com/android/settingslib/spa/slice/presenter/Demo*", + "com/android/settingslib/spa/slice/provider/Demo*", ], ) executionData.from = fileTree(dir: "$buildDir/outputs/code_coverage/debugAndroidTest/connected") diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/debug/DebugFormat.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/debug/DebugFormat.kt index 58736350dc7f..6ecf9c39c9fa 100644 --- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/debug/DebugFormat.kt +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/debug/DebugFormat.kt @@ -40,7 +40,7 @@ private fun EntryStatusData.debugContent(): String { } fun SettingsPage.debugArguments(): String { - val normArguments = parameter.normalize(arguments) + val normArguments = parameter.normalize(arguments, eraseRuntimeValues = true) if (normArguments == null || normArguments.isEmpty) return "[No arguments]" return normArguments.toString().removeRange(0, 6) } diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/debug/DebugLogger.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/debug/DebugLogger.kt new file mode 100644 index 000000000000..7d4833635f9d --- /dev/null +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/debug/DebugLogger.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.settingslib.spa.debug + +import android.os.Bundle +import android.util.Log +import com.android.settingslib.spa.framework.common.LogCategory +import com.android.settingslib.spa.framework.common.LogEvent +import com.android.settingslib.spa.framework.common.SpaLogger + +class DebugLogger : SpaLogger { + override fun message(tag: String, msg: String, category: LogCategory) { + Log.d("SpaMsg-$category", "[$tag] $msg") + } + + override fun event(id: String, event: LogEvent, category: LogCategory, extraData: Bundle) { + val extraMsg = extraData.toString().removeRange(0, 6) + Log.d("SpaEvent-$category", "[$id] $event $extraMsg") + } +} diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/debug/DebugProvider.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/debug/DebugProvider.kt index 59ec985ba253..838c0cf7cbad 100644 --- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/debug/DebugProvider.kt +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/debug/DebugProvider.kt @@ -27,11 +27,7 @@ import android.database.Cursor import android.database.MatrixCursor import android.net.Uri import android.util.Log -import com.android.settingslib.spa.framework.common.ColumnEnum -import com.android.settingslib.spa.framework.common.QueryEnum import com.android.settingslib.spa.framework.common.SpaEnvironmentFactory -import com.android.settingslib.spa.framework.common.addUri -import com.android.settingslib.spa.framework.common.getColumns import com.android.settingslib.spa.framework.util.KEY_DESTINATION import com.android.settingslib.spa.framework.util.KEY_HIGHLIGHT_ENTRY import com.android.settingslib.spa.framework.util.KEY_SESSION_SOURCE_NAME diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/common/ProviderColumn.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/debug/ProviderColumn.kt index 61b46be443c2..bb9a1345b70b 100644 --- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/common/ProviderColumn.kt +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/debug/ProviderColumn.kt @@ -14,10 +14,9 @@ * limitations under the License. */ -package com.android.settingslib.spa.framework.common +package com.android.settingslib.spa.debug import android.content.UriMatcher -import androidx.annotation.VisibleForTesting /** * Enum to define all column names in provider. @@ -39,12 +38,6 @@ enum class ColumnEnum(val id: String) { ENTRY_INTENT_URI("entryIntent"), ENTRY_HIERARCHY_PATH("entryPath"), ENTRY_START_ADB("entryStartAdb"), - - // Columns related to search - SEARCH_TITLE("searchTitle"), - SEARCH_KEYWORD("searchKw"), - SEARCH_PATH("searchPath"), - SEARCH_STATUS_DISABLED("searchDisabled"), } /** @@ -89,54 +82,16 @@ enum class QueryEnum( ColumnEnum.ENTRY_HIERARCHY_PATH, ) ), - - SEARCH_STATIC_DATA_QUERY( - "search_static", 301, - listOf( - ColumnEnum.ENTRY_ID, - ColumnEnum.ENTRY_INTENT_URI, - ColumnEnum.SEARCH_TITLE, - ColumnEnum.SEARCH_KEYWORD, - ColumnEnum.SEARCH_PATH, - ) - ), - SEARCH_DYNAMIC_DATA_QUERY( - "search_dynamic", 302, - listOf( - ColumnEnum.ENTRY_ID, - ColumnEnum.ENTRY_INTENT_URI, - ColumnEnum.SEARCH_TITLE, - ColumnEnum.SEARCH_KEYWORD, - ColumnEnum.SEARCH_PATH, - ) - ), - SEARCH_IMMUTABLE_STATUS_DATA_QUERY( - "search_immutable_status", 303, - listOf( - ColumnEnum.ENTRY_ID, - ColumnEnum.SEARCH_STATUS_DISABLED, - ) - ), - SEARCH_MUTABLE_STATUS_DATA_QUERY( - "search_mutable_status", 304, - listOf( - ColumnEnum.ENTRY_ID, - ColumnEnum.SEARCH_STATUS_DISABLED, - ) - ), } -@VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE) -fun QueryEnum.getColumns(): Array<String> { +internal fun QueryEnum.getColumns(): Array<String> { return columnNames.map { it.id }.toTypedArray() } -@VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE) -fun QueryEnum.getIndex(name: ColumnEnum): Int { +internal fun QueryEnum.getIndex(name: ColumnEnum): Int { return columnNames.indexOf(name) } -@VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE) -fun QueryEnum.addUri(uriMatcher: UriMatcher, authority: String) { +internal fun QueryEnum.addUri(uriMatcher: UriMatcher, authority: String) { uriMatcher.addURI(authority, queryPath, queryMatchCode) } diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/common/SettingsEntry.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/common/SettingsEntry.kt index 702c07585be1..0871304fa873 100644 --- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/common/SettingsEntry.kt +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/common/SettingsEntry.kt @@ -25,8 +25,8 @@ import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.remember import com.android.settingslib.spa.framework.compose.LocalNavController -const val INJECT_ENTRY_NAME = "INJECT" -const val ROOT_ENTRY_NAME = "ROOT" +private const val INJECT_ENTRY_NAME = "INJECT" +private const val ROOT_ENTRY_NAME = "ROOT" interface EntryData { val pageId: String? @@ -35,6 +35,8 @@ interface EntryData { get() = null val isHighlighted: Boolean get() = false + val arguments: Bundle? + get() = null } val LocalEntryDataProvider = @@ -121,11 +123,11 @@ data class SettingsEntry( } private fun fullArgument(runtimeArguments: Bundle? = null): Bundle { - val arguments = Bundle() - if (owner.arguments != null) arguments.putAll(owner.arguments) - // Put runtime args later, which can override page args. - if (runtimeArguments != null) arguments.putAll(runtimeArguments) - return arguments + return Bundle().apply { + if (owner.arguments != null) putAll(owner.arguments) + // Put runtime args later, which can override page args. + if (runtimeArguments != null) putAll(runtimeArguments) + } } fun getStatusData(runtimeArguments: Bundle? = null): EntryStatusData? { @@ -142,19 +144,21 @@ data class SettingsEntry( @Composable fun UiLayout(runtimeArguments: Bundle? = null) { - CompositionLocalProvider(provideLocalEntryData()) { - uiLayoutImpl(fullArgument(runtimeArguments)) + val arguments = remember { fullArgument(runtimeArguments) } + CompositionLocalProvider(provideLocalEntryData(arguments)) { + uiLayoutImpl(arguments) } } @Composable - fun provideLocalEntryData(): ProvidedValue<EntryData> { + private fun provideLocalEntryData(arguments: Bundle): ProvidedValue<EntryData> { val controller = LocalNavController.current return LocalEntryDataProvider provides remember { object : EntryData { override val pageId = containerPage().id override val entryId = id override val isHighlighted = controller.highlightEntryId == id + override val arguments = arguments } } } diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/common/SettingsPage.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/common/SettingsPage.kt index 7a39b730342c..2bfa2a4375da 100644 --- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/common/SettingsPage.kt +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/common/SettingsPage.kt @@ -69,7 +69,7 @@ data class SettingsPage( parameter: List<NamedNavArgument> = emptyList(), arguments: Bundle? = null ): String { - val normArguments = parameter.normalize(arguments) + val normArguments = parameter.normalize(arguments, eraseRuntimeValues = true) return "$name:${normArguments?.toString()}".toHashId() } } diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/common/SpaEnvironment.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/common/SpaEnvironment.kt index 6d0b810d0cb6..f672ee01d070 100644 --- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/common/SpaEnvironment.kt +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/common/SpaEnvironment.kt @@ -29,6 +29,10 @@ private const val TAG = "SpaEnvironment" object SpaEnvironmentFactory { private var spaEnvironment: SpaEnvironment? = null + fun reset() { + spaEnvironment = null + } + fun reset(env: SpaEnvironment) { spaEnvironment = env Log.d(TAG, "reset") diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/common/SpaLogger.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/common/SpaLogger.kt index 6ecb7fa94c3c..78df0f27cc6a 100644 --- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/common/SpaLogger.kt +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/common/SpaLogger.kt @@ -17,7 +17,6 @@ package com.android.settingslib.spa.framework.common import android.os.Bundle -import android.util.Log // Defines the category of the log, for quick filter enum class LogCategory { @@ -62,14 +61,3 @@ interface SpaLogger { ) { } } - -class LocalLogger : SpaLogger { - override fun message(tag: String, msg: String, category: LogCategory) { - Log.d("SpaMsg-$category", "[$tag] $msg") - } - - override fun event(id: String, event: LogEvent, category: LogCategory, extraData: Bundle) { - val extraMsg = extraData.toString().removeRange(0, 6) - Log.d("SpaEvent-$category", "[$id] $event $extraMsg") - } -}
\ No newline at end of file diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/theme/SettingsColors.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/theme/SettingsColors.kt index fa17e08e9885..d72ec264cf74 100644 --- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/theme/SettingsColors.kt +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/theme/SettingsColors.kt @@ -18,6 +18,7 @@ package com.android.settingslib.spa.framework.theme import android.content.Context import android.os.Build +import androidx.annotation.VisibleForTesting import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.runtime.staticCompositionLocalOf @@ -64,7 +65,8 @@ internal fun settingsColorScheme(isDarkTheme: Boolean): SettingsColorScheme { * * @param context The context required to get system resource data. */ -private fun dynamicLightColorScheme(context: Context): SettingsColorScheme { +@VisibleForTesting +internal fun dynamicLightColorScheme(context: Context): SettingsColorScheme { val tonalPalette = dynamicTonalPalette(context) return SettingsColorScheme( background = tonalPalette.neutral95, @@ -90,7 +92,8 @@ private fun dynamicLightColorScheme(context: Context): SettingsColorScheme { * * @param context The context required to get system resource data. */ -private fun dynamicDarkColorScheme(context: Context): SettingsColorScheme { +@VisibleForTesting +internal fun dynamicDarkColorScheme(context: Context): SettingsColorScheme { val tonalPalette = dynamicTonalPalette(context) return SettingsColorScheme( background = tonalPalette.neutral10, @@ -107,7 +110,8 @@ private fun dynamicDarkColorScheme(context: Context): SettingsColorScheme { ) } -private fun darkColorScheme(): SettingsColorScheme { +@VisibleForTesting +internal fun darkColorScheme(): SettingsColorScheme { val tonalPalette = tonalPalette() return SettingsColorScheme( background = tonalPalette.neutral10, @@ -124,7 +128,8 @@ private fun darkColorScheme(): SettingsColorScheme { ) } -private fun lightColorScheme(): SettingsColorScheme { +@VisibleForTesting +internal fun lightColorScheme(): SettingsColorScheme { val tonalPalette = tonalPalette() return SettingsColorScheme( background = tonalPalette.neutral95, diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/EntryLogger.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/EntryLogger.kt index 1c881878f751..8ff436866502 100644 --- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/EntryLogger.kt +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/EntryLogger.kt @@ -28,9 +28,12 @@ import com.android.settingslib.spa.framework.common.SpaEnvironmentFactory @Composable fun logEntryEvent(): (event: LogEvent, extraData: Bundle) -> Unit { val entryId = LocalEntryDataProvider.current.entryId ?: return { _, _ -> } + val arguments = LocalEntryDataProvider.current.arguments return { event, extraData -> SpaEnvironmentFactory.instance.logger.event( - entryId, event, category = LogCategory.VIEW, extraData = extraData + entryId, event, category = LogCategory.VIEW, extraData = extraData.apply { + if (arguments != null) putAll(arguments) + } ) } } @@ -40,7 +43,7 @@ fun wrapOnClickWithLog(onClick: (() -> Unit)?): (() -> Unit)? { if (onClick == null) return null val logEvent = logEntryEvent() return { - logEvent(LogEvent.ENTRY_CLICK, Bundle.EMPTY) + logEvent(LogEvent.ENTRY_CLICK, bundleOf()) onClick() } } diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/PageLogger.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/PageLogger.kt index a88125472b52..271443e86dac 100644 --- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/PageLogger.kt +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/PageLogger.kt @@ -48,7 +48,10 @@ internal fun SettingsPageProvider.PageEvent(arguments: Bundle? = null) { extraData = bundleOf( LOG_DATA_DISPLAY_NAME to page.displayName, LOG_DATA_SESSION_NAME to navController.sessionSourceName, - ) + ).apply { + val normArguments = parameter.normalize(arguments) + if (normArguments != null) putAll(normArguments) + } ) } if (event == Lifecycle.Event.ON_START) { diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/Parameter.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/Parameter.kt index f10d3b097fc8..be303f09fb75 100644 --- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/Parameter.kt +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/framework/util/Parameter.kt @@ -47,12 +47,15 @@ fun List<NamedNavArgument>.navLink(arguments: Bundle? = null): String { return argsArray.joinToString("") { arg -> "/$arg" } } -fun List<NamedNavArgument>.normalize(arguments: Bundle? = null): Bundle? { +fun List<NamedNavArgument>.normalize( + arguments: Bundle? = null, + eraseRuntimeValues: Boolean = false +): Bundle? { if (this.isEmpty()) return null val normArgs = Bundle() for (navArg in this) { // Erase value of runtime parameters. - if (navArg.isRuntimeParam()) { + if (navArg.isRuntimeParam() && eraseRuntimeValues) { normArgs.putString(navArg.name, null) continue } diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/search/SpaSearchProvider.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/search/SpaSearchProvider.kt index 21bc75a11942..a1543d4a7a70 100644 --- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/search/SpaSearchProvider.kt +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/search/SpaSearchProvider.kt @@ -125,7 +125,7 @@ class SpaSearchProvider : ContentProvider() { } @VisibleForTesting - fun querySearchImmutableStatusData(): Cursor { + internal fun querySearchImmutableStatusData(): Cursor { val entryRepository by spaEnvironment.entryRepository val cursor = MatrixCursor(QueryEnum.SEARCH_IMMUTABLE_STATUS_DATA_QUERY.getColumns()) for (entry in entryRepository.getAllEntries()) { @@ -136,7 +136,7 @@ class SpaSearchProvider : ContentProvider() { } @VisibleForTesting - fun querySearchMutableStatusData(): Cursor { + internal fun querySearchMutableStatusData(): Cursor { val entryRepository by spaEnvironment.entryRepository val cursor = MatrixCursor(QueryEnum.SEARCH_MUTABLE_STATUS_DATA_QUERY.getColumns()) for (entry in entryRepository.getAllEntries()) { @@ -147,7 +147,7 @@ class SpaSearchProvider : ContentProvider() { } @VisibleForTesting - fun querySearchStaticData(): Cursor { + internal fun querySearchStaticData(): Cursor { val entryRepository by spaEnvironment.entryRepository val cursor = MatrixCursor(QueryEnum.SEARCH_STATIC_DATA_QUERY.getColumns()) for (entry in entryRepository.getAllEntries()) { @@ -158,7 +158,7 @@ class SpaSearchProvider : ContentProvider() { } @VisibleForTesting - fun querySearchDynamicData(): Cursor { + internal fun querySearchDynamicData(): Cursor { val entryRepository by spaEnvironment.entryRepository val cursor = MatrixCursor(QueryEnum.SEARCH_DYNAMIC_DATA_QUERY.getColumns()) for (entry in entryRepository.getAllEntries()) { diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/slice/provider/Demo.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/slice/provider/Demo.kt index b65b91f7990e..e4a738631474 100644 --- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/slice/provider/Demo.kt +++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/slice/provider/Demo.kt @@ -19,6 +19,7 @@ package com.android.settingslib.spa.slice.provider import android.app.PendingIntent import android.content.Context import android.net.Uri +import androidx.core.R import androidx.core.graphics.drawable.IconCompat import androidx.slice.Slice import androidx.slice.SliceManager @@ -52,10 +53,7 @@ fun createDemoSlice(sliceUri: Uri, title: String, summary: String, intent: Pendi private fun createSliceAction(context: Context, intent: PendingIntent): SliceAction { return SliceAction.create( intent, - IconCompat.createWithResource( - context, - com.google.android.material.R.drawable.navigation_empty_icon - ), + IconCompat.createWithResource(context, R.drawable.notification_action_background), ListBuilder.ICON_IMAGE, "Enter app" ) diff --git a/packages/SettingsLib/Spa/tests/Android.bp b/packages/SettingsLib/Spa/tests/Android.bp index 6974005819ea..f9e64aee1513 100644 --- a/packages/SettingsLib/Spa/tests/Android.bp +++ b/packages/SettingsLib/Spa/tests/Android.bp @@ -22,7 +22,10 @@ android_test { name: "SpaLibTests", test_suites: ["device-tests"], - srcs: ["src/**/*.kt"], + srcs: [ + ":SpaLib_srcs", + "src/**/*.kt", + ], static_libs: [ "SpaLib", diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/common/SettingsEntryTest.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/common/SettingsEntryTest.kt index f98963c869de..b600ac6cd322 100644 --- a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/common/SettingsEntryTest.kt +++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/common/SettingsEntryTest.kt @@ -16,10 +16,13 @@ package com.android.settingslib.spa.framework.common +import android.net.Uri import androidx.compose.runtime.Composable import androidx.compose.ui.test.junit4.createComposeRule import androidx.core.os.bundleOf import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.android.settingslib.spa.slice.appendSpaParams +import com.android.settingslib.spa.slice.getEntryId import com.android.settingslib.spa.tests.testutils.getUniqueEntryId import com.android.settingslib.spa.tests.testutils.getUniquePageId import com.google.common.truth.Truth.assertThat @@ -27,8 +30,8 @@ import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith -const val INJECT_ENTRY_NAME = "INJECT" -const val ROOT_ENTRY_NAME = "ROOT" +const val INJECT_ENTRY_NAME_TEST = "INJECT" +const val ROOT_ENTRY_NAME_TEST = "ROOT" class MacroForTest(private val pageId: String, private val entryId: String) : EntryMacro { @Composable @@ -95,12 +98,12 @@ class SettingsEntryTest { val entryInject = SettingsEntryBuilder.createInject(owner).build() assertThat(entryInject.id).isEqualTo( getUniqueEntryId( - INJECT_ENTRY_NAME, + INJECT_ENTRY_NAME_TEST, owner, toPage = owner ) ) - assertThat(entryInject.displayName).isEqualTo("${INJECT_ENTRY_NAME}_mySpp") + assertThat(entryInject.displayName).isEqualTo("${INJECT_ENTRY_NAME_TEST}_mySpp") assertThat(entryInject.fromPage).isNull() assertThat(entryInject.toPage).isNotNull() } @@ -111,7 +114,7 @@ class SettingsEntryTest { val entryInject = SettingsEntryBuilder.createRoot(owner, "myRootEntry").build() assertThat(entryInject.id).isEqualTo( getUniqueEntryId( - ROOT_ENTRY_NAME, + ROOT_ENTRY_NAME_TEST, owner, toPage = owner ) @@ -169,4 +172,25 @@ class SettingsEntryTest { assertThat(statusData?.isDisabled).isTrue() assertThat(statusData?.isSwitchOff).isTrue() } + + @Test + fun testSetSliceDataFn() { + val owner = SettingsPage.create("mySpp") + val entryId = getUniqueEntryId("myEntry", owner) + val emptySliceData = EntrySliceData() + + val entryBuilder = SettingsEntryBuilder.create(owner, "myEntry") + .setSliceDataFn { uri, _ -> + return@setSliceDataFn if (uri.getEntryId() == entryId) emptySliceData else null + } + val entry = entryBuilder.build() + assertThat(entry.id).isEqualTo(entryId) + assertThat(entry.hasSliceSupport).isTrue() + assertThat(entry.getSliceData(Uri.EMPTY)).isNull() + assertThat( + entry.getSliceData( + Uri.Builder().scheme("content").appendSpaParams(entryId = entryId).build() + ) + ).isEqualTo(emptySliceData) + } } diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/common/SpaEnvironmentTest.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/common/SpaEnvironmentTest.kt new file mode 100644 index 000000000000..3b0e36b91666 --- /dev/null +++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/common/SpaEnvironmentTest.kt @@ -0,0 +1,60 @@ +/* + * 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.common + +import android.content.Context +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.android.settingslib.spa.tests.testutils.SpaEnvironmentForTest +import com.google.common.truth.Truth +import org.junit.Assert +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class SpaEnvironmentTest { + private val context: Context = ApplicationProvider.getApplicationContext() + private val spaEnvironment = SpaEnvironmentForTest(context) + + @get:Rule + val composeTestRule = createComposeRule() + + @Test + fun testSpaEnvironmentFactory() { + SpaEnvironmentFactory.reset() + Truth.assertThat(SpaEnvironmentFactory.isReady()).isFalse() + Assert.assertThrows(UnsupportedOperationException::class.java) { + SpaEnvironmentFactory.instance + } + + SpaEnvironmentFactory.reset(spaEnvironment) + Truth.assertThat(SpaEnvironmentFactory.isReady()).isTrue() + Truth.assertThat(SpaEnvironmentFactory.instance).isEqualTo(spaEnvironment) + } + + @Test + fun testSpaEnvironmentFactoryForPreview() { + SpaEnvironmentFactory.reset() + composeTestRule.setContent { + Truth.assertThat(SpaEnvironmentFactory.isReady()).isFalse() + SpaEnvironmentFactory.resetForPreview() + Truth.assertThat(SpaEnvironmentFactory.isReady()).isTrue() + } + } +}
\ No newline at end of file diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/theme/SettingsColorsTest.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/theme/SettingsColorsTest.kt new file mode 100644 index 000000000000..5ea92abefbef --- /dev/null +++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/theme/SettingsColorsTest.kt @@ -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.settingslib.spa.framework.theme + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import org.junit.runner.RunWith +import androidx.compose.ui.graphics.Color + +@RunWith(AndroidJUnit4::class) +class SettingsColorsTest { + private val context: Context = ApplicationProvider.getApplicationContext() + + @Test + fun testDynamicTheme() { + // The dynamic color could be different in different device, just check basic restrictions: + // 1. text color is different with background color + // 2. primary / spinner color is different with its on-item color + val ls = dynamicLightColorScheme(context) + assertThat(ls.categoryTitle).isNotEqualTo(ls.background) + assertThat(ls.secondaryText).isNotEqualTo(ls.background) + assertThat(ls.primaryContainer).isNotEqualTo(ls.onPrimaryContainer) + assertThat(ls.spinnerHeaderContainer).isNotEqualTo(ls.onSpinnerHeaderContainer) + assertThat(ls.spinnerItemContainer).isNotEqualTo(ls.onSpinnerItemContainer) + + val ds = dynamicDarkColorScheme(context) + assertThat(ds.categoryTitle).isNotEqualTo(ds.background) + assertThat(ds.secondaryText).isNotEqualTo(ds.background) + assertThat(ds.primaryContainer).isNotEqualTo(ds.onPrimaryContainer) + assertThat(ds.spinnerHeaderContainer).isNotEqualTo(ds.onSpinnerHeaderContainer) + assertThat(ds.spinnerItemContainer).isNotEqualTo(ds.onSpinnerItemContainer) + } + + @Test + fun testStaticTheme() { + val ls = lightColorScheme() + assertThat(ls.background).isEqualTo(Color(red = 244, green = 239, blue = 244)) + assertThat(ls.categoryTitle).isEqualTo(Color(red = 103, green = 80, blue = 164)) + assertThat(ls.surface).isEqualTo(Color(red = 255, green = 251, blue = 254)) + assertThat(ls.surfaceHeader).isEqualTo(Color(red = 230, green = 225, blue = 229)) + assertThat(ls.secondaryText).isEqualTo(Color(red = 73, green = 69, blue = 79)) + assertThat(ls.primaryContainer).isEqualTo(Color(red = 234, green = 221, blue = 255)) + assertThat(ls.onPrimaryContainer).isEqualTo(Color(red = 28, green = 27, blue = 31)) + assertThat(ls.spinnerHeaderContainer).isEqualTo(Color(red = 234, green = 221, blue = 255)) + assertThat(ls.onSpinnerHeaderContainer).isEqualTo(Color(red = 28, green = 27, blue = 31)) + assertThat(ls.spinnerItemContainer).isEqualTo(Color(red = 232, green = 222, blue = 248)) + assertThat(ls.onSpinnerItemContainer).isEqualTo(Color(red = 73, green = 69, blue = 79)) + + val ds = darkColorScheme() + assertThat(ds.background).isEqualTo(Color(red = 28, green = 27, blue = 31)) + assertThat(ds.categoryTitle).isEqualTo(Color(red = 234, green = 221, blue = 255)) + assertThat(ds.surface).isEqualTo(Color(red = 49, green = 48, blue = 51)) + assertThat(ds.surfaceHeader).isEqualTo(Color(red = 72, green = 70, blue = 73)) + assertThat(ds.secondaryText).isEqualTo(Color(red = 202, green = 196, blue = 208)) + assertThat(ds.primaryContainer).isEqualTo(Color(red = 232, green = 222, blue = 248)) + assertThat(ds.onPrimaryContainer).isEqualTo(Color(red = 28, green = 27, blue = 31)) + assertThat(ds.spinnerHeaderContainer).isEqualTo(Color(red = 234, green = 221, blue = 255)) + assertThat(ds.onSpinnerHeaderContainer).isEqualTo(Color(red = 28, green = 27, blue = 31)) + assertThat(ds.spinnerItemContainer).isEqualTo(Color(red = 232, green = 222, blue = 248)) + assertThat(ds.onSpinnerItemContainer).isEqualTo(Color(red = 73, green = 69, blue = 79)) + } +} diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/CollectionsTest.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/CollectionsTest.kt new file mode 100644 index 000000000000..62f470793a88 --- /dev/null +++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/CollectionsTest.kt @@ -0,0 +1,47 @@ +/* + * 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.test.ext.junit.runners.AndroidJUnit4 +import com.google.common.truth.Truth +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.runTest +import org.junit.Test +import org.junit.runner.RunWith + +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(AndroidJUnit4::class) +class CollectionsTest { + @Test + fun testAsyncForEach() = runTest { + var sum = 0 + listOf(1, 2, 3).asyncForEach { sum += it } + Truth.assertThat(sum).isEqualTo(6) + } + + @Test + fun testAsyncFilter() = runTest { + val res = listOf(1, 2, 3).asyncFilter { it >= 2 } + Truth.assertThat(res).containsExactly(2, 3).inOrder() + } + + @Test + fun testAsyncMap() = runTest { + val res = listOf(1, 2, 3).asyncMap { it + 1 } + Truth.assertThat(res).containsExactly(2, 3, 4).inOrder() + } +} diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/ParameterTest.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/ParameterTest.kt index 48ebd8d8ade8..0aa846c6f997 100644 --- a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/ParameterTest.kt +++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/framework/util/ParameterTest.kt @@ -88,7 +88,7 @@ class ParameterTest { val emptyParam = navArguments.normalize() assertThat(emptyParam).isNotNull() assertThat(emptyParam.toString()).isEqualTo( - "Bundle[{rt_param=null, unset_string_param=null, unset_int_param=null}]" + "Bundle[{unset_rt_param=null, unset_string_param=null, unset_int_param=null}]" ) val setPartialParam = navArguments.normalize( @@ -99,7 +99,7 @@ class ParameterTest { ) assertThat(setPartialParam).isNotNull() assertThat(setPartialParam.toString()).isEqualTo( - "Bundle[{rt_param=null, string_param=myStr, unset_int_param=null}]" + "Bundle[{rt_param=rtStr, string_param=myStr, unset_int_param=null}]" ) val setAllParam = navArguments.normalize( @@ -107,7 +107,8 @@ class ParameterTest { "string_param" to "myStr", "int_param" to 10, "rt_param" to "rtStr", - ) + ), + eraseRuntimeValues = true ) assertThat(setAllParam).isNotNull() assertThat(setAllParam.toString()).isEqualTo( diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/tests/testutils/UniqueIdHelper.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/tests/testutils/UniqueIdHelper.kt index 7e51fea69041..ce9b7917b769 100644 --- a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/tests/testutils/UniqueIdHelper.kt +++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/tests/testutils/UniqueIdHelper.kt @@ -27,7 +27,7 @@ fun getUniquePageId( parameter: List<NamedNavArgument> = emptyList(), arguments: Bundle? = null ): String { - val normArguments = parameter.normalize(arguments) + val normArguments = parameter.normalize(arguments, eraseRuntimeValues = true) return "$name:${normArguments?.toString()}".toHashId() } diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/preference/ProgressBarPreferenceTest.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/preference/ProgressBarPreferenceTest.kt index 5611f8ce14db..2140c07090e1 100644 --- a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/preference/ProgressBarPreferenceTest.kt +++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/preference/ProgressBarPreferenceTest.kt @@ -16,6 +16,9 @@ package com.android.settingslib.spa.widget.preference +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Launch +import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.semantics.ProgressBarRangeInfo import androidx.compose.ui.semantics.SemanticsProperties.ProgressBarRangeInfo import androidx.compose.ui.test.SemanticsMatcher @@ -49,6 +52,7 @@ class ProgressBarPreferenceTest { ProgressBarWithDataPreference(model = object : ProgressBarPreferenceModel { override val title = "Title" override val progress = 0.2f + override val icon: ImageVector = Icons.Outlined.Launch }, data = "Data") } composeTestRule.onNodeWithText("Title").assertIsDisplayed() diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/ui/ProgressBarTest.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/ui/ProgressBarTest.kt new file mode 100644 index 000000000000..072c2cca8b8b --- /dev/null +++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/ui/ProgressBarTest.kt @@ -0,0 +1,49 @@ +/* + * 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.ui + +import androidx.compose.ui.semantics.ProgressBarRangeInfo +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class ProgressBarTest { + @get:Rule + val composeTestRule = createComposeRule() + + @Test + fun testProgressBar() { + composeTestRule.setContent { + LinearProgressBar(progress = .5f) + CircularProgressBar(progress = .2f) + } + + fun progressEqualsTo(progress: Float): SemanticsMatcher = + SemanticsMatcher.expectValue( + SemanticsProperties.ProgressBarRangeInfo, + ProgressBarRangeInfo(progress, 0f..1f, 0) + ) + composeTestRule.onNode(progressEqualsTo(0.5f)).assertIsDisplayed() + composeTestRule.onNode(progressEqualsTo(0.2f)).assertIsDisplayed() + } +} diff --git a/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/ui/TextTest.kt b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/ui/TextTest.kt new file mode 100644 index 000000000000..7e5b4f851250 --- /dev/null +++ b/packages/SettingsLib/Spa/tests/src/com/android/settingslib/spa/widget/ui/TextTest.kt @@ -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.settingslib.spa.widget.ui + +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithText +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.android.settingslib.spa.framework.compose.toState +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class TextTest { + @get:Rule + val composeTestRule = createComposeRule() + + @Test + fun testTitle() { + composeTestRule.setContent { + SettingsTitle(title = "myTitleValue") + SettingsTitle(title = "myTitleState".toState()) + PlaceholderTitle(title = "myTitlePlaceholder") + } + composeTestRule.onNodeWithText("myTitleState").assertIsDisplayed() + composeTestRule.onNodeWithText("myTitleValue").assertIsDisplayed() + composeTestRule.onNodeWithText("myTitlePlaceholder").assertIsDisplayed() + } +} diff --git a/packages/SettingsProvider/res/xml/bookmarks.xml b/packages/SettingsProvider/res/xml/bookmarks.xml index 454f4562a239..4b97b4779e1b 100644 --- a/packages/SettingsProvider/res/xml/bookmarks.xml +++ b/packages/SettingsProvider/res/xml/bookmarks.xml @@ -19,7 +19,6 @@ Bookmarks for vendor apps should be added to a bookmarks resource overlay; not here. Typical shortcuts (not necessarily defined here): - 'a': Calculator 'b': Browser 'c': Contacts 'e': Email @@ -29,13 +28,11 @@ 'p': Music 's': SMS 't': Talk + 'u': Calculator 'y': YouTube --> <bookmarks> <bookmark - category="android.intent.category.APP_CALCULATOR" - shortcut="a" /> - <bookmark category="android.intent.category.APP_BROWSER" shortcut="b" /> <bookmark @@ -46,7 +43,7 @@ shortcut="e" /> <bookmark category="android.intent.category.APP_CALENDAR" - shortcut="l" /> + shortcut="k" /> <bookmark category="android.intent.category.APP_MAPS" shortcut="m" /> @@ -56,4 +53,7 @@ <bookmark category="android.intent.category.APP_MESSAGING" shortcut="s" /> + <bookmark + category="android.intent.category.APP_CALCULATOR" + shortcut="u" /> </bookmarks> diff --git a/packages/SettingsProvider/src/android/provider/settings/validators/SystemSettingsValidators.java b/packages/SettingsProvider/src/android/provider/settings/validators/SystemSettingsValidators.java index 3e5802e0b98d..2ee890fdb68f 100644 --- a/packages/SettingsProvider/src/android/provider/settings/validators/SystemSettingsValidators.java +++ b/packages/SettingsProvider/src/android/provider/settings/validators/SystemSettingsValidators.java @@ -111,7 +111,6 @@ public class SystemSettingsValidators { }); VALIDATORS.put(System.DISPLAY_COLOR_MODE_VENDOR_HINT, ANY_STRING_VALIDATOR); VALIDATORS.put(System.SCREEN_OFF_TIMEOUT, NON_NEGATIVE_INTEGER_VALIDATOR); - VALIDATORS.put(System.SCREEN_BRIGHTNESS_FOR_VR, new InclusiveIntegerRangeValidator(0, 255)); VALIDATORS.put(System.SCREEN_BRIGHTNESS_MODE, BOOLEAN_VALIDATOR); VALIDATORS.put(System.ADAPTIVE_SLEEP, BOOLEAN_VALIDATOR); VALIDATORS.put(System.MODE_RINGER_STREAMS_AFFECTED, NON_NEGATIVE_INTEGER_VALIDATOR); diff --git a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java index 85d0b1820474..74774167caa0 100644 --- a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java +++ b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java @@ -33,7 +33,6 @@ import android.media.AudioSystem; import android.net.ConnectivityManager; import android.os.Build; import android.os.Environment; -import android.os.RemoteException; import android.os.SystemProperties; import android.os.UserHandle; import android.provider.Settings; @@ -2243,9 +2242,6 @@ class DatabaseHelper extends SQLiteOpenHelper { loadIntegerSetting(stmt, Settings.System.SCREEN_BRIGHTNESS, R.integer.def_screen_brightness); - loadIntegerSetting(stmt, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, - com.android.internal.R.integer.config_screenBrightnessForVrSettingDefault); - loadBooleanSetting(stmt, Settings.System.SCREEN_BRIGHTNESS_MODE, R.bool.def_screen_brightness_automatic_mode); diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java index 17078c4c81f2..8d4a35dc0d88 100644 --- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java +++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java @@ -2841,9 +2841,6 @@ class SettingsProtoDumpUtil { Settings.System.SCREEN_BRIGHTNESS, SystemSettingsProto.Screen.BRIGHTNESS); dumpSetting(s, p, - Settings.System.SCREEN_BRIGHTNESS_FOR_VR, - SystemSettingsProto.Screen.BRIGHTNESS_FOR_VR); - dumpSetting(s, p, Settings.System.SCREEN_BRIGHTNESS_MODE, SystemSettingsProto.Screen.BRIGHTNESS_MODE); dumpSetting(s, p, @@ -2852,9 +2849,6 @@ class SettingsProtoDumpUtil { dumpSetting(s, p, Settings.System.SCREEN_BRIGHTNESS_FLOAT, SystemSettingsProto.Screen.BRIGHTNESS_FLOAT); - dumpSetting(s, p, - Settings.System.SCREEN_BRIGHTNESS_FOR_VR_FLOAT, - SystemSettingsProto.Screen.BRIGHTNESS_FOR_VR_FLOAT); p.end(screenToken); dumpSetting(s, p, diff --git a/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java b/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java index 153f0b4711c5..48114ba1eb3d 100644 --- a/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java +++ b/packages/SettingsProvider/test/src/android/provider/SettingsBackupTest.java @@ -100,8 +100,6 @@ public class SettingsBackupTest { Settings.System.MIN_REFRESH_RATE, // depends on hardware capabilities Settings.System.PEAK_REFRESH_RATE, // depends on hardware capabilities Settings.System.SCREEN_BRIGHTNESS_FLOAT, - Settings.System.SCREEN_BRIGHTNESS_FOR_VR, - Settings.System.SCREEN_BRIGHTNESS_FOR_VR_FLOAT, Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, Settings.System.MULTI_AUDIO_FOCUS_ENABLED // form-factor/OEM specific ); diff --git a/packages/Shell/AndroidManifest.xml b/packages/Shell/AndroidManifest.xml index d3ba5e6d0803..dd58743276e7 100644 --- a/packages/Shell/AndroidManifest.xml +++ b/packages/Shell/AndroidManifest.xml @@ -23,6 +23,7 @@ > <!-- Standard permissions granted to the shell. --> + <uses-permission android:name="android.permission.MANAGE_HEALTH_DATA" /> <uses-permission android:name="android.permission.LAUNCH_DEVICE_MANAGER_SETUP" /> <uses-permission android:name="android.permission.GET_RUNTIME_PERMISSIONS" /> <uses-permission android:name="android.permission.SEND_SMS" /> @@ -360,6 +361,9 @@ <!-- Permission needed to test wallpaper dimming --> <uses-permission android:name="android.permission.SET_WALLPAPER_DIM_AMOUNT" /> + <!-- Permission needed to test wallpapers supporting ambient mode --> + <uses-permission android:name="android.permission.AMBIENT_WALLPAPER" /> + <!-- Permission required to test ContentResolver caching. --> <uses-permission android:name="android.permission.CACHE_CONTENT" /> @@ -774,6 +778,9 @@ <!-- Permissions required for CTS test - CtsAppFgsTestCases --> <uses-permission android:name="android.permission.USE_EXACT_ALARM" /> + <!-- Permission required for CTS test - CtsHardwareTestCases --> + <uses-permission android:name="android.permission.REMAP_MODIFIER_KEYS" /> + <!-- Permissions required for CTS test - CtsAppFgsTestCases --> <uses-permission android:name="android.permission.health.READ_ACTIVE_CALORIES_BURNED" /> <uses-permission android:name="android.permission.health.READ_BASAL_BODY_TEMPERATURE" /> diff --git a/packages/Shell/src/com/android/shell/BugreportProgressService.java b/packages/Shell/src/com/android/shell/BugreportProgressService.java index 68679c794c35..6f7d20a950d5 100644 --- a/packages/Shell/src/com/android/shell/BugreportProgressService.java +++ b/packages/Shell/src/com/android/shell/BugreportProgressService.java @@ -455,8 +455,7 @@ public class BugreportProgressService extends Service { intent.putExtra(DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH, bugreportHash); intent.putExtra(DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_NONCE, nonce); intent.putExtra(EXTRA_BUGREPORT, bugreportFileName); - context.sendBroadcastAsUser(intent, UserHandle.SYSTEM, - android.Manifest.permission.DUMP); + context.sendBroadcast(intent, android.Manifest.permission.DUMP); } /** diff --git a/packages/SystemUI/compose/core/src/com/android/systemui/compose/theme/SystemUITheme.kt b/packages/SystemUI/compose/core/src/com/android/systemui/compose/theme/SystemUITheme.kt index 79e3d3d475a8..00532f4e46b8 100644 --- a/packages/SystemUI/compose/core/src/com/android/systemui/compose/theme/SystemUITheme.kt +++ b/packages/SystemUI/compose/core/src/com/android/systemui/compose/theme/SystemUITheme.kt @@ -18,12 +18,17 @@ package com.android.systemui.compose.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Typography import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext +import com.android.systemui.compose.theme.typography.TypeScaleTokens +import com.android.systemui.compose.theme.typography.TypefaceNames +import com.android.systemui.compose.theme.typography.TypefaceTokens +import com.android.systemui.compose.theme.typography.TypographyTokens +import com.android.systemui.compose.theme.typography.systemUITypography /** The Material 3 theme that should wrap all SystemUI Composables. */ @Composable @@ -33,7 +38,7 @@ fun SystemUITheme( ) { val context = LocalContext.current - // TODO(b/230605885): Define our typography and color scheme. + // TODO(b/230605885): Define our color scheme. val colorScheme = if (isDarkTheme) { dynamicDarkColorScheme(context) @@ -41,7 +46,11 @@ fun SystemUITheme( dynamicLightColorScheme(context) } val androidColorScheme = AndroidColorScheme(context) - val typography = Typography() + val typefaceNames = remember(context) { TypefaceNames.get(context) } + val typography = + remember(typefaceNames) { + systemUITypography(TypographyTokens(TypeScaleTokens(TypefaceTokens(typefaceNames)))) + } MaterialTheme(colorScheme, typography = typography) { CompositionLocalProvider( diff --git a/packages/SystemUI/compose/core/src/com/android/systemui/compose/theme/typography/SystemUITypography.kt b/packages/SystemUI/compose/core/src/com/android/systemui/compose/theme/typography/SystemUITypography.kt new file mode 100644 index 000000000000..365f4bb69897 --- /dev/null +++ b/packages/SystemUI/compose/core/src/com/android/systemui/compose/theme/typography/SystemUITypography.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.compose.theme.typography + +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Typography + +/** + * The SystemUI typography. + * + * Do not use directly and call [MaterialTheme.typography] instead to access the different text + * styles. + */ +internal fun systemUITypography(typographyTokens: TypographyTokens): Typography { + return Typography( + displayLarge = typographyTokens.displayLarge, + displayMedium = typographyTokens.displayMedium, + displaySmall = typographyTokens.displaySmall, + headlineLarge = typographyTokens.headlineLarge, + headlineMedium = typographyTokens.headlineMedium, + headlineSmall = typographyTokens.headlineSmall, + titleLarge = typographyTokens.titleLarge, + titleMedium = typographyTokens.titleMedium, + titleSmall = typographyTokens.titleSmall, + bodyLarge = typographyTokens.bodyLarge, + bodyMedium = typographyTokens.bodyMedium, + bodySmall = typographyTokens.bodySmall, + labelLarge = typographyTokens.labelLarge, + labelMedium = typographyTokens.labelMedium, + labelSmall = typographyTokens.labelSmall, + ) +} diff --git a/packages/SystemUI/compose/core/src/com/android/systemui/compose/theme/typography/TypeScaleTokens.kt b/packages/SystemUI/compose/core/src/com/android/systemui/compose/theme/typography/TypeScaleTokens.kt new file mode 100644 index 000000000000..537ba0b7a834 --- /dev/null +++ b/packages/SystemUI/compose/core/src/com/android/systemui/compose/theme/typography/TypeScaleTokens.kt @@ -0,0 +1,97 @@ +/* + * 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.compose.theme.typography + +import androidx.compose.ui.unit.sp + +internal class TypeScaleTokens(typefaceTokens: TypefaceTokens) { + val bodyLargeFont = typefaceTokens.plain + val bodyLargeLineHeight = 24.0.sp + val bodyLargeSize = 16.sp + val bodyLargeTracking = 0.0.sp + val bodyLargeWeight = TypefaceTokens.WeightRegular + val bodyMediumFont = typefaceTokens.plain + val bodyMediumLineHeight = 20.0.sp + val bodyMediumSize = 14.sp + val bodyMediumTracking = 0.0.sp + val bodyMediumWeight = TypefaceTokens.WeightRegular + val bodySmallFont = typefaceTokens.plain + val bodySmallLineHeight = 16.0.sp + val bodySmallSize = 12.sp + val bodySmallTracking = 0.1.sp + val bodySmallWeight = TypefaceTokens.WeightRegular + val displayLargeFont = typefaceTokens.brand + val displayLargeLineHeight = 64.0.sp + val displayLargeSize = 57.sp + val displayLargeTracking = 0.0.sp + val displayLargeWeight = TypefaceTokens.WeightRegular + val displayMediumFont = typefaceTokens.brand + val displayMediumLineHeight = 52.0.sp + val displayMediumSize = 45.sp + val displayMediumTracking = 0.0.sp + val displayMediumWeight = TypefaceTokens.WeightRegular + val displaySmallFont = typefaceTokens.brand + val displaySmallLineHeight = 44.0.sp + val displaySmallSize = 36.sp + val displaySmallTracking = 0.0.sp + val displaySmallWeight = TypefaceTokens.WeightRegular + val headlineLargeFont = typefaceTokens.brand + val headlineLargeLineHeight = 40.0.sp + val headlineLargeSize = 32.sp + val headlineLargeTracking = 0.0.sp + val headlineLargeWeight = TypefaceTokens.WeightRegular + val headlineMediumFont = typefaceTokens.brand + val headlineMediumLineHeight = 36.0.sp + val headlineMediumSize = 28.sp + val headlineMediumTracking = 0.0.sp + val headlineMediumWeight = TypefaceTokens.WeightRegular + val headlineSmallFont = typefaceTokens.brand + val headlineSmallLineHeight = 32.0.sp + val headlineSmallSize = 24.sp + val headlineSmallTracking = 0.0.sp + val headlineSmallWeight = TypefaceTokens.WeightRegular + val labelLargeFont = typefaceTokens.plain + val labelLargeLineHeight = 20.0.sp + val labelLargeSize = 14.sp + val labelLargeTracking = 0.0.sp + val labelLargeWeight = TypefaceTokens.WeightMedium + val labelMediumFont = typefaceTokens.plain + val labelMediumLineHeight = 16.0.sp + val labelMediumSize = 12.sp + val labelMediumTracking = 0.1.sp + val labelMediumWeight = TypefaceTokens.WeightMedium + val labelSmallFont = typefaceTokens.plain + val labelSmallLineHeight = 16.0.sp + val labelSmallSize = 11.sp + val labelSmallTracking = 0.1.sp + val labelSmallWeight = TypefaceTokens.WeightMedium + val titleLargeFont = typefaceTokens.brand + val titleLargeLineHeight = 28.0.sp + val titleLargeSize = 22.sp + val titleLargeTracking = 0.0.sp + val titleLargeWeight = TypefaceTokens.WeightRegular + val titleMediumFont = typefaceTokens.plain + val titleMediumLineHeight = 24.0.sp + val titleMediumSize = 16.sp + val titleMediumTracking = 0.0.sp + val titleMediumWeight = TypefaceTokens.WeightMedium + val titleSmallFont = typefaceTokens.plain + val titleSmallLineHeight = 20.0.sp + val titleSmallSize = 14.sp + val titleSmallTracking = 0.0.sp + val titleSmallWeight = TypefaceTokens.WeightMedium +} diff --git a/packages/SystemUI/compose/core/src/com/android/systemui/compose/theme/typography/TypefaceTokens.kt b/packages/SystemUI/compose/core/src/com/android/systemui/compose/theme/typography/TypefaceTokens.kt new file mode 100644 index 000000000000..f3d554fc9363 --- /dev/null +++ b/packages/SystemUI/compose/core/src/com/android/systemui/compose/theme/typography/TypefaceTokens.kt @@ -0,0 +1,74 @@ +/* + * 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. + */ + +@file:OptIn(ExperimentalTextApi::class) + +package com.android.systemui.compose.theme.typography + +import android.content.Context +import androidx.compose.ui.text.ExperimentalTextApi +import androidx.compose.ui.text.font.DeviceFontFamilyName +import androidx.compose.ui.text.font.Font +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight + +internal class TypefaceTokens(typefaceNames: TypefaceNames) { + companion object { + val WeightMedium = FontWeight.Medium + val WeightRegular = FontWeight.Normal + } + + private val brandFont = DeviceFontFamilyName(typefaceNames.brand) + private val plainFont = DeviceFontFamilyName(typefaceNames.plain) + + val brand = + FontFamily( + Font(brandFont, weight = WeightMedium), + Font(brandFont, weight = WeightRegular), + ) + val plain = + FontFamily( + Font(plainFont, weight = WeightMedium), + Font(plainFont, weight = WeightRegular), + ) +} + +internal data class TypefaceNames +private constructor( + val brand: String, + val plain: String, +) { + private enum class Config(val configName: String, val default: String) { + Brand("config_headlineFontFamily", "sans-serif"), + Plain("config_bodyFontFamily", "sans-serif"), + } + + companion object { + fun get(context: Context): TypefaceNames { + return TypefaceNames( + brand = getTypefaceName(context, Config.Brand), + plain = getTypefaceName(context, Config.Plain), + ) + } + + private fun getTypefaceName(context: Context, config: Config): String { + return context + .getString(context.resources.getIdentifier(config.configName, "string", "android")) + .takeIf { it.isNotEmpty() } + ?: config.default + } + } +} diff --git a/packages/SystemUI/compose/core/src/com/android/systemui/compose/theme/typography/TypographyTokens.kt b/packages/SystemUI/compose/core/src/com/android/systemui/compose/theme/typography/TypographyTokens.kt new file mode 100644 index 000000000000..55f3d1fef05a --- /dev/null +++ b/packages/SystemUI/compose/core/src/com/android/systemui/compose/theme/typography/TypographyTokens.kt @@ -0,0 +1,142 @@ +/* + * 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.compose.theme.typography + +import androidx.compose.ui.text.TextStyle + +internal class TypographyTokens(typeScaleTokens: TypeScaleTokens) { + val bodyLarge = + TextStyle( + fontFamily = typeScaleTokens.bodyLargeFont, + fontWeight = typeScaleTokens.bodyLargeWeight, + fontSize = typeScaleTokens.bodyLargeSize, + lineHeight = typeScaleTokens.bodyLargeLineHeight, + letterSpacing = typeScaleTokens.bodyLargeTracking, + ) + val bodyMedium = + TextStyle( + fontFamily = typeScaleTokens.bodyMediumFont, + fontWeight = typeScaleTokens.bodyMediumWeight, + fontSize = typeScaleTokens.bodyMediumSize, + lineHeight = typeScaleTokens.bodyMediumLineHeight, + letterSpacing = typeScaleTokens.bodyMediumTracking, + ) + val bodySmall = + TextStyle( + fontFamily = typeScaleTokens.bodySmallFont, + fontWeight = typeScaleTokens.bodySmallWeight, + fontSize = typeScaleTokens.bodySmallSize, + lineHeight = typeScaleTokens.bodySmallLineHeight, + letterSpacing = typeScaleTokens.bodySmallTracking, + ) + val displayLarge = + TextStyle( + fontFamily = typeScaleTokens.displayLargeFont, + fontWeight = typeScaleTokens.displayLargeWeight, + fontSize = typeScaleTokens.displayLargeSize, + lineHeight = typeScaleTokens.displayLargeLineHeight, + letterSpacing = typeScaleTokens.displayLargeTracking, + ) + val displayMedium = + TextStyle( + fontFamily = typeScaleTokens.displayMediumFont, + fontWeight = typeScaleTokens.displayMediumWeight, + fontSize = typeScaleTokens.displayMediumSize, + lineHeight = typeScaleTokens.displayMediumLineHeight, + letterSpacing = typeScaleTokens.displayMediumTracking, + ) + val displaySmall = + TextStyle( + fontFamily = typeScaleTokens.displaySmallFont, + fontWeight = typeScaleTokens.displaySmallWeight, + fontSize = typeScaleTokens.displaySmallSize, + lineHeight = typeScaleTokens.displaySmallLineHeight, + letterSpacing = typeScaleTokens.displaySmallTracking, + ) + val headlineLarge = + TextStyle( + fontFamily = typeScaleTokens.headlineLargeFont, + fontWeight = typeScaleTokens.headlineLargeWeight, + fontSize = typeScaleTokens.headlineLargeSize, + lineHeight = typeScaleTokens.headlineLargeLineHeight, + letterSpacing = typeScaleTokens.headlineLargeTracking, + ) + val headlineMedium = + TextStyle( + fontFamily = typeScaleTokens.headlineMediumFont, + fontWeight = typeScaleTokens.headlineMediumWeight, + fontSize = typeScaleTokens.headlineMediumSize, + lineHeight = typeScaleTokens.headlineMediumLineHeight, + letterSpacing = typeScaleTokens.headlineMediumTracking, + ) + val headlineSmall = + TextStyle( + fontFamily = typeScaleTokens.headlineSmallFont, + fontWeight = typeScaleTokens.headlineSmallWeight, + fontSize = typeScaleTokens.headlineSmallSize, + lineHeight = typeScaleTokens.headlineSmallLineHeight, + letterSpacing = typeScaleTokens.headlineSmallTracking, + ) + val labelLarge = + TextStyle( + fontFamily = typeScaleTokens.labelLargeFont, + fontWeight = typeScaleTokens.labelLargeWeight, + fontSize = typeScaleTokens.labelLargeSize, + lineHeight = typeScaleTokens.labelLargeLineHeight, + letterSpacing = typeScaleTokens.labelLargeTracking, + ) + val labelMedium = + TextStyle( + fontFamily = typeScaleTokens.labelMediumFont, + fontWeight = typeScaleTokens.labelMediumWeight, + fontSize = typeScaleTokens.labelMediumSize, + lineHeight = typeScaleTokens.labelMediumLineHeight, + letterSpacing = typeScaleTokens.labelMediumTracking, + ) + val labelSmall = + TextStyle( + fontFamily = typeScaleTokens.labelSmallFont, + fontWeight = typeScaleTokens.labelSmallWeight, + fontSize = typeScaleTokens.labelSmallSize, + lineHeight = typeScaleTokens.labelSmallLineHeight, + letterSpacing = typeScaleTokens.labelSmallTracking, + ) + val titleLarge = + TextStyle( + fontFamily = typeScaleTokens.titleLargeFont, + fontWeight = typeScaleTokens.titleLargeWeight, + fontSize = typeScaleTokens.titleLargeSize, + lineHeight = typeScaleTokens.titleLargeLineHeight, + letterSpacing = typeScaleTokens.titleLargeTracking, + ) + val titleMedium = + TextStyle( + fontFamily = typeScaleTokens.titleMediumFont, + fontWeight = typeScaleTokens.titleMediumWeight, + fontSize = typeScaleTokens.titleMediumSize, + lineHeight = typeScaleTokens.titleMediumLineHeight, + letterSpacing = typeScaleTokens.titleMediumTracking, + ) + val titleSmall = + TextStyle( + fontFamily = typeScaleTokens.titleSmallFont, + fontWeight = typeScaleTokens.titleSmallWeight, + fontSize = typeScaleTokens.titleSmallSize, + lineHeight = typeScaleTokens.titleSmallLineHeight, + letterSpacing = typeScaleTokens.titleSmallTracking, + ) +} diff --git a/packages/SystemUI/res-keyguard/layout/fgs_footer.xml b/packages/SystemUI/res-keyguard/layout/fgs_footer.xml deleted file mode 100644 index ee588f997ab8..000000000000 --- a/packages/SystemUI/res-keyguard/layout/fgs_footer.xml +++ /dev/null @@ -1,105 +0,0 @@ -<?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. ---> -<!-- TODO(b/242040009): Remove this file. --> -<FrameLayout - xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="0dp" - android:layout_height="@dimen/qs_security_footer_single_line_height" - android:layout_weight="1" - android:gravity="center" - android:clickable="true" - android:visibility="gone"> - - <LinearLayout - android:id="@+id/fgs_text_container" - android:layout_width="match_parent" - android:layout_height="match_parent" - android:layout_marginEnd="@dimen/qs_footer_action_inset" - android:background="@drawable/qs_security_footer_background" - android:layout_gravity="end" - android:gravity="center" - android:paddingHorizontal="@dimen/qs_footer_padding" - > - - <ImageView - android:id="@+id/primary_footer_icon" - android:layout_width="@dimen/qs_footer_icon_size" - android:layout_height="@dimen/qs_footer_icon_size" - android:gravity="start" - android:layout_marginEnd="12dp" - android:contentDescription="@null" - android:src="@drawable/ic_info_outline" - android:tint="?android:attr/textColorSecondary" /> - - <TextView - android:id="@+id/footer_text" - android:layout_width="0dp" - android:layout_height="wrap_content" - android:layout_weight="1" - android:maxLines="1" - android:ellipsize="end" - android:textAppearance="@style/TextAppearance.QS.SecurityFooter" - android:textColor="?android:attr/textColorSecondary"/> - - <ImageView - android:id="@+id/fgs_new" - android:layout_width="12dp" - android:layout_height="12dp" - android:scaleType="fitCenter" - android:src="@drawable/fgs_dot" - android:contentDescription="@string/fgs_dot_content_description" - /> - - <ImageView - android:id="@+id/footer_icon" - android:layout_width="@dimen/qs_footer_icon_size" - android:layout_height="@dimen/qs_footer_icon_size" - android:layout_marginStart="8dp" - android:contentDescription="@null" - android:src="@*android:drawable/ic_chevron_end" - android:autoMirrored="true" - android:tint="?android:attr/textColorSecondary" /> - </LinearLayout> - - <FrameLayout - android:id="@+id/fgs_number_container" - android:layout_width="@dimen/qs_footer_action_button_size" - android:layout_height="@dimen/qs_footer_action_button_size" - android:background="@drawable/qs_footer_action_circle" - android:focusable="true" - android:visibility="gone"> - - <TextView - android:id="@+id/fgs_number" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:textAppearance="@style/TextAppearance.QS.SecurityFooter" - android:layout_gravity="center" - android:textColor="?android:attr/textColorPrimary" - android:textSize="18sp"/> - <ImageView - android:id="@+id/fgs_collapsed_new" - android:layout_width="12dp" - android:layout_height="12dp" - android:scaleType="fitCenter" - android:layout_gravity="bottom|end" - android:src="@drawable/fgs_dot" - android:contentDescription="@string/fgs_dot_content_description" - /> - </FrameLayout> - -</FrameLayout>
\ No newline at end of file diff --git a/packages/SystemUI/res-keyguard/layout/footer_actions.xml b/packages/SystemUI/res-keyguard/layout/footer_actions.xml index 2261ae8d7714..4a2a1cb9dc6d 100644 --- a/packages/SystemUI/res-keyguard/layout/footer_actions.xml +++ b/packages/SystemUI/res-keyguard/layout/footer_actions.xml @@ -16,10 +16,8 @@ --> <!-- Action buttons for footer in QS/QQS, containing settings button, power off button etc --> -<!-- TODO(b/242040009): Clean up this file. --> -<com.android.systemui.qs.FooterActionsView +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:androidprv="http://schemas.android.com/apk/prv/res/android" android:layout_width="match_parent" android:layout_height="@dimen/footer_actions_height" android:elevation="@dimen/qs_panel_elevation" @@ -28,74 +26,4 @@ android:background="@drawable/qs_footer_actions_background" android:gravity="center_vertical|end" android:layout_gravity="bottom" -> - - <LinearLayout - android:id="@+id/security_footers_container" - android:orientation="horizontal" - android:layout_height="@dimen/qs_footer_action_button_size" - android:layout_width="0dp" - android:layout_weight="1" - /> - - <!-- Negative margin equal to --> - <LinearLayout - android:layout_height="match_parent" - android:layout_width="wrap_content" - android:layout_marginEnd="@dimen/qs_footer_action_inset_negative" - > - - <com.android.systemui.statusbar.phone.MultiUserSwitch - android:id="@id/multi_user_switch" - android:layout_width="@dimen/qs_footer_action_button_size" - android:layout_height="@dimen/qs_footer_action_button_size" - android:background="@drawable/qs_footer_action_circle" - android:focusable="true"> - - <ImageView - android:id="@+id/multi_user_avatar" - android:layout_width="@dimen/qs_footer_icon_size" - android:layout_height="@dimen/qs_footer_icon_size" - android:layout_gravity="center" - android:scaleType="centerInside" /> - </com.android.systemui.statusbar.phone.MultiUserSwitch> - - <com.android.systemui.statusbar.AlphaOptimizedFrameLayout - android:id="@id/settings_button_container" - android:layout_width="@dimen/qs_footer_action_button_size" - android:layout_height="@dimen/qs_footer_action_button_size" - android:background="@drawable/qs_footer_action_circle" - android:clipChildren="false" - android:clipToPadding="false"> - - <com.android.systemui.statusbar.phone.SettingsButton - android:id="@+id/settings_button" - android:layout_width="@dimen/qs_footer_icon_size" - android:layout_height="@dimen/qs_footer_icon_size" - android:layout_gravity="center" - android:background="@android:color/transparent" - android:focusable="false" - android:clickable="false" - android:importantForAccessibility="yes" - android:contentDescription="@string/accessibility_quick_settings_settings" - android:scaleType="centerInside" - android:src="@drawable/ic_settings" - android:tint="?android:attr/textColorPrimary" /> - - </com.android.systemui.statusbar.AlphaOptimizedFrameLayout> - - <com.android.systemui.statusbar.AlphaOptimizedImageView - android:id="@id/pm_lite" - android:layout_width="@dimen/qs_footer_action_button_size" - android:layout_height="@dimen/qs_footer_action_button_size" - android:background="@drawable/qs_footer_action_circle_color" - android:clickable="true" - android:clipToPadding="false" - android:focusable="true" - android:padding="@dimen/qs_footer_icon_padding" - android:src="@*android:drawable/ic_lock_power_off" - android:contentDescription="@string/accessibility_quick_settings_power_menu" - android:tint="?androidprv:attr/textColorOnAccent" /> - - </LinearLayout> -</com.android.systemui.qs.FooterActionsView>
\ No newline at end of file +/>
\ No newline at end of file diff --git a/packages/SystemUI/res-keyguard/layout/keyguard_num_pad_key.xml b/packages/SystemUI/res-keyguard/layout/keyguard_num_pad_key.xml index 316ad39a9f05..411fea5dd22d 100644 --- a/packages/SystemUI/res-keyguard/layout/keyguard_num_pad_key.xml +++ b/packages/SystemUI/res-keyguard/layout/keyguard_num_pad_key.xml @@ -18,8 +18,6 @@ <TextView android:id="@+id/digit_text" style="@style/Widget.TextView.NumPadKey.Digit" - android:autoSizeMaxTextSize="32sp" - android:autoSizeTextType="uniform" android:layout_width="wrap_content" android:layout_height="wrap_content" /> diff --git a/packages/SystemUI/res/drawable/ic_circle_check_box.xml b/packages/SystemUI/res/drawable/ic_circle_check_box.xml index b44a32dda172..00c10cecfe95 100644 --- a/packages/SystemUI/res/drawable/ic_circle_check_box.xml +++ b/packages/SystemUI/res/drawable/ic_circle_check_box.xml @@ -18,7 +18,7 @@ <item android:id="@+id/checked" android:state_checked="true" - android:drawable="@drawable/media_output_status_check" /> + android:drawable="@drawable/media_output_status_filled_checked" /> <item android:id="@+id/unchecked" android:state_checked="false" diff --git a/packages/SystemUI/res/drawable/media_output_dialog_seekbar_background.xml b/packages/SystemUI/res/drawable/media_output_dialog_seekbar_background.xml index 55dce8f7e66c..43cf00332f63 100644 --- a/packages/SystemUI/res/drawable/media_output_dialog_seekbar_background.xml +++ b/packages/SystemUI/res/drawable/media_output_dialog_seekbar_background.xml @@ -17,7 +17,10 @@ <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@android:id/background"> <shape> - <corners android:radius="28dp" /> + <corners + android:bottomRightRadius="28dp" + android:topRightRadius="28dp" + /> <solid android:color="@android:color/transparent" /> <size android:height="64dp"/> diff --git a/packages/SystemUI/res/drawable/media_output_icon_volume_off.xml b/packages/SystemUI/res/drawable/media_output_icon_volume_off.xml new file mode 100644 index 000000000000..f29f44ce8226 --- /dev/null +++ b/packages/SystemUI/res/drawable/media_output_icon_volume_off.xml @@ -0,0 +1,27 @@ +<!-- + ~ 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. + --> + +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="48dp" + android:height="48dp" + android:viewportWidth="48" + android:viewportHeight="48" + android:tint="?attr/colorControlNormal" + android:autoMirrored="true"> + <path + android:fillColor="@color/media_dialog_item_main_content" + android:pathData="M40.65,45.2 L34.05,38.6Q32.65,39.6 31.025,40.325Q29.4,41.05 27.65,41.45V38.35Q28.8,38 29.875,37.575Q30.95,37.15 31.9,36.45L23.65,28.15V40L13.65,30H5.65V18H13.45L2.45,7L4.6,4.85L42.8,43ZM38.85,33.6 L36.7,31.45Q37.7,29.75 38.175,27.85Q38.65,25.95 38.65,23.95Q38.65,18.8 35.65,14.725Q32.65,10.65 27.65,9.55V6.45Q33.85,7.85 37.75,12.725Q41.65,17.6 41.65,23.95Q41.65,26.5 40.95,28.95Q40.25,31.4 38.85,33.6ZM32.15,26.9 L27.65,22.4V15.9Q30,17 31.325,19.2Q32.65,21.4 32.65,24Q32.65,24.75 32.525,25.475Q32.4,26.2 32.15,26.9ZM23.65,18.4 L18.45,13.2 23.65,8ZM20.65,32.7V25.2L16.45,21H8.65V27H14.95ZM18.55,23.1Z"/> +</vector> diff --git a/packages/SystemUI/res/drawable/media_output_item_check_box.xml b/packages/SystemUI/res/drawable/media_output_item_check_box.xml new file mode 100644 index 000000000000..a0742900e4c6 --- /dev/null +++ b/packages/SystemUI/res/drawable/media_output_item_check_box.xml @@ -0,0 +1,26 @@ +<!-- + ~ 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. + --> + +<selector xmlns:android="http://schemas.android.com/apk/res/android"> + <item + android:id="@+id/checked" + android:state_checked="true" + android:drawable="@drawable/media_output_status_checked" /> + <item + android:id="@+id/unchecked" + android:state_checked="false" + android:drawable="@drawable/media_output_status_selectable" /> +</selector> diff --git a/packages/SystemUI/res/drawable/media_output_status_checked.xml b/packages/SystemUI/res/drawable/media_output_status_checked.xml new file mode 100644 index 000000000000..8f83ee2fa160 --- /dev/null +++ b/packages/SystemUI/res/drawable/media_output_status_checked.xml @@ -0,0 +1,26 @@ +<!-- + ~ 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. + --> + +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="24dp" + android:height="24dp" + android:viewportWidth="24" + android:viewportHeight="24" + android:tint="?attr/colorControlNormal"> + <path + android:fillColor="@android:color/white" + android:pathData="M9.55,18 L3.85,12.3 5.275,10.875 9.55,15.15 18.725,5.975 20.15,7.4Z"/> +</vector> diff --git a/packages/SystemUI/res/drawable/media_output_status_check.xml b/packages/SystemUI/res/drawable/media_output_status_filled_checked.xml index 3d64f83eabe3..3d64f83eabe3 100644 --- a/packages/SystemUI/res/drawable/media_output_status_check.xml +++ b/packages/SystemUI/res/drawable/media_output_status_filled_checked.xml diff --git a/packages/SystemUI/res/drawable/media_output_status_selectable.xml b/packages/SystemUI/res/drawable/media_output_status_selectable.xml new file mode 100644 index 000000000000..5465aa7300ab --- /dev/null +++ b/packages/SystemUI/res/drawable/media_output_status_selectable.xml @@ -0,0 +1,26 @@ +<!-- + ~ 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. + --> + +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="24dp" + android:height="24dp" + android:viewportWidth="24" + android:viewportHeight="24" + android:tint="?attr/colorControlNormal"> + <path + android:fillColor="@android:color/white" + android:pathData="M11,19V13H5V11H11V5H13V11H19V13H13V19Z"/> +</vector> diff --git a/packages/SystemUI/res/drawable/media_output_title_icon_area.xml b/packages/SystemUI/res/drawable/media_output_title_icon_area.xml new file mode 100644 index 000000000000..b93793773179 --- /dev/null +++ b/packages/SystemUI/res/drawable/media_output_title_icon_area.xml @@ -0,0 +1,25 @@ +<!-- + ~ 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. + --> + +<shape xmlns:android="http://schemas.android.com/apk/res/android" + android:shape="rectangle"> + <corners + android:bottomLeftRadius="28dp" + android:topLeftRadius="28dp" + android:bottomRightRadius="0dp" + android:topRightRadius="0dp"/> + <solid android:color="@color/media_dialog_item_background" /> +</shape>
\ No newline at end of file diff --git a/packages/SystemUI/res/layout/activity_rear_display_education.xml b/packages/SystemUI/res/layout/activity_rear_display_education.xml index 73d3f0236fff..f5fc48c70003 100644 --- a/packages/SystemUI/res/layout/activity_rear_display_education.xml +++ b/packages/SystemUI/res/layout/activity_rear_display_education.xml @@ -33,7 +33,7 @@ android:layout_width="@dimen/rear_display_animation_width" android:layout_height="@dimen/rear_display_animation_height" android:layout_gravity="center" - android:contentDescription="@null" + android:contentDescription="@string/rear_display_accessibility_folded_animation" android:scaleType="fitXY" app:lottie_rawRes="@raw/rear_display_folded" app:lottie_autoPlay="true" diff --git a/packages/SystemUI/res/layout/activity_rear_display_education_opened.xml b/packages/SystemUI/res/layout/activity_rear_display_education_opened.xml index 20b93d9bc40d..6de06f76ebbf 100644 --- a/packages/SystemUI/res/layout/activity_rear_display_education_opened.xml +++ b/packages/SystemUI/res/layout/activity_rear_display_education_opened.xml @@ -34,7 +34,7 @@ android:layout_width="@dimen/rear_display_animation_width" android:layout_height="@dimen/rear_display_animation_height" android:layout_gravity="center" - android:contentDescription="@null" + android:contentDescription="@string/rear_display_accessibility_unfolded_animation" android:scaleType="fitXY" app:lottie_rawRes="@raw/rear_display_turnaround" app:lottie_autoPlay="true" diff --git a/packages/SystemUI/res/layout/media_output_list_group_divider.xml b/packages/SystemUI/res/layout/media_output_list_group_divider.xml new file mode 100644 index 000000000000..5e96866c0a9a --- /dev/null +++ b/packages/SystemUI/res/layout/media_output_list_group_divider.xml @@ -0,0 +1,35 @@ +<?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. + --> + +<LinearLayout + xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/device_container" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical"> + <TextView + android:id="@+id/title" + android:layout_width="wrap_content" + android:layout_height="36dp" + android:layout_gravity="center_vertical|start" + android:layout_marginStart="16dp" + android:layout_marginEnd="56dp" + android:ellipsize="end" + android:maxLines="1" + android:fontFamily="@*android:string/config_headlineFontFamilyMedium" + android:textSize="16sp"/> +</LinearLayout>
\ No newline at end of file diff --git a/packages/SystemUI/res/layout/media_output_list_item_advanced.xml b/packages/SystemUI/res/layout/media_output_list_item_advanced.xml new file mode 100644 index 000000000000..d49b9f105803 --- /dev/null +++ b/packages/SystemUI/res/layout/media_output_list_item_advanced.xml @@ -0,0 +1,156 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + ~ Copyright (C) 2020 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. + --> + +<FrameLayout + xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/device_container" + android:layout_width="match_parent" + android:layout_height="wrap_content"> + <FrameLayout + android:layout_width="match_parent" + android:layout_height="64dp" + android:id="@+id/item_layout" + android:background="@drawable/media_output_item_background" + android:layout_marginStart="16dp" + android:layout_marginEnd="80dp" + android:layout_marginBottom="12dp"> + <FrameLayout + android:layout_width="match_parent" + android:layout_height="match_parent" + android:layout_gravity="center_vertical|start"> + <com.android.systemui.media.dialog.MediaOutputSeekbar + android:id="@+id/volume_seekbar" + android:splitTrack="false" + android:visibility="gone" + android:paddingStart="64dp" + android:paddingEnd="0dp" + android:background="@null" + android:contentDescription="@string/media_output_dialog_accessibility_seekbar" + android:progressDrawable="@drawable/media_output_dialog_seekbar_background" + android:thumb="@null" + android:layout_width="match_parent" + android:layout_height="match_parent"/> + </FrameLayout> + + <FrameLayout + android:id="@+id/icon_area" + android:layout_width="64dp" + android:layout_height="64dp" + android:background="@drawable/media_output_title_icon_area" + android:layout_gravity="center_vertical|start"> + <ImageView + android:id="@+id/title_icon" + android:layout_width="24dp" + android:layout_height="24dp" + android:animateLayoutChanges="true" + android:layout_gravity="center"/> + <TextView + android:id="@+id/volume_value" + android:animateLayoutChanges="true" + android:layout_gravity="center" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:fontFamily="@*android:string/config_headlineFontFamilyMedium" + android:textSize="16sp" + android:visibility="gone"/> + </FrameLayout> + + <TextView + android:id="@+id/title" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_gravity="center_vertical|start" + android:layout_marginStart="72dp" + android:layout_marginEnd="56dp" + android:ellipsize="end" + android:maxLines="1" + android:fontFamily="@*android:string/config_headlineFontFamilyMedium" + android:textSize="16sp"/> + + <LinearLayout + android:id="@+id/two_line_layout" + android:orientation="vertical" + android:layout_width="wrap_content" + android:layout_gravity="center_vertical|start" + android:layout_height="48dp" + android:layout_marginEnd="56dp" + android:layout_marginStart="72dp"> + <TextView + android:id="@+id/two_line_title" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:ellipsize="end" + android:maxLines="1" + android:fontFamily="@*android:string/config_headlineFontFamilyMedium" + android:textColor="@color/media_dialog_item_main_content" + android:textSize="16sp"/> + <TextView + android:id="@+id/subtitle" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:ellipsize="end" + android:maxLines="1" + android:textColor="@color/media_dialog_item_main_content" + android:textSize="14sp" + android:fontFamily="@*android:string/config_bodyFontFamily" + android:visibility="gone"/> + </LinearLayout> + + <ProgressBar + android:id="@+id/volume_indeterminate_progress" + style="?android:attr/progressBarStyleSmallTitle" + android:layout_width="24dp" + android:layout_height="24dp" + android:layout_marginEnd="16dp" + android:indeterminate="true" + android:layout_gravity="end|center" + android:indeterminateOnly="true" + android:visibility="gone"/> + + <ImageView + android:id="@+id/media_output_item_status" + android:layout_width="24dp" + android:layout_height="24dp" + android:layout_marginEnd="16dp" + android:indeterminate="true" + android:layout_gravity="end|center" + android:indeterminateOnly="true" + android:importantForAccessibility="no" + android:visibility="gone"/> + </FrameLayout> + <FrameLayout + android:id="@+id/end_action_area" + android:layout_width="64dp" + android:layout_height="64dp" + android:visibility="gone" + android:layout_marginBottom="6dp" + android:layout_marginEnd="8dp" + android:layout_gravity="end|center" + android:gravity="center" + android:background="@drawable/media_output_item_background_active"> + <CheckBox + android:id="@+id/check_box" + android:focusable="false" + android:importantForAccessibility="no" + android:layout_gravity="center" + android:layout_width="24dp" + android:layout_height="24dp" + android:button="@drawable/media_output_item_check_box" + android:visibility="gone" + /> + </FrameLayout> +</FrameLayout>
\ No newline at end of file diff --git a/packages/SystemUI/res/layout/quick_settings_security_footer.xml b/packages/SystemUI/res/layout/quick_settings_security_footer.xml deleted file mode 100644 index 194f3dd5dc26..000000000000 --- a/packages/SystemUI/res/layout/quick_settings_security_footer.xml +++ /dev/null @@ -1,61 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- - Copyright (C) 2014 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. ---> -<!-- TODO(b/242040009): Remove this file. --> -<LinearLayout - xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="0dp" - android:layout_height="@dimen/qs_security_footer_single_line_height" - android:layout_weight="1" - android:clickable="true" - android:orientation="horizontal" - android:paddingHorizontal="@dimen/qs_footer_padding" - android:gravity="center_vertical" - android:layout_gravity="center_vertical|center_horizontal" - android:layout_marginEnd="@dimen/qs_footer_action_inset" - android:background="@drawable/qs_security_footer_background" - > - - <ImageView - android:id="@+id/primary_footer_icon" - android:layout_width="@dimen/qs_footer_icon_size" - android:layout_height="@dimen/qs_footer_icon_size" - android:gravity="start" - android:layout_marginEnd="12dp" - android:contentDescription="@null" - android:tint="?android:attr/textColorSecondary" /> - - <TextView - android:id="@+id/footer_text" - android:layout_width="0dp" - android:layout_height="wrap_content" - android:layout_weight="1" - android:singleLine="true" - android:ellipsize="end" - android:textAppearance="@style/TextAppearance.QS.SecurityFooter" - android:textColor="?android:attr/textColorSecondary"/> - - <ImageView - android:id="@+id/footer_icon" - android:layout_width="@dimen/qs_footer_icon_size" - android:layout_height="@dimen/qs_footer_icon_size" - android:layout_marginStart="8dp" - android:contentDescription="@null" - android:src="@*android:drawable/ic_chevron_end" - android:autoMirrored="true" - android:tint="?android:attr/textColorSecondary" /> - -</LinearLayout> diff --git a/packages/SystemUI/res/layout/super_notification_shade.xml b/packages/SystemUI/res/layout/super_notification_shade.xml index bafdb11ab211..4abc1769ab54 100644 --- a/packages/SystemUI/res/layout/super_notification_shade.xml +++ b/packages/SystemUI/res/layout/super_notification_shade.xml @@ -98,16 +98,18 @@ android:singleLine="true" android:ellipsize="marquee" android:focusable="true" /> - <FrameLayout android:id="@+id/keyguard_bouncer_container" - android:layout_height="0dp" - android:layout_width="match_parent" - android:layout_weight="1" - android:background="@android:color/transparent" - android:visibility="invisible" - android:clipChildren="false" - android:clipToPadding="false" /> </LinearLayout> + <FrameLayout android:id="@+id/keyguard_bouncer_container" + android:paddingTop="@dimen/status_bar_height" + android:layout_height="match_parent" + android:layout_width="match_parent" + android:layout_weight="1" + android:background="@android:color/transparent" + android:visibility="invisible" + android:clipChildren="false" + android:clipToPadding="false" /> + <com.android.systemui.biometrics.AuthRippleView android:id="@+id/auth_ripple" android:layout_width="match_parent" diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml index dc7e4e4d8947..73baeacc22c3 100644 --- a/packages/SystemUI/res/values/dimens.xml +++ b/packages/SystemUI/res/values/dimens.xml @@ -1222,6 +1222,8 @@ <dimen name="media_output_dialog_app_tier_icon_size">20dp</dimen> <dimen name="media_output_dialog_background_radius">16dp</dimen> <dimen name="media_output_dialog_active_background_radius">28dp</dimen> + <dimen name="media_output_dialog_default_margin_end">16dp</dimen> + <dimen name="media_output_dialog_selectable_margin_end">80dp</dimen> <!-- Distance that the full shade transition takes in order to complete by tapping on a button like "expand". --> diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml index 9ee918dde6dc..5d4fa58cfcd1 100644 --- a/packages/SystemUI/res/values/strings.xml +++ b/packages/SystemUI/res/values/strings.xml @@ -849,7 +849,7 @@ <string name="sensor_privacy_htt_blocked_dialog_content">To use the microphone button, enable microphone access in Settings.</string> <!-- Sensor privacy dialog: Button to open system settings [CHAR LIMIT=50] --> - <string name="sensor_privacy_dialog_open_settings">Open settings.</string> + <string name="sensor_privacy_dialog_open_settings">Open Settings</string> <!-- Default name for the media device shown in the output switcher when the name is not available [CHAR LIMIT=30] --> <string name="media_seamless_other_device">Other device</string> @@ -2481,7 +2481,7 @@ <!-- Controls menu, edit [CHAR_LIMIT=30] --> <string name="controls_menu_edit">Edit controls</string> - <!-- Title for the media output group dialog with media related devices [CHAR LIMIT=50] --> + <!-- Title for the media output dialog with media related devices [CHAR LIMIT=50] --> <string name="media_output_dialog_add_output">Add outputs</string> <!-- Title for the media output slice with group devices [CHAR LIMIT=50] --> <string name="media_output_dialog_group">Group</string> @@ -2505,6 +2505,8 @@ <string name="media_output_dialog_accessibility_title">Available devices for audio output.</string> <!-- Accessibility text describing purpose of seekbar in media output dialog. [CHAR LIMIT=NONE] --> <string name="media_output_dialog_accessibility_seekbar">Volume</string> + <!-- Summary for media output volume of a device in percentage [CHAR LIMIT=NONE] --> + <string name="media_output_dialog_volume_percentage"><xliff:g id="percentage" example="10">%1$d</xliff:g>%%</string> <!-- Media Output Broadcast Dialog --> <!-- Title for Broadcast First Notify Dialog [CHAR LIMIT=60] --> @@ -2872,4 +2874,8 @@ <string name="rear_display_bottom_sheet_description">Use the rear-facing camera for a wider photo with higher resolution.</string> <!-- Text for education page description to warn user that the display will turn off if the button is clicked. [CHAR_LIMIT=NONE] --> <string name="rear_display_bottom_sheet_warning"><b>✱ This screen will turn off</b></string> + <!-- Text for education page content description for folded animation. [CHAR_LIMIT=NONE] --> + <string name="rear_display_accessibility_folded_animation">Foldable device being unfolded</string> + <!-- Text for education page content description for unfolded animation. [CHAR_LIMIT=NONE] --> + <string name="rear_display_accessibility_unfolded_animation">Foldable device being flipped around</string> </resources> diff --git a/packages/SystemUI/screenshot/src/com/android/systemui/testing/screenshot/ViewScreenshotTestRule.kt b/packages/SystemUI/screenshot/src/com/android/systemui/testing/screenshot/ViewScreenshotTestRule.kt index 6d0cc5ee4feb..738b37c9eea4 100644 --- a/packages/SystemUI/screenshot/src/com/android/systemui/testing/screenshot/ViewScreenshotTestRule.kt +++ b/packages/SystemUI/screenshot/src/com/android/systemui/testing/screenshot/ViewScreenshotTestRule.kt @@ -34,7 +34,6 @@ import org.junit.runners.model.Statement import platform.test.screenshot.DeviceEmulationRule import platform.test.screenshot.DeviceEmulationSpec import platform.test.screenshot.MaterialYouColorsRule -import platform.test.screenshot.PathConfig import platform.test.screenshot.ScreenshotTestRule import platform.test.screenshot.getEmulatedDevicePathConfig import platform.test.screenshot.matchers.BitmapMatcher @@ -43,7 +42,6 @@ import platform.test.screenshot.matchers.BitmapMatcher class ViewScreenshotTestRule( emulationSpec: DeviceEmulationSpec, private val matcher: BitmapMatcher = UnitTestBitmapMatcher, - pathConfig: PathConfig = getEmulatedDevicePathConfig(emulationSpec), assetsPathRelativeToBuildRoot: String ) : TestRule { private val colorsRule = MaterialYouColorsRule() diff --git a/packages/SystemUI/shared/src/com/android/systemui/flags/FlagManager.kt b/packages/SystemUI/shared/src/com/android/systemui/flags/FlagManager.kt index d172690e2488..d85292a90d63 100644 --- a/packages/SystemUI/shared/src/com/android/systemui/flags/FlagManager.kt +++ b/packages/SystemUI/shared/src/com/android/systemui/flags/FlagManager.kt @@ -38,6 +38,7 @@ class FlagManager constructor( const val ACTION_SET_FLAG = "com.android.systemui.action.SET_FLAG" const val ACTION_GET_FLAGS = "com.android.systemui.action.GET_FLAGS" const val FLAGS_PERMISSION = "com.android.systemui.permission.FLAGS" + const val ACTION_SYSUI_STARTED = "com.android.systemui.STARTED" const val EXTRA_ID = "id" const val EXTRA_VALUE = "value" const val EXTRA_FLAGS = "flags" diff --git a/packages/SystemUI/src/com/android/systemui/util/condition/CombinedCondition.kt b/packages/SystemUI/shared/src/com/android/systemui/shared/condition/CombinedCondition.kt index da81d540f189..2d83458ec2f7 100644 --- a/packages/SystemUI/src/com/android/systemui/util/condition/CombinedCondition.kt +++ b/packages/SystemUI/shared/src/com/android/systemui/shared/condition/CombinedCondition.kt @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.systemui.util.condition +package com.android.systemui.shared.condition /** * A higher order [Condition] which combines multiple conditions with a specified diff --git a/packages/SystemUI/src/com/android/systemui/util/condition/Condition.java b/packages/SystemUI/shared/src/com/android/systemui/shared/condition/Condition.java index b39adefa238b..cc48090e1217 100644 --- a/packages/SystemUI/src/com/android/systemui/util/condition/Condition.java +++ b/packages/SystemUI/shared/src/com/android/systemui/shared/condition/Condition.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 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. @@ -14,13 +14,14 @@ * limitations under the License. */ -package com.android.systemui.util.condition; +package com.android.systemui.shared.condition; import android.util.Log; -import com.android.systemui.statusbar.policy.CallbackController; - -import org.jetbrains.annotations.NotNull; +import androidx.annotation.NonNull; +import androidx.lifecycle.Lifecycle; +import androidx.lifecycle.LifecycleEventObserver; +import androidx.lifecycle.LifecycleOwner; import java.lang.ref.WeakReference; import java.util.ArrayList; @@ -33,7 +34,7 @@ import java.util.List; * Base class for a condition that needs to be fulfilled in order for {@link Monitor} to inform * its callbacks. */ -public abstract class Condition implements CallbackController<Condition.Callback> { +public abstract class Condition { private final String mTag = getClass().getSimpleName(); private final ArrayList<WeakReference<Callback>> mCallbacks = new ArrayList<>(); @@ -79,8 +80,7 @@ public abstract class Condition implements CallbackController<Condition.Callback * Registers a callback to receive updates once started. This should be called before * {@link #start()}. Also triggers the callback immediately if already started. */ - @Override - public void addCallback(@NotNull Callback callback) { + public void addCallback(@NonNull Callback callback) { if (shouldLog()) Log.d(mTag, "adding callback"); mCallbacks.add(new WeakReference<>(callback)); @@ -96,8 +96,7 @@ public abstract class Condition implements CallbackController<Condition.Callback /** * Removes the provided callback from further receiving updates. */ - @Override - public void removeCallback(@NotNull Callback callback) { + public void removeCallback(@NonNull Callback callback) { if (shouldLog()) Log.d(mTag, "removing callback"); final Iterator<WeakReference<Callback>> iterator = mCallbacks.iterator(); while (iterator.hasNext()) { @@ -116,6 +115,29 @@ public abstract class Condition implements CallbackController<Condition.Callback } /** + * Wrapper to {@link #addCallback(Callback)} when a lifecycle is in the resumed state + * and {@link #removeCallback(Callback)} when not resumed automatically. + */ + public Callback observe(LifecycleOwner owner, Callback listener) { + return observe(owner.getLifecycle(), listener); + } + + /** + * Wrapper to {@link #addCallback(Callback)} when a lifecycle is in the resumed state + * and {@link #removeCallback(Condition.Callback)} when not resumed automatically. + */ + public Callback observe(Lifecycle lifecycle, Callback listener) { + lifecycle.addObserver((LifecycleEventObserver) (lifecycleOwner, event) -> { + if (event == Lifecycle.Event.ON_RESUME) { + addCallback(listener); + } else if (event == Lifecycle.Event.ON_PAUSE) { + removeCallback(listener); + } + }); + return listener; + } + + /** * Updates the value for whether the condition has been fulfilled, and sends an update if the * value changes and any callback is registered. * @@ -187,7 +209,7 @@ public abstract class Condition implements CallbackController<Condition.Callback * Creates a new condition which will only be true when both this condition and all the provided * conditions are true. */ - public Condition and(Collection<Condition> others) { + public Condition and(@NonNull Collection<Condition> others) { final List<Condition> conditions = new ArrayList<>(others); conditions.add(this); return new CombinedCondition(conditions, Evaluator.OP_AND); @@ -197,7 +219,7 @@ public abstract class Condition implements CallbackController<Condition.Callback * Creates a new condition which will only be true when both this condition and the provided * condition is true. */ - public Condition and(Condition other) { + public Condition and(@NonNull Condition other) { return new CombinedCondition(Arrays.asList(this, other), Evaluator.OP_AND); } @@ -205,7 +227,7 @@ public abstract class Condition implements CallbackController<Condition.Callback * Creates a new condition which will only be true when either this condition or any of the * provided conditions are true. */ - public Condition or(Collection<Condition> others) { + public Condition or(@NonNull Collection<Condition> others) { final List<Condition> conditions = new ArrayList<>(others); conditions.add(this); return new CombinedCondition(conditions, Evaluator.OP_OR); @@ -215,7 +237,7 @@ public abstract class Condition implements CallbackController<Condition.Callback * Creates a new condition which will only be true when either this condition or the provided * condition is true. */ - public Condition or(Condition other) { + public Condition or(@NonNull Condition other) { return new CombinedCondition(Arrays.asList(this, other), Evaluator.OP_OR); } diff --git a/packages/SystemUI/src/com/android/systemui/util/condition/Evaluator.kt b/packages/SystemUI/shared/src/com/android/systemui/shared/condition/Evaluator.kt index cf44e84a563f..23742c503ed3 100644 --- a/packages/SystemUI/src/com/android/systemui/util/condition/Evaluator.kt +++ b/packages/SystemUI/shared/src/com/android/systemui/shared/condition/Evaluator.kt @@ -1,4 +1,20 @@ -package com.android.systemui.util.condition +/* + * 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.condition import android.annotation.IntDef diff --git a/packages/SystemUI/src/com/android/systemui/util/condition/Monitor.java b/packages/SystemUI/shared/src/com/android/systemui/shared/condition/Monitor.java index 24bc9078475f..95675cef9136 100644 --- a/packages/SystemUI/src/com/android/systemui/util/condition/Monitor.java +++ b/packages/SystemUI/shared/src/com/android/systemui/shared/condition/Monitor.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 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. @@ -14,14 +14,14 @@ * limitations under the License. */ -package com.android.systemui.util.condition; +package com.android.systemui.shared.condition; import android.util.ArraySet; import android.util.Log; -import com.android.systemui.dagger.qualifiers.Main; +import androidx.annotation.NonNull; -import org.jetbrains.annotations.NotNull; +import com.android.systemui.dagger.qualifiers.Main; import java.util.ArrayList; import java.util.Collections; @@ -100,7 +100,7 @@ public class Monitor { * @param subscription A {@link Subscription} detailing the desired conditions and callback. * @return A {@link Subscription.Token} that can be used to remove the subscription. */ - public Subscription.Token addSubscription(@NotNull Subscription subscription) { + public Subscription.Token addSubscription(@NonNull Subscription subscription) { final Subscription.Token token = new Subscription.Token(); final SubscriptionState state = new SubscriptionState(subscription); @@ -131,7 +131,7 @@ public class Monitor { * @param token The {@link Subscription.Token} returned when the {@link Subscription} was * originally added. */ - public void removeSubscription(@NotNull Subscription.Token token) { + public void removeSubscription(@NonNull Subscription.Token token) { mExecutor.execute(() -> { if (shouldLog()) Log.d(mTag, "removing subscription"); if (!mSubscriptions.containsKey(token)) { diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/recents/utilities/PreviewPositionHelper.java b/packages/SystemUI/shared/src/com/android/systemui/shared/recents/utilities/PreviewPositionHelper.java index c9ea79432360..5883b6c0e723 100644 --- a/packages/SystemUI/shared/src/com/android/systemui/shared/recents/utilities/PreviewPositionHelper.java +++ b/packages/SystemUI/shared/src/com/android/systemui/shared/recents/utilities/PreviewPositionHelper.java @@ -87,8 +87,8 @@ public class PreviewPositionHelper { taskPercent = mDesiredStagePosition != STAGE_POSITION_TOP_OR_LEFT ? mSplitBounds.topTaskPercent : (1 - (mSplitBounds.topTaskPercent + mSplitBounds.dividerHeightPercent)); - // Scale portrait height to that of (actual screen - taskbar inset) - fullscreenTaskHeight = (screenHeightPx) * taskPercent; + // Scale portrait height to that of the actual screen + fullscreenTaskHeight = screenHeightPx * taskPercent; if (mTaskbarInApp) { canvasScreenRatio = canvasHeight / fullscreenTaskHeight; } else { diff --git a/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt b/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt index 87e9d5630b74..8f38e5800015 100644 --- a/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt +++ b/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt @@ -15,6 +15,7 @@ */ package com.android.keyguard +import android.app.WallpaperManager import android.content.BroadcastReceiver import android.content.Context import android.content.Intent @@ -100,9 +101,13 @@ open class ClockEventController @Inject constructor( private val regionSamplingEnabled = featureFlags.isEnabled(REGION_SAMPLING) private fun updateColors() { + if (regionSamplingEnabled && smallRegionSampler != null && largeRegionSampler != null) { - smallClockIsDark = smallRegionSampler!!.currentRegionDarkness().isDark - largeClockIsDark = largeRegionSampler!!.currentRegionDarkness().isDark + val wallpaperManager = WallpaperManager.getInstance(context) + if (!wallpaperManager.lockScreenWallpaperExists()) { + smallClockIsDark = smallRegionSampler!!.currentRegionDarkness().isDark + largeClockIsDark = largeRegionSampler!!.currentRegionDarkness().isDark + } } else { val isLightTheme = TypedValue() context.theme.resolveAttribute(android.R.attr.isLightTheme, isLightTheme, true) diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputViewController.java index 860c8e3a9f77..7da27b1d6898 100644 --- a/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputViewController.java +++ b/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputViewController.java @@ -260,7 +260,8 @@ public abstract class KeyguardAbsKeyInputViewController<T extends KeyguardAbsKey if (reason != PROMPT_REASON_NONE) { int promtReasonStringRes = mView.getPromptReasonStringRes(reason); if (promtReasonStringRes != 0) { - mMessageAreaController.setMessage(promtReasonStringRes); + mMessageAreaController.setMessage( + mView.getResources().getString(promtReasonStringRes), false); } } } diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardInputViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardInputViewController.java index 2e9ad5868eba..53b569af29e1 100644 --- a/packages/SystemUI/src/com/android/keyguard/KeyguardInputViewController.java +++ b/packages/SystemUI/src/com/android/keyguard/KeyguardInputViewController.java @@ -143,7 +143,9 @@ public abstract class KeyguardInputViewController<T extends KeyguardInputView> public void startAppearAnimation() { if (TextUtils.isEmpty(mMessageAreaController.getMessage())) { - mMessageAreaController.setMessage(getInitialMessageResId()); + mMessageAreaController.setMessage( + mView.getResources().getString(getInitialMessageResId()), + /* animate= */ false); } mView.startAppearAnimation(); } diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardPINView.java b/packages/SystemUI/src/com/android/keyguard/KeyguardPINView.java index 5d86ccd5409e..67e3400670ba 100644 --- a/packages/SystemUI/src/com/android/keyguard/KeyguardPINView.java +++ b/packages/SystemUI/src/com/android/keyguard/KeyguardPINView.java @@ -52,6 +52,7 @@ public class KeyguardPINView extends KeyguardPinBasedInputView { private int mYTransOffset; private View mBouncerMessageView; @DevicePostureInt private int mLastDevicePosture = DEVICE_POSTURE_UNKNOWN; + public static final long ANIMATION_DURATION = 650; public KeyguardPINView(Context context) { this(context, null); @@ -181,7 +182,7 @@ public class KeyguardPINView extends KeyguardPinBasedInputView { if (mAppearAnimator.isRunning()) { mAppearAnimator.cancel(); } - mAppearAnimator.setDuration(650); + mAppearAnimator.setDuration(ANIMATION_DURATION); mAppearAnimator.addUpdateListener(animation -> animate(animation.getAnimatedFraction())); mAppearAnimator.start(); } diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java index 8f3484a0c99b..5d7a6f122e69 100644 --- a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java +++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java @@ -36,8 +36,11 @@ import static com.android.systemui.plugins.FalsingManager.LOW_PENALTY; import static java.lang.Integer.max; +import android.animation.Animator; +import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; +import android.animation.ValueAnimator; import android.app.Activity; import android.app.AlertDialog; import android.app.admin.DevicePolicyManager; @@ -967,11 +970,23 @@ public class KeyguardSecurityContainer extends ConstraintLayout { } mUserSwitcherViewGroup.setAlpha(0f); - ObjectAnimator alphaAnim = ObjectAnimator.ofFloat(mUserSwitcherViewGroup, View.ALPHA, - 1f); - alphaAnim.setInterpolator(Interpolators.ALPHA_IN); - alphaAnim.setDuration(500); - alphaAnim.start(); + ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f); + int yTrans = mView.getResources().getDimensionPixelSize(R.dimen.pin_view_trans_y_entry); + animator.setInterpolator(Interpolators.STANDARD_DECELERATE); + animator.setDuration(650); + animator.addListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animation) { + mUserSwitcherViewGroup.setAlpha(1f); + mUserSwitcherViewGroup.setTranslationY(0f); + } + }); + animator.addUpdateListener(animation -> { + float value = (float) animation.getAnimatedValue(); + mUserSwitcherViewGroup.setAlpha(value); + mUserSwitcherViewGroup.setTranslationY(yTrans - yTrans * value); + }); + animator.start(); } @Override diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java index 51ade29bd392..84ef505c0af9 100644 --- a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java +++ b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java @@ -382,6 +382,9 @@ public class KeyguardUpdateMonitor implements TrustManager.TrustListener, Dumpab private static final int HAL_ERROR_RETRY_MAX = 20; @VisibleForTesting + protected static final int HAL_POWER_PRESS_TIMEOUT = 50; // ms + + @VisibleForTesting protected final Runnable mFpCancelNotReceived = this::onFingerprintCancelNotReceived; private final Runnable mFaceCancelNotReceived = this::onFaceCancelNotReceived; @@ -902,7 +905,7 @@ public class KeyguardUpdateMonitor implements TrustManager.TrustListener, Dumpab } } - private final Runnable mRetryFingerprintAuthentication = new Runnable() { + private final Runnable mRetryFingerprintAuthenticationAfterHwUnavailable = new Runnable() { @SuppressLint("MissingPermission") @Override public void run() { @@ -911,7 +914,8 @@ public class KeyguardUpdateMonitor implements TrustManager.TrustListener, Dumpab updateFingerprintListeningState(BIOMETRIC_ACTION_UPDATE); } else if (mHardwareFingerprintUnavailableRetryCount < HAL_ERROR_RETRY_MAX) { mHardwareFingerprintUnavailableRetryCount++; - mHandler.postDelayed(mRetryFingerprintAuthentication, HAL_ERROR_RETRY_TIMEOUT); + mHandler.postDelayed(mRetryFingerprintAuthenticationAfterHwUnavailable, + HAL_ERROR_RETRY_TIMEOUT); } } }; @@ -941,12 +945,16 @@ public class KeyguardUpdateMonitor implements TrustManager.TrustListener, Dumpab if (msgId == FingerprintManager.FINGERPRINT_ERROR_HW_UNAVAILABLE) { mLogger.logRetryAfterFpErrorWithDelay(msgId, errString, HAL_ERROR_RETRY_TIMEOUT); - mHandler.postDelayed(mRetryFingerprintAuthentication, HAL_ERROR_RETRY_TIMEOUT); + mHandler.postDelayed(mRetryFingerprintAuthenticationAfterHwUnavailable, + HAL_ERROR_RETRY_TIMEOUT); } if (msgId == FingerprintManager.BIOMETRIC_ERROR_POWER_PRESSED) { - mLogger.logRetryAfterFpErrorWithDelay(msgId, errString, 0); - updateFingerprintListeningState(BIOMETRIC_ACTION_START); + mLogger.logRetryAfterFpErrorWithDelay(msgId, errString, HAL_POWER_PRESS_TIMEOUT); + mHandler.postDelayed(() -> { + mLogger.d("Retrying fingerprint listening after power pressed error."); + updateFingerprintListeningState(BIOMETRIC_ACTION_START); + }, HAL_POWER_PRESS_TIMEOUT); } boolean lockedOutStateChanged = false; diff --git a/packages/SystemUI/src/com/android/keyguard/logging/KeyguardUpdateMonitorLogger.kt b/packages/SystemUI/src/com/android/keyguard/logging/KeyguardUpdateMonitorLogger.kt index b66ae286171a..ceebe4c69091 100644 --- a/packages/SystemUI/src/com/android/keyguard/logging/KeyguardUpdateMonitorLogger.kt +++ b/packages/SystemUI/src/com/android/keyguard/logging/KeyguardUpdateMonitorLogger.kt @@ -231,7 +231,7 @@ class KeyguardUpdateMonitorLogger @Inject constructor( int2 = delay str1 = "$errString" }, { - "Fingerprint retrying auth after $int2 ms due to($int1) -> $str1" + "Fingerprint scheduling retry auth after $int2 ms due to($int1) -> $str1" }) } diff --git a/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuAnimationController.java b/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuAnimationController.java index 1e14763e57d5..e2a9d5456a8e 100644 --- a/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuAnimationController.java +++ b/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuAnimationController.java @@ -25,6 +25,9 @@ import android.os.Handler; import android.os.Looper; import android.util.Log; import android.view.View; +import android.view.animation.Animation; +import android.view.animation.OvershootInterpolator; +import android.view.animation.TranslateAnimation; import androidx.dynamicanimation.animation.DynamicAnimation; import androidx.dynamicanimation.animation.FlingAnimation; @@ -33,6 +36,7 @@ import androidx.dynamicanimation.animation.SpringAnimation; import androidx.dynamicanimation.animation.SpringForce; import androidx.recyclerview.widget.RecyclerView; +import com.android.internal.annotations.VisibleForTesting; import com.android.internal.util.Preconditions; import java.util.HashMap; @@ -55,7 +59,11 @@ class MenuAnimationController { private static final float SPRING_AFTER_FLING_DAMPING_RATIO = 0.85f; private static final float SPRING_STIFFNESS = 700f; private static final float ESCAPE_VELOCITY = 750f; + // Make tucked animation by using translation X relative to the view itself. + private static final float ANIMATION_TO_X_VALUE = 0.5f; + private static final int ANIMATION_START_OFFSET_MS = 600; + private static final int ANIMATION_DURATION_MS = 600; private static final int FADE_OUT_DURATION_MS = 1000; private static final int FADE_EFFECT_DURATION_MS = 3000; @@ -64,10 +72,12 @@ class MenuAnimationController { private final Handler mHandler; private boolean mIsFadeEffectEnabled; private DismissAnimationController.DismissCallback mDismissCallback; + private Runnable mSpringAnimationsEndAction; // Cache the animations state of {@link DynamicAnimation.TRANSLATION_X} and {@link // DynamicAnimation.TRANSLATION_Y} to be well controlled by the touch handler - private final HashMap<DynamicAnimation.ViewProperty, DynamicAnimation> mPositionAnimations = + @VisibleForTesting + final HashMap<DynamicAnimation.ViewProperty, DynamicAnimation> mPositionAnimations = new HashMap<>(); MenuAnimationController(MenuView menuView) { @@ -102,6 +112,13 @@ class MenuAnimationController { } } + /** + * Sets the action to be called when the all dynamic animations are completed. + */ + void setSpringAnimationsEndAction(Runnable runnable) { + mSpringAnimationsEndAction = runnable; + } + void setDismissCallback( DismissAnimationController.DismissCallback dismissCallback) { mDismissCallback = dismissCallback; @@ -192,7 +209,7 @@ class MenuAnimationController { ? bounds.right : bounds.bottom; - final FlingAnimation flingAnimation = new FlingAnimation(mMenuView, menuPositionProperty); + final FlingAnimation flingAnimation = createFlingAnimation(mMenuView, menuPositionProperty); flingAnimation.setFriction(friction) .setStartVelocity(velocity) .setMinValue(Math.min(currentValue, min)) @@ -217,7 +234,14 @@ class MenuAnimationController { flingAnimation.start(); } - private void springMenuWith(DynamicAnimation.ViewProperty property, SpringForce spring, + @VisibleForTesting + FlingAnimation createFlingAnimation(MenuView menuView, + MenuPositionProperty menuPositionProperty) { + return new FlingAnimation(menuView, menuPositionProperty); + } + + @VisibleForTesting + void springMenuWith(DynamicAnimation.ViewProperty property, SpringForce spring, float velocity, float finalPosition) { final MenuPositionProperty menuPositionProperty = new MenuPositionProperty(property); final SpringAnimation springAnimation = @@ -228,8 +252,13 @@ class MenuAnimationController { return; } - onSpringAnimationEnd(new PointF(mMenuView.getTranslationX(), - mMenuView.getTranslationY())); + final boolean areAnimationsRunning = + mPositionAnimations.values().stream().anyMatch( + DynamicAnimation::isRunning); + if (!areAnimationsRunning) { + onSpringAnimationsEnd(new PointF(mMenuView.getTranslationX(), + mMenuView.getTranslationY())); + } }) .setStartVelocity(velocity); @@ -332,11 +361,15 @@ class MenuAnimationController { .start(); } - private void onSpringAnimationEnd(PointF position) { + private void onSpringAnimationsEnd(PointF position) { mMenuView.onBoundsInParentChanged((int) position.x, (int) position.y); constrainPositionAndUpdate(position); fadeOutIfEnabled(); + + if (mSpringAnimationsEndAction != null) { + mSpringAnimationsEndAction.run(); + } } private void constrainPositionAndUpdate(PointF position) { @@ -387,6 +420,26 @@ class MenuAnimationController { mHandler.removeCallbacksAndMessages(/* token= */ null); } + void startTuckedAnimationPreview() { + fadeInNowIfEnabled(); + + final float toXValue = isOnLeftSide() + ? -ANIMATION_TO_X_VALUE + : ANIMATION_TO_X_VALUE; + final TranslateAnimation animation = + new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, + Animation.RELATIVE_TO_SELF, toXValue, + Animation.RELATIVE_TO_SELF, 0, + Animation.RELATIVE_TO_SELF, 0); + animation.setDuration(ANIMATION_DURATION_MS); + animation.setRepeatMode(Animation.REVERSE); + animation.setInterpolator(new OvershootInterpolator()); + animation.setRepeatCount(Animation.INFINITE); + animation.setStartOffset(ANIMATION_START_OFFSET_MS); + + mMenuView.startAnimation(animation); + } + private Handler createUiHandler() { return new Handler(requireNonNull(Looper.myLooper(), "looper must not be null")); } diff --git a/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuEduTooltipView.java b/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuEduTooltipView.java new file mode 100644 index 000000000000..440053450d2f --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuEduTooltipView.java @@ -0,0 +1,222 @@ +/* + * 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.accessibility.floatingmenu; + +import static android.util.TypedValue.COMPLEX_UNIT_PX; +import static android.view.View.MeasureSpec.AT_MOST; +import static android.view.View.MeasureSpec.UNSPECIFIED; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.res.Configuration; +import android.content.res.Resources; +import android.graphics.CornerPathEffect; +import android.graphics.Paint; +import android.graphics.PointF; +import android.graphics.Rect; +import android.graphics.drawable.GradientDrawable; +import android.graphics.drawable.ShapeDrawable; +import android.text.method.LinkMovementMethod; +import android.view.LayoutInflater; +import android.view.View; +import android.widget.FrameLayout; +import android.widget.LinearLayout; +import android.widget.TextView; + +import androidx.annotation.NonNull; + +import com.android.settingslib.Utils; +import com.android.systemui.R; +import com.android.systemui.recents.TriangleShape; + +/** + * The tooltip view shows the information about the operation of the anchor view {@link MenuView} + * . It's just shown on the left or right of the anchor view. + */ +@SuppressLint("ViewConstructor") +class MenuEduTooltipView extends FrameLayout { + private int mFontSize; + private int mTextViewMargin; + private int mTextViewPadding; + private int mTextViewCornerRadius; + private int mArrowMargin; + private int mArrowWidth; + private int mArrowHeight; + private int mArrowCornerRadius; + private int mColorAccentPrimary; + private View mArrowLeftView; + private View mArrowRightView; + private TextView mMessageView; + private final MenuViewAppearance mMenuViewAppearance; + + MenuEduTooltipView(@NonNull Context context, MenuViewAppearance menuViewAppearance) { + super(context); + + mMenuViewAppearance = menuViewAppearance; + + updateResources(); + initViews(); + } + + @Override + protected void onConfigurationChanged(Configuration newConfig) { + super.onConfigurationChanged(newConfig); + + updateResources(); + updateMessageView(); + updateArrowView(); + + updateLocationAndVisibility(); + } + + void show(CharSequence message) { + mMessageView.setText(message); + + updateLocationAndVisibility(); + } + + void updateLocationAndVisibility() { + final boolean isTooltipOnRightOfAnchor = mMenuViewAppearance.isMenuOnLeftSide(); + updateArrowVisibilityWith(isTooltipOnRightOfAnchor); + updateLocationWith(getMenuBoundsInParent(), isTooltipOnRightOfAnchor); + } + + /** + * Gets the bounds of the {@link MenuView}. Besides, its parent view {@link MenuViewLayer} is + * also the root view of the tooltip view. + * + * @return The menu bounds based on its parent view. + */ + private Rect getMenuBoundsInParent() { + final Rect bounds = new Rect(); + final PointF position = mMenuViewAppearance.getMenuPosition(); + + bounds.set((int) position.x, (int) position.y, + (int) position.x + mMenuViewAppearance.getMenuWidth(), + (int) position.y + mMenuViewAppearance.getMenuHeight()); + + return bounds; + } + + private void updateResources() { + final Resources res = getResources(); + + mArrowWidth = + res.getDimensionPixelSize(R.dimen.accessibility_floating_tooltip_arrow_width); + mArrowHeight = + res.getDimensionPixelSize(R.dimen.accessibility_floating_tooltip_arrow_height); + mArrowMargin = + res.getDimensionPixelSize( + R.dimen.accessibility_floating_tooltip_arrow_margin); + mArrowCornerRadius = + res.getDimensionPixelSize( + R.dimen.accessibility_floating_tooltip_arrow_corner_radius); + mFontSize = + res.getDimensionPixelSize(R.dimen.accessibility_floating_tooltip_font_size); + mTextViewMargin = + res.getDimensionPixelSize(R.dimen.accessibility_floating_tooltip_margin); + mTextViewPadding = + res.getDimensionPixelSize(R.dimen.accessibility_floating_tooltip_padding); + mTextViewCornerRadius = + res.getDimensionPixelSize( + R.dimen.accessibility_floating_tooltip_text_corner_radius); + mColorAccentPrimary = Utils.getColorAttrDefaultColor(getContext(), + com.android.internal.R.attr.colorAccentPrimary); + } + + private void updateLocationWith(Rect anchorBoundsInParent, boolean isTooltipOnRightOfAnchor) { + final int widthSpec = MeasureSpec.makeMeasureSpec( + getAvailableTextViewWidth(isTooltipOnRightOfAnchor), AT_MOST); + final int heightSpec = MeasureSpec.makeMeasureSpec(/* size= */ 0, UNSPECIFIED); + mMessageView.measure(widthSpec, heightSpec); + final LinearLayout.LayoutParams textViewParams = + (LinearLayout.LayoutParams) mMessageView.getLayoutParams(); + textViewParams.width = mMessageView.getMeasuredWidth(); + mMessageView.setLayoutParams(textViewParams); + + final int layoutWidth = mMessageView.getMeasuredWidth() + mArrowWidth + mArrowMargin; + setTranslationX(isTooltipOnRightOfAnchor + ? anchorBoundsInParent.right + : anchorBoundsInParent.left - layoutWidth); + + setTranslationY(anchorBoundsInParent.centerY() - (mMessageView.getMeasuredHeight() / 2.0f)); + } + + private void updateMessageView() { + mMessageView.setTextSize(COMPLEX_UNIT_PX, mFontSize); + mMessageView.setPadding(mTextViewPadding, mTextViewPadding, mTextViewPadding, + mTextViewPadding); + + final GradientDrawable gradientDrawable = (GradientDrawable) mMessageView.getBackground(); + gradientDrawable.setCornerRadius(mTextViewCornerRadius); + gradientDrawable.setColor(mColorAccentPrimary); + } + + private void updateArrowView() { + drawArrow(mArrowLeftView, /* isPointingLeft= */ true); + drawArrow(mArrowRightView, /* isPointingLeft= */ false); + } + + private void updateArrowVisibilityWith(boolean isTooltipOnRightOfAnchor) { + if (isTooltipOnRightOfAnchor) { + mArrowLeftView.setVisibility(VISIBLE); + mArrowRightView.setVisibility(GONE); + } else { + mArrowLeftView.setVisibility(GONE); + mArrowRightView.setVisibility(VISIBLE); + } + } + + private void drawArrow(View arrowView, boolean isPointingLeft) { + final TriangleShape triangleShape = + TriangleShape.createHorizontal(mArrowWidth, mArrowHeight, isPointingLeft); + final ShapeDrawable arrowDrawable = new ShapeDrawable(triangleShape); + final Paint arrowPaint = arrowDrawable.getPaint(); + arrowPaint.setColor(mColorAccentPrimary); + + final CornerPathEffect effect = new CornerPathEffect(mArrowCornerRadius); + arrowPaint.setPathEffect(effect); + + arrowView.setBackground(arrowDrawable); + } + + private void initViews() { + final View contentView = LayoutInflater.from(getContext()).inflate( + R.layout.accessibility_floating_menu_tooltip, /* root= */ this, /* attachToRoot= */ + false); + + mMessageView = contentView.findViewById(R.id.text); + mMessageView.setMovementMethod(LinkMovementMethod.getInstance()); + + mArrowLeftView = contentView.findViewById(R.id.arrow_left); + mArrowRightView = contentView.findViewById(R.id.arrow_right); + + updateMessageView(); + updateArrowView(); + + addView(contentView); + } + + private int getAvailableTextViewWidth(boolean isOnRightOfAnchor) { + final PointF position = mMenuViewAppearance.getMenuPosition(); + final int availableWidth = isOnRightOfAnchor + ? mMenuViewAppearance.getMenuDraggableBounds().width() - (int) position.x + : (int) position.x; + + return availableWidth - mArrowWidth - mArrowMargin - mTextViewMargin; + } +} diff --git a/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuInfoRepository.java b/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuInfoRepository.java index 5bc7406bb9d0..05e1d3f0e126 100644 --- a/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuInfoRepository.java +++ b/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuInfoRepository.java @@ -17,6 +17,7 @@ package com.android.systemui.accessibility.floatingmenu; import static android.provider.Settings.Secure.ACCESSIBILITY_FLOATING_MENU_FADE_ENABLED; +import static android.provider.Settings.Secure.ACCESSIBILITY_FLOATING_MENU_MIGRATION_TOOLTIP_PROMPT; import static android.provider.Settings.Secure.ACCESSIBILITY_FLOATING_MENU_OPACITY; import static android.provider.Settings.Secure.ACCESSIBILITY_FLOATING_MENU_SIZE; import static android.provider.Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES; @@ -28,6 +29,7 @@ import static com.android.systemui.accessibility.floatingmenu.MenuFadeEffectInfo import static com.android.systemui.accessibility.floatingmenu.MenuViewAppearance.MenuSizeType.SMALL; import android.annotation.FloatRange; +import android.annotation.IntDef; import android.content.Context; import android.database.ContentObserver; import android.os.Handler; @@ -40,6 +42,8 @@ import com.android.internal.accessibility.dialog.AccessibilityTarget; import com.android.internal.annotations.VisibleForTesting; import com.android.systemui.Prefs; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; import java.util.List; /** @@ -52,12 +56,24 @@ class MenuInfoRepository { @FloatRange(from = 0.0, to = 1.0) private static final float DEFAULT_MENU_POSITION_Y_PERCENT = 0.77f; private static final boolean DEFAULT_MOVE_TO_TUCKED_VALUE = false; + private static final boolean DEFAULT_HAS_SEEN_DOCK_TOOLTIP_VALUE = false; + private static final int DEFAULT_MIGRATION_TOOLTIP_VALUE_PROMPT = MigrationPrompt.DISABLED; private final Context mContext; private final Handler mHandler = new Handler(Looper.getMainLooper()); private final OnSettingsContentsChanged mSettingsContentsCallback; private Position mPercentagePosition; + @IntDef({ + MigrationPrompt.DISABLED, + MigrationPrompt.ENABLED, + }) + @Retention(RetentionPolicy.SOURCE) + @interface MigrationPrompt { + int DISABLED = 0; + int ENABLED = 1; + } + private final ContentObserver mMenuTargetFeaturesContentObserver = new ContentObserver(mHandler) { @Override @@ -99,6 +115,19 @@ class MenuInfoRepository { DEFAULT_MOVE_TO_TUCKED_VALUE)); } + void loadDockTooltipVisibility(OnInfoReady<Boolean> callback) { + callback.onReady(Prefs.getBoolean(mContext, + Prefs.Key.HAS_SEEN_ACCESSIBILITY_FLOATING_MENU_DOCK_TOOLTIP, + DEFAULT_HAS_SEEN_DOCK_TOOLTIP_VALUE)); + } + + void loadMigrationTooltipVisibility(OnInfoReady<Boolean> callback) { + callback.onReady(Settings.Secure.getIntForUser(mContext.getContentResolver(), + ACCESSIBILITY_FLOATING_MENU_MIGRATION_TOOLTIP_PROMPT, + DEFAULT_MIGRATION_TOOLTIP_VALUE_PROMPT, UserHandle.USER_CURRENT) + == MigrationPrompt.ENABLED); + } + void loadMenuPosition(OnInfoReady<Position> callback) { callback.onReady(mPercentagePosition); } @@ -131,6 +160,18 @@ class MenuInfoRepository { percentagePosition.toString()); } + void updateDockTooltipVisibility(boolean hasSeen) { + Prefs.putBoolean(mContext, Prefs.Key.HAS_SEEN_ACCESSIBILITY_FLOATING_MENU_DOCK_TOOLTIP, + hasSeen); + } + + void updateMigrationTooltipVisibility(boolean visible) { + Settings.Secure.putIntForUser(mContext.getContentResolver(), + ACCESSIBILITY_FLOATING_MENU_MIGRATION_TOOLTIP_PROMPT, + visible ? MigrationPrompt.ENABLED : MigrationPrompt.DISABLED, + UserHandle.USER_CURRENT); + } + private Position getStartPosition() { final String absolutePositionString = Prefs.getString(mContext, Prefs.Key.ACCESSIBILITY_FLOATING_MENU_POSITION, /* defaultValue= */ null); diff --git a/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuListViewTouchHandler.java b/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuListViewTouchHandler.java index bc3cf0a6bab0..8a31142a0212 100644 --- a/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuListViewTouchHandler.java +++ b/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuListViewTouchHandler.java @@ -25,6 +25,8 @@ import android.view.ViewConfiguration; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; +import java.util.Optional; + /** * Controls the all touch events of the accessibility target features view{@link RecyclerView} in * the {@link MenuView}. And then compute the gestures' velocity for fling and spring @@ -39,6 +41,7 @@ class MenuListViewTouchHandler implements RecyclerView.OnItemTouchListener { private boolean mIsDragging = false; private float mTouchSlop; private final DismissAnimationController mDismissAnimationController; + private Optional<Runnable> mOnActionDownEnd = Optional.empty(); MenuListViewTouchHandler(MenuAnimationController menuAnimationController, DismissAnimationController dismissAnimationController) { @@ -65,6 +68,8 @@ class MenuListViewTouchHandler implements RecyclerView.OnItemTouchListener { mMenuAnimationController.cancelAnimations(); mDismissAnimationController.maybeConsumeDownMotionEvent(motionEvent); + + mOnActionDownEnd.ifPresent(Runnable::run); break; case MotionEvent.ACTION_MOVE: if (mIsDragging || Math.hypot(dx, dy) > mTouchSlop) { @@ -125,6 +130,10 @@ class MenuListViewTouchHandler implements RecyclerView.OnItemTouchListener { // Do nothing } + void setOnActionDownEndListener(Runnable onActionDownEndListener) { + mOnActionDownEnd = Optional.ofNullable(onActionDownEndListener); + } + /** * Adds a movement to the velocity tracker using raw screen coordinates. */ diff --git a/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuViewAppearance.java b/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuViewAppearance.java index a7cdeab7c127..3cd250fb4575 100644 --- a/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuViewAppearance.java +++ b/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuViewAppearance.java @@ -293,7 +293,7 @@ class MenuViewAppearance { return bounds; } - private boolean isMenuOnLeftSide() { + boolean isMenuOnLeftSide() { return mPercentagePosition.getPercentageX() < 0.5f; } diff --git a/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuViewLayer.java b/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuViewLayer.java index c42943cf56e2..6f5b39cc7d56 100644 --- a/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuViewLayer.java +++ b/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuViewLayer.java @@ -20,6 +20,7 @@ import static android.view.WindowInsets.Type.ime; import static androidx.core.view.WindowInsetsCompat.Type; +import static com.android.internal.accessibility.AccessibilityShortcutController.ACCESSIBILITY_BUTTON_COMPONENT_NAME; import static com.android.internal.accessibility.common.ShortcutConstants.AccessibilityFragmentType.INVISIBLE_TOGGLE; import static com.android.internal.accessibility.util.AccessibilityUtils.getAccessibilityServiceFragmentType; import static com.android.internal.accessibility.util.AccessibilityUtils.setAccessibilityServiceState; @@ -27,8 +28,10 @@ import static com.android.systemui.accessibility.floatingmenu.MenuMessageView.In import android.accessibilityservice.AccessibilityServiceInfo; import android.annotation.IntDef; +import android.annotation.StringDef; import android.annotation.SuppressLint; import android.content.Context; +import android.content.Intent; import android.content.res.Configuration; import android.graphics.Rect; import android.os.Handler; @@ -37,6 +40,8 @@ import android.os.UserHandle; import android.provider.Settings; import android.util.PluralsMessageFormatter; import android.view.MotionEvent; +import android.view.View; +import android.view.ViewTreeObserver; import android.view.WindowInsets; import android.view.WindowManager; import android.view.WindowMetrics; @@ -45,6 +50,7 @@ import android.widget.FrameLayout; import android.widget.TextView; import androidx.annotation.NonNull; +import androidx.lifecycle.Observer; import com.android.internal.accessibility.dialog.AccessibilityTarget; import com.android.internal.annotations.VisibleForTesting; @@ -58,6 +64,7 @@ import java.lang.annotation.RetentionPolicy; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; /** * The basic interactions with the child views {@link MenuView}, {@link DismissView}, and @@ -66,11 +73,13 @@ import java.util.Map; * message view would be shown and allowed users to undo it. */ @SuppressLint("ViewConstructor") -class MenuViewLayer extends FrameLayout { +class MenuViewLayer extends FrameLayout implements + ViewTreeObserver.OnComputeInternalInsetsListener, View.OnClickListener { private static final int SHOW_MESSAGE_DELAY_MS = 3000; private final WindowManager mWindowManager; private final MenuView mMenuView; + private final MenuListViewTouchHandler mMenuListViewTouchHandler; private final MenuMessageView mMessageView; private final DismissView mDismissView; private final MenuViewAppearance mMenuViewAppearance; @@ -79,18 +88,38 @@ class MenuViewLayer extends FrameLayout { private final Handler mHandler = new Handler(Looper.getMainLooper()); private final IAccessibilityFloatingMenu mFloatingMenu; private final DismissAnimationController mDismissAnimationController; + private final MenuViewModel mMenuViewModel; + private final Observer<Boolean> mDockTooltipObserver = + this::onDockTooltipVisibilityChanged; + private final Observer<Boolean> mMigrationTooltipObserver = + this::onMigrationTooltipVisibilityChanged; private final Rect mImeInsetsRect = new Rect(); + private boolean mIsMigrationTooltipShowing; + private boolean mShouldShowDockTooltip; + private Optional<MenuEduTooltipView> mEduTooltipView = Optional.empty(); @IntDef({ LayerIndex.MENU_VIEW, LayerIndex.DISMISS_VIEW, LayerIndex.MESSAGE_VIEW, + LayerIndex.TOOLTIP_VIEW, }) @Retention(RetentionPolicy.SOURCE) @interface LayerIndex { int MENU_VIEW = 0; int DISMISS_VIEW = 1; int MESSAGE_VIEW = 2; + int TOOLTIP_VIEW = 3; + } + + @StringDef({ + TooltipType.MIGRATION, + TooltipType.DOCK, + }) + @Retention(RetentionPolicy.SOURCE) + @interface TooltipType { + String MIGRATION = "migration"; + String DOCK = "dock"; } @VisibleForTesting @@ -125,12 +154,12 @@ class MenuViewLayer extends FrameLayout { mAccessibilityManager = accessibilityManager; mFloatingMenu = floatingMenu; - final MenuViewModel menuViewModel = new MenuViewModel(context); + mMenuViewModel = new MenuViewModel(context); mMenuViewAppearance = new MenuViewAppearance(context, windowManager); - mMenuView = new MenuView(context, menuViewModel, mMenuViewAppearance); + mMenuView = new MenuView(context, mMenuViewModel, mMenuViewAppearance); mMenuAnimationController = mMenuView.getMenuAnimationController(); mMenuAnimationController.setDismissCallback(this::hideMenuAndShowMessage); - + mMenuAnimationController.setSpringAnimationsEndAction(this::onSpringAnimationsEndAction); mDismissView = new DismissView(context); mDismissAnimationController = new DismissAnimationController(mDismissView, mMenuView); mDismissAnimationController.setMagnetListener(new MagnetizedObject.MagnetListener() { @@ -153,9 +182,9 @@ class MenuViewLayer extends FrameLayout { } }); - final MenuListViewTouchHandler menuListViewTouchHandler = new MenuListViewTouchHandler( - mMenuAnimationController, mDismissAnimationController); - mMenuView.addOnItemTouchListenerToList(menuListViewTouchHandler); + mMenuListViewTouchHandler = new MenuListViewTouchHandler(mMenuAnimationController, + mDismissAnimationController); + mMenuView.addOnItemTouchListenerToList(mMenuListViewTouchHandler); mMessageView = new MenuMessageView(context); @@ -210,7 +239,12 @@ class MenuViewLayer extends FrameLayout { super.onAttachedToWindow(); mMenuView.show(); + setOnClickListener(this); setOnApplyWindowInsetsListener((view, insets) -> onWindowInsetsApplied(insets)); + getViewTreeObserver().addOnComputeInternalInsetsListener(this); + mMenuViewModel.getDockTooltipVisibilityData().observeForever(mDockTooltipObserver); + mMenuViewModel.getMigrationTooltipVisibilityData().observeForever( + mMigrationTooltipObserver); mMessageView.setUndoListener(view -> undo()); mContext.registerComponentCallbacks(mDismissAnimationController); } @@ -220,11 +254,32 @@ class MenuViewLayer extends FrameLayout { super.onDetachedFromWindow(); mMenuView.hide(); + setOnClickListener(null); setOnApplyWindowInsetsListener(null); + getViewTreeObserver().removeOnComputeInternalInsetsListener(this); + mMenuViewModel.getDockTooltipVisibilityData().removeObserver(mDockTooltipObserver); + mMenuViewModel.getMigrationTooltipVisibilityData().removeObserver( + mMigrationTooltipObserver); mHandler.removeCallbacksAndMessages(/* token= */ null); mContext.unregisterComponentCallbacks(mDismissAnimationController); } + @Override + public void onComputeInternalInsets(ViewTreeObserver.InternalInsetsInfo inoutInfo) { + inoutInfo.setTouchableInsets(ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_REGION); + + if (mEduTooltipView.isPresent()) { + final int x = (int) getX(); + final int y = (int) getY(); + inoutInfo.touchableRegion.union(new Rect(x, y, x + getWidth(), y + getHeight())); + } + } + + @Override + public void onClick(View v) { + mEduTooltipView.ifPresent(this::removeTooltip); + } + private WindowInsets onWindowInsetsApplied(WindowInsets insets) { final WindowMetrics windowMetrics = mWindowManager.getCurrentWindowMetrics(); final WindowInsets windowInsets = windowMetrics.getWindowInsets(); @@ -249,6 +304,78 @@ class MenuViewLayer extends FrameLayout { return insets; } + private void onMigrationTooltipVisibilityChanged(boolean visible) { + mIsMigrationTooltipShowing = visible; + + if (mIsMigrationTooltipShowing) { + mEduTooltipView = Optional.of(new MenuEduTooltipView(mContext, mMenuViewAppearance)); + mEduTooltipView.ifPresent( + view -> addTooltipView(view, getMigrationMessage(), TooltipType.MIGRATION)); + } + } + + private void onDockTooltipVisibilityChanged(boolean hasSeenTooltip) { + mShouldShowDockTooltip = !hasSeenTooltip; + } + + private void onSpringAnimationsEndAction() { + if (mShouldShowDockTooltip) { + mEduTooltipView = Optional.of(new MenuEduTooltipView(mContext, mMenuViewAppearance)); + mEduTooltipView.ifPresent(view -> addTooltipView(view, + getContext().getText(R.string.accessibility_floating_button_docking_tooltip), + TooltipType.DOCK)); + + mMenuAnimationController.startTuckedAnimationPreview(); + } + } + + private CharSequence getMigrationMessage() { + final Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_DETAILS_SETTINGS); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + intent.putExtra(Intent.EXTRA_COMPONENT_NAME, + ACCESSIBILITY_BUTTON_COMPONENT_NAME.flattenToShortString()); + + final AnnotationLinkSpan.LinkInfo linkInfo = new AnnotationLinkSpan.LinkInfo( + AnnotationLinkSpan.LinkInfo.DEFAULT_ANNOTATION, + v -> { + getContext().startActivity(intent); + mEduTooltipView.ifPresent(this::removeTooltip); + }); + + final int textResId = R.string.accessibility_floating_button_migration_tooltip; + + return AnnotationLinkSpan.linkify(getContext().getText(textResId), linkInfo); + } + + private void addTooltipView(MenuEduTooltipView tooltipView, CharSequence message, + CharSequence tag) { + addView(tooltipView, LayerIndex.TOOLTIP_VIEW); + + tooltipView.show(message); + tooltipView.setTag(tag); + + mMenuListViewTouchHandler.setOnActionDownEndListener( + () -> mEduTooltipView.ifPresent(this::removeTooltip)); + } + + private void removeTooltip(View tooltipView) { + if (tooltipView.getTag().equals(TooltipType.MIGRATION)) { + mMenuViewModel.updateMigrationTooltipVisibility(/* visible= */ false); + mIsMigrationTooltipShowing = false; + } + + if (tooltipView.getTag().equals(TooltipType.DOCK)) { + mMenuViewModel.updateDockTooltipVisibility(/* hasSeen= */ true); + mMenuView.clearAnimation(); + mShouldShowDockTooltip = false; + } + + removeView(tooltipView); + + mMenuListViewTouchHandler.setOnActionDownEndListener(null); + mEduTooltipView = Optional.empty(); + } + private void hideMenuAndShowMessage() { final int delayTime = mAccessibilityManager.getRecommendedTimeoutMillis( SHOW_MESSAGE_DELAY_MS, diff --git a/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuViewModel.java b/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuViewModel.java index bd417877c124..5fea3b0ba2f9 100644 --- a/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuViewModel.java +++ b/packages/SystemUI/src/com/android/systemui/accessibility/floatingmenu/MenuViewModel.java @@ -36,6 +36,8 @@ class MenuViewModel implements MenuInfoRepository.OnSettingsContentsChanged { private final MutableLiveData<MenuFadeEffectInfo> mFadeEffectInfoData = new MutableLiveData<>(); private final MutableLiveData<Boolean> mMoveToTuckedData = new MutableLiveData<>(); + private final MutableLiveData<Boolean> mDockTooltipData = new MutableLiveData<>(); + private final MutableLiveData<Boolean> mMigrationTooltipData = new MutableLiveData<>(); private final MutableLiveData<Position> mPercentagePositionData = new MutableLiveData<>(); private final MenuInfoRepository mInfoRepository; @@ -66,11 +68,29 @@ class MenuViewModel implements MenuInfoRepository.OnSettingsContentsChanged { mInfoRepository.updateMenuSavingPosition(percentagePosition); } + void updateDockTooltipVisibility(boolean hasSeen) { + mInfoRepository.updateDockTooltipVisibility(hasSeen); + } + + void updateMigrationTooltipVisibility(boolean visible) { + mInfoRepository.updateMigrationTooltipVisibility(visible); + } + LiveData<Boolean> getMoveToTuckedData() { mInfoRepository.loadMenuMoveToTucked(mMoveToTuckedData::setValue); return mMoveToTuckedData; } + LiveData<Boolean> getDockTooltipVisibilityData() { + mInfoRepository.loadDockTooltipVisibility(mDockTooltipData::setValue); + return mDockTooltipData; + } + + LiveData<Boolean> getMigrationTooltipVisibilityData() { + mInfoRepository.loadMigrationTooltipVisibility(mMigrationTooltipData::setValue); + return mMigrationTooltipData; + } + LiveData<Position> getPercentagePositionData() { mInfoRepository.loadMenuPosition(mPercentagePositionData::setValue); return mPercentagePositionData; diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsController.java b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsController.java index 19b054879d89..1613ca1fd034 100644 --- a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsController.java +++ b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsController.java @@ -97,6 +97,7 @@ import java.util.Set; import java.util.concurrent.Executor; import javax.inject.Inject; +import javax.inject.Provider; import kotlin.Unit; @@ -115,7 +116,7 @@ import kotlin.Unit; @SysUISingleton public class UdfpsController implements DozeReceiver, Dumpable { private static final String TAG = "UdfpsController"; - private static final long AOD_INTERRUPT_TIMEOUT_MILLIS = 1000; + private static final long AOD_SEND_FINGER_UP_DELAY_MILLIS = 1000; // Minimum required delay between consecutive touch logs in milliseconds. private static final long MIN_TOUCH_LOG_INTERVAL = 50; @@ -178,7 +179,7 @@ public class UdfpsController implements DozeReceiver, Dumpable { // interrupt is being tracked and a timeout is used as a last resort to turn off high brightness // mode. private boolean mIsAodInterruptActive; - @Nullable private Runnable mCancelAodTimeoutAction; + @Nullable private Runnable mCancelAodFingerUpAction; private boolean mScreenOn; private Runnable mAodInterruptRunnable; private boolean mOnFingerDown; @@ -280,6 +281,7 @@ public class UdfpsController implements DozeReceiver, Dumpable { if (view != null && isOptical()) { unconfigureDisplay(view); } + tryAodSendFingerUp(); if (acquiredGood) { mOverlay.onAcquiredGood(); } @@ -747,7 +749,7 @@ public class UdfpsController implements DozeReceiver, Dumpable { @NonNull SystemUIDialogManager dialogManager, @NonNull LatencyTracker latencyTracker, @NonNull ActivityLaunchAnimator activityLaunchAnimator, - @NonNull Optional<AlternateUdfpsTouchProvider> alternateTouchProvider, + @NonNull Optional<Provider<AlternateUdfpsTouchProvider>> alternateTouchProvider, @NonNull @BiometricsBackground Executor biometricsExecutor, @NonNull PrimaryBouncerInteractor primaryBouncerInteractor, @NonNull SinglePointerTouchProcessor singlePointerTouchProcessor) { @@ -779,7 +781,7 @@ public class UdfpsController implements DozeReceiver, Dumpable { mUnlockedScreenOffAnimationController = unlockedScreenOffAnimationController; mLatencyTracker = latencyTracker; mActivityLaunchAnimator = activityLaunchAnimator; - mAlternateTouchProvider = alternateTouchProvider.orElse(null); + mAlternateTouchProvider = alternateTouchProvider.map(Provider::get).orElse(null); mSensorProps = new FingerprintSensorPropertiesInternal( -1 /* sensorId */, SensorProperties.STRENGTH_CONVENIENCE, @@ -900,12 +902,6 @@ public class UdfpsController implements DozeReceiver, Dumpable { private void unconfigureDisplay(@NonNull UdfpsView view) { if (view.isDisplayConfigured()) { view.unconfigureDisplay(); - - if (mCancelAodTimeoutAction != null) { - mCancelAodTimeoutAction.run(); - mCancelAodTimeoutAction = null; - } - mIsAodInterruptActive = false; } } @@ -945,8 +941,8 @@ public class UdfpsController implements DozeReceiver, Dumpable { // ACTION_UP/ACTION_CANCEL, we need to be careful about not letting the screen // accidentally remain in high brightness mode. As a mitigation, queue a call to // cancel the fingerprint scan. - mCancelAodTimeoutAction = mFgExecutor.executeDelayed(this::cancelAodInterrupt, - AOD_INTERRUPT_TIMEOUT_MILLIS); + mCancelAodFingerUpAction = mFgExecutor.executeDelayed(this::tryAodSendFingerUp, + AOD_SEND_FINGER_UP_DELAY_MILLIS); // using a hard-coded value for major and minor until it is available from the sensor onFingerDown(requestId, screenX, screenY, minor, major); }; @@ -980,15 +976,27 @@ public class UdfpsController implements DozeReceiver, Dumpable { * sensors, this can result in illumination persisting for longer than necessary. */ @VisibleForTesting - void cancelAodInterrupt() { + void tryAodSendFingerUp() { if (!mIsAodInterruptActive) { return; } + cancelAodSendFingerUpAction(); if (mOverlay != null && mOverlay.getOverlayView() != null) { onFingerUp(mOverlay.getRequestId(), mOverlay.getOverlayView()); } - mCancelAodTimeoutAction = null; + } + + /** + * Cancels any scheduled AoD finger-up actions without triggered the finger-up action. Only + * call this method if the finger-up event has been guaranteed to have already occurred. + */ + @VisibleForTesting + void cancelAodSendFingerUpAction() { mIsAodInterruptActive = false; + if (mCancelAodFingerUpAction != null) { + mCancelAodFingerUpAction.run(); + mCancelAodFingerUpAction = null; + } } private boolean isOptical() { @@ -1150,6 +1158,7 @@ public class UdfpsController implements DozeReceiver, Dumpable { if (isOptical()) { unconfigureDisplay(view); } + cancelAodSendFingerUpAction(); } /** diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsOverlay.kt b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsOverlay.kt index 142642a2411f..802b9b6c0295 100644 --- a/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsOverlay.kt +++ b/packages/SystemUI/src/com/android/systemui/biometrics/UdfpsOverlay.kt @@ -42,6 +42,7 @@ import com.android.systemui.util.concurrency.Execution import java.util.Optional import java.util.concurrent.Executor import javax.inject.Inject +import javax.inject.Provider import kotlin.math.cos import kotlin.math.pow import kotlin.math.sin @@ -64,7 +65,7 @@ constructor( private val fingerprintManager: FingerprintManager?, private val handler: Handler, private val biometricExecutor: Executor, - private val alternateTouchProvider: Optional<AlternateUdfpsTouchProvider>, + private val alternateTouchProvider: Optional<Provider<AlternateUdfpsTouchProvider>>, @Main private val fgExecutor: DelayableExecutor, private val keyguardUpdateMonitor: KeyguardUpdateMonitor, private val authController: AuthController, @@ -126,6 +127,7 @@ constructor( if (!processedMotionEvent && goodOverlap) { biometricExecutor.execute { alternateTouchProvider + .map(Provider<AlternateUdfpsTouchProvider>::get) .get() .onPointerDown( requestId, @@ -142,7 +144,10 @@ constructor( view.configureDisplay { biometricExecutor.execute { - alternateTouchProvider.get().onUiReady() + alternateTouchProvider + .map(Provider<AlternateUdfpsTouchProvider>::get) + .get() + .onUiReady() } } @@ -158,7 +163,10 @@ constructor( MotionEvent.ACTION_CANCEL -> { if (processedMotionEvent && alternateTouchProvider.isPresent) { biometricExecutor.execute { - alternateTouchProvider.get().onPointerUp(requestId) + alternateTouchProvider + .map(Provider<AlternateUdfpsTouchProvider>::get) + .get() + .onPointerUp(requestId) } fgExecutor.execute { if (keyguardUpdateMonitor.isFingerprintDetectionRunning) { @@ -241,7 +249,10 @@ constructor( if (overlayView != null && isShowing && alternateTouchProvider.isPresent) { if (processedMotionEvent) { biometricExecutor.execute { - alternateTouchProvider.get().onPointerUp(requestId) + alternateTouchProvider + .map(Provider<AlternateUdfpsTouchProvider>::get) + .get() + .onPointerUp(requestId) } fgExecutor.execute { if (keyguardUpdateMonitor.isFingerprintDetectionRunning) { diff --git a/packages/SystemUI/src/com/android/systemui/clipboardoverlay/ClipboardOverlayController.java b/packages/SystemUI/src/com/android/systemui/clipboardoverlay/ClipboardOverlayController.java index fb37defd844d..63c20651fcd5 100644 --- a/packages/SystemUI/src/com/android/systemui/clipboardoverlay/ClipboardOverlayController.java +++ b/packages/SystemUI/src/com/android/systemui/clipboardoverlay/ClipboardOverlayController.java @@ -301,7 +301,9 @@ public class ClipboardOverlayController implements ClipboardListener.ClipboardOv } else { mView.showDefaultTextPreview(); } - maybeShowRemoteCopy(clipData); + if (!isRemote) { + maybeShowRemoteCopy(clipData); + } animateIn(); mView.announceForAccessibility(accessibilityAnnouncement); if (isRemote) { diff --git a/packages/SystemUI/src/com/android/systemui/common/shared/model/TintedIcon.kt b/packages/SystemUI/src/com/android/systemui/common/shared/model/TintedIcon.kt new file mode 100644 index 000000000000..5dabbbb81701 --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/common/shared/model/TintedIcon.kt @@ -0,0 +1,25 @@ +/* + * 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.common.shared.model + +import androidx.annotation.AttrRes + +/** Models an icon with a specific tint. */ +data class TintedIcon( + val icon: Icon, + @AttrRes val tintAttr: Int?, +) diff --git a/packages/SystemUI/src/com/android/systemui/common/ui/binder/TintedIconViewBinder.kt b/packages/SystemUI/src/com/android/systemui/common/ui/binder/TintedIconViewBinder.kt new file mode 100644 index 000000000000..dea8cfda80c3 --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/common/ui/binder/TintedIconViewBinder.kt @@ -0,0 +1,42 @@ +/* + * 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.common.ui.binder + +import android.widget.ImageView +import com.android.settingslib.Utils +import com.android.systemui.common.shared.model.TintedIcon + +object TintedIconViewBinder { + /** + * Binds the given tinted icon to the view. + * + * [TintedIcon.tintAttr] will always be applied, meaning that if it is null, then the tint + * *will* be reset to null. + */ + fun bind( + tintedIcon: TintedIcon, + view: ImageView, + ) { + IconViewBinder.bind(tintedIcon.icon, view) + view.imageTintList = + if (tintedIcon.tintAttr != null) { + Utils.getColorAttr(view.context, tintedIcon.tintAttr) + } else { + null + } + } +} diff --git a/packages/SystemUI/src/com/android/systemui/controls/ControlsServiceInfo.kt b/packages/SystemUI/src/com/android/systemui/controls/ControlsServiceInfo.kt index 66e5d7c4a3bc..dbe301df8e78 100644 --- a/packages/SystemUI/src/com/android/systemui/controls/ControlsServiceInfo.kt +++ b/packages/SystemUI/src/com/android/systemui/controls/ControlsServiceInfo.kt @@ -69,12 +69,14 @@ class ControlsServiceInfo( private var resolved: Boolean = false @WorkerThread - fun resolvePanelActivity() { + fun resolvePanelActivity( + allowAllApps: Boolean = false + ) { if (resolved) return resolved = true val validPackages = context.resources .getStringArray(R.array.config_controlsPreferredPackages) - if (componentName.packageName !in validPackages) return + if (componentName.packageName !in validPackages && !allowAllApps) return panelActivity = _panelActivity?.let { val resolveInfos = mPm.queryIntentActivitiesAsUser( Intent().setComponent(it), diff --git a/packages/SystemUI/src/com/android/systemui/controls/dagger/ControlsComponent.kt b/packages/SystemUI/src/com/android/systemui/controls/dagger/ControlsComponent.kt index 77d0496e43db..27466d4f58bc 100644 --- a/packages/SystemUI/src/com/android/systemui/controls/dagger/ControlsComponent.kt +++ b/packages/SystemUI/src/com/android/systemui/controls/dagger/ControlsComponent.kt @@ -19,7 +19,7 @@ package com.android.systemui.controls.dagger import android.content.Context import com.android.internal.widget.LockPatternUtils import com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_BOOT -import com.android.systemui.controls.ControlsSettingsRepository +import com.android.systemui.controls.settings.ControlsSettingsRepository import com.android.systemui.controls.controller.ControlsController import com.android.systemui.controls.controller.ControlsTileResourceConfiguration import com.android.systemui.controls.controller.ControlsTileResourceConfigurationImpl diff --git a/packages/SystemUI/src/com/android/systemui/controls/dagger/ControlsModule.kt b/packages/SystemUI/src/com/android/systemui/controls/dagger/ControlsModule.kt index 9ae605e30a83..6d6410de1a91 100644 --- a/packages/SystemUI/src/com/android/systemui/controls/dagger/ControlsModule.kt +++ b/packages/SystemUI/src/com/android/systemui/controls/dagger/ControlsModule.kt @@ -20,8 +20,8 @@ import android.app.Activity import android.content.pm.PackageManager import com.android.systemui.controls.ControlsMetricsLogger import com.android.systemui.controls.ControlsMetricsLoggerImpl -import com.android.systemui.controls.ControlsSettingsRepository -import com.android.systemui.controls.ControlsSettingsRepositoryImpl +import com.android.systemui.controls.settings.ControlsSettingsRepository +import com.android.systemui.controls.settings.ControlsSettingsRepositoryImpl import com.android.systemui.controls.controller.ControlsBindingController import com.android.systemui.controls.controller.ControlsBindingControllerImpl import com.android.systemui.controls.controller.ControlsController @@ -34,6 +34,8 @@ import com.android.systemui.controls.management.ControlsListingController import com.android.systemui.controls.management.ControlsListingControllerImpl import com.android.systemui.controls.management.ControlsProviderSelectorActivity import com.android.systemui.controls.management.ControlsRequestDialog +import com.android.systemui.controls.settings.ControlsSettingsDialogManager +import com.android.systemui.controls.settings.ControlsSettingsDialogManagerImpl import com.android.systemui.controls.ui.ControlActionCoordinator import com.android.systemui.controls.ui.ControlActionCoordinatorImpl import com.android.systemui.controls.ui.ControlsActivity @@ -90,6 +92,11 @@ abstract class ControlsModule { ): ControlsSettingsRepository @Binds + abstract fun provideDialogManager( + manager: ControlsSettingsDialogManagerImpl + ): ControlsSettingsDialogManager + + @Binds abstract fun provideMetricsLogger(logger: ControlsMetricsLoggerImpl): ControlsMetricsLogger @Binds diff --git a/packages/SystemUI/src/com/android/systemui/controls/management/ControlsListingControllerImpl.kt b/packages/SystemUI/src/com/android/systemui/controls/management/ControlsListingControllerImpl.kt index c6428ef6eb8e..c81a2c7e2ac6 100644 --- a/packages/SystemUI/src/com/android/systemui/controls/management/ControlsListingControllerImpl.kt +++ b/packages/SystemUI/src/com/android/systemui/controls/management/ControlsListingControllerImpl.kt @@ -98,7 +98,9 @@ class ControlsListingControllerImpl @VisibleForTesting constructor( backgroundExecutor.execute { if (userChangeInProgress.get() > 0) return@execute if (featureFlags.isEnabled(Flags.USE_APP_PANELS)) { - newServices.forEach(ControlsServiceInfo::resolvePanelActivity) + val allowAllApps = featureFlags.isEnabled(Flags.APP_PANELS_ALL_APPS_ALLOWED) + newServices.forEach { + it.resolvePanelActivity(allowAllApps) } } if (newServices != availableServices) { diff --git a/packages/SystemUI/src/com/android/systemui/controls/settings/ControlsSettingsDialogManager.kt b/packages/SystemUI/src/com/android/systemui/controls/settings/ControlsSettingsDialogManager.kt new file mode 100644 index 000000000000..bb2e2d701aa0 --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/controls/settings/ControlsSettingsDialogManager.kt @@ -0,0 +1,231 @@ +/* + * 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.controls.settings + +import android.app.AlertDialog +import android.content.Context +import android.content.Context.MODE_PRIVATE +import android.content.DialogInterface +import android.content.SharedPreferences +import android.provider.Settings +import androidx.annotation.VisibleForTesting +import com.android.systemui.R +import com.android.systemui.controls.settings.ControlsSettingsDialogManager.Companion.MAX_NUMBER_ATTEMPTS_CONTROLS_DIALOG +import com.android.systemui.controls.settings.ControlsSettingsDialogManager.Companion.PREFS_SETTINGS_DIALOG_ATTEMPTS +import com.android.systemui.dagger.SysUISingleton +import com.android.systemui.plugins.ActivityStarter +import com.android.systemui.settings.UserFileManager +import com.android.systemui.settings.UserTracker +import com.android.systemui.statusbar.phone.SystemUIDialog +import com.android.systemui.statusbar.policy.DeviceControlsControllerImpl +import com.android.systemui.util.settings.SecureSettings +import javax.inject.Inject + +/** + * Manager to display a dialog to prompt user to enable controls related Settings: + * + * * [Settings.Secure.LOCKSCREEN_SHOW_CONTROLS] + * * [Settings.Secure.LOCKSCREEN_ALLOW_TRIVIAL_CONTROLS] + */ +interface ControlsSettingsDialogManager { + + /** + * Shows the corresponding dialog. In order for a dialog to appear, the following must be true + * + * * At least one of the Settings in [ControlsSettingsRepository] are `false`. + * * The dialog has not been seen by the user too many times (as defined by + * [MAX_NUMBER_ATTEMPTS_CONTROLS_DIALOG]). + * + * When the dialogs are shown, the following outcomes are possible: + * * User cancels the dialog by clicking outside or going back: we register that the dialog was + * seen but the settings don't change. + * * User responds negatively to the dialog: we register that the user doesn't want to change + * the settings (dialog will not appear again) and the settings don't change. + * * User responds positively to the dialog: the settings are set to `true` and the dialog will + * not appear again. + * * SystemUI closes the dialogs (for example, the activity showing it is closed). In this case, + * we don't modify anything. + * + * Of those four scenarios, only the first three will cause [onAttemptCompleted] to be called. + * It will also be called if the dialogs are not shown. + */ + fun maybeShowDialog(activityContext: Context, onAttemptCompleted: () -> Unit) + + /** + * Closes the dialog without registering anything from the user. The state of the settings after + * this is called will be the same as before the dialogs were shown. + */ + fun closeDialog() + + companion object { + @VisibleForTesting internal const val MAX_NUMBER_ATTEMPTS_CONTROLS_DIALOG = 2 + @VisibleForTesting + internal const val PREFS_SETTINGS_DIALOG_ATTEMPTS = "show_settings_attempts" + } +} + +@SysUISingleton +class ControlsSettingsDialogManagerImpl +@VisibleForTesting +internal constructor( + private val secureSettings: SecureSettings, + private val userFileManager: UserFileManager, + private val controlsSettingsRepository: ControlsSettingsRepository, + private val userTracker: UserTracker, + private val activityStarter: ActivityStarter, + private val dialogProvider: (context: Context, theme: Int) -> AlertDialog +) : ControlsSettingsDialogManager { + + @Inject + constructor( + secureSettings: SecureSettings, + userFileManager: UserFileManager, + controlsSettingsRepository: ControlsSettingsRepository, + userTracker: UserTracker, + activityStarter: ActivityStarter + ) : this( + secureSettings, + userFileManager, + controlsSettingsRepository, + userTracker, + activityStarter, + { context, theme -> SettingsDialog(context, theme) } + ) + + private var dialog: AlertDialog? = null + private set + + private val showDeviceControlsInLockscreen: Boolean + get() = controlsSettingsRepository.canShowControlsInLockscreen.value + + private val allowTrivialControls: Boolean + get() = controlsSettingsRepository.allowActionOnTrivialControlsInLockscreen.value + + override fun maybeShowDialog(activityContext: Context, onAttemptCompleted: () -> Unit) { + closeDialog() + + val prefs = + userFileManager.getSharedPreferences( + DeviceControlsControllerImpl.PREFS_CONTROLS_FILE, + MODE_PRIVATE, + userTracker.userId + ) + val attempts = prefs.getInt(PREFS_SETTINGS_DIALOG_ATTEMPTS, 0) + if ( + attempts >= MAX_NUMBER_ATTEMPTS_CONTROLS_DIALOG || + (showDeviceControlsInLockscreen && allowTrivialControls) + ) { + onAttemptCompleted() + return + } + + val listener = DialogListener(prefs, attempts, onAttemptCompleted) + val d = + dialogProvider(activityContext, R.style.Theme_SystemUI_Dialog).apply { + setIcon(R.drawable.ic_warning) + setOnCancelListener(listener) + setNeutralButton(R.string.controls_settings_dialog_neutral_button, listener) + setPositiveButton(R.string.controls_settings_dialog_positive_button, listener) + if (showDeviceControlsInLockscreen) { + setTitle(R.string.controls_settings_trivial_controls_dialog_title) + setMessage(R.string.controls_settings_trivial_controls_dialog_message) + } else { + setTitle(R.string.controls_settings_show_controls_dialog_title) + setMessage(R.string.controls_settings_show_controls_dialog_message) + } + } + + SystemUIDialog.registerDismissListener(d) { dialog = null } + SystemUIDialog.setDialogSize(d) + SystemUIDialog.setShowForAllUsers(d, true) + dialog = d + d.show() + } + + private fun turnOnSettingSecurely(settings: List<String>) { + val action = + ActivityStarter.OnDismissAction { + settings.forEach { setting -> + secureSettings.putIntForUser(setting, 1, userTracker.userId) + } + true + } + activityStarter.dismissKeyguardThenExecute( + action, + /* cancel */ null, + /* afterKeyguardGone */ true + ) + } + + override fun closeDialog() { + dialog?.dismiss() + } + + private inner class DialogListener( + private val prefs: SharedPreferences, + private val attempts: Int, + private val onComplete: () -> Unit + ) : DialogInterface.OnClickListener, DialogInterface.OnCancelListener { + override fun onClick(dialog: DialogInterface?, which: Int) { + if (dialog == null) return + if (which == DialogInterface.BUTTON_POSITIVE) { + val settings = mutableListOf(Settings.Secure.LOCKSCREEN_ALLOW_TRIVIAL_CONTROLS) + if (!showDeviceControlsInLockscreen) { + settings.add(Settings.Secure.LOCKSCREEN_SHOW_CONTROLS) + } + turnOnSettingSecurely(settings) + } + if (attempts != MAX_NUMBER_ATTEMPTS_CONTROLS_DIALOG) { + prefs + .edit() + .putInt(PREFS_SETTINGS_DIALOG_ATTEMPTS, MAX_NUMBER_ATTEMPTS_CONTROLS_DIALOG) + .apply() + } + onComplete() + } + + override fun onCancel(dialog: DialogInterface?) { + if (dialog == null) return + if (attempts < MAX_NUMBER_ATTEMPTS_CONTROLS_DIALOG) { + prefs.edit().putInt(PREFS_SETTINGS_DIALOG_ATTEMPTS, attempts + 1).apply() + } + onComplete() + } + } + + private fun AlertDialog.setNeutralButton( + msgId: Int, + listener: DialogInterface.OnClickListener + ) { + setButton(DialogInterface.BUTTON_NEUTRAL, context.getText(msgId), listener) + } + + private fun AlertDialog.setPositiveButton( + msgId: Int, + listener: DialogInterface.OnClickListener + ) { + setButton(DialogInterface.BUTTON_POSITIVE, context.getText(msgId), listener) + } + + private fun AlertDialog.setMessage(msgId: Int) { + setMessage(context.getText(msgId)) + } + + /** This is necessary because the constructors are `protected`. */ + private class SettingsDialog(context: Context, theme: Int) : AlertDialog(context, theme) +} diff --git a/packages/SystemUI/src/com/android/systemui/controls/ControlsSettingsRepository.kt b/packages/SystemUI/src/com/android/systemui/controls/settings/ControlsSettingsRepository.kt index 3d10ab906f2f..df2831c6eb96 100644 --- a/packages/SystemUI/src/com/android/systemui/controls/ControlsSettingsRepository.kt +++ b/packages/SystemUI/src/com/android/systemui/controls/settings/ControlsSettingsRepository.kt @@ -15,7 +15,7 @@ * */ -package com.android.systemui.controls +package com.android.systemui.controls.settings import kotlinx.coroutines.flow.StateFlow diff --git a/packages/SystemUI/src/com/android/systemui/controls/ControlsSettingsRepositoryImpl.kt b/packages/SystemUI/src/com/android/systemui/controls/settings/ControlsSettingsRepositoryImpl.kt index 9dc422a09674..8e3b5109339c 100644 --- a/packages/SystemUI/src/com/android/systemui/controls/ControlsSettingsRepositoryImpl.kt +++ b/packages/SystemUI/src/com/android/systemui/controls/settings/ControlsSettingsRepositoryImpl.kt @@ -15,7 +15,7 @@ * */ -package com.android.systemui.controls +package com.android.systemui.controls.settings import android.provider.Settings import com.android.systemui.common.coroutine.ConflatedCallbackFlow.conflatedCallbackFlow diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlActionCoordinatorImpl.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlActionCoordinatorImpl.kt index 041ed1d557d7..99a10a33ab0f 100644 --- a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlActionCoordinatorImpl.kt +++ b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlActionCoordinatorImpl.kt @@ -19,15 +19,12 @@ package com.android.systemui.controls.ui import android.annotation.AnyThread import android.annotation.MainThread import android.app.Activity -import android.app.AlertDialog import android.app.Dialog import android.app.PendingIntent import android.content.Context import android.content.pm.PackageManager import android.content.pm.ResolveInfo -import android.os.UserHandle import android.os.VibrationEffect -import android.provider.Settings.Secure import android.service.controls.Control import android.service.controls.actions.BooleanAction import android.service.controls.actions.CommandAction @@ -35,39 +32,36 @@ import android.service.controls.actions.FloatAction import android.util.Log import android.view.HapticFeedbackConstants import com.android.internal.annotations.VisibleForTesting -import com.android.systemui.R import com.android.systemui.broadcast.BroadcastSender import com.android.systemui.controls.ControlsMetricsLogger -import com.android.systemui.controls.ControlsSettingsRepository +import com.android.systemui.controls.settings.ControlsSettingsDialogManager +import com.android.systemui.controls.settings.ControlsSettingsRepository import com.android.systemui.dagger.SysUISingleton import com.android.systemui.dagger.qualifiers.Main +import com.android.systemui.flags.FeatureFlags +import com.android.systemui.flags.Flags import com.android.systemui.plugins.ActivityStarter -import com.android.systemui.settings.UserContextProvider import com.android.systemui.statusbar.VibratorHelper -import com.android.systemui.statusbar.phone.SystemUIDialog -import com.android.systemui.statusbar.policy.DeviceControlsControllerImpl.Companion.PREFS_CONTROLS_FILE -import com.android.systemui.statusbar.policy.DeviceControlsControllerImpl.Companion.PREFS_SETTINGS_DIALOG_ATTEMPTS import com.android.systemui.statusbar.policy.KeyguardStateController import com.android.systemui.util.concurrency.DelayableExecutor -import com.android.systemui.util.settings.SecureSettings import com.android.wm.shell.TaskViewFactory import java.util.Optional import javax.inject.Inject @SysUISingleton class ControlActionCoordinatorImpl @Inject constructor( - private val context: Context, - private val bgExecutor: DelayableExecutor, - @Main private val uiExecutor: DelayableExecutor, - private val activityStarter: ActivityStarter, - private val broadcastSender: BroadcastSender, - private val keyguardStateController: KeyguardStateController, - private val taskViewFactory: Optional<TaskViewFactory>, - private val controlsMetricsLogger: ControlsMetricsLogger, - private val vibrator: VibratorHelper, - private val secureSettings: SecureSettings, - private val userContextProvider: UserContextProvider, - private val controlsSettingsRepository: ControlsSettingsRepository, + private val context: Context, + private val bgExecutor: DelayableExecutor, + @Main private val uiExecutor: DelayableExecutor, + private val activityStarter: ActivityStarter, + private val broadcastSender: BroadcastSender, + private val keyguardStateController: KeyguardStateController, + private val taskViewFactory: Optional<TaskViewFactory>, + private val controlsMetricsLogger: ControlsMetricsLogger, + private val vibrator: VibratorHelper, + private val controlsSettingsRepository: ControlsSettingsRepository, + private val controlsSettingsDialogManager: ControlsSettingsDialogManager, + private val featureFlags: FeatureFlags, ) : ControlActionCoordinator { private var dialog: Dialog? = null private var pendingAction: Action? = null @@ -76,16 +70,16 @@ class ControlActionCoordinatorImpl @Inject constructor( get() = !keyguardStateController.isUnlocked() private val allowTrivialControls: Boolean get() = controlsSettingsRepository.allowActionOnTrivialControlsInLockscreen.value - private val showDeviceControlsInLockscreen: Boolean - get() = controlsSettingsRepository.canShowControlsInLockscreen.value override lateinit var activityContext: Context companion object { private const val RESPONSE_TIMEOUT_IN_MILLIS = 3000L - private const val MAX_NUMBER_ATTEMPTS_CONTROLS_DIALOG = 2 } override fun closeDialogs() { + if (!featureFlags.isEnabled(Flags.USE_APP_PANELS)) { + controlsSettingsDialogManager.closeDialog() + } val isActivityFinishing = (activityContext as? Activity)?.let { it.isFinishing || it.isDestroyed } if (isActivityFinishing == true) { @@ -253,71 +247,9 @@ class ControlActionCoordinatorImpl @Inject constructor( if (action.authIsRequired) { return } - val prefs = userContextProvider.userContext.getSharedPreferences( - PREFS_CONTROLS_FILE, Context.MODE_PRIVATE) - val attempts = prefs.getInt(PREFS_SETTINGS_DIALOG_ATTEMPTS, 0) - if (attempts >= MAX_NUMBER_ATTEMPTS_CONTROLS_DIALOG || - (showDeviceControlsInLockscreen && allowTrivialControls)) { - return + if (!featureFlags.isEnabled(Flags.USE_APP_PANELS)) { + controlsSettingsDialogManager.maybeShowDialog(activityContext) {} } - val builder = AlertDialog - .Builder(activityContext, R.style.Theme_SystemUI_Dialog) - .setIcon(R.drawable.ic_warning) - .setOnCancelListener { - if (attempts < MAX_NUMBER_ATTEMPTS_CONTROLS_DIALOG) { - prefs.edit().putInt(PREFS_SETTINGS_DIALOG_ATTEMPTS, attempts + 1) - .commit() - } - true - } - .setNeutralButton(R.string.controls_settings_dialog_neutral_button) { _, _ -> - if (attempts != MAX_NUMBER_ATTEMPTS_CONTROLS_DIALOG) { - prefs.edit().putInt(PREFS_SETTINGS_DIALOG_ATTEMPTS, - MAX_NUMBER_ATTEMPTS_CONTROLS_DIALOG) - .commit() - } - true - } - - if (showDeviceControlsInLockscreen) { - dialog = builder - .setTitle(R.string.controls_settings_trivial_controls_dialog_title) - .setMessage(R.string.controls_settings_trivial_controls_dialog_message) - .setPositiveButton(R.string.controls_settings_dialog_positive_button) { _, _ -> - if (attempts != MAX_NUMBER_ATTEMPTS_CONTROLS_DIALOG) { - prefs.edit().putInt(PREFS_SETTINGS_DIALOG_ATTEMPTS, - MAX_NUMBER_ATTEMPTS_CONTROLS_DIALOG) - .commit() - } - secureSettings.putIntForUser(Secure.LOCKSCREEN_ALLOW_TRIVIAL_CONTROLS, 1, - UserHandle.USER_CURRENT) - true - } - .create() - } else { - dialog = builder - .setTitle(R.string.controls_settings_show_controls_dialog_title) - .setMessage(R.string.controls_settings_show_controls_dialog_message) - .setPositiveButton(R.string.controls_settings_dialog_positive_button) { _, _ -> - if (attempts != MAX_NUMBER_ATTEMPTS_CONTROLS_DIALOG) { - prefs.edit().putInt(PREFS_SETTINGS_DIALOG_ATTEMPTS, - MAX_NUMBER_ATTEMPTS_CONTROLS_DIALOG) - .commit() - } - secureSettings.putIntForUser(Secure.LOCKSCREEN_SHOW_CONTROLS, - 1, UserHandle.USER_CURRENT) - secureSettings.putIntForUser(Secure.LOCKSCREEN_ALLOW_TRIVIAL_CONTROLS, - 1, UserHandle.USER_CURRENT) - true - } - .create() - } - - SystemUIDialog.registerDismissListener(dialog) - SystemUIDialog.setDialogSize(dialog) - - dialog?.create() - dialog?.show() } @VisibleForTesting diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlsActivity.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlsActivity.kt index bd704c1ff086..5d611c4c8212 100644 --- a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlsActivity.kt +++ b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlsActivity.kt @@ -32,8 +32,10 @@ import androidx.activity.ComponentActivity import com.android.systemui.R import com.android.systemui.broadcast.BroadcastDispatcher import com.android.systemui.controls.management.ControlsAnimations +import com.android.systemui.controls.settings.ControlsSettingsDialogManager import com.android.systemui.flags.FeatureFlags import com.android.systemui.flags.Flags +import com.android.systemui.statusbar.policy.KeyguardStateController import javax.inject.Inject /** @@ -47,7 +49,9 @@ class ControlsActivity @Inject constructor( private val uiController: ControlsUiController, private val broadcastDispatcher: BroadcastDispatcher, private val dreamManager: IDreamManager, - private val featureFlags: FeatureFlags + private val featureFlags: FeatureFlags, + private val controlsSettingsDialogManager: ControlsSettingsDialogManager, + private val keyguardStateController: KeyguardStateController ) : ComponentActivity() { private lateinit var parent: ViewGroup @@ -92,7 +96,13 @@ class ControlsActivity @Inject constructor( parent = requireViewById<ViewGroup>(R.id.global_actions_controls) parent.alpha = 0f - uiController.show(parent, { finishOrReturnToDream() }, this) + if (featureFlags.isEnabled(Flags.USE_APP_PANELS) && !keyguardStateController.isUnlocked) { + controlsSettingsDialogManager.maybeShowDialog(this) { + uiController.show(parent, { finishOrReturnToDream() }, this) + } + } else { + uiController.show(parent, { finishOrReturnToDream() }, this) + } ControlsAnimations.enterAnimation(parent).start() } @@ -124,6 +134,7 @@ class ControlsActivity @Inject constructor( mExitToDream = false uiController.hide() + controlsSettingsDialogManager.closeDialog() } override fun onDestroy() { diff --git a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlsUiControllerImpl.kt b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlsUiControllerImpl.kt index a07c716bc8f9..fb678aa420bf 100644 --- a/packages/SystemUI/src/com/android/systemui/controls/ui/ControlsUiControllerImpl.kt +++ b/packages/SystemUI/src/com/android/systemui/controls/ui/ControlsUiControllerImpl.kt @@ -49,7 +49,7 @@ import com.android.systemui.Dumpable import com.android.systemui.R import com.android.systemui.controls.ControlsMetricsLogger import com.android.systemui.controls.ControlsServiceInfo -import com.android.systemui.controls.ControlsSettingsRepository +import com.android.systemui.controls.settings.ControlsSettingsRepository import com.android.systemui.controls.CustomIconCache import com.android.systemui.controls.controller.ControlsController import com.android.systemui.controls.controller.StructureInfo diff --git a/packages/SystemUI/src/com/android/systemui/dagger/FrameworkServicesModule.java b/packages/SystemUI/src/com/android/systemui/dagger/FrameworkServicesModule.java index 8b4b30c89b14..3644d4242a6f 100644 --- a/packages/SystemUI/src/com/android/systemui/dagger/FrameworkServicesModule.java +++ b/packages/SystemUI/src/com/android/systemui/dagger/FrameworkServicesModule.java @@ -36,6 +36,8 @@ import android.app.job.JobScheduler; import android.app.role.RoleManager; import android.app.smartspace.SmartspaceManager; import android.app.trust.TrustManager; +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothManager; import android.content.ClipboardManager; import android.content.ContentResolver; import android.content.Context; @@ -616,4 +618,16 @@ public class FrameworkServicesModule { static CameraManager provideCameraManager(Context context) { return context.getSystemService(CameraManager.class); } + + @Provides + @Singleton + static BluetoothManager provideBluetoothManager(Context context) { + return context.getSystemService(BluetoothManager.class); + } + + @Provides + @Singleton + static BluetoothAdapter provideBluetoothAdapter(BluetoothManager bluetoothManager) { + return bluetoothManager.getAdapter(); + } } diff --git a/packages/SystemUI/src/com/android/systemui/dagger/SysUIComponent.java b/packages/SystemUI/src/com/android/systemui/dagger/SysUIComponent.java index 6dc4f5c60108..68f4dbe53500 100644 --- a/packages/SystemUI/src/com/android/systemui/dagger/SysUIComponent.java +++ b/packages/SystemUI/src/com/android/systemui/dagger/SysUIComponent.java @@ -125,10 +125,10 @@ public interface SysUIComponent { default void init() { // Initialize components that have no direct tie to the dagger dependency graph, // but are critical to this component's operation - // TODO(b/205034537): I think this is a good idea? getSysUIUnfoldComponent().ifPresent(c -> { c.getUnfoldLightRevealOverlayAnimation().init(); c.getUnfoldTransitionWallpaperController().init(); + c.getUnfoldHapticsPlayer(); }); getNaturalRotationUnfoldProgressProvider().ifPresent(o -> o.init()); // No init method needed, just needs to be gotten so that it's created. diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeLog.java b/packages/SystemUI/src/com/android/systemui/doze/DozeLog.java index 0c14ed5c2164..5d21349fce11 100644 --- a/packages/SystemUI/src/com/android/systemui/doze/DozeLog.java +++ b/packages/SystemUI/src/com/android/systemui/doze/DozeLog.java @@ -28,6 +28,8 @@ import com.android.systemui.dagger.SysUISingleton; import com.android.systemui.dump.DumpManager; import com.android.systemui.statusbar.policy.DevicePostureController; +import com.google.errorprone.annotations.CompileTimeConstant; + import java.io.PrintWriter; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -80,6 +82,13 @@ public class DozeLog implements Dumpable { } /** + * Log debug message to LogBuffer. + */ + public void d(@CompileTimeConstant String msg) { + mLogger.log(msg); + } + + /** * Appends pickup wakeup event to the logs */ public void tracePickupWakeUp(boolean withinVibrationThreshold) { @@ -88,6 +97,10 @@ public class DozeLog implements Dumpable { : mPickupPulseNotNearVibrationStats).append(); } + public void traceSetIgnoreTouchWhilePulsing(boolean ignoreTouch) { + mLogger.logSetIgnoreTouchWhilePulsing(ignoreTouch); + } + /** * Appends pulse started event to the logs. * @param reason why the pulse started diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeLogger.kt b/packages/SystemUI/src/com/android/systemui/doze/DozeLogger.kt index b5dbe21a2cf7..d19c6ec01109 100644 --- a/packages/SystemUI/src/com/android/systemui/doze/DozeLogger.kt +++ b/packages/SystemUI/src/com/android/systemui/doze/DozeLogger.kt @@ -364,6 +364,14 @@ class DozeLogger @Inject constructor( }) } + fun logSetIgnoreTouchWhilePulsing(ignoreTouchWhilePulsing: Boolean) { + buffer.log(TAG, DEBUG, { + bool1 = ignoreTouchWhilePulsing + }, { + "Prox changed while pulsing. setIgnoreTouchWhilePulsing=$bool1" + }) + } + fun log(@CompileTimeConstant msg: String) { buffer.log(TAG, DEBUG, msg) } diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java b/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java index 5daf1ceaf592..3f9f14c620b5 100644 --- a/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java +++ b/packages/SystemUI/src/com/android/systemui/doze/DozeTriggers.java @@ -333,15 +333,18 @@ public class DozeTriggers implements DozeMachine.Part { } gentleWakeUp(pulseReason); } else if (isUdfpsLongPress) { - final State state = mMachine.getState(); - if (state == State.DOZE_AOD || state == State.DOZE) { + if (canPulse(mMachine.getState(), true)) { + mDozeLog.d("updfsLongPress - setting aodInterruptRunnable to run when " + + "the display is on"); // Since the gesture won't be received by the UDFPS view, we need to // manually inject an event once the display is ON mAodInterruptRunnable = () -> - mAuthController.onAodInterrupt((int) screenX, (int) screenY, - rawValues[3] /* major */, rawValues[4] /* minor */); + mAuthController.onAodInterrupt((int) screenX, (int) screenY, + rawValues[3] /* major */, rawValues[4] /* minor */); + } else { + mDozeLog.d("udfpsLongPress - Not sending aodInterrupt. " + + "Unsupported doze state."); } - requestPulse(DozeLog.REASON_SENSOR_UDFPS_LONG_PRESS, true, null); } else { mDozeHost.extendPulse(pulseReason); @@ -380,7 +383,7 @@ public class DozeTriggers implements DozeMachine.Part { // when a new event is arriving. This means that a state transition might have happened // and the proximity check is now obsolete. if (mMachine.isExecutingTransition()) { - Log.w(TAG, "onProximityFar called during transition. Ignoring sensor response."); + mDozeLog.d("onProximityFar called during transition. Ignoring sensor response."); return; } @@ -392,21 +395,15 @@ public class DozeTriggers implements DozeMachine.Part { if (state == DozeMachine.State.DOZE_PULSING || state == DozeMachine.State.DOZE_PULSING_BRIGHT) { - if (DEBUG) { - Log.i(TAG, "Prox changed, ignore touch = " + near); - } + mDozeLog.traceSetIgnoreTouchWhilePulsing(near); mDozeHost.onIgnoreTouchWhilePulsing(near); } if (far && (paused || pausing)) { - if (DEBUG) { - Log.i(TAG, "Prox FAR, unpausing AOD"); - } + mDozeLog.d("Prox FAR, unpausing AOD"); mMachine.requestState(DozeMachine.State.DOZE_AOD); } else if (near && aod) { - if (DEBUG) { - Log.i(TAG, "Prox NEAR, pausing AOD"); - } + mDozeLog.d("Prox NEAR, starting pausing AOD countdown"); mMachine.requestState(DozeMachine.State.DOZE_AOD_PAUSING); } } @@ -551,12 +548,13 @@ public class DozeTriggers implements DozeMachine.Part { return; } - if (!mAllowPulseTriggers || mDozeHost.isPulsePending() || !canPulse(dozeState)) { + if (!mAllowPulseTriggers || mDozeHost.isPulsePending() + || !canPulse(dozeState, performedProxCheck)) { if (!mAllowPulseTriggers) { mDozeLog.tracePulseDropped("requestPulse - !mAllowPulseTriggers"); } else if (mDozeHost.isPulsePending()) { mDozeLog.tracePulseDropped("requestPulse - pulsePending"); - } else if (!canPulse(dozeState)) { + } else if (!canPulse(dozeState, performedProxCheck)) { mDozeLog.tracePulseDropped("requestPulse - dozeState cannot pulse", dozeState); } runIfNotNull(onPulseSuppressedListener); @@ -574,14 +572,15 @@ public class DozeTriggers implements DozeMachine.Part { // not in pocket, continue pulsing final boolean isPulsePending = mDozeHost.isPulsePending(); mDozeHost.setPulsePending(false); - if (!isPulsePending || mDozeHost.isPulsingBlocked() || !canPulse(dozeState)) { + if (!isPulsePending || mDozeHost.isPulsingBlocked() + || !canPulse(dozeState, performedProxCheck)) { if (!isPulsePending) { mDozeLog.tracePulseDropped("continuePulseRequest - pulse no longer" + " pending, pulse was cancelled before it could start" + " transitioning to pulsing state."); } else if (mDozeHost.isPulsingBlocked()) { mDozeLog.tracePulseDropped("continuePulseRequest - pulsingBlocked"); - } else if (!canPulse(dozeState)) { + } else if (!canPulse(dozeState, performedProxCheck)) { mDozeLog.tracePulseDropped("continuePulseRequest" + " - doze state cannot pulse", dozeState); } @@ -598,10 +597,13 @@ public class DozeTriggers implements DozeMachine.Part { .ifPresent(uiEventEnum -> mUiEventLogger.log(uiEventEnum, getKeyguardSessionId())); } - private boolean canPulse(DozeMachine.State dozeState) { + private boolean canPulse(DozeMachine.State dozeState, boolean pulsePerformedProximityCheck) { + final boolean dozePausedOrPausing = dozeState == State.DOZE_AOD_PAUSED + || dozeState == State.DOZE_AOD_PAUSING; return dozeState == DozeMachine.State.DOZE || dozeState == DozeMachine.State.DOZE_AOD - || dozeState == DozeMachine.State.DOZE_AOD_DOCKED; + || dozeState == DozeMachine.State.DOZE_AOD_DOCKED + || (dozePausedOrPausing && pulsePerformedProximityCheck); } @Nullable diff --git a/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsDebug.java b/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsDebug.java index 81df4ed51d8d..267e0366b00e 100644 --- a/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsDebug.java +++ b/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsDebug.java @@ -87,7 +87,7 @@ public class FeatureFlagsDebug implements FeatureFlags { new ServerFlagReader.ChangeListener() { @Override public void onChange() { - mRestarter.restart(); + mRestarter.restartSystemUI(); } }; @@ -327,9 +327,7 @@ public class FeatureFlagsDebug implements FeatureFlags { Log.i(TAG, "SystemUI Restart Suppressed"); return; } - Log.i(TAG, "Restarting SystemUI"); - // SysUI starts back when up exited. Is there a better way to do this? - System.exit(0); + mRestarter.restartSystemUI(); } private void restartAndroid(boolean requestSuppress) { @@ -337,7 +335,7 @@ public class FeatureFlagsDebug implements FeatureFlags { Log.i(TAG, "Android Restart Suppressed"); return; } - mRestarter.restart(); + mRestarter.restartAndroid(); } void setBooleanFlagInternal(Flag<?> flag, boolean value) { diff --git a/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsDebugRestarter.kt b/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsDebugRestarter.kt index 3d9f62768a37..069e6127aa30 100644 --- a/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsDebugRestarter.kt +++ b/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsDebugRestarter.kt @@ -28,6 +28,8 @@ constructor( private val systemExitRestarter: SystemExitRestarter, ) : Restarter { + private var androidRestartRequested = false + val observer = object : WakefulnessLifecycle.Observer { override fun onFinishedGoingToSleep() { @@ -36,8 +38,18 @@ constructor( } } - override fun restart() { - Log.d(FeatureFlagsDebug.TAG, "Restart requested. Restarting on next screen off.") + override fun restartSystemUI() { + Log.d(FeatureFlagsDebug.TAG, "SystemUI Restart requested. Restarting on next screen off.") + scheduleRestart() + } + + override fun restartAndroid() { + Log.d(FeatureFlagsDebug.TAG, "Android Restart requested. Restarting on next screen off.") + androidRestartRequested = true + scheduleRestart() + } + + fun scheduleRestart() { if (wakefulnessLifecycle.wakefulness == WakefulnessLifecycle.WAKEFULNESS_ASLEEP) { restartNow() } else { @@ -46,6 +58,10 @@ constructor( } private fun restartNow() { - systemExitRestarter.restart() + if (androidRestartRequested) { + systemExitRestarter.restartAndroid() + } else { + systemExitRestarter.restartSystemUI() + } } } diff --git a/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsDebugStartable.kt b/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsDebugStartable.kt index 7189f00457a4..b94d781154dd 100644 --- a/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsDebugStartable.kt +++ b/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsDebugStartable.kt @@ -16,7 +16,9 @@ package com.android.systemui.flags +import android.content.Intent import com.android.systemui.CoreStartable +import com.android.systemui.broadcast.BroadcastSender import com.android.systemui.dump.DumpManager import com.android.systemui.statusbar.commandline.CommandRegistry import dagger.Binds @@ -31,7 +33,8 @@ constructor( dumpManager: DumpManager, private val commandRegistry: CommandRegistry, private val flagCommand: FlagCommand, - private val featureFlags: FeatureFlagsDebug + private val featureFlags: FeatureFlagsDebug, + private val broadcastSender: BroadcastSender ) : CoreStartable { init { @@ -43,6 +46,8 @@ constructor( override fun start() { featureFlags.init() commandRegistry.registerCommand(FlagCommand.FLAG_COMMAND) { flagCommand } + val intent = Intent(FlagManager.ACTION_SYSUI_STARTED) + broadcastSender.sendBroadcast(intent) } } diff --git a/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsRelease.java b/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsRelease.java index 3c83682210b6..8bddacc4e32c 100644 --- a/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsRelease.java +++ b/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsRelease.java @@ -61,7 +61,7 @@ public class FeatureFlagsRelease implements FeatureFlags { new ServerFlagReader.ChangeListener() { @Override public void onChange() { - mRestarter.restart(); + mRestarter.restartSystemUI(); } }; diff --git a/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsReleaseRestarter.kt b/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsReleaseRestarter.kt index a3f0f665c056..7ff3876f5d4e 100644 --- a/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsReleaseRestarter.kt +++ b/packages/SystemUI/src/com/android/systemui/flags/FeatureFlagsReleaseRestarter.kt @@ -34,35 +34,48 @@ constructor( @Background private val bgExecutor: DelayableExecutor, private val systemExitRestarter: SystemExitRestarter ) : Restarter { - var shouldRestart = false + var listenersAdded = false var pendingRestart: Runnable? = null + var androidRestartRequested = false val observer = object : WakefulnessLifecycle.Observer { override fun onFinishedGoingToSleep() { - maybeScheduleRestart() + scheduleRestart() } } val batteryCallback = object : BatteryController.BatteryStateChangeCallback { override fun onBatteryLevelChanged(level: Int, pluggedIn: Boolean, charging: Boolean) { - maybeScheduleRestart() + scheduleRestart() } } - override fun restart() { - Log.d(FeatureFlagsDebug.TAG, "Restart requested. Restarting when plugged in and idle.") - if (!shouldRestart) { - // Don't bother scheduling twice. - shouldRestart = true + override fun restartSystemUI() { + Log.d( + FeatureFlagsDebug.TAG, + "SystemUI Restart requested. Restarting when plugged in and idle." + ) + scheduleRestart() + } + + override fun restartAndroid() { + Log.d( + FeatureFlagsDebug.TAG, + "Android Restart requested. Restarting when plugged in and idle." + ) + androidRestartRequested = true + scheduleRestart() + } + + private fun scheduleRestart() { + // Don't bother adding listeners twice. + if (!listenersAdded) { + listenersAdded = true wakefulnessLifecycle.addObserver(observer) batteryController.addCallback(batteryCallback) - maybeScheduleRestart() } - } - - private fun maybeScheduleRestart() { if ( wakefulnessLifecycle.wakefulness == WAKEFULNESS_ASLEEP && batteryController.isPluggedIn ) { @@ -77,6 +90,10 @@ constructor( private fun restartNow() { Log.d(FeatureFlagsRelease.TAG, "Restarting due to systemui flag change") - systemExitRestarter.restart() + if (androidRestartRequested) { + systemExitRestarter.restartAndroid() + } else { + systemExitRestarter.restartSystemUI() + } } } diff --git a/packages/SystemUI/src/com/android/systemui/flags/Flags.kt b/packages/SystemUI/src/com/android/systemui/flags/Flags.kt index ae2e1d1324ff..c712a94df606 100644 --- a/packages/SystemUI/src/com/android/systemui/flags/Flags.kt +++ b/packages/SystemUI/src/com/android/systemui/flags/Flags.kt @@ -71,6 +71,9 @@ object Flags { val NOTIFICATION_MEMORY_MONITOR_ENABLED = releasedFlag(112, "notification_memory_monitor_enabled") + val NOTIFICATION_MEMORY_LOGGING_ENABLED = + unreleasedFlag(119, "notification_memory_logging_enabled", teamfood = true) + // TODO(b/254512731): Tracking Bug @JvmField val NOTIFICATION_DISMISSAL_FADE = @@ -91,14 +94,14 @@ object Flags { unreleasedFlag(259217907, "notification_group_dismissal_animation", teamfood = true) // TODO(b/257506350): Tracking Bug - val FSI_CHROME = unreleasedFlag(117, "fsi_chrome") + @JvmField val FSI_CHROME = unreleasedFlag(117, "fsi_chrome") @JvmField val SIMPLIFIED_APPEAR_FRACTION = unreleasedFlag(259395680, "simplified_appear_fraction", teamfood = true) // TODO(b/257315550): Tracking Bug - val NO_HUN_FOR_OLD_WHEN = unreleasedFlag(118, "no_hun_for_old_when") + val NO_HUN_FOR_OLD_WHEN = unreleasedFlag(118, "no_hun_for_old_when", teamfood = true) val FILTER_UNSEEN_NOTIFS_ON_KEYGUARD = unreleasedFlag(254647461, "filter_unseen_notifs_on_keyguard", teamfood = true) @@ -134,7 +137,8 @@ object Flags { * Whether the clock on a wide lock screen should use the new "stepping" animation for moving * the digits when the clock moves. */ - @JvmField val STEP_CLOCK_ANIMATION = unreleasedFlag(212, "step_clock_animation") + @JvmField + val STEP_CLOCK_ANIMATION = unreleasedFlag(212, "step_clock_animation", teamfood = true) /** * Migration from the legacy isDozing/dozeAmount paths to the new KeyguardTransitionRepository @@ -204,9 +208,6 @@ object Flags { "full_screen_user_switcher" ) - // TODO(b/254512678): Tracking Bug - @JvmField val NEW_FOOTER_ACTIONS = releasedFlag(507, "new_footer_actions") - // TODO(b/244064524): Tracking Bug @JvmField val QS_SECONDARY_DATA_SUB_INFO = releasedFlag(508, "qs_secondary_data_sub_info") @@ -249,7 +250,7 @@ object Flags { // 801 - region sampling // TODO(b/254512848): Tracking Bug - val REGION_SAMPLING = unreleasedFlag(801, "region_sampling") + val REGION_SAMPLING = unreleasedFlag(801, "region_sampling", teamfood = true) // 802 - wallpaper rendering // TODO(b/254512923): Tracking Bug @@ -417,6 +418,10 @@ object Flags { // 2000 - device controls @Keep @JvmField val USE_APP_PANELS = unreleasedFlag(2000, "use_app_panels", teamfood = true) + @JvmField + val APP_PANELS_ALL_APPS_ALLOWED = + unreleasedFlag(2001, "app_panels_all_apps_allowed", teamfood = true) + // 2100 - Falsing Manager @JvmField val FALSING_FOR_LONG_TAPS = releasedFlag(2100, "falsing_for_long_taps") @@ -428,6 +433,7 @@ object Flags { // 2300 - stylus @JvmField val TRACK_STYLUS_EVER_USED = unreleasedFlag(2300, "track_stylus_ever_used") + @JvmField val ENABLE_STYLUS_CHARGING_UI = unreleasedFlag(2301, "enable_stylus_charging_ui") // 2400 - performance tools and debugging info // TODO(b/238923086): Tracking Bug @@ -435,6 +441,11 @@ object Flags { val WARN_ON_BLOCKING_BINDER_TRANSACTIONS = unreleasedFlag(2400, "warn_on_blocking_binder_transactions") + // 2500 - output switcher + // TODO(b/261538825): Tracking Bug + @JvmField + val OUTPUT_SWITCHER_ADVANCED_LAYOUT = unreleasedFlag(2500, "output_switcher_advanced_layout") + // TODO(b259590361): Tracking bug val EXPERIMENTAL_FLAG = unreleasedFlag(2, "exp_flag_release") } diff --git a/packages/SystemUI/src/com/android/systemui/flags/Restarter.kt b/packages/SystemUI/src/com/android/systemui/flags/Restarter.kt index 8f095a24de94..ce8b821b1182 100644 --- a/packages/SystemUI/src/com/android/systemui/flags/Restarter.kt +++ b/packages/SystemUI/src/com/android/systemui/flags/Restarter.kt @@ -16,5 +16,7 @@ package com.android.systemui.flags interface Restarter { - fun restart() -}
\ No newline at end of file + fun restartSystemUI() + + fun restartAndroid() +} diff --git a/packages/SystemUI/src/com/android/systemui/flags/SystemExitRestarter.kt b/packages/SystemUI/src/com/android/systemui/flags/SystemExitRestarter.kt index f1b1be47a84f..89daa6487fbc 100644 --- a/packages/SystemUI/src/com/android/systemui/flags/SystemExitRestarter.kt +++ b/packages/SystemUI/src/com/android/systemui/flags/SystemExitRestarter.kt @@ -16,10 +16,19 @@ package com.android.systemui.flags +import com.android.internal.statusbar.IStatusBarService import javax.inject.Inject -class SystemExitRestarter @Inject constructor() : Restarter { - override fun restart() { +class SystemExitRestarter +@Inject +constructor( + private val barService: IStatusBarService, +) : Restarter { + override fun restartAndroid() { + barService.restart() + } + + override fun restartSystemUI() { System.exit(0) } } diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardUnlockAnimationController.kt b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardUnlockAnimationController.kt index c4eac1c3c401..c0d6cc9fd2b8 100644 --- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardUnlockAnimationController.kt +++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardUnlockAnimationController.kt @@ -824,7 +824,11 @@ class KeyguardUnlockAnimationController @Inject constructor( surfaceBehindEntryAnimator.cancel() surfaceBehindAlpha = 1f setSurfaceBehindAppearAmount(1f) - launcherUnlockController?.setUnlockAmount(1f, false /* forceIfAnimating */) + try { + launcherUnlockController?.setUnlockAmount(1f, false /* forceIfAnimating */) + } catch (e: RemoteException) { + Log.e(TAG, "Remote exception in notifyFinishedKeyguardExitAnimation", e) + } // That target is no longer valid since the animation finished, null it out. surfaceBehindRemoteAnimationTargets = null diff --git a/packages/SystemUI/src/com/android/systemui/log/SessionTracker.java b/packages/SystemUI/src/com/android/systemui/log/SessionTracker.java index c7e4c5e93090..b98a92ff8600 100644 --- a/packages/SystemUI/src/com/android/systemui/log/SessionTracker.java +++ b/packages/SystemUI/src/com/android/systemui/log/SessionTracker.java @@ -49,7 +49,9 @@ import javax.inject.Inject; @SysUISingleton public class SessionTracker implements CoreStartable { private static final String TAG = "SessionTracker"; - private static final boolean DEBUG = false; + + // To enable logs: `adb shell setprop log.tag.SessionTracker DEBUG` & restart sysui + private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG); // At most 20 bits: ~1m possibilities, ~0.5% probability of collision in 100 values private final InstanceIdSequence mInstanceIdGenerator = new InstanceIdSequence(1 << 20); @@ -81,8 +83,8 @@ public class SessionTracker implements CoreStartable { mKeyguardUpdateMonitor.registerCallback(mKeyguardUpdateMonitorCallback); mKeyguardStateController.addCallback(mKeyguardStateCallback); - mKeyguardSessionStarted = mKeyguardStateController.isShowing(); - if (mKeyguardSessionStarted) { + if (mKeyguardStateController.isShowing()) { + mKeyguardSessionStarted = true; startSession(SESSION_KEYGUARD); } } @@ -136,12 +138,11 @@ public class SessionTracker implements CoreStartable { new KeyguardUpdateMonitorCallback() { @Override public void onStartedGoingToSleep(int why) { - // we need to register to the KeyguardUpdateMonitor lifecycle b/c it gets called - // before the WakefulnessLifecycle if (mKeyguardSessionStarted) { - return; + endSession(SESSION_KEYGUARD); } + // Start a new session whenever the device goes to sleep mKeyguardSessionStarted = true; startSession(SESSION_KEYGUARD); } @@ -154,6 +155,9 @@ public class SessionTracker implements CoreStartable { boolean wasSessionStarted = mKeyguardSessionStarted; boolean keyguardShowing = mKeyguardStateController.isShowing(); if (keyguardShowing && !wasSessionStarted) { + // the keyguard can start showing without the device going to sleep (ie: lockdown + // from the power button), so we start a new keyguard session when the keyguard is + // newly shown in addition to when the device starts going to sleep mKeyguardSessionStarted = true; startSession(SESSION_KEYGUARD); } else if (!keyguardShowing && wasSessionStarted) { diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/pipeline/MediaDataManager.kt b/packages/SystemUI/src/com/android/systemui/media/controls/pipeline/MediaDataManager.kt index 3012bb41445e..2dd339d409a6 100644 --- a/packages/SystemUI/src/com/android/systemui/media/controls/pipeline/MediaDataManager.kt +++ b/packages/SystemUI/src/com/android/systemui/media/controls/pipeline/MediaDataManager.kt @@ -422,6 +422,7 @@ class MediaDataManager( appUid = appUid ) mediaEntries.put(packageName, resumeData) + logSingleVsMultipleMediaAdded(appUid, packageName, instanceId) logger.logResumeMediaAdded(appUid, packageName, instanceId) } backgroundExecutor.execute { @@ -812,6 +813,7 @@ class MediaDataManager( val appUid = appInfo?.uid ?: Process.INVALID_UID if (logEvent) { + logSingleVsMultipleMediaAdded(appUid, sbn.packageName, instanceId) logger.logActiveMediaAdded(appUid, sbn.packageName, instanceId, playbackLocation) } else if (playbackLocation != currentEntry?.playbackLocation) { logger.logPlaybackLocationChange(appUid, sbn.packageName, instanceId, playbackLocation) @@ -855,6 +857,20 @@ class MediaDataManager( } } + private fun logSingleVsMultipleMediaAdded( + appUid: Int, + packageName: String, + instanceId: InstanceId + ) { + if (mediaEntries.size == 1) { + logger.logSingleMediaPlayerInCarousel(appUid, packageName, instanceId) + } else if (mediaEntries.size == 2) { + // Since this method is only called when there is a new media session added. + // logging needed once there is more than one media session in carousel. + logger.logMultipleMediaPlayersInCarousel(appUid, packageName, instanceId) + } + } + private fun getAppInfoFromPackage(packageName: String): ApplicationInfo? { try { return context.packageManager.getApplicationInfo(packageName, 0) diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/util/MediaUiEventLogger.kt b/packages/SystemUI/src/com/android/systemui/media/controls/util/MediaUiEventLogger.kt index 3ad8c21e8a1e..ea943be85f21 100644 --- a/packages/SystemUI/src/com/android/systemui/media/controls/util/MediaUiEventLogger.kt +++ b/packages/SystemUI/src/com/android/systemui/media/controls/util/MediaUiEventLogger.kt @@ -213,6 +213,24 @@ class MediaUiEventLogger @Inject constructor(private val logger: UiEventLogger) instanceId ) } + + fun logSingleMediaPlayerInCarousel(uid: Int, packageName: String, instanceId: InstanceId) { + logger.logWithInstanceId( + MediaUiEvent.MEDIA_CAROUSEL_SINGLE_PLAYER, + uid, + packageName, + instanceId + ) + } + + fun logMultipleMediaPlayersInCarousel(uid: Int, packageName: String, instanceId: InstanceId) { + logger.logWithInstanceId( + MediaUiEvent.MEDIA_CAROUSEL_MULTIPLE_PLAYERS, + uid, + packageName, + instanceId + ) + } } enum class MediaUiEvent(val metricId: Int) : UiEventLogger.UiEventEnum { @@ -269,7 +287,11 @@ enum class MediaUiEvent(val metricId: Int) : UiEventLogger.UiEventEnum { @UiEvent(doc = "User tapped on a media recommendation card") MEDIA_RECOMMENDATION_CARD_TAP(1045), @UiEvent(doc = "User opened the broadcast dialog from a media control") - MEDIA_OPEN_BROADCAST_DIALOG(1079); + MEDIA_OPEN_BROADCAST_DIALOG(1079), + @UiEvent(doc = "The media carousel contains one media player card") + MEDIA_CAROUSEL_SINGLE_PLAYER(1244), + @UiEvent(doc = "The media carousel contains multiple media player cards") + MEDIA_CAROUSEL_MULTIPLE_PLAYERS(1245); override fun getId() = metricId } diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaItem.java b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaItem.java new file mode 100644 index 000000000000..875a01087908 --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaItem.java @@ -0,0 +1,97 @@ +/* + * 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.media.dialog; + +import androidx.annotation.IntDef; + +import com.android.settingslib.media.MediaDevice; +import com.android.systemui.R; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.util.Optional; + +/** + * MediaItem represents an item in OutputSwitcher list (could be a MediaDevice, group divider or + * connect new device item). + */ +public class MediaItem { + private final Optional<MediaDevice> mMediaDeviceOptional; + private final String mTitle; + @MediaItemType + private final int mMediaItemType; + + @Retention(RetentionPolicy.SOURCE) + @IntDef({ + MediaItemType.TYPE_DEVICE, + MediaItemType.TYPE_GROUP_DIVIDER, + MediaItemType.TYPE_PAIR_NEW_DEVICE}) + public @interface MediaItemType { + int TYPE_DEVICE = 0; + int TYPE_GROUP_DIVIDER = 1; + int TYPE_PAIR_NEW_DEVICE = 2; + } + + public MediaItem() { + this.mMediaDeviceOptional = Optional.empty(); + this.mTitle = null; + this.mMediaItemType = MediaItemType.TYPE_PAIR_NEW_DEVICE; + } + + public MediaItem(String title, int mediaItemType) { + this.mMediaDeviceOptional = Optional.empty(); + this.mTitle = title; + this.mMediaItemType = mediaItemType; + } + + public MediaItem(MediaDevice mediaDevice) { + this.mMediaDeviceOptional = Optional.of(mediaDevice); + this.mTitle = mediaDevice.getName(); + this.mMediaItemType = MediaItemType.TYPE_DEVICE; + } + + public Optional<MediaDevice> getMediaDevice() { + return mMediaDeviceOptional; + } + + /** + * Get layout id based on media item Type. + */ + public static int getMediaLayoutId(int mediaItemType) { + switch (mediaItemType) { + case MediaItemType.TYPE_DEVICE: + case MediaItemType.TYPE_PAIR_NEW_DEVICE: + return R.layout.media_output_list_item_advanced; + case MediaItemType.TYPE_GROUP_DIVIDER: + default: + return R.layout.media_output_list_group_divider; + } + } + + public String getTitle() { + return mTitle; + } + + public boolean isMutingExpectedDevice() { + return mMediaDeviceOptional.isPresent() + && mMediaDeviceOptional.get().isMutingExpectedDevice(); + } + + public int getMediaItemType() { + return mMediaItemType; + } +} 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 ee5956105b7b..fb47d97ed1d4 100644 --- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputAdapter.java +++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputAdapter.java @@ -16,7 +16,6 @@ package com.android.systemui.media.dialog; -import android.annotation.DrawableRes; import android.content.res.ColorStateList; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; @@ -25,9 +24,11 @@ import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; +import android.widget.TextView; import androidx.annotation.NonNull; import androidx.core.widget.CompoundButtonCompat; +import androidx.recyclerview.widget.RecyclerView; import com.android.settingslib.media.LocalMediaManager.MediaDeviceState; import com.android.settingslib.media.MediaDevice; @@ -49,29 +50,68 @@ public class MediaOutputAdapter extends MediaOutputBaseAdapter { } @Override - public MediaDeviceBaseViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, + public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) { super.onCreateViewHolder(viewGroup, viewType); - return new MediaDeviceViewHolder(mHolderView); + if (mController.isAdvancedLayoutSupported()) { + switch (viewType) { + case MediaItem.MediaItemType.TYPE_GROUP_DIVIDER: + return new MediaGroupDividerViewHolder(mHolderView); + case MediaItem.MediaItemType.TYPE_PAIR_NEW_DEVICE: + case MediaItem.MediaItemType.TYPE_DEVICE: + default: + return new MediaDeviceViewHolder(mHolderView); + } + } else { + return new MediaDeviceViewHolder(mHolderView); + } } @Override - public void onBindViewHolder(@NonNull MediaDeviceBaseViewHolder viewHolder, int position) { - final int size = mController.getMediaDevices().size(); - if (position == size) { - viewHolder.onBind(CUSTOMIZED_ITEM_PAIR_NEW, false /* topMargin */, - true /* bottomMargin */); - } else if (position < size) { - viewHolder.onBind(((List<MediaDevice>) (mController.getMediaDevices())).get(position), - position == 0 /* topMargin */, position == (size - 1) /* bottomMargin */, - position); - } else if (DEBUG) { - Log.d(TAG, "Incorrect position: " + position); + public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) { + if (mController.isAdvancedLayoutSupported()) { + MediaItem currentMediaItem = mController.getMediaItemList().get(position); + switch (currentMediaItem.getMediaItemType()) { + case MediaItem.MediaItemType.TYPE_GROUP_DIVIDER: + ((MediaGroupDividerViewHolder) viewHolder).onBind(currentMediaItem.getTitle()); + break; + case MediaItem.MediaItemType.TYPE_PAIR_NEW_DEVICE: + ((MediaDeviceViewHolder) viewHolder).onBind(CUSTOMIZED_ITEM_PAIR_NEW); + break; + case MediaItem.MediaItemType.TYPE_DEVICE: + ((MediaDeviceViewHolder) viewHolder).onBind( + currentMediaItem.getMediaDevice().get(), + position); + break; + default: + Log.d(TAG, "Incorrect position: " + position); + } + } else { + final int size = mController.getMediaDevices().size(); + if (position == size) { + ((MediaDeviceViewHolder) viewHolder).onBind(CUSTOMIZED_ITEM_PAIR_NEW); + } else if (position < size) { + ((MediaDeviceViewHolder) viewHolder).onBind( + ((List<MediaDevice>) (mController.getMediaDevices())).get(position), + position); + } else if (DEBUG) { + Log.d(TAG, "Incorrect position: " + position); + } } } @Override public long getItemId(int position) { + if (mController.isAdvancedLayoutSupported()) { + if (position >= mController.getMediaItemList().size()) { + Log.d(TAG, "Incorrect position for item id: " + position); + return position; + } + MediaItem currentMediaItem = mController.getMediaItemList().get(position); + return currentMediaItem.getMediaDevice().isPresent() + ? currentMediaItem.getMediaDevice().get().getId().hashCode() + : position; + } final int size = mController.getMediaDevices().size(); if (position == size) { return -1; @@ -85,9 +125,18 @@ public class MediaOutputAdapter extends MediaOutputBaseAdapter { } @Override + public int getItemViewType(int position) { + return mController.isAdvancedLayoutSupported() + ? mController.getMediaItemList().get(position).getMediaItemType() + : super.getItemViewType(position); + } + + @Override public int getItemCount() { // Add extra one for "pair new" - return mController.getMediaDevices().size() + 1; + return mController.isAdvancedLayoutSupported() + ? mController.getMediaItemList().size() + : mController.getMediaDevices().size() + 1; } class MediaDeviceViewHolder extends MediaDeviceBaseViewHolder { @@ -97,8 +146,8 @@ public class MediaOutputAdapter extends MediaOutputBaseAdapter { } @Override - void onBind(MediaDevice device, boolean topMargin, boolean bottomMargin, int position) { - super.onBind(device, topMargin, bottomMargin, position); + void onBind(MediaDevice device, int position) { + super.onBind(device, position); boolean isMutingExpectedDeviceExist = mController.hasMutingExpectedDevice(); final boolean currentlyConnected = isCurrentlyConnected(device); boolean isCurrentSeekbarInvisible = mSeekBar.getVisibility() == View.GONE; @@ -122,17 +171,19 @@ public class MediaOutputAdapter extends MediaOutputBaseAdapter { // Set different layout for each device if (device.isMutingExpectedDevice() && !mController.isCurrentConnectedDeviceRemote()) { - updateTitleIcon(R.drawable.media_output_icon_volume, - mController.getColorItemContent()); + if (!mController.isAdvancedLayoutSupported()) { + updateTitleIcon(R.drawable.media_output_icon_volume, + mController.getColorItemContent()); + } initMutingExpectedDevice(); mCurrentActivePosition = position; - updateContainerClickListener(v -> onItemClick(v, device)); + updateFullItemClickListener(v -> onItemClick(v, device)); setSingleLineLayout(getItemTitle(device)); } else if (device.getState() == MediaDeviceState.STATE_CONNECTING_FAILED) { setUpDeviceIcon(device); updateConnectionFailedStatusIcon(); mSubTitleText.setText(R.string.media_output_dialog_connect_failed); - updateContainerClickListener(v -> onItemClick(v, device)); + updateFullItemClickListener(v -> onItemClick(v, device)); setTwoLineLayout(device, false /* bFocused */, false /* showSeekBar */, false /* showProgressBar */, true /* showSubtitle */, true /* showStatus */); @@ -146,8 +197,10 @@ public class MediaOutputAdapter extends MediaOutputBaseAdapter { && isDeviceIncluded(mController.getSelectedMediaDevice(), device)) { boolean isDeviceDeselectable = isDeviceIncluded( mController.getDeselectableMediaDevice(), device); - updateTitleIcon(R.drawable.media_output_icon_volume, - mController.getColorItemContent()); + if (!mController.isAdvancedLayoutSupported()) { + updateTitleIcon(R.drawable.media_output_icon_volume, + mController.getColorItemContent()); + } updateGroupableCheckBox(true, isDeviceDeselectable, device); updateEndClickArea(device, isDeviceDeselectable); setUpContentDescriptionForView(mContainerLayout, false, device); @@ -161,8 +214,22 @@ public class MediaOutputAdapter extends MediaOutputBaseAdapter { && !mController.isCurrentConnectedDeviceRemote()) { // mark as disconnected and set special click listener setUpDeviceIcon(device); - updateContainerClickListener(v -> cancelMuteAwaitConnection()); + updateFullItemClickListener(v -> cancelMuteAwaitConnection()); setSingleLineLayout(getItemTitle(device)); + } else if (mController.isCurrentConnectedDeviceRemote() + && !mController.getSelectableMediaDevice().isEmpty() + && mController.isAdvancedLayoutSupported()) { + //If device is connected and there's other selectable devices, layout as + // one of selected devices. + boolean isDeviceDeselectable = isDeviceIncluded( + mController.getDeselectableMediaDevice(), device); + updateGroupableCheckBox(true, isDeviceDeselectable, device); + updateEndClickArea(device, isDeviceDeselectable); + setUpContentDescriptionForView(mContainerLayout, false, device); + setSingleLineLayout(getItemTitle(device), true /* showSeekBar */, + false /* showProgressBar */, true /* showCheckBox */, + true /* showEndTouchArea */); + initSeekbar(device, isCurrentSeekbarInvisible); } else { updateTitleIcon(R.drawable.media_output_icon_volume, mController.getColorItemContent()); @@ -176,14 +243,19 @@ public class MediaOutputAdapter extends MediaOutputBaseAdapter { } else if (isDeviceIncluded(mController.getSelectableMediaDevice(), device)) { setUpDeviceIcon(device); updateGroupableCheckBox(false, true, device); - updateContainerClickListener(v -> onGroupActionTriggered(true, device)); + if (mController.isAdvancedLayoutSupported()) { + updateEndClickArea(device, true); + } + updateFullItemClickListener(mController.isAdvancedLayoutSupported() + ? v -> onItemClick(v, device) + : v -> onGroupActionTriggered(true, device)); setSingleLineLayout(getItemTitle(device), false /* showSeekBar */, false /* showProgressBar */, true /* showCheckBox */, true /* showEndTouchArea */); } else { setUpDeviceIcon(device); setSingleLineLayout(getItemTitle(device)); - updateContainerClickListener(v -> onItemClick(v, device)); + updateFullItemClickListener(v -> onItemClick(v, device)); } } } @@ -214,6 +286,11 @@ public class MediaOutputAdapter extends MediaOutputBaseAdapter { isDeviceDeselectable ? (v) -> mCheckBox.performClick() : null); mEndTouchArea.setImportantForAccessibility( View.IMPORTANT_FOR_ACCESSIBILITY_YES); + if (mController.isAdvancedLayoutSupported()) { + mEndTouchArea.getBackground().setColorFilter( + new PorterDuffColorFilter(mController.getColorItemBackground(), + PorterDuff.Mode.SRC_IN)); + } setUpContentDescriptionForView(mEndTouchArea, true, device); } @@ -228,17 +305,13 @@ public class MediaOutputAdapter extends MediaOutputBaseAdapter { 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) { + private void updateFullItemClickListener(View.OnClickListener listener) { mContainerLayout.setOnClickListener(listener); + updateIconAreaClickListener(listener); } @Override - void onBind(int customizedItem, boolean topMargin, boolean bottomMargin) { + void onBind(int customizedItem) { if (customizedItem == CUSTOMIZED_ITEM_PAIR_NEW) { mTitleText.setTextColor(mController.getColorItemContent()); mCheckBox.setVisibility(View.GONE); @@ -246,6 +319,11 @@ public class MediaOutputAdapter extends MediaOutputBaseAdapter { final Drawable addDrawable = mContext.getDrawable(R.drawable.ic_add); mTitleIcon.setImageDrawable(addDrawable); mTitleIcon.setColorFilter(mController.getColorItemContent()); + if (mController.isAdvancedLayoutSupported()) { + mIconAreaLayout.getBackground().setColorFilter( + new PorterDuffColorFilter(mController.getColorItemBackground(), + PorterDuff.Mode.SRC_IN)); + } mContainerLayout.setOnClickListener(mController::launchBluetoothPairing); } } @@ -290,4 +368,18 @@ public class MediaOutputAdapter extends MediaOutputBaseAdapter { : R.string.accessibility_cast_name, device.getName())); } } + + class MediaGroupDividerViewHolder extends RecyclerView.ViewHolder { + final TextView mTitleText; + + MediaGroupDividerViewHolder(@NonNull View itemView) { + super(itemView); + mTitleText = itemView.requireViewById(R.id.title); + } + + void onBind(String groupDividerTitle) { + mTitleText.setTextColor(mController.getColorItemContent()); + mTitleText.setText(groupDividerTitle); + } + } } 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 3f7b2261ea52..3b1d861d0312 100644 --- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBaseAdapter.java +++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBaseAdapter.java @@ -16,8 +16,11 @@ package com.android.systemui.media.dialog; +import static com.android.systemui.media.dialog.MediaOutputSeekbar.VOLUME_PERCENTAGE_SCALE_SIZE; + import android.animation.Animator; import android.animation.ValueAnimator; +import android.annotation.DrawableRes; import android.app.WallpaperColors; import android.content.Context; import android.graphics.PorterDuff; @@ -55,7 +58,7 @@ import java.util.List; * Base adapter for media output dialog. */ public abstract class MediaOutputBaseAdapter extends - RecyclerView.Adapter<MediaOutputBaseAdapter.MediaDeviceBaseViewHolder> { + RecyclerView.Adapter<RecyclerView.ViewHolder> { static final int CUSTOMIZED_ITEM_PAIR_NEW = 1; static final int CUSTOMIZED_ITEM_GROUP = 2; @@ -77,11 +80,13 @@ public abstract class MediaOutputBaseAdapter extends } @Override - public MediaDeviceBaseViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, + public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) { mContext = viewGroup.getContext(); - mHolderView = LayoutInflater.from(mContext).inflate(R.layout.media_output_list_item, - viewGroup, false); + mHolderView = LayoutInflater.from(mContext).inflate( + mController.isAdvancedLayoutSupported() ? MediaItem.getMediaLayoutId( + viewType) /*R.layout.media_output_list_item_advanced*/ + : R.layout.media_output_list_item, viewGroup, false); return null; } @@ -129,18 +134,20 @@ public abstract class MediaOutputBaseAdapter extends private static final int ANIM_DURATION = 500; - final LinearLayout mContainerLayout; + final ViewGroup mContainerLayout; final FrameLayout mItemLayout; + final FrameLayout mIconAreaLayout; final TextView mTitleText; final TextView mTwoLineTitleText; final TextView mSubTitleText; + final TextView mVolumeValueText; final ImageView mTitleIcon; final ProgressBar mProgressBar; final MediaOutputSeekbar mSeekBar; final LinearLayout mTwoLineLayout; final ImageView mStatusIcon; final CheckBox mCheckBox; - final LinearLayout mEndTouchArea; + final ViewGroup mEndTouchArea; private String mDeviceId; private ValueAnimator mCornerAnimator; private ValueAnimator mVolumeAnimator; @@ -159,10 +166,17 @@ public abstract class MediaOutputBaseAdapter extends mStatusIcon = view.requireViewById(R.id.media_output_item_status); mCheckBox = view.requireViewById(R.id.check_box); mEndTouchArea = view.requireViewById(R.id.end_action_area); + if (mController.isAdvancedLayoutSupported()) { + mVolumeValueText = view.requireViewById(R.id.volume_value); + mIconAreaLayout = view.requireViewById(R.id.icon_area); + } else { + mVolumeValueText = null; + mIconAreaLayout = null; + } initAnimator(); } - void onBind(MediaDevice device, boolean topMargin, boolean bottomMargin, int position) { + void onBind(MediaDevice device, int position) { mDeviceId = device.getId(); mCheckBox.setVisibility(View.GONE); mStatusIcon.setVisibility(View.GONE); @@ -170,15 +184,20 @@ public abstract class MediaOutputBaseAdapter extends mEndTouchArea.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); mContainerLayout.setOnClickListener(null); mContainerLayout.setContentDescription(null); + mTitleIcon.setOnClickListener(null); mTitleText.setTextColor(mController.getColorItemContent()); mSubTitleText.setTextColor(mController.getColorItemContent()); mTwoLineTitleText.setTextColor(mController.getColorItemContent()); + if (mController.isAdvancedLayoutSupported()) { + mIconAreaLayout.setOnClickListener(null); + mVolumeValueText.setTextColor(mController.getColorItemContent()); + } mSeekBar.getProgressDrawable().setColorFilter( new PorterDuffColorFilter(mController.getColorSeekbarProgress(), PorterDuff.Mode.SRC_IN)); } - abstract void onBind(int customizedItem, boolean topMargin, boolean bottomMargin); + abstract void onBind(int customizedItem); void setSingleLineLayout(CharSequence title) { setSingleLineLayout(title, false, false, false, false); @@ -203,13 +222,28 @@ public abstract class MediaOutputBaseAdapter extends .findDrawableByLayerId(android.R.id.progress); final GradientDrawable progressDrawable = (GradientDrawable) clipDrawable.getDrawable(); - progressDrawable.setCornerRadius(mController.getActiveRadius()); + if (mController.isAdvancedLayoutSupported()) { + progressDrawable.setCornerRadii( + new float[]{0, 0, mController.getActiveRadius(), + mController.getActiveRadius(), + mController.getActiveRadius(), + mController.getActiveRadius(), 0, 0}); + } else { + progressDrawable.setCornerRadius(mController.getActiveRadius()); + } } } mItemLayout.getBackground().setColorFilter(new PorterDuffColorFilter( isActive ? mController.getColorConnectedItemBackground() : mController.getColorItemBackground(), PorterDuff.Mode.SRC_IN)); + if (mController.isAdvancedLayoutSupported()) { + mIconAreaLayout.getBackground().setColorFilter(new PorterDuffColorFilter( + showSeekBar ? mController.getColorSeekbarProgress() + : showProgressBar ? 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); @@ -220,6 +254,13 @@ public abstract class MediaOutputBaseAdapter extends mTitleText.setVisibility(View.VISIBLE); mCheckBox.setVisibility(showCheckBox ? View.VISIBLE : View.GONE); mEndTouchArea.setVisibility(showEndTouchArea ? View.VISIBLE : View.GONE); + if (mController.isAdvancedLayoutSupported()) { + ViewGroup.MarginLayoutParams params = + (ViewGroup.MarginLayoutParams) mItemLayout.getLayoutParams(); + params.rightMargin = showEndTouchArea ? mController.getItemMarginEndSelectable() + : mController.getItemMarginEndDefault(); + } + mTitleIcon.setColorFilter(mController.getColorItemContent()); } void setTwoLineLayout(MediaDevice device, boolean bFocused, boolean showSeekBar, @@ -263,42 +304,134 @@ public abstract class MediaOutputBaseAdapter extends final int currentVolume = device.getCurrentVolume(); if (mSeekBar.getVolume() != currentVolume) { if (isCurrentSeekbarInvisible && !mIsInitVolumeFirstTime) { + if (mController.isAdvancedLayoutSupported()) { + updateTitleIcon(currentVolume == 0 ? R.drawable.media_output_icon_volume_off + : R.drawable.media_output_icon_volume, + mController.getColorItemContent()); + } animateCornerAndVolume(mSeekBar.getProgress(), MediaOutputSeekbar.scaleVolumeToProgress(currentVolume)); } else { if (!mVolumeAnimator.isStarted()) { + if (mController.isAdvancedLayoutSupported()) { + int percentage = + (int) ((double) currentVolume * VOLUME_PERCENTAGE_SCALE_SIZE + / (double) mSeekBar.getMax()); + if (percentage == 0) { + updateMutedVolumeIcon(); + } else { + updateUnmutedVolumeIcon(); + } + } mSeekBar.setVolume(currentVolume); } } + } else if (mController.isAdvancedLayoutSupported() && currentVolume == 0) { + mSeekBar.resetVolume(); + updateMutedVolumeIcon(); } if (mIsInitVolumeFirstTime) { mIsInitVolumeFirstTime = false; } + if (mController.isAdvancedLayoutSupported()) { + updateIconAreaClickListener((v) -> { + mSeekBar.resetVolume(); + mController.adjustVolume(device, 0); + updateMutedVolumeIcon(); + }); + } mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (device == null || !fromUser) { return; } - int currentVolume = MediaOutputSeekbar.scaleProgressToVolume(progress); + int progressToVolume = MediaOutputSeekbar.scaleProgressToVolume(progress); int deviceVolume = device.getCurrentVolume(); - if (currentVolume != deviceVolume) { - mController.adjustVolume(device, currentVolume); + if (mController.isAdvancedLayoutSupported()) { + int percentage = + (int) ((double) progressToVolume * VOLUME_PERCENTAGE_SCALE_SIZE + / (double) seekBar.getMax()); + mVolumeValueText.setText(mContext.getResources().getString( + R.string.media_output_dialog_volume_percentage, percentage)); + mVolumeValueText.setVisibility(View.VISIBLE); + } + if (progressToVolume != deviceVolume) { + mController.adjustVolume(device, progressToVolume); + if (mController.isAdvancedLayoutSupported() && deviceVolume == 0) { + updateUnmutedVolumeIcon(); + } } } @Override public void onStartTrackingTouch(SeekBar seekBar) { + if (mController.isAdvancedLayoutSupported()) { + mTitleIcon.setVisibility(View.INVISIBLE); + mVolumeValueText.setVisibility(View.VISIBLE); + } mIsDragging = true; } @Override public void onStopTrackingTouch(SeekBar seekBar) { + if (mController.isAdvancedLayoutSupported()) { + int currentVolume = MediaOutputSeekbar.scaleProgressToVolume( + seekBar.getProgress()); + int percentage = + (int) ((double) currentVolume * VOLUME_PERCENTAGE_SCALE_SIZE + / (double) seekBar.getMax()); + if (percentage == 0) { + seekBar.setProgress(0); + updateMutedVolumeIcon(); + } else { + updateUnmutedVolumeIcon(); + } + mTitleIcon.setVisibility(View.VISIBLE); + mVolumeValueText.setVisibility(View.GONE); + } mIsDragging = false; } }); } + void updateMutedVolumeIcon() { + updateTitleIcon(R.drawable.media_output_icon_volume_off, + mController.getColorItemContent()); + final GradientDrawable iconAreaBackgroundDrawable = + (GradientDrawable) mIconAreaLayout.getBackground(); + iconAreaBackgroundDrawable.setCornerRadius(mController.getActiveRadius()); + } + + void updateUnmutedVolumeIcon() { + updateTitleIcon(R.drawable.media_output_icon_volume, + mController.getColorItemContent()); + final GradientDrawable iconAreaBackgroundDrawable = + (GradientDrawable) mIconAreaLayout.getBackground(); + iconAreaBackgroundDrawable.setCornerRadii(new float[]{ + mController.getActiveRadius(), + mController.getActiveRadius(), + 0, 0, 0, 0, mController.getActiveRadius(), mController.getActiveRadius() + }); + } + + void updateTitleIcon(@DrawableRes int id, int color) { + mTitleIcon.setImageDrawable(mContext.getDrawable(id)); + mTitleIcon.setColorFilter(color); + if (mController.isAdvancedLayoutSupported()) { + mIconAreaLayout.getBackground().setColorFilter( + new PorterDuffColorFilter(mController.getColorSeekbarProgress(), + PorterDuff.Mode.SRC_IN)); + } + } + + void updateIconAreaClickListener(View.OnClickListener listener) { + if (mController.isAdvancedLayoutSupported()) { + mIconAreaLayout.setOnClickListener(listener); + } + mTitleIcon.setOnClickListener(listener); + } + void initMutingExpectedDevice() { disableSeekBar(); final Drawable backgroundDrawable = mContext.getDrawable( @@ -316,11 +449,26 @@ public abstract class MediaOutputBaseAdapter extends final ClipDrawable clipDrawable = (ClipDrawable) ((LayerDrawable) mSeekBar.getProgressDrawable()) .findDrawableByLayerId(android.R.id.progress); - final GradientDrawable progressDrawable = (GradientDrawable) clipDrawable.getDrawable(); + final GradientDrawable targetBackgroundDrawable = + (GradientDrawable) (mController.isAdvancedLayoutSupported() + ? mIconAreaLayout.getBackground() + : clipDrawable.getDrawable()); mCornerAnimator.addUpdateListener(animation -> { float value = (float) animation.getAnimatedValue(); layoutBackgroundDrawable.setCornerRadius(value); - progressDrawable.setCornerRadius(value); + if (mController.isAdvancedLayoutSupported()) { + if (toProgress == 0) { + targetBackgroundDrawable.setCornerRadius(value); + } else { + targetBackgroundDrawable.setCornerRadii(new float[]{ + value, + value, + 0, 0, 0, 0, value, value + }); + } + } else { + targetBackgroundDrawable.setCornerRadius(value); + } }); mVolumeAnimator.setIntValues(fromProgress, toProgress); mVolumeAnimator.start(); @@ -391,6 +539,7 @@ public abstract class MediaOutputBaseAdapter extends return; } mTitleIcon.setImageIcon(icon); + mTitleIcon.setColorFilter(mController.getColorItemContent()); }); }); } diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBroadcastDialogFactory.kt b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBroadcastDialogFactory.kt index 2b5d6fd63995..cdd00f99fa29 100644 --- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBroadcastDialogFactory.kt +++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBroadcastDialogFactory.kt @@ -26,6 +26,7 @@ import com.android.internal.logging.UiEventLogger import com.android.settingslib.bluetooth.LocalBluetoothManager import com.android.systemui.animation.DialogLaunchAnimator import com.android.systemui.broadcast.BroadcastSender +import com.android.systemui.flags.FeatureFlags import com.android.systemui.media.nearby.NearbyMediaDevicesManager import com.android.systemui.plugins.ActivityStarter import com.android.systemui.statusbar.notification.collection.notifcollection.CommonNotifCollection @@ -47,7 +48,8 @@ class MediaOutputBroadcastDialogFactory @Inject constructor( private val nearbyMediaDevicesManagerOptional: Optional<NearbyMediaDevicesManager>, private val audioManager: AudioManager, private val powerExemptionManager: PowerExemptionManager, - private val keyGuardManager: KeyguardManager + private val keyGuardManager: KeyguardManager, + private val featureFlags: FeatureFlags ) { var mediaOutputBroadcastDialog: MediaOutputBroadcastDialog? = null @@ -59,7 +61,7 @@ class MediaOutputBroadcastDialogFactory @Inject constructor( val controller = MediaOutputController(context, packageName, mediaSessionManager, lbm, starter, notifCollection, dialogLaunchAnimator, nearbyMediaDevicesManagerOptional, audioManager, - powerExemptionManager, keyGuardManager) + powerExemptionManager, keyGuardManager, featureFlags) val dialog = MediaOutputBroadcastDialog(context, aboveStatusBar, broadcastSender, controller) mediaOutputBroadcastDialog = dialog 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 19b401d80600..b43656207821 100644 --- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputController.java +++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputController.java @@ -73,6 +73,8 @@ import com.android.systemui.R; import com.android.systemui.animation.ActivityLaunchAnimator; import com.android.systemui.animation.DialogLaunchAnimator; import com.android.systemui.broadcast.BroadcastSender; +import com.android.systemui.flags.FeatureFlags; +import com.android.systemui.flags.Flags; import com.android.systemui.media.nearby.NearbyMediaDevicesManager; import com.android.systemui.monet.ColorScheme; import com.android.systemui.plugins.ActivityStarter; @@ -91,6 +93,7 @@ import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executor; +import java.util.stream.Collectors; import javax.inject.Inject; @@ -119,6 +122,7 @@ public class MediaOutputController implements LocalMediaManager.DeviceCallback, @VisibleForTesting final List<MediaDevice> mMediaDevices = new CopyOnWriteArrayList<>(); final List<MediaDevice> mCachedMediaDevices = new CopyOnWriteArrayList<>(); + private final List<MediaItem> mMediaItemList = new CopyOnWriteArrayList<>(); private final AudioManager mAudioManager; private final PowerExemptionManager mPowerExemptionManager; private final KeyguardManager mKeyGuardManager; @@ -145,8 +149,11 @@ public class MediaOutputController implements LocalMediaManager.DeviceCallback, private int mColorConnectedItemBackground; private int mColorPositiveButtonText; private int mColorDialogBackground; + private int mItemMarginEndDefault; + private int mItemMarginEndSelectable; private float mInactiveRadius; private float mActiveRadius; + private FeatureFlags mFeatureFlags; public enum BroadcastNotifyDialog { ACTION_FIRST_LAUNCH, @@ -162,7 +169,8 @@ public class MediaOutputController implements LocalMediaManager.DeviceCallback, Optional<NearbyMediaDevicesManager> nearbyMediaDevicesManagerOptional, AudioManager audioManager, PowerExemptionManager powerExemptionManager, - KeyguardManager keyGuardManager) { + KeyguardManager keyGuardManager, + FeatureFlags featureFlags) { mContext = context; mPackageName = packageName; mMediaSessionManager = mediaSessionManager; @@ -172,6 +180,7 @@ public class MediaOutputController implements LocalMediaManager.DeviceCallback, mAudioManager = audioManager; mPowerExemptionManager = powerExemptionManager; mKeyGuardManager = keyGuardManager; + mFeatureFlags = featureFlags; InfoMediaManager imm = new InfoMediaManager(mContext, packageName, null, lbm); mLocalMediaManager = new LocalMediaManager(mContext, lbm, imm, packageName); mMetricLogger = new MediaOutputMetricLogger(mContext, mPackageName); @@ -195,12 +204,17 @@ public class MediaOutputController implements LocalMediaManager.DeviceCallback, R.dimen.media_output_dialog_active_background_radius); mColorDialogBackground = Utils.getColorStateListDefaultColor(mContext, R.color.media_dialog_background); + mItemMarginEndDefault = (int) mContext.getResources().getDimension( + R.dimen.media_output_dialog_default_margin_end); + mItemMarginEndSelectable = (int) mContext.getResources().getDimension( + R.dimen.media_output_dialog_selectable_margin_end); } void start(@NonNull Callback cb) { synchronized (mMediaDevicesLock) { mCachedMediaDevices.clear(); mMediaDevices.clear(); + mMediaItemList.clear(); } mNearbyDeviceInfoMap.clear(); if (mNearbyMediaDevicesManager != null) { @@ -251,6 +265,7 @@ public class MediaOutputController implements LocalMediaManager.DeviceCallback, synchronized (mMediaDevicesLock) { mCachedMediaDevices.clear(); mMediaDevices.clear(); + mMediaItemList.clear(); } if (mNearbyMediaDevicesManager != null) { mNearbyMediaDevicesManager.unregisterNearbyDevicesCallback(this); @@ -276,7 +291,11 @@ public class MediaOutputController implements LocalMediaManager.DeviceCallback, public void onSelectedDeviceStateChanged(MediaDevice device, @LocalMediaManager.MediaDeviceState int state) { mCallback.onRouteChanged(); - mMetricLogger.logOutputSuccess(device.toString(), new ArrayList<>(mMediaDevices)); + if (isAdvancedLayoutSupported()) { + mMetricLogger.logOutputItemSuccess(device.toString(), new ArrayList<>(mMediaItemList)); + } else { + mMetricLogger.logOutputSuccess(device.toString(), new ArrayList<>(mMediaDevices)); + } } @Override @@ -287,7 +306,11 @@ public class MediaOutputController implements LocalMediaManager.DeviceCallback, @Override public void onRequestFailed(int reason) { mCallback.onRouteChanged(); - mMetricLogger.logOutputFailure(new ArrayList<>(mMediaDevices), reason); + if (isAdvancedLayoutSupported()) { + mMetricLogger.logOutputItemFailure(new ArrayList<>(mMediaItemList), reason); + } else { + mMetricLogger.logOutputFailure(new ArrayList<>(mMediaDevices), reason); + } } /** @@ -307,6 +330,7 @@ public class MediaOutputController implements LocalMediaManager.DeviceCallback, try { synchronized (mMediaDevicesLock) { mMediaDevices.removeIf(MediaDevice::isMutingExpectedDevice); + mMediaItemList.removeIf((MediaItem::isMutingExpectedDevice)); } mAudioManager.cancelMuteAwaitConnection(mAudioManager.getMutingExpectedDevice()); } catch (Exception e) { @@ -527,7 +551,23 @@ public class MediaOutputController implements LocalMediaManager.DeviceCallback, return mActiveRadius; } + public int getItemMarginEndDefault() { + return mItemMarginEndDefault; + } + + public int getItemMarginEndSelectable() { + return mItemMarginEndSelectable; + } + private void buildMediaDevices(List<MediaDevice> devices) { + if (isAdvancedLayoutSupported()) { + buildMediaItems(devices); + } else { + buildDefaultMediaDevices(devices); + } + } + + private void buildDefaultMediaDevices(List<MediaDevice> devices) { synchronized (mMediaDevicesLock) { attachRangeInfo(devices); Collections.sort(devices, Comparator.naturalOrder()); @@ -584,6 +624,81 @@ public class MediaOutputController implements LocalMediaManager.DeviceCallback, } } + private void buildMediaItems(List<MediaDevice> devices) { + synchronized (mMediaDevicesLock) { + //TODO(b/257851968): do the organization only when there's no suggested sorted order + // we get from application + attachRangeInfo(devices); + Collections.sort(devices, Comparator.naturalOrder()); + // For the first time building list, to make sure the top device is the connected + // device. + if (mMediaItemList.isEmpty()) { + boolean needToHandleMutingExpectedDevice = + hasMutingExpectedDevice() && !isCurrentConnectedDeviceRemote(); + final MediaDevice connectedMediaDevice = + needToHandleMutingExpectedDevice ? null + : getCurrentConnectedMediaDevice(); + if (connectedMediaDevice == null) { + if (DEBUG) { + Log.d(TAG, "No connected media device or muting expected device exist."); + } + if (needToHandleMutingExpectedDevice) { + for (MediaDevice device : devices) { + if (device.isMutingExpectedDevice()) { + mMediaItemList.add(0, new MediaItem(device)); + } else { + mMediaItemList.add(new MediaItem(device)); + } + } + } else { + mMediaItemList.addAll( + devices.stream().map(MediaItem::new).collect(Collectors.toList())); + } + + categorizeMediaItems(); + return; + } + // selected device exist + for (MediaDevice device : devices) { + if (TextUtils.equals(device.getId(), connectedMediaDevice.getId())) { + mMediaItemList.add(0, new MediaItem(device)); + } else { + mMediaItemList.add(new MediaItem(device)); + } + } + categorizeMediaItems(); + return; + } + // To keep the same list order + final List<MediaDevice> targetMediaDevices = new ArrayList<>(); + for (MediaItem originalMediaItem : mMediaItemList) { + for (MediaDevice newDevice : devices) { + if (originalMediaItem.getMediaDevice().isPresent() + && TextUtils.equals(originalMediaItem.getMediaDevice().get().getId(), + newDevice.getId())) { + targetMediaDevices.add(newDevice); + break; + } + } + } + if (targetMediaDevices.size() != devices.size()) { + devices.removeAll(targetMediaDevices); + targetMediaDevices.addAll(devices); + } + mMediaItemList.clear(); + mMediaItemList.addAll( + targetMediaDevices.stream().map(MediaItem::new).collect(Collectors.toList())); + categorizeMediaItems(); + } + } + + private void categorizeMediaItems() { + synchronized (mMediaDevicesLock) { + //TODO(255124239): do the categorization here + mMediaItemList.add(new MediaItem()); + } + } + private void attachRangeInfo(List<MediaDevice> devices) { for (MediaDevice mediaDevice : devices) { if (mNearbyDeviceInfoMap.containsKey(mediaDevice.getId())) { @@ -599,6 +714,10 @@ public class MediaOutputController implements LocalMediaManager.DeviceCallback, currentConnectedMediaDevice); } + public boolean isAdvancedLayoutSupported() { + return mFeatureFlags.isEnabled(Flags.OUTPUT_SWITCHER_ADVANCED_LAYOUT); + } + List<MediaDevice> getGroupMediaDevices() { final List<MediaDevice> selectedDevices = getSelectedMediaDevice(); final List<MediaDevice> selectableDevices = getSelectableMediaDevice(); @@ -647,6 +766,10 @@ public class MediaOutputController implements LocalMediaManager.DeviceCallback, return mMediaDevices; } + public List<MediaItem> getMediaItemList() { + return mMediaItemList; + } + MediaDevice getCurrentConnectedMediaDevice() { return mLocalMediaManager.getCurrentConnectedDevice(); } @@ -726,9 +849,19 @@ public class MediaOutputController implements LocalMediaManager.DeviceCallback, boolean isAnyDeviceTransferring() { synchronized (mMediaDevicesLock) { - for (MediaDevice device : mMediaDevices) { - if (device.getState() == LocalMediaManager.MediaDeviceState.STATE_CONNECTING) { - return true; + if (isAdvancedLayoutSupported()) { + for (MediaItem mediaItem : mMediaItemList) { + if (mediaItem.getMediaDevice().isPresent() + && mediaItem.getMediaDevice().get().getState() + == LocalMediaManager.MediaDeviceState.STATE_CONNECTING) { + return true; + } + } + } else { + for (MediaDevice device : mMediaDevices) { + if (device.getState() == LocalMediaManager.MediaDeviceState.STATE_CONNECTING) { + return true; + } } } } @@ -792,7 +925,7 @@ public class MediaOutputController implements LocalMediaManager.DeviceCallback, MediaOutputController controller = new MediaOutputController(mContext, mPackageName, mMediaSessionManager, mLocalBluetoothManager, mActivityStarter, mNotifCollection, mDialogLaunchAnimator, Optional.of(mNearbyMediaDevicesManager), - mAudioManager, mPowerExemptionManager, mKeyGuardManager); + mAudioManager, mPowerExemptionManager, mKeyGuardManager, mFeatureFlags); MediaOutputBroadcastDialog dialog = new MediaOutputBroadcastDialog(mContext, true, broadcastSender, controller); mDialogLaunchAnimator.showFromView(dialog, mediaOutputDialog); diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputDialogFactory.kt b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputDialogFactory.kt index 543efed8378e..7dbf876bb377 100644 --- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputDialogFactory.kt +++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputDialogFactory.kt @@ -31,6 +31,7 @@ import com.android.systemui.broadcast.BroadcastSender import com.android.systemui.media.nearby.NearbyMediaDevicesManager import com.android.systemui.plugins.ActivityStarter import com.android.systemui.statusbar.notification.collection.notifcollection.CommonNotifCollection +import com.android.systemui.flags.FeatureFlags import java.util.Optional import javax.inject.Inject @@ -49,7 +50,8 @@ class MediaOutputDialogFactory @Inject constructor( private val nearbyMediaDevicesManagerOptional: Optional<NearbyMediaDevicesManager>, private val audioManager: AudioManager, private val powerExemptionManager: PowerExemptionManager, - private val keyGuardManager: KeyguardManager + private val keyGuardManager: KeyguardManager, + private val featureFlags: FeatureFlags ) { companion object { private const val INTERACTION_JANK_TAG = "media_output" @@ -65,7 +67,7 @@ class MediaOutputDialogFactory @Inject constructor( context, packageName, mediaSessionManager, lbm, starter, notifCollection, dialogLaunchAnimator, nearbyMediaDevicesManagerOptional, audioManager, - powerExemptionManager, keyGuardManager) + powerExemptionManager, keyGuardManager, featureFlags) val dialog = MediaOutputDialog(context, aboveStatusBar, broadcastSender, controller, uiEventLogger) mediaOutputDialog = dialog diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputMetricLogger.java b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputMetricLogger.java index 7d3e82c9d47f..2250d72d8658 100644 --- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputMetricLogger.java +++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputMetricLogger.java @@ -96,6 +96,31 @@ public class MediaOutputMetricLogger { } /** + * Do the metric logging of content switching success. + * @param selectedDeviceType string representation of the target media device + * @param deviceItemList media item list for device count updating + */ + public void logOutputItemSuccess(String selectedDeviceType, List<MediaItem> deviceItemList) { + if (DEBUG) { + Log.d(TAG, "logOutputSuccess - selected device: " + selectedDeviceType); + } + + updateLoggingMediaItemCount(deviceItemList); + + SysUiStatsLog.write( + SysUiStatsLog.MEDIAOUTPUT_OP_SWITCH_REPORTED, + getLoggingDeviceType(mSourceDevice, true), + getLoggingDeviceType(mTargetDevice, false), + SysUiStatsLog.MEDIA_OUTPUT_OP_SWITCH_REPORTED__RESULT__OK, + SysUiStatsLog.MEDIA_OUTPUT_OP_SWITCH_REPORTED__SUBRESULT__NO_ERROR, + getLoggingPackageName(), + mWiredDeviceCount, + mConnectedBluetoothDeviceCount, + mRemoteDeviceCount, + mAppliedDeviceCountWithinRemoteGroup); + } + + /** * Do the metric logging of volume adjustment. * @param source the device been adjusted */ @@ -166,6 +191,31 @@ public class MediaOutputMetricLogger { mAppliedDeviceCountWithinRemoteGroup); } + /** + * Do the metric logging of content switching failure. + * @param deviceItemList media item list for device count updating + * @param reason the reason of content switching failure + */ + public void logOutputItemFailure(List<MediaItem> deviceItemList, int reason) { + if (DEBUG) { + Log.e(TAG, "logRequestFailed - " + reason); + } + + updateLoggingMediaItemCount(deviceItemList); + + SysUiStatsLog.write( + SysUiStatsLog.MEDIAOUTPUT_OP_SWITCH_REPORTED, + getLoggingDeviceType(mSourceDevice, true), + getLoggingDeviceType(mTargetDevice, false), + SysUiStatsLog.MEDIA_OUTPUT_OP_SWITCH_REPORTED__RESULT__ERROR, + getLoggingSwitchOpSubResult(reason), + getLoggingPackageName(), + mWiredDeviceCount, + mConnectedBluetoothDeviceCount, + mRemoteDeviceCount, + mAppliedDeviceCountWithinRemoteGroup); + } + private void updateLoggingDeviceCount(List<MediaDevice> deviceList) { mWiredDeviceCount = mConnectedBluetoothDeviceCount = mRemoteDeviceCount = 0; mAppliedDeviceCountWithinRemoteGroup = 0; @@ -196,6 +246,37 @@ public class MediaOutputMetricLogger { } } + private void updateLoggingMediaItemCount(List<MediaItem> deviceItemList) { + mWiredDeviceCount = mConnectedBluetoothDeviceCount = mRemoteDeviceCount = 0; + mAppliedDeviceCountWithinRemoteGroup = 0; + + for (MediaItem mediaItem: deviceItemList) { + if (mediaItem.getMediaDevice().isPresent() + && mediaItem.getMediaDevice().get().isConnected()) { + switch (mediaItem.getMediaDevice().get().getDeviceType()) { + case MediaDevice.MediaDeviceType.TYPE_3POINT5_MM_AUDIO_DEVICE: + case MediaDevice.MediaDeviceType.TYPE_USB_C_AUDIO_DEVICE: + mWiredDeviceCount++; + break; + case MediaDevice.MediaDeviceType.TYPE_BLUETOOTH_DEVICE: + mConnectedBluetoothDeviceCount++; + break; + case MediaDevice.MediaDeviceType.TYPE_CAST_DEVICE: + case MediaDevice.MediaDeviceType.TYPE_CAST_GROUP_DEVICE: + mRemoteDeviceCount++; + break; + default: + } + } + } + + if (DEBUG) { + Log.d(TAG, "connected devices:" + " wired: " + mWiredDeviceCount + + " bluetooth: " + mConnectedBluetoothDeviceCount + + " remote: " + mRemoteDeviceCount); + } + } + private int getLoggingDeviceType(MediaDevice device, boolean isSourceDevice) { if (device == null) { return isSourceDevice diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputSeekbar.java b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputSeekbar.java index 4ff79d689037..253c3c713485 100644 --- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputSeekbar.java +++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputSeekbar.java @@ -26,6 +26,7 @@ import android.widget.SeekBar; */ public class MediaOutputSeekbar extends SeekBar { private static final int SCALE_SIZE = 1000; + public static final int VOLUME_PERCENTAGE_SCALE_SIZE = 100000; public MediaOutputSeekbar(Context context, AttributeSet attrs) { super(context, attrs); diff --git a/packages/SystemUI/src/com/android/systemui/media/taptotransfer/common/MediaTttUtils.kt b/packages/SystemUI/src/com/android/systemui/media/taptotransfer/common/MediaTttUtils.kt index 769494a58842..009595a6da8b 100644 --- a/packages/SystemUI/src/com/android/systemui/media/taptotransfer/common/MediaTttUtils.kt +++ b/packages/SystemUI/src/com/android/systemui/media/taptotransfer/common/MediaTttUtils.kt @@ -19,10 +19,12 @@ package com.android.systemui.media.taptotransfer.common import android.content.Context import android.content.pm.PackageManager import android.graphics.drawable.Drawable -import com.android.settingslib.Utils +import androidx.annotation.AttrRes +import androidx.annotation.DrawableRes import com.android.systemui.R import com.android.systemui.common.shared.model.ContentDescription import com.android.systemui.common.shared.model.Icon +import com.android.systemui.common.shared.model.TintedIcon /** Utility methods for media tap-to-transfer. */ class MediaTttUtils { @@ -34,23 +36,6 @@ class MediaTttUtils { const val WAKE_REASON_RECEIVER = "MEDIA_TRANSFER_ACTIVATED_RECEIVER" /** - * Returns the information needed to display the icon in [Icon] form. - * - * See [getIconInfoFromPackageName]. - */ - fun getIconFromPackageName( - context: Context, - appPackageName: String?, - logger: MediaTttLogger, - ): Icon { - val iconInfo = getIconInfoFromPackageName(context, appPackageName, logger) - return Icon.Loaded( - iconInfo.drawable, - ContentDescription.Loaded(iconInfo.contentDescription) - ) - } - - /** * Returns the information needed to display the icon. * * The information will either contain app name and icon of the app playing media, or a @@ -65,18 +50,22 @@ class MediaTttUtils { logger: MediaTttLogger ): IconInfo { if (appPackageName != null) { + val packageManager = context.packageManager try { val contentDescription = - context.packageManager - .getApplicationInfo( - appPackageName, - PackageManager.ApplicationInfoFlags.of(0) - ) - .loadLabel(context.packageManager) - .toString() + ContentDescription.Loaded( + packageManager + .getApplicationInfo( + appPackageName, + PackageManager.ApplicationInfoFlags.of(0) + ) + .loadLabel(packageManager) + .toString() + ) return IconInfo( contentDescription, - drawable = context.packageManager.getApplicationIcon(appPackageName), + MediaTttIcon.Loaded(packageManager.getApplicationIcon(appPackageName)), + tintAttr = null, isAppIcon = true ) } catch (e: PackageManager.NameNotFoundException) { @@ -84,25 +73,41 @@ class MediaTttUtils { } } return IconInfo( - contentDescription = - context.getString(R.string.media_output_dialog_unknown_launch_app_name), - drawable = - context.resources.getDrawable(R.drawable.ic_cast).apply { - this.setTint( - Utils.getColorAttrDefaultColor(context, android.R.attr.textColorPrimary) - ) - }, + ContentDescription.Resource(R.string.media_output_dialog_unknown_launch_app_name), + MediaTttIcon.Resource(R.drawable.ic_cast), + tintAttr = android.R.attr.textColorPrimary, isAppIcon = false ) } } } +/** Stores all the information for an icon shown with media TTT. */ data class IconInfo( - val contentDescription: String, - val drawable: Drawable, + val contentDescription: ContentDescription, + val icon: MediaTttIcon, + @AttrRes val tintAttr: Int?, /** * True if [drawable] is the app's icon, and false if [drawable] is some generic default icon. */ val isAppIcon: Boolean -) +) { + /** Converts this into a [TintedIcon]. */ + fun toTintedIcon(): TintedIcon { + val iconOutput = + when (icon) { + is MediaTttIcon.Loaded -> Icon.Loaded(icon.drawable, contentDescription) + is MediaTttIcon.Resource -> Icon.Resource(icon.res, contentDescription) + } + return TintedIcon(iconOutput, tintAttr) + } +} + +/** + * Mimics [com.android.systemui.common.shared.model.Icon] but without the content description, since + * the content description may need to be overridden. + */ +sealed interface MediaTttIcon { + data class Loaded(val drawable: Drawable) : MediaTttIcon + data class Resource(@DrawableRes val res: Int) : MediaTttIcon +} 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 cc5e256c0956..1c3a53cbf815 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 @@ -33,9 +33,12 @@ import android.view.accessibility.AccessibilityManager import com.android.internal.widget.CachingIconView import com.android.settingslib.Utils import com.android.systemui.R +import com.android.systemui.common.shared.model.ContentDescription +import com.android.systemui.common.ui.binder.TintedIconViewBinder import com.android.systemui.dagger.SysUISingleton import com.android.systemui.dagger.qualifiers.Main import com.android.systemui.media.taptotransfer.MediaTttFlags +import com.android.systemui.media.taptotransfer.common.MediaTttIcon import com.android.systemui.media.taptotransfer.common.MediaTttLogger import com.android.systemui.media.taptotransfer.common.MediaTttUtils import com.android.systemui.statusbar.CommandQueue @@ -161,11 +164,23 @@ open class MediaTttChipControllerReceiver @Inject constructor( } override fun updateView(newInfo: ChipReceiverInfo, currentView: ViewGroup) { - val iconInfo = MediaTttUtils.getIconInfoFromPackageName( + var iconInfo = MediaTttUtils.getIconInfoFromPackageName( context, newInfo.routeInfo.clientPackageName, logger ) - val iconDrawable = newInfo.appIconDrawableOverride ?: iconInfo.drawable - val iconContentDescription = newInfo.appNameOverride ?: iconInfo.contentDescription + + if (newInfo.appNameOverride != null) { + iconInfo = iconInfo.copy( + contentDescription = ContentDescription.Loaded(newInfo.appNameOverride.toString()) + ) + } + + if (newInfo.appIconDrawableOverride != null) { + iconInfo = iconInfo.copy( + icon = MediaTttIcon.Loaded(newInfo.appIconDrawableOverride), + isAppIcon = true, + ) + } + val iconPadding = if (iconInfo.isAppIcon) { 0 @@ -175,8 +190,7 @@ open class MediaTttChipControllerReceiver @Inject constructor( val iconView = currentView.getAppIconView() iconView.setPadding(iconPadding, iconPadding, iconPadding, iconPadding) - iconView.setImageDrawable(iconDrawable) - iconView.contentDescription = iconContentDescription + TintedIconViewBinder.bind(iconInfo.toTintedIcon(), iconView) } override fun animateViewIn(view: ViewGroup) { diff --git a/packages/SystemUI/src/com/android/systemui/media/taptotransfer/sender/MediaTttSenderCoordinator.kt b/packages/SystemUI/src/com/android/systemui/media/taptotransfer/sender/MediaTttSenderCoordinator.kt index e34b0cbdbdc3..ec1984d78cf9 100644 --- a/packages/SystemUI/src/com/android/systemui/media/taptotransfer/sender/MediaTttSenderCoordinator.kt +++ b/packages/SystemUI/src/com/android/systemui/media/taptotransfer/sender/MediaTttSenderCoordinator.kt @@ -153,7 +153,9 @@ constructor( return ChipbarInfo( // Display the app's icon as the start icon - startIcon = MediaTttUtils.getIconFromPackageName(context, packageName, logger), + startIcon = + MediaTttUtils.getIconInfoFromPackageName(context, packageName, logger) + .toTintedIcon(), text = chipStateSender.getChipTextString(context, otherDeviceName), endItem = when (chipStateSender.endItem) { diff --git a/packages/SystemUI/src/com/android/systemui/navigationbar/NavigationBarController.java b/packages/SystemUI/src/com/android/systemui/navigationbar/NavigationBarController.java index e2f55f0d81b8..9791e82e5a3f 100644 --- a/packages/SystemUI/src/com/android/systemui/navigationbar/NavigationBarController.java +++ b/packages/SystemUI/src/com/android/systemui/navigationbar/NavigationBarController.java @@ -98,7 +98,7 @@ public class NavigationBarController implements // Tracks config changes that will actually recreate the nav bar private final InterestingConfigChanges mConfigChanges = new InterestingConfigChanges( - ActivityInfo.CONFIG_FONT_SCALE | ActivityInfo.CONFIG_SCREEN_LAYOUT + ActivityInfo.CONFIG_FONT_SCALE | ActivityInfo.CONFIG_UI_MODE); @Inject diff --git a/packages/SystemUI/src/com/android/systemui/navigationbar/TaskbarDelegate.java b/packages/SystemUI/src/com/android/systemui/navigationbar/TaskbarDelegate.java index ac7c70bd1d9e..f60d7ea8d664 100644 --- a/packages/SystemUI/src/com/android/systemui/navigationbar/TaskbarDelegate.java +++ b/packages/SystemUI/src/com/android/systemui/navigationbar/TaskbarDelegate.java @@ -55,6 +55,7 @@ import android.view.WindowInsetsController.Appearance; import android.view.WindowInsetsController.Behavior; import androidx.annotation.NonNull; +import androidx.annotation.VisibleForTesting; import com.android.internal.statusbar.LetterboxDetails; import com.android.internal.view.AppearanceRegion; @@ -125,7 +126,7 @@ public class TaskbarDelegate implements CommandQueue.Callbacks, private final DisplayManager mDisplayManager; private Context mWindowContext; private ScreenPinningNotify mScreenPinningNotify; - private int mNavigationMode; + private int mNavigationMode = -1; private final Consumer<Rect> mPipListener; /** @@ -217,8 +218,7 @@ public class TaskbarDelegate implements CommandQueue.Callbacks, parseCurrentSysuiState(); mCommandQueue.addCallback(this); mOverviewProxyService.addCallback(this); - mEdgeBackGestureHandler.onNavigationModeChanged( - mNavigationModeController.addListener(this)); + onNavigationModeChanged(mNavigationModeController.addListener(this)); mNavBarHelper.registerNavTaskStateUpdater(mNavbarTaskbarStateUpdater); mNavBarHelper.init(); mEdgeBackGestureHandler.onNavBarAttached(); @@ -492,6 +492,11 @@ public class TaskbarDelegate implements CommandQueue.Callbacks, !QuickStepContract.isGesturalMode(mNavigationMode)); } + @VisibleForTesting + int getNavigationMode() { + return mNavigationMode; + } + @Override public void dump(@NonNull PrintWriter pw, @NonNull String[] args) { pw.println("TaskbarDelegate (displayId=" + mDisplayId + "):"); diff --git a/packages/SystemUI/src/com/android/systemui/qs/FgsManagerController.kt b/packages/SystemUI/src/com/android/systemui/qs/FgsManagerController.kt index 3c1077867582..930de1302c58 100644 --- a/packages/SystemUI/src/com/android/systemui/qs/FgsManagerController.kt +++ b/packages/SystemUI/src/com/android/systemui/qs/FgsManagerController.kt @@ -122,10 +122,6 @@ interface FgsManagerController { /** Remove a [OnDialogDismissedListener]. */ fun removeOnDialogDismissedListener(listener: OnDialogDismissedListener) - /** Whether we should update the footer visibility. */ - // TODO(b/242040009): Remove this. - fun shouldUpdateFooterVisibility(): Boolean - @VisibleForTesting fun visibleButtonsCount(): Int @@ -375,8 +371,6 @@ class FgsManagerControllerImpl @Inject constructor( } } - override fun shouldUpdateFooterVisibility() = dialog == null - override fun showDialog(expandable: Expandable?) { synchronized(lock) { if (dialog == null) { diff --git a/packages/SystemUI/src/com/android/systemui/qs/FooterActionsController.kt b/packages/SystemUI/src/com/android/systemui/qs/FooterActionsController.kt index a9943e886339..b52233fc748b 100644 --- a/packages/SystemUI/src/com/android/systemui/qs/FooterActionsController.kt +++ b/packages/SystemUI/src/com/android/systemui/qs/FooterActionsController.kt @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 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,261 +16,17 @@ package com.android.systemui.qs -import android.content.Intent -import android.content.res.Configuration -import android.os.Handler -import android.os.UserManager -import android.provider.Settings -import android.provider.Settings.Global.USER_SWITCHER_ENABLED -import android.view.View -import android.view.ViewGroup -import androidx.annotation.VisibleForTesting -import com.android.internal.jank.InteractionJankMonitor -import com.android.internal.logging.MetricsLogger -import com.android.internal.logging.UiEventLogger -import com.android.internal.logging.nano.MetricsProto -import com.android.keyguard.KeyguardUpdateMonitor -import com.android.systemui.R -import com.android.systemui.animation.ActivityLaunchAnimator -import com.android.systemui.animation.Expandable -import com.android.systemui.globalactions.GlobalActionsDialogLite -import com.android.systemui.plugins.ActivityStarter -import com.android.systemui.plugins.FalsingManager -import com.android.systemui.qs.dagger.QSFlagsModule.PM_LITE_ENABLED -import com.android.systemui.qs.dagger.QSScope -import com.android.systemui.settings.UserTracker -import com.android.systemui.statusbar.phone.MultiUserSwitchController -import com.android.systemui.statusbar.policy.ConfigurationController -import com.android.systemui.statusbar.policy.DeviceProvisionedController -import com.android.systemui.statusbar.policy.UserInfoController -import com.android.systemui.statusbar.policy.UserInfoController.OnUserInfoChangedListener -import com.android.systemui.util.LargeScreenUtils -import com.android.systemui.util.ViewController -import com.android.systemui.util.settings.GlobalSettings +import com.android.systemui.dagger.SysUISingleton import javax.inject.Inject -import javax.inject.Named -import javax.inject.Provider -/** - * Manages [FooterActionsView] behaviour, both when it's placed in QS or QQS (split shade). - * Main difference between QS and QQS behaviour is condition when buttons should be visible, - * determined by [buttonsVisibleState] - */ -@QSScope -// TODO(b/242040009): Remove this file. -internal class FooterActionsController @Inject constructor( - view: FooterActionsView, - multiUserSwitchControllerFactory: MultiUserSwitchController.Factory, - private val activityStarter: ActivityStarter, - private val userManager: UserManager, - private val userTracker: UserTracker, - private val userInfoController: UserInfoController, - private val deviceProvisionedController: DeviceProvisionedController, - private val securityFooterController: QSSecurityFooter, - private val fgsManagerFooterController: QSFgsManagerFooter, - private val falsingManager: FalsingManager, - private val metricsLogger: MetricsLogger, - private val globalActionsDialogProvider: Provider<GlobalActionsDialogLite>, - private val uiEventLogger: UiEventLogger, - @Named(PM_LITE_ENABLED) private val showPMLiteButton: Boolean, - private val globalSetting: GlobalSettings, - private val handler: Handler, - private val configurationController: ConfigurationController, -) : ViewController<FooterActionsView>(view) { - - private var globalActionsDialog: GlobalActionsDialogLite? = null - - private var lastExpansion = -1f - private var listening: Boolean = false - private var inSplitShade = false - - private val singleShadeAnimator by lazy { - // In single shade, the actions footer should only appear at the end of the expansion, - // so that it doesn't overlap with the notifications panel. - TouchAnimator.Builder().addFloat(mView, "alpha", 0f, 1f).setStartDelay(0.9f).build() - } - - private val splitShadeAnimator by lazy { - // The Actions footer view has its own background which is the same color as the qs panel's - // background. - // We don't want it to fade in at the same time as the rest of the panel, otherwise it is - // more opaque than the rest of the panel's background. Only applies to split shade. - val alphaAnimator = TouchAnimator.Builder().addFloat(mView, "alpha", 0f, 1f).build() - val bgAlphaAnimator = - TouchAnimator.Builder() - .addFloat(mView, "backgroundAlpha", 0f, 1f) - .setStartDelay(0.9f) - .build() - // In split shade, we want the actions footer to fade in exactly at the same time as the - // rest of the shade, as there is no overlap. - TouchAnimator.Builder() - .addFloat(alphaAnimator, "position", 0f, 1f) - .addFloat(bgAlphaAnimator, "position", 0f, 1f) - .build() - } - - private val animators: TouchAnimator - get() = if (inSplitShade) splitShadeAnimator else singleShadeAnimator - - var visible = true - set(value) { - field = value - updateVisibility() - } - - private val settingsButtonContainer: View = view.findViewById(R.id.settings_button_container) - private val securityFootersContainer: ViewGroup? = - view.findViewById(R.id.security_footers_container) - private val powerMenuLite: View = view.findViewById(R.id.pm_lite) - private val multiUserSwitchController = multiUserSwitchControllerFactory.create(view) - - @VisibleForTesting - internal val securityFootersSeparator = View(context).apply { visibility = View.GONE } - - private val onUserInfoChangedListener = OnUserInfoChangedListener { _, picture, _ -> - val isGuestUser: Boolean = userManager.isGuestUser(KeyguardUpdateMonitor.getCurrentUser()) - mView.onUserInfoChanged(picture, isGuestUser) - } - - private val multiUserSetting = - object : SettingObserver( - globalSetting, handler, USER_SWITCHER_ENABLED, userTracker.userId) { - override fun handleValueChanged(value: Int, observedChange: Boolean) { - if (observedChange) { - updateView() - } - } - } - - private val onClickListener = View.OnClickListener { v -> - // Don't do anything if the tap looks suspicious. - if (!visible || falsingManager.isFalseTap(FalsingManager.LOW_PENALTY)) { - return@OnClickListener - } - if (v === settingsButtonContainer) { - if (!deviceProvisionedController.isCurrentUserSetup) { - // If user isn't setup just unlock the device and dump them back at SUW. - activityStarter.postQSRunnableDismissingKeyguard {} - return@OnClickListener - } - metricsLogger.action(MetricsProto.MetricsEvent.ACTION_QS_EXPANDED_SETTINGS_LAUNCH) - startSettingsActivity() - } else if (v === powerMenuLite) { - uiEventLogger.log(GlobalActionsDialogLite.GlobalActionsEvent.GA_OPEN_QS) - globalActionsDialog?.showOrHideDialog(false, true, Expandable.fromView(powerMenuLite)) - } - } - - private val configurationListener = - object : ConfigurationController.ConfigurationListener { - override fun onConfigChanged(newConfig: Configuration?) { - updateResources() - } - } - - private fun updateResources() { - inSplitShade = LargeScreenUtils.shouldUseSplitNotificationShade(resources) - } - - override fun onInit() { - multiUserSwitchController.init() - securityFooterController.init() - fgsManagerFooterController.init() - } - - private fun updateVisibility() { - val previousVisibility = mView.visibility - mView.visibility = if (visible) View.VISIBLE else View.INVISIBLE - if (previousVisibility != mView.visibility) updateView() - } - - private fun startSettingsActivity() { - val animationController = settingsButtonContainer?.let { - ActivityLaunchAnimator.Controller.fromView( - it, - InteractionJankMonitor.CUJ_SHADE_APP_LAUNCH_FROM_SETTINGS_BUTTON) - } - activityStarter.startActivity(Intent(Settings.ACTION_SETTINGS), - true /* dismissShade */, animationController) - } - - @VisibleForTesting - public override fun onViewAttached() { - globalActionsDialog = globalActionsDialogProvider.get() - if (showPMLiteButton) { - powerMenuLite.visibility = View.VISIBLE - powerMenuLite.setOnClickListener(onClickListener) - } else { - powerMenuLite.visibility = View.GONE - } - settingsButtonContainer.setOnClickListener(onClickListener) - multiUserSetting.isListening = true - - val securityFooter = securityFooterController.view - securityFootersContainer?.addView(securityFooter) - val separatorWidth = resources.getDimensionPixelSize(R.dimen.qs_footer_action_inset) - securityFootersContainer?.addView(securityFootersSeparator, separatorWidth, 1) - - val fgsFooter = fgsManagerFooterController.view - securityFootersContainer?.addView(fgsFooter) - - val visibilityListener = - VisibilityChangedDispatcher.OnVisibilityChangedListener { visibility -> - if (securityFooter.visibility == View.VISIBLE && - fgsFooter.visibility == View.VISIBLE) { - securityFootersSeparator.visibility = View.VISIBLE - } else { - securityFootersSeparator.visibility = View.GONE - } - fgsManagerFooterController - .setCollapsed(securityFooter.visibility == View.VISIBLE) - } - securityFooterController.setOnVisibilityChangedListener(visibilityListener) - fgsManagerFooterController.setOnVisibilityChangedListener(visibilityListener) - - configurationController.addCallback(configurationListener) - - updateResources() - updateView() - } - - private fun updateView() { - mView.updateEverything(multiUserSwitchController.isMultiUserEnabled) - } - - override fun onViewDetached() { - globalActionsDialog?.destroy() - globalActionsDialog = null - setListening(false) - multiUserSetting.isListening = false - configurationController.removeCallback(configurationListener) - } - - fun setListening(listening: Boolean) { - if (this.listening == listening) { - return - } - this.listening = listening - if (this.listening) { - userInfoController.addCallback(onUserInfoChangedListener) - updateView() - } else { - userInfoController.removeCallback(onUserInfoChangedListener) - } - - fgsManagerFooterController.setListening(listening) - securityFooterController.setListening(listening) - } - - fun disable(state2: Int) { - mView.disable(state2, multiUserSwitchController.isMultiUserEnabled) - } - - fun setExpansion(headerExpansionFraction: Float) { - animators.setPosition(headerExpansionFraction) - } - - fun setKeyguardShowing(showing: Boolean) { - setExpansion(lastExpansion) +/** Controller for the footer actions. This manages the initialization of its dependencies. */ +@SysUISingleton +class FooterActionsController +@Inject +constructor( + private val fgsManagerController: FgsManagerController, +) { + fun init() { + fgsManagerController.init() } } diff --git a/packages/SystemUI/src/com/android/systemui/qs/FooterActionsView.kt b/packages/SystemUI/src/com/android/systemui/qs/FooterActionsView.kt deleted file mode 100644 index d602b0b27977..000000000000 --- a/packages/SystemUI/src/com/android/systemui/qs/FooterActionsView.kt +++ /dev/null @@ -1,135 +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. - */ -package com.android.systemui.qs - -import android.app.StatusBarManager -import android.content.Context -import android.graphics.PorterDuff -import android.graphics.drawable.Drawable -import android.graphics.drawable.RippleDrawable -import android.os.UserManager -import android.util.AttributeSet -import android.util.Log -import android.view.MotionEvent -import android.view.View -import android.widget.ImageView -import android.widget.LinearLayout -import androidx.annotation.Keep -import com.android.settingslib.Utils -import com.android.settingslib.drawable.UserIconDrawable -import com.android.systemui.R -import com.android.systemui.statusbar.phone.MultiUserSwitch - -/** - * Quick Settings bottom buttons placed in footer (aka utility bar) - always visible in expanded QS, - * in split shade mode visible also in collapsed state. May contain up to 5 buttons: settings, - * edit tiles, power off and conditionally: user switch and tuner - */ -// TODO(b/242040009): Remove this file. -class FooterActionsView(context: Context?, attrs: AttributeSet?) : LinearLayout(context, attrs) { - private lateinit var settingsContainer: View - private lateinit var multiUserSwitch: MultiUserSwitch - private lateinit var multiUserAvatar: ImageView - - private var qsDisabled = false - private var expansionAmount = 0f - - /** - * Sets the alpha of the background of this view. - * - * Used from a [TouchAnimator] in the controller. - */ - var backgroundAlpha: Float = 1f - @Keep - set(value) { - field = value - background?.alpha = (value * 255).toInt() - } - @Keep get - - override fun onFinishInflate() { - super.onFinishInflate() - settingsContainer = findViewById(R.id.settings_button_container) - multiUserSwitch = findViewById(R.id.multi_user_switch) - multiUserAvatar = multiUserSwitch.findViewById(R.id.multi_user_avatar) - - // RenderThread is doing more harm than good when touching the header (to expand quick - // settings), so disable it for this view - if (settingsContainer.background is RippleDrawable) { - (settingsContainer.background as RippleDrawable).setForceSoftware(true) - } - importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_YES - } - - fun disable( - state2: Int, - multiUserEnabled: Boolean - ) { - val disabled = state2 and StatusBarManager.DISABLE2_QUICK_SETTINGS != 0 - if (disabled == qsDisabled) return - qsDisabled = disabled - updateEverything(multiUserEnabled) - } - - fun updateEverything( - multiUserEnabled: Boolean - ) { - post { - updateVisibilities(multiUserEnabled) - updateClickabilities() - isClickable = false - } - } - - private fun updateClickabilities() { - multiUserSwitch.isClickable = multiUserSwitch.visibility == VISIBLE - settingsContainer.isClickable = settingsContainer.visibility == VISIBLE - } - - private fun updateVisibilities( - multiUserEnabled: Boolean - ) { - settingsContainer.visibility = if (qsDisabled) GONE else VISIBLE - multiUserSwitch.visibility = if (multiUserEnabled) VISIBLE else GONE - val isDemo = UserManager.isDeviceInDemoMode(context) - settingsContainer.visibility = if (isDemo) INVISIBLE else VISIBLE - } - - fun onUserInfoChanged(picture: Drawable?, isGuestUser: Boolean) { - var pictureToSet = picture - if (picture != null && isGuestUser && picture !is UserIconDrawable) { - pictureToSet = picture.constantState.newDrawable(resources).mutate() - pictureToSet.setColorFilter( - Utils.getColorAttrDefaultColor(mContext, android.R.attr.colorForeground), - PorterDuff.Mode.SRC_IN) - } - multiUserAvatar.setImageDrawable(pictureToSet) - } - - override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean { - if (VERBOSE) Log.d(TAG, "FooterActionsView onInterceptTouchEvent ${ev?.string}") - return super.onInterceptTouchEvent(ev) - } - - override fun onTouchEvent(event: MotionEvent?): Boolean { - if (VERBOSE) Log.d(TAG, "FooterActionsView onTouchEvent ${event?.string}") - return super.onTouchEvent(event) - } -} -private const val TAG = "FooterActionsView" -private val VERBOSE = Log.isLoggable(TAG, Log.VERBOSE) -private val MotionEvent.string - get() = "($id): ($x,$y)" diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSContainerImpl.java b/packages/SystemUI/src/com/android/systemui/qs/QSContainerImpl.java index dc9dcc295e6e..0c242d9da25f 100644 --- a/packages/SystemUI/src/com/android/systemui/qs/QSContainerImpl.java +++ b/packages/SystemUI/src/com/android/systemui/qs/QSContainerImpl.java @@ -215,7 +215,7 @@ public class QSContainerImpl extends FrameLayout implements Dumpable { // Some views are always full width or have dependent padding continue; } - if (!(view instanceof FooterActionsView)) { + if (view.getId() != R.id.qs_footer_actions) { // Only padding for FooterActionsView, no margin. That way, the background goes // all the way to the edge. LayoutParams lp = (LayoutParams) view.getLayoutParams(); diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSFgsManagerFooter.java b/packages/SystemUI/src/com/android/systemui/qs/QSFgsManagerFooter.java deleted file mode 100644 index b1b9dd721eaf..000000000000 --- a/packages/SystemUI/src/com/android/systemui/qs/QSFgsManagerFooter.java +++ /dev/null @@ -1,178 +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.qs; - -import static com.android.systemui.qs.dagger.QSFragmentModule.QS_FGS_MANAGER_FOOTER_VIEW; -import static com.android.systemui.util.PluralMessageFormaterKt.icuMessageFormat; - -import android.content.Context; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.TextView; - -import androidx.annotation.Nullable; - -import com.android.systemui.R; -import com.android.systemui.animation.Expandable; -import com.android.systemui.dagger.qualifiers.Background; -import com.android.systemui.dagger.qualifiers.Main; -import com.android.systemui.qs.dagger.QSScope; - -import java.util.concurrent.Executor; - -import javax.inject.Inject; -import javax.inject.Named; - -/** - * Footer entry point for the foreground service manager - */ -// TODO(b/242040009): Remove this file. -@QSScope -public class QSFgsManagerFooter implements View.OnClickListener, - FgsManagerController.OnDialogDismissedListener, - FgsManagerController.OnNumberOfPackagesChangedListener, - VisibilityChangedDispatcher { - - private final View mRootView; - private final TextView mFooterText; - private final Context mContext; - private final Executor mMainExecutor; - private final Executor mExecutor; - - private final FgsManagerController mFgsManagerController; - - private boolean mIsInitialized = false; - private int mNumPackages; - - private final View mTextContainer; - private final View mNumberContainer; - private final TextView mNumberView; - private final ImageView mDotView; - private final ImageView mCollapsedDotView; - - @Nullable - private VisibilityChangedDispatcher.OnVisibilityChangedListener mVisibilityChangedListener; - - @Inject - QSFgsManagerFooter(@Named(QS_FGS_MANAGER_FOOTER_VIEW) View rootView, - @Main Executor mainExecutor, @Background Executor executor, - FgsManagerController fgsManagerController) { - mRootView = rootView; - mFooterText = mRootView.findViewById(R.id.footer_text); - mTextContainer = mRootView.findViewById(R.id.fgs_text_container); - mNumberContainer = mRootView.findViewById(R.id.fgs_number_container); - mNumberView = mRootView.findViewById(R.id.fgs_number); - mDotView = mRootView.findViewById(R.id.fgs_new); - mCollapsedDotView = mRootView.findViewById(R.id.fgs_collapsed_new); - mContext = rootView.getContext(); - mMainExecutor = mainExecutor; - mExecutor = executor; - mFgsManagerController = fgsManagerController; - } - - /** - * Whether to show the footer in collapsed mode (just a number) or not (text). - * @param collapsed - */ - public void setCollapsed(boolean collapsed) { - mTextContainer.setVisibility(collapsed ? View.GONE : View.VISIBLE); - mNumberContainer.setVisibility(collapsed ? View.VISIBLE : View.GONE); - LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mRootView.getLayoutParams(); - lp.width = collapsed ? ViewGroup.LayoutParams.WRAP_CONTENT : 0; - lp.weight = collapsed ? 0f : 1f; - mRootView.setLayoutParams(lp); - } - - public void init() { - if (mIsInitialized) { - return; - } - - mFgsManagerController.init(); - - mRootView.setOnClickListener(this); - - mIsInitialized = true; - } - - public void setListening(boolean listening) { - if (listening) { - mFgsManagerController.addOnDialogDismissedListener(this); - mFgsManagerController.addOnNumberOfPackagesChangedListener(this); - mNumPackages = mFgsManagerController.getNumRunningPackages(); - refreshState(); - } else { - mFgsManagerController.removeOnDialogDismissedListener(this); - mFgsManagerController.removeOnNumberOfPackagesChangedListener(this); - } - } - - @Override - public void setOnVisibilityChangedListener( - @Nullable OnVisibilityChangedListener onVisibilityChangedListener) { - mVisibilityChangedListener = onVisibilityChangedListener; - } - - @Override - public void onClick(View view) { - mFgsManagerController.showDialog(Expandable.fromView(view)); - } - - public void refreshState() { - mExecutor.execute(this::handleRefreshState); - } - - public View getView() { - return mRootView; - } - - public void handleRefreshState() { - mMainExecutor.execute(() -> { - CharSequence text = icuMessageFormat(mContext.getResources(), - R.string.fgs_manager_footer_label, mNumPackages); - mFooterText.setText(text); - mNumberView.setText(Integer.toString(mNumPackages)); - mNumberView.setContentDescription(text); - if (mFgsManagerController.shouldUpdateFooterVisibility()) { - mRootView.setVisibility(mNumPackages > 0 - && mFgsManagerController.isAvailable().getValue() ? View.VISIBLE - : View.GONE); - int dotVis = mFgsManagerController.getShowFooterDot().getValue() - && mFgsManagerController.getNewChangesSinceDialogWasDismissed() - ? View.VISIBLE : View.GONE; - mDotView.setVisibility(dotVis); - mCollapsedDotView.setVisibility(dotVis); - if (mVisibilityChangedListener != null) { - mVisibilityChangedListener.onVisibilityChanged(mRootView.getVisibility()); - } - } - }); - } - - @Override - public void onDialogDismissed() { - refreshState(); - } - - @Override - public void onNumberOfPackagesChanged(int numPackages) { - mNumPackages = numPackages; - refreshState(); - } -} diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSFragment.java b/packages/SystemUI/src/com/android/systemui/qs/QSFragment.java index c0533bae233f..893574a59d94 100644 --- a/packages/SystemUI/src/com/android/systemui/qs/QSFragment.java +++ b/packages/SystemUI/src/com/android/systemui/qs/QSFragment.java @@ -33,6 +33,7 @@ import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; +import android.widget.LinearLayout; import androidx.annotation.FloatRange; import androidx.annotation.Nullable; @@ -48,7 +49,6 @@ import com.android.systemui.animation.Interpolators; import com.android.systemui.animation.ShadeInterpolation; import com.android.systemui.dump.DumpManager; import com.android.systemui.flags.FeatureFlags; -import com.android.systemui.flags.Flags; import com.android.systemui.media.controls.ui.MediaHost; import com.android.systemui.plugins.FalsingManager; import com.android.systemui.plugins.qs.QS; @@ -114,7 +114,7 @@ public class QSFragment extends LifecycleFragment implements QS, CommandQueue.Ca private final QSFragmentDisableFlagsLogger mQsFragmentDisableFlagsLogger; private final QSTileHost mHost; private final FeatureFlags mFeatureFlags; - private final NewFooterActionsController mNewFooterActionsController; + private final FooterActionsController mFooterActionsController; private final FooterActionsViewModel.Factory mFooterActionsViewModelFactory; private final ListeningAndVisibilityLifecycleOwner mListeningAndVisibilityLifecycleOwner; private boolean mShowCollapsedOnKeyguard; @@ -132,9 +132,6 @@ public class QSFragment extends LifecycleFragment implements QS, CommandQueue.Ca private QSPanelController mQSPanelController; private QuickQSPanelController mQuickQSPanelController; private QSCustomizerController mQSCustomizerController; - @Nullable - private FooterActionsController mQSFooterActionController; - @Nullable private FooterActionsViewModel mQSFooterActionsViewModel; @Nullable private ScrollListener mScrollListener; @@ -185,7 +182,7 @@ public class QSFragment extends LifecycleFragment implements QS, CommandQueue.Ca QSFragmentComponent.Factory qsComponentFactory, QSFragmentDisableFlagsLogger qsFragmentDisableFlagsLogger, FalsingManager falsingManager, DumpManager dumpManager, FeatureFlags featureFlags, - NewFooterActionsController newFooterActionsController, + FooterActionsController footerActionsController, FooterActionsViewModel.Factory footerActionsViewModelFactory) { mRemoteInputQuickSettingsDisabler = remoteInputQsDisabler; mQsMediaHost = qsMediaHost; @@ -199,7 +196,7 @@ public class QSFragment extends LifecycleFragment implements QS, CommandQueue.Ca mStatusBarStateController = statusBarStateController; mDumpManager = dumpManager; mFeatureFlags = featureFlags; - mNewFooterActionsController = newFooterActionsController; + mFooterActionsController = footerActionsController; mFooterActionsViewModelFactory = footerActionsViewModelFactory; mListeningAndVisibilityLifecycleOwner = new ListeningAndVisibilityLifecycleOwner(); } @@ -226,18 +223,12 @@ public class QSFragment extends LifecycleFragment implements QS, CommandQueue.Ca mQSPanelController.init(); mQuickQSPanelController.init(); - if (mFeatureFlags.isEnabled(Flags.NEW_FOOTER_ACTIONS)) { - mQSFooterActionsViewModel = mFooterActionsViewModelFactory.create(/* lifecycleOwner */ - this); - FooterActionsView footerActionsView = view.findViewById(R.id.qs_footer_actions); - FooterActionsViewBinder.bind(footerActionsView, mQSFooterActionsViewModel, - mListeningAndVisibilityLifecycleOwner); - - mNewFooterActionsController.init(); - } else { - mQSFooterActionController = qsFragmentComponent.getQSFooterActionController(); - mQSFooterActionController.init(); - } + mQSFooterActionsViewModel = mFooterActionsViewModelFactory.create(/* lifecycleOwner */ + this); + LinearLayout footerActionsView = view.findViewById(R.id.qs_footer_actions); + FooterActionsViewBinder.bind(footerActionsView, mQSFooterActionsViewModel, + mListeningAndVisibilityLifecycleOwner); + mFooterActionsController.init(); mQSPanelScrollView = view.findViewById(R.id.expanded_qs_scroll_view); mQSPanelScrollView.addOnLayoutChangeListener( @@ -436,9 +427,6 @@ public class QSFragment extends LifecycleFragment implements QS, CommandQueue.Ca mContainer.disable(state1, state2, animate); mHeader.disable(state1, state2, animate); mFooter.disable(state1, state2, animate); - if (mQSFooterActionController != null) { - mQSFooterActionController.disable(state2); - } updateQsState(); } @@ -457,11 +445,7 @@ public class QSFragment extends LifecycleFragment implements QS, CommandQueue.Ca boolean footerVisible = qsPanelVisible && (mQsExpanded || !keyguardShowing || mHeaderAnimating || mShowCollapsedOnKeyguard); mFooter.setVisibility(footerVisible ? View.VISIBLE : View.INVISIBLE); - if (mQSFooterActionController != null) { - mQSFooterActionController.setVisible(footerVisible); - } else { - mQSFooterActionsViewModel.onVisibilityChangeRequested(footerVisible); - } + mQSFooterActionsViewModel.onVisibilityChangeRequested(footerVisible); mFooter.setExpanded((keyguardShowing && !mHeaderAnimating && !mShowCollapsedOnKeyguard) || (mQsExpanded && !mStackScrollerOverscrolling)); mQSPanelController.setVisibility(qsPanelVisible ? View.VISIBLE : View.INVISIBLE); @@ -534,9 +518,6 @@ public class QSFragment extends LifecycleFragment implements QS, CommandQueue.Ca } mFooter.setKeyguardShowing(keyguardShowing); - if (mQSFooterActionController != null) { - mQSFooterActionController.setKeyguardShowing(keyguardShowing); - } updateQsState(); } @@ -552,9 +533,6 @@ public class QSFragment extends LifecycleFragment implements QS, CommandQueue.Ca if (DEBUG) Log.d(TAG, "setListening " + listening); mListening = listening; mQSContainerImplController.setListening(listening && mQsVisible); - if (mQSFooterActionController != null) { - mQSFooterActionController.setListening(listening && mQsVisible); - } mListeningAndVisibilityLifecycleOwner.updateState(); updateQsPanelControllerListening(); } @@ -665,12 +643,8 @@ public class QSFragment extends LifecycleFragment implements QS, CommandQueue.Ca mFooter.setExpansion(onKeyguardAndExpanded ? 1 : expansion); float footerActionsExpansion = onKeyguardAndExpanded ? 1 : mInSplitShade ? alphaProgress : expansion; - if (mQSFooterActionController != null) { - mQSFooterActionController.setExpansion(footerActionsExpansion); - } else { - mQSFooterActionsViewModel.onQuickSettingsExpansionChanged(footerActionsExpansion, - mInSplitShade); - } + mQSFooterActionsViewModel.onQuickSettingsExpansionChanged(footerActionsExpansion, + mInSplitShade); mQSPanelController.setRevealExpansion(expansion); mQSPanelController.getTileLayout().setExpansion(expansion, proposedTranslation); mQuickQSPanelController.getTileLayout().setExpansion(expansion, proposedTranslation); @@ -835,11 +809,7 @@ public class QSFragment extends LifecycleFragment implements QS, CommandQueue.Ca boolean customizing = isCustomizing(); mQSPanelScrollView.setVisibility(!customizing ? View.VISIBLE : View.INVISIBLE); mFooter.setVisibility(!customizing ? View.VISIBLE : View.INVISIBLE); - if (mQSFooterActionController != null) { - mQSFooterActionController.setVisible(!customizing); - } else { - mQSFooterActionsViewModel.onVisibilityChangeRequested(!customizing); - } + mQSFooterActionsViewModel.onVisibilityChangeRequested(!customizing); mHeader.setVisibility(!customizing ? View.VISIBLE : View.INVISIBLE); // Let the panel know the position changed and it needs to update where notifications // and whatnot are. @@ -927,6 +897,11 @@ public class QSFragment extends LifecycleFragment implements QS, CommandQueue.Ca updateShowCollapsedOnKeyguard(); } + @VisibleForTesting + public ListeningAndVisibilityLifecycleOwner getListeningAndVisibilityLifecycleOwner() { + return mListeningAndVisibilityLifecycleOwner; + } + @Override public void dump(PrintWriter pw, String[] args) { IndentingPrintWriter indentingPw = new IndentingPrintWriter(pw, /* singleIndent= */ " "); @@ -994,7 +969,8 @@ public class QSFragment extends LifecycleFragment implements QS, CommandQueue.Ca * - STARTED when mListening == true && mQsVisible == false. * - RESUMED when mListening == true && mQsVisible == true. */ - private class ListeningAndVisibilityLifecycleOwner implements LifecycleOwner { + @VisibleForTesting + class ListeningAndVisibilityLifecycleOwner implements LifecycleOwner { private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); private boolean mDestroyed = false; diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSSecurityFooter.java b/packages/SystemUI/src/com/android/systemui/qs/QSSecurityFooter.java deleted file mode 100644 index 6c1e95645550..000000000000 --- a/packages/SystemUI/src/com/android/systemui/qs/QSSecurityFooter.java +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Copyright (C) 2014 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.qs; - -import static com.android.systemui.qs.dagger.QSFragmentModule.QS_SECURITY_FOOTER_VIEW; - -import android.app.admin.DevicePolicyEventLogger; -import android.app.admin.DevicePolicyManager; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.res.Resources; -import android.os.Handler; -import android.os.Looper; -import android.os.Message; -import android.os.UserHandle; -import android.util.Log; -import android.view.View; -import android.view.View.OnClickListener; -import android.widget.ImageView; -import android.widget.TextView; - -import androidx.annotation.Nullable; - -import com.android.internal.util.FrameworkStatsLog; -import com.android.systemui.FontSizeUtils; -import com.android.systemui.R; -import com.android.systemui.animation.Expandable; -import com.android.systemui.broadcast.BroadcastDispatcher; -import com.android.systemui.common.shared.model.Icon; -import com.android.systemui.dagger.qualifiers.Background; -import com.android.systemui.dagger.qualifiers.Main; -import com.android.systemui.qs.dagger.QSScope; -import com.android.systemui.qs.footer.domain.model.SecurityButtonConfig; -import com.android.systemui.security.data.model.SecurityModel; -import com.android.systemui.statusbar.policy.SecurityController; -import com.android.systemui.util.ViewController; - -import javax.inject.Inject; -import javax.inject.Named; - -/** ViewController for the footer actions. */ -// TODO(b/242040009): Remove this class. -@QSScope -public class QSSecurityFooter extends ViewController<View> - implements OnClickListener, VisibilityChangedDispatcher { - protected static final String TAG = "QSSecurityFooter"; - - private final TextView mFooterText; - private final ImageView mPrimaryFooterIcon; - private Context mContext; - private final Callback mCallback = new Callback(); - private final SecurityController mSecurityController; - private final Handler mMainHandler; - private final BroadcastDispatcher mBroadcastDispatcher; - private final QSSecurityFooterUtils mQSSecurityFooterUtils; - - protected H mHandler; - - private boolean mIsVisible; - private boolean mIsClickable; - @Nullable - private CharSequence mFooterTextContent = null; - private Icon mFooterIcon; - - @Nullable - private VisibilityChangedDispatcher.OnVisibilityChangedListener mVisibilityChangedListener; - - private final BroadcastReceiver mReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - if (intent.getAction().equals( - DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG)) { - showDeviceMonitoringDialog(); - } - } - }; - - @Inject - QSSecurityFooter(@Named(QS_SECURITY_FOOTER_VIEW) View rootView, - @Main Handler mainHandler, SecurityController securityController, - @Background Looper bgLooper, BroadcastDispatcher broadcastDispatcher, - QSSecurityFooterUtils qSSecurityFooterUtils) { - super(rootView); - mFooterText = mView.findViewById(R.id.footer_text); - mPrimaryFooterIcon = mView.findViewById(R.id.primary_footer_icon); - mFooterIcon = new Icon.Resource( - R.drawable.ic_info_outline, /* contentDescription= */ null); - mContext = rootView.getContext(); - mSecurityController = securityController; - mMainHandler = mainHandler; - mHandler = new H(bgLooper); - mBroadcastDispatcher = broadcastDispatcher; - mQSSecurityFooterUtils = qSSecurityFooterUtils; - } - - @Override - protected void onViewAttached() { - // Use background handler, as it's the same thread that handleClick is called on. - mBroadcastDispatcher.registerReceiverWithHandler(mReceiver, - new IntentFilter(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG), - mHandler, UserHandle.ALL); - mView.setOnClickListener(this); - } - - @Override - protected void onViewDetached() { - mBroadcastDispatcher.unregisterReceiver(mReceiver); - mView.setOnClickListener(null); - } - - public void setListening(boolean listening) { - if (listening) { - mSecurityController.addCallback(mCallback); - refreshState(); - } else { - mSecurityController.removeCallback(mCallback); - } - } - - @Override - public void setOnVisibilityChangedListener( - @Nullable OnVisibilityChangedListener onVisibilityChangedListener) { - mVisibilityChangedListener = onVisibilityChangedListener; - } - - public void onConfigurationChanged() { - FontSizeUtils.updateFontSize(mFooterText, R.dimen.qs_tile_text_size); - Resources r = mContext.getResources(); - - int padding = r.getDimensionPixelSize(R.dimen.qs_footer_padding); - mView.setPaddingRelative(padding, 0, padding, 0); - mView.setBackground(mContext.getDrawable(R.drawable.qs_security_footer_background)); - } - - public View getView() { - return mView; - } - - public boolean hasFooter() { - return mView.getVisibility() != View.GONE; - } - - @Override - public void onClick(View v) { - if (!hasFooter()) return; - mHandler.sendEmptyMessage(H.CLICK); - } - - private void handleClick() { - showDeviceMonitoringDialog(); - DevicePolicyEventLogger - .createEvent(FrameworkStatsLog.DEVICE_POLICY_EVENT__EVENT_ID__DO_USER_INFO_CLICKED) - .write(); - } - - // TODO(b/242040009): Remove this. - public void showDeviceMonitoringDialog() { - mQSSecurityFooterUtils.showDeviceMonitoringDialog(mContext, Expandable.fromView(mView)); - } - - public void refreshState() { - mHandler.sendEmptyMessage(H.REFRESH_STATE); - } - - private void handleRefreshState() { - SecurityModel securityModel = SecurityModel.create(mSecurityController); - SecurityButtonConfig buttonConfig = mQSSecurityFooterUtils.getButtonConfig(securityModel); - - if (buttonConfig == null) { - mIsVisible = false; - } else { - mIsVisible = true; - mIsClickable = buttonConfig.isClickable(); - mFooterTextContent = buttonConfig.getText(); - mFooterIcon = buttonConfig.getIcon(); - } - - // Update the UI. - mMainHandler.post(mUpdatePrimaryIcon); - mMainHandler.post(mUpdateDisplayState); - } - - private final Runnable mUpdatePrimaryIcon = new Runnable() { - @Override - public void run() { - if (mFooterIcon instanceof Icon.Loaded) { - mPrimaryFooterIcon.setImageDrawable(((Icon.Loaded) mFooterIcon).getDrawable()); - } else if (mFooterIcon instanceof Icon.Resource) { - mPrimaryFooterIcon.setImageResource(((Icon.Resource) mFooterIcon).getRes()); - } - } - }; - - private final Runnable mUpdateDisplayState = new Runnable() { - @Override - public void run() { - if (mFooterTextContent != null) { - mFooterText.setText(mFooterTextContent); - } - mView.setVisibility(mIsVisible ? View.VISIBLE : View.GONE); - if (mVisibilityChangedListener != null) { - mVisibilityChangedListener.onVisibilityChanged(mView.getVisibility()); - } - - if (mIsVisible && mIsClickable) { - mView.setClickable(true); - mView.findViewById(R.id.footer_icon).setVisibility(View.VISIBLE); - } else { - mView.setClickable(false); - mView.findViewById(R.id.footer_icon).setVisibility(View.GONE); - } - } - }; - - private class Callback implements SecurityController.SecurityControllerCallback { - @Override - public void onStateChanged() { - refreshState(); - } - } - - private class H extends Handler { - private static final int CLICK = 0; - private static final int REFRESH_STATE = 1; - - private H(Looper looper) { - super(looper); - } - - @Override - public void handleMessage(Message msg) { - String name = null; - try { - if (msg.what == REFRESH_STATE) { - name = "handleRefreshState"; - handleRefreshState(); - } else if (msg.what == CLICK) { - name = "handleClick"; - handleClick(); - } - } catch (Throwable t) { - final String error = "Error in " + name; - Log.w(TAG, error, t); - } - } - } -} diff --git a/packages/SystemUI/src/com/android/systemui/qs/dagger/QSFragmentModule.java b/packages/SystemUI/src/com/android/systemui/qs/dagger/QSFragmentModule.java index aa505fb0b6bd..01eb636f75d6 100644 --- a/packages/SystemUI/src/com/android/systemui/qs/dagger/QSFragmentModule.java +++ b/packages/SystemUI/src/com/android/systemui/qs/dagger/QSFragmentModule.java @@ -28,7 +28,6 @@ import com.android.systemui.battery.BatteryMeterView; import com.android.systemui.dagger.qualifiers.RootView; import com.android.systemui.plugins.qs.QS; import com.android.systemui.privacy.OngoingPrivacyChip; -import com.android.systemui.qs.FooterActionsView; import com.android.systemui.qs.QSContainerImpl; import com.android.systemui.qs.QSFooter; import com.android.systemui.qs.QSFooterView; @@ -51,8 +50,6 @@ import dagger.Provides; */ @Module public interface QSFragmentModule { - String QS_FGS_MANAGER_FOOTER_VIEW = "qs_fgs_manager_footer"; - String QS_SECURITY_FOOTER_VIEW = "qs_security_footer"; String QS_USING_MEDIA_PLAYER = "qs_using_media_player"; String QS_USING_COLLAPSED_LANDSCAPE_MEDIA = "qs_using_collapsed_landscape_media"; @@ -119,16 +116,6 @@ public interface QSFragmentModule { return view.findViewById(R.id.qs_footer); } - /** - * Provides a {@link FooterActionsView}. - * - * This will replace a ViewStub either in {@link QSFooterView} or in {@link QSContainerImpl}. - */ - @Provides - static FooterActionsView providesQSFooterActionsView(@RootView View view) { - return view.findViewById(R.id.qs_footer_actions); - } - /** */ @Provides @QSScope @@ -146,18 +133,6 @@ public interface QSFragmentModule { /** */ @Provides - @QSScope - @Named(QS_SECURITY_FOOTER_VIEW) - static View providesQSSecurityFooterView( - @QSThemedContext LayoutInflater layoutInflater, - FooterActionsView footerActionsView - ) { - return layoutInflater.inflate(R.layout.quick_settings_security_footer, footerActionsView, - false); - } - - /** */ - @Provides @Named(QS_USING_MEDIA_PLAYER) static boolean providesQSUsingMediaPlayer(Context context) { return useQsMediaPlayer(context); @@ -183,15 +158,4 @@ public interface QSFragmentModule { static StatusIconContainer providesStatusIconContainer(QuickStatusBarHeader qsHeader) { return qsHeader.findViewById(R.id.statusIcons); } - - /** */ - @Provides - @QSScope - @Named(QS_FGS_MANAGER_FOOTER_VIEW) - static View providesQSFgsManagerFooterView( - @QSThemedContext LayoutInflater layoutInflater, - FooterActionsView footerActionsView - ) { - return layoutInflater.inflate(R.layout.fgs_footer, footerActionsView, false); - } }
\ No newline at end of file diff --git a/packages/SystemUI/src/com/android/systemui/qs/footer/ui/binder/FooterActionsViewBinder.kt b/packages/SystemUI/src/com/android/systemui/qs/footer/ui/binder/FooterActionsViewBinder.kt index 3e39c8ee62f1..6db3c9941b78 100644 --- a/packages/SystemUI/src/com/android/systemui/qs/footer/ui/binder/FooterActionsViewBinder.kt +++ b/packages/SystemUI/src/com/android/systemui/qs/footer/ui/binder/FooterActionsViewBinder.kt @@ -35,35 +35,31 @@ import com.android.systemui.animation.Expandable import com.android.systemui.common.ui.binder.IconViewBinder import com.android.systemui.lifecycle.repeatWhenAttached import com.android.systemui.people.ui.view.PeopleViewBinder.bind -import com.android.systemui.qs.FooterActionsView import com.android.systemui.qs.footer.ui.viewmodel.FooterActionsButtonViewModel import com.android.systemui.qs.footer.ui.viewmodel.FooterActionsForegroundServicesButtonViewModel import com.android.systemui.qs.footer.ui.viewmodel.FooterActionsSecurityButtonViewModel import com.android.systemui.qs.footer.ui.viewmodel.FooterActionsViewModel +import kotlin.math.roundToInt import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch /** A ViewBinder for [FooterActionsViewBinder]. */ object FooterActionsViewBinder { - /** - * Create a [FooterActionsView] that can later be [bound][bind] to a [FooterActionsViewModel]. - */ + /** Create a view that can later be [bound][bind] to a [FooterActionsViewModel]. */ @JvmStatic - fun create(context: Context): FooterActionsView { + fun create(context: Context): LinearLayout { return LayoutInflater.from(context).inflate(R.layout.footer_actions, /* root= */ null) - as FooterActionsView + as LinearLayout } /** Bind [view] to [viewModel]. */ @JvmStatic fun bind( - view: FooterActionsView, + view: LinearLayout, viewModel: FooterActionsViewModel, qsVisibilityLifecycleOwner: LifecycleOwner, ) { - // Remove all children of the FooterActionsView that are used by the old implementation. - // TODO(b/242040009): Clean up the XML once the old implementation is removed. - view.removeAllViews() + view.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_YES // Add the views used by this new implementation. val context = view.context @@ -117,7 +113,11 @@ object FooterActionsViewBinder { } launch { viewModel.alpha.collect { view.alpha = it } } - launch { viewModel.backgroundAlpha.collect { view.backgroundAlpha = it } } + launch { + viewModel.backgroundAlpha.collect { + view.background?.alpha = (it * 255).roundToInt() + } + } } // Listen for model changes only when QS are visible. diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/InternetTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/InternetTile.java index 9542a024d4cb..28dd986c931b 100644 --- a/packages/SystemUI/src/com/android/systemui/qs/tiles/InternetTile.java +++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/InternetTile.java @@ -333,7 +333,14 @@ public class InternetTile extends QSTileImpl<SignalState> { mCellularInfo.mAirplaneModeEnabled = icon.visible; mWifiInfo.mAirplaneModeEnabled = icon.visible; if (!mSignalCallback.mEthernetInfo.mConnected) { - if (mWifiInfo.mEnabled && (mWifiInfo.mWifiSignalIconId > 0) + // Always use mWifiInfo to refresh the Internet Tile if airplane mode is enabled, + // because Internet Tile will show different information depending on whether WiFi + // is enabled or not. + if (mWifiInfo.mAirplaneModeEnabled) { + refreshState(mWifiInfo); + // If airplane mode is disabled, we will use mWifiInfo to refresh the Internet Tile + // if WiFi is currently connected to avoid any icon flickering. + } else if (mWifiInfo.mEnabled && (mWifiInfo.mWifiSignalIconId > 0) && (mWifiInfo.mSsid != null)) { refreshState(mWifiInfo); } else { diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotView.java b/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotView.java index fae938d542f1..9c7718d0e001 100644 --- a/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotView.java +++ b/packages/SystemUI/src/com/android/systemui/screenshot/ScreenshotView.java @@ -881,6 +881,13 @@ public class ScreenshotView extends FrameLayout implements } void addQuickShareChip(Notification.Action quickShareAction) { + if (mQuickShareChip != null) { + mSmartChips.remove(mQuickShareChip); + mActionsView.removeView(mQuickShareChip); + } + if (mPendingInteraction == PendingInteraction.QUICK_SHARE) { + mPendingInteraction = null; + } if (mPendingInteraction == null) { LayoutInflater inflater = LayoutInflater.from(mContext); mQuickShareChip = (OverlayActionChip) inflater.inflate( diff --git a/packages/SystemUI/src/com/android/systemui/security/data/model/SecurityModel.kt b/packages/SystemUI/src/com/android/systemui/security/data/model/SecurityModel.kt index 50af260684f8..1cf5a8fe5f97 100644 --- a/packages/SystemUI/src/com/android/systemui/security/data/model/SecurityModel.kt +++ b/packages/SystemUI/src/com/android/systemui/security/data/model/SecurityModel.kt @@ -17,6 +17,7 @@ package com.android.systemui.security.data.model import android.graphics.drawable.Drawable +import androidx.annotation.VisibleForTesting import com.android.systemui.dagger.qualifiers.Background import com.android.systemui.statusbar.policy.SecurityController import kotlinx.coroutines.CoroutineDispatcher @@ -55,8 +56,8 @@ data class SecurityModel( * Important: This method should be called from a background thread as this will do a lot of * binder calls. */ - // TODO(b/242040009): Remove this. @JvmStatic + @VisibleForTesting fun create(securityController: SecurityController): SecurityModel { val deviceAdminInfo = if (securityController.isParentalControlsEnabled) { diff --git a/packages/SystemUI/src/com/android/systemui/settings/brightness/BrightnessController.java b/packages/SystemUI/src/com/android/systemui/settings/brightness/BrightnessController.java index 5880003cdb1a..6bd9158b2a0c 100644 --- a/packages/SystemUI/src/com/android/systemui/settings/brightness/BrightnessController.java +++ b/packages/SystemUI/src/com/android/systemui/settings/brightness/BrightnessController.java @@ -67,11 +67,6 @@ public class BrightnessController implements ToggleSlider.Listener, MirroredBrig private static final Uri BRIGHTNESS_MODE_URI = Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS_MODE); - private static final Uri BRIGHTNESS_FOR_VR_FLOAT_URI = - Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS_FOR_VR_FLOAT); - - private final float mMinimumBacklightForVr; - private final float mMaximumBacklightForVr; private final int mDisplayId; private final Context mContext; @@ -126,8 +121,6 @@ public class BrightnessController implements ToggleSlider.Listener, MirroredBrig if (BRIGHTNESS_MODE_URI.equals(uri)) { mBackgroundHandler.post(mUpdateModeRunnable); mBackgroundHandler.post(mUpdateSliderRunnable); - } else if (BRIGHTNESS_FOR_VR_FLOAT_URI.equals(uri)) { - mBackgroundHandler.post(mUpdateSliderRunnable); } else { mBackgroundHandler.post(mUpdateModeRunnable); mBackgroundHandler.post(mUpdateSliderRunnable); @@ -140,9 +133,6 @@ public class BrightnessController implements ToggleSlider.Listener, MirroredBrig cr.registerContentObserver( BRIGHTNESS_MODE_URI, false, this, UserHandle.USER_ALL); - cr.registerContentObserver( - BRIGHTNESS_FOR_VR_FLOAT_URI, - false, this, UserHandle.USER_ALL); mDisplayManager.registerDisplayListener(mDisplayListener, mHandler, DisplayManager.EVENT_FLAG_DISPLAY_BRIGHTNESS); } @@ -304,10 +294,6 @@ public class BrightnessController implements ToggleSlider.Listener, MirroredBrig mDisplayId = mContext.getDisplayId(); PowerManager pm = context.getSystemService(PowerManager.class); - mMinimumBacklightForVr = pm.getBrightnessConstraint( - PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_MINIMUM_VR); - mMaximumBacklightForVr = pm.getBrightnessConstraint( - PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_MAXIMUM_VR); mDisplayManager = context.getSystemService(DisplayManager.class); mVrManager = IVrManager.Stub.asInterface(ServiceManager.getService( @@ -336,17 +322,12 @@ public class BrightnessController implements ToggleSlider.Listener, MirroredBrig final float maxBacklight; final int metric; - if (mIsVrModeEnabled) { - metric = MetricsEvent.ACTION_BRIGHTNESS_FOR_VR; - minBacklight = mMinimumBacklightForVr; - maxBacklight = mMaximumBacklightForVr; - } else { - metric = mAutomatic - ? MetricsEvent.ACTION_BRIGHTNESS_AUTO - : MetricsEvent.ACTION_BRIGHTNESS; - minBacklight = mBrightnessMin; - maxBacklight = mBrightnessMax; - } + + metric = mAutomatic + ? MetricsEvent.ACTION_BRIGHTNESS_AUTO + : MetricsEvent.ACTION_BRIGHTNESS; + minBacklight = mBrightnessMin; + maxBacklight = mBrightnessMax; final float valFloat = MathUtils.min( convertGammaToLinearFloat(value, minBacklight, maxBacklight), maxBacklight); @@ -398,15 +379,8 @@ public class BrightnessController implements ToggleSlider.Listener, MirroredBrig } private void updateSlider(float brightnessValue, boolean inVrMode) { - final float min; - final float max; - if (inVrMode) { - min = mMinimumBacklightForVr; - max = mMaximumBacklightForVr; - } else { - min = mBrightnessMin; - max = mBrightnessMax; - } + final float min = mBrightnessMin; + final float max = mBrightnessMax; // Ensure the slider is in a fixed position first, then check if we should animate. if (mSliderAnimator != null && mSliderAnimator.isStarted()) { diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/NetworkControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/NetworkControllerImpl.java index 336356eae364..b9074f0b9e2a 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/NetworkControllerImpl.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/NetworkControllerImpl.java @@ -68,7 +68,7 @@ import com.android.systemui.Dumpable; import com.android.systemui.R; import com.android.systemui.broadcast.BroadcastDispatcher; import com.android.systemui.dagger.SysUISingleton; -import com.android.systemui.dagger.qualifiers.LongRunning; +import com.android.systemui.dagger.qualifiers.Background; import com.android.systemui.dagger.qualifiers.Main; import com.android.systemui.demomode.DemoMode; import com.android.systemui.demomode.DemoModeController; @@ -225,15 +225,12 @@ public class NetworkControllerImpl extends BroadcastReceiver /** * Construct this controller object and register for updates. - * - * {@code @LongRunning} looper and bgExecutor instead {@code @Background} ones are used to - * address the b/246456655. This can be reverted after b/240663726 is fixed. */ @Inject public NetworkControllerImpl( Context context, - @LongRunning Looper bgLooper, - @LongRunning Executor bgExecutor, + @Background Looper bgLooper, + @Background Executor bgExecutor, SubscriptionManager subscriptionManager, CallbackHandler callbackHandler, DeviceProvisionedController deviceProvisionedController, diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/lockscreen/LockscreenSmartspaceController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/lockscreen/LockscreenSmartspaceController.kt index 6bd9502263ff..56d3b7cf788f 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/lockscreen/LockscreenSmartspaceController.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/lockscreen/LockscreenSmartspaceController.kt @@ -17,6 +17,7 @@ package com.android.systemui.statusbar.lockscreen import android.app.PendingIntent +import android.app.WallpaperManager import android.app.smartspace.SmartspaceConfig import android.app.smartspace.SmartspaceManager import android.app.smartspace.SmartspaceSession @@ -102,6 +103,8 @@ class LockscreenSmartspaceController @Inject constructor( private var showSensitiveContentForManagedUser = false private var managedUserHandle: UserHandle? = null + // TODO(b/202758428): refactor so that we can test color updates via region samping, similar to + // how we test color updates when theme changes (See testThemeChangeUpdatesTextColor). private val updateFun: UpdateColorCallback = { updateTextColorFromRegionSampler() } // TODO: Move logic into SmartspaceView @@ -109,16 +112,19 @@ class LockscreenSmartspaceController @Inject constructor( override fun onViewAttachedToWindow(v: View) { smartspaceViews.add(v as SmartspaceView) - var regionSampler = RegionSampler( - v, - uiExecutor, - bgExecutor, - regionSamplingEnabled, - updateFun - ) - initializeTextColors(regionSampler) - regionSampler.startRegionSampler() - regionSamplers.put(v, regionSampler) + if (regionSamplingEnabled) { + var regionSampler = RegionSampler( + v, + uiExecutor, + bgExecutor, + regionSamplingEnabled, + updateFun + ) + initializeTextColors(regionSampler) + regionSampler.startRegionSampler() + regionSamplers.put(v, regionSampler) + } + connectSession() updateTextColorFromWallpaper() @@ -128,9 +134,11 @@ class LockscreenSmartspaceController @Inject constructor( override fun onViewDetachedFromWindow(v: View) { smartspaceViews.remove(v as SmartspaceView) - var regionSampler = regionSamplers.getValue(v) - regionSampler.stopRegionSampler() - regionSamplers.remove(v) + if (regionSamplingEnabled) { + var regionSampler = regionSamplers.getValue(v) + regionSampler.stopRegionSampler() + regionSamplers.remove(v) + } if (smartspaceViews.isEmpty()) { disconnect() @@ -383,7 +391,8 @@ class LockscreenSmartspaceController @Inject constructor( } private fun updateTextColorFromWallpaper() { - if (!regionSamplingEnabled) { + val wallpaperManager = WallpaperManager.getInstance(context) + if (!regionSamplingEnabled || wallpaperManager.lockScreenWallpaperExists()) { val wallpaperTextColor = Utils.getColorAttrDefaultColor(context, R.attr.wallpaperTextColor) smartspaceViews.forEach { it.setPrimaryTextColor(wallpaperTextColor) } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/KeyguardCoordinator.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/KeyguardCoordinator.kt index 9da94ce968c7..4133802189a5 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/KeyguardCoordinator.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/KeyguardCoordinator.kt @@ -119,6 +119,9 @@ constructor( // Don't apply the filter to (non-promoted) group summaries // - summary will be pruned if necessary, depending on if children are filtered entry.parent?.summary == entry -> false + // Check that the entry satisfies certain characteristics that would bypass the + // filter + shouldIgnoreUnseenCheck(entry) -> false else -> true }.also { hasFiltered -> hasFilteredAnyNotifs = hasFilteredAnyNotifs || hasFiltered } @@ -134,6 +137,13 @@ constructor( keyguardNotificationVisibilityProvider.shouldHideNotification(entry) } + private fun shouldIgnoreUnseenCheck(entry: NotificationEntry): Boolean = + when { + entry.isMediaNotification -> true + entry.sbn.isOngoing -> true + else -> false + } + // TODO(b/206118999): merge this class with SensitiveContentCoordinator which also depends on // these same updates private fun setupInvalidateNotifListCallbacks() {} diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/fsi/FsiDebug.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/fsi/FsiDebug.kt new file mode 100644 index 000000000000..d9e3f8fbf146 --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/fsi/FsiDebug.kt @@ -0,0 +1,16 @@ +package com.android.systemui.statusbar.notification.fsi + +class FsiDebug { + + companion object { + private const val debugTag = "FsiDebug" + private const val debug = true + + fun log(s: Any) { + if (!debug) { + return + } + android.util.Log.d(debugTag, "$s") + } + } +}
\ No newline at end of file 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 1169d3f21e28..c7be2193e9b5 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/DemoStatusIcons.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/DemoStatusIcons.java @@ -40,6 +40,8 @@ import com.android.systemui.statusbar.StatusIconDisplayable; import com.android.systemui.statusbar.connectivity.ui.MobileContextProvider; import com.android.systemui.statusbar.phone.StatusBarSignalPolicy.MobileIconState; import com.android.systemui.statusbar.phone.StatusBarSignalPolicy.WifiIconState; +import com.android.systemui.statusbar.pipeline.mobile.ui.view.ModernStatusBarMobileView; +import com.android.systemui.statusbar.pipeline.mobile.ui.viewmodel.MobileIconsViewModel; import java.util.ArrayList; import java.util.List; @@ -50,20 +52,25 @@ public class DemoStatusIcons extends StatusIconContainer implements DemoMode, Da private final LinearLayout mStatusIcons; private final ArrayList<StatusBarMobileView> mMobileViews = new ArrayList<>(); + private final ArrayList<ModernStatusBarMobileView> mModernMobileViews = new ArrayList<>(); private final int mIconSize; private StatusBarWifiView mWifiView; private boolean mDemoMode; private int mColor; + private final MobileIconsViewModel mMobileIconsViewModel; + public DemoStatusIcons( LinearLayout statusIcons, + MobileIconsViewModel mobileIconsViewModel, int iconSize ) { super(statusIcons.getContext()); mStatusIcons = statusIcons; mIconSize = iconSize; mColor = DarkIconDispatcher.DEFAULT_ICON_TINT; + mMobileIconsViewModel = mobileIconsViewModel; if (statusIcons instanceof StatusIconContainer) { setShouldRestrictIcons(((StatusIconContainer) statusIcons).isRestrictingIcons()); @@ -71,7 +78,7 @@ public class DemoStatusIcons extends StatusIconContainer implements DemoMode, Da setShouldRestrictIcons(false); } setLayoutParams(mStatusIcons.getLayoutParams()); - setPadding(mStatusIcons.getPaddingLeft(),mStatusIcons.getPaddingTop(), + setPadding(mStatusIcons.getPaddingLeft(), mStatusIcons.getPaddingTop(), mStatusIcons.getPaddingRight(), mStatusIcons.getPaddingBottom()); setOrientation(mStatusIcons.getOrientation()); setGravity(Gravity.CENTER_VERTICAL); // no LL.getGravity() @@ -115,6 +122,8 @@ public class DemoStatusIcons extends StatusIconContainer implements DemoMode, Da public void onDemoModeFinished() { mDemoMode = false; mStatusIcons.setVisibility(View.VISIBLE); + mModernMobileViews.clear(); + mMobileViews.clear(); setVisibility(View.GONE); } @@ -269,6 +278,24 @@ public class DemoStatusIcons extends StatusIconContainer implements DemoMode, Da } /** + * Add a {@link ModernStatusBarMobileView} + * @param mobileContext possibly mcc/mnc overridden mobile context + * @param subId the subscriptionId for this mobile view + */ + public void addModernMobileView(Context mobileContext, int subId) { + Log.d(TAG, "addModernMobileView (subId=" + subId + ")"); + ModernStatusBarMobileView view = ModernStatusBarMobileView.constructAndBind( + mobileContext, + "mobile", + mMobileIconsViewModel.viewModelForSub(subId) + ); + + // mobile always goes at the end + mModernMobileViews.add(view); + addView(view, getChildCount(), createLayoutParams()); + } + + /** * Apply an update to a mobile icon view for the given {@link MobileIconState}. For * compatibility with {@link MobileContextProvider}, we have to recreate the view every time we * update it, since the context (and thus the {@link Configuration}) may have changed @@ -292,12 +319,19 @@ public class DemoStatusIcons extends StatusIconContainer implements DemoMode, Da if (view.getSlot().equals("wifi")) { removeView(mWifiView); mWifiView = null; - } else { + } else if (view instanceof StatusBarMobileView) { StatusBarMobileView mobileView = matchingMobileView(view); if (mobileView != null) { removeView(mobileView); mMobileViews.remove(mobileView); } + } else if (view instanceof ModernStatusBarMobileView) { + ModernStatusBarMobileView mobileView = matchingModernMobileView( + (ModernStatusBarMobileView) view); + if (mobileView != null) { + removeView(mobileView); + mModernMobileViews.remove(mobileView); + } } } @@ -316,6 +350,16 @@ public class DemoStatusIcons extends StatusIconContainer implements DemoMode, Da return null; } + private ModernStatusBarMobileView matchingModernMobileView(ModernStatusBarMobileView other) { + for (ModernStatusBarMobileView v : mModernMobileViews) { + if (v.getSubId() == other.getSubId()) { + return v; + } + } + + return null; + } + private LayoutParams createLayoutParams() { return new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, mIconSize); } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/MultiUserSwitchController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/MultiUserSwitchController.java deleted file mode 100644 index 5e2a7c8ca540..000000000000 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/MultiUserSwitchController.java +++ /dev/null @@ -1,171 +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. - */ - -package com.android.systemui.statusbar.phone; - -import static com.android.systemui.DejankUtils.whitelistIpcs; - -import android.content.Intent; -import android.os.UserHandle; -import android.os.UserManager; -import android.view.View; -import android.view.ViewGroup; - -import com.android.systemui.R; -import com.android.systemui.animation.ActivityLaunchAnimator; -import com.android.systemui.animation.Expandable; -import com.android.systemui.flags.FeatureFlags; -import com.android.systemui.flags.Flags; -import com.android.systemui.plugins.ActivityStarter; -import com.android.systemui.plugins.FalsingManager; -import com.android.systemui.qs.FooterActionsView; -import com.android.systemui.qs.dagger.QSScope; -import com.android.systemui.qs.user.UserSwitchDialogController; -import com.android.systemui.statusbar.policy.BaseUserSwitcherAdapter; -import com.android.systemui.statusbar.policy.UserSwitcherController; -import com.android.systemui.user.UserSwitcherActivity; -import com.android.systemui.util.ViewController; - -import javax.inject.Inject; - -/** View Controller for {@link MultiUserSwitch}. */ -// TODO(b/242040009): Remove this file. -public class MultiUserSwitchController extends ViewController<MultiUserSwitch> { - private final UserManager mUserManager; - private final UserSwitcherController mUserSwitcherController; - private final FalsingManager mFalsingManager; - private final UserSwitchDialogController mUserSwitchDialogController; - private final ActivityStarter mActivityStarter; - private final FeatureFlags mFeatureFlags; - - private BaseUserSwitcherAdapter mUserListener; - - private final View.OnClickListener mOnClickListener = new View.OnClickListener() { - @Override - public void onClick(View v) { - if (mFalsingManager.isFalseTap(FalsingManager.LOW_PENALTY)) { - return; - } - - if (mFeatureFlags.isEnabled(Flags.FULL_SCREEN_USER_SWITCHER)) { - Intent intent = new Intent(v.getContext(), UserSwitcherActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); - - mActivityStarter.startActivity(intent, true /* dismissShade */, - ActivityLaunchAnimator.Controller.fromView(v, null), - true /* showOverlockscreenwhenlocked */, UserHandle.SYSTEM); - } else { - mUserSwitchDialogController.showDialog(v.getContext(), Expandable.fromView(v)); - } - } - }; - - @QSScope - public static class Factory { - private final UserManager mUserManager; - private final UserSwitcherController mUserSwitcherController; - private final FalsingManager mFalsingManager; - private final UserSwitchDialogController mUserSwitchDialogController; - private final ActivityStarter mActivityStarter; - private final FeatureFlags mFeatureFlags; - - @Inject - public Factory(UserManager userManager, UserSwitcherController userSwitcherController, - FalsingManager falsingManager, - UserSwitchDialogController userSwitchDialogController, FeatureFlags featureFlags, - ActivityStarter activityStarter) { - mUserManager = userManager; - mUserSwitcherController = userSwitcherController; - mFalsingManager = falsingManager; - mUserSwitchDialogController = userSwitchDialogController; - mActivityStarter = activityStarter; - mFeatureFlags = featureFlags; - } - - public MultiUserSwitchController create(FooterActionsView view) { - return new MultiUserSwitchController(view.findViewById(R.id.multi_user_switch), - mUserManager, mUserSwitcherController, - mFalsingManager, mUserSwitchDialogController, mFeatureFlags, - mActivityStarter); - } - } - - private MultiUserSwitchController(MultiUserSwitch view, UserManager userManager, - UserSwitcherController userSwitcherController, - FalsingManager falsingManager, UserSwitchDialogController userSwitchDialogController, - FeatureFlags featureFlags, ActivityStarter activityStarter) { - super(view); - mUserManager = userManager; - mUserSwitcherController = userSwitcherController; - mFalsingManager = falsingManager; - mUserSwitchDialogController = userSwitchDialogController; - mFeatureFlags = featureFlags; - mActivityStarter = activityStarter; - } - - @Override - protected void onInit() { - registerListener(); - mView.refreshContentDescription(getCurrentUser()); - } - - @Override - protected void onViewAttached() { - mView.setOnClickListener(mOnClickListener); - } - - @Override - protected void onViewDetached() { - mView.setOnClickListener(null); - } - - private void registerListener() { - if (mUserManager.isUserSwitcherEnabled() && mUserListener == null) { - - final UserSwitcherController controller = mUserSwitcherController; - if (controller != null) { - mUserListener = new BaseUserSwitcherAdapter(controller) { - @Override - public void notifyDataSetChanged() { - mView.refreshContentDescription(getCurrentUser()); - } - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - return null; - } - }; - mView.refreshContentDescription(getCurrentUser()); - } - } - } - - private String getCurrentUser() { - // TODO(b/138661450) - if (whitelistIpcs(() -> mUserManager.isUserSwitcherEnabled())) { - return mUserSwitcherController.getCurrentUserName(); - } - - return null; - } - - /** Returns true if view should be made visible. */ - public boolean isMultiUserEnabled() { - // TODO(b/138661450) Move IPC calls to background - return whitelistIpcs(() -> mUserManager.isUserSwitcherEnabled( - getResources().getBoolean(R.bool.qs_show_user_switcher_for_single_user))); - } -} 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 0a0ded24ef30..df3ab493a4da 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarIconController.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarIconController.java @@ -536,8 +536,7 @@ public interface StatusBarIconController { mGroup.addView(view, index, onCreateLayoutParams()); if (mIsInDemoMode) { - // TODO (b/249790009): demo mode should be handled at the data layer in the - // new pipeline + mDemoStatusIcons.addModernMobileView(mContext, subId); } return view; @@ -565,11 +564,13 @@ public interface StatusBarIconController { private ModernStatusBarMobileView onCreateModernStatusBarMobileView( String slot, int subId) { + Context mobileContext = mMobileContextProvider.getMobileContextForSub(subId, mContext); return ModernStatusBarMobileView .constructAndBind( - mContext, + mobileContext, slot, - mMobileIconsViewModel.viewModelForSub(subId)); + mMobileIconsViewModel.viewModelForSub(subId) + ); } protected LinearLayout.LayoutParams onCreateLayoutParams() { @@ -704,7 +705,7 @@ public interface StatusBarIconController { } protected DemoStatusIcons createDemoStatusIcons() { - return new DemoStatusIcons((LinearLayout) mGroup, mIconSize); + return new DemoStatusIcons((LinearLayout) mGroup, mMobileIconsViewModel, mIconSize); } } } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarIconControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarIconControllerImpl.java index 674e5747e331..9fbe6cbc0e32 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarIconControllerImpl.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarIconControllerImpl.java @@ -276,6 +276,11 @@ public class StatusBarIconControllerImpl implements Tunable, String slotName = mContext.getString(com.android.internal.R.string.status_bar_mobile); Slot mobileSlot = mStatusBarIconList.getSlot(slotName); + // Because of the way we cache the icon holders, we need to remove everything any time + // we get a new set of subscriptions. This might change in the future, but is required + // to support demo mode for now + removeAllIconsForSlot(slotName); + Collections.reverse(subIds); for (Integer subId : subIds) { diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/model/MobileSubscriptionModel.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/model/MobileConnectionModel.kt index 6341a114112c..1d00c330c420 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/model/MobileSubscriptionModel.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/model/MobileConnectionModel.kt @@ -27,7 +27,6 @@ import android.telephony.TelephonyCallback.ServiceStateListener import android.telephony.TelephonyCallback.SignalStrengthsListener import android.telephony.TelephonyDisplayInfo import android.telephony.TelephonyManager -import android.telephony.TelephonyManager.NETWORK_TYPE_UNKNOWN import com.android.systemui.statusbar.pipeline.mobile.data.model.DataConnectionState.Disconnected /** @@ -39,7 +38,7 @@ import com.android.systemui.statusbar.pipeline.mobile.data.model.DataConnectionS * any new field that needs to be tracked should be copied into this data class rather than * threading complex system objects through the pipeline. */ -data class MobileSubscriptionModel( +data class MobileConnectionModel( /** From [ServiceStateListener.onServiceStateChanged] */ val isEmergencyOnly: Boolean = false, @@ -65,5 +64,5 @@ data class MobileSubscriptionModel( * [resolvedNetworkType] is the [TelephonyDisplayInfo.getOverrideNetworkType] if it exists or * [TelephonyDisplayInfo.getNetworkType]. This is used to look up the proper network type icon */ - val resolvedNetworkType: ResolvedNetworkType = DefaultNetworkType(NETWORK_TYPE_UNKNOWN), + val resolvedNetworkType: ResolvedNetworkType = ResolvedNetworkType.UnknownNetworkType, ) diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/model/ResolvedNetworkType.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/model/ResolvedNetworkType.kt index f385806c1b22..dd93541d7c8f 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/model/ResolvedNetworkType.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/model/ResolvedNetworkType.kt @@ -17,6 +17,7 @@ package com.android.systemui.statusbar.pipeline.mobile.data.model import android.telephony.Annotation.NetworkType +import android.telephony.TelephonyManager.NETWORK_TYPE_UNKNOWN import com.android.systemui.statusbar.pipeline.mobile.util.MobileMappingsProxy /** @@ -26,8 +27,20 @@ import com.android.systemui.statusbar.pipeline.mobile.util.MobileMappingsProxy */ sealed interface ResolvedNetworkType { @NetworkType val type: Int -} + val lookupKey: String + + object UnknownNetworkType : ResolvedNetworkType { + override val type: Int = NETWORK_TYPE_UNKNOWN + override val lookupKey: String = "unknown" + } -data class DefaultNetworkType(@NetworkType override val type: Int) : ResolvedNetworkType + data class DefaultNetworkType( + @NetworkType override val type: Int, + override val lookupKey: String, + ) : ResolvedNetworkType -data class OverrideNetworkType(@NetworkType override val type: Int) : ResolvedNetworkType + data class OverrideNetworkType( + @NetworkType override val type: Int, + override val lookupKey: String, + ) : ResolvedNetworkType +} diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/model/SubscriptionModel.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/model/SubscriptionModel.kt new file mode 100644 index 000000000000..2f34516285cf --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/model/SubscriptionModel.kt @@ -0,0 +1,32 @@ +/* + * 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.mobile.data.model + +/** + * SystemUI representation of [SubscriptionInfo]. Currently we only use two fields on the + * subscriptions themselves: subscriptionId and isOpportunistic. Any new fields that we need can be + * added below and provided in the repository classes + */ +data class SubscriptionModel( + val subscriptionId: Int, + /** + * True if the subscription that this model represents has [SubscriptionInfo.isOpportunistic]. + * Opportunistic networks are networks with limited coverage, and we use this bit to determine + * filtering in certain cases. See [MobileIconsInteractor] for the filtering logic + */ + val isOpportunistic: Boolean = false, +) diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt index f09456342f78..2621f997d486 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionRepository.kt @@ -20,7 +20,7 @@ import android.telephony.SubscriptionInfo import android.telephony.SubscriptionManager import android.telephony.TelephonyCallback import android.telephony.TelephonyManager -import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileSubscriptionModel +import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileConnectionModel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.StateFlow @@ -36,11 +36,13 @@ import kotlinx.coroutines.flow.StateFlow * eventually becomes a single icon in the status bar. */ interface MobileConnectionRepository { + /** The subscriptionId that this connection represents */ + val subId: Int /** * A flow that aggregates all necessary callbacks from [TelephonyCallback] into a single * listener + model. */ - val subscriptionModelFlow: Flow<MobileSubscriptionModel> + val connectionInfo: Flow<MobileConnectionModel> /** Observable tracking [TelephonyManager.isDataConnectionAllowed] */ val dataEnabled: StateFlow<Boolean> /** diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionsRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionsRepository.kt index 14200f090c87..aea85eb020bd 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionsRepository.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileConnectionsRepository.kt @@ -17,11 +17,10 @@ package com.android.systemui.statusbar.pipeline.mobile.data.repository import android.provider.Settings -import android.telephony.SubscriptionInfo import android.telephony.SubscriptionManager -import com.android.settingslib.mobile.MobileMappings -import com.android.settingslib.mobile.MobileMappings.Config +import com.android.settingslib.SignalIcon.MobileIconGroup import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileConnectivityModel +import com.android.systemui.statusbar.pipeline.mobile.data.model.SubscriptionModel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.StateFlow @@ -31,14 +30,11 @@ import kotlinx.coroutines.flow.StateFlow */ interface MobileConnectionsRepository { /** Observable list of current mobile subscriptions */ - val subscriptionsFlow: Flow<List<SubscriptionInfo>> + val subscriptions: StateFlow<List<SubscriptionModel>> /** Observable for the subscriptionId of the current mobile data connection */ val activeMobileDataSubscriptionId: StateFlow<Int> - /** Observable for [MobileMappings.Config] tracking the defaults */ - val defaultDataSubRatConfig: StateFlow<Config> - /** Tracks [SubscriptionManager.getDefaultDataSubscriptionId] */ val defaultDataSubId: StateFlow<Int> @@ -50,4 +46,10 @@ interface MobileConnectionsRepository { /** Observe changes to the [Settings.Global.MOBILE_DATA] setting */ val globalMobileDataSettingChangedEvent: Flow<Unit> + + /** The icon mapping from network type to [MobileIconGroup] for the default subscription */ + val defaultMobileIconMapping: Flow<Map<String, MobileIconGroup>> + + /** Fallback [MobileIconGroup] in the case where there is no icon in the mapping */ + val defaultMobileIconGroup: Flow<MobileIconGroup> } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileRepositorySwitcher.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileRepositorySwitcher.kt index e21400525f00..d8e0e81837c1 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileRepositorySwitcher.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileRepositorySwitcher.kt @@ -17,14 +17,14 @@ package com.android.systemui.statusbar.pipeline.mobile.data.repository import android.os.Bundle -import android.telephony.SubscriptionInfo import androidx.annotation.VisibleForTesting -import com.android.settingslib.mobile.MobileMappings +import com.android.settingslib.SignalIcon import com.android.systemui.common.coroutine.ConflatedCallbackFlow.conflatedCallbackFlow import com.android.systemui.dagger.qualifiers.Application import com.android.systemui.demomode.DemoMode import com.android.systemui.demomode.DemoModeController import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileConnectivityModel +import com.android.systemui.statusbar.pipeline.mobile.data.model.SubscriptionModel import com.android.systemui.statusbar.pipeline.mobile.data.repository.demo.DemoMobileConnectionsRepository import com.android.systemui.statusbar.pipeline.mobile.data.repository.prod.MobileConnectionsRepositoryImpl import javax.inject.Inject @@ -109,14 +109,10 @@ constructor( } .stateIn(scope, SharingStarted.WhileSubscribed(), realRepository) - override val subscriptionsFlow: StateFlow<List<SubscriptionInfo>> = + override val subscriptions: StateFlow<List<SubscriptionModel>> = activeRepo - .flatMapLatest { it.subscriptionsFlow } - .stateIn( - scope, - SharingStarted.WhileSubscribed(), - realRepository.subscriptionsFlow.value - ) + .flatMapLatest { it.subscriptions } + .stateIn(scope, SharingStarted.WhileSubscribed(), realRepository.subscriptions.value) override val activeMobileDataSubscriptionId: StateFlow<Int> = activeRepo @@ -127,14 +123,11 @@ constructor( realRepository.activeMobileDataSubscriptionId.value ) - override val defaultDataSubRatConfig: StateFlow<MobileMappings.Config> = - activeRepo - .flatMapLatest { it.defaultDataSubRatConfig } - .stateIn( - scope, - SharingStarted.WhileSubscribed(), - realRepository.defaultDataSubRatConfig.value - ) + override val defaultMobileIconMapping: Flow<Map<String, SignalIcon.MobileIconGroup>> = + activeRepo.flatMapLatest { it.defaultMobileIconMapping } + + override val defaultMobileIconGroup: Flow<SignalIcon.MobileIconGroup> = + activeRepo.flatMapLatest { it.defaultMobileIconGroup } override val defaultDataSubId: StateFlow<Int> = activeRepo diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionsRepository.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionsRepository.kt index 5f2feb26b739..1e7fae717a2d 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionsRepository.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionsRepository.kt @@ -17,26 +17,18 @@ package com.android.systemui.statusbar.pipeline.mobile.data.repository.demo import android.content.Context -import android.telephony.Annotation -import android.telephony.SubscriptionInfo import android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID -import android.telephony.TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NR_ADVANCED -import android.telephony.TelephonyManager.NETWORK_TYPE_GSM -import android.telephony.TelephonyManager.NETWORK_TYPE_LTE -import android.telephony.TelephonyManager.NETWORK_TYPE_NR -import android.telephony.TelephonyManager.NETWORK_TYPE_UMTS -import android.telephony.TelephonyManager.NETWORK_TYPE_UNKNOWN import android.util.Log import com.android.settingslib.SignalIcon import com.android.settingslib.mobile.MobileMappings import com.android.settingslib.mobile.TelephonyIcons import com.android.systemui.dagger.qualifiers.Application import com.android.systemui.statusbar.pipeline.mobile.data.model.DataConnectionState -import com.android.systemui.statusbar.pipeline.mobile.data.model.DefaultNetworkType +import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileConnectionModel import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileConnectivityModel -import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileSubscriptionModel -import com.android.systemui.statusbar.pipeline.mobile.data.model.OverrideNetworkType import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType +import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType.DefaultNetworkType +import com.android.systemui.statusbar.pipeline.mobile.data.model.SubscriptionModel import com.android.systemui.statusbar.pipeline.mobile.data.repository.MobileConnectionRepository import com.android.systemui.statusbar.pipeline.mobile.data.repository.MobileConnectionsRepository import com.android.systemui.statusbar.pipeline.mobile.data.repository.demo.model.FakeNetworkEventModel @@ -49,7 +41,9 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.filterNotNull +import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.stateIn @@ -67,61 +61,40 @@ constructor( private var demoCommandJob: Job? = null - private val connectionRepoCache = mutableMapOf<Int, DemoMobileConnectionRepository>() - private val subscriptionInfoCache = mutableMapOf<Int, SubscriptionInfo>() + private var connectionRepoCache = mutableMapOf<Int, DemoMobileConnectionRepository>() + private val subscriptionInfoCache = mutableMapOf<Int, SubscriptionModel>() val demoModeFinishedEvent = MutableSharedFlow<Unit>(extraBufferCapacity = 1) - private val _subscriptions = MutableStateFlow<List<SubscriptionInfo>>(listOf()) - override val subscriptionsFlow = + private val _subscriptions = MutableStateFlow<List<SubscriptionModel>>(listOf()) + override val subscriptions = _subscriptions .onEach { infos -> dropUnusedReposFromCache(infos) } .stateIn(scope, SharingStarted.WhileSubscribed(), _subscriptions.value) - private fun dropUnusedReposFromCache(newInfos: List<SubscriptionInfo>) { + private fun dropUnusedReposFromCache(newInfos: List<SubscriptionModel>) { // Remove any connection repository from the cache that isn't in the new set of IDs. They // will get garbage collected once their subscribers go away val currentValidSubscriptionIds = newInfos.map { it.subscriptionId } - connectionRepoCache.keys.forEach { - if (!currentValidSubscriptionIds.contains(it)) { - connectionRepoCache.remove(it) - } - } + connectionRepoCache = + connectionRepoCache + .filter { currentValidSubscriptionIds.contains(it.key) } + .toMutableMap() } private fun maybeCreateSubscription(subId: Int) { if (!subscriptionInfoCache.containsKey(subId)) { - createSubscriptionForSubId(subId, subId).also { subscriptionInfoCache[subId] = it } + SubscriptionModel(subscriptionId = subId, isOpportunistic = false).also { + subscriptionInfoCache[subId] = it + } _subscriptions.value = subscriptionInfoCache.values.toList() } } - /** Mimics the old NetworkControllerImpl for now */ - private fun createSubscriptionForSubId(subId: Int, slotIndex: Int): SubscriptionInfo { - return SubscriptionInfo( - subId, - "", - slotIndex, - "", - "", - 0, - 0, - "", - 0, - null, - null, - null, - "", - false, - null, - null, - ) - } - // TODO(b/261029387): add a command for this value override val activeMobileDataSubscriptionId = - subscriptionsFlow + subscriptions .mapLatest { infos -> // For now, active is just the first in the list infos.firstOrNull()?.subscriptionId ?: INVALID_SUBSCRIPTION_ID @@ -129,12 +102,35 @@ constructor( .stateIn( scope, SharingStarted.WhileSubscribed(), - subscriptionsFlow.value.firstOrNull()?.subscriptionId ?: INVALID_SUBSCRIPTION_ID + subscriptions.value.firstOrNull()?.subscriptionId ?: INVALID_SUBSCRIPTION_ID ) /** Demo mode doesn't currently support modifications to the mobile mappings */ - override val defaultDataSubRatConfig = - MutableStateFlow(MobileMappings.Config.readConfig(context)) + val defaultDataSubRatConfig = MutableStateFlow(MobileMappings.Config.readConfig(context)) + + override val defaultMobileIconGroup = flowOf(TelephonyIcons.THREE_G) + + override val defaultMobileIconMapping = MutableStateFlow(TelephonyIcons.ICON_NAME_TO_ICON) + + /** + * In order to maintain compatibility with the old demo mode shell command API, reverse the + * [MobileMappings] lookup from (NetworkType: String -> Icon: MobileIconGroup), so that we can + * parse the string from the command line into a preferred icon group, and send _a_ valid + * network type for that icon through the pipeline. + * + * Note: collisions don't matter here, because the data source (the command line) only cares + * about the resulting icon, not the underlying network type. + */ + private val mobileMappingsReverseLookup: StateFlow<Map<SignalIcon.MobileIconGroup, String>> = + defaultMobileIconMapping + .mapLatest { networkToIconMap -> networkToIconMap.reverse() } + .stateIn( + scope, + SharingStarted.WhileSubscribed(), + defaultMobileIconMapping.value.reverse() + ) + + private fun <K, V> Map<K, V>.reverse() = entries.associateBy({ it.value }) { it.key } // TODO(b/261029387): add a command for this value override val defaultDataSubId = @@ -189,7 +185,7 @@ constructor( connection.dataEnabled.value = true connection.isDefaultDataSubscription.value = state.dataType != null - connection.subscriptionModelFlow.value = state.toMobileSubscriptionModel() + connection.connectionInfo.value = state.toMobileConnectionModel() } private fun processDisabledMobileState(state: MobileDisabled) { @@ -229,47 +225,36 @@ constructor( private fun subIdsString(): String = _subscriptions.value.joinToString(",") { it.subscriptionId.toString() } - companion object { - private const val TAG = "DemoMobileConnectionsRepo" + private fun Mobile.toMobileConnectionModel(): MobileConnectionModel { + return MobileConnectionModel( + isEmergencyOnly = false, // TODO(b/261029387): not yet supported + isGsm = false, // TODO(b/261029387): not yet supported + cdmaLevel = level ?: 0, + primaryLevel = level ?: 0, + dataConnectionState = + DataConnectionState.Connected, // TODO(b/261029387): not yet supported + dataActivityDirection = activity, + carrierNetworkChangeActive = carrierNetworkChange, + resolvedNetworkType = dataType.toResolvedNetworkType() + ) + } - private const val DEFAULT_SUB_ID = 1 + private fun SignalIcon.MobileIconGroup?.toResolvedNetworkType(): ResolvedNetworkType { + val key = mobileMappingsReverseLookup.value[this] ?: "dis" + return DefaultNetworkType(DEMO_NET_TYPE, key) } -} -private fun Mobile.toMobileSubscriptionModel(): MobileSubscriptionModel { - return MobileSubscriptionModel( - isEmergencyOnly = false, // TODO(b/261029387): not yet supported - isGsm = false, // TODO(b/261029387): not yet supported - cdmaLevel = level ?: 0, - primaryLevel = level ?: 0, - dataConnectionState = DataConnectionState.Connected, // TODO(b/261029387): not yet supported - dataActivityDirection = activity, - carrierNetworkChangeActive = carrierNetworkChange, - // TODO(b/261185097): once mobile mappings can be mocked at this layer, we can build our - // own demo map - resolvedNetworkType = dataType.toResolvedNetworkType() - ) -} + companion object { + private const val TAG = "DemoMobileConnectionsRepo" -@Annotation.NetworkType -private fun SignalIcon.MobileIconGroup?.toNetworkType(): Int = - when (this) { - TelephonyIcons.THREE_G -> NETWORK_TYPE_GSM - TelephonyIcons.LTE -> NETWORK_TYPE_LTE - TelephonyIcons.FOUR_G -> NETWORK_TYPE_UMTS - TelephonyIcons.NR_5G -> NETWORK_TYPE_NR - TelephonyIcons.NR_5G_PLUS -> OVERRIDE_NETWORK_TYPE_NR_ADVANCED - else -> NETWORK_TYPE_UNKNOWN - } + private const val DEFAULT_SUB_ID = 1 -private fun SignalIcon.MobileIconGroup?.toResolvedNetworkType(): ResolvedNetworkType = - when (this) { - TelephonyIcons.NR_5G_PLUS -> OverrideNetworkType(toNetworkType()) - else -> DefaultNetworkType(toNetworkType()) + private const val DEMO_NET_TYPE = 1234 } +} -class DemoMobileConnectionRepository(val subId: Int) : MobileConnectionRepository { - override val subscriptionModelFlow = MutableStateFlow(MobileSubscriptionModel()) +class DemoMobileConnectionRepository(override val subId: Int) : MobileConnectionRepository { + override val connectionInfo = MutableStateFlow(MobileConnectionModel()) override val dataEnabled = MutableStateFlow(true) diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryImpl.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryImpl.kt index 4c1cf4a3ed08..15505fd3d9e5 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryImpl.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryImpl.kt @@ -27,18 +27,20 @@ import android.telephony.TelephonyCallback import android.telephony.TelephonyDisplayInfo import android.telephony.TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE import android.telephony.TelephonyManager +import android.telephony.TelephonyManager.NETWORK_TYPE_UNKNOWN import com.android.systemui.common.coroutine.ConflatedCallbackFlow.conflatedCallbackFlow import com.android.systemui.dagger.qualifiers.Application import com.android.systemui.dagger.qualifiers.Background -import com.android.systemui.statusbar.pipeline.mobile.data.model.DefaultNetworkType -import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileSubscriptionModel -import com.android.systemui.statusbar.pipeline.mobile.data.model.OverrideNetworkType +import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileConnectionModel +import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType.DefaultNetworkType +import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType.OverrideNetworkType +import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType.UnknownNetworkType import com.android.systemui.statusbar.pipeline.mobile.data.model.toDataConnectionType import com.android.systemui.statusbar.pipeline.mobile.data.repository.MobileConnectionRepository +import com.android.systemui.statusbar.pipeline.mobile.util.MobileMappingsProxy import com.android.systemui.statusbar.pipeline.shared.ConnectivityPipelineLogger import com.android.systemui.statusbar.pipeline.shared.ConnectivityPipelineLogger.Companion.logOutputChange import com.android.systemui.util.settings.GlobalSettings -import java.lang.IllegalStateException import javax.inject.Inject import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope @@ -58,11 +60,12 @@ import kotlinx.coroutines.flow.stateIn @OptIn(ExperimentalCoroutinesApi::class) class MobileConnectionRepositoryImpl( private val context: Context, - private val subId: Int, + override val subId: Int, private val telephonyManager: TelephonyManager, private val globalSettings: GlobalSettings, defaultDataSubId: StateFlow<Int>, globalMobileDataSettingChangedEvent: Flow<Unit>, + mobileMappingsProxy: MobileMappingsProxy, bgDispatcher: CoroutineDispatcher, logger: ConnectivityPipelineLogger, scope: CoroutineScope, @@ -78,8 +81,8 @@ class MobileConnectionRepositoryImpl( private val telephonyCallbackEvent = MutableSharedFlow<Unit>(extraBufferCapacity = 1) - override val subscriptionModelFlow: StateFlow<MobileSubscriptionModel> = run { - var state = MobileSubscriptionModel() + override val connectionInfo: StateFlow<MobileConnectionModel> = run { + var state = MobileConnectionModel() conflatedCallbackFlow { // TODO (b/240569788): log all of these into the connectivity logger val callback = @@ -141,14 +144,27 @@ class MobileConnectionRepositoryImpl( override fun onDisplayInfoChanged( telephonyDisplayInfo: TelephonyDisplayInfo ) { + val networkType = - if ( + if (telephonyDisplayInfo.networkType == NETWORK_TYPE_UNKNOWN) { + UnknownNetworkType + } else if ( telephonyDisplayInfo.overrideNetworkType == OVERRIDE_NETWORK_TYPE_NONE ) { - DefaultNetworkType(telephonyDisplayInfo.networkType) + DefaultNetworkType( + telephonyDisplayInfo.networkType, + mobileMappingsProxy.toIconKey( + telephonyDisplayInfo.networkType + ) + ) } else { - OverrideNetworkType(telephonyDisplayInfo.overrideNetworkType) + OverrideNetworkType( + telephonyDisplayInfo.overrideNetworkType, + mobileMappingsProxy.toIconKeyOverride( + telephonyDisplayInfo.overrideNetworkType + ) + ) } state = state.copy(resolvedNetworkType = networkType) trySend(state) @@ -211,6 +227,7 @@ class MobileConnectionRepositoryImpl( private val telephonyManager: TelephonyManager, private val logger: ConnectivityPipelineLogger, private val globalSettings: GlobalSettings, + private val mobileMappingsProxy: MobileMappingsProxy, @Background private val bgDispatcher: CoroutineDispatcher, @Application private val scope: CoroutineScope, ) { @@ -226,6 +243,7 @@ class MobileConnectionRepositoryImpl( globalSettings, defaultDataSubId, globalMobileDataSettingChangedEvent, + mobileMappingsProxy, bgDispatcher, logger, scope, diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryImpl.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryImpl.kt index 08d6010f0d99..f27a9c9cca98 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryImpl.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryImpl.kt @@ -36,6 +36,7 @@ import android.telephony.TelephonyCallback.ActiveDataSubscriptionIdListener import android.telephony.TelephonyManager import androidx.annotation.VisibleForTesting import com.android.internal.telephony.PhoneConstants +import com.android.settingslib.SignalIcon.MobileIconGroup import com.android.settingslib.mobile.MobileMappings import com.android.settingslib.mobile.MobileMappings.Config import com.android.systemui.broadcast.BroadcastDispatcher @@ -44,8 +45,10 @@ import com.android.systemui.dagger.SysUISingleton import com.android.systemui.dagger.qualifiers.Application import com.android.systemui.dagger.qualifiers.Background import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileConnectivityModel +import com.android.systemui.statusbar.pipeline.mobile.data.model.SubscriptionModel import com.android.systemui.statusbar.pipeline.mobile.data.repository.MobileConnectionRepository import com.android.systemui.statusbar.pipeline.mobile.data.repository.MobileConnectionsRepository +import com.android.systemui.statusbar.pipeline.mobile.util.MobileMappingsProxy import com.android.systemui.statusbar.pipeline.shared.ConnectivityPipelineLogger import com.android.systemui.util.settings.GlobalSettings import javax.inject.Inject @@ -59,6 +62,7 @@ import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.onEach @@ -75,6 +79,7 @@ constructor( private val subscriptionManager: SubscriptionManager, private val telephonyManager: TelephonyManager, private val logger: ConnectivityPipelineLogger, + mobileMappingsProxy: MobileMappingsProxy, broadcastDispatcher: BroadcastDispatcher, private val globalSettings: GlobalSettings, private val context: Context, @@ -82,14 +87,14 @@ constructor( @Application private val scope: CoroutineScope, private val mobileConnectionRepositoryFactory: MobileConnectionRepositoryImpl.Factory ) : MobileConnectionsRepository { - private val subIdRepositoryCache: MutableMap<Int, MobileConnectionRepository> = mutableMapOf() + private var subIdRepositoryCache: MutableMap<Int, MobileConnectionRepository> = mutableMapOf() /** * State flow that emits the set of mobile data subscriptions, each represented by its own * [SubscriptionInfo]. We probably only need the [SubscriptionInfo.getSubscriptionId] of each * info object, but for now we keep track of the infos themselves. */ - override val subscriptionsFlow: StateFlow<List<SubscriptionInfo>> = + override val subscriptions: StateFlow<List<SubscriptionModel>> = conflatedCallbackFlow { val callback = object : SubscriptionManager.OnSubscriptionsChangedListener() { @@ -105,7 +110,7 @@ constructor( awaitClose { subscriptionManager.removeOnSubscriptionsChangedListener(callback) } } - .mapLatest { fetchSubscriptionsList() } + .mapLatest { fetchSubscriptionsList().map { it.toSubscriptionModel() } } .onEach { infos -> dropUnusedReposFromCache(infos) } .stateIn(scope, started = SharingStarted.WhileSubscribed(), listOf()) @@ -157,7 +162,7 @@ constructor( * * This flow will produce whenever the default data subscription or the carrier config changes. */ - override val defaultDataSubRatConfig: StateFlow<Config> = + private val defaultDataSubRatConfig: StateFlow<Config> = merge(defaultDataSubIdChangeEvent, carrierConfigChangedEvent) .mapLatest { Config.readConfig(context) } .stateIn( @@ -166,6 +171,12 @@ constructor( initialValue = Config.readConfig(context) ) + override val defaultMobileIconMapping: Flow<Map<String, MobileIconGroup>> = + defaultDataSubRatConfig.map { mobileMappingsProxy.mapIconSets(it) } + + override val defaultMobileIconGroup: Flow<MobileIconGroup> = + defaultDataSubRatConfig.map { mobileMappingsProxy.getDefaultIcons(it) } + override fun getRepoForSubId(subId: Int): MobileConnectionRepository { if (!isValidSubId(subId)) { throw IllegalArgumentException( @@ -229,7 +240,7 @@ constructor( .stateIn(scope, SharingStarted.WhileSubscribed(), MobileConnectivityModel()) private fun isValidSubId(subId: Int): Boolean { - subscriptionsFlow.value.forEach { + subscriptions.value.forEach { if (it.subscriptionId == subId) { return true } @@ -248,18 +259,23 @@ constructor( ) } - private fun dropUnusedReposFromCache(newInfos: List<SubscriptionInfo>) { + private fun dropUnusedReposFromCache(newInfos: List<SubscriptionModel>) { // Remove any connection repository from the cache that isn't in the new set of IDs. They // will get garbage collected once their subscribers go away val currentValidSubscriptionIds = newInfos.map { it.subscriptionId } - subIdRepositoryCache.keys.forEach { - if (!currentValidSubscriptionIds.contains(it)) { - subIdRepositoryCache.remove(it) - } - } + subIdRepositoryCache = + subIdRepositoryCache + .filter { currentValidSubscriptionIds.contains(it.key) } + .toMutableMap() } private suspend fun fetchSubscriptionsList(): List<SubscriptionInfo> = withContext(bgDispatcher) { subscriptionManager.completeActiveSubscriptionInfoList } + + private fun SubscriptionInfo.toSubscriptionModel(): SubscriptionModel = + SubscriptionModel( + subscriptionId = subscriptionId, + isOpportunistic = isOpportunistic, + ) } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt index 0da84f0bec9c..8e1197ca7c5c 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractor.kt @@ -20,10 +20,7 @@ import android.telephony.CarrierConfigManager import com.android.settingslib.SignalIcon.MobileIconGroup import com.android.systemui.dagger.qualifiers.Application import com.android.systemui.statusbar.pipeline.mobile.data.model.DataConnectionState.Connected -import com.android.systemui.statusbar.pipeline.mobile.data.model.DefaultNetworkType -import com.android.systemui.statusbar.pipeline.mobile.data.model.OverrideNetworkType import com.android.systemui.statusbar.pipeline.mobile.data.repository.MobileConnectionRepository -import com.android.systemui.statusbar.pipeline.mobile.util.MobileMappingsProxy import com.android.systemui.util.CarrierConfigTracker import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -70,10 +67,9 @@ class MobileIconInteractorImpl( defaultMobileIconMapping: StateFlow<Map<String, MobileIconGroup>>, defaultMobileIconGroup: StateFlow<MobileIconGroup>, override val isDefaultConnectionFailed: StateFlow<Boolean>, - mobileMappingsProxy: MobileMappingsProxy, connectionRepository: MobileConnectionRepository, ) : MobileIconInteractor { - private val mobileStatusInfo = connectionRepository.subscriptionModelFlow + private val connectionInfo = connectionRepository.connectionInfo override val isDataEnabled: StateFlow<Boolean> = connectionRepository.dataEnabled @@ -82,33 +78,27 @@ class MobileIconInteractorImpl( /** Observable for the current RAT indicator icon ([MobileIconGroup]) */ override val networkTypeIconGroup: StateFlow<MobileIconGroup> = combine( - mobileStatusInfo, + connectionInfo, defaultMobileIconMapping, defaultMobileIconGroup, ) { info, mapping, defaultGroup -> - val lookupKey = - when (val resolved = info.resolvedNetworkType) { - is DefaultNetworkType -> mobileMappingsProxy.toIconKey(resolved.type) - is OverrideNetworkType -> - mobileMappingsProxy.toIconKeyOverride(resolved.type) - } - mapping[lookupKey] ?: defaultGroup + mapping[info.resolvedNetworkType.lookupKey] ?: defaultGroup } .stateIn(scope, SharingStarted.WhileSubscribed(), defaultMobileIconGroup.value) override val isEmergencyOnly: StateFlow<Boolean> = - mobileStatusInfo + connectionInfo .mapLatest { it.isEmergencyOnly } .stateIn(scope, SharingStarted.WhileSubscribed(), false) override val level: StateFlow<Int> = - mobileStatusInfo - .mapLatest { mobileModel -> + connectionInfo + .mapLatest { connection -> // TODO: incorporate [MobileMappings.Config.alwaysShowCdmaRssi] - if (mobileModel.isGsm) { - mobileModel.primaryLevel + if (connection.isGsm) { + connection.primaryLevel } else { - mobileModel.cdmaLevel + connection.cdmaLevel } } .stateIn(scope, SharingStarted.WhileSubscribed(), 0) @@ -120,7 +110,7 @@ class MobileIconInteractorImpl( override val numberOfLevels: StateFlow<Int> = MutableStateFlow(4) override val isDataConnected: StateFlow<Boolean> = - mobileStatusInfo - .mapLatest { subscriptionModel -> subscriptionModel.dataConnectionState == Connected } + connectionInfo + .mapLatest { connection -> connection.dataConnectionState == Connected } .stateIn(scope, SharingStarted.WhileSubscribed(), false) } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractor.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractor.kt index a4175c3a6ab1..6f8fb2e2332b 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractor.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractor.kt @@ -17,17 +17,16 @@ package com.android.systemui.statusbar.pipeline.mobile.domain.interactor import android.telephony.CarrierConfigManager -import android.telephony.SubscriptionInfo import android.telephony.SubscriptionManager import android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID import com.android.settingslib.SignalIcon.MobileIconGroup import com.android.settingslib.mobile.TelephonyIcons import com.android.systemui.dagger.SysUISingleton import com.android.systemui.dagger.qualifiers.Application +import com.android.systemui.statusbar.pipeline.mobile.data.model.SubscriptionModel import com.android.systemui.statusbar.pipeline.mobile.data.repository.MobileConnectionRepository import com.android.systemui.statusbar.pipeline.mobile.data.repository.MobileConnectionsRepository import com.android.systemui.statusbar.pipeline.mobile.data.repository.UserSetupRepository -import com.android.systemui.statusbar.pipeline.mobile.util.MobileMappingsProxy import com.android.systemui.util.CarrierConfigTracker import javax.inject.Inject import kotlinx.coroutines.CoroutineScope @@ -53,7 +52,7 @@ import kotlinx.coroutines.flow.stateIn */ interface MobileIconsInteractor { /** List of subscriptions, potentially filtered for CBRS */ - val filteredSubscriptions: Flow<List<SubscriptionInfo>> + val filteredSubscriptions: Flow<List<SubscriptionModel>> /** True if the active mobile data subscription has data enabled */ val activeDataConnectionHasDataEnabled: StateFlow<Boolean> /** The icon mapping from network type to [MobileIconGroup] for the default subscription */ @@ -79,7 +78,6 @@ class MobileIconsInteractorImpl constructor( private val mobileConnectionsRepo: MobileConnectionsRepository, private val carrierConfigTracker: CarrierConfigTracker, - private val mobileMappingsProxy: MobileMappingsProxy, userSetupRepo: UserSetupRepository, @Application private val scope: CoroutineScope, ) : MobileIconsInteractor { @@ -102,8 +100,8 @@ constructor( .flatMapLatest { it?.dataEnabled ?: flowOf(false) } .stateIn(scope, SharingStarted.WhileSubscribed(), false) - private val unfilteredSubscriptions: Flow<List<SubscriptionInfo>> = - mobileConnectionsRepo.subscriptionsFlow + private val unfilteredSubscriptions: Flow<List<SubscriptionModel>> = + mobileConnectionsRepo.subscriptions /** * Generally, SystemUI wants to show iconography for each subscription that is listed by @@ -118,7 +116,7 @@ constructor( * [CarrierConfigManager.KEY_ALWAYS_SHOW_PRIMARY_SIGNAL_BAR_IN_OPPORTUNISTIC_NETWORK_BOOLEAN], * and by checking which subscription is opportunistic, or which one is active. */ - override val filteredSubscriptions: Flow<List<SubscriptionInfo>> = + override val filteredSubscriptions: Flow<List<SubscriptionModel>> = combine(unfilteredSubscriptions, activeMobileDataSubscriptionId) { unfilteredSubs, activeId -> // Based on the old logic, @@ -154,15 +152,19 @@ constructor( * subscription Id. This mapping is the same for every subscription. */ override val defaultMobileIconMapping: StateFlow<Map<String, MobileIconGroup>> = - mobileConnectionsRepo.defaultDataSubRatConfig - .mapLatest { mobileMappingsProxy.mapIconSets(it) } - .stateIn(scope, SharingStarted.WhileSubscribed(), initialValue = mapOf()) + mobileConnectionsRepo.defaultMobileIconMapping.stateIn( + scope, + SharingStarted.WhileSubscribed(), + initialValue = mapOf() + ) /** If there is no mapping in [defaultMobileIconMapping], then use this default icon group */ override val defaultMobileIconGroup: StateFlow<MobileIconGroup> = - mobileConnectionsRepo.defaultDataSubRatConfig - .mapLatest { mobileMappingsProxy.getDefaultIcons(it) } - .stateIn(scope, SharingStarted.WhileSubscribed(), initialValue = TelephonyIcons.G) + mobileConnectionsRepo.defaultMobileIconGroup.stateIn( + scope, + SharingStarted.WhileSubscribed(), + initialValue = TelephonyIcons.G + ) /** * We want to show an error state when cellular has actually failed to validate, but not if some @@ -189,7 +191,6 @@ constructor( defaultMobileIconMapping, defaultMobileIconGroup, isDefaultConnectionFailed, - mobileMappingsProxy, mobileConnectionsRepo.getRepoForSubId(subId), ) } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/MobileUiAdapter.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/MobileUiAdapter.kt index d9487bf92260..62fa723dbf04 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/MobileUiAdapter.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/MobileUiAdapter.kt @@ -56,8 +56,8 @@ constructor( private val statusBarPipelineFlags: StatusBarPipelineFlags, ) : CoreStartable { private val mobileSubIds: Flow<List<Int>> = - interactor.filteredSubscriptions.mapLatest { infos -> - infos.map { subscriptionInfo -> subscriptionInfo.subscriptionId } + interactor.filteredSubscriptions.mapLatest { subscriptions -> + subscriptions.map { subscriptionModel -> subscriptionModel.subscriptionId } } /** diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/view/ModernStatusBarMobileView.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/view/ModernStatusBarMobileView.kt index ec4fa9ca8128..0ab7bcd96844 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/view/ModernStatusBarMobileView.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/view/ModernStatusBarMobileView.kt @@ -32,6 +32,8 @@ class ModernStatusBarMobileView( attrs: AttributeSet?, ) : BaseStatusBarFrameLayout(context, attrs) { + var subId: Int = -1 + private lateinit var slot: String override fun getSlot() = slot @@ -76,6 +78,7 @@ class ModernStatusBarMobileView( as ModernStatusBarMobileView) .also { it.slot = slot + it.subId = viewModel.subscriptionId MobileIconBinder.bind(it, viewModel) } } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModel.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModel.kt index 24c1db995d50..2349cb7c5d80 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModel.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModel.kt @@ -23,7 +23,7 @@ import com.android.systemui.statusbar.pipeline.mobile.ui.view.ModernStatusBarMob import com.android.systemui.statusbar.pipeline.shared.ConnectivityPipelineLogger import javax.inject.Inject import kotlinx.coroutines.InternalCoroutinesApi -import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.StateFlow /** * View model for describing the system's current mobile cellular connections. The result is a list @@ -33,7 +33,7 @@ import kotlinx.coroutines.flow.Flow class MobileIconsViewModel @Inject constructor( - val subscriptionIdsFlow: Flow<List<Int>>, + val subscriptionIdsFlow: StateFlow<List<Int>>, private val interactor: MobileIconsInteractor, private val logger: ConnectivityPipelineLogger, ) { @@ -51,7 +51,7 @@ constructor( private val interactor: MobileIconsInteractor, private val logger: ConnectivityPipelineLogger, ) { - fun create(subscriptionIdsFlow: Flow<List<Int>>): MobileIconsViewModel { + fun create(subscriptionIdsFlow: StateFlow<List<Int>>): MobileIconsViewModel { return MobileIconsViewModel( subscriptionIdsFlow, interactor, diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceControlsControllerImpl.kt b/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceControlsControllerImpl.kt index 6c66f0bb1e47..341eb3b0425c 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceControlsControllerImpl.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/DeviceControlsControllerImpl.kt @@ -68,7 +68,6 @@ public class DeviceControlsControllerImpl @Inject constructor( internal const val PREFS_CONTROLS_SEEDING_COMPLETED = "SeedingCompleted" const val PREFS_CONTROLS_FILE = "controls_prefs" - internal const val PREFS_SETTINGS_DIALOG_ATTEMPTS = "show_settings_attempts" private const val SEEDING_MAX = 2 } diff --git a/packages/SystemUI/src/com/android/systemui/stylus/StylusManager.kt b/packages/SystemUI/src/com/android/systemui/stylus/StylusManager.kt new file mode 100644 index 000000000000..3e111e6de785 --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/stylus/StylusManager.kt @@ -0,0 +1,199 @@ +/* + * 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.stylus + +import android.bluetooth.BluetoothAdapter +import android.bluetooth.BluetoothDevice +import android.hardware.input.InputManager +import android.os.Handler +import android.util.ArrayMap +import android.util.Log +import android.view.InputDevice +import com.android.systemui.dagger.SysUISingleton +import com.android.systemui.dagger.qualifiers.Background +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.Executor +import javax.inject.Inject + +/** + * A class which keeps track of InputDevice events related to stylus devices, and notifies + * registered callbacks of stylus events. + */ +@SysUISingleton +class StylusManager +@Inject +constructor( + private val inputManager: InputManager, + private val bluetoothAdapter: BluetoothAdapter, + @Background private val handler: Handler, + @Background private val executor: Executor, +) : InputManager.InputDeviceListener, BluetoothAdapter.OnMetadataChangedListener { + + private val stylusCallbacks: CopyOnWriteArrayList<StylusCallback> = CopyOnWriteArrayList() + private val stylusBatteryCallbacks: CopyOnWriteArrayList<StylusBatteryCallback> = + CopyOnWriteArrayList() + // This map should only be accessed on the handler + private val inputDeviceAddressMap: MutableMap<Int, String?> = ArrayMap() + + /** + * Starts listening to InputManager InputDevice events. Will also load the InputManager snapshot + * at time of starting. + */ + fun startListener() { + addExistingStylusToMap() + inputManager.registerInputDeviceListener(this, handler) + } + + /** Registers a StylusCallback to listen to stylus events. */ + fun registerCallback(callback: StylusCallback) { + stylusCallbacks.add(callback) + } + + /** Unregisters a StylusCallback. If StylusCallback is not registered, is a no-op. */ + fun unregisterCallback(callback: StylusCallback) { + stylusCallbacks.remove(callback) + } + + fun registerBatteryCallback(callback: StylusBatteryCallback) { + stylusBatteryCallbacks.add(callback) + } + + fun unregisterBatteryCallback(callback: StylusBatteryCallback) { + stylusBatteryCallbacks.remove(callback) + } + + override fun onInputDeviceAdded(deviceId: Int) { + val device: InputDevice = inputManager.getInputDevice(deviceId) ?: return + if (!device.supportsSource(InputDevice.SOURCE_STYLUS)) return + + // TODO(b/257936830): get address once input api available + val btAddress: String? = null + inputDeviceAddressMap[deviceId] = btAddress + executeStylusCallbacks { cb -> cb.onStylusAdded(deviceId) } + + if (btAddress != null) { + onStylusBluetoothConnected(btAddress) + executeStylusCallbacks { cb -> cb.onStylusBluetoothConnected(deviceId, btAddress) } + } + } + + override fun onInputDeviceChanged(deviceId: Int) { + val device: InputDevice = inputManager.getInputDevice(deviceId) ?: return + if (!device.supportsSource(InputDevice.SOURCE_STYLUS)) return + + // TODO(b/257936830): get address once input api available + val currAddress: String? = null + val prevAddress: String? = inputDeviceAddressMap[deviceId] + inputDeviceAddressMap[deviceId] = currAddress + + if (prevAddress == null && currAddress != null) { + onStylusBluetoothConnected(currAddress) + executeStylusCallbacks { cb -> cb.onStylusBluetoothConnected(deviceId, currAddress) } + } + + if (prevAddress != null && currAddress == null) { + onStylusBluetoothDisconnected(prevAddress) + executeStylusCallbacks { cb -> cb.onStylusBluetoothDisconnected(deviceId, prevAddress) } + } + } + + override fun onInputDeviceRemoved(deviceId: Int) { + if (!inputDeviceAddressMap.contains(deviceId)) return + + val btAddress: String? = inputDeviceAddressMap[deviceId] + inputDeviceAddressMap.remove(deviceId) + if (btAddress != null) { + onStylusBluetoothDisconnected(btAddress) + executeStylusCallbacks { cb -> cb.onStylusBluetoothDisconnected(deviceId, btAddress) } + } + executeStylusCallbacks { cb -> cb.onStylusRemoved(deviceId) } + } + + override fun onMetadataChanged(device: BluetoothDevice, key: Int, value: ByteArray?) { + handler.post executeMetadataChanged@{ + if (key != BluetoothDevice.METADATA_MAIN_CHARGING || value == null) + return@executeMetadataChanged + + val inputDeviceId: Int = + inputDeviceAddressMap.filterValues { it == device.address }.keys.firstOrNull() + ?: return@executeMetadataChanged + + val isCharging = String(value) == "true" + + executeStylusBatteryCallbacks { cb -> + cb.onStylusBluetoothChargingStateChanged(inputDeviceId, device, isCharging) + } + } + } + + private fun onStylusBluetoothConnected(btAddress: String) { + val device: BluetoothDevice = bluetoothAdapter.getRemoteDevice(btAddress) ?: return + try { + bluetoothAdapter.addOnMetadataChangedListener(device, executor, this) + } catch (e: IllegalArgumentException) { + Log.e(TAG, "$e: Metadata listener already registered for device. Ignoring.") + } + } + + private fun onStylusBluetoothDisconnected(btAddress: String) { + val device: BluetoothDevice = bluetoothAdapter.getRemoteDevice(btAddress) ?: return + try { + bluetoothAdapter.removeOnMetadataChangedListener(device, this) + } catch (e: IllegalArgumentException) { + Log.e(TAG, "$e: Metadata listener does not exist for device. Ignoring.") + } + } + + private fun executeStylusCallbacks(run: (cb: StylusCallback) -> Unit) { + stylusCallbacks.forEach(run) + } + + private fun executeStylusBatteryCallbacks(run: (cb: StylusBatteryCallback) -> Unit) { + stylusBatteryCallbacks.forEach(run) + } + + private fun addExistingStylusToMap() { + for (deviceId: Int in inputManager.inputDeviceIds) { + val device: InputDevice = inputManager.getInputDevice(deviceId) ?: continue + if (device.supportsSource(InputDevice.SOURCE_STYLUS)) { + // TODO(b/257936830): get address once input api available + inputDeviceAddressMap[deviceId] = null + } + } + } + + /** Callback interface to receive events from the StylusManager. */ + interface StylusCallback { + fun onStylusAdded(deviceId: Int) {} + fun onStylusRemoved(deviceId: Int) {} + fun onStylusBluetoothConnected(deviceId: Int, btAddress: String) {} + fun onStylusBluetoothDisconnected(deviceId: Int, btAddress: String) {} + } + + /** Callback interface to receive stylus battery events from the StylusManager. */ + interface StylusBatteryCallback { + fun onStylusBluetoothChargingStateChanged( + inputDeviceId: Int, + btDevice: BluetoothDevice, + isCharging: Boolean + ) {} + } + + companion object { + private val TAG = StylusManager::class.simpleName.orEmpty() + } +} diff --git a/packages/SystemUI/src/com/android/systemui/temporarydisplay/chipbar/ChipbarCoordinator.kt b/packages/SystemUI/src/com/android/systemui/temporarydisplay/chipbar/ChipbarCoordinator.kt index fb17b693e17e..4d91e35856dc 100644 --- a/packages/SystemUI/src/com/android/systemui/temporarydisplay/chipbar/ChipbarCoordinator.kt +++ b/packages/SystemUI/src/com/android/systemui/temporarydisplay/chipbar/ChipbarCoordinator.kt @@ -34,8 +34,8 @@ import com.android.systemui.animation.ViewHierarchyAnimator import com.android.systemui.classifier.FalsingCollector import com.android.systemui.common.shared.model.ContentDescription.Companion.loadContentDescription import com.android.systemui.common.shared.model.Text.Companion.loadText -import com.android.systemui.common.ui.binder.IconViewBinder import com.android.systemui.common.ui.binder.TextViewBinder +import com.android.systemui.common.ui.binder.TintedIconViewBinder import com.android.systemui.dagger.SysUISingleton import com.android.systemui.dagger.qualifiers.Main import com.android.systemui.plugins.FalsingManager @@ -121,7 +121,7 @@ open class ChipbarCoordinator @Inject constructor( // ---- Start icon ---- val iconView = currentView.requireViewById<CachingIconView>(R.id.start_icon) - IconViewBinder.bind(newInfo.startIcon, iconView) + TintedIconViewBinder.bind(newInfo.startIcon, iconView) // ---- Text ---- val textView = currentView.requireViewById<TextView>(R.id.text) @@ -156,11 +156,14 @@ open class ChipbarCoordinator @Inject constructor( } // ---- Overall accessibility ---- - currentView.requireViewById<ViewGroup>( - R.id.chipbar_inner - ).contentDescription = - "${newInfo.startIcon.contentDescription.loadContentDescription(context)} " + - "${newInfo.text.loadText(context)}" + val iconDesc = newInfo.startIcon.icon.contentDescription + val loadedIconDesc = if (iconDesc != null) { + "${iconDesc.loadContentDescription(context)} " + } else { + "" + } + currentView.requireViewById<ViewGroup>(R.id.chipbar_inner).contentDescription = + "$loadedIconDesc${newInfo.text.loadText(context)}" // ---- Haptics ---- newInfo.vibrationEffect?.let { diff --git a/packages/SystemUI/src/com/android/systemui/temporarydisplay/chipbar/ChipbarInfo.kt b/packages/SystemUI/src/com/android/systemui/temporarydisplay/chipbar/ChipbarInfo.kt index b92e0ec0428f..a3eef8032b3b 100644 --- a/packages/SystemUI/src/com/android/systemui/temporarydisplay/chipbar/ChipbarInfo.kt +++ b/packages/SystemUI/src/com/android/systemui/temporarydisplay/chipbar/ChipbarInfo.kt @@ -18,8 +18,9 @@ package com.android.systemui.temporarydisplay.chipbar import android.os.VibrationEffect import android.view.View -import com.android.systemui.common.shared.model.Icon +import androidx.annotation.AttrRes import com.android.systemui.common.shared.model.Text +import com.android.systemui.common.shared.model.TintedIcon import com.android.systemui.temporarydisplay.TemporaryViewInfo /** @@ -33,7 +34,7 @@ import com.android.systemui.temporarydisplay.TemporaryViewInfo * @property vibrationEffect an optional vibration effect when the chipbar is displayed */ data class ChipbarInfo( - val startIcon: Icon, + val startIcon: TintedIcon, val text: Text, val endItem: ChipbarEndItem?, val vibrationEffect: VibrationEffect? = null, @@ -41,7 +42,11 @@ data class ChipbarInfo( override val wakeReason: String, override val timeoutMs: Int, override val id: String, -) : TemporaryViewInfo() +) : TemporaryViewInfo() { + companion object { + @AttrRes const val DEFAULT_ICON_TINT_ATTR = android.R.attr.textColorPrimary + } +} /** The possible items to display at the end of the chipbar. */ sealed class ChipbarEndItem { diff --git a/packages/SystemUI/src/com/android/systemui/unfold/SysUIUnfoldModule.kt b/packages/SystemUI/src/com/android/systemui/unfold/SysUIUnfoldModule.kt index 13ac39c77c93..209d93f786a2 100644 --- a/packages/SystemUI/src/com/android/systemui/unfold/SysUIUnfoldModule.kt +++ b/packages/SystemUI/src/com/android/systemui/unfold/SysUIUnfoldModule.kt @@ -92,5 +92,7 @@ interface SysUIUnfoldComponent { fun getUnfoldTransitionWallpaperController(): UnfoldTransitionWallpaperController + fun getUnfoldHapticsPlayer(): UnfoldHapticsPlayer + fun getUnfoldLightRevealOverlayAnimation(): UnfoldLightRevealOverlayAnimation } diff --git a/packages/SystemUI/src/com/android/systemui/unfold/UnfoldHapticsPlayer.kt b/packages/SystemUI/src/com/android/systemui/unfold/UnfoldHapticsPlayer.kt new file mode 100644 index 000000000000..7726d09cf971 --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/unfold/UnfoldHapticsPlayer.kt @@ -0,0 +1,93 @@ +package com.android.systemui.unfold + +import android.os.SystemProperties +import android.os.VibrationEffect +import android.os.Vibrator +import com.android.systemui.unfold.UnfoldTransitionProgressProvider.TransitionProgressListener +import javax.inject.Inject + +/** + * Class that plays a haptics effect during unfolding a foldable device + */ +@SysUIUnfoldScope +class UnfoldHapticsPlayer +@Inject +constructor( + unfoldTransitionProgressProvider: UnfoldTransitionProgressProvider, + private val vibrator: Vibrator? +) : TransitionProgressListener { + + init { + if (vibrator != null) { + // We don't need to remove the callback because we should listen to it + // the whole time when SystemUI process is alive + unfoldTransitionProgressProvider.addCallback(this) + } + } + + private var lastTransitionProgress = TRANSITION_PROGRESS_FULL_OPEN + + override fun onTransitionStarted() { + lastTransitionProgress = TRANSITION_PROGRESS_CLOSED + } + + override fun onTransitionProgress(progress: Float) { + lastTransitionProgress = progress + } + + override fun onTransitionFinishing() { + // Run haptics only if the animation is long enough to notice + if (lastTransitionProgress < TRANSITION_NOTICEABLE_THRESHOLD) { + playHaptics() + } + } + + override fun onTransitionFinished() { + lastTransitionProgress = TRANSITION_PROGRESS_FULL_OPEN + } + + private fun playHaptics() { + vibrator?.vibrate(effect) + } + + private val hapticsScale: Float + get() { + val intensityString = SystemProperties.get("persist.unfold.haptics_scale", "0.1") + return intensityString.toFloatOrNull() ?: 0.1f + } + + private val hapticsScaleTick: Float + get() { + val intensityString = + SystemProperties.get("persist.unfold.haptics_scale_end_tick", "0.6") + return intensityString.toFloatOrNull() ?: 0.6f + } + + private val primitivesCount: Int + get() { + val count = SystemProperties.get("persist.unfold.primitives_count", "18") + return count.toIntOrNull() ?: 18 + } + + private val effect: VibrationEffect by lazy { + val composition = + VibrationEffect.startComposition() + .addPrimitive(VibrationEffect.Composition.PRIMITIVE_TICK, 0F, 0) + + repeat(primitivesCount) { + composition.addPrimitive( + VibrationEffect.Composition.PRIMITIVE_LOW_TICK, + hapticsScale, + 0 + ) + } + + composition + .addPrimitive(VibrationEffect.Composition.PRIMITIVE_TICK, hapticsScaleTick) + .compose() + } +} + +private const val TRANSITION_PROGRESS_CLOSED = 0f +private const val TRANSITION_PROGRESS_FULL_OPEN = 1f +private const val TRANSITION_NOTICEABLE_THRESHOLD = 0.9f diff --git a/packages/SystemUI/src/com/android/systemui/user/domain/interactor/UserInteractor.kt b/packages/SystemUI/src/com/android/systemui/user/domain/interactor/UserInteractor.kt index 512fadf1384f..74295f0b8859 100644 --- a/packages/SystemUI/src/com/android/systemui/user/domain/interactor/UserInteractor.kt +++ b/packages/SystemUI/src/com/android/systemui/user/domain/interactor/UserInteractor.kt @@ -31,6 +31,7 @@ import android.os.UserHandle import android.os.UserManager import android.provider.Settings import android.util.Log +import com.android.internal.logging.UiEventLogger import com.android.internal.util.UserIcons import com.android.systemui.R import com.android.systemui.SystemUISecondaryUserService @@ -54,6 +55,7 @@ import com.android.systemui.user.domain.model.ShowDialogRequestModel import com.android.systemui.user.legacyhelper.data.LegacyUserDataHelper import com.android.systemui.user.shared.model.UserActionModel import com.android.systemui.user.shared.model.UserModel +import com.android.systemui.user.utils.MultiUserActionsEvent import com.android.systemui.util.kotlin.pairwise import java.io.PrintWriter import javax.inject.Inject @@ -93,6 +95,7 @@ constructor( private val activityManager: ActivityManager, private val refreshUsersScheduler: RefreshUsersScheduler, private val guestUserInteractor: GuestUserInteractor, + private val uiEventLogger: UiEventLogger, ) { /** * Defines interface for classes that can be notified when the state of users on the device is @@ -115,9 +118,7 @@ constructor( private val callbackMutex = Mutex() private val callbacks = mutableSetOf<UserCallback>() private val userInfos: Flow<List<UserInfo>> = - repository.userInfos.map { userInfos -> - userInfos.filter { it.isFull } - } + repository.userInfos.map { userInfos -> userInfos.filter { it.isFull } } /** List of current on-device users to select from. */ val users: Flow<List<UserModel>> @@ -427,14 +428,17 @@ constructor( dialogShower: UserSwitchDialogController.DialogShower? = null, ) { when (action) { - UserActionModel.ENTER_GUEST_MODE -> + UserActionModel.ENTER_GUEST_MODE -> { + uiEventLogger.log(MultiUserActionsEvent.CREATE_GUEST_FROM_USER_SWITCHER) guestUserInteractor.createAndSwitchTo( this::showDialog, this::dismissDialog, ) { userId -> selectUser(userId, dialogShower) } + } UserActionModel.ADD_USER -> { + uiEventLogger.log(MultiUserActionsEvent.CREATE_USER_FROM_USER_SWITCHER) val currentUser = repository.getSelectedUserInfo() showDialog( ShowDialogRequestModel.ShowAddUserDialog( @@ -445,7 +449,8 @@ constructor( ) ) } - UserActionModel.ADD_SUPERVISED_USER -> + UserActionModel.ADD_SUPERVISED_USER -> { + uiEventLogger.log(MultiUserActionsEvent.CREATE_RESTRICTED_USER_FROM_USER_SWITCHER) activityStarter.startActivity( Intent() .setAction(UserManager.ACTION_CREATE_SUPERVISED_USER) @@ -453,6 +458,7 @@ constructor( .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), /* dismissShade= */ true, ) + } UserActionModel.NAVIGATE_TO_USER_MANAGEMENT -> activityStarter.startActivity( Intent(Settings.ACTION_USER_SETTINGS), diff --git a/packages/SystemUI/src/com/android/systemui/user/utils/MultiUserActionsEvent.kt b/packages/SystemUI/src/com/android/systemui/user/utils/MultiUserActionsEvent.kt new file mode 100644 index 000000000000..bfedac9e6f2c --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/user/utils/MultiUserActionsEvent.kt @@ -0,0 +1,31 @@ +/* + * 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.user.utils + +import com.android.internal.logging.UiEvent +import com.android.internal.logging.UiEventLogger + +enum class MultiUserActionsEvent(val value: Int) : UiEventLogger.UiEventEnum { + @UiEvent(doc = "Add User tap from User Switcher.") CREATE_USER_FROM_USER_SWITCHER(1257), + @UiEvent(doc = "Add Guest tap from User Switcher.") CREATE_GUEST_FROM_USER_SWITCHER(1258), + @UiEvent(doc = "Add Restricted User tap from User Switcher.") + CREATE_RESTRICTED_USER_FROM_USER_SWITCHER(1259); + + override fun getId(): Int { + return value + } +} diff --git a/packages/SystemUI/src/com/android/systemui/wallpapers/ImageWallpaper.java b/packages/SystemUI/src/com/android/systemui/wallpapers/ImageWallpaper.java index 5df4a5b54ccc..aa4890015977 100644 --- a/packages/SystemUI/src/com/android/systemui/wallpapers/ImageWallpaper.java +++ b/packages/SystemUI/src/com/android/systemui/wallpapers/ImageWallpaper.java @@ -46,7 +46,6 @@ import androidx.annotation.NonNull; import com.android.internal.annotations.VisibleForTesting; import com.android.systemui.dagger.qualifiers.Background; -import com.android.systemui.dagger.qualifiers.Main; import com.android.systemui.flags.FeatureFlags; import com.android.systemui.util.concurrency.DelayableExecutor; import com.android.systemui.wallpapers.canvas.WallpaperLocalColorExtractor; @@ -58,7 +57,6 @@ import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.Executor; import javax.inject.Inject; @@ -89,17 +87,12 @@ public class ImageWallpaper extends WallpaperService { private final DelayableExecutor mBackgroundExecutor; private static final int DELAY_UNLOAD_BITMAP = 2000; - @Main - private final Executor mMainExecutor; - @Inject public ImageWallpaper(FeatureFlags featureFlags, - @Background DelayableExecutor backgroundExecutor, - @Main Executor mainExecutor) { + @Background DelayableExecutor backgroundExecutor) { super(); mFeatureFlags = featureFlags; mBackgroundExecutor = backgroundExecutor; - mMainExecutor = mainExecutor; } @Override @@ -672,13 +665,9 @@ public class ImageWallpaper extends WallpaperService { loadWallpaperAndDrawFrameInternal(); } else { mBitmapUsages++; - - // drawing is done on the main thread - mMainExecutor.execute(() -> { - drawFrameOnCanvas(mBitmap); - reportEngineShown(false); - unloadBitmapIfNotUsed(); - }); + drawFrameOnCanvas(mBitmap); + reportEngineShown(false); + unloadBitmapIfNotUsedInternal(); } } @@ -716,11 +705,15 @@ public class ImageWallpaper extends WallpaperService { private void unloadBitmapIfNotUsedSynchronized() { synchronized (mLock) { - mBitmapUsages -= 1; - if (mBitmapUsages <= 0) { - mBitmapUsages = 0; - unloadBitmapInternal(); - } + unloadBitmapIfNotUsedInternal(); + } + } + + private void unloadBitmapIfNotUsedInternal() { + mBitmapUsages -= 1; + if (mBitmapUsages <= 0) { + mBitmapUsages = 0; + unloadBitmapInternal(); } } diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardAbsKeyInputViewControllerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardAbsKeyInputViewControllerTest.java index 8bbaf3dff1e5..4903d31f89f4 100644 --- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardAbsKeyInputViewControllerTest.java +++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardAbsKeyInputViewControllerTest.java @@ -19,6 +19,7 @@ package com.android.keyguard; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; @@ -87,6 +88,7 @@ public class KeyguardAbsKeyInputViewControllerTest extends SysuiTestCase { when(mAbsKeyInputView.isAttachedToWindow()).thenReturn(true); when(mAbsKeyInputView.requireViewById(R.id.bouncer_message_area)) .thenReturn(mKeyguardMessageArea); + when(mAbsKeyInputView.getResources()).thenReturn(getContext().getResources()); mKeyguardAbsKeyInputViewController = new KeyguardAbsKeyInputViewController(mAbsKeyInputView, mKeyguardUpdateMonitor, mSecurityMode, mLockPatternUtils, mKeyguardSecurityCallback, mKeyguardMessageAreaControllerFactory, mLatencyTracker, mFalsingCollector, @@ -125,4 +127,22 @@ public class KeyguardAbsKeyInputViewControllerTest extends SysuiTestCase { verifyZeroInteractions(mKeyguardSecurityCallback); verifyZeroInteractions(mKeyguardMessageAreaController); } + + @Test + public void onPromptReasonNone_doesNotSetMessage() { + mKeyguardAbsKeyInputViewController.showPromptReason(0); + verify(mKeyguardMessageAreaController, never()).setMessage( + getContext().getResources().getString(R.string.kg_prompt_reason_restart_password), + false); + } + + @Test + public void onPromptReason_setsMessage() { + when(mAbsKeyInputView.getPromptReasonStringRes(1)).thenReturn( + R.string.kg_prompt_reason_restart_password); + mKeyguardAbsKeyInputViewController.showPromptReason(1); + verify(mKeyguardMessageAreaController).setMessage( + getContext().getResources().getString(R.string.kg_prompt_reason_restart_password), + false); + } } diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPasswordViewControllerTest.kt b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPasswordViewControllerTest.kt index d20be56d6c6b..d91279399341 100644 --- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPasswordViewControllerTest.kt +++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPasswordViewControllerTest.kt @@ -30,64 +30,54 @@ import com.android.systemui.util.concurrency.DelayableExecutor import org.junit.Before import org.junit.Test import org.junit.runner.RunWith +import org.mockito.ArgumentMatchers.anyBoolean +import org.mockito.ArgumentMatchers.anyString import org.mockito.Mock import org.mockito.Mockito -import org.mockito.Mockito.`when` import org.mockito.Mockito.never import org.mockito.Mockito.verify +import org.mockito.Mockito.`when` import org.mockito.MockitoAnnotations @SmallTest @RunWith(AndroidTestingRunner::class) @TestableLooper.RunWithLooper class KeyguardPasswordViewControllerTest : SysuiTestCase() { - @Mock - private lateinit var keyguardPasswordView: KeyguardPasswordView - @Mock - private lateinit var passwordEntry: EditText - @Mock - lateinit var keyguardUpdateMonitor: KeyguardUpdateMonitor - @Mock - lateinit var securityMode: KeyguardSecurityModel.SecurityMode - @Mock - lateinit var lockPatternUtils: LockPatternUtils - @Mock - lateinit var keyguardSecurityCallback: KeyguardSecurityCallback - @Mock - lateinit var messageAreaControllerFactory: KeyguardMessageAreaController.Factory - @Mock - lateinit var latencyTracker: LatencyTracker - @Mock - lateinit var inputMethodManager: InputMethodManager - @Mock - lateinit var emergencyButtonController: EmergencyButtonController - @Mock - lateinit var mainExecutor: DelayableExecutor - @Mock - lateinit var falsingCollector: FalsingCollector - @Mock - lateinit var keyguardViewController: KeyguardViewController - @Mock - private lateinit var mKeyguardMessageArea: BouncerKeyguardMessageArea - @Mock - private lateinit var mKeyguardMessageAreaController: - KeyguardMessageAreaController<BouncerKeyguardMessageArea> + @Mock private lateinit var keyguardPasswordView: KeyguardPasswordView + @Mock private lateinit var passwordEntry: EditText + @Mock lateinit var keyguardUpdateMonitor: KeyguardUpdateMonitor + @Mock lateinit var securityMode: KeyguardSecurityModel.SecurityMode + @Mock lateinit var lockPatternUtils: LockPatternUtils + @Mock lateinit var keyguardSecurityCallback: KeyguardSecurityCallback + @Mock lateinit var messageAreaControllerFactory: KeyguardMessageAreaController.Factory + @Mock lateinit var latencyTracker: LatencyTracker + @Mock lateinit var inputMethodManager: InputMethodManager + @Mock lateinit var emergencyButtonController: EmergencyButtonController + @Mock lateinit var mainExecutor: DelayableExecutor + @Mock lateinit var falsingCollector: FalsingCollector + @Mock lateinit var keyguardViewController: KeyguardViewController + @Mock private lateinit var mKeyguardMessageArea: BouncerKeyguardMessageArea + @Mock + private lateinit var mKeyguardMessageAreaController: + KeyguardMessageAreaController<BouncerKeyguardMessageArea> - private lateinit var keyguardPasswordViewController: KeyguardPasswordViewController + private lateinit var keyguardPasswordViewController: KeyguardPasswordViewController - @Before - fun setup() { - MockitoAnnotations.initMocks(this) - Mockito.`when`( - keyguardPasswordView - .requireViewById<BouncerKeyguardMessageArea>(R.id.bouncer_message_area) - ).thenReturn(mKeyguardMessageArea) - Mockito.`when`(messageAreaControllerFactory.create(mKeyguardMessageArea)) - .thenReturn(mKeyguardMessageAreaController) - Mockito.`when`(keyguardPasswordView.passwordTextViewId).thenReturn(R.id.passwordEntry) - Mockito.`when`(keyguardPasswordView.findViewById<EditText>(R.id.passwordEntry) - ).thenReturn(passwordEntry) - keyguardPasswordViewController = KeyguardPasswordViewController( + @Before + fun setup() { + MockitoAnnotations.initMocks(this) + Mockito.`when`( + keyguardPasswordView.requireViewById<BouncerKeyguardMessageArea>( + R.id.bouncer_message_area)) + .thenReturn(mKeyguardMessageArea) + Mockito.`when`(messageAreaControllerFactory.create(mKeyguardMessageArea)) + .thenReturn(mKeyguardMessageAreaController) + Mockito.`when`(keyguardPasswordView.passwordTextViewId).thenReturn(R.id.passwordEntry) + Mockito.`when`(keyguardPasswordView.findViewById<EditText>(R.id.passwordEntry)) + .thenReturn(passwordEntry) + `when`(keyguardPasswordView.resources).thenReturn(context.resources) + keyguardPasswordViewController = + KeyguardPasswordViewController( keyguardPasswordView, keyguardUpdateMonitor, securityMode, @@ -100,51 +90,48 @@ class KeyguardPasswordViewControllerTest : SysuiTestCase() { mainExecutor, mContext.resources, falsingCollector, - keyguardViewController - ) - } + keyguardViewController) + } - @Test - fun testFocusWhenBouncerIsShown() { - Mockito.`when`(keyguardViewController.isBouncerShowing).thenReturn(true) - Mockito.`when`(keyguardPasswordView.isShown).thenReturn(true) - keyguardPasswordViewController.onResume(KeyguardSecurityView.VIEW_REVEALED) - keyguardPasswordView.post { - verify(keyguardPasswordView).requestFocus() - verify(keyguardPasswordView).showKeyboard() - } + @Test + fun testFocusWhenBouncerIsShown() { + Mockito.`when`(keyguardViewController.isBouncerShowing).thenReturn(true) + Mockito.`when`(keyguardPasswordView.isShown).thenReturn(true) + keyguardPasswordViewController.onResume(KeyguardSecurityView.VIEW_REVEALED) + keyguardPasswordView.post { + verify(keyguardPasswordView).requestFocus() + verify(keyguardPasswordView).showKeyboard() } + } - @Test - fun testDoNotFocusWhenBouncerIsHidden() { - Mockito.`when`(keyguardViewController.isBouncerShowing).thenReturn(false) - Mockito.`when`(keyguardPasswordView.isShown).thenReturn(true) - keyguardPasswordViewController.onResume(KeyguardSecurityView.VIEW_REVEALED) - verify(keyguardPasswordView, never()).requestFocus() - } + @Test + fun testDoNotFocusWhenBouncerIsHidden() { + Mockito.`when`(keyguardViewController.isBouncerShowing).thenReturn(false) + Mockito.`when`(keyguardPasswordView.isShown).thenReturn(true) + keyguardPasswordViewController.onResume(KeyguardSecurityView.VIEW_REVEALED) + verify(keyguardPasswordView, never()).requestFocus() + } - @Test - fun testHideKeyboardWhenOnPause() { - keyguardPasswordViewController.onPause() - keyguardPasswordView.post { - verify(keyguardPasswordView).clearFocus() - verify(keyguardPasswordView).hideKeyboard() - } + @Test + fun testHideKeyboardWhenOnPause() { + keyguardPasswordViewController.onPause() + keyguardPasswordView.post { + verify(keyguardPasswordView).clearFocus() + verify(keyguardPasswordView).hideKeyboard() } + } - @Test - fun startAppearAnimation() { - keyguardPasswordViewController.startAppearAnimation() - verify(mKeyguardMessageAreaController).setMessage(R.string.keyguard_enter_your_password) - } + @Test + fun startAppearAnimation() { + keyguardPasswordViewController.startAppearAnimation() + verify(mKeyguardMessageAreaController) + .setMessage(context.resources.getString(R.string.keyguard_enter_your_password), false) + } - @Test - fun startAppearAnimation_withExistingMessage() { - `when`(mKeyguardMessageAreaController.message).thenReturn("Unlock to continue.") - keyguardPasswordViewController.startAppearAnimation() - verify( - mKeyguardMessageAreaController, - never() - ).setMessage(R.string.keyguard_enter_your_password) - } + @Test + fun startAppearAnimation_withExistingMessage() { + `when`(mKeyguardMessageAreaController.message).thenReturn("Unlock to continue.") + keyguardPasswordViewController.startAppearAnimation() + verify(mKeyguardMessageAreaController, never()).setMessage(anyString(), anyBoolean()) + } } diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPatternViewControllerTest.kt b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPatternViewControllerTest.kt index b3d1c8f909d8..85dbdb8330a3 100644 --- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPatternViewControllerTest.kt +++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPatternViewControllerTest.kt @@ -30,97 +30,93 @@ import com.android.systemui.statusbar.policy.DevicePostureController import org.junit.Before import org.junit.Test import org.junit.runner.RunWith +import org.mockito.ArgumentMatchers.anyBoolean +import org.mockito.ArgumentMatchers.anyString import org.mockito.Mock +import org.mockito.Mockito.never import org.mockito.Mockito.verify import org.mockito.Mockito.`when` -import org.mockito.Mockito.never import org.mockito.MockitoAnnotations @SmallTest @RunWith(AndroidTestingRunner::class) @TestableLooper.RunWithLooper class KeyguardPatternViewControllerTest : SysuiTestCase() { - @Mock - private lateinit var mKeyguardPatternView: KeyguardPatternView + @Mock private lateinit var mKeyguardPatternView: KeyguardPatternView - @Mock - private lateinit var mKeyguardUpdateMonitor: KeyguardUpdateMonitor + @Mock private lateinit var mKeyguardUpdateMonitor: KeyguardUpdateMonitor - @Mock - private lateinit var mSecurityMode: KeyguardSecurityModel.SecurityMode + @Mock private lateinit var mSecurityMode: KeyguardSecurityModel.SecurityMode - @Mock - private lateinit var mLockPatternUtils: LockPatternUtils + @Mock private lateinit var mLockPatternUtils: LockPatternUtils - @Mock - private lateinit var mKeyguardSecurityCallback: KeyguardSecurityCallback + @Mock private lateinit var mKeyguardSecurityCallback: KeyguardSecurityCallback - @Mock - private lateinit var mLatencyTracker: LatencyTracker - private var mFalsingCollector: FalsingCollector = FalsingCollectorFake() + @Mock private lateinit var mLatencyTracker: LatencyTracker + private var mFalsingCollector: FalsingCollector = FalsingCollectorFake() - @Mock - private lateinit var mEmergencyButtonController: EmergencyButtonController + @Mock private lateinit var mEmergencyButtonController: EmergencyButtonController - @Mock - private lateinit - var mKeyguardMessageAreaControllerFactory: KeyguardMessageAreaController.Factory + @Mock + private lateinit var mKeyguardMessageAreaControllerFactory: KeyguardMessageAreaController.Factory - @Mock - private lateinit var mKeyguardMessageArea: BouncerKeyguardMessageArea + @Mock private lateinit var mKeyguardMessageArea: BouncerKeyguardMessageArea - @Mock - private lateinit var mKeyguardMessageAreaController: - KeyguardMessageAreaController<BouncerKeyguardMessageArea> + @Mock + private lateinit var mKeyguardMessageAreaController: + KeyguardMessageAreaController<BouncerKeyguardMessageArea> - @Mock - private lateinit var mLockPatternView: LockPatternView + @Mock private lateinit var mLockPatternView: LockPatternView - @Mock - private lateinit var mPostureController: DevicePostureController + @Mock private lateinit var mPostureController: DevicePostureController - private lateinit var mKeyguardPatternViewController: KeyguardPatternViewController + private lateinit var mKeyguardPatternViewController: KeyguardPatternViewController - @Before - fun setup() { - MockitoAnnotations.initMocks(this) - `when`(mKeyguardPatternView.isAttachedToWindow).thenReturn(true) - `when`(mKeyguardPatternView - .requireViewById<BouncerKeyguardMessageArea>(R.id.bouncer_message_area)) - .thenReturn(mKeyguardMessageArea) - `when`(mKeyguardPatternView.findViewById<LockPatternView>(R.id.lockPatternView)) - .thenReturn(mLockPatternView) - `when`(mKeyguardMessageAreaControllerFactory.create(mKeyguardMessageArea)) - .thenReturn(mKeyguardMessageAreaController) - mKeyguardPatternViewController = KeyguardPatternViewController( + @Before + fun setup() { + MockitoAnnotations.initMocks(this) + `when`(mKeyguardPatternView.isAttachedToWindow).thenReturn(true) + `when`( + mKeyguardPatternView.requireViewById<BouncerKeyguardMessageArea>( + R.id.bouncer_message_area)) + .thenReturn(mKeyguardMessageArea) + `when`(mKeyguardPatternView.findViewById<LockPatternView>(R.id.lockPatternView)) + .thenReturn(mLockPatternView) + `when`(mKeyguardMessageAreaControllerFactory.create(mKeyguardMessageArea)) + .thenReturn(mKeyguardMessageAreaController) + `when`(mKeyguardPatternView.resources).thenReturn(context.resources) + mKeyguardPatternViewController = + KeyguardPatternViewController( mKeyguardPatternView, - mKeyguardUpdateMonitor, mSecurityMode, mLockPatternUtils, mKeyguardSecurityCallback, - mLatencyTracker, mFalsingCollector, mEmergencyButtonController, - mKeyguardMessageAreaControllerFactory, mPostureController - ) - } - - @Test - fun onPause_resetsText() { - mKeyguardPatternViewController.init() - mKeyguardPatternViewController.onPause() - verify(mKeyguardMessageAreaController).setMessage(R.string.keyguard_enter_your_pattern) - } - - - @Test - fun startAppearAnimation() { - mKeyguardPatternViewController.startAppearAnimation() - verify(mKeyguardMessageAreaController).setMessage(R.string.keyguard_enter_your_pattern) - } - - @Test - fun startAppearAnimation_withExistingMessage() { - `when`(mKeyguardMessageAreaController.message).thenReturn("Unlock to continue.") - mKeyguardPatternViewController.startAppearAnimation() - verify( - mKeyguardMessageAreaController, - never() - ).setMessage(R.string.keyguard_enter_your_password) - } + mKeyguardUpdateMonitor, + mSecurityMode, + mLockPatternUtils, + mKeyguardSecurityCallback, + mLatencyTracker, + mFalsingCollector, + mEmergencyButtonController, + mKeyguardMessageAreaControllerFactory, + mPostureController) + } + + @Test + fun onPause_resetsText() { + mKeyguardPatternViewController.init() + mKeyguardPatternViewController.onPause() + verify(mKeyguardMessageAreaController).setMessage(R.string.keyguard_enter_your_pattern) + } + + @Test + fun startAppearAnimation() { + mKeyguardPatternViewController.startAppearAnimation() + verify(mKeyguardMessageAreaController) + .setMessage(context.resources.getString(R.string.keyguard_enter_your_pattern), false) + } + + @Test + fun startAppearAnimation_withExistingMessage() { + `when`(mKeyguardMessageAreaController.message).thenReturn("Unlock to continue.") + mKeyguardPatternViewController.startAppearAnimation() + verify(mKeyguardMessageAreaController, never()).setMessage(anyString(), anyBoolean()) + } } diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPinViewControllerTest.kt b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPinViewControllerTest.kt index 8bcfe6f2b6f5..cdb7bbb9f823 100644 --- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPinViewControllerTest.kt +++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardPinViewControllerTest.kt @@ -31,10 +31,13 @@ import com.android.systemui.statusbar.policy.DevicePostureController import org.junit.Before import org.junit.Test import org.junit.runner.RunWith +import org.mockito.ArgumentMatchers.anyBoolean +import org.mockito.ArgumentMatchers.anyString import org.mockito.Mock import org.mockito.Mockito import org.mockito.Mockito.any import org.mockito.Mockito.verify +import org.mockito.Mockito.`when` import org.mockito.MockitoAnnotations @SmallTest @@ -79,6 +82,7 @@ class KeyguardPinViewControllerTest : SysuiTestCase() { keyguardMessageAreaControllerFactory.create(any(KeyguardMessageArea::class.java)) ) .thenReturn(keyguardMessageAreaController) + `when`(keyguardPinView.resources).thenReturn(context.resources) pinViewController = KeyguardPinViewController( keyguardPinView, @@ -98,14 +102,14 @@ class KeyguardPinViewControllerTest : SysuiTestCase() { @Test fun startAppearAnimation() { pinViewController.startAppearAnimation() - verify(keyguardMessageAreaController).setMessage(R.string.keyguard_enter_your_pin) + verify(keyguardMessageAreaController) + .setMessage(context.resources.getString(R.string.keyguard_enter_your_pin), false) } @Test fun startAppearAnimation_withExistingMessage() { Mockito.`when`(keyguardMessageAreaController.message).thenReturn("Unlock to continue.") pinViewController.startAppearAnimation() - verify(keyguardMessageAreaController, Mockito.never()) - .setMessage(R.string.keyguard_enter_your_password) + verify(keyguardMessageAreaController, Mockito.never()).setMessage(anyString(), anyBoolean()) } } diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java index 002da551046a..bdd29aa93b2c 100644 --- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java +++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java @@ -31,6 +31,7 @@ import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STR import static com.android.keyguard.FaceAuthApiRequestReason.NOTIFICATION_PANEL_CLICKED; import static com.android.keyguard.KeyguardUpdateMonitor.BIOMETRIC_STATE_CANCELLING_RESTARTING; import static com.android.keyguard.KeyguardUpdateMonitor.DEFAULT_CANCEL_SIGNAL_TIMEOUT; +import static com.android.keyguard.KeyguardUpdateMonitor.HAL_POWER_PRESS_TIMEOUT; import static com.android.keyguard.KeyguardUpdateMonitor.getCurrentUser; import static com.google.common.truth.Truth.assertThat; @@ -855,12 +856,21 @@ public class KeyguardUpdateMonitorTest extends SysuiTestCase { } @Test - public void testFingerprintPowerPressed_restartsFingerprintListeningStateImmediately() { + public void testFingerprintPowerPressed_restartsFingerprintListeningStateWithDelay() { mKeyguardUpdateMonitor.mFingerprintAuthenticationCallback .onAuthenticationError(FingerprintManager.BIOMETRIC_ERROR_POWER_PRESSED, ""); - verify(mFingerprintManager).authenticate(any(), any(), any(), any(), anyInt(), anyInt(), - anyInt()); + // THEN doesn't authenticate immediately + verify(mFingerprintManager, never()).authenticate(any(), + any(), any(), any(), anyInt(), anyInt(), anyInt()); + + // WHEN all messages (with delays) are processed + mTestableLooper.moveTimeForward(HAL_POWER_PRESS_TIMEOUT); + mTestableLooper.processAllMessages(); + + // THEN fingerprint manager attempts to authenticate again + verify(mFingerprintManager).authenticate(any(), + any(), any(), any(), anyInt(), anyInt(), anyInt()); } @Test diff --git a/packages/SystemUI/tests/src/com/android/systemui/accessibility/floatingmenu/MenuAnimationControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/accessibility/floatingmenu/MenuAnimationControllerTest.java index b2c52668e057..0cdd6e2ce85e 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/accessibility/floatingmenu/MenuAnimationControllerTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/accessibility/floatingmenu/MenuAnimationControllerTest.java @@ -20,8 +20,10 @@ import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; import android.graphics.PointF; import android.testing.AndroidTestingRunner; @@ -30,6 +32,10 @@ import android.view.View; import android.view.ViewPropertyAnimator; import android.view.WindowManager; +import androidx.dynamicanimation.animation.DynamicAnimation; +import androidx.dynamicanimation.animation.FlingAnimation; +import androidx.dynamicanimation.animation.SpringAnimation; +import androidx.dynamicanimation.animation.SpringForce; import androidx.test.filters.SmallTest; import com.android.systemui.Prefs; @@ -39,6 +45,9 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; + +import java.util.Optional; /** Tests for {@link MenuAnimationController}. */ @RunWith(AndroidTestingRunner.class) @@ -47,9 +56,10 @@ import org.junit.runner.RunWith; public class MenuAnimationControllerTest extends SysuiTestCase { private boolean mLastIsMoveToTucked; + private ArgumentCaptor<DynamicAnimation.OnAnimationEndListener> mEndListenerCaptor; private ViewPropertyAnimator mViewPropertyAnimator; private MenuView mMenuView; - private MenuAnimationController mMenuAnimationController; + private TestMenuAnimationController mMenuAnimationController; @Before public void setUp() throws Exception { @@ -62,15 +72,17 @@ public class MenuAnimationControllerTest extends SysuiTestCase { mViewPropertyAnimator = spy(mMenuView.animate()); doReturn(mViewPropertyAnimator).when(mMenuView).animate(); - mMenuAnimationController = new MenuAnimationController(mMenuView); + mMenuAnimationController = new TestMenuAnimationController(mMenuView); mLastIsMoveToTucked = Prefs.getBoolean(mContext, Prefs.Key.HAS_ACCESSIBILITY_FLOATING_MENU_TUCKED, /* defaultValue= */ false); + mEndListenerCaptor = ArgumentCaptor.forClass(DynamicAnimation.OnAnimationEndListener.class); } @After public void tearDown() throws Exception { Prefs.putBoolean(mContext, Prefs.Key.HAS_ACCESSIBILITY_FLOATING_MENU_TUCKED, mLastIsMoveToTucked); + mEndListenerCaptor.getAllValues().clear(); } @Test @@ -122,4 +134,115 @@ public class MenuAnimationControllerTest extends SysuiTestCase { assertThat(isMoveToTucked).isFalse(); } + + @Test + public void startTuckedAnimationPreview_hasAnimation() { + mMenuView.clearAnimation(); + + mMenuAnimationController.startTuckedAnimationPreview(); + + assertThat(mMenuView.getAnimation()).isNotNull(); + } + + @Test + public void startSpringAnimationsAndEndOneAnimation_notTriggerEndAction() { + final Runnable onSpringAnimationsEndCallback = mock(Runnable.class); + mMenuAnimationController.setSpringAnimationsEndAction(onSpringAnimationsEndCallback); + + setupAndRunSpringAnimations(); + final Optional<DynamicAnimation> anyAnimation = + mMenuAnimationController.mPositionAnimations.values().stream().findAny(); + anyAnimation.ifPresent(this::skipAnimationToEnd); + + verifyZeroInteractions(onSpringAnimationsEndCallback); + } + + @Test + public void startAndEndSpringAnimations_triggerEndAction() { + final Runnable onSpringAnimationsEndCallback = mock(Runnable.class); + mMenuAnimationController.setSpringAnimationsEndAction(onSpringAnimationsEndCallback); + + setupAndRunSpringAnimations(); + mMenuAnimationController.mPositionAnimations.values().forEach(this::skipAnimationToEnd); + + verify(onSpringAnimationsEndCallback).run(); + } + + @Test + public void flingThenSpringAnimationsAreEnded_triggerEndAction() { + final Runnable onSpringAnimationsEndCallback = mock(Runnable.class); + mMenuAnimationController.setSpringAnimationsEndAction(onSpringAnimationsEndCallback); + + mMenuAnimationController.flingMenuThenSpringToEdge(/* x= */ 0, /* velocityX= */ + 100, /* velocityY= */ 100); + mMenuAnimationController.mPositionAnimations.values() + .forEach(animation -> verify((FlingAnimation) animation).addEndListener( + mEndListenerCaptor.capture())); + mEndListenerCaptor.getAllValues() + .forEach(listener -> listener.onAnimationEnd(mock(DynamicAnimation.class), + /* canceled */ false, /* endValue */ 0, /* endVelocity */ 0)); + mMenuAnimationController.mPositionAnimations.values().forEach(this::skipAnimationToEnd); + + verify(onSpringAnimationsEndCallback).run(); + } + + @Test + public void existFlingIsRunningAndTheOtherAreEnd_notTriggerEndAction() { + final Runnable onSpringAnimationsEndCallback = mock(Runnable.class); + mMenuAnimationController.setSpringAnimationsEndAction(onSpringAnimationsEndCallback); + + mMenuAnimationController.flingMenuThenSpringToEdge(/* x= */ 0, /* velocityX= */ + 200, /* velocityY= */ 200); + mMenuAnimationController.mPositionAnimations.values() + .forEach(animation -> verify((FlingAnimation) animation).addEndListener( + mEndListenerCaptor.capture())); + final Optional<DynamicAnimation.OnAnimationEndListener> anyAnimation = + mEndListenerCaptor.getAllValues().stream().findAny(); + anyAnimation.ifPresent( + listener -> listener.onAnimationEnd(mock(DynamicAnimation.class), /* canceled */ + false, /* endValue */ 0, /* endVelocity */ 0)); + mMenuAnimationController.mPositionAnimations.values() + .stream() + .filter(animation -> animation instanceof SpringAnimation) + .forEach(this::skipAnimationToEnd); + + verifyZeroInteractions(onSpringAnimationsEndCallback); + } + + private void setupAndRunSpringAnimations() { + final float stiffness = 700f; + final float dampingRatio = 0.85f; + final float velocity = 100f; + final float finalPosition = 300f; + + mMenuAnimationController.springMenuWith(DynamicAnimation.TRANSLATION_X, new SpringForce() + .setStiffness(stiffness) + .setDampingRatio(dampingRatio), velocity, finalPosition); + mMenuAnimationController.springMenuWith(DynamicAnimation.TRANSLATION_Y, new SpringForce() + .setStiffness(stiffness) + .setDampingRatio(dampingRatio), velocity, finalPosition); + } + + private void skipAnimationToEnd(DynamicAnimation animation) { + final SpringAnimation springAnimation = ((SpringAnimation) animation); + // The doAnimationFrame function is used for skipping animation to the end. + springAnimation.doAnimationFrame(100); + springAnimation.skipToEnd(); + springAnimation.doAnimationFrame(200); + } + + /** + * Wrapper class for testing. + */ + private static class TestMenuAnimationController extends MenuAnimationController { + TestMenuAnimationController(MenuView menuView) { + super(menuView); + } + + @Override + FlingAnimation createFlingAnimation(MenuView menuView, + MenuPositionProperty menuPositionProperty) { + return spy(super.createFlingAnimation(menuView, menuPositionProperty)); + } + } } diff --git a/packages/SystemUI/tests/src/com/android/systemui/accessibility/floatingmenu/MenuEduTooltipViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/accessibility/floatingmenu/MenuEduTooltipViewTest.java new file mode 100644 index 000000000000..42b610a18bc0 --- /dev/null +++ b/packages/SystemUI/tests/src/com/android/systemui/accessibility/floatingmenu/MenuEduTooltipViewTest.java @@ -0,0 +1,105 @@ +/* + * 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.accessibility.floatingmenu; + +import static com.google.common.truth.Truth.assertThat; + +import android.content.res.Resources; +import android.testing.AndroidTestingRunner; +import android.testing.TestableLooper; +import android.view.WindowManager; +import android.widget.TextView; + +import androidx.test.filters.SmallTest; + +import com.android.systemui.R; +import com.android.systemui.SysuiTestCase; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +/** Tests for {@link MenuEduTooltipView}. */ +@SmallTest +@RunWith(AndroidTestingRunner.class) +@TestableLooper.RunWithLooper +public class MenuEduTooltipViewTest extends SysuiTestCase { + private MenuViewAppearance mMenuViewAppearance; + private MenuEduTooltipView mMenuEduTooltipView; + + @Before + public void setUp() throws Exception { + final WindowManager windowManager = mContext.getSystemService(WindowManager.class); + mMenuViewAppearance = new MenuViewAppearance(mContext, windowManager); + mMenuEduTooltipView = new MenuEduTooltipView(mContext, mMenuViewAppearance); + } + + @Test + public void show_matchMessageText() { + final CharSequence text = "Message"; + + mMenuEduTooltipView.show(text); + + final TextView messageView = mMenuEduTooltipView.findViewById(R.id.text); + assertThat(messageView.getText().toString().contentEquals(text)).isTrue(); + } + + @Test + public void show_menuOnLeft_onRightOfAnchor() { + mMenuViewAppearance.setPercentagePosition( + new Position(/* percentageX= */ 0.0f, /* percentageY= */ 0.0f)); + final CharSequence text = "Message"; + + mMenuEduTooltipView.show(text); + final int tooltipViewX = (int) (mMenuViewAppearance.getMenuPosition().x + + mMenuViewAppearance.getMenuWidth()); + + assertThat(mMenuEduTooltipView.getX()).isEqualTo(tooltipViewX); + } + + @Test + public void show_menuCloseToLeftOfCenter_onLeftOfAnchor() { + mMenuViewAppearance.setPercentagePosition( + new Position(/* percentageX= */ 0.4f, /* percentageY= */ 0.0f)); + final CharSequence text = "Message"; + + mMenuEduTooltipView.show(text); + final int tooltipViewX = (int) (mMenuViewAppearance.getMenuPosition().x + + mMenuViewAppearance.getMenuWidth()); + + assertThat(mMenuEduTooltipView.getX()).isEqualTo(tooltipViewX); + } + + @Test + public void show_menuOnRight_onLeftOfAnchor() { + mMenuViewAppearance.setPercentagePosition( + new Position(/* percentageX= */ 1.0f, /* percentageY= */ 0.0f)); + final Resources res = getContext().getResources(); + final int arrowWidth = + res.getDimensionPixelSize(R.dimen.accessibility_floating_tooltip_arrow_width); + final int arrowMargin = + res.getDimensionPixelSize(R.dimen.accessibility_floating_tooltip_arrow_margin); + final CharSequence text = "Message"; + + mMenuEduTooltipView.show(text); + final TextView messageView = mMenuEduTooltipView.findViewById(R.id.text); + final int layoutWidth = messageView.getMeasuredWidth() + arrowWidth + arrowMargin; + + assertThat(mMenuEduTooltipView.getX()).isEqualTo( + mMenuViewAppearance.getMenuPosition().x - layoutWidth); + } +} diff --git a/packages/SystemUI/tests/src/com/android/systemui/accessibility/floatingmenu/MenuListViewTouchHandlerTest.java b/packages/SystemUI/tests/src/com/android/systemui/accessibility/floatingmenu/MenuListViewTouchHandlerTest.java index 4acb394bee95..d29ebb86686f 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/accessibility/floatingmenu/MenuListViewTouchHandlerTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/accessibility/floatingmenu/MenuListViewTouchHandlerTest.java @@ -181,6 +181,20 @@ public class MenuListViewTouchHandlerTest extends SysuiTestCase { verify(mMenuAnimationController).moveToEdgeAndHide(); } + @Test + public void receiveActionDownMotionEvent_verifyOnActionDownEnd() { + final Runnable onActionDownEnd = mock(Runnable.class); + mTouchHandler.setOnActionDownEndListener(onActionDownEnd); + + final MotionEvent stubDownEvent = + mMotionEventHelper.obtainMotionEvent(/* downTime= */ 0, /* eventTime= */ 1, + MotionEvent.ACTION_DOWN, mStubMenuView.getTranslationX(), + mStubMenuView.getTranslationY()); + mTouchHandler.onInterceptTouchEvent(mStubListView, stubDownEvent); + + verify(onActionDownEnd).run(); + } + @After public void tearDown() { mMotionEventHelper.recycleEvents(); diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/UdfpsControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/biometrics/UdfpsControllerTest.java index b267a5c23a49..b061eb395119 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/UdfpsControllerTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/UdfpsControllerTest.java @@ -16,6 +16,7 @@ package com.android.systemui.biometrics; +import static android.hardware.biometrics.BiometricFingerprintConstants.FINGERPRINT_ACQUIRED_GOOD; import static android.view.MotionEvent.ACTION_DOWN; import static android.view.MotionEvent.ACTION_MOVE; import static android.view.MotionEvent.ACTION_UP; @@ -23,6 +24,8 @@ import static android.view.MotionEvent.ACTION_UP; import static com.android.internal.util.FunctionalUtils.ThrowingConsumer; import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; @@ -110,6 +113,8 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; +import javax.inject.Provider; + @SmallTest @RunWith(AndroidTestingRunner.class) @RunWithLooper(setAsMainLooper = true) @@ -122,7 +127,7 @@ public class UdfpsControllerTest extends SysuiTestCase { // Unit under test private UdfpsController mUdfpsController; // Dependencies - private FakeExecutor mBiometricsExecutor; + private FakeExecutor mBiometricExecutor; @Mock private LayoutInflater mLayoutInflater; @Mock @@ -210,6 +215,8 @@ public class UdfpsControllerTest extends SysuiTestCase { private ArgumentCaptor<Runnable> mOnDisplayConfiguredCaptor; @Captor private ArgumentCaptor<ScreenLifecycle.Observer> mScreenObserverCaptor; + @Captor + private ArgumentCaptor<UdfpsController.UdfpsOverlayController> mUdfpsOverlayControllerCaptor; private ScreenLifecycle.Observer mScreenObserver; private FingerprintSensorPropertiesInternal mOpticalProps; private FingerprintSensorPropertiesInternal mUltrasonicProps; @@ -256,11 +263,12 @@ public class UdfpsControllerTest extends SysuiTestCase { mFgExecutor = new FakeExecutor(new FakeSystemClock()); // Create a fake background executor. - mBiometricsExecutor = new FakeExecutor(new FakeSystemClock()); + mBiometricExecutor = new FakeExecutor(new FakeSystemClock()); initUdfpsController(true /* hasAlternateTouchProvider */); } + private void initUdfpsController(boolean hasAlternateTouchProvider) { initUdfpsController(mOpticalProps, hasAlternateTouchProvider); } @@ -270,8 +278,10 @@ public class UdfpsControllerTest extends SysuiTestCase { reset(mFingerprintManager); reset(mScreenLifecycle); - final Optional<AlternateUdfpsTouchProvider> alternateTouchProvider = - hasAlternateTouchProvider ? Optional.of(mAlternateTouchProvider) : Optional.empty(); + final Optional<Provider<AlternateUdfpsTouchProvider>> alternateTouchProvider = + hasAlternateTouchProvider ? Optional.of( + (Provider<AlternateUdfpsTouchProvider>) () -> mAlternateTouchProvider) + : Optional.empty(); mUdfpsController = new UdfpsController(mContext, new FakeExecution(), mLayoutInflater, mFingerprintManager, mWindowManager, mStatusBarStateController, mFgExecutor, @@ -281,7 +291,7 @@ public class UdfpsControllerTest extends SysuiTestCase { mVibrator, mUdfpsHapticsSimulator, mUdfpsShell, mKeyguardStateController, mDisplayManager, mHandler, mConfigurationController, mSystemClock, mUnlockedScreenOffAnimationController, mSystemUIDialogManager, mLatencyTracker, - mActivityLaunchAnimator, alternateTouchProvider, mBiometricsExecutor, + mActivityLaunchAnimator, alternateTouchProvider, mBiometricExecutor, mPrimaryBouncerInteractor, mSinglePointerTouchProcessor); verify(mFingerprintManager).setUdfpsOverlayController(mOverlayCaptor.capture()); mOverlayController = mOverlayCaptor.getValue(); @@ -317,7 +327,7 @@ public class UdfpsControllerTest extends SysuiTestCase { verify(mUdfpsView).setOnTouchListener(mTouchListenerCaptor.capture()); MotionEvent downEvent = MotionEvent.obtain(0, 0, ACTION_DOWN, 0, 0, 0); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, downEvent); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); downEvent.recycle(); // THEN notify keyguard authenticate to dismiss the keyguard @@ -355,7 +365,7 @@ public class UdfpsControllerTest extends SysuiTestCase { mFgExecutor.runAllReady(); } mTouchListenerCaptor.getValue().onTouch(mUdfpsView, moveEvent); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); moveEvent.recycle(); // THEN notify keyguard authenticate to dismiss the keyguard @@ -379,12 +389,12 @@ public class UdfpsControllerTest extends SysuiTestCase { verify(mUdfpsView).setOnTouchListener(mTouchListenerCaptor.capture()); MotionEvent downEvent = MotionEvent.obtain(0, 0, ACTION_DOWN, 0, 0, 0); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, downEvent); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); downEvent.recycle(); MotionEvent moveEvent = MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0, 0, 0); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, moveEvent); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, moveEvent); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); moveEvent.recycle(); // THEN notify keyguard authenticate to dismiss the keyguard @@ -573,11 +583,11 @@ public class UdfpsControllerTest extends SysuiTestCase { MotionEvent event = obtainMotionEvent(ACTION_DOWN, displayWidth, displayHeight, touchMinor, touchMajor); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, event); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); event.recycle(); event = obtainMotionEvent(ACTION_MOVE, displayWidth, displayHeight, touchMinor, touchMajor); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, event); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); event.recycle(); if (testParams.hasAlternateTouchProvider) { verify(mAlternateTouchProvider).onPointerDown(eq(TEST_REQUEST_ID), eq(expectedX), @@ -596,11 +606,11 @@ public class UdfpsControllerTest extends SysuiTestCase { scaleFactor, Surface.ROTATION_90)); event = obtainMotionEvent(ACTION_DOWN, displayHeight, 0, touchMinor, touchMajor); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, event); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); event.recycle(); event = obtainMotionEvent(ACTION_MOVE, displayHeight, 0, touchMinor, touchMajor); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, event); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); event.recycle(); if (testParams.hasAlternateTouchProvider) { verify(mAlternateTouchProvider).onPointerDown(eq(TEST_REQUEST_ID), eq(expectedX), @@ -619,11 +629,11 @@ public class UdfpsControllerTest extends SysuiTestCase { scaleFactor, Surface.ROTATION_270)); event = obtainMotionEvent(ACTION_DOWN, 0, displayWidth, touchMinor, touchMajor); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, event); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); event.recycle(); event = obtainMotionEvent(ACTION_MOVE, 0, displayWidth, touchMinor, touchMajor); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, event); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); event.recycle(); if (testParams.hasAlternateTouchProvider) { verify(mAlternateTouchProvider).onPointerDown(eq(TEST_REQUEST_ID), eq(expectedX), @@ -643,11 +653,11 @@ public class UdfpsControllerTest extends SysuiTestCase { // ROTATION_180 is not supported. It should be treated like ROTATION_0. event = obtainMotionEvent(ACTION_DOWN, displayWidth, displayHeight, touchMinor, touchMajor); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, event); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); event.recycle(); event = obtainMotionEvent(ACTION_MOVE, displayWidth, displayHeight, touchMinor, touchMajor); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, event); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); event.recycle(); if (testParams.hasAlternateTouchProvider) { verify(mAlternateTouchProvider).onPointerDown(eq(TEST_REQUEST_ID), eq(expectedX), @@ -682,12 +692,12 @@ public class UdfpsControllerTest extends SysuiTestCase { // WHEN ACTION_DOWN is received MotionEvent downEvent = MotionEvent.obtain(0, 0, ACTION_DOWN, 0, 0, 0); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, downEvent); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); downEvent.recycle(); MotionEvent moveEvent = MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0, 0, 0); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, moveEvent); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); moveEvent.recycle(); mFgExecutor.runAllReady(); @@ -720,7 +730,7 @@ public class UdfpsControllerTest extends SysuiTestCase { if (testParams.sensorProps.sensorType == FingerprintSensorProperties.TYPE_UDFPS_OPTICAL) { // AND onDisplayConfigured notifies FingerprintManager about onUiReady mOnDisplayConfiguredCaptor.getValue().run(); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); if (testParams.hasAlternateTouchProvider) { InOrder inOrder = inOrder(mAlternateTouchProvider, mLatencyTracker); inOrder.verify(mAlternateTouchProvider).onUiReady(); @@ -743,13 +753,15 @@ public class UdfpsControllerTest extends SysuiTestCase { } } + + @Test public void aodInterrupt() { runWithAllParams(this::aodInterruptParameterized); } private void aodInterruptParameterized(TestParams testParams) throws RemoteException { - mUdfpsController.cancelAodInterrupt(); + mUdfpsController.cancelAodSendFingerUpAction(); reset(mUdfpsView, mAlternateTouchProvider, mFingerprintManager, mKeyguardUpdateMonitor); when(mKeyguardUpdateMonitor.isFingerprintDetectionRunning()).thenReturn(true); @@ -769,7 +781,7 @@ public class UdfpsControllerTest extends SysuiTestCase { } else { verify(mUdfpsView, never()).configureDisplay(mOnDisplayConfiguredCaptor.capture()); } - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); if (testParams.hasAlternateTouchProvider) { verify(mAlternateTouchProvider).onPointerDown(eq(TEST_REQUEST_ID), eq(0), eq(0), @@ -787,7 +799,7 @@ public class UdfpsControllerTest extends SysuiTestCase { } @Test - public void cancelAodInterrupt() { + public void tryAodSendFingerUp_displayConfigurationChanges() { runWithAllParams(this::cancelAodInterruptParameterized); } @@ -803,24 +815,25 @@ public class UdfpsControllerTest extends SysuiTestCase { if (testParams.sensorProps.sensorType == FingerprintSensorProperties.TYPE_UDFPS_OPTICAL) { when(mUdfpsView.isDisplayConfigured()).thenReturn(true); // WHEN it is cancelled - mUdfpsController.cancelAodInterrupt(); + mUdfpsController.tryAodSendFingerUp(); // THEN the display is unconfigured verify(mUdfpsView).unconfigureDisplay(); } else { when(mUdfpsView.isDisplayConfigured()).thenReturn(false); // WHEN it is cancelled - mUdfpsController.cancelAodInterrupt(); + mUdfpsController.tryAodSendFingerUp(); // THEN the display configuration is unchanged. verify(mUdfpsView, never()).unconfigureDisplay(); } } @Test - public void aodInterruptTimeout() { - runWithAllParams(this::aodInterruptTimeoutParameterized); + public void onFingerUp_displayConfigurationChange() { + runWithAllParams(this::onFingerUp_displayConfigurationParameterized); } - private void aodInterruptTimeoutParameterized(TestParams testParams) throws RemoteException { + private void onFingerUp_displayConfigurationParameterized(TestParams testParams) + throws RemoteException { reset(mUdfpsView); // GIVEN AOD interrupt @@ -829,99 +842,105 @@ public class UdfpsControllerTest extends SysuiTestCase { mScreenObserver.onScreenTurnedOn(); mFgExecutor.runAllReady(); mUdfpsController.onAodInterrupt(0, 0, 0f, 0f); - mFgExecutor.runAllReady(); if (testParams.sensorProps.sensorType == FingerprintSensorProperties.TYPE_UDFPS_OPTICAL) { when(mUdfpsView.isDisplayConfigured()).thenReturn(true); - } else { - when(mUdfpsView.isDisplayConfigured()).thenReturn(false); - } - // WHEN it times out - mFgExecutor.advanceClockToNext(); - mFgExecutor.runAllReady(); - if (testParams.sensorProps.sensorType == FingerprintSensorProperties.TYPE_UDFPS_OPTICAL) { - // THEN the display is unconfigured. + + // WHEN up-action received + verify(mUdfpsView).setOnTouchListener(mTouchListenerCaptor.capture()); + MotionEvent upEvent = MotionEvent.obtain(0, 0, ACTION_UP, 0, 0, 0); + mTouchListenerCaptor.getValue().onTouch(mUdfpsView, upEvent); + mBiometricExecutor.runAllReady(); + upEvent.recycle(); + mFgExecutor.runAllReady(); + + // THEN the display is unconfigured verify(mUdfpsView).unconfigureDisplay(); } else { + when(mUdfpsView.isDisplayConfigured()).thenReturn(false); + + // WHEN up-action received + verify(mUdfpsView).setOnTouchListener(mTouchListenerCaptor.capture()); + MotionEvent upEvent = MotionEvent.obtain(0, 0, ACTION_UP, 0, 0, 0); + mTouchListenerCaptor.getValue().onTouch(mUdfpsView, upEvent); + mBiometricExecutor.runAllReady(); + upEvent.recycle(); + mFgExecutor.runAllReady(); + // THEN the display configuration is unchanged. verify(mUdfpsView, never()).unconfigureDisplay(); } } @Test - public void aodInterruptCancelTimeoutActionOnFingerUp() { - runWithAllParams(this::aodInterruptCancelTimeoutActionOnFingerUpParameterized); + public void onAcquiredGood_displayConfigurationChange() { + runWithAllParams(this::onAcquiredGood_displayConfigurationParameterized); } - private void aodInterruptCancelTimeoutActionOnFingerUpParameterized(TestParams testParams) + private void onAcquiredGood_displayConfigurationParameterized(TestParams testParams) throws RemoteException { reset(mUdfpsView); - when(mUdfpsView.isWithinSensorArea(anyFloat(), anyFloat())).thenReturn(true); - // GIVEN AOD interrupt + // GIVEN overlay is showing mOverlayController.showUdfpsOverlay(TEST_REQUEST_ID, testParams.sensorProps.sensorId, BiometricOverlayConstants.REASON_AUTH_KEYGUARD, mUdfpsOverlayControllerCallback); - mScreenObserver.onScreenTurnedOn(); - mFgExecutor.runAllReady(); - mUdfpsController.onAodInterrupt(0, 0, 0f, 0f); mFgExecutor.runAllReady(); - if (testParams.sensorProps.sensorType == FingerprintSensorProperties.TYPE_UDFPS_OPTICAL) { - // Configure UdfpsView to accept the ACTION_UP event when(mUdfpsView.isDisplayConfigured()).thenReturn(true); + // WHEN ACQUIRED_GOOD received + mOverlayController.onAcquired(testParams.sensorProps.sensorId, + BiometricFingerprintConstants.FINGERPRINT_ACQUIRED_GOOD); + mFgExecutor.runAllReady(); + // THEN the display is unconfigured + verify(mUdfpsView).unconfigureDisplay(); } else { when(mUdfpsView.isDisplayConfigured()).thenReturn(false); + // WHEN ACQUIRED_GOOD received + mOverlayController.onAcquired(testParams.sensorProps.sensorId, + BiometricFingerprintConstants.FINGERPRINT_ACQUIRED_GOOD); + mFgExecutor.runAllReady(); + // THEN the display configuration is unchanged. + verify(mUdfpsView, never()).unconfigureDisplay(); } + } - // WHEN ACTION_UP is received - verify(mUdfpsView).setOnTouchListener(mTouchListenerCaptor.capture()); - MotionEvent upEvent = MotionEvent.obtain(0, 0, ACTION_UP, 0, 0, 0); - mTouchListenerCaptor.getValue().onTouch(mUdfpsView, upEvent); - mBiometricsExecutor.runAllReady(); - upEvent.recycle(); - - // Configure UdfpsView to accept the ACTION_DOWN event - when(mUdfpsView.isDisplayConfigured()).thenReturn(false); + @Test + public void aodInterruptTimeout() { + runWithAllParams(this::aodInterruptTimeoutParameterized); + } - // WHEN ACTION_DOWN is received - MotionEvent downEvent = MotionEvent.obtain(0, 0, ACTION_DOWN, 0, 0, 0); - mTouchListenerCaptor.getValue().onTouch(mUdfpsView, downEvent); - mBiometricsExecutor.runAllReady(); - downEvent.recycle(); + private void aodInterruptTimeoutParameterized(TestParams testParams) throws RemoteException { + reset(mUdfpsView); - // WHEN ACTION_MOVE is received - MotionEvent moveEvent = MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0, 0, 0); - mTouchListenerCaptor.getValue().onTouch(mUdfpsView, moveEvent); - mBiometricsExecutor.runAllReady(); - moveEvent.recycle(); + // GIVEN AOD interrupt + mOverlayController.showUdfpsOverlay(TEST_REQUEST_ID, testParams.sensorProps.sensorId, + BiometricOverlayConstants.REASON_AUTH_KEYGUARD, mUdfpsOverlayControllerCallback); + mScreenObserver.onScreenTurnedOn(); + mFgExecutor.runAllReady(); + mUdfpsController.onAodInterrupt(0, 0, 0f, 0f); mFgExecutor.runAllReady(); - if (testParams.sensorProps.sensorType == FingerprintSensorProperties.TYPE_UDFPS_OPTICAL) { - // Configure UdfpsView to accept the finger up event when(mUdfpsView.isDisplayConfigured()).thenReturn(true); } else { when(mUdfpsView.isDisplayConfigured()).thenReturn(false); } - // WHEN it times out mFgExecutor.advanceClockToNext(); mFgExecutor.runAllReady(); - if (testParams.sensorProps.sensorType == FingerprintSensorProperties.TYPE_UDFPS_OPTICAL) { - // THEN the display should be unconfigured once. If the timeout action is not - // cancelled, the display would be unconfigured twice which would cause two - // FP attempts. - verify(mUdfpsView, times(1)).unconfigureDisplay(); + // THEN the display is unconfigured. + verify(mUdfpsView).unconfigureDisplay(); } else { + // THEN the display configuration is unchanged. verify(mUdfpsView, never()).unconfigureDisplay(); } } @Test - public void aodInterruptCancelTimeoutActionOnAcquired() { - runWithAllParams(this::aodInterruptCancelTimeoutActionOnAcquiredParameterized); + public void aodInterruptCancelTimeoutActionOnFingerUp() { + runWithAllParams(this::aodInterruptCancelTimeoutActionOnFingerUpParameterized); } - private void aodInterruptCancelTimeoutActionOnAcquiredParameterized(TestParams testParams) + private void aodInterruptCancelTimeoutActionOnFingerUpParameterized(TestParams testParams) throws RemoteException { reset(mUdfpsView); when(mUdfpsView.isWithinSensorArea(anyFloat(), anyFloat())).thenReturn(true); @@ -935,30 +954,32 @@ public class UdfpsControllerTest extends SysuiTestCase { mFgExecutor.runAllReady(); if (testParams.sensorProps.sensorType == FingerprintSensorProperties.TYPE_UDFPS_OPTICAL) { - // Configure UdfpsView to accept the acquired event + // Configure UdfpsView to accept the ACTION_UP event when(mUdfpsView.isDisplayConfigured()).thenReturn(true); } else { when(mUdfpsView.isDisplayConfigured()).thenReturn(false); } - // WHEN acquired is received - mOverlayController.onAcquired(testParams.sensorProps.sensorId, - BiometricFingerprintConstants.FINGERPRINT_ACQUIRED_GOOD); + // WHEN ACTION_UP is received + verify(mUdfpsView).setOnTouchListener(mTouchListenerCaptor.capture()); + MotionEvent upEvent = MotionEvent.obtain(0, 0, ACTION_UP, 0, 0, 0); + mTouchListenerCaptor.getValue().onTouch(mUdfpsView, upEvent); + mBiometricExecutor.runAllReady(); + upEvent.recycle(); // Configure UdfpsView to accept the ACTION_DOWN event when(mUdfpsView.isDisplayConfigured()).thenReturn(false); // WHEN ACTION_DOWN is received - verify(mUdfpsView).setOnTouchListener(mTouchListenerCaptor.capture()); MotionEvent downEvent = MotionEvent.obtain(0, 0, ACTION_DOWN, 0, 0, 0); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, downEvent); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); downEvent.recycle(); // WHEN ACTION_MOVE is received MotionEvent moveEvent = MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0, 0, 0); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, moveEvent); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); moveEvent.recycle(); mFgExecutor.runAllReady(); @@ -1078,11 +1099,11 @@ public class UdfpsControllerTest extends SysuiTestCase { verify(mUdfpsView).setOnTouchListener(mTouchListenerCaptor.capture()); MotionEvent downEvent = MotionEvent.obtain(0, 0, ACTION_DOWN, 0, 0, 0); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, downEvent); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); downEvent.recycle(); MotionEvent moveEvent = MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0, 0, 0); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, moveEvent); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); moveEvent.recycle(); // THEN NO haptic played @@ -1118,19 +1139,19 @@ public class UdfpsControllerTest extends SysuiTestCase { // WHEN ACTION_DOWN is received MotionEvent downEvent = MotionEvent.obtain(0, 0, ACTION_DOWN, 0, 0, 0); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, downEvent); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); downEvent.recycle(); // AND ACTION_MOVE is received MotionEvent moveEvent = MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0, 0, 0); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, moveEvent); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); moveEvent.recycle(); // AND ACTION_UP is received MotionEvent upEvent = MotionEvent.obtain(0, 0, MotionEvent.ACTION_UP, 0, 0, 0); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, upEvent); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); upEvent.recycle(); // THEN the old FingerprintManager path is invoked. @@ -1140,7 +1161,7 @@ public class UdfpsControllerTest extends SysuiTestCase { } @Test - public void onTouch_withNewTouchDetection_shouldCallOldFingerprintManagerPath() + public void onTouch_withNewTouchDetection_shouldCallNewFingerprintManagerPath() throws RemoteException { final NormalizedTouchData touchData = new NormalizedTouchData(0, 0f, 0f, 0f, 0f, 0f, 0L, 0L); @@ -1172,7 +1193,7 @@ public class UdfpsControllerTest extends SysuiTestCase { processorResultDown); MotionEvent downEvent = MotionEvent.obtain(0, 0, ACTION_DOWN, 0, 0, 0); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, downEvent); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); downEvent.recycle(); // AND ACTION_UP is received @@ -1180,7 +1201,7 @@ public class UdfpsControllerTest extends SysuiTestCase { processorResultUp); MotionEvent upEvent = MotionEvent.obtain(0, 0, MotionEvent.ACTION_UP, 0, 0, 0); mTouchListenerCaptor.getValue().onTouch(mUdfpsView, upEvent); - mBiometricsExecutor.runAllReady(); + mBiometricExecutor.runAllReady(); upEvent.recycle(); // THEN the new FingerprintManager path is invoked. @@ -1189,4 +1210,31 @@ public class UdfpsControllerTest extends SysuiTestCase { verify(mFingerprintManager).onPointerUp(anyLong(), anyInt(), anyInt(), anyFloat(), anyFloat(), anyFloat(), anyFloat(), anyFloat(), anyLong(), anyLong(), anyBoolean()); } + + @Test + public void onAodInterrupt_onAcquiredGood_fingerNoLongerDown() throws RemoteException { + // GIVEN UDFPS overlay is showing + mOverlayController.showUdfpsOverlay(TEST_REQUEST_ID, mOpticalProps.sensorId, + BiometricOverlayConstants.REASON_AUTH_KEYGUARD, mUdfpsOverlayControllerCallback); + mFgExecutor.runAllReady(); + + // GIVEN there's been an AoD interrupt + when(mKeyguardUpdateMonitor.isFingerprintDetectionRunning()).thenReturn(true); + mScreenObserver.onScreenTurnedOn(); + mUdfpsController.onAodInterrupt(0, 0, 0, 0); + + // THEN finger is considered down + assertTrue(mUdfpsController.isFingerDown()); + + // WHEN udfps receives an ACQUIRED_GOOD after the display is configured + when(mUdfpsView.isDisplayConfigured()).thenReturn(true); + verify(mFingerprintManager).setUdfpsOverlayController( + mUdfpsOverlayControllerCaptor.capture()); + mUdfpsOverlayControllerCaptor.getValue().onAcquired(0, FINGERPRINT_ACQUIRED_GOOD); + mFgExecutor.runAllReady(); + + // THEN is fingerDown should be FALSE + assertFalse(mUdfpsController.isFingerDown()); + + } } diff --git a/packages/SystemUI/tests/src/com/android/systemui/controls/controller/ControlActionCoordinatorImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/controls/controller/ControlActionCoordinatorImplTest.kt index 1d00d6b05568..16fb50c15af6 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/controls/controller/ControlActionCoordinatorImplTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/controls/controller/ControlActionCoordinatorImplTest.kt @@ -16,21 +16,19 @@ package com.android.systemui.controls.ui -import android.content.Context -import android.content.SharedPreferences import android.test.suitebuilder.annotation.SmallTest import android.testing.AndroidTestingRunner import com.android.systemui.SysuiTestCase import com.android.systemui.broadcast.BroadcastSender import com.android.systemui.controls.ControlsMetricsLogger -import com.android.systemui.controls.FakeControlsSettingsRepository +import com.android.systemui.controls.settings.ControlsSettingsDialogManager +import com.android.systemui.controls.settings.FakeControlsSettingsRepository +import com.android.systemui.flags.FeatureFlags +import com.android.systemui.flags.Flags import com.android.systemui.plugins.ActivityStarter -import com.android.systemui.settings.UserContextProvider import com.android.systemui.statusbar.VibratorHelper -import com.android.systemui.statusbar.policy.DeviceControlsControllerImpl import com.android.systemui.statusbar.policy.KeyguardStateController import com.android.systemui.util.concurrency.DelayableExecutor -import com.android.systemui.util.settings.SecureSettings import com.android.wm.shell.TaskViewFactory import org.junit.Before import org.junit.Test @@ -40,8 +38,8 @@ import org.mockito.Mock import org.mockito.Mockito import org.mockito.Mockito.`when` import org.mockito.Mockito.anyBoolean +import org.mockito.Mockito.doNothing import org.mockito.Mockito.doReturn -import org.mockito.Mockito.mock import org.mockito.Mockito.never import org.mockito.Mockito.reset import org.mockito.Mockito.spy @@ -71,9 +69,9 @@ class ControlActionCoordinatorImplTest : SysuiTestCase() { @Mock private lateinit var metricsLogger: ControlsMetricsLogger @Mock - private lateinit var secureSettings: SecureSettings + private lateinit var featureFlags: FeatureFlags @Mock - private lateinit var userContextProvider: UserContextProvider + private lateinit var controlsSettingsDialogManager: ControlsSettingsDialogManager companion object { fun <T> any(): T = Mockito.any<T>() @@ -103,23 +101,16 @@ class ControlActionCoordinatorImplTest : SysuiTestCase() { taskViewFactory, metricsLogger, vibratorHelper, - secureSettings, - userContextProvider, - controlsSettingsRepository + controlsSettingsRepository, + controlsSettingsDialogManager, + featureFlags )) - - val userContext = mock(Context::class.java) - val pref = mock(SharedPreferences::class.java) - `when`(userContextProvider.userContext).thenReturn(userContext) - `when`(userContext.getSharedPreferences( - DeviceControlsControllerImpl.PREFS_CONTROLS_FILE, Context.MODE_PRIVATE)) - .thenReturn(pref) - // Just return 2 so we don't test any Dialog logic which requires a launched activity. - `when`(pref.getInt(DeviceControlsControllerImpl.PREFS_SETTINGS_DIALOG_ATTEMPTS, 0)) - .thenReturn(2) + coordinator.activityContext = mContext `when`(cvh.cws.ci.controlId).thenReturn(ID) `when`(cvh.cws.control?.isAuthRequired()).thenReturn(true) + `when`(featureFlags.isEnabled(Flags.USE_APP_PANELS)).thenReturn(false) + action = spy(coordinator.Action(ID, {}, false, true)) doReturn(action).`when`(coordinator).createAction(any(), any(), anyBoolean(), anyBoolean()) } @@ -160,15 +151,31 @@ class ControlActionCoordinatorImplTest : SysuiTestCase() { doReturn(action).`when`(coordinator).createAction(any(), any(), anyBoolean(), anyBoolean()) `when`(keyguardStateController.isShowing()).thenReturn(true) - `when`(keyguardStateController.isUnlocked()).thenReturn(false) coordinator.toggle(cvh, "", true) verify(coordinator).bouncerOrRun(action) + verify(controlsSettingsDialogManager).maybeShowDialog(any(), any()) verify(action).invoke() } @Test + fun testToggleWhenLockedDoesNotTriggerDialog_featureFlagEnabled() { + `when`(featureFlags.isEnabled(Flags.USE_APP_PANELS)).thenReturn(true) + action = spy(coordinator.Action(ID, {}, false, false)) + doReturn(action).`when`(coordinator).createAction(any(), any(), anyBoolean(), anyBoolean()) + + `when`(keyguardStateController.isShowing()).thenReturn(true) + `when`(keyguardStateController.isUnlocked()).thenReturn(false) + doNothing().`when`(controlsSettingsDialogManager).maybeShowDialog(any(), any()) + + coordinator.toggle(cvh, "", true) + + verify(coordinator).bouncerOrRun(action) + verify(controlsSettingsDialogManager, never()).maybeShowDialog(any(), any()) + } + + @Test fun testToggleDoesNotRunsWhenLockedAndAuthRequired() { action = spy(coordinator.Action(ID, {}, false, true)) doReturn(action).`when`(coordinator).createAction(any(), any(), anyBoolean(), anyBoolean()) diff --git a/packages/SystemUI/tests/src/com/android/systemui/controls/dagger/ControlsComponentTest.kt b/packages/SystemUI/tests/src/com/android/systemui/controls/dagger/ControlsComponentTest.kt index 48fc46b7e730..9144b13c7f3e 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/controls/dagger/ControlsComponentTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/controls/dagger/ControlsComponentTest.kt @@ -22,7 +22,7 @@ import com.android.internal.widget.LockPatternUtils import com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_NOT_REQUIRED import com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_BOOT import com.android.systemui.SysuiTestCase -import com.android.systemui.controls.FakeControlsSettingsRepository +import com.android.systemui.controls.settings.FakeControlsSettingsRepository import com.android.systemui.controls.controller.ControlsController import com.android.systemui.controls.controller.ControlsTileResourceConfiguration import com.android.systemui.controls.management.ControlsListingController diff --git a/packages/SystemUI/tests/src/com/android/systemui/controls/management/ControlsListingControllerImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/controls/management/ControlsListingControllerImplTest.kt index c677f19f93e5..35cd3d261562 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/controls/management/ControlsListingControllerImplTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/controls/management/ControlsListingControllerImplTest.kt @@ -36,6 +36,7 @@ import com.android.systemui.SysuiTestCase import com.android.systemui.controls.ControlsServiceInfo import com.android.systemui.dump.DumpManager import com.android.systemui.flags.FeatureFlags +import com.android.systemui.flags.Flags.APP_PANELS_ALL_APPS_ALLOWED import com.android.systemui.flags.Flags.USE_APP_PANELS import com.android.systemui.settings.UserTracker import com.android.systemui.util.concurrency.FakeExecutor @@ -119,6 +120,8 @@ class ControlsListingControllerImplTest : SysuiTestCase() { // Return true by default, we'll test the false path `when`(featureFlags.isEnabled(USE_APP_PANELS)).thenReturn(true) + // Return false by default, we'll test the true path + `when`(featureFlags.isEnabled(APP_PANELS_ALL_APPS_ALLOWED)).thenReturn(false) val wrapper = object : ContextWrapper(mContext) { override fun createContextAsUser(user: UserHandle, flags: Int): Context { @@ -518,6 +521,37 @@ class ControlsListingControllerImplTest : SysuiTestCase() { } @Test + fun testPackageNotPreferred_allowAllApps_correctPanel() { + `when`(featureFlags.isEnabled(APP_PANELS_ALL_APPS_ALLOWED)).thenReturn(true) + + mContext.orCreateTestableResources + .addOverride(R.array.config_controlsPreferredPackages, arrayOf<String>()) + + val serviceInfo = ServiceInfo( + componentName, + activityName + ) + + `when`(packageManager.getComponentEnabledSetting(eq(activityName))) + .thenReturn(PackageManager.COMPONENT_ENABLED_STATE_ENABLED) + + setUpQueryResult(listOf( + ActivityInfo( + activityName, + exported = true, + permission = Manifest.permission.BIND_CONTROLS + ) + )) + + val list = listOf(serviceInfo) + serviceListingCallbackCaptor.value.onServicesReloaded(list) + + executor.runAllReady() + + assertEquals(activityName, controller.getCurrentServices()[0].panelActivity) + } + + @Test fun testListingsNotModifiedByCallback() { // This test checks that if the list passed to the callback is modified, it has no effect // in the resulting services diff --git a/packages/SystemUI/tests/src/com/android/systemui/controls/settings/ControlsSettingsDialogManagerImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/controls/settings/ControlsSettingsDialogManagerImplTest.kt new file mode 100644 index 000000000000..0c9986d82447 --- /dev/null +++ b/packages/SystemUI/tests/src/com/android/systemui/controls/settings/ControlsSettingsDialogManagerImplTest.kt @@ -0,0 +1,328 @@ +/* + * 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.controls.settings + +import android.content.DialogInterface +import android.content.SharedPreferences +import android.database.ContentObserver +import android.provider.Settings.Secure.LOCKSCREEN_ALLOW_TRIVIAL_CONTROLS +import android.provider.Settings.Secure.LOCKSCREEN_SHOW_CONTROLS +import android.testing.AndroidTestingRunner +import android.testing.TestableLooper +import androidx.test.filters.SmallTest +import com.android.systemui.SysuiTestCase +import com.android.systemui.controls.settings.ControlsSettingsDialogManager.Companion.PREFS_SETTINGS_DIALOG_ATTEMPTS +import com.android.systemui.plugins.ActivityStarter +import com.android.systemui.settings.UserFileManager +import com.android.systemui.settings.UserTracker +import com.android.systemui.statusbar.policy.DeviceControlsControllerImpl +import com.android.systemui.util.FakeSharedPreferences +import com.android.systemui.util.TestableAlertDialog +import com.android.systemui.util.mockito.any +import com.android.systemui.util.mockito.eq +import com.android.systemui.util.mockito.nullable +import com.android.systemui.util.settings.FakeSettings +import com.google.common.truth.Truth.assertThat +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentMatchers.anyBoolean +import org.mockito.Mock +import org.mockito.Mockito.anyInt +import org.mockito.Mockito.never +import org.mockito.Mockito.verify +import org.mockito.Mockito.`when` +import org.mockito.MockitoAnnotations + +@SmallTest +@RunWith(AndroidTestingRunner::class) +@TestableLooper.RunWithLooper +class ControlsSettingsDialogManagerImplTest : SysuiTestCase() { + + companion object { + private const val SETTING_SHOW = LOCKSCREEN_SHOW_CONTROLS + private const val SETTING_ACTION = LOCKSCREEN_ALLOW_TRIVIAL_CONTROLS + private const val MAX_NUMBER_ATTEMPTS_CONTROLS_DIALOG = 2 + } + + @Mock private lateinit var userFileManager: UserFileManager + @Mock private lateinit var userTracker: UserTracker + @Mock private lateinit var activityStarter: ActivityStarter + @Mock private lateinit var completedRunnable: () -> Unit + + private lateinit var controlsSettingsRepository: FakeControlsSettingsRepository + private lateinit var sharedPreferences: FakeSharedPreferences + private lateinit var secureSettings: FakeSettings + + private lateinit var underTest: ControlsSettingsDialogManagerImpl + + private var dialog: TestableAlertDialog? = null + + @Before + fun setUp() { + MockitoAnnotations.initMocks(this) + + controlsSettingsRepository = FakeControlsSettingsRepository() + sharedPreferences = FakeSharedPreferences() + secureSettings = FakeSettings() + + `when`(userTracker.userId).thenReturn(0) + secureSettings.userId = userTracker.userId + `when`( + userFileManager.getSharedPreferences( + eq(DeviceControlsControllerImpl.PREFS_CONTROLS_FILE), + anyInt(), + anyInt() + ) + ) + .thenReturn(sharedPreferences) + + `when`(activityStarter.dismissKeyguardThenExecute(any(), nullable(), anyBoolean())) + .thenAnswer { (it.arguments[0] as ActivityStarter.OnDismissAction).onDismiss() } + + attachRepositoryToSettings() + underTest = + ControlsSettingsDialogManagerImpl( + secureSettings, + userFileManager, + controlsSettingsRepository, + userTracker, + activityStarter + ) { context, _ -> TestableAlertDialog(context).also { dialog = it } } + } + + @After + fun tearDown() { + underTest.closeDialog() + } + + @Test + fun dialogNotShownIfPrefsAtMaximum() { + sharedPreferences.putAttempts(MAX_NUMBER_ATTEMPTS_CONTROLS_DIALOG) + + underTest.maybeShowDialog(context, completedRunnable) + + assertThat(dialog?.isShowing ?: false).isFalse() + verify(completedRunnable).invoke() + } + + @Test + fun dialogNotShownIfSettingsAreTrue() { + sharedPreferences.putAttempts(0) + secureSettings.putBool(SETTING_SHOW, true) + secureSettings.putBool(SETTING_ACTION, true) + + underTest.maybeShowDialog(context, completedRunnable) + + assertThat(dialog?.isShowing ?: false).isFalse() + verify(completedRunnable).invoke() + } + + @Test + fun dialogShownIfAllowTrivialControlsFalse() { + sharedPreferences.putAttempts(0) + secureSettings.putBool(SETTING_SHOW, true) + secureSettings.putBool(SETTING_ACTION, false) + + underTest.maybeShowDialog(context, completedRunnable) + + assertThat(dialog?.isShowing ?: false).isTrue() + } + + @Test + fun dialogDispossedAfterClosing() { + sharedPreferences.putAttempts(0) + secureSettings.putBool(SETTING_SHOW, true) + secureSettings.putBool(SETTING_ACTION, false) + + underTest.maybeShowDialog(context, completedRunnable) + underTest.closeDialog() + + assertThat(dialog?.isShowing ?: false).isFalse() + } + + @Test + fun dialogNeutralButtonDoesntChangeSetting() { + sharedPreferences.putAttempts(0) + secureSettings.putBool(SETTING_SHOW, true) + secureSettings.putBool(SETTING_ACTION, false) + + underTest.maybeShowDialog(context, completedRunnable) + clickButton(DialogInterface.BUTTON_NEUTRAL) + + assertThat(secureSettings.getBool(SETTING_ACTION, false)).isFalse() + } + + @Test + fun dialogNeutralButtonPutsMaxAttempts() { + sharedPreferences.putAttempts(0) + secureSettings.putBool(SETTING_SHOW, true) + secureSettings.putBool(SETTING_ACTION, false) + + underTest.maybeShowDialog(context, completedRunnable) + clickButton(DialogInterface.BUTTON_NEUTRAL) + + assertThat(sharedPreferences.getInt(PREFS_SETTINGS_DIALOG_ATTEMPTS, 0)) + .isEqualTo(MAX_NUMBER_ATTEMPTS_CONTROLS_DIALOG) + } + + @Test + fun dialogNeutralButtonCallsOnComplete() { + sharedPreferences.putAttempts(0) + secureSettings.putBool(SETTING_SHOW, true) + secureSettings.putBool(SETTING_ACTION, false) + + underTest.maybeShowDialog(context, completedRunnable) + clickButton(DialogInterface.BUTTON_NEUTRAL) + + verify(completedRunnable).invoke() + } + + @Test + fun dialogPositiveButtonChangesSetting() { + sharedPreferences.putAttempts(0) + secureSettings.putBool(SETTING_SHOW, true) + secureSettings.putBool(SETTING_ACTION, false) + + underTest.maybeShowDialog(context, completedRunnable) + clickButton(DialogInterface.BUTTON_POSITIVE) + + assertThat(secureSettings.getBool(SETTING_ACTION, false)).isTrue() + } + + @Test + fun dialogPositiveButtonPutsMaxAttempts() { + sharedPreferences.putAttempts(0) + secureSettings.putBool(SETTING_SHOW, true) + secureSettings.putBool(SETTING_ACTION, false) + + underTest.maybeShowDialog(context, completedRunnable) + clickButton(DialogInterface.BUTTON_POSITIVE) + + assertThat(sharedPreferences.getInt(PREFS_SETTINGS_DIALOG_ATTEMPTS, 0)) + .isEqualTo(MAX_NUMBER_ATTEMPTS_CONTROLS_DIALOG) + } + + @Test + fun dialogPositiveButtonCallsOnComplete() { + sharedPreferences.putAttempts(0) + secureSettings.putBool(SETTING_SHOW, true) + secureSettings.putBool(SETTING_ACTION, false) + + underTest.maybeShowDialog(context, completedRunnable) + clickButton(DialogInterface.BUTTON_POSITIVE) + + verify(completedRunnable).invoke() + } + + @Test + fun dialogCancelDoesntChangeSetting() { + sharedPreferences.putAttempts(0) + secureSettings.putBool(SETTING_SHOW, true) + secureSettings.putBool(SETTING_ACTION, false) + + underTest.maybeShowDialog(context, completedRunnable) + dialog?.cancel() + + assertThat(secureSettings.getBool(SETTING_ACTION, false)).isFalse() + } + + @Test + fun dialogCancelPutsOneExtraAttempt() { + val attempts = 0 + sharedPreferences.putAttempts(attempts) + secureSettings.putBool(SETTING_SHOW, true) + secureSettings.putBool(SETTING_ACTION, false) + + underTest.maybeShowDialog(context, completedRunnable) + dialog?.cancel() + + assertThat(sharedPreferences.getInt(PREFS_SETTINGS_DIALOG_ATTEMPTS, 0)) + .isEqualTo(attempts + 1) + } + + @Test + fun dialogCancelCallsOnComplete() { + sharedPreferences.putAttempts(0) + secureSettings.putBool(SETTING_SHOW, true) + secureSettings.putBool(SETTING_ACTION, false) + + underTest.maybeShowDialog(context, completedRunnable) + dialog?.cancel() + + verify(completedRunnable).invoke() + } + + @Test + fun closeDialogDoesNotCallOnComplete() { + sharedPreferences.putAttempts(0) + secureSettings.putBool(SETTING_SHOW, true) + secureSettings.putBool(SETTING_ACTION, false) + + underTest.maybeShowDialog(context, completedRunnable) + underTest.closeDialog() + + verify(completedRunnable, never()).invoke() + } + + @Test + fun dialogPositiveWithBothSettingsFalseTogglesBothSettings() { + sharedPreferences.putAttempts(0) + secureSettings.putBool(SETTING_SHOW, false) + secureSettings.putBool(SETTING_ACTION, false) + + underTest.maybeShowDialog(context, completedRunnable) + clickButton(DialogInterface.BUTTON_POSITIVE) + + assertThat(secureSettings.getBool(SETTING_SHOW)).isTrue() + assertThat(secureSettings.getBool(SETTING_ACTION)).isTrue() + } + + private fun clickButton(which: Int) { + dialog?.clickButton(which) + } + + private fun attachRepositoryToSettings() { + secureSettings.registerContentObserver( + SETTING_SHOW, + object : ContentObserver(null) { + override fun onChange(selfChange: Boolean) { + controlsSettingsRepository.setCanShowControlsInLockscreen( + secureSettings.getBool(SETTING_SHOW, false) + ) + } + } + ) + + secureSettings.registerContentObserver( + SETTING_ACTION, + object : ContentObserver(null) { + override fun onChange(selfChange: Boolean) { + controlsSettingsRepository.setAllowActionOnTrivialControlsInLockscreen( + secureSettings.getBool(SETTING_ACTION, false) + ) + } + } + ) + } + + private fun SharedPreferences.putAttempts(value: Int) { + edit().putInt(PREFS_SETTINGS_DIALOG_ATTEMPTS, value).commit() + } +} diff --git a/packages/SystemUI/tests/src/com/android/systemui/controls/ControlsSettingsRepositoryImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/controls/settings/ControlsSettingsRepositoryImplTest.kt index 4b88b44c3f03..b904ac14e707 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/controls/ControlsSettingsRepositoryImplTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/controls/settings/ControlsSettingsRepositoryImplTest.kt @@ -15,7 +15,7 @@ * */ -package com.android.systemui.controls +package com.android.systemui.controls.settings import android.content.pm.UserInfo import android.provider.Settings diff --git a/packages/SystemUI/tests/src/com/android/systemui/controls/FakeControlsSettingsRepository.kt b/packages/SystemUI/tests/src/com/android/systemui/controls/settings/FakeControlsSettingsRepository.kt index 8a1bed20e700..b6628db14235 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/controls/FakeControlsSettingsRepository.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/controls/settings/FakeControlsSettingsRepository.kt @@ -15,7 +15,7 @@ * */ -package com.android.systemui.controls +package com.android.systemui.controls.settings import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow diff --git a/packages/SystemUI/tests/src/com/android/systemui/controls/ui/ControlsUiControllerImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/controls/ui/ControlsUiControllerImplTest.kt index d965e337f47a..779788aa0075 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/controls/ui/ControlsUiControllerImplTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/controls/ui/ControlsUiControllerImplTest.kt @@ -35,10 +35,10 @@ import com.android.systemui.SysuiTestCase import com.android.systemui.controls.ControlsMetricsLogger import com.android.systemui.controls.ControlsServiceInfo import com.android.systemui.controls.CustomIconCache -import com.android.systemui.controls.FakeControlsSettingsRepository import com.android.systemui.controls.controller.ControlsController import com.android.systemui.controls.controller.StructureInfo import com.android.systemui.controls.management.ControlsListingController +import com.android.systemui.controls.settings.FakeControlsSettingsRepository import com.android.systemui.dump.DumpManager import com.android.systemui.plugins.ActivityStarter import com.android.systemui.settings.UserFileManager diff --git a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeTriggersTest.java b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeTriggersTest.java index 82432ce31fa2..b66a454638ac 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/doze/DozeTriggersTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/doze/DozeTriggersTest.java @@ -357,6 +357,44 @@ public class DozeTriggersTest extends SysuiTestCase { verify(mDozeLog).tracePulseDropped(anyString(), eq(null)); } + @Test + public void udfpsLongPress_triggeredWhenAodPaused() { + // GIVEN device is DOZE_AOD_PAUSED + when(mMachine.getState()).thenReturn(DozeMachine.State.DOZE_AOD_PAUSED); + + // WHEN udfps long-press is triggered + mTriggers.onSensor(DozeLog.REASON_SENSOR_UDFPS_LONG_PRESS, 100, 100, + new float[]{0, 1, 2, 3, 4}); + + // THEN the pulse is NOT dropped + verify(mDozeLog, never()).tracePulseDropped(anyString(), any()); + + // WHEN the screen state is ON + mTriggers.onScreenState(Display.STATE_ON); + + // THEN aod interrupt is sent + verify(mAuthController).onAodInterrupt(anyInt(), anyInt(), anyFloat(), anyFloat()); + } + + @Test + public void udfpsLongPress_triggeredWhenAodPausing() { + // GIVEN device is DOZE_AOD_PAUSED + when(mMachine.getState()).thenReturn(DozeMachine.State.DOZE_AOD_PAUSING); + + // WHEN udfps long-press is triggered + mTriggers.onSensor(DozeLog.REASON_SENSOR_UDFPS_LONG_PRESS, 100, 100, + new float[]{0, 1, 2, 3, 4}); + + // THEN the pulse is NOT dropped + verify(mDozeLog, never()).tracePulseDropped(anyString(), any()); + + // WHEN the screen state is ON + mTriggers.onScreenState(Display.STATE_ON); + + // THEN aod interrupt is sent + verify(mAuthController).onAodInterrupt(anyInt(), anyInt(), anyFloat(), anyFloat()); + } + private void waitForSensorManager() { mExecutor.runAllReady(); } diff --git a/packages/SystemUI/tests/src/com/android/systemui/flags/FeatureFlagsDebugRestarterTest.kt b/packages/SystemUI/tests/src/com/android/systemui/flags/FeatureFlagsDebugRestarterTest.kt index 1e7b1f26ba8c..ed167212c96a 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/flags/FeatureFlagsDebugRestarterTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/flags/FeatureFlagsDebugRestarterTest.kt @@ -48,22 +48,22 @@ class FeatureFlagsDebugRestarterTest : SysuiTestCase() { @Test fun testRestart_ImmediateWhenAsleep() { whenever(wakefulnessLifecycle.wakefulness).thenReturn(WAKEFULNESS_ASLEEP) - restarter.restart() - verify(systemExitRestarter).restart() + restarter.restartSystemUI() + verify(systemExitRestarter).restartSystemUI() } @Test fun testRestart_WaitsForSceenOff() { whenever(wakefulnessLifecycle.wakefulness).thenReturn(WAKEFULNESS_AWAKE) - restarter.restart() - verify(systemExitRestarter, never()).restart() + restarter.restartSystemUI() + verify(systemExitRestarter, never()).restartSystemUI() val captor = ArgumentCaptor.forClass(WakefulnessLifecycle.Observer::class.java) verify(wakefulnessLifecycle).addObserver(captor.capture()) captor.value.onFinishedGoingToSleep() - verify(systemExitRestarter).restart() + verify(systemExitRestarter).restartSystemUI() } } diff --git a/packages/SystemUI/tests/src/com/android/systemui/flags/FeatureFlagsReleaseRestarterTest.kt b/packages/SystemUI/tests/src/com/android/systemui/flags/FeatureFlagsReleaseRestarterTest.kt index 68ca48dd327d..7d807e2ff207 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/flags/FeatureFlagsReleaseRestarterTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/flags/FeatureFlagsReleaseRestarterTest.kt @@ -63,7 +63,7 @@ class FeatureFlagsReleaseRestarterTest : SysuiTestCase() { whenever(batteryController.isPluggedIn).thenReturn(true) assertThat(executor.numPending()).isEqualTo(0) - restarter.restart() + restarter.restartSystemUI() assertThat(executor.numPending()).isEqualTo(1) } @@ -72,11 +72,11 @@ class FeatureFlagsReleaseRestarterTest : SysuiTestCase() { whenever(wakefulnessLifecycle.wakefulness).thenReturn(WAKEFULNESS_ASLEEP) whenever(batteryController.isPluggedIn).thenReturn(true) - restarter.restart() - verify(systemExitRestarter, never()).restart() + restarter.restartSystemUI() + verify(systemExitRestarter, never()).restartSystemUI() executor.advanceClockToLast() executor.runAllReady() - verify(systemExitRestarter).restart() + verify(systemExitRestarter).restartSystemUI() } @Test @@ -85,7 +85,7 @@ class FeatureFlagsReleaseRestarterTest : SysuiTestCase() { whenever(batteryController.isPluggedIn).thenReturn(true) assertThat(executor.numPending()).isEqualTo(0) - restarter.restart() + restarter.restartSystemUI() assertThat(executor.numPending()).isEqualTo(0) } @@ -95,7 +95,7 @@ class FeatureFlagsReleaseRestarterTest : SysuiTestCase() { whenever(batteryController.isPluggedIn).thenReturn(false) assertThat(executor.numPending()).isEqualTo(0) - restarter.restart() + restarter.restartSystemUI() assertThat(executor.numPending()).isEqualTo(0) } @@ -105,8 +105,8 @@ class FeatureFlagsReleaseRestarterTest : SysuiTestCase() { whenever(batteryController.isPluggedIn).thenReturn(true) assertThat(executor.numPending()).isEqualTo(0) - restarter.restart() - restarter.restart() + restarter.restartSystemUI() + restarter.restartSystemUI() assertThat(executor.numPending()).isEqualTo(1) } @@ -115,7 +115,7 @@ class FeatureFlagsReleaseRestarterTest : SysuiTestCase() { whenever(wakefulnessLifecycle.wakefulness).thenReturn(WAKEFULNESS_AWAKE) whenever(batteryController.isPluggedIn).thenReturn(true) assertThat(executor.numPending()).isEqualTo(0) - restarter.restart() + restarter.restartSystemUI() val captor = ArgumentCaptor.forClass(WakefulnessLifecycle.Observer::class.java) verify(wakefulnessLifecycle).addObserver(captor.capture()) @@ -131,7 +131,7 @@ class FeatureFlagsReleaseRestarterTest : SysuiTestCase() { whenever(wakefulnessLifecycle.wakefulness).thenReturn(WAKEFULNESS_ASLEEP) whenever(batteryController.isPluggedIn).thenReturn(false) assertThat(executor.numPending()).isEqualTo(0) - restarter.restart() + restarter.restartSystemUI() val captor = ArgumentCaptor.forClass(BatteryController.BatteryStateChangeCallback::class.java) diff --git a/packages/SystemUI/tests/src/com/android/systemui/log/SessionTrackerTest.java b/packages/SystemUI/tests/src/com/android/systemui/log/SessionTrackerTest.java index dc5522efe406..aa54a1cdf579 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/log/SessionTrackerTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/log/SessionTrackerTest.java @@ -23,8 +23,10 @@ import static android.app.StatusBarManager.SESSION_KEYGUARD; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; +import static org.junit.Assert.assertNotEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -171,6 +173,34 @@ public class SessionTrackerTest extends SysuiTestCase { } @Test + public void testKeyguardSessionOnDeviceStartsSleepingTwiceInARow_startsNewKeyguardSession() + throws RemoteException { + // GIVEN session tracker started w/o any sessions + mSessionTracker.start(); + captureKeyguardUpdateMonitorCallback(); + + // WHEN device starts going to sleep + mKeyguardUpdateMonitorCallback.onStartedGoingToSleep(0); + + // THEN the keyguard session has a session id + final InstanceId firstSessionId = mSessionTracker.getSessionId(SESSION_KEYGUARD); + assertNotNull(firstSessionId); + + // WHEN device starts going to sleep a second time + mKeyguardUpdateMonitorCallback.onStartedGoingToSleep(0); + + // THEN there's a new keyguard session with a unique session id + final InstanceId secondSessionId = mSessionTracker.getSessionId(SESSION_KEYGUARD); + assertNotNull(secondSessionId); + assertNotEquals(firstSessionId, secondSessionId); + + // THEN session start event gets sent to status bar service twice (once per going to + // sleep signal) + verify(mStatusBarService, times(2)).onSessionStarted( + eq(SESSION_KEYGUARD), any(InstanceId.class)); + } + + @Test public void testKeyguardSessionOnKeyguardShowingChange() throws RemoteException { // GIVEN session tracker started w/o any sessions mSessionTracker.start(); 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 5f643363bd2e..7c3c9d2a1bb1 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 @@ -38,12 +38,15 @@ import com.android.settingslib.media.MediaDevice; import com.android.systemui.R; import com.android.systemui.SysuiTestCase; +import com.google.common.collect.ImmutableList; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.List; +import java.util.stream.Collectors; @SmallTest @RunWith(AndroidTestingRunner.class) @@ -69,15 +72,13 @@ public class MediaOutputAdapterTest extends SysuiTestCase { private MediaOutputAdapter mMediaOutputAdapter; private MediaOutputAdapter.MediaDeviceViewHolder mViewHolder; private List<MediaDevice> mMediaDevices = new ArrayList<>(); + private List<MediaItem> mMediaItems = new ArrayList<>(); MediaOutputSeekbar mSpyMediaOutputSeekbar; @Before public void setUp() { - mMediaOutputAdapter = new MediaOutputAdapter(mMediaOutputController); - mViewHolder = (MediaOutputAdapter.MediaDeviceViewHolder) mMediaOutputAdapter - .onCreateViewHolder(new LinearLayout(mContext), 0); - mSpyMediaOutputSeekbar = spy(mViewHolder.mSeekBar); - + when(mMediaOutputController.isAdvancedLayoutSupported()).thenReturn(false); + when(mMediaOutputController.getMediaItemList()).thenReturn(mMediaItems); when(mMediaOutputController.getMediaDevices()).thenReturn(mMediaDevices); when(mMediaOutputController.hasAdjustVolumeUserRestriction()).thenReturn(false); when(mMediaOutputController.isAnyDeviceTransferring()).thenReturn(false); @@ -96,6 +97,13 @@ public class MediaOutputAdapterTest extends SysuiTestCase { LocalMediaManager.MediaDeviceState.STATE_DISCONNECTED); mMediaDevices.add(mMediaDevice1); mMediaDevices.add(mMediaDevice2); + mMediaItems.add(new MediaItem(mMediaDevice1)); + mMediaItems.add(new MediaItem(mMediaDevice2)); + + mMediaOutputAdapter = new MediaOutputAdapter(mMediaOutputController); + mViewHolder = (MediaOutputAdapter.MediaDeviceViewHolder) mMediaOutputAdapter + .onCreateViewHolder(new LinearLayout(mContext), 0); + mSpyMediaOutputSeekbar = spy(mViewHolder.mSeekBar); } @Test @@ -116,6 +124,26 @@ public class MediaOutputAdapterTest extends SysuiTestCase { } @Test + public void advanced_getItemCount_returnsMediaItemSize() { + when(mMediaOutputController.isAdvancedLayoutSupported()).thenReturn(true); + assertThat(mMediaOutputAdapter.getItemCount()).isEqualTo(mMediaItems.size()); + } + + @Test + public void advanced_getItemId_validPosition_returnCorrespondingId() { + when(mMediaOutputController.isAdvancedLayoutSupported()).thenReturn(true); + assertThat(mMediaOutputAdapter.getItemId(0)).isEqualTo(mMediaItems.get( + 0).getMediaDevice().get().getId().hashCode()); + } + + @Test + public void advanced_getItemId_invalidPosition_returnPosition() { + when(mMediaOutputController.isAdvancedLayoutSupported()).thenReturn(true); + int invalidPosition = mMediaItems.size() + 1; + assertThat(mMediaOutputAdapter.getItemId(invalidPosition)).isEqualTo(invalidPosition); + } + + @Test public void onBindViewHolder_bindPairNew_verifyView() { mMediaOutputAdapter.onBindViewHolder(mViewHolder, 2); @@ -156,6 +184,63 @@ public class MediaOutputAdapterTest extends SysuiTestCase { } @Test + public void advanced_onBindViewHolder_bindPairNew_verifyView() { + when(mMediaOutputController.isAdvancedLayoutSupported()).thenReturn(true); + mMediaOutputAdapter = new MediaOutputAdapter(mMediaOutputController); + mViewHolder = (MediaOutputAdapter.MediaDeviceViewHolder) mMediaOutputAdapter + .onCreateViewHolder(new LinearLayout(mContext), 0); + mMediaItems.add(new MediaItem()); + mMediaOutputAdapter.onBindViewHolder(mViewHolder, 2); + + assertThat(mViewHolder.mTitleText.getVisibility()).isEqualTo(View.VISIBLE); + assertThat(mViewHolder.mTwoLineLayout.getVisibility()).isEqualTo(View.GONE); + assertThat(mViewHolder.mProgressBar.getVisibility()).isEqualTo(View.GONE); + assertThat(mViewHolder.mCheckBox.getVisibility()).isEqualTo(View.GONE); + assertThat(mViewHolder.mTitleText.getText()).isEqualTo(mContext.getText( + R.string.media_output_dialog_pairing_new)); + } + + @Test + public void advanced_onBindViewHolder_bindGroup_withSessionName_verifyView() { + when(mMediaOutputController.isAdvancedLayoutSupported()).thenReturn(true); + when(mMediaOutputController.getSelectedMediaDevice()).thenReturn( + mMediaItems.stream().map((item) -> item.getMediaDevice().get()).collect( + Collectors.toList())); + when(mMediaOutputController.getSessionName()).thenReturn(TEST_SESSION_NAME); + mMediaOutputAdapter = new MediaOutputAdapter(mMediaOutputController); + mViewHolder = (MediaOutputAdapter.MediaDeviceViewHolder) mMediaOutputAdapter + .onCreateViewHolder(new LinearLayout(mContext), 0); + mMediaOutputAdapter.getItemCount(); + mMediaOutputAdapter.onBindViewHolder(mViewHolder, 0); + + assertThat(mViewHolder.mSeekBar.getVisibility()).isEqualTo(View.VISIBLE); + assertThat(mViewHolder.mTwoLineLayout.getVisibility()).isEqualTo(View.GONE); + assertThat(mViewHolder.mTitleText.getVisibility()).isEqualTo(View.VISIBLE); + assertThat(mViewHolder.mProgressBar.getVisibility()).isEqualTo(View.GONE); + assertThat(mViewHolder.mCheckBox.getVisibility()).isEqualTo(View.VISIBLE); + } + + @Test + public void advanced_onBindViewHolder_bindGroup_noSessionName_verifyView() { + when(mMediaOutputController.isAdvancedLayoutSupported()).thenReturn(true); + when(mMediaOutputController.getSelectedMediaDevice()).thenReturn( + mMediaItems.stream().map((item) -> item.getMediaDevice().get()).collect( + Collectors.toList())); + when(mMediaOutputController.getSessionName()).thenReturn(null); + mMediaOutputAdapter = new MediaOutputAdapter(mMediaOutputController); + mViewHolder = (MediaOutputAdapter.MediaDeviceViewHolder) mMediaOutputAdapter + .onCreateViewHolder(new LinearLayout(mContext), 0); + mMediaOutputAdapter.getItemCount(); + mMediaOutputAdapter.onBindViewHolder(mViewHolder, 0); + + assertThat(mViewHolder.mSeekBar.getVisibility()).isEqualTo(View.VISIBLE); + assertThat(mViewHolder.mTwoLineLayout.getVisibility()).isEqualTo(View.GONE); + assertThat(mViewHolder.mTitleText.getVisibility()).isEqualTo(View.VISIBLE); + assertThat(mViewHolder.mProgressBar.getVisibility()).isEqualTo(View.GONE); + assertThat(mViewHolder.mCheckBox.getVisibility()).isEqualTo(View.VISIBLE); + } + + @Test public void onBindViewHolder_bindConnectedDevice_verifyView() { mMediaOutputAdapter.onBindViewHolder(mViewHolder, 0); @@ -169,6 +254,63 @@ public class MediaOutputAdapterTest extends SysuiTestCase { } @Test + public void advanced_onBindViewHolder_bindNonRemoteConnectedDevice_verifyView() { + when(mMediaOutputController.isAdvancedLayoutSupported()).thenReturn(true); + when(mMediaOutputController.isActiveRemoteDevice(mMediaDevice1)).thenReturn(false); + mViewHolder = (MediaOutputAdapter.MediaDeviceViewHolder) mMediaOutputAdapter + .onCreateViewHolder(new LinearLayout(mContext), 0); + mMediaOutputAdapter.onBindViewHolder(mViewHolder, 0); + + assertThat(mViewHolder.mTitleText.getVisibility()).isEqualTo(View.VISIBLE); + assertThat(mViewHolder.mTitleText.getText().toString()).isEqualTo(TEST_DEVICE_NAME_1); + assertThat(mViewHolder.mSubTitleText.getVisibility()).isEqualTo(View.GONE); + assertThat(mViewHolder.mProgressBar.getVisibility()).isEqualTo(View.GONE); + assertThat(mViewHolder.mCheckBox.getVisibility()).isEqualTo(View.GONE); + assertThat(mViewHolder.mTwoLineLayout.getVisibility()).isEqualTo(View.GONE); + assertThat(mViewHolder.mSeekBar.getVisibility()).isEqualTo(View.VISIBLE); + } + + @Test + public void advanced_onBindViewHolder_bindConnectedRemoteDevice_verifyView() { + when(mMediaOutputController.isAdvancedLayoutSupported()).thenReturn(true); + when(mMediaOutputController.getSelectableMediaDevice()).thenReturn( + ImmutableList.of(mMediaDevice2)); + when(mMediaOutputController.isCurrentConnectedDeviceRemote()).thenReturn(true); + mViewHolder = (MediaOutputAdapter.MediaDeviceViewHolder) mMediaOutputAdapter + .onCreateViewHolder(new LinearLayout(mContext), 0); + mMediaOutputAdapter.onBindViewHolder(mViewHolder, 0); + + assertThat(mViewHolder.mTitleText.getVisibility()).isEqualTo(View.VISIBLE); + assertThat(mViewHolder.mTitleText.getText().toString()).isEqualTo(TEST_DEVICE_NAME_1); + assertThat(mViewHolder.mSubTitleText.getVisibility()).isEqualTo(View.GONE); + assertThat(mViewHolder.mProgressBar.getVisibility()).isEqualTo(View.GONE); + assertThat(mViewHolder.mCheckBox.getVisibility()).isEqualTo(View.VISIBLE); + assertThat(mViewHolder.mTwoLineLayout.getVisibility()).isEqualTo(View.GONE); + assertThat(mViewHolder.mSeekBar.getVisibility()).isEqualTo(View.VISIBLE); + assertThat(mViewHolder.mEndTouchArea.getVisibility()).isEqualTo(View.VISIBLE); + } + + @Test + public void advanced_onBindViewHolder_bindSingleConnectedRemoteDevice_verifyView() { + when(mMediaOutputController.isAdvancedLayoutSupported()).thenReturn(true); + when(mMediaOutputController.getSelectableMediaDevice()).thenReturn( + ImmutableList.of()); + when(mMediaOutputController.isCurrentConnectedDeviceRemote()).thenReturn(true); + mViewHolder = (MediaOutputAdapter.MediaDeviceViewHolder) mMediaOutputAdapter + .onCreateViewHolder(new LinearLayout(mContext), 0); + mMediaOutputAdapter.onBindViewHolder(mViewHolder, 0); + + assertThat(mViewHolder.mTitleText.getVisibility()).isEqualTo(View.VISIBLE); + assertThat(mViewHolder.mTitleText.getText().toString()).isEqualTo(TEST_DEVICE_NAME_1); + assertThat(mViewHolder.mSubTitleText.getVisibility()).isEqualTo(View.GONE); + assertThat(mViewHolder.mProgressBar.getVisibility()).isEqualTo(View.GONE); + assertThat(mViewHolder.mCheckBox.getVisibility()).isEqualTo(View.GONE); + assertThat(mViewHolder.mTwoLineLayout.getVisibility()).isEqualTo(View.GONE); + assertThat(mViewHolder.mSeekBar.getVisibility()).isEqualTo(View.VISIBLE); + assertThat(mViewHolder.mEndTouchArea.getVisibility()).isEqualTo(View.GONE); + } + + @Test public void onBindViewHolder_bindConnectedDeviceWithMutingExpectedDeviceExist_verifyView() { when(mMediaOutputController.hasMutingExpectedDevice()).thenReturn(true); when(mMediaOutputController.isCurrentConnectedDeviceRemote()).thenReturn(false); @@ -316,6 +458,19 @@ public class MediaOutputAdapterTest extends SysuiTestCase { } @Test + public void advanced_onItemClick_clickPairNew_verifyLaunchBluetoothPairing() { + when(mMediaOutputController.isAdvancedLayoutSupported()).thenReturn(true); + mMediaOutputAdapter = new MediaOutputAdapter(mMediaOutputController); + mViewHolder = (MediaOutputAdapter.MediaDeviceViewHolder) mMediaOutputAdapter + .onCreateViewHolder(new LinearLayout(mContext), 0); + mMediaItems.add(new MediaItem()); + mMediaOutputAdapter.onBindViewHolder(mViewHolder, 2); + mViewHolder.mContainerLayout.performClick(); + + verify(mMediaOutputController).launchBluetoothPairing(mViewHolder.mContainerLayout); + } + + @Test public void onItemClick_clickDevice_verifyConnectDevice() { assertThat(mMediaDevice2.getState()).isEqualTo( LocalMediaManager.MediaDeviceState.STATE_DISCONNECTED); @@ -352,6 +507,38 @@ public class MediaOutputAdapterTest extends SysuiTestCase { } @Test + public void advanced_onGroupActionTriggered_clicksEndAreaOfSelectableDevice_triggerGrouping() { + when(mMediaOutputController.isAdvancedLayoutSupported()).thenReturn(true); + List<MediaDevice> selectableDevices = new ArrayList<>(); + selectableDevices.add(mMediaDevice2); + when(mMediaOutputController.getSelectableMediaDevice()).thenReturn(selectableDevices); + mViewHolder = (MediaOutputAdapter.MediaDeviceViewHolder) mMediaOutputAdapter + .onCreateViewHolder(new LinearLayout(mContext), 0); + mMediaOutputAdapter.onBindViewHolder(mViewHolder, 1); + + mViewHolder.mEndTouchArea.performClick(); + + verify(mMediaOutputController).addDeviceToPlayMedia(mMediaDevice2); + } + + @Test + public void advanced_onGroupActionTriggered_clickSelectedRemoteDevice_triggerUngrouping() { + when(mMediaOutputController.isAdvancedLayoutSupported()).thenReturn(true); + when(mMediaOutputController.getSelectableMediaDevice()).thenReturn( + ImmutableList.of(mMediaDevice2)); + when(mMediaOutputController.getDeselectableMediaDevice()).thenReturn( + ImmutableList.of(mMediaDevice1)); + when(mMediaOutputController.isCurrentConnectedDeviceRemote()).thenReturn(true); + mViewHolder = (MediaOutputAdapter.MediaDeviceViewHolder) mMediaOutputAdapter + .onCreateViewHolder(new LinearLayout(mContext), 0); + mMediaOutputAdapter.onBindViewHolder(mViewHolder, 0); + + mViewHolder.mEndTouchArea.performClick(); + + verify(mMediaOutputController).removeDeviceFromPlayMedia(mMediaDevice1); + } + + @Test public void onItemClick_onGroupActionTriggered_verifySeekbarDisabled() { when(mMediaOutputController.getSelectedMediaDevice()).thenReturn(mMediaDevices); List<MediaDevice> selectableDevices = new ArrayList<>(); @@ -366,6 +553,26 @@ public class MediaOutputAdapterTest extends SysuiTestCase { } @Test + public void advanced_onItemClick_onGroupActionTriggered_verifySeekbarDisabled() { + when(mMediaOutputController.isAdvancedLayoutSupported()).thenReturn(true); + when(mMediaOutputController.getSelectedMediaDevice()).thenReturn( + mMediaItems.stream().map((item) -> item.getMediaDevice().get()).collect( + Collectors.toList())); + mMediaOutputAdapter = new MediaOutputAdapter(mMediaOutputController); + mViewHolder = (MediaOutputAdapter.MediaDeviceViewHolder) mMediaOutputAdapter + .onCreateViewHolder(new LinearLayout(mContext), 0); + List<MediaDevice> selectableDevices = new ArrayList<>(); + selectableDevices.add(mMediaDevice1); + when(mMediaOutputController.getSelectableMediaDevice()).thenReturn(selectableDevices); + when(mMediaOutputController.hasAdjustVolumeUserRestriction()).thenReturn(true); + mMediaOutputAdapter.onBindViewHolder(mViewHolder, 0); + + mViewHolder.mContainerLayout.performClick(); + + assertThat(mViewHolder.mSeekBar.isEnabled()).isFalse(); + } + + @Test public void onBindViewHolder_volumeControlChangeToEnabled_enableSeekbarAgain() { when(mMediaOutputController.isVolumeControlEnabled(mMediaDevice1)).thenReturn(false); mMediaOutputAdapter.onBindViewHolder(mViewHolder, 0); diff --git a/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputBaseDialogTest.java b/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputBaseDialogTest.java index 9be201e99b2b..094d69a9d392 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputBaseDialogTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputBaseDialogTest.java @@ -51,6 +51,7 @@ import com.android.systemui.R; import com.android.systemui.SysuiTestCase; import com.android.systemui.animation.DialogLaunchAnimator; import com.android.systemui.broadcast.BroadcastSender; +import com.android.systemui.flags.FeatureFlags; import com.android.systemui.media.nearby.NearbyMediaDevicesManager; import com.android.systemui.plugins.ActivityStarter; import com.android.systemui.statusbar.notification.collection.notifcollection.CommonNotifCollection; @@ -89,6 +90,7 @@ public class MediaOutputBaseDialogTest extends SysuiTestCase { private final AudioManager mAudioManager = mock(AudioManager.class); private PowerExemptionManager mPowerExemptionManager = mock(PowerExemptionManager.class); private KeyguardManager mKeyguardManager = mock(KeyguardManager.class); + private FeatureFlags mFlags = mock(FeatureFlags.class); private List<MediaController> mMediaControllers = new ArrayList<>(); private MediaOutputBaseDialogImpl mMediaOutputBaseDialogImpl; @@ -121,7 +123,7 @@ public class MediaOutputBaseDialogTest extends SysuiTestCase { mMediaSessionManager, mLocalBluetoothManager, mStarter, mNotifCollection, mDialogLaunchAnimator, Optional.of(mNearbyMediaDevicesManager), mAudioManager, mPowerExemptionManager, - mKeyguardManager); + mKeyguardManager, mFlags); mMediaOutputBaseDialogImpl = new MediaOutputBaseDialogImpl(mContext, mBroadcastSender, mMediaOutputController); mMediaOutputBaseDialogImpl.onCreate(new Bundle()); diff --git a/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputControllerTest.java index cb31fde26bf2..71c300c3fb6f 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputControllerTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputControllerTest.java @@ -62,6 +62,8 @@ import com.android.systemui.R; import com.android.systemui.SysuiTestCase; import com.android.systemui.animation.ActivityLaunchAnimator; import com.android.systemui.animation.DialogLaunchAnimator; +import com.android.systemui.flags.FeatureFlags; +import com.android.systemui.flags.Flags; import com.android.systemui.media.nearby.NearbyMediaDevicesManager; import com.android.systemui.plugins.ActivityStarter; import com.android.systemui.statusbar.notification.collection.NotificationEntry; @@ -110,6 +112,7 @@ public class MediaOutputControllerTest extends SysuiTestCase { private PowerExemptionManager mPowerExemptionManager = mock(PowerExemptionManager.class); private CommonNotifCollection mNotifCollection = mock(CommonNotifCollection.class); private final DialogLaunchAnimator mDialogLaunchAnimator = mock(DialogLaunchAnimator.class); + private FeatureFlags mFlags = mock(FeatureFlags.class); private final ActivityLaunchAnimator.Controller mActivityLaunchAnimatorController = mock( ActivityLaunchAnimator.Controller.class); private final NearbyMediaDevicesManager mNearbyMediaDevicesManager = mock( @@ -141,7 +144,8 @@ public class MediaOutputControllerTest extends SysuiTestCase { mMediaSessionManager, mLocalBluetoothManager, mStarter, mNotifCollection, mDialogLaunchAnimator, Optional.of(mNearbyMediaDevicesManager), mAudioManager, mPowerExemptionManager, - mKeyguardManager); + mKeyguardManager, mFlags); + when(mFlags.isEnabled(Flags.OUTPUT_SWITCHER_ADVANCED_LAYOUT)).thenReturn(false); mLocalMediaManager = spy(mMediaOutputController.mLocalMediaManager); mMediaOutputController.mLocalMediaManager = mLocalMediaManager; MediaDescription.Builder builder = new MediaDescription.Builder(); @@ -194,7 +198,7 @@ public class MediaOutputControllerTest extends SysuiTestCase { mMediaSessionManager, mLocalBluetoothManager, mStarter, mNotifCollection, mDialogLaunchAnimator, Optional.of(mNearbyMediaDevicesManager), mAudioManager, mPowerExemptionManager, - mKeyguardManager); + mKeyguardManager, mFlags); mMediaOutputController.start(mCb); @@ -224,7 +228,7 @@ public class MediaOutputControllerTest extends SysuiTestCase { mMediaSessionManager, mLocalBluetoothManager, mStarter, mNotifCollection, mDialogLaunchAnimator, Optional.of(mNearbyMediaDevicesManager), mAudioManager, mPowerExemptionManager, - mKeyguardManager); + mKeyguardManager, mFlags); mMediaOutputController.start(mCb); @@ -280,6 +284,25 @@ public class MediaOutputControllerTest extends SysuiTestCase { } @Test + public void advanced_onDeviceListUpdate_verifyDeviceListCallback() { + when(mFlags.isEnabled(Flags.OUTPUT_SWITCHER_ADVANCED_LAYOUT)).thenReturn(true); + mMediaOutputController.start(mCb); + reset(mCb); + + mMediaOutputController.onDeviceListUpdate(mMediaDevices); + final List<MediaDevice> devices = new ArrayList<>(); + for (MediaItem item : mMediaOutputController.getMediaItemList()) { + if (item.getMediaDevice().isPresent()) { + devices.add(item.getMediaDevice().get()); + } + } + + assertThat(devices.containsAll(mMediaDevices)).isTrue(); + assertThat(devices.size()).isEqualTo(mMediaDevices.size()); + verify(mCb).onDeviceListChanged(); + } + + @Test public void onDeviceListUpdate_isRefreshing_updatesNeedRefreshToTrue() { mMediaOutputController.start(mCb); reset(mCb); @@ -318,7 +341,7 @@ public class MediaOutputControllerTest extends SysuiTestCase { mMediaSessionManager, mLocalBluetoothManager, mStarter, mNotifCollection, mDialogLaunchAnimator, Optional.of(mNearbyMediaDevicesManager), mAudioManager, mPowerExemptionManager, - mKeyguardManager); + mKeyguardManager, mFlags); testMediaOutputController.start(mCb); reset(mCb); @@ -341,7 +364,7 @@ public class MediaOutputControllerTest extends SysuiTestCase { mMediaSessionManager, mLocalBluetoothManager, mStarter, mNotifCollection, mDialogLaunchAnimator, Optional.of(mNearbyMediaDevicesManager), mAudioManager, mPowerExemptionManager, - mKeyguardManager); + mKeyguardManager, mFlags); testMediaOutputController.start(mCb); reset(mCb); @@ -377,7 +400,7 @@ public class MediaOutputControllerTest extends SysuiTestCase { mMediaSessionManager, mLocalBluetoothManager, mStarter, mNotifCollection, mDialogLaunchAnimator, Optional.of(mNearbyMediaDevicesManager), mAudioManager, mPowerExemptionManager, - mKeyguardManager); + mKeyguardManager, mFlags); LocalMediaManager testLocalMediaManager = spy(testMediaOutputController.mLocalMediaManager); testMediaOutputController.mLocalMediaManager = testLocalMediaManager; @@ -394,7 +417,7 @@ public class MediaOutputControllerTest extends SysuiTestCase { mMediaSessionManager, mLocalBluetoothManager, mStarter, mNotifCollection, mDialogLaunchAnimator, Optional.of(mNearbyMediaDevicesManager), mAudioManager, mPowerExemptionManager, - mKeyguardManager); + mKeyguardManager, mFlags); LocalMediaManager testLocalMediaManager = spy(testMediaOutputController.mLocalMediaManager); testMediaOutputController.mLocalMediaManager = testLocalMediaManager; @@ -671,7 +694,7 @@ public class MediaOutputControllerTest extends SysuiTestCase { mMediaSessionManager, mLocalBluetoothManager, mStarter, mNotifCollection, mDialogLaunchAnimator, Optional.of(mNearbyMediaDevicesManager), mAudioManager, mPowerExemptionManager, - mKeyguardManager); + mKeyguardManager, mFlags); assertThat(mMediaOutputController.getNotificationIcon()).isNull(); } diff --git a/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputDialogTest.java b/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputDialogTest.java index bae3569cdc93..31866a8df7e5 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputDialogTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputDialogTest.java @@ -50,6 +50,7 @@ import com.android.systemui.R; import com.android.systemui.SysuiTestCase; import com.android.systemui.animation.DialogLaunchAnimator; import com.android.systemui.broadcast.BroadcastSender; +import com.android.systemui.flags.FeatureFlags; import com.android.systemui.media.nearby.NearbyMediaDevicesManager; import com.android.systemui.plugins.ActivityStarter; import com.android.systemui.statusbar.notification.collection.notifcollection.CommonNotifCollection; @@ -93,6 +94,7 @@ public class MediaOutputDialogTest extends SysuiTestCase { private final AudioManager mAudioManager = mock(AudioManager.class); private PowerExemptionManager mPowerExemptionManager = mock(PowerExemptionManager.class); private KeyguardManager mKeyguardManager = mock(KeyguardManager.class); + private FeatureFlags mFlags = mock(FeatureFlags.class); private List<MediaController> mMediaControllers = new ArrayList<>(); private MediaOutputDialog mMediaOutputDialog; @@ -115,7 +117,7 @@ public class MediaOutputDialogTest extends SysuiTestCase { mMediaSessionManager, mLocalBluetoothManager, mStarter, mNotifCollection, mDialogLaunchAnimator, Optional.of(mNearbyMediaDevicesManager), mAudioManager, mPowerExemptionManager, - mKeyguardManager); + mKeyguardManager, mFlags); mMediaOutputController.mLocalMediaManager = mLocalMediaManager; mMediaOutputDialog = new MediaOutputDialog(mContext, false, mBroadcastSender, mMediaOutputController, mUiEventLogger); diff --git a/packages/SystemUI/tests/src/com/android/systemui/media/taptotransfer/common/MediaTttUtilsTest.kt b/packages/SystemUI/tests/src/com/android/systemui/media/taptotransfer/common/MediaTttUtilsTest.kt index 6a4c0f60466d..cce3e369c0b8 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/media/taptotransfer/common/MediaTttUtilsTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/media/taptotransfer/common/MediaTttUtilsTest.kt @@ -65,41 +65,14 @@ class MediaTttUtilsTest : SysuiTestCase() { } @Test - fun getIconFromPackageName_nullPackageName_returnsDefault() { - val icon = MediaTttUtils.getIconFromPackageName(context, appPackageName = null, logger) - - val expectedDesc = - ContentDescription.Resource(R.string.media_output_dialog_unknown_launch_app_name) - .loadContentDescription(context) - assertThat(icon.contentDescription.loadContentDescription(context)).isEqualTo(expectedDesc) - } - - @Test - fun getIconFromPackageName_invalidPackageName_returnsDefault() { - val icon = MediaTttUtils.getIconFromPackageName(context, "fakePackageName", logger) - - val expectedDesc = - ContentDescription.Resource(R.string.media_output_dialog_unknown_launch_app_name) - .loadContentDescription(context) - assertThat(icon.contentDescription.loadContentDescription(context)).isEqualTo(expectedDesc) - } - - @Test - fun getIconFromPackageName_validPackageName_returnsAppInfo() { - val icon = MediaTttUtils.getIconFromPackageName(context, PACKAGE_NAME, logger) - - assertThat(icon) - .isEqualTo(Icon.Loaded(appIconFromPackageName, ContentDescription.Loaded(APP_NAME))) - } - - @Test fun getIconInfoFromPackageName_nullPackageName_returnsDefault() { val iconInfo = MediaTttUtils.getIconInfoFromPackageName(context, appPackageName = null, logger) assertThat(iconInfo.isAppIcon).isFalse() - assertThat(iconInfo.contentDescription) + assertThat(iconInfo.contentDescription.loadContentDescription(context)) .isEqualTo(context.getString(R.string.media_output_dialog_unknown_launch_app_name)) + assertThat(iconInfo.icon).isEqualTo(MediaTttIcon.Resource(R.drawable.ic_cast)) } @Test @@ -107,8 +80,9 @@ class MediaTttUtilsTest : SysuiTestCase() { val iconInfo = MediaTttUtils.getIconInfoFromPackageName(context, "fakePackageName", logger) assertThat(iconInfo.isAppIcon).isFalse() - assertThat(iconInfo.contentDescription) + assertThat(iconInfo.contentDescription.loadContentDescription(context)) .isEqualTo(context.getString(R.string.media_output_dialog_unknown_launch_app_name)) + assertThat(iconInfo.icon).isEqualTo(MediaTttIcon.Resource(R.drawable.ic_cast)) } @Test @@ -116,8 +90,48 @@ class MediaTttUtilsTest : SysuiTestCase() { val iconInfo = MediaTttUtils.getIconInfoFromPackageName(context, PACKAGE_NAME, logger) assertThat(iconInfo.isAppIcon).isTrue() - assertThat(iconInfo.drawable).isEqualTo(appIconFromPackageName) - assertThat(iconInfo.contentDescription).isEqualTo(APP_NAME) + assertThat(iconInfo.icon).isEqualTo(MediaTttIcon.Loaded(appIconFromPackageName)) + assertThat(iconInfo.contentDescription.loadContentDescription(context)).isEqualTo(APP_NAME) + } + + @Test + fun iconInfo_toTintedIcon_loaded() { + val contentDescription = ContentDescription.Loaded("test") + val drawable = context.getDrawable(R.drawable.ic_cake)!! + val tintAttr = android.R.attr.textColorTertiary + + val iconInfo = + IconInfo( + contentDescription, + MediaTttIcon.Loaded(drawable), + tintAttr, + isAppIcon = false, + ) + + val tinted = iconInfo.toTintedIcon() + + assertThat(tinted.icon).isEqualTo(Icon.Loaded(drawable, contentDescription)) + assertThat(tinted.tintAttr).isEqualTo(tintAttr) + } + + @Test + fun iconInfo_toTintedIcon_resource() { + val contentDescription = ContentDescription.Loaded("test") + val drawableRes = R.drawable.ic_cake + val tintAttr = android.R.attr.textColorTertiary + + val iconInfo = + IconInfo( + contentDescription, + MediaTttIcon.Resource(drawableRes), + tintAttr, + isAppIcon = false + ) + + val tinted = iconInfo.toTintedIcon() + + assertThat(tinted.icon).isEqualTo(Icon.Resource(drawableRes, contentDescription)) + assertThat(tinted.tintAttr).isEqualTo(tintAttr) } } diff --git a/packages/SystemUI/tests/src/com/android/systemui/navigationbar/TaskbarDelegateTest.kt b/packages/SystemUI/tests/src/com/android/systemui/navigationbar/TaskbarDelegateTest.kt new file mode 100644 index 000000000000..1742c6994246 --- /dev/null +++ b/packages/SystemUI/tests/src/com/android/systemui/navigationbar/TaskbarDelegateTest.kt @@ -0,0 +1,93 @@ +package com.android.systemui.navigationbar + +import androidx.test.filters.SmallTest +import com.android.systemui.SysuiTestCase +import com.android.systemui.dump.DumpManager +import com.android.systemui.model.SysUiState +import com.android.systemui.navigationbar.gestural.EdgeBackGestureHandler +import com.android.systemui.recents.OverviewProxyService +import com.android.systemui.statusbar.CommandQueue +import com.android.systemui.statusbar.phone.AutoHideController +import com.android.systemui.statusbar.phone.LightBarController +import com.android.systemui.statusbar.phone.LightBarTransitionsController +import com.android.wm.shell.back.BackAnimation +import com.android.wm.shell.pip.Pip +import org.junit.Before +import org.junit.Test +import org.mockito.Mock +import org.mockito.Mockito.`when` +import org.mockito.Mockito.any +import org.mockito.Mockito.anyBoolean +import org.mockito.Mockito.anyInt +import org.mockito.Mockito.times +import org.mockito.Mockito.verify +import org.mockito.MockitoAnnotations +import java.util.Optional + +@SmallTest +class TaskbarDelegateTest : SysuiTestCase() { + val DISPLAY_ID = 0; + val MODE_GESTURE = 0; + val MODE_THREE_BUTTON = 1; + + private lateinit var mTaskbarDelegate: TaskbarDelegate + @Mock + lateinit var mEdgeBackGestureHandlerFactory : EdgeBackGestureHandler.Factory + @Mock + lateinit var mEdgeBackGestureHandler : EdgeBackGestureHandler + @Mock + lateinit var mLightBarControllerFactory : LightBarTransitionsController.Factory + @Mock + lateinit var mLightBarTransitionController: LightBarTransitionsController + @Mock + lateinit var mCommandQueue: CommandQueue + @Mock + lateinit var mOverviewProxyService: OverviewProxyService + @Mock + lateinit var mNavBarHelper: NavBarHelper + @Mock + lateinit var mNavigationModeController: NavigationModeController + @Mock + lateinit var mSysUiState: SysUiState + @Mock + lateinit var mDumpManager: DumpManager + @Mock + lateinit var mAutoHideController: AutoHideController + @Mock + lateinit var mLightBarController: LightBarController + @Mock + lateinit var mOptionalPip: Optional<Pip> + @Mock + lateinit var mBackAnimation: BackAnimation + @Mock + lateinit var mCurrentSysUiState: NavBarHelper.CurrentSysuiState + + @Before + fun setup() { + MockitoAnnotations.initMocks(this) + `when`(mEdgeBackGestureHandlerFactory.create(context)).thenReturn(mEdgeBackGestureHandler) + `when`(mLightBarControllerFactory.create(any())).thenReturn(mLightBarTransitionController) + `when`(mNavBarHelper.currentSysuiState).thenReturn(mCurrentSysUiState) + `when`(mSysUiState.setFlag(anyInt(), anyBoolean())).thenReturn(mSysUiState) + mTaskbarDelegate = TaskbarDelegate(context, mEdgeBackGestureHandlerFactory, + mLightBarControllerFactory) + mTaskbarDelegate.setDependencies(mCommandQueue, mOverviewProxyService, mNavBarHelper, + mNavigationModeController, mSysUiState, mDumpManager, mAutoHideController, + mLightBarController, mOptionalPip, mBackAnimation) + } + + @Test + fun navigationModeInitialized() { + `when`(mNavigationModeController.addListener(any())).thenReturn(MODE_THREE_BUTTON) + assert(mTaskbarDelegate.navigationMode == -1) + mTaskbarDelegate.init(DISPLAY_ID) + assert(mTaskbarDelegate.navigationMode == MODE_THREE_BUTTON) + } + + @Test + fun navigationModeInitialized_notifyEdgeBackHandler() { + `when`(mNavigationModeController.addListener(any())).thenReturn(MODE_GESTURE) + mTaskbarDelegate.init(DISPLAY_ID) + verify(mEdgeBackGestureHandler, times(1)).onNavigationModeChanged(MODE_GESTURE) + } +}
\ No newline at end of file diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/FooterActionsControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/FooterActionsControllerTest.kt deleted file mode 100644 index 2ba8782c6d02..000000000000 --- a/packages/SystemUI/tests/src/com/android/systemui/qs/FooterActionsControllerTest.kt +++ /dev/null @@ -1,440 +0,0 @@ -package com.android.systemui.qs - -import android.content.Intent -import android.os.Handler -import android.os.UserManager -import android.provider.Settings -import android.testing.AndroidTestingRunner -import android.testing.TestableLooper -import android.testing.ViewUtils -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import androidx.test.filters.SmallTest -import com.android.internal.logging.MetricsLogger -import com.android.internal.logging.UiEventLogger -import com.android.internal.logging.testing.FakeMetricsLogger -import com.android.systemui.R -import com.android.systemui.animation.ActivityLaunchAnimator -import com.android.systemui.classifier.FalsingManagerFake -import com.android.systemui.globalactions.GlobalActionsDialogLite -import com.android.systemui.plugins.ActivityStarter -import com.android.systemui.settings.UserTracker -import com.android.systemui.statusbar.phone.MultiUserSwitchController -import com.android.systemui.statusbar.policy.DeviceProvisionedController -import com.android.systemui.statusbar.policy.FakeConfigurationController -import com.android.systemui.statusbar.policy.UserInfoController -import com.android.systemui.util.mockito.capture -import com.android.systemui.util.settings.FakeSettings -import com.android.systemui.utils.leaks.LeakCheckedTest -import com.google.common.truth.Expect -import com.google.common.truth.Truth.assertThat -import javax.inject.Provider -import org.junit.After -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.ArgumentCaptor -import org.mockito.ArgumentMatchers.any -import org.mockito.ArgumentMatchers.anyBoolean -import org.mockito.Captor -import org.mockito.Mock -import org.mockito.Mockito -import org.mockito.Mockito.atLeastOnce -import org.mockito.Mockito.clearInvocations -import org.mockito.Mockito.never -import org.mockito.Mockito.reset -import org.mockito.Mockito.verify -import org.mockito.Mockito.`when` as whenever -import org.mockito.MockitoAnnotations - -@SmallTest -@TestableLooper.RunWithLooper(setAsMainLooper = true) -@RunWith(AndroidTestingRunner::class) -class FooterActionsControllerTest : LeakCheckedTest() { - - @get:Rule var expect: Expect = Expect.create() - - @Mock private lateinit var userManager: UserManager - @Mock private lateinit var userTracker: UserTracker - @Mock private lateinit var activityStarter: ActivityStarter - @Mock private lateinit var deviceProvisionedController: DeviceProvisionedController - @Mock private lateinit var userInfoController: UserInfoController - @Mock private lateinit var multiUserSwitchControllerFactory: MultiUserSwitchController.Factory - @Mock private lateinit var multiUserSwitchController: MultiUserSwitchController - @Mock private lateinit var globalActionsDialogProvider: Provider<GlobalActionsDialogLite> - @Mock private lateinit var globalActionsDialog: GlobalActionsDialogLite - @Mock private lateinit var uiEventLogger: UiEventLogger - @Mock private lateinit var securityFooterController: QSSecurityFooter - @Mock private lateinit var fgsManagerController: QSFgsManagerFooter - @Captor - private lateinit var visibilityChangedCaptor: - ArgumentCaptor<VisibilityChangedDispatcher.OnVisibilityChangedListener> - - private lateinit var controller: FooterActionsController - - private val configurationController = FakeConfigurationController() - private val metricsLogger: MetricsLogger = FakeMetricsLogger() - private val falsingManager: FalsingManagerFake = FalsingManagerFake() - private lateinit var view: FooterActionsView - private lateinit var testableLooper: TestableLooper - private lateinit var fakeSettings: FakeSettings - private lateinit var securityFooter: View - private lateinit var fgsFooter: View - - @Before - fun setUp() { - // We want to make sure testable resources are always used - context.ensureTestableResources() - - MockitoAnnotations.initMocks(this) - testableLooper = TestableLooper.get(this) - fakeSettings = FakeSettings() - - whenever(multiUserSwitchControllerFactory.create(any())) - .thenReturn(multiUserSwitchController) - whenever(globalActionsDialogProvider.get()).thenReturn(globalActionsDialog) - - securityFooter = View(mContext) - fgsFooter = View(mContext) - - whenever(securityFooterController.view).thenReturn(securityFooter) - whenever(fgsManagerController.view).thenReturn(fgsFooter) - - view = inflateView() - - controller = constructFooterActionsController(view) - controller.init() - ViewUtils.attachView(view) - // View looper is the testable looper associated with the test - testableLooper.processAllMessages() - } - - @After - fun tearDown() { - if (view.isAttachedToWindow) { - ViewUtils.detachView(view) - } - } - - @Test - fun testInitializesControllers() { - verify(multiUserSwitchController).init() - verify(fgsManagerController).init() - verify(securityFooterController).init() - } - - @Test - fun testLogPowerMenuClick() { - controller.visible = true - falsingManager.setFalseTap(false) - - view.findViewById<View>(R.id.pm_lite).performClick() - // Verify clicks are logged - verify(uiEventLogger, Mockito.times(1)) - .log(GlobalActionsDialogLite.GlobalActionsEvent.GA_OPEN_QS) - } - - @Test - fun testSettings() { - val captor = ArgumentCaptor.forClass(Intent::class.java) - whenever(deviceProvisionedController.isCurrentUserSetup).thenReturn(true) - view.findViewById<View>(R.id.settings_button_container).performClick() - - verify(activityStarter) - .startActivity(capture(captor), anyBoolean(), any<ActivityLaunchAnimator.Controller>()) - - assertThat(captor.value.action).isEqualTo(Settings.ACTION_SETTINGS) - } - - @Test - fun testSettings_UserNotSetup() { - whenever(deviceProvisionedController.isCurrentUserSetup).thenReturn(false) - view.findViewById<View>(R.id.settings_button_container).performClick() - // Verify Settings wasn't launched. - verify(activityStarter, never()) - .startActivity(any(), anyBoolean(), any<ActivityLaunchAnimator.Controller>()) - } - - @Test - fun testMultiUserSwitchUpdatedWhenExpansionStarts() { - // When expansion starts, listening is set to true - val multiUserSwitch = view.requireViewById<View>(R.id.multi_user_switch) - - assertThat(multiUserSwitch.visibility).isNotEqualTo(View.VISIBLE) - - whenever(multiUserSwitchController.isMultiUserEnabled).thenReturn(true) - - controller.setListening(true) - testableLooper.processAllMessages() - - assertThat(multiUserSwitch.visibility).isEqualTo(View.VISIBLE) - } - - @Test - fun testMultiUserSwitchUpdatedWhenSettingChanged() { - // Always listening to setting while View is attached - testableLooper.processAllMessages() - - val multiUserSwitch = view.requireViewById<View>(R.id.multi_user_switch) - assertThat(multiUserSwitch.visibility).isNotEqualTo(View.VISIBLE) - - // The setting is only used as an indicator for whether the view should refresh. The actual - // value of the setting is ignored; isMultiUserEnabled is the source of truth - whenever(multiUserSwitchController.isMultiUserEnabled).thenReturn(true) - - // Changing the value of USER_SWITCHER_ENABLED should cause the view to update - fakeSettings.putIntForUser(Settings.Global.USER_SWITCHER_ENABLED, 1, userTracker.userId) - testableLooper.processAllMessages() - - assertThat(multiUserSwitch.visibility).isEqualTo(View.VISIBLE) - } - - @Test - fun testMultiUserSettingNotListenedAfterDetach() { - testableLooper.processAllMessages() - - val multiUserSwitch = view.requireViewById<View>(R.id.multi_user_switch) - assertThat(multiUserSwitch.visibility).isNotEqualTo(View.VISIBLE) - - ViewUtils.detachView(view) - - // The setting is only used as an indicator for whether the view should refresh. The actual - // value of the setting is ignored; isMultiUserEnabled is the source of truth - whenever(multiUserSwitchController.isMultiUserEnabled).thenReturn(true) - - // Changing the value of USER_SWITCHER_ENABLED should cause the view to update - fakeSettings.putIntForUser(Settings.Global.USER_SWITCHER_ENABLED, 1, userTracker.userId) - testableLooper.processAllMessages() - - assertThat(multiUserSwitch.visibility).isNotEqualTo(View.VISIBLE) - } - - @Test - fun testCleanUpGAD() { - reset(globalActionsDialogProvider) - // We are creating a new controller, so detach the views from it - (securityFooter.parent as ViewGroup).removeView(securityFooter) - (fgsFooter.parent as ViewGroup).removeView(fgsFooter) - - whenever(globalActionsDialogProvider.get()).thenReturn(globalActionsDialog) - val view = inflateView() - controller = constructFooterActionsController(view) - controller.init() - verify(globalActionsDialogProvider, never()).get() - - // GAD is constructed during attachment - ViewUtils.attachView(view) - testableLooper.processAllMessages() - verify(globalActionsDialogProvider).get() - - ViewUtils.detachView(view) - testableLooper.processAllMessages() - verify(globalActionsDialog).destroy() - } - - @Test - fun testSeparatorVisibility_noneVisible_gone() { - verify(securityFooterController) - .setOnVisibilityChangedListener(capture(visibilityChangedCaptor)) - val listener = visibilityChangedCaptor.value - val separator = controller.securityFootersSeparator - - setVisibilities(securityFooterVisible = false, fgsFooterVisible = false, listener) - assertThat(separator.visibility).isEqualTo(View.GONE) - } - - @Test - fun testSeparatorVisibility_onlySecurityFooterVisible_gone() { - verify(securityFooterController) - .setOnVisibilityChangedListener(capture(visibilityChangedCaptor)) - val listener = visibilityChangedCaptor.value - val separator = controller.securityFootersSeparator - - setVisibilities(securityFooterVisible = true, fgsFooterVisible = false, listener) - assertThat(separator.visibility).isEqualTo(View.GONE) - } - - @Test - fun testSeparatorVisibility_onlyFgsFooterVisible_gone() { - verify(securityFooterController) - .setOnVisibilityChangedListener(capture(visibilityChangedCaptor)) - val listener = visibilityChangedCaptor.value - val separator = controller.securityFootersSeparator - - setVisibilities(securityFooterVisible = false, fgsFooterVisible = true, listener) - assertThat(separator.visibility).isEqualTo(View.GONE) - } - - @Test - fun testSeparatorVisibility_bothVisible_visible() { - verify(securityFooterController) - .setOnVisibilityChangedListener(capture(visibilityChangedCaptor)) - val listener = visibilityChangedCaptor.value - val separator = controller.securityFootersSeparator - - setVisibilities(securityFooterVisible = true, fgsFooterVisible = true, listener) - assertThat(separator.visibility).isEqualTo(View.VISIBLE) - } - - @Test - fun testFgsFooterCollapsed() { - verify(securityFooterController) - .setOnVisibilityChangedListener(capture(visibilityChangedCaptor)) - val listener = visibilityChangedCaptor.value - - val booleanCaptor = ArgumentCaptor.forClass(Boolean::class.java) - - clearInvocations(fgsManagerController) - setVisibilities(securityFooterVisible = false, fgsFooterVisible = true, listener) - verify(fgsManagerController, atLeastOnce()).setCollapsed(capture(booleanCaptor)) - assertThat(booleanCaptor.allValues.last()).isFalse() - - clearInvocations(fgsManagerController) - setVisibilities(securityFooterVisible = true, fgsFooterVisible = true, listener) - verify(fgsManagerController, atLeastOnce()).setCollapsed(capture(booleanCaptor)) - assertThat(booleanCaptor.allValues.last()).isTrue() - } - - @Test - fun setExpansion_inSplitShade_alphaFollowsExpansion() { - enableSplitShade() - - controller.setExpansion(0f) - expect.that(view.alpha).isEqualTo(0f) - - controller.setExpansion(0.25f) - expect.that(view.alpha).isEqualTo(0.25f) - - controller.setExpansion(0.5f) - expect.that(view.alpha).isEqualTo(0.5f) - - controller.setExpansion(0.75f) - expect.that(view.alpha).isEqualTo(0.75f) - - controller.setExpansion(1f) - expect.that(view.alpha).isEqualTo(1f) - } - - @Test - fun setExpansion_inSplitShade_backgroundAlphaFollowsExpansion_with_0_9_delay() { - enableSplitShade() - - controller.setExpansion(0f) - expect.that(view.backgroundAlphaFraction).isEqualTo(0f) - - controller.setExpansion(0.5f) - expect.that(view.backgroundAlphaFraction).isEqualTo(0f) - - controller.setExpansion(0.9f) - expect.that(view.backgroundAlphaFraction).isEqualTo(0f) - - controller.setExpansion(0.91f) - expect.that(view.backgroundAlphaFraction).isWithin(FLOAT_TOLERANCE).of(0.1f) - - controller.setExpansion(0.95f) - expect.that(view.backgroundAlphaFraction).isWithin(FLOAT_TOLERANCE).of(0.5f) - - controller.setExpansion(1f) - expect.that(view.backgroundAlphaFraction).isEqualTo(1f) - } - - @Test - fun setExpansion_inSingleShade_alphaFollowsExpansion_with_0_9_delay() { - disableSplitShade() - - controller.setExpansion(0f) - expect.that(view.alpha).isEqualTo(0f) - - controller.setExpansion(0.5f) - expect.that(view.alpha).isEqualTo(0f) - - controller.setExpansion(0.9f) - expect.that(view.alpha).isEqualTo(0f) - - controller.setExpansion(0.91f) - expect.that(view.alpha).isWithin(FLOAT_TOLERANCE).of(0.1f) - - controller.setExpansion(0.95f) - expect.that(view.alpha).isWithin(FLOAT_TOLERANCE).of(0.5f) - - controller.setExpansion(1f) - expect.that(view.alpha).isEqualTo(1f) - } - - @Test - fun setExpansion_inSingleShade_backgroundAlphaAlways1() { - disableSplitShade() - - controller.setExpansion(0f) - expect.that(view.backgroundAlphaFraction).isEqualTo(1f) - - controller.setExpansion(0.5f) - expect.that(view.backgroundAlphaFraction).isEqualTo(1f) - - controller.setExpansion(1f) - expect.that(view.backgroundAlphaFraction).isEqualTo(1f) - } - - private fun setVisibilities( - securityFooterVisible: Boolean, - fgsFooterVisible: Boolean, - listener: VisibilityChangedDispatcher.OnVisibilityChangedListener - ) { - securityFooter.visibility = if (securityFooterVisible) View.VISIBLE else View.GONE - listener.onVisibilityChanged(securityFooter.visibility) - fgsFooter.visibility = if (fgsFooterVisible) View.VISIBLE else View.GONE - listener.onVisibilityChanged(fgsFooter.visibility) - } - - private fun inflateView(): FooterActionsView { - return LayoutInflater.from(context).inflate(R.layout.footer_actions, null) - as FooterActionsView - } - - private fun constructFooterActionsController(view: FooterActionsView): FooterActionsController { - return FooterActionsController( - view, - multiUserSwitchControllerFactory, - activityStarter, - userManager, - userTracker, - userInfoController, - deviceProvisionedController, - securityFooterController, - fgsManagerController, - falsingManager, - metricsLogger, - globalActionsDialogProvider, - uiEventLogger, - showPMLiteButton = true, - fakeSettings, - Handler(testableLooper.looper), - configurationController) - } - - private fun enableSplitShade() { - setSplitShadeEnabled(true) - } - - private fun disableSplitShade() { - setSplitShadeEnabled(false) - } - - private fun setSplitShadeEnabled(enabled: Boolean) { - overrideResource(R.bool.config_use_split_notification_shade, enabled) - configurationController.notifyConfigurationChanged() - } -} - -private const val FLOAT_TOLERANCE = 0.01f - -private val View.backgroundAlphaFraction: Float? - get() { - return if (background != null) { - background.alpha / 255f - } else { - null - } - } diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/QSFragmentTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/QSFragmentTest.java index aedb9354e6db..ffe918d36d6f 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/qs/QSFragmentTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/qs/QSFragmentTest.java @@ -25,6 +25,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -32,6 +33,7 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import android.annotation.Nullable; import android.app.Fragment; import android.content.Context; import android.graphics.Rect; @@ -42,6 +44,7 @@ import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; +import androidx.lifecycle.Lifecycle; import androidx.test.filters.SmallTest; import com.android.keyguard.BouncerPanelExpansionCalculator; @@ -50,12 +53,12 @@ import com.android.systemui.SysuiBaseFragmentTest; import com.android.systemui.animation.ShadeInterpolation; import com.android.systemui.dump.DumpManager; import com.android.systemui.flags.FakeFeatureFlags; -import com.android.systemui.flags.Flags; import com.android.systemui.media.controls.ui.MediaHost; import com.android.systemui.plugins.FalsingManager; import com.android.systemui.qs.customize.QSCustomizerController; import com.android.systemui.qs.dagger.QSFragmentComponent; import com.android.systemui.qs.external.TileServiceRequestController; +import com.android.systemui.qs.footer.ui.binder.FooterActionsViewBinder; import com.android.systemui.qs.footer.ui.viewmodel.FooterActionsViewModel; import com.android.systemui.statusbar.CommandQueue; import com.android.systemui.statusbar.StatusBarState; @@ -99,6 +102,8 @@ public class QSFragmentTest extends SysuiBaseFragmentTest { @Mock private QSAnimator mQSAnimator; @Mock private SysuiStatusBarStateController mStatusBarStateController; @Mock private QSSquishinessController mSquishinessController; + @Mock private FooterActionsViewModel mFooterActionsViewModel; + @Mock private FooterActionsViewModel.Factory mFooterActionsViewModelFactory; private View mQsFragmentView; public QSFragmentTest() { @@ -245,7 +250,8 @@ public class QSFragmentTest extends SysuiBaseFragmentTest { fragment.setQsExpansion(expansion, panelExpansionFraction, proposedTranslation, squishinessFraction); - verify(mQSFooterActionController).setExpansion(panelExpansionFraction); + verify(mFooterActionsViewModel).onQuickSettingsExpansionChanged( + panelExpansionFraction, /* isInSplitShade= */ true); } @Test @@ -262,7 +268,8 @@ public class QSFragmentTest extends SysuiBaseFragmentTest { fragment.setQsExpansion(expansion, panelExpansionFraction, proposedTranslation, squishinessFraction); - verify(mQSFooterActionController).setExpansion(expansion); + verify(mFooterActionsViewModel).onQuickSettingsExpansionChanged( + expansion, /* isInSplitShade= */ false); } @Test @@ -379,6 +386,13 @@ public class QSFragmentTest extends SysuiBaseFragmentTest { assertThat(mQsFragmentView.getTranslationY()).isEqualTo(0); } + private Lifecycle.State getListeningAndVisibilityLifecycleState() { + return getFragment() + .getListeningAndVisibilityLifecycleOwner() + .getLifecycle() + .getCurrentState(); + } + @Test public void setListeningFalse_notVisible() { QSFragment fragment = resumeAndGetFragment(); @@ -387,7 +401,7 @@ public class QSFragmentTest extends SysuiBaseFragmentTest { fragment.setListening(false); verify(mQSContainerImplController).setListening(false); - verify(mQSFooterActionController).setListening(false); + assertThat(getListeningAndVisibilityLifecycleState()).isEqualTo(Lifecycle.State.CREATED); verify(mQSPanelController).setListening(eq(false), anyBoolean()); } @@ -399,7 +413,7 @@ public class QSFragmentTest extends SysuiBaseFragmentTest { fragment.setListening(true); verify(mQSContainerImplController).setListening(false); - verify(mQSFooterActionController).setListening(false); + assertThat(getListeningAndVisibilityLifecycleState()).isEqualTo(Lifecycle.State.STARTED); verify(mQSPanelController).setListening(eq(false), anyBoolean()); } @@ -411,7 +425,7 @@ public class QSFragmentTest extends SysuiBaseFragmentTest { fragment.setListening(false); verify(mQSContainerImplController).setListening(false); - verify(mQSFooterActionController).setListening(false); + assertThat(getListeningAndVisibilityLifecycleState()).isEqualTo(Lifecycle.State.CREATED); verify(mQSPanelController).setListening(eq(false), anyBoolean()); } @@ -423,7 +437,7 @@ public class QSFragmentTest extends SysuiBaseFragmentTest { fragment.setListening(true); verify(mQSContainerImplController).setListening(true); - verify(mQSFooterActionController).setListening(true); + assertThat(getListeningAndVisibilityLifecycleState()).isEqualTo(Lifecycle.State.RESUMED); verify(mQSPanelController).setListening(eq(true), anyBoolean()); } @@ -480,7 +494,6 @@ public class QSFragmentTest extends SysuiBaseFragmentTest { setUpOther(); FakeFeatureFlags featureFlags = new FakeFeatureFlags(); - featureFlags.set(Flags.NEW_FOOTER_ACTIONS, false); return new QSFragment( new RemoteInputQuickSettingsDisabler( context, commandQueue, mock(ConfigurationController.class)), @@ -495,8 +508,8 @@ public class QSFragmentTest extends SysuiBaseFragmentTest { mFalsingManager, mock(DumpManager.class), featureFlags, - mock(NewFooterActionsController.class), - mock(FooterActionsViewModel.Factory.class)); + mock(FooterActionsController.class), + mFooterActionsViewModelFactory); } private void setUpOther() { @@ -505,6 +518,7 @@ public class QSFragmentTest extends SysuiBaseFragmentTest { when(mQSContainerImplController.getView()).thenReturn(mContainer); when(mQSPanelController.getTileLayout()).thenReturn(mQQsTileLayout); when(mQuickQSPanelController.getTileLayout()).thenReturn(mQsTileLayout); + when(mFooterActionsViewModelFactory.create(any())).thenReturn(mFooterActionsViewModel); } private void setUpMedia() { @@ -519,15 +533,40 @@ public class QSFragmentTest extends SysuiBaseFragmentTest { .thenReturn(mQSPanelScrollView); when(mQsFragmentView.findViewById(R.id.header)).thenReturn(mHeader); when(mQsFragmentView.findViewById(android.R.id.edit)).thenReturn(new View(mContext)); + when(mQsFragmentView.findViewById(R.id.qs_footer_actions)).thenAnswer( + invocation -> FooterActionsViewBinder.create(mContext)); } private void setUpInflater() { + LayoutInflater realInflater = LayoutInflater.from(mContext); + when(mLayoutInflater.cloneInContext(any(Context.class))).thenReturn(mLayoutInflater); - when(mLayoutInflater.inflate(anyInt(), any(ViewGroup.class), anyBoolean())) - .thenReturn(mQsFragmentView); + when(mLayoutInflater.inflate(anyInt(), nullable(ViewGroup.class), anyBoolean())) + .thenAnswer((invocation) -> inflate(realInflater, (int) invocation.getArgument(0), + (ViewGroup) invocation.getArgument(1), + (boolean) invocation.getArgument(2))); + when(mLayoutInflater.inflate(anyInt(), nullable(ViewGroup.class))) + .thenAnswer((invocation) -> inflate(realInflater, (int) invocation.getArgument(0), + (ViewGroup) invocation.getArgument(1))); mContext.addMockSystemService(Context.LAYOUT_INFLATER_SERVICE, mLayoutInflater); } + private View inflate(LayoutInflater realInflater, int layoutRes, @Nullable ViewGroup root) { + return inflate(realInflater, layoutRes, root, root != null); + } + + private View inflate(LayoutInflater realInflater, int layoutRes, @Nullable ViewGroup root, + boolean attachToRoot) { + if (layoutRes == R.layout.footer_actions + || layoutRes == R.layout.footer_actions_text_button + || layoutRes == R.layout.footer_actions_number_button + || layoutRes == R.layout.footer_actions_icon_button) { + return realInflater.inflate(layoutRes, root, attachToRoot); + } + + return mQsFragmentView; + } + private void setupQsComponent() { when(mQsComponentFactory.create(any(QSFragment.class))).thenReturn(mQsFragmentComponent); when(mQsFragmentComponent.getQSPanelController()).thenReturn(mQSPanelController); diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/QSSecurityFooterTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/QSSecurityFooterTest.java index 906c20b1d032..c656d6dd1a35 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/qs/QSSecurityFooterTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/qs/QSSecurityFooterTest.java @@ -17,23 +17,24 @@ package com.android.systemui.qs; import static android.app.admin.DevicePolicyManager.DEVICE_OWNER_TYPE_DEFAULT; import static android.app.admin.DevicePolicyManager.DEVICE_OWNER_TYPE_FINANCED; +import static com.google.common.truth.Truth.assertThat; + import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; +import static junit.framework.Assert.assertNull; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import android.annotation.IdRes; import android.app.AlertDialog; import android.app.admin.DevicePolicyManager; -import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.DialogInterface; -import android.content.Intent; import android.content.pm.UserInfo; import android.graphics.drawable.Drawable; import android.graphics.drawable.VectorDrawable; @@ -42,27 +43,27 @@ import android.os.Looper; import android.provider.Settings; import android.test.suitebuilder.annotation.SmallTest; import android.testing.AndroidTestingRunner; -import android.testing.LayoutInflaterBuilder; -import android.testing.TestableImageView; import android.testing.TestableLooper; import android.testing.TestableLooper.RunWithLooper; -import android.testing.ViewUtils; import android.text.SpannableStringBuilder; import android.view.LayoutInflater; import android.view.View; -import android.view.ViewGroup; -import android.widget.FrameLayout; import android.widget.TextView; +import androidx.annotation.Nullable; + import com.android.systemui.R; import com.android.systemui.SysuiTestCase; import com.android.systemui.animation.DialogLaunchAnimator; +import com.android.systemui.animation.Expandable; import com.android.systemui.broadcast.BroadcastDispatcher; +import com.android.systemui.common.shared.model.Icon; import com.android.systemui.plugins.ActivityStarter; +import com.android.systemui.qs.footer.domain.model.SecurityButtonConfig; +import com.android.systemui.security.data.model.SecurityModel; import com.android.systemui.settings.UserTracker; import com.android.systemui.statusbar.policy.SecurityController; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -71,8 +72,6 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import java.util.concurrent.atomic.AtomicInteger; - /* * Compile and run the whole SystemUI test suite: runtest --path frameworks/base/packages/SystemUI/tests @@ -96,11 +95,6 @@ public class QSSecurityFooterTest extends SysuiTestCase { new ComponentName("TestDPC", "Test"); private static final int DEFAULT_ICON_ID = R.drawable.ic_info_outline; - private ViewGroup mRootView; - private ViewGroup mSecurityFooterView; - private TextView mFooterText; - private TestableImageView mPrimaryFooterIcon; - private QSSecurityFooter mFooter; private QSSecurityFooterUtils mFooterUtils; @Mock private SecurityController mSecurityController; @@ -122,58 +116,53 @@ public class QSSecurityFooterTest extends SysuiTestCase { Looper looper = mTestableLooper.getLooper(); Handler mainHandler = new Handler(looper); when(mUserTracker.getUserInfo()).thenReturn(mock(UserInfo.class)); - mSecurityFooterView = (ViewGroup) new LayoutInflaterBuilder(mContext) - .replace("ImageView", TestableImageView.class) - .build().inflate(R.layout.quick_settings_security_footer, null, false); mFooterUtils = new QSSecurityFooterUtils(getContext(), getContext().getSystemService(DevicePolicyManager.class), mUserTracker, mainHandler, mActivityStarter, mSecurityController, looper, mDialogLaunchAnimator); - mFooter = new QSSecurityFooter(mSecurityFooterView, mainHandler, mSecurityController, - looper, mBroadcastDispatcher, mFooterUtils); - mFooterText = mSecurityFooterView.findViewById(R.id.footer_text); - mPrimaryFooterIcon = mSecurityFooterView.findViewById(R.id.primary_footer_icon); when(mSecurityController.getDeviceOwnerComponentOnAnyUser()) .thenReturn(DEVICE_OWNER_COMPONENT); when(mSecurityController.getDeviceOwnerType(DEVICE_OWNER_COMPONENT)) .thenReturn(DEVICE_OWNER_TYPE_DEFAULT); + } - // mSecurityFooterView must have a ViewGroup parent so that - // DialogLaunchAnimator.Controller.fromView() does not return null. - mRootView = new FrameLayout(mContext); - mRootView.addView(mSecurityFooterView); - ViewUtils.attachView(mRootView); + @Nullable + private SecurityButtonConfig getButtonConfig() { + SecurityModel securityModel = SecurityModel.create(mSecurityController); + return mFooterUtils.getButtonConfig(securityModel); + } + + private void assertIsDefaultIcon(Icon icon) { + assertIsIconResource(icon, DEFAULT_ICON_ID); + } - mFooter.init(); + private void assertIsIconResource(Icon icon, @IdRes int res) { + assertThat(icon).isInstanceOf(Icon.Resource.class); + assertEquals(res, ((Icon.Resource) icon).getRes()); } - @After - public void tearDown() { - ViewUtils.detachView(mRootView); + private void assertIsIconDrawable(Icon icon, Drawable drawable) { + assertThat(icon).isInstanceOf(Icon.Loaded.class); + assertEquals(drawable, ((Icon.Loaded) icon).getDrawable()); } @Test public void testUnmanaged() { when(mSecurityController.isDeviceManaged()).thenReturn(false); when(mSecurityController.isProfileOwnerOfOrganizationOwnedDevice()).thenReturn(false); - mFooter.refreshState(); - - TestableLooper.get(this).processAllMessages(); - assertEquals(View.GONE, mSecurityFooterView.getVisibility()); + assertNull(getButtonConfig()); } @Test public void testManagedNoOwnerName() { when(mSecurityController.isDeviceManaged()).thenReturn(true); when(mSecurityController.getDeviceOwnerOrganizationName()).thenReturn(null); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); + SecurityButtonConfig buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); assertEquals(mContext.getString(R.string.quick_settings_disclosure_management), - mFooterText.getText()); - assertEquals(View.VISIBLE, mSecurityFooterView.getVisibility()); - assertEquals(View.VISIBLE, mPrimaryFooterIcon.getVisibility()); - assertEquals(DEFAULT_ICON_ID, mPrimaryFooterIcon.getLastImageResource()); + buttonConfig.getText()); + assertIsDefaultIcon(buttonConfig.getIcon()); } @Test @@ -181,15 +170,13 @@ public class QSSecurityFooterTest extends SysuiTestCase { when(mSecurityController.isDeviceManaged()).thenReturn(true); when(mSecurityController.getDeviceOwnerOrganizationName()) .thenReturn(MANAGING_ORGANIZATION); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); + SecurityButtonConfig buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); assertEquals(mContext.getString(R.string.quick_settings_disclosure_named_management, - MANAGING_ORGANIZATION), - mFooterText.getText()); - assertEquals(View.VISIBLE, mSecurityFooterView.getVisibility()); - assertEquals(View.VISIBLE, mPrimaryFooterIcon.getVisibility()); - assertEquals(DEFAULT_ICON_ID, mPrimaryFooterIcon.getLastImageResource()); + MANAGING_ORGANIZATION), + buttonConfig.getText()); + assertIsDefaultIcon(buttonConfig.getIcon()); } @Test @@ -200,15 +187,13 @@ public class QSSecurityFooterTest extends SysuiTestCase { when(mSecurityController.getDeviceOwnerType(DEVICE_OWNER_COMPONENT)) .thenReturn(DEVICE_OWNER_TYPE_FINANCED); - mFooter.refreshState(); - - TestableLooper.get(this).processAllMessages(); + SecurityButtonConfig buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); assertEquals(mContext.getString( - R.string.quick_settings_financed_disclosure_named_management, - MANAGING_ORGANIZATION), mFooterText.getText()); - assertEquals(View.VISIBLE, mSecurityFooterView.getVisibility()); - assertEquals(View.VISIBLE, mPrimaryFooterIcon.getVisibility()); - assertEquals(DEFAULT_ICON_ID, mPrimaryFooterIcon.getLastImageResource()); + R.string.quick_settings_financed_disclosure_named_management, + MANAGING_ORGANIZATION), + buttonConfig.getText()); + assertIsDefaultIcon(buttonConfig.getIcon()); } @Test @@ -220,21 +205,16 @@ public class QSSecurityFooterTest extends SysuiTestCase { when(mUserTracker.getUserInfo()).thenReturn(mockUserInfo); Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.DEVICE_DEMO_MODE, 1); - mFooter.refreshState(); - - TestableLooper.get(this).processAllMessages(); - assertEquals(View.GONE, mSecurityFooterView.getVisibility()); + assertNull(getButtonConfig()); } @Test public void testUntappableView_profileOwnerOfOrgOwnedDevice() { when(mSecurityController.isProfileOwnerOfOrganizationOwnedDevice()).thenReturn(true); - mFooter.refreshState(); - - TestableLooper.get(this).processAllMessages(); - assertFalse(mSecurityFooterView.isClickable()); - assertEquals(View.GONE, mSecurityFooterView.findViewById(R.id.footer_icon).getVisibility()); + SecurityButtonConfig buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); + assertFalse(buttonConfig.isClickable()); } @Test @@ -244,12 +224,9 @@ public class QSSecurityFooterTest extends SysuiTestCase { when(mSecurityController.isWorkProfileOn()).thenReturn(true); when(mSecurityController.hasWorkProfile()).thenReturn(true); - mFooter.refreshState(); - - TestableLooper.get(this).processAllMessages(); - assertTrue(mSecurityFooterView.isClickable()); - assertEquals(View.VISIBLE, - mSecurityFooterView.findViewById(R.id.footer_icon).getVisibility()); + SecurityButtonConfig buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); + assertTrue(buttonConfig.isClickable()); } @Test @@ -258,35 +235,31 @@ public class QSSecurityFooterTest extends SysuiTestCase { when(mSecurityController.isNetworkLoggingEnabled()).thenReturn(true); when(mSecurityController.isWorkProfileOn()).thenReturn(false); - mFooter.refreshState(); - - TestableLooper.get(this).processAllMessages(); - assertFalse(mSecurityFooterView.isClickable()); - assertEquals(View.GONE, mSecurityFooterView.findViewById(R.id.footer_icon).getVisibility()); + SecurityButtonConfig buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); + assertFalse(buttonConfig.isClickable()); } @Test public void testNetworkLoggingEnabled_deviceOwner() { when(mSecurityController.isDeviceManaged()).thenReturn(true); when(mSecurityController.isNetworkLoggingEnabled()).thenReturn(true); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); + SecurityButtonConfig buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); assertEquals(mContext.getString(R.string.quick_settings_disclosure_management_monitoring), - mFooterText.getText()); - assertEquals(View.VISIBLE, mPrimaryFooterIcon.getVisibility()); - assertEquals(DEFAULT_ICON_ID, mPrimaryFooterIcon.getLastImageResource()); + buttonConfig.getText()); + assertIsDefaultIcon(buttonConfig.getIcon()); // Same situation, but with organization name set when(mSecurityController.getDeviceOwnerOrganizationName()) .thenReturn(MANAGING_ORGANIZATION); - mFooter.refreshState(); - - TestableLooper.get(this).processAllMessages(); + buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); assertEquals(mContext.getString( - R.string.quick_settings_disclosure_named_management_monitoring, - MANAGING_ORGANIZATION), - mFooterText.getText()); + R.string.quick_settings_disclosure_named_management_monitoring, + MANAGING_ORGANIZATION), + buttonConfig.getText()); } @Test @@ -294,12 +267,12 @@ public class QSSecurityFooterTest extends SysuiTestCase { when(mSecurityController.hasWorkProfile()).thenReturn(true); when(mSecurityController.isNetworkLoggingEnabled()).thenReturn(true); when(mSecurityController.isWorkProfileOn()).thenReturn(true); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); + SecurityButtonConfig buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); assertEquals(mContext.getString( - R.string.quick_settings_disclosure_managed_profile_network_activity), - mFooterText.getText()); + R.string.quick_settings_disclosure_managed_profile_network_activity), + buttonConfig.getText()); } @Test @@ -307,21 +280,19 @@ public class QSSecurityFooterTest extends SysuiTestCase { when(mSecurityController.hasWorkProfile()).thenReturn(true); when(mSecurityController.isNetworkLoggingEnabled()).thenReturn(true); when(mSecurityController.isWorkProfileOn()).thenReturn(false); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); - assertEquals("", mFooterText.getText()); + assertNull(getButtonConfig()); } @Test public void testManagedCACertsInstalled() { when(mSecurityController.isDeviceManaged()).thenReturn(true); when(mSecurityController.hasCACertInCurrentUser()).thenReturn(true); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); + SecurityButtonConfig buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); assertEquals(mContext.getString(R.string.quick_settings_disclosure_management_monitoring), - mFooterText.getText()); + buttonConfig.getText()); } @Test @@ -329,25 +300,23 @@ public class QSSecurityFooterTest extends SysuiTestCase { when(mSecurityController.isDeviceManaged()).thenReturn(true); when(mSecurityController.isVpnEnabled()).thenReturn(true); when(mSecurityController.getPrimaryVpnName()).thenReturn(VPN_PACKAGE); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); + SecurityButtonConfig buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); assertEquals(mContext.getString(R.string.quick_settings_disclosure_management_named_vpn, - VPN_PACKAGE), - mFooterText.getText()); - assertEquals(View.VISIBLE, mPrimaryFooterIcon.getVisibility()); - assertEquals(R.drawable.stat_sys_vpn_ic, mPrimaryFooterIcon.getLastImageResource()); + VPN_PACKAGE), + buttonConfig.getText()); + assertIsIconResource(buttonConfig.getIcon(), R.drawable.stat_sys_vpn_ic); // Same situation, but with organization name set when(mSecurityController.getDeviceOwnerOrganizationName()) .thenReturn(MANAGING_ORGANIZATION); - mFooter.refreshState(); - - TestableLooper.get(this).processAllMessages(); + buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); assertEquals(mContext.getString( - R.string.quick_settings_disclosure_named_management_named_vpn, - MANAGING_ORGANIZATION, VPN_PACKAGE), - mFooterText.getText()); + R.string.quick_settings_disclosure_named_management_named_vpn, + MANAGING_ORGANIZATION, VPN_PACKAGE), + buttonConfig.getText()); } @Test @@ -356,23 +325,21 @@ public class QSSecurityFooterTest extends SysuiTestCase { when(mSecurityController.isVpnEnabled()).thenReturn(true); when(mSecurityController.getPrimaryVpnName()).thenReturn(VPN_PACKAGE); when(mSecurityController.getWorkProfileVpnName()).thenReturn(VPN_PACKAGE_2); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); + SecurityButtonConfig buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); assertEquals(mContext.getString(R.string.quick_settings_disclosure_management_vpns), - mFooterText.getText()); - assertEquals(View.VISIBLE, mPrimaryFooterIcon.getVisibility()); - assertEquals(R.drawable.stat_sys_vpn_ic, mPrimaryFooterIcon.getLastImageResource()); + buttonConfig.getText()); + assertIsIconResource(buttonConfig.getIcon(), R.drawable.stat_sys_vpn_ic); // Same situation, but with organization name set when(mSecurityController.getDeviceOwnerOrganizationName()) .thenReturn(MANAGING_ORGANIZATION); - mFooter.refreshState(); - - TestableLooper.get(this).processAllMessages(); + buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); assertEquals(mContext.getString(R.string.quick_settings_disclosure_named_management_vpns, MANAGING_ORGANIZATION), - mFooterText.getText()); + buttonConfig.getText()); } @Test @@ -381,13 +348,12 @@ public class QSSecurityFooterTest extends SysuiTestCase { when(mSecurityController.isNetworkLoggingEnabled()).thenReturn(true); when(mSecurityController.isVpnEnabled()).thenReturn(true); when(mSecurityController.getPrimaryVpnName()).thenReturn("VPN Test App"); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); - assertEquals(View.VISIBLE, mPrimaryFooterIcon.getVisibility()); - assertEquals(R.drawable.stat_sys_vpn_ic, mPrimaryFooterIcon.getLastImageResource()); + SecurityButtonConfig buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); + assertIsIconResource(buttonConfig.getIcon(), R.drawable.stat_sys_vpn_ic); assertEquals(mContext.getString(R.string.quick_settings_disclosure_management_monitoring), - mFooterText.getText()); + buttonConfig.getText()); } @Test @@ -395,24 +361,23 @@ public class QSSecurityFooterTest extends SysuiTestCase { when(mSecurityController.isDeviceManaged()).thenReturn(false); when(mSecurityController.hasCACertInWorkProfile()).thenReturn(true); when(mSecurityController.isWorkProfileOn()).thenReturn(true); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); - assertEquals(DEFAULT_ICON_ID, mPrimaryFooterIcon.getLastImageResource()); + SecurityButtonConfig buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); + assertIsDefaultIcon(buttonConfig.getIcon()); assertEquals(mContext.getString( R.string.quick_settings_disclosure_managed_profile_monitoring), - mFooterText.getText()); + buttonConfig.getText()); // Same situation, but with organization name set when(mSecurityController.getWorkProfileOrganizationName()) .thenReturn(MANAGING_ORGANIZATION); - mFooter.refreshState(); - - TestableLooper.get(this).processAllMessages(); + buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); assertEquals(mContext.getString( R.string.quick_settings_disclosure_named_managed_profile_monitoring, MANAGING_ORGANIZATION), - mFooterText.getText()); + buttonConfig.getText()); } @Test @@ -420,22 +385,20 @@ public class QSSecurityFooterTest extends SysuiTestCase { when(mSecurityController.isDeviceManaged()).thenReturn(false); when(mSecurityController.hasCACertInWorkProfile()).thenReturn(true); when(mSecurityController.isWorkProfileOn()).thenReturn(false); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); - assertEquals("", mFooterText.getText()); + assertNull(getButtonConfig()); } @Test public void testCACertsInstalled() { when(mSecurityController.isDeviceManaged()).thenReturn(false); when(mSecurityController.hasCACertInCurrentUser()).thenReturn(true); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); - assertEquals(DEFAULT_ICON_ID, mPrimaryFooterIcon.getLastImageResource()); + SecurityButtonConfig buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); + assertIsDefaultIcon(buttonConfig.getIcon()); assertEquals(mContext.getString(R.string.quick_settings_disclosure_monitoring), - mFooterText.getText()); + buttonConfig.getText()); } @Test @@ -443,12 +406,12 @@ public class QSSecurityFooterTest extends SysuiTestCase { when(mSecurityController.isVpnEnabled()).thenReturn(true); when(mSecurityController.getPrimaryVpnName()).thenReturn(VPN_PACKAGE); when(mSecurityController.getWorkProfileVpnName()).thenReturn(VPN_PACKAGE_2); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); - assertEquals(R.drawable.stat_sys_vpn_ic, mPrimaryFooterIcon.getLastImageResource()); + SecurityButtonConfig buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); + assertIsIconResource(buttonConfig.getIcon(), R.drawable.stat_sys_vpn_ic); assertEquals(mContext.getString(R.string.quick_settings_disclosure_vpns), - mFooterText.getText()); + buttonConfig.getText()); } @Test @@ -456,14 +419,14 @@ public class QSSecurityFooterTest extends SysuiTestCase { when(mSecurityController.isVpnEnabled()).thenReturn(true); when(mSecurityController.getWorkProfileVpnName()).thenReturn(VPN_PACKAGE_2); when(mSecurityController.isWorkProfileOn()).thenReturn(true); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); - assertEquals(R.drawable.stat_sys_vpn_ic, mPrimaryFooterIcon.getLastImageResource()); + SecurityButtonConfig buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); + assertIsIconResource(buttonConfig.getIcon(), R.drawable.stat_sys_vpn_ic); assertEquals(mContext.getString( R.string.quick_settings_disclosure_managed_profile_named_vpn, VPN_PACKAGE_2), - mFooterText.getText()); + buttonConfig.getText()); } @Test @@ -471,22 +434,19 @@ public class QSSecurityFooterTest extends SysuiTestCase { when(mSecurityController.isVpnEnabled()).thenReturn(true); when(mSecurityController.getWorkProfileVpnName()).thenReturn(VPN_PACKAGE_2); when(mSecurityController.isWorkProfileOn()).thenReturn(false); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); - assertEquals("", mFooterText.getText()); + assertNull(getButtonConfig()); } @Test public void testProfileOwnerOfOrganizationOwnedDeviceNoName() { when(mSecurityController.isProfileOwnerOfOrganizationOwnedDevice()).thenReturn(true); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); - + SecurityButtonConfig buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); assertEquals(mContext.getString( R.string.quick_settings_disclosure_management), - mFooterText.getText()); + buttonConfig.getText()); } @Test @@ -495,35 +455,33 @@ public class QSSecurityFooterTest extends SysuiTestCase { when(mSecurityController.getWorkProfileOrganizationName()) .thenReturn(MANAGING_ORGANIZATION); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); - + SecurityButtonConfig buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); assertEquals(mContext.getString( R.string.quick_settings_disclosure_named_management, MANAGING_ORGANIZATION), - mFooterText.getText()); + buttonConfig.getText()); } @Test public void testVpnEnabled() { when(mSecurityController.isVpnEnabled()).thenReturn(true); when(mSecurityController.getPrimaryVpnName()).thenReturn(VPN_PACKAGE); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); - assertEquals(R.drawable.stat_sys_vpn_ic, mPrimaryFooterIcon.getLastImageResource()); + SecurityButtonConfig buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); + assertIsIconResource(buttonConfig.getIcon(), R.drawable.stat_sys_vpn_ic); assertEquals(mContext.getString(R.string.quick_settings_disclosure_named_vpn, VPN_PACKAGE), - mFooterText.getText()); + buttonConfig.getText()); when(mSecurityController.hasWorkProfile()).thenReturn(true); - mFooter.refreshState(); - - TestableLooper.get(this).processAllMessages(); + buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); assertEquals(mContext.getString( R.string.quick_settings_disclosure_personal_profile_named_vpn, VPN_PACKAGE), - mFooterText.getText()); + buttonConfig.getText()); } @Test @@ -687,19 +645,6 @@ public class QSSecurityFooterTest extends SysuiTestCase { } @Test - public void testNoClickWhenGone() { - mFooter.refreshState(); - - TestableLooper.get(this).processAllMessages(); - - assertFalse(mFooter.hasFooter()); - mFooter.onClick(mFooter.getView()); - - // Proxy for dialog being created - verify(mDialogLaunchAnimator, never()).showFromView(any(), any()); - } - - @Test public void testParentalControls() { // Make sure the security footer is visible, so that the images are updated. when(mSecurityController.isProfileOwnerOfOrganizationOwnedDevice()).thenReturn(true); @@ -707,29 +652,26 @@ public class QSSecurityFooterTest extends SysuiTestCase { // We use the default icon when there is no admin icon. when(mSecurityController.getIcon(any())).thenReturn(null); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); + SecurityButtonConfig buttonConfig = getButtonConfig(); assertEquals(mContext.getString(R.string.quick_settings_disclosure_parental_controls), - mFooterText.getText()); - assertEquals(DEFAULT_ICON_ID, mPrimaryFooterIcon.getLastImageResource()); + buttonConfig.getText()); + assertIsDefaultIcon(buttonConfig.getIcon()); Drawable testDrawable = new VectorDrawable(); when(mSecurityController.getIcon(any())).thenReturn(testDrawable); assertNotNull(mSecurityController.getIcon(null)); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); - + buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); assertEquals(mContext.getString(R.string.quick_settings_disclosure_parental_controls), - mFooterText.getText()); - assertEquals(View.VISIBLE, mPrimaryFooterIcon.getVisibility()); - assertEquals(testDrawable, mPrimaryFooterIcon.getDrawable()); + buttonConfig.getText()); + assertIsIconDrawable(buttonConfig.getIcon(), testDrawable); // Ensure the primary icon is back to default after parental controls are gone when(mSecurityController.isParentalControlsEnabled()).thenReturn(false); - mFooter.refreshState(); - TestableLooper.get(this).processAllMessages(); - assertEquals(DEFAULT_ICON_ID, mPrimaryFooterIcon.getLastImageResource()); + buttonConfig = getButtonConfig(); + assertNotNull(buttonConfig); + assertIsDefaultIcon(buttonConfig.getIcon()); } @Test @@ -743,16 +685,6 @@ public class QSSecurityFooterTest extends SysuiTestCase { } @Test - public void testDialogUsesDialogLauncher() { - when(mSecurityController.isDeviceManaged()).thenReturn(true); - mFooter.onClick(mSecurityFooterView); - - mTestableLooper.processAllMessages(); - - verify(mDialogLaunchAnimator).show(any(), any()); - } - - @Test public void testCreateDialogViewForFinancedDevice() { when(mSecurityController.isDeviceManaged()).thenReturn(true); when(mSecurityController.getDeviceOwnerOrganizationName()) @@ -782,7 +714,10 @@ public class QSSecurityFooterTest extends SysuiTestCase { when(mSecurityController.getDeviceOwnerType(DEVICE_OWNER_COMPONENT)) .thenReturn(DEVICE_OWNER_TYPE_FINANCED); - mFooter.showDeviceMonitoringDialog(); + Expandable expandable = mock(Expandable.class); + when(expandable.dialogLaunchController(any())).thenReturn( + mock(DialogLaunchAnimator.Controller.class)); + mFooterUtils.showDeviceMonitoringDialog(getContext(), expandable); ArgumentCaptor<AlertDialog> dialogCaptor = ArgumentCaptor.forClass(AlertDialog.class); mTestableLooper.processAllMessages(); @@ -797,47 +732,6 @@ public class QSSecurityFooterTest extends SysuiTestCase { dialog.dismiss(); } - @Test - public void testVisibilityListener() { - final AtomicInteger lastVisibility = new AtomicInteger(-1); - VisibilityChangedDispatcher.OnVisibilityChangedListener listener = lastVisibility::set; - - mFooter.setOnVisibilityChangedListener(listener); - - when(mSecurityController.isDeviceManaged()).thenReturn(true); - mFooter.refreshState(); - mTestableLooper.processAllMessages(); - assertEquals(View.VISIBLE, lastVisibility.get()); - - when(mSecurityController.isDeviceManaged()).thenReturn(false); - mFooter.refreshState(); - mTestableLooper.processAllMessages(); - assertEquals(View.GONE, lastVisibility.get()); - } - - @Test - public void testBroadcastShowsDialog() { - // Setup dialog content - when(mSecurityController.isDeviceManaged()).thenReturn(true); - when(mSecurityController.getDeviceOwnerOrganizationName()) - .thenReturn(MANAGING_ORGANIZATION); - when(mSecurityController.getDeviceOwnerType(DEVICE_OWNER_COMPONENT)) - .thenReturn(DEVICE_OWNER_TYPE_FINANCED); - - ArgumentCaptor<BroadcastReceiver> captor = ArgumentCaptor.forClass(BroadcastReceiver.class); - verify(mBroadcastDispatcher).registerReceiverWithHandler(captor.capture(), any(), any(), - any()); - - // Pretend view is not attached anymore. - mRootView.removeView(mSecurityFooterView); - captor.getValue().onReceive(mContext, - new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG)); - mTestableLooper.processAllMessages(); - - assertTrue(mFooterUtils.getDialog().isShowing()); - mFooterUtils.getDialog().dismiss(); - } - private CharSequence addLink(CharSequence description) { final SpannableStringBuilder message = new SpannableStringBuilder(); message.append(description); diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/footer/ui/viewmodel/FooterActionsViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/qs/footer/ui/viewmodel/FooterActionsViewModelTest.kt index 47afa70fa84b..01411c9e7f04 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/qs/footer/ui/viewmodel/FooterActionsViewModelTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/qs/footer/ui/viewmodel/FooterActionsViewModelTest.kt @@ -385,4 +385,86 @@ class FooterActionsViewModelTest : SysuiTestCase() { underTest.onVisibilityChangeRequested(visible = true) assertThat(underTest.isVisible.value).isTrue() } + + @Test + fun alpha_inSplitShade_followsExpansion() { + val underTest = utils.footerActionsViewModel() + + underTest.onQuickSettingsExpansionChanged(0f, isInSplitShade = true) + assertThat(underTest.alpha.value).isEqualTo(0f) + + underTest.onQuickSettingsExpansionChanged(0.25f, isInSplitShade = true) + assertThat(underTest.alpha.value).isEqualTo(0.25f) + + underTest.onQuickSettingsExpansionChanged(0.5f, isInSplitShade = true) + assertThat(underTest.alpha.value).isEqualTo(0.5f) + + underTest.onQuickSettingsExpansionChanged(0.75f, isInSplitShade = true) + assertThat(underTest.alpha.value).isEqualTo(0.75f) + + underTest.onQuickSettingsExpansionChanged(1f, isInSplitShade = true) + assertThat(underTest.alpha.value).isEqualTo(1f) + } + + @Test + fun backgroundAlpha_inSplitShade_followsExpansion_with_0_99_delay() { + val underTest = utils.footerActionsViewModel() + val floatTolerance = 0.01f + + underTest.onQuickSettingsExpansionChanged(0f, isInSplitShade = true) + assertThat(underTest.backgroundAlpha.value).isEqualTo(0f) + + underTest.onQuickSettingsExpansionChanged(0.5f, isInSplitShade = true) + assertThat(underTest.backgroundAlpha.value).isEqualTo(0f) + + underTest.onQuickSettingsExpansionChanged(0.9f, isInSplitShade = true) + assertThat(underTest.backgroundAlpha.value).isEqualTo(0f) + + underTest.onQuickSettingsExpansionChanged(0.991f, isInSplitShade = true) + assertThat(underTest.backgroundAlpha.value).isWithin(floatTolerance).of(0.1f) + + underTest.onQuickSettingsExpansionChanged(0.995f, isInSplitShade = true) + assertThat(underTest.backgroundAlpha.value).isWithin(floatTolerance).of(0.5f) + + underTest.onQuickSettingsExpansionChanged(1f, isInSplitShade = true) + assertThat(underTest.backgroundAlpha.value).isEqualTo(1f) + } + + @Test + fun alpha_inSingleShade_followsExpansion_with_0_9_delay() { + val underTest = utils.footerActionsViewModel() + val floatTolerance = 0.01f + + underTest.onQuickSettingsExpansionChanged(0f, isInSplitShade = false) + assertThat(underTest.alpha.value).isEqualTo(0f) + + underTest.onQuickSettingsExpansionChanged(0.5f, isInSplitShade = false) + assertThat(underTest.alpha.value).isEqualTo(0f) + + underTest.onQuickSettingsExpansionChanged(0.9f, isInSplitShade = false) + assertThat(underTest.alpha.value).isEqualTo(0f) + + underTest.onQuickSettingsExpansionChanged(0.91f, isInSplitShade = false) + assertThat(underTest.alpha.value).isWithin(floatTolerance).of(0.1f) + + underTest.onQuickSettingsExpansionChanged(0.95f, isInSplitShade = false) + assertThat(underTest.alpha.value).isWithin(floatTolerance).of(0.5f) + + underTest.onQuickSettingsExpansionChanged(1f, isInSplitShade = false) + assertThat(underTest.alpha.value).isEqualTo(1f) + } + + @Test + fun backgroundAlpha_inSingleShade_always1() { + val underTest = utils.footerActionsViewModel() + + underTest.onQuickSettingsExpansionChanged(0f, isInSplitShade = false) + assertThat(underTest.backgroundAlpha.value).isEqualTo(1f) + + underTest.onQuickSettingsExpansionChanged(0.5f, isInSplitShade = false) + assertThat(underTest.backgroundAlpha.value).isEqualTo(1f) + + underTest.onQuickSettingsExpansionChanged(1f, isInSplitShade = false) + assertThat(underTest.backgroundAlpha.value).isEqualTo(1f) + } } diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/InternetTileTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/InternetTileTest.java index d91baa5e7fcb..80c39cf9e4cd 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/InternetTileTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/qs/tiles/InternetTileTest.java @@ -23,6 +23,7 @@ import static org.mockito.Mockito.when; import android.os.Handler; +import android.service.quicksettings.Tile; import android.testing.AndroidTestingRunner; import android.testing.TestableLooper; @@ -38,6 +39,7 @@ import com.android.systemui.qs.QSTileHost; import com.android.systemui.qs.logging.QSLogger; import com.android.systemui.qs.tiles.dialog.InternetDialogFactory; import com.android.systemui.statusbar.connectivity.AccessPointController; +import com.android.systemui.statusbar.connectivity.IconState; import com.android.systemui.statusbar.connectivity.NetworkController; import org.junit.Before; @@ -113,4 +115,24 @@ public class InternetTileTest extends SysuiTestCase { .isNotEqualTo(mContext.getString(R.string.quick_settings_networks_available)); assertThat(mTile.getLastTileState()).isEqualTo(-1); } + + @Test + public void setIsAirplaneMode_APM_enabled_wifi_disabled() { + IconState state = new IconState(true, 0, ""); + mTile.mSignalCallback.setIsAirplaneMode(state); + mTestableLooper.processAllMessages(); + assertThat(mTile.getState().state).isEqualTo(Tile.STATE_INACTIVE); + assertThat(mTile.getState().secondaryLabel) + .isEqualTo(mContext.getString(R.string.status_bar_airplane)); + } + + @Test + public void setIsAirplaneMode_APM_enabled_wifi_enabled() { + IconState state = new IconState(false, 0, ""); + mTile.mSignalCallback.setIsAirplaneMode(state); + mTestableLooper.processAllMessages(); + assertThat(mTile.getState().state).isEqualTo(Tile.STATE_ACTIVE); + assertThat(mTile.getState().secondaryLabel) + .isNotEqualTo(mContext.getString(R.string.status_bar_airplane)); + } } 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 56a840cae267..0302dade0a8c 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/shade/NotificationPanelViewControllerTest.java @@ -173,6 +173,7 @@ import com.android.wm.shell.animation.FlingAnimationUtils; import org.junit.After; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; @@ -611,6 +612,7 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase { } @Test + @Ignore("b/261472011 - Test appears inconsistent across environments") public void getVerticalSpaceForLockscreenNotifications_useLockIconBottomPadding_returnsSpaceAvailable() { setBottomPadding(/* stackScrollLayoutBottom= */ 180, /* lockIconPadding= */ 20, @@ -622,6 +624,7 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase { } @Test + @Ignore("b/261472011 - Test appears inconsistent across environments") public void getVerticalSpaceForLockscreenNotifications_useIndicationBottomPadding_returnsSpaceAvailable() { setBottomPadding(/* stackScrollLayoutBottom= */ 180, /* lockIconPadding= */ 0, @@ -633,6 +636,7 @@ public class NotificationPanelViewControllerTest extends SysuiTestCase { } @Test + @Ignore("b/261472011 - Test appears inconsistent across environments") public void getVerticalSpaceForLockscreenNotifications_useAmbientBottomPadding_returnsSpaceAvailable() { setBottomPadding(/* stackScrollLayoutBottom= */ 180, /* lockIconPadding= */ 0, diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/condition/ConditionMonitorTest.java b/packages/SystemUI/tests/src/com/android/systemui/shared/condition/ConditionMonitorTest.java index 17d81c8338cb..7693fee0a1c4 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/util/condition/ConditionMonitorTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/shared/condition/ConditionMonitorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 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. @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.systemui.util.condition; +package com.android.systemui.shared.condition; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -68,13 +68,15 @@ public class ConditionMonitorTest extends SysuiTestCase { mConditionMonitor = new Monitor(mExecutor); } - public Monitor.Subscription.Builder getDefaultBuilder(Monitor.Callback callback) { + public Monitor.Subscription.Builder getDefaultBuilder( + Monitor.Callback callback) { return new Monitor.Subscription.Builder(callback) .addConditions(mConditions); } private Condition createMockCondition() { - final Condition condition = Mockito.mock(Condition.class); + final Condition condition = Mockito.mock( + Condition.class); when(condition.isConditionSet()).thenReturn(true); return condition; } @@ -83,11 +85,14 @@ public class ConditionMonitorTest extends SysuiTestCase { public void testOverridingCondition() { final Condition overridingCondition = createMockCondition(); final Condition regularCondition = createMockCondition(); - final Monitor.Callback callback = Mockito.mock(Monitor.Callback.class); + final Monitor.Callback callback = Mockito.mock( + Monitor.Callback.class); - final Monitor.Callback referenceCallback = Mockito.mock(Monitor.Callback.class); + final Monitor.Callback referenceCallback = Mockito.mock( + Monitor.Callback.class); - final Monitor monitor = new Monitor(mExecutor); + final Monitor + monitor = new Monitor(mExecutor); monitor.addSubscription(getDefaultBuilder(callback) .addCondition(overridingCondition) @@ -136,9 +141,11 @@ public class ConditionMonitorTest extends SysuiTestCase { final Condition overridingCondition = createMockCondition(); final Condition overridingCondition2 = createMockCondition(); final Condition regularCondition = createMockCondition(); - final Monitor.Callback callback = Mockito.mock(Monitor.Callback.class); + final Monitor.Callback callback = Mockito.mock( + Monitor.Callback.class); - final Monitor monitor = new Monitor(mExecutor); + final Monitor + monitor = new Monitor(mExecutor); monitor.addSubscription(getDefaultBuilder(callback) .addCondition(overridingCondition) @@ -211,9 +218,11 @@ public class ConditionMonitorTest extends SysuiTestCase { public void addCallback_addSecondCallback_reportWithExistingValue() { final Monitor.Callback callback1 = mock(Monitor.Callback.class); - final Condition condition = mock(Condition.class); + final Condition condition = mock( + Condition.class); when(condition.isConditionMet()).thenReturn(true); - final Monitor monitor = new Monitor(mExecutor); + final Monitor + monitor = new Monitor(mExecutor); monitor.addSubscription(new Monitor.Subscription.Builder(callback1) .addCondition(condition) .build()); @@ -229,8 +238,10 @@ public class ConditionMonitorTest extends SysuiTestCase { @Test public void addCallback_noConditions_reportAllConditionsMet() { - final Monitor monitor = new Monitor(mExecutor); - final Monitor.Callback callback = mock(Monitor.Callback.class); + final Monitor + monitor = new Monitor(mExecutor); + final Monitor.Callback callback = mock( + Monitor.Callback.class); monitor.addSubscription(new Monitor.Subscription.Builder(callback).build()); mExecutor.runAllReady(); @@ -239,8 +250,10 @@ public class ConditionMonitorTest extends SysuiTestCase { @Test public void removeCallback_noFailureOnDoubleRemove() { - final Condition condition = mock(Condition.class); - final Monitor monitor = new Monitor(mExecutor); + final Condition condition = mock( + Condition.class); + final Monitor + monitor = new Monitor(mExecutor); final Monitor.Callback callback = mock(Monitor.Callback.class); final Monitor.Subscription.Token token = monitor.addSubscription( @@ -255,8 +268,10 @@ public class ConditionMonitorTest extends SysuiTestCase { @Test public void removeCallback_shouldNoLongerReceiveUpdate() { - final Condition condition = mock(Condition.class); - final Monitor monitor = new Monitor(mExecutor); + final Condition condition = mock( + Condition.class); + final Monitor + monitor = new Monitor(mExecutor); final Monitor.Callback callback = mock(Monitor.Callback.class); final Monitor.Subscription.Token token = monitor.addSubscription( diff --git a/packages/SystemUI/tests/src/com/android/systemui/util/condition/ConditionTest.java b/packages/SystemUI/tests/src/com/android/systemui/shared/condition/ConditionTest.java index 28788647dd58..8443221e8b7a 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/util/condition/ConditionTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/shared/condition/ConditionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 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. @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.systemui.util.condition; +package com.android.systemui.shared.condition; import static com.google.common.truth.Truth.assertThat; @@ -47,16 +47,20 @@ public class ConditionTest extends SysuiTestCase { @Test public void addCallback_addFirstCallback_triggerStart() { - final Condition.Callback callback = mock(Condition.Callback.class); + final Condition.Callback callback = mock( + Condition.Callback.class); mCondition.addCallback(callback); verify(mCondition).start(); } @Test public void addCallback_addMultipleCallbacks_triggerStartOnlyOnce() { - final Condition.Callback callback1 = mock(Condition.Callback.class); - final Condition.Callback callback2 = mock(Condition.Callback.class); - final Condition.Callback callback3 = mock(Condition.Callback.class); + final Condition.Callback callback1 = mock( + Condition.Callback.class); + final Condition.Callback callback2 = mock( + Condition.Callback.class); + final Condition.Callback callback3 = mock( + Condition.Callback.class); mCondition.addCallback(callback1); mCondition.addCallback(callback2); @@ -67,12 +71,14 @@ public class ConditionTest extends SysuiTestCase { @Test public void addCallback_alreadyStarted_triggerUpdate() { - final Condition.Callback callback1 = mock(Condition.Callback.class); + final Condition.Callback callback1 = mock( + Condition.Callback.class); mCondition.addCallback(callback1); mCondition.fakeUpdateCondition(true); - final Condition.Callback callback2 = mock(Condition.Callback.class); + final Condition.Callback callback2 = mock( + Condition.Callback.class); mCondition.addCallback(callback2); verify(callback2).onConditionChanged(mCondition); assertThat(mCondition.isConditionMet()).isTrue(); @@ -80,7 +86,8 @@ public class ConditionTest extends SysuiTestCase { @Test public void removeCallback_removeLastCallback_triggerStop() { - final Condition.Callback callback = mock(Condition.Callback.class); + final Condition.Callback callback = mock( + Condition.Callback.class); mCondition.addCallback(callback); verify(mCondition, never()).stop(); @@ -92,7 +99,8 @@ public class ConditionTest extends SysuiTestCase { public void updateCondition_falseToTrue_reportTrue() { mCondition.fakeUpdateCondition(false); - final Condition.Callback callback = mock(Condition.Callback.class); + final Condition.Callback callback = mock( + Condition.Callback.class); mCondition.addCallback(callback); mCondition.fakeUpdateCondition(true); @@ -104,7 +112,8 @@ public class ConditionTest extends SysuiTestCase { public void updateCondition_trueToFalse_reportFalse() { mCondition.fakeUpdateCondition(true); - final Condition.Callback callback = mock(Condition.Callback.class); + final Condition.Callback callback = mock( + Condition.Callback.class); mCondition.addCallback(callback); mCondition.fakeUpdateCondition(false); @@ -116,7 +125,8 @@ public class ConditionTest extends SysuiTestCase { public void updateCondition_trueToTrue_reportNothing() { mCondition.fakeUpdateCondition(true); - final Condition.Callback callback = mock(Condition.Callback.class); + final Condition.Callback callback = mock( + Condition.Callback.class); mCondition.addCallback(callback); mCondition.fakeUpdateCondition(true); @@ -127,7 +137,8 @@ public class ConditionTest extends SysuiTestCase { public void updateCondition_falseToFalse_reportNothing() { mCondition.fakeUpdateCondition(false); - final Condition.Callback callback = mock(Condition.Callback.class); + final Condition.Callback callback = mock( + Condition.Callback.class); mCondition.addCallback(callback); mCondition.fakeUpdateCondition(false); @@ -149,7 +160,8 @@ public class ConditionTest extends SysuiTestCase { final Condition combinedCondition = mCondition.or( new FakeCondition(/* initialValue= */ false)); - final Condition.Callback callback = mock(Condition.Callback.class); + final Condition.Callback callback = mock( + Condition.Callback.class); combinedCondition.addCallback(callback); assertThat(combinedCondition.isConditionSet()).isTrue(); @@ -164,7 +176,8 @@ public class ConditionTest extends SysuiTestCase { final Condition combinedCondition = mCondition.or( new FakeCondition(/* initialValue= */ true)); - final Condition.Callback callback = mock(Condition.Callback.class); + final Condition.Callback callback = mock( + Condition.Callback.class); combinedCondition.addCallback(callback); assertThat(combinedCondition.isConditionSet()).isTrue(); @@ -179,7 +192,8 @@ public class ConditionTest extends SysuiTestCase { final Condition combinedCondition = mCondition.or( new FakeCondition(/* initialValue= */ true)); - final Condition.Callback callback = mock(Condition.Callback.class); + final Condition.Callback callback = mock( + Condition.Callback.class); combinedCondition.addCallback(callback); assertThat(combinedCondition.isConditionSet()).isTrue(); @@ -195,7 +209,8 @@ public class ConditionTest extends SysuiTestCase { final Condition combinedCondition = mCondition.or( new FakeCondition(/* initialValue= */ null)); - final Condition.Callback callback = mock(Condition.Callback.class); + final Condition.Callback callback = mock( + Condition.Callback.class); combinedCondition.addCallback(callback); assertThat(combinedCondition.isConditionSet()).isTrue(); @@ -211,7 +226,8 @@ public class ConditionTest extends SysuiTestCase { final Condition combinedCondition = mCondition.or( new FakeCondition(/* initialValue= */ null)); - final Condition.Callback callback = mock(Condition.Callback.class); + final Condition.Callback callback = mock( + Condition.Callback.class); combinedCondition.addCallback(callback); assertThat(combinedCondition.isConditionSet()).isFalse(); @@ -226,7 +242,8 @@ public class ConditionTest extends SysuiTestCase { final Condition combinedCondition = mCondition.and( new FakeCondition(/* initialValue= */ false)); - final Condition.Callback callback = mock(Condition.Callback.class); + final Condition.Callback callback = mock( + Condition.Callback.class); combinedCondition.addCallback(callback); assertThat(combinedCondition.isConditionSet()).isTrue(); @@ -241,7 +258,8 @@ public class ConditionTest extends SysuiTestCase { final Condition combinedCondition = mCondition.and( new FakeCondition(/* initialValue= */ true)); - final Condition.Callback callback = mock(Condition.Callback.class); + final Condition.Callback callback = mock( + Condition.Callback.class); combinedCondition.addCallback(callback); assertThat(combinedCondition.isConditionSet()).isTrue(); @@ -256,7 +274,8 @@ public class ConditionTest extends SysuiTestCase { final Condition combinedCondition = mCondition.and( new FakeCondition(/* initialValue= */ false)); - final Condition.Callback callback = mock(Condition.Callback.class); + final Condition.Callback callback = mock( + Condition.Callback.class); combinedCondition.addCallback(callback); assertThat(combinedCondition.isConditionSet()).isTrue(); @@ -272,7 +291,8 @@ public class ConditionTest extends SysuiTestCase { final Condition combinedCondition = mCondition.and( new FakeCondition(/* initialValue= */ null)); - final Condition.Callback callback = mock(Condition.Callback.class); + final Condition.Callback callback = mock( + Condition.Callback.class); combinedCondition.addCallback(callback); assertThat(combinedCondition.isConditionSet()).isFalse(); @@ -288,7 +308,8 @@ public class ConditionTest extends SysuiTestCase { final Condition combinedCondition = mCondition.and( new FakeCondition(/* initialValue= */ null)); - final Condition.Callback callback = mock(Condition.Callback.class); + final Condition.Callback callback = mock( + Condition.Callback.class); combinedCondition.addCallback(callback); assertThat(combinedCondition.isConditionSet()).isTrue(); diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/util/condition/FakeCondition.java b/packages/SystemUI/tests/src/com/android/systemui/shared/condition/FakeCondition.java index 07ed1102e990..55a6d39d4644 100644 --- a/packages/SystemUI/tests/utils/src/com/android/systemui/util/condition/FakeCondition.java +++ b/packages/SystemUI/tests/src/com/android/systemui/shared/condition/FakeCondition.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 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. @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.systemui.util.condition; +package com.android.systemui.shared.condition; /** * Fake implementation of {@link Condition}, and provides a way for tests to update diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/KeyguardCoordinatorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/KeyguardCoordinatorTest.kt index 7f73856bff89..5f19fac8666a 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/KeyguardCoordinatorTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/collection/coordinator/KeyguardCoordinatorTest.kt @@ -17,6 +17,7 @@ package com.android.systemui.statusbar.notification.collection.coordinator +import android.app.Notification import android.testing.AndroidTestingRunner import androidx.test.filters.SmallTest import com.android.systemui.SysuiTestCase @@ -33,6 +34,7 @@ import com.android.systemui.statusbar.notification.collection.provider.SectionHe import com.android.systemui.statusbar.notification.collection.provider.SeenNotificationsProvider import com.android.systemui.statusbar.notification.collection.provider.SeenNotificationsProviderImpl import com.android.systemui.statusbar.notification.interruption.KeyguardNotificationVisibilityProvider +import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow import com.android.systemui.util.mockito.eq import com.android.systemui.util.mockito.mock import com.android.systemui.util.mockito.withArgCaptor @@ -105,6 +107,50 @@ class KeyguardCoordinatorTest : SysuiTestCase() { } @Test + fun unseenFilterDoesNotSuppressSeenOngoingNotifWhileKeyguardShowing() { + whenever(notifPipelineFlags.shouldFilterUnseenNotifsOnKeyguard).thenReturn(true) + + // GIVEN: Keyguard is not showing, and an ongoing notification is present + keyguardRepository.setKeyguardShowing(false) + runKeyguardCoordinatorTest { + val fakeEntry = NotificationEntryBuilder() + .setNotification(Notification.Builder(mContext).setOngoing(true).build()) + .build() + collectionListener.onEntryAdded(fakeEntry) + + // WHEN: The keyguard is now showing + keyguardRepository.setKeyguardShowing(true) + testScheduler.runCurrent() + + // THEN: The notification is recognized as "ongoing" and is not filtered out. + assertThat(unseenFilter.shouldFilterOut(fakeEntry, 0L)).isFalse() + } + } + + @Test + fun unseenFilterDoesNotSuppressSeenMediaNotifWhileKeyguardShowing() { + whenever(notifPipelineFlags.shouldFilterUnseenNotifsOnKeyguard).thenReturn(true) + + // GIVEN: Keyguard is not showing, and a media notification is present + keyguardRepository.setKeyguardShowing(false) + runKeyguardCoordinatorTest { + val fakeEntry = NotificationEntryBuilder().build().apply { + row = mock<ExpandableNotificationRow>().apply { + whenever(isMediaRow).thenReturn(true) + } + } + collectionListener.onEntryAdded(fakeEntry) + + // WHEN: The keyguard is now showing + keyguardRepository.setKeyguardShowing(true) + testScheduler.runCurrent() + + // THEN: The notification is recognized as "media" and is not filtered out. + assertThat(unseenFilter.shouldFilterOut(fakeEntry, 0L)).isFalse() + } + } + + @Test fun unseenFilterUpdatesSeenProviderWhenSuppressing() { whenever(notifPipelineFlags.shouldFilterUnseenNotifsOnKeyguard).thenReturn(true) diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManagerTest.java index 471f8d3404ba..14a319bc87e9 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManagerTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManagerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 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. @@ -11,7 +11,7 @@ * 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 + * limitations under the License. */ package com.android.systemui.statusbar.phone; @@ -105,7 +105,6 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { @Mock private KeyguardBouncer.Factory mKeyguardBouncerFactory; @Mock private KeyguardMessageAreaController.Factory mKeyguardMessageAreaFactory; @Mock private KeyguardMessageAreaController mKeyguardMessageAreaController; - @Mock private KeyguardBouncer mPrimaryBouncer; @Mock private StatusBarKeyguardViewManager.AlternateBouncer mAlternateBouncer; @Mock private KeyguardMessageArea mKeyguardMessageArea; @Mock private ShadeController mShadeController; @@ -133,16 +132,14 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { @Before public void setUp() { MockitoAnnotations.initMocks(this); - when(mKeyguardBouncerFactory.create( - any(ViewGroup.class), - any(KeyguardBouncer.PrimaryBouncerExpansionCallback.class))) - .thenReturn(mPrimaryBouncer); when(mCentralSurfaces.getBouncerContainer()).thenReturn(mContainer); when(mContainer.findViewById(anyInt())).thenReturn(mKeyguardMessageArea); when(mKeyguardMessageAreaFactory.create(any(KeyguardMessageArea.class))) .thenReturn(mKeyguardMessageAreaController); when(mBouncerView.getDelegate()).thenReturn(mBouncerViewDelegate); + when(mFeatureFlags.isEnabled(MODERN_BOUNCER)).thenReturn(true); + mStatusBarKeyguardViewManager = new StatusBarKeyguardViewManager( getContext(), @@ -184,7 +181,7 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { mStatusBarKeyguardViewManager.show(null); ArgumentCaptor<KeyguardBouncer.PrimaryBouncerExpansionCallback> callbackArgumentCaptor = ArgumentCaptor.forClass(KeyguardBouncer.PrimaryBouncerExpansionCallback.class); - verify(mKeyguardBouncerFactory).create(any(ViewGroup.class), + verify(mPrimaryBouncerCallbackInteractor).addBouncerExpansionCallback( callbackArgumentCaptor.capture()); mBouncerExpansionCallback = callbackArgumentCaptor.getValue(); } @@ -195,87 +192,87 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { Runnable cancelAction = () -> {}; mStatusBarKeyguardViewManager.dismissWithAction( action, cancelAction, false /* afterKeyguardGone */); - verify(mPrimaryBouncer).showWithDismissAction(eq(action), eq(cancelAction)); + verify(mPrimaryBouncerInteractor).setDismissAction(eq(action), eq(cancelAction)); + verify(mPrimaryBouncerInteractor).show(eq(true)); } @Test public void showBouncer_onlyWhenShowing() { mStatusBarKeyguardViewManager.hide(0 /* startTime */, 0 /* fadeoutDuration */); mStatusBarKeyguardViewManager.showPrimaryBouncer(true /* scrimmed */); - verify(mPrimaryBouncer, never()).show(anyBoolean(), anyBoolean()); - verify(mPrimaryBouncer, never()).show(anyBoolean()); + verify(mPrimaryBouncerInteractor, never()).show(anyBoolean()); } @Test public void showBouncer_notWhenBouncerAlreadyShowing() { mStatusBarKeyguardViewManager.hide(0 /* startTime */, 0 /* fadeoutDuration */); - when(mPrimaryBouncer.isSecure()).thenReturn(true); + when(mKeyguardSecurityModel.getSecurityMode(anyInt())).thenReturn( + KeyguardSecurityModel.SecurityMode.Password); mStatusBarKeyguardViewManager.showPrimaryBouncer(true /* scrimmed */); - verify(mPrimaryBouncer, never()).show(anyBoolean(), anyBoolean()); - verify(mPrimaryBouncer, never()).show(anyBoolean()); + verify(mPrimaryBouncerInteractor, never()).show(anyBoolean()); } @Test public void showBouncer_showsTheBouncer() { mStatusBarKeyguardViewManager.showPrimaryBouncer(true /* scrimmed */); - verify(mPrimaryBouncer).show(anyBoolean(), eq(true)); + verify(mPrimaryBouncerInteractor).show(eq(true)); } @Test public void onPanelExpansionChanged_neverShowsDuringHintAnimation() { when(mNotificationPanelView.isUnlockHintRunning()).thenReturn(true); mStatusBarKeyguardViewManager.onPanelExpansionChanged(EXPANSION_EVENT); - verify(mPrimaryBouncer, never()).setExpansion(anyFloat()); + verify(mPrimaryBouncerInteractor, never()).setPanelExpansion(anyFloat()); } @Test public void onPanelExpansionChanged_propagatesToBouncerOnlyIfShowing() { mStatusBarKeyguardViewManager.onPanelExpansionChanged(EXPANSION_EVENT); - verify(mPrimaryBouncer, never()).setExpansion(eq(0.5f)); + verify(mPrimaryBouncerInteractor, never()).setPanelExpansion(eq(0.5f)); - when(mPrimaryBouncer.isShowing()).thenReturn(true); + when(mPrimaryBouncerInteractor.isFullyShowing()).thenReturn(true); mStatusBarKeyguardViewManager.onPanelExpansionChanged( expansionEvent(/* fraction= */ 0.6f, /* expanded= */ false, /* tracking= */ true)); - verify(mPrimaryBouncer).setExpansion(eq(0.6f)); + verify(mPrimaryBouncerInteractor).setPanelExpansion(eq(0.6f)); } @Test public void onPanelExpansionChanged_duplicateEventsAreIgnored() { - when(mPrimaryBouncer.isShowing()).thenReturn(true); + when(mPrimaryBouncerInteractor.isFullyShowing()).thenReturn(true); mStatusBarKeyguardViewManager.onPanelExpansionChanged(EXPANSION_EVENT); - verify(mPrimaryBouncer).setExpansion(eq(0.5f)); + verify(mPrimaryBouncerInteractor).setPanelExpansion(eq(0.5f)); - reset(mPrimaryBouncer); + reset(mPrimaryBouncerInteractor); mStatusBarKeyguardViewManager.onPanelExpansionChanged(EXPANSION_EVENT); - verify(mPrimaryBouncer, never()).setExpansion(eq(0.5f)); + verify(mPrimaryBouncerInteractor, never()).setPanelExpansion(eq(0.5f)); } @Test public void onPanelExpansionChanged_hideBouncer_afterKeyguardHidden() { mStatusBarKeyguardViewManager.hide(0, 0); - when(mPrimaryBouncer.inTransit()).thenReturn(true); + when(mPrimaryBouncerInteractor.isInTransit()).thenReturn(true); mStatusBarKeyguardViewManager.onPanelExpansionChanged(EXPANSION_EVENT); - verify(mPrimaryBouncer).setExpansion(eq(KeyguardBouncer.EXPANSION_HIDDEN)); + verify(mPrimaryBouncerInteractor).setPanelExpansion(eq(KeyguardBouncer.EXPANSION_HIDDEN)); } @Test public void onPanelExpansionChanged_showsBouncerWhenSwiping() { mKeyguardStateController.setCanDismissLockScreen(false); mStatusBarKeyguardViewManager.onPanelExpansionChanged(EXPANSION_EVENT); - verify(mPrimaryBouncer).show(eq(false), eq(false)); + verify(mPrimaryBouncerInteractor).show(eq(false)); // But not when it's already visible - reset(mPrimaryBouncer); - when(mPrimaryBouncer.isShowing()).thenReturn(true); + reset(mPrimaryBouncerInteractor); + when(mPrimaryBouncerInteractor.isFullyShowing()).thenReturn(true); mStatusBarKeyguardViewManager.onPanelExpansionChanged(EXPANSION_EVENT); - verify(mPrimaryBouncer, never()).show(eq(false), eq(false)); + verify(mPrimaryBouncerInteractor, never()).show(eq(false)); // Or animating away - reset(mPrimaryBouncer); - when(mPrimaryBouncer.isAnimatingAway()).thenReturn(true); + reset(mPrimaryBouncerInteractor); + when(mPrimaryBouncerInteractor.isAnimatingAway()).thenReturn(true); mStatusBarKeyguardViewManager.onPanelExpansionChanged(EXPANSION_EVENT); - verify(mPrimaryBouncer, never()).show(eq(false), eq(false)); + verify(mPrimaryBouncerInteractor, never()).show(eq(false)); } @Test @@ -287,7 +284,7 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { /* fraction= */ KeyguardBouncer.EXPANSION_VISIBLE, /* expanded= */ true, /* tracking= */ false)); - verify(mPrimaryBouncer, never()).setExpansion(anyFloat()); + verify(mPrimaryBouncerInteractor, never()).setPanelExpansion(anyFloat()); } @Test @@ -304,7 +301,7 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { /* fraction= */ KeyguardBouncer.EXPANSION_VISIBLE, /* expanded= */ true, /* tracking= */ false)); - verify(mPrimaryBouncer, never()).setExpansion(anyFloat()); + verify(mPrimaryBouncerInteractor, never()).setPanelExpansion(anyFloat()); } @Test @@ -315,7 +312,7 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { /* fraction= */ KeyguardBouncer.EXPANSION_VISIBLE, /* expanded= */ true, /* tracking= */ false)); - verify(mPrimaryBouncer, never()).setExpansion(anyFloat()); + verify(mPrimaryBouncerInteractor, never()).setPanelExpansion(anyFloat()); } @Test @@ -332,7 +329,7 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { /* fraction= */ KeyguardBouncer.EXPANSION_VISIBLE, /* expanded= */ true, /* tracking= */ false)); - verify(mPrimaryBouncer, never()).setExpansion(anyFloat()); + verify(mPrimaryBouncerInteractor, never()).setPanelExpansion(anyFloat()); } @Test @@ -343,7 +340,7 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { /* fraction= */ KeyguardBouncer.EXPANSION_VISIBLE, /* expanded= */ true, /* tracking= */ false)); - verify(mPrimaryBouncer, never()).setExpansion(anyFloat()); + verify(mPrimaryBouncerInteractor, never()).setPanelExpansion(anyFloat()); } @Test @@ -351,7 +348,7 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { mStatusBarKeyguardViewManager.setOccluded(false /* occluded */, true /* animated */); verify(mCentralSurfaces).animateKeyguardUnoccluding(); - when(mPrimaryBouncer.isShowing()).thenReturn(true); + when(mPrimaryBouncerInteractor.isFullyShowing()).thenReturn(true); clearInvocations(mCentralSurfaces); mStatusBarKeyguardViewManager.setOccluded(false /* occluded */, true /* animated */); verify(mCentralSurfaces, never()).animateKeyguardUnoccluding(); @@ -402,7 +399,7 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { mStatusBarKeyguardViewManager.dismissWithAction( action, cancelAction, true /* afterKeyguardGone */); - when(mPrimaryBouncer.isShowing()).thenReturn(false); + when(mPrimaryBouncerInteractor.isFullyShowing()).thenReturn(false); mStatusBarKeyguardViewManager.hideBouncer(true); mStatusBarKeyguardViewManager.hide(0, 30); verify(action, never()).onDismiss(); @@ -416,7 +413,7 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { mStatusBarKeyguardViewManager.dismissWithAction( action, cancelAction, true /* afterKeyguardGone */); - when(mPrimaryBouncer.isShowing()).thenReturn(false); + when(mPrimaryBouncerInteractor.isFullyShowing()).thenReturn(false); mStatusBarKeyguardViewManager.hideBouncer(true); verify(action, never()).onDismiss(); @@ -438,7 +435,7 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { @Test public void testShowing_whenAlternateAuthShowing() { mStatusBarKeyguardViewManager.setAlternateBouncer(mAlternateBouncer); - when(mPrimaryBouncer.isShowing()).thenReturn(false); + when(mPrimaryBouncerInteractor.isFullyShowing()).thenReturn(false); when(mAlternateBouncer.isShowingAlternateBouncer()).thenReturn(true); assertTrue( "Is showing not accurate when alternative auth showing", @@ -448,7 +445,7 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { @Test public void testWillBeShowing_whenAlternateAuthShowing() { mStatusBarKeyguardViewManager.setAlternateBouncer(mAlternateBouncer); - when(mPrimaryBouncer.isShowing()).thenReturn(false); + when(mPrimaryBouncerInteractor.isFullyShowing()).thenReturn(false); when(mAlternateBouncer.isShowingAlternateBouncer()).thenReturn(true); assertTrue( "Is or will be showing not accurate when alternative auth showing", @@ -459,7 +456,7 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { public void testHideAlternateBouncer_onShowBouncer() { // GIVEN alt auth is showing mStatusBarKeyguardViewManager.setAlternateBouncer(mAlternateBouncer); - when(mPrimaryBouncer.isShowing()).thenReturn(false); + when(mPrimaryBouncerInteractor.isFullyShowing()).thenReturn(false); when(mAlternateBouncer.isShowingAlternateBouncer()).thenReturn(true); reset(mAlternateBouncer); @@ -472,8 +469,8 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { @Test public void testBouncerIsOrWillBeShowing_whenBouncerIsInTransit() { - when(mPrimaryBouncer.isShowing()).thenReturn(false); - when(mPrimaryBouncer.inTransit()).thenReturn(true); + when(mPrimaryBouncerInteractor.isFullyShowing()).thenReturn(false); + when(mPrimaryBouncerInteractor.isInTransit()).thenReturn(true); assertTrue( "Is or will be showing should be true when bouncer is in transit", @@ -484,7 +481,7 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { public void testShowAltAuth_unlockingWithBiometricNotAllowed() { // GIVEN alt auth exists, unlocking with biometric isn't allowed mStatusBarKeyguardViewManager.setAlternateBouncer(mAlternateBouncer); - when(mPrimaryBouncer.isShowing()).thenReturn(false); + when(mPrimaryBouncerInteractor.isFullyShowing()).thenReturn(false); when(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(anyBoolean())) .thenReturn(false); @@ -493,7 +490,7 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { mStatusBarKeyguardViewManager.showBouncer(scrimmed); // THEN regular bouncer is shown - verify(mPrimaryBouncer).show(anyBoolean(), eq(scrimmed)); + verify(mPrimaryBouncerInteractor).show(eq(scrimmed)); verify(mAlternateBouncer, never()).showAlternateBouncer(); } @@ -501,7 +498,7 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { public void testShowAlternateBouncer_unlockingWithBiometricAllowed() { // GIVEN alt auth exists, unlocking with biometric is allowed mStatusBarKeyguardViewManager.setAlternateBouncer(mAlternateBouncer); - when(mPrimaryBouncer.isShowing()).thenReturn(false); + when(mPrimaryBouncerInteractor.isFullyShowing()).thenReturn(false); when(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(true); // WHEN showGenericBouncer is called @@ -509,30 +506,28 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { // THEN alt auth bouncer is shown verify(mAlternateBouncer).showAlternateBouncer(); - verify(mPrimaryBouncer, never()).show(anyBoolean(), anyBoolean()); + verify(mPrimaryBouncerInteractor, never()).show(anyBoolean()); } @Test public void testUpdateResources_delegatesToBouncer() { mStatusBarKeyguardViewManager.updateResources(); - verify(mPrimaryBouncer).updateResources(); + verify(mPrimaryBouncerInteractor).updateResources(); } @Test public void updateKeyguardPosition_delegatesToBouncer() { mStatusBarKeyguardViewManager.updateKeyguardPosition(1.0f); - verify(mPrimaryBouncer).updateKeyguardPosition(1.0f); + verify(mPrimaryBouncerInteractor).setKeyguardPosition(1.0f); } @Test public void testIsBouncerInTransit() { - when(mPrimaryBouncer.inTransit()).thenReturn(true); + when(mPrimaryBouncerInteractor.isInTransit()).thenReturn(true); Truth.assertThat(mStatusBarKeyguardViewManager.isPrimaryBouncerInTransit()).isTrue(); - when(mPrimaryBouncer.inTransit()).thenReturn(false); - Truth.assertThat(mStatusBarKeyguardViewManager.isPrimaryBouncerInTransit()).isFalse(); - mPrimaryBouncer = null; + when(mPrimaryBouncerInteractor.isInTransit()).thenReturn(false); Truth.assertThat(mStatusBarKeyguardViewManager.isPrimaryBouncerInTransit()).isFalse(); } @@ -564,7 +559,7 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { eq(OnBackInvokedDispatcher.PRIORITY_OVERLAY), mOnBackInvokedCallback.capture()); - when(mPrimaryBouncer.isShowing()).thenReturn(true); + when(mPrimaryBouncerInteractor.isFullyShowing()).thenReturn(true); when(mCentralSurfaces.shouldKeyguardHideImmediately()).thenReturn(true); /* invoke the back callback directly */ mOnBackInvokedCallback.getValue().onBackInvoked(); @@ -594,13 +589,6 @@ public class StatusBarKeyguardViewManagerTest extends SysuiTestCase { } @Test - public void flag_off_DoesNotCallBouncerInteractor() { - when(mFeatureFlags.isEnabled(MODERN_BOUNCER)).thenReturn(false); - mStatusBarKeyguardViewManager.hideBouncer(false); - verify(mPrimaryBouncerInteractor, never()).hide(); - } - - @Test public void hideAlternateBouncer_beforeCentralSurfacesRegistered() { mStatusBarKeyguardViewManager = new StatusBarKeyguardViewManager( diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManagerTest_Old.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManagerTest_Old.java new file mode 100644 index 000000000000..96fba39d6b59 --- /dev/null +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManagerTest_Old.java @@ -0,0 +1,641 @@ +/* + * 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.statusbar.phone; + +import static com.android.systemui.flags.Flags.MODERN_BOUNCER; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyFloat; +import static org.mockito.ArgumentMatchers.anyInt; +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.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.testing.AndroidTestingRunner; +import android.testing.TestableLooper; +import android.view.View; +import android.view.ViewGroup; +import android.view.ViewRootImpl; +import android.window.OnBackInvokedCallback; +import android.window.OnBackInvokedDispatcher; +import android.window.WindowOnBackInvokedDispatcher; + +import androidx.test.filters.SmallTest; + +import com.android.internal.util.LatencyTracker; +import com.android.internal.widget.LockPatternUtils; +import com.android.keyguard.KeyguardMessageArea; +import com.android.keyguard.KeyguardMessageAreaController; +import com.android.keyguard.KeyguardSecurityModel; +import com.android.keyguard.KeyguardUpdateMonitor; +import com.android.keyguard.ViewMediatorCallback; +import com.android.systemui.SysuiTestCase; +import com.android.systemui.dock.DockManager; +import com.android.systemui.dreams.DreamOverlayStateController; +import com.android.systemui.flags.FeatureFlags; +import com.android.systemui.keyguard.data.BouncerView; +import com.android.systemui.keyguard.data.BouncerViewDelegate; +import com.android.systemui.keyguard.domain.interactor.PrimaryBouncerCallbackInteractor; +import com.android.systemui.keyguard.domain.interactor.PrimaryBouncerInteractor; +import com.android.systemui.navigationbar.NavigationModeController; +import com.android.systemui.plugins.ActivityStarter.OnDismissAction; +import com.android.systemui.shade.NotificationPanelViewController; +import com.android.systemui.shade.ShadeController; +import com.android.systemui.shade.ShadeExpansionChangeEvent; +import com.android.systemui.shade.ShadeExpansionStateManager; +import com.android.systemui.statusbar.NotificationMediaManager; +import com.android.systemui.statusbar.NotificationShadeWindowController; +import com.android.systemui.statusbar.StatusBarState; +import com.android.systemui.statusbar.SysuiStatusBarStateController; +import com.android.systemui.statusbar.policy.ConfigurationController; +import com.android.systemui.unfold.SysUIUnfoldComponent; + +import com.google.common.truth.Truth; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.util.Optional; + +/** + * StatusBarKeyguardViewManager Test with deprecated KeyguardBouncer.java. + * TODO: Delete when deleting {@link KeyguardBouncer} + */ +@SmallTest +@RunWith(AndroidTestingRunner.class) +@TestableLooper.RunWithLooper +public class StatusBarKeyguardViewManagerTest_Old extends SysuiTestCase { + private static final ShadeExpansionChangeEvent EXPANSION_EVENT = + expansionEvent(/* fraction= */ 0.5f, /* expanded= */ false, /* tracking= */ true); + + @Mock private ViewMediatorCallback mViewMediatorCallback; + @Mock private LockPatternUtils mLockPatternUtils; + @Mock private CentralSurfaces mCentralSurfaces; + @Mock private ViewGroup mContainer; + @Mock private NotificationPanelViewController mNotificationPanelView; + @Mock private BiometricUnlockController mBiometricUnlockController; + @Mock private SysuiStatusBarStateController mStatusBarStateController; + @Mock private KeyguardUpdateMonitor mKeyguardUpdateMonitor; + @Mock private View mNotificationContainer; + @Mock private KeyguardBypassController mBypassController; + @Mock private KeyguardBouncer.Factory mKeyguardBouncerFactory; + @Mock private KeyguardMessageAreaController.Factory mKeyguardMessageAreaFactory; + @Mock private KeyguardMessageAreaController mKeyguardMessageAreaController; + @Mock private KeyguardBouncer mPrimaryBouncer; + @Mock private StatusBarKeyguardViewManager.AlternateBouncer mAlternateBouncer; + @Mock private KeyguardMessageArea mKeyguardMessageArea; + @Mock private ShadeController mShadeController; + @Mock private SysUIUnfoldComponent mSysUiUnfoldComponent; + @Mock private DreamOverlayStateController mDreamOverlayStateController; + @Mock private LatencyTracker mLatencyTracker; + @Mock private FeatureFlags mFeatureFlags; + @Mock private KeyguardSecurityModel mKeyguardSecurityModel; + @Mock private PrimaryBouncerCallbackInteractor mPrimaryBouncerCallbackInteractor; + @Mock private PrimaryBouncerInteractor mPrimaryBouncerInteractor; + @Mock private BouncerView mBouncerView; + @Mock private BouncerViewDelegate mBouncerViewDelegate; + + private StatusBarKeyguardViewManager mStatusBarKeyguardViewManager; + private KeyguardBouncer.PrimaryBouncerExpansionCallback mBouncerExpansionCallback; + private FakeKeyguardStateController mKeyguardStateController = + spy(new FakeKeyguardStateController()); + + @Mock private ViewRootImpl mViewRootImpl; + @Mock private WindowOnBackInvokedDispatcher mOnBackInvokedDispatcher; + @Captor + private ArgumentCaptor<OnBackInvokedCallback> mOnBackInvokedCallback; + + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + when(mKeyguardBouncerFactory.create( + any(ViewGroup.class), + any(KeyguardBouncer.PrimaryBouncerExpansionCallback.class))) + .thenReturn(mPrimaryBouncer); + when(mCentralSurfaces.getBouncerContainer()).thenReturn(mContainer); + when(mContainer.findViewById(anyInt())).thenReturn(mKeyguardMessageArea); + when(mKeyguardMessageAreaFactory.create(any(KeyguardMessageArea.class))) + .thenReturn(mKeyguardMessageAreaController); + when(mBouncerView.getDelegate()).thenReturn(mBouncerViewDelegate); + + mStatusBarKeyguardViewManager = + new StatusBarKeyguardViewManager( + getContext(), + mViewMediatorCallback, + mLockPatternUtils, + mStatusBarStateController, + mock(ConfigurationController.class), + mKeyguardUpdateMonitor, + mDreamOverlayStateController, + mock(NavigationModeController.class), + mock(DockManager.class), + mock(NotificationShadeWindowController.class), + mKeyguardStateController, + mock(NotificationMediaManager.class), + mKeyguardBouncerFactory, + mKeyguardMessageAreaFactory, + Optional.of(mSysUiUnfoldComponent), + () -> mShadeController, + mLatencyTracker, + mKeyguardSecurityModel, + mFeatureFlags, + mPrimaryBouncerCallbackInteractor, + mPrimaryBouncerInteractor, + mBouncerView) { + @Override + public ViewRootImpl getViewRootImpl() { + return mViewRootImpl; + } + }; + when(mViewRootImpl.getOnBackInvokedDispatcher()) + .thenReturn(mOnBackInvokedDispatcher); + mStatusBarKeyguardViewManager.registerCentralSurfaces( + mCentralSurfaces, + mNotificationPanelView, + new ShadeExpansionStateManager(), + mBiometricUnlockController, + mNotificationContainer, + mBypassController); + mStatusBarKeyguardViewManager.show(null); + ArgumentCaptor<KeyguardBouncer.PrimaryBouncerExpansionCallback> callbackArgumentCaptor = + ArgumentCaptor.forClass(KeyguardBouncer.PrimaryBouncerExpansionCallback.class); + verify(mKeyguardBouncerFactory).create(any(ViewGroup.class), + callbackArgumentCaptor.capture()); + mBouncerExpansionCallback = callbackArgumentCaptor.getValue(); + } + + @Test + public void dismissWithAction_AfterKeyguardGoneSetToFalse() { + OnDismissAction action = () -> false; + Runnable cancelAction = () -> {}; + mStatusBarKeyguardViewManager.dismissWithAction( + action, cancelAction, false /* afterKeyguardGone */); + verify(mPrimaryBouncer).showWithDismissAction(eq(action), eq(cancelAction)); + } + + @Test + public void showBouncer_onlyWhenShowing() { + mStatusBarKeyguardViewManager.hide(0 /* startTime */, 0 /* fadeoutDuration */); + mStatusBarKeyguardViewManager.showPrimaryBouncer(true /* scrimmed */); + verify(mPrimaryBouncer, never()).show(anyBoolean(), anyBoolean()); + verify(mPrimaryBouncer, never()).show(anyBoolean()); + } + + @Test + public void showBouncer_notWhenBouncerAlreadyShowing() { + mStatusBarKeyguardViewManager.hide(0 /* startTime */, 0 /* fadeoutDuration */); + when(mPrimaryBouncer.isSecure()).thenReturn(true); + mStatusBarKeyguardViewManager.showPrimaryBouncer(true /* scrimmed */); + verify(mPrimaryBouncer, never()).show(anyBoolean(), anyBoolean()); + verify(mPrimaryBouncer, never()).show(anyBoolean()); + } + + @Test + public void showBouncer_showsTheBouncer() { + mStatusBarKeyguardViewManager.showPrimaryBouncer(true /* scrimmed */); + verify(mPrimaryBouncer).show(anyBoolean(), eq(true)); + } + + @Test + public void onPanelExpansionChanged_neverShowsDuringHintAnimation() { + when(mNotificationPanelView.isUnlockHintRunning()).thenReturn(true); + mStatusBarKeyguardViewManager.onPanelExpansionChanged(EXPANSION_EVENT); + verify(mPrimaryBouncer, never()).setExpansion(anyFloat()); + } + + @Test + public void onPanelExpansionChanged_propagatesToBouncerOnlyIfShowing() { + mStatusBarKeyguardViewManager.onPanelExpansionChanged(EXPANSION_EVENT); + verify(mPrimaryBouncer, never()).setExpansion(eq(0.5f)); + + when(mPrimaryBouncer.isShowing()).thenReturn(true); + mStatusBarKeyguardViewManager.onPanelExpansionChanged( + expansionEvent(/* fraction= */ 0.6f, /* expanded= */ false, /* tracking= */ true)); + verify(mPrimaryBouncer).setExpansion(eq(0.6f)); + } + + @Test + public void onPanelExpansionChanged_duplicateEventsAreIgnored() { + when(mPrimaryBouncer.isShowing()).thenReturn(true); + mStatusBarKeyguardViewManager.onPanelExpansionChanged(EXPANSION_EVENT); + verify(mPrimaryBouncer).setExpansion(eq(0.5f)); + + reset(mPrimaryBouncer); + mStatusBarKeyguardViewManager.onPanelExpansionChanged(EXPANSION_EVENT); + verify(mPrimaryBouncer, never()).setExpansion(eq(0.5f)); + } + + @Test + public void onPanelExpansionChanged_hideBouncer_afterKeyguardHidden() { + mStatusBarKeyguardViewManager.hide(0, 0); + when(mPrimaryBouncer.inTransit()).thenReturn(true); + + mStatusBarKeyguardViewManager.onPanelExpansionChanged(EXPANSION_EVENT); + verify(mPrimaryBouncer).setExpansion(eq(KeyguardBouncer.EXPANSION_HIDDEN)); + } + + @Test + public void onPanelExpansionChanged_showsBouncerWhenSwiping() { + mKeyguardStateController.setCanDismissLockScreen(false); + mStatusBarKeyguardViewManager.onPanelExpansionChanged(EXPANSION_EVENT); + verify(mPrimaryBouncer).show(eq(false), eq(false)); + + // But not when it's already visible + reset(mPrimaryBouncer); + when(mPrimaryBouncer.isShowing()).thenReturn(true); + mStatusBarKeyguardViewManager.onPanelExpansionChanged(EXPANSION_EVENT); + verify(mPrimaryBouncer, never()).show(eq(false), eq(false)); + + // Or animating away + reset(mPrimaryBouncer); + when(mPrimaryBouncer.isAnimatingAway()).thenReturn(true); + mStatusBarKeyguardViewManager.onPanelExpansionChanged(EXPANSION_EVENT); + verify(mPrimaryBouncer, never()).show(eq(false), eq(false)); + } + + @Test + public void onPanelExpansionChanged_neverTranslatesBouncerWhenWakeAndUnlock() { + when(mBiometricUnlockController.getMode()) + .thenReturn(BiometricUnlockController.MODE_WAKE_AND_UNLOCK); + mStatusBarKeyguardViewManager.onPanelExpansionChanged( + expansionEvent( + /* fraction= */ KeyguardBouncer.EXPANSION_VISIBLE, + /* expanded= */ true, + /* tracking= */ false)); + verify(mPrimaryBouncer, never()).setExpansion(anyFloat()); + } + + @Test + public void onPanelExpansionChanged_neverTranslatesBouncerWhenDismissBouncer() { + // Since KeyguardBouncer.EXPANSION_VISIBLE = 0 panel expansion, if the unlock is dismissing + // the bouncer, there may be an onPanelExpansionChanged(0) call to collapse the panel + // which would mistakenly cause the bouncer to show briefly before its visibility + // is set to hide. Therefore, we don't want to propagate panelExpansionChanged to the + // bouncer if the bouncer is dismissing as a result of a biometric unlock. + when(mBiometricUnlockController.getMode()) + .thenReturn(BiometricUnlockController.MODE_DISMISS_BOUNCER); + mStatusBarKeyguardViewManager.onPanelExpansionChanged( + expansionEvent( + /* fraction= */ KeyguardBouncer.EXPANSION_VISIBLE, + /* expanded= */ true, + /* tracking= */ false)); + verify(mPrimaryBouncer, never()).setExpansion(anyFloat()); + } + + @Test + public void onPanelExpansionChanged_neverTranslatesBouncerWhenOccluded() { + when(mKeyguardStateController.isOccluded()).thenReturn(true); + mStatusBarKeyguardViewManager.onPanelExpansionChanged( + expansionEvent( + /* fraction= */ KeyguardBouncer.EXPANSION_VISIBLE, + /* expanded= */ true, + /* tracking= */ false)); + verify(mPrimaryBouncer, never()).setExpansion(anyFloat()); + } + + @Test + public void onPanelExpansionChanged_neverTranslatesBouncerWhenShowBouncer() { + // Since KeyguardBouncer.EXPANSION_VISIBLE = 0 panel expansion, if the unlock is dismissing + // the bouncer, there may be an onPanelExpansionChanged(0) call to collapse the panel + // which would mistakenly cause the bouncer to show briefly before its visibility + // is set to hide. Therefore, we don't want to propagate panelExpansionChanged to the + // bouncer if the bouncer is dismissing as a result of a biometric unlock. + when(mBiometricUnlockController.getMode()) + .thenReturn(BiometricUnlockController.MODE_SHOW_BOUNCER); + mStatusBarKeyguardViewManager.onPanelExpansionChanged( + expansionEvent( + /* fraction= */ KeyguardBouncer.EXPANSION_VISIBLE, + /* expanded= */ true, + /* tracking= */ false)); + verify(mPrimaryBouncer, never()).setExpansion(anyFloat()); + } + + @Test + public void onPanelExpansionChanged_neverTranslatesBouncerWhenShadeLocked() { + when(mStatusBarStateController.getState()).thenReturn(StatusBarState.SHADE_LOCKED); + mStatusBarKeyguardViewManager.onPanelExpansionChanged( + expansionEvent( + /* fraction= */ KeyguardBouncer.EXPANSION_VISIBLE, + /* expanded= */ true, + /* tracking= */ false)); + verify(mPrimaryBouncer, never()).setExpansion(anyFloat()); + } + + @Test + public void setOccluded_animatesPanelExpansion_onlyIfBouncerHidden() { + mStatusBarKeyguardViewManager.setOccluded(false /* occluded */, true /* animated */); + verify(mCentralSurfaces).animateKeyguardUnoccluding(); + + when(mPrimaryBouncer.isShowing()).thenReturn(true); + clearInvocations(mCentralSurfaces); + mStatusBarKeyguardViewManager.setOccluded(false /* occluded */, true /* animated */); + verify(mCentralSurfaces, never()).animateKeyguardUnoccluding(); + } + + @Test + public void setOccluded_onKeyguardOccludedChangedCalled() { + clearInvocations(mKeyguardStateController); + clearInvocations(mKeyguardUpdateMonitor); + + mStatusBarKeyguardViewManager.setOccluded(false /* occluded */, false /* animated */); + verify(mKeyguardStateController).notifyKeyguardState(true, false); + + clearInvocations(mKeyguardUpdateMonitor); + clearInvocations(mKeyguardStateController); + + mStatusBarKeyguardViewManager.setOccluded(true /* occluded */, false /* animated */); + verify(mKeyguardStateController).notifyKeyguardState(true, true); + + clearInvocations(mKeyguardUpdateMonitor); + clearInvocations(mKeyguardStateController); + + mStatusBarKeyguardViewManager.setOccluded(false /* occluded */, false /* animated */); + verify(mKeyguardStateController).notifyKeyguardState(true, false); + } + + @Test + public void setOccluded_isInLaunchTransition_onKeyguardOccludedChangedCalled() { + mStatusBarKeyguardViewManager.show(null); + + mStatusBarKeyguardViewManager.setOccluded(true /* occluded */, false /* animated */); + verify(mKeyguardStateController).notifyKeyguardState(true, true); + } + + @Test + public void setOccluded_isLaunchingActivityOverLockscreen_onKeyguardOccludedChangedCalled() { + when(mCentralSurfaces.isLaunchingActivityOverLockscreen()).thenReturn(true); + mStatusBarKeyguardViewManager.show(null); + + mStatusBarKeyguardViewManager.setOccluded(true /* occluded */, false /* animated */); + verify(mKeyguardStateController).notifyKeyguardState(true, true); + } + + @Test + public void testHiding_cancelsGoneRunnable() { + OnDismissAction action = mock(OnDismissAction.class); + Runnable cancelAction = mock(Runnable.class); + mStatusBarKeyguardViewManager.dismissWithAction( + action, cancelAction, true /* afterKeyguardGone */); + + when(mPrimaryBouncer.isShowing()).thenReturn(false); + mStatusBarKeyguardViewManager.hideBouncer(true); + mStatusBarKeyguardViewManager.hide(0, 30); + verify(action, never()).onDismiss(); + verify(cancelAction).run(); + } + + @Test + public void testHidingBouncer_cancelsGoneRunnable() { + OnDismissAction action = mock(OnDismissAction.class); + Runnable cancelAction = mock(Runnable.class); + mStatusBarKeyguardViewManager.dismissWithAction( + action, cancelAction, true /* afterKeyguardGone */); + + when(mPrimaryBouncer.isShowing()).thenReturn(false); + mStatusBarKeyguardViewManager.hideBouncer(true); + + verify(action, never()).onDismiss(); + verify(cancelAction).run(); + } + + @Test + public void testHiding_doesntCancelWhenShowing() { + OnDismissAction action = mock(OnDismissAction.class); + Runnable cancelAction = mock(Runnable.class); + mStatusBarKeyguardViewManager.dismissWithAction( + action, cancelAction, true /* afterKeyguardGone */); + + mStatusBarKeyguardViewManager.hide(0, 30); + verify(action).onDismiss(); + verify(cancelAction, never()).run(); + } + + @Test + public void testShowing_whenAlternateAuthShowing() { + mStatusBarKeyguardViewManager.setAlternateBouncer(mAlternateBouncer); + when(mPrimaryBouncer.isShowing()).thenReturn(false); + when(mAlternateBouncer.isShowingAlternateBouncer()).thenReturn(true); + assertTrue( + "Is showing not accurate when alternative auth showing", + mStatusBarKeyguardViewManager.isBouncerShowing()); + } + + @Test + public void testWillBeShowing_whenAlternateAuthShowing() { + mStatusBarKeyguardViewManager.setAlternateBouncer(mAlternateBouncer); + when(mPrimaryBouncer.isShowing()).thenReturn(false); + when(mAlternateBouncer.isShowingAlternateBouncer()).thenReturn(true); + assertTrue( + "Is or will be showing not accurate when alternative auth showing", + mStatusBarKeyguardViewManager.primaryBouncerIsOrWillBeShowing()); + } + + @Test + public void testHideAlternateBouncer_onShowBouncer() { + // GIVEN alt auth is showing + mStatusBarKeyguardViewManager.setAlternateBouncer(mAlternateBouncer); + when(mPrimaryBouncer.isShowing()).thenReturn(false); + when(mAlternateBouncer.isShowingAlternateBouncer()).thenReturn(true); + reset(mAlternateBouncer); + + // WHEN showBouncer is called + mStatusBarKeyguardViewManager.showPrimaryBouncer(true); + + // THEN alt bouncer should be hidden + verify(mAlternateBouncer).hideAlternateBouncer(); + } + + @Test + public void testBouncerIsOrWillBeShowing_whenBouncerIsInTransit() { + when(mPrimaryBouncer.isShowing()).thenReturn(false); + when(mPrimaryBouncer.inTransit()).thenReturn(true); + + assertTrue( + "Is or will be showing should be true when bouncer is in transit", + mStatusBarKeyguardViewManager.primaryBouncerIsOrWillBeShowing()); + } + + @Test + public void testShowAltAuth_unlockingWithBiometricNotAllowed() { + // GIVEN alt auth exists, unlocking with biometric isn't allowed + mStatusBarKeyguardViewManager.setAlternateBouncer(mAlternateBouncer); + when(mPrimaryBouncer.isShowing()).thenReturn(false); + when(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(anyBoolean())) + .thenReturn(false); + + // WHEN showGenericBouncer is called + final boolean scrimmed = true; + mStatusBarKeyguardViewManager.showBouncer(scrimmed); + + // THEN regular bouncer is shown + verify(mPrimaryBouncer).show(anyBoolean(), eq(scrimmed)); + verify(mAlternateBouncer, never()).showAlternateBouncer(); + } + + @Test + public void testShowAlternateBouncer_unlockingWithBiometricAllowed() { + // GIVEN alt auth exists, unlocking with biometric is allowed + mStatusBarKeyguardViewManager.setAlternateBouncer(mAlternateBouncer); + when(mPrimaryBouncer.isShowing()).thenReturn(false); + when(mKeyguardUpdateMonitor.isUnlockingWithBiometricAllowed(anyBoolean())).thenReturn(true); + + // WHEN showGenericBouncer is called + mStatusBarKeyguardViewManager.showBouncer(true); + + // THEN alt auth bouncer is shown + verify(mAlternateBouncer).showAlternateBouncer(); + verify(mPrimaryBouncer, never()).show(anyBoolean(), anyBoolean()); + } + + @Test + public void testUpdateResources_delegatesToBouncer() { + mStatusBarKeyguardViewManager.updateResources(); + + verify(mPrimaryBouncer).updateResources(); + } + + @Test + public void updateKeyguardPosition_delegatesToBouncer() { + mStatusBarKeyguardViewManager.updateKeyguardPosition(1.0f); + + verify(mPrimaryBouncer).updateKeyguardPosition(1.0f); + } + + @Test + public void testIsBouncerInTransit() { + when(mPrimaryBouncer.inTransit()).thenReturn(true); + Truth.assertThat(mStatusBarKeyguardViewManager.isPrimaryBouncerInTransit()).isTrue(); + when(mPrimaryBouncer.inTransit()).thenReturn(false); + Truth.assertThat(mStatusBarKeyguardViewManager.isPrimaryBouncerInTransit()).isFalse(); + mPrimaryBouncer = null; + Truth.assertThat(mStatusBarKeyguardViewManager.isPrimaryBouncerInTransit()).isFalse(); + } + + private static ShadeExpansionChangeEvent expansionEvent( + float fraction, boolean expanded, boolean tracking) { + return new ShadeExpansionChangeEvent( + fraction, expanded, tracking, /* dragDownPxAmount= */ 0f); + } + + @Test + public void testPredictiveBackCallback_registration() { + /* verify that a predictive back callback is registered when the bouncer becomes visible */ + mBouncerExpansionCallback.onVisibilityChanged(true); + verify(mOnBackInvokedDispatcher).registerOnBackInvokedCallback( + eq(OnBackInvokedDispatcher.PRIORITY_OVERLAY), + mOnBackInvokedCallback.capture()); + + /* verify that the same callback is unregistered when the bouncer becomes invisible */ + mBouncerExpansionCallback.onVisibilityChanged(false); + verify(mOnBackInvokedDispatcher).unregisterOnBackInvokedCallback( + eq(mOnBackInvokedCallback.getValue())); + } + + @Test + public void testPredictiveBackCallback_invocationHidesBouncer() { + mBouncerExpansionCallback.onVisibilityChanged(true); + /* capture the predictive back callback during registration */ + verify(mOnBackInvokedDispatcher).registerOnBackInvokedCallback( + eq(OnBackInvokedDispatcher.PRIORITY_OVERLAY), + mOnBackInvokedCallback.capture()); + + when(mPrimaryBouncer.isShowing()).thenReturn(true); + when(mCentralSurfaces.shouldKeyguardHideImmediately()).thenReturn(true); + /* invoke the back callback directly */ + mOnBackInvokedCallback.getValue().onBackInvoked(); + + /* verify that the bouncer will be hidden as a result of the invocation */ + verify(mCentralSurfaces).setBouncerShowing(eq(false)); + } + + @Test + public void testReportBouncerOnDreamWhenVisible() { + mBouncerExpansionCallback.onVisibilityChanged(true); + verify(mCentralSurfaces).setBouncerShowingOverDream(false); + Mockito.clearInvocations(mCentralSurfaces); + when(mDreamOverlayStateController.isOverlayActive()).thenReturn(true); + mBouncerExpansionCallback.onVisibilityChanged(true); + verify(mCentralSurfaces).setBouncerShowingOverDream(true); + } + + @Test + public void testReportBouncerOnDreamWhenNotVisible() { + mBouncerExpansionCallback.onVisibilityChanged(false); + verify(mCentralSurfaces).setBouncerShowingOverDream(false); + Mockito.clearInvocations(mCentralSurfaces); + when(mDreamOverlayStateController.isOverlayActive()).thenReturn(true); + mBouncerExpansionCallback.onVisibilityChanged(false); + verify(mCentralSurfaces).setBouncerShowingOverDream(false); + } + + @Test + public void flag_off_DoesNotCallBouncerInteractor() { + when(mFeatureFlags.isEnabled(MODERN_BOUNCER)).thenReturn(false); + mStatusBarKeyguardViewManager.hideBouncer(false); + verify(mPrimaryBouncerInteractor, never()).hide(); + } + + @Test + public void hideAlternateBouncer_beforeCentralSurfacesRegistered() { + mStatusBarKeyguardViewManager = + new StatusBarKeyguardViewManager( + getContext(), + mViewMediatorCallback, + mLockPatternUtils, + mStatusBarStateController, + mock(ConfigurationController.class), + mKeyguardUpdateMonitor, + mDreamOverlayStateController, + mock(NavigationModeController.class), + mock(DockManager.class), + mock(NotificationShadeWindowController.class), + mKeyguardStateController, + mock(NotificationMediaManager.class), + mKeyguardBouncerFactory, + mKeyguardMessageAreaFactory, + Optional.of(mSysUiUnfoldComponent), + () -> mShadeController, + mLatencyTracker, + mKeyguardSecurityModel, + mFeatureFlags, + mPrimaryBouncerCallbackInteractor, + mPrimaryBouncerInteractor, + mBouncerView) { + @Override + public ViewRootImpl getViewRootImpl() { + return mViewRootImpl; + } + }; + + // the following call before registering centralSurfaces should NOT throw a NPE: + mStatusBarKeyguardViewManager.hideAlternateBouncer(true); + } +} diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionRepository.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionRepository.kt index 288f54c7d03c..5265ec66bc24 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionRepository.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionRepository.kt @@ -16,12 +16,13 @@ package com.android.systemui.statusbar.pipeline.mobile.data.repository -import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileSubscriptionModel +import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileConnectionModel import kotlinx.coroutines.flow.MutableStateFlow -class FakeMobileConnectionRepository : MobileConnectionRepository { - private val _subscriptionsModelFlow = MutableStateFlow(MobileSubscriptionModel()) - override val subscriptionModelFlow = _subscriptionsModelFlow +// TODO(b/261632894): remove this in favor of the real impl or DemoMobileConnectionRepository +class FakeMobileConnectionRepository(override val subId: Int) : MobileConnectionRepository { + private val _connectionInfo = MutableStateFlow(MobileConnectionModel()) + override val connectionInfo = _connectionInfo private val _dataEnabled = MutableStateFlow(true) override val dataEnabled = _dataEnabled @@ -29,8 +30,8 @@ class FakeMobileConnectionRepository : MobileConnectionRepository { private val _isDefaultDataSubscription = MutableStateFlow(true) override val isDefaultDataSubscription = _isDefaultDataSubscription - fun setMobileSubscriptionModel(model: MobileSubscriptionModel) { - _subscriptionsModelFlow.value = model + fun setConnectionInfo(model: MobileConnectionModel) { + _connectionInfo.value = model } fun setDataEnabled(enabled: Boolean) { diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionsRepository.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionsRepository.kt index 533d5d9d5b4a..d6af0e6b3a82 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionsRepository.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/FakeMobileConnectionsRepository.kt @@ -16,23 +16,43 @@ package com.android.systemui.statusbar.pipeline.mobile.data.repository -import android.telephony.SubscriptionInfo import android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID -import com.android.settingslib.mobile.MobileMappings.Config +import android.telephony.TelephonyDisplayInfo +import android.telephony.TelephonyManager +import com.android.settingslib.SignalIcon +import com.android.settingslib.mobile.TelephonyIcons import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileConnectivityModel -import kotlinx.coroutines.flow.Flow +import com.android.systemui.statusbar.pipeline.mobile.data.model.SubscriptionModel +import com.android.systemui.statusbar.pipeline.mobile.util.MobileMappingsProxy import kotlinx.coroutines.flow.MutableStateFlow -class FakeMobileConnectionsRepository : MobileConnectionsRepository { - private val _subscriptionsFlow = MutableStateFlow<List<SubscriptionInfo>>(listOf()) - override val subscriptionsFlow: Flow<List<SubscriptionInfo>> = _subscriptionsFlow +// TODO(b/261632894): remove this in favor of the real impl or DemoMobileConnectionsRepository +class FakeMobileConnectionsRepository(mobileMappings: MobileMappingsProxy) : + MobileConnectionsRepository { + val GSM_KEY = mobileMappings.toIconKey(GSM) + val LTE_KEY = mobileMappings.toIconKey(LTE) + val UMTS_KEY = mobileMappings.toIconKey(UMTS) + val LTE_ADVANCED_KEY = mobileMappings.toIconKeyOverride(LTE_ADVANCED_PRO) + + /** + * To avoid a reliance on [MobileMappings], we'll build a simpler map from network type to + * mobile icon. See TelephonyManager.NETWORK_TYPES for a list of types and [TelephonyIcons] for + * the exhaustive set of icons + */ + val TEST_MAPPING: Map<String, SignalIcon.MobileIconGroup> = + mapOf( + GSM_KEY to TelephonyIcons.THREE_G, + LTE_KEY to TelephonyIcons.LTE, + UMTS_KEY to TelephonyIcons.FOUR_G, + LTE_ADVANCED_KEY to TelephonyIcons.NR_5G, + ) + + private val _subscriptions = MutableStateFlow<List<SubscriptionModel>>(listOf()) + override val subscriptions = _subscriptions private val _activeMobileDataSubscriptionId = MutableStateFlow(INVALID_SUBSCRIPTION_ID) override val activeMobileDataSubscriptionId = _activeMobileDataSubscriptionId - private val _defaultDataSubRatConfig = MutableStateFlow(Config()) - override val defaultDataSubRatConfig = _defaultDataSubRatConfig - private val _defaultDataSubId = MutableStateFlow(INVALID_SUBSCRIPTION_ID) override val defaultDataSubId = _defaultDataSubId @@ -41,18 +61,21 @@ class FakeMobileConnectionsRepository : MobileConnectionsRepository { private val subIdRepos = mutableMapOf<Int, MobileConnectionRepository>() override fun getRepoForSubId(subId: Int): MobileConnectionRepository { - return subIdRepos[subId] ?: FakeMobileConnectionRepository().also { subIdRepos[subId] = it } + return subIdRepos[subId] + ?: FakeMobileConnectionRepository(subId).also { subIdRepos[subId] = it } } private val _globalMobileDataSettingChangedEvent = MutableStateFlow(Unit) override val globalMobileDataSettingChangedEvent = _globalMobileDataSettingChangedEvent - fun setSubscriptions(subs: List<SubscriptionInfo>) { - _subscriptionsFlow.value = subs - } + private val _defaultMobileIconMapping = MutableStateFlow(TEST_MAPPING) + override val defaultMobileIconMapping = _defaultMobileIconMapping + + private val _defaultMobileIconGroup = MutableStateFlow(DEFAULT_ICON) + override val defaultMobileIconGroup = _defaultMobileIconGroup - fun setDefaultDataSubRatConfig(config: Config) { - _defaultDataSubRatConfig.value = config + fun setSubscriptions(subs: List<SubscriptionModel>) { + _subscriptions.value = subs } fun setDefaultDataSubId(id: Int) { @@ -74,4 +97,14 @@ class FakeMobileConnectionsRepository : MobileConnectionsRepository { fun setMobileConnectionRepositoryMap(connections: Map<Int, MobileConnectionRepository>) { connections.forEach { entry -> subIdRepos[entry.key] = entry.value } } + + companion object { + val DEFAULT_ICON = TelephonyIcons.G + + // Use [MobileMappings] to define some simple definitions + const val GSM = TelephonyManager.NETWORK_TYPE_GSM + const val LTE = TelephonyManager.NETWORK_TYPE_LTE + const val UMTS = TelephonyManager.NETWORK_TYPE_UMTS + const val LTE_ADVANCED_PRO = TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_LTE_ADVANCED_PRO + } } diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileRepositorySwitcherTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileRepositorySwitcherTest.kt index 96a280a296ed..18ae90db881a 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileRepositorySwitcherTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/MobileRepositorySwitcherTest.kt @@ -24,11 +24,13 @@ import androidx.test.filters.SmallTest import com.android.systemui.SysuiTestCase import com.android.systemui.demomode.DemoMode import com.android.systemui.demomode.DemoModeController +import com.android.systemui.statusbar.pipeline.mobile.data.model.SubscriptionModel import com.android.systemui.statusbar.pipeline.mobile.data.repository.demo.DemoMobileConnectionsRepository import com.android.systemui.statusbar.pipeline.mobile.data.repository.demo.DemoModeMobileConnectionDataSource import com.android.systemui.statusbar.pipeline.mobile.data.repository.demo.model.FakeNetworkEventModel import com.android.systemui.statusbar.pipeline.mobile.data.repository.demo.validMobileEvent import com.android.systemui.statusbar.pipeline.mobile.data.repository.prod.MobileConnectionsRepositoryImpl +import com.android.systemui.statusbar.pipeline.mobile.util.FakeMobileMappingsProxy import com.android.systemui.statusbar.pipeline.shared.ConnectivityPipelineLogger import com.android.systemui.util.mockito.any import com.android.systemui.util.mockito.kotlinArgumentCaptor @@ -76,6 +78,7 @@ class MobileRepositorySwitcherTest : SysuiTestCase() { private val globalSettings = FakeSettings() private val fakeNetworkEventsFlow = MutableStateFlow<FakeNetworkEventModel?>(null) + private val mobileMappings = FakeMobileMappingsProxy() private val scope = CoroutineScope(IMMEDIATE) @@ -97,6 +100,7 @@ class MobileRepositorySwitcherTest : SysuiTestCase() { subscriptionManager, telephonyManager, logger, + mobileMappings, fakeBroadcastDispatcher, globalSettings, context, @@ -155,15 +159,15 @@ class MobileRepositorySwitcherTest : SysuiTestCase() { whenever(subscriptionManager.completeActiveSubscriptionInfoList) .thenReturn(listOf(SUB_1, SUB_2)) - var latest: List<SubscriptionInfo>? = null - val job = underTest.subscriptionsFlow.onEach { latest = it }.launchIn(this) + var latest: List<SubscriptionModel>? = null + val job = underTest.subscriptions.onEach { latest = it }.launchIn(this) // The real subscriptions has 2 subs whenever(subscriptionManager.completeActiveSubscriptionInfoList) .thenReturn(listOf(SUB_1, SUB_2)) getSubscriptionCallback().onSubscriptionsChanged() - assertThat(latest).isEqualTo(listOf(SUB_1, SUB_2)) + assertThat(latest).isEqualTo(listOf(MODEL_1, MODEL_2)) // Demo mode turns on, and we should see only the demo subscriptions startDemoMode() @@ -176,7 +180,7 @@ class MobileRepositorySwitcherTest : SysuiTestCase() { finishDemoMode() - assertThat(latest).isEqualTo(listOf(SUB_1, SUB_2)) + assertThat(latest).isEqualTo(listOf(MODEL_1, MODEL_2)) job.cancel() } @@ -211,9 +215,11 @@ class MobileRepositorySwitcherTest : SysuiTestCase() { private const val SUB_1_ID = 1 private val SUB_1 = mock<SubscriptionInfo>().also { whenever(it.subscriptionId).thenReturn(SUB_1_ID) } + private val MODEL_1 = SubscriptionModel(subscriptionId = SUB_1_ID) private const val SUB_2_ID = 2 private val SUB_2 = mock<SubscriptionInfo>().also { whenever(it.subscriptionId).thenReturn(SUB_2_ID) } + private val MODEL_2 = SubscriptionModel(subscriptionId = SUB_2_ID) } } diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionParameterizedTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionParameterizedTest.kt index bf5ecd895c40..e943de25c15f 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionParameterizedTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionParameterizedTest.kt @@ -23,7 +23,7 @@ import com.android.settingslib.SignalIcon import com.android.settingslib.mobile.TelephonyIcons import com.android.systemui.SysuiTestCase import com.android.systemui.statusbar.pipeline.mobile.data.model.DataConnectionState -import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileSubscriptionModel +import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileConnectionModel import com.android.systemui.statusbar.pipeline.mobile.data.repository.demo.model.FakeNetworkEventModel import com.android.systemui.util.mockito.mock import com.android.systemui.util.mockito.whenever @@ -109,18 +109,18 @@ internal class DemoMobileConnectionParameterizedTest(private val testCase: TestC ) { when (model) { is FakeNetworkEventModel.Mobile -> { - val subscriptionModel: MobileSubscriptionModel = conn.subscriptionModelFlow.value + val connectionInfo: MobileConnectionModel = conn.connectionInfo.value assertThat(conn.subId).isEqualTo(model.subId) - assertThat(subscriptionModel.cdmaLevel).isEqualTo(model.level) - assertThat(subscriptionModel.primaryLevel).isEqualTo(model.level) - assertThat(subscriptionModel.dataActivityDirection).isEqualTo(model.activity) - assertThat(subscriptionModel.carrierNetworkChangeActive) + assertThat(connectionInfo.cdmaLevel).isEqualTo(model.level) + assertThat(connectionInfo.primaryLevel).isEqualTo(model.level) + assertThat(connectionInfo.dataActivityDirection).isEqualTo(model.activity) + assertThat(connectionInfo.carrierNetworkChangeActive) .isEqualTo(model.carrierNetworkChange) // TODO(b/261029387): check these once we start handling them - assertThat(subscriptionModel.isEmergencyOnly).isFalse() - assertThat(subscriptionModel.isGsm).isFalse() - assertThat(subscriptionModel.dataConnectionState) + assertThat(connectionInfo.isEmergencyOnly).isFalse() + assertThat(connectionInfo.isGsm).isFalse() + assertThat(connectionInfo.dataConnectionState) .isEqualTo(DataConnectionState.Connected) } // MobileDisabled isn't combinatorial in nature, and is tested in diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionsRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionsRepositoryTest.kt index a8f6993373d2..32d0410d589d 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionsRepositoryTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/demo/DemoMobileConnectionsRepositoryTest.kt @@ -16,7 +16,6 @@ package com.android.systemui.statusbar.pipeline.mobile.data.repository.demo -import android.telephony.SubscriptionInfo import android.telephony.TelephonyManager.DATA_ACTIVITY_INOUT import android.telephony.TelephonyManager.UNKNOWN_CARRIER_ID import androidx.test.filters.SmallTest @@ -24,7 +23,8 @@ import com.android.settingslib.SignalIcon import com.android.settingslib.mobile.TelephonyIcons.THREE_G import com.android.systemui.SysuiTestCase import com.android.systemui.statusbar.pipeline.mobile.data.model.DataConnectionState -import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileSubscriptionModel +import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileConnectionModel +import com.android.systemui.statusbar.pipeline.mobile.data.model.SubscriptionModel import com.android.systemui.statusbar.pipeline.mobile.data.repository.demo.model.FakeNetworkEventModel import com.android.systemui.statusbar.pipeline.mobile.data.repository.demo.model.FakeNetworkEventModel.MobileDisabled import com.android.systemui.util.mockito.mock @@ -73,8 +73,8 @@ class DemoMobileConnectionsRepositoryTest : SysuiTestCase() { @Test fun `network event - create new subscription`() = testScope.runTest { - var latest: List<SubscriptionInfo>? = null - val job = underTest.subscriptionsFlow.onEach { latest = it }.launchIn(this) + var latest: List<SubscriptionModel>? = null + val job = underTest.subscriptions.onEach { latest = it }.launchIn(this) assertThat(latest).isEmpty() @@ -89,8 +89,8 @@ class DemoMobileConnectionsRepositoryTest : SysuiTestCase() { @Test fun `network event - reuses subscription when same Id`() = testScope.runTest { - var latest: List<SubscriptionInfo>? = null - val job = underTest.subscriptionsFlow.onEach { latest = it }.launchIn(this) + var latest: List<SubscriptionModel>? = null + val job = underTest.subscriptions.onEach { latest = it }.launchIn(this) assertThat(latest).isEmpty() @@ -111,8 +111,8 @@ class DemoMobileConnectionsRepositoryTest : SysuiTestCase() { @Test fun `multiple subscriptions`() = testScope.runTest { - var latest: List<SubscriptionInfo>? = null - val job = underTest.subscriptionsFlow.onEach { latest = it }.launchIn(this) + var latest: List<SubscriptionModel>? = null + val job = underTest.subscriptions.onEach { latest = it }.launchIn(this) fakeNetworkEventFlow.value = validMobileEvent(subId = 1) fakeNetworkEventFlow.value = validMobileEvent(subId = 2) @@ -125,8 +125,8 @@ class DemoMobileConnectionsRepositoryTest : SysuiTestCase() { @Test fun `mobile disabled event - disables connection - subId specified - single conn`() = testScope.runTest { - var latest: List<SubscriptionInfo>? = null - val job = underTest.subscriptionsFlow.onEach { latest = it }.launchIn(this) + var latest: List<SubscriptionModel>? = null + val job = underTest.subscriptions.onEach { latest = it }.launchIn(this) fakeNetworkEventFlow.value = validMobileEvent(subId = 1, level = 1) @@ -140,8 +140,8 @@ class DemoMobileConnectionsRepositoryTest : SysuiTestCase() { @Test fun `mobile disabled event - disables connection - subId not specified - single conn`() = testScope.runTest { - var latest: List<SubscriptionInfo>? = null - val job = underTest.subscriptionsFlow.onEach { latest = it }.launchIn(this) + var latest: List<SubscriptionModel>? = null + val job = underTest.subscriptions.onEach { latest = it }.launchIn(this) fakeNetworkEventFlow.value = validMobileEvent(subId = 1, level = 1) @@ -155,8 +155,8 @@ class DemoMobileConnectionsRepositoryTest : SysuiTestCase() { @Test fun `mobile disabled event - disables connection - subId specified - multiple conn`() = testScope.runTest { - var latest: List<SubscriptionInfo>? = null - val job = underTest.subscriptionsFlow.onEach { latest = it }.launchIn(this) + var latest: List<SubscriptionModel>? = null + val job = underTest.subscriptions.onEach { latest = it }.launchIn(this) fakeNetworkEventFlow.value = validMobileEvent(subId = 1, level = 1) fakeNetworkEventFlow.value = validMobileEvent(subId = 2, level = 1) @@ -171,8 +171,8 @@ class DemoMobileConnectionsRepositoryTest : SysuiTestCase() { @Test fun `mobile disabled event - subId not specified - multiple conn - ignores command`() = testScope.runTest { - var latest: List<SubscriptionInfo>? = null - val job = underTest.subscriptionsFlow.onEach { latest = it }.launchIn(this) + var latest: List<SubscriptionModel>? = null + val job = underTest.subscriptions.onEach { latest = it }.launchIn(this) fakeNetworkEventFlow.value = validMobileEvent(subId = 1, level = 1) fakeNetworkEventFlow.value = validMobileEvent(subId = 2, level = 1) @@ -184,13 +184,32 @@ class DemoMobileConnectionsRepositoryTest : SysuiTestCase() { job.cancel() } + /** Regression test for b/261706421 */ + @Test + fun `multiple connections - remove all - does not throw`() = + testScope.runTest { + var latest: List<SubscriptionModel>? = null + val job = underTest.subscriptions.onEach { latest = it }.launchIn(this) + + // Two subscriptions are added + fakeNetworkEventFlow.value = validMobileEvent(subId = 1, level = 1) + fakeNetworkEventFlow.value = validMobileEvent(subId = 2, level = 1) + + // Then both are removed by turning off demo mode + underTest.stopProcessingCommands() + + assertThat(latest).isEmpty() + + job.cancel() + } + @Test fun `demo connection - single subscription`() = testScope.runTest { var currentEvent: FakeNetworkEventModel = validMobileEvent(subId = 1) var connections: List<DemoMobileConnectionRepository>? = null val job = - underTest.subscriptionsFlow + underTest.subscriptions .onEach { infos -> connections = infos.map { info -> underTest.getRepoForSubId(info.subscriptionId) } @@ -222,7 +241,7 @@ class DemoMobileConnectionsRepositoryTest : SysuiTestCase() { var connection2: DemoMobileConnectionRepository? = null var connections: List<DemoMobileConnectionRepository>? = null val job = - underTest.subscriptionsFlow + underTest.subscriptions .onEach { infos -> connections = infos.map { info -> underTest.getRepoForSubId(info.subscriptionId) } @@ -266,18 +285,18 @@ class DemoMobileConnectionsRepositoryTest : SysuiTestCase() { ) { when (model) { is FakeNetworkEventModel.Mobile -> { - val subscriptionModel: MobileSubscriptionModel = conn.subscriptionModelFlow.value + val connectionInfo: MobileConnectionModel = conn.connectionInfo.value assertThat(conn.subId).isEqualTo(model.subId) - assertThat(subscriptionModel.cdmaLevel).isEqualTo(model.level) - assertThat(subscriptionModel.primaryLevel).isEqualTo(model.level) - assertThat(subscriptionModel.dataActivityDirection).isEqualTo(model.activity) - assertThat(subscriptionModel.carrierNetworkChangeActive) + assertThat(connectionInfo.cdmaLevel).isEqualTo(model.level) + assertThat(connectionInfo.primaryLevel).isEqualTo(model.level) + assertThat(connectionInfo.dataActivityDirection).isEqualTo(model.activity) + assertThat(connectionInfo.carrierNetworkChangeActive) .isEqualTo(model.carrierNetworkChange) // TODO(b/261029387) check these once we start handling them - assertThat(subscriptionModel.isEmergencyOnly).isFalse() - assertThat(subscriptionModel.isGsm).isFalse() - assertThat(subscriptionModel.dataConnectionState) + assertThat(connectionInfo.isEmergencyOnly).isFalse() + assertThat(connectionInfo.isGsm).isFalse() + assertThat(connectionInfo.dataConnectionState) .isEqualTo(DataConnectionState.Connected) } else -> {} diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryTest.kt index c8df5ac17dff..1fc9c60cd9ce 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionRepositoryTest.kt @@ -37,10 +37,12 @@ import android.telephony.TelephonyManager.NETWORK_TYPE_UNKNOWN import androidx.test.filters.SmallTest import com.android.systemui.SysuiTestCase import com.android.systemui.statusbar.pipeline.mobile.data.model.DataConnectionState -import com.android.systemui.statusbar.pipeline.mobile.data.model.DefaultNetworkType -import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileSubscriptionModel -import com.android.systemui.statusbar.pipeline.mobile.data.model.OverrideNetworkType +import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileConnectionModel +import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType.DefaultNetworkType +import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType.OverrideNetworkType +import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType.UnknownNetworkType import com.android.systemui.statusbar.pipeline.mobile.data.repository.FakeMobileConnectionsRepository +import com.android.systemui.statusbar.pipeline.mobile.util.FakeMobileMappingsProxy import com.android.systemui.statusbar.pipeline.shared.ConnectivityPipelineLogger import com.android.systemui.util.mockito.any import com.android.systemui.util.mockito.argumentCaptor @@ -72,8 +74,9 @@ class MobileConnectionRepositoryTest : SysuiTestCase() { @Mock private lateinit var logger: ConnectivityPipelineLogger private val scope = CoroutineScope(IMMEDIATE) + private val mobileMappings = FakeMobileMappingsProxy() private val globalSettings = FakeSettings() - private val connectionsRepo = FakeMobileConnectionsRepository() + private val connectionsRepo = FakeMobileConnectionsRepository(mobileMappings) @Before fun setUp() { @@ -89,6 +92,7 @@ class MobileConnectionRepositoryTest : SysuiTestCase() { globalSettings, connectionsRepo.defaultDataSubId, connectionsRepo.globalMobileDataSettingChangedEvent, + mobileMappings, IMMEDIATE, logger, scope, @@ -103,10 +107,10 @@ class MobileConnectionRepositoryTest : SysuiTestCase() { @Test fun testFlowForSubId_default() = runBlocking(IMMEDIATE) { - var latest: MobileSubscriptionModel? = null - val job = underTest.subscriptionModelFlow.onEach { latest = it }.launchIn(this) + var latest: MobileConnectionModel? = null + val job = underTest.connectionInfo.onEach { latest = it }.launchIn(this) - assertThat(latest).isEqualTo(MobileSubscriptionModel()) + assertThat(latest).isEqualTo(MobileConnectionModel()) job.cancel() } @@ -114,8 +118,8 @@ class MobileConnectionRepositoryTest : SysuiTestCase() { @Test fun testFlowForSubId_emergencyOnly() = runBlocking(IMMEDIATE) { - var latest: MobileSubscriptionModel? = null - val job = underTest.subscriptionModelFlow.onEach { latest = it }.launchIn(this) + var latest: MobileConnectionModel? = null + val job = underTest.connectionInfo.onEach { latest = it }.launchIn(this) val serviceState = ServiceState() serviceState.isEmergencyOnly = true @@ -130,8 +134,8 @@ class MobileConnectionRepositoryTest : SysuiTestCase() { @Test fun testFlowForSubId_emergencyOnly_toggles() = runBlocking(IMMEDIATE) { - var latest: MobileSubscriptionModel? = null - val job = underTest.subscriptionModelFlow.onEach { latest = it }.launchIn(this) + var latest: MobileConnectionModel? = null + val job = underTest.connectionInfo.onEach { latest = it }.launchIn(this) val callback = getTelephonyCallbackForType<ServiceStateListener>() val serviceState = ServiceState() @@ -148,8 +152,8 @@ class MobileConnectionRepositoryTest : SysuiTestCase() { @Test fun testFlowForSubId_signalStrengths_levelsUpdate() = runBlocking(IMMEDIATE) { - var latest: MobileSubscriptionModel? = null - val job = underTest.subscriptionModelFlow.onEach { latest = it }.launchIn(this) + var latest: MobileConnectionModel? = null + val job = underTest.connectionInfo.onEach { latest = it }.launchIn(this) val callback = getTelephonyCallbackForType<TelephonyCallback.SignalStrengthsListener>() val strength = signalStrength(gsmLevel = 1, cdmaLevel = 2, isGsm = true) @@ -165,8 +169,8 @@ class MobileConnectionRepositoryTest : SysuiTestCase() { @Test fun testFlowForSubId_dataConnectionState_connected() = runBlocking(IMMEDIATE) { - var latest: MobileSubscriptionModel? = null - val job = underTest.subscriptionModelFlow.onEach { latest = it }.launchIn(this) + var latest: MobileConnectionModel? = null + val job = underTest.connectionInfo.onEach { latest = it }.launchIn(this) val callback = getTelephonyCallbackForType<TelephonyCallback.DataConnectionStateListener>() @@ -180,8 +184,8 @@ class MobileConnectionRepositoryTest : SysuiTestCase() { @Test fun testFlowForSubId_dataConnectionState_connecting() = runBlocking(IMMEDIATE) { - var latest: MobileSubscriptionModel? = null - val job = underTest.subscriptionModelFlow.onEach { latest = it }.launchIn(this) + var latest: MobileConnectionModel? = null + val job = underTest.connectionInfo.onEach { latest = it }.launchIn(this) val callback = getTelephonyCallbackForType<TelephonyCallback.DataConnectionStateListener>() @@ -195,8 +199,8 @@ class MobileConnectionRepositoryTest : SysuiTestCase() { @Test fun testFlowForSubId_dataConnectionState_disconnected() = runBlocking(IMMEDIATE) { - var latest: MobileSubscriptionModel? = null - val job = underTest.subscriptionModelFlow.onEach { latest = it }.launchIn(this) + var latest: MobileConnectionModel? = null + val job = underTest.connectionInfo.onEach { latest = it }.launchIn(this) val callback = getTelephonyCallbackForType<TelephonyCallback.DataConnectionStateListener>() @@ -210,8 +214,8 @@ class MobileConnectionRepositoryTest : SysuiTestCase() { @Test fun testFlowForSubId_dataConnectionState_disconnecting() = runBlocking(IMMEDIATE) { - var latest: MobileSubscriptionModel? = null - val job = underTest.subscriptionModelFlow.onEach { latest = it }.launchIn(this) + var latest: MobileConnectionModel? = null + val job = underTest.connectionInfo.onEach { latest = it }.launchIn(this) val callback = getTelephonyCallbackForType<TelephonyCallback.DataConnectionStateListener>() @@ -225,8 +229,8 @@ class MobileConnectionRepositoryTest : SysuiTestCase() { @Test fun testFlowForSubId_dataConnectionState_unknown() = runBlocking(IMMEDIATE) { - var latest: MobileSubscriptionModel? = null - val job = underTest.subscriptionModelFlow.onEach { latest = it }.launchIn(this) + var latest: MobileConnectionModel? = null + val job = underTest.connectionInfo.onEach { latest = it }.launchIn(this) val callback = getTelephonyCallbackForType<TelephonyCallback.DataConnectionStateListener>() @@ -240,8 +244,8 @@ class MobileConnectionRepositoryTest : SysuiTestCase() { @Test fun testFlowForSubId_dataActivity() = runBlocking(IMMEDIATE) { - var latest: MobileSubscriptionModel? = null - val job = underTest.subscriptionModelFlow.onEach { latest = it }.launchIn(this) + var latest: MobileConnectionModel? = null + val job = underTest.connectionInfo.onEach { latest = it }.launchIn(this) val callback = getTelephonyCallbackForType<TelephonyCallback.DataActivityListener>() callback.onDataActivity(3) @@ -254,8 +258,8 @@ class MobileConnectionRepositoryTest : SysuiTestCase() { @Test fun testFlowForSubId_carrierNetworkChange() = runBlocking(IMMEDIATE) { - var latest: MobileSubscriptionModel? = null - val job = underTest.subscriptionModelFlow.onEach { latest = it }.launchIn(this) + var latest: MobileConnectionModel? = null + val job = underTest.connectionInfo.onEach { latest = it }.launchIn(this) val callback = getTelephonyCallbackForType<TelephonyCallback.CarrierNetworkListener>() callback.onCarrierNetworkChange(true) @@ -268,11 +272,11 @@ class MobileConnectionRepositoryTest : SysuiTestCase() { @Test fun subscriptionFlow_networkType_default() = runBlocking(IMMEDIATE) { - var latest: MobileSubscriptionModel? = null - val job = underTest.subscriptionModelFlow.onEach { latest = it }.launchIn(this) + var latest: MobileConnectionModel? = null + val job = underTest.connectionInfo.onEach { latest = it }.launchIn(this) val type = NETWORK_TYPE_UNKNOWN - val expected = DefaultNetworkType(type) + val expected = UnknownNetworkType assertThat(latest?.resolvedNetworkType).isEqualTo(expected) @@ -282,12 +286,12 @@ class MobileConnectionRepositoryTest : SysuiTestCase() { @Test fun subscriptionFlow_networkType_updatesUsingDefault() = runBlocking(IMMEDIATE) { - var latest: MobileSubscriptionModel? = null - val job = underTest.subscriptionModelFlow.onEach { latest = it }.launchIn(this) + var latest: MobileConnectionModel? = null + val job = underTest.connectionInfo.onEach { latest = it }.launchIn(this) val callback = getTelephonyCallbackForType<TelephonyCallback.DisplayInfoListener>() val type = NETWORK_TYPE_LTE - val expected = DefaultNetworkType(type) + val expected = DefaultNetworkType(type, mobileMappings.toIconKey(type)) val ti = mock<TelephonyDisplayInfo>().also { whenever(it.networkType).thenReturn(type) } callback.onDisplayInfoChanged(ti) @@ -299,14 +303,15 @@ class MobileConnectionRepositoryTest : SysuiTestCase() { @Test fun subscriptionFlow_networkType_updatesUsingOverride() = runBlocking(IMMEDIATE) { - var latest: MobileSubscriptionModel? = null - val job = underTest.subscriptionModelFlow.onEach { latest = it }.launchIn(this) + var latest: MobileConnectionModel? = null + val job = underTest.connectionInfo.onEach { latest = it }.launchIn(this) val callback = getTelephonyCallbackForType<TelephonyCallback.DisplayInfoListener>() val type = OVERRIDE_NETWORK_TYPE_LTE_CA - val expected = OverrideNetworkType(type) + val expected = OverrideNetworkType(type, mobileMappings.toIconKeyOverride(type)) val ti = mock<TelephonyDisplayInfo>().also { + whenever(it.networkType).thenReturn(type) whenever(it.overrideNetworkType).thenReturn(type) } callback.onDisplayInfoChanged(ti) diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryTest.kt index 359ea18fcb84..4b82b398360d 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/data/repository/prod/MobileConnectionsRepositoryTest.kt @@ -32,6 +32,8 @@ import androidx.test.filters.SmallTest import com.android.internal.telephony.PhoneConstants import com.android.systemui.SysuiTestCase import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileConnectivityModel +import com.android.systemui.statusbar.pipeline.mobile.data.model.SubscriptionModel +import com.android.systemui.statusbar.pipeline.mobile.util.FakeMobileMappingsProxy import com.android.systemui.statusbar.pipeline.shared.ConnectivityPipelineLogger import com.android.systemui.util.mockito.any import com.android.systemui.util.mockito.argumentCaptor @@ -50,6 +52,7 @@ import org.junit.After import org.junit.Assert.assertThrows import org.junit.Before import org.junit.Test +import org.mockito.ArgumentMatchers.anyInt import org.mockito.Mock import org.mockito.Mockito.verify import org.mockito.MockitoAnnotations @@ -65,6 +68,8 @@ class MobileConnectionsRepositoryTest : SysuiTestCase() { @Mock private lateinit var telephonyManager: TelephonyManager @Mock private lateinit var logger: ConnectivityPipelineLogger + private val mobileMappings = FakeMobileMappingsProxy() + private val scope = CoroutineScope(IMMEDIATE) private val globalSettings = FakeSettings() @@ -72,18 +77,37 @@ class MobileConnectionsRepositoryTest : SysuiTestCase() { fun setUp() { MockitoAnnotations.initMocks(this) + // Set up so the individual connection repositories + whenever(telephonyManager.createForSubscriptionId(anyInt())).thenAnswer { invocation -> + telephonyManager.also { + whenever(telephonyManager.subscriptionId).thenReturn(invocation.getArgument(0)) + } + } + + val connectionFactory: MobileConnectionRepositoryImpl.Factory = + MobileConnectionRepositoryImpl.Factory( + context = context, + telephonyManager = telephonyManager, + bgDispatcher = IMMEDIATE, + globalSettings = globalSettings, + logger = logger, + mobileMappingsProxy = mobileMappings, + scope = scope, + ) + underTest = MobileConnectionsRepositoryImpl( connectivityManager, subscriptionManager, telephonyManager, logger, + mobileMappings, fakeBroadcastDispatcher, globalSettings, context, IMMEDIATE, scope, - mock(), + connectionFactory, ) } @@ -95,21 +119,21 @@ class MobileConnectionsRepositoryTest : SysuiTestCase() { @Test fun testSubscriptions_initiallyEmpty() = runBlocking(IMMEDIATE) { - assertThat(underTest.subscriptionsFlow.value).isEqualTo(listOf<SubscriptionInfo>()) + assertThat(underTest.subscriptions.value).isEqualTo(listOf<SubscriptionModel>()) } @Test fun testSubscriptions_listUpdates() = runBlocking(IMMEDIATE) { - var latest: List<SubscriptionInfo>? = null + var latest: List<SubscriptionModel>? = null - val job = underTest.subscriptionsFlow.onEach { latest = it }.launchIn(this) + val job = underTest.subscriptions.onEach { latest = it }.launchIn(this) whenever(subscriptionManager.completeActiveSubscriptionInfoList) .thenReturn(listOf(SUB_1, SUB_2)) getSubscriptionCallback().onSubscriptionsChanged() - assertThat(latest).isEqualTo(listOf(SUB_1, SUB_2)) + assertThat(latest).isEqualTo(listOf(MODEL_1, MODEL_2)) job.cancel() } @@ -117,9 +141,9 @@ class MobileConnectionsRepositoryTest : SysuiTestCase() { @Test fun testSubscriptions_removingSub_updatesList() = runBlocking(IMMEDIATE) { - var latest: List<SubscriptionInfo>? = null + var latest: List<SubscriptionModel>? = null - val job = underTest.subscriptionsFlow.onEach { latest = it }.launchIn(this) + val job = underTest.subscriptions.onEach { latest = it }.launchIn(this) // WHEN 2 networks show up whenever(subscriptionManager.completeActiveSubscriptionInfoList) @@ -132,7 +156,7 @@ class MobileConnectionsRepositoryTest : SysuiTestCase() { getSubscriptionCallback().onSubscriptionsChanged() // THEN the subscriptions list represents the newest change - assertThat(latest).isEqualTo(listOf(SUB_2)) + assertThat(latest).isEqualTo(listOf(MODEL_2)) job.cancel() } @@ -162,7 +186,7 @@ class MobileConnectionsRepositoryTest : SysuiTestCase() { @Test fun testConnectionRepository_validSubId_isCached() = runBlocking(IMMEDIATE) { - val job = underTest.subscriptionsFlow.launchIn(this) + val job = underTest.subscriptions.launchIn(this) whenever(subscriptionManager.completeActiveSubscriptionInfoList) .thenReturn(listOf(SUB_1)) @@ -179,7 +203,7 @@ class MobileConnectionsRepositoryTest : SysuiTestCase() { @Test fun testConnectionCache_clearsInvalidSubscriptions() = runBlocking(IMMEDIATE) { - val job = underTest.subscriptionsFlow.launchIn(this) + val job = underTest.subscriptions.launchIn(this) whenever(subscriptionManager.completeActiveSubscriptionInfoList) .thenReturn(listOf(SUB_1, SUB_2)) @@ -202,10 +226,36 @@ class MobileConnectionsRepositoryTest : SysuiTestCase() { job.cancel() } + /** Regression test for b/261706421 */ + @Test + fun testConnectionsCache_clearMultipleSubscriptionsAtOnce_doesNotThrow() = + runBlocking(IMMEDIATE) { + val job = underTest.subscriptions.launchIn(this) + + whenever(subscriptionManager.completeActiveSubscriptionInfoList) + .thenReturn(listOf(SUB_1, SUB_2)) + getSubscriptionCallback().onSubscriptionsChanged() + + // Get repos to trigger caching + val repo1 = underTest.getRepoForSubId(SUB_1_ID) + val repo2 = underTest.getRepoForSubId(SUB_2_ID) + + assertThat(underTest.getSubIdRepoCache()) + .containsExactly(SUB_1_ID, repo1, SUB_2_ID, repo2) + + // All subscriptions disappear + whenever(subscriptionManager.completeActiveSubscriptionInfoList).thenReturn(listOf()) + getSubscriptionCallback().onSubscriptionsChanged() + + assertThat(underTest.getSubIdRepoCache()).isEmpty() + + job.cancel() + } + @Test fun testConnectionRepository_invalidSubId_throws() = runBlocking(IMMEDIATE) { - val job = underTest.subscriptionsFlow.launchIn(this) + val job = underTest.subscriptions.launchIn(this) assertThrows(IllegalArgumentException::class.java) { underTest.getRepoForSubId(SUB_1_ID) @@ -371,10 +421,12 @@ class MobileConnectionsRepositoryTest : SysuiTestCase() { private const val SUB_1_ID = 1 private val SUB_1 = mock<SubscriptionInfo>().also { whenever(it.subscriptionId).thenReturn(SUB_1_ID) } + private val MODEL_1 = SubscriptionModel(subscriptionId = SUB_1_ID) private const val SUB_2_ID = 2 private val SUB_2 = mock<SubscriptionInfo>().also { whenever(it.subscriptionId).thenReturn(SUB_2_ID) } + private val MODEL_2 = SubscriptionModel(subscriptionId = SUB_2_ID) private const val NET_ID = 123 private val NETWORK = mock<Network>().apply { whenever(getNetId()).thenReturn(NET_ID) } diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconsInteractor.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconsInteractor.kt index 061c3b54650e..0d4044db71e0 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconsInteractor.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconsInteractor.kt @@ -16,14 +16,15 @@ package com.android.systemui.statusbar.pipeline.mobile.domain.interactor -import android.telephony.SubscriptionInfo import android.telephony.TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_LTE_ADVANCED_PRO import android.telephony.TelephonyManager.NETWORK_TYPE_GSM import android.telephony.TelephonyManager.NETWORK_TYPE_LTE import android.telephony.TelephonyManager.NETWORK_TYPE_UMTS import com.android.settingslib.SignalIcon.MobileIconGroup import com.android.settingslib.mobile.TelephonyIcons +import com.android.systemui.statusbar.pipeline.mobile.data.model.SubscriptionModel import com.android.systemui.statusbar.pipeline.mobile.util.MobileMappingsProxy +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow class FakeMobileIconsInteractor(mobileMappings: MobileMappingsProxy) : MobileIconsInteractor { @@ -47,8 +48,8 @@ class FakeMobileIconsInteractor(mobileMappings: MobileMappingsProxy) : MobileIco override val isDefaultConnectionFailed = MutableStateFlow(false) - private val _filteredSubscriptions = MutableStateFlow<List<SubscriptionInfo>>(listOf()) - override val filteredSubscriptions = _filteredSubscriptions + private val _filteredSubscriptions = MutableStateFlow<List<SubscriptionModel>>(listOf()) + override val filteredSubscriptions: Flow<List<SubscriptionModel>> = _filteredSubscriptions private val _activeDataConnectionHasDataEnabled = MutableStateFlow(false) override val activeDataConnectionHasDataEnabled = _activeDataConnectionHasDataEnabled diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorTest.kt index 7fc1c0f6272c..fd41b5bebd39 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorTest.kt @@ -24,9 +24,9 @@ import com.android.settingslib.SignalIcon.MobileIconGroup import com.android.settingslib.mobile.TelephonyIcons import com.android.systemui.SysuiTestCase import com.android.systemui.statusbar.pipeline.mobile.data.model.DataConnectionState -import com.android.systemui.statusbar.pipeline.mobile.data.model.DefaultNetworkType -import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileSubscriptionModel -import com.android.systemui.statusbar.pipeline.mobile.data.model.OverrideNetworkType +import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileConnectionModel +import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType.DefaultNetworkType +import com.android.systemui.statusbar.pipeline.mobile.data.model.ResolvedNetworkType.OverrideNetworkType import com.android.systemui.statusbar.pipeline.mobile.data.repository.FakeMobileConnectionRepository import com.android.systemui.statusbar.pipeline.mobile.domain.interactor.FakeMobileIconsInteractor.Companion.FIVE_G_OVERRIDE import com.android.systemui.statusbar.pipeline.mobile.domain.interactor.FakeMobileIconsInteractor.Companion.FOUR_G @@ -49,7 +49,7 @@ class MobileIconInteractorTest : SysuiTestCase() { private lateinit var underTest: MobileIconInteractor private val mobileMappingsProxy = FakeMobileMappingsProxy() private val mobileIconsInteractor = FakeMobileIconsInteractor(mobileMappingsProxy) - private val connectionRepository = FakeMobileConnectionRepository() + private val connectionRepository = FakeMobileConnectionRepository(SUB_1_ID) private val scope = CoroutineScope(IMMEDIATE) @@ -62,7 +62,6 @@ class MobileIconInteractorTest : SysuiTestCase() { mobileIconsInteractor.defaultMobileIconMapping, mobileIconsInteractor.defaultMobileIconGroup, mobileIconsInteractor.isDefaultConnectionFailed, - mobileMappingsProxy, connectionRepository, ) } @@ -70,8 +69,8 @@ class MobileIconInteractorTest : SysuiTestCase() { @Test fun gsm_level_default_unknown() = runBlocking(IMMEDIATE) { - connectionRepository.setMobileSubscriptionModel( - MobileSubscriptionModel(isGsm = true), + connectionRepository.setConnectionInfo( + MobileConnectionModel(isGsm = true), ) var latest: Int? = null @@ -85,8 +84,8 @@ class MobileIconInteractorTest : SysuiTestCase() { @Test fun gsm_usesGsmLevel() = runBlocking(IMMEDIATE) { - connectionRepository.setMobileSubscriptionModel( - MobileSubscriptionModel( + connectionRepository.setConnectionInfo( + MobileConnectionModel( isGsm = true, primaryLevel = GSM_LEVEL, cdmaLevel = CDMA_LEVEL @@ -104,8 +103,8 @@ class MobileIconInteractorTest : SysuiTestCase() { @Test fun cdma_level_default_unknown() = runBlocking(IMMEDIATE) { - connectionRepository.setMobileSubscriptionModel( - MobileSubscriptionModel(isGsm = false), + connectionRepository.setConnectionInfo( + MobileConnectionModel(isGsm = false), ) var latest: Int? = null @@ -118,8 +117,8 @@ class MobileIconInteractorTest : SysuiTestCase() { @Test fun cdma_usesCdmaLevel() = runBlocking(IMMEDIATE) { - connectionRepository.setMobileSubscriptionModel( - MobileSubscriptionModel( + connectionRepository.setConnectionInfo( + MobileConnectionModel( isGsm = false, primaryLevel = GSM_LEVEL, cdmaLevel = CDMA_LEVEL @@ -137,8 +136,11 @@ class MobileIconInteractorTest : SysuiTestCase() { @Test fun iconGroup_three_g() = runBlocking(IMMEDIATE) { - connectionRepository.setMobileSubscriptionModel( - MobileSubscriptionModel(resolvedNetworkType = DefaultNetworkType(THREE_G)), + connectionRepository.setConnectionInfo( + MobileConnectionModel( + resolvedNetworkType = + DefaultNetworkType(THREE_G, mobileMappingsProxy.toIconKey(THREE_G)) + ), ) var latest: MobileIconGroup? = null @@ -152,16 +154,23 @@ class MobileIconInteractorTest : SysuiTestCase() { @Test fun iconGroup_updates_on_change() = runBlocking(IMMEDIATE) { - connectionRepository.setMobileSubscriptionModel( - MobileSubscriptionModel(resolvedNetworkType = DefaultNetworkType(THREE_G)), + connectionRepository.setConnectionInfo( + MobileConnectionModel( + resolvedNetworkType = + DefaultNetworkType(THREE_G, mobileMappingsProxy.toIconKey(THREE_G)) + ), ) var latest: MobileIconGroup? = null val job = underTest.networkTypeIconGroup.onEach { latest = it }.launchIn(this) - connectionRepository.setMobileSubscriptionModel( - MobileSubscriptionModel( - resolvedNetworkType = DefaultNetworkType(FOUR_G), + connectionRepository.setConnectionInfo( + MobileConnectionModel( + resolvedNetworkType = + DefaultNetworkType( + FOUR_G, + mobileMappingsProxy.toIconKey(FOUR_G), + ), ), ) yield() @@ -174,8 +183,14 @@ class MobileIconInteractorTest : SysuiTestCase() { @Test fun iconGroup_5g_override_type() = runBlocking(IMMEDIATE) { - connectionRepository.setMobileSubscriptionModel( - MobileSubscriptionModel(resolvedNetworkType = OverrideNetworkType(FIVE_G_OVERRIDE)), + connectionRepository.setConnectionInfo( + MobileConnectionModel( + resolvedNetworkType = + OverrideNetworkType( + FIVE_G_OVERRIDE, + mobileMappingsProxy.toIconKeyOverride(FIVE_G_OVERRIDE) + ) + ), ) var latest: MobileIconGroup? = null @@ -189,9 +204,13 @@ class MobileIconInteractorTest : SysuiTestCase() { @Test fun iconGroup_default_if_no_lookup() = runBlocking(IMMEDIATE) { - connectionRepository.setMobileSubscriptionModel( - MobileSubscriptionModel( - resolvedNetworkType = DefaultNetworkType(NETWORK_TYPE_UNKNOWN), + connectionRepository.setConnectionInfo( + MobileConnectionModel( + resolvedNetworkType = + DefaultNetworkType( + NETWORK_TYPE_UNKNOWN, + mobileMappingsProxy.toIconKey(NETWORK_TYPE_UNKNOWN) + ), ), ) @@ -238,8 +257,8 @@ class MobileIconInteractorTest : SysuiTestCase() { var latest: Boolean? = null val job = underTest.isDataConnected.onEach { latest = it }.launchIn(this) - connectionRepository.setMobileSubscriptionModel( - MobileSubscriptionModel(dataConnectionState = DataConnectionState.Connected) + connectionRepository.setConnectionInfo( + MobileConnectionModel(dataConnectionState = DataConnectionState.Connected) ) yield() @@ -254,8 +273,8 @@ class MobileIconInteractorTest : SysuiTestCase() { var latest: Boolean? = null val job = underTest.isDataConnected.onEach { latest = it }.launchIn(this) - connectionRepository.setMobileSubscriptionModel( - MobileSubscriptionModel(dataConnectionState = DataConnectionState.Disconnected) + connectionRepository.setConnectionInfo( + MobileConnectionModel(dataConnectionState = DataConnectionState.Disconnected) ) assertThat(latest).isFalse() diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractorTest.kt index b56dcd752557..58e57e298e51 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractorTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractorTest.kt @@ -16,17 +16,16 @@ package com.android.systemui.statusbar.pipeline.mobile.domain.interactor -import android.telephony.SubscriptionInfo import android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID import androidx.test.filters.SmallTest import com.android.systemui.SysuiTestCase import com.android.systemui.statusbar.pipeline.mobile.data.model.MobileConnectivityModel +import com.android.systemui.statusbar.pipeline.mobile.data.model.SubscriptionModel import com.android.systemui.statusbar.pipeline.mobile.data.repository.FakeMobileConnectionRepository import com.android.systemui.statusbar.pipeline.mobile.data.repository.FakeMobileConnectionsRepository import com.android.systemui.statusbar.pipeline.mobile.data.repository.FakeUserSetupRepository import com.android.systemui.statusbar.pipeline.mobile.util.FakeMobileMappingsProxy import com.android.systemui.util.CarrierConfigTracker -import com.android.systemui.util.mockito.mock import com.android.systemui.util.mockito.whenever import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.CoroutineScope @@ -45,8 +44,8 @@ import org.mockito.MockitoAnnotations class MobileIconsInteractorTest : SysuiTestCase() { private lateinit var underTest: MobileIconsInteractor private val userSetupRepository = FakeUserSetupRepository() - private val connectionsRepository = FakeMobileConnectionsRepository() private val mobileMappingsProxy = FakeMobileMappingsProxy() + private val connectionsRepository = FakeMobileConnectionsRepository(mobileMappingsProxy) private val scope = CoroutineScope(IMMEDIATE) @Mock private lateinit var carrierConfigTracker: CarrierConfigTracker @@ -69,7 +68,6 @@ class MobileIconsInteractorTest : SysuiTestCase() { MobileIconsInteractorImpl( connectionsRepository, carrierConfigTracker, - mobileMappingsProxy, userSetupRepository, scope ) @@ -80,10 +78,10 @@ class MobileIconsInteractorTest : SysuiTestCase() { @Test fun filteredSubscriptions_default() = runBlocking(IMMEDIATE) { - var latest: List<SubscriptionInfo>? = null + var latest: List<SubscriptionModel>? = null val job = underTest.filteredSubscriptions.onEach { latest = it }.launchIn(this) - assertThat(latest).isEqualTo(listOf<SubscriptionInfo>()) + assertThat(latest).isEqualTo(listOf<SubscriptionModel>()) job.cancel() } @@ -93,7 +91,7 @@ class MobileIconsInteractorTest : SysuiTestCase() { runBlocking(IMMEDIATE) { connectionsRepository.setSubscriptions(listOf(SUB_1, SUB_2)) - var latest: List<SubscriptionInfo>? = null + var latest: List<SubscriptionModel>? = null val job = underTest.filteredSubscriptions.onEach { latest = it }.launchIn(this) assertThat(latest).isEqualTo(listOf(SUB_1, SUB_2)) @@ -109,7 +107,7 @@ class MobileIconsInteractorTest : SysuiTestCase() { whenever(carrierConfigTracker.alwaysShowPrimarySignalBarInOpportunisticNetworkDefault) .thenReturn(false) - var latest: List<SubscriptionInfo>? = null + var latest: List<SubscriptionModel>? = null val job = underTest.filteredSubscriptions.onEach { latest = it }.launchIn(this) // Filtered subscriptions should show the active one when the config is false @@ -126,7 +124,7 @@ class MobileIconsInteractorTest : SysuiTestCase() { whenever(carrierConfigTracker.alwaysShowPrimarySignalBarInOpportunisticNetworkDefault) .thenReturn(false) - var latest: List<SubscriptionInfo>? = null + var latest: List<SubscriptionModel>? = null val job = underTest.filteredSubscriptions.onEach { latest = it }.launchIn(this) // Filtered subscriptions should show the active one when the config is false @@ -143,7 +141,7 @@ class MobileIconsInteractorTest : SysuiTestCase() { whenever(carrierConfigTracker.alwaysShowPrimarySignalBarInOpportunisticNetworkDefault) .thenReturn(true) - var latest: List<SubscriptionInfo>? = null + var latest: List<SubscriptionModel>? = null val job = underTest.filteredSubscriptions.onEach { latest = it }.launchIn(this) // Filtered subscriptions should show the primary (non-opportunistic) if the config is @@ -161,7 +159,7 @@ class MobileIconsInteractorTest : SysuiTestCase() { whenever(carrierConfigTracker.alwaysShowPrimarySignalBarInOpportunisticNetworkDefault) .thenReturn(true) - var latest: List<SubscriptionInfo>? = null + var latest: List<SubscriptionModel>? = null val job = underTest.filteredSubscriptions.onEach { latest = it }.launchIn(this) // Filtered subscriptions should show the primary (non-opportunistic) if the config is @@ -261,29 +259,19 @@ class MobileIconsInteractorTest : SysuiTestCase() { private val IMMEDIATE = Dispatchers.Main.immediate private const val SUB_1_ID = 1 - private val SUB_1 = - mock<SubscriptionInfo>().also { whenever(it.subscriptionId).thenReturn(SUB_1_ID) } - private val CONNECTION_1 = FakeMobileConnectionRepository() + private val SUB_1 = SubscriptionModel(subscriptionId = SUB_1_ID) + private val CONNECTION_1 = FakeMobileConnectionRepository(SUB_1_ID) private const val SUB_2_ID = 2 - private val SUB_2 = - mock<SubscriptionInfo>().also { whenever(it.subscriptionId).thenReturn(SUB_2_ID) } - private val CONNECTION_2 = FakeMobileConnectionRepository() + private val SUB_2 = SubscriptionModel(subscriptionId = SUB_2_ID) + private val CONNECTION_2 = FakeMobileConnectionRepository(SUB_2_ID) private const val SUB_3_ID = 3 - private val SUB_3_OPP = - mock<SubscriptionInfo>().also { - whenever(it.subscriptionId).thenReturn(SUB_3_ID) - whenever(it.isOpportunistic).thenReturn(true) - } - private val CONNECTION_3 = FakeMobileConnectionRepository() + private val SUB_3_OPP = SubscriptionModel(subscriptionId = SUB_3_ID, isOpportunistic = true) + private val CONNECTION_3 = FakeMobileConnectionRepository(SUB_3_ID) private const val SUB_4_ID = 4 - private val SUB_4_OPP = - mock<SubscriptionInfo>().also { - whenever(it.subscriptionId).thenReturn(SUB_4_ID) - whenever(it.isOpportunistic).thenReturn(true) - } - private val CONNECTION_4 = FakeMobileConnectionRepository() + private val SUB_4_OPP = SubscriptionModel(subscriptionId = SUB_4_ID, isOpportunistic = true) + private val CONNECTION_4 = FakeMobileConnectionRepository(SUB_4_ID) } } diff --git a/packages/SystemUI/tests/src/com/android/systemui/stylus/StylusManagerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/stylus/StylusManagerTest.kt new file mode 100644 index 000000000000..58b55602a39c --- /dev/null +++ b/packages/SystemUI/tests/src/com/android/systemui/stylus/StylusManagerTest.kt @@ -0,0 +1,338 @@ +/* + * 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.stylus + +import android.bluetooth.BluetoothAdapter +import android.bluetooth.BluetoothDevice +import android.hardware.input.InputManager +import android.os.Handler +import android.testing.AndroidTestingRunner +import android.view.InputDevice +import androidx.test.filters.SmallTest +import com.android.systemui.SysuiTestCase +import com.android.systemui.util.mockito.any +import com.android.systemui.util.mockito.whenever +import java.util.concurrent.Executor +import org.junit.Before +import org.junit.Ignore +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mock +import org.mockito.Mockito.inOrder +import org.mockito.Mockito.never +import org.mockito.Mockito.times +import org.mockito.Mockito.verify +import org.mockito.Mockito.verifyNoMoreInteractions +import org.mockito.MockitoAnnotations + +@RunWith(AndroidTestingRunner::class) +@SmallTest +@Ignore("b/257936830 until bt APIs") +class StylusManagerTest : SysuiTestCase() { + @Mock lateinit var inputManager: InputManager + + @Mock lateinit var stylusDevice: InputDevice + + @Mock lateinit var btStylusDevice: InputDevice + + @Mock lateinit var otherDevice: InputDevice + + @Mock lateinit var bluetoothAdapter: BluetoothAdapter + + @Mock lateinit var bluetoothDevice: BluetoothDevice + + @Mock lateinit var handler: Handler + + @Mock lateinit var stylusCallback: StylusManager.StylusCallback + + @Mock lateinit var otherStylusCallback: StylusManager.StylusCallback + + @Mock lateinit var stylusBatteryCallback: StylusManager.StylusBatteryCallback + + @Mock lateinit var otherStylusBatteryCallback: StylusManager.StylusBatteryCallback + + private lateinit var stylusManager: StylusManager + + @Before + fun setUp() { + MockitoAnnotations.initMocks(this) + + whenever(handler.post(any())).thenAnswer { + (it.arguments[0] as Runnable).run() + true + } + + stylusManager = StylusManager(inputManager, bluetoothAdapter, handler, EXECUTOR) + + stylusManager.registerCallback(stylusCallback) + + stylusManager.registerBatteryCallback(stylusBatteryCallback) + + whenever(otherDevice.supportsSource(InputDevice.SOURCE_STYLUS)).thenReturn(false) + whenever(stylusDevice.supportsSource(InputDevice.SOURCE_STYLUS)).thenReturn(true) + whenever(btStylusDevice.supportsSource(InputDevice.SOURCE_STYLUS)).thenReturn(true) + + // whenever(stylusDevice.bluetoothAddress).thenReturn(null) + // whenever(btStylusDevice.bluetoothAddress).thenReturn(STYLUS_BT_ADDRESS) + + whenever(inputManager.getInputDevice(OTHER_DEVICE_ID)).thenReturn(otherDevice) + whenever(inputManager.getInputDevice(STYLUS_DEVICE_ID)).thenReturn(stylusDevice) + whenever(inputManager.getInputDevice(BT_STYLUS_DEVICE_ID)).thenReturn(btStylusDevice) + whenever(inputManager.inputDeviceIds).thenReturn(intArrayOf(STYLUS_DEVICE_ID)) + + whenever(bluetoothAdapter.getRemoteDevice(STYLUS_BT_ADDRESS)).thenReturn(bluetoothDevice) + whenever(bluetoothDevice.address).thenReturn(STYLUS_BT_ADDRESS) + } + + @Test + fun startListener_registersInputDeviceListener() { + stylusManager.startListener() + + verify(inputManager, times(1)).registerInputDeviceListener(any(), any()) + } + + @Test + fun onInputDeviceAdded_multipleRegisteredCallbacks_callsAll() { + stylusManager.registerCallback(otherStylusCallback) + + stylusManager.onInputDeviceAdded(STYLUS_DEVICE_ID) + + verify(stylusCallback, times(1)).onStylusAdded(STYLUS_DEVICE_ID) + verifyNoMoreInteractions(stylusCallback) + verify(otherStylusCallback, times(1)).onStylusAdded(STYLUS_DEVICE_ID) + verifyNoMoreInteractions(otherStylusCallback) + } + + @Test + fun onInputDeviceAdded_stylus_callsCallbacksOnStylusAdded() { + stylusManager.onInputDeviceAdded(STYLUS_DEVICE_ID) + + verify(stylusCallback, times(1)).onStylusAdded(STYLUS_DEVICE_ID) + verifyNoMoreInteractions(stylusCallback) + } + + @Test + fun onInputDeviceAdded_btStylus_callsCallbacksWithAddress() { + stylusManager.onInputDeviceAdded(BT_STYLUS_DEVICE_ID) + + inOrder(stylusCallback).let { + it.verify(stylusCallback, times(1)).onStylusAdded(BT_STYLUS_DEVICE_ID) + it.verify(stylusCallback, times(1)) + .onStylusBluetoothConnected(BT_STYLUS_DEVICE_ID, STYLUS_BT_ADDRESS) + } + } + + @Test + fun onInputDeviceAdded_notStylus_doesNotCallCallbacks() { + stylusManager.onInputDeviceAdded(OTHER_DEVICE_ID) + + verifyNoMoreInteractions(stylusCallback) + } + + @Test + fun onInputDeviceChanged_multipleRegisteredCallbacks_callsAll() { + stylusManager.onInputDeviceAdded(STYLUS_DEVICE_ID) + // whenever(stylusDevice.bluetoothAddress).thenReturn(STYLUS_BT_ADDRESS) + stylusManager.registerCallback(otherStylusCallback) + + stylusManager.onInputDeviceChanged(STYLUS_DEVICE_ID) + + verify(stylusCallback, times(1)) + .onStylusBluetoothConnected(STYLUS_DEVICE_ID, STYLUS_BT_ADDRESS) + verify(otherStylusCallback, times(1)) + .onStylusBluetoothConnected(STYLUS_DEVICE_ID, STYLUS_BT_ADDRESS) + } + + @Test + fun onInputDeviceChanged_stylusNewBtConnection_callsCallbacks() { + stylusManager.onInputDeviceAdded(STYLUS_DEVICE_ID) + // whenever(stylusDevice.bluetoothAddress).thenReturn(STYLUS_BT_ADDRESS) + + stylusManager.onInputDeviceChanged(STYLUS_DEVICE_ID) + + verify(stylusCallback, times(1)) + .onStylusBluetoothConnected(STYLUS_DEVICE_ID, STYLUS_BT_ADDRESS) + } + + @Test + fun onInputDeviceChanged_stylusLostBtConnection_callsCallbacks() { + stylusManager.onInputDeviceAdded(BT_STYLUS_DEVICE_ID) + // whenever(btStylusDevice.bluetoothAddress).thenReturn(null) + + stylusManager.onInputDeviceChanged(BT_STYLUS_DEVICE_ID) + + verify(stylusCallback, times(1)) + .onStylusBluetoothDisconnected(BT_STYLUS_DEVICE_ID, STYLUS_BT_ADDRESS) + } + + @Test + fun onInputDeviceChanged_btConnection_stylusAlreadyBtConnected_onlyCallsListenersOnce() { + stylusManager.onInputDeviceAdded(BT_STYLUS_DEVICE_ID) + + stylusManager.onInputDeviceChanged(BT_STYLUS_DEVICE_ID) + + verify(stylusCallback, times(1)) + .onStylusBluetoothConnected(BT_STYLUS_DEVICE_ID, STYLUS_BT_ADDRESS) + } + + @Test + fun onInputDeviceChanged_noBtConnection_stylusNeverBtConnected_doesNotCallCallbacks() { + stylusManager.onInputDeviceAdded(STYLUS_DEVICE_ID) + + stylusManager.onInputDeviceChanged(STYLUS_DEVICE_ID) + + verify(stylusCallback, never()).onStylusBluetoothDisconnected(any(), any()) + } + + @Test + fun onInputDeviceRemoved_multipleRegisteredCallbacks_callsAll() { + stylusManager.onInputDeviceAdded(STYLUS_DEVICE_ID) + stylusManager.registerCallback(otherStylusCallback) + + stylusManager.onInputDeviceAdded(STYLUS_DEVICE_ID) + + verify(stylusCallback, times(1)).onStylusRemoved(STYLUS_DEVICE_ID) + verify(otherStylusCallback, times(1)).onStylusRemoved(STYLUS_DEVICE_ID) + } + + @Test + fun onInputDeviceRemoved_stylus_callsCallbacks() { + stylusManager.onInputDeviceAdded(STYLUS_DEVICE_ID) + + stylusManager.onInputDeviceRemoved(STYLUS_DEVICE_ID) + + verify(stylusCallback, times(1)).onStylusRemoved(STYLUS_DEVICE_ID) + verify(stylusCallback, never()).onStylusBluetoothDisconnected(any(), any()) + } + + @Test + fun onInputDeviceRemoved_btStylus_callsCallbacks() { + stylusManager.onInputDeviceAdded(BT_STYLUS_DEVICE_ID) + + stylusManager.onInputDeviceRemoved(BT_STYLUS_DEVICE_ID) + + inOrder(stylusCallback).let { + it.verify(stylusCallback, times(1)) + .onStylusBluetoothDisconnected(BT_STYLUS_DEVICE_ID, STYLUS_BT_ADDRESS) + it.verify(stylusCallback, times(1)).onStylusRemoved(BT_STYLUS_DEVICE_ID) + } + } + + @Test + fun onStylusBluetoothConnected_registersMetadataListener() { + stylusManager.onInputDeviceAdded(BT_STYLUS_DEVICE_ID) + + verify(bluetoothAdapter, times(1)).addOnMetadataChangedListener(any(), any(), any()) + } + + @Test + fun onStylusBluetoothConnected_noBluetoothDevice_doesNotRegisterMetadataListener() { + whenever(bluetoothAdapter.getRemoteDevice(STYLUS_BT_ADDRESS)).thenReturn(null) + + stylusManager.onInputDeviceAdded(BT_STYLUS_DEVICE_ID) + + verify(bluetoothAdapter, never()).addOnMetadataChangedListener(any(), any(), any()) + } + + @Test + fun onStylusBluetoothDisconnected_unregistersMetadataListener() { + stylusManager.onInputDeviceAdded(BT_STYLUS_DEVICE_ID) + + stylusManager.onInputDeviceRemoved(BT_STYLUS_DEVICE_ID) + + verify(bluetoothAdapter, times(1)).removeOnMetadataChangedListener(any(), any()) + } + + @Test + fun onMetadataChanged_multipleRegisteredBatteryCallbacks_executesAll() { + stylusManager.onInputDeviceAdded(BT_STYLUS_DEVICE_ID) + stylusManager.registerBatteryCallback(otherStylusBatteryCallback) + + stylusManager.onMetadataChanged( + bluetoothDevice, + BluetoothDevice.METADATA_MAIN_CHARGING, + "true".toByteArray() + ) + + verify(stylusBatteryCallback, times(1)) + .onStylusBluetoothChargingStateChanged(BT_STYLUS_DEVICE_ID, bluetoothDevice, true) + verify(otherStylusBatteryCallback, times(1)) + .onStylusBluetoothChargingStateChanged(BT_STYLUS_DEVICE_ID, bluetoothDevice, true) + } + + @Test + fun onMetadataChanged_chargingStateTrue_executesBatteryCallbacks() { + stylusManager.onInputDeviceAdded(BT_STYLUS_DEVICE_ID) + + stylusManager.onMetadataChanged( + bluetoothDevice, + BluetoothDevice.METADATA_MAIN_CHARGING, + "true".toByteArray() + ) + + verify(stylusBatteryCallback, times(1)) + .onStylusBluetoothChargingStateChanged(BT_STYLUS_DEVICE_ID, bluetoothDevice, true) + } + + @Test + fun onMetadataChanged_chargingStateFalse_executesBatteryCallbacks() { + stylusManager.onInputDeviceAdded(BT_STYLUS_DEVICE_ID) + + stylusManager.onMetadataChanged( + bluetoothDevice, + BluetoothDevice.METADATA_MAIN_CHARGING, + "false".toByteArray() + ) + + verify(stylusBatteryCallback, times(1)) + .onStylusBluetoothChargingStateChanged(BT_STYLUS_DEVICE_ID, bluetoothDevice, false) + } + + @Test + fun onMetadataChanged_chargingStateNoDevice_doesNotExecuteBatteryCallbacks() { + stylusManager.onMetadataChanged( + bluetoothDevice, + BluetoothDevice.METADATA_MAIN_CHARGING, + "true".toByteArray() + ) + + verifyNoMoreInteractions(stylusBatteryCallback) + } + + @Test + fun onMetadataChanged_notChargingState_doesNotExecuteBatteryCallbacks() { + stylusManager.onInputDeviceAdded(BT_STYLUS_DEVICE_ID) + + stylusManager.onMetadataChanged( + bluetoothDevice, + BluetoothDevice.METADATA_DEVICE_TYPE, + "true".toByteArray() + ) + + verify(stylusBatteryCallback, never()) + .onStylusBluetoothChargingStateChanged(any(), any(), any()) + } + + companion object { + private val EXECUTOR = Executor { r -> r.run() } + + private const val OTHER_DEVICE_ID = 0 + private const val STYLUS_DEVICE_ID = 1 + private const val BT_STYLUS_DEVICE_ID = 2 + + private const val STYLUS_BT_ADDRESS = "SOME:ADDRESS" + } +} diff --git a/packages/SystemUI/tests/src/com/android/systemui/temporarydisplay/chipbar/ChipbarCoordinatorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/temporarydisplay/chipbar/ChipbarCoordinatorTest.kt index 47c84ab48093..7014f93fba4a 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/temporarydisplay/chipbar/ChipbarCoordinatorTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/temporarydisplay/chipbar/ChipbarCoordinatorTest.kt @@ -35,6 +35,7 @@ import com.android.systemui.common.shared.model.ContentDescription import com.android.systemui.common.shared.model.ContentDescription.Companion.loadContentDescription import com.android.systemui.common.shared.model.Icon import com.android.systemui.common.shared.model.Text +import com.android.systemui.common.shared.model.TintedIcon import com.android.systemui.plugins.FalsingManager import com.android.systemui.statusbar.VibratorHelper import com.android.systemui.statusbar.policy.ConfigurationController @@ -109,6 +110,35 @@ class ChipbarCoordinatorTest : SysuiTestCase() { } @Test + fun displayView_contentDescription_iconHasDescription() { + underTest.displayView( + createChipbarInfo( + Icon.Resource(R.drawable.ic_cake, ContentDescription.Loaded("loadedCD")), + Text.Loaded("text"), + endItem = null, + ) + ) + + val contentDescView = getChipbarView().requireViewById<ViewGroup>(R.id.chipbar_inner) + assertThat(contentDescView.contentDescription.toString()).contains("loadedCD") + assertThat(contentDescView.contentDescription.toString()).contains("text") + } + + @Test + fun displayView_contentDescription_iconHasNoDescription() { + underTest.displayView( + createChipbarInfo( + Icon.Resource(R.drawable.ic_cake, contentDescription = null), + Text.Loaded("text"), + endItem = null, + ) + ) + + val contentDescView = getChipbarView().requireViewById<ViewGroup>(R.id.chipbar_inner) + assertThat(contentDescView.contentDescription.toString()).isEqualTo("text") + } + + @Test fun displayView_loadedIcon_correctlyRendered() { val drawable = context.getDrawable(R.drawable.ic_celebration)!! @@ -370,7 +400,7 @@ class ChipbarCoordinatorTest : SysuiTestCase() { vibrationEffect: VibrationEffect? = null, ): ChipbarInfo { return ChipbarInfo( - startIcon, + TintedIcon(startIcon, tintAttr = null), text, endItem, vibrationEffect, diff --git a/packages/SystemUI/tests/src/com/android/systemui/unfold/progress/PhysicsBasedUnfoldTransitionProgressProviderTest.kt b/packages/SystemUI/tests/src/com/android/systemui/unfold/progress/PhysicsBasedUnfoldTransitionProgressProviderTest.kt index 03fd624a8c1d..abbdab0d41f5 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/unfold/progress/PhysicsBasedUnfoldTransitionProgressProviderTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/unfold/progress/PhysicsBasedUnfoldTransitionProgressProviderTest.kt @@ -69,6 +69,22 @@ class PhysicsBasedUnfoldTransitionProgressProviderTest : SysuiTestCase() { } @Test + fun testUnfold_emitsFinishingEvent() { + runOnMainThreadWithInterval( + { foldStateProvider.sendFoldUpdate(FOLD_UPDATE_START_OPENING) }, + { foldStateProvider.sendHingeAngleUpdate(10f) }, + { foldStateProvider.sendFoldUpdate(FOLD_UPDATE_UNFOLDED_SCREEN_AVAILABLE) }, + { foldStateProvider.sendHingeAngleUpdate(90f) }, + { foldStateProvider.sendHingeAngleUpdate(180f) }, + { foldStateProvider.sendFoldUpdate(FOLD_UPDATE_FINISH_FULL_OPEN) }, + ) + + with(listener.ensureTransitionFinished()) { + assertHasSingleFinishingEvent() + } + } + + @Test fun testUnfold_screenAvailableOnlyAfterFullUnfold_emitsIncreasingTransitionEvents() { runOnMainThreadWithInterval( { foldStateProvider.sendFoldUpdate(FOLD_UPDATE_START_OPENING) }, @@ -157,6 +173,12 @@ class PhysicsBasedUnfoldTransitionProgressProviderTest : SysuiTestCase() { currentRecording!!.addProgress(progress) } + override fun onTransitionFinishing() { + assertWithMessage("Received transition finishing event when it's not started") + .that(currentRecording).isNotNull() + currentRecording!!.onFinishing() + } + override fun onTransitionFinished() { assertWithMessage("Received transition finish event when it's not started") .that(currentRecording).isNotNull() @@ -171,6 +193,7 @@ class PhysicsBasedUnfoldTransitionProgressProviderTest : SysuiTestCase() { class UnfoldTransitionRecording { private val progressHistory: MutableList<Float> = arrayListOf() + private var finishingInvocations: Int = 0 fun addProgress(progress: Float) { assertThat(progress).isAtMost(1.0f) @@ -179,6 +202,10 @@ class PhysicsBasedUnfoldTransitionProgressProviderTest : SysuiTestCase() { progressHistory += progress } + fun onFinishing() { + finishingInvocations++ + } + fun assertIncreasingProgress() { assertThat(progressHistory.size).isGreaterThan(MIN_ANIMATION_EVENTS) assertThat(progressHistory).isInOrder() @@ -206,6 +233,11 @@ class PhysicsBasedUnfoldTransitionProgressProviderTest : SysuiTestCase() { .isInOrder(Comparator.reverseOrder<Float>()) assertThat(progressHistory.last()).isEqualTo(0.0f) } + + fun assertHasSingleFinishingEvent() { + assertWithMessage("onTransitionFinishing callback should be invoked exactly " + + "one time").that(finishingInvocations).isEqualTo(1) + } } private companion object { diff --git a/packages/SystemUI/tests/src/com/android/systemui/user/domain/interactor/UserInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/user/domain/interactor/UserInteractorTest.kt index 5beb2b389349..ffa4e2d8f158 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/user/domain/interactor/UserInteractorTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/user/domain/interactor/UserInteractorTest.kt @@ -52,6 +52,7 @@ import com.android.systemui.user.data.source.UserRecord import com.android.systemui.user.domain.model.ShowDialogRequestModel import com.android.systemui.user.shared.model.UserActionModel import com.android.systemui.user.shared.model.UserModel +import com.android.systemui.user.utils.MultiUserActionsEvent import com.android.systemui.util.mockito.any import com.android.systemui.util.mockito.argumentCaptor import com.android.systemui.util.mockito.eq @@ -74,6 +75,7 @@ import org.mockito.ArgumentMatchers.anyBoolean import org.mockito.ArgumentMatchers.anyInt import org.mockito.Mock import org.mockito.Mockito.never +import org.mockito.Mockito.times import org.mockito.Mockito.verify import org.mockito.MockitoAnnotations @@ -158,6 +160,7 @@ class UserInteractorTest : SysuiTestCase() { resumeSessionReceiver = resumeSessionReceiver, resetOrExitSessionReceiver = resetOrExitSessionReceiver, ), + uiEventLogger = uiEventLogger, featureFlags = featureFlags, ) } @@ -457,6 +460,9 @@ class UserInteractorTest : SysuiTestCase() { val dialogShower: UserSwitchDialogController.DialogShower = mock() underTest.executeAction(UserActionModel.ADD_USER, dialogShower) + + verify(uiEventLogger, times(1)) + .log(MultiUserActionsEvent.CREATE_USER_FROM_USER_SWITCHER) assertThat(dialogRequest) .isEqualTo( ShowDialogRequestModel.ShowAddUserDialog( @@ -478,6 +484,8 @@ class UserInteractorTest : SysuiTestCase() { runBlocking(IMMEDIATE) { underTest.executeAction(UserActionModel.ADD_SUPERVISED_USER) + verify(uiEventLogger, times(1)) + .log(MultiUserActionsEvent.CREATE_RESTRICTED_USER_FROM_USER_SWITCHER) val intentCaptor = kotlinArgumentCaptor<Intent>() verify(activityStarter).startActivity(intentCaptor.capture(), eq(true)) assertThat(intentCaptor.value.action) @@ -525,6 +533,8 @@ class UserInteractorTest : SysuiTestCase() { underTest.executeAction(UserActionModel.ENTER_GUEST_MODE) + verify(uiEventLogger, times(1)) + .log(MultiUserActionsEvent.CREATE_GUEST_FROM_USER_SWITCHER) assertThat(dialogRequests) .contains( ShowDialogRequestModel.ShowUserCreationDialog(isGuest = true), diff --git a/packages/SystemUI/tests/src/com/android/systemui/user/ui/viewmodel/StatusBarUserChipViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/user/ui/viewmodel/StatusBarUserChipViewModelTest.kt index 108fa6246e9c..5d4c1cc163d4 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/user/ui/viewmodel/StatusBarUserChipViewModelTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/user/ui/viewmodel/StatusBarUserChipViewModelTest.kt @@ -255,6 +255,7 @@ class StatusBarUserChipViewModelTest : SysuiTestCase() { activityManager = activityManager, refreshUsersScheduler = refreshUsersScheduler, guestUserInteractor = guestUserInteractor, + uiEventLogger = uiEventLogger, ) ) } diff --git a/packages/SystemUI/tests/src/com/android/systemui/user/ui/viewmodel/UserSwitcherViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/user/ui/viewmodel/UserSwitcherViewModelTest.kt index 784a26bb371b..0efede1c2a1c 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/user/ui/viewmodel/UserSwitcherViewModelTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/user/ui/viewmodel/UserSwitcherViewModelTest.kt @@ -158,6 +158,7 @@ class UserSwitcherViewModelTest : SysuiTestCase() { activityManager = activityManager, refreshUsersScheduler = refreshUsersScheduler, guestUserInteractor = guestUserInteractor, + uiEventLogger = uiEventLogger, ), powerInteractor = PowerInteractor( diff --git a/packages/SystemUI/tests/src/com/android/systemui/wallpapers/ImageWallpaperTest.java b/packages/SystemUI/tests/src/com/android/systemui/wallpapers/ImageWallpaperTest.java index 379bb28ae032..30dc0d20600f 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/wallpapers/ImageWallpaperTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/wallpapers/ImageWallpaperTest.java @@ -108,7 +108,6 @@ public class ImageWallpaperTest extends SysuiTestCase { private FeatureFlags mFeatureFlags; FakeSystemClock mFakeSystemClock = new FakeSystemClock(); - FakeExecutor mFakeMainExecutor = new FakeExecutor(mFakeSystemClock); FakeExecutor mFakeBackgroundExecutor = new FakeExecutor(mFakeSystemClock); private CountDownLatch mEventCountdown; @@ -163,7 +162,7 @@ public class ImageWallpaperTest extends SysuiTestCase { } private ImageWallpaper createImageWallpaper() { - return new ImageWallpaper(mFeatureFlags, mFakeBackgroundExecutor, mFakeMainExecutor) { + return new ImageWallpaper(mFeatureFlags, mFakeBackgroundExecutor) { @Override public Engine onCreateEngine() { return new GLEngine(mHandler) { @@ -242,7 +241,7 @@ public class ImageWallpaperTest extends SysuiTestCase { private ImageWallpaper createImageWallpaperCanvas() { - return new ImageWallpaper(mFeatureFlags, mFakeBackgroundExecutor, mFakeMainExecutor) { + return new ImageWallpaper(mFeatureFlags, mFakeBackgroundExecutor) { @Override public Engine onCreateEngine() { return new CanvasEngine() { @@ -315,11 +314,10 @@ public class ImageWallpaperTest extends SysuiTestCase { assertThat(mFakeBackgroundExecutor.numPending()).isAtLeast(1); int n = 0; - while (mFakeBackgroundExecutor.numPending() + mFakeMainExecutor.numPending() >= 1) { + while (mFakeBackgroundExecutor.numPending() >= 1) { n++; assertThat(n).isAtMost(10); mFakeBackgroundExecutor.runNextReady(); - mFakeMainExecutor.runNextReady(); mFakeSystemClock.advanceTime(1000); } diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/qs/FakeFgsManagerController.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/qs/FakeFgsManagerController.kt index b31f119b7a7c..ced7955100f7 100644 --- a/packages/SystemUI/tests/utils/src/com/android/systemui/qs/FakeFgsManagerController.kt +++ b/packages/SystemUI/tests/utils/src/com/android/systemui/qs/FakeFgsManagerController.kt @@ -77,7 +77,5 @@ class FakeFgsManagerController( dialogDismissedListeners.remove(listener) } - override fun shouldUpdateFooterVisibility(): Boolean = false - override fun visibleButtonsCount(): Int = 0 } diff --git a/packages/SystemUI/unfold/Android.bp b/packages/SystemUI/unfold/Android.bp index 108295b90e58..180b611aa13b 100644 --- a/packages/SystemUI/unfold/Android.bp +++ b/packages/SystemUI/unfold/Android.bp @@ -33,6 +33,7 @@ android_library { "dagger2", "jsr330", ], + kotlincflags: ["-Xjvm-default=enable"], java_version: "1.8", min_sdk_version: "current", plugins: ["dagger2-compiler"], diff --git a/packages/SystemUI/unfold/src/com/android/systemui/unfold/UnfoldTransitionProgressProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/UnfoldTransitionProgressProvider.kt index 7117aafba54a..fee485d97afa 100644 --- a/packages/SystemUI/unfold/src/com/android/systemui/unfold/UnfoldTransitionProgressProvider.kt +++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/UnfoldTransitionProgressProvider.kt @@ -34,8 +34,28 @@ interface UnfoldTransitionProgressProvider : CallbackController<TransitionProgre fun destroy() interface TransitionProgressListener { + /** Called when transition is started */ + @JvmDefault fun onTransitionStarted() {} - fun onTransitionFinished() {} + + /** + * Called whenever transition progress is updated, [progress] is a value of the animation + * where 0 is fully folded, 1 is fully unfolded + */ + @JvmDefault fun onTransitionProgress(@FloatRange(from = 0.0, to = 1.0) progress: Float) {} + + /** + * Called when the progress provider determined that the transition is about to finish soon. + * + * For example, in [PhysicsBasedUnfoldTransitionProgressProvider] this could happen when the + * animation is not tied to the hinge angle anymore and it is about to run fixed animation. + */ + @JvmDefault + fun onTransitionFinishing() {} + + /** Called when transition is completely finished */ + @JvmDefault + fun onTransitionFinished() {} } } diff --git a/packages/SystemUI/unfold/src/com/android/systemui/unfold/progress/FixedTimingTransitionProgressProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/progress/FixedTimingTransitionProgressProvider.kt index 4c85b055aeae..fa59cb4d12be 100644 --- a/packages/SystemUI/unfold/src/com/android/systemui/unfold/progress/FixedTimingTransitionProgressProvider.kt +++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/progress/FixedTimingTransitionProgressProvider.kt @@ -88,6 +88,7 @@ internal class FixedTimingTransitionProgressProvider( override fun onAnimationStart(animator: Animator) { listeners.forEach { it.onTransitionStarted() } + listeners.forEach { it.onTransitionFinishing() } } override fun onAnimationEnd(animator: Animator) { diff --git a/packages/SystemUI/unfold/src/com/android/systemui/unfold/progress/PhysicsBasedUnfoldTransitionProgressProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/progress/PhysicsBasedUnfoldTransitionProgressProvider.kt index b56818693124..ecc029dc1a07 100644 --- a/packages/SystemUI/unfold/src/com/android/systemui/unfold/progress/PhysicsBasedUnfoldTransitionProgressProvider.kt +++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/progress/PhysicsBasedUnfoldTransitionProgressProvider.kt @@ -31,6 +31,7 @@ import com.android.systemui.unfold.updates.FOLD_UPDATE_UNFOLDED_SCREEN_AVAILABLE import com.android.systemui.unfold.updates.FoldStateProvider import com.android.systemui.unfold.updates.FoldStateProvider.FoldUpdate import com.android.systemui.unfold.updates.FoldStateProvider.FoldUpdatesListener +import com.android.systemui.unfold.updates.name /** Maps fold updates to unfold transition progress using DynamicAnimation. */ class PhysicsBasedUnfoldTransitionProgressProvider( @@ -117,13 +118,17 @@ class PhysicsBasedUnfoldTransitionProgressProvider( } if (DEBUG) { - Log.d(TAG, "onFoldUpdate = $update") + Log.d(TAG, "onFoldUpdate = ${update.name()}") Trace.traceCounter(Trace.TRACE_TAG_APP, "fold_update", update) } } private fun cancelTransition(endValue: Float, animate: Boolean) { if (isTransitionRunning && animate) { + if (endValue == 1.0f && !isAnimatedCancelRunning) { + listeners.forEach { it.onTransitionFinishing() } + } + isAnimatedCancelRunning = true springAnimation.animateToFinalPosition(endValue) } else { diff --git a/packages/SystemUI/unfold/src/com/android/systemui/unfold/util/ScopedUnfoldTransitionProgressProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/util/ScopedUnfoldTransitionProgressProvider.kt index 8491f832b740..b7bab3e5ed5a 100644 --- a/packages/SystemUI/unfold/src/com/android/systemui/unfold/util/ScopedUnfoldTransitionProgressProvider.kt +++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/util/ScopedUnfoldTransitionProgressProvider.kt @@ -110,6 +110,12 @@ constructor(source: UnfoldTransitionProgressProvider? = null) : lastTransitionProgress = progress } + override fun onTransitionFinishing() { + if (isReadyToHandleTransition) { + listeners.forEach { it.onTransitionFinishing() } + } + } + override fun onTransitionFinished() { if (isReadyToHandleTransition) { listeners.forEach { it.onTransitionFinished() } diff --git a/services/Android.bp b/services/Android.bp index f6570e9d2702..3f3ba067632b 100644 --- a/services/Android.bp +++ b/services/Android.bp @@ -187,6 +187,7 @@ java_library { "framework-tethering.stubs.module_lib", "service-art.stubs.system_server", "service-permission.stubs.system_server", + "service-rkp.stubs.system_server", "service-sdksandbox.stubs.system_server", ], diff --git a/services/api/current.txt b/services/api/current.txt index 18b1df3d418b..da5b1fcaae99 100644 --- a/services/api/current.txt +++ b/services/api/current.txt @@ -57,7 +57,6 @@ package com.android.server.pm { public static interface PackageManagerLocal.FilteredSnapshot extends java.lang.AutoCloseable { method public void close(); - method public void forAllPackageStates(@NonNull java.util.function.Consumer<com.android.server.pm.pkg.PackageState>); method @Nullable public com.android.server.pm.pkg.PackageState getPackageState(@NonNull String); method @NonNull public java.util.Map<java.lang.String,com.android.server.pm.pkg.PackageState> getPackageStates(); } @@ -130,13 +129,6 @@ package com.android.server.pm.pkg { } -package com.android.server.pm.snapshot { - - public interface PackageDataSnapshot { - } - -} - package com.android.server.role { public interface RoleServicePlatformHelper { diff --git a/services/companion/java/com/android/server/companion/virtual/VirtualDeviceManagerService.java b/services/companion/java/com/android/server/companion/virtual/VirtualDeviceManagerService.java index 2b62f69d78f3..f07d2855c986 100644 --- a/services/companion/java/com/android/server/companion/virtual/VirtualDeviceManagerService.java +++ b/services/companion/java/com/android/server/companion/virtual/VirtualDeviceManagerService.java @@ -47,6 +47,7 @@ import android.util.ArraySet; import android.util.ExceptionUtils; import android.util.Slog; import android.util.SparseArray; +import android.view.Display; import android.widget.Toast; import com.android.internal.annotations.GuardedBy; @@ -385,7 +386,32 @@ public class VirtualDeviceManagerService extends SystemService { @Override // BinderCall @VirtualDeviceParams.DevicePolicy public int getDevicePolicy(int deviceId, @VirtualDeviceParams.PolicyType int policyType) { - return mLocalService.getDevicePolicy(deviceId, policyType); + synchronized (mVirtualDeviceManagerLock) { + for (int i = 0; i < mVirtualDevices.size(); i++) { + final VirtualDeviceImpl device = mVirtualDevices.valueAt(i); + if (device.getDeviceId() == deviceId) { + return device.getDevicePolicy(policyType); + } + } + } + return VirtualDeviceParams.DEVICE_POLICY_DEFAULT; + } + + + @Override // Binder call + public int getDeviceIdForDisplayId(int displayId) { + if (displayId == Display.INVALID_DISPLAY || displayId == Display.DEFAULT_DISPLAY) { + return VirtualDeviceManager.DEFAULT_DEVICE_ID; + } + synchronized (mVirtualDeviceManagerLock) { + for (int i = 0; i < mVirtualDevices.size(); i++) { + VirtualDeviceImpl virtualDevice = mVirtualDevices.valueAt(i); + if (virtualDevice.isDisplayOwnedByVirtualDevice(displayId)) { + return virtualDevice.getDeviceId(); + } + } + } + return VirtualDeviceManager.DEFAULT_DEVICE_ID; } @Nullable @@ -469,20 +495,6 @@ public class VirtualDeviceManagerService extends SystemService { } @Override - @VirtualDeviceParams.DevicePolicy - public int getDevicePolicy(int deviceId, @VirtualDeviceParams.PolicyType int policyType) { - synchronized (mVirtualDeviceManagerLock) { - for (int i = 0; i < mVirtualDevices.size(); i++) { - final VirtualDeviceImpl device = mVirtualDevices.valueAt(i); - if (device.getDeviceId() == deviceId) { - return device.getDevicePolicy(policyType); - } - } - } - return VirtualDeviceParams.DEVICE_POLICY_DEFAULT; - } - - @Override public void onVirtualDisplayCreated(int displayId) { final VirtualDisplayListener[] listeners; synchronized (mVirtualDeviceManagerLock) { @@ -543,19 +555,6 @@ public class VirtualDeviceManagerService extends SystemService { } @Override - public boolean isAppOwnerOfAnyVirtualDevice(int uid) { - synchronized (mVirtualDeviceManagerLock) { - int size = mVirtualDevices.size(); - for (int i = 0; i < size; i++) { - if (mVirtualDevices.valueAt(i).getOwnerUid() == uid) { - return true; - } - } - return false; - } - } - - @Override public boolean isAppRunningOnAnyVirtualDevice(int uid) { synchronized (mVirtualDeviceManagerLock) { int size = mVirtualDevices.size(); diff --git a/services/core/Android.bp b/services/core/Android.bp index b6f0237e616e..1e1d61050a5d 100644 --- a/services/core/Android.bp +++ b/services/core/Android.bp @@ -132,6 +132,7 @@ java_library_static { "framework-tethering.stubs.module_lib", "service-art.stubs.system_server", "service-permission.stubs.system_server", + "service-rkp.stubs.system_server", "service-sdksandbox.stubs.system_server", ], plugins: ["ImmutabilityAnnotationProcessor"], diff --git a/services/core/java/com/android/server/BinaryTransparencyService.java b/services/core/java/com/android/server/BinaryTransparencyService.java index 6cd7ce8a1c43..cbe6091f9d04 100644 --- a/services/core/java/com/android/server/BinaryTransparencyService.java +++ b/services/core/java/com/android/server/BinaryTransparencyService.java @@ -476,6 +476,7 @@ public class BinaryTransparencyService extends SystemService { } private void printPackageMeasurements(PackageInfo packageInfo, + boolean useSha256, final PrintWriter pw) { Map<Integer, byte[]> contentDigests = computeApkContentDigest( packageInfo.applicationInfo.sourceDir); @@ -485,6 +486,14 @@ public class BinaryTransparencyService extends SystemService { return; } + if (useSha256) { + byte[] fileBuff = PackageUtils.createLargeFileBuffer(); + String hexEncodedSha256Digest = + PackageUtils.computeSha256DigestForLargeFile( + packageInfo.applicationInfo.sourceDir, fileBuff); + pw.print(hexEncodedSha256Digest + ","); + } + for (Map.Entry<Integer, byte[]> entry : contentDigests.entrySet()) { Integer algorithmId = entry.getKey(); byte[] contentDigest = entry.getValue(); @@ -497,6 +506,7 @@ public class BinaryTransparencyService extends SystemService { } private void printPackageInstallationInfo(PackageInfo packageInfo, + boolean useSha256, final PrintWriter pw) { pw.println("--- Package Installation Info ---"); pw.println("Current install location: " @@ -507,11 +517,13 @@ public class BinaryTransparencyService extends SystemService { pw.println("|--> Pre-installed package install location: " + origPackageFilepath); - // TODO(b/259347186): revive this with the proper cmd options. - /* - String digest = PackageUtils.computeSha256DigestForLargeFile( - origPackageFilepath, PackageUtils.createLargeFileBuffer()); - */ + if (useSha256) { + String sha256Digest = PackageUtils.computeSha256DigestForLargeFile( + origPackageFilepath, PackageUtils.createLargeFileBuffer()); + pw.println("|--> Pre-installed package SHA-256 digest: " + + sha256Digest); + } + Map<Integer, byte[]> contentDigests = computeApkContentDigest( origPackageFilepath); @@ -530,7 +542,9 @@ public class BinaryTransparencyService extends SystemService { } } pw.println("First install time (ms): " + packageInfo.firstInstallTime); - pw.println("Last update time (ms): " + packageInfo.lastUpdateTime); + pw.println("Last update time (ms): " + packageInfo.lastUpdateTime); + // TODO(b/261493591): Determination of whether a package is preinstalled can be + // made more robust boolean isPreloaded = (packageInfo.firstInstallTime == packageInfo.lastUpdateTime); pw.println("Is preloaded: " + isPreloaded); @@ -562,6 +576,8 @@ public class BinaryTransparencyService extends SystemService { } pw.println("--- Package Signer Info ---"); pw.println("Has multiple signers: " + signerInfo.hasMultipleSigners()); + pw.println("Signing key has been rotated: " + + signerInfo.hasPastSigningCertificates()); Signature[] packageSigners = signerInfo.getApkContentsSigners(); for (Signature packageSigner : packageSigners) { byte[] packageSignerDigestBytes = @@ -575,8 +591,31 @@ public class BinaryTransparencyService extends SystemService { } catch (CertificateException e) { Slog.e(TAG, "Failed to obtain public key of signer for cert with hash: " - + packageSignerDigestHextring); - e.printStackTrace(); + + packageSignerDigestHextring, e); + } + } + + if (!signerInfo.hasMultipleSigners() + && signerInfo.hasPastSigningCertificates()) { + pw.println("== Signing Cert Lineage (Excluding The Most Recent) =="); + pw.println("(Certs are sorted in the order of rotation, beginning with the " + + "original signing cert)"); + Signature[] signingCertHistory = signerInfo.getSigningCertificateHistory(); + for (int i = 0; i < (signingCertHistory.length - 1); i++) { + Signature signature = signingCertHistory[i]; + byte[] signatureDigestBytes = PackageUtils.computeSha256DigestBytes( + signature.toByteArray()); + String certHashHexString = HexEncoding.encodeToString( + signatureDigestBytes, false); + pw.println(" ++ Signer cert #" + (i + 1) + " ++"); + pw.println(" Cert SHA256-digest: " + certHashHexString); + try { + PublicKey publicKey = signature.getPublicKey(); + pw.println(" Signing key algorithm: " + publicKey.getAlgorithm()); + } catch (CertificateException e) { + Slog.e(TAG, "Failed to obtain public key of signer for cert " + + "with hash: " + certHashHexString, e); + } } } @@ -615,7 +654,7 @@ public class BinaryTransparencyService extends SystemService { pw.println("Component factory: " + packageInfo.applicationInfo.appComponentFactory); pw.println("Process name: " + packageInfo.applicationInfo.processName); - pw.println("Task affinity : " + packageInfo.applicationInfo.taskAffinity); + pw.println("Task affinity: " + packageInfo.applicationInfo.taskAffinity); pw.println("UID: " + packageInfo.applicationInfo.uid); pw.println("Shared UID: " + packageInfo.sharedUserId); @@ -669,15 +708,35 @@ public class BinaryTransparencyService extends SystemService { } + private void printHeadersHelper(@NonNull String packageType, + boolean useSha256, + @NonNull final PrintWriter pw) { + pw.print(packageType + " Info [Format: package_name,package_version,"); + if (useSha256) { + pw.print("package_sha256_digest,"); + } + pw.print("content_digest_algorithm:content_digest]:\n"); + } + private int printAllApexs() { final PrintWriter pw = getOutPrintWriter(); boolean verbose = false; + boolean useSha256 = false; + boolean printHeaders = true; String opt; while ((opt = getNextOption()) != null) { switch (opt) { case "-v": + case "--verbose": verbose = true; break; + case "-o": + case "--old": + useSha256 = true; + break; + case "--no-headers": + printHeaders = false; + break; default: pw.println("ERROR: Unknown option: " + opt); return 1; @@ -690,23 +749,17 @@ public class BinaryTransparencyService extends SystemService { return -1; } - if (!verbose) { - pw.println("APEX Info [Format: package_name,package_version," - // TODO(b/259347186): revive via special cmd line option - //+ "package_sha256_digest," - + "content_digest_algorithm:content_digest]:"); + if (!verbose && printHeaders) { + printHeadersHelper("APEX", useSha256, pw); } for (PackageInfo packageInfo : getCurrentInstalledApexs()) { - if (verbose) { - pw.println("APEX Info [Format: package_name,package_version," - // TODO(b/259347186): revive via special cmd line option - //+ "package_sha256_digest," - + "content_digest_algorithm:content_digest]:"); + if (verbose && printHeaders) { + printHeadersHelper("APEX", useSha256, pw); } String packageName = packageInfo.packageName; pw.print(packageName + "," + packageInfo.getLongVersionCode() + ","); - printPackageMeasurements(packageInfo, pw); + printPackageMeasurements(packageInfo, useSha256, pw); if (verbose) { ModuleInfo moduleInfo; @@ -718,7 +771,7 @@ public class BinaryTransparencyService extends SystemService { pw.println("Is a module: false"); } - printPackageInstallationInfo(packageInfo, pw); + printPackageInstallationInfo(packageInfo, useSha256, pw); printPackageSignerDetails(packageInfo.signingInfo, pw); pw.println(""); } @@ -729,12 +782,22 @@ public class BinaryTransparencyService extends SystemService { private int printAllModules() { final PrintWriter pw = getOutPrintWriter(); boolean verbose = false; + boolean useSha256 = false; + boolean printHeaders = true; String opt; while ((opt = getNextOption()) != null) { switch (opt) { case "-v": + case "--verbose": verbose = true; break; + case "-o": + case "--old": + useSha256 = true; + break; + case "--no-headers": + printHeaders = false; + break; default: pw.println("ERROR: Unknown option: " + opt); return 1; @@ -747,32 +810,25 @@ public class BinaryTransparencyService extends SystemService { return -1; } - if (!verbose) { - pw.println("Module Info [Format: package_name,package_version," - // TODO(b/259347186): revive via special cmd line option - //+ "package_sha256_digest," - + "content_digest_algorithm:content_digest]:"); + if (!verbose && printHeaders) { + printHeadersHelper("Module", useSha256, pw); } for (ModuleInfo module : pm.getInstalledModules(PackageManager.MATCH_ALL)) { String packageName = module.getPackageName(); - if (verbose) { - pw.println("Module Info [Format: package_name,package_version," - // TODO(b/259347186): revive via special cmd line option - //+ "package_sha256_digest," - + "content_digest_algorithm:content_digest]:"); + if (verbose && printHeaders) { + printHeadersHelper("Module", useSha256, pw); } try { PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.MATCH_APEX | PackageManager.GET_SIGNING_CERTIFICATES); - //pw.print("package:"); pw.print(packageInfo.packageName + ","); pw.print(packageInfo.getLongVersionCode() + ","); - printPackageMeasurements(packageInfo, pw); + printPackageMeasurements(packageInfo, useSha256, pw); if (verbose) { printModuleDetails(module, pw); - printPackageInstallationInfo(packageInfo, pw); + printPackageInstallationInfo(packageInfo, useSha256, pw); printPackageSignerDetails(packageInfo.signingInfo, pw); pw.println(""); } @@ -793,41 +849,45 @@ public class BinaryTransparencyService extends SystemService { final PrintWriter pw = getOutPrintWriter(); boolean verbose = false; boolean printLibraries = false; + boolean useSha256 = false; + boolean printHeaders = true; String opt; while ((opt = getNextOption()) != null) { switch (opt) { case "-v": + case "--verbose": verbose = true; break; case "-l": printLibraries = true; break; + case "-o": + case "--old": + useSha256 = true; + break; + case "--no-headers": + printHeaders = false; + break; default: pw.println("ERROR: Unknown option: " + opt); return 1; } } - if (!verbose) { - pw.println("MBA Info [Format: package_name,package_version," - // TODO(b/259347186): revive via special cmd line option - //+ "package_sha256_digest," - + "content_digest_algorithm:content_digest]:"); + if (!verbose && printHeaders) { + printHeadersHelper("MBA", useSha256, pw); } for (PackageInfo packageInfo : getNewlyInstalledMbas()) { - if (verbose) { - pw.println("MBA Info [Format: package_name,package_version," - // TODO(b/259347186): revive via special cmd line option - //+ "package_sha256_digest," - + "content_digest_algorithm:content_digest]:"); + if (verbose && printHeaders) { + printHeadersHelper("MBA", useSha256, pw); } pw.print(packageInfo.packageName + ","); pw.print(packageInfo.getLongVersionCode() + ","); - printPackageMeasurements(packageInfo, pw); + printPackageMeasurements(packageInfo, useSha256, pw); if (verbose) { printAppDetails(packageInfo, printLibraries, pw); - printPackageInstallationInfo(packageInfo, pw); + printPackageInstallationInfo(packageInfo, useSha256, pw); printPackageSignerDetails(packageInfo.signingInfo, pw); pw.println(""); } @@ -894,27 +954,39 @@ public class BinaryTransparencyService extends SystemService { private void printHelpMenu() { final PrintWriter pw = getOutPrintWriter(); pw.println("Transparency manager (transparency) commands:"); - pw.println(" help"); - pw.println(" Print this help text."); + pw.println(" help"); + pw.println(" Print this help text."); pw.println(""); - pw.println(" get image_info [-a]"); - pw.println(" Print information about loaded image (firmware). Options:"); - pw.println(" -a: lists all other identifiable partitions."); + pw.println(" get image_info [-a]"); + pw.println(" Print information about loaded image (firmware). Options:"); + pw.println(" -a: lists all other identifiable partitions."); pw.println(""); - pw.println(" get apex_info [-v]"); - pw.println(" Print information about installed APEXs on device."); - pw.println(" -v: lists more verbose information about each APEX."); + pw.println(" get apex_info [-o] [-v] [--no-headers]"); + pw.println(" Print information about installed APEXs on device."); + pw.println(" -o: also uses the old digest scheme (SHA256) to compute " + + "APEX hashes. WARNING: This can be a very slow and CPU-intensive " + + "computation."); + pw.println(" -v: lists more verbose information about each APEX."); + pw.println(" --no-headers: does not print the header if specified"); pw.println(""); - pw.println(" get module_info [-v]"); - pw.println(" Print information about installed modules on device."); - pw.println(" -v: lists more verbose information about each module."); + pw.println(" get module_info [-o] [-v] [--no-headers]"); + pw.println(" Print information about installed modules on device."); + pw.println(" -o: also uses the old digest scheme (SHA256) to compute " + + "module hashes. WARNING: This can be a very slow and " + + "CPU-intensive computation."); + pw.println(" -v: lists more verbose information about each module."); + pw.println(" --no-headers: does not print the header if specified"); pw.println(""); - pw.println(" get mba_info [-v] [-l]"); - pw.println(" Print information about installed mobile bundle apps " + pw.println(" get mba_info [-o] [-v] [-l] [--no-headers]"); + pw.println(" Print information about installed mobile bundle apps " + "(MBAs on device)."); - pw.println(" -v: lists more verbose information about each app."); - pw.println(" -l: lists shared library info. This will only be " - + "listed with -v"); + pw.println(" -o: also uses the old digest scheme (SHA256) to compute " + + "MBA hashes. WARNING: This can be a very slow and CPU-intensive " + + "computation."); + pw.println(" -v: lists more verbose information about each app."); + pw.println(" -l: lists shared library info. (This option only works " + + "when -v option is also specified)"); + pw.println(" --no-headers: does not print the header if specified"); pw.println(""); } diff --git a/services/core/java/com/android/server/BootReceiver.java b/services/core/java/com/android/server/BootReceiver.java index 84c033cbdf0e..572e9c2a5d82 100644 --- a/services/core/java/com/android/server/BootReceiver.java +++ b/services/core/java/com/android/server/BootReceiver.java @@ -337,12 +337,10 @@ public class BootReceiver extends BroadcastReceiver { return; } - // Check if we should rate limit and abort early if needed. Do this for both proto and - // non-proto tombstones, even though proto tombstones do not support including the counter - // of events dropped since rate limiting activated yet. + // Check if we should rate limit and abort early if needed. DropboxRateLimiter.RateLimitResult rateLimitResult = sDropboxRateLimiter.shouldRateLimit( - proto ? TAG_TOMBSTONE_PROTO : TAG_TOMBSTONE, processName); + proto ? TAG_TOMBSTONE_PROTO_WITH_HEADERS : TAG_TOMBSTONE, processName); if (rateLimitResult.shouldRateLimit()) return; HashMap<String, Long> timestamps = readTimestamps(); diff --git a/services/core/java/com/android/server/CountryDetectorService.java b/services/core/java/com/android/server/CountryDetectorService.java index a2a7dd35371f..a6549253dcab 100644 --- a/services/core/java/com/android/server/CountryDetectorService.java +++ b/services/core/java/com/android/server/CountryDetectorService.java @@ -148,6 +148,10 @@ public class CountryDetectorService extends ICountryDetector.Stub { Receiver r = new Receiver(listener); try { listener.asBinder().linkToDeath(r, 0); + final Country country = detectCountry(); + if (country != null) { + listener.onCountryDetected(country); + } mReceivers.put(listener.asBinder(), r); if (mReceivers.size() == 1) { Slog.d(TAG, "The first listener is added"); diff --git a/services/core/java/com/android/server/NetworkManagementService.java b/services/core/java/com/android/server/NetworkManagementService.java index 5d54b6c1c81f..fc26f0989f45 100644 --- a/services/core/java/com/android/server/NetworkManagementService.java +++ b/services/core/java/com/android/server/NetworkManagementService.java @@ -17,9 +17,6 @@ package com.android.server; import static android.Manifest.permission.CONNECTIVITY_INTERNAL; -import static android.Manifest.permission.NETWORK_SETTINGS; -import static android.Manifest.permission.OBSERVE_NETWORK_POLICY; -import static android.Manifest.permission.SHUTDOWN; import static android.net.ConnectivityManager.FIREWALL_CHAIN_DOZABLE; import static android.net.ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY; import static android.net.ConnectivityManager.FIREWALL_CHAIN_POWERSAVE; @@ -63,6 +60,7 @@ import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.os.INetworkManagementService; +import android.os.PermissionEnforcer; import android.os.Process; import android.os.RemoteCallbackList; import android.os.RemoteException; @@ -230,6 +228,7 @@ public class NetworkManagementService extends INetworkManagementService.Stub { */ private NetworkManagementService( Context context, Dependencies deps) { + super(PermissionEnforcer.fromContext(context)); mContext = context; mDeps = deps; diff --git a/services/core/java/com/android/server/StorageManagerService.java b/services/core/java/com/android/server/StorageManagerService.java index 6b6351f9b909..64358696b07f 100644 --- a/services/core/java/com/android/server/StorageManagerService.java +++ b/services/core/java/com/android/server/StorageManagerService.java @@ -672,6 +672,7 @@ class StorageManagerService extends IStorageManager.Stub private static final int H_COMPLETE_UNLOCK_USER = 14; private static final int H_VOLUME_STATE_CHANGED = 15; private static final int H_CLOUD_MEDIA_PROVIDER_CHANGED = 16; + private static final int H_SECURE_KEYGUARD_STATE_CHANGED = 17; class StorageManagerServiceHandler extends Handler { public StorageManagerServiceHandler(Looper looper) { @@ -819,6 +820,14 @@ class StorageManagerService extends IStorageManager.Stub } break; } + case H_SECURE_KEYGUARD_STATE_CHANGED: { + try { + mVold.onSecureKeyguardStateChanged((boolean) msg.obj); + } catch (Exception e) { + Slog.wtf(TAG, e); + } + break; + } } } } @@ -836,7 +845,15 @@ class StorageManagerService extends IStorageManager.Stub if (Intent.ACTION_USER_ADDED.equals(action)) { final UserManager um = mContext.getSystemService(UserManager.class); final int userSerialNumber = um.getUserSerialNumber(userId); - mVold.onUserAdded(userId, userSerialNumber); + final UserInfo userInfo = um.getUserInfo(userId); + if (userInfo.isCloneProfile()) { + // Only clone profiles share storage with their parent + mVold.onUserAdded(userId, userSerialNumber, + userInfo.profileGroupId /* sharesStorageWithUserId */); + } else { + mVold.onUserAdded(userId, userSerialNumber, + -1 /* shareStorageWithUserId */); + } } else if (Intent.ACTION_USER_REMOVED.equals(action)) { synchronized (mLock) { final int size = mVolumes.size(); @@ -1050,7 +1067,11 @@ class StorageManagerService extends IStorageManager.Stub // Tell vold about all existing and started users for (UserInfo user : users) { - mVold.onUserAdded(user.id, user.serialNumber); + if (user.isCloneProfile()) { + mVold.onUserAdded(user.id, user.serialNumber, user.profileGroupId); + } else { + mVold.onUserAdded(user.id, user.serialNumber, -1); + } } for (int userId : systemUnlockedUsers) { mVold.onUserStarted(userId); @@ -1242,12 +1263,12 @@ class StorageManagerService extends IStorageManager.Stub public void onKeyguardStateChanged(boolean isShowing) { // Push down current secure keyguard status so that we ignore malicious // USB devices while locked. - mSecureKeyguardShowing = isShowing + boolean isSecureKeyguardShowing = isShowing && mContext.getSystemService(KeyguardManager.class).isDeviceSecure(mCurrentUserId); - try { - mVold.onSecureKeyguardStateChanged(mSecureKeyguardShowing); - } catch (Exception e) { - Slog.wtf(TAG, e); + if (mSecureKeyguardShowing != isSecureKeyguardShowing) { + mSecureKeyguardShowing = isSecureKeyguardShowing; + mHandler.obtainMessage(H_SECURE_KEYGUARD_STATE_CHANGED, mSecureKeyguardShowing) + .sendToTarget(); } } diff --git a/services/core/java/com/android/server/am/ActiveServices.java b/services/core/java/com/android/server/am/ActiveServices.java index 0d672bd8b21e..fa62b89c2f13 100644 --- a/services/core/java/com/android/server/am/ActiveServices.java +++ b/services/core/java/com/android/server/am/ActiveServices.java @@ -2939,6 +2939,8 @@ public final class ActiveServices { void unscheduleShortFgsTimeoutLocked(ServiceRecord sr) { mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_SHORT_FGS_ANR_TIMEOUT_MSG, sr); + mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_SHORT_FGS_PROCSTATE_TIMEOUT_MSG, + sr); mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_SHORT_FGS_TIMEOUT_MSG, sr); } @@ -2981,6 +2983,9 @@ public final class ActiveServices { void onShortFgsTimeout(ServiceRecord sr) { synchronized (mAm) { if (!sr.shouldTriggerShortFgsTimeout()) { + if (DEBUG_SHORT_SERVICE) { + Slog.d(TAG_SERVICE, "[STALE] Short FGS timed out: " + sr); + } return; } Slog.e(TAG_SERVICE, "Short FGS timed out: " + sr); @@ -2989,10 +2994,19 @@ public final class ActiveServices { } catch (RemoteException e) { // TODO(short-service): Anything to do here? } - // Schedule the ANR timeout. - final Message msg = mAm.mHandler.obtainMessage( - ActivityManagerService.SERVICE_SHORT_FGS_ANR_TIMEOUT_MSG, sr); - mAm.mHandler.sendMessageAtTime(msg, sr.getShortFgsInfo().getAnrTime()); + // Schedule the procstate demotion timeout and ANR timeout. + { + final Message msg = mAm.mHandler.obtainMessage( + ActivityManagerService.SERVICE_SHORT_FGS_PROCSTATE_TIMEOUT_MSG, sr); + mAm.mHandler.sendMessageAtTime( + msg, sr.getShortFgsInfo().getProcStateDemoteTime()); + } + + { + final Message msg = mAm.mHandler.obtainMessage( + ActivityManagerService.SERVICE_SHORT_FGS_ANR_TIMEOUT_MSG, sr); + mAm.mHandler.sendMessageAtTime(msg, sr.getShortFgsInfo().getAnrTime()); + } } } @@ -3010,6 +3024,21 @@ public final class ActiveServices { } } + void onShortFgsProcstateTimeout(ServiceRecord sr) { + synchronized (mAm) { + if (!sr.shouldDemoteShortFgsProcState()) { + if (DEBUG_SHORT_SERVICE) { + Slog.d(TAG_SERVICE, "[STALE] Short FGS procstate demotion: " + sr); + } + return; + } + + Slog.e(TAG_SERVICE, "Short FGS procstate demoted: " + sr); + + mAm.updateOomAdjLocked(sr.app, OomAdjuster.OOM_ADJ_REASON_SHORT_FGS_TIMEOUT); + } + } + void onShortFgsAnrTimeout(ServiceRecord sr) { final String reason = "A foreground service of FOREGROUND_SERVICE_TYPE_SHORT_SERVICE" + " did not stop within a timeout: " + sr.getComponentName(); @@ -3021,6 +3050,9 @@ public final class ActiveServices { tr.mLatencyTracker.waitingOnAMSLockEnded(); if (!sr.shouldTriggerShortFgsAnr()) { + if (DEBUG_SHORT_SERVICE) { + Slog.d(TAG_SERVICE, "[STALE] Short FGS ANR'ed: " + sr); + } return; } @@ -7713,4 +7745,35 @@ public final class ActiveServices { Slog.e(TAG, "stopForegroundServiceDelegateLocked delegate does not exist"); } } + + private static void getClientPackages(ServiceRecord sr, ArraySet<String> output) { + var connections = sr.getConnections(); + for (int conni = connections.size() - 1; conni >= 0; conni--) { + var connl = connections.valueAt(conni); + for (int i = 0, size = connl.size(); i < size; i++) { + var conn = connl.get(i); + if (conn.binding.client != null) { + output.add(conn.binding.client.info.packageName); + } + } + } + } + + /** + * Return all client package names of a service. + */ + ArraySet<String> getClientPackagesLocked(@NonNull String servicePackageName) { + var results = new ArraySet<String>(); + int[] users = mAm.mUserController.getUsers(); + for (int ui = 0; ui < users.length; ui++) { + ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(users[ui]); + for (int i = 0, size = alls.size(); i < size; i++) { + ServiceRecord sr = alls.valueAt(i); + if (sr.name.getPackageName().equals(servicePackageName)) { + getClientPackages(sr, results); + } + } + } + return results; + } } diff --git a/services/core/java/com/android/server/am/ActivityManagerConstants.java b/services/core/java/com/android/server/am/ActivityManagerConstants.java index 2d69667da575..b0a2912b5413 100644 --- a/services/core/java/com/android/server/am/ActivityManagerConstants.java +++ b/services/core/java/com/android/server/am/ActivityManagerConstants.java @@ -129,6 +129,7 @@ final class ActivityManagerConstants extends ContentObserver { static final String KEY_KILL_BG_RESTRICTED_CACHED_IDLE = "kill_bg_restricted_cached_idle"; static final String KEY_KILL_BG_RESTRICTED_CACHED_IDLE_SETTLE_TIME = "kill_bg_restricted_cached_idle_settle_time"; + static final String KEY_MAX_PREVIOUS_TIME = "max_previous_time"; /** * Note this key is on {@link DeviceConfig#NAMESPACE_ACTIVITY_MANAGER_COMPONENT_ALIAS}. * @see #mEnableComponentAlias @@ -192,6 +193,7 @@ final class ActivityManagerConstants extends ContentObserver { private static final float DEFAULT_FGS_START_DENIED_LOG_SAMPLE_RATE = 1; // 100% private static final long DEFAULT_PROCESS_KILL_TIMEOUT_MS = 10 * 1000; private static final long DEFAULT_NETWORK_ACCESS_TIMEOUT_MS = 200; // 0.2 sec + private static final long DEFAULT_MAX_PREVIOUS_TIME = 60 * 1000; // 60s static final long DEFAULT_BACKGROUND_SETTLE_TIME = 60 * 1000; static final long DEFAULT_KILL_BG_RESTRICTED_CACHED_IDLE_SETTLE_TIME_MS = 60 * 1000; @@ -513,7 +515,7 @@ final class ActivityManagerConstants extends ContentObserver { // Allow app just moving from TOP to FOREGROUND_SERVICE to stay in a higher adj value for // this long. - public long TOP_TO_FGS_GRACE_DURATION = DEFAULT_TOP_TO_FGS_GRACE_DURATION; + public volatile long TOP_TO_FGS_GRACE_DURATION = DEFAULT_TOP_TO_FGS_GRACE_DURATION; /** * Allow app just leaving TOP with an already running ALMOST_PERCEPTIBLE service to stay in @@ -522,6 +524,9 @@ final class ActivityManagerConstants extends ContentObserver { public long TOP_TO_ALMOST_PERCEPTIBLE_GRACE_DURATION = DEFAULT_TOP_TO_ALMOST_PERCEPTIBLE_GRACE_DURATION; + // How long a process can remain at previous oom_adj before dropping to cached + public static long MAX_PREVIOUS_TIME = DEFAULT_MAX_PREVIOUS_TIME; + /** * The minimum time we allow between crashes, for us to consider this * application to be bad and stop its services and reject broadcasts. @@ -1142,6 +1147,12 @@ final class ActivityManagerConstants extends ContentObserver { case KEY_LOW_SWAP_THRESHOLD_PERCENT: updateLowSwapThresholdPercent(); break; + case KEY_TOP_TO_FGS_GRACE_DURATION: + updateTopToFgsGraceDuration(); + break; + case KEY_MAX_PREVIOUS_TIME: + updateMaxPreviousTime(); + break; default: break; } @@ -1359,8 +1370,6 @@ final class ActivityManagerConstants extends ContentObserver { DEFAULT_PROCESS_START_ASYNC); MEMORY_INFO_THROTTLE_TIME = mParser.getLong(KEY_MEMORY_INFO_THROTTLE_TIME, DEFAULT_MEMORY_INFO_THROTTLE_TIME); - TOP_TO_FGS_GRACE_DURATION = mParser.getDurationMillis(KEY_TOP_TO_FGS_GRACE_DURATION, - DEFAULT_TOP_TO_FGS_GRACE_DURATION); TOP_TO_ALMOST_PERCEPTIBLE_GRACE_DURATION = mParser.getDurationMillis( KEY_TOP_TO_ALMOST_PERCEPTIBLE_GRACE_DURATION, DEFAULT_TOP_TO_ALMOST_PERCEPTIBLE_GRACE_DURATION); @@ -1790,6 +1799,21 @@ final class ActivityManagerConstants extends ContentObserver { DEFAULT_LOW_SWAP_THRESHOLD_PERCENT); } + + private void updateTopToFgsGraceDuration() { + TOP_TO_FGS_GRACE_DURATION = DeviceConfig.getLong( + DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, + KEY_TOP_TO_FGS_GRACE_DURATION, + DEFAULT_TOP_TO_FGS_GRACE_DURATION); + } + + private void updateMaxPreviousTime() { + MAX_PREVIOUS_TIME = DeviceConfig.getLong( + DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, + KEY_MAX_PREVIOUS_TIME, + DEFAULT_MAX_PREVIOUS_TIME); + } + private void updateMinAssocLogDuration() { MIN_ASSOC_LOG_DURATION = DeviceConfig.getLong( DeviceConfig.NAMESPACE_ACTIVITY_MANAGER, KEY_MIN_ASSOC_LOG_DURATION, diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java index 699a622efe55..5b9350027f07 100644 --- a/services/core/java/com/android/server/am/ActivityManagerService.java +++ b/services/core/java/com/android/server/am/ActivityManagerService.java @@ -137,6 +137,8 @@ import static com.android.server.am.ProcessProfileRecord.HOSTING_COMPONENT_TYPE_ import static com.android.server.am.ProcessProfileRecord.HOSTING_COMPONENT_TYPE_SYSTEM; import static com.android.server.net.NetworkPolicyManagerInternal.updateBlockedReasonsWithProcState; import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME; +import static com.android.server.pm.UserManagerInternal.USER_START_MODE_BACKGROUND; +import static com.android.server.pm.UserManagerInternal.USER_START_MODE_FOREGROUND; import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CLEANUP; import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH; import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION; @@ -220,6 +222,7 @@ import android.appwidget.AppWidgetManagerInternal; import android.compat.annotation.ChangeId; import android.compat.annotation.EnabledAfter; import android.compat.annotation.EnabledSince; +import android.compat.annotation.Overridable; import android.content.AttributionSource; import android.content.AutofillOptions; import android.content.BroadcastReceiver; @@ -328,6 +331,7 @@ import android.util.ArrayMap; import android.util.ArraySet; import android.util.EventLog; import android.util.FeatureFlagUtils; +import android.util.IndentingPrintWriter; import android.util.IntArray; import android.util.Log; import android.util.Pair; @@ -606,6 +610,7 @@ public class ActivityManagerService extends IActivityManager.Stub * This applies specifically to activities and broadcasts. */ @ChangeId + @Overridable @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.TIRAMISU) public static final long IMPLICIT_INTENTS_ONLY_MATCH_EXPORTED_COMPONENTS = 229362273; @@ -759,6 +764,9 @@ public class ActivityManagerService extends IActivityManager.Stub final AppErrors mAppErrors; final PackageWatchdog mPackageWatchdog; + @GuardedBy("mDeliveryGroupPolicyIgnoredActions") + private final ArraySet<String> mDeliveryGroupPolicyIgnoredActions = new ArraySet(); + /** * Uids of apps with current active camera sessions. Access synchronized on * the IntArray instance itself, and no other locks must be acquired while that @@ -1538,7 +1546,8 @@ public class ActivityManagerService extends IActivityManager.Stub static final int DISPATCH_SENDING_BROADCAST_EVENT = 74; static final int DISPATCH_BINDING_SERVICE_EVENT = 75; static final int SERVICE_SHORT_FGS_TIMEOUT_MSG = 76; - static final int SERVICE_SHORT_FGS_ANR_TIMEOUT_MSG = 77; + static final int SERVICE_SHORT_FGS_PROCSTATE_TIMEOUT_MSG = 77; + static final int SERVICE_SHORT_FGS_ANR_TIMEOUT_MSG = 78; static final int FIRST_BROADCAST_QUEUE_MSG = 200; @@ -1876,6 +1885,9 @@ public class ActivityManagerService extends IActivityManager.Stub case SERVICE_SHORT_FGS_TIMEOUT_MSG: { mServices.onShortFgsTimeout((ServiceRecord) msg.obj); } break; + case SERVICE_SHORT_FGS_PROCSTATE_TIMEOUT_MSG: { + mServices.onShortFgsProcstateTimeout((ServiceRecord) msg.obj); + } break; case SERVICE_SHORT_FGS_ANR_TIMEOUT_MSG: { mServices.onShortFgsAnrTimeout((ServiceRecord) msg.obj); } break; @@ -7426,10 +7438,11 @@ public class ActivityManagerService extends IActivityManager.Stub if (shareDescription != null) { triggerShellBugreport.putExtra(EXTRA_DESCRIPTION, shareDescription); } + UserHandle callingUser = Binder.getCallingUserHandle(); final long identity = Binder.clearCallingIdentity(); try { // Send broadcast to shell to trigger bugreport using Bugreport API - mContext.sendBroadcastAsUser(triggerShellBugreport, UserHandle.SYSTEM); + mContext.sendBroadcastAsUser(triggerShellBugreport, callingUser); } finally { Binder.restoreCallingIdentity(identity); } @@ -12667,7 +12680,7 @@ public class ActivityManagerService extends IActivityManager.Stub * @param platformCompat the instance of platform compat */ private static void filterNonExportedComponents(Intent intent, int callingUid, - List query, PlatformCompat platformCompat, String callerPackage) { + List query, PlatformCompat platformCompat, String callerPackage, String resolvedType) { if (query == null || intent.getPackage() != null || intent.getComponent() != null @@ -12694,19 +12707,24 @@ public class ActivityManagerService extends IActivityManager.Stub } else { continue; } - if (!platformCompat.isChangeEnabledByUid( - IMPLICIT_INTENTS_ONLY_MATCH_EXPORTED_COMPONENTS, callingUid)) { - Slog.w(TAG, "Non-exported component not filtered out " - + "(will be filtered out once the app targets U+)- intent: " - + intent.getAction() + ", component: " - + componentInfo + ", sender: " - + callerPackage); + boolean hasToBeExportedToMatch = platformCompat.isChangeEnabledByUid( + ActivityManagerService.IMPLICIT_INTENTS_ONLY_MATCH_EXPORTED_COMPONENTS, + callingUid); + String[] categories = intent.getCategories() == null ? new String[0] + : intent.getCategories().toArray(String[]::new); + FrameworkStatsLog.write(FrameworkStatsLog.UNSAFE_INTENT_EVENT_REPORTED, + FrameworkStatsLog.UNSAFE_INTENT_EVENT_REPORTED__EVENT_TYPE__INTERNAL_NON_EXPORTED_COMPONENT_MATCH, + callingUid, + componentInfo, + callerPackage, + intent.getAction(), + categories, + resolvedType, + intent.getScheme(), + hasToBeExportedToMatch); + if (!hasToBeExportedToMatch) { return; } - Slog.w(TAG, "Non-exported component filtered out - intent: " - + intent.getAction() + ", component: " - + componentInfo + ", sender: " - + callerPackage); query.remove(i); } } @@ -14620,7 +14638,7 @@ public class ActivityManagerService extends IActivityManager.Stub } filterNonExportedComponents(intent, callingUid, registeredReceivers, - mPlatformCompat, callerPackage); + mPlatformCompat, callerPackage, resolvedType); int NR = registeredReceivers != null ? registeredReceivers.size() : 0; if (!ordered && NR > 0 && !mEnableModernQueue) { // If we are not serializing this broadcast, then send the @@ -14726,7 +14744,7 @@ public class ActivityManagerService extends IActivityManager.Stub || resultTo != null) { BroadcastQueue queue = broadcastQueueForIntent(intent); filterNonExportedComponents(intent, callingUid, receivers, - mPlatformCompat, callerPackage); + mPlatformCompat, callerPackage, resolvedType); BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage, callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType, requiredPermissions, excludedPermissions, excludedPackages, appOp, brOptions, @@ -16566,14 +16584,14 @@ public class ActivityManagerService extends IActivityManager.Stub @Override public boolean startUserInBackgroundWithListener(final int userId, @Nullable IProgressListener unlockListener) { - return mUserController.startUser(userId, /* foreground */ false, unlockListener); + return mUserController.startUser(userId, USER_START_MODE_BACKGROUND, unlockListener); } @Override public boolean startUserInForegroundWithListener(final int userId, @Nullable IProgressListener unlockListener) { // Permission check done inside UserController. - return mUserController.startUser(userId, /* foreground */ true, unlockListener); + return mUserController.startUser(userId, USER_START_MODE_FOREGROUND, unlockListener); } @Override @@ -18191,6 +18209,13 @@ public class ActivityManagerService extends IActivityManager.Stub mServices.stopForegroundServiceDelegateLocked(connection); } } + + @Override + public ArraySet<String> getClientPackages(String servicePackageName) { + synchronized (ActivityManagerService.this) { + return mServices.getClientPackagesLocked(servicePackageName); + } + } } long inputDispatchingTimedOut(int pid, final boolean aboveSystem, TimeoutRecord timeoutRecord) { @@ -18332,6 +18357,37 @@ public class ActivityManagerService extends IActivityManager.Stub } } + void setIgnoreDeliveryGroupPolicy(@NonNull String broadcastAction) { + Objects.requireNonNull(broadcastAction); + enforceCallingPermission(permission.DUMP, "waitForBroadcastBarrier()"); + synchronized (mDeliveryGroupPolicyIgnoredActions) { + mDeliveryGroupPolicyIgnoredActions.add(broadcastAction); + } + } + + void clearIgnoreDeliveryGroupPolicy(@NonNull String broadcastAction) { + Objects.requireNonNull(broadcastAction); + enforceCallingPermission(permission.DUMP, "waitForBroadcastBarrier()"); + synchronized (mDeliveryGroupPolicyIgnoredActions) { + mDeliveryGroupPolicyIgnoredActions.remove(broadcastAction); + } + } + + boolean shouldIgnoreDeliveryGroupPolicy(@Nullable String broadcastAction) { + if (broadcastAction == null) { + return false; + } + synchronized (mDeliveryGroupPolicyIgnoredActions) { + return mDeliveryGroupPolicyIgnoredActions.contains(broadcastAction); + } + } + + void dumpDeliveryGroupPolicyIgnoredActions(IndentingPrintWriter ipw) { + synchronized (mDeliveryGroupPolicyIgnoredActions) { + ipw.println(mDeliveryGroupPolicyIgnoredActions); + } + } + @Override @ReasonCode public int getBackgroundRestrictionExemptionReason(int uid) { @@ -18488,7 +18544,7 @@ public class ActivityManagerService extends IActivityManager.Stub @Override public int restartUserInBackground(final int userId) { - return mUserController.restartUser(userId, /* foreground */ false); + return mUserController.restartUser(userId, USER_START_MODE_BACKGROUND); } @Override diff --git a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java index be18c08f7ba5..94c15babb1e5 100644 --- a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java +++ b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java @@ -345,6 +345,10 @@ final class ActivityManagerShellCommand extends ShellCommand { return runWaitForBroadcastIdle(pw); case "wait-for-broadcast-barrier": return runWaitForBroadcastBarrier(pw); + case "set-ignore-delivery-group-policy": + return runSetIgnoreDeliveryGroupPolicy(pw); + case "clear-ignore-delivery-group-policy": + return runClearIgnoreDeliveryGroupPolicy(pw); case "compat": return runCompat(pw); case "refresh-settings-cache": @@ -2006,12 +2010,6 @@ final class ActivityManagerShellCommand extends ShellCommand { } int runSwitchUser(PrintWriter pw) throws RemoteException { - UserManager userManager = mInternal.mContext.getSystemService(UserManager.class); - final int userSwitchable = userManager.getUserSwitchability(); - if (userSwitchable != UserManager.SWITCHABILITY_STATUS_OK) { - getErrPrintWriter().println("Error: " + userSwitchable); - return -1; - } boolean wait = false; String opt; while ((opt = getNextOption()) != null) { @@ -2024,6 +2022,14 @@ final class ActivityManagerShellCommand extends ShellCommand { } int userId = Integer.parseInt(getNextArgRequired()); + + UserManager userManager = mInternal.mContext.getSystemService(UserManager.class); + final int userSwitchable = userManager.getUserSwitchability(UserHandle.of(userId)); + if (userSwitchable != UserManager.SWITCHABILITY_STATUS_OK) { + getErrPrintWriter().println("Error: UserSwitchabilityResult=" + userSwitchable); + return -1; + } + boolean switched; Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "shell_runSwitchUser"); try { @@ -3145,6 +3151,18 @@ final class ActivityManagerShellCommand extends ShellCommand { return 0; } + int runSetIgnoreDeliveryGroupPolicy(PrintWriter pw) throws RemoteException { + final String broadcastAction = getNextArgRequired(); + mInternal.setIgnoreDeliveryGroupPolicy(broadcastAction); + return 0; + } + + int runClearIgnoreDeliveryGroupPolicy(PrintWriter pw) throws RemoteException { + final String broadcastAction = getNextArgRequired(); + mInternal.clearIgnoreDeliveryGroupPolicy(broadcastAction); + return 0; + } + int runRefreshSettingsCache() throws RemoteException { mInternal.refreshSettingsCache(); return 0; @@ -4029,7 +4047,10 @@ final class ActivityManagerShellCommand extends ShellCommand { + "background."); pw.println(" set-foreground-service-delegate [--user <USER_ID>] <PACKAGE> start|stop"); pw.println(" Start/stop an app's foreground service delegate."); - pw.println(); + pw.println(" set-ignore-delivery-group-policy <ACTION>"); + pw.println(" Start ignoring delivery group policy set for a broadcast action"); + pw.println(" clear-ignore-delivery-group-policy <ACTION>"); + pw.println(" Stop ignoring delivery group policy set for a broadcast action"); Intent.printIntentArgsHelp(pw, ""); } } diff --git a/services/core/java/com/android/server/am/BroadcastProcessQueue.java b/services/core/java/com/android/server/am/BroadcastProcessQueue.java index 15d2fa334dcf..632f6145c8d6 100644 --- a/services/core/java/com/android/server/am/BroadcastProcessQueue.java +++ b/services/core/java/com/android/server/am/BroadcastProcessQueue.java @@ -796,6 +796,7 @@ class BroadcastProcessQueue { */ private void updateRunnableAt() { final SomeArgs next = peekNextBroadcast(); + mRunnableAtInvalidated = false; if (next != null) { final BroadcastRecord r = (BroadcastRecord) next.arg1; final int index = next.argi1; diff --git a/services/core/java/com/android/server/am/BroadcastQueueModernImpl.java b/services/core/java/com/android/server/am/BroadcastQueueModernImpl.java index 6ba1b1fd13c5..eb5c03bec560 100644 --- a/services/core/java/com/android/server/am/BroadcastQueueModernImpl.java +++ b/services/core/java/com/android/server/am/BroadcastQueueModernImpl.java @@ -648,6 +648,9 @@ class BroadcastQueueModernImpl extends BroadcastQueue { } private void applyDeliveryGroupPolicy(@NonNull BroadcastRecord r) { + if (mService.shouldIgnoreDeliveryGroupPolicy(r.intent.getAction())) { + return; + } final int policy = (r.options != null) ? r.options.getDeliveryGroupPolicy() : BroadcastOptions.DELIVERY_GROUP_POLICY_ALL; final BroadcastConsumer broadcastConsumer; @@ -1685,6 +1688,12 @@ class BroadcastQueueModernImpl extends BroadcastQueue { ipw.decreaseIndent(); ipw.println(); + ipw.println(" Broadcasts with ignored delivery group policies:"); + ipw.increaseIndent(); + mService.dumpDeliveryGroupPolicyIgnoredActions(ipw); + ipw.decreaseIndent(); + ipw.println(); + if (dumpConstants) { mConstants.dump(ipw); } diff --git a/services/core/java/com/android/server/am/ContentProviderHelper.java b/services/core/java/com/android/server/am/ContentProviderHelper.java index 16055b9c44cd..d2fb7b55952d 100644 --- a/services/core/java/com/android/server/am/ContentProviderHelper.java +++ b/services/core/java/com/android/server/am/ContentProviderHelper.java @@ -22,6 +22,10 @@ import static android.os.Process.PROC_PARENS; import static android.os.Process.PROC_SPACE_TERM; import static android.os.Process.SYSTEM_UID; +import static com.android.internal.util.FrameworkStatsLog.GET_TYPE_ACCESSED_WITHOUT_PERMISSION; +import static com.android.internal.util.FrameworkStatsLog.GET_TYPE_ACCESSED_WITHOUT_PERMISSION__LOCATION__AM_CHECK_URI_PERMISSION; +import static com.android.internal.util.FrameworkStatsLog.GET_TYPE_ACCESSED_WITHOUT_PERMISSION__LOCATION__AM_ERROR; +import static com.android.internal.util.FrameworkStatsLog.GET_TYPE_ACCESSED_WITHOUT_PERMISSION__LOCATION__AM_FRAMEWORK_PERMISSION; import static com.android.internal.util.FrameworkStatsLog.PROVIDER_ACQUISITION_EVENT_REPORTED; import static com.android.internal.util.FrameworkStatsLog.PROVIDER_ACQUISITION_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_COLD; import static com.android.internal.util.FrameworkStatsLog.PROVIDER_ACQUISITION_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM; @@ -46,6 +50,7 @@ import android.content.ContentResolver; import android.content.Context; import android.content.IContentProvider; import android.content.Intent; +import android.content.PermissionChecker; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; @@ -1003,7 +1008,11 @@ public class ContentProviderHelper { }; mService.mHandler.postDelayed(providerNotResponding, 1000); try { - return holder.provider.getType(uri); + final String type = holder.provider.getType(uri); + if (type != null) { + backgroundLogging(callingUid, callingPid, userId, uri, holder, type); + } + return type; } finally { mService.mHandler.removeCallbacks(providerNotResponding); // We need to clear the identity to call removeContentProviderExternalUnchecked @@ -1060,6 +1069,10 @@ public class ContentProviderHelper { Binder.restoreCallingIdentity(identity); } resultCallback.sendResult(result); + final String type = result.getPairValue(); + if (type != null) { + backgroundLogging(callingUid, callingPid, userId, uri, holder, type); + } })); } else { resultCallback.sendResult(Bundle.EMPTY); @@ -1070,6 +1083,63 @@ public class ContentProviderHelper { } } + private void backgroundLogging(int callingUid, int callingPid, int userId, Uri uri, + ContentProviderHolder holder, String type) { + // Push the logging code in a different handlerThread. + try { + mService.mHandler.post(new Runnable() { + @Override + public void run() { + logGetTypeData(callingUid, callingPid, userId, + uri, holder, type); + } + }); + } catch (Exception e) { + // To ensure logging does not break the getType calls. + } + } + + // Utility function to log the getTypeData calls + private void logGetTypeData(int callingUid, int callingPid, int userId, Uri uri, + ContentProviderHolder holder, String type) { + try { + boolean checkUser = true; + final String authority = uri.getAuthority(); + if (isAuthorityRedirectedForCloneProfile(authority)) { + UserManagerInternal umInternal = + LocalServices.getService(UserManagerInternal.class); + UserInfo userInfo = umInternal.getUserInfo(userId); + + if (userInfo != null && userInfo.isCloneProfile()) { + userId = umInternal.getProfileParentId(userId); + checkUser = false; + } + } + final ProviderInfo cpi = holder.info; + final AttributionSource attributionSource = + new AttributionSource.Builder(callingUid).build(); + final String permissionCheck = + checkContentProviderPermission(cpi, callingPid, callingUid, + userId, checkUser, null); + if (permissionCheck != null) { + FrameworkStatsLog.write(GET_TYPE_ACCESSED_WITHOUT_PERMISSION, + GET_TYPE_ACCESSED_WITHOUT_PERMISSION__LOCATION__AM_FRAMEWORK_PERMISSION, + callingUid, authority, type); + } else if (cpi.forceUriPermissions + && holder.provider.checkUriPermission(attributionSource, + uri, callingUid, Intent.FLAG_GRANT_READ_URI_PERMISSION) + != PermissionChecker.PERMISSION_GRANTED) { + FrameworkStatsLog.write(GET_TYPE_ACCESSED_WITHOUT_PERMISSION, + GET_TYPE_ACCESSED_WITHOUT_PERMISSION__LOCATION__AM_CHECK_URI_PERMISSION, + callingUid, authority, type); + } + } catch (Exception e) { + FrameworkStatsLog.write(GET_TYPE_ACCESSED_WITHOUT_PERMISSION, + GET_TYPE_ACCESSED_WITHOUT_PERMISSION__LOCATION__AM_ERROR, callingUid, + uri.getAuthority(), type); + } + } + private boolean canClearIdentity(int callingPid, int callingUid, int userId) { if (UserHandle.getUserId(callingUid) == userId) { return true; diff --git a/services/core/java/com/android/server/am/OomAdjuster.java b/services/core/java/com/android/server/am/OomAdjuster.java index 66a8babe224e..64787577a43f 100644 --- a/services/core/java/com/android/server/am/OomAdjuster.java +++ b/services/core/java/com/android/server/am/OomAdjuster.java @@ -163,6 +163,7 @@ public class OomAdjuster { static final int OOM_ADJ_REASON_ALLOWLIST = 10; static final int OOM_ADJ_REASON_PROCESS_BEGIN = 11; static final int OOM_ADJ_REASON_PROCESS_END = 12; + static final int OOM_ADJ_REASON_SHORT_FGS_TIMEOUT = 13; @IntDef(prefix = {"OOM_ADJ_REASON_"}, value = {OOM_ADJ_REASON_NONE, OOM_ADJ_REASON_ACTIVITY, OOM_ADJ_REASON_FINISH_RECEIVER, @@ -170,7 +171,8 @@ public class OomAdjuster { OOM_ADJ_REASON_UNBIND_SERVICE, OOM_ADJ_REASON_START_SERVICE, OOM_ADJ_REASON_GET_PROVIDER, OOM_ADJ_REASON_REMOVE_PROVIDER, OOM_ADJ_REASON_UI_VISIBILITY, OOM_ADJ_REASON_ALLOWLIST, - OOM_ADJ_REASON_PROCESS_BEGIN, OOM_ADJ_REASON_PROCESS_END}) + OOM_ADJ_REASON_PROCESS_BEGIN, OOM_ADJ_REASON_PROCESS_END, + OOM_ADJ_REASON_SHORT_FGS_TIMEOUT}) @Retention(RetentionPolicy.SOURCE) public @interface OomAdjReason {} @@ -202,6 +204,7 @@ public class OomAdjuster { return AppProtoEnums.OOM_ADJ_REASON_PROCESS_BEGIN; case OOM_ADJ_REASON_PROCESS_END: return AppProtoEnums.OOM_ADJ_REASON_PROCESS_END; + case OOM_ADJ_REASON_SHORT_FGS_TIMEOUT: // TODO(short-service) add value to AppProtoEnums default: return AppProtoEnums.OOM_ADJ_REASON_UNKNOWN_TO_PROTO; } @@ -236,6 +239,8 @@ public class OomAdjuster { return OOM_ADJ_REASON_METHOD + "_processBegin"; case OOM_ADJ_REASON_PROCESS_END: return OOM_ADJ_REASON_METHOD + "_processEnd"; + case OOM_ADJ_REASON_SHORT_FGS_TIMEOUT: + return OOM_ADJ_REASON_METHOD + "_shortFgs"; default: return "_unknown"; } @@ -704,7 +709,9 @@ public class OomAdjuster { ConnectionRecord cr = psr.getConnectionAt(i); ProcessRecord service = (cr.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) != 0 ? cr.binding.service.isolationHostProc : cr.binding.service.app; - if (service == null || service == pr) { + if (service == null || service == pr + || ((service.mState.getMaxAdj() >= ProcessList.SYSTEM_ADJ) + && (service.mState.getMaxAdj() < FOREGROUND_APP_ADJ))) { continue; } containsCycle |= service.mState.isReachable(); @@ -724,7 +731,9 @@ public class OomAdjuster { for (int i = ppr.numberOfProviderConnections() - 1; i >= 0; i--) { ContentProviderConnection cpc = ppr.getProviderConnectionAt(i); ProcessRecord provider = cpc.provider.proc; - if (provider == null || provider == pr) { + if (provider == null || provider == pr + || ((provider.mState.getMaxAdj() >= ProcessList.SYSTEM_ADJ) + && (provider.mState.getMaxAdj() < FOREGROUND_APP_ADJ))) { continue; } containsCycle |= provider.mState.isReachable(); @@ -1957,25 +1966,37 @@ public class OomAdjuster { } } } - if (state.getCachedIsPreviousProcess() && state.getCachedHasActivities()) { - if (adj > PREVIOUS_APP_ADJ) { - // This was the previous process that showed UI to the user. - // We want to try to keep it around more aggressively, to give - // a good experience around switching between two apps. - adj = PREVIOUS_APP_ADJ; + // This was the previous process that showed UI to the user. We want to + // try to keep it around more aggressively, to give a good experience + // around switching between two apps. However, we don't want to keep the + // process in this privileged state indefinitely. Eventually, allow the + // app to be demoted to cached. + if ((state.getSetProcState() == PROCESS_STATE_LAST_ACTIVITY + && (state.getLastStateTime() + mConstants.MAX_PREVIOUS_TIME) < now)) { + procState = PROCESS_STATE_LAST_ACTIVITY; schedGroup = SCHED_GROUP_BACKGROUND; - state.setCached(false); - state.setAdjType("previous"); + state.setAdjType("previous-expired"); + adj = CACHED_APP_MIN_ADJ; if (DEBUG_OOM_ADJ_REASON || logUid == appUid) { - reportOomAdjMessageLocked(TAG_OOM_ADJ, "Raise adj to prev: " + app); + reportOomAdjMessageLocked(TAG_OOM_ADJ, "Expire prev adj: " + app); } - } - if (procState > PROCESS_STATE_LAST_ACTIVITY) { - procState = PROCESS_STATE_LAST_ACTIVITY; - state.setAdjType("previous"); - if (DEBUG_OOM_ADJ_REASON || logUid == appUid) { - reportOomAdjMessageLocked(TAG_OOM_ADJ, "Raise procstate to prev: " + app); + } else { + if (adj > PREVIOUS_APP_ADJ) { + adj = PREVIOUS_APP_ADJ; + schedGroup = SCHED_GROUP_BACKGROUND; + state.setCached(false); + state.setAdjType("previous"); + if (DEBUG_OOM_ADJ_REASON || logUid == appUid) { + reportOomAdjMessageLocked(TAG_OOM_ADJ, "Raise adj to prev: " + app); + } + } + if (procState > PROCESS_STATE_LAST_ACTIVITY) { + procState = PROCESS_STATE_LAST_ACTIVITY; + state.setAdjType("previous"); + if (DEBUG_OOM_ADJ_REASON || logUid == appUid) { + reportOomAdjMessageLocked(TAG_OOM_ADJ, "Raise procstate to prev: " + app); + } } } } diff --git a/services/core/java/com/android/server/am/ProcessStatsService.java b/services/core/java/com/android/server/am/ProcessStatsService.java index 438a2d4302af..bac9253d5b93 100644 --- a/services/core/java/com/android/server/am/ProcessStatsService.java +++ b/services/core/java/com/android/server/am/ProcessStatsService.java @@ -634,7 +634,6 @@ public final class ProcessStatsService extends IProcessStats.Stub { if (files != null) { String highWaterMarkStr = DateFormat.format("yyyy-MM-dd-HH-mm-ss", highWaterMarkMs).toString(); - ProcessStats stats = new ProcessStats(false); for (int i = files.size() - 1; i >= 0; i--) { String fileName = files.get(i); try { @@ -647,7 +646,7 @@ public final class ProcessStatsService extends IProcessStats.Stub { new File(fileName), ParcelFileDescriptor.MODE_READ_ONLY); InputStream is = new ParcelFileDescriptor.AutoCloseInputStream(pfd); - stats.reset(); + final ProcessStats stats = new ProcessStats(false); stats.read(is); is.close(); if (stats.mTimePeriodStartClock > newHighWaterMark) { diff --git a/services/core/java/com/android/server/am/SameProcessApplicationThread.java b/services/core/java/com/android/server/am/SameProcessApplicationThread.java index a3c011188539..62fd6e9d551b 100644 --- a/services/core/java/com/android/server/am/SameProcessApplicationThread.java +++ b/services/core/java/com/android/server/am/SameProcessApplicationThread.java @@ -18,6 +18,7 @@ package com.android.server.am; import android.annotation.NonNull; import android.app.IApplicationThread; +import android.app.ReceiverInfo; import android.content.IIntentReceiver; import android.content.Intent; import android.content.pm.ActivityInfo; @@ -26,6 +27,7 @@ import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; +import java.util.List; import java.util.Objects; /** @@ -70,4 +72,20 @@ public class SameProcessApplicationThread extends IApplicationThread.Default { } }); } + + @Override + public void scheduleReceiverList(List<ReceiverInfo> info) { + for (int i = 0; i < info.size(); i++) { + ReceiverInfo r = info.get(i); + if (r.registered) { + scheduleRegisteredReceiver(r.receiver, r.intent, + r.resultCode, r.data, r.extras, r.ordered, r.sticky, + r.sendingUser, r.processState); + } else { + scheduleReceiver(r.intent, r.activityInfo, r.compatInfo, + r.resultCode, r.data, r.extras, r.sync, + r.sendingUser, r.processState); + } + } + } } diff --git a/services/core/java/com/android/server/am/ServiceRecord.java b/services/core/java/com/android/server/am/ServiceRecord.java index ef195aa13354..05726f4c39eb 100644 --- a/services/core/java/com/android/server/am/ServiceRecord.java +++ b/services/core/java/com/android/server/am/ServiceRecord.java @@ -1416,7 +1416,21 @@ final class ServiceRecord extends Binder implements ComponentName.WithComponentN || !mShortFgsInfo.isCurrent()) { return false; } - return mShortFgsInfo.getTimeoutTime() < SystemClock.uptimeMillis(); + return mShortFgsInfo.getTimeoutTime() <= SystemClock.uptimeMillis(); + } + + /** + * @return true if it's a short FGS's procstate should be demoted. + */ + public boolean shouldDemoteShortFgsProcState() { + if (!isAppAlive()) { + return false; + } + if (!this.startRequested || !isShortFgs() || mShortFgsInfo == null + || !mShortFgsInfo.isCurrent()) { + return false; + } + return mShortFgsInfo.getProcStateDemoteTime() <= SystemClock.uptimeMillis(); } /** @@ -1431,7 +1445,7 @@ final class ServiceRecord extends Binder implements ComponentName.WithComponentN || !mShortFgsInfo.isCurrent()) { return false; } - return mShortFgsInfo.getAnrTime() < SystemClock.uptimeMillis(); + return mShortFgsInfo.getAnrTime() <= SystemClock.uptimeMillis(); } private boolean isAppAlive() { diff --git a/services/core/java/com/android/server/am/UserController.java b/services/core/java/com/android/server/am/UserController.java index aefa2f5bf66e..280256fb49d7 100644 --- a/services/core/java/com/android/server/am/UserController.java +++ b/services/core/java/com/android/server/am/UserController.java @@ -46,6 +46,11 @@ import static com.android.server.am.UserState.STATE_BOOTING; import static com.android.server.am.UserState.STATE_RUNNING_LOCKED; import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKED; import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKING; +import static com.android.server.pm.UserManagerInternal.USER_ASSIGNMENT_RESULT_FAILURE; +import static com.android.server.pm.UserManagerInternal.USER_START_MODE_BACKGROUND_VISIBLE; +import static com.android.server.pm.UserManagerInternal.USER_START_MODE_FOREGROUND; +import static com.android.server.pm.UserManagerInternal.userAssignmentResultToString; +import static com.android.server.pm.UserManagerInternal.userStartModeToString; import android.annotation.IntDef; import android.annotation.NonNull; @@ -119,6 +124,7 @@ import com.android.server.SystemServiceManager; import com.android.server.am.UserState.KeyEvictedCallback; import com.android.server.pm.UserManagerInternal; import com.android.server.pm.UserManagerInternal.UserLifecycleListener; +import com.android.server.pm.UserManagerInternal.UserStartMode; import com.android.server.pm.UserManagerService; import com.android.server.utils.Slogf; import com.android.server.utils.TimingsTraceAndSlog; @@ -903,14 +909,14 @@ class UserController implements Handler.Callback { }); } - int restartUser(final int userId, final boolean foreground) { + int restartUser(final int userId, @UserStartMode int userStartMode) { return stopUser(userId, /* force= */ true, /* allowDelayedLocking= */ false, /* stopUserCallback= */ null, new KeyEvictedCallback() { @Override public void keyEvicted(@UserIdInt int userId) { // Post to the same handler that this callback is called from to ensure // the user cleanup is complete before restarting. - mHandler.post(() -> UserController.this.startUser(userId, foreground)); + mHandler.post(() -> UserController.this.startUser(userId, userStartMode)); } }); } @@ -1267,7 +1273,7 @@ class UserController implements Handler.Callback { if (userStart.userId == userId) { Slogf.i(TAG, "resumePendingUserStart for" + userStart); mHandler.post(() -> startUser(userStart.userId, - userStart.isForeground, userStart.unlockListener)); + userStart.userStartMode, userStart.unlockListener)); handledUserStarts.add(userStart); } @@ -1450,7 +1456,7 @@ class UserController implements Handler.Callback { for (; i < profilesToStartSize && i < (getMaxRunningUsers() - 1); ++i) { // NOTE: this method is setting the profiles of the current user - which is always // assigned to the default display - startUser(profilesToStart.get(i).id, /* foreground= */ false); + startUser(profilesToStart.get(i).id, USER_START_MODE_BACKGROUND_VISIBLE); } if (i < profilesToStartSize) { Slogf.w(TAG, "More profiles than MAX_RUNNING_USERS"); @@ -1492,18 +1498,20 @@ class UserController implements Handler.Callback { return false; } - return startUserNoChecks(userId, Display.DEFAULT_DISPLAY, /* foreground= */ false, - /* unlockListener= */ null); + return startUserNoChecks(userId, Display.DEFAULT_DISPLAY, + USER_START_MODE_BACKGROUND_VISIBLE, /* unlockListener= */ null); } @VisibleForTesting - boolean startUser(final @UserIdInt int userId, final boolean foreground) { - return startUser(userId, foreground, null); + boolean startUser(@UserIdInt int userId, @UserStartMode int userStartMode) { + return startUser(userId, userStartMode, /* unlockListener= */ null); } /** * Start user, if its not already running. - * <p>The user will be brought to the foreground, if {@code foreground} parameter is set. + * + * <p>The user will be brought to the foreground, if {@code userStartMode} parameter is + * set to {@link UserManagerInternal#USER_START_MODE_FOREGROUND} * When starting the user, multiple intents will be broadcast in the following order:</p> * <ul> * <li>{@link Intent#ACTION_USER_STARTED} - sent to registered receivers of the new user @@ -1529,17 +1537,15 @@ class UserController implements Handler.Callback { * </ul> * * @param userId ID of the user to start - * @param foreground true if user should be brought to the foreground + * @param userStartMode user starting mode * @param unlockListener Listener to be informed when the user has started and unlocked. * @return true if the user has been successfully started */ - boolean startUser( - final @UserIdInt int userId, - final boolean foreground, + boolean startUser(@UserIdInt int userId, @UserStartMode int userStartMode, @Nullable IProgressListener unlockListener) { checkCallingPermission(INTERACT_ACROSS_USERS_FULL, "startUser"); - return startUserNoChecks(userId, Display.DEFAULT_DISPLAY, foreground, unlockListener); + return startUserNoChecks(userId, Display.DEFAULT_DISPLAY, userStartMode, unlockListener); } /** @@ -1572,7 +1578,7 @@ class UserController implements Handler.Callback { "Cannot use DEFAULT_DISPLAY"); try { - return startUserNoChecks(userId, displayId, /* foreground= */ false, + return startUserNoChecks(userId, displayId, USER_START_MODE_BACKGROUND_VISIBLE, /* unlockListener= */ null); } catch (RuntimeException e) { Slogf.e(TAG, "startUserOnSecondaryDisplay(%d, %d) failed: %s", userId, displayId, e); @@ -1580,26 +1586,29 @@ class UserController implements Handler.Callback { } } - private boolean startUserNoChecks(@UserIdInt int userId, int displayId, boolean foreground, - @Nullable IProgressListener unlockListener) { + private boolean startUserNoChecks(@UserIdInt int userId, int displayId, + @UserStartMode int userStartMode, @Nullable IProgressListener unlockListener) { TimingsTraceAndSlog t = new TimingsTraceAndSlog(); t.traceBegin("UserController.startUser-" + userId + (displayId == Display.DEFAULT_DISPLAY ? "" : "-display-" + displayId) - + "-" + (foreground ? "fg" : "bg")); + + "-" + (userStartMode == USER_START_MODE_FOREGROUND ? "fg" : "bg") + + "-start-mode-" + userStartMode); try { - return startUserInternal(userId, displayId, foreground, unlockListener, t); + return startUserInternal(userId, displayId, userStartMode, unlockListener, t); } finally { t.traceEnd(); } } - private boolean startUserInternal(@UserIdInt int userId, int displayId, boolean foreground, - @Nullable IProgressListener unlockListener, @NonNull TimingsTraceAndSlog t) { + private boolean startUserInternal(@UserIdInt int userId, int displayId, + @UserStartMode int userStartMode, @Nullable IProgressListener unlockListener, + TimingsTraceAndSlog t) { if (DEBUG_MU) { - Slogf.i(TAG, "Starting user %d on display %d%s", userId, displayId, - foreground ? " in foreground" : ""); + Slogf.i(TAG, "Starting user %d on display %d with mode %s", userId, displayId, + userStartModeToString(userStartMode)); } + boolean foreground = userStartMode == USER_START_MODE_FOREGROUND; boolean onSecondaryDisplay = displayId != Display.DEFAULT_DISPLAY; if (onSecondaryDisplay) { @@ -1664,13 +1673,13 @@ class UserController implements Handler.Callback { t.traceBegin("assignUserToDisplayOnStart"); int result = mInjector.getUserManagerInternal().assignUserToDisplayOnStart(userId, - userInfo.profileGroupId, foreground, displayId); + userInfo.profileGroupId, userStartMode, displayId); t.traceEnd(); - if (result == UserManagerInternal.USER_ASSIGNMENT_RESULT_FAILURE) { + if (result == USER_ASSIGNMENT_RESULT_FAILURE) { Slogf.e(TAG, "%s user(%d) / display (%d) assignment failed: %s", - (foreground ? "fg" : "bg"), userId, displayId, - UserManagerInternal.userAssignmentResultToString(result)); + userStartModeToString(userStartMode), userId, displayId, + userAssignmentResultToString(result)); return false; } @@ -1700,8 +1709,8 @@ class UserController implements Handler.Callback { } else if (uss.state == UserState.STATE_SHUTDOWN) { Slogf.i(TAG, "User #" + userId + " is shutting down - will start after full shutdown"); - mPendingUserStarts.add(new PendingUserStart(userId, - foreground, unlockListener)); + mPendingUserStarts.add(new PendingUserStart(userId, userStartMode, + unlockListener)); t.traceEnd(); // updateStartedUserArrayStarting return true; } @@ -1862,8 +1871,8 @@ class UserController implements Handler.Callback { /** * Start user, if its not already running, and bring it to foreground. */ - void startUserInForeground(final int targetUserId) { - boolean success = startUser(targetUserId, /* foreground */ true); + void startUserInForeground(@UserIdInt int targetUserId) { + boolean success = startUser(targetUserId, USER_START_MODE_FOREGROUND); if (!success) { mInjector.getWindowManager().setSwitchingUser(false); } @@ -3433,13 +3442,13 @@ class UserController implements Handler.Callback { */ private static class PendingUserStart { public final @UserIdInt int userId; - public final boolean isForeground; + public final @UserStartMode int userStartMode; public final IProgressListener unlockListener; - PendingUserStart(int userId, boolean foreground, + PendingUserStart(int userId, @UserStartMode int userStartMode, IProgressListener unlockListener) { this.userId = userId; - this.isForeground = foreground; + this.userStartMode = userStartMode; this.unlockListener = unlockListener; } @@ -3447,7 +3456,7 @@ class UserController implements Handler.Callback { public String toString() { return "PendingUserStart{" + "userId=" + userId - + ", isForeground=" + isForeground + + ", userStartMode=" + userStartModeToString(userStartMode) + ", unlockListener=" + unlockListener + '}'; } diff --git a/services/core/java/com/android/server/app/GameManagerService.java b/services/core/java/com/android/server/app/GameManagerService.java index cda18b07c02e..46d3ff1273ec 100644 --- a/services/core/java/com/android/server/app/GameManagerService.java +++ b/services/core/java/com/android/server/app/GameManagerService.java @@ -524,8 +524,8 @@ public final class GameManagerService extends IGameManagerService.Stub { private final ArrayMap<Integer, GameModeConfiguration> mModeConfigs = new ArrayMap<>(); // if adding new properties or make any of the below overridable, the method // copyAndApplyOverride should be updated accordingly - private boolean mPerfModeOptedIn = false; - private boolean mBatteryModeOptedIn = false; + private boolean mPerfModeOverridden = false; + private boolean mBatteryModeOverridden = false; private boolean mAllowDownscale = true; private boolean mAllowAngle = true; private boolean mAllowFpsOverride = true; @@ -542,8 +542,8 @@ public final class GameManagerService extends IGameManagerService.Stub { PackageManager.GET_META_DATA, userId); if (!parseInterventionFromXml(packageManager, ai, packageName) && ai.metaData != null) { - mPerfModeOptedIn = ai.metaData.getBoolean(METADATA_PERFORMANCE_MODE_ENABLE); - mBatteryModeOptedIn = ai.metaData.getBoolean(METADATA_BATTERY_MODE_ENABLE); + mPerfModeOverridden = ai.metaData.getBoolean(METADATA_PERFORMANCE_MODE_ENABLE); + mBatteryModeOverridden = 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); } @@ -595,9 +595,9 @@ public final class GameManagerService extends IGameManagerService.Stub { } else { final TypedArray array = resources.obtainAttributes(attributeSet, com.android.internal.R.styleable.GameModeConfig); - mPerfModeOptedIn = array.getBoolean( + mPerfModeOverridden = array.getBoolean( GameModeConfig_supportsPerformanceGameMode, false); - mBatteryModeOptedIn = array.getBoolean( + mBatteryModeOverridden = array.getBoolean( GameModeConfig_supportsBatteryGameMode, false); mAllowDownscale = array.getBoolean(GameModeConfig_allowGameDownscaling, @@ -610,8 +610,8 @@ public final class GameManagerService extends IGameManagerService.Stub { } } catch (NameNotFoundException | XmlPullParserException | IOException ex) { // set flag back to default values when parsing fails - mPerfModeOptedIn = false; - mBatteryModeOptedIn = false; + mPerfModeOverridden = false; + mBatteryModeOverridden = false; mAllowDownscale = true; mAllowAngle = true; mAllowFpsOverride = true; @@ -667,8 +667,8 @@ public final class GameManagerService extends IGameManagerService.Stub { GameModeConfiguration(KeyValueListParser parser) { mGameMode = parser.getInt(MODE_KEY, GameManager.GAME_MODE_UNSUPPORTED); - // isGameModeOptedIn() returns if an app will handle all of the changes necessary - // for a particular game mode. If so, the Android framework (i.e. + // willGamePerformOptimizations() returns if an app will handle all of the changes + // necessary for a particular game mode. If so, the Android framework (i.e. // GameManagerService) will not do anything for the app (like window scaling or // using ANGLE). mScaling = !mAllowDownscale || willGamePerformOptimizations(mGameMode) @@ -775,8 +775,8 @@ public final class GameManagerService extends IGameManagerService.Stub { * "com.android.app.gamemode.battery.enabled" with a value of "true" */ public boolean willGamePerformOptimizations(@GameMode int gameMode) { - return (mBatteryModeOptedIn && gameMode == GameManager.GAME_MODE_BATTERY) - || (mPerfModeOptedIn && gameMode == GameManager.GAME_MODE_PERFORMANCE); + return (mBatteryModeOverridden && gameMode == GameManager.GAME_MODE_BATTERY) + || (mPerfModeOverridden && gameMode == GameManager.GAME_MODE_PERFORMANCE); } private int getAvailableGameModesBitfield() { @@ -787,10 +787,10 @@ public final class GameManagerService extends IGameManagerService.Stub { field |= modeToBitmask(mode); } } - if (mBatteryModeOptedIn) { + if (mBatteryModeOverridden) { field |= modeToBitmask(GameManager.GAME_MODE_BATTERY); } - if (mPerfModeOptedIn) { + if (mPerfModeOverridden) { field |= modeToBitmask(GameManager.GAME_MODE_PERFORMANCE); } return field; @@ -814,14 +814,14 @@ public final class GameManagerService extends IGameManagerService.Stub { } /** - * Get an array of a package's opted-in game modes. + * Get an array of a package's overridden game modes. */ - public @GameMode int[] getOptedInGameModes() { - if (mBatteryModeOptedIn && mPerfModeOptedIn) { + public @GameMode int[] getOverriddenGameModes() { + if (mBatteryModeOverridden && mPerfModeOverridden) { return new int[]{GameManager.GAME_MODE_BATTERY, GameManager.GAME_MODE_PERFORMANCE}; - } else if (mBatteryModeOptedIn) { + } else if (mBatteryModeOverridden) { return new int[]{GameManager.GAME_MODE_BATTERY}; - } else if (mPerfModeOptedIn) { + } else if (mPerfModeOverridden) { return new int[]{GameManager.GAME_MODE_PERFORMANCE}; } else { return new int[]{}; @@ -864,18 +864,18 @@ public final class GameManagerService extends IGameManagerService.Stub { public boolean isActive() { synchronized (mModeConfigLock) { - return mModeConfigs.size() > 0 || mBatteryModeOptedIn || mPerfModeOptedIn; + return mModeConfigs.size() > 0 || mBatteryModeOverridden || mPerfModeOverridden; } } GamePackageConfiguration copyAndApplyOverride(GamePackageConfiguration overrideConfig) { GamePackageConfiguration copy = new GamePackageConfiguration(mPackageName); // if a game mode is overridden, we treat it with the highest priority and reset any - // opt-in game modes so that interventions are always executed. - copy.mPerfModeOptedIn = mPerfModeOptedIn && !(overrideConfig != null + // overridden game modes so that interventions are always executed. + copy.mPerfModeOverridden = mPerfModeOverridden && !(overrideConfig != null && overrideConfig.getGameModeConfiguration(GameManager.GAME_MODE_PERFORMANCE) != null); - copy.mBatteryModeOptedIn = mBatteryModeOptedIn && !(overrideConfig != null + copy.mBatteryModeOverridden = mBatteryModeOverridden && !(overrideConfig != null && overrideConfig.getGameModeConfiguration(GameManager.GAME_MODE_BATTERY) != null); @@ -1092,12 +1092,12 @@ public final class GameManagerService extends IGameManagerService.Stub { final @GameMode int activeGameMode = getGameModeFromSettingsUnchecked(packageName, userId); final GamePackageConfiguration config = getConfig(packageName, userId); if (config != null) { - final @GameMode int[] optedInGameModes = config.getOptedInGameModes(); + final @GameMode int[] overriddenGameModes = config.getOverriddenGameModes(); final @GameMode int[] availableGameModes = config.getAvailableGameModes(); GameModeInfo.Builder gameModeInfoBuilder = new GameModeInfo.Builder() .setActiveGameMode(activeGameMode) .setAvailableGameModes(availableGameModes) - .setOptedInGameModes(optedInGameModes) + .setOverriddenGameModes(overriddenGameModes) .setDownscalingAllowed(config.mAllowDownscale) .setFpsOverrideAllowed(config.mAllowFpsOverride); for (int gameMode : availableGameModes) { @@ -2059,7 +2059,7 @@ public final class GameManagerService extends IGameManagerService.Stub { if (atomTag == FrameworkStatsLog.GAME_MODE_INFO) { data.add( FrameworkStatsLog.buildStatsEvent(FrameworkStatsLog.GAME_MODE_INFO, uid, - gameModesToStatsdGameModes(config.getOptedInGameModes()), + gameModesToStatsdGameModes(config.getOverriddenGameModes()), gameModesToStatsdGameModes(config.getAvailableGameModes()))); } else if (atomTag == FrameworkStatsLog.GAME_MODE_CONFIGURATION) { for (int gameMode : config.getAvailableGameModes()) { diff --git a/services/core/java/com/android/server/appop/AppOpsCheckingServiceTracingDecorator.java b/services/core/java/com/android/server/appop/AppOpsCheckingServiceTracingDecorator.java new file mode 100644 index 000000000000..44360028704e --- /dev/null +++ b/services/core/java/com/android/server/appop/AppOpsCheckingServiceTracingDecorator.java @@ -0,0 +1,279 @@ +/* + * 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.appop; + +import android.annotation.NonNull; +import android.annotation.Nullable; +import android.annotation.UserIdInt; +import android.app.AppOpsManager; +import android.os.Trace; +import android.util.ArraySet; +import android.util.SparseBooleanArray; +import android.util.SparseIntArray; + +import java.io.PrintWriter; + +/** + * Surrounds all AppOpsCheckingServiceInterface method calls with Trace.traceBegin and + * Trace.traceEnd. These traces are used for performance testing. + */ +public class AppOpsCheckingServiceTracingDecorator implements AppOpsCheckingServiceInterface { + private static final long TRACE_TAG = Trace.TRACE_TAG_SYSTEM_SERVER; + private final AppOpsCheckingServiceInterface mService; + + AppOpsCheckingServiceTracingDecorator( + @NonNull AppOpsCheckingServiceInterface appOpsCheckingServiceInterface) { + mService = appOpsCheckingServiceInterface; + } + + @Override + public SparseIntArray getNonDefaultUidModes(int uid) { + Trace.traceBegin(TRACE_TAG, + "TaggedTracingAppOpsCheckingServiceInterfaceImpl#getNonDefaultUidModes"); + try { + return mService.getNonDefaultUidModes(uid); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } + + @Override + public int getUidMode(int uid, int op) { + Trace.traceBegin(TRACE_TAG, "TaggedTracingAppOpsCheckingServiceInterfaceImpl#getUidMode"); + try { + return mService.getUidMode(uid, op); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } + + @Override + public boolean setUidMode(int uid, int op, @AppOpsManager.Mode int mode) { + Trace.traceBegin(TRACE_TAG, "TaggedTracingAppOpsCheckingServiceInterfaceImpl#setUidMode"); + try { + return mService.setUidMode(uid, op, mode); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } + + @Override + public int getPackageMode(@NonNull String packageName, int op, @UserIdInt int userId) { + Trace.traceBegin(TRACE_TAG, + "TaggedTracingAppOpsCheckingServiceInterfaceImpl#getPackageMode"); + try { + return mService.getPackageMode(packageName, op, userId); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } + + @Override + public void setPackageMode(@NonNull String packageName, int op, @AppOpsManager.Mode int mode, + @UserIdInt int userId) { + Trace.traceBegin(TRACE_TAG, + "TaggedTracingAppOpsCheckingServiceInterfaceImpl#setPackageMode"); + try { + mService.setPackageMode(packageName, op, mode, userId); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } + + @Override + public boolean removePackage(@NonNull String packageName, @UserIdInt int userId) { + Trace.traceBegin(TRACE_TAG, + "TaggedTracingAppOpsCheckingServiceInterfaceImpl#removePackage"); + try { + return mService.removePackage(packageName, userId); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } + + @Override + public void removeUid(int uid) { + Trace.traceBegin(TRACE_TAG, + "TaggedTracingAppOpsCheckingServiceInterfaceImpl#removeUid"); + try { + mService.removeUid(uid); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } + + @Override + public boolean areUidModesDefault(int uid) { + Trace.traceBegin(TRACE_TAG, + "TaggedTracingAppOpsCheckingServiceInterfaceImpl#areUidModesDefault"); + try { + return mService.areUidModesDefault(uid); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } + + @Override + public boolean arePackageModesDefault(String packageName, @UserIdInt int userId) { + Trace.traceBegin(TRACE_TAG, + "TaggedTracingAppOpsCheckingServiceInterfaceImpl#arePackageModesDefault"); + try { + return mService.arePackageModesDefault(packageName, userId); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } + + @Override + public void clearAllModes() { + Trace.traceBegin(TRACE_TAG, + "TaggedTracingAppOpsCheckingServiceInterfaceImpl#clearAllModes"); + try { + mService.clearAllModes(); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } + + @Override + public void startWatchingOpModeChanged(@NonNull OnOpModeChangedListener changedListener, + int op) { + Trace.traceBegin(TRACE_TAG, + "TaggedTracingAppOpsCheckingServiceInterfaceImpl#startWatchingOpModeChanged"); + try { + mService.startWatchingOpModeChanged(changedListener, op); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } + + @Override + public void startWatchingPackageModeChanged(@NonNull OnOpModeChangedListener changedListener, + @NonNull String packageName) { + Trace.traceBegin(TRACE_TAG, + "TaggedTracingAppOpsCheckingServiceInterfaceImpl#startWatchingPackageModeChanged"); + try { + mService.startWatchingPackageModeChanged(changedListener, packageName); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } + + @Override + public void removeListener(@NonNull OnOpModeChangedListener changedListener) { + Trace.traceBegin(TRACE_TAG, + "TaggedTracingAppOpsCheckingServiceInterfaceImpl#removeListener"); + try { + mService.removeListener(changedListener); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } + + @Override + public ArraySet<OnOpModeChangedListener> getOpModeChangedListeners(int op) { + Trace.traceBegin(TRACE_TAG, + "TaggedTracingAppOpsCheckingServiceInterfaceImpl#getOpModeChangedListeners"); + try { + return mService.getOpModeChangedListeners(op); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } + + @Override + public ArraySet<OnOpModeChangedListener> getPackageModeChangedListeners( + @NonNull String packageName) { + Trace.traceBegin(TRACE_TAG, + "TaggedTracingAppOpsCheckingServiceInterfaceImpl#getPackageModeChangedListeners"); + try { + return mService.getPackageModeChangedListeners(packageName); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } + + @Override + public void notifyWatchersOfChange(int op, int uid) { + Trace.traceBegin(TRACE_TAG, + "TaggedTracingAppOpsCheckingServiceInterfaceImpl#notifyWatchersOfChange"); + try { + mService.notifyWatchersOfChange(op, uid); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } + + @Override + public void notifyOpChanged(@NonNull OnOpModeChangedListener changedListener, int op, int uid, + @Nullable String packageName) { + Trace.traceBegin(TRACE_TAG, + "TaggedTracingAppOpsCheckingServiceInterfaceImpl#notifyOpChanged"); + try { + mService.notifyOpChanged(changedListener, op, uid, packageName); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } + + @Override + public void notifyOpChangedForAllPkgsInUid(int op, int uid, boolean onlyForeground, + @Nullable OnOpModeChangedListener callbackToIgnore) { + Trace.traceBegin(TRACE_TAG, + "TaggedTracingAppOpsCheckingServiceInterfaceImpl#notifyOpChangedForAllPkgsInUid"); + try { + mService.notifyOpChangedForAllPkgsInUid(op, uid, onlyForeground, callbackToIgnore); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } + + @Override + public SparseBooleanArray evalForegroundUidOps(int uid, SparseBooleanArray foregroundOps) { + Trace.traceBegin(TRACE_TAG, + "TaggedTracingAppOpsCheckingServiceInterfaceImpl#evalForegroundUidOps"); + try { + return mService.evalForegroundUidOps(uid, foregroundOps); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } + + @Override + public SparseBooleanArray evalForegroundPackageOps(String packageName, + SparseBooleanArray foregroundOps, @UserIdInt int userId) { + Trace.traceBegin(TRACE_TAG, + "TaggedTracingAppOpsCheckingServiceInterfaceImpl#evalForegroundPackageOps"); + try { + return mService.evalForegroundPackageOps(packageName, foregroundOps, userId); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } + + @Override + public boolean dumpListeners(int dumpOp, int dumpUid, String dumpPackage, + PrintWriter printWriter) { + Trace.traceBegin(TRACE_TAG, + "TaggedTracingAppOpsCheckingServiceInterfaceImpl#dumpListeners"); + try { + return mService.dumpListeners(dumpOp, dumpUid, dumpPackage, printWriter); + } finally { + Trace.traceEnd(TRACE_TAG); + } + } +} diff --git a/services/core/java/com/android/server/appop/AppOpsServiceImpl.java b/services/core/java/com/android/server/appop/AppOpsServiceImpl.java index 70f3bcc64ef0..c3d2717ce795 100644 --- a/services/core/java/com/android/server/appop/AppOpsServiceImpl.java +++ b/services/core/java/com/android/server/appop/AppOpsServiceImpl.java @@ -44,6 +44,7 @@ import static android.app.AppOpsManager.OP_PLAY_AUDIO; import static android.app.AppOpsManager.OP_RECEIVE_AMBIENT_TRIGGER_AUDIO; import static android.app.AppOpsManager.OP_RECORD_AUDIO; import static android.app.AppOpsManager.OP_RECORD_AUDIO_HOTWORD; +import static android.app.AppOpsManager.OP_SCHEDULE_EXACT_ALARM; import static android.app.AppOpsManager.OP_VIBRATE; import static android.app.AppOpsManager.OnOpStartedListener.START_TYPE_FAILED; import static android.app.AppOpsManager.OnOpStartedListener.START_TYPE_STARTED; @@ -130,6 +131,8 @@ import com.android.modules.utils.TypedXmlSerializer; import com.android.server.LocalServices; import com.android.server.LockGuard; import com.android.server.SystemServerInitThreadPool; +import com.android.server.pm.UserManagerInternal; +import com.android.server.pm.permission.PermissionManagerServiceInternal; import com.android.server.pm.pkg.AndroidPackage; import com.android.server.pm.pkg.component.ParsedAttribution; @@ -163,12 +166,30 @@ class AppOpsServiceImpl implements AppOpsServiceInterface { static final String TAG = "AppOps"; static final boolean DEBUG = false; + /** + * Sentinel integer version to denote that there was no appops.xml found on boot. + * This will happen when a device boots with no existing userdata. + */ + private static final int NO_FILE_VERSION = -2; + + /** + * Sentinel integer version to denote that there was no version in the appops.xml found on boot. + * This means the file is coming from a build before versioning was added. + */ private static final int NO_VERSION = -1; + /** * Increment by one every time and add the corresponding upgrade logic in - * {@link #upgradeLocked(int)} below. The first version was 1 + * {@link #upgradeLocked(int)} below. The first version was 1. */ - private static final int CURRENT_VERSION = 1; + @VisibleForTesting + static final int CURRENT_VERSION = 2; + + /** + * This stores the version of appops.xml seen at boot. If this is smaller than + * {@link #CURRENT_VERSION}, then we will run {@link #upgradeLocked(int)} on startup. + */ + private int mVersionAtBoot = NO_FILE_VERSION; // Write at most every 30 minutes. static final long WRITE_DELAY = DEBUG ? 1000 : 30 * 60 * 1000; @@ -828,8 +849,8 @@ class AppOpsServiceImpl implements AppOpsServiceInterface { mSwitchedOps.put(switchCode, ArrayUtils.appendInt(mSwitchedOps.get(switchCode), switchedCode)); } - mAppOpsServiceInterface = - new AppOpsCheckingServiceImpl(this, this, handler, context, mSwitchedOps); + mAppOpsServiceInterface = new AppOpsCheckingServiceTracingDecorator( + new AppOpsCheckingServiceImpl(this, this, handler, context, mSwitchedOps)); mAppOpsRestrictions = new AppOpsRestrictionsImpl(context, handler, mAppOpsServiceInterface); @@ -936,6 +957,10 @@ class AppOpsServiceImpl implements AppOpsServiceInterface { @Override public void systemReady() { + synchronized (this) { + upgradeLocked(mVersionAtBoot); + } + mConstants.startMonitoring(mContext.getContentResolver()); mHistoricalRegistry.systemReady(mContext.getContentResolver()); @@ -3191,7 +3216,6 @@ class AppOpsServiceImpl implements AppOpsServiceInterface { @Override public void readState() { - int oldVersion = NO_VERSION; synchronized (mFile) { synchronized (this) { FileInputStream stream; @@ -3216,7 +3240,7 @@ class AppOpsServiceImpl implements AppOpsServiceInterface { throw new IllegalStateException("no start tag found"); } - oldVersion = parser.getAttributeInt(null, "v", NO_VERSION); + mVersionAtBoot = parser.getAttributeInt(null, "v", NO_VERSION); int outerDepth = parser.getDepth(); while ((type = parser.next()) != XmlPullParser.END_DOCUMENT @@ -3261,12 +3285,11 @@ class AppOpsServiceImpl implements AppOpsServiceInterface { } } } - synchronized (this) { - upgradeLocked(oldVersion); - } } - private void upgradeRunAnyInBackgroundLocked() { + @VisibleForTesting + @GuardedBy("this") + void upgradeRunAnyInBackgroundLocked() { for (int i = 0; i < mUidStates.size(); i++) { final UidState uidState = mUidStates.valueAt(i); if (uidState == null) { @@ -3303,8 +3326,45 @@ class AppOpsServiceImpl implements AppOpsServiceInterface { } } + /** + * The interpretation of the default mode - MODE_DEFAULT - for OP_SCHEDULE_EXACT_ALARM is + * changing. Simultaneously, we want to change this op's mode from MODE_DEFAULT to MODE_ALLOWED + * for already installed apps. For newer apps, it will stay as MODE_DEFAULT. + */ + @VisibleForTesting + @GuardedBy("this") + void upgradeScheduleExactAlarmLocked() { + final PermissionManagerServiceInternal pmsi = LocalServices.getService( + PermissionManagerServiceInternal.class); + final UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class); + final PackageManagerInternal pmi = getPackageManagerInternal(); + + final String[] packagesDeclaringPermission = pmsi.getAppOpPermissionPackages( + AppOpsManager.opToPermission(OP_SCHEDULE_EXACT_ALARM)); + final int[] userIds = umi.getUserIds(); + + for (final String pkg : packagesDeclaringPermission) { + for (int userId : userIds) { + final int uid = pmi.getPackageUid(pkg, 0, userId); + + UidState uidState = mUidStates.get(uid); + if (uidState == null) { + uidState = new UidState(uid); + mUidStates.put(uid, uidState); + } + final int oldMode = uidState.getUidMode(OP_SCHEDULE_EXACT_ALARM); + if (oldMode == AppOpsManager.opToDefaultMode(OP_SCHEDULE_EXACT_ALARM)) { + uidState.setUidMode(OP_SCHEDULE_EXACT_ALARM, MODE_ALLOWED); + } + } + // This appop is meant to be controlled at a uid level. So we leave package modes as + // they are. + } + } + + @GuardedBy("this") private void upgradeLocked(int oldVersion) { - if (oldVersion >= CURRENT_VERSION) { + if (oldVersion == NO_FILE_VERSION || oldVersion >= CURRENT_VERSION) { return; } Slog.d(TAG, "Upgrading app-ops xml from version " + oldVersion + " to " + CURRENT_VERSION); @@ -3313,6 +3373,9 @@ class AppOpsServiceImpl implements AppOpsServiceInterface { upgradeRunAnyInBackgroundLocked(); // fall through case 1: + upgradeScheduleExactAlarmLocked(); + // fall through + case 2: // for future upgrades } scheduleFastWriteLocked(); diff --git a/services/core/java/com/android/server/audio/AudioDeviceBroker.java b/services/core/java/com/android/server/audio/AudioDeviceBroker.java index 2fe06094bd88..418027fb37f6 100644 --- a/services/core/java/com/android/server/audio/AudioDeviceBroker.java +++ b/services/core/java/com/android/server/audio/AudioDeviceBroker.java @@ -1998,4 +1998,13 @@ import java.util.concurrent.atomic.AtomicBoolean; return mDeviceInventory.getDeviceSensorUuid(device); } } + + void dispatchPreferredMixerAttributesChangedCausedByDeviceRemoved(AudioDeviceInfo info) { + // Currently, only media usage will be allowed to set preferred mixer attributes + mAudioService.dispatchPreferredMixerAttributesChanged( + new AudioAttributes.Builder() + .setUsage(AudioAttributes.USAGE_MEDIA).build(), + info.getId(), + null /*mixerAttributes*/); + } } diff --git a/services/core/java/com/android/server/audio/AudioDeviceInventory.java b/services/core/java/com/android/server/audio/AudioDeviceInventory.java index c8f282fd576e..34457b09ce17 100644 --- a/services/core/java/com/android/server/audio/AudioDeviceInventory.java +++ b/services/core/java/com/android/server/audio/AudioDeviceInventory.java @@ -22,6 +22,7 @@ import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; import android.content.Intent; import android.media.AudioDeviceAttributes; +import android.media.AudioDeviceInfo; import android.media.AudioDevicePort; import android.media.AudioFormat; import android.media.AudioManager; @@ -532,6 +533,18 @@ public class AudioDeviceInventory { .set(MediaMetrics.Property.STATE, wdcs.mState == AudioService.CONNECTION_STATE_DISCONNECTED ? MediaMetrics.Value.DISCONNECTED : MediaMetrics.Value.CONNECTED); + AudioDeviceInfo info = null; + if (wdcs.mState == AudioService.CONNECTION_STATE_DISCONNECTED + && AudioSystem.DEVICE_OUT_ALL_USB_SET.contains( + wdcs.mAttributes.getInternalType())) { + for (AudioDeviceInfo deviceInfo : AudioManager.getDevicesStatic( + AudioManager.GET_DEVICES_OUTPUTS)) { + if (deviceInfo.getInternalType() == wdcs.mAttributes.getInternalType()) { + info = deviceInfo; + break; + } + } + } synchronized (mDevicesLock) { if ((wdcs.mState == AudioService.CONNECTION_STATE_DISCONNECTED) && DEVICE_OVERRIDE_A2DP_ROUTE_ON_PLUG_SET.contains(type)) { @@ -556,6 +569,11 @@ public class AudioDeviceInventory { if (type == AudioSystem.DEVICE_OUT_HDMI) { mDeviceBroker.checkVolumeCecOnHdmiConnection(wdcs.mState, wdcs.mCaller); } + if (wdcs.mState == AudioService.CONNECTION_STATE_DISCONNECTED + && AudioSystem.DEVICE_OUT_ALL_USB_SET.contains( + wdcs.mAttributes.getInternalType())) { + mDeviceBroker.dispatchPreferredMixerAttributesChangedCausedByDeviceRemoved(info); + } sendDeviceConnectionIntent(type, wdcs.mState, wdcs.mAttributes.getAddress(), wdcs.mAttributes.getName()); updateAudioRoutes(type, wdcs.mState); diff --git a/services/core/java/com/android/server/audio/AudioService.java b/services/core/java/com/android/server/audio/AudioService.java index aa8ee3d2d8aa..6fbd7b6a5f9d 100644 --- a/services/core/java/com/android/server/audio/AudioService.java +++ b/services/core/java/com/android/server/audio/AudioService.java @@ -27,6 +27,7 @@ import static android.provider.Settings.Secure.VOLUME_HUSH_MUTE; import static android.provider.Settings.Secure.VOLUME_HUSH_OFF; import static android.provider.Settings.Secure.VOLUME_HUSH_VIBRATE; +import static com.android.server.audio.SoundDoseHelper.ACTION_CHECK_MUSIC_ACTIVE; import static com.android.server.utils.EventLogger.Event.ALOGE; import static com.android.server.utils.EventLogger.Event.ALOGI; import static com.android.server.utils.EventLogger.Event.ALOGW; @@ -42,12 +43,10 @@ import android.annotation.UserIdInt; import android.app.ActivityManager; import android.app.ActivityManagerInternal; import android.app.ActivityThread; -import android.app.AlarmManager; import android.app.AppGlobals; import android.app.AppOpsManager; import android.app.IUidObserver; import android.app.NotificationManager; -import android.app.PendingIntent; import android.app.role.OnRoleHoldersChangedListener; import android.app.role.RoleManager; import android.bluetooth.BluetoothAdapter; @@ -89,6 +88,7 @@ import android.media.AudioFormat; import android.media.AudioHalVersionInfo; import android.media.AudioManager; import android.media.AudioManagerInternal; +import android.media.AudioMixerAttributes; import android.media.AudioPlaybackConfiguration; import android.media.AudioRecordingConfiguration; import android.media.AudioRoutesInfo; @@ -105,6 +105,7 @@ import android.media.ICommunicationDeviceDispatcher; import android.media.IDeviceVolumeBehaviorDispatcher; import android.media.IMuteAwaitConnectionCallback; import android.media.IPlaybackConfigDispatcher; +import android.media.IPreferredMixerAttributesDispatcher; import android.media.IRecordingConfigDispatcher; import android.media.IRingtonePlayer; import android.media.ISpatializerCallback; @@ -166,7 +167,6 @@ import android.util.ArrayMap; import android.util.ArraySet; import android.util.IntArray; import android.util.Log; -import android.util.MathUtils; import android.util.PrintWriterPrinter; import android.util.Slog; import android.util.SparseArray; @@ -332,7 +332,7 @@ public class AudioService extends IAudioService.Stub private static final int SENDMSG_QUEUE = 2; // AudioHandler messages - private static final int MSG_SET_DEVICE_VOLUME = 0; + /*package*/ static final int MSG_SET_DEVICE_VOLUME = 0; private static final int MSG_PERSIST_VOLUME = 1; private static final int MSG_PERSIST_VOLUME_GROUP = 2; private static final int MSG_PERSIST_RINGER_MODE = 3; @@ -342,13 +342,8 @@ public class AudioService extends IAudioService.Stub private static final int MSG_SET_FORCE_USE = 8; private static final int MSG_BT_HEADSET_CNCT_FAILED = 9; private static final int MSG_SET_ALL_VOLUMES = 10; - private static final int MSG_CHECK_MUSIC_ACTIVE = 11; - private static final int MSG_CONFIGURE_SAFE_MEDIA_VOLUME = 12; - private static final int MSG_CONFIGURE_SAFE_MEDIA_VOLUME_FORCED = 13; - private static final int MSG_PERSIST_SAFE_VOLUME_STATE = 14; private static final int MSG_UNLOAD_SOUND_EFFECTS = 15; private static final int MSG_SYSTEM_READY = 16; - private static final int MSG_PERSIST_MUSIC_ACTIVE_MS = 17; private static final int MSG_UNMUTE_STREAM = 18; private static final int MSG_DYN_POLICY_MIX_STATE_UPDATE = 19; private static final int MSG_INDICATE_SYSTEM_READY = 20; @@ -383,6 +378,10 @@ public class AudioService extends IAudioService.Stub private static final int MSG_FOLD_UPDATE = 49; private static final int MSG_RESET_SPATIALIZER = 50; private static final int MSG_NO_LOG_FOR_PLAYER_I = 51; + private static final int MSG_DISPATCH_PREFERRED_MIXER_ATTRIBUTES = 52; + + /** Messages handled by the {@link SoundDoseHelper}. */ + /*package*/ static final int SAFE_MEDIA_VOLUME_MSG_START = 1000; // start of messages handled under wakelock // these messages can only be queued, i.e. sent with queueMsgUnderWakeLock(), @@ -399,6 +398,9 @@ public class AudioService extends IAudioService.Stub // List of empty UIDs used to reset the active assistant list private static final int[] NO_ACTIVE_ASSISTANT_SERVICE_UIDS = new int[0]; + // check playback or record activity every 6 seconds for UIDs owning mode IN_COMMUNICATION + private static final int CHECK_MODE_FOR_UID_PERIOD_MS = 6000; + /** @see AudioSystemThread */ private AudioSystemThread mAudioSystemThread; /** @see AudioHandler */ @@ -410,6 +412,10 @@ public class AudioService extends IAudioService.Stub return mStreamStates[stream].getIndex(device); } + /*package*/ VolumeStreamState getVssVolumeForStream(int stream) { + return mStreamStates[stream]; + } + /*package*/ int getMaxVssVolumeForStream(int stream) { return mStreamStates[stream].getMaxIndex(); } @@ -838,11 +844,6 @@ public class AudioService extends IAudioService.Stub private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED; - // Used when safe volume warning message display is requested by setStreamVolume(). In this - // case, the new requested volume, stream type and device are stored in mPendingVolumeCommand - // and used later when/if disableSafeMediaVolume() is called. - private StreamVolumeCommand mPendingVolumeCommand; - private PowerManager.WakeLock mAudioEventWakeLock; private final MediaFocusControl mMediaFocusControl; @@ -894,6 +895,8 @@ public class AudioService extends IAudioService.Stub private boolean mNavigationRepeatSoundEffectsEnabled; private boolean mHomeSoundEffectEnabled; + private final SoundDoseHelper mSoundDoseHelper; + @GuardedBy("mSettingsLock") private int mCurrentImeUid; @@ -1184,6 +1187,9 @@ public class AudioService extends IAudioService.Stub mAudioHandler = new AudioHandler(looper); } + mSoundDoseHelper = new SoundDoseHelper(this, mContext, mAudioHandler, mSettings, + mVolumeController); + AudioSystem.setErrorCallback(mAudioSystemCallback); updateAudioHalPids(); @@ -1199,16 +1205,6 @@ public class AudioService extends IAudioService.Stub new String("AudioService ctor"), 0); - mSafeMediaVolumeState = mSettings.getGlobalInt(mContentResolver, - Settings.Global.AUDIO_SAFE_VOLUME_STATE, - SAFE_MEDIA_VOLUME_NOT_CONFIGURED); - // The default safe volume index read here will be replaced by the actual value when - // the mcc is read by onConfigureSafeVolume() - mSafeMediaVolumeIndex = mContext.getResources().getInteger( - com.android.internal.R.integer.config_safe_media_volume_index) * 10; - - mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); - mUseFixedVolume = mContext.getResources().getBoolean( com.android.internal.R.bool.config_useFixedVolume); @@ -1285,9 +1281,7 @@ public class AudioService extends IAudioService.Stub // persistent data initVolumeGroupStates(); - // mSafeUsbMediaVolumeIndex must be initialized after createStreamStates() because it - // relies on audio policy having correct ranges for volume indexes. - mSafeUsbMediaVolumeIndex = getSafeUsbMediaVolumeIndex(); + mSoundDoseHelper.initSafeUsbMediaVolumeIndex(); // Call setRingerModeInt() to apply correct mute // state on streams affected by ringer mode. @@ -1442,14 +1436,7 @@ public class AudioService extends IAudioService.Stub mNm = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); - sendMsg(mAudioHandler, - MSG_CONFIGURE_SAFE_MEDIA_VOLUME_FORCED, - SENDMSG_REPLACE, - 0, - 0, - TAG, - SystemProperties.getBoolean("audio.safemedia.bypass", false) ? - 0 : SAFE_VOLUME_CONFIGURE_TIMEOUT_MS); + mSoundDoseHelper.configureSafeMediaVolume(/*forced=*/true, TAG); initA11yMonitoring(); @@ -1715,6 +1702,7 @@ public class AudioService extends IAudioService.Stub } mSpatializerHelper.reset(/* featureEnabled */ mHasSpatializerEffect); + mSoundDoseHelper.reset(); onIndicateSystemReady(); // indicate the end of reconfiguration phase to audio HAL @@ -1987,8 +1975,8 @@ public class AudioService extends IAudioService.Stub @AudioService.ConnectionState int state, String caller) { if (state == AudioService.CONNECTION_STATE_CONNECTED) { // DEVICE_OUT_HDMI is now connected - if (mSafeMediaVolumeDevices.contains(AudioSystem.DEVICE_OUT_HDMI)) { - scheduleMusicActiveCheck(); + if (mSoundDoseHelper.safeDevicesContains(AudioSystem.DEVICE_OUT_HDMI)) { + mSoundDoseHelper.scheduleMusicActiveCheck(); } if (isPlatformTelevision()) { @@ -3283,10 +3271,7 @@ public class AudioService extends IAudioService.Stub return; } - // reset any pending volume command - synchronized (mSafeMediaVolumeStateLock) { - mPendingVolumeCommand = null; - } + mSoundDoseHelper.invalidatPendingVolumeCommand(); flags &= ~AudioManager.FLAG_FIXED_VOLUME; if (streamTypeAlias == AudioSystem.STREAM_MUSIC && isFixedVolumeDevice(device)) { @@ -3295,10 +3280,8 @@ public class AudioService extends IAudioService.Stub // Always toggle between max safe volume and 0 for fixed volume devices where safe // volume is enforced, and max and 0 for the others. // This is simulated by stepping by the full allowed volume range - if (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE && - mSafeMediaVolumeDevices.contains(device)) { - step = safeMediaVolumeIndex(device); - } else { + step = mSoundDoseHelper.getSafeMediaVolumeIndex(device); + if (step < 0) { step = streamState.getMaxIndex(); } if (aliasIndex != 0) { @@ -3371,10 +3354,10 @@ public class AudioService extends IAudioService.Stub } } } - } else if ((direction == AudioManager.ADJUST_RAISE) && - !checkSafeMediaVolume(streamTypeAlias, aliasIndex + step, device)) { + } else if ((direction == AudioManager.ADJUST_RAISE) + && mSoundDoseHelper.raiseVolumeDisplaySafeMediaVolume(streamTypeAlias, + aliasIndex + step, device, flags)) { Log.e(TAG, "adjustStreamVolume() safe volume index = " + oldIndex); - mVolumeController.postDisplaySafeVolumeWarning(flags); } else if (!isFullVolumeDevice(device) && (streamState.adjustIndex(direction * step, device, caller, hasModifyAudioSettings) @@ -3545,29 +3528,6 @@ public class AudioService extends IAudioService.Stub Binder.restoreCallingIdentity(identity); } - // StreamVolumeCommand contains the information needed to defer the process of - // setStreamVolume() in case the user has to acknowledge the safe volume warning message. - static class StreamVolumeCommand { - public final int mStreamType; - public final int mIndex; - public final int mFlags; - public final int mDevice; - - StreamVolumeCommand(int streamType, int index, int flags, int device) { - mStreamType = streamType; - mIndex = index; - mFlags = flags; - mDevice = device; - } - - @Override - public String toString() { - return new StringBuilder().append("{streamType=").append(mStreamType).append(",index=") - .append(mIndex).append(",flags=").append(mFlags).append(",device=") - .append(mDevice).append('}').toString(); - } - } - private int getNewRingerMode(int stream, int index, int flags) { // setRingerMode does nothing if the device is single volume,so the value would be unchanged if (mIsSingleVolume) { @@ -3615,7 +3575,7 @@ public class AudioService extends IAudioService.Stub return false; } - private void onSetStreamVolume(int streamType, int index, int flags, int device, + /*package*/ void onSetStreamVolume(int streamType, int index, int flags, int device, String caller, boolean hasModifyAudioSettings) { final int stream = mStreamVolumeAlias[streamType]; setStreamVolumeInt(stream, index, device, false, caller, hasModifyAudioSettings); @@ -3959,7 +3919,7 @@ public class AudioService extends IAudioService.Stub updateHearingAidVolumeOnVoiceActivityUpdate(); } if (mMediaPlaybackActive.getAndSet(mediaActive) != mediaActive && mediaActive) { - scheduleMusicActiveCheck(); + mSoundDoseHelper.scheduleMusicActiveCheck(); } // Update playback active state for all apps in audio mode stack. // When the audio mode owner becomes active, replace any delayed MSG_UPDATE_AUDIO_MODE @@ -4205,71 +4165,64 @@ public class AudioService extends IAudioService.Stub return; } - synchronized (mSafeMediaVolumeStateLock) { - // reset any pending volume command - mPendingVolumeCommand = null; - - oldIndex = streamState.getIndex(device); + mSoundDoseHelper.invalidatPendingVolumeCommand(); - index = rescaleIndex(index * 10, streamType, streamTypeAlias); + oldIndex = streamState.getIndex(device); - if (streamTypeAlias == AudioSystem.STREAM_MUSIC - && AudioSystem.DEVICE_OUT_ALL_A2DP_SET.contains(device) - && (flags & AudioManager.FLAG_BLUETOOTH_ABS_VOLUME) == 0) { - if (DEBUG_VOL) { - Log.d(TAG, "setStreamVolume postSetAvrcpAbsoluteVolumeIndex index=" + index - + "stream=" + streamType); - } - mDeviceBroker.postSetAvrcpAbsoluteVolumeIndex(index / 10); - } else if (isAbsoluteVolumeDevice(device) - && ((flags & AudioManager.FLAG_ABSOLUTE_VOLUME) == 0)) { - AbsoluteVolumeDeviceInfo info = mAbsoluteVolumeDeviceInfoMap.get(device); + index = rescaleIndex(index * 10, streamType, streamTypeAlias); - dispatchAbsoluteVolumeChanged(streamType, info, index); + if (streamTypeAlias == AudioSystem.STREAM_MUSIC + && AudioSystem.DEVICE_OUT_ALL_A2DP_SET.contains(device) + && (flags & AudioManager.FLAG_BLUETOOTH_ABS_VOLUME) == 0) { + if (DEBUG_VOL) { + Log.d(TAG, "setStreamVolume postSetAvrcpAbsoluteVolumeIndex index=" + index + + "stream=" + streamType); } + mDeviceBroker.postSetAvrcpAbsoluteVolumeIndex(index / 10); + } else if (isAbsoluteVolumeDevice(device) + && ((flags & AudioManager.FLAG_ABSOLUTE_VOLUME) == 0)) { + AbsoluteVolumeDeviceInfo info = mAbsoluteVolumeDeviceInfoMap.get(device); - if (AudioSystem.isLeAudioDeviceType(device) - && streamType == getBluetoothContextualVolumeStream() - && (flags & AudioManager.FLAG_BLUETOOTH_ABS_VOLUME) == 0) { - if (DEBUG_VOL) { - Log.d(TAG, "adjustSreamVolume postSetLeAudioVolumeIndex index=" - + index + " stream=" + streamType); - } - mDeviceBroker.postSetLeAudioVolumeIndex(index, - mStreamStates[streamType].getMaxIndex(), streamType); - } + dispatchAbsoluteVolumeChanged(streamType, info, index); + } - if (device == AudioSystem.DEVICE_OUT_HEARING_AID - && streamType == getBluetoothContextualVolumeStream()) { - Log.i(TAG, "setStreamVolume postSetHearingAidVolumeIndex index=" + index - + " stream=" + streamType); - mDeviceBroker.postSetHearingAidVolumeIndex(index, streamType); + if (AudioSystem.isLeAudioDeviceType(device) + && streamType == getBluetoothContextualVolumeStream() + && (flags & AudioManager.FLAG_BLUETOOTH_ABS_VOLUME) == 0) { + if (DEBUG_VOL) { + Log.d(TAG, "adjustSreamVolume postSetLeAudioVolumeIndex index=" + + index + " stream=" + streamType); } + mDeviceBroker.postSetLeAudioVolumeIndex(index, mStreamStates[streamType].getMaxIndex(), + streamType); + } - flags &= ~AudioManager.FLAG_FIXED_VOLUME; - if (streamTypeAlias == AudioSystem.STREAM_MUSIC && isFixedVolumeDevice(device)) { - flags |= AudioManager.FLAG_FIXED_VOLUME; + if (device == AudioSystem.DEVICE_OUT_HEARING_AID + && streamType == getBluetoothContextualVolumeStream()) { + Log.i(TAG, "setStreamVolume postSetHearingAidVolumeIndex index=" + index + + " stream=" + streamType); + mDeviceBroker.postSetHearingAidVolumeIndex(index, streamType); + } - // volume is either 0 or max allowed for fixed volume devices - if (index != 0) { - if (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE && - mSafeMediaVolumeDevices.contains(device)) { - index = safeMediaVolumeIndex(device); - } else { - index = streamState.getMaxIndex(); - } + flags &= ~AudioManager.FLAG_FIXED_VOLUME; + if (streamTypeAlias == AudioSystem.STREAM_MUSIC && isFixedVolumeDevice(device)) { + flags |= AudioManager.FLAG_FIXED_VOLUME; + + // volume is either 0 or max allowed for fixed volume devices + if (index != 0) { + index = mSoundDoseHelper.getSafeMediaVolumeIndex(device); + if (index < 0) { + index = streamState.getMaxIndex(); } } + } - if (!checkSafeMediaVolume(streamTypeAlias, index, device)) { - mVolumeController.postDisplaySafeVolumeWarning(flags); - mPendingVolumeCommand = new StreamVolumeCommand( - streamType, index, flags, device); - } else { - onSetStreamVolume(streamType, index, flags, device, caller, hasModifyAudioSettings); - index = mStreamStates[streamType].getIndex(device); - } + if (!mSoundDoseHelper.willDisplayWarningAfterCheckVolume(streamType, index, device, + flags)) { + onSetStreamVolume(streamType, index, flags, device, caller, hasModifyAudioSettings); + index = mStreamStates[streamType].getIndex(device); } + synchronized (mHdmiClientLock) { if (streamTypeAlias == AudioSystem.STREAM_MUSIC && (oldIndex != index)) { @@ -5846,14 +5799,8 @@ public class AudioService extends IAudioService.Stub checkAllAliasStreamVolumes(); checkMuteAffectedStreams(); - synchronized (mSafeMediaVolumeStateLock) { - mMusicActiveMs = MathUtils.constrain(mSettings.getSecureIntForUser(mContentResolver, - Settings.Secure.UNSAFE_VOLUME_MUSIC_ACTIVE_MS, 0, UserHandle.USER_CURRENT), - 0, UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX); - if (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE) { - enforceSafeMediaVolume(TAG); - } - } + mSoundDoseHelper.restoreMusicActiveMs(); + mSoundDoseHelper.enforceSafeMediaVolumeIfActive(TAG); readVolumeGroupsSettings(); @@ -6189,139 +6136,6 @@ public class AudioService extends IAudioService.Stub return mContentResolver; } - private void scheduleMusicActiveCheck() { - synchronized (mSafeMediaVolumeStateLock) { - cancelMusicActiveCheck(); - mMusicActiveIntent = PendingIntent.getBroadcast(mContext, - REQUEST_CODE_CHECK_MUSIC_ACTIVE, - new Intent(ACTION_CHECK_MUSIC_ACTIVE), - PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); - mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, - SystemClock.elapsedRealtime() - + MUSIC_ACTIVE_POLL_PERIOD_MS, mMusicActiveIntent); - } - } - - private void cancelMusicActiveCheck() { - synchronized (mSafeMediaVolumeStateLock) { - if (mMusicActiveIntent != null) { - mAlarmManager.cancel(mMusicActiveIntent); - mMusicActiveIntent = null; - } - } - } - private void onCheckMusicActive(String caller) { - synchronized (mSafeMediaVolumeStateLock) { - if (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_INACTIVE) { - int device = getDeviceForStream(AudioSystem.STREAM_MUSIC); - if (mSafeMediaVolumeDevices.contains(device) - && mAudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, 0)) { - scheduleMusicActiveCheck(); - int index = mStreamStates[AudioSystem.STREAM_MUSIC].getIndex(device); - if (index > safeMediaVolumeIndex(device)) { - // Approximate cumulative active music time - long curTimeMs = SystemClock.elapsedRealtime(); - if (mLastMusicActiveTimeMs != 0) { - mMusicActiveMs += (int) (curTimeMs - mLastMusicActiveTimeMs); - } - mLastMusicActiveTimeMs = curTimeMs; - Log.i(TAG, "onCheckMusicActive() mMusicActiveMs: " + mMusicActiveMs); - if (mMusicActiveMs > UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX) { - setSafeMediaVolumeEnabled(true, caller); - mMusicActiveMs = 0; - } - saveMusicActiveMs(); - } - } else { - cancelMusicActiveCheck(); - mLastMusicActiveTimeMs = 0; - } - } - } - } - - private void saveMusicActiveMs() { - mAudioHandler.obtainMessage(MSG_PERSIST_MUSIC_ACTIVE_MS, mMusicActiveMs, 0).sendToTarget(); - } - - private int getSafeUsbMediaVolumeIndex() { - // determine UI volume index corresponding to the wanted safe gain in dBFS - int min = MIN_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]; - int max = MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]; - - mSafeUsbMediaVolumeDbfs = mContext.getResources().getInteger( - com.android.internal.R.integer.config_safe_media_volume_usb_mB) / 100.0f; - - while (Math.abs(max - min) > 1) { - int index = (max + min) / 2; - float gainDB = AudioSystem.getStreamVolumeDB( - AudioSystem.STREAM_MUSIC, index, AudioSystem.DEVICE_OUT_USB_HEADSET); - if (Float.isNaN(gainDB)) { - //keep last min in case of read error - break; - } else if (gainDB == mSafeUsbMediaVolumeDbfs) { - min = index; - break; - } else if (gainDB < mSafeUsbMediaVolumeDbfs) { - min = index; - } else { - max = index; - } - } - return min * 10; - } - - private void onConfigureSafeVolume(boolean force, String caller) { - synchronized (mSafeMediaVolumeStateLock) { - int mcc = mContext.getResources().getConfiguration().mcc; - if ((mMcc != mcc) || ((mMcc == 0) && force)) { - mSafeMediaVolumeIndex = mContext.getResources().getInteger( - com.android.internal.R.integer.config_safe_media_volume_index) * 10; - - mSafeUsbMediaVolumeIndex = getSafeUsbMediaVolumeIndex(); - - boolean safeMediaVolumeEnabled = - SystemProperties.getBoolean("audio.safemedia.force", false) - || mContext.getResources().getBoolean( - com.android.internal.R.bool.config_safe_media_volume_enabled); - - boolean safeMediaVolumeBypass = - SystemProperties.getBoolean("audio.safemedia.bypass", false); - - // The persisted state is either "disabled" or "active": this is the state applied - // next time we boot and cannot be "inactive" - int persistedState; - if (safeMediaVolumeEnabled && !safeMediaVolumeBypass) { - persistedState = SAFE_MEDIA_VOLUME_ACTIVE; - // The state can already be "inactive" here if the user has forced it before - // the 30 seconds timeout for forced configuration. In this case we don't reset - // it to "active". - if (mSafeMediaVolumeState != SAFE_MEDIA_VOLUME_INACTIVE) { - if (mMusicActiveMs == 0) { - mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_ACTIVE; - enforceSafeMediaVolume(caller); - } else { - // We have existing playback time recorded, already confirmed. - mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_INACTIVE; - mLastMusicActiveTimeMs = 0; - } - } - } else { - persistedState = SAFE_MEDIA_VOLUME_DISABLED; - mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_DISABLED; - } - mMcc = mcc; - sendMsg(mAudioHandler, - MSG_PERSIST_SAFE_VOLUME_STATE, - SENDMSG_QUEUE, - persistedState, - 0, - null, - 0); - } - } - } - /////////////////////////////////////////////////////////////////////////// // Internal methods /////////////////////////////////////////////////////////////////////////// @@ -6756,6 +6570,20 @@ public class AudioService extends IAudioService.Stub handler.sendMessageAtTime(handler.obtainMessage(msg, arg1, arg2, obj), time); } + private static void sendBundleMsg(Handler handler, int msg, + int existingMsgPolicy, int arg1, int arg2, Object obj, Bundle bundle, int delay) { + if (existingMsgPolicy == SENDMSG_REPLACE) { + handler.removeMessages(msg); + } else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) { + return; + } + + final long time = SystemClock.uptimeMillis() + delay; + Message message = handler.obtainMessage(msg, arg1, arg2, obj); + message.setData(bundle); + handler.sendMessageAtTime(message, time); + } + boolean checkAudioSettingsPermission(String method) { if (callingOrSelfHasAudioSettingsPermission()) { return true; @@ -7711,7 +7539,7 @@ public class AudioService extends IAudioService.Stub // 2 mSetModeLock // 3 mSettingsLock // 4 VolumeStreamState.class - private class VolumeStreamState { + /*package*/ class VolumeStreamState { private final int mStreamType; private int mIndexMin; // min index when user doesn't have permission to change audio settings @@ -8364,8 +8192,8 @@ public class AudioService extends IAudioService.Stub final VolumeStreamState streamState = mStreamStates[update.mStreamType]; if (update.hasVolumeIndex()) { int index = update.getVolumeIndex(); - if (!checkSafeMediaVolume(update.mStreamType, index, update.mDevice)) { - index = safeMediaVolumeIndex(update.mDevice); + if (!mSoundDoseHelper.checkSafeMediaVolume(update.mStreamType, index, update.mDevice)) { + index = mSoundDoseHelper.safeMediaVolumeIndex(update.mDevice); } streamState.setIndex(index, update.mDevice, update.mCaller, // trusted as index is always validated before message is posted @@ -8415,7 +8243,7 @@ public class AudioService extends IAudioService.Stub } /** Handles internal volume messages in separate volume thread. */ - private class AudioHandler extends Handler { + /*package*/ class AudioHandler extends Handler { AudioHandler() { super(); @@ -8462,12 +8290,6 @@ public class AudioService extends IAudioService.Stub mSettings.putGlobalInt(mContentResolver, Settings.Global.MODE_RINGER, ringerMode); } - private void onPersistSafeVolumeState(int state) { - mSettings.putGlobalInt(mContentResolver, - Settings.Global.AUDIO_SAFE_VOLUME_STATE, - state); - } - private void onNotifyVolumeEvent(@NonNull IAudioPolicyCallback apc, @AudioManager.VolumeAdjustment int direction) { try { @@ -8585,19 +8407,6 @@ public class AudioService extends IAudioService.Stub mSpatializerHelper.reset(/* featureEnabled */ mHasSpatializerEffect); break; - case MSG_CHECK_MUSIC_ACTIVE: - onCheckMusicActive((String) msg.obj); - break; - - case MSG_CONFIGURE_SAFE_MEDIA_VOLUME_FORCED: - case MSG_CONFIGURE_SAFE_MEDIA_VOLUME: - onConfigureSafeVolume((msg.what == MSG_CONFIGURE_SAFE_MEDIA_VOLUME_FORCED), - (String) msg.obj); - break; - case MSG_PERSIST_SAFE_VOLUME_STATE: - onPersistSafeVolumeState(msg.arg1); - break; - case MSG_SYSTEM_READY: onSystemReady(); break; @@ -8610,13 +8419,6 @@ public class AudioService extends IAudioService.Stub onAccessoryPlugMediaUnmute(msg.arg1); break; - case MSG_PERSIST_MUSIC_ACTIVE_MS: - final int musicActiveMs = msg.arg1; - mSettings.putSecureIntForUser(mContentResolver, - Settings.Secure.UNSAFE_VOLUME_MUSIC_ACTIVE_MS, musicActiveMs, - UserHandle.USER_CURRENT); - break; - case MSG_UNMUTE_STREAM: onUnmuteStream(msg.arg1, msg.arg2); break; @@ -8746,6 +8548,16 @@ public class AudioService extends IAudioService.Stub case MSG_NO_LOG_FOR_PLAYER_I: mPlaybackMonitor.ignorePlayerIId(msg.arg1); break; + + case MSG_DISPATCH_PREFERRED_MIXER_ATTRIBUTES: + onDispatchPreferredMixerAttributesChanged(msg.getData(), msg.arg1); + break; + + default: + if (msg.what >= SAFE_MEDIA_VOLUME_MSG_START) { + // msg could be for the SoundDoseHelper + mSoundDoseHelper.handleMessage(msg); + } } } } @@ -8862,8 +8674,8 @@ public class AudioService extends IAudioService.Stub /** only public for mocking/spying, do not call outside of AudioService */ @VisibleForTesting public void checkMusicActive(int deviceType, String caller) { - if (mSafeMediaVolumeDevices.contains(deviceType)) { - scheduleMusicActiveCheck(); + if (mSoundDoseHelper.safeDevicesContains(deviceType)) { + mSoundDoseHelper.scheduleMusicActiveCheck(); } } @@ -8997,7 +8809,8 @@ public class AudioService extends IAudioService.Stub } } } else if (action.equals(ACTION_CHECK_MUSIC_ACTIVE)) { - onCheckMusicActive(ACTION_CHECK_MUSIC_ACTIVE); + mSoundDoseHelper.onCheckMusicActive(ACTION_CHECK_MUSIC_ACTIVE, + mAudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, 0)); } } } // end class AudioServiceBroadcastReceiver @@ -9883,13 +9696,7 @@ public class AudioService extends IAudioService.Stub // reading new configuration "safely" (i.e. under try catch) in case anything // goes wrong. Configuration config = context.getResources().getConfiguration(); - sendMsg(mAudioHandler, - MSG_CONFIGURE_SAFE_MEDIA_VOLUME, - SENDMSG_REPLACE, - 0, - 0, - TAG, - 0); + mSoundDoseHelper.configureSafeMediaVolume(/*forced*/false, TAG); boolean cameraSoundForced = readCameraSoundForced(); synchronized (mSettingsLock) { @@ -9947,143 +9754,10 @@ public class AudioService extends IAudioService.Stub return mDeviceBroker.startWatchingRoutes(observer); } - - //========================================================================================== - // Safe media volume management. - // MUSIC stream volume level is limited when headphones are connected according to safety - // regulation. When the user attempts to raise the volume above the limit, a warning is - // displayed and the user has to acknowlegde before the volume is actually changed. - // The volume index corresponding to the limit is stored in config_safe_media_volume_index - // property. Platforms with a different limit must set this property accordingly in their - // overlay. - //========================================================================================== - - // mSafeMediaVolumeState indicates whether the media volume is limited over headphones. - // It is SAFE_MEDIA_VOLUME_NOT_CONFIGURED at boot time until a network service is connected - // or the configure time is elapsed. It is then set to SAFE_MEDIA_VOLUME_ACTIVE or - // SAFE_MEDIA_VOLUME_DISABLED according to country option. If not SAFE_MEDIA_VOLUME_DISABLED, it - // can be set to SAFE_MEDIA_VOLUME_INACTIVE by calling AudioService.disableSafeMediaVolume() - // (when user opts out). - private static final int SAFE_MEDIA_VOLUME_NOT_CONFIGURED = 0; - private static final int SAFE_MEDIA_VOLUME_DISABLED = 1; - private static final int SAFE_MEDIA_VOLUME_INACTIVE = 2; // confirmed - private static final int SAFE_MEDIA_VOLUME_ACTIVE = 3; // unconfirmed - private int mSafeMediaVolumeState; - private final Object mSafeMediaVolumeStateLock = new Object(); - - private int mMcc = 0; - // mSafeMediaVolumeIndex is the cached value of config_safe_media_volume_index property - private int mSafeMediaVolumeIndex; - // mSafeUsbMediaVolumeDbfs is the cached value of the config_safe_media_volume_usb_mB - // property, divided by 100.0. - private float mSafeUsbMediaVolumeDbfs; - // mSafeUsbMediaVolumeIndex is used for USB Headsets and is the music volume UI index - // corresponding to a gain of mSafeUsbMediaVolumeDbfs (defaulting to -37dB) in audio - // flinger mixer. - // We remove -22 dBs from the theoretical -15dB to account for the EQ + bass boost - // amplification when both effects are on with all band gains at maximum. - // This level corresponds to a loudness of 85 dB SPL for the warning to be displayed when - // the headset is compliant to EN 60950 with a max loudness of 100dB SPL. - private int mSafeUsbMediaVolumeIndex; - // mSafeMediaVolumeDevices lists the devices for which safe media volume is enforced, - /*package*/ final Set<Integer> mSafeMediaVolumeDevices = new HashSet<>( - Arrays.asList(AudioSystem.DEVICE_OUT_WIRED_HEADSET, - AudioSystem.DEVICE_OUT_WIRED_HEADPHONE, AudioSystem.DEVICE_OUT_USB_HEADSET)); - // mMusicActiveMs is the cumulative time of music activity since safe volume was disabled. - // When this time reaches UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX, the safe media volume is re-enabled - // automatically. mMusicActiveMs is rounded to a multiple of MUSIC_ACTIVE_POLL_PERIOD_MS. - private int mMusicActiveMs; - private long mLastMusicActiveTimeMs = 0; - private PendingIntent mMusicActiveIntent = null; - private AlarmManager mAlarmManager; - - private static final int UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX = (20 * 3600 * 1000); // 20 hours - private static final int MUSIC_ACTIVE_POLL_PERIOD_MS = 60000; // 1 minute polling interval - private static final int SAFE_VOLUME_CONFIGURE_TIMEOUT_MS = 30000; // 30s after boot completed - // check playback or record activity every 6 seconds for UIDs owning mode IN_COMMUNICATION - private static final int CHECK_MODE_FOR_UID_PERIOD_MS = 6000; - - private static final String ACTION_CHECK_MUSIC_ACTIVE = - AudioService.class.getSimpleName() + ".CHECK_MUSIC_ACTIVE"; - private static final int REQUEST_CODE_CHECK_MUSIC_ACTIVE = 1; - - private int safeMediaVolumeIndex(int device) { - if (!mSafeMediaVolumeDevices.contains(device)) { - return MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]; - } - if (device == AudioSystem.DEVICE_OUT_USB_HEADSET) { - return mSafeUsbMediaVolumeIndex; - } else { - return mSafeMediaVolumeIndex; - } - } - - private void setSafeMediaVolumeEnabled(boolean on, String caller) { - synchronized (mSafeMediaVolumeStateLock) { - if ((mSafeMediaVolumeState != SAFE_MEDIA_VOLUME_NOT_CONFIGURED) && - (mSafeMediaVolumeState != SAFE_MEDIA_VOLUME_DISABLED)) { - if (on && (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_INACTIVE)) { - mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_ACTIVE; - enforceSafeMediaVolume(caller); - } else if (!on && (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE)) { - mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_INACTIVE; - mMusicActiveMs = 1; // nonzero = confirmed - mLastMusicActiveTimeMs = 0; - saveMusicActiveMs(); - scheduleMusicActiveCheck(); - } - } - } - } - - private void enforceSafeMediaVolume(String caller) { - VolumeStreamState streamState = mStreamStates[AudioSystem.STREAM_MUSIC]; - Set<Integer> devices = mSafeMediaVolumeDevices; - - for (int device : devices) { - int index = streamState.getIndex(device); - if (index > safeMediaVolumeIndex(device)) { - streamState.setIndex(safeMediaVolumeIndex(device), device, caller, - true /*hasModifyAudioSettings*/); - sendMsg(mAudioHandler, - MSG_SET_DEVICE_VOLUME, - SENDMSG_QUEUE, - device, - 0, - streamState, - 0); - } - } - } - - private boolean checkSafeMediaVolume(int streamType, int index, int device) { - synchronized (mSafeMediaVolumeStateLock) { - if ((mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE) - && (mStreamVolumeAlias[streamType] == AudioSystem.STREAM_MUSIC) - && (mSafeMediaVolumeDevices.contains(device)) - && (index > safeMediaVolumeIndex(device))) { - return false; - } - return true; - } - } - @Override public void disableSafeMediaVolume(String callingPackage) { enforceVolumeController("disable the safe media volume"); - synchronized (mSafeMediaVolumeStateLock) { - final long identity = Binder.clearCallingIdentity(); - setSafeMediaVolumeEnabled(false, callingPackage); - Binder.restoreCallingIdentity(identity); - if (mPendingVolumeCommand != null) { - onSetStreamVolume(mPendingVolumeCommand.mStreamType, - mPendingVolumeCommand.mIndex, - mPendingVolumeCommand.mFlags, - mPendingVolumeCommand.mDevice, - callingPackage, true /*hasModifyAudioSettings*/); - mPendingVolumeCommand = null; - } - } + mSoundDoseHelper.disableSafeMediaVolume(callingPackage); } //========================================================================================== @@ -10411,15 +10085,8 @@ public class AudioService extends IAudioService.Stub pw.println("\nOther state:"); pw.print(" mVolumeController="); pw.println(mVolumeController); - pw.print(" mSafeMediaVolumeState="); - pw.println(safeMediaVolumeStateToString(mSafeMediaVolumeState)); - pw.print(" mSafeMediaVolumeIndex="); pw.println(mSafeMediaVolumeIndex); - pw.print(" mSafeUsbMediaVolumeIndex="); pw.println(mSafeUsbMediaVolumeIndex); - pw.print(" mSafeUsbMediaVolumeDbfs="); pw.println(mSafeUsbMediaVolumeDbfs); + mSoundDoseHelper.dump(pw); pw.print(" sIndependentA11yVolume="); pw.println(sIndependentA11yVolume); - pw.print(" mPendingVolumeCommand="); pw.println(mPendingVolumeCommand); - pw.print(" mMusicActiveMs="); pw.println(mMusicActiveMs); - pw.print(" mMcc="); pw.println(mMcc); pw.print(" mCameraSoundForced="); pw.println(isCameraSoundForced()); pw.print(" mHasVibrator="); pw.println(mHasVibrator); pw.print(" mVolumePolicy="); pw.println(mVolumePolicy); @@ -10520,16 +10187,6 @@ public class AudioService extends IAudioService.Stub private static final String mMetricsId = MediaMetrics.Name.AUDIO_SERVICE + MediaMetrics.SEPARATOR; - private static String safeMediaVolumeStateToString(int state) { - switch(state) { - case SAFE_MEDIA_VOLUME_NOT_CONFIGURED: return "SAFE_MEDIA_VOLUME_NOT_CONFIGURED"; - case SAFE_MEDIA_VOLUME_DISABLED: return "SAFE_MEDIA_VOLUME_DISABLED"; - case SAFE_MEDIA_VOLUME_INACTIVE: return "SAFE_MEDIA_VOLUME_INACTIVE"; - case SAFE_MEDIA_VOLUME_ACTIVE: return "SAFE_MEDIA_VOLUME_ACTIVE"; - } - return null; - } - // Inform AudioFlinger of our device's low RAM attribute private static void readAndSetLowRamDevice() { @@ -10609,7 +10266,14 @@ public class AudioService extends IAudioService.Stub } } - public class VolumeController { + /** Interface used for enforcing the safe hearing standard. */ + public interface ISafeHearingVolumeController { + /** Displays an instructional safeguard as required by the safe hearing standard. */ + void postDisplaySafeVolumeWarning(int flags); + } + + /** Wrapper which encapsulates the {@link IVolumeController} functionality. */ + public class VolumeController implements ISafeHearingVolumeController { private static final String TAG = "VolumeController"; private IVolumeController mController; @@ -10696,6 +10360,7 @@ public class AudioService extends IAudioService.Stub return "VolumeController(" + asBinder() + ",mVisible=" + mVisible + ")"; } + @Override public void postDisplaySafeVolumeWarning(int flags) { if (mController == null) return; @@ -11352,6 +11017,125 @@ public class AudioService extends IAudioService.Stub } } + /** + * @see AudioManager#setPreferredMixerAttributes( + * AudioAttributes, AudioDeviceInfo, AudioMixerAttributes) + */ + public int setPreferredMixerAttributes(AudioAttributes attributes, + int portId, AudioMixerAttributes mixerAttributes) { + Objects.requireNonNull(attributes); + Objects.requireNonNull(mixerAttributes); + if (!checkAudioSettingsPermission("setPreferredMixerAttributes()")) { + return AudioSystem.PERMISSION_DENIED; + } + final int uid = Binder.getCallingUid(); + final int pid = Binder.getCallingPid(); + int status = AudioSystem.SUCCESS; + final long token = Binder.clearCallingIdentity(); + try { + final String logString = TextUtils.formatSimple( + "setPreferredMixerAttributes u/pid:%d/%d attr:%s mixerAttributes:%s portId:%d", + uid, pid, attributes.toString(), mixerAttributes.toString(), portId); + sDeviceLogger.enqueue(new EventLogger.StringEvent(logString).printLog(TAG)); + + status = mAudioSystem.setPreferredMixerAttributes( + attributes, portId, uid, mixerAttributes); + if (status == AudioSystem.SUCCESS) { + dispatchPreferredMixerAttributesChanged(attributes, portId, mixerAttributes); + } else { + Log.e(TAG, TextUtils.formatSimple("Error %d in %s)", status, logString)); + } + } finally { + Binder.restoreCallingIdentity(token); + } + return status; + } + + /** + * @see AudioManager#clearPreferredMixerAttributes(AudioAttributes, AudioDeviceInfo) + */ + public int clearPreferredMixerAttributes(AudioAttributes attributes, int portId) { + Objects.requireNonNull(attributes); + if (!checkAudioSettingsPermission("clearPreferredMixerAttributes()")) { + return AudioSystem.PERMISSION_DENIED; + } + final int uid = Binder.getCallingUid(); + final int pid = Binder.getCallingPid(); + int status = AudioSystem.SUCCESS; + final long token = Binder.clearCallingIdentity(); + try { + final String logString = TextUtils.formatSimple( + "clearPreferredMixerAttributes u/pid:%d/%d attr:%s", + uid, pid, attributes.toString()); + sDeviceLogger.enqueue(new EventLogger.StringEvent(logString).printLog(TAG)); + + status = mAudioSystem.clearPreferredMixerAttributes(attributes, portId, uid); + if (status == AudioSystem.SUCCESS) { + dispatchPreferredMixerAttributesChanged(attributes, portId, null /*mixerAttr*/); + } else { + Log.e(TAG, TextUtils.formatSimple("Error %d in %s)", status, logString)); + } + } finally { + Binder.restoreCallingIdentity(token); + } + return status; + } + + void dispatchPreferredMixerAttributesChanged( + AudioAttributes attr, int deviceId, AudioMixerAttributes mixerAttr) { + Bundle bundle = new Bundle(); + bundle.putParcelable(KEY_AUDIO_ATTRIBUTES, attr); + bundle.putParcelable(KEY_AUDIO_MIXER_ATTRIBUTES, mixerAttr); + sendBundleMsg(mAudioHandler, MSG_DISPATCH_PREFERRED_MIXER_ATTRIBUTES, SENDMSG_QUEUE, + deviceId, 0, null, bundle, 0); + } + + final RemoteCallbackList<IPreferredMixerAttributesDispatcher> mPrefMixerAttrDispatcher = + new RemoteCallbackList<IPreferredMixerAttributesDispatcher>(); + private static final String KEY_AUDIO_ATTRIBUTES = "audio_attributes"; + private static final String KEY_AUDIO_MIXER_ATTRIBUTES = "audio_mixer_attributes"; + + /** @see AudioManager#addOnPreferredMixerAttributesChangedListener( + * Executor, AudioManager.OnPreferredMixerAttributesChangedListener) + */ + public void registerPreferredMixerAttributesDispatcher( + @Nullable IPreferredMixerAttributesDispatcher dispatcher) { + if (dispatcher == null) { + return; + } + mPrefMixerAttrDispatcher.register(dispatcher); + } + + /** @see AudioManager#removeOnPreferredMixerAttributesChangedListener( + * AudioManager.OnPreferredMixerAttributesChangedListener) + */ + public void unregisterPreferredMixerAttributesDispatcher( + @Nullable IPreferredMixerAttributesDispatcher dispatcher) { + if (dispatcher == null) { + return; + } + mPrefMixerAttrDispatcher.unregister(dispatcher); + } + + protected void onDispatchPreferredMixerAttributesChanged(Bundle data, int deviceId) { + final int nbDispathers = mPrefMixerAttrDispatcher.beginBroadcast(); + final AudioAttributes attr = data.getParcelable( + KEY_AUDIO_ATTRIBUTES, AudioAttributes.class); + final AudioMixerAttributes mixerAttr = data.getParcelable( + KEY_AUDIO_MIXER_ATTRIBUTES, AudioMixerAttributes.class); + for (int i = 0; i < nbDispathers; i++) { + try { + mPrefMixerAttrDispatcher.getBroadcastItem(i) + .dispatchPrefMixerAttributesChanged(attr, deviceId, mixerAttr); + } catch (RemoteException e) { + Log.e(TAG, "Can't call dispatchPrefMixerAttributesChanged() " + + "IPreferredMixerAttributesDispatcher " + + mPrefMixerAttrDispatcher.getBroadcastItem(i).asBinder(), e); + } + } + mPrefMixerAttrDispatcher.finishBroadcast(); + } + private final Object mExtVolumeControllerLock = new Object(); private IAudioPolicyCallback mExtVolumeController; private void setExtVolumeController(IAudioPolicyCallback apc) { @@ -11427,8 +11211,8 @@ public class AudioService extends IAudioService.Stub } public List<AudioRecordingConfiguration> getActiveRecordingConfigurations() { - final boolean isPrivileged = - (PackageManager.PERMISSION_GRANTED == mContext.checkCallingPermission( + final boolean isPrivileged = Binder.getCallingUid() == Process.SYSTEM_UID + || (PackageManager.PERMISSION_GRANTED == mContext.checkCallingPermission( android.Manifest.permission.MODIFY_AUDIO_ROUTING)); return mRecordMonitor.getActiveRecordingConfigurations(isPrivileged); } diff --git a/services/core/java/com/android/server/audio/AudioSystemAdapter.java b/services/core/java/com/android/server/audio/AudioSystemAdapter.java index c3754eb3e44c..1d25e31ab8e2 100644 --- a/services/core/java/com/android/server/audio/AudioSystemAdapter.java +++ b/services/core/java/com/android/server/audio/AudioSystemAdapter.java @@ -20,7 +20,10 @@ import android.annotation.NonNull; import android.annotation.Nullable; import android.media.AudioAttributes; import android.media.AudioDeviceAttributes; +import android.media.AudioMixerAttributes; import android.media.AudioSystem; +import android.media.ISoundDose; +import android.media.ISoundDoseCallback; import android.media.audiopolicy.AudioMix; import android.os.SystemClock; import android.util.Log; @@ -495,6 +498,45 @@ public class AudioSystemAdapter implements AudioSystem.RoutingUpdateCallback, } /** + * Same as {@link AudioSystem#getSoundDoseInterface(ISoundDoseCallback)} + * @param callback + * @return + */ + public ISoundDose getSoundDoseInterface(ISoundDoseCallback callback) { + return AudioSystem.getSoundDoseInterface(callback); + } + + /** + * Same as + * {@link AudioSystem#setPreferredMixerAttributes( + * AudioAttributes, int, int, AudioMixerAttributes)} + * @param attributes + * @param mixerAttributes + * @param uid + * @param portId + * @return + */ + public int setPreferredMixerAttributes( + @NonNull AudioAttributes attributes, + int portId, + int uid, + @NonNull AudioMixerAttributes mixerAttributes) { + return AudioSystem.setPreferredMixerAttributes(attributes, portId, uid, mixerAttributes); + } + + /** + * Same as {@link AudioSystem#clearPreferredMixerAttributes(AudioAttributes, int, int)} + * @param attributes + * @param uid + * @param portId + * @return + */ + public int clearPreferredMixerAttributes( + @NonNull AudioAttributes attributes, int portId, int uid) { + return AudioSystem.clearPreferredMixerAttributes(attributes, portId, uid); + } + + /** * Part of AudioService dump * @param pw */ diff --git a/services/core/java/com/android/server/audio/SoundDoseHelper.java b/services/core/java/com/android/server/audio/SoundDoseHelper.java new file mode 100644 index 000000000000..0d0de8ad2886 --- /dev/null +++ b/services/core/java/com/android/server/audio/SoundDoseHelper.java @@ -0,0 +1,577 @@ +/* + * 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.audio; + +import static com.android.server.audio.AudioService.MAX_STREAM_VOLUME; +import static com.android.server.audio.AudioService.MIN_STREAM_VOLUME; +import static com.android.server.audio.AudioService.MSG_SET_DEVICE_VOLUME; +import static com.android.server.audio.AudioService.SAFE_MEDIA_VOLUME_MSG_START; + +import android.annotation.NonNull; +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.media.AudioSystem; +import android.media.ISoundDose; +import android.media.ISoundDoseCallback; +import android.media.SoundDoseRecord; +import android.os.Binder; +import android.os.Message; +import android.os.RemoteException; +import android.os.SystemClock; +import android.os.SystemProperties; +import android.os.UserHandle; +import android.provider.Settings; +import android.util.Log; +import android.util.MathUtils; + +import com.android.internal.annotations.GuardedBy; +import com.android.server.audio.AudioService.AudioHandler; +import com.android.server.audio.AudioService.ISafeHearingVolumeController; + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Safe media volume management. + * MUSIC stream volume level is limited when headphones are connected according to safety + * regulation. When the user attempts to raise the volume above the limit, a warning is + * displayed and the user has to acknowledge before the volume is actually changed. + * The volume index corresponding to the limit is stored in config_safe_media_volume_index + * property. Platforms with a different limit must set this property accordingly in their + * overlay. + */ +public class SoundDoseHelper { + private static final String TAG = "AS.SoundDoseHelper"; + + /*package*/ static final String ACTION_CHECK_MUSIC_ACTIVE = + AudioService.class.getSimpleName() + ".CHECK_MUSIC_ACTIVE"; + + /** Flag to enable/disable the sound dose computation. */ + private static final boolean USE_CSD_FOR_SAFE_HEARING = false; + + // mSafeMediaVolumeState indicates whether the media volume is limited over headphones. + // It is SAFE_MEDIA_VOLUME_NOT_CONFIGURED at boot time until a network service is connected + // or the configure time is elapsed. It is then set to SAFE_MEDIA_VOLUME_ACTIVE or + // SAFE_MEDIA_VOLUME_DISABLED according to country option. If not SAFE_MEDIA_VOLUME_DISABLED, it + // can be set to SAFE_MEDIA_VOLUME_INACTIVE by calling AudioService.disableSafeMediaVolume() + // (when user opts out). + private static final int SAFE_MEDIA_VOLUME_NOT_CONFIGURED = 0; + private static final int SAFE_MEDIA_VOLUME_DISABLED = 1; + private static final int SAFE_MEDIA_VOLUME_INACTIVE = 2; // confirmed + private static final int SAFE_MEDIA_VOLUME_ACTIVE = 3; // unconfirmed + + private static final int MSG_CONFIGURE_SAFE_MEDIA_VOLUME = SAFE_MEDIA_VOLUME_MSG_START + 1; + private static final int MSG_PERSIST_SAFE_VOLUME_STATE = SAFE_MEDIA_VOLUME_MSG_START + 2; + private static final int MSG_PERSIST_MUSIC_ACTIVE_MS = SAFE_MEDIA_VOLUME_MSG_START + 3; + + private static final int UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX = (20 * 3600 * 1000); // 20 hours + + // 30s after boot completed + private static final int SAFE_VOLUME_CONFIGURE_TIMEOUT_MS = 30000; + + private static final int MUSIC_ACTIVE_POLL_PERIOD_MS = 60000; // 1 minute polling interval + private static final int REQUEST_CODE_CHECK_MUSIC_ACTIVE = 1; + + private static final float CUSTOM_RS2_VALUE = 90; + + private int mMcc = 0; + + final Object mSafeMediaVolumeStateLock = new Object(); + private int mSafeMediaVolumeState; + + // Used when safe volume warning message display is requested by setStreamVolume(). In this + // case, the new requested volume, stream type and device are stored in mPendingVolumeCommand + // and used later when/if disableSafeMediaVolume() is called. + private StreamVolumeCommand mPendingVolumeCommand; + + // mSafeMediaVolumeIndex is the cached value of config_safe_media_volume_index property + private int mSafeMediaVolumeIndex; + // mSafeUsbMediaVolumeDbfs is the cached value of the config_safe_media_volume_usb_mB + // property, divided by 100.0. + private float mSafeUsbMediaVolumeDbfs; + + // mSafeUsbMediaVolumeIndex is used for USB Headsets and is the music volume UI index + // corresponding to a gain of mSafeUsbMediaVolumeDbfs (defaulting to -37dB) in audio + // flinger mixer. + // We remove -22 dBs from the theoretical -15dB to account for the EQ + bass boost + // amplification when both effects are on with all band gains at maximum. + // This level corresponds to a loudness of 85 dB SPL for the warning to be displayed when + // the headset is compliant to EN 60950 with a max loudness of 100dB SPL. + private int mSafeUsbMediaVolumeIndex; + // mSafeMediaVolumeDevices lists the devices for which safe media volume is enforced, + private final Set<Integer> mSafeMediaVolumeDevices = new HashSet<>( + Arrays.asList(AudioSystem.DEVICE_OUT_WIRED_HEADSET, + AudioSystem.DEVICE_OUT_WIRED_HEADPHONE, AudioSystem.DEVICE_OUT_USB_HEADSET)); + + + // mMusicActiveMs is the cumulative time of music activity since safe volume was disabled. + // When this time reaches UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX, the safe media volume is re-enabled + // automatically. mMusicActiveMs is rounded to a multiple of MUSIC_ACTIVE_POLL_PERIOD_MS. + private int mMusicActiveMs; + private long mLastMusicActiveTimeMs = 0; + private PendingIntent mMusicActiveIntent = null; + private final AlarmManager mAlarmManager; + + @NonNull private final AudioService mAudioService; + @NonNull private final SettingsAdapter mSettings; + @NonNull private final AudioHandler mAudioHandler; + @NonNull private final ISafeHearingVolumeController mVolumeController; + + private ISoundDose mSoundDose; + private float mCurrentCsd = 0.f; + private final List<SoundDoseRecord> mDoseRecords = new ArrayList<>(); + + private final Context mContext; + + private final ISoundDoseCallback.Stub mSoundDoseCallback = new ISoundDoseCallback.Stub() { + public void onMomentaryExposure(float currentMel, int deviceId) { + Log.w(TAG, "DeviceId " + deviceId + " triggered momentary exposure with value: " + + currentMel); + } + + public void onNewCsdValue(float currentCsd, SoundDoseRecord[] records) { + Log.i(TAG, "onNewCsdValue: " + currentCsd); + mCurrentCsd = currentCsd; + mDoseRecords.addAll(Arrays.asList(records)); + for (SoundDoseRecord record : records) { + Log.i(TAG, " new record: csd=" + record.value + + " averageMel=" + record.averageMel + " timestamp=" + record.timestamp + + " duration=" + record.duration); + } + } + }; + + SoundDoseHelper(@NonNull AudioService audioService, Context context, + @NonNull AudioHandler audioHandler, + @NonNull SettingsAdapter settings, + @NonNull ISafeHearingVolumeController volumeController) { + mAudioService = audioService; + mAudioHandler = audioHandler; + mSettings = settings; + mVolumeController = volumeController; + + mContext = context; + + mSafeMediaVolumeState = mSettings.getGlobalInt(audioService.getContentResolver(), + Settings.Global.AUDIO_SAFE_VOLUME_STATE, 0); + + // The default safe volume index read here will be replaced by the actual value when + // the mcc is read by onConfigureSafeVolume() + mSafeMediaVolumeIndex = mContext.getResources().getInteger( + com.android.internal.R.integer.config_safe_media_volume_index) * 10; + + mAlarmManager = (AlarmManager) mContext.getSystemService( + Context.ALARM_SERVICE); + + initCsd(); + } + + /*package*/ int safeMediaVolumeIndex(int device) { + if (!mSafeMediaVolumeDevices.contains(device)) { + return MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]; + } + if (device == AudioSystem.DEVICE_OUT_USB_HEADSET) { + return mSafeUsbMediaVolumeIndex; + } else { + return mSafeMediaVolumeIndex; + } + } + + /*package*/ void restoreMusicActiveMs() { + synchronized (mSafeMediaVolumeStateLock) { + mMusicActiveMs = MathUtils.constrain( + mSettings.getSecureIntForUser(mAudioService.getContentResolver(), + Settings.Secure.UNSAFE_VOLUME_MUSIC_ACTIVE_MS, 0, + UserHandle.USER_CURRENT), + 0, UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX); + } + } + + /*package*/ void enforceSafeMediaVolumeIfActive(String caller) { + synchronized (mSafeMediaVolumeStateLock) { + if (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE) { + enforceSafeMediaVolume(caller); + } + } + } + + /*package*/ void enforceSafeMediaVolume(String caller) { + AudioService.VolumeStreamState streamState = mAudioService.getVssVolumeForStream( + AudioSystem.STREAM_MUSIC); + Set<Integer> devices = mSafeMediaVolumeDevices; + + for (int device : devices) { + int index = streamState.getIndex(device); + int safeIndex = safeMediaVolumeIndex(device); + if (index > safeIndex) { + streamState.setIndex(safeIndex, device, caller, true /*hasModifyAudioSettings*/); + mAudioHandler.sendMessageAtTime( + mAudioHandler.obtainMessage(MSG_SET_DEVICE_VOLUME, device, /*arg2=*/0, + streamState), /*delay=*/0); + } + } + } + + /*package*/ boolean checkSafeMediaVolume(int streamType, int index, int device) { + boolean result; + synchronized (mSafeMediaVolumeStateLock) { + result = checkSafeMediaVolume_l(streamType, index, device); + } + return result; + } + + @GuardedBy("mSafeMediaVolumeStateLock") + private boolean checkSafeMediaVolume_l(int streamType, int index, int device) { + return (mSafeMediaVolumeState != SAFE_MEDIA_VOLUME_ACTIVE) + || (AudioService.mStreamVolumeAlias[streamType] != AudioSystem.STREAM_MUSIC) + || (!mSafeMediaVolumeDevices.contains(device)) + || (index <= safeMediaVolumeIndex(device)) + || USE_CSD_FOR_SAFE_HEARING; + } + + /*package*/ boolean willDisplayWarningAfterCheckVolume(int streamType, int index, int device, + int flags) { + synchronized (mSafeMediaVolumeStateLock) { + if (!checkSafeMediaVolume_l(streamType, index, device)) { + mVolumeController.postDisplaySafeVolumeWarning(flags); + mPendingVolumeCommand = new StreamVolumeCommand( + streamType, index, flags, device); + return true; + } + } + return false; + } + + /*package*/ void disableSafeMediaVolume(String callingPackage) { + synchronized (mSafeMediaVolumeStateLock) { + final long identity = Binder.clearCallingIdentity(); + setSafeMediaVolumeEnabled(false, callingPackage); + Binder.restoreCallingIdentity(identity); + + if (mPendingVolumeCommand != null) { + mAudioService.onSetStreamVolume(mPendingVolumeCommand.mStreamType, + mPendingVolumeCommand.mIndex, + mPendingVolumeCommand.mFlags, + mPendingVolumeCommand.mDevice, + callingPackage, true /*hasModifyAudioSettings*/); + mPendingVolumeCommand = null; + } + } + } + + /*package*/ void scheduleMusicActiveCheck() { + synchronized (mSafeMediaVolumeStateLock) { + cancelMusicActiveCheck(); + if (!USE_CSD_FOR_SAFE_HEARING) { + mMusicActiveIntent = PendingIntent.getBroadcast(mContext, + REQUEST_CODE_CHECK_MUSIC_ACTIVE, + new Intent(ACTION_CHECK_MUSIC_ACTIVE), + PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); + mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, + SystemClock.elapsedRealtime() + + MUSIC_ACTIVE_POLL_PERIOD_MS, mMusicActiveIntent); + } + } + } + + /*package*/ void onCheckMusicActive(String caller, boolean isStreamActive) { + synchronized (mSafeMediaVolumeStateLock) { + if (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_INACTIVE) { + int device = mAudioService.getDeviceForStream(AudioSystem.STREAM_MUSIC); + if (mSafeMediaVolumeDevices.contains(device) && isStreamActive) { + scheduleMusicActiveCheck(); + int index = mAudioService.getVssVolumeForDevice(AudioSystem.STREAM_MUSIC, + device); + if (index > safeMediaVolumeIndex(device)) { + // Approximate cumulative active music time + long curTimeMs = SystemClock.elapsedRealtime(); + if (mLastMusicActiveTimeMs != 0) { + mMusicActiveMs += (int) (curTimeMs - mLastMusicActiveTimeMs); + } + mLastMusicActiveTimeMs = curTimeMs; + Log.i(TAG, "onCheckMusicActive() mMusicActiveMs: " + mMusicActiveMs); + if (mMusicActiveMs > UNSAFE_VOLUME_MUSIC_ACTIVE_MS_MAX) { + setSafeMediaVolumeEnabled(true, caller); + mMusicActiveMs = 0; + } + saveMusicActiveMs(); + } + } else { + cancelMusicActiveCheck(); + mLastMusicActiveTimeMs = 0; + } + } + } + } + + /*package*/ void configureSafeMediaVolume(boolean forced, String caller) { + int msg = MSG_CONFIGURE_SAFE_MEDIA_VOLUME; + mAudioHandler.removeMessages(msg); + + long time = 0; + if (forced) { + time = (SystemClock.uptimeMillis() + (SystemProperties.getBoolean( + "audio.safemedia.bypass", false) ? 0 : SAFE_VOLUME_CONFIGURE_TIMEOUT_MS)); + } + mAudioHandler.sendMessageAtTime( + mAudioHandler.obtainMessage(msg, /*arg1=*/forced ? 1 : 0, /*arg2=*/0, caller), + time); + } + + /*package*/ void initSafeUsbMediaVolumeIndex() { + // mSafeUsbMediaVolumeIndex must be initialized after createStreamStates() because it + // relies on audio policy having correct ranges for volume indexes. + mSafeUsbMediaVolumeIndex = getSafeUsbMediaVolumeIndex(); + } + + /*package*/ int getSafeMediaVolumeIndex(int device) { + if (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE && mSafeMediaVolumeDevices.contains( + device)) { + return safeMediaVolumeIndex(device); + } else { + return -1; + } + } + + /*package*/ boolean raiseVolumeDisplaySafeMediaVolume(int streamType, int index, int device, + int flags) { + if (checkSafeMediaVolume(streamType, index, device)) { + return false; + } + + mVolumeController.postDisplaySafeVolumeWarning(flags); + return true; + } + + /*package*/ boolean safeDevicesContains(int device) { + return mSafeMediaVolumeDevices.contains(device); + } + + /*package*/ void invalidatPendingVolumeCommand() { + synchronized (mSafeMediaVolumeStateLock) { + mPendingVolumeCommand = null; + } + } + + /*package*/ void handleMessage(Message msg) { + switch (msg.what) { + case MSG_CONFIGURE_SAFE_MEDIA_VOLUME: + onConfigureSafeVolume((msg.arg1 == 1), (String) msg.obj); + break; + case MSG_PERSIST_SAFE_VOLUME_STATE: + onPersistSafeVolumeState(msg.arg1); + break; + case MSG_PERSIST_MUSIC_ACTIVE_MS: + final int musicActiveMs = msg.arg1; + mSettings.putSecureIntForUser(mAudioService.getContentResolver(), + Settings.Secure.UNSAFE_VOLUME_MUSIC_ACTIVE_MS, musicActiveMs, + UserHandle.USER_CURRENT); + break; + } + + } + + /*package*/ void dump(PrintWriter pw) { + pw.print(" mSafeMediaVolumeState="); + pw.println(safeMediaVolumeStateToString(mSafeMediaVolumeState)); + pw.print(" mSafeMediaVolumeIndex="); pw.println(mSafeMediaVolumeIndex); + pw.print(" mSafeUsbMediaVolumeIndex="); pw.println(mSafeUsbMediaVolumeIndex); + pw.print(" mSafeUsbMediaVolumeDbfs="); pw.println(mSafeUsbMediaVolumeDbfs); + pw.print(" mMusicActiveMs="); pw.println(mMusicActiveMs); + pw.print(" mMcc="); pw.println(mMcc); + pw.print(" mPendingVolumeCommand="); pw.println(mPendingVolumeCommand); + } + + /*package*/void reset() { + Log.d(TAG, "Reset the sound dose helper"); + initCsd(); + } + + private void initCsd() { + synchronized (mSafeMediaVolumeStateLock) { + if (USE_CSD_FOR_SAFE_HEARING) { + Log.v(TAG, "Initializing sound dose"); + + mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_DISABLED; + mSoundDose = AudioSystem.getSoundDoseInterface(mSoundDoseCallback); + try { + if (mSoundDose != null && mSoundDose.asBinder().isBinderAlive()) { + mSoundDose.setOutputRs2(CUSTOM_RS2_VALUE); + if (mCurrentCsd != 0.f) { + Log.d(TAG, "Resetting the saved sound dose value " + mCurrentCsd); + SoundDoseRecord[] records = mDoseRecords.toArray( + new SoundDoseRecord[0]); + mSoundDose.resetCsd(mCurrentCsd, records); + } + } + } catch (RemoteException e) { + // noop + } + } + } + } + + private void onConfigureSafeVolume(boolean force, String caller) { + synchronized (mSafeMediaVolumeStateLock) { + int mcc = mContext.getResources().getConfiguration().mcc; + if ((mMcc != mcc) || ((mMcc == 0) && force)) { + mSafeMediaVolumeIndex = mContext.getResources().getInteger( + com.android.internal.R.integer.config_safe_media_volume_index) * 10; + + mSafeUsbMediaVolumeIndex = getSafeUsbMediaVolumeIndex(); + + boolean safeMediaVolumeEnabled = + SystemProperties.getBoolean("audio.safemedia.force", false) + || mContext.getResources().getBoolean( + com.android.internal.R.bool.config_safe_media_volume_enabled); + + boolean safeMediaVolumeBypass = + SystemProperties.getBoolean("audio.safemedia.bypass", false); + + // The persisted state is either "disabled" or "active": this is the state applied + // next time we boot and cannot be "inactive" + int persistedState; + if (safeMediaVolumeEnabled && !safeMediaVolumeBypass && !USE_CSD_FOR_SAFE_HEARING) { + persistedState = SAFE_MEDIA_VOLUME_ACTIVE; + // The state can already be "inactive" here if the user has forced it before + // the 30 seconds timeout for forced configuration. In this case we don't reset + // it to "active". + if (mSafeMediaVolumeState != SAFE_MEDIA_VOLUME_INACTIVE) { + if (mMusicActiveMs == 0) { + mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_ACTIVE; + enforceSafeMediaVolume(caller); + } else { + // We have existing playback time recorded, already confirmed. + mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_INACTIVE; + mLastMusicActiveTimeMs = 0; + } + } + } else { + persistedState = SAFE_MEDIA_VOLUME_DISABLED; + mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_DISABLED; + } + mMcc = mcc; + mAudioHandler.sendMessageAtTime( + mAudioHandler.obtainMessage(MSG_PERSIST_SAFE_VOLUME_STATE, + persistedState, /*arg2=*/0, + /*obj=*/null), /*delay=*/0); + } + } + } + + @GuardedBy("mSafeMediaVolumeStateLock") + private void setSafeMediaVolumeEnabled(boolean on, String caller) { + if ((mSafeMediaVolumeState != SAFE_MEDIA_VOLUME_NOT_CONFIGURED) && (mSafeMediaVolumeState + != SAFE_MEDIA_VOLUME_DISABLED)) { + if (on && (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_INACTIVE)) { + mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_ACTIVE; + enforceSafeMediaVolume(caller); + } else if (!on && (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE)) { + mSafeMediaVolumeState = SAFE_MEDIA_VOLUME_INACTIVE; + mMusicActiveMs = 1; // nonzero = confirmed + mLastMusicActiveTimeMs = 0; + saveMusicActiveMs(); + scheduleMusicActiveCheck(); + } + } + } + + @GuardedBy("mSafeMediaVolumeStateLock") + private void cancelMusicActiveCheck() { + if (mMusicActiveIntent != null) { + mAlarmManager.cancel(mMusicActiveIntent); + mMusicActiveIntent = null; + } + } + + @GuardedBy("mSafeMediaVolumeStateLock") + private void saveMusicActiveMs() { + mAudioHandler.obtainMessage(MSG_PERSIST_MUSIC_ACTIVE_MS, mMusicActiveMs, 0).sendToTarget(); + } + + private int getSafeUsbMediaVolumeIndex() { + // determine UI volume index corresponding to the wanted safe gain in dBFS + int min = MIN_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]; + int max = MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]; + + mSafeUsbMediaVolumeDbfs = mContext.getResources().getInteger( + com.android.internal.R.integer.config_safe_media_volume_usb_mB) / 100.0f; + + while (Math.abs(max - min) > 1) { + int index = (max + min) / 2; + float gainDB = AudioSystem.getStreamVolumeDB( + AudioSystem.STREAM_MUSIC, index, AudioSystem.DEVICE_OUT_USB_HEADSET); + if (Float.isNaN(gainDB)) { + //keep last min in case of read error + break; + } else if (gainDB == mSafeUsbMediaVolumeDbfs) { + min = index; + break; + } else if (gainDB < mSafeUsbMediaVolumeDbfs) { + min = index; + } else { + max = index; + } + } + return min * 10; + } + + private void onPersistSafeVolumeState(int state) { + mSettings.putGlobalInt(mAudioService.getContentResolver(), + Settings.Global.AUDIO_SAFE_VOLUME_STATE, + state); + } + + private static String safeMediaVolumeStateToString(int state) { + switch(state) { + case SAFE_MEDIA_VOLUME_NOT_CONFIGURED: return "SAFE_MEDIA_VOLUME_NOT_CONFIGURED"; + case SAFE_MEDIA_VOLUME_DISABLED: return "SAFE_MEDIA_VOLUME_DISABLED"; + case SAFE_MEDIA_VOLUME_INACTIVE: return "SAFE_MEDIA_VOLUME_INACTIVE"; + case SAFE_MEDIA_VOLUME_ACTIVE: return "SAFE_MEDIA_VOLUME_ACTIVE"; + } + return null; + } + + // StreamVolumeCommand contains the information needed to defer the process of + // setStreamVolume() in case the user has to acknowledge the safe volume warning message. + private static class StreamVolumeCommand { + public final int mStreamType; + public final int mIndex; + public final int mFlags; + public final int mDevice; + + StreamVolumeCommand(int streamType, int index, int flags, int device) { + mStreamType = streamType; + mIndex = index; + mFlags = flags; + mDevice = device; + } + + @Override + public String toString() { + return new StringBuilder().append("{streamType=").append(mStreamType).append(",index=") + .append(mIndex).append(",flags=").append(mFlags).append(",device=") + .append(mDevice).append('}').toString(); + } + } +} diff --git a/services/core/java/com/android/server/audio/TEST_MAPPING b/services/core/java/com/android/server/audio/TEST_MAPPING index f3a73f043c29..d6c2fb27cf76 100644 --- a/services/core/java/com/android/server/audio/TEST_MAPPING +++ b/services/core/java/com/android/server/audio/TEST_MAPPING @@ -13,6 +13,17 @@ "include-filter": "android.media.audio.cts.SpatializerTest" } ] + }, + { + "name": "audiopolicytest", + "options": [ + { + "include-filter": "com.android.audiopolicytest.AudioPolicyDeathTest" + }, + { + "include-annotation": "android.platform.test.annotations.Presubmit" + } + ] } ] } diff --git a/services/core/java/com/android/server/companion/virtual/OWNERS b/services/core/java/com/android/server/companion/virtual/OWNERS new file mode 100644 index 000000000000..2e475a9a2742 --- /dev/null +++ b/services/core/java/com/android/server/companion/virtual/OWNERS @@ -0,0 +1 @@ +include /services/companion/java/com/android/server/companion/virtual/OWNERS
\ No newline at end of file diff --git a/services/core/java/com/android/server/companion/virtual/VirtualDeviceManagerInternal.java b/services/core/java/com/android/server/companion/virtual/VirtualDeviceManagerInternal.java index d2e572f2f979..218be9de5ffb 100644 --- a/services/core/java/com/android/server/companion/virtual/VirtualDeviceManagerInternal.java +++ b/services/core/java/com/android/server/companion/virtual/VirtualDeviceManagerInternal.java @@ -18,7 +18,6 @@ package com.android.server.companion.virtual; import android.annotation.NonNull; import android.companion.virtual.IVirtualDevice; -import android.companion.virtual.VirtualDeviceParams; import java.util.Set; @@ -94,12 +93,6 @@ public abstract class VirtualDeviceManagerInternal { public abstract int getBaseVirtualDisplayFlags(IVirtualDevice virtualDevice); /** - * Returns true if the given {@code uid} is the owner of any virtual devices that are - * currently active. - */ - public abstract boolean isAppOwnerOfAnyVirtualDevice(int uid); - - /** * Returns true if the given {@code uid} is currently running on any virtual devices. This is * determined by whether the app has any activities in the task stack on a virtual-device-owned * display. @@ -110,14 +103,4 @@ public abstract class VirtualDeviceManagerInternal { * Returns true if the {@code displayId} is owned by any virtual device */ public abstract boolean isDisplayOwnedByAnyVirtualDevice(int displayId); - - /** - * Returns the device policy for the given virtual device and policy type. - * - * <p>In case the virtual device identifier is not valid, or there's no explicitly specified - * policy for that device and policy type, then - * {@link VirtualDeviceParams#DEVICE_POLICY_DEFAULT} is returned. - */ - public abstract @VirtualDeviceParams.DevicePolicy int getDevicePolicy( - int deviceId, @VirtualDeviceParams.PolicyType int policyType); } diff --git a/services/core/java/com/android/server/connectivity/Vpn.java b/services/core/java/com/android/server/connectivity/Vpn.java index bc9bc031ca35..4fcde97fc772 100644 --- a/services/core/java/com/android/server/connectivity/Vpn.java +++ b/services/core/java/com/android/server/connectivity/Vpn.java @@ -3475,6 +3475,8 @@ public class Vpn { return; } else { mActiveNetwork = null; + mUnderlyingNetworkCapabilities = null; + mUnderlyingLinkProperties = null; } if (mScheduledHandleNetworkLostFuture != null) { @@ -3664,9 +3666,6 @@ public class Vpn { scheduleRetryNewIkeSession(); } - mUnderlyingNetworkCapabilities = null; - mUnderlyingLinkProperties = null; - // Close all obsolete state, but keep VPN alive incase a usable network comes up. // (Mirrors VpnService behavior) Log.d(TAG, "Resetting state for token: " + mCurrentToken); diff --git a/services/core/java/com/android/server/display/LocalDisplayAdapter.java b/services/core/java/com/android/server/display/LocalDisplayAdapter.java index ee53b6087143..be5980bdfffd 100644 --- a/services/core/java/com/android/server/display/LocalDisplayAdapter.java +++ b/services/core/java/com/android/server/display/LocalDisplayAdapter.java @@ -112,13 +112,13 @@ final class LocalDisplayAdapter extends DisplayAdapter { mSurfaceControlProxy.getPhysicalDisplayToken(physicalDisplayId); if (displayToken != null) { SurfaceControl.StaticDisplayInfo staticInfo = - mSurfaceControlProxy.getStaticDisplayInfo(displayToken); + mSurfaceControlProxy.getStaticDisplayInfo(physicalDisplayId); if (staticInfo == null) { Slog.w(TAG, "No valid static info found for display device " + physicalDisplayId); return; } SurfaceControl.DynamicDisplayInfo dynamicInfo = - mSurfaceControlProxy.getDynamicDisplayInfo(displayToken); + mSurfaceControlProxy.getDynamicDisplayInfo(physicalDisplayId); if (dynamicInfo == null) { Slog.w(TAG, "No valid dynamic info found for display device " + physicalDisplayId); return; @@ -1402,8 +1402,8 @@ final class LocalDisplayAdapter extends DisplayAdapter { @VisibleForTesting public static class SurfaceControlProxy { - public SurfaceControl.DynamicDisplayInfo getDynamicDisplayInfo(IBinder token) { - return SurfaceControl.getDynamicDisplayInfo(token); + public SurfaceControl.DynamicDisplayInfo getDynamicDisplayInfo(long displayId) { + return SurfaceControl.getDynamicDisplayInfo(displayId); } public long[] getPhysicalDisplayIds() { @@ -1414,8 +1414,8 @@ final class LocalDisplayAdapter extends DisplayAdapter { return DisplayControl.getPhysicalDisplayToken(physicalDisplayId); } - public SurfaceControl.StaticDisplayInfo getStaticDisplayInfo(IBinder displayToken) { - return SurfaceControl.getStaticDisplayInfo(displayToken); + public SurfaceControl.StaticDisplayInfo getStaticDisplayInfo(long displayId) { + return SurfaceControl.getStaticDisplayInfo(displayId); } public SurfaceControl.DesiredDisplayModeSpecs getDesiredDisplayModeSpecs( diff --git a/services/core/java/com/android/server/dreams/DreamManagerService.java b/services/core/java/com/android/server/dreams/DreamManagerService.java index ea096299cf48..b8225419cb9b 100644 --- a/services/core/java/com/android/server/dreams/DreamManagerService.java +++ b/services/core/java/com/android/server/dreams/DreamManagerService.java @@ -378,6 +378,10 @@ public final class DreamManagerService extends SystemService { return false; } + if (!dreamsEnabledForUser(ActivityManager.getCurrentUser())) { + return false; + } + if ((mWhenToDream & DREAM_ON_CHARGE) == DREAM_ON_CHARGE) { return mIsCharging; } diff --git a/services/core/java/com/android/server/graphics/fonts/FontManagerService.java b/services/core/java/com/android/server/graphics/fonts/FontManagerService.java index 28dc318d3cd1..3c5b0671afa3 100644 --- a/services/core/java/com/android/server/graphics/fonts/FontManagerService.java +++ b/services/core/java/com/android/server/graphics/fonts/FontManagerService.java @@ -187,8 +187,8 @@ public final class FontManagerService extends IFontManager.Stub { } @Override - public void setUpFsverity(String filePath, byte[] pkcs7Signature) throws IOException { - VerityUtils.setUpFsverity(filePath, pkcs7Signature); + public void setUpFsverity(String filePath) throws IOException { + VerityUtils.setUpFsverity(filePath, /* signature */ (byte[]) null); } @Override diff --git a/services/core/java/com/android/server/graphics/fonts/UpdatableFontDir.java b/services/core/java/com/android/server/graphics/fonts/UpdatableFontDir.java index 457d5b7afe84..6f9360844542 100644 --- a/services/core/java/com/android/server/graphics/fonts/UpdatableFontDir.java +++ b/services/core/java/com/android/server/graphics/fonts/UpdatableFontDir.java @@ -78,7 +78,7 @@ final class UpdatableFontDir { interface FsverityUtil { boolean isFromTrustedProvider(String path, byte[] pkcs7Signature); - void setUpFsverity(String path, byte[] pkcs7Signature) throws IOException; + void setUpFsverity(String path) throws IOException; boolean rename(File src, File dest); } @@ -354,8 +354,7 @@ final class UpdatableFontDir { try { // Do not parse font file before setting up fs-verity. // setUpFsverity throws IOException if failed. - mFsverityUtil.setUpFsverity(tempNewFontFile.getAbsolutePath(), - pkcs7Signature); + mFsverityUtil.setUpFsverity(tempNewFontFile.getAbsolutePath()); } catch (IOException e) { throw new SystemFontException( FontManager.RESULT_ERROR_VERIFICATION_FAILURE, diff --git a/services/core/java/com/android/server/incident/IncidentCompanionService.java b/services/core/java/com/android/server/incident/IncidentCompanionService.java index 87fe785ca614..b8e7d4971790 100644 --- a/services/core/java/com/android/server/incident/IncidentCompanionService.java +++ b/services/core/java/com/android/server/incident/IncidentCompanionService.java @@ -34,7 +34,6 @@ import android.os.IncidentManager; import android.os.RemoteException; import android.os.ServiceManager; import android.os.UserHandle; -import android.os.UserManager; import android.util.Log; import com.android.internal.util.DumpUtils; @@ -128,21 +127,21 @@ public class IncidentCompanionService extends SystemService { try { final Context context = getContext(); - final int primaryUser = getAndValidateUser(context); - if (primaryUser == UserHandle.USER_NULL) { + // Get the current admin user. Only they can do incident reports. + final int currentAdminUser = getCurrentUserIfAdmin(); + if (currentAdminUser == UserHandle.USER_NULL) { return; } final Intent intent = new Intent(Intent.ACTION_INCIDENT_REPORT_READY); intent.setComponent(new ComponentName(pkg, cls)); - Log.d(TAG, "sendReportReadyBroadcast sending primaryUser=" + primaryUser - + " userHandle=" + UserHandle.getUserHandleForUid(primaryUser) + Log.d(TAG, "sendReportReadyBroadcast sending currentUser=" + currentAdminUser + + " userHandle=" + UserHandle.of(currentAdminUser) + " intent=" + intent); - // Send it to the primary user. Only they can do incident reports. context.sendBroadcastAsUserMultiplePermissions(intent, - UserHandle.getUserHandleForUid(primaryUser), + UserHandle.of(currentAdminUser), DUMP_AND_USAGE_STATS_PERMISSIONS); } finally { Binder.restoreCallingIdentity(ident); @@ -414,10 +413,10 @@ public class IncidentCompanionService extends SystemService { } /** - * Check whether the current user is the primary user, and return the user id if they are. + * Check whether the current user is an admin user, and return the user id if they are. * Returns UserHandle.USER_NULL if not valid. */ - public static int getAndValidateUser(Context context) { + public static int getCurrentUserIfAdmin() { // Current user UserInfo currentUser; try { @@ -427,28 +426,21 @@ public class IncidentCompanionService extends SystemService { throw new RuntimeException(ex); } - // Primary user - final UserManager um = UserManager.get(context); - final UserInfo primaryUser = um.getPrimaryUser(); - // Check that we're using the right user. if (currentUser == null) { Log.w(TAG, "No current user. Nobody to approve the report." + " The report will be denied."); return UserHandle.USER_NULL; } - if (primaryUser == null) { - Log.w(TAG, "No primary user. Nobody to approve the report." - + " The report will be denied."); - return UserHandle.USER_NULL; - } - if (primaryUser.id != currentUser.id) { - Log.w(TAG, "Only the primary user can approve bugreports, but they are not" - + " the current user. The report will be denied."); + + if (!currentUser.isAdmin()) { + Log.w(TAG, "Only an admin user running in foreground can approve " + + "bugreports, but the current foreground user is not an admin user. " + + "The report will be denied."); return UserHandle.USER_NULL; } - return primaryUser.id; + return currentUser.id; } } diff --git a/services/core/java/com/android/server/incident/PendingReports.java b/services/core/java/com/android/server/incident/PendingReports.java index f39bebf060f7..6285bc3f531b 100644 --- a/services/core/java/com/android/server/incident/PendingReports.java +++ b/services/core/java/com/android/server/incident/PendingReports.java @@ -16,6 +16,7 @@ package com.android.server.incident; +import android.annotation.UserIdInt; import android.app.AppOpsManager; import android.app.BroadcastOptions; import android.content.ComponentName; @@ -272,15 +273,19 @@ class PendingReports { return; } - // Find the primary user of this device. - final int primaryUser = getAndValidateUser(); - if (primaryUser == UserHandle.USER_NULL) { + // Find the current user of the device and check if they are an admin. + final int currentAdminUser = getCurrentUserIfAdmin(); + + // Deny the report if the current admin user is null + // or not the user who requested the report. + if (currentAdminUser == UserHandle.USER_NULL + || currentAdminUser != UserHandle.getUserId(callingUid)) { denyReportBeforeAddingRec(listener, callingPackage); return; } // Find the approver app (hint: it's PermissionController). - final ComponentName receiver = getApproverComponent(primaryUser); + final ComponentName receiver = getApproverComponent(currentAdminUser); if (receiver == null) { // We couldn't find an approver... so deny the request here and now, before we // do anything else. @@ -298,26 +303,26 @@ class PendingReports { try { listener.asBinder().linkToDeath(() -> { Log.i(TAG, "Got death notification listener=" + listener); - cancelReportImpl(listener, receiver, primaryUser); + cancelReportImpl(listener, receiver, currentAdminUser); }, 0); } catch (RemoteException ex) { Log.e(TAG, "Remote died while trying to register death listener: " + rec.getUri()); // First, remove from our list. - cancelReportImpl(listener, receiver, primaryUser); + cancelReportImpl(listener, receiver, currentAdminUser); } // Go tell Permission controller to start asking the user. - sendBroadcast(receiver, primaryUser); + sendBroadcast(receiver, currentAdminUser); } /** * Cancel a pending report request (because of an explicit call to cancel) */ private void cancelReportImpl(IIncidentAuthListener listener) { - final int primaryUser = getAndValidateUser(); - final ComponentName receiver = getApproverComponent(primaryUser); - if (primaryUser != UserHandle.USER_NULL && receiver != null) { - cancelReportImpl(listener, receiver, primaryUser); + final int currentAdminUser = getCurrentUserIfAdmin(); + final ComponentName receiver = getApproverComponent(currentAdminUser); + if (currentAdminUser != UserHandle.USER_NULL && receiver != null) { + cancelReportImpl(listener, receiver, currentAdminUser); } } @@ -326,13 +331,13 @@ class PendingReports { * by the calling app, or because of a binder death). */ private void cancelReportImpl(IIncidentAuthListener listener, ComponentName receiver, - int primaryUser) { + @UserIdInt int user) { // First, remove from our list. synchronized (mLock) { removePendingReportRecLocked(listener); } // Second, call back to PermissionController to say it's canceled. - sendBroadcast(receiver, primaryUser); + sendBroadcast(receiver, user); } /** @@ -342,21 +347,21 @@ class PendingReports { * cleanup cases to keep the apps' list in sync with ours. */ private void sendBroadcast() { - final int primaryUser = getAndValidateUser(); - if (primaryUser == UserHandle.USER_NULL) { + final int currentAdminUser = getCurrentUserIfAdmin(); + if (currentAdminUser == UserHandle.USER_NULL) { return; } - final ComponentName receiver = getApproverComponent(primaryUser); + final ComponentName receiver = getApproverComponent(currentAdminUser); if (receiver == null) { return; } - sendBroadcast(receiver, primaryUser); + sendBroadcast(receiver, currentAdminUser); } /** * Send the confirmation broadcast. */ - private void sendBroadcast(ComponentName receiver, int primaryUser) { + private void sendBroadcast(ComponentName receiver, int currentUser) { final Intent intent = new Intent(Intent.ACTION_PENDING_INCIDENT_REPORTS_CHANGED); intent.setComponent(receiver); intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); @@ -364,8 +369,8 @@ class PendingReports { final BroadcastOptions options = BroadcastOptions.makeBasic(); options.setBackgroundActivityStartsAllowed(true); - // Send it to the primary user. - mContext.sendBroadcastAsUser(intent, UserHandle.getUserHandleForUid(primaryUser), + // Send it to the current user. + mContext.sendBroadcastAsUser(intent, UserHandle.of(currentUser), android.Manifest.permission.APPROVE_INCIDENT_REPORTS, options.toBundle()); } @@ -420,11 +425,11 @@ class PendingReports { } /** - * Check whether the current user is the primary user, and return the user id if they are. + * Check whether the current user is an admin user, and return the user id if they are. * Returns UserHandle.USER_NULL if not valid. */ - private int getAndValidateUser() { - return IncidentCompanionService.getAndValidateUser(mContext); + private int getCurrentUserIfAdmin() { + return IncidentCompanionService.getCurrentUserIfAdmin(); } /** diff --git a/services/core/java/com/android/server/input/InputManagerService.java b/services/core/java/com/android/server/input/InputManagerService.java index 81d782e9b863..0da04a22d31f 100644 --- a/services/core/java/com/android/server/input/InputManagerService.java +++ b/services/core/java/com/android/server/input/InputManagerService.java @@ -294,6 +294,9 @@ public class InputManagerService extends IInputManager.Stub // Manages Keyboard backlight private final KeyboardBacklightController mKeyboardBacklightController; + // Manages Keyboard modifier keys remapping + private final KeyRemapper mKeyRemapper; + // Maximum number of milliseconds to wait for input event injection. private static final int INJECTION_TIMEOUT_MILLIS = 30 * 1000; @@ -408,6 +411,7 @@ public class InputManagerService extends IInputManager.Stub mBatteryController = new BatteryController(mContext, mNative, injector.getLooper()); mKeyboardBacklightController = new KeyboardBacklightController(mContext, mNative, mDataStore, injector.getLooper()); + mKeyRemapper = new KeyRemapper(mContext, mNative, mDataStore, injector.getLooper()); mUseDevInputEventForAudioJack = mContext.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack); @@ -536,6 +540,7 @@ public class InputManagerService extends IInputManager.Stub mKeyboardLayoutManager.systemRunning(); mBatteryController.systemRunning(); mKeyboardBacklightController.systemRunning(); + mKeyRemapper.systemRunning(); } private void reloadDeviceAliases() { @@ -2738,6 +2743,27 @@ public class InputManagerService extends IInputManager.Stub return mKeyboardLayoutManager.getKeyboardLayoutOverlay(identifier); } + @EnforcePermission(Manifest.permission.REMAP_MODIFIER_KEYS) + @Override // Binder call + public void remapModifierKey(int fromKey, int toKey) { + super.remapModifierKey_enforcePermission(); + mKeyRemapper.remapKey(fromKey, toKey); + } + + @EnforcePermission(Manifest.permission.REMAP_MODIFIER_KEYS) + @Override // Binder call + public void clearAllModifierKeyRemappings() { + super.clearAllModifierKeyRemappings_enforcePermission(); + mKeyRemapper.clearAllKeyRemappings(); + } + + @EnforcePermission(Manifest.permission.REMAP_MODIFIER_KEYS) + @Override // Binder call + public Map<Integer, Integer> getModifierKeyRemapping() { + super.getModifierKeyRemapping_enforcePermission(); + return mKeyRemapper.getKeyRemapping(); + } + // Native callback. @SuppressWarnings("unused") private String getDeviceAlias(String uniqueId) { diff --git a/services/core/java/com/android/server/input/KeyRemapper.java b/services/core/java/com/android/server/input/KeyRemapper.java new file mode 100644 index 000000000000..950e094a205d --- /dev/null +++ b/services/core/java/com/android/server/input/KeyRemapper.java @@ -0,0 +1,161 @@ +/* + * 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.input; + +import android.content.Context; +import android.hardware.input.InputManager; +import android.os.Handler; +import android.os.Looper; +import android.os.Message; +import android.view.InputDevice; + +import com.android.internal.annotations.GuardedBy; + +import java.util.Map; +import java.util.Objects; + +/** + * A component of {@link InputManagerService} responsible for managing key remappings. + * + * @hide + */ +final class KeyRemapper implements InputManager.InputDeviceListener { + + private static final int MSG_UPDATE_EXISTING_DEVICES = 1; + private static final int MSG_REMAP_KEY = 2; + private static final int MSG_CLEAR_ALL_REMAPPING = 3; + + private final Context mContext; + private final NativeInputManagerService mNative; + // The PersistentDataStore should be locked before use. + @GuardedBy("mDataStore") + private final PersistentDataStore mDataStore; + private final Handler mHandler; + + KeyRemapper(Context context, NativeInputManagerService nativeService, + PersistentDataStore dataStore, Looper looper) { + mContext = context; + mNative = nativeService; + mDataStore = dataStore; + mHandler = new Handler(looper, this::handleMessage); + } + + public void systemRunning() { + InputManager inputManager = Objects.requireNonNull( + mContext.getSystemService(InputManager.class)); + inputManager.registerInputDeviceListener(this, mHandler); + + Message msg = Message.obtain(mHandler, MSG_UPDATE_EXISTING_DEVICES, + inputManager.getInputDeviceIds()); + mHandler.sendMessage(msg); + } + + public void remapKey(int fromKey, int toKey) { + Message msg = Message.obtain(mHandler, MSG_REMAP_KEY, fromKey, toKey); + mHandler.sendMessage(msg); + } + + public void clearAllKeyRemappings() { + Message msg = Message.obtain(mHandler, MSG_CLEAR_ALL_REMAPPING); + mHandler.sendMessage(msg); + } + + public Map<Integer, Integer> getKeyRemapping() { + synchronized (mDataStore) { + return mDataStore.getKeyRemapping(); + } + } + + private void addKeyRemapping(int fromKey, int toKey) { + InputManager inputManager = Objects.requireNonNull( + mContext.getSystemService(InputManager.class)); + for (int deviceId : inputManager.getInputDeviceIds()) { + InputDevice inputDevice = inputManager.getInputDevice(deviceId); + if (inputDevice != null && !inputDevice.isVirtual() && inputDevice.isFullKeyboard()) { + mNative.addKeyRemapping(deviceId, fromKey, toKey); + } + } + } + + private void remapKeyInternal(int fromKey, int toKey) { + addKeyRemapping(fromKey, toKey); + synchronized (mDataStore) { + try { + if (fromKey == toKey) { + mDataStore.clearMappedKey(fromKey); + } else { + mDataStore.remapKey(fromKey, toKey); + } + } finally { + mDataStore.saveIfNeeded(); + } + } + } + + private void clearAllRemappingsInternal() { + synchronized (mDataStore) { + try { + Map<Integer, Integer> keyRemapping = mDataStore.getKeyRemapping(); + for (int fromKey : keyRemapping.keySet()) { + mDataStore.clearMappedKey(fromKey); + + // Remapping to itself will clear the remapping on native side + addKeyRemapping(fromKey, fromKey); + } + } finally { + mDataStore.saveIfNeeded(); + } + } + } + + @Override + public void onInputDeviceAdded(int deviceId) { + InputManager inputManager = Objects.requireNonNull( + mContext.getSystemService(InputManager.class)); + InputDevice inputDevice = inputManager.getInputDevice(deviceId); + if (inputDevice != null && !inputDevice.isVirtual() && inputDevice.isFullKeyboard()) { + Map<Integer, Integer> remapping = getKeyRemapping(); + remapping.forEach( + (fromKey, toKey) -> mNative.addKeyRemapping(deviceId, fromKey, toKey)); + } + } + + @Override + public void onInputDeviceRemoved(int deviceId) { + } + + @Override + public void onInputDeviceChanged(int deviceId) { + } + + private boolean handleMessage(Message msg) { + switch (msg.what) { + case MSG_UPDATE_EXISTING_DEVICES: + for (int deviceId : (int[]) msg.obj) { + onInputDeviceAdded(deviceId); + } + return true; + case MSG_REMAP_KEY: + remapKeyInternal(msg.arg1, msg.arg2); + return true; + case MSG_CLEAR_ALL_REMAPPING: + clearAllRemappingsInternal(); + return true; + } + return false; + } +} diff --git a/services/core/java/com/android/server/input/NativeInputManagerService.java b/services/core/java/com/android/server/input/NativeInputManagerService.java index cfa7fb141be1..8781c6e2b934 100644 --- a/services/core/java/com/android/server/input/NativeInputManagerService.java +++ b/services/core/java/com/android/server/input/NativeInputManagerService.java @@ -47,6 +47,8 @@ interface NativeInputManagerService { int getSwitchState(int deviceId, int sourceMask, int sw); + void addKeyRemapping(int deviceId, int fromKeyCode, int toKeyCode); + boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists); int getKeyCodeForKeyLocation(int deviceId, int locationKeyCode); @@ -235,6 +237,9 @@ interface NativeInputManagerService { public native int getSwitchState(int deviceId, int sourceMask, int sw); @Override + public native void addKeyRemapping(int deviceId, int fromKeyCode, int toKeyCode); + + @Override public native boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists); diff --git a/services/core/java/com/android/server/input/PersistentDataStore.java b/services/core/java/com/android/server/input/PersistentDataStore.java index 1bb10c710839..375377a7510d 100644 --- a/services/core/java/com/android/server/input/PersistentDataStore.java +++ b/services/core/java/com/android/server/input/PersistentDataStore.java @@ -27,14 +27,13 @@ import android.view.Surface; import com.android.internal.annotations.VisibleForTesting; import com.android.internal.util.ArrayUtils; import com.android.internal.util.XmlUtils; +import com.android.modules.utils.TypedXmlPullParser; +import com.android.modules.utils.TypedXmlSerializer; import libcore.io.IoUtils; import org.xmlpull.v1.XmlPullParserException; -import com.android.modules.utils.TypedXmlPullParser; -import com.android.modules.utils.TypedXmlSerializer; - import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; @@ -64,6 +63,8 @@ import java.util.Set; final class PersistentDataStore { static final String TAG = "InputManager"; + private static final int INVALID_VALUE = -1; + // Input device state by descriptor. private final HashMap<String, InputDeviceState> mInputDevices = new HashMap<String, InputDeviceState>(); @@ -77,6 +78,9 @@ final class PersistentDataStore { // True if there are changes to be saved. private boolean mDirty; + // Storing key remapping + private Map<Integer, Integer> mKeyRemapping = new HashMap<>(); + public PersistentDataStore() { this(new Injector()); } @@ -187,6 +191,30 @@ final class PersistentDataStore { return state.getKeyboardBacklightBrightness(lightId); } + public boolean remapKey(int fromKey, int toKey) { + loadIfNeeded(); + if (mKeyRemapping.getOrDefault(fromKey, INVALID_VALUE) == toKey) { + return false; + } + mKeyRemapping.put(fromKey, toKey); + setDirty(); + return true; + } + + public boolean clearMappedKey(int key) { + loadIfNeeded(); + if (mKeyRemapping.containsKey(key)) { + mKeyRemapping.remove(key); + setDirty(); + } + return true; + } + + public Map<Integer, Integer> getKeyRemapping() { + loadIfNeeded(); + return new HashMap<>(mKeyRemapping); + } + public boolean removeUninstalledKeyboardLayouts(Set<String> availableKeyboardLayouts) { boolean changed = false; for (InputDeviceState state : mInputDevices.values()) { @@ -229,6 +257,7 @@ final class PersistentDataStore { } private void clearState() { + mKeyRemapping.clear(); mInputDevices.clear(); } @@ -280,7 +309,9 @@ final class PersistentDataStore { XmlUtils.beginDocument(parser, "input-manager-state"); final int outerDepth = parser.getDepth(); while (XmlUtils.nextElementWithin(parser, outerDepth)) { - if (parser.getName().equals("input-devices")) { + if (parser.getName().equals("key-remapping")) { + loadKeyRemappingFromXml(parser); + } else if (parser.getName().equals("input-devices")) { loadInputDevicesFromXml(parser); } } @@ -307,10 +338,31 @@ final class PersistentDataStore { } } + private void loadKeyRemappingFromXml(TypedXmlPullParser parser) + throws IOException, XmlPullParserException { + final int outerDepth = parser.getDepth(); + while (XmlUtils.nextElementWithin(parser, outerDepth)) { + if (parser.getName().equals("remap")) { + int fromKey = parser.getAttributeInt(null, "from-key"); + int toKey = parser.getAttributeInt(null, "to-key"); + mKeyRemapping.put(fromKey, toKey); + } + } + } + private void saveToXml(TypedXmlSerializer serializer) throws IOException { serializer.startDocument(null, true); serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); serializer.startTag(null, "input-manager-state"); + serializer.startTag(null, "key-remapping"); + for (int fromKey : mKeyRemapping.keySet()) { + int toKey = mKeyRemapping.get(fromKey); + serializer.startTag(null, "remap"); + serializer.attributeInt(null, "from-key", fromKey); + serializer.attributeInt(null, "to-key", toKey); + serializer.endTag(null, "remap"); + } + serializer.endTag(null, "key-remapping"); serializer.startTag(null, "input-devices"); for (Map.Entry<String, InputDeviceState> entry : mInputDevices.entrySet()) { final String descriptor = entry.getKey(); @@ -329,7 +381,6 @@ final class PersistentDataStore { private static final String[] CALIBRATION_NAME = { "x_scale", "x_ymix", "x_offset", "y_xmix", "y_scale", "y_offset" }; - private static final int INVALID_VALUE = -1; private final TouchCalibration[] mTouchCalibration = new TouchCalibration[4]; @Nullable private String mCurrentKeyboardLayout; diff --git a/services/core/java/com/android/server/inputmethod/InputMethodUtils.java b/services/core/java/com/android/server/inputmethod/InputMethodUtils.java index ebf9237d61ea..be99bfbc2bc9 100644 --- a/services/core/java/com/android/server/inputmethod/InputMethodUtils.java +++ b/services/core/java/com/android/server/inputmethod/InputMethodUtils.java @@ -199,9 +199,14 @@ final class InputMethodUtils { } /** - * Utility class for putting and getting settings for InputMethod + * Utility class for putting and getting settings for InputMethod. + * + * This is used in two ways: + * - Singleton instance in {@link InputMethodManagerService}, which is updated on user-switch to + * follow the current user. + * - On-demand instances when we need settings for non-current users. + * * TODO: Move all putters and getters of settings to this class. - * TODO(b/235661780): Make the setting supports multi-users. */ @UserHandleAware public static class InputMethodSettings { @@ -212,9 +217,9 @@ final class InputMethodUtils { new TextUtils.SimpleStringSplitter(INPUT_METHOD_SUBTYPE_SEPARATOR); @NonNull - private final Context mUserAwareContext; - private final Resources mRes; - private final ContentResolver mResolver; + private Context mUserAwareContext; + private Resources mRes; + private ContentResolver mResolver; private final ArrayMap<String, InputMethodInfo> mMethodMap; /** @@ -272,15 +277,19 @@ final class InputMethodUtils { return imsList; } - InputMethodSettings(@NonNull Context context, - ArrayMap<String, InputMethodInfo> methodMap, @UserIdInt int userId, - boolean copyOnWrite) { + private void initContentWithUserContext(@NonNull Context context, @UserIdInt int userId) { mUserAwareContext = context.getUserId() == userId ? context : context.createContextAsUser(UserHandle.of(userId), 0 /* flags */); mRes = mUserAwareContext.getResources(); mResolver = mUserAwareContext.getContentResolver(); + } + + InputMethodSettings(@NonNull Context context, + ArrayMap<String, InputMethodInfo> methodMap, @UserIdInt int userId, + boolean copyOnWrite) { mMethodMap = methodMap; + initContentWithUserContext(context, userId); switchCurrentUser(userId, copyOnWrite); } @@ -301,6 +310,9 @@ final class InputMethodUtils { mEnabledInputMethodsStrCache = ""; // TODO: mCurrentProfileIds should be cleared here. } + if (mUserAwareContext.getUserId() != userId) { + initContentWithUserContext(mUserAwareContext, userId); + } mCurrentUserId = userId; mCopyOnWrite = copyOnWrite; // TODO: mCurrentProfileIds should be updated here. diff --git a/services/core/java/com/android/server/locksettings/LockSettingsService.java b/services/core/java/com/android/server/locksettings/LockSettingsService.java index 99d77d6f7cc9..2dc1e1cc5747 100644 --- a/services/core/java/com/android/server/locksettings/LockSettingsService.java +++ b/services/core/java/com/android/server/locksettings/LockSettingsService.java @@ -21,6 +21,8 @@ import static android.Manifest.permission.MANAGE_BIOMETRIC; import static android.Manifest.permission.READ_CONTACTS; import static android.Manifest.permission.SET_AND_VERIFY_LOCKSCREEN_CREDENTIALS; import static android.Manifest.permission.SET_INITIAL_LOCK; +import static android.app.admin.DevicePolicyManager.DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_DEFAULT; +import static android.app.admin.DevicePolicyManager.DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_FLAG; import static android.app.admin.DevicePolicyResources.Strings.Core.PROFILE_ENCRYPTED_DETAIL; import static android.app.admin.DevicePolicyResources.Strings.Core.PROFILE_ENCRYPTED_MESSAGE; import static android.app.admin.DevicePolicyResources.Strings.Core.PROFILE_ENCRYPTED_TITLE; @@ -91,6 +93,7 @@ import android.os.UserHandle; import android.os.UserManager; import android.os.storage.IStorageManager; import android.os.storage.StorageManager; +import android.provider.DeviceConfig; import android.provider.Settings; import android.provider.Settings.Secure; import android.security.AndroidKeyStoreMaintenance; @@ -3183,18 +3186,34 @@ public class LockSettingsService extends ILockSettings.Stub { * if we are running an automotive build. */ private void disableEscrowTokenOnNonManagedDevicesIfNeeded(int userId) { - final UserManagerInternal userManagerInternal = mInjector.getUserManagerInternal(); + // TODO(b/258213147): Remove + final long identity = Binder.clearCallingIdentity(); + try { + if (DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_DEVICE_POLICY_MANAGER, + DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_FLAG, + DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_DEFAULT)) { - // Managed profile should have escrow enabled - if (userManagerInternal.isUserManaged(userId)) { - Slog.i(TAG, "Managed profile can have escrow token"); - return; - } + if (mInjector.getDeviceStateCache().isUserOrganizationManaged(userId)) { + Slog.i(TAG, "Organization managed users can have escrow token"); + return; + } + } else { + final UserManagerInternal userManagerInternal = mInjector.getUserManagerInternal(); - // Devices with Device Owner should have escrow enabled on all users. - if (userManagerInternal.isDeviceManaged()) { - Slog.i(TAG, "Corp-owned device can have escrow token"); - return; + // Managed profile should have escrow enabled + if (userManagerInternal.isUserManaged(userId)) { + Slog.i(TAG, "Managed profile can have escrow token"); + return; + } + + // Devices with Device Owner should have escrow enabled on all users. + if (userManagerInternal.isDeviceManaged()) { + Slog.i(TAG, "Corp-owned device can have escrow token"); + return; + } + } + } finally { + Binder.restoreCallingIdentity(identity); } // If the device is yet to be provisioned (still in SUW), there is still diff --git a/services/core/java/com/android/server/media/MediaSessionService.java b/services/core/java/com/android/server/media/MediaSessionService.java index d08150cf0a56..e51ed1b520a9 100644 --- a/services/core/java/com/android/server/media/MediaSessionService.java +++ b/services/core/java/com/android/server/media/MediaSessionService.java @@ -2046,6 +2046,11 @@ public class MediaSessionService extends SystemService implements Monitor { int controllerUid) { final int uid = Binder.getCallingUid(); final int userId = UserHandle.getUserHandleForUid(uid).getIdentifier(); + if (LocalServices.getService(PackageManagerInternal.class) + .filterAppAccess(controllerPackageName, uid, userId)) { + // The controllerPackageName is not visible to the caller. + return false; + } final long token = Binder.clearCallingIdentity(); try { // Don't perform check between controllerPackageName and controllerUid. diff --git a/services/core/java/com/android/server/media/projection/OWNERS b/services/core/java/com/android/server/media/projection/OWNERS index 9ca391013aa3..832bcd9d70e6 100644 --- a/services/core/java/com/android/server/media/projection/OWNERS +++ b/services/core/java/com/android/server/media/projection/OWNERS @@ -1,2 +1 @@ -michaelwr@google.com -santoscordon@google.com +include /media/java/android/media/projection/OWNERS diff --git a/services/core/java/com/android/server/notification/NotificationRecordLogger.java b/services/core/java/com/android/server/notification/NotificationRecordLogger.java index ef1e11ccad55..4031c833f3c1 100644 --- a/services/core/java/com/android/server/notification/NotificationRecordLogger.java +++ b/services/core/java/com/android/server/notification/NotificationRecordLogger.java @@ -18,8 +18,8 @@ package com.android.server.notification; import static android.service.notification.NotificationListenerService.REASON_ASSISTANT_CANCEL; import static android.service.notification.NotificationListenerService.REASON_CANCEL; +import static android.service.notification.NotificationListenerService.REASON_CLEAR_DATA; import static android.service.notification.NotificationListenerService.REASON_CLICK; -import static android.service.notification.NotificationListenerService.REASON_TIMEOUT; import android.annotation.NonNull; import android.annotation.Nullable; @@ -172,7 +172,12 @@ public interface NotificationRecordLogger { NOTIFICATION_CANCEL_SNOOZED(181), @UiEvent(doc = "Notification was canceled due to timeout") NOTIFICATION_CANCEL_TIMEOUT(182), - // Values 183-189 reserved for future system dismissal reasons + @UiEvent(doc = "Notification was canceled due to the backing channel being deleted") + NOTIFICATION_CANCEL_CHANNEL_REMOVED(1261), + @UiEvent(doc = "Notification was canceled due to the app's storage being cleared") + NOTIFICATION_CANCEL_CLEAR_DATA(1262), + // Values above this line must remain in the same order as the corresponding + // NotificationCancelReason enum values. @UiEvent(doc = "Notification was canceled due to user dismissal of a peeking notification.") NOTIFICATION_CANCEL_USER_PEEK(190), @UiEvent(doc = "Notification was canceled due to user dismissal from the always-on display") @@ -208,7 +213,7 @@ public interface NotificationRecordLogger { // Most cancel reasons do not have a meaningful surface. Reason codes map directly // to NotificationCancelledEvent codes. if (surface == NotificationStats.DISMISSAL_OTHER) { - if ((REASON_CLICK <= reason) && (reason <= REASON_TIMEOUT)) { + if ((REASON_CLICK <= reason) && (reason <= REASON_CLEAR_DATA)) { return NotificationCancelledEvent.values()[reason]; } if (reason == REASON_ASSISTANT_CANCEL) { diff --git a/services/core/java/com/android/server/os/BugreportManagerServiceImpl.java b/services/core/java/com/android/server/os/BugreportManagerServiceImpl.java index 58428ca48c97..2fdc4cd5f7c1 100644 --- a/services/core/java/com/android/server/os/BugreportManagerServiceImpl.java +++ b/services/core/java/com/android/server/os/BugreportManagerServiceImpl.java @@ -33,8 +33,8 @@ import android.os.ServiceManager; import android.os.SystemClock; import android.os.SystemProperties; import android.os.UserHandle; -import android.os.UserManager; import android.telephony.TelephonyManager; +import android.text.TextUtils; import android.util.ArraySet; import android.util.Slog; @@ -189,10 +189,10 @@ class BugreportManagerServiceImpl extends IDumpstate.Stub { } /** - * Validates that the current user is the primary user or when bugreport is requested remotely - * and current user is affiliated user. + * Validates that the current user is an admin user or, when bugreport is requested remotely + * that the current user is an affiliated user. * - * @throws IllegalArgumentException if the current user is not the primary user + * @throws IllegalArgumentException if the current user is not an admin user */ private void ensureUserCanTakeBugReport(int bugreportMode) { UserInfo currentUser = null; @@ -202,20 +202,17 @@ class BugreportManagerServiceImpl extends IDumpstate.Stub { // Impossible to get RemoteException for an in-process call. } - UserInfo primaryUser = UserManager.get(mContext).getPrimaryUser(); if (currentUser == null) { - logAndThrow("No current user. Only primary user is allowed to take bugreports."); + logAndThrow("There is no current user, so no bugreport can be requested."); } - if (primaryUser == null) { - logAndThrow("No primary user. Only primary user is allowed to take bugreports."); - } - if (primaryUser.id != currentUser.id) { + + if (!currentUser.isAdmin()) { if (bugreportMode == BugreportParams.BUGREPORT_MODE_REMOTE && isCurrentUserAffiliated(currentUser.id)) { return; } - logAndThrow("Current user not primary user. Only primary user" - + " is allowed to take bugreports."); + logAndThrow(TextUtils.formatSimple("Current user %s is not an admin user." + + " Only admin users are allowed to take bugreport.", currentUser.id)); } } diff --git a/services/core/java/com/android/server/pm/AppStateHelper.java b/services/core/java/com/android/server/pm/AppStateHelper.java index 9ea350f265b6..e6e8212ac16a 100644 --- a/services/core/java/com/android/server/pm/AppStateHelper.java +++ b/services/core/java/com/android/server/pm/AppStateHelper.java @@ -16,15 +16,22 @@ package com.android.server.pm; +import static android.media.AudioAttributes.USAGE_VOICE_COMMUNICATION; +import static android.media.AudioAttributes.USAGE_VOICE_COMMUNICATION_SIGNALLING; + import android.app.ActivityManager; import android.app.ActivityManager.RunningAppProcessInfo; +import android.app.ActivityManagerInternal; import android.content.Context; +import android.media.AudioManager; import android.media.IAudioService; import android.os.ServiceManager; +import android.telecom.TelecomManager; import android.text.TextUtils; import android.util.ArraySet; import com.android.internal.util.ArrayUtils; +import com.android.server.LocalServices; import java.util.ArrayList; import java.util.List; @@ -72,6 +79,43 @@ public class AppStateHelper { } /** + * True if any app is using voice communication. + */ + private boolean hasVoiceCall() { + var am = mContext.getSystemService(AudioManager.class); + try { + for (var apc : am.getActivePlaybackConfigurations()) { + if (!apc.isActive()) { + continue; + } + var usage = apc.getAudioAttributes().getUsage(); + if (usage == USAGE_VOICE_COMMUNICATION + || usage == USAGE_VOICE_COMMUNICATION_SIGNALLING) { + return true; + } + } + } catch (Exception ignore) { + } + return false; + } + + /** + * True if the app is recording audio. + */ + private boolean isRecordingAudio(String packageName) { + var am = mContext.getSystemService(AudioManager.class); + try { + for (var arc : am.getActiveRecordingConfigurations()) { + if (TextUtils.equals(arc.getClientPackageName(), packageName)) { + return true; + } + } + } catch (Exception ignore) { + } + return false; + } + + /** * True if the app is in the foreground. */ private boolean isAppForeground(String packageName) { @@ -89,8 +133,7 @@ public class AppStateHelper { * True if the app is playing/recording audio. */ private boolean hasActiveAudio(String packageName) { - // TODO(b/235306967): also check recording - return hasAudioFocus(packageName); + return hasAudioFocus(packageName) || isRecordingAudio(packageName); } /** @@ -143,16 +186,16 @@ public class AppStateHelper { * True if there is an ongoing phone call. */ public boolean isInCall() { - // To be implemented - return false; + // TelecomManager doesn't handle the case where some apps don't implement ConnectionService. + // We check apps using voice communication to detect if the device is in call. + var tm = mContext.getSystemService(TelecomManager.class); + return tm.isInCall() || hasVoiceCall(); } /** * Returns a list of packages which depend on {@code packageNames}. These are the packages * that will be affected when updating {@code packageNames} and should participate in * the evaluation of install constraints. - * - * TODO(b/235306967): Also include bounded services as dependency. */ public List<String> getDependencyPackages(List<String> packageNames) { var results = new ArraySet<String>(); @@ -167,6 +210,10 @@ public class AppStateHelper { } } } + var amInternal = LocalServices.getService(ActivityManagerInternal.class); + for (var packageName : packageNames) { + results.addAll(amInternal.getClientPackages(packageName)); + } return new ArrayList<>(results); } } diff --git a/services/core/java/com/android/server/pm/DeletePackageHelper.java b/services/core/java/com/android/server/pm/DeletePackageHelper.java index 6998db76e338..a6def7d61637 100644 --- a/services/core/java/com/android/server/pm/DeletePackageHelper.java +++ b/services/core/java/com/android/server/pm/DeletePackageHelper.java @@ -261,7 +261,7 @@ final class DeletePackageHelper { final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; info.sendPackageRemovedBroadcasts(killApp, removedBySystem); info.sendSystemPackageUpdatedBroadcasts(); - PackageMetrics.onUninstallSucceeded(info, deleteFlags, mUserManagerInternal); + PackageMetrics.onUninstallSucceeded(info, deleteFlags, userId); } // Force a gc to clear up things. @@ -550,6 +550,7 @@ final class DeletePackageHelper { outInfo.mRemovedUsers = userIds; outInfo.mBroadcastUsers = userIds; outInfo.mIsExternal = ps.isExternalStorage(); + outInfo.mRemovedPackageVersionCode = ps.getVersionCode(); } } diff --git a/services/core/java/com/android/server/pm/InstallPackageHelper.java b/services/core/java/com/android/server/pm/InstallPackageHelper.java index 7553370bf4c6..33fe4c53c89e 100644 --- a/services/core/java/com/android/server/pm/InstallPackageHelper.java +++ b/services/core/java/com/android/server/pm/InstallPackageHelper.java @@ -1608,6 +1608,7 @@ final class InstallPackageHelper { ps.getUninstallReason(userId)); } removedInfo.mIsExternal = oldPackage.isExternalStorage(); + removedInfo.mRemovedPackageVersionCode = oldPackage.getLongVersionCode(); request.setRemovedInfo(removedInfo); sysPkg = oldPackage.isSystem(); @@ -2241,6 +2242,7 @@ final class InstallPackageHelper { @GuardedBy("mPm.mInstallLock") private void executePostCommitStepsLIF(List<ReconciledPackage> reconciledPackages) { final ArraySet<IncrementalStorage> incrementalStorages = new ArraySet<>(); + final ArrayList<String> apkPaths = new ArrayList<>(); for (ReconciledPackage reconciledPkg : reconciledPackages) { final InstallRequest installRequest = reconciledPkg.mInstallRequest; final boolean instantApp = ((installRequest.getScanFlags() & SCAN_AS_INSTANT_APP) != 0); @@ -2260,25 +2262,11 @@ final class InstallPackageHelper { } // Enabling fs-verity is a blocking operation. To reduce the impact to the install time, - // run in a background thread. - final ArrayList<String> apkPaths = new ArrayList<>(); + // collect the files to later enable in a background thread. apkPaths.add(pkg.getBaseApkPath()); if (pkg.getSplitCodePaths() != null) { Collections.addAll(apkPaths, pkg.getSplitCodePaths()); } - mInjector.getBackgroundHandler().post(() -> { - try { - for (String path : apkPaths) { - if (!VerityUtils.hasFsverity(path)) { - VerityUtils.setUpFsverity(path, (byte[]) null); - } - } - } catch (IOException e) { - // There's nothing we can do if the setup failed. Since fs-verity is - // optional, just ignore the error for now. - Slog.e(TAG, "Failed to fully enable fs-verity to " + packageName); - } - }); // Hardcode previousAppId to 0 to disable any data migration (http://b/221088088) mAppDataHelper.prepareAppDataPostCommitLIF(pkg, 0); @@ -2392,6 +2380,20 @@ final class InstallPackageHelper { } PackageManagerServiceUtils.waitForNativeBinariesExtractionForIncremental( incrementalStorages); + + mInjector.getBackgroundHandler().post(() -> { + for (String path : apkPaths) { + if (!VerityUtils.hasFsverity(path)) { + try { + VerityUtils.setUpFsverity(path, (byte[]) null); + } catch (IOException e) { + // There's nothing we can do if the setup failed. Since fs-verity is + // optional, just ignore the error for now. + Slog.e(TAG, "Failed to fully enable fs-verity to " + path); + } + } + } + }); } Pair<Integer, String> verifyReplacingVersionCode(PackageInfoLite pkgLite, diff --git a/services/core/java/com/android/server/pm/InstallRequest.java b/services/core/java/com/android/server/pm/InstallRequest.java index 5974a9cbab67..c6cdc4cd350d 100644 --- a/services/core/java/com/android/server/pm/InstallRequest.java +++ b/services/core/java/com/android/server/pm/InstallRequest.java @@ -773,10 +773,10 @@ final class InstallRequest { } } - public void onInstallCompleted() { + public void onInstallCompleted(int userId) { if (getReturnCode() == INSTALL_SUCCEEDED) { if (mPackageMetrics != null) { - mPackageMetrics.onInstallSucceed(); + mPackageMetrics.onInstallSucceed(userId); } } } diff --git a/services/core/java/com/android/server/pm/InstallingSession.java b/services/core/java/com/android/server/pm/InstallingSession.java index 2b6398af348e..b600aa80b388 100644 --- a/services/core/java/com/android/server/pm/InstallingSession.java +++ b/services/core/java/com/android/server/pm/InstallingSession.java @@ -535,7 +535,7 @@ class InstallingSession { mInstallPackageHelper.installPackagesTraced(installRequests); for (InstallRequest request : installRequests) { - request.onInstallCompleted(); + request.onInstallCompleted(mUser.getIdentifier()); doPostInstall(request); } } diff --git a/services/core/java/com/android/server/pm/PackageInstallerService.java b/services/core/java/com/android/server/pm/PackageInstallerService.java index 409d3524c312..4803c5e873b6 100644 --- a/services/core/java/com/android/server/pm/PackageInstallerService.java +++ b/services/core/java/com/android/server/pm/PackageInstallerService.java @@ -154,6 +154,11 @@ public class PackageInstallerService extends IPackageInstaller.Stub implements /** Destroy sessions older than this on storage free request */ private static final long MAX_SESSION_AGE_ON_LOW_STORAGE_MILLIS = 8 * DateUtils.HOUR_IN_MILLIS; + /** Threshold of historical sessions size */ + private static final int HISTORICAL_SESSIONS_THRESHOLD = 500; + /** Size of historical sessions to be cleared when reaching threshold */ + private static final int HISTORICAL_CLEAR_SIZE = 400; + /** * Allow verification-skipping if it's a development app installed through ADB with * disable verification flag specified. @@ -549,6 +554,10 @@ public class PackageInstallerService extends IPackageInstaller.Stub implements CharArrayWriter writer = new CharArrayWriter(); IndentingPrintWriter pw = new IndentingPrintWriter(writer, " "); session.dump(pw); + if (mHistoricalSessions.size() > HISTORICAL_SESSIONS_THRESHOLD) { + Slog.d(TAG, "Historical sessions size reaches threshold, clear the oldest"); + mHistoricalSessions.subList(0, HISTORICAL_CLEAR_SIZE).clear(); + } mHistoricalSessions.add(writer.toString()); int installerUid = session.getInstallerUid(); diff --git a/services/core/java/com/android/server/pm/PackageManagerLocal.java b/services/core/java/com/android/server/pm/PackageManagerLocal.java index fad61b858902..d163d3d7a085 100644 --- a/services/core/java/com/android/server/pm/PackageManagerLocal.java +++ b/services/core/java/com/android/server/pm/PackageManagerLocal.java @@ -30,7 +30,6 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.List; import java.util.Map; -import java.util.function.Consumer; /** * In-process API for server side PackageManager related infrastructure. @@ -177,8 +176,6 @@ public interface PackageManagerLocal { @NonNull Map<String, PackageState> getPackageStates(); - void forAllPackageStates(@NonNull Consumer<PackageState> consumer); - @Override void close(); } diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java index cf59a1e248e0..91f7011c90c7 100644 --- a/services/core/java/com/android/server/pm/PackageManagerService.java +++ b/services/core/java/com/android/server/pm/PackageManagerService.java @@ -3078,6 +3078,7 @@ public class PackageManagerService implements PackageSender, TestUtilityService info.mRemovedUsers = new int[] {userId}; info.mBroadcastUsers = new int[] {userId}; info.mUid = UserHandle.getUid(userId, packageState.getAppId()); + info.mRemovedPackageVersionCode = packageState.getVersionCode(); info.sendPackageRemovedBroadcasts(true /*killApp*/, false /*removedBySystem*/); } diff --git a/services/core/java/com/android/server/pm/PackageMetrics.java b/services/core/java/com/android/server/pm/PackageMetrics.java index 81f1a987c0a4..8252a9fa65c5 100644 --- a/services/core/java/com/android/server/pm/PackageMetrics.java +++ b/services/core/java/com/android/server/pm/PackageMetrics.java @@ -19,6 +19,7 @@ package com.android.server.pm; import static android.os.Process.INVALID_UID; import android.annotation.IntDef; +import android.app.admin.SecurityLog; import android.content.pm.PackageManager; import android.content.pm.parsing.ApkLiteParseUtils; import android.util.Pair; @@ -67,8 +68,8 @@ final class PackageMetrics { mInstallRequest = installRequest; } - public void onInstallSucceed() { - // TODO(b/239722919): report to SecurityLog if on work profile or managed device + public void onInstallSucceed(int userId) { + reportInstallationToSecurityLog(userId); reportInstallationStats(true /* success */); } @@ -77,8 +78,13 @@ final class PackageMetrics { } private void reportInstallationStats(boolean success) { - UserManagerInternal userManagerInternal = + final UserManagerInternal userManagerInternal = LocalServices.getService(UserManagerInternal.class); + if (userManagerInternal == null) { + // UserManagerService is not available. Skip metrics reporting. + return; + } + final long installDurationMillis = System.currentTimeMillis() - mInstallStartTimestampMillis; // write to stats @@ -196,12 +202,17 @@ final class PackageMetrics { } } - public static void onUninstallSucceeded(PackageRemovedInfo info, int deleteFlags, - UserManagerInternal userManagerInternal) { + public static void onUninstallSucceeded(PackageRemovedInfo info, int deleteFlags, int userId) { if (info.mIsUpdate) { // Not logging uninstalls caused by app updates return; } + final UserManagerInternal userManagerInternal = + LocalServices.getService(UserManagerInternal.class); + if (userManagerInternal == null) { + // UserManagerService is not available. Skip metrics reporting. + return; + } final int[] removedUsers = info.mRemovedUsers; final int[] removedUserTypes = userManagerInternal.getUserTypesForStatsd(removedUsers); final int[] originalUsers = info.mOrigUsers; @@ -210,6 +221,9 @@ final class PackageMetrics { info.mUid, removedUsers, removedUserTypes, originalUsers, originalUserTypes, deleteFlags, PackageManager.DELETE_SUCCEEDED, info.mIsRemovedPackageSystemUpdate, !info.mRemovedForAllUsers); + final String packageName = info.mRemovedPackage; + final long versionCode = info.mRemovedPackageVersionCode; + reportUninstallationToSecurityLog(packageName, versionCode, userId); } public static void onVerificationFailed(VerifyingSession verifyingSession) { @@ -242,4 +256,32 @@ final class PackageMetrics { verifyingSession.isStaged() /* is_staged */ ); } + + private void reportInstallationToSecurityLog(int userId) { + if (!SecurityLog.isLoggingEnabled()) { + return; + } + final PackageSetting ps = mInstallRequest.getScannedPackageSetting(); + if (ps == null) { + return; + } + final String packageName = ps.getPackageName(); + final long versionCode = ps.getVersionCode(); + if (!mInstallRequest.isInstallReplace()) { + SecurityLog.writeEvent(SecurityLog.TAG_PACKAGE_INSTALLED, packageName, versionCode, + userId); + } else { + SecurityLog.writeEvent(SecurityLog.TAG_PACKAGE_UPDATED, packageName, versionCode, + userId); + } + } + + private static void reportUninstallationToSecurityLog(String packageName, long versionCode, + int userId) { + if (!SecurityLog.isLoggingEnabled()) { + return; + } + SecurityLog.writeEvent(SecurityLog.TAG_PACKAGE_UNINSTALLED, packageName, versionCode, + userId); + } } diff --git a/services/core/java/com/android/server/pm/PackageRemovedInfo.java b/services/core/java/com/android/server/pm/PackageRemovedInfo.java index dd580a5e43aa..c762fd3f9648 100644 --- a/services/core/java/com/android/server/pm/PackageRemovedInfo.java +++ b/services/core/java/com/android/server/pm/PackageRemovedInfo.java @@ -51,6 +51,7 @@ final class PackageRemovedInfo { boolean mRemovedForAllUsers; boolean mIsStaticSharedLib; boolean mIsExternal; + long mRemovedPackageVersionCode; // a two dimensional array mapping userId to the set of appIds that can receive notice // of package changes SparseArray<int[]> mBroadcastAllowList; diff --git a/services/core/java/com/android/server/pm/RemovePackageHelper.java b/services/core/java/com/android/server/pm/RemovePackageHelper.java index 8c58397fb1a1..41985e3890fe 100644 --- a/services/core/java/com/android/server/pm/RemovePackageHelper.java +++ b/services/core/java/com/android/server/pm/RemovePackageHelper.java @@ -275,6 +275,7 @@ final class RemovePackageHelper { outInfo.populateUsers(deletedPs.queryInstalledUsers( mUserManagerInternal.getUserIds(), true), deletedPs); outInfo.mIsExternal = deletedPs.isExternalStorage(); + outInfo.mRemovedPackageVersionCode = deletedPs.getVersionCode(); } removePackageLI(deletedPs.getPackageName(), (flags & PackageManager.DELETE_CHATTY) != 0); diff --git a/services/core/java/com/android/server/pm/ResolveIntentHelper.java b/services/core/java/com/android/server/pm/ResolveIntentHelper.java index fada5778b634..622c6ee43cac 100644 --- a/services/core/java/com/android/server/pm/ResolveIntentHelper.java +++ b/services/core/java/com/android/server/pm/ResolveIntentHelper.java @@ -52,6 +52,7 @@ import android.util.Slog; import com.android.internal.app.ResolverActivity; import com.android.internal.util.ArrayUtils; +import com.android.internal.util.FrameworkStatsLog; import com.android.server.am.ActivityManagerService; import com.android.server.compat.PlatformCompat; import com.android.server.pm.pkg.AndroidPackage; @@ -102,7 +103,8 @@ final class ResolveIntentHelper { } private static void filterNonExportedComponents(Intent intent, int filterCallingUid, - List<ResolveInfo> query, PlatformCompat platformCompat, Computer computer) { + List<ResolveInfo> query, PlatformCompat platformCompat, String resolvedType, + Computer computer) { if (query == null || intent.getPackage() != null || intent.getComponent() != null @@ -113,21 +115,24 @@ final class ResolveIntentHelper { String callerPackage = caller == null ? "Not specified" : caller.getPackageName(); for (int i = query.size() - 1; i >= 0; i--) { if (!query.get(i).getComponentInfo().exported) { - if (!platformCompat.isChangeEnabledByUid( + boolean hasToBeExportedToMatch = platformCompat.isChangeEnabledByUid( ActivityManagerService.IMPLICIT_INTENTS_ONLY_MATCH_EXPORTED_COMPONENTS, - filterCallingUid)) { - Slog.w(TAG, "Non-exported component not filtered out " - + "(will be filtered out once the app targets U+)- intent: " - + intent.getAction() + ", component: " - + query.get(i).getComponentInfo() - .getComponentName().flattenToShortString() - + ", starter: " + callerPackage); + filterCallingUid); + String[] categories = intent.getCategories() == null ? new String[0] + : intent.getCategories().toArray(String[]::new); + FrameworkStatsLog.write(FrameworkStatsLog.UNSAFE_INTENT_EVENT_REPORTED, + FrameworkStatsLog.UNSAFE_INTENT_EVENT_REPORTED__EVENT_TYPE__INTERNAL_NON_EXPORTED_COMPONENT_MATCH, + filterCallingUid, + query.get(i).getComponentInfo().getComponentName().flattenToShortString(), + callerPackage, + intent.getAction(), + categories, + resolvedType, + intent.getScheme(), + hasToBeExportedToMatch); + if (!hasToBeExportedToMatch) { return; } - Slog.w(TAG, "Non-exported component filtered out - intent: " - + intent.getAction() + ", component: " - + query.get(i).getComponentInfo().getComponentName().flattenToShortString() - + ", starter: " + callerPackage); query.remove(i); } } @@ -173,7 +178,7 @@ final class ResolveIntentHelper { resolveForStart, true /*allowDynamicSplits*/); if (exportedComponentsOnly) { filterNonExportedComponents(intent, filterCallingUid, query, - mPlatformCompat, computer); + mPlatformCompat, resolvedType, computer); } Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); diff --git a/services/core/java/com/android/server/pm/Settings.java b/services/core/java/com/android/server/pm/Settings.java index bc9f7b21f9a8..89b74f400919 100644 --- a/services/core/java/com/android/server/pm/Settings.java +++ b/services/core/java/com/android/server/pm/Settings.java @@ -369,6 +369,8 @@ public final class Settings implements Watchable, Snappable { // Current settings file. private final File mSettingsFilename; + // Compressed current settings file. + private final File mCompressedSettingsFilename; // Previous settings file. // Removed when the current settings file successfully stored. private final File mPreviousSettingsFilename; @@ -639,6 +641,7 @@ public final class Settings implements Watchable, Snappable { mRuntimePermissionsPersistence = null; mPermissionDataProvider = null; mSettingsFilename = null; + mCompressedSettingsFilename = null; mPreviousSettingsFilename = null; mPackageListFilename = null; mStoppedPackagesFilename = null; @@ -710,6 +713,7 @@ public final class Settings implements Watchable, Snappable { |FileUtils.S_IROTH|FileUtils.S_IXOTH, -1, -1); mSettingsFilename = new File(mSystemDir, "packages.xml"); + mCompressedSettingsFilename = new File(mSystemDir, "packages.compressed"); mPreviousSettingsFilename = new File(mSystemDir, "packages-backup.xml"); mPackageListFilename = new File(mSystemDir, "packages.list"); FileUtils.setPermissions(mPackageListFilename, 0640, SYSTEM_UID, PACKAGE_INFO_GID); @@ -751,6 +755,7 @@ public final class Settings implements Watchable, Snappable { mLock = null; mRuntimePermissionsPersistence = r.mRuntimePermissionsPersistence; mSettingsFilename = null; + mCompressedSettingsFilename = null; mPreviousSettingsFilename = null; mPackageListFilename = null; mStoppedPackagesFilename = null; @@ -2465,7 +2470,7 @@ public final class Settings implements Watchable, Snappable { mReadMessages.append("Reading from backup stopped packages file\n"); PackageManagerService.reportSettingsProblem(Log.INFO, "Need to read from backup stopped packages file"); - if (mSettingsFilename.exists()) { + if (mStoppedPackagesFilename.exists()) { // If both the backup and normal file exist, we // ignore the normal one since it might have been // corrupted. @@ -2588,6 +2593,8 @@ public final class Settings implements Watchable, Snappable { Slog.w(PackageManagerService.TAG, "Preserving older settings backup"); } } + // Compressed settings are not valid anymore. + mCompressedSettingsFilename.delete(); mPastSignatures.clear(); @@ -2677,10 +2684,30 @@ public final class Settings implements Watchable, Snappable { mPreviousSettingsFilename.delete(); FileUtils.setPermissions(mSettingsFilename.toString(), - FileUtils.S_IRUSR|FileUtils.S_IWUSR - |FileUtils.S_IRGRP|FileUtils.S_IWGRP, + FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP | FileUtils.S_IWGRP, -1, -1); + final FileInputStream fis = new FileInputStream(mSettingsFilename); + final AtomicFile compressed = new AtomicFile(mCompressedSettingsFilename); + final FileOutputStream fos = compressed.startWrite(); + + BackgroundThread.getHandler().post(() -> { + try { + if (!nativeCompressLz4(fis.getFD().getInt$(), fos.getFD().getInt$())) { + throw new IOException("Failed to compress"); + } + compressed.finishWrite(fos); + FileUtils.setPermissions(mCompressedSettingsFilename.toString(), + FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP + | FileUtils.S_IWGRP, -1, -1); + } catch (IOException e) { + Slog.e(PackageManagerService.TAG, "Failed to write compressed settings file: " + + mCompressedSettingsFilename, e); + compressed.delete(); + } + IoUtils.closeQuietly(fis); + }); + writeKernelMappingLPr(); writePackageListLPr(); writeAllUsersPackageRestrictionsLPr(sync); @@ -2703,6 +2730,8 @@ public final class Settings implements Watchable, Snappable { //Debug.stopMethodTracing(); } + private native boolean nativeCompressLz4(int inputFd, int outputFd); + private void writeKernelRemoveUserLPr(int userId) { if (mKernelMappingFilename == null) return; diff --git a/services/core/java/com/android/server/pm/ShortcutPackage.java b/services/core/java/com/android/server/pm/ShortcutPackage.java index 0362dddf09a8..4fddc9c17b62 100644 --- a/services/core/java/com/android/server/pm/ShortcutPackage.java +++ b/services/core/java/com/android/server/pm/ShortcutPackage.java @@ -1470,9 +1470,15 @@ class ShortcutPackage extends ShortcutPackageItem { } // Then make sure none of the activities have more than the max number of shortcuts. + int total = 0; for (int i = counts.size() - 1; i >= 0; i--) { - service.enforceMaxActivityShortcuts(counts.valueAt(i)); + int count = counts.valueAt(i); + service.enforceMaxActivityShortcuts(count); + total += count; } + + // Finally make sure that the app doesn't have more than the max number of shortcuts. + service.enforceMaxAppShortcuts(total); } /** diff --git a/services/core/java/com/android/server/pm/ShortcutService.java b/services/core/java/com/android/server/pm/ShortcutService.java index 83720f1445fa..12a33ee488bb 100644 --- a/services/core/java/com/android/server/pm/ShortcutService.java +++ b/services/core/java/com/android/server/pm/ShortcutService.java @@ -181,6 +181,9 @@ public class ShortcutService extends IShortcutService.Stub { static final int DEFAULT_MAX_SHORTCUTS_PER_ACTIVITY = 15; @VisibleForTesting + static final int DEFAULT_MAX_SHORTCUTS_PER_APP = 60; + + @VisibleForTesting static final int DEFAULT_MAX_ICON_DIMENSION_DP = 96; @VisibleForTesting @@ -257,6 +260,11 @@ public class ShortcutService extends IShortcutService.Stub { String KEY_MAX_SHORTCUTS = "max_shortcuts"; /** + * Key name for the max dynamic shortcuts per app. (int) + */ + String KEY_MAX_SHORTCUTS_PER_APP = "max_shortcuts_per_app"; + + /** * Key name for icon compression quality, 0-100. */ String KEY_ICON_QUALITY = "icon_quality"; @@ -329,9 +337,14 @@ public class ShortcutService extends IShortcutService.Stub { new SparseArray<>(); /** + * Max number of dynamic + manifest shortcuts that each activity can have at a time. + */ + private int mMaxShortcutsPerActivity; + + /** * Max number of dynamic + manifest shortcuts that each application can have at a time. */ - private int mMaxShortcuts; + private int mMaxShortcutsPerApp; /** * Max number of updating API calls that each application can make during the interval. @@ -804,9 +817,12 @@ public class ShortcutService extends IShortcutService.Stub { mMaxUpdatesPerInterval = Math.max(0, (int) parser.getLong( ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL, DEFAULT_MAX_UPDATES_PER_INTERVAL)); - mMaxShortcuts = Math.max(0, (int) parser.getLong( + mMaxShortcutsPerActivity = Math.max(0, (int) parser.getLong( ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_ACTIVITY)); + mMaxShortcutsPerApp = Math.max(0, (int) parser.getLong( + ConfigConstants.KEY_MAX_SHORTCUTS_PER_APP, DEFAULT_MAX_SHORTCUTS_PER_APP)); + final int iconDimensionDp = Math.max(1, injectIsLowRamDevice() ? (int) parser.getLong( ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM, @@ -1746,16 +1762,33 @@ public class ShortcutService extends IShortcutService.Stub { * {@link #getMaxActivityShortcuts()}. */ void enforceMaxActivityShortcuts(int numShortcuts) { - if (numShortcuts > mMaxShortcuts) { + if (numShortcuts > mMaxShortcutsPerActivity) { throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded"); } } /** + * @throws IllegalArgumentException if {@code numShortcuts} is bigger than + * {@link #getMaxAppShortcuts()}. + */ + void enforceMaxAppShortcuts(int numShortcuts) { + if (numShortcuts > mMaxShortcutsPerApp) { + throw new IllegalArgumentException("Max number of dynamic shortcuts per app exceeded"); + } + } + + /** * Return the max number of dynamic + manifest shortcuts for each launcher icon. */ int getMaxActivityShortcuts() { - return mMaxShortcuts; + return mMaxShortcutsPerActivity; + } + + /** + * Return the max number of dynamic + manifest shortcuts for each launcher icon. + */ + int getMaxAppShortcuts() { + return mMaxShortcutsPerApp; } /** @@ -2188,6 +2221,8 @@ public class ShortcutService extends IShortcutService.Stub { ps.ensureNotImmutable(shortcut.getId(), /*ignoreInvisible=*/ true); fillInDefaultActivity(Arrays.asList(shortcut)); + enforceMaxAppShortcuts(ps.getShortcutCount()); + if (!shortcut.hasRank()) { shortcut.setRank(0); } @@ -2575,7 +2610,7 @@ public class ShortcutService extends IShortcutService.Stub { throws RemoteException { verifyCaller(packageName, userId); - return mMaxShortcuts; + return mMaxShortcutsPerActivity; } @Override @@ -4724,7 +4759,7 @@ public class ShortcutService extends IShortcutService.Stub { pw.print(" maxUpdatesPerInterval: "); pw.println(mMaxUpdatesPerInterval); pw.print(" maxShortcutsPerActivity: "); - pw.println(mMaxShortcuts); + pw.println(mMaxShortcutsPerActivity); pw.println(); mStatLogger.dump(pw, " "); @@ -5211,7 +5246,7 @@ public class ShortcutService extends IShortcutService.Stub { @VisibleForTesting int getMaxShortcutsForTest() { - return mMaxShortcuts; + return mMaxShortcutsPerActivity; } @VisibleForTesting diff --git a/services/core/java/com/android/server/pm/UserManagerInternal.java b/services/core/java/com/android/server/pm/UserManagerInternal.java index 0f920c6a4e90..2ae8b52da172 100644 --- a/services/core/java/com/android/server/pm/UserManagerInternal.java +++ b/services/core/java/com/android/server/pm/UserManagerInternal.java @@ -59,6 +59,18 @@ public abstract class UserManagerInternal { }) public @interface UserAssignmentResult {} + public static final int USER_START_MODE_FOREGROUND = 1; + public static final int USER_START_MODE_BACKGROUND = 2; + public static final int USER_START_MODE_BACKGROUND_VISIBLE = 3; + + private static final String PREFIX_USER_START_MODE = "USER_START_MODE_"; + @IntDef(flag = false, prefix = {PREFIX_USER_START_MODE}, value = { + USER_START_MODE_FOREGROUND, + USER_START_MODE_BACKGROUND, + USER_START_MODE_BACKGROUND_VISIBLE + }) + public @interface UserStartMode {} + public interface UserRestrictionsListener { /** * Called when a user restriction changes. @@ -141,23 +153,39 @@ public abstract class UserManagerInternal { /** * Called by {@link com.android.server.devicepolicy.DevicePolicyManagerService} to update * whether the device is managed by device owner. + * + * @deprecated Use methods in {@link android.app.admin.DevicePolicyManagerInternal}. */ + @Deprecated + // TODO(b/258213147): Remove public abstract void setDeviceManaged(boolean isManaged); /** * Returns whether the device is managed by device owner. + * + * @deprecated Use methods in {@link android.app.admin.DevicePolicyManagerInternal}. */ + @Deprecated + // TODO(b/258213147): Remove public abstract boolean isDeviceManaged(); /** * Called by {@link com.android.server.devicepolicy.DevicePolicyManagerService} to update * whether the user is managed by profile owner. + * + * @deprecated Use methods in {@link android.app.admin.DevicePolicyManagerInternal}. */ + // TODO(b/258213147): Remove + @Deprecated public abstract void setUserManaged(int userId, boolean isManaged); /** - * whether a profile owner manages this user. + * Whether a profile owner manages this user. + * + * @deprecated Use methods in {@link android.app.admin.DevicePolicyManagerInternal}. */ + // TODO(b/258213147): Remove + @Deprecated public abstract boolean isUserManaged(int userId); /** @@ -367,8 +395,7 @@ public abstract class UserManagerInternal { * pass a valid display id. */ public abstract @UserAssignmentResult int assignUserToDisplayOnStart(@UserIdInt int userId, - @UserIdInt int profileGroupId, - boolean foreground, int displayId); + @UserIdInt int profileGroupId, @UserStartMode int userStartMode, int displayId); /** * Unassigns a user from its current display when it's stopping. @@ -429,6 +456,13 @@ public abstract class UserManagerInternal { result); } + /** + * Gets the user-friendly representation of a user start {@code mode}. + */ + public static String userStartModeToString(@UserStartMode int mode) { + return DebugUtils.constantToString(UserManagerInternal.class, PREFIX_USER_START_MODE, mode); + } + /** Adds a {@link UserVisibilityListener}. */ public abstract void addUserVisibilityListener(UserVisibilityListener listener); diff --git a/services/core/java/com/android/server/pm/UserManagerService.java b/services/core/java/com/android/server/pm/UserManagerService.java index 3234e87a7125..0a650c912b3e 100644 --- a/services/core/java/com/android/server/pm/UserManagerService.java +++ b/services/core/java/com/android/server/pm/UserManagerService.java @@ -93,6 +93,7 @@ import android.os.storage.StorageManagerInternal; import android.provider.Settings; import android.service.voice.VoiceInteractionManagerInternal; import android.stats.devicepolicy.DevicePolicyEnums; +import android.telecom.TelecomManager; import android.text.TextUtils; import android.util.ArrayMap; import android.util.ArraySet; @@ -126,8 +127,10 @@ import com.android.server.LocalServices; import com.android.server.LockGuard; import com.android.server.SystemService; import com.android.server.am.UserState; +import com.android.server.pm.UserManagerInternal.UserAssignmentResult; import com.android.server.pm.UserManagerInternal.UserLifecycleListener; import com.android.server.pm.UserManagerInternal.UserRestrictionsListener; +import com.android.server.pm.UserManagerInternal.UserStartMode; import com.android.server.pm.UserManagerInternal.UserVisibilityListener; import com.android.server.storage.DeviceStorageMonitorInternal; import com.android.server.utils.Slogf; @@ -1970,6 +1973,63 @@ public class UserManagerService extends IUserManager.Stub { } } + /** + * Returns whether switching users is currently allowed for the provided user. + * <p> + * Switching users is not allowed in the following cases: + * <li>the user is in a phone call</li> + * <li>{@link UserManager#DISALLOW_USER_SWITCH} is set</li> + * <li>system user hasn't been unlocked yet</li> + * + * @return A {@link UserManager.UserSwitchabilityResult} flag indicating if the user is + * switchable. + */ + public @UserManager.UserSwitchabilityResult int getUserSwitchability(int userId) { + checkManageOrInteractPermissionIfCallerInOtherProfileGroup(userId, "getUserSwitchability"); + + final TimingsTraceAndSlog t = new TimingsTraceAndSlog(); + t.traceBegin("getUserSwitchability-" + userId); + + int flags = UserManager.SWITCHABILITY_STATUS_OK; + + t.traceBegin("TM.isInCall"); + final long identity = Binder.clearCallingIdentity(); + try { + final TelecomManager telecomManager = mContext.getSystemService(TelecomManager.class); + if (telecomManager != null && telecomManager.isInCall()) { + flags |= UserManager.SWITCHABILITY_STATUS_USER_IN_CALL; + } + } finally { + Binder.restoreCallingIdentity(identity); + } + t.traceEnd(); + + t.traceBegin("hasUserRestriction-DISALLOW_USER_SWITCH"); + if (mLocalService.hasUserRestriction(DISALLOW_USER_SWITCH, userId)) { + flags |= UserManager.SWITCHABILITY_STATUS_USER_SWITCH_DISALLOWED; + } + t.traceEnd(); + + // System User is always unlocked in Headless System User Mode, so ignore this flag + if (!isHeadlessSystemUserMode()) { + t.traceBegin("getInt-ALLOW_USER_SWITCHING_WHEN_SYSTEM_USER_LOCKED"); + final boolean allowUserSwitchingWhenSystemUserLocked = Settings.Global.getInt( + mContext.getContentResolver(), + Settings.Global.ALLOW_USER_SWITCHING_WHEN_SYSTEM_USER_LOCKED, 0) != 0; + t.traceEnd(); + t.traceBegin("isUserUnlocked-USER_SYSTEM"); + final boolean systemUserUnlocked = mLocalService.isUserUnlocked(UserHandle.USER_SYSTEM); + t.traceEnd(); + + if (!allowUserSwitchingWhenSystemUserLocked && !systemUserUnlocked) { + flags |= UserManager.SWITCHABILITY_STATUS_SYSTEM_USER_LOCKED; + } + } + t.traceEnd(); + + return flags; + } + @VisibleForTesting boolean isUserSwitcherEnabled(@UserIdInt int mUserId) { boolean multiUserSettingOn = Settings.Global.getInt(mContext.getContentResolver(), @@ -6602,6 +6662,7 @@ public class UserManagerService extends IUserManager.Stub { } } + // TODO(b/258213147): Remove @Override public void setDeviceManaged(boolean isManaged) { synchronized (mUsersLock) { @@ -6609,6 +6670,7 @@ public class UserManagerService extends IUserManager.Stub { } } + // TODO(b/258213147): Remove @Override public boolean isDeviceManaged() { synchronized (mUsersLock) { @@ -6616,6 +6678,7 @@ public class UserManagerService extends IUserManager.Stub { } } + // TODO(b/258213147): Remove @Override public void setUserManaged(@UserIdInt int userId, boolean isManaged) { synchronized (mUsersLock) { @@ -6623,6 +6686,7 @@ public class UserManagerService extends IUserManager.Stub { } } + // TODO(b/258213147): Remove @Override public boolean isUserManaged(@UserIdInt int userId) { synchronized (mUsersLock) { @@ -6919,8 +6983,11 @@ public class UserManagerService extends IUserManager.Stub { } @Override - public int assignUserToDisplayOnStart(@UserIdInt int userId, @UserIdInt int profileGroupId, - boolean foreground, int displayId) { + @UserAssignmentResult + public int assignUserToDisplayOnStart(@UserIdInt int userId, + @UserIdInt int profileGroupId, @UserStartMode int userStartMode, int displayId) { + // TODO(245939659): change UserVisibilityMediator to take @UserStartMode + boolean foreground = userStartMode == UserManagerInternal.USER_START_MODE_FOREGROUND; return mUserVisibilityMediator.assignUserToDisplayOnStart(userId, profileGroupId, foreground, displayId); } diff --git a/services/core/java/com/android/server/pm/UserVisibilityMediator.java b/services/core/java/com/android/server/pm/UserVisibilityMediator.java index 9b9ca1088064..92e8f55287d4 100644 --- a/services/core/java/com/android/server/pm/UserVisibilityMediator.java +++ b/services/core/java/com/android/server/pm/UserVisibilityMediator.java @@ -139,7 +139,7 @@ public final class UserVisibilityMediator implements Dumpable { } /** - * See {@link UserManagerInternal#assignUserToDisplayOnStart(int, int, boolean, int)}. + * See {@link UserManagerInternal#assignUserToDisplayOnStart(int, int, int, int)}. */ public @UserAssignmentResult int assignUserToDisplayOnStart(@UserIdInt int userId, @UserIdInt int unResolvedProfileGroupId, boolean foreground, int displayId) { diff --git a/services/core/java/com/android/server/pm/dex/ArtStatsLogUtils.java b/services/core/java/com/android/server/pm/dex/ArtStatsLogUtils.java index 9f21097d4910..f0bf1ea80570 100644 --- a/services/core/java/com/android/server/pm/dex/ArtStatsLogUtils.java +++ b/services/core/java/com/android/server/pm/dex/ArtStatsLogUtils.java @@ -299,7 +299,8 @@ public class ArtStatsLogUtils { apkType, ISA_MAP.getOrDefault(isa, ArtStatsLog.ART_DATUM_REPORTED__ISA__ART_ISA_UNKNOWN), - ArtStatsLog.ART_DATUM_REPORTED__GC__ART_GC_COLLECTOR_TYPE_UNKNOWN); + ArtStatsLog.ART_DATUM_REPORTED__GC__ART_GC_COLLECTOR_TYPE_UNKNOWN, + ArtStatsLog.ART_DATUM_REPORTED__UFFD_SUPPORT__ART_UFFD_SUPPORT_UNKNOWN); } } diff --git a/services/core/java/com/android/server/pm/local/PackageManagerLocalImpl.java b/services/core/java/com/android/server/pm/local/PackageManagerLocalImpl.java index 024b63ea5fe2..f8e154755cff 100644 --- a/services/core/java/com/android/server/pm/local/PackageManagerLocalImpl.java +++ b/services/core/java/com/android/server/pm/local/PackageManagerLocalImpl.java @@ -34,7 +34,6 @@ import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.function.Consumer; /** @hide */ public class PackageManagerLocalImpl implements PackageManagerLocal { @@ -198,18 +197,5 @@ public class PackageManagerLocalImpl implements PackageManagerLocal { return mFilteredPackageStates; } - - @Override - public void forAllPackageStates(@NonNull Consumer<PackageState> consumer) { - checkClosed(); - - var packageStates = mSnapshot.getPackageStates(); - for (int index = 0, size = packageStates.size(); index < size; index++) { - var packageState = packageStates.valueAt(index); - if (!mSnapshot.shouldFilterApplication(packageState, mCallingUid, mUserId)) { - consumer.accept(packageState); - } - } - } } } diff --git a/services/core/java/com/android/server/pm/permission/Permission.java b/services/core/java/com/android/server/pm/permission/Permission.java index 69e7bf119304..165c52d990ee 100644 --- a/services/core/java/com/android/server/pm/permission/Permission.java +++ b/services/core/java/com/android/server/pm/permission/Permission.java @@ -322,6 +322,10 @@ public final class Permission { return (mPermissionInfo.protectionLevel & PermissionInfo.PROTECTION_FLAG_COMPANION) != 0; } + public boolean isModule() { + return (mPermissionInfo.protectionLevel & PermissionInfo.PROTECTION_FLAG_MODULE) != 0; + } + public boolean isRetailDemo() { return (mPermissionInfo.protectionLevel & PermissionInfo.PROTECTION_FLAG_RETAIL_DEMO) != 0; } diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java index e56edeb73ad7..2a2bcab56258 100644 --- a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java +++ b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java @@ -238,6 +238,8 @@ public class PermissionManagerServiceImpl implements PermissionManagerServiceInt NOTIFICATION_PERMISSIONS.add(Manifest.permission.POST_NOTIFICATIONS); } + @NonNull private final ApexManager mApexManager; + /** Set of source package names for Privileged Permission Allowlist */ private final ArraySet<String> mPrivilegedPermissionAllowlistSourcePackageNames = new ArraySet<>(); @@ -421,6 +423,7 @@ public class PermissionManagerServiceImpl implements PermissionManagerServiceInt mPackageManagerInt = LocalServices.getService(PackageManagerInternal.class); mUserManagerInt = LocalServices.getService(UserManagerInternal.class); mIsLeanback = availableFeatures.containsKey(PackageManager.FEATURE_LEANBACK); + mApexManager = ApexManager.getInstance(); mPrivilegedPermissionAllowlistSourcePackageNames.add(PLATFORM_PACKAGE_NAME); // PackageManager.hasSystemFeature() is not used here because PackageManagerService @@ -3309,9 +3312,8 @@ public class PermissionManagerServiceImpl implements PermissionManagerServiceInt return true; } final String permissionName = permission.getName(); - final ApexManager apexManager = ApexManager.getInstance(); final String containingApexPackageName = - apexManager.getActiveApexPackageNameContainingPackage(packageName); + mApexManager.getActiveApexPackageNameContainingPackage(packageName); if (isInSystemConfigPrivAppPermissions(pkg, permissionName, containingApexPackageName)) { return true; @@ -3365,8 +3367,7 @@ public class PermissionManagerServiceImpl implements PermissionManagerServiceInt } else if (pkg.isSystemExt()) { permissions = systemConfig.getSystemExtPrivAppPermissions(pkg.getPackageName()); } else if (containingApexPackageName != null) { - final ApexManager apexManager = ApexManager.getInstance(); - final String apexName = apexManager.getApexModuleNameForPackageName( + final String apexName = mApexManager.getApexModuleNameForPackageName( containingApexPackageName); final Set<String> privAppPermissions = systemConfig.getPrivAppPermissions( pkg.getPackageName()); @@ -3582,6 +3583,11 @@ public class PermissionManagerServiceImpl implements PermissionManagerServiceInt // Special permission for the recents app. allowed = true; } + if (!allowed && bp.isModule() && mApexManager.getActiveApexPackageNameContainingPackage( + pkg.getPackageName()) != null) { + // Special permission granted for APKs inside APEX modules. + allowed = true; + } return allowed; } diff --git a/services/core/java/com/android/server/pm/snapshot/PackageDataSnapshot.java b/services/core/java/com/android/server/pm/snapshot/PackageDataSnapshot.java index b2080b2d43b1..90a0c7cdf609 100644 --- a/services/core/java/com/android/server/pm/snapshot/PackageDataSnapshot.java +++ b/services/core/java/com/android/server/pm/snapshot/PackageDataSnapshot.java @@ -16,7 +16,6 @@ package com.android.server.pm.snapshot; -import android.annotation.SystemApi; import android.content.pm.PackageManagerInternal; import com.android.server.pm.Computer; @@ -32,6 +31,5 @@ import com.android.server.pm.PackageManagerService; * * @hide */ -@SystemApi(client = SystemApi.Client.SYSTEM_SERVER) public interface PackageDataSnapshot { } diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java index 2f0f88a0c019..7919e193ca04 100644 --- a/services/core/java/com/android/server/policy/PhoneWindowManager.java +++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java @@ -1054,6 +1054,19 @@ public class PhoneWindowManager implements WindowManagerPolicy { return; } + // Make sure the device locks. Unfortunately, this has the side-effect of briefly revealing + // the lock screen before the dream appears. Note that this locking behavior needs to + // happen regardless of whether we end up dreaming (below) or not. + // TODO(b/261662912): Find a better way to lock the device that doesn't result in jank. + lockNow(null); + + // Don't dream if the user isn't user zero. + // TODO(b/261907079): Move this check to DreamManagerService#canStartDreamingInternal(). + if (ActivityManager.getCurrentUser() != UserHandle.USER_SYSTEM) { + noDreamAction.run(); + return; + } + final DreamManagerInternal dreamManagerInternal = getDreamManagerInternal(); if (dreamManagerInternal == null || !dreamManagerInternal.canStartDreaming(isScreenOn)) { noDreamAction.run(); @@ -1714,6 +1727,11 @@ public class PhoneWindowManager implements WindowManagerPolicy { } } + private void showSystemSettings() { + startActivityAsUser(new Intent(android.provider.Settings.ACTION_SETTINGS), + UserHandle.CURRENT_OR_SELF); + } + private void showPictureInPictureMenu(KeyEvent event) { if (DEBUG_INPUT) Log.d(TAG, "showPictureInPictureMenu event=" + event); mHandler.removeMessages(MSG_SHOW_PICTURE_IN_PICTURE_MENU); @@ -2868,16 +2886,7 @@ public class PhoneWindowManager implements WindowManagerPolicy { switch(keyCode) { case KeyEvent.KEYCODE_HOME: - // First we always handle the home key here, so applications - // can never break it, although if keyguard is on, we do let - // it handle it, because that gives us the correct 5 second - // timeout. - DisplayHomeButtonHandler handler = mDisplayHomeButtonHandlers.get(displayId); - if (handler == null) { - handler = new DisplayHomeButtonHandler(displayId); - mDisplayHomeButtonHandlers.put(displayId, handler); - } - return handler.handleHomeButton(focusedToken, event); + return handleHomeShortcuts(displayId, focusedToken, event); case KeyEvent.KEYCODE_MENU: // Hijack modified menu keys for debugging features final int chordBug = KeyEvent.META_SHIFT_ON; @@ -2900,6 +2909,25 @@ public class PhoneWindowManager implements WindowManagerPolicy { } } return key_consumed; + case KeyEvent.KEYCODE_A: + if (down && event.isMetaPressed()) { + launchAssistAction(Intent.EXTRA_ASSIST_INPUT_HINT_KEYBOARD, + event.getDeviceId(), + event.getEventTime(), AssistUtils.INVOCATION_TYPE_UNKNOWN); + return key_consumed; + } + break; + case KeyEvent.KEYCODE_H: + if (down && event.isMetaPressed()) { + return handleHomeShortcuts(displayId, focusedToken, event); + } + break; + case KeyEvent.KEYCODE_I: + if (down && event.isMetaPressed()) { + showSystemSettings(); + return key_consumed; + } + break; case KeyEvent.KEYCODE_N: if (down && event.isMetaPressed()) { IStatusBarService service = getStatusBarService(); @@ -2933,6 +2961,11 @@ public class PhoneWindowManager implements WindowManagerPolicy { if (down && event.isMetaPressed() && event.isCtrlPressed() && repeatCount == 0) { enterStageSplitFromRunningApp(true /* leftOrTop */); return key_consumed; + } else if (!down && event.isMetaPressed()) { + boolean backKeyHandled = backKeyPress(); + if (backKeyHandled) { + return key_consumed; + } } break; case KeyEvent.KEYCODE_DPAD_RIGHT: @@ -2941,6 +2974,14 @@ public class PhoneWindowManager implements WindowManagerPolicy { return key_consumed; } break; + case KeyEvent.KEYCODE_GRAVE: + if (!down && event.isMetaPressed()) { + boolean backKeyHandled = backKeyPress(); + if (backKeyHandled) { + return key_consumed; + } + } + break; case KeyEvent.KEYCODE_SLASH: if (down && repeatCount == 0 && event.isMetaPressed() && !keyguardOn) { toggleKeyboardShortcutsMenu(event.getDeviceId()); @@ -3040,12 +3081,13 @@ public class PhoneWindowManager implements WindowManagerPolicy { } break; case KeyEvent.KEYCODE_TAB: - if (event.isMetaPressed()) { - // Pass through keyboard navigation keys. - return key_not_consumed; - } - // Display task switcher for ALT-TAB. - if (down && repeatCount == 0) { + if (down && event.isMetaPressed()) { + if (!keyguardOn && isUserSetupComplete()) { + showRecentApps(false); + return key_consumed; + } + } else if (down && repeatCount == 0) { + // Display task switcher for ALT-TAB. if (mRecentAppsHeldModifiers == 0 && !keyguardOn && isUserSetupComplete()) { final int shiftlessModifiers = event.getModifiers() & ~KeyEvent.META_SHIFT_MASK; @@ -3100,9 +3142,7 @@ public class PhoneWindowManager implements WindowManagerPolicy { mPendingCapsLockToggle = false; } else if (mPendingMetaAction) { if (!canceled) { - launchAssistAction(Intent.EXTRA_ASSIST_INPUT_HINT_KEYBOARD, - event.getDeviceId(), - event.getEventTime(), AssistUtils.INVOCATION_TYPE_UNKNOWN); + // TODO: launch all apps here. } mPendingMetaAction = false; } @@ -3157,6 +3197,19 @@ public class PhoneWindowManager implements WindowManagerPolicy { return key_not_consumed; } + private int handleHomeShortcuts(int displayId, IBinder focusedToken, KeyEvent event) { + // First we always handle the home key here, so applications + // can never break it, although if keyguard is on, we do let + // it handle it, because that gives us the correct 5 second + // timeout. + DisplayHomeButtonHandler handler = mDisplayHomeButtonHandlers.get(displayId); + if (handler == null) { + handler = new DisplayHomeButtonHandler(displayId); + mDisplayHomeButtonHandlers.put(displayId, handler); + } + return handler.handleHomeButton(focusedToken, event); + } + private void toggleMicrophoneMuteFromKey() { if (mSensorPrivacyManager.supportsSensorToggle( SensorPrivacyManager.TOGGLE_TYPE_SOFTWARE, diff --git a/services/core/java/com/android/server/power/ThermalManagerService.java b/services/core/java/com/android/server/power/ThermalManagerService.java index f3785885e4ec..6b2c6e30efe7 100644 --- a/services/core/java/com/android/server/power/ThermalManagerService.java +++ b/services/core/java/com/android/server/power/ThermalManagerService.java @@ -19,16 +19,18 @@ package com.android.server.power; import android.annotation.NonNull; import android.annotation.Nullable; import android.content.Context; +import android.hardware.thermal.IThermal; +import android.hardware.thermal.IThermalChangedCallback; +import android.hardware.thermal.TemperatureThreshold; +import android.hardware.thermal.ThrottlingSeverity; import android.hardware.thermal.V1_0.ThermalStatus; import android.hardware.thermal.V1_0.ThermalStatusCode; import android.hardware.thermal.V1_1.IThermalCallback; -import android.hardware.thermal.V2_0.IThermalChangedCallback; -import android.hardware.thermal.V2_0.TemperatureThreshold; -import android.hardware.thermal.V2_0.ThrottlingSeverity; import android.os.Binder; import android.os.CoolingDevice; import android.os.Handler; import android.os.HwBinder; +import android.os.IBinder; import android.os.IThermalEventListener; import android.os.IThermalService; import android.os.IThermalStatusListener; @@ -37,6 +39,7 @@ import android.os.Process; import android.os.RemoteCallbackList; import android.os.RemoteException; import android.os.ResultReceiver; +import android.os.ServiceManager; import android.os.ShellCallback; import android.os.ShellCommand; import android.os.SystemClock; @@ -56,12 +59,14 @@ import com.android.server.SystemService; import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; /** * This is a system service that listens to HAL thermal events and dispatch those to listeners. @@ -98,7 +103,7 @@ public class ThermalManagerService extends SystemService { @GuardedBy("mLock") private int mStatus; - /** If override status takes effect*/ + /** If override status takes effect */ @GuardedBy("mLock") private boolean mIsStatusOverride; @@ -144,6 +149,10 @@ public class ThermalManagerService extends SystemService { // Connect to HAL and post to listeners. boolean halConnected = (mHalWrapper != null); if (!halConnected) { + mHalWrapper = new ThermalHalAidlWrapper(); + halConnected = mHalWrapper.connectToHal(); + } + if (!halConnected) { mHalWrapper = new ThermalHal20Wrapper(); halConnected = mHalWrapper.connectToHal(); } @@ -684,6 +693,162 @@ public class ThermalManagerService extends SystemService { } } + @VisibleForTesting + static class ThermalHalAidlWrapper extends ThermalHalWrapper implements IBinder.DeathRecipient { + /* Proxy object for the Thermal HAL AIDL service. */ + private IThermal mInstance = null; + + /** Callback for Thermal HAL AIDL. */ + private final IThermalChangedCallback mThermalChangedCallback = + new IThermalChangedCallback.Stub() { + @Override public void notifyThrottling( + android.hardware.thermal.Temperature temperature) + throws RemoteException { + Temperature svcTemperature = new Temperature(temperature.value, + temperature.type, temperature.name, temperature.throttlingStatus); + final long token = Binder.clearCallingIdentity(); + try { + mCallback.onValues(svcTemperature); + } finally { + Binder.restoreCallingIdentity(token); + } + } + + @Override public int getInterfaceVersion() throws RemoteException { + return this.VERSION; + } + + @Override public String getInterfaceHash() throws RemoteException { + return this.HASH; + } + }; + + @Override + protected List<Temperature> getCurrentTemperatures(boolean shouldFilter, + int type) { + synchronized (mHalLock) { + final List<Temperature> ret = new ArrayList<>(); + if (mInstance == null) { + return ret; + } + try { + final android.hardware.thermal.Temperature[] halRet = + shouldFilter ? mInstance.getTemperaturesWithType(type) + : mInstance.getTemperatures(); + for (android.hardware.thermal.Temperature t : halRet) { + if (!Temperature.isValidStatus(t.throttlingStatus)) { + Slog.e(TAG, "Invalid temperature status " + t.throttlingStatus + + " received from AIDL HAL"); + t.throttlingStatus = Temperature.THROTTLING_NONE; + } + if (shouldFilter && t.type != type) { + continue; + } + ret.add(new Temperature(t.value, t.type, t.name, t.throttlingStatus)); + } + } catch (RemoteException e) { + Slog.e(TAG, "Couldn't getCurrentTemperatures, reconnecting", e); + connectToHal(); + } + return ret; + } + } + + @Override + protected List<CoolingDevice> getCurrentCoolingDevices(boolean shouldFilter, + int type) { + synchronized (mHalLock) { + final List<CoolingDevice> ret = new ArrayList<>(); + if (mInstance == null) { + return ret; + } + try { + final android.hardware.thermal.CoolingDevice[] halRet = shouldFilter + ? mInstance.getCoolingDevicesWithType(type) + : mInstance.getCoolingDevices(); + for (android.hardware.thermal.CoolingDevice t : halRet) { + if (!CoolingDevice.isValidType(t.type)) { + Slog.e(TAG, "Invalid cooling device type " + t.type + " from AIDL HAL"); + continue; + } + if (shouldFilter && t.type != type) { + continue; + } + ret.add(new CoolingDevice(t.value, t.type, t.name)); + } + } catch (RemoteException e) { + Slog.e(TAG, "Couldn't getCurrentCoolingDevices, reconnecting", e); + connectToHal(); + } + return ret; + } + } + + @Override + @NonNull protected List<TemperatureThreshold> getTemperatureThresholds( + boolean shouldFilter, int type) { + synchronized (mHalLock) { + final List<TemperatureThreshold> ret = new ArrayList<>(); + if (mInstance == null) { + return ret; + } + try { + final TemperatureThreshold[] halRet = + shouldFilter ? mInstance.getTemperatureThresholdsWithType(type) + : mInstance.getTemperatureThresholds(); + + return Arrays.stream(halRet).filter(t -> t.type == type).collect( + Collectors.toList()); + } catch (RemoteException e) { + Slog.e(TAG, "Couldn't getTemperatureThresholds, reconnecting...", e); + connectToHal(); + } + return ret; + } + } + + @Override + protected boolean connectToHal() { + synchronized (mHalLock) { + IBinder binder = Binder.allowBlocking(ServiceManager.waitForDeclaredService( + IThermal.DESCRIPTOR + "/default")); + initProxyAndRegisterCallback(binder); + } + return mInstance != null; + } + + @VisibleForTesting + void initProxyAndRegisterCallback(IBinder binder) { + synchronized (mHalLock) { + if (binder != null) { + mInstance = IThermal.Stub.asInterface(binder); + try { + binder.linkToDeath(this, 0); + mInstance.registerThermalChangedCallback(mThermalChangedCallback); + } catch (RemoteException e) { + Slog.e(TAG, "Unable to connect IThermal AIDL instance", e); + mInstance = null; + } + } + } + } + + @Override + protected void dump(PrintWriter pw, String prefix) { + synchronized (mHalLock) { + pw.print(prefix); + pw.println( + "ThermalHAL AIDL " + IThermal.VERSION + " connected: " + (mInstance != null + ? "yes" : "no")); + } + } + + @Override + public synchronized void binderDied() { + Slog.w(TAG, "IThermal HAL instance died"); + mInstance = null; + } + } static class ThermalHal10Wrapper extends ThermalHalWrapper { /** Proxy object for the Thermal HAL 1.0 service. */ @@ -814,8 +979,8 @@ public class ThermalManagerService extends SystemService { android.hardware.thermal.V1_0.Temperature temperature) { Temperature thermalSvcTemp = new Temperature( temperature.currentValue, temperature.type, temperature.name, - isThrottling ? ThrottlingSeverity.SEVERE - : ThrottlingSeverity.NONE); + isThrottling ? Temperature.THROTTLING_SEVERE + : Temperature.THROTTLING_NONE); final long token = Binder.clearCallingIdentity(); try { mCallback.onValues(thermalSvcTemp); @@ -941,8 +1106,9 @@ public class ThermalManagerService extends SystemService { private android.hardware.thermal.V2_0.IThermal mThermalHal20 = null; /** HWbinder callback for Thermal HAL 2.0. */ - private final IThermalChangedCallback.Stub mThermalCallback20 = - new IThermalChangedCallback.Stub() { + private final android.hardware.thermal.V2_0.IThermalChangedCallback.Stub + mThermalCallback20 = + new android.hardware.thermal.V2_0.IThermalChangedCallback.Stub() { @Override public void notifyThrottling( android.hardware.thermal.V2_0.Temperature temperature) { @@ -976,7 +1142,7 @@ public class ThermalManagerService extends SystemService { temperature.throttlingStatus)) { Slog.e(TAG, "Invalid status data from HAL"); temperature.throttlingStatus = - Temperature.THROTTLING_NONE; + Temperature.THROTTLING_NONE; } ret.add(new Temperature( temperature.value, temperature.type, @@ -1043,7 +1209,9 @@ public class ThermalManagerService extends SystemService { mThermalHal20.getTemperatureThresholds(shouldFilter, type, (status, thresholds) -> { if (ThermalStatusCode.SUCCESS == status.code) { - ret.addAll(thresholds); + ret.addAll(thresholds.stream().map( + this::convertToAidlTemperatureThreshold).collect( + Collectors.toList())); } else { Slog.e(TAG, "Couldn't get temperature thresholds because of HAL " @@ -1057,6 +1225,16 @@ public class ThermalManagerService extends SystemService { } } + private TemperatureThreshold convertToAidlTemperatureThreshold( + android.hardware.thermal.V2_0.TemperatureThreshold threshold) { + final TemperatureThreshold ret = new TemperatureThreshold(); + ret.name = threshold.name; + ret.type = threshold.type; + ret.coldThrottlingThresholds = threshold.coldThrottlingThresholds; + ret.hotThrottlingThresholds = threshold.hotThrottlingThresholds; + return ret; + } + @Override protected boolean connectToHal() { synchronized (mHalLock) { 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 af4fa85ba5a3..2a88473cb895 100644 --- a/services/core/java/com/android/server/power/stats/BatteryStatsImpl.java +++ b/services/core/java/com/android/server/power/stats/BatteryStatsImpl.java @@ -4658,10 +4658,10 @@ public class BatteryStatsImpl extends BatteryStats { final int mappedUid = mapUid(uid); if (type == WAKE_TYPE_PARTIAL) { mWakeLockNesting--; + if (historyName == null) { + historyName = name; + } if (mRecordAllHistory) { - if (historyName == null) { - historyName = name; - } if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, mappedUid, 0)) { mHistory.recordEvent(elapsedRealtimeMs, uptimeMs, @@ -4669,8 +4669,8 @@ public class BatteryStatsImpl extends BatteryStats { } } if (mWakeLockNesting == 0) { - mHistory.recordStateStopEvent(elapsedRealtimeMs, uptimeMs, - HistoryItem.STATE_WAKE_LOCK_FLAG); + mHistory.recordWakelockStopEvent(elapsedRealtimeMs, uptimeMs, historyName, + mappedUid); } } if (mappedUid >= 0) { diff --git a/services/core/java/com/android/server/power/stats/BatteryUsageStatsProvider.java b/services/core/java/com/android/server/power/stats/BatteryUsageStatsProvider.java index c36d950b6cf6..7da9197eb7b1 100644 --- a/services/core/java/com/android/server/power/stats/BatteryUsageStatsProvider.java +++ b/services/core/java/com/android/server/power/stats/BatteryUsageStatsProvider.java @@ -286,16 +286,15 @@ public class BatteryUsageStatsProvider { BatteryStats.Uid.PROCESS_STATE_FOREGROUND, realtimeUs, BatteryStats.STATS_SINCE_CHARGED); - totalForegroundDurationUs += uid.getProcessStateTime( - BatteryStats.Uid.PROCESS_STATE_FOREGROUND_SERVICE, realtimeUs, - BatteryStats.STATS_SINCE_CHARGED); - return totalForegroundDurationUs / 1000; } private long getProcessBackgroundTimeMs(BatteryStats.Uid uid, long realtimeUs) { - return uid.getProcessStateTime(BatteryStats.Uid.PROCESS_STATE_BACKGROUND, realtimeUs, - BatteryStats.STATS_SINCE_CHARGED) / 1000; + return (uid.getProcessStateTime(BatteryStats.Uid.PROCESS_STATE_BACKGROUND, + realtimeUs, BatteryStats.STATS_SINCE_CHARGED) + + uid.getProcessStateTime(BatteryStats.Uid.PROCESS_STATE_FOREGROUND_SERVICE, + realtimeUs, BatteryStats.STATS_SINCE_CHARGED)) + / 1000; } private BatteryUsageStats getAggregatedBatteryUsageStats(BatteryUsageStatsQuery query) { diff --git a/services/core/java/com/android/server/security/rkp/OWNERS b/services/core/java/com/android/server/security/rkp/OWNERS new file mode 100644 index 000000000000..348f94048311 --- /dev/null +++ b/services/core/java/com/android/server/security/rkp/OWNERS @@ -0,0 +1 @@ +file:platform/frameworks/base:master:/core/java/android/security/rkp/OWNERS diff --git a/services/core/java/com/android/server/security/rkp/RemoteProvisioningService.java b/services/core/java/com/android/server/security/rkp/RemoteProvisioningService.java new file mode 100644 index 000000000000..65a4b38629b6 --- /dev/null +++ b/services/core/java/com/android/server/security/rkp/RemoteProvisioningService.java @@ -0,0 +1,126 @@ +/* + * 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.security.rkp; + +import android.content.Context; +import android.os.Binder; +import android.os.OutcomeReceiver; +import android.os.RemoteException; +import android.security.rkp.IGetKeyCallback; +import android.security.rkp.IGetRegistrationCallback; +import android.security.rkp.IRegistration; +import android.security.rkp.IRemoteProvisioning; +import android.security.rkp.service.RegistrationProxy; +import android.util.Log; + +import com.android.server.SystemService; + +import java.time.Duration; + +/** + * Implements the remote provisioning system service. This service is backed by a mainline + * module, allowing the underlying implementation to be updated. The code here is a thin + * proxy for the code in android.security.rkp.service. + * + * @hide + */ +public class RemoteProvisioningService extends SystemService { + public static final String TAG = "RemoteProvisionSysSvc"; + private static final Duration CREATE_REGISTRATION_TIMEOUT = Duration.ofSeconds(10); + private final RemoteProvisioningImpl mBinderImpl = new RemoteProvisioningImpl(); + + /** @hide */ + public RemoteProvisioningService(Context context) { + super(context); + } + + @Override + public void onStart() { + publishBinderService(Context.REMOTE_PROVISIONING_SERVICE, mBinderImpl); + } + + private final class RemoteProvisioningImpl extends IRemoteProvisioning.Stub { + + final class RegistrationBinder extends IRegistration.Stub { + static final String TAG = RemoteProvisioningService.TAG; + private final RegistrationProxy mRegistration; + + RegistrationBinder(RegistrationProxy registration) { + mRegistration = registration; + } + + @Override + public void getKey(int keyId, IGetKeyCallback callback) { + Log.e(TAG, "RegistrationBinder.getKey NOT YET IMPLEMENTED"); + } + + @Override + public void cancelGetKey(IGetKeyCallback callback) { + Log.e(TAG, "RegistrationBinder.cancelGetKey NOT YET IMPLEMENTED"); + } + + @Override + public void storeUpgradedKey(byte[] oldKeyBlob, byte[] newKeyBlob) { + Log.e(TAG, "RegistrationBinder.storeUpgradedKey NOT YET IMPLEMENTED"); + } + } + + @Override + public void getRegistration(String irpcName, IGetRegistrationCallback callback) + throws RemoteException { + final int callerUid = Binder.getCallingUidOrThrow(); + final long callingIdentity = Binder.clearCallingIdentity(); + try { + Log.i(TAG, "getRegistration(" + irpcName + ")"); + RegistrationProxy.createAsync( + getContext(), + callerUid, + irpcName, + CREATE_REGISTRATION_TIMEOUT, + getContext().getMainExecutor(), + new OutcomeReceiver<>() { + @Override + public void onResult(RegistrationProxy registration) { + try { + callback.onSuccess(new RegistrationBinder(registration)); + } catch (RemoteException e) { + Log.e(TAG, "Error calling success callback", e); + } + } + + @Override + public void onError(Exception error) { + try { + callback.onError(error.toString()); + } catch (RemoteException e) { + Log.e(TAG, "Error calling error callback", e); + } + } + }); + } finally { + Binder.restoreCallingIdentity(callingIdentity); + } + } + + @Override + public void cancelGetRegistration(IGetRegistrationCallback callback) + throws RemoteException { + Log.i(TAG, "cancelGetRegistration()"); + callback.onError("cancelGetRegistration not yet implemented"); + } + } +} diff --git a/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java b/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java index 5d084616bfea..4480d521323e 100644 --- a/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java +++ b/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java @@ -34,6 +34,7 @@ import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER; import android.annotation.NonNull; import android.app.ActivityManager; +import android.app.ActivityOptions; import android.app.AppGlobals; import android.app.AppOpsManager; import android.app.ILocalWallpaperColorConsumer; @@ -3166,6 +3167,15 @@ public class WallpaperManagerService extends IWallpaperManager.Stub } } + final ActivityOptions clientOptions = ActivityOptions.makeBasic(); + clientOptions.setIgnorePendingIntentCreatorForegroundState(true); + PendingIntent clientIntent = PendingIntent.getActivityAsUser( + mContext, 0, Intent.createChooser( + new Intent(Intent.ACTION_SET_WALLPAPER), + mContext.getText(com.android.internal.R.string.chooser_wallpaper)), + PendingIntent.FLAG_IMMUTABLE, clientOptions.toBundle(), + UserHandle.of(serviceUserId)); + // Bind the service! if (DEBUG) Slog.v(TAG, "Binding to:" + componentName); final int componentUid = mIPackageManager.getPackageUid(componentName.getPackageName(), @@ -3174,11 +3184,7 @@ public class WallpaperManagerService extends IWallpaperManager.Stub intent.setComponent(componentName); intent.putExtra(Intent.EXTRA_CLIENT_LABEL, com.android.internal.R.string.wallpaper_binding_label); - intent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivityAsUser( - mContext, 0, - Intent.createChooser(new Intent(Intent.ACTION_SET_WALLPAPER), - mContext.getText(com.android.internal.R.string.chooser_wallpaper)), - PendingIntent.FLAG_IMMUTABLE, null, new UserHandle(serviceUserId))); + intent.putExtra(Intent.EXTRA_CLIENT_INTENT, clientIntent); if (!mContext.bindServiceAsUser(intent, newConn, Context.BIND_AUTO_CREATE | Context.BIND_SHOWING_UI | Context.BIND_FOREGROUND_SERVICE_WHILE_AWAKE diff --git a/services/core/java/com/android/server/wearable/WearableSensingManagerService.java b/services/core/java/com/android/server/wearable/WearableSensingManagerService.java index 707d00449ef5..e14589860a86 100644 --- a/services/core/java/com/android/server/wearable/WearableSensingManagerService.java +++ b/services/core/java/com/android/server/wearable/WearableSensingManagerService.java @@ -38,6 +38,7 @@ import android.provider.DeviceConfig; import android.util.Slog; import com.android.internal.R; +import com.android.internal.annotations.VisibleForTesting; import com.android.server.LocalServices; import com.android.server.SystemService; import com.android.server.infra.AbstractMasterSystemService; @@ -161,7 +162,7 @@ public class WearableSensingManagerService extends return null; } - // Used in testing. + @VisibleForTesting void provideDataStream(@UserIdInt int userId, ParcelFileDescriptor parcelFileDescriptor, RemoteCallback callback) { synchronized (mLock) { @@ -174,7 +175,7 @@ public class WearableSensingManagerService extends } } - // Used in testing. + @VisibleForTesting void provideData(@UserIdInt int userId, PersistableBundle data, SharedMemory sharedMemory, RemoteCallback callback) { synchronized (mLock) { diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java index aec06f0a25dd..f725d1a11243 100644 --- a/services/core/java/com/android/server/wm/ActivityRecord.java +++ b/services/core/java/com/android/server/wm/ActivityRecord.java @@ -513,7 +513,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A // dies. After an activity is launched it follows the value // of #mIcicle. boolean launchFailed; // set if a launched failed, to abort on 2nd try - boolean stopped; // is activity pause finished? boolean delayedResume; // not yet resumed because of stopped app switches? boolean finishing; // activity in pending finish list? boolean deferRelaunchUntilPaused; // relaunch of activity is being deferred until pause is @@ -796,12 +795,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A // TODO: Make this final int mTargetSdk; - // Is this window's surface needed? This is almost like visible, except - // it will sometimes be true a little earlier: when the activity record has - // been shown, but is still waiting for its app transition to execute - // before making its windows shown. - private boolean mVisibleRequested; - // Last visibility state we reported to the app token. boolean reportedVisible; @@ -881,6 +874,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A boolean mOverrideTaskTransition; boolean mDismissKeyguard; + /** True if the activity has reported stopped; False if the activity becomes visible. */ boolean mAppStopped; // A hint to override the window specified rotation animation, or -1 to use the window specified // value. We use this so that we can select the right animation in the cases of starting @@ -1141,7 +1135,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A pw.print(prefix); pw.print("mHaveState="); pw.print(mHaveState); pw.print(" mIcicle="); pw.println(mIcicle); pw.print(prefix); pw.print("state="); pw.print(mState); - pw.print(" stopped="); pw.print(stopped); pw.print(" delayedResume="); pw.print(delayedResume); pw.print(" finishing="); pw.println(finishing); pw.print(prefix); pw.print("keysPaused="); pw.print(keysPaused); @@ -1574,15 +1567,9 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A if (oldParent != null) { oldParent.cleanUpActivityReferences(this); - // Update isVisibleRequested value of parent TaskFragment and send the callback to the - // client side if needed. - oldParent.onActivityVisibleRequestedChanged(); } if (newParent != null) { - // Update isVisibleRequested value of parent TaskFragment and send the callback to the - // client side if needed. - newParent.onActivityVisibleRequestedChanged(); if (isState(RESUMED)) { newParent.setResumedActivity(this, "onParentChanged"); mImeInsetsFrozenUntilStartInput = false; @@ -2033,7 +2020,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A requestCode = _reqCode; setState(INITIALIZING, "ActivityRecord ctor"); launchFailed = false; - stopped = false; delayedResume = false; finishing = false; deferRelaunchUntilPaused = false; @@ -3883,7 +3869,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A } taskFragment.sendTaskFragmentInfoChanged(); } - if (stopped) { + if (mAppStopped) { abortAndClearOptionsAnimation(); } } @@ -5086,11 +5072,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A return mVisible; } - @Override - boolean isVisibleRequested() { - return mVisibleRequested; - } - void setVisible(boolean visible) { if (visible != mVisible) { mVisible = visible; @@ -5105,16 +5086,9 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A * This is the only place that writes {@link #mVisibleRequested} (except unit test). The caller * outside of this class should use {@link #setVisibility}. */ - @VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE) - void setVisibleRequested(boolean visible) { - if (visible == mVisibleRequested) { - return; - } - mVisibleRequested = visible; - final TaskFragment taskFragment = getTaskFragment(); - if (taskFragment != null) { - taskFragment.onActivityVisibleRequestedChanged(); - } + @Override + boolean setVisibleRequested(boolean visible) { + if (!super.setVisibleRequested(visible)) return false; setInsetsFrozen(!visible); if (app != null) { mTaskSupervisor.onProcessActivityStateChanged(app, false /* forceBatch */); @@ -5123,6 +5097,13 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A if (!visible) { finishOrAbortReplacingWindow(); } + return true; + } + + @Override + protected boolean onChildVisibleRequestedChanged(@Nullable WindowContainer child) { + // Activity manages visibleRequested directly (it's not determined by children) + return false; } /** @@ -5724,11 +5705,12 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A } } - void notifyAppResumed(boolean wasStopped) { + void notifyAppResumed() { if (getParent() == null) { Slog.w(TAG_WM, "Attempted to notify resumed of non-existing app token: " + token); return; } + final boolean wasStopped = mAppStopped; ProtoLog.v(WM_DEBUG_ADD_REMOVE, "notifyAppResumed: wasStopped=%b %s", wasStopped, this); mAppStopped = false; @@ -5743,32 +5725,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A } /** - * Notify that the app has stopped, and it is okay to destroy any surfaces which were - * keeping alive in case they were still being used. - */ - void notifyAppStopped() { - ProtoLog.v(WM_DEBUG_ADD_REMOVE, "notifyAppStopped: %s", this); - mAppStopped = true; - firstWindowDrawn = false; - // This is to fix the edge case that auto-enter-pip is finished in Launcher but app calls - // setAutoEnterEnabled(false) and transitions to STOPPED state, see b/191930787. - // Clear any surface transactions and content overlay in this case. - if (task != null && task.mLastRecentsAnimationTransaction != null) { - task.clearLastRecentsAnimationTransaction(true /* forceRemoveOverlay */); - } - // Reset the last saved PiP snap fraction on app stop. - mDisplayContent.mPinnedTaskController.onActivityHidden(mActivityComponent); - mDisplayContent.mUnknownAppVisibilityController.appRemovedOrHidden(this); - if (isClientVisible()) { - // Though this is usually unlikely to happen, still make sure the client is invisible. - setClientVisible(false); - } - destroySurfaces(); - // Remove any starting window that was added for this app if they are still around. - removeStartingWindow(); - } - - /** * Suppress transition until the new activity becomes ready, otherwise the keyguard can appear * for a short amount of time before the new process with the new activity had the ability to * set its showWhenLocked flags. @@ -6128,7 +6084,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A mLastNewIntent = newIntents.get(newIntents.size() - 1); } newIntents = null; - stopped = false; if (isActivityTypeHome()) { mTaskSupervisor.updateHomeProcess(task.getBottomMostActivity().app); @@ -6250,7 +6205,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A } resumeKeyDispatchingLocked(); try { - stopped = false; ProtoLog.v(WM_DEBUG_STATES, "Moving to STOPPING: %s (stop requested)", this); setState(STOPPING, "stopIfPossible"); @@ -6268,7 +6222,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A // notification will clean things up. Slog.w(TAG, "Exception thrown during pause", e); // Just in case, assume it to be stopped. - stopped = true; + mAppStopped = true; ProtoLog.v(WM_DEBUG_STATES, "Stop failed; moving to STOPPED: %s", this); setState(STOPPED, "stopIfPossible"); if (deferRelaunchUntilPaused) { @@ -6277,12 +6231,16 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A } } + /** + * Notifies that the activity has stopped, and it is okay to destroy any surfaces which were + * keeping alive in case they were still being used. + */ void activityStopped(Bundle newIcicle, PersistableBundle newPersistentState, CharSequence description) { + removeStopTimeout(); final boolean isStopping = mState == STOPPING; if (!isStopping && mState != RESTARTING_PROCESS) { Slog.i(TAG, "Activity reported stop, but no longer stopping: " + this + " " + mState); - removeStopTimeout(); return; } if (newPersistentState != null) { @@ -6298,28 +6256,42 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A updateTaskDescription(description); } ProtoLog.i(WM_DEBUG_STATES, "Saving icicle of %s: %s", this, mIcicle); - if (!stopped) { + + if (isStopping) { ProtoLog.v(WM_DEBUG_STATES, "Moving to STOPPED: %s (stop complete)", this); - removeStopTimeout(); - stopped = true; - if (isStopping) { - setState(STOPPED, "activityStoppedLocked"); - } + setState(STOPPED, "activityStopped"); + } - notifyAppStopped(); + mAppStopped = true; + firstWindowDrawn = false; + // This is to fix the edge case that auto-enter-pip is finished in Launcher but app calls + // setAutoEnterEnabled(false) and transitions to STOPPED state, see b/191930787. + // Clear any surface transactions and content overlay in this case. + if (task.mLastRecentsAnimationTransaction != null) { + task.clearLastRecentsAnimationTransaction(true /* forceRemoveOverlay */); + } + // Reset the last saved PiP snap fraction on app stop. + mDisplayContent.mPinnedTaskController.onActivityHidden(mActivityComponent); + mDisplayContent.mUnknownAppVisibilityController.appRemovedOrHidden(this); + if (isClientVisible()) { + // Though this is usually unlikely to happen, still make sure the client is invisible. + setClientVisible(false); + } + destroySurfaces(); + // Remove any starting window that was added for this app if they are still around. + removeStartingWindow(); - if (finishing) { - abortAndClearOptionsAnimation(); + if (finishing) { + abortAndClearOptionsAnimation(); + } else { + if (deferRelaunchUntilPaused) { + destroyImmediately("stop-config"); + mRootWindowContainer.resumeFocusedTasksTopActivities(); } else { - if (deferRelaunchUntilPaused) { - destroyImmediately("stop-config"); - mRootWindowContainer.resumeFocusedTasksTopActivities(); - } else { - mAtmService.updatePreviousProcess(this); - } + mAtmService.updatePreviousProcess(this); } - mTaskSupervisor.checkReadyForSleepLocked(true /* allowDelay */); } + mTaskSupervisor.checkReadyForSleepLocked(true /* allowDelay */); } void addToStopping(boolean scheduleIdle, boolean idleDelayed, String reason) { @@ -6857,7 +6829,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A private ActivityRecord getWaitingHistoryRecordLocked() { // First find the real culprit... if this activity has stopped, then the key dispatching // timeout should not be caused by this. - if (stopped) { + if (mAppStopped) { final Task rootTask = mRootWindowContainer.getTopDisplayFocusedRootTask(); if (rootTask == null) { return this; @@ -6938,7 +6910,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A } if (isState(RESUMED) || getRootTask() == null || this == getTaskFragment().getPausingActivity() - || !mHaveState || !stopped) { + || !mHaveState || !mAppStopped) { // We're not ready for this kind of thing. return false; } @@ -7700,6 +7672,10 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A // This activity may relaunch or perform configuration change so once it has reported drawn, // the screen can be unfrozen. ensureActivityConfiguration(0 /* globalChanges */, !PRESERVE_WINDOWS); + if (mTransitionController.isCollecting(this)) { + // In case the task was changed from PiP but still keeps old transform. + task.resetSurfaceControlTransforms(); + } } void setRequestedOrientation(int requestedOrientation) { diff --git a/services/core/java/com/android/server/wm/ActivityStarter.java b/services/core/java/com/android/server/wm/ActivityStarter.java index 1e063754c8c3..2f4d154503d1 100644 --- a/services/core/java/com/android/server/wm/ActivityStarter.java +++ b/services/core/java/com/android/server/wm/ActivityStarter.java @@ -2285,6 +2285,15 @@ class ActivityStarter { mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK; } + if (r.info.requiredDisplayCategory != null && mSourceRecord != null + && !r.info.requiredDisplayCategory.equals( + mSourceRecord.info.requiredDisplayCategory)) { + // Adding NEW_TASK flag for activity with display category attribute if the display + // category of the source record is different, so that the activity won't be launched + // in source record's task. + mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK; + } + sendNewTaskResultRequestIfNeeded(); if ((mLaunchFlags & FLAG_ACTIVITY_NEW_DOCUMENT) != 0 && r.resultTo == null) { @@ -2372,6 +2381,12 @@ class ActivityStarter { Slog.w(TAG, "Starting activity in task not in recents: " + inTask); mInTask = null; } + // Prevent to start activity in Task with different display category + if (mInTask != null && !mInTask.isSameRequiredDisplayCategory(r.info)) { + Slog.w(TAG, "Starting activity in task with different display category: " + + mInTask); + mInTask = null; + } mInTaskFragment = inTaskFragment; mStartFlags = startFlags; diff --git a/services/core/java/com/android/server/wm/BackNavigationController.java b/services/core/java/com/android/server/wm/BackNavigationController.java index b16602e0e475..14131e693561 100644 --- a/services/core/java/com/android/server/wm/BackNavigationController.java +++ b/services/core/java/com/android/server/wm/BackNavigationController.java @@ -235,6 +235,7 @@ class BackNavigationController { // We don't have an application callback, let's find the destination of the back gesture // The search logic should align with ActivityClientController#finishActivity prevActivity = currentTask.topRunningActivity(currentActivity.token, INVALID_TASK_ID); + final boolean isOccluded = isKeyguardOccluded(window); // TODO Dialog window does not need to attach on activity, check // window.mAttrs.type != TYPE_BASE_APPLICATION if ((window.getParent().getChildCount() > 1 @@ -244,16 +245,24 @@ class BackNavigationController { backType = BackNavigationInfo.TYPE_DIALOG_CLOSE; removedWindowContainer = window; } else if (prevActivity != null) { - // We have another Activity in the same currentTask to go to - backType = BackNavigationInfo.TYPE_CROSS_ACTIVITY; - removedWindowContainer = currentActivity; - prevTask = prevActivity.getTask(); + if (!isOccluded || prevActivity.canShowWhenLocked()) { + // We have another Activity in the same currentTask to go to + backType = BackNavigationInfo.TYPE_CROSS_ACTIVITY; + removedWindowContainer = currentActivity; + prevTask = prevActivity.getTask(); + } else { + backType = BackNavigationInfo.TYPE_CALLBACK; + } } else if (currentTask.returnsToHomeRootTask()) { - // Our Task should bring back to home - removedWindowContainer = currentTask; - prevTask = currentTask.getDisplayArea().getRootHomeTask(); - backType = BackNavigationInfo.TYPE_RETURN_TO_HOME; - mShowWallpaper = true; + if (isOccluded) { + backType = BackNavigationInfo.TYPE_CALLBACK; + } else { + // Our Task should bring back to home + removedWindowContainer = currentTask; + prevTask = currentTask.getDisplayArea().getRootHomeTask(); + backType = BackNavigationInfo.TYPE_RETURN_TO_HOME; + mShowWallpaper = true; + } } else if (currentActivity.isRootOfTask()) { // TODO(208789724): Create single source of truth for this, maybe in // RootWindowContainer @@ -267,7 +276,9 @@ class BackNavigationController { backType = BackNavigationInfo.TYPE_CALLBACK; } else { prevActivity = prevTask.getTopNonFinishingActivity(); - if (prevTask.isActivityTypeHome()) { + if (prevActivity == null || (isOccluded && !prevActivity.canShowWhenLocked())) { + backType = BackNavigationInfo.TYPE_CALLBACK; + } else if (prevTask.isActivityTypeHome()) { backType = BackNavigationInfo.TYPE_RETURN_TO_HOME; mShowWallpaper = true; } else { @@ -323,6 +334,12 @@ class BackNavigationController { return mAnimationTargets.mComposed && mAnimationTargets.mWaitTransition; } + boolean isKeyguardOccluded(WindowState focusWindow) { + final KeyguardController kc = mWindowManagerService.mAtmService.mKeyguardController; + final int displayId = focusWindow.getDisplayId(); + return kc.isKeyguardLocked(displayId) && kc.isDisplayOccluded(displayId); + } + // For legacy transition. /** * Once we find the transition targets match back animation targets, remove the target from diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java index d5802cf37bad..c6dc24f32837 100644 --- a/services/core/java/com/android/server/wm/DisplayContent.java +++ b/services/core/java/com/android/server/wm/DisplayContent.java @@ -3392,6 +3392,9 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp if (!controller.isCollecting(this)) { controller.collect(this); startAsyncRotationIfNeeded(); + if (mFixedRotationLaunchingApp != null) { + setSeamlessTransitionForFixedRotation(controller.getCollectingTransition()); + } } return; } @@ -3401,12 +3404,8 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp mAtmService.startLaunchPowerMode(POWER_MODE_REASON_CHANGE_DISPLAY); if (mFixedRotationLaunchingApp != null) { // A fixed-rotation transition is done, then continue to start a seamless display - // transition. And be fore the start transaction is applied, the non-app windows - // need to keep in previous rotation to avoid showing inconsistent content. - t.setSeamlessRotation(this); - if (mAsyncRotationController != null) { - mAsyncRotationController.keepAppearanceInPreviousRotation(); - } + // transition. + setSeamlessTransitionForFixedRotation(t); } else if (isRotationChanging()) { if (displayChange != null) { final boolean seamless = mDisplayRotation.shouldRotateSeamlessly( @@ -3425,6 +3424,15 @@ class DisplayContent extends RootDisplayArea implements WindowManagerPolicy.Disp } } + private void setSeamlessTransitionForFixedRotation(Transition t) { + t.setSeamlessRotation(this); + // Before the start transaction is applied, the non-app windows need to keep in previous + // rotation to avoid showing inconsistent content. + if (mAsyncRotationController != null) { + mAsyncRotationController.keepAppearanceInPreviousRotation(); + } + } + /** If the display is in transition, there should be a screenshot covering it. */ @Override boolean inTransition() { diff --git a/services/core/java/com/android/server/wm/DisplayPolicy.java b/services/core/java/com/android/server/wm/DisplayPolicy.java index b419f36e45a3..300deca1d09a 100644 --- a/services/core/java/com/android/server/wm/DisplayPolicy.java +++ b/services/core/java/com/android/server/wm/DisplayPolicy.java @@ -2128,15 +2128,10 @@ public class DisplayPolicy { } void updateSystemBarAttributes() { - WindowState winCandidate = mFocusedWindow; - if (winCandidate == null && mTopFullscreenOpaqueWindowState != null - && (mTopFullscreenOpaqueWindowState.mAttrs.flags - & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) == 0) { - // Only focusable window can take system bar control. - winCandidate = mTopFullscreenOpaqueWindowState; - } // If there is no window focused, there will be nobody to handle the events // anyway, so just hang on in whatever state we're in until things settle down. + WindowState winCandidate = mFocusedWindow != null ? mFocusedWindow + : mTopFullscreenOpaqueWindowState; if (winCandidate == null) { return; } diff --git a/services/core/java/com/android/server/wm/RootWindowContainer.java b/services/core/java/com/android/server/wm/RootWindowContainer.java index 1ee4d6b5eb3b..749fa1f6610b 100644 --- a/services/core/java/com/android/server/wm/RootWindowContainer.java +++ b/services/core/java/com/android/server/wm/RootWindowContainer.java @@ -418,7 +418,8 @@ class RootWindowContainer extends WindowContainer<DisplayContent> } else if (!isDocument && !taskIsDocument && mIdealRecord == null && mCandidateRecord == null && task.rootAffinity != null) { - if (task.rootAffinity.equals(mTaskAffinity)) { + if (task.rootAffinity.equals(mTaskAffinity) + && task.isSameRequiredDisplayCategory(mInfo)) { ProtoLog.d(WM_DEBUG_TASKS, "Found matching affinity candidate!"); // It is possible for multiple tasks to have the same root affinity especially // if they are in separate root tasks. We save off this candidate, but keep @@ -2099,6 +2100,7 @@ class RootWindowContainer extends WindowContainer<DisplayContent> // from the client organizer, so the PIP activity can get the correct config // from the Task, and prevent conflict with the PipTaskOrganizer. tf.updateRequestedOverrideConfiguration(EMPTY); + tf.updateRelativeEmbeddedBounds(); } }); rootTask.setWindowingMode(WINDOWING_MODE_PINNED); diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java index a74a4b001670..03e3e936c179 100644 --- a/services/core/java/com/android/server/wm/Task.java +++ b/services/core/java/com/android/server/wm/Task.java @@ -491,6 +491,9 @@ class Task extends TaskFragment { private int mForceHiddenFlags = 0; private boolean mForceTranslucent = false; + // The display category name for this task. + String mRequiredDisplayCategory; + // TODO(b/160201781): Revisit double invocation issue in Task#removeChild. /** * Skip {@link ActivityTaskSupervisor#removeTask(Task, boolean, boolean, String)} execution if @@ -1011,6 +1014,7 @@ class Task extends TaskFragment { // affinity -- we don't want it changing after initially set, but the initially // set value may be null. rootAffinity = affinity; + mRequiredDisplayCategory = info.requiredDisplayCategory; } effectiveUid = info.applicationInfo.uid; mIsEffectivelySystemApp = info.applicationInfo.isSystemApp(); @@ -1121,11 +1125,12 @@ class Task extends TaskFragment { if (inMultiWindowMode() || !hasChild()) return false; if (intent != null) { final int returnHomeFlags = FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_TASK_ON_HOME; + if ((intent.getFlags() & returnHomeFlags) != returnHomeFlags) { + return false; + } final Task task = getDisplayArea() != null ? getDisplayArea().getRootHomeTask() : null; - final boolean isLockTaskModeViolation = task != null - && mAtmService.getLockTaskController().isLockTaskModeViolation(task); - return (intent.getFlags() & returnHomeFlags) == returnHomeFlags - && !isLockTaskModeViolation; + return !(task != null + && mAtmService.getLockTaskController().isLockTaskModeViolation(task)); } final Task bottomTask = getBottomMostTask(); return bottomTask != this && bottomTask.returnsToHomeRootTask(); @@ -1591,15 +1596,22 @@ class Task extends TaskFragment { removeChild(r, reason); }); } else { + final ArrayList<ActivityRecord> finishingActivities = new ArrayList<>(); + forAllActivities(r -> { + if (r.finishing || (excludingTaskOverlay && r.isTaskOverlay())) { + return; + } + finishingActivities.add(r); + }); + // Finish or destroy apps from the bottom to ensure that all the other activity have // been finished and the top task in another task gets resumed when a top activity is // removed. Otherwise, the next top activity could be started while the top activity // is removed, which is not necessary since the next top activity is on the same Task // and should also be removed. - forAllActivities((r) -> { - if (r.finishing || (excludingTaskOverlay && r.isTaskOverlay())) { - return; - } + for (int i = finishingActivities.size() - 1; i >= 0; i--) { + final ActivityRecord r = finishingActivities.get(i); + // Prevent the transition from being executed too early if the top activity is // resumed but the mVisibleRequested of any other activity is true, the transition // should wait until next activity resumed. @@ -1609,7 +1621,7 @@ class Task extends TaskFragment { } else { r.destroyIfPossible(reason); } - }, false /* traverseTopToBottom */); + } } } @@ -1914,7 +1926,6 @@ class Task extends TaskFragment { mTaskSupervisor.scheduleUpdateMultiWindowMode(this); } - final int newWinMode = getWindowingMode(); if (shouldStartChangeTransition(prevWinMode, mTmpPrevBounds)) { initializeChangeTransition(mTmpPrevBounds); } @@ -1928,16 +1939,15 @@ class Task extends TaskFragment { } } - if (pipChanging && wasInPictureInPicture) { + if (pipChanging && wasInPictureInPicture + && !mTransitionController.isShellTransitionsEnabled()) { // If the top activity is changing from PiP to fullscreen with fixed rotation, // clear the crop and rotation matrix of task because fixed rotation will handle // the transformation on activity level. This also avoids flickering caused by the // latency of fullscreen task organizer configuring the surface. final ActivityRecord r = topRunningActivity(); if (r != null && mDisplayContent.isFixedRotationLaunchingApp(r)) { - getSyncTransaction().setWindowCrop(mSurfaceControl, null) - .setCornerRadius(mSurfaceControl, 0f) - .setMatrix(mSurfaceControl, Matrix.IDENTITY_MATRIX, new float[9]); + resetSurfaceControlTransforms(); } } @@ -3529,13 +3539,10 @@ class Task extends TaskFragment { } @Override - void onActivityVisibleRequestedChanged() { - final boolean prevVisibleRequested = mVisibleRequested; - // mVisibleRequested is updated in super method. - super.onActivityVisibleRequestedChanged(); - if (prevVisibleRequested != mVisibleRequested) { - sendTaskFragmentParentInfoChangedIfNeeded(); - } + protected boolean onChildVisibleRequestedChanged(@Nullable WindowContainer child) { + if (!super.onChildVisibleRequestedChanged(child)) return false; + sendTaskFragmentParentInfoChangedIfNeeded(); + return true; } void sendTaskFragmentParentInfoChangedIfNeeded() { @@ -6076,6 +6083,15 @@ class Task extends TaskFragment { } } + /** + * Return true if the activityInfo has the same requiredDisplayCategory as this task. + */ + boolean isSameRequiredDisplayCategory(@NonNull ActivityInfo info) { + return mRequiredDisplayCategory != null && mRequiredDisplayCategory.equals( + info.requiredDisplayCategory) + || (mRequiredDisplayCategory == null && info.requiredDisplayCategory == null); + } + @Override public void dumpDebug(ProtoOutputStream proto, long fieldId, @WindowTraceLogLevel int logLevel) { diff --git a/services/core/java/com/android/server/wm/TaskFragment.java b/services/core/java/com/android/server/wm/TaskFragment.java index 66b868a9107c..9126586bafd9 100644 --- a/services/core/java/com/android/server/wm/TaskFragment.java +++ b/services/core/java/com/android/server/wm/TaskFragment.java @@ -302,6 +302,14 @@ class TaskFragment extends WindowContainer<WindowContainer> { private final IBinder mFragmentToken; /** + * The bounds of the embedded TaskFragment relative to the parent Task. + * {@code null} if it is not {@link #mIsEmbedded} + * TODO(b/261785978) cleanup with legacy app transition + */ + @Nullable + private final Rect mRelativeEmbeddedBounds; + + /** * Whether to delay the call to {@link #updateOrganizedTaskFragmentSurface()} when there is a * configuration change. */ @@ -316,9 +324,6 @@ class TaskFragment extends WindowContainer<WindowContainer> { final Point mLastSurfaceSize = new Point(); - /** The latest updated value when there's a child {@link #onActivityVisibleRequestedChanged} */ - boolean mVisibleRequested; - private final Rect mTmpBounds = new Rect(); private final Rect mTmpFullBounds = new Rect(); /** For calculating screenWidthDp and screenWidthDp, i.e. the area without the system bars. */ @@ -383,6 +388,7 @@ class TaskFragment extends WindowContainer<WindowContainer> { mRootWindowContainer = mAtmService.mRootWindowContainer; mCreatedByOrganizer = createdByOrganizer; mIsEmbedded = isEmbedded; + mRelativeEmbeddedBounds = isEmbedded ? new Rect() : null; mTaskFragmentOrganizerController = mAtmService.mWindowOrganizerController.mTaskFragmentOrganizerController; mFragmentToken = fragmentToken; @@ -1355,7 +1361,7 @@ class TaskFragment extends WindowContainer<WindowContainer> { if (next.attachedToProcess()) { if (DEBUG_SWITCH) { - Slog.v(TAG_SWITCH, "Resume running: " + next + " stopped=" + next.stopped + Slog.v(TAG_SWITCH, "Resume running: " + next + " stopped=" + next.mAppStopped + " visibleRequested=" + next.isVisibleRequested()); } @@ -1370,7 +1376,7 @@ class TaskFragment extends WindowContainer<WindowContainer> { || mLastPausedActivity != null && !mLastPausedActivity.occludesParent(); // This activity is now becoming visible. - if (!next.isVisibleRequested() || next.stopped || lastActivityTranslucent) { + if (!next.isVisibleRequested() || next.mAppStopped || lastActivityTranslucent) { next.app.addToPendingTop(); next.setVisibility(true); } @@ -1421,7 +1427,7 @@ class TaskFragment extends WindowContainer<WindowContainer> { // Do over! mTaskSupervisor.scheduleResumeTopActivities(); } - if (!next.isVisibleRequested() || next.stopped) { + if (!next.isVisibleRequested() || next.mAppStopped) { next.setVisibility(true); } next.completeResumeLocked(); @@ -1450,7 +1456,7 @@ class TaskFragment extends WindowContainer<WindowContainer> { // Well the app will no longer be stopped. // Clear app token stopped state in window manager if needed. - next.notifyAppResumed(next.stopped); + next.notifyAppResumed(); EventLogTags.writeWmResumeActivity(next.mUserId, System.identityHashCode(next), next.getTask().mTaskId, next.shortComponentName); @@ -2410,16 +2416,53 @@ class TaskFragment extends WindowContainer<WindowContainer> { } } - /** Whether we should prepare a transition for this {@link TaskFragment} bounds change. */ - boolean shouldStartChangeTransition(Rect startBounds) { + /** + * Gets the relative bounds of this embedded TaskFragment. This should only be called on + * embedded TaskFragment. + */ + @NonNull + Rect getRelativeEmbeddedBounds() { + if (mRelativeEmbeddedBounds == null) { + throw new IllegalStateException("The TaskFragment is not embedded"); + } + return mRelativeEmbeddedBounds; + } + + /** + * Updates the record of the relative bounds of this embedded TaskFragment. This should only be + * called when the embedded TaskFragment's override bounds are changed. + * Returns {@code true} if the bounds is changed. + */ + void updateRelativeEmbeddedBounds() { + // We only record the override bounds, which means it will not be changed when it is filling + // Task, and resize with the parent. + getRequestedOverrideBounds(mTmpBounds); + getRelativePosition(mTmpPoint); + mTmpBounds.offsetTo(mTmpPoint.x, mTmpPoint.y); + mRelativeEmbeddedBounds.set(mTmpBounds); + } + + /** + * Updates the record of relative bounds of this embedded TaskFragment, and checks whether we + * should prepare a transition for the bounds change. + */ + boolean shouldStartChangeTransition(@NonNull Rect absStartBounds, + @NonNull Rect relStartBounds) { if (mTaskFragmentOrganizer == null || !canStartChangeTransition()) { return false; } - // Only take snapshot if the bounds are resized. - final Rect endBounds = getConfiguration().windowConfiguration.getBounds(); - return endBounds.width() != startBounds.width() - || endBounds.height() != startBounds.height(); + if (mTransitionController.isShellTransitionsEnabled()) { + // For Shell transition, the change will be collected anyway, so only take snapshot when + // the bounds are resized. + final Rect endBounds = getConfiguration().windowConfiguration.getBounds(); + return endBounds.width() != absStartBounds.width() + || endBounds.height() != absStartBounds.height(); + } else { + // For legacy transition, we need to trigger a change transition as long as the bounds + // is changed, even if it is not resized. + return !relStartBounds.equals(mRelativeEmbeddedBounds); + } } /** Records the starting bounds of the closing organized TaskFragment. */ @@ -2787,22 +2830,6 @@ class TaskFragment extends WindowContainer<WindowContainer> { return getWindowingMode() == WINDOWING_MODE_FULLSCREEN || matchParentBounds(); } - void onActivityVisibleRequestedChanged() { - final boolean isVisibleRequested = isVisibleRequested(); - if (mVisibleRequested == isVisibleRequested) { - return; - } - mVisibleRequested = isVisibleRequested; - final WindowContainer<?> parent = getParent(); - if (parent == null) { - return; - } - final TaskFragment parentTf = parent.asTaskFragment(); - if (parentTf != null) { - parentTf.onActivityVisibleRequestedChanged(); - } - } - @Nullable @Override TaskFragment getTaskFragment(Predicate<TaskFragment> callback) { diff --git a/services/core/java/com/android/server/wm/Transition.java b/services/core/java/com/android/server/wm/Transition.java index 27374561fa12..b7f3cb4d800d 100644 --- a/services/core/java/com/android/server/wm/Transition.java +++ b/services/core/java/com/android/server/wm/Transition.java @@ -636,7 +636,7 @@ class Transition implements BLASTSyncEngine.TransactionReadyListener { // No need to clip the display in case seeing the clipped content when during the // display rotation. No need to clip activities because they rely on clipping on // task layers. - if (target.asDisplayContent() != null || target.asActivityRecord() != null) { + if (target.asTaskFragment() == null) { t.setCrop(targetLeash, null /* crop */); } else { // Crop to the resolved override bounds. diff --git a/services/core/java/com/android/server/wm/WallpaperWindowToken.java b/services/core/java/com/android/server/wm/WallpaperWindowToken.java index 32cfb70fd2a4..87f4ad42d8bf 100644 --- a/services/core/java/com/android/server/wm/WallpaperWindowToken.java +++ b/services/core/java/com/android/server/wm/WallpaperWindowToken.java @@ -41,8 +41,6 @@ class WallpaperWindowToken extends WindowToken { private static final String TAG = TAG_WITH_CLASS_NAME ? "WallpaperWindowToken" : TAG_WM; - private boolean mVisibleRequested = false; - WallpaperWindowToken(WindowManagerService service, IBinder token, boolean explicit, DisplayContent dc, boolean ownerCanManageAppTokens) { this(service, token, explicit, dc, ownerCanManageAppTokens, null /* options */); @@ -221,15 +219,17 @@ class WallpaperWindowToken extends WindowToken { return false; } - void setVisibleRequested(boolean visible) { - if (mVisibleRequested == visible) return; - mVisibleRequested = visible; + @Override + protected boolean setVisibleRequested(boolean visible) { + if (!super.setVisibleRequested(visible)) return false; setInsetsFrozen(!visible); + return true; } @Override - boolean isVisibleRequested() { - return mVisibleRequested; + protected boolean onChildVisibleRequestedChanged(@Nullable WindowContainer child) { + // Wallpaper manages visibleRequested directly (it's not determined by children) + return false; } @Override diff --git a/services/core/java/com/android/server/wm/WindowContainer.java b/services/core/java/com/android/server/wm/WindowContainer.java index 6e61071b2cf9..1d17cd43384a 100644 --- a/services/core/java/com/android/server/wm/WindowContainer.java +++ b/services/core/java/com/android/server/wm/WindowContainer.java @@ -315,6 +315,13 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer< private boolean mIsFocusable = true; /** + * This indicates whether this window is visible by policy. This can precede physical + * visibility ({@link #isVisible} - whether it has a surface showing on the screen) in + * cases where an animation is on-going. + */ + protected boolean mVisibleRequested; + + /** * Used as a unique, cross-process identifier for this Container. It also serves a minimal * interface to other processes. */ @@ -772,6 +779,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer< parent.mTreeWeight += child.mTreeWeight; parent = parent.getParent(); } + onChildVisibleRequestedChanged(child); onChildPositionChanged(child); } @@ -800,6 +808,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer< parent.mTreeWeight -= child.mTreeWeight; parent = parent.getParent(); } + onChildVisibleRequestedChanged(null); onChildPositionChanged(child); } @@ -1023,10 +1032,11 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer< * @param dc The display this container is on after changes. */ void onDisplayChanged(DisplayContent dc) { - if (mDisplayContent != null) { + if (mDisplayContent != null && mDisplayContent != dc) { + // Cancel any change transition queued-up for this container on the old display when + // this container is moved from the old display. mDisplayContent.mClosingChangingContainers.remove(this); if (mDisplayContent.mChangingContainers.remove(this)) { - // Cancel any change transition queued-up for this container on the old display. mSurfaceFreezer.unfreeze(getSyncTransaction()); } } @@ -1288,13 +1298,41 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer< * the transition is finished. */ boolean isVisibleRequested() { - for (int i = mChildren.size() - 1; i >= 0; --i) { - final WindowContainer child = mChildren.get(i); - if (child.isVisibleRequested()) { - return true; + return mVisibleRequested; + } + + /** @return `true` if visibleRequested changed. */ + @VisibleForTesting(visibility = VisibleForTesting.Visibility.PROTECTED) + boolean setVisibleRequested(boolean visible) { + if (mVisibleRequested == visible) return false; + mVisibleRequested = visible; + final WindowContainer parent = getParent(); + if (parent != null) { + parent.onChildVisibleRequestedChanged(this); + } + return true; + } + + /** + * @param child The changed or added child. `null` if a child was removed. + * @return `true` if visibleRequested changed. + */ + protected boolean onChildVisibleRequestedChanged(@Nullable WindowContainer child) { + final boolean childVisReq = child != null && child.isVisibleRequested(); + boolean newVisReq = mVisibleRequested; + if (childVisReq && !mVisibleRequested) { + newVisReq = true; + } else if (!childVisReq && mVisibleRequested) { + newVisReq = false; + for (int i = mChildren.size() - 1; i >= 0; --i) { + final WindowContainer wc = mChildren.get(i); + if (wc != child && wc.isVisibleRequested()) { + newVisReq = true; + break; + } } } - return false; + return setVisibleRequested(newVisReq); } /** @@ -3025,13 +3063,16 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer< // When there are more than one changing containers, it may leave part of the // screen empty. Show background color to cover that. showBackdrop = getDisplayContent().mChangingContainers.size() > 1; + backdropColor = appTransition.getNextAppTransitionBackgroundColor(); } else { // Check whether the app has requested to show backdrop for open/close // transition. final Animation a = appTransition.getNextAppRequestedAnimation(enter); - showBackdrop = a != null && a.getShowBackdrop(); + if (a != null) { + showBackdrop = a.getShowBackdrop(); + backdropColor = a.getBackdropColor(); + } } - backdropColor = appTransition.getNextAppTransitionBackgroundColor(); } final Rect localBounds = new Rect(mTmpRect); localBounds.offsetTo(mTmpPoint.x, mTmpPoint.y); diff --git a/services/core/java/com/android/server/wm/WindowOrganizerController.java b/services/core/java/com/android/server/wm/WindowOrganizerController.java index 738adc360683..72411727361a 100644 --- a/services/core/java/com/android/server/wm/WindowOrganizerController.java +++ b/services/core/java/com/android/server/wm/WindowOrganizerController.java @@ -148,7 +148,8 @@ class WindowOrganizerController extends IWindowOrganizerController.Stub @VisibleForTesting final ArrayMap<IBinder, TaskFragment> mLaunchTaskFragments = new ArrayMap<>(); - private final Rect mTmpBounds = new Rect(); + private final Rect mTmpBounds0 = new Rect(); + private final Rect mTmpBounds1 = new Rect(); WindowOrganizerController(ActivityTaskManagerService atm) { mService = atm; @@ -797,14 +798,15 @@ class WindowOrganizerController extends IWindowOrganizerController.Stub // When the TaskFragment is resized, we may want to create a change transition for it, for // which we want to defer the surface update until we determine whether or not to start // change transition. - mTmpBounds.set(taskFragment.getBounds()); + mTmpBounds0.set(taskFragment.getBounds()); + mTmpBounds1.set(taskFragment.getRelativeEmbeddedBounds()); taskFragment.deferOrganizedTaskFragmentSurfaceUpdate(); final int effects = applyChanges(taskFragment, c, errorCallbackToken); - if (taskFragment.shouldStartChangeTransition(mTmpBounds)) { - taskFragment.initializeChangeTransition(mTmpBounds); + taskFragment.updateRelativeEmbeddedBounds(); + if (taskFragment.shouldStartChangeTransition(mTmpBounds0, mTmpBounds1)) { + taskFragment.initializeChangeTransition(mTmpBounds0); } taskFragment.continueOrganizedTaskFragmentSurfaceUpdate(); - mTmpBounds.set(0, 0, 0, 0); return effects; } @@ -1907,7 +1909,18 @@ class WindowOrganizerController extends IWindowOrganizerController.Stub // actions. taskFragment.setTaskFragmentOrganizer(creationParams.getOrganizer(), ownerActivity.getUid(), ownerActivity.info.processName); - ownerTask.addChild(taskFragment, POSITION_TOP); + final int position; + if (creationParams.getPairedPrimaryFragmentToken() != null) { + // When there is a paired primary TaskFragment, we want to place the new TaskFragment + // right above the paired one to make sure there is no other window in between. + final TaskFragment pairedPrimaryTaskFragment = getTaskFragment( + creationParams.getPairedPrimaryFragmentToken()); + final int pairedPosition = ownerTask.mChildren.indexOf(pairedPrimaryTaskFragment); + position = pairedPosition != -1 ? pairedPosition + 1 : POSITION_TOP; + } else { + position = POSITION_TOP; + } + ownerTask.addChild(taskFragment, position); taskFragment.setWindowingMode(creationParams.getWindowingMode()); taskFragment.setBounds(creationParams.getInitialBounds()); mLaunchTaskFragments.put(creationParams.getFragmentToken(), taskFragment); diff --git a/services/core/java/com/android/server/wm/WindowProcessController.java b/services/core/java/com/android/server/wm/WindowProcessController.java index d2cd8f8e8b0b..e9b81ec03081 100644 --- a/services/core/java/com/android/server/wm/WindowProcessController.java +++ b/services/core/java/com/android/server/wm/WindowProcessController.java @@ -903,7 +903,7 @@ public class WindowProcessController extends ConfigurationContainer<Configuratio if (launchedActivity == activity) { continue; } - if (!activity.stopped) { + if (!activity.mAppStopped) { return true; } } @@ -926,7 +926,7 @@ public class WindowProcessController extends ConfigurationContainer<Configuratio boolean shouldKillProcessForRemovedTask(Task task) { for (int k = 0; k < mActivities.size(); k++) { final ActivityRecord activity = mActivities.get(k); - if (!activity.stopped) { + if (!activity.mAppStopped) { // Don't kill process(es) that has an activity not stopped. return false; } @@ -956,7 +956,7 @@ public class WindowProcessController extends ConfigurationContainer<Configuratio } // Don't consider any activities that are currently not in a state where they // can be destroyed. - if (r.isVisibleRequested() || !r.stopped || !r.hasSavedState() || !r.isDestroyable() + if (r.isVisibleRequested() || !r.mAppStopped || !r.hasSavedState() || !r.isDestroyable() || r.isState(STARTED, RESUMED, PAUSING, PAUSED, STOPPING)) { if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Not releasing in-use activity: " + r); continue; diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java index c6578ef19c72..1b7bd9e1f36f 100644 --- a/services/core/java/com/android/server/wm/WindowState.java +++ b/services/core/java/com/android/server/wm/WindowState.java @@ -2090,7 +2090,10 @@ class WindowState extends WindowContainer<WindowState> implements WindowManagerP } else { final Task task = getTask(); final boolean canFromTask = task != null && task.canAffectSystemUiFlags(); - return canFromTask && mActivityRecord.isVisible(); + return canFromTask && mActivityRecord.isVisible() + // Do not let snapshot window control the bar + && (mAttrs.type != TYPE_APPLICATION_STARTING + || !(mStartingData instanceof SnapshotStartingData)); } } diff --git a/services/core/java/com/android/server/wm/WindowToken.java b/services/core/java/com/android/server/wm/WindowToken.java index f2527b622208..c6b78982169c 100644 --- a/services/core/java/com/android/server/wm/WindowToken.java +++ b/services/core/java/com/android/server/wm/WindowToken.java @@ -582,9 +582,7 @@ class WindowToken extends WindowContainer<WindowState> { .setCallsite("WindowToken.getOrCreateFixedRotationLeash") .build(); t.setPosition(leash, mLastSurfacePosition.x, mLastSurfacePosition.y); - t.show(leash); t.reparent(getSurfaceControl(), leash); - t.setAlpha(getSurfaceControl(), 1.f); mFixedRotationTransformLeash = leash; updateSurfaceRotation(t, rotation, mFixedRotationTransformLeash); return mFixedRotationTransformLeash; diff --git a/services/core/jni/Android.bp b/services/core/jni/Android.bp index 413e168cf563..07819b9a18fc 100644 --- a/services/core/jni/Android.bp +++ b/services/core/jni/Android.bp @@ -71,6 +71,7 @@ cc_library_static { "com_android_server_PersistentDataBlockService.cpp", "com_android_server_am_LowMemDetector.cpp", "com_android_server_pm_PackageManagerShellCommandDataLoader.cpp", + "com_android_server_pm_Settings.cpp", "com_android_server_sensor_SensorService.cpp", "com_android_server_wm_TaskFpsCallbackController.cpp", "onload.cpp", @@ -152,6 +153,7 @@ cc_defaults { "libpsi", "libdataloader", "libincfs", + "liblz4", "android.hardware.audio.common@2.0", "android.media.audio.common.types-V1-ndk", "android.hardware.broadcastradio@1.0", @@ -167,7 +169,7 @@ cc_defaults { "android.hardware.graphics.bufferqueue@2.0", "android.hardware.graphics.common@1.2", "android.hardware.graphics.mapper@4.0", - "android.hardware.input.processor-V2-ndk", + "android.hardware.input.processor-V1-ndk", "android.hardware.ir@1.0", "android.hardware.light@2.0", "android.hardware.memtrack-V1-ndk", @@ -232,3 +234,26 @@ filegroup { "com_android_server_app_GameManagerService.cpp", ], } + +// Settings JNI library for unit tests. +cc_library_shared { + name: "libservices.core.settings.testonly", + defaults: ["libservices.core-libs"], + + cpp_std: "c++2a", + cflags: [ + "-Wall", + "-Werror", + "-Wno-unused-parameter", + "-Wthread-safety", + ], + + srcs: [ + "com_android_server_pm_Settings.cpp", + "onload_settings.cpp", + ], + + header_libs: [ + "bionic_libc_platform_headers", + ], +} diff --git a/services/core/jni/com_android_server_input_InputManagerService.cpp b/services/core/jni/com_android_server_input_InputManagerService.cpp index 969056e7c8b4..145e0885b105 100644 --- a/services/core/jni/com_android_server_input_InputManagerService.cpp +++ b/services/core/jni/com_android_server_input_InputManagerService.cpp @@ -1578,6 +1578,12 @@ static std::vector<int32_t> getIntArray(JNIEnv* env, jintArray arr) { return vec; } +static void nativeAddKeyRemapping(JNIEnv* env, jobject nativeImplObj, jint deviceId, + jint fromKeyCode, jint toKeyCode) { + NativeInputManager* im = getNativeInputManager(env, nativeImplObj); + im->getInputManager()->getReader().addKeyRemapping(deviceId, fromKeyCode, toKeyCode); +} + static jboolean nativeHasKeys(JNIEnv* env, jobject nativeImplObj, jint deviceId, jint sourceMask, jintArray keyCodes, jbooleanArray outFlags) { NativeInputManager* im = getNativeInputManager(env, nativeImplObj); @@ -2360,6 +2366,7 @@ static const JNINativeMethod gInputManagerMethods[] = { {"getScanCodeState", "(III)I", (void*)nativeGetScanCodeState}, {"getKeyCodeState", "(III)I", (void*)nativeGetKeyCodeState}, {"getSwitchState", "(III)I", (void*)nativeGetSwitchState}, + {"addKeyRemapping", "(III)V", (void*)nativeAddKeyRemapping}, {"hasKeys", "(II[I[Z)Z", (void*)nativeHasKeys}, {"getKeyCodeForKeyLocation", "(II)I", (void*)nativeGetKeyCodeForKeyLocation}, {"createInputChannel", "(Ljava/lang/String;)Landroid/view/InputChannel;", diff --git a/services/core/jni/com_android_server_pm_Settings.cpp b/services/core/jni/com_android_server_pm_Settings.cpp new file mode 100644 index 000000000000..9633a115d718 --- /dev/null +++ b/services/core/jni/com_android_server_pm_Settings.cpp @@ -0,0 +1,161 @@ +/* + * 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. + */ + +#define ATRACE_TAG ATRACE_TAG_ADB +#define LOG_TAG "Settings-jni" +#include <android-base/file.h> +#include <android-base/logging.h> +#include <android-base/no_destructor.h> +#include <core_jni_helpers.h> +#include <lz4frame.h> +#include <nativehelper/JNIHelp.h> + +#include <vector> + +namespace android { + +namespace { + +struct LZ4FCContextDeleter { + void operator()(LZ4F_cctx* cctx) { LZ4F_freeCompressionContext(cctx); } +}; + +static constexpr int LZ4_BUFFER_SIZE = 64 * 1024; + +static bool writeToFile(std::vector<char>& outBuffer, int fdOut) { + if (!android::base::WriteFully(fdOut, outBuffer.data(), outBuffer.size())) { + PLOG(ERROR) << "Error to write to output file"; + return false; + } + outBuffer.clear(); + return true; +} + +static bool compressAndWriteLz4(LZ4F_cctx* context, std::vector<char>& inBuffer, + std::vector<char>& outBuffer, int fdOut) { + auto inSize = inBuffer.size(); + if (inSize > 0) { + auto prvSize = outBuffer.size(); + auto outSize = LZ4F_compressBound(inSize, nullptr); + outBuffer.resize(prvSize + outSize); + auto rc = LZ4F_compressUpdate(context, outBuffer.data() + prvSize, outSize, inBuffer.data(), + inSize, nullptr); + if (LZ4F_isError(rc)) { + LOG(ERROR) << "LZ4F_compressUpdate failed: " << LZ4F_getErrorName(rc); + return false; + } + outBuffer.resize(prvSize + rc); + } + + if (outBuffer.size() > LZ4_BUFFER_SIZE) { + return writeToFile(outBuffer, fdOut); + } + + return true; +} + +static jboolean nativeCompressLz4(JNIEnv* env, jclass klass, jint fdIn, jint fdOut) { + LZ4F_cctx* cctx; + if (LZ4F_createCompressionContext(&cctx, LZ4F_VERSION) != 0) { + LOG(ERROR) << "Failed to initialize LZ4 compression context."; + return false; + } + std::unique_ptr<LZ4F_cctx, LZ4FCContextDeleter> context(cctx); + + std::vector<char> inBuffer, outBuffer; + inBuffer.reserve(LZ4_BUFFER_SIZE); + outBuffer.reserve(2 * LZ4_BUFFER_SIZE); + + LZ4F_preferences_t prefs; + + memset(&prefs, 0, sizeof(prefs)); + + // Set compression parameters. + prefs.autoFlush = 0; + prefs.compressionLevel = 0; + prefs.frameInfo.blockMode = LZ4F_blockLinked; + prefs.frameInfo.blockSizeID = LZ4F_default; + prefs.frameInfo.blockChecksumFlag = LZ4F_noBlockChecksum; + prefs.frameInfo.contentChecksumFlag = LZ4F_contentChecksumEnabled; + prefs.favorDecSpeed = 0; + + struct stat sb; + if (fstat(fdIn, &sb) == -1) { + PLOG(ERROR) << "Failed to obtain input file size."; + return false; + } + prefs.frameInfo.contentSize = sb.st_size; + + // Write header first. + outBuffer.resize(LZ4F_HEADER_SIZE_MAX); + auto rc = LZ4F_compressBegin(context.get(), outBuffer.data(), outBuffer.size(), &prefs); + if (LZ4F_isError(rc)) { + LOG(ERROR) << "LZ4F_compressBegin failed: " << LZ4F_getErrorName(rc); + return false; + } + outBuffer.resize(rc); + + bool eof = false; + while (!eof) { + constexpr auto capacity = LZ4_BUFFER_SIZE; + inBuffer.resize(capacity); + auto read = TEMP_FAILURE_RETRY(::read(fdIn, inBuffer.data(), inBuffer.size())); + if (read < 0) { + PLOG(ERROR) << "Failed to read from input file."; + return false; + } + + inBuffer.resize(read); + + if (read == 0) { + eof = true; + } + + if (!compressAndWriteLz4(context.get(), inBuffer, outBuffer, fdOut)) { + return false; + } + } + + // Footer. + auto prvSize = outBuffer.size(); + outBuffer.resize(outBuffer.capacity()); + rc = LZ4F_compressEnd(context.get(), outBuffer.data() + prvSize, outBuffer.size() - prvSize, + nullptr); + if (LZ4F_isError(rc)) { + LOG(ERROR) << "LZ4F_compressEnd failed: " << LZ4F_getErrorName(rc); + return false; + } + outBuffer.resize(prvSize + rc); + + if (!writeToFile(outBuffer, fdOut)) { + return false; + } + + return true; +} + +static const JNINativeMethod method_table[] = { + {"nativeCompressLz4", "(II)Z", (void*)nativeCompressLz4}, +}; + +} // namespace + +int register_android_server_com_android_server_pm_Settings(JNIEnv* env) { + return jniRegisterNativeMethods(env, "com/android/server/pm/Settings", method_table, + NELEM(method_table)); +} + +} // namespace android diff --git a/services/core/jni/onload.cpp b/services/core/jni/onload.cpp index 00f851f9f4ff..184505713420 100644 --- a/services/core/jni/onload.cpp +++ b/services/core/jni/onload.cpp @@ -56,6 +56,7 @@ int register_android_server_am_LowMemDetector(JNIEnv* env); int register_com_android_server_soundtrigger_middleware_AudioSessionProviderImpl(JNIEnv* env); int register_com_android_server_soundtrigger_middleware_ExternalCaptureStateTracker(JNIEnv* env); int register_android_server_com_android_server_pm_PackageManagerShellCommandDataLoader(JNIEnv* env); +int register_android_server_com_android_server_pm_Settings(JNIEnv* env); int register_android_server_AdbDebuggingManager(JNIEnv* env); int register_android_server_FaceService(JNIEnv* env); int register_android_server_GpuService(JNIEnv* env); @@ -114,6 +115,7 @@ extern "C" jint JNI_OnLoad(JavaVM* vm, void* /* reserved */) register_com_android_server_soundtrigger_middleware_AudioSessionProviderImpl(env); register_com_android_server_soundtrigger_middleware_ExternalCaptureStateTracker(env); register_android_server_com_android_server_pm_PackageManagerShellCommandDataLoader(env); + register_android_server_com_android_server_pm_Settings(env); register_android_server_AdbDebuggingManager(env); register_android_server_FaceService(env); register_android_server_GpuService(env); diff --git a/services/core/jni/onload_settings.cpp b/services/core/jni/onload_settings.cpp new file mode 100644 index 000000000000..b21c34a9f9b9 --- /dev/null +++ b/services/core/jni/onload_settings.cpp @@ -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. + */ + +#include "jni.h" +#include "utils/Log.h" + +namespace android { +int register_android_server_com_android_server_pm_Settings(JNIEnv* env); +}; + +using namespace android; + +extern "C" jint JNI_OnLoad(JavaVM* vm, void* /* reserved */) { + JNIEnv* env = NULL; + jint result = -1; + + if (vm->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK) { + ALOGE("GetEnv failed!"); + return result; + } + ALOG_ASSERT(env, "Could not retrieve the env!"); + + register_android_server_com_android_server_pm_Settings(env); + + return JNI_VERSION_1_4; +} diff --git a/services/core/jni/stats/SurfaceFlingerPuller.cpp b/services/core/jni/stats/SurfaceFlingerPuller.cpp index 88736732a61c..b959798d0969 100644 --- a/services/core/jni/stats/SurfaceFlingerPuller.cpp +++ b/services/core/jni/stats/SurfaceFlingerPuller.cpp @@ -122,9 +122,12 @@ AStatsManager_PullAtomCallbackReturn SurfaceFlingerPuller::parseLayerInfoPull( for (const auto& atom : atomList.atom()) { // The strings must outlive the BytesFields, which only have a pointer to the data. std::string present2PresentStr, post2presentStr, acquire2PresentStr, latch2PresentStr, - desired2PresentStr, post2AcquireStr, frameRateVoteStr, appDeadlineMissesStr; + desired2PresentStr, post2AcquireStr, frameRateVoteStr, appDeadlineMissesStr, + present2PresentDeltaStr; optional<BytesField> present2Present = getBytes(atom.present_to_present(), present2PresentStr); + optional<BytesField> present2PresentDelta = + getBytes(atom.present_to_present_delta(), present2PresentDeltaStr); optional<BytesField> post2present = getBytes(atom.post_to_present(), post2presentStr); optional<BytesField> acquire2Present = getBytes(atom.acquire_to_present(), acquire2PresentStr); @@ -138,7 +141,8 @@ AStatsManager_PullAtomCallbackReturn SurfaceFlingerPuller::parseLayerInfoPull( // Fail if any serialization to bytes failed. if (!present2Present || !post2present || !acquire2Present || !latch2Present || - !desired2Present || !post2Acquire || !frameRateVote || !appDeadlineMisses) { + !desired2Present || !post2Acquire || !frameRateVote || !appDeadlineMisses || + !present2PresentDelta) { return AStatsManager_PULL_SKIP; } @@ -159,7 +163,7 @@ AStatsManager_PullAtomCallbackReturn SurfaceFlingerPuller::parseLayerInfoPull( atom.total_jank_frames_app_buffer_stuffing(), atom.display_refresh_rate_bucket(), atom.render_rate_bucket(), frameRateVote.value(), appDeadlineMisses.value(), - atom.game_mode()); + atom.game_mode(), present2PresentDelta.value()); } return AStatsManager_PULL_SUCCESS; } diff --git a/services/credentials/java/com/android/server/credentials/CredentialManagerService.java b/services/credentials/java/com/android/server/credentials/CredentialManagerService.java index d3b9e10a436a..2f951ed63bb9 100644 --- a/services/credentials/java/com/android/server/credentials/CredentialManagerService.java +++ b/services/credentials/java/com/android/server/credentials/CredentialManagerService.java @@ -36,7 +36,7 @@ import android.os.ICancellationSignal; import android.os.UserHandle; import android.provider.Settings; import android.service.credentials.BeginCreateCredentialRequest; -import android.service.credentials.GetCredentialsRequest; +import android.service.credentials.BeginGetCredentialsRequest; import android.text.TextUtils; import android.util.Log; import android.util.Slog; @@ -169,8 +169,8 @@ public final class CredentialManagerService extends // Iterate over all provider sessions and invoke the request providerSessions.forEach(providerGetSession -> { - providerGetSession.getRemoteCredentialService().onGetCredentials( - (GetCredentialsRequest) providerGetSession.getProviderRequest(), + providerGetSession.getRemoteCredentialService().onBeginGetCredentials( + (BeginGetCredentialsRequest) providerGetSession.getProviderRequest(), /*callback=*/providerGetSession); }); return cancelTransport; diff --git a/services/credentials/java/com/android/server/credentials/PendingIntentResultHandler.java b/services/credentials/java/com/android/server/credentials/PendingIntentResultHandler.java index d0bc0744f8a5..7f9e57a5bdb6 100644 --- a/services/credentials/java/com/android/server/credentials/PendingIntentResultHandler.java +++ b/services/credentials/java/com/android/server/credentials/PendingIntentResultHandler.java @@ -19,7 +19,7 @@ package com.android.server.credentials; import android.app.Activity; import android.content.Intent; import android.credentials.CreateCredentialResponse; -import android.credentials.Credential; +import android.credentials.GetCredentialResponse; import android.credentials.ui.ProviderPendingIntentResponse; import android.service.credentials.CredentialProviderService; import android.service.credentials.CredentialsResponseContent; @@ -43,8 +43,7 @@ public class PendingIntentResultHandler { return null; } return resultData.getParcelableExtra( - CredentialProviderService - .EXTRA_GET_CREDENTIALS_CONTENT_RESULT, + CredentialProviderService.EXTRA_CREDENTIALS_RESPONSE_CONTENT, CredentialsResponseContent.class); } @@ -54,17 +53,17 @@ public class PendingIntentResultHandler { return null; } return resultData.getParcelableExtra( - CredentialProviderService.EXTRA_CREATE_CREDENTIAL_RESULT, + CredentialProviderService.EXTRA_CREATE_CREDENTIAL_RESPONSE, CreateCredentialResponse.class); } - /** Extracts the {@link Credential} object added to the result data. */ - public static Credential extractCredential(Intent resultData) { + /** Extracts the {@link GetCredentialResponse} object added to the result data. */ + public static GetCredentialResponse extractGetCredentialResponse(Intent resultData) { if (resultData == null) { return null; } return resultData.getParcelableExtra( - CredentialProviderService.EXTRA_CREDENTIAL_RESULT, - Credential.class); + CredentialProviderService.EXTRA_GET_CREDENTIAL_RESPONSE, + GetCredentialResponse.class); } } diff --git a/services/credentials/java/com/android/server/credentials/ProviderGetSession.java b/services/credentials/java/com/android/server/credentials/ProviderGetSession.java index 6cd011b7a686..9888cc0a3732 100644 --- a/services/credentials/java/com/android/server/credentials/ProviderGetSession.java +++ b/services/credentials/java/com/android/server/credentials/ProviderGetSession.java @@ -19,19 +19,23 @@ package com.android.server.credentials; import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.UserIdInt; +import android.app.PendingIntent; import android.content.Context; -import android.credentials.Credential; +import android.content.Intent; import android.credentials.GetCredentialOption; import android.credentials.GetCredentialResponse; import android.credentials.ui.Entry; import android.credentials.ui.GetCredentialProviderData; import android.credentials.ui.ProviderPendingIntentResponse; import android.service.credentials.Action; +import android.service.credentials.BeginGetCredentialOption; +import android.service.credentials.BeginGetCredentialsRequest; +import android.service.credentials.BeginGetCredentialsResponse; import android.service.credentials.CredentialEntry; import android.service.credentials.CredentialProviderInfo; +import android.service.credentials.CredentialProviderService; import android.service.credentials.CredentialsResponseContent; -import android.service.credentials.GetCredentialsRequest; -import android.service.credentials.GetCredentialsResponse; +import android.service.credentials.GetCredentialRequest; import android.util.Log; import android.util.Pair; import android.util.Slog; @@ -41,6 +45,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.stream.Collectors; /** * Central provider session that listens for provider callbacks, and maintains provider state. @@ -48,10 +53,10 @@ import java.util.UUID; * * @hide */ -public final class ProviderGetSession extends ProviderSession<GetCredentialsRequest, - GetCredentialsResponse> +public final class ProviderGetSession extends ProviderSession<BeginGetCredentialsRequest, + BeginGetCredentialsResponse> implements - RemoteCredentialService.ProviderCallbacks<GetCredentialsResponse> { + RemoteCredentialService.ProviderCallbacks<BeginGetCredentialsResponse> { private static final String TAG = "ProviderGetSession"; // Key to be used as an entry key for a credential entry @@ -69,6 +74,9 @@ public final class ProviderGetSession extends ProviderSession<GetCredentialsRequ @Nullable private Pair<String, Action> mUiAuthenticationAction = null; + /** The complete request to be used in the second round. */ + private final GetCredentialRequest mCompleteRequest; + /** Creates a new provider session to be used by the request session. */ @Nullable public static ProviderGetSession createNewSession( Context context, @@ -76,20 +84,34 @@ public final class ProviderGetSession extends ProviderSession<GetCredentialsRequ CredentialProviderInfo providerInfo, GetRequestSession getRequestSession, RemoteCredentialService remoteCredentialService) { - GetCredentialsRequest providerRequest = + GetCredentialRequest completeRequest = createProviderRequest(providerInfo.getCapabilities(), getRequestSession.mClientRequest, getRequestSession.mClientCallingPackage); - if (providerRequest != null) { + if (completeRequest != null) { + // TODO: Update to using query data when ready + BeginGetCredentialsRequest beginGetCredentialsRequest = + new BeginGetCredentialsRequest.Builder( + completeRequest.getCallingPackage()) + .setBeginGetCredentialOptions( + completeRequest.getGetCredentialOptions().stream().map( + option -> { + //TODO : Replace with option.getCandidateQueryData + // when ready + return new BeginGetCredentialOption( + option.getType(), + option.getCandidateQueryData()); + }).collect(Collectors.toList())) + .build(); return new ProviderGetSession(context, providerInfo, getRequestSession, userId, - remoteCredentialService, providerRequest); + remoteCredentialService, beginGetCredentialsRequest, completeRequest); } Log.i(TAG, "Unable to create provider session"); return null; } @Nullable - private static GetCredentialsRequest createProviderRequest(List<String> providerCapabilities, + private static GetCredentialRequest createProviderRequest(List<String> providerCapabilities, android.credentials.GetCredentialRequest clientRequest, String clientCallingPackage) { List<GetCredentialOption> filteredOptions = new ArrayList<>(); @@ -104,7 +126,7 @@ public final class ProviderGetSession extends ProviderSession<GetCredentialsRequ } } if (!filteredOptions.isEmpty()) { - return new GetCredentialsRequest.Builder(clientCallingPackage).setGetCredentialOptions( + return new GetCredentialRequest.Builder(clientCallingPackage).setGetCredentialOptions( filteredOptions).build(); } Log.i(TAG, "In createProviderRequest - returning null"); @@ -115,8 +137,10 @@ public final class ProviderGetSession extends ProviderSession<GetCredentialsRequ CredentialProviderInfo info, ProviderInternalCallback callbacks, int userId, RemoteCredentialService remoteCredentialService, - GetCredentialsRequest request) { - super(context, info, request, callbacks, userId, remoteCredentialService); + BeginGetCredentialsRequest beginGetRequest, + GetCredentialRequest completeGetRequest) { + super(context, info, beginGetRequest, callbacks, userId, remoteCredentialService); + mCompleteRequest = completeGetRequest; setStatus(Status.PENDING); } @@ -128,7 +152,7 @@ public final class ProviderGetSession extends ProviderSession<GetCredentialsRequ /** Called when the provider response has been updated by an external source. */ @Override // Callback from the remote provider - public void onProviderResponseSuccess(@Nullable GetCredentialsResponse response) { + public void onProviderResponseSuccess(@Nullable BeginGetCredentialsResponse response) { Log.i(TAG, "in onProviderResponseSuccess"); onUpdateResponse(response); } @@ -254,19 +278,26 @@ public final class ProviderGetSession extends ProviderSession<GetCredentialsRequ mUiCredentialEntries.put(entryId, credentialEntry); Log.i(TAG, "in prepareUiProviderData creating ui entry with id " + entryId); if (credentialEntry.getPendingIntent() != null) { + setUpFillInIntent(credentialEntry.getPendingIntent()); credentialUiEntries.add(new Entry(CREDENTIAL_ENTRY_KEY, entryId, credentialEntry.getSlice(), credentialEntry.getPendingIntent(), /*fillInIntent=*/null)); - } else if (credentialEntry.getCredential() != null) { - credentialUiEntries.add(new Entry(CREDENTIAL_ENTRY_KEY, entryId, - credentialEntry.getSlice())); } else { - Log.i(TAG, "No credential or pending intent. Should not happen."); + Log.i(TAG, "No pending intent. Should not happen."); } } return credentialUiEntries; } + private Intent setUpFillInIntent(PendingIntent pendingIntent) { + Intent intent = pendingIntent.getIntent(); + intent.putExtra( + CredentialProviderService + .EXTRA_GET_CREDENTIAL_REQUEST, + mCompleteRequest); + return intent; + } + private List<Entry> prepareUiActionEntries(@Nullable List<Action> actions) { List<Entry> actionEntries = new ArrayList<>(); for (Action action : actions) { @@ -292,17 +323,14 @@ public final class ProviderGetSession extends ProviderSession<GetCredentialsRequ private void onCredentialEntrySelected(CredentialEntry credentialEntry, ProviderPendingIntentResponse providerPendingIntentResponse) { - if (credentialEntry.getCredential() != null) { - mCallbacks.onFinalResponseReceived(mComponentName, new GetCredentialResponse( - credentialEntry.getCredential())); - return; - } else if (providerPendingIntentResponse != null) { + if (providerPendingIntentResponse != null) { if (PendingIntentResultHandler.isSuccessfulResponse(providerPendingIntentResponse)) { - Credential credential = PendingIntentResultHandler.extractCredential( - providerPendingIntentResponse.getResultData()); - if (credential != null) { - mCallbacks.onFinalResponseReceived(mComponentName, - new GetCredentialResponse(credential)); + // TODO: Remove credential extraction when flow is fully transitioned + GetCredentialResponse getCredentialResponse = PendingIntentResultHandler + .extractGetCredentialResponse( + providerPendingIntentResponse.getResultData()); + if (getCredentialResponse != null) { + mCallbacks.onFinalResponseReceived(mComponentName, getCredentialResponse); return; } } @@ -320,7 +348,8 @@ public final class ProviderGetSession extends ProviderSession<GetCredentialsRequ .extractResponseContent(providerPendingIntentResponse .getResultData()); if (content != null) { - onUpdateResponse(GetCredentialsResponse.createWithResponseContent(content)); + onUpdateResponse( + BeginGetCredentialsResponse.createWithResponseContent(content)); return; } } @@ -337,7 +366,7 @@ public final class ProviderGetSession extends ProviderSession<GetCredentialsRequ /** Updates the response being maintained in state by this provider session. */ - private void onUpdateResponse(GetCredentialsResponse response) { + private void onUpdateResponse(BeginGetCredentialsResponse response) { mProviderResponse = response; if (response.getAuthenticationAction() != null) { Log.i(TAG , "updateResponse with authentication entry"); diff --git a/services/credentials/java/com/android/server/credentials/RemoteCredentialService.java b/services/credentials/java/com/android/server/credentials/RemoteCredentialService.java index e385bcb32201..7a883b359d9f 100644 --- a/services/credentials/java/com/android/server/credentials/RemoteCredentialService.java +++ b/services/credentials/java/com/android/server/credentials/RemoteCredentialService.java @@ -26,14 +26,14 @@ import android.os.ICancellationSignal; import android.os.RemoteException; import android.service.credentials.BeginCreateCredentialRequest; import android.service.credentials.BeginCreateCredentialResponse; +import android.service.credentials.BeginGetCredentialsRequest; +import android.service.credentials.BeginGetCredentialsResponse; import android.service.credentials.CredentialProviderException; import android.service.credentials.CredentialProviderException.CredentialProviderError; import android.service.credentials.CredentialProviderService; -import android.service.credentials.GetCredentialsRequest; -import android.service.credentials.GetCredentialsResponse; import android.service.credentials.IBeginCreateCredentialCallback; +import android.service.credentials.IBeginGetCredentialsCallback; import android.service.credentials.ICredentialProviderService; -import android.service.credentials.IGetCredentialsCallback; import android.text.format.DateUtils; import android.util.Log; import android.util.Slog; @@ -106,19 +106,21 @@ public class RemoteCredentialService extends ServiceConnector.Impl<ICredentialPr * @param callback the callback to be used to send back the provider response to the * {@link ProviderGetSession} class that maintains provider state */ - public void onGetCredentials(@NonNull GetCredentialsRequest request, - ProviderCallbacks<GetCredentialsResponse> callback) { + public void onBeginGetCredentials(@NonNull BeginGetCredentialsRequest request, + ProviderCallbacks<BeginGetCredentialsResponse> callback) { Log.i(TAG, "In onGetCredentials in RemoteCredentialService"); AtomicReference<ICancellationSignal> cancellationSink = new AtomicReference<>(); - AtomicReference<CompletableFuture<GetCredentialsResponse>> futureRef = + AtomicReference<CompletableFuture<BeginGetCredentialsResponse>> futureRef = new AtomicReference<>(); - CompletableFuture<GetCredentialsResponse> connectThenExecute = postAsync(service -> { - CompletableFuture<GetCredentialsResponse> getCredentials = new CompletableFuture<>(); + CompletableFuture<BeginGetCredentialsResponse> connectThenExecute = postAsync(service -> { + CompletableFuture<BeginGetCredentialsResponse> getCredentials = + new CompletableFuture<>(); ICancellationSignal cancellationSignal = - service.onGetCredentials(request, new IGetCredentialsCallback.Stub() { + service.onBeginGetCredentials(request, + new IBeginGetCredentialsCallback.Stub() { @Override - public void onSuccess(GetCredentialsResponse response) { + public void onSuccess(BeginGetCredentialsResponse response) { Log.i(TAG, "In onSuccess in RemoteCredentialService"); getCredentials.complete(response); } @@ -132,7 +134,7 @@ public class RemoteCredentialService extends ServiceConnector.Impl<ICredentialPr errorCode, errorMsg)); } }); - CompletableFuture<GetCredentialsResponse> future = futureRef.get(); + CompletableFuture<BeginGetCredentialsResponse> future = futureRef.get(); if (future != null && future.isCancelled()) { dispatchCancellationSignal(cancellationSignal); } else { @@ -159,7 +161,8 @@ public class RemoteCredentialService extends ServiceConnector.Impl<ICredentialPr AtomicReference<CompletableFuture<BeginCreateCredentialResponse>> futureRef = new AtomicReference<>(); - CompletableFuture<BeginCreateCredentialResponse> connectThenExecute = postAsync(service -> { + CompletableFuture<BeginCreateCredentialResponse> connectThenExecute = + postAsync(service -> { CompletableFuture<BeginCreateCredentialResponse> createCredentialFuture = new CompletableFuture<>(); ICancellationSignal cancellationSignal = service.onBeginCreateCredential( diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/ActiveAdmin.java b/services/devicepolicy/java/com/android/server/devicepolicy/ActiveAdmin.java index 8047a534f4a3..9af30ba14b47 100644 --- a/services/devicepolicy/java/com/android/server/devicepolicy/ActiveAdmin.java +++ b/services/devicepolicy/java/com/android/server/devicepolicy/ActiveAdmin.java @@ -162,6 +162,7 @@ class ActiveAdmin { private static final String TAG_PREFERENTIAL_NETWORK_SERVICE_CONFIG = "preferential_network_service_config"; private static final String TAG_PROTECTED_PACKAGES = "protected_packages"; + private static final String TAG_SUSPENDED_PACKAGES = "suspended-packages"; private static final String ATTR_VALUE = "value"; private static final String ATTR_LAST_NETWORK_LOGGING_NOTIFICATION = "last-notification"; private static final String ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS = "num-notifications"; @@ -257,6 +258,8 @@ class ActiveAdmin { // List of packages for which the user cannot invoke "clear data" or "force stop". List<String> protectedPackages; + List<String> suspendedPackages; + // Wi-Fi SSID restriction policy. WifiSsidPolicy mWifiSsidPolicy; @@ -508,6 +511,7 @@ class ActiveAdmin { writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages); writePackageListToXml(out, TAG_METERED_DATA_DISABLED_PACKAGES, meteredDisabledPackages); writePackageListToXml(out, TAG_PROTECTED_PACKAGES, protectedPackages); + writePackageListToXml(out, TAG_SUSPENDED_PACKAGES, suspendedPackages); if (hasUserRestrictions()) { UserRestrictionsUtils.writeRestrictions( out, userRestrictions, TAG_USER_RESTRICTIONS); @@ -776,6 +780,8 @@ class ActiveAdmin { meteredDisabledPackages = readPackageList(parser, tag); } else if (TAG_PROTECTED_PACKAGES.equals(tag)) { protectedPackages = readPackageList(parser, tag); + } else if (TAG_SUSPENDED_PACKAGES.equals(tag)) { + suspendedPackages = readPackageList(parser, tag); } else if (TAG_USER_RESTRICTIONS.equals(tag)) { userRestrictions = UserRestrictionsUtils.readRestrictions(parser); } else if (TAG_DEFAULT_ENABLED_USER_RESTRICTIONS.equals(tag)) { @@ -1225,6 +1231,11 @@ class ActiveAdmin { pw.println(protectedPackages); } + if (suspendedPackages != null) { + pw.print("suspendedPackages="); + pw.println(suspendedPackages); + } + pw.print("organizationColor="); pw.println(organizationColor); diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java index 775e3d833403..e93809d1b2c4 100644 --- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java +++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java @@ -336,7 +336,6 @@ import android.util.AtomicFile; import android.util.DebugUtils; import android.util.IndentingPrintWriter; import android.util.IntArray; -import android.util.Log; import android.util.Pair; import android.util.Slog; import android.util.SparseArray; @@ -546,7 +545,7 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager { // to decide whether an existing policy in the {@link #DEVICE_POLICIES_XML} needs to // be upgraded. See {@link PolicyVersionUpgrader} on instructions how to add an upgrade // step. - static final int DPMS_VERSION = 3; + static final int DPMS_VERSION = 4; static { SECURE_SETTINGS_ALLOWLIST = new ArraySet<>(); @@ -718,6 +717,16 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager { private static final String ENABLE_COEXISTENCE_FLAG = "enable_coexistence"; private static final boolean DEFAULT_ENABLE_COEXISTENCE_FLAG = false; + // TODO(b/258425381) remove the flag after rollout. + private static final String KEEP_PROFILES_RUNNING_FLAG = "enable_keep_profiles_running"; + private static final boolean DEFAULT_KEEP_PROFILES_RUNNING_FLAG = false; + + /** + * This feature flag is checked once after boot and this value us used until the next reboot to + * avoid needing to handle the flag changing on the fly. + */ + private final boolean mKeepProfilesRunning = isKeepProfilesRunningFlagEnabled(); + /** * For apps targeting U+ * Enable multiple admins to coexist on the same device. @@ -1210,6 +1219,9 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager { PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle) == null) { + Slogf.e(LOG_TAG, String.format( + "Admin package %s not found for user %d, removing active admin", + packageName, userHandle)); removedAdmin = true; policy.mAdminList.remove(i); policy.mAdminMap.remove(aa.info.getComponent()); @@ -1488,8 +1500,11 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager { } PackageManager getPackageManager(int userId) { - return mContext - .createContextAsUser(UserHandle.of(userId), 0 /* flags */).getPackageManager(); + try { + return createContextAsUser(UserHandle.of(userId)).getPackageManager(); + } catch (NameNotFoundException e) { + throw new IllegalStateException(e); + } } PowerManagerInternal getPowerManagerInternal() { @@ -1935,10 +1950,11 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager { } private Owners makeOwners(Injector injector, PolicyPathProvider pathProvider) { - return new Owners(injector.getUserManager(), injector.getUserManagerInternal(), + return new Owners( + injector.getUserManager(), injector.getUserManagerInternal(), injector.getPackageManagerInternal(), injector.getActivityTaskManagerInternal(), - injector.getActivityManagerInternal(), pathProvider); + injector.getActivityManagerInternal(), mStateCache, pathProvider); } /** @@ -3101,6 +3117,20 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager { List<UserInfo> allUsers = mUserManager.getUsers(); return allUsers.stream().mapToInt(u -> u.id).toArray(); } + + @Override + public List<String> getPlatformSuspendedPackages(int userId) { + PackageManagerInternal pmi = mInjector.getPackageManagerInternal(); + return mInjector.getPackageManager(userId) + .getInstalledPackages(PackageManager.PackageInfoFlags.of( + MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE)) + .stream() + .map(packageInfo -> packageInfo.packageName) + .filter(pkg -> + PLATFORM_PACKAGE_NAME.equals(pmi.getSuspendingPackage(pkg, userId)) + ) + .collect(Collectors.toList()); + } } private void performPolicyVersionUpgrade() { @@ -3151,7 +3181,7 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager { userId = mOwners.getDeviceOwnerUserId(); } if (VERBOSE_LOG) { - Log.v(LOG_TAG, "Starting non-system DO user: " + userId); + Slogf.v(LOG_TAG, "Starting non-system DO user: " + userId); } if (userId != UserHandle.USER_SYSTEM) { try { @@ -9892,6 +9922,8 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager { (size == 1 ? "" : "s")); } pw.println(); + pw.println("Keep profiles running: " + mKeepProfilesRunning); + pw.println(); mPolicyCache.dump(pw); pw.println(); @@ -11371,6 +11403,30 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager { Slogf.w(LOG_TAG, "PM failed to suspend packages (%s)", Arrays.toString(packageNames)); return packageNames; } + + ArraySet<String> changed = new ArraySet<>(packageNames); + if (suspended) { + // Only save those packages that are actually suspended. If a package is exempt or is + // unsuspendable, it is skipped. + changed.removeAll(List.of(nonSuspendedPackages)); + } else { + // If an admin tries to unsuspend a package that is either exempt or is not + // suspendable, drop it from the stored list assuming it must be already unsuspended. + changed.addAll(exemptApps); + } + + synchronized (getLockObject()) { + ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId()); + ArraySet<String> current = new ArraySet<>(admin.suspendedPackages); + if (suspended) { + current.addAll(changed); + } else { + current.removeAll(changed); + } + admin.suspendedPackages = current.isEmpty() ? null : new ArrayList<>(current); + saveSettingsLocked(caller.getUserId()); + } + if (exemptApps.isEmpty()) { return nonSuspendedPackages; } @@ -13240,7 +13296,7 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager { CallerIdentity caller = new CallerIdentity(callerUid, null, null); if (isUserAffiliatedWithDevice(UserHandle.getUserId(callerUid)) && (isActiveProfileOwner(callerUid) - || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller))) { + || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller))) { // device owner or a profile owner affiliated with the device owner return true; } @@ -13533,11 +13589,21 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager { } } + @Override + public boolean isKeepProfilesRunningEnabled() { + return mKeepProfilesRunning; + } + private @Mode int findInteractAcrossProfilesResetMode(String packageName) { return getDefaultCrossProfilePackages().contains(packageName) ? AppOpsManager.MODE_ALLOWED : AppOpsManager.opToDefaultMode(AppOpsManager.OP_INTERACT_ACROSS_PROFILES); } + + @Override + public boolean isUserOrganizationManaged(@UserIdInt int userHandle) { + return getDeviceStateCache().isUserOrganizationManaged(userHandle); + } } private Intent createShowAdminSupportIntent(int userId) { @@ -14387,7 +14453,7 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager { // Bail out if we are trying to provision a work profile but one already exists. if (!mUserManager.canAddMoreManagedProfiles( callingUserId, /* allowedToRemoveOne= */ false)) { - Slogf.i(LOG_TAG, "A work profile already exists."); + Slogf.i(LOG_TAG, "Cannot add more managed profiles."); return STATUS_CANNOT_ADD_MANAGED_PROFILE; } } finally { @@ -19167,4 +19233,11 @@ public class DevicePolicyManagerService extends BaseIDevicePolicyManager { ENABLE_COEXISTENCE_FLAG, DEFAULT_ENABLE_COEXISTENCE_FLAG); } + + private static boolean isKeepProfilesRunningFlagEnabled() { + return DeviceConfig.getBoolean( + NAMESPACE_DEVICE_POLICY_MANAGER, + KEEP_PROFILES_RUNNING_FLAG, + DEFAULT_KEEP_PROFILES_RUNNING_FLAG); + } } diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DeviceStateCacheImpl.java b/services/devicepolicy/java/com/android/server/devicepolicy/DeviceStateCacheImpl.java index 1215253dacaf..011a282ead7a 100644 --- a/services/devicepolicy/java/com/android/server/devicepolicy/DeviceStateCacheImpl.java +++ b/services/devicepolicy/java/com/android/server/devicepolicy/DeviceStateCacheImpl.java @@ -15,11 +15,17 @@ */ package com.android.server.devicepolicy; +import android.annotation.UserIdInt; +import android.app.admin.DevicePolicyManager; import android.app.admin.DeviceStateCache; import android.util.IndentingPrintWriter; import com.android.internal.annotations.GuardedBy; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; + /** * Implementation of {@link DeviceStateCache}, to which {@link DevicePolicyManagerService} pushes * device state. @@ -32,6 +38,11 @@ public class DeviceStateCacheImpl extends DeviceStateCache { */ private final Object mLock = new Object(); + public static final int NO_DEVICE_OWNER = -1; + + private AtomicInteger mDeviceOwnerType = new AtomicInteger(NO_DEVICE_OWNER); + private Map<Integer, Boolean> mHasProfileOwner = new ConcurrentHashMap<>(); + @GuardedBy("mLock") private boolean mIsDeviceProvisioned = false; @@ -47,11 +58,43 @@ public class DeviceStateCacheImpl extends DeviceStateCache { } } + void setDeviceOwnerType(int deviceOwnerType) { + mDeviceOwnerType.set(deviceOwnerType); + } + + void setHasProfileOwner(int userId, boolean hasProfileOwner) { + if (hasProfileOwner) { + mHasProfileOwner.put(userId, true); + } else { + mHasProfileOwner.remove(userId); + } + } + + @Override + public boolean isUserOrganizationManaged(@UserIdInt int userHandle) { + if (mHasProfileOwner.getOrDefault(userHandle, false) + || hasEnterpriseDeviceOwner()) { + return true; + } + + // TODO: Support role holder override + return false; + } + + private boolean hasEnterpriseDeviceOwner() { + return mDeviceOwnerType.get() == DevicePolicyManager.DEVICE_OWNER_TYPE_DEFAULT; + } + /** Dump content */ public void dump(IndentingPrintWriter pw) { pw.println("Device state cache:"); pw.increaseIndent(); pw.println("Device provisioned: " + mIsDeviceProvisioned); + pw.println("Device Owner Type: " + mDeviceOwnerType.get()); + pw.println("Has PO:"); + for (Integer id : mHasProfileOwner.keySet()) { + pw.println("User " + id + ": " + mHasProfileOwner.get(id)); + } pw.decreaseIndent(); } } diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/Owners.java b/services/devicepolicy/java/com/android/server/devicepolicy/Owners.java index 3b46d5238e6a..6f172e4515fc 100644 --- a/services/devicepolicy/java/com/android/server/devicepolicy/Owners.java +++ b/services/devicepolicy/java/com/android/server/devicepolicy/Owners.java @@ -16,8 +16,12 @@ package com.android.server.devicepolicy; +import static android.app.admin.DevicePolicyManager.DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_DEFAULT; +import static android.app.admin.DevicePolicyManager.DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_FLAG; import static android.app.admin.DevicePolicyManager.DEVICE_OWNER_TYPE_DEFAULT; +import static com.android.server.devicepolicy.DeviceStateCacheImpl.NO_DEVICE_OWNER; + import android.annotation.Nullable; import android.app.ActivityManagerInternal; import android.app.AppOpsManagerInternal; @@ -31,6 +35,7 @@ import android.os.Binder; import android.os.Process; import android.os.UserHandle; import android.os.UserManager; +import android.provider.DeviceConfig; import android.util.ArraySet; import android.util.IndentingPrintWriter; import android.util.Pair; @@ -69,6 +74,7 @@ class Owners { private final PackageManagerInternal mPackageManagerInternal; private final ActivityTaskManagerInternal mActivityTaskManagerInternal; private final ActivityManagerInternal mActivityManagerInternal; + private final DeviceStateCacheImpl mDeviceStateCache; @GuardedBy("mData") private final OwnersData mData; @@ -81,12 +87,14 @@ class Owners { PackageManagerInternal packageManagerInternal, ActivityTaskManagerInternal activityTaskManagerInternal, ActivityManagerInternal activityManagerInternal, + DeviceStateCacheImpl deviceStateCache, PolicyPathProvider pathProvider) { mUserManager = userManager; mUserManagerInternal = userManagerInternal; mPackageManagerInternal = packageManagerInternal; mActivityTaskManagerInternal = activityTaskManagerInternal; mActivityManagerInternal = activityManagerInternal; + mDeviceStateCache = deviceStateCache; mData = new OwnersData(pathProvider); } @@ -99,9 +107,24 @@ class Owners { mUserManager.getAliveUsers().stream().mapToInt(u -> u.id).toArray(); mData.load(usersIds); - mUserManagerInternal.setDeviceManaged(hasDeviceOwner()); - for (int userId : usersIds) { - mUserManagerInternal.setUserManaged(userId, hasProfileOwner(userId)); + // TODO(b/258213147): Remove + if (DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_DEVICE_POLICY_MANAGER, + DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_FLAG, + DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_DEFAULT)) { + if (hasDeviceOwner()) { + int deviceOwnerType = mData.mDeviceOwnerTypes.getOrDefault( + mData.mDeviceOwner.packageName, + /* defaultValue= */ DEVICE_OWNER_TYPE_DEFAULT); + mDeviceStateCache.setDeviceOwnerType(deviceOwnerType); + } else { + mDeviceStateCache.setDeviceOwnerType(NO_DEVICE_OWNER); + } + + } else { + mUserManagerInternal.setDeviceManaged(hasDeviceOwner()); + for (int userId : usersIds) { + mUserManagerInternal.setUserManaged(userId, hasProfileOwner(userId)); + } } notifyChangeLocked(); @@ -224,7 +247,18 @@ class Owners { /* remoteBugreportHash =*/ null, /* isOrganizationOwnedDevice =*/ true); mData.mDeviceOwnerUserId = userId; - mUserManagerInternal.setDeviceManaged(true); + // TODO(b/258213147): Remove + if (DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_DEVICE_POLICY_MANAGER, + DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_FLAG, + DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_DEFAULT)) { + int deviceOwnerType = mData.mDeviceOwnerTypes.getOrDefault( + mData.mDeviceOwner.packageName, + /* defaultValue= */ DEVICE_OWNER_TYPE_DEFAULT); + mDeviceStateCache.setDeviceOwnerType(deviceOwnerType); + } else { + mUserManagerInternal.setDeviceManaged(true); + } + notifyChangeLocked(); pushToActivityTaskManagerLocked(); } @@ -236,7 +270,14 @@ class Owners { mData.mDeviceOwner = null; mData.mDeviceOwnerUserId = UserHandle.USER_NULL; - mUserManagerInternal.setDeviceManaged(false); + // TODO(b/258213147): Remove + if (DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_DEVICE_POLICY_MANAGER, + DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_FLAG, + DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_DEFAULT)) { + mDeviceStateCache.setDeviceOwnerType(NO_DEVICE_OWNER); + } else { + mUserManagerInternal.setDeviceManaged(false); + } notifyChangeLocked(); pushToActivityTaskManagerLocked(); } @@ -248,7 +289,15 @@ class Owners { mData.mProfileOwners.put(userId, new OwnerInfo(admin, /* remoteBugreportUri =*/ null, /* remoteBugreportHash =*/ null, /* isOrganizationOwnedDevice =*/ false)); - mUserManagerInternal.setUserManaged(userId, true); + + // TODO(b/258213147): Remove + if (DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_DEVICE_POLICY_MANAGER, + DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_FLAG, + DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_DEFAULT)) { + mDeviceStateCache.setHasProfileOwner(userId, true); + } else { + mUserManagerInternal.setUserManaged(userId, true); + } notifyChangeLocked(); } } @@ -256,7 +305,14 @@ class Owners { void removeProfileOwner(int userId) { synchronized (mData) { mData.mProfileOwners.remove(userId); - mUserManagerInternal.setUserManaged(userId, false); + // TODO(b/258213147): Remove + if (DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_DEVICE_POLICY_MANAGER, + DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_FLAG, + DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_DEFAULT)) { + mDeviceStateCache.setHasProfileOwner(userId, false); + } else { + mUserManagerInternal.setUserManaged(userId, false); + } notifyChangeLocked(); } } diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/PolicyUpgraderDataProvider.java b/services/devicepolicy/java/com/android/server/devicepolicy/PolicyUpgraderDataProvider.java index 147474907f29..c0ef0b0f80df 100644 --- a/services/devicepolicy/java/com/android/server/devicepolicy/PolicyUpgraderDataProvider.java +++ b/services/devicepolicy/java/com/android/server/devicepolicy/PolicyUpgraderDataProvider.java @@ -21,6 +21,7 @@ import android.content.ComponentName; import com.android.internal.util.JournaledFile; +import java.util.List; import java.util.function.Function; /** @@ -48,4 +49,9 @@ public interface PolicyUpgraderDataProvider { * Returns the users to upgrade. */ int[] getUsersForUpgrade(); + + /** + * Returns packages suspended by platform for a given user. + */ + List<String> getPlatformSuspendedPackages(int userId); } diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/PolicyVersionUpgrader.java b/services/devicepolicy/java/com/android/server/devicepolicy/PolicyVersionUpgrader.java index 808133164cd1..1fe4b571a770 100644 --- a/services/devicepolicy/java/com/android/server/devicepolicy/PolicyVersionUpgrader.java +++ b/services/devicepolicy/java/com/android/server/devicepolicy/PolicyVersionUpgrader.java @@ -104,6 +104,12 @@ public class PolicyVersionUpgrader { currentVersion = 3; } + if (currentVersion == 3) { + Slog.i(LOG_TAG, String.format("Upgrading from version %d", currentVersion)); + upgradePackageSuspension(allUsers, ownersData, allUsersData); + currentVersion = 4; + } + writePoliciesAndVersion(allUsers, allUsersData, ownersData, currentVersion); } @@ -170,6 +176,44 @@ public class PolicyVersionUpgrader { } } + /** + * This upgrade step stores packages suspended via DPM.setPackagesSuspended() into ActiveAdmin + * data structure. Prior to this it was only persisted in PackageManager which doesn't have any + * way of knowing which admin suspended it. + */ + private void upgradePackageSuspension( + int[] allUsers, OwnersData ownersData, SparseArray<DevicePolicyData> allUsersData) { + if (ownersData.mDeviceOwner != null) { + saveSuspendedPackages(allUsersData, ownersData.mDeviceOwnerUserId, + ownersData.mDeviceOwner.admin); + } + + for (int i = 0; i < ownersData.mProfileOwners.size(); i++) { + int ownerUserId = ownersData.mProfileOwners.keyAt(i); + OwnersData.OwnerInfo ownerInfo = ownersData.mProfileOwners.valueAt(i); + saveSuspendedPackages(allUsersData, ownerUserId, ownerInfo.admin); + } + } + + private void saveSuspendedPackages(SparseArray<DevicePolicyData> allUsersData, int ownerUserId, + ComponentName ownerPackage) { + DevicePolicyData ownerUserData = allUsersData.get(ownerUserId); + if (ownerUserData == null) { + Slog.e(LOG_TAG, "No policy data for owner user, cannot migrate suspended packages"); + return; + } + + ActiveAdmin ownerAdmin = ownerUserData.mAdminMap.get(ownerPackage); + if (ownerAdmin == null) { + Slog.e(LOG_TAG, "No admin for owner, cannot migrate suspended packages"); + return; + } + + ownerAdmin.suspendedPackages = mProvider.getPlatformSuspendedPackages(ownerUserId); + Slog.i(LOG_TAG, String.format("Saved %d packages suspended by %s in user %d", + ownerAdmin.suspendedPackages.size(), ownerPackage, ownerUserId)); + } + private OwnersData loadOwners(int[] allUsers) { OwnersData ownersData = new OwnersData(mPathProvider); ownersData.load(allUsers); diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java index e96eff21bcc5..e41e781b7c22 100644 --- a/services/java/com/android/server/SystemServer.java +++ b/services/java/com/android/server/SystemServer.java @@ -187,6 +187,7 @@ import com.android.server.security.AttestationVerificationManagerService; import com.android.server.security.FileIntegrityService; import com.android.server.security.KeyAttestationApplicationIdProviderService; import com.android.server.security.KeyChainSystemService; +import com.android.server.security.rkp.RemoteProvisioningService; import com.android.server.sensorprivacy.SensorPrivacyService; import com.android.server.sensors.SensorService; import com.android.server.signedconfig.SignedConfigService; @@ -1361,11 +1362,16 @@ public final class SystemServer implements Dumpable { mSystemServiceManager.startService(BugreportManagerService.class); t.traceEnd(); - // Serivce for GPU and GPU driver. + // Service for GPU and GPU driver. t.traceBegin("GpuService"); mSystemServiceManager.startService(GpuService.class); t.traceEnd(); + // Handles system process requests for remotely provisioned keys & data. + t.traceBegin("StartRemoteProvisioningService"); + mSystemServiceManager.startService(RemoteProvisioningService.class); + t.traceEnd(); + t.traceEnd(); // startCoreServices } diff --git a/services/midi/java/com/android/server/midi/MidiService.java b/services/midi/java/com/android/server/midi/MidiService.java index b519a782ce26..4aba30a661ad 100644 --- a/services/midi/java/com/android/server/midi/MidiService.java +++ b/services/midi/java/com/android/server/midi/MidiService.java @@ -23,7 +23,6 @@ import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; -// import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; @@ -31,6 +30,7 @@ import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.pm.ServiceInfo; import android.content.res.XmlResourceParser; +import android.media.MediaMetrics; import android.media.midi.IBluetoothMidiService; import android.media.midi.IMidiDeviceListener; import android.media.midi.IMidiDeviceOpenCallback; @@ -63,12 +63,16 @@ import org.xmlpull.v1.XmlPullParser; import java.io.FileDescriptor; import java.io.IOException; import java.io.PrintWriter; +import java.time.Duration; +import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; // NOTE about locking order: // if there is a path that syncs on BOTH mDevicesByInfo AND mDeviceConnections, @@ -359,6 +363,17 @@ public class MidiService extends IMidiManager.Stub { private final ArrayList<DeviceConnection> mDeviceConnections = new ArrayList<DeviceConnection>(); + // Keep track of number of added and removed collections for logging + private AtomicInteger mDeviceConnectionsAdded = new AtomicInteger(); + private AtomicInteger mDeviceConnectionsRemoved = new AtomicInteger(); + + // Keep track of total time with at least one active connection + private AtomicLong mTotalTimeConnectedNs = new AtomicLong(); + private Instant mPreviousCounterInstant = null; + + private AtomicInteger mTotalInputBytes = new AtomicInteger(); + private AtomicInteger mTotalOutputBytes = new AtomicInteger(); + public Device(IMidiDeviceServer server, MidiDeviceInfo deviceInfo, ServiceInfo serviceInfo, int uid) { mDeviceInfo = deviceInfo; @@ -460,6 +475,11 @@ public class MidiService extends IMidiManager.Stub { public void addDeviceConnection(DeviceConnection connection) { Log.d(TAG, "addDeviceConnection() [A] connection:" + connection); synchronized (mDeviceConnections) { + mDeviceConnectionsAdded.incrementAndGet(); + if (mPreviousCounterInstant == null) { + mPreviousCounterInstant = Instant.now(); + } + Log.d(TAG, " mServer:" + mServer); if (mServer != null) { Log.i(TAG, "++++ A"); @@ -533,6 +553,20 @@ public class MidiService extends IMidiManager.Stub { public void removeDeviceConnection(DeviceConnection connection) { synchronized (mDevicesByInfo) { synchronized (mDeviceConnections) { + int numRemovedConnections = mDeviceConnectionsRemoved.incrementAndGet(); + if (mPreviousCounterInstant != null) { + mTotalTimeConnectedNs.addAndGet(Duration.between( + mPreviousCounterInstant, Instant.now()).toNanos()); + } + // Stop the clock if all devices have been removed. + // Otherwise, start the clock from the current instant. + if (numRemovedConnections >= mDeviceConnectionsAdded.get()) { + mPreviousCounterInstant = null; + } else { + mPreviousCounterInstant = Instant.now(); + } + logMetrics(false /* isDeviceDisconnected */); + mDeviceConnections.remove(connection); if (connection.getDevice().getDeviceInfo().getType() @@ -569,6 +603,16 @@ public class MidiService extends IMidiManager.Stub { connection.getClient().removeDeviceConnection(connection); } mDeviceConnections.clear(); + + // If the timer is still going, some clients have not closed the connection yet. + if (mPreviousCounterInstant != null) { + Instant currentInstant = Instant.now(); + mTotalTimeConnectedNs.addAndGet(Duration.between( + mPreviousCounterInstant, currentInstant).toNanos()); + mPreviousCounterInstant = currentInstant; + } + + logMetrics(true /* isDeviceDisconnected */); } setDeviceServer(null); @@ -585,6 +629,35 @@ public class MidiService extends IMidiManager.Stub { } } + private void logMetrics(boolean isDeviceDisconnected) { + // Only log metrics if the device was used in a connection + int numDeviceConnectionAdded = mDeviceConnectionsAdded.get(); + if (mDeviceInfo != null && numDeviceConnectionAdded > 0) { + new MediaMetrics.Item(MediaMetrics.Name.AUDIO_MIDI) + .setUid(mUid) + .set(MediaMetrics.Property.DEVICE_ID, mDeviceInfo.getId()) + .set(MediaMetrics.Property.INPUT_PORT_COUNT, mDeviceInfo.getInputPortCount()) + .set(MediaMetrics.Property.OUTPUT_PORT_COUNT, + mDeviceInfo.getOutputPortCount()) + .set(MediaMetrics.Property.HARDWARE_TYPE, mDeviceInfo.getType()) + .set(MediaMetrics.Property.DURATION_NS, mTotalTimeConnectedNs.get()) + .set(MediaMetrics.Property.OPENED_COUNT, numDeviceConnectionAdded) + .set(MediaMetrics.Property.CLOSED_COUNT, mDeviceConnectionsRemoved.get()) + .set(MediaMetrics.Property.DEVICE_DISCONNECTED, + isDeviceDisconnected ? "true" : "false") + .set(MediaMetrics.Property.IS_SHARED, + !mDeviceInfo.isPrivate() ? "true" : "false") + .set(MediaMetrics.Property.SUPPORTS_MIDI_UMP, mDeviceInfo.getDefaultProtocol() + != MidiDeviceInfo.PROTOCOL_UNKNOWN ? "true" : "false") + .set(MediaMetrics.Property.USING_ALSA, mDeviceInfo.getProperties().get( + MidiDeviceInfo.PROPERTY_ALSA_CARD) != null ? "true" : "false") + .set(MediaMetrics.Property.EVENT, "deviceClosed") + .set(MediaMetrics.Property.TOTAL_INPUT_BYTES, mTotalInputBytes.get()) + .set(MediaMetrics.Property.TOTAL_OUTPUT_BYTES, mTotalOutputBytes.get()) + .record(); + } + } + @Override public void binderDied() { Log.d(TAG, "Device died: " + this); @@ -593,6 +666,11 @@ public class MidiService extends IMidiManager.Stub { } } + public void updateTotalBytes(int totalInputBytes, int totalOutputBytes) { + mTotalInputBytes.set(totalInputBytes); + mTotalOutputBytes.set(totalOutputBytes); + } + @Override public String toString() { StringBuilder sb = new StringBuilder("Device Info: "); @@ -1373,6 +1451,17 @@ public class MidiService extends IMidiManager.Stub { } @Override + public void updateTotalBytes(IMidiDeviceServer server, int totalInputBytes, + int totalOutputBytes) { + synchronized (mDevicesByInfo) { + Device device = mDevicesByServer.get(server.asBinder()); + if (device != null) { + device.updateTotalBytes(totalInputBytes, totalOutputBytes); + } + } + } + + @Override public void dump(FileDescriptor fd, PrintWriter writer, String[] args) { if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return; final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " "); diff --git a/services/tests/InputMethodSystemServerTests/Android.bp b/services/tests/InputMethodSystemServerTests/Android.bp index 939fb6a9d170..70a5c3f961c4 100644 --- a/services/tests/InputMethodSystemServerTests/Android.bp +++ b/services/tests/InputMethodSystemServerTests/Android.bp @@ -28,7 +28,7 @@ android_test { ], srcs: [ - "src/**/*.java", + "src/server/**/*.java", ], static_libs: [ @@ -60,3 +60,52 @@ android_test { enabled: false, }, } + +android_test { + name: "FrameworksImeTests", + defaults: [ + "modules-utils-testable-device-config-defaults", + ], + + srcs: [ + "src/com/android/inputmethodservice/**/*.java", + ], + + manifest: "src/com/android/inputmethodservice/AndroidManifest.xml", + test_config: "src/com/android/inputmethodservice/AndroidTest.xml", + + static_libs: [ + "androidx.test.core", + "androidx.test.runner", + "androidx.test.espresso.core", + "androidx.test.espresso.contrib", + "androidx.test.ext.truth", + "frameworks-base-testutils", + "mockito-target-extended-minus-junit4", + "platform-test-annotations", + "services.core", + "servicestests-core-utils", + "servicestests-utils-mockito-extended", + "truth-prebuilt", + "SimpleImeTestingLib", + "SimpleImeImsLib", + ], + + libs: [ + "android.test.mock", + "android.test.base", + "android.test.runner", + ], + + data: [ + ":SimpleTestIme", + ], + + certificate: "platform", + platform_apis: true, + test_suites: ["device-tests"], + + optimize: { + enabled: false, + }, +} diff --git a/services/tests/InputMethodSystemServerTests/src/com/android/inputmethodservice/AndroidManifest.xml b/services/tests/InputMethodSystemServerTests/src/com/android/inputmethodservice/AndroidManifest.xml new file mode 100644 index 000000000000..0104f7142bea --- /dev/null +++ b/services/tests/InputMethodSystemServerTests/src/com/android/inputmethodservice/AndroidManifest.xml @@ -0,0 +1,43 @@ +<?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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.inputmethod.imetests"> + + <uses-sdk android:targetSdkVersion="31" /> + + <!-- Permissions required for granting and logging --> + <uses-permission android:name="android.permission.LOG_COMPAT_CHANGE"/> + <uses-permission android:name="android.permission.READ_COMPAT_CHANGE_CONFIG"/> + <uses-permission android:name="android.permission.OVERRIDE_COMPAT_CHANGE_CONFIG"/> + <uses-permission android:name="android.permission.OVERRIDE_COMPAT_CHANGE_CONFIG_ON_RELEASE_BUILD"/> + + <!-- Permissions for reading system info --> + <uses-permission android:name="android.permission.READ_DEVICE_CONFIG" /> + <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" /> + + <application android:debuggable="true"> + <uses-library android:name="android.test.runner" /> + </application> + + <!-- The "targetPackage" reference the instruments APK package, which is the FakeImeApk, while + the test package is "com.android.inputmethod.imetests" (FrameworksImeTests.apk).--> + <instrumentation + android:name="androidx.test.runner.AndroidJUnitRunner" + android:targetPackage="com.android.apps.inputmethod.simpleime" + android:label="Frameworks IME Tests" /> +</manifest> diff --git a/services/tests/InputMethodSystemServerTests/src/com/android/inputmethodservice/AndroidTest.xml b/services/tests/InputMethodSystemServerTests/src/com/android/inputmethodservice/AndroidTest.xml new file mode 100644 index 000000000000..6c24d6d6e5a6 --- /dev/null +++ b/services/tests/InputMethodSystemServerTests/src/com/android/inputmethodservice/AndroidTest.xml @@ -0,0 +1,41 @@ +<?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 Frameworks IME Tests."> + <option name="test-suite-tag" value="apct" /> + <option name="test-suite-tag" value="apct-instrumentation" /> + + <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="FrameworksImeTests.apk" /> + <option name="test-file-name" value="SimpleTestIme.apk" /> + </target_preparer> + + <option name="test-tag" value="FrameworksImeTests" /> + + <test class="com.android.tradefed.testtype.AndroidJUnitTest" > + <option name="package" value="com.android.inputmethod.imetests" /> + <option name="runner" value="androidx.test.runner.AndroidJUnitRunner" /> + <option name="hidden-api-checks" value="false"/> + </test> + + <!-- Collect the files in the dump directory for debugging --> + <metrics_collector class="com.android.tradefed.device.metric.FilePullerLogCollector"> + <option name="directory-keys" value="/sdcard/FrameworksImeTests/" /> + <option name="collect-on-run-ended-only" value="true" /> + </metrics_collector> +</configuration> diff --git a/services/tests/InputMethodSystemServerTests/src/com/android/inputmethodservice/InputMethodServiceTest.java b/services/tests/InputMethodSystemServerTests/src/com/android/inputmethodservice/InputMethodServiceTest.java new file mode 100644 index 000000000000..16a98454d135 --- /dev/null +++ b/services/tests/InputMethodSystemServerTests/src/com/android/inputmethodservice/InputMethodServiceTest.java @@ -0,0 +1,276 @@ +/* + * 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.inputmethodservice; + +import static com.android.compatibility.common.util.SystemUtil.eventually; + +import static com.google.common.truth.Truth.assertThat; + +import android.app.Instrumentation; +import android.content.Context; +import android.content.res.Configuration; +import android.os.RemoteException; +import android.support.test.uiautomator.By; +import android.support.test.uiautomator.UiDevice; +import android.support.test.uiautomator.UiObject2; +import android.support.test.uiautomator.Until; +import android.util.Log; +import android.view.inputmethod.EditorInfo; +import android.view.inputmethod.InputMethodManager; +import android.widget.EditText; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.filters.MediumTest; +import androidx.test.platform.app.InstrumentationRegistry; + +import com.android.apps.inputmethod.simpleime.ims.InputMethodServiceWrapper; +import com.android.apps.inputmethod.simpleime.testing.TestActivity; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +@RunWith(AndroidJUnit4.class) +@MediumTest +public class InputMethodServiceTest { + private static final String TAG = "SimpleIMSTest"; + private static final String INPUT_METHOD_SERVICE_NAME = ".SimpleInputMethodService"; + private static final String EDIT_TEXT_DESC = "Input box"; + private static final long TIMEOUT_IN_SECONDS = 3; + + public Instrumentation mInstrumentation; + public UiDevice mUiDevice; + public Context mContext; + public String mTargetPackageName; + public TestActivity mActivity; + public EditText mEditText; + public InputMethodServiceWrapper mInputMethodService; + public String mInputMethodId; + + @Before + public void setUp() throws Exception { + mInstrumentation = InstrumentationRegistry.getInstrumentation(); + mUiDevice = UiDevice.getInstance(mInstrumentation); + mContext = mInstrumentation.getContext(); + mTargetPackageName = mInstrumentation.getTargetContext().getPackageName(); + mInputMethodId = getInputMethodId(); + prepareIme(); + prepareEditor(); + + // Waits for input binding ready. + eventually( + () -> { + mInputMethodService = + InputMethodServiceWrapper.getInputMethodServiceWrapperForTesting(); + assertThat(mInputMethodService).isNotNull(); + + // The editor won't bring up keyboard by default. + assertThat(mInputMethodService.getCurrentInputStarted()).isTrue(); + assertThat(mInputMethodService.getCurrentInputViewStarted()).isFalse(); + }); + } + + @Test + public void testShowHideKeyboard_byUserAction() throws InterruptedException { + // Performs click on editor box to bring up the soft keyboard. + Log.i(TAG, "Click on EditText."); + verifyInputViewStatus(() -> clickOnEditorText(), true /* inputViewStarted */); + + // Press back key to hide soft keyboard. + Log.i(TAG, "Press back"); + verifyInputViewStatus( + () -> assertThat(mUiDevice.pressHome()).isTrue(), false /* inputViewStarted */); + } + + @Test + public void testShowHideKeyboard_byApi() throws InterruptedException { + // Triggers to show IME via public API. + verifyInputViewStatus( + () -> assertThat(mActivity.showImeWithWindowInsetsController()).isTrue(), + true /* inputViewStarted */); + + // Triggers to hide IME via public API. + // TODO(b/242838873): investigate why WIC#hide(ime()) does not work, likely related to + // triggered from IME process. + verifyInputViewStatusOnMainSync( + () -> assertThat(mActivity.hideImeWithInputMethodManager(0 /* flags */)).isTrue(), + false /* inputViewStarted */); + } + + @Test + public void testShowHideSelf() throws InterruptedException { + // IME requests to show itself without any flags: expect shown. + Log.i(TAG, "Call IMS#requestShowSelf(0)"); + verifyInputViewStatusOnMainSync( + () -> mInputMethodService.requestShowSelf(0), true /* inputViewStarted */); + + // IME requests to hide itself with flag: HIDE_IMPLICIT_ONLY, expect not hide (shown). + Log.i(TAG, "Call IMS#requestHideSelf(InputMethodManager.HIDE_IMPLICIT_ONLY)"); + verifyInputViewStatusOnMainSync( + () -> mInputMethodService.requestHideSelf(InputMethodManager.HIDE_IMPLICIT_ONLY), + true /* inputViewStarted */); + + // IME request to hide itself without any flags: expect hidden. + Log.i(TAG, "Call IMS#requestHideSelf(0)"); + verifyInputViewStatusOnMainSync( + () -> mInputMethodService.requestHideSelf(0), false /* inputViewStarted */); + + // IME request to show itself with flag SHOW_IMPLICIT: expect shown. + Log.i(TAG, "Call IMS#requestShowSelf(InputMethodManager.SHOW_IMPLICIT)"); + verifyInputViewStatusOnMainSync( + () -> mInputMethodService.requestShowSelf(InputMethodManager.SHOW_IMPLICIT), + true /* inputViewStarted */); + + // IME request to hide itself with flag: HIDE_IMPLICIT_ONLY, expect hidden. + Log.i(TAG, "Call IMS#requestHideSelf(InputMethodManager.HIDE_IMPLICIT_ONLY)"); + verifyInputViewStatusOnMainSync( + () -> mInputMethodService.requestHideSelf(InputMethodManager.HIDE_IMPLICIT_ONLY), + false /* inputViewStarted */); + } + + private void verifyInputViewStatus(Runnable runnable, boolean inputViewStarted) + throws InterruptedException { + verifyInputViewStatusInternal(runnable, inputViewStarted, false /*runOnMainSync*/); + } + + private void verifyInputViewStatusOnMainSync(Runnable runnable, boolean inputViewStarted) + throws InterruptedException { + verifyInputViewStatusInternal(runnable, inputViewStarted, true /*runOnMainSync*/); + } + + private void verifyInputViewStatusInternal( + Runnable runnable, boolean inputViewStarted, boolean runOnMainSync) + throws InterruptedException { + CountDownLatch signal = new CountDownLatch(1); + mInputMethodService.setCountDownLatchForTesting(signal); + // Runnable to trigger onStartInputView()/ onFinishInputView() + if (runOnMainSync) { + mInstrumentation.runOnMainSync(runnable); + } else { + runnable.run(); + } + // Waits for onStartInputView() to finish. + mInstrumentation.waitForIdleSync(); + signal.await(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS); + // Input is not finished. + assertThat(mInputMethodService.getCurrentInputStarted()).isTrue(); + assertThat(mInputMethodService.getCurrentInputViewStarted()).isEqualTo(inputViewStarted); + } + + @Test + public void testFullScreenMode() throws Exception { + Log.i(TAG, "Set orientation natural"); + verifyFullscreenMode(() -> setOrientation(0), true /* orientationPortrait */); + + Log.i(TAG, "Set orientation left"); + verifyFullscreenMode(() -> setOrientation(1), false /* orientationPortrait */); + + Log.i(TAG, "Set orientation right"); + verifyFullscreenMode(() -> setOrientation(2), false /* orientationPortrait */); + + mUiDevice.unfreezeRotation(); + } + + private void setOrientation(int orientation) { + // Simple wrapper for catching RemoteException. + try { + switch (orientation) { + case 1: + mUiDevice.setOrientationLeft(); + break; + case 2: + mUiDevice.setOrientationRight(); + break; + default: + mUiDevice.setOrientationNatural(); + } + } catch (RemoteException e) { + throw new RuntimeException(e); + } + } + + private void verifyFullscreenMode(Runnable runnable, boolean orientationPortrait) + throws InterruptedException { + CountDownLatch signal = new CountDownLatch(1); + mInputMethodService.setCountDownLatchForTesting(signal); + + // Runnable to trigger onConfigurationChanged() + try { + runnable.run(); + } catch (Exception e) { + throw new RuntimeException(e); + } + // Waits for onConfigurationChanged() to finish. + mInstrumentation.waitForIdleSync(); + signal.await(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS); + + clickOnEditorText(); + eventually(() -> assertThat(mInputMethodService.isInputViewShown()).isTrue()); + + assertThat(mInputMethodService.getResources().getConfiguration().orientation) + .isEqualTo( + orientationPortrait + ? Configuration.ORIENTATION_PORTRAIT + : Configuration.ORIENTATION_LANDSCAPE); + EditorInfo editorInfo = mInputMethodService.getCurrentInputEditorInfo(); + assertThat(editorInfo.imeOptions & EditorInfo.IME_FLAG_NO_FULLSCREEN).isEqualTo(0); + assertThat(editorInfo.internalImeOptions & EditorInfo.IME_INTERNAL_FLAG_APP_WINDOW_PORTRAIT) + .isEqualTo( + orientationPortrait ? EditorInfo.IME_INTERNAL_FLAG_APP_WINDOW_PORTRAIT : 0); + assertThat(mInputMethodService.onEvaluateFullscreenMode()).isEqualTo(!orientationPortrait); + assertThat(mInputMethodService.isFullscreenMode()).isEqualTo(!orientationPortrait); + + mUiDevice.pressBack(); + } + + private void prepareIme() throws Exception { + executeShellCommand("ime enable " + mInputMethodId); + executeShellCommand("ime set " + mInputMethodId); + mInstrumentation.waitForIdleSync(); + Log.i(TAG, "Finish preparing IME"); + } + + private void prepareEditor() { + mActivity = TestActivity.start(mInstrumentation); + mEditText = mActivity.mEditText; + Log.i(TAG, "Finish preparing activity with editor."); + } + + private String getInputMethodId() { + return mTargetPackageName + "/" + INPUT_METHOD_SERVICE_NAME; + } + + private String executeShellCommand(String cmd) throws Exception { + Log.i(TAG, "Run command: " + cmd); + return UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) + .executeShellCommand(cmd); + } + + private void clickOnEditorText() { + // Find the editText and click it. + UiObject2 editTextUiObject = + mUiDevice.wait( + Until.findObject(By.desc(EDIT_TEXT_DESC)), + TimeUnit.SECONDS.toMillis(TIMEOUT_IN_SECONDS)); + assertThat(editTextUiObject).isNotNull(); + editTextUiObject.click(); + mInstrumentation.waitForIdleSync(); + } +} diff --git a/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/Android.bp b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/Android.bp new file mode 100644 index 000000000000..ef50476c2928 --- /dev/null +++ b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/Android.bp @@ -0,0 +1,62 @@ +// 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 { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_base_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_base_license"], +} + +android_test_helper_app { + name: "SimpleTestIme", + + srcs: [ + "src/com/android/apps/inputmethod/simpleime/*.java", + ], + + static_libs: [ + "SimpleImeImsLib", + "SimpleImeTestingLib", + ], + resource_dirs: ["res"], + manifest: "AndroidManifest.xml", + + dex_preopt: { + enabled: false, + }, + optimize: { + enabled: false, + }, + export_package_resources: true, + sdk_version: "current", +} + +android_library { + name: "SimpleImeImsLib", + srcs: [ + "src/com/android/apps/inputmethod/simpleime/ims/*.java", + ], + sdk_version: "current", +} + +android_library { + name: "SimpleImeTestingLib", + srcs: [ + "src/com/android/apps/inputmethod/simpleime/testing/*.java", + ], + sdk_version: "current", +} diff --git a/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/AndroidManifest.xml b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/AndroidManifest.xml new file mode 100644 index 000000000000..802caf132db5 --- /dev/null +++ b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/AndroidManifest.xml @@ -0,0 +1,54 @@ +<?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. + --> + +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.apps.inputmethod.simpleime"> + + <uses-sdk android:targetSdkVersion="31" /> + + <application android:debuggable="true" + android:label="@string/app_name"> + <service + android:name="com.android.apps.inputmethod.simpleime.SimpleInputMethodService" + android:label="@string/app_name" + android:directBootAware="true" + android:permission="android.permission.BIND_INPUT_METHOD" + android:exported="true"> + + <meta-data + android:name="android.view.im" + android:resource="@xml/method"/> + + <intent-filter> + <action android:name="android.view.InputMethod"/> + </intent-filter> + </service> + + <!-- This is for test only. --> + <activity android:name="com.android.apps.inputmethod.simpleime.testing.TestActivity" + android:exported="false" + android:label="TestActivity" + android:launchMode="singleInstance" + android:excludeFromRecents="true" + android:noHistory="true" + android:taskAffinity=""> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + </intent-filter> + </activity> + </application> +</manifest>
\ No newline at end of file diff --git a/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/drawable/key_border.xml b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/drawable/key_border.xml new file mode 100644 index 000000000000..dbfcc30a7f4e --- /dev/null +++ b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/drawable/key_border.xml @@ -0,0 +1,30 @@ +<?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. + --> + +<shape xmlns:android="http://schemas.android.com/apk/res/android" + android:shape="rectangle" > + <solid + android:color="#FAFAFA" > + </solid> + <stroke + android:width="1dp" + android:color="#0F000000" > + </stroke> + <corners + android:radius="2dp" > + </corners> +</shape>
\ No newline at end of file diff --git a/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/layout/input_view.xml b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/layout/input_view.xml new file mode 100644 index 000000000000..f2292701e795 --- /dev/null +++ b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/layout/input_view.xml @@ -0,0 +1,22 @@ +<?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. + --> + +<FrameLayout + xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/input" + android:layout_width="match_parent" + android:layout_height="match_parent"/>
\ No newline at end of file diff --git a/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/layout/qwerty_10_9_9.xml b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/layout/qwerty_10_9_9.xml new file mode 100644 index 000000000000..ee94ea9eee1e --- /dev/null +++ b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/layout/qwerty_10_9_9.xml @@ -0,0 +1,200 @@ +<?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. + --> + +<LinearLayout + xmlns:android="http://schemas.android.com/apk/res/android" + style="@style/KeyboardArea"> + + <View style="@style/KeyboardRow.Header"/> + + <LinearLayout style="@style/KeyboardRow"> + <TextView + android:id="@+id/key_pos_0_0" + android:text="q" + android:tag="KEYCODE_Q" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_0_1" + android:text="w" + android:tag="KEYCODE_W" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_0_2" + android:text="e" + android:tag="KEYCODE_E" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_0_3" + android:text="r" + android:tag="KEYCODE_R" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_0_4" + android:text="t" + android:tag="KEYCODE_T" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_0_5" + android:text="y" + android:tag="KEYCODE_Y" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_0_6" + android:text="u" + android:tag="KEYCODE_U" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_0_7" + android:text="i" + android:tag="KEYCODE_I" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_0_8" + android:text="o" + android:tag="KEYCODE_O" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_0_9" + android:text="p" + android:tag="KEYCODE_P" + style="@style/SoftKey"/> + </LinearLayout> + + <LinearLayout style="@style/KeyboardRow"> + <TextView + android:id="@+id/key_pos_1_0" + android:text="a" + android:tag="KEYCODE_A" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_1_1" + android:text="s" + android:tag="KEYCODE_S" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_1_2" + android:text="d" + android:tag="KEYCODE_D" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_1_3" + android:text="f" + android:tag="KEYCODE_F" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_1_4" + android:text="g" + android:tag="KEYCODE_G" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_1_5" + android:text="h" + android:tag="KEYCODE_H" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_1_6" + android:text="j" + android:tag="KEYCODE_J" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_1_7" + android:text="k" + android:tag="KEYCODE_K" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_1_8" + android:text="l" + android:tag="KEYCODE_L" + style="@style/SoftKey"/> + </LinearLayout> + + <LinearLayout style="@style/KeyboardRow"> + <TextView + android:id="@+id/key_pos_shift" + android:text="SHI" + android:tag="KEYCODE_SHIFT" + style="@style/SoftKey.Function"/> + <TextView + android:id="@+id/key_pos_2_0" + android:text="z" + android:tag="KEYCODE_Z" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_2_1" + android:text="x" + android:tag="KEYCODE_X" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_2_2" + style="@style/SoftKey" + android:text="c" + android:tag="KEYCODE_C"/> + <TextView + android:id="@+id/key_pos_2_3" + android:text="v" + android:tag="KEYCODE_V" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_2_4" + android:text="b" + android:tag="KEYCODE_B" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_2_5" + android:text="n" + android:tag="KEYCODE_N" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_2_6" + android:text="m" + android:tag="KEYCODE_M" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_del" + android:text="DEL" + android:tag="KEYCODE_DEL" + style="@style/SoftKey.Function"/> + </LinearLayout> + + <LinearLayout style="@style/KeyboardRow"> + <TextView + android:id="@+id/key_pos_symbol" + android:text="TAB" + android:tag="KEYCODE_TAB" + style="@style/SoftKey.Function"/> + <TextView + android:id="@+id/key_pos_comma" + android:text="," + android:tag="KEYCODE_COMMA" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_space" + android:text="SPACE" + android:tag="KEYCODE_SPACE" + style="@style/SoftKey.Space"/> + <TextView + android:id="@+id/key_pos_period" + android:text="." + android:tag="KEYCODE_PERIOD" + style="@style/SoftKey"/> + <TextView + android:id="@+id/key_pos_enter" + android:text="ENT" + android:tag="KEYCODE_ENTER" + style="@style/SoftKey.Function.Bottom"/> + </LinearLayout> +</LinearLayout> diff --git a/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/values/dimens.xml b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/values/dimens.xml new file mode 100644 index 000000000000..1a4959e14a1f --- /dev/null +++ b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/values/dimens.xml @@ -0,0 +1,24 @@ +<?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> + <dimen name="text_size_normal">24dp</dimen> + <dimen name="text_size_symbol">14dp</dimen> + + <dimen name="keyboard_header_height">40dp</dimen> + <dimen name="keyboard_row_height">50dp</dimen> +</resources>
\ No newline at end of file diff --git a/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/values/strings.xml b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/values/strings.xml new file mode 100644 index 000000000000..11377fa02dc9 --- /dev/null +++ b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/values/strings.xml @@ -0,0 +1,20 @@ +<?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> + <string name="app_name">Fake IME</string> +</resources>
\ No newline at end of file diff --git a/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/values/styles.xml b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/values/styles.xml new file mode 100644 index 000000000000..83f7bc317066 --- /dev/null +++ b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/values/styles.xml @@ -0,0 +1,66 @@ +<?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> + <style name="KeyboardArea"> + <item name="android:layout_width">match_parent</item> + <item name="android:layout_height">wrap_content</item> + <item name="android:layout_gravity">bottom</item> + <item name="android:orientation">vertical</item> + <item name="android:background">#FFFFFFFF</item> + </style> + + <style name="KeyboardRow"> + <item name="android:layout_width">match_parent</item> + <item name="android:layout_height">@dimen/keyboard_row_height</item> + <item name="android:orientation">horizontal</item> + </style> + + <style name="KeyboardRow.Header"> + <item name="android:layout_height">@dimen/keyboard_header_height</item> + <item name="android:background">#FFEEEEEE</item> + </style> + + <style name="SoftKey"> + <item name="android:layout_width">0dp</item> + <item name="android:layout_height">match_parent</item> + <item name="android:layout_weight">2</item> + <item name="android:gravity">center</item> + <item name="android:textColor">#FF000000</item> + <item name="android:textSize">@dimen/text_size_normal</item> + <item name="android:fontFamily">roboto-regular</item> + <item name="android:background">@drawable/key_border</item> + </style> + + <style name="SoftKey.Function"> + <item name="android:layout_weight">3</item> + <item name="android:textColor">#FF333333</item> + <item name="android:textSize">@dimen/text_size_symbol</item> + </style> + + <style name="SoftKey.Function.Bottom"> + <item name="android:layout_weight">3</item> + <item name="android:textColor">#FF333333</item> + <item name="android:textSize">@dimen/text_size_symbol</item> + </style> + + <style name="SoftKey.Space"> + <item name="android:layout_weight">10</item> + <item name="android:textColor">#FF333333</item> + <item name="android:textSize">@dimen/text_size_symbol</item> + </style> +</resources>
\ No newline at end of file diff --git a/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/xml/method.xml b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/xml/method.xml new file mode 100644 index 000000000000..872b0688814a --- /dev/null +++ b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/res/xml/method.xml @@ -0,0 +1,23 @@ +<?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. + --> + +<input-method xmlns:android="http://schemas.android.com/apk/res/android"> + <subtype + android:label="FakeIme" + android:imeSubtypeLocale="en_US" + android:imeSubtypeMode="keyboard"/> +</input-method>
\ No newline at end of file diff --git a/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/src/com/android/apps/inputmethod/simpleime/KeyCodeConstants.java b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/src/com/android/apps/inputmethod/simpleime/KeyCodeConstants.java new file mode 100644 index 000000000000..990fa24aad22 --- /dev/null +++ b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/src/com/android/apps/inputmethod/simpleime/KeyCodeConstants.java @@ -0,0 +1,68 @@ +/* + * 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.apps.inputmethod.simpleime; + +import android.view.KeyEvent; + +import java.util.HashMap; + +/** Holder of key codes and their name. */ +public final class KeyCodeConstants { + private KeyCodeConstants() {} + + static final HashMap<String, Integer> KEY_NAME_TO_CODE_MAP = new HashMap<>(); + + static { + KEY_NAME_TO_CODE_MAP.put("KEYCODE_A", KeyEvent.KEYCODE_A); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_B", KeyEvent.KEYCODE_B); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_C", KeyEvent.KEYCODE_C); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_D", KeyEvent.KEYCODE_D); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_E", KeyEvent.KEYCODE_E); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_F", KeyEvent.KEYCODE_F); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_G", KeyEvent.KEYCODE_G); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_H", KeyEvent.KEYCODE_H); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_I", KeyEvent.KEYCODE_I); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_J", KeyEvent.KEYCODE_J); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_K", KeyEvent.KEYCODE_K); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_L", KeyEvent.KEYCODE_L); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_M", KeyEvent.KEYCODE_M); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_N", KeyEvent.KEYCODE_N); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_O", KeyEvent.KEYCODE_O); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_P", KeyEvent.KEYCODE_P); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_Q", KeyEvent.KEYCODE_Q); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_R", KeyEvent.KEYCODE_R); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_S", KeyEvent.KEYCODE_S); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_T", KeyEvent.KEYCODE_T); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_U", KeyEvent.KEYCODE_U); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_V", KeyEvent.KEYCODE_V); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_W", KeyEvent.KEYCODE_W); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_X", KeyEvent.KEYCODE_X); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_Y", KeyEvent.KEYCODE_Y); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_Z", KeyEvent.KEYCODE_Z); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_SHIFT", KeyEvent.KEYCODE_SHIFT_LEFT); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_DEL", KeyEvent.KEYCODE_DEL); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_SPACE", KeyEvent.KEYCODE_SPACE); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_ENTER", KeyEvent.KEYCODE_ENTER); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_COMMA", KeyEvent.KEYCODE_COMMA); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_PERIOD", KeyEvent.KEYCODE_PERIOD); + KEY_NAME_TO_CODE_MAP.put("KEYCODE_TAB", KeyEvent.KEYCODE_TAB); + } + + public static boolean isAlphaKeyCode(int keyCode) { + return keyCode >= KeyEvent.KEYCODE_A && keyCode <= KeyEvent.KEYCODE_Z; + } +} diff --git a/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/src/com/android/apps/inputmethod/simpleime/SimpleInputMethodService.java b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/src/com/android/apps/inputmethod/simpleime/SimpleInputMethodService.java new file mode 100644 index 000000000000..48942a31658f --- /dev/null +++ b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/src/com/android/apps/inputmethod/simpleime/SimpleInputMethodService.java @@ -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.apps.inputmethod.simpleime; + +import android.inputmethodservice.InputMethodService; +import android.os.SystemClock; +import android.util.Log; +import android.view.KeyEvent; +import android.view.LayoutInflater; +import android.view.View; +import android.view.inputmethod.EditorInfo; +import android.view.inputmethod.InputConnection; +import android.widget.FrameLayout; + +import com.android.apps.inputmethod.simpleime.ims.InputMethodServiceWrapper; + +/** The {@link InputMethodService} implementation for SimpeTestIme app. */ +public class SimpleInputMethodService extends InputMethodServiceWrapper { + private static final String TAG = "SimpleIMS"; + + private FrameLayout mInputView; + + @Override + public View onCreateInputView() { + Log.i(TAG, "onCreateInputView()"); + mInputView = (FrameLayout) LayoutInflater.from(this).inflate(R.layout.input_view, null); + return mInputView; + } + + @Override + public void onStartInputView(EditorInfo info, boolean restarting) { + super.onStartInputView(info, restarting); + mInputView.removeAllViews(); + SimpleKeyboard keyboard = new SimpleKeyboard(this, R.layout.qwerty_10_9_9); + mInputView.addView(keyboard.inflateKeyboardView(LayoutInflater.from(this), mInputView)); + } + + void handle(String data, int keyboardState) { + InputConnection inputConnection = getCurrentInputConnection(); + Integer keyCode = KeyCodeConstants.KEY_NAME_TO_CODE_MAP.get(data); + Log.v(TAG, "keyCode: " + keyCode); + if (keyCode != null) { + inputConnection.sendKeyEvent( + new KeyEvent( + SystemClock.uptimeMillis(), + SystemClock.uptimeMillis(), + KeyEvent.ACTION_DOWN, + keyCode, + 0, + KeyCodeConstants.isAlphaKeyCode(keyCode) ? keyboardState : 0)); + } + } +} diff --git a/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/src/com/android/apps/inputmethod/simpleime/SimpleKeyboard.java b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/src/com/android/apps/inputmethod/simpleime/SimpleKeyboard.java new file mode 100644 index 000000000000..b16ec9ebd718 --- /dev/null +++ b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/src/com/android/apps/inputmethod/simpleime/SimpleKeyboard.java @@ -0,0 +1,126 @@ +/* + * 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.apps.inputmethod.simpleime; + +import android.text.TextUtils; +import android.util.Log; +import android.util.SparseArray; +import android.view.KeyEvent; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +/** Controls the visible virtual keyboard view. */ +final class SimpleKeyboard { + private static final String TAG = "SimpleKeyboard"; + + private static final int[] SOFT_KEY_IDS = + new int[] { + R.id.key_pos_0_0, + R.id.key_pos_0_1, + R.id.key_pos_0_2, + R.id.key_pos_0_3, + R.id.key_pos_0_4, + R.id.key_pos_0_5, + R.id.key_pos_0_6, + R.id.key_pos_0_7, + R.id.key_pos_0_8, + R.id.key_pos_0_9, + R.id.key_pos_1_0, + R.id.key_pos_1_1, + R.id.key_pos_1_2, + R.id.key_pos_1_3, + R.id.key_pos_1_4, + R.id.key_pos_1_5, + R.id.key_pos_1_6, + R.id.key_pos_1_7, + R.id.key_pos_1_8, + R.id.key_pos_2_0, + R.id.key_pos_2_1, + R.id.key_pos_2_2, + R.id.key_pos_2_3, + R.id.key_pos_2_4, + R.id.key_pos_2_5, + R.id.key_pos_2_6, + R.id.key_pos_shift, + R.id.key_pos_del, + R.id.key_pos_symbol, + R.id.key_pos_comma, + R.id.key_pos_space, + R.id.key_pos_period, + R.id.key_pos_enter, + }; + + private final SimpleInputMethodService mSimpleInputMethodService; + private final int mViewResId; + private final SparseArray<TextView> mSoftKeyViews = new SparseArray<>(); + private View mKeyboardView; + private int mKeyboardState; + + SimpleKeyboard(SimpleInputMethodService simpleInputMethodService, int viewResId) { + this.mSimpleInputMethodService = simpleInputMethodService; + this.mViewResId = viewResId; + this.mKeyboardState = 0; + } + + View inflateKeyboardView(LayoutInflater inflater, ViewGroup inputView) { + mKeyboardView = inflater.inflate(mViewResId, inputView, false); + mapSoftKeys(); + return mKeyboardView; + } + + private void mapSoftKeys() { + for (int id : SOFT_KEY_IDS) { + TextView softKeyView = mKeyboardView.findViewById(id); + mSoftKeyViews.put(id, softKeyView); + String tagData = softKeyView.getTag() != null ? softKeyView.getTag().toString() : null; + softKeyView.setOnClickListener(v -> handle(tagData)); + } + } + + private void handle(String data) { + Log.i(TAG, "handle(): " + data); + if (TextUtils.isEmpty(data)) { + return; + } + if ("KEYCODE_SHIFT".equals(data)) { + handleShift(); + return; + } + + mSimpleInputMethodService.handle(data, mKeyboardState); + } + + private void handleShift() { + mKeyboardState = toggleShiftState(mKeyboardState); + Log.v(TAG, "currentKeyboardState: " + mKeyboardState); + boolean isShiftOn = isShiftOn(mKeyboardState); + for (int i = 0; i < mSoftKeyViews.size(); i++) { + TextView softKeyView = mSoftKeyViews.valueAt(i); + softKeyView.setAllCaps(isShiftOn); + } + } + + private static boolean isShiftOn(int state) { + return (state & KeyEvent.META_SHIFT_ON) == KeyEvent.META_SHIFT_ON; + } + + private static int toggleShiftState(int state) { + return state ^ KeyEvent.META_SHIFT_ON; + } +} diff --git a/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/src/com/android/apps/inputmethod/simpleime/ims/InputMethodServiceWrapper.java b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/src/com/android/apps/inputmethod/simpleime/ims/InputMethodServiceWrapper.java new file mode 100644 index 000000000000..b706a654e3a8 --- /dev/null +++ b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/src/com/android/apps/inputmethod/simpleime/ims/InputMethodServiceWrapper.java @@ -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.apps.inputmethod.simpleime.ims; + +import android.content.res.Configuration; +import android.inputmethodservice.InputMethodService; +import android.util.Log; +import android.view.inputmethod.EditorInfo; + +import java.util.concurrent.CountDownLatch; + +/** Wrapper of {@link InputMethodService} to expose interfaces for testing purpose. */ +public class InputMethodServiceWrapper extends InputMethodService { + private static final String TAG = "InputMethodServiceWrapper"; + + private static InputMethodServiceWrapper sInputMethodServiceWrapper; + + public static InputMethodServiceWrapper getInputMethodServiceWrapperForTesting() { + return sInputMethodServiceWrapper; + } + + private boolean mInputViewStarted; + private CountDownLatch mCountDownLatchForTesting; + + public boolean getCurrentInputViewStarted() { + return mInputViewStarted; + } + + public void setCountDownLatchForTesting(CountDownLatch countDownLatchForTesting) { + mCountDownLatchForTesting = countDownLatchForTesting; + } + + @Override + public void onCreate() { + Log.i(TAG, "onCreate()"); + super.onCreate(); + sInputMethodServiceWrapper = this; + } + + @Override + public void onStartInput(EditorInfo info, boolean restarting) { + Log.i(TAG, "onStartInput() editor=" + info + ", restarting=" + restarting); + super.onStartInput(info, restarting); + } + + @Override + public void onStartInputView(EditorInfo info, boolean restarting) { + Log.i(TAG, "onStartInputView() editor=" + info + ", restarting=" + restarting); + super.onStartInputView(info, restarting); + mInputViewStarted = true; + if (mCountDownLatchForTesting != null) { + mCountDownLatchForTesting.countDown(); + } + } + + @Override + public void onFinishInput() { + Log.i(TAG, "onFinishInput()"); + super.onFinishInput(); + } + + @Override + public void onFinishInputView(boolean finishingInput) { + Log.i(TAG, "onFinishInputView()"); + super.onFinishInputView(finishingInput); + mInputViewStarted = false; + + if (mCountDownLatchForTesting != null) { + mCountDownLatchForTesting.countDown(); + } + } + + @Override + public void requestHideSelf(int flags) { + Log.i(TAG, "requestHideSelf() " + flags); + super.requestHideSelf(flags); + } + + @Override + public void onConfigurationChanged(Configuration newConfig) { + Log.i(TAG, "onConfigurationChanged() " + newConfig); + super.onConfigurationChanged(newConfig); + + if (mCountDownLatchForTesting != null) { + mCountDownLatchForTesting.countDown(); + } + } +} diff --git a/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/src/com/android/apps/inputmethod/simpleime/testing/TestActivity.java b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/src/com/android/apps/inputmethod/simpleime/testing/TestActivity.java new file mode 100644 index 000000000000..0eec7e629d87 --- /dev/null +++ b/services/tests/InputMethodSystemServerTests/test-apps/SimpleTestIme/src/com/android/apps/inputmethod/simpleime/testing/TestActivity.java @@ -0,0 +1,105 @@ +/* + * 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.apps.inputmethod.simpleime.testing; + +import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; +import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; + +import android.app.Activity; +import android.app.Instrumentation; +import android.content.Intent; +import android.os.Bundle; +import android.util.Log; +import android.view.WindowInsets; +import android.view.WindowInsetsController; +import android.view.WindowManager; +import android.view.inputmethod.InputMethodManager; +import android.widget.EditText; +import android.widget.LinearLayout; + +/** + * A special activity for testing purpose. + * + * <p>This is used when the instruments package is SimpleTestIme, as the Intent needs to be started + * in the instruments package. More details see {@link + * Instrumentation#startActivitySync(Intent)}.</> + */ +public class TestActivity extends Activity { + private static final String TAG = "TestActivity"; + + /** + * Start a new test activity with an editor and wait for it to begin running before returning. + * + * @param instrumentation application instrumentation + * @return the newly started activity + */ + public static TestActivity start(Instrumentation instrumentation) { + Intent intent = + new Intent() + .setAction(Intent.ACTION_MAIN) + .setClass(instrumentation.getTargetContext(), TestActivity.class) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + return (TestActivity) instrumentation.startActivitySync(intent); + } + + public EditText mEditText; + + @Override + protected void onCreate(Bundle savedInstanceState) { + getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + LinearLayout rootView = new LinearLayout(this); + mEditText = new EditText(this); + mEditText.setContentDescription("Input box"); + rootView.addView(mEditText, new LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)); + setContentView(rootView); + mEditText.requestFocus(); + super.onCreate(savedInstanceState); + } + + /** Shows soft keyboard via InputMethodManager. */ + public boolean showImeWithInputMethodManager(int flags) { + InputMethodManager imm = getSystemService(InputMethodManager.class); + boolean result = imm.showSoftInput(mEditText, flags); + Log.i(TAG, "hideIme() via InputMethodManager, result=" + result); + return result; + } + + /** Shows soft keyboard via WindowInsetsController. */ + public boolean showImeWithWindowInsetsController() { + WindowInsetsController windowInsetsController = mEditText.getWindowInsetsController(); + windowInsetsController.show(WindowInsets.Type.ime()); + Log.i(TAG, "showIme() via WindowInsetsController"); + return true; + } + + /** Hides soft keyboard via InputMethodManager. */ + public boolean hideImeWithInputMethodManager(int flags) { + InputMethodManager imm = getSystemService(InputMethodManager.class); + boolean result = imm.hideSoftInputFromWindow(mEditText.getWindowToken(), flags); + Log.i(TAG, "hideIme() via InputMethodManager, result=" + result); + return result; + } + + /** Hides soft keyboard via WindowInsetsController. */ + public boolean hideImeWithWindowInsetsController() { + WindowInsetsController windowInsetsController = mEditText.getWindowInsetsController(); + windowInsetsController.hide(WindowInsets.Type.ime()); + Log.i(TAG, "hideIme() via WindowInsetsController"); + return true; + } +} diff --git a/services/tests/PackageManagerServiceTests/server/Android.bp b/services/tests/PackageManagerServiceTests/server/Android.bp index ebd6b649c4a8..cc2659308a95 100644 --- a/services/tests/PackageManagerServiceTests/server/Android.bp +++ b/services/tests/PackageManagerServiceTests/server/Android.bp @@ -94,6 +94,7 @@ android_test { "libunwindstack", "libutils", "netd_aidl_interface-V5-cpp", + "libservices.core.settings.testonly", ], dxflags: ["--multi-dex"], diff --git a/services/tests/PackageManagerServiceTests/server/src/com/android/server/PackageManagerSettingsTests.java b/services/tests/PackageManagerServiceTests/server/src/com/android/server/PackageManagerSettingsTests.java index 3727d660f9a7..b3f64b6db54c 100644 --- a/services/tests/PackageManagerServiceTests/server/src/com/android/server/PackageManagerSettingsTests.java +++ b/services/tests/PackageManagerServiceTests/server/src/com/android/server/PackageManagerSettingsTests.java @@ -111,6 +111,10 @@ public class PackageManagerSettingsTests { private static final String PACKAGE_NAME_3 = "com.android.app3"; private static final int TEST_RESOURCE_ID = 2131231283; + static { + System.loadLibrary("services.core.settings.testonly"); + } + @Mock RuntimePermissionsPersistence mRuntimePermissionsPersistence; @Mock diff --git a/services/tests/mockingservicestests/assets/AppOpsUpgradeTest/appops-version-1.xml b/services/tests/mockingservicestests/assets/AppOpsUpgradeTest/appops-version-1.xml new file mode 100644 index 000000000000..1dde7dcc4720 --- /dev/null +++ b/services/tests/mockingservicestests/assets/AppOpsUpgradeTest/appops-version-1.xml @@ -0,0 +1,781 @@ +<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
+<app-ops v="1">
+ <uid n="1001">
+ <op n="0" m="4" />
+ <op n="1" m="4" />
+ <op n="15" m="0" />
+ <op n="27" m="4" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="1002">
+ <op n="0" m="4" />
+ <op n="1" m="4" />
+ <op n="15" m="0" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10077">
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10079">
+ <op n="116" m="1" />
+ </uid>
+ <uid n="10080">
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10081">
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10086">
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10087">
+ <op n="59" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10090">
+ <op n="0" m="4" />
+ <op n="1" m="4" />
+ </uid>
+ <uid n="10096">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ </uid>
+ <uid n="10112">
+ <op n="11" m="1" />
+ <op n="51" m="1" />
+ <op n="59" m="1" />
+ <op n="62" m="1" />
+ <op n="81" m="1" />
+ <op n="83" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10113">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ <op n="51" m="1" />
+ <op n="62" m="1" />
+ </uid>
+ <uid n="10114">
+ <op n="4" m="1" />
+ </uid>
+ <uid n="10115">
+ <op n="0" m="1" />
+ </uid>
+ <uid n="10116">
+ <op n="0" m="1" />
+ </uid>
+ <uid n="10117">
+ <op n="0" m="4" />
+ <op n="1" m="4" />
+ <op n="13" m="1" />
+ <op n="14" m="1" />
+ <op n="16" m="1" />
+ <op n="26" m="4" />
+ <op n="27" m="4" />
+ </uid>
+ <uid n="10118">
+ <op n="51" m="1" />
+ </uid>
+ <uid n="10119">
+ <op n="11" m="1" />
+ <op n="77" m="1" />
+ <op n="111" m="1" />
+ </uid>
+ <uid n="10120">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ <op n="4" m="1" />
+ <op n="6" m="1" />
+ <op n="7" m="1" />
+ <op n="11" m="1" />
+ <op n="13" m="1" />
+ <op n="26" m="1" />
+ <op n="27" m="1" />
+ <op n="54" m="1" />
+ <op n="59" m="1" />
+ <op n="81" m="1" />
+ <op n="83" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10121">
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10122">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ <op n="51" m="1" />
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="81" m="1" />
+ <op n="83" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10123">
+ <op n="0" m="4" />
+ <op n="1" m="4" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10124">
+ <op n="11" m="1" />
+ <op n="26" m="1" />
+ </uid>
+ <uid n="10125">
+ <op n="11" m="1" />
+ </uid>
+ <uid n="10127">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ <op n="26" m="4" />
+ <op n="27" m="4" />
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="65" m="1" />
+ <op n="81" m="1" />
+ <op n="83" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="1" />
+ <op n="111" m="1" />
+ </uid>
+ <uid n="10129">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ </uid>
+ <uid n="10130">
+ <op n="51" m="1" />
+ </uid>
+ <uid n="10131">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="81" m="1" />
+ <op n="83" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10132">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ <op n="26" m="1" />
+ <op n="27" m="1" />
+ <op n="69" m="1" />
+ <op n="79" m="1" />
+ </uid>
+ <uid n="10133">
+ <op n="11" m="1" />
+ </uid>
+ <uid n="10136">
+ <op n="0" m="1" />
+ <op n="4" m="1" />
+ <op n="77" m="1" />
+ <op n="87" m="1" />
+ <op n="111" m="1" />
+ <op n="114" m="1" />
+ </uid>
+ <uid n="10137">
+ <op n="62" m="1" />
+ </uid>
+ <uid n="10138">
+ <op n="26" m="4" />
+ </uid>
+ <uid n="10140">
+ <op n="26" m="4" />
+ <op n="27" m="4" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10141">
+ <op n="11" m="1" />
+ <op n="27" m="1" />
+ <op n="111" m="1" />
+ </uid>
+ <uid n="10142">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ <op n="11" m="1" />
+ </uid>
+ <uid n="10144">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ <op n="4" m="1" />
+ <op n="11" m="1" />
+ <op n="27" m="4" />
+ <op n="111" m="1" />
+ </uid>
+ <uid n="10145">
+ <op n="11" m="1" />
+ </uid>
+ <uid n="10149">
+ <op n="11" m="1" />
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="81" m="1" />
+ <op n="83" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10150">
+ <op n="51" m="1" />
+ </uid>
+ <uid n="10151">
+ <op n="11" m="1" />
+ </uid>
+ <uid n="10152">
+ <op n="11" m="1" />
+ </uid>
+ <uid n="10154">
+ <op n="0" m="4" />
+ <op n="1" m="4" />
+ <op n="27" m="4" />
+ </uid>
+ <uid n="10155">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ </uid>
+ <uid n="10157">
+ <op n="13" m="1" />
+ </uid>
+ <uid n="10158">
+ <op n="11" m="1" />
+ </uid>
+ <uid n="10160">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ <op n="11" m="1" />
+ <op n="26" m="4" />
+ <op n="27" m="4" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10161">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ <op n="11" m="1" />
+ <op n="51" m="1" />
+ <op n="77" m="1" />
+ <op n="87" m="1" />
+ <op n="111" m="1" />
+ <op n="114" m="1" />
+ </uid>
+ <uid n="10162">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ <op n="15" m="0" />
+ <op n="26" m="4" />
+ <op n="27" m="4" />
+ <op n="87" m="1" />
+ <op n="89" m="0" />
+ </uid>
+ <uid n="10163">
+ <op n="26" m="4" />
+ <op n="27" m="4" />
+ <op n="56" m="4" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10164">
+ <op n="26" m="1" />
+ <op n="27" m="4" />
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="69" m="1" />
+ <op n="79" m="1" />
+ <op n="81" m="1" />
+ <op n="83" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10169">
+ <op n="11" m="1" />
+ </uid>
+ <uid n="10170">
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10171">
+ <op n="26" m="1" />
+ <op n="51" m="1" />
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="81" m="1" />
+ <op n="83" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10172">
+ <op n="11" m="1" />
+ </uid>
+ <uid n="10173">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ <op n="23" m="0" />
+ <op n="26" m="1" />
+ <op n="51" m="1" />
+ <op n="62" m="1" />
+ <op n="65" m="1" />
+ </uid>
+ <uid n="10175">
+ <op n="0" m="1" />
+ <op n="11" m="1" />
+ <op n="26" m="1" />
+ <op n="27" m="1" />
+ </uid>
+ <uid n="10178">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ <op n="11" m="1" />
+ <op n="27" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10179">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ <op n="4" m="1" />
+ <op n="11" m="1" />
+ <op n="26" m="1" />
+ <op n="27" m="1" />
+ <op n="51" m="1" />
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="62" m="1" />
+ <op n="81" m="1" />
+ <op n="83" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10180">
+ <op n="11" m="1" />
+ </uid>
+ <uid n="10181">
+ <op n="4" m="1" />
+ <op n="11" m="1" />
+ <op n="26" m="1" />
+ <op n="27" m="1" />
+ <op n="59" m="1" />
+ <op n="62" m="1" />
+ <op n="81" m="1" />
+ <op n="83" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="1110181">
+ <op n="4" m="1" />
+ <op n="11" m="1" />
+ <op n="26" m="1" />
+ <op n="27" m="1" />
+ <op n="81" m="1" />
+ <op n="83" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="1" />
+ <op n="107" m="2" />
+ </uid>
+ <uid n="10182">
+ <op n="27" m="4" />
+ </uid>
+ <uid n="10183">
+ <op n="11" m="1" />
+ <op n="26" m="4" />
+ </uid>
+ <uid n="10184">
+ <op n="4" m="1" />
+ <op n="11" m="1" />
+ <op n="13" m="1" />
+ <op n="26" m="1" />
+ <op n="27" m="4" />
+ </uid>
+ <uid n="10185">
+ <op n="8" m="1" />
+ <op n="59" m="1" />
+ <op n="81" m="1" />
+ <op n="83" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10187">
+ <op n="11" m="1" />
+ </uid>
+ <uid n="10189">
+ <op n="11" m="1" />
+ <op n="26" m="1" />
+ <op n="27" m="1" />
+ <op n="51" m="1" />
+ </uid>
+ <uid n="10190">
+ <op n="0" m="1" />
+ <op n="13" m="1" />
+ </uid>
+ <uid n="10191">
+ <op n="11" m="1" />
+ </uid>
+ <uid n="10192">
+ <op n="11" m="1" />
+ <op n="13" m="1" />
+ <op n="26" m="1" />
+ <op n="27" m="1" />
+ <op n="51" m="1" />
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="81" m="1" />
+ <op n="83" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10193">
+ <op n="11" m="1" />
+ </uid>
+ <uid n="10197">
+ <op n="11" m="1" />
+ </uid>
+ <uid n="10198">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ <op n="4" m="1" />
+ <op n="11" m="1" />
+ <op n="26" m="1" />
+ <op n="27" m="1" />
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="77" m="1" />
+ <op n="81" m="1" />
+ <op n="83" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="1" />
+ <op n="90" m="1" />
+ <op n="107" m="0" />
+ <op n="111" m="1" />
+ </uid>
+ <uid n="10199">
+ <op n="4" m="1" />
+ <op n="11" m="1" />
+ <op n="26" m="1" />
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="62" m="1" />
+ <op n="81" m="1" />
+ <op n="83" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10200">
+ <op n="11" m="1" />
+ <op n="65" m="1" />
+ <op n="107" m="1" />
+ </uid>
+ <uid n="1110200">
+ <op n="11" m="1" />
+ <op n="65" m="1" />
+ <op n="107" m="2" />
+ </uid>
+ <uid n="10201">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ <op n="4" m="1" />
+ <op n="11" m="1" />
+ <op n="51" m="1" />
+ <op n="62" m="1" />
+ <op n="84" m="0" />
+ <op n="86" m="0" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10206">
+ <op n="0" m="4" />
+ <op n="1" m="4" />
+ <op n="26" m="4" />
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10209">
+ <op n="11" m="1" />
+ <op n="51" m="1" />
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="81" m="1" />
+ <op n="83" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10210">
+ <op n="51" m="1" />
+ </uid>
+ <uid n="10212">
+ <op n="11" m="1" />
+ <op n="62" m="1" />
+ </uid>
+ <uid n="10214">
+ <op n="26" m="4" />
+ </uid>
+ <uid n="10216">
+ <op n="51" m="1" />
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10225">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ <op n="51" m="1" />
+ <op n="59" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10229">
+ <op n="11" m="1" />
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="62" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10231">
+ <op n="51" m="1" />
+ </uid>
+ <uid n="10232">
+ <op n="51" m="1" />
+ </uid>
+ <uid n="10234">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ <op n="11" m="1" />
+ <op n="13" m="1" />
+ <op n="20" m="1" />
+ <op n="26" m="1" />
+ <op n="27" m="1" />
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="81" m="1" />
+ <op n="83" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10235">
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10237">
+ <op n="0" m="4" />
+ <op n="1" m="4" />
+ </uid>
+ <uid n="10238">
+ <op n="26" m="4" />
+ <op n="27" m="4" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10240">
+ <op n="112" m="1" />
+ </uid>
+ <uid n="10241">
+ <op n="59" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10245">
+ <op n="13" m="1" />
+ <op n="51" m="1" />
+ </uid>
+ <uid n="10247">
+ <op n="0" m="1" />
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="81" m="1" />
+ <op n="83" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="0" />
+ <op n="90" m="1" />
+ </uid>
+ <uid n="10254">
+ <op n="11" m="1" />
+ </uid>
+ <uid n="10255">
+ <op n="11" m="1" />
+ </uid>
+ <uid n="10256">
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10258">
+ <op n="11" m="1" />
+ </uid>
+ <uid n="10260">
+ <op n="51" m="1" />
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <uid n="10262">
+ <op n="15" m="0" />
+ </uid>
+ <uid n="10266">
+ <op n="0" m="4" />
+ </uid>
+ <uid n="10267">
+ <op n="0" m="1" />
+ <op n="1" m="1" />
+ <op n="4" m="1" />
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="62" m="1" />
+ <op n="77" m="1" />
+ <op n="81" m="1" />
+ <op n="83" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="1" />
+ <op n="107" m="2" />
+ <op n="111" m="1" />
+ </uid>
+ <uid n="10268">
+ <op n="4" m="1" />
+ <op n="11" m="1" />
+ <op n="62" m="1" />
+ </uid>
+ <uid n="10269">
+ <op n="11" m="1" />
+ <op n="26" m="1" />
+ <op n="27" m="1" />
+ <op n="59" m="1" />
+ <op n="60" m="1" />
+ <op n="85" m="1" />
+ <op n="87" m="1" />
+ </uid>
+ <pkg n="com.google.android.iwlan">
+ <uid n="0">
+ <op n="1" />
+ <op n="75" m="0" />
+ </uid>
+ </pkg>
+ <pkg n="com.android.phone">
+ <uid n="0">
+ <op n="1" />
+ <op n="75" m="0" />
+ </uid>
+ </pkg>
+ <pkg n="android">
+ <uid n="1000">
+ <op n="0">
+ <st n="214748364801" t="1670287941040" />
+ </op>
+ <op n="4">
+ <st n="214748364801" t="1670289665522" />
+ </op>
+ <op n="6">
+ <st n="214748364801" t="1670287946650" />
+ </op>
+ <op n="8">
+ <st n="214748364801" t="1670289624396" />
+ </op>
+ <op n="14">
+ <st n="214748364801" t="1670287951031" />
+ </op>
+ <op n="40">
+ <st n="214748364801" t="1670291786337" d="156" />
+ </op>
+ <op n="41">
+ <st id="SensorNotificationService" n="214748364801" t="1670287585567" d="4251183" />
+ <st id="CountryDetector" n="214748364801" t="1670287583306" d="6700" />
+ </op>
+ <op n="43">
+ <st n="214748364801" r="1670291755062" />
+ </op>
+ <op n="61">
+ <st n="214748364801" r="1670291754997" />
+ </op>
+ <op n="105">
+ <st n="214748364801" r="1670291473903" />
+ <st id="GnssService" n="214748364801" r="1670288044920" />
+ </op>
+ <op n="111">
+ <st n="214748364801" t="1670291441554" />
+ </op>
+ </uid>
+ </pkg>
+ <pkg n="com.android.server.telecom">
+ <uid n="1000">
+ <op n="6">
+ <st n="214748364801" t="1670287609092" />
+ </op>
+ <op n="111">
+ <st n="214748364801" t="1670287583728" />
+ </op>
+ </uid>
+ </pkg>
+ <pkg n="com.android.settings">
+ <uid n="1000">
+ <op n="43">
+ <st n="214748364801" r="1670291447349" />
+ </op>
+ <op n="105">
+ <st n="214748364801" r="1670291399231" />
+ </op>
+ <op n="111">
+ <st n="214748364801" t="1670291756910" />
+ </op>
+ </uid>
+ </pkg>
+ <pkg n="com.android.phone">
+ <uid n="1001">
+ <op n="15">
+ <st n="214748364801" t="1670287951022" />
+ </op>
+ <op n="40">
+ <st n="214748364801" t="1670291786177" />
+ </op>
+ <op n="105">
+ <st n="214748364801" r="1670291756403" />
+ </op>
+ </uid>
+ </pkg>
+ <pkg n="com.android.bluetooth">
+ <uid n="1002">
+ <op n="4">
+ <st n="214748364801" t="1670289671076" />
+ </op>
+ <op n="40">
+ <st n="214748364801" t="1670287585676" d="8" />
+ </op>
+ <op n="43">
+ <st n="214748364801" r="1670287585818" />
+ </op>
+ <op n="77">
+ <st n="214748364801" t="1670288037629" />
+ </op>
+ <op n="111">
+ <st n="214748364801" t="1670287592081" />
+ </op>
+ </uid>
+ </pkg>
+ <pkg n="com.android.vending">
+ <uid n="10136">
+ <op n="40">
+ <st n="429496729601" t="1670289621210" d="114" />
+ <st n="858993459201" t="1670289879730" d="349" />
+ <st n="1288490188801" t="1670287942622" d="937" />
+ </op>
+ <op n="43">
+ <st n="429496729601" r="1670289755305" />
+ <st n="858993459201" r="1670288019246" />
+ <st n="1073741824001" r="1670289571783" />
+ <st n="1288490188801" r="1670289373336" />
+ </op>
+ <op n="76">
+ <st n="429496729601" t="1670289748735" d="15991" />
+ <st n="858993459201" t="1670291395180" d="79201" />
+ <st n="1073741824001" t="1670291395168" d="12" />
+ <st n="1288490188801" t="1670291526029" d="3" />
+ <st n="1503238553601" t="1670291526032" d="310718" />
+ </op>
+ <op n="105">
+ <st n="429496729601" r="1670289538910" />
+ <st n="858993459201" r="1670288054519" />
+ <st n="1073741824001" r="1670287599379" />
+ <st n="1288490188801" r="1670289526854" />
+ <st n="1503238553601" r="1670289528242" />
+ </op>
+ </uid>
+ </pkg>
+ <pkg n="com.android.nfc">
+ <uid n="1027">
+ <op n="40">
+ <st n="214748364801" t="1670291786330" d="22" />
+ </op>
+ </uid>
+ </pkg>
+</app-ops>
\ No newline at end of file diff --git a/services/tests/mockingservicestests/src/com/android/server/app/GameManagerServiceTests.java b/services/tests/mockingservicestests/src/com/android/server/app/GameManagerServiceTests.java index a8d894511213..d3fa92ce68d7 100644 --- a/services/tests/mockingservicestests/src/com/android/server/app/GameManagerServiceTests.java +++ b/services/tests/mockingservicestests/src/com/android/server/app/GameManagerServiceTests.java @@ -647,15 +647,15 @@ public class GameManagerServiceTests { } } - private void checkReportedOptedInGameModes(GameManagerService gameManagerService, - int... requiredOptedInModes) { - Arrays.sort(requiredOptedInModes); - // check GetModeInfo.getOptedInGameModes + private void checkReportedOverriddenGameModes(GameManagerService gameManagerService, + int... requiredOverriddenModes) { + Arrays.sort(requiredOverriddenModes); + // check GetModeInfo.getOverriddenGameModes GameModeInfo info = gameManagerService.getGameModeInfo(mPackageName, USER_ID_1); assertNotNull(info); - int[] optedInModes = info.getOptedInGameModes(); - Arrays.sort(optedInModes); - assertArrayEquals(requiredOptedInModes, optedInModes); + int[] overriddenModes = info.getOverriddenGameModes(); + Arrays.sort(overriddenModes); + assertArrayEquals(requiredOverriddenModes, overriddenModes); } private void checkDownscaling(GameManagerService gameManagerService, @@ -697,7 +697,7 @@ public class GameManagerServiceTests { assertEquals(fps, config.getGameModeConfiguration(gameMode).getFps()); } - private boolean checkOptedIn(GameManagerService gameManagerService, int gameMode) { + private boolean checkOverridden(GameManagerService gameManagerService, int gameMode) { GameManagerService.GamePackageConfiguration config = gameManagerService.getConfig(mPackageName, USER_ID_1); return config.willGamePerformOptimizations(gameMode); @@ -870,8 +870,8 @@ public class GameManagerServiceTests { mTestLooper.getLooper()); startUser(gameManagerService, USER_ID_1); - assertFalse(checkOptedIn(gameManagerService, GameManager.GAME_MODE_PERFORMANCE)); - assertFalse(checkOptedIn(gameManagerService, GameManager.GAME_MODE_BATTERY)); + assertFalse(checkOverridden(gameManagerService, GameManager.GAME_MODE_PERFORMANCE)); + assertFalse(checkOverridden(gameManagerService, GameManager.GAME_MODE_BATTERY)); checkFps(gameManagerService, GameManager.GAME_MODE_PERFORMANCE, 0); gameManagerService.setGameModeConfigOverride(mPackageName, USER_ID_1, 3, "40", @@ -884,9 +884,9 @@ public class GameManagerServiceTests { mockInterventionsDisabledAllOptInFromXml(); gameManagerService.updateConfigsForUser(USER_ID_1, false, mPackageName); - assertTrue(checkOptedIn(gameManagerService, GameManager.GAME_MODE_PERFORMANCE)); + assertTrue(checkOverridden(gameManagerService, GameManager.GAME_MODE_PERFORMANCE)); // opt-in is still false for battery mode as override exists - assertFalse(checkOptedIn(gameManagerService, GameManager.GAME_MODE_BATTERY)); + assertFalse(checkOverridden(gameManagerService, GameManager.GAME_MODE_BATTERY)); } /** @@ -1310,7 +1310,7 @@ public class GameManagerServiceTests { checkReportedAvailableGameModes(gameManagerService, GameManager.GAME_MODE_PERFORMANCE, GameManager.GAME_MODE_BATTERY, GameManager.GAME_MODE_STANDARD, GameManager.GAME_MODE_CUSTOM); - checkReportedOptedInGameModes(gameManagerService); + checkReportedOverriddenGameModes(gameManagerService); assertEquals(new GameModeConfiguration.Builder() .setFpsOverride(30) @@ -1337,7 +1337,7 @@ public class GameManagerServiceTests { checkReportedAvailableGameModes(gameManagerService, GameManager.GAME_MODE_BATTERY, GameManager.GAME_MODE_STANDARD, GameManager.GAME_MODE_CUSTOM); - checkReportedOptedInGameModes(gameManagerService); + checkReportedOverriddenGameModes(gameManagerService); assertNotNull(gameModeInfo.getGameModeConfiguration(GameManager.GAME_MODE_BATTERY)); assertNull(gameModeInfo.getGameModeConfiguration(GameManager.GAME_MODE_PERFORMANCE)); @@ -1357,7 +1357,7 @@ public class GameManagerServiceTests { checkReportedAvailableGameModes(gameManagerService, GameManager.GAME_MODE_PERFORMANCE, GameManager.GAME_MODE_STANDARD, GameManager.GAME_MODE_CUSTOM); - checkReportedOptedInGameModes(gameManagerService); + checkReportedOverriddenGameModes(gameManagerService); assertNotNull(gameModeInfo.getGameModeConfiguration(GameManager.GAME_MODE_PERFORMANCE)); assertNull(gameModeInfo.getGameModeConfiguration(GameManager.GAME_MODE_BATTERY)); @@ -1382,7 +1382,7 @@ public class GameManagerServiceTests { } @Test - public void testGetGameModeInfoWithAllGameModesOptedIn_noDeviceConfig() + public void testGetGameModeInfoWithAllGameModesOverridden_noDeviceConfig() throws Exception { mockModifyGameModeGranted(); mockInterventionsEnabledAllOptInFromXml(); @@ -1390,14 +1390,14 @@ public class GameManagerServiceTests { GameManagerService gameManagerService = createServiceAndStartUser(USER_ID_1); GameModeInfo gameModeInfo = gameManagerService.getGameModeInfo(mPackageName, USER_ID_1); assertEquals(GameManager.GAME_MODE_STANDARD, gameModeInfo.getActiveGameMode()); - verifyAllModesOptedInAndInterventionsAvailable(gameManagerService, gameModeInfo); + verifyAllModesOverriddenAndInterventionsAvailable(gameManagerService, gameModeInfo); assertNull(gameModeInfo.getGameModeConfiguration(GameManager.GAME_MODE_BATTERY)); assertNull(gameModeInfo.getGameModeConfiguration(GameManager.GAME_MODE_PERFORMANCE)); } @Test - public void testGetGameModeInfoWithAllGameModesOptedIn_allDeviceConfig() + public void testGetGameModeInfoWithAllGameModesOverridden_allDeviceConfig() throws Exception { mockModifyGameModeGranted(); mockInterventionsEnabledAllOptInFromXml(); @@ -1405,26 +1405,26 @@ public class GameManagerServiceTests { GameManagerService gameManagerService = createServiceAndStartUser(USER_ID_1); GameModeInfo gameModeInfo = gameManagerService.getGameModeInfo(mPackageName, USER_ID_1); assertEquals(GameManager.GAME_MODE_STANDARD, gameModeInfo.getActiveGameMode()); - verifyAllModesOptedInAndInterventionsAvailable(gameManagerService, gameModeInfo); + verifyAllModesOverriddenAndInterventionsAvailable(gameManagerService, gameModeInfo); assertNull(gameModeInfo.getGameModeConfiguration(GameManager.GAME_MODE_BATTERY)); assertNull(gameModeInfo.getGameModeConfiguration(GameManager.GAME_MODE_PERFORMANCE)); } - private void verifyAllModesOptedInAndInterventionsAvailable( + private void verifyAllModesOverriddenAndInterventionsAvailable( GameManagerService gameManagerService, GameModeInfo gameModeInfo) { checkReportedAvailableGameModes(gameManagerService, GameManager.GAME_MODE_PERFORMANCE, GameManager.GAME_MODE_BATTERY, GameManager.GAME_MODE_STANDARD, GameManager.GAME_MODE_CUSTOM); - checkReportedOptedInGameModes(gameManagerService, + checkReportedOverriddenGameModes(gameManagerService, GameManager.GAME_MODE_PERFORMANCE, GameManager.GAME_MODE_BATTERY); assertTrue(gameModeInfo.isFpsOverrideAllowed()); assertTrue(gameModeInfo.isDownscalingAllowed()); } @Test - public void testGetGameModeInfoWithBatteryModeOptedIn_withBatteryDeviceConfig() + public void testGetGameModeInfoWithBatteryModeOverridden_withBatteryDeviceConfig() throws Exception { mockModifyGameModeGranted(); mockInterventionsEnabledBatteryOptInFromXml(); @@ -1435,14 +1435,14 @@ public class GameManagerServiceTests { checkReportedAvailableGameModes(gameManagerService, GameManager.GAME_MODE_BATTERY, GameManager.GAME_MODE_STANDARD, GameManager.GAME_MODE_CUSTOM); - checkReportedOptedInGameModes(gameManagerService, GameManager.GAME_MODE_BATTERY); + checkReportedOverriddenGameModes(gameManagerService, GameManager.GAME_MODE_BATTERY); assertNull(gameModeInfo.getGameModeConfiguration(GameManager.GAME_MODE_BATTERY)); assertNull(gameModeInfo.getGameModeConfiguration(GameManager.GAME_MODE_PERFORMANCE)); } @Test - public void testGetGameModeInfoWithPerformanceModeOptedIn_withAllDeviceConfig() + public void testGetGameModeInfoWithPerformanceModeOverridden_withAllDeviceConfig() throws Exception { mockModifyGameModeGranted(); mockInterventionsEnabledPerformanceOptInFromXml(); @@ -1454,7 +1454,7 @@ public class GameManagerServiceTests { checkReportedAvailableGameModes(gameManagerService, GameManager.GAME_MODE_PERFORMANCE, GameManager.GAME_MODE_BATTERY, GameManager.GAME_MODE_STANDARD, GameManager.GAME_MODE_CUSTOM); - checkReportedOptedInGameModes(gameManagerService, GameManager.GAME_MODE_PERFORMANCE); + checkReportedOverriddenGameModes(gameManagerService, GameManager.GAME_MODE_PERFORMANCE); assertNotNull(gameModeInfo.getGameModeConfiguration(GameManager.GAME_MODE_BATTERY)); assertNull(gameModeInfo.getGameModeConfiguration(GameManager.GAME_MODE_PERFORMANCE)); @@ -1993,7 +1993,7 @@ public class GameManagerServiceTests { } @Test - public void testResetInterventions_onGameModeOptedIn() throws Exception { + public void testResetInterventions_onGameModeOverridden() throws Exception { mockModifyGameModeGranted(); String configStringBefore = "mode=2,downscaleFactor=1.0,fps=90"; diff --git a/services/tests/mockingservicestests/src/com/android/server/appop/AppOpsUpgradeTest.java b/services/tests/mockingservicestests/src/com/android/server/appop/AppOpsUpgradeTest.java index 298dbf47d86d..302fa0f0c528 100644 --- a/services/tests/mockingservicestests/src/com/android/server/appop/AppOpsUpgradeTest.java +++ b/services/tests/mockingservicestests/src/com/android/server/appop/AppOpsUpgradeTest.java @@ -16,23 +16,32 @@ package com.android.server.appop; +import static android.app.AppOpsManager.OP_SCHEDULE_EXACT_ALARM; + +import static com.android.dx.mockito.inline.extended.ExtendedMockito.doAnswer; +import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn; +import static com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession; +import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify; + import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; import android.app.AppOpsManager; import android.content.Context; import android.content.pm.PackageManager; +import android.content.pm.PackageManagerInternal; import android.content.res.AssetManager; import android.os.Handler; -import android.os.HandlerThread; +import android.os.UserHandle; import android.util.Log; import android.util.SparseArray; import android.util.SparseIntArray; @@ -42,11 +51,20 @@ import androidx.test.InstrumentationRegistry; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; +import com.android.internal.util.ArrayUtils; import com.android.modules.utils.TypedXmlPullParser; +import com.android.server.LocalServices; +import com.android.server.SystemServerInitThreadPool; +import com.android.server.pm.UserManagerInternal; +import com.android.server.pm.permission.PermissionManagerServiceInternal; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoSession; +import org.mockito.quality.Strictness; import org.xmlpull.v1.XmlPullParser; import java.io.File; @@ -64,29 +82,39 @@ public class AppOpsUpgradeTest { private static final String TAG = AppOpsUpgradeTest.class.getSimpleName(); private static final String APP_OPS_UNVERSIONED_ASSET_PATH = "AppOpsUpgradeTest/appops-unversioned.xml"; + private static final String APP_OPS_VERSION_1_ASSET_PATH = + "AppOpsUpgradeTest/appops-version-1.xml"; private static final String APP_OPS_FILENAME = "appops-test.xml"; private static final int NON_DEFAULT_OPS_IN_FILE = 4; - private static final int CURRENT_VERSION = 1; - private File mAppOpsFile; - private Context mContext; + private static final Context sContext = InstrumentationRegistry.getTargetContext(); + private static final File sAppOpsFile = new File(sContext.getFilesDir(), APP_OPS_FILENAME); + + private Context mTestContext; + private MockitoSession mMockitoSession; + + @Mock + private PackageManagerInternal mPackageManagerInternal; + @Mock + private PackageManager mPackageManager; + @Mock + private UserManagerInternal mUserManagerInternal; + @Mock + private PermissionManagerServiceInternal mPermissionManagerInternal; + @Mock private Handler mHandler; - private void extractAppOpsFile() { - mAppOpsFile.getParentFile().mkdirs(); - if (mAppOpsFile.exists()) { - mAppOpsFile.delete(); - } - try (FileOutputStream out = new FileOutputStream(mAppOpsFile); - InputStream in = mContext.getAssets().open(APP_OPS_UNVERSIONED_ASSET_PATH, - AssetManager.ACCESS_BUFFER)) { + private static void extractAppOpsFile(String assetPath) { + sAppOpsFile.getParentFile().mkdirs(); + try (FileOutputStream out = new FileOutputStream(sAppOpsFile); + InputStream in = sContext.getAssets().open(assetPath, AssetManager.ACCESS_BUFFER)) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = in.read(buffer)) >= 0) { out.write(buffer, 0, bytesRead); } out.flush(); - Log.d(TAG, "Successfully copied xml to " + mAppOpsFile.getAbsolutePath()); + Log.d(TAG, "Successfully copied xml to " + sAppOpsFile.getAbsolutePath()); } catch (IOException exc) { Log.e(TAG, "Exception while copying appops xml", exc); fail(); @@ -98,7 +126,7 @@ public class AppOpsUpgradeTest { int numberOfNonDefaultOps = 0; final int defaultModeOp1 = AppOpsManager.opToDefaultMode(op1); final int defaultModeOp2 = AppOpsManager.opToDefaultMode(op2); - for(int i = 0; i < uidStates.size(); i++) { + for (int i = 0; i < uidStates.size(); i++) { final AppOpsServiceImpl.UidState uidState = uidStates.valueAt(i); SparseIntArray opModes = uidState.getNonDefaultUidModes(); if (opModes != null) { @@ -132,41 +160,191 @@ public class AppOpsUpgradeTest { @Before public void setUp() { - mContext = InstrumentationRegistry.getTargetContext(); - mAppOpsFile = new File(mContext.getFilesDir(), APP_OPS_FILENAME); - extractAppOpsFile(); - HandlerThread handlerThread = new HandlerThread(TAG); - handlerThread.start(); - mHandler = new Handler(handlerThread.getLooper()); + if (sAppOpsFile.exists()) { + sAppOpsFile.delete(); + } + + mMockitoSession = mockitoSession() + .initMocks(this) + .spyStatic(LocalServices.class) + .mockStatic(SystemServerInitThreadPool.class) + .strictness(Strictness.LENIENT) + .startMocking(); + + doReturn(mPermissionManagerInternal).when( + () -> LocalServices.getService(PermissionManagerServiceInternal.class)); + doReturn(mUserManagerInternal).when( + () -> LocalServices.getService(UserManagerInternal.class)); + doReturn(mPackageManagerInternal).when( + () -> LocalServices.getService(PackageManagerInternal.class)); + + mTestContext = spy(sContext); + + // Pretend everybody has all permissions + doNothing().when(mTestContext).enforcePermission(anyString(), anyInt(), anyInt(), + nullable(String.class)); + + doReturn(mPackageManager).when(mTestContext).getPackageManager(); + + // Stub out package calls to disable AppOpsService#updatePermissionRevokedCompat + doReturn(null).when(mPackageManager).getPackagesForUid(anyInt()); + } + + @After + public void tearDown() { + mMockitoSession.finishMocking(); } @Test - public void testUpgradeFromNoVersion() throws Exception { - AppOpsDataParser parser = new AppOpsDataParser(mAppOpsFile); + public void upgradeRunAnyInBackground() { + extractAppOpsFile(APP_OPS_UNVERSIONED_ASSET_PATH); + + AppOpsServiceImpl testService = new AppOpsServiceImpl(sAppOpsFile, mHandler, mTestContext); + + testService.upgradeRunAnyInBackgroundLocked(); + assertSameModes(testService.mUidStates, AppOpsManager.OP_RUN_IN_BACKGROUND, + AppOpsManager.OP_RUN_ANY_IN_BACKGROUND); + } + + private static int getModeInFile(int uid) { + switch (uid) { + case 10198: + return 0; + case 10200: + return 1; + case 1110200: + case 10267: + case 1110181: + return 2; + default: + return AppOpsManager.opToDefaultMode(OP_SCHEDULE_EXACT_ALARM); + } + } + + @Test + public void upgradeScheduleExactAlarm() { + extractAppOpsFile(APP_OPS_VERSION_1_ASSET_PATH); + + String[] packageNames = {"p1", "package2", "pkg3", "package.4", "pkg-5", "pkg.6"}; + int[] appIds = {10267, 10181, 10198, 10199, 10200, 4213}; + int[] userIds = {0, 10, 11}; + + doReturn(userIds).when(mUserManagerInternal).getUserIds(); + + doReturn(packageNames).when(mPermissionManagerInternal).getAppOpPermissionPackages( + AppOpsManager.opToPermission(OP_SCHEDULE_EXACT_ALARM)); + + doAnswer(invocation -> { + String pkg = invocation.getArgument(0); + int index = ArrayUtils.indexOf(packageNames, pkg); + if (index < 0) { + return index; + } + int userId = invocation.getArgument(2); + return UserHandle.getUid(userId, appIds[index]); + }).when(mPackageManagerInternal).getPackageUid(anyString(), anyLong(), anyInt()); + + AppOpsServiceImpl testService = new AppOpsServiceImpl(sAppOpsFile, mHandler, mTestContext); + + testService.upgradeScheduleExactAlarmLocked(); + + for (int userId : userIds) { + for (int appId : appIds) { + final int uid = UserHandle.getUid(userId, appId); + final int previousMode = getModeInFile(uid); + + final int expectedMode; + if (previousMode == AppOpsManager.opToDefaultMode(OP_SCHEDULE_EXACT_ALARM)) { + expectedMode = AppOpsManager.MODE_ALLOWED; + } else { + expectedMode = previousMode; + } + final AppOpsServiceImpl.UidState uidState = testService.mUidStates.get(uid); + assertEquals(expectedMode, uidState.getUidMode(OP_SCHEDULE_EXACT_ALARM)); + } + } + + // These uids don't even declare the permission. So should stay as default / empty. + int[] unrelatedUidsInFile = {10225, 10178}; + + for (int uid : unrelatedUidsInFile) { + final AppOpsServiceImpl.UidState uidState = testService.mUidStates.get(uid); + assertEquals(AppOpsManager.opToDefaultMode(OP_SCHEDULE_EXACT_ALARM), + uidState.getUidMode(OP_SCHEDULE_EXACT_ALARM)); + } + } + + @Test + public void upgradeFromNoFile() { + assertFalse(sAppOpsFile.exists()); + + AppOpsServiceImpl testService = spy( + new AppOpsServiceImpl(sAppOpsFile, mHandler, mTestContext)); + + doNothing().when(testService).upgradeRunAnyInBackgroundLocked(); + doNothing().when(testService).upgradeScheduleExactAlarmLocked(); + + // trigger upgrade + testService.systemReady(); + + verify(testService, never()).upgradeRunAnyInBackgroundLocked(); + verify(testService, never()).upgradeScheduleExactAlarmLocked(); + + testService.writeState(); + + assertTrue(sAppOpsFile.exists()); + + AppOpsDataParser parser = new AppOpsDataParser(sAppOpsFile); + assertTrue(parser.parse()); + assertEquals(AppOpsServiceImpl.CURRENT_VERSION, parser.mVersion); + } + + @Test + public void upgradeFromNoVersion() { + extractAppOpsFile(APP_OPS_UNVERSIONED_ASSET_PATH); + AppOpsDataParser parser = new AppOpsDataParser(sAppOpsFile); assertTrue(parser.parse()); assertEquals(AppOpsDataParser.NO_VERSION, parser.mVersion); - // Use mock context and package manager to fake permision package manager calls. - Context testContext = spy(mContext); + AppOpsServiceImpl testService = spy( + new AppOpsServiceImpl(sAppOpsFile, mHandler, mTestContext)); - // Pretent everybody has all permissions - doNothing().when(testContext).enforcePermission(anyString(), anyInt(), anyInt(), - nullable(String.class)); + doNothing().when(testService).upgradeRunAnyInBackgroundLocked(); + doNothing().when(testService).upgradeScheduleExactAlarmLocked(); - PackageManager testPM = mock(PackageManager.class); - when(testContext.getPackageManager()).thenReturn(testPM); + // trigger upgrade + testService.systemReady(); - // Stub out package calls to disable AppOpsService#updatePermissionRevokedCompat - when(testPM.getPackagesForUid(anyInt())).thenReturn(null); + verify(testService).upgradeRunAnyInBackgroundLocked(); + verify(testService).upgradeScheduleExactAlarmLocked(); + + testService.writeState(); + assertTrue(parser.parse()); + assertEquals(AppOpsServiceImpl.CURRENT_VERSION, parser.mVersion); + } + + @Test + public void upgradeFromVersion1() { + extractAppOpsFile(APP_OPS_VERSION_1_ASSET_PATH); + AppOpsDataParser parser = new AppOpsDataParser(sAppOpsFile); + assertTrue(parser.parse()); + assertEquals(1, parser.mVersion); AppOpsServiceImpl testService = spy( - new AppOpsServiceImpl(mAppOpsFile, mHandler, testContext)); // trigger upgrade - assertSameModes(testService.mUidStates, AppOpsManager.OP_RUN_IN_BACKGROUND, - AppOpsManager.OP_RUN_ANY_IN_BACKGROUND); - mHandler.removeCallbacks(testService.mWriteRunner); + new AppOpsServiceImpl(sAppOpsFile, mHandler, mTestContext)); + + doNothing().when(testService).upgradeRunAnyInBackgroundLocked(); + doNothing().when(testService).upgradeScheduleExactAlarmLocked(); + + // trigger upgrade + testService.systemReady(); + + verify(testService, never()).upgradeRunAnyInBackgroundLocked(); + verify(testService).upgradeScheduleExactAlarmLocked(); + testService.writeState(); assertTrue(parser.parse()); - assertEquals(CURRENT_VERSION, parser.mVersion); + assertEquals(AppOpsServiceImpl.CURRENT_VERSION, parser.mVersion); } /** @@ -174,7 +352,7 @@ public class AppOpsUpgradeTest { * Other fields may be added as and when required for testing. */ private static final class AppOpsDataParser { - static final int NO_VERSION = -1; + static final int NO_VERSION = -123; int mVersion; private File mFile; diff --git a/services/tests/mockingservicestests/src/com/android/server/display/LocalDisplayAdapterTest.java b/services/tests/mockingservicestests/src/com/android/server/display/LocalDisplayAdapterTest.java index f10597114a5e..5e5cbdc22a23 100644 --- a/services/tests/mockingservicestests/src/com/android/server/display/LocalDisplayAdapterTest.java +++ b/services/tests/mockingservicestests/src/com/android/server/display/LocalDisplayAdapterTest.java @@ -1046,9 +1046,9 @@ public class LocalDisplayAdapterTest { mAddresses.add(display.address); when(mSurfaceControlProxy.getPhysicalDisplayToken(display.address.getPhysicalDisplayId())) .thenReturn(display.token); - when(mSurfaceControlProxy.getStaticDisplayInfo(display.token)) + when(mSurfaceControlProxy.getStaticDisplayInfo(display.address.getPhysicalDisplayId())) .thenReturn(display.info); - when(mSurfaceControlProxy.getDynamicDisplayInfo(display.token)) + when(mSurfaceControlProxy.getDynamicDisplayInfo(display.address.getPhysicalDisplayId())) .thenReturn(display.dynamicInfo); when(mSurfaceControlProxy.getDesiredDisplayModeSpecs(display.token)) .thenReturn(display.desiredDisplayModeSpecs); diff --git a/services/tests/mockingservicestests/src/com/android/server/job/JobConcurrencyManagerTest.java b/services/tests/mockingservicestests/src/com/android/server/job/JobConcurrencyManagerTest.java index 6e4d21456cd0..a9dc4af07bab 100644 --- a/services/tests/mockingservicestests/src/com/android/server/job/JobConcurrencyManagerTest.java +++ b/services/tests/mockingservicestests/src/com/android/server/job/JobConcurrencyManagerTest.java @@ -113,7 +113,8 @@ public final class JobConcurrencyManagerTest { @Override JobServiceContext createJobServiceContext(JobSchedulerService service, - JobConcurrencyManager concurrencyManager, IBatteryStats batteryStats, + JobConcurrencyManager concurrencyManager, + JobNotificationCoordinator notificationCoordinator, IBatteryStats batteryStats, JobPackageTracker tracker, Looper looper) { final JobServiceContext context = mock(JobServiceContext.class); doAnswer((Answer<Boolean>) invocationOnMock -> { diff --git a/services/tests/mockingservicestests/src/com/android/server/job/JobNotificationCoordinatorTest.java b/services/tests/mockingservicestests/src/com/android/server/job/JobNotificationCoordinatorTest.java new file mode 100644 index 000000000000..b4104dbc89f9 --- /dev/null +++ b/services/tests/mockingservicestests/src/com/android/server/job/JobNotificationCoordinatorTest.java @@ -0,0 +1,440 @@ +/* + * 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.job; + + +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.inOrder; +import static com.android.dx.mockito.inline.extended.ExtendedMockito.mock; +import static com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession; + +import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +import android.app.Notification; +import android.app.NotificationChannel; +import android.app.job.JobService; +import android.graphics.drawable.Icon; +import android.os.UserHandle; + +import com.android.server.LocalServices; +import com.android.server.notification.NotificationManagerInternal; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mock; +import org.mockito.MockitoSession; +import org.mockito.quality.Strictness; + +public class JobNotificationCoordinatorTest { + private static final String TEST_PACKAGE = "com.android.test"; + private static final String NOTIFICATION_CHANNEL_ID = "validNotificationChannelId"; + + private MockitoSession mMockingSession; + + @Mock + private NotificationManagerInternal mNotificationManagerInternal; + + @Before + public void setUp() { + mMockingSession = mockitoSession() + .initMocks(this) + .mockStatic(LocalServices.class) + .strictness(Strictness.LENIENT) + .startMocking(); + doReturn(mNotificationManagerInternal) + .when(() -> LocalServices.getService(NotificationManagerInternal.class)); + doNothing().when(mNotificationManagerInternal) + .enqueueNotification(anyString(), anyString(), anyInt(), anyInt(), any(), + anyInt(), any(), anyInt()); + doNothing().when(mNotificationManagerInternal) + .enqueueNotification(anyString(), anyString(), anyInt(), anyInt(), any(), + anyInt(), any(), anyInt()); + doReturn(mock(NotificationChannel.class)).when(mNotificationManagerInternal) + .getNotificationChannel(anyString(), anyInt(), eq(NOTIFICATION_CHANNEL_ID)); + } + + @After + public void tearDown() throws Exception { + if (mMockingSession != null) { + mMockingSession.finishMocking(); + } + } + + @Test + public void testParameterValidation() { + final JobNotificationCoordinator coordinator = new JobNotificationCoordinator(); + final JobServiceContext jsc = mock(JobServiceContext.class); + final int uid = 10123; + final int pid = 42; + final int notificationId = 23; + + try { + coordinator.enqueueNotification(jsc, TEST_PACKAGE, pid, uid, notificationId, null, + JobService.JOB_END_NOTIFICATION_POLICY_DETACH); + fail("Successfully enqueued a null notification"); + } catch (NullPointerException e) { + // Success + } + + Notification notification = createValidNotification(); + doReturn(null).when(notification).getSmallIcon(); + try { + coordinator.enqueueNotification(jsc, TEST_PACKAGE, pid, uid, notificationId, + notification, JobService.JOB_END_NOTIFICATION_POLICY_DETACH); + fail("Successfully enqueued a notification with no small icon"); + } catch (IllegalArgumentException e) { + // Success + } + + notification = createValidNotification(); + doReturn(null).when(notification).getChannelId(); + try { + coordinator.enqueueNotification(jsc, TEST_PACKAGE, pid, uid, notificationId, + notification, JobService.JOB_END_NOTIFICATION_POLICY_DETACH); + fail("Successfully enqueued a notification with no valid channel"); + } catch (IllegalArgumentException e) { + // Success + } + + notification = createValidNotification(); + try { + coordinator.enqueueNotification(jsc, TEST_PACKAGE, pid, uid, notificationId, + notification, Integer.MAX_VALUE); + fail("Successfully enqueued a notification with an invalid job end notification " + + "policy"); + } catch (IllegalArgumentException e) { + // Success + } + } + + @Test + public void testSingleJob_DetachOnStop() { + final JobNotificationCoordinator coordinator = new JobNotificationCoordinator(); + final JobServiceContext jsc = mock(JobServiceContext.class); + final Notification notification = createValidNotification(); + final int uid = 10123; + final int pid = 42; + final int notificationId = 23; + + coordinator.enqueueNotification(jsc, TEST_PACKAGE, pid, uid, notificationId, notification, + JobService.JOB_END_NOTIFICATION_POLICY_DETACH); + verify(mNotificationManagerInternal) + .enqueueNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid), eq(pid), any(), + eq(notificationId), eq(notification), eq(UserHandle.getUserId(uid))); + + coordinator.removeNotificationAssociation(jsc); + verify(mNotificationManagerInternal, never()) + .cancelNotification(anyString(), anyString(), anyInt(), anyInt(), any(), + anyInt(), anyInt()); + } + + @Test + public void testSingleJob_RemoveOnStop() { + final JobNotificationCoordinator coordinator = new JobNotificationCoordinator(); + final JobServiceContext jsc = mock(JobServiceContext.class); + final Notification notification = createValidNotification(); + final int uid = 10123; + final int pid = 42; + final int notificationId = 23; + + coordinator.enqueueNotification(jsc, TEST_PACKAGE, pid, uid, notificationId, notification, + JobService.JOB_END_NOTIFICATION_POLICY_REMOVE); + verify(mNotificationManagerInternal) + .enqueueNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid), eq(pid), any(), + eq(notificationId), eq(notification), eq(UserHandle.getUserId(uid))); + + coordinator.removeNotificationAssociation(jsc); + verify(mNotificationManagerInternal) + .cancelNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid), eq(pid), any(), + eq(notificationId), eq(UserHandle.getUserId(uid))); + } + + @Test + public void testSingleJob_EnqueueDifferentNotificationId_DetachOnStop() { + final JobNotificationCoordinator coordinator = new JobNotificationCoordinator(); + final JobServiceContext jsc = mock(JobServiceContext.class); + final Notification notification1 = createValidNotification(); + final Notification notification2 = createValidNotification(); + final int uid = 10123; + final int pid = 42; + final int notificationId1 = 23; + final int notificationId2 = 46; + + InOrder inOrder = inOrder(mNotificationManagerInternal); + + coordinator.enqueueNotification(jsc, TEST_PACKAGE, pid, uid, notificationId1, notification1, + JobService.JOB_END_NOTIFICATION_POLICY_DETACH); + inOrder.verify(mNotificationManagerInternal) + .enqueueNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid), eq(pid), any(), + eq(notificationId1), eq(notification1), eq(UserHandle.getUserId(uid))); + + coordinator.enqueueNotification(jsc, TEST_PACKAGE, pid, uid, notificationId2, notification2, + JobService.JOB_END_NOTIFICATION_POLICY_DETACH); + inOrder.verify(mNotificationManagerInternal, never()) + .cancelNotification(anyString(), anyString(), anyInt(), anyInt(), any(), + anyInt(), anyInt()); + inOrder.verify(mNotificationManagerInternal) + .enqueueNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid), eq(pid), any(), + eq(notificationId2), eq(notification2), eq(UserHandle.getUserId(uid))); + } + + @Test + public void testSingleJob_EnqueueDifferentNotificationId_RemoveOnStop() { + final JobNotificationCoordinator coordinator = new JobNotificationCoordinator(); + final JobServiceContext jsc = mock(JobServiceContext.class); + final Notification notification1 = createValidNotification(); + final Notification notification2 = createValidNotification(); + final int uid = 10123; + final int pid = 42; + final int notificationId1 = 23; + final int notificationId2 = 46; + + InOrder inOrder = inOrder(mNotificationManagerInternal); + + coordinator.enqueueNotification(jsc, TEST_PACKAGE, pid, uid, notificationId1, notification1, + JobService.JOB_END_NOTIFICATION_POLICY_REMOVE); + inOrder.verify(mNotificationManagerInternal) + .enqueueNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid), eq(pid), any(), + eq(notificationId1), eq(notification1), eq(UserHandle.getUserId(uid))); + + coordinator.enqueueNotification(jsc, TEST_PACKAGE, pid, uid, notificationId2, notification2, + JobService.JOB_END_NOTIFICATION_POLICY_REMOVE); + inOrder.verify(mNotificationManagerInternal) + .cancelNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid), eq(pid), any(), + eq(notificationId1), eq(UserHandle.getUserId(uid))); + inOrder.verify(mNotificationManagerInternal) + .enqueueNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid), eq(pid), any(), + eq(notificationId2), eq(notification2), eq(UserHandle.getUserId(uid))); + } + + @Test + public void testSingleJob_EnqueueSameNotificationId() { + final JobNotificationCoordinator coordinator = new JobNotificationCoordinator(); + final JobServiceContext jsc = mock(JobServiceContext.class); + final Notification notification1 = createValidNotification(); + final Notification notification2 = createValidNotification(); + final int uid = 10123; + final int pid = 42; + final int notificationId = 23; + + InOrder inOrder = inOrder(mNotificationManagerInternal); + + coordinator.enqueueNotification(jsc, TEST_PACKAGE, pid, uid, notificationId, notification1, + JobService.JOB_END_NOTIFICATION_POLICY_DETACH); + inOrder.verify(mNotificationManagerInternal) + .enqueueNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid), eq(pid), any(), + eq(notificationId), eq(notification1), eq(UserHandle.getUserId(uid))); + + coordinator.enqueueNotification(jsc, TEST_PACKAGE, pid, uid, notificationId, notification2, + JobService.JOB_END_NOTIFICATION_POLICY_DETACH); + inOrder.verify(mNotificationManagerInternal, never()) + .cancelNotification(anyString(), anyString(), anyInt(), anyInt(), any(), + anyInt(), anyInt()); + inOrder.verify(mNotificationManagerInternal) + .enqueueNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid), eq(pid), any(), + eq(notificationId), eq(notification2), eq(UserHandle.getUserId(uid))); + } + + @Test + public void testMultipleJobs_sameApp_EnqueueDifferentNotificationId() { + final JobNotificationCoordinator coordinator = new JobNotificationCoordinator(); + final JobServiceContext jsc1 = mock(JobServiceContext.class); + final JobServiceContext jsc2 = mock(JobServiceContext.class); + final Notification notification1 = createValidNotification(); + final Notification notification2 = createValidNotification(); + final int uid = 10123; + final int pid = 42; + final int notificationId1 = 23; + final int notificationId2 = 46; + + InOrder inOrder = inOrder(mNotificationManagerInternal); + + coordinator.enqueueNotification(jsc1, TEST_PACKAGE, pid, uid, notificationId1, + notification1, JobService.JOB_END_NOTIFICATION_POLICY_REMOVE); + inOrder.verify(mNotificationManagerInternal) + .enqueueNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid), eq(pid), any(), + eq(notificationId1), eq(notification1), eq(UserHandle.getUserId(uid))); + + coordinator.enqueueNotification(jsc2, TEST_PACKAGE, pid, uid, notificationId2, + notification2, JobService.JOB_END_NOTIFICATION_POLICY_REMOVE); + inOrder.verify(mNotificationManagerInternal, never()) + .cancelNotification(anyString(), anyString(), anyInt(), anyInt(), any(), + anyInt(), anyInt()); + inOrder.verify(mNotificationManagerInternal) + .enqueueNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid), eq(pid), any(), + eq(notificationId2), eq(notification2), eq(UserHandle.getUserId(uid))); + + // Remove the first job. Only the first notification should be removed. + coordinator.removeNotificationAssociation(jsc1); + inOrder.verify(mNotificationManagerInternal) + .cancelNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid), eq(pid), any(), + eq(notificationId1), eq(UserHandle.getUserId(uid))); + inOrder.verify(mNotificationManagerInternal, never()) + .cancelNotification(anyString(), anyString(), anyInt(), anyInt(), any(), + eq(notificationId2), anyInt()); + + coordinator.removeNotificationAssociation(jsc2); + inOrder.verify(mNotificationManagerInternal) + .cancelNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid), eq(pid), any(), + eq(notificationId2), eq(UserHandle.getUserId(uid))); + } + + @Test + public void testMultipleJobs_sameApp_EnqueueSameNotificationId() { + final JobNotificationCoordinator coordinator = new JobNotificationCoordinator(); + final JobServiceContext jsc1 = mock(JobServiceContext.class); + final JobServiceContext jsc2 = mock(JobServiceContext.class); + final Notification notification1 = createValidNotification(); + final Notification notification2 = createValidNotification(); + final int uid = 10123; + final int pid = 42; + final int notificationId = 23; + + InOrder inOrder = inOrder(mNotificationManagerInternal); + + coordinator.enqueueNotification(jsc1, TEST_PACKAGE, pid, uid, notificationId, notification1, + JobService.JOB_END_NOTIFICATION_POLICY_DETACH); + inOrder.verify(mNotificationManagerInternal) + .enqueueNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid), eq(pid), any(), + eq(notificationId), eq(notification1), eq(UserHandle.getUserId(uid))); + + coordinator.enqueueNotification(jsc2, TEST_PACKAGE, pid, uid, notificationId, notification2, + JobService.JOB_END_NOTIFICATION_POLICY_REMOVE); + inOrder.verify(mNotificationManagerInternal, never()) + .cancelNotification(anyString(), anyString(), anyInt(), anyInt(), any(), + anyInt(), anyInt()); + inOrder.verify(mNotificationManagerInternal) + .enqueueNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid), eq(pid), any(), + eq(notificationId), eq(notification2), eq(UserHandle.getUserId(uid))); + + // Remove the first job. The notification shouldn't be touched because of the 2nd job. + coordinator.removeNotificationAssociation(jsc1); + inOrder.verify(mNotificationManagerInternal, never()) + .cancelNotification(anyString(), anyString(), anyInt(), anyInt(), any(), + anyInt(), anyInt()); + + coordinator.removeNotificationAssociation(jsc2); + inOrder.verify(mNotificationManagerInternal) + .cancelNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid), eq(pid), any(), + eq(notificationId), eq(UserHandle.getUserId(uid))); + } + + @Test + public void testMultipleJobs_sameApp_DifferentUsers() { + final JobNotificationCoordinator coordinator = new JobNotificationCoordinator(); + final JobServiceContext jsc1 = mock(JobServiceContext.class); + final JobServiceContext jsc2 = mock(JobServiceContext.class); + final Notification notification1 = createValidNotification(); + final Notification notification2 = createValidNotification(); + final int uid1 = 10123; + final int uid2 = 1010123; + final int pid = 42; + final int notificationId = 23; + + InOrder inOrder = inOrder(mNotificationManagerInternal); + + coordinator.enqueueNotification(jsc1, TEST_PACKAGE, pid, uid1, notificationId, + notification1, JobService.JOB_END_NOTIFICATION_POLICY_REMOVE); + inOrder.verify(mNotificationManagerInternal) + .enqueueNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid1), eq(pid), any(), + eq(notificationId), eq(notification1), eq(UserHandle.getUserId(uid1))); + + coordinator.enqueueNotification(jsc2, TEST_PACKAGE, pid, uid2, notificationId, + notification2, JobService.JOB_END_NOTIFICATION_POLICY_REMOVE); + inOrder.verify(mNotificationManagerInternal, never()) + .cancelNotification(anyString(), anyString(), anyInt(), anyInt(), any(), + anyInt(), anyInt()); + inOrder.verify(mNotificationManagerInternal) + .enqueueNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid2), eq(pid), any(), + eq(notificationId), eq(notification2), eq(UserHandle.getUserId(uid2))); + + // Remove the first job. Only the first notification should be removed. + coordinator.removeNotificationAssociation(jsc1); + inOrder.verify(mNotificationManagerInternal) + .cancelNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid1), eq(pid), any(), + eq(notificationId), eq(UserHandle.getUserId(uid1))); + inOrder.verify(mNotificationManagerInternal, never()) + .cancelNotification(anyString(), anyString(), eq(uid2), anyInt(), any(), + anyInt(), anyInt()); + + coordinator.removeNotificationAssociation(jsc2); + inOrder.verify(mNotificationManagerInternal) + .cancelNotification(eq(TEST_PACKAGE), eq(TEST_PACKAGE), eq(uid2), eq(pid), any(), + eq(notificationId), eq(UserHandle.getUserId(uid2))); + } + + @Test + public void testMultipleJobs_differentApps() { + final JobNotificationCoordinator coordinator = new JobNotificationCoordinator(); + final String pkg1 = "pkg1"; + final String pkg2 = "pkg2"; + final JobServiceContext jsc1 = mock(JobServiceContext.class); + final JobServiceContext jsc2 = mock(JobServiceContext.class); + final Notification notification1 = createValidNotification(); + final Notification notification2 = createValidNotification(); + final int uid = 10123; + final int pid = 42; + final int notificationId = 23; + + InOrder inOrder = inOrder(mNotificationManagerInternal); + + coordinator.enqueueNotification(jsc1, pkg1, pid, uid, notificationId, notification1, + JobService.JOB_END_NOTIFICATION_POLICY_REMOVE); + inOrder.verify(mNotificationManagerInternal) + .enqueueNotification(eq(pkg1), eq(pkg1), eq(uid), eq(pid), any(), + eq(notificationId), eq(notification1), eq(UserHandle.getUserId(uid))); + + coordinator.enqueueNotification(jsc2, pkg2, pid, uid, notificationId, notification2, + JobService.JOB_END_NOTIFICATION_POLICY_REMOVE); + inOrder.verify(mNotificationManagerInternal, never()) + .cancelNotification(anyString(), anyString(), anyInt(), anyInt(), any(), + anyInt(), anyInt()); + inOrder.verify(mNotificationManagerInternal) + .enqueueNotification(eq(pkg2), eq(pkg2), eq(uid), eq(pid), any(), + eq(notificationId), eq(notification2), eq(UserHandle.getUserId(uid))); + + // Remove the first job. Only the first notification should be removed. + coordinator.removeNotificationAssociation(jsc1); + inOrder.verify(mNotificationManagerInternal) + .cancelNotification(eq(pkg1), eq(pkg1), eq(uid), eq(pid), any(), + eq(notificationId), eq(UserHandle.getUserId(uid))); + inOrder.verify(mNotificationManagerInternal, never()) + .cancelNotification(anyString(), anyString(), eq(uid), anyInt(), any(), + anyInt(), anyInt()); + + coordinator.removeNotificationAssociation(jsc2); + inOrder.verify(mNotificationManagerInternal) + .cancelNotification(eq(pkg2), eq(pkg2), eq(uid), eq(pid), any(), + eq(notificationId), eq(UserHandle.getUserId(uid))); + } + + private Notification createValidNotification() { + final Notification notification = mock(Notification.class); + doReturn(mock(Icon.class)).when(notification).getSmallIcon(); + doReturn(NOTIFICATION_CHANNEL_ID).when(notification).getChannelId(); + return notification; + } +} diff --git a/services/tests/mockingservicestests/src/com/android/server/job/JobSchedulerServiceTest.java b/services/tests/mockingservicestests/src/com/android/server/job/JobSchedulerServiceTest.java index fc737d06059d..8e4849043984 100644 --- a/services/tests/mockingservicestests/src/com/android/server/job/JobSchedulerServiceTest.java +++ b/services/tests/mockingservicestests/src/com/android/server/job/JobSchedulerServiceTest.java @@ -34,6 +34,8 @@ import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; import android.app.ActivityManager; @@ -46,6 +48,7 @@ import android.app.job.JobScheduler; import android.app.usage.UsageStatsManagerInternal; import android.content.ComponentName; import android.content.Context; +import android.content.PermissionChecker; import android.content.pm.PackageManager; import android.content.pm.PackageManagerInternal; import android.content.res.Resources; @@ -63,6 +66,7 @@ import com.android.server.DeviceIdleInternal; import com.android.server.LocalServices; import com.android.server.PowerAllowlistInternal; import com.android.server.SystemServiceManager; +import com.android.server.job.controllers.ConnectivityController; import com.android.server.job.controllers.JobStatus; import com.android.server.pm.UserManagerInternal; import com.android.server.usage.AppStandbyInternal; @@ -102,6 +106,7 @@ public class JobSchedulerServiceTest { .initMocks(this) .strictness(Strictness.LENIENT) .mockStatic(LocalServices.class) + .mockStatic(PermissionChecker.class) .mockStatic(ServiceManager.class) .startMocking(); @@ -193,6 +198,15 @@ public class JobSchedulerServiceTest { jobInfoBuilder.build(), callingUid, "com.android.test", 0, testTag); } + private void grantRunLongJobsPermission(boolean grant) { + final int permissionStatus = grant + ? PermissionChecker.PERMISSION_GRANTED : PermissionChecker.PERMISSION_HARD_DENIED; + doReturn(permissionStatus) + .when(() -> PermissionChecker.checkPermissionForPreflight( + any(), eq(android.Manifest.permission.RUN_LONG_JOBS), + anyInt(), anyInt(), anyString())); + } + @Test public void testGetMinJobExecutionGuaranteeMs() { JobStatus ejMax = createJobStatus("testGetMinJobExecutionGuaranteeMs", @@ -207,6 +221,15 @@ public class JobSchedulerServiceTest { createJobInfo(5).setPriority(JobInfo.PRIORITY_HIGH)); JobStatus jobDef = createJobStatus("testGetMinJobExecutionGuaranteeMs", createJobInfo(6)); + JobStatus jobDT = createJobStatus("testGetMinJobExecutionGuaranteeMs", + createJobInfo(7) + .setDataTransfer(true).setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)); + JobStatus jobUI = createJobStatus("testGetMinJobExecutionGuaranteeMs", + createJobInfo(8)); // TODO(255371817): add setUserInitiated(true) + JobStatus jobUIDT = createJobStatus("testGetMinJobExecutionGuaranteeMs", + // TODO(255371817): add setUserInitiated(true) + createJobInfo(9) + .setDataTransfer(true).setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)); spyOn(ejMax); spyOn(ejHigh); @@ -214,6 +237,9 @@ public class JobSchedulerServiceTest { spyOn(ejHighDowngraded); spyOn(jobHigh); spyOn(jobDef); + spyOn(jobDT); + spyOn(jobUI); + spyOn(jobUIDT); when(ejMax.shouldTreatAsExpeditedJob()).thenReturn(true); when(ejHigh.shouldTreatAsExpeditedJob()).thenReturn(true); @@ -221,6 +247,16 @@ public class JobSchedulerServiceTest { when(ejHighDowngraded.shouldTreatAsExpeditedJob()).thenReturn(false); when(jobHigh.shouldTreatAsExpeditedJob()).thenReturn(false); when(jobDef.shouldTreatAsExpeditedJob()).thenReturn(false); + when(jobUI.shouldTreatAsUserInitiated()).thenReturn(true); + when(jobUIDT.shouldTreatAsUserInitiated()).thenReturn(true); + + ConnectivityController connectivityController = mService.getConnectivityController(); + spyOn(connectivityController); + mService.mConstants.RUNTIME_MIN_DATA_TRANSFER_GUARANTEE_MS = 10 * MINUTE_IN_MILLIS; + mService.mConstants.RUNTIME_DATA_TRANSFER_LIMIT_MS = 60 * MINUTE_IN_MILLIS; + mService.mConstants.RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_BUFFER_FACTOR = 1.5f; + mService.mConstants.RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_MS = HOUR_IN_MILLIS; + mService.mConstants.RUNTIME_USER_INITIATED_DATA_TRANSFER_LIMIT_MS = 6 * HOUR_IN_MILLIS; assertEquals(mService.mConstants.RUNTIME_MIN_EJ_GUARANTEE_MS, mService.getMinJobExecutionGuaranteeMs(ejMax)); @@ -234,8 +270,81 @@ public class JobSchedulerServiceTest { mService.getMinJobExecutionGuaranteeMs(jobHigh)); assertEquals(mService.mConstants.RUNTIME_MIN_GUARANTEE_MS, mService.getMinJobExecutionGuaranteeMs(jobDef)); + grantRunLongJobsPermission(false); // Without permission + assertEquals(mService.mConstants.RUNTIME_MIN_GUARANTEE_MS, + mService.getMinJobExecutionGuaranteeMs(jobDT)); + grantRunLongJobsPermission(true); // With permission + doReturn(ConnectivityController.UNKNOWN_TIME) + .when(connectivityController).getEstimatedTransferTimeMs(any()); + assertEquals(mService.mConstants.RUNTIME_MIN_DATA_TRANSFER_GUARANTEE_MS, + mService.getMinJobExecutionGuaranteeMs(jobDT)); + doReturn(mService.mConstants.RUNTIME_MIN_DATA_TRANSFER_GUARANTEE_MS / 2) + .when(connectivityController).getEstimatedTransferTimeMs(any()); + assertEquals(mService.mConstants.RUNTIME_MIN_DATA_TRANSFER_GUARANTEE_MS, + mService.getMinJobExecutionGuaranteeMs(jobDT)); + doReturn(mService.mConstants.RUNTIME_MIN_DATA_TRANSFER_GUARANTEE_MS * 2) + .when(connectivityController).getEstimatedTransferTimeMs(any()); + assertEquals(mService.mConstants.RUNTIME_MIN_DATA_TRANSFER_GUARANTEE_MS, + mService.getMinJobExecutionGuaranteeMs(jobDT)); + doReturn(mService.mConstants.RUNTIME_DATA_TRANSFER_LIMIT_MS * 2) + .when(connectivityController).getEstimatedTransferTimeMs(any()); + assertEquals(mService.mConstants.RUNTIME_MIN_DATA_TRANSFER_GUARANTEE_MS, + mService.getMinJobExecutionGuaranteeMs(jobDT)); + // UserInitiated + assertEquals(mService.mConstants.RUNTIME_MIN_USER_INITIATED_GUARANTEE_MS, + mService.getMinJobExecutionGuaranteeMs(jobUI)); + grantRunLongJobsPermission(false); + assertEquals(mService.mConstants.RUNTIME_MIN_USER_INITIATED_GUARANTEE_MS, + mService.getMinJobExecutionGuaranteeMs(jobUIDT)); + grantRunLongJobsPermission(true); // With permission + doReturn(ConnectivityController.UNKNOWN_TIME) + .when(connectivityController).getEstimatedTransferTimeMs(any()); + assertEquals(mService.mConstants.RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_MS, + mService.getMinJobExecutionGuaranteeMs(jobUIDT)); + doReturn(mService.mConstants.RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_MS / 2) + .when(connectivityController).getEstimatedTransferTimeMs(any()); + assertEquals(mService.mConstants.RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_MS, + mService.getMinJobExecutionGuaranteeMs(jobUIDT)); + doReturn(mService.mConstants.RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_MS * 2) + .when(connectivityController).getEstimatedTransferTimeMs(any()); + assertEquals( + (long) (mService.mConstants.RUNTIME_MIN_USER_INITIATED_DATA_TRANSFER_GUARANTEE_MS + * 2 * 1.5), + mService.getMinJobExecutionGuaranteeMs(jobUIDT)); + doReturn(mService.mConstants.RUNTIME_USER_INITIATED_DATA_TRANSFER_LIMIT_MS * 2) + .when(connectivityController).getEstimatedTransferTimeMs(any()); + assertEquals(mService.mConstants.RUNTIME_USER_INITIATED_DATA_TRANSFER_LIMIT_MS, + mService.getMinJobExecutionGuaranteeMs(jobUIDT)); } + @Test + public void testGetMaxJobExecutionTimeMs() { + JobStatus jobDT = createJobStatus("testGetMaxJobExecutionTimeMs", + createJobInfo(7) + .setDataTransfer(true).setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)); + JobStatus jobUI = createJobStatus("testGetMaxJobExecutionTimeMs", + createJobInfo(9)); // TODO(255371817): add setUserInitiated(true) + JobStatus jobUIDT = createJobStatus("testGetMaxJobExecutionTimeMs", + // TODO(255371817): add setUserInitiated(true) + createJobInfo(10) + .setDataTransfer(true).setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)); + + spyOn(jobDT); + spyOn(jobUI); + spyOn(jobUIDT); + + when(jobUI.shouldTreatAsUserInitiated()).thenReturn(true); + when(jobUIDT.shouldTreatAsUserInitiated()).thenReturn(true); + + grantRunLongJobsPermission(true); + + assertEquals(mService.mConstants.RUNTIME_DATA_TRANSFER_LIMIT_MS, + mService.getMaxJobExecutionTimeMs(jobDT)); + assertEquals(mService.mConstants.RUNTIME_USER_INITIATED_LIMIT_MS, + mService.getMaxJobExecutionTimeMs(jobUI)); + assertEquals(mService.mConstants.RUNTIME_USER_INITIATED_DATA_TRANSFER_LIMIT_MS, + mService.getMaxJobExecutionTimeMs(jobUIDT)); + } /** * Confirm that {@link JobSchedulerService#getRescheduleJobForFailureLocked(JobStatus, int)} 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 1f85f2c2c46e..42e22f3f7c2f 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 @@ -24,6 +24,7 @@ import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED; import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED; import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR; import static android.net.NetworkCapabilities.TRANSPORT_VPN; +import static android.text.format.DateUtils.SECOND_IN_MILLIS; import static com.android.dx.mockito.inline.extended.ExtendedMockito.doNothing; import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn; @@ -35,6 +36,7 @@ import static com.android.server.job.JobSchedulerService.FREQUENT_INDEX; import static com.android.server.job.JobSchedulerService.RARE_INDEX; import static com.android.server.job.JobSchedulerService.RESTRICTED_INDEX; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -240,20 +242,20 @@ public class ConnectivityControllerTest { .setLinkDownstreamBandwidthKbps(1).build(), mConstants)); // Slow downstream assertFalse(controller.isSatisfied(createJobStatus(job), net, - createCapabilitiesBuilder().setLinkUpstreamBandwidthKbps(137) + createCapabilitiesBuilder().setLinkUpstreamBandwidthKbps(140) .setLinkDownstreamBandwidthKbps(1).build(), mConstants)); // Slow upstream assertFalse(controller.isSatisfied(createJobStatus(job), net, createCapabilitiesBuilder().setLinkUpstreamBandwidthKbps(1) - .setLinkDownstreamBandwidthKbps(137).build(), mConstants)); + .setLinkDownstreamBandwidthKbps(140).build(), mConstants)); // Network good enough assertTrue(controller.isSatisfied(createJobStatus(job), net, - createCapabilitiesBuilder().setLinkUpstreamBandwidthKbps(137) - .setLinkDownstreamBandwidthKbps(137).build(), mConstants)); + createCapabilitiesBuilder().setLinkUpstreamBandwidthKbps(140) + .setLinkDownstreamBandwidthKbps(140).build(), mConstants)); // Network slightly too slow given reduced time assertFalse(controller.isSatisfied(createJobStatus(job), net, - createCapabilitiesBuilder().setLinkUpstreamBandwidthKbps(130) - .setLinkDownstreamBandwidthKbps(130).build(), mConstants)); + createCapabilitiesBuilder().setLinkUpstreamBandwidthKbps(139) + .setLinkDownstreamBandwidthKbps(139).build(), mConstants)); // Slow network is too slow, but device is charging and network is unmetered. when(mService.isBatteryCharging()).thenReturn(true); controller.onBatteryStateChangedLocked(); @@ -1188,6 +1190,78 @@ public class ConnectivityControllerTest { assertFalse(unnetworked.isConstraintSatisfied(JobStatus.CONSTRAINT_CONNECTIVITY)); } + @Test + public void testCalculateTransferTimeMs() { + assertEquals(ConnectivityController.UNKNOWN_TIME, + ConnectivityController.calculateTransferTimeMs(1, 0)); + assertEquals(ConnectivityController.UNKNOWN_TIME, + ConnectivityController.calculateTransferTimeMs(JobInfo.NETWORK_BYTES_UNKNOWN, 512)); + assertEquals(1, ConnectivityController.calculateTransferTimeMs(1, 8)); + assertEquals(1000, ConnectivityController.calculateTransferTimeMs(1000, 8)); + assertEquals(8, ConnectivityController.calculateTransferTimeMs(1024, 1024)); + } + + @Test + public void testGetEstimatedTransferTimeMs() { + final ArgumentCaptor<NetworkCallback> callbackCaptor = + ArgumentCaptor.forClass(NetworkCallback.class); + doNothing().when(mConnManager).registerNetworkCallback(any(), callbackCaptor.capture()); + + final JobStatus job = createJobStatus(createJob() + .setEstimatedNetworkBytes(DataUnit.MEBIBYTES.toBytes(10_000), + DataUnit.MEBIBYTES.toBytes(1_000)) + .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)); + + final ConnectivityController controller = new ConnectivityController(mService, + mFlexibilityController); + + final JobStatus jobNoEstimates = createJobStatus(createJob()); + assertEquals(ConnectivityController.UNKNOWN_TIME, + controller.getEstimatedTransferTimeMs(jobNoEstimates)); + + // No network + job.network = null; + assertEquals(ConnectivityController.UNKNOWN_TIME, + controller.getEstimatedTransferTimeMs(job)); + + final NetworkCallback generalCallback = callbackCaptor.getValue(); + + // No capabilities + final Network network = mock(Network.class); + answerNetwork(generalCallback, null, null, network, null); + job.network = network; + assertEquals(ConnectivityController.UNKNOWN_TIME, + controller.getEstimatedTransferTimeMs(job)); + + // Capabilities don't have bandwidth values + NetworkCapabilities caps = createCapabilitiesBuilder().build(); + answerNetwork(generalCallback, null, null, network, caps); + assertEquals(ConnectivityController.UNKNOWN_TIME, + controller.getEstimatedTransferTimeMs(job)); + + // Capabilities only has downstream bandwidth + caps = createCapabilitiesBuilder() + .setLinkDownstreamBandwidthKbps(1024) + .build(); + answerNetwork(generalCallback, null, null, network, caps); + assertEquals(81920 * SECOND_IN_MILLIS, controller.getEstimatedTransferTimeMs(job)); + + // Capabilities only has upstream bandwidth + caps = createCapabilitiesBuilder() + .setLinkUpstreamBandwidthKbps(2 * 1024) + .build(); + answerNetwork(generalCallback, null, null, network, caps); + assertEquals(4096 * SECOND_IN_MILLIS, controller.getEstimatedTransferTimeMs(job)); + + // Capabilities only both stream bandwidths + caps = createCapabilitiesBuilder() + .setLinkDownstreamBandwidthKbps(1024) + .setLinkUpstreamBandwidthKbps(2 * 1024) + .build(); + answerNetwork(generalCallback, null, null, network, caps); + assertEquals((81920 + 4096) * SECOND_IN_MILLIS, controller.getEstimatedTransferTimeMs(job)); + } + private void answerNetwork(@NonNull NetworkCallback generalCallback, @Nullable NetworkCallback uidCallback, @Nullable Network lastNetwork, @Nullable Network net, @Nullable NetworkCapabilities caps) { @@ -1198,11 +1272,15 @@ public class ConnectivityControllerTest { } } else { generalCallback.onAvailable(net); - generalCallback.onCapabilitiesChanged(net, caps); + if (caps != null) { + generalCallback.onCapabilitiesChanged(net, caps); + } if (uidCallback != null) { uidCallback.onAvailable(net); uidCallback.onBlockedStatusChanged(net, ConnectivityManager.BLOCKED_REASON_NONE); - uidCallback.onCapabilitiesChanged(net, caps); + if (caps != null) { + uidCallback.onCapabilitiesChanged(net, caps); + } } } } diff --git a/services/tests/mockingservicestests/src/com/android/server/job/restrictions/ThermalStatusRestrictionTest.java b/services/tests/mockingservicestests/src/com/android/server/job/restrictions/ThermalStatusRestrictionTest.java index f88e18b4ced1..49426901b142 100644 --- a/services/tests/mockingservicestests/src/com/android/server/job/restrictions/ThermalStatusRestrictionTest.java +++ b/services/tests/mockingservicestests/src/com/android/server/job/restrictions/ThermalStatusRestrictionTest.java @@ -180,14 +180,47 @@ public class ThermalStatusRestrictionTest { createJobBuilder(7).setExpedited(true).build()); final JobStatus ej = spy(createJobStatus("testIsJobRestricted", createJobBuilder(8).setExpedited(true).build())); + final JobStatus ejRetried = spy(createJobStatus("testIsJobRestricted", + createJobBuilder(11).setExpedited(true).build())); + final JobStatus ejRunning = spy(createJobStatus("testIsJobRestricted", + createJobBuilder(12).setExpedited(true).build())); + final JobStatus ejRunningLong = spy(createJobStatus("testIsJobRestricted", + createJobBuilder(13).setExpedited(true).build())); + final JobStatus ui = spy(createJobStatus("testIsJobRestricted", + createJobBuilder(14).build())); + final JobStatus uiRetried = spy(createJobStatus("testIsJobRestricted", + createJobBuilder(15).build())); + final JobStatus uiRunning = spy(createJobStatus("testIsJobRestricted", + createJobBuilder(16).build())); + final JobStatus uiRunningLong = spy(createJobStatus("testIsJobRestricted", + createJobBuilder(17).build())); when(ej.shouldTreatAsExpeditedJob()).thenReturn(true); + when(ejRetried.shouldTreatAsExpeditedJob()).thenReturn(true); + when(ejRunning.shouldTreatAsExpeditedJob()).thenReturn(true); + when(ejRunningLong.shouldTreatAsExpeditedJob()).thenReturn(true); + when(ui.shouldTreatAsUserInitiated()).thenReturn(true); + when(uiRetried.shouldTreatAsUserInitiated()).thenReturn(true); + when(uiRunning.shouldTreatAsUserInitiated()).thenReturn(true); + when(uiRunningLong.shouldTreatAsUserInitiated()).thenReturn(true); + when(ejRetried.getNumPreviousAttempts()).thenReturn(1); + when(uiRetried.getNumPreviousAttempts()).thenReturn(2); when(mJobSchedulerService.isCurrentlyRunningLocked(jobLowPriorityRunning)).thenReturn(true); when(mJobSchedulerService.isCurrentlyRunningLocked(jobHighPriorityRunning)) .thenReturn(true); + when(mJobSchedulerService.isCurrentlyRunningLocked(jobLowPriorityRunningLong)) + .thenReturn(true); + when(mJobSchedulerService.isCurrentlyRunningLocked(jobHighPriorityRunningLong)) + .thenReturn(true); + when(mJobSchedulerService.isCurrentlyRunningLocked(ejRunning)).thenReturn(true); + when(mJobSchedulerService.isCurrentlyRunningLocked(ejRunningLong)).thenReturn(true); + when(mJobSchedulerService.isCurrentlyRunningLocked(uiRunning)).thenReturn(true); + when(mJobSchedulerService.isCurrentlyRunningLocked(uiRunningLong)).thenReturn(true); when(mJobSchedulerService.isJobInOvertimeLocked(jobLowPriorityRunningLong)) .thenReturn(true); when(mJobSchedulerService.isJobInOvertimeLocked(jobHighPriorityRunningLong)) .thenReturn(true); + when(mJobSchedulerService.isJobInOvertimeLocked(ejRunningLong)).thenReturn(true); + when(mJobSchedulerService.isJobInOvertimeLocked(uiRunningLong)).thenReturn(true); assertFalse(mThermalStatusRestriction.isJobRestricted(jobMinPriority)); assertFalse(mThermalStatusRestriction.isJobRestricted(jobLowPriority)); @@ -199,6 +232,13 @@ public class ThermalStatusRestrictionTest { assertFalse(mThermalStatusRestriction.isJobRestricted(jobHighPriorityRunningLong)); assertFalse(mThermalStatusRestriction.isJobRestricted(ej)); assertFalse(mThermalStatusRestriction.isJobRestricted(ejDowngraded)); + assertFalse(mThermalStatusRestriction.isJobRestricted(ejRetried)); + assertFalse(mThermalStatusRestriction.isJobRestricted(ejRunning)); + assertFalse(mThermalStatusRestriction.isJobRestricted(ejRunningLong)); + assertFalse(mThermalStatusRestriction.isJobRestricted(ui)); + assertFalse(mThermalStatusRestriction.isJobRestricted(uiRetried)); + assertFalse(mThermalStatusRestriction.isJobRestricted(uiRunning)); + assertFalse(mThermalStatusRestriction.isJobRestricted(uiRunningLong)); mStatusChangedListener.onThermalStatusChanged(THERMAL_STATUS_LIGHT); @@ -212,6 +252,13 @@ public class ThermalStatusRestrictionTest { assertFalse(mThermalStatusRestriction.isJobRestricted(jobHighPriorityRunningLong)); assertFalse(mThermalStatusRestriction.isJobRestricted(ejDowngraded)); assertFalse(mThermalStatusRestriction.isJobRestricted(ej)); + assertFalse(mThermalStatusRestriction.isJobRestricted(ejRetried)); + assertFalse(mThermalStatusRestriction.isJobRestricted(ejRunning)); + assertFalse(mThermalStatusRestriction.isJobRestricted(ejRunningLong)); + assertFalse(mThermalStatusRestriction.isJobRestricted(ui)); + assertFalse(mThermalStatusRestriction.isJobRestricted(uiRetried)); + assertFalse(mThermalStatusRestriction.isJobRestricted(uiRunning)); + assertFalse(mThermalStatusRestriction.isJobRestricted(uiRunningLong)); mStatusChangedListener.onThermalStatusChanged(THERMAL_STATUS_MODERATE); @@ -225,6 +272,13 @@ public class ThermalStatusRestrictionTest { assertTrue(mThermalStatusRestriction.isJobRestricted(jobHighPriorityRunningLong)); assertTrue(mThermalStatusRestriction.isJobRestricted(ejDowngraded)); assertFalse(mThermalStatusRestriction.isJobRestricted(ej)); + assertTrue(mThermalStatusRestriction.isJobRestricted(ejRetried)); + assertFalse(mThermalStatusRestriction.isJobRestricted(ejRunning)); + assertTrue(mThermalStatusRestriction.isJobRestricted(ejRunningLong)); + assertFalse(mThermalStatusRestriction.isJobRestricted(ui)); + assertTrue(mThermalStatusRestriction.isJobRestricted(uiRetried)); + assertFalse(mThermalStatusRestriction.isJobRestricted(uiRunning)); + assertTrue(mThermalStatusRestriction.isJobRestricted(uiRunningLong)); mStatusChangedListener.onThermalStatusChanged(THERMAL_STATUS_SEVERE); @@ -238,6 +292,13 @@ public class ThermalStatusRestrictionTest { assertTrue(mThermalStatusRestriction.isJobRestricted(jobHighPriorityRunningLong)); assertTrue(mThermalStatusRestriction.isJobRestricted(ejDowngraded)); assertTrue(mThermalStatusRestriction.isJobRestricted(ej)); + assertTrue(mThermalStatusRestriction.isJobRestricted(ejRetried)); + assertTrue(mThermalStatusRestriction.isJobRestricted(ejRunning)); + assertTrue(mThermalStatusRestriction.isJobRestricted(ejRunningLong)); + assertTrue(mThermalStatusRestriction.isJobRestricted(ui)); + assertTrue(mThermalStatusRestriction.isJobRestricted(uiRetried)); + assertTrue(mThermalStatusRestriction.isJobRestricted(uiRunning)); + assertTrue(mThermalStatusRestriction.isJobRestricted(uiRunningLong)); mStatusChangedListener.onThermalStatusChanged(THERMAL_STATUS_CRITICAL); @@ -251,6 +312,13 @@ public class ThermalStatusRestrictionTest { assertTrue(mThermalStatusRestriction.isJobRestricted(jobHighPriorityRunningLong)); assertTrue(mThermalStatusRestriction.isJobRestricted(ejDowngraded)); assertTrue(mThermalStatusRestriction.isJobRestricted(ej)); + assertTrue(mThermalStatusRestriction.isJobRestricted(ejRetried)); + assertTrue(mThermalStatusRestriction.isJobRestricted(ejRunning)); + assertTrue(mThermalStatusRestriction.isJobRestricted(ejRunningLong)); + assertTrue(mThermalStatusRestriction.isJobRestricted(ui)); + assertTrue(mThermalStatusRestriction.isJobRestricted(uiRetried)); + assertTrue(mThermalStatusRestriction.isJobRestricted(uiRunning)); + assertTrue(mThermalStatusRestriction.isJobRestricted(uiRunningLong)); } private JobInfo.Builder createJobBuilder(int jobId) { diff --git a/services/tests/mockingservicestests/src/com/android/server/power/ThermalManagerServiceMockingTest.java b/services/tests/mockingservicestests/src/com/android/server/power/ThermalManagerServiceMockingTest.java new file mode 100644 index 000000000000..34b17c7901b3 --- /dev/null +++ b/services/tests/mockingservicestests/src/com/android/server/power/ThermalManagerServiceMockingTest.java @@ -0,0 +1,218 @@ +/* + * 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.power; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import android.hardware.thermal.CoolingType; +import android.hardware.thermal.IThermal; +import android.hardware.thermal.IThermalChangedCallback; +import android.hardware.thermal.TemperatureThreshold; +import android.hardware.thermal.TemperatureType; +import android.hardware.thermal.ThrottlingSeverity; +import android.os.Binder; +import android.os.CoolingDevice; +import android.os.RemoteException; +import android.os.Temperature; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + + +public class ThermalManagerServiceMockingTest { + @Mock private IThermal mAidlHalMock; + private Binder mAidlBinder = new Binder(); + private CompletableFuture<Temperature> mTemperatureFuture; + private ThermalManagerService.ThermalHalWrapper.TemperatureChangedCallback mTemperatureCallback; + private ThermalManagerService.ThermalHalAidlWrapper mAidlWrapper; + @Captor + ArgumentCaptor<IThermalChangedCallback> mAidlCallbackCaptor; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + Mockito.when(mAidlHalMock.asBinder()).thenReturn(mAidlBinder); + mAidlBinder.attachInterface(mAidlHalMock, IThermal.class.getName()); + mTemperatureFuture = new CompletableFuture<>(); + mTemperatureCallback = temperature -> mTemperatureFuture.complete(temperature); + mAidlWrapper = new ThermalManagerService.ThermalHalAidlWrapper(); + mAidlWrapper.setCallback(mTemperatureCallback); + mAidlWrapper.initProxyAndRegisterCallback(mAidlBinder); + } + + @Test + public void setCallback_aidl() throws Exception { + Mockito.verify(mAidlHalMock, Mockito.times(1)).registerThermalChangedCallback( + mAidlCallbackCaptor.capture()); + android.hardware.thermal.Temperature halT = + new android.hardware.thermal.Temperature(); + halT.type = TemperatureType.SOC; + halT.name = "test"; + halT.throttlingStatus = ThrottlingSeverity.SHUTDOWN; + halT.value = 99.0f; + mAidlCallbackCaptor.getValue().notifyThrottling(halT); + Temperature temperature = mTemperatureFuture.get(100, TimeUnit.MILLISECONDS); + assertEquals(halT.name, temperature.getName()); + assertEquals(halT.type, temperature.getType()); + assertEquals(halT.value, temperature.getValue(), 0.1f); + assertEquals(halT.throttlingStatus, temperature.getStatus()); + } + + @Test + public void getCurrentTemperatures_withFilter_aidl() throws RemoteException { + android.hardware.thermal.Temperature halT1 = new android.hardware.thermal.Temperature(); + halT1.type = TemperatureType.MODEM; + halT1.name = "test1"; + halT1.throttlingStatus = ThrottlingSeverity.EMERGENCY; + halT1.value = 99.0f; + android.hardware.thermal.Temperature halT2 = new android.hardware.thermal.Temperature(); + halT2.name = "test2"; + halT2.type = TemperatureType.MODEM; + halT2.throttlingStatus = ThrottlingSeverity.NONE; + + android.hardware.thermal.Temperature halT3WithDiffType = + new android.hardware.thermal.Temperature(); + halT3WithDiffType.type = TemperatureType.BCL_CURRENT; + halT3WithDiffType.throttlingStatus = ThrottlingSeverity.CRITICAL; + + Mockito.when(mAidlHalMock.getTemperaturesWithType(Mockito.anyInt())).thenReturn( + new android.hardware.thermal.Temperature[]{ + halT2, halT1, halT3WithDiffType, + }); + List<Temperature> ret = mAidlWrapper.getCurrentTemperatures(true, TemperatureType.MODEM); + Mockito.verify(mAidlHalMock, Mockito.times(1)).getTemperaturesWithType( + TemperatureType.MODEM); + + Temperature expectedT1 = new Temperature(halT1.value, halT1.type, halT1.name, + halT1.throttlingStatus); + Temperature expectedT2 = new Temperature(halT2.value, halT2.type, halT2.name, + halT2.throttlingStatus); + List<Temperature> expectedRet = List.of(expectedT1, expectedT2); + assertTrue("Got temperature list as " + ret + " with different values compared to " + + expectedRet, expectedRet.containsAll(ret)); + } + + @Test + public void getCurrentTemperatures_invalidStatus_aidl() throws RemoteException { + android.hardware.thermal.Temperature halTInvalid = + new android.hardware.thermal.Temperature(); + halTInvalid.name = "test"; + halTInvalid.type = TemperatureType.MODEM; + halTInvalid.throttlingStatus = 99; + + Mockito.when(mAidlHalMock.getTemperatures()).thenReturn( + new android.hardware.thermal.Temperature[]{ + halTInvalid + }); + List<Temperature> ret = mAidlWrapper.getCurrentTemperatures(false, 0); + Mockito.verify(mAidlHalMock, Mockito.times(1)).getTemperatures(); + + List<Temperature> expectedRet = List.of( + new Temperature(halTInvalid.value, halTInvalid.type, halTInvalid.name, + ThrottlingSeverity.NONE)); + assertEquals(expectedRet, ret); + } + + @Test + public void getCurrentCoolingDevices_withFilter_aidl() throws RemoteException { + android.hardware.thermal.CoolingDevice halC1 = new android.hardware.thermal.CoolingDevice(); + halC1.type = CoolingType.SPEAKER; + halC1.name = "test1"; + halC1.value = 10; + android.hardware.thermal.CoolingDevice halC2 = new android.hardware.thermal.CoolingDevice(); + halC2.type = CoolingType.MODEM; + halC2.name = "test2"; + halC2.value = 110; + + Mockito.when(mAidlHalMock.getCoolingDevicesWithType(Mockito.anyInt())).thenReturn( + new android.hardware.thermal.CoolingDevice[]{ + halC1, halC2 + } + ); + List<CoolingDevice> ret = mAidlWrapper.getCurrentCoolingDevices(true, CoolingType.SPEAKER); + Mockito.verify(mAidlHalMock, Mockito.times(1)).getCoolingDevicesWithType( + CoolingType.SPEAKER); + + CoolingDevice expectedC1 = new CoolingDevice(halC1.value, halC1.type, halC1.name); + List<CoolingDevice> expectedRet = List.of(expectedC1); + assertTrue("Got cooling device list as " + ret + " with different values compared to " + + expectedRet, expectedRet.containsAll(ret)); + } + + @Test + public void getCurrentCoolingDevices_invalidType_aidl() throws RemoteException { + android.hardware.thermal.CoolingDevice halC1 = new android.hardware.thermal.CoolingDevice(); + halC1.type = 99; + halC1.name = "test1"; + halC1.value = 10; + android.hardware.thermal.CoolingDevice halC2 = new android.hardware.thermal.CoolingDevice(); + halC2.type = -1; + halC2.name = "test2"; + halC2.value = 110; + + Mockito.when(mAidlHalMock.getCoolingDevices()).thenReturn( + new android.hardware.thermal.CoolingDevice[]{ + halC1, halC2 + } + ); + List<CoolingDevice> ret = mAidlWrapper.getCurrentCoolingDevices(false, 0); + Mockito.verify(mAidlHalMock, Mockito.times(1)).getCoolingDevices(); + + assertTrue("Got cooling device list as " + ret + ", expecting empty list", ret.isEmpty()); + } + + @Test + public void getTemperatureThresholds_withFilter_aidl() throws RemoteException { + TemperatureThreshold halT1 = new TemperatureThreshold(); + halT1.name = "test1"; + halT1.type = Temperature.TYPE_SKIN; + halT1.hotThrottlingThresholds = new float[]{1, 2, 3}; + halT1.coldThrottlingThresholds = new float[]{}; + + TemperatureThreshold halT2 = new TemperatureThreshold(); + halT1.name = "test2"; + halT1.type = Temperature.TYPE_SOC; + halT1.hotThrottlingThresholds = new float[]{}; + halT1.coldThrottlingThresholds = new float[]{3, 2, 1}; + + Mockito.when(mAidlHalMock.getTemperatureThresholdsWithType(Mockito.anyInt())).thenReturn( + new TemperatureThreshold[]{halT1, halT2} + ); + List<TemperatureThreshold> ret = mAidlWrapper.getTemperatureThresholds(true, + Temperature.TYPE_SOC); + Mockito.verify(mAidlHalMock, Mockito.times(1)).getTemperatureThresholdsWithType( + Temperature.TYPE_SOC); + + assertEquals("Got unexpected temperature thresholds size", 1, ret.size()); + TemperatureThreshold threshold = ret.get(0); + assertEquals(halT1.name, threshold.name); + assertEquals(halT1.type, threshold.type); + assertArrayEquals(halT1.hotThrottlingThresholds, threshold.hotThrottlingThresholds, 0.1f); + assertArrayEquals(halT1.coldThrottlingThresholds, threshold.coldThrottlingThresholds, 0.1f); + } +} diff --git a/services/tests/servicestests/AndroidManifest.xml b/services/tests/servicestests/AndroidManifest.xml index 9eb3b92abc6f..71492656913b 100644 --- a/services/tests/servicestests/AndroidManifest.xml +++ b/services/tests/servicestests/AndroidManifest.xml @@ -98,6 +98,7 @@ <uses-permission android:name="android.permission.MAINLINE_NETWORK_STACK"/> <uses-permission android:name="android.permission.OVERRIDE_COMPAT_CHANGE_CONFIG_ON_RELEASE_BUILD"/> + <uses-permission android:name="android.permission.OVERRIDE_COMPAT_CHANGE_CONFIG"/> <uses-permission android:name="android.permission.ASSOCIATE_INPUT_DEVICE_TO_DISPLAY" /> <uses-permission android:name="android.permission.READ_NEARBY_STREAMING_POLICY" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_ROUTING" /> diff --git a/services/tests/servicestests/src/com/android/server/NetworkManagementServiceTest.java b/services/tests/servicestests/src/com/android/server/NetworkManagementServiceTest.java index cbe6d2687a55..17a587603009 100644 --- a/services/tests/servicestests/src/com/android/server/NetworkManagementServiceTest.java +++ b/services/tests/servicestests/src/com/android/server/NetworkManagementServiceTest.java @@ -37,6 +37,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import android.annotation.NonNull; +import android.content.AttributionSource; import android.content.Context; import android.net.ConnectivityManager; import android.net.INetd; @@ -46,8 +47,10 @@ import android.net.NetworkPolicyManager; import android.os.BatteryStats; import android.os.Binder; import android.os.IBinder; +import android.os.PermissionEnforcer; import android.os.Process; import android.os.RemoteException; +import android.permission.PermissionCheckerManager; import android.test.suitebuilder.annotation.SmallTest; import android.util.ArrayMap; @@ -87,6 +90,7 @@ public class NetworkManagementServiceTest { private ArgumentCaptor<INetdUnsolicitedEventListener> mUnsolListenerCaptor; private final MockDependencies mDeps = new MockDependencies(); + private final MockPermissionEnforcer mPermissionEnforcer = new MockPermissionEnforcer(); private final class MockDependencies extends Dependencies { @Override @@ -114,6 +118,24 @@ public class NetworkManagementServiceTest { } } + private static final class MockPermissionEnforcer extends PermissionEnforcer { + @Override + protected int checkPermission(@NonNull String permission, + @NonNull AttributionSource source) { + String[] granted = new String [] { + android.Manifest.permission.NETWORK_SETTINGS, + android.Manifest.permission.OBSERVE_NETWORK_POLICY, + android.Manifest.permission.SHUTDOWN + }; + for (String p : granted) { + if (p.equals(permission)) { + return PermissionCheckerManager.PERMISSION_GRANTED; + } + } + return PermissionCheckerManager.PERMISSION_HARD_DENIED; + } + } + @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); @@ -122,6 +144,13 @@ public class NetworkManagementServiceTest { doReturn(Context.CONNECTIVITY_SERVICE).when(mContext).getSystemServiceName( eq(ConnectivityManager.class)); doReturn(mCm).when(mContext).getSystemService(eq(Context.CONNECTIVITY_SERVICE)); + // The AIDL stub will use PermissionEnforcer to check permission from the caller. + // Mock the service. See MockPermissionEnforcer above. + doReturn(Context.PERMISSION_ENFORCER_SERVICE).when(mContext).getSystemServiceName( + eq(PermissionEnforcer.class)); + doReturn(mPermissionEnforcer).when(mContext).getSystemService( + eq(Context.PERMISSION_ENFORCER_SERVICE)); + // Start the service and wait until it connects to our socket. mNMService = NetworkManagementService.create(mContext, mDeps); } diff --git a/services/tests/servicestests/src/com/android/server/am/UserControllerTest.java b/services/tests/servicestests/src/com/android/server/am/UserControllerTest.java index d47f063caec5..98037d792bf4 100644 --- a/services/tests/servicestests/src/com/android/server/am/UserControllerTest.java +++ b/services/tests/servicestests/src/com/android/server/am/UserControllerTest.java @@ -38,6 +38,8 @@ import static com.android.server.am.UserController.USER_COMPLETED_EVENT_MSG; import static com.android.server.am.UserController.USER_CURRENT_MSG; import static com.android.server.am.UserController.USER_START_MSG; import static com.android.server.am.UserController.USER_SWITCH_TIMEOUT_MSG; +import static com.android.server.pm.UserManagerInternal.USER_START_MODE_BACKGROUND; +import static com.android.server.pm.UserManagerInternal.USER_START_MODE_FOREGROUND; import static com.google.android.collect.Lists.newArrayList; import static com.google.android.collect.Sets.newHashSet; @@ -190,7 +192,7 @@ public class UserControllerTest { // that's not the case, the test should call mockAssignUserToMainDisplay() doReturn(UserManagerInternal.USER_ASSIGNMENT_RESULT_SUCCESS_VISIBLE) .when(mInjector.mUserManagerInternalMock) - .assignUserToDisplayOnStart(anyInt(), anyInt(), anyBoolean(), anyInt()); + .assignUserToDisplayOnStart(anyInt(), anyInt(), anyInt(), anyInt()); mUserController = new UserController(mInjector); mUserController.setAllowUserUnlocking(true); @@ -207,7 +209,7 @@ public class UserControllerTest { @Test public void testStartUser_foreground() { - mUserController.startUser(TEST_USER_ID, true /* foreground */); + mUserController.startUser(TEST_USER_ID, USER_START_MODE_FOREGROUND); verify(mInjector.getWindowManager()).startFreezingScreen(anyInt(), anyInt()); verify(mInjector.getWindowManager(), never()).stopFreezingScreen(); verify(mInjector.getWindowManager(), times(1)).setSwitchingUser(anyBoolean()); @@ -219,7 +221,7 @@ public class UserControllerTest { @Test public void testStartUser_background() { - boolean started = mUserController.startUser(TEST_USER_ID, /* foreground= */ false); + boolean started = mUserController.startUser(TEST_USER_ID, USER_START_MODE_BACKGROUND); assertWithMessage("startUser(%s, foreground=false)", TEST_USER_ID).that(started).isTrue(); verify(mInjector.getWindowManager(), never()).startFreezingScreen(anyInt(), anyInt()); verify(mInjector.getWindowManager(), never()).setSwitchingUser(anyBoolean()); @@ -232,9 +234,10 @@ public class UserControllerTest { public void testStartUser_displayAssignmentFailed() { doReturn(UserManagerInternal.USER_ASSIGNMENT_RESULT_FAILURE) .when(mInjector.mUserManagerInternalMock) - .assignUserToDisplayOnStart(eq(TEST_USER_ID), anyInt(), eq(true), anyInt()); + .assignUserToDisplayOnStart(eq(TEST_USER_ID), anyInt(), + eq(USER_START_MODE_FOREGROUND), anyInt()); - boolean started = mUserController.startUser(TEST_USER_ID, /* foreground= */ true); + boolean started = mUserController.startUser(TEST_USER_ID, USER_START_MODE_FOREGROUND); assertWithMessage("startUser(%s, foreground=true)", TEST_USER_ID).that(started).isFalse(); } @@ -266,7 +269,7 @@ public class UserControllerTest { mUserController.setInitialConfig(/* userSwitchUiEnabled= */ false, /* maxRunningUsers= */ 3, /* delayUserDataLocking= */ false); - mUserController.startUser(TEST_USER_ID, /* foreground= */ true); + mUserController.startUser(TEST_USER_ID, USER_START_MODE_FOREGROUND); verify(mInjector.getWindowManager(), never()).startFreezingScreen(anyInt(), anyInt()); verify(mInjector.getWindowManager(), never()).stopFreezingScreen(); verify(mInjector.getWindowManager(), never()).setSwitchingUser(anyBoolean()); @@ -275,7 +278,8 @@ public class UserControllerTest { @Test public void testStartPreCreatedUser_foreground() { - assertFalse(mUserController.startUser(TEST_PRE_CREATED_USER_ID, /* foreground= */ true)); + assertFalse( + mUserController.startUser(TEST_PRE_CREATED_USER_ID, USER_START_MODE_FOREGROUND)); // Make sure no intents have been fired for pre-created users. assertTrue(mInjector.mSentIntents.isEmpty()); @@ -284,7 +288,7 @@ public class UserControllerTest { @Test public void testStartPreCreatedUser_background() throws Exception { - assertTrue(mUserController.startUser(TEST_PRE_CREATED_USER_ID, /* foreground= */ false)); + assertTrue(mUserController.startUser(TEST_PRE_CREATED_USER_ID, USER_START_MODE_BACKGROUND)); // Make sure no intents have been fired for pre-created users. assertTrue(mInjector.mSentIntents.isEmpty()); @@ -352,7 +356,7 @@ public class UserControllerTest { }).when(observer).onUserSwitching(anyInt(), any()); mUserController.registerUserSwitchObserver(observer, "mock"); // Start user -- this will update state of mUserController - mUserController.startUser(TEST_USER_ID, true); + mUserController.startUser(TEST_USER_ID, USER_START_MODE_FOREGROUND); Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); assertNotNull(reportMsg); UserState userState = (UserState) reportMsg.obj; @@ -382,7 +386,7 @@ public class UserControllerTest { when(observer.asBinder()).thenReturn(new Binder()); mUserController.registerUserSwitchObserver(observer, "mock"); // Start user -- this will update state of mUserController - mUserController.startUser(TEST_USER_ID, true); + mUserController.startUser(TEST_USER_ID, USER_START_MODE_FOREGROUND); Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); assertNotNull(reportMsg); UserState userState = (UserState) reportMsg.obj; @@ -408,7 +412,7 @@ public class UserControllerTest { mUserController.setInitialConfig(/* userSwitchUiEnabled= */ true, /* maxRunningUsers= */ 3, /* delayUserDataLocking= */ false); // Start user -- this will update state of mUserController - mUserController.startUser(TEST_USER_ID, true); + mUserController.startUser(TEST_USER_ID, USER_START_MODE_FOREGROUND); Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); assertNotNull(reportMsg); UserState userState = (UserState) reportMsg.obj; @@ -429,7 +433,7 @@ public class UserControllerTest { mUserController.setInitialConfig(/* userSwitchUiEnabled= */ true, /* maxRunningUsers= */ 3, /* delayUserDataLocking= */ false); // Start user -- this will update state of mUserController - mUserController.startUser(TEST_USER_ID, /* foreground=*/ true); + mUserController.startUser(TEST_USER_ID, USER_START_MODE_FOREGROUND); Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); assertNotNull(reportMsg); UserState userState = (UserState) reportMsg.obj; @@ -450,7 +454,7 @@ public class UserControllerTest { /* maxRunningUsers= */ 3, /* delayUserDataLocking= */ false); // Start user -- this will update state of mUserController - mUserController.startUser(TEST_USER_ID, /* foreground=*/ true); + mUserController.startUser(TEST_USER_ID, USER_START_MODE_FOREGROUND); Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); assertNotNull(reportMsg); UserState userState = (UserState) reportMsg.obj; @@ -487,7 +491,7 @@ public class UserControllerTest { when(observer.asBinder()).thenReturn(new Binder()); mUserController.registerUserSwitchObserver(observer, "mock"); // Start user -- this will update state of mUserController - mUserController.startUser(TEST_USER_ID, true); + mUserController.startUser(TEST_USER_ID, USER_START_MODE_FOREGROUND); Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); assertNotNull(reportMsg); int oldUserId = reportMsg.arg1; @@ -511,7 +515,8 @@ public class UserControllerTest { public void testExplicitSystemUserStartInBackground() { setUpUser(UserHandle.USER_SYSTEM, 0); assertFalse(mUserController.isSystemUserStarted()); - assertTrue(mUserController.startUser(UserHandle.USER_SYSTEM, false, null)); + assertTrue(mUserController.startUser(UserHandle.USER_SYSTEM, USER_START_MODE_BACKGROUND, + null)); assertTrue(mUserController.isSystemUserStarted()); } @@ -662,7 +667,7 @@ public class UserControllerTest { @Test public void testStopUser_currentUser() { setUpUser(TEST_USER_ID1, /* flags= */ 0); - mUserController.startUser(TEST_USER_ID1, /* foreground= */ true); + mUserController.startUser(TEST_USER_ID1, USER_START_MODE_FOREGROUND); int r = mUserController.stopUser(TEST_USER_ID1, /* force= */ true, /* allowDelayedLocking= */ true, /* stopUserCallback= */ null, @@ -701,7 +706,7 @@ public class UserControllerTest { public void testUserNotUnlockedBeforeAllowed() throws Exception { mUserController.setAllowUserUnlocking(false); - mUserController.startUser(TEST_USER_ID, /* foreground= */ false); + mUserController.startUser(TEST_USER_ID, USER_START_MODE_BACKGROUND); verify(mInjector.mStorageManagerMock, never()) .unlockUserKey(eq(TEST_USER_ID), anyInt(), any()); @@ -862,10 +867,10 @@ public class UserControllerTest { setUpUser(user1, 0); setUpUser(user2, 0); - mUserController.startUser(user1, /* foreground= */ true); + mUserController.startUser(user1, USER_START_MODE_FOREGROUND); mUserController.getStartedUserState(user1).setState(UserState.STATE_RUNNING_UNLOCKED); - mUserController.startUser(user2, /* foreground= */ false); + mUserController.startUser(user2, USER_START_MODE_BACKGROUND); mUserController.getStartedUserState(user2).setState(UserState.STATE_RUNNING_LOCKED); final int event1a = SystemService.UserCompletedEventType.EVENT_TYPE_USER_STARTING; @@ -902,7 +907,7 @@ public class UserControllerTest { private void setUpAndStartUserInBackground(int userId) throws Exception { setUpUser(userId, 0); - mUserController.startUser(userId, /* foreground= */ false); + mUserController.startUser(userId, USER_START_MODE_BACKGROUND); verify(mInjector.mLockPatternUtilsMock, times(1)).unlockUserKeyIfUnsecured(userId); mUserStates.put(userId, mUserController.getStartedUserState(userId)); } @@ -946,7 +951,7 @@ public class UserControllerTest { private void addForegroundUserAndContinueUserSwitch(int newUserId, int expectedOldUserId, int expectedNumberOfCalls, boolean expectOldUserStopping) { // Start user -- this will update state of mUserController - mUserController.startUser(newUserId, true); + mUserController.startUser(newUserId, USER_START_MODE_FOREGROUND); Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); assertNotNull(reportMsg); UserState userState = (UserState) reportMsg.obj; @@ -1005,12 +1010,12 @@ public class UserControllerTest { private void verifyUserAssignedToDisplay(@UserIdInt int userId, int displayId) { verify(mInjector.getUserManagerInternal()).assignUserToDisplayOnStart(eq(userId), anyInt(), - anyBoolean(), eq(displayId)); + anyInt(), eq(displayId)); } private void verifyUserNeverAssignedToDisplay() { verify(mInjector.getUserManagerInternal(), never()).assignUserToDisplayOnStart(anyInt(), - anyInt(), anyBoolean(), anyInt()); + anyInt(), anyInt(), anyInt()); } private void verifyUserUnassignedFromDisplay(@UserIdInt int userId) { diff --git a/services/tests/servicestests/src/com/android/server/companion/virtual/VirtualDeviceManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/companion/virtual/VirtualDeviceManagerServiceTest.java index 9de619055e9f..ded8179d765e 100644 --- a/services/tests/servicestests/src/com/android/server/companion/virtual/VirtualDeviceManagerServiceTest.java +++ b/services/tests/servicestests/src/com/android/server/companion/virtual/VirtualDeviceManagerServiceTest.java @@ -16,6 +16,8 @@ package com.android.server.companion.virtual; +import static android.companion.virtual.VirtualDeviceManager.DEFAULT_DEVICE_ID; +import static android.companion.virtual.VirtualDeviceManager.INVALID_DEVICE_ID; import static android.companion.virtual.VirtualDeviceParams.DEVICE_POLICY_CUSTOM; import static android.companion.virtual.VirtualDeviceParams.DEVICE_POLICY_DEFAULT; import static android.companion.virtual.VirtualDeviceParams.POLICY_TYPE_SENSORS; @@ -47,7 +49,6 @@ import android.app.WindowConfiguration; import android.app.admin.DevicePolicyManager; import android.companion.AssociationInfo; import android.companion.virtual.IVirtualDeviceActivityListener; -import android.companion.virtual.VirtualDeviceManager; import android.companion.virtual.VirtualDeviceParams; import android.companion.virtual.audio.IAudioConfigChangedCallback; import android.companion.virtual.audio.IAudioRoutingCallback; @@ -84,6 +85,7 @@ import android.platform.test.annotations.Presubmit; import android.testing.AndroidTestingRunner; import android.testing.TestableLooper; import android.util.ArraySet; +import android.view.Display; import android.view.DisplayInfo; import android.view.KeyEvent; import android.view.WindowManager; @@ -178,6 +180,7 @@ public class VirtualDeviceManagerServiceTest { private AssociationInfo mAssociationInfo; private VirtualDeviceManagerService mVdms; private VirtualDeviceManagerInternal mLocalService; + private VirtualDeviceManagerService.VirtualDeviceManagerImpl mVdm; @Mock private InputController.NativeWrapper mNativeWrapperMock; @Mock @@ -303,45 +306,68 @@ public class VirtualDeviceManagerServiceTest { mVdms = new VirtualDeviceManagerService(mContext); mLocalService = mVdms.getLocalServiceInstance(); + mVdm = mVdms.new VirtualDeviceManagerImpl(); VirtualDeviceParams params = new VirtualDeviceParams .Builder() .setBlockedActivities(getBlockedActivities()) .build(); mDeviceImpl = new VirtualDeviceImpl(mContext, - mAssociationInfo, new Binder(), /* ownerUid */ 0, VIRTUAL_DEVICE_ID, + mAssociationInfo, new Binder(), /* ownerUid= */ 0, VIRTUAL_DEVICE_ID, mInputController, mSensorController, (int associationId) -> {}, mPendingTrampolineCallback, mActivityListener, mRunningAppsChangedCallback, params); mVdms.addVirtualDevice(mDeviceImpl); } @Test + public void getDeviceIdForDisplayId_invalidDisplayId_returnsDefault() { + assertThat(mVdm.getDeviceIdForDisplayId(Display.INVALID_DISPLAY)) + .isEqualTo(DEFAULT_DEVICE_ID); + } + + @Test + public void getDeviceIdForDisplayId_defaultDisplayId_returnsDefault() { + assertThat(mVdm.getDeviceIdForDisplayId(Display.DEFAULT_DISPLAY)) + .isEqualTo(DEFAULT_DEVICE_ID); + } + + @Test + public void getDeviceIdForDisplayId_nonExistentDisplayId_returnsDefault() { + mDeviceImpl.mVirtualDisplayIds.remove(DISPLAY_ID); + + assertThat(mVdm.getDeviceIdForDisplayId(DISPLAY_ID)) + .isEqualTo(DEFAULT_DEVICE_ID); + } + + @Test + public void getDeviceIdForDisplayId_withValidVirtualDisplayId_returnsDeviceId() { + mDeviceImpl.mVirtualDisplayIds.add(DISPLAY_ID); + + assertThat(mVdm.getDeviceIdForDisplayId(DISPLAY_ID)) + .isEqualTo(mDeviceImpl.getDeviceId()); + } + + @Test public void getDevicePolicy_invalidDeviceId_returnsDefault() { - assertThat( - mLocalService.getDevicePolicy( - VirtualDeviceManager.INVALID_DEVICE_ID, POLICY_TYPE_SENSORS)) + assertThat(mVdm.getDevicePolicy(INVALID_DEVICE_ID, POLICY_TYPE_SENSORS)) .isEqualTo(DEVICE_POLICY_DEFAULT); } @Test public void getDevicePolicy_defaultDeviceId_returnsDefault() { - assertThat( - mLocalService.getDevicePolicy( - VirtualDeviceManager.DEFAULT_DEVICE_ID, POLICY_TYPE_SENSORS)) + assertThat(mVdm.getDevicePolicy(DEFAULT_DEVICE_ID, POLICY_TYPE_SENSORS)) .isEqualTo(DEVICE_POLICY_DEFAULT); } @Test public void getDevicePolicy_nonExistentDeviceId_returnsDefault() { - assertThat( - mLocalService.getDevicePolicy(mDeviceImpl.getDeviceId() + 1, POLICY_TYPE_SENSORS)) + assertThat(mVdm.getDevicePolicy(mDeviceImpl.getDeviceId() + 1, POLICY_TYPE_SENSORS)) .isEqualTo(DEVICE_POLICY_DEFAULT); } @Test public void getDevicePolicy_unspecifiedPolicy_returnsDefault() { - assertThat( - mLocalService.getDevicePolicy(mDeviceImpl.getDeviceId(), POLICY_TYPE_SENSORS)) + assertThat(mVdm.getDevicePolicy(mDeviceImpl.getDeviceId(), POLICY_TYPE_SENSORS)) .isEqualTo(DEVICE_POLICY_DEFAULT); } @@ -358,8 +384,7 @@ public class VirtualDeviceManagerServiceTest { mPendingTrampolineCallback, mActivityListener, mRunningAppsChangedCallback, params); mVdms.addVirtualDevice(mDeviceImpl); - assertThat( - mLocalService.getDevicePolicy(mDeviceImpl.getDeviceId(), POLICY_TYPE_SENSORS)) + assertThat(mVdm.getDevicePolicy(mDeviceImpl.getDeviceId(), POLICY_TYPE_SENSORS)) .isEqualTo(DEVICE_POLICY_CUSTOM); } @@ -1160,5 +1185,4 @@ public class VirtualDeviceManagerServiceTest { verify(mContext).startActivityAsUser(argThat(intent -> intent.filterEquals(blockedAppIntent)), any(), any()); } - } diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java index a02b0f165383..88314ab86c28 100644 --- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java @@ -4310,7 +4310,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); assertExpectException(SecurityException.class, null, () -> - dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0")); + dpm.setSystemSetting(admin1, Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, "0")); } @Test diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/OwnersTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/OwnersTest.java index f535fdac6cf6..85a2446cc316 100644 --- a/services/tests/servicestests/src/com/android/server/devicepolicy/OwnersTest.java +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/OwnersTest.java @@ -44,6 +44,7 @@ import org.junit.runner.RunWith; public class OwnersTest extends DpmTestBase { private static final String TESTDPC_PACKAGE = "com.afwsamples.testdpc"; + private final DeviceStateCacheImpl mDeviceStateCache = new DeviceStateCacheImpl(); @Before public void setUp() throws Exception { @@ -120,6 +121,6 @@ public class OwnersTest extends DpmTestBase { final MockSystemServices services = getServices(); return new Owners(services.userManager, services.userManagerInternal, services.packageManagerInternal, services.activityTaskManagerInternal, - services.activityManagerInternal, services.pathProvider); + services.activityManagerInternal, mDeviceStateCache, services.pathProvider); } } diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/PolicyVersionUpgraderTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/PolicyVersionUpgraderTest.java index d540734d0938..1779b16a7471 100644 --- a/services/tests/servicestests/src/com/android/server/devicepolicy/PolicyVersionUpgraderTest.java +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/PolicyVersionUpgraderTest.java @@ -33,6 +33,7 @@ import android.content.pm.ApplicationInfo; import android.os.IpcDataCache; import android.os.Parcel; import android.os.UserHandle; +import android.util.ArraySet; import android.util.Xml; import androidx.test.InstrumentationRegistry; @@ -47,29 +48,42 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; +import org.xmlpull.v1.XmlSerializer; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.Set; import java.util.function.Function; +import javax.xml.parsers.DocumentBuilderFactory; + @RunWith(JUnit4.class) public class PolicyVersionUpgraderTest extends DpmTestBase { // NOTE: Only change this value if the corresponding CL also adds a test to test the upgrade // to the new version. - private static final int LATEST_TESTED_VERSION = 3; + private static final int LATEST_TESTED_VERSION = 4; public static final String PERMISSIONS_TAG = "admin-can-grant-sensors-permissions"; public static final String DEVICE_OWNER_XML = "device_owner_2.xml"; private ComponentName mFakeAdmin; private class FakePolicyUpgraderDataProvider implements PolicyUpgraderDataProvider { Map<ComponentName, DeviceAdminInfo> mComponentToDeviceAdminInfo = new HashMap<>(); + ArrayList<String> mPlatformSuspendedPackages = new ArrayList<>(); int[] mUsers; private JournaledFile makeJournaledFile(int userId, String fileName) { @@ -98,6 +112,11 @@ public class PolicyVersionUpgraderTest extends DpmTestBase { public int[] getUsersForUpgrade() { return mUsers; } + + @Override + public List<String> getPlatformSuspendedPackages(int userId) { + return mPlatformSuspendedPackages; + } } private final Context mRealTestContext = InstrumentationRegistry.getTargetContext(); @@ -257,10 +276,71 @@ public class PolicyVersionUpgraderTest extends DpmTestBase { } @Test + public void testAdminPackageSuspensionSaved() throws Exception { + final int ownerUser = 0; + mProvider.mUsers = new int[]{ownerUser}; + getServices().addUser(ownerUser, FLAG_PRIMARY, USER_TYPE_FULL_SYSTEM); + setUpPackageManagerForAdmin(admin1, UserHandle.getUid(ownerUser, 123 /* admin app ID */)); + writeVersionToXml(3); + preparePoliciesFile(ownerUser, "device_policies.xml"); + prepareDeviceOwnerFile(ownerUser, "device_owner_2.xml"); + + // Pretend package manager thinks these packages are suspended by the platform. + Set<String> suspendedPkgs = Set.of("com.some.app", "foo.bar.baz"); + mProvider.mPlatformSuspendedPackages.addAll(suspendedPkgs); + + mUpgrader.upgradePolicy(4); + + assertThat(readVersionFromXml()).isAtLeast(4); + + assertAdminSuspendedPackages(ownerUser, suspendedPkgs); + } + + private void assertAdminSuspendedPackages(int ownerUser, Set<String> suspendedPkgs) + throws Exception { + Document policies = readPolicies(ownerUser); + Element adminElem = + (Element) policies.getDocumentElement().getElementsByTagName("admin").item(0); + Element suspendedElem = + (Element) adminElem.getElementsByTagName("suspended-packages").item(0); + NodeList pkgsNodes = suspendedElem.getElementsByTagName("item"); + Set<String> storedSuspendedPkgs = new ArraySet<>(); + for (int i = 0; i < pkgsNodes.getLength(); i++) { + Element item = (Element) pkgsNodes.item(i); + storedSuspendedPkgs.add(item.getAttribute("value")); + } + assertThat(storedSuspendedPkgs).isEqualTo(suspendedPkgs); + } + + @Test public void isLatestVersionTested() { assertThat(DevicePolicyManagerService.DPMS_VERSION).isEqualTo(LATEST_TESTED_VERSION); } + /** + * Reads ABX binary XML, converts it to text, and returns as an input stream. + */ + private InputStream abxToXmlStream(File file) throws Exception { + FileInputStream fileIn = new FileInputStream(file); + XmlPullParser in = Xml.newBinaryPullParser(); + in.setInput(fileIn, StandardCharsets.UTF_8.name()); + + ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + XmlSerializer out = Xml.newSerializer(); + out.setOutput(byteOut, StandardCharsets.UTF_8.name()); + + Xml.copy(in, out); + out.flush(); + + return new ByteArrayInputStream(byteOut.toByteArray()); + } + + private Document readPolicies(int userId) throws Exception { + File policiesFile = mProvider.makeDevicePoliciesJournaledFile(userId).chooseForRead(); + InputStream is = abxToXmlStream(policiesFile); + return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is); + } + private void writeVersionToXml(int dpmsVersion) throws IOException { JournaledFile versionFile = mProvider.makePoliciesVersionJournaledFile(0); Files.asCharSink(versionFile.chooseForWrite(), Charset.defaultCharset()).write( diff --git a/services/tests/servicestests/src/com/android/server/display/DisplayManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/display/DisplayManagerServiceTest.java index ca8e45a79bc4..f676a3f84c0f 100644 --- a/services/tests/servicestests/src/com/android/server/display/DisplayManagerServiceTest.java +++ b/services/tests/servicestests/src/com/android/server/display/DisplayManagerServiceTest.java @@ -214,7 +214,7 @@ public class DisplayManagerServiceTest { .thenReturn(mMockDisplayToken); SurfaceControl.StaticDisplayInfo staticDisplayInfo = new SurfaceControl.StaticDisplayInfo(); staticDisplayInfo.isInternal = true; - when(mSurfaceControlProxy.getStaticDisplayInfo(mMockDisplayToken)) + when(mSurfaceControlProxy.getStaticDisplayInfo(anyLong())) .thenReturn(staticDisplayInfo); SurfaceControl.DynamicDisplayInfo dynamicDisplayMode = new SurfaceControl.DynamicDisplayInfo(); @@ -223,7 +223,7 @@ public class DisplayManagerServiceTest { displayMode.height = 200; displayMode.supportedHdrTypes = new int[]{1, 2}; dynamicDisplayMode.supportedDisplayModes = new SurfaceControl.DisplayMode[] {displayMode}; - when(mSurfaceControlProxy.getDynamicDisplayInfo(mMockDisplayToken)) + when(mSurfaceControlProxy.getDynamicDisplayInfo(anyLong())) .thenReturn(dynamicDisplayMode); when(mSurfaceControlProxy.getDesiredDisplayModeSpecs(mMockDisplayToken)) .thenReturn(new SurfaceControl.DesiredDisplayModeSpecs()); diff --git a/services/tests/servicestests/src/com/android/server/graphics/fonts/UpdatableFontDirTest.java b/services/tests/servicestests/src/com/android/server/graphics/fonts/UpdatableFontDirTest.java index 9672085b8f3a..68e5ebf027ad 100644 --- a/services/tests/servicestests/src/com/android/server/graphics/fonts/UpdatableFontDirTest.java +++ b/services/tests/servicestests/src/com/android/server/graphics/fonts/UpdatableFontDirTest.java @@ -109,17 +109,16 @@ public final class UpdatableFontDirTest { @Override public boolean isFromTrustedProvider(String path, byte[] signature) { - return mHasFsverityPaths.contains(path); + if (!mHasFsverityPaths.contains(path)) { + return false; + } + String fakeSignature = new String(signature, StandardCharsets.UTF_8); + return GOOD_SIGNATURE.equals(fakeSignature); } @Override - public void setUpFsverity(String path, byte[] pkcs7Signature) throws IOException { - String fakeSignature = new String(pkcs7Signature, StandardCharsets.UTF_8); - if (GOOD_SIGNATURE.equals(fakeSignature)) { - mHasFsverityPaths.add(path); - } else { - throw new IOException("Failed to set up fake fs-verity"); - } + public void setUpFsverity(String path) throws IOException { + mHasFsverityPaths.add(path); } @Override @@ -813,8 +812,8 @@ public final class UpdatableFontDirTest { } @Override - public void setUpFsverity(String path, byte[] pkcs7Signature) throws IOException { - mFakeFsverityUtil.setUpFsverity(path, pkcs7Signature); + public void setUpFsverity(String path) throws IOException { + mFakeFsverityUtil.setUpFsverity(path); } @Override diff --git a/services/tests/servicestests/src/com/android/server/input/KeyRemapperTests.kt b/services/tests/servicestests/src/com/android/server/input/KeyRemapperTests.kt new file mode 100644 index 000000000000..c22782c91bdf --- /dev/null +++ b/services/tests/servicestests/src/com/android/server/input/KeyRemapperTests.kt @@ -0,0 +1,150 @@ +/* + * 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.input + +import android.content.Context +import android.content.ContextWrapper +import android.hardware.input.IInputManager +import android.hardware.input.InputManager +import android.os.test.TestLooper +import android.platform.test.annotations.Presubmit +import android.view.InputDevice +import android.view.KeyEvent +import androidx.test.core.app.ApplicationProvider +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.junit.MockitoJUnit +import java.io.FileNotFoundException +import java.io.FileOutputStream +import java.io.IOException +import java.io.InputStream + +private fun createKeyboard(deviceId: Int): InputDevice = + InputDevice.Builder() + .setId(deviceId) + .setName("Device $deviceId") + .setDescriptor("descriptor $deviceId") + .setSources(InputDevice.SOURCE_KEYBOARD) + .setKeyboardType(InputDevice.KEYBOARD_TYPE_ALPHABETIC) + .setExternal(true) + .build() + +/** + * Tests for {@link KeyRemapper}. + * + * Build/Install/Run: + * atest FrameworksServicesTests:KeyRemapperTests + */ +@Presubmit +class KeyRemapperTests { + + companion object { + const val DEVICE_ID = 1 + val REMAPPABLE_KEYS = intArrayOf( + KeyEvent.KEYCODE_CTRL_LEFT, KeyEvent.KEYCODE_CTRL_RIGHT, + KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_META_RIGHT, + KeyEvent.KEYCODE_ALT_LEFT, KeyEvent.KEYCODE_ALT_RIGHT, + KeyEvent.KEYCODE_SHIFT_LEFT, KeyEvent.KEYCODE_SHIFT_RIGHT, + KeyEvent.KEYCODE_CAPS_LOCK + ) + } + + @get:Rule + val rule = MockitoJUnit.rule()!! + + @Mock + private lateinit var iInputManager: IInputManager + @Mock + private lateinit var native: NativeInputManagerService + private lateinit var mKeyRemapper: KeyRemapper + private lateinit var context: Context + private lateinit var dataStore: PersistentDataStore + private lateinit var testLooper: TestLooper + + @Before + fun setup() { + context = Mockito.spy(ContextWrapper(ApplicationProvider.getApplicationContext())) + dataStore = PersistentDataStore(object : PersistentDataStore.Injector() { + override fun openRead(): InputStream? { + throw FileNotFoundException() + } + + override fun startWrite(): FileOutputStream? { + throw IOException() + } + + override fun finishWrite(fos: FileOutputStream?, success: Boolean) {} + }) + testLooper = TestLooper() + mKeyRemapper = KeyRemapper( + context, + native, + dataStore, + testLooper.looper + ) + val inputManager = InputManager.resetInstance(iInputManager) + Mockito.`when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE))) + .thenReturn(inputManager) + Mockito.`when`(iInputManager.inputDeviceIds).thenReturn(intArrayOf(DEVICE_ID)) + } + + @After + fun tearDown() { + InputManager.clearInstance() + } + + @Test + fun testKeyRemapping() { + val keyboard = createKeyboard(DEVICE_ID) + Mockito.`when`(iInputManager.getInputDevice(DEVICE_ID)).thenReturn(keyboard) + + for (i in REMAPPABLE_KEYS.indices) { + val fromKeyCode = REMAPPABLE_KEYS[i] + val toKeyCode = REMAPPABLE_KEYS[(i + 1) % REMAPPABLE_KEYS.size] + mKeyRemapper.remapKey(fromKeyCode, toKeyCode) + testLooper.dispatchNext() + } + + val remapping = mKeyRemapper.keyRemapping + val expectedSize = REMAPPABLE_KEYS.size + assertEquals("Remapping size should be $expectedSize", expectedSize, remapping.size) + + for (i in REMAPPABLE_KEYS.indices) { + val fromKeyCode = REMAPPABLE_KEYS[i] + val toKeyCode = REMAPPABLE_KEYS[(i + 1) % REMAPPABLE_KEYS.size] + assertEquals( + "Remapping should include mapping from $fromKeyCode to $toKeyCode", + toKeyCode, + remapping.getOrDefault(fromKeyCode, -1) + ) + } + + mKeyRemapper.clearAllKeyRemappings() + testLooper.dispatchNext() + + assertEquals( + "Remapping size should be 0 after clearAllModifierKeyRemappings", + 0, + mKeyRemapper.keyRemapping.size + ) + } +}
\ No newline at end of file diff --git a/services/tests/servicestests/src/com/android/server/inputmethod/InputMethodUtilsTest.java b/services/tests/servicestests/src/com/android/server/inputmethod/InputMethodUtilsTest.java index 426b9433492d..4b318de78827 100644 --- a/services/tests/servicestests/src/com/android/server/inputmethod/InputMethodUtilsTest.java +++ b/services/tests/servicestests/src/com/android/server/inputmethod/InputMethodUtilsTest.java @@ -25,8 +25,16 @@ 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.Mockito.atLeastOnce; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import android.content.ContentResolver; import android.content.Context; +import android.content.ContextWrapper; +import android.content.IContentProvider; import android.content.pm.ApplicationInfo; import android.content.pm.ResolveInfo; import android.content.pm.ServiceInfo; @@ -35,6 +43,9 @@ import android.content.res.Resources; import android.os.Build; import android.os.LocaleList; import android.os.Parcel; +import android.os.UserHandle; +import android.provider.Settings; +import android.test.mock.MockContentResolver; import android.text.TextUtils; import android.util.ArrayMap; import android.util.IntArray; @@ -1214,6 +1225,42 @@ public class InputMethodUtilsTest { StartInputFlags.VIEW_HAS_FOCUS | StartInputFlags.IS_TEXT_EDITOR)); } + @Test + public void testInputMethodSettings_SwitchCurrentUser() { + TestContext ownerUserContext = createMockContext(0 /* userId */); + final InputMethodInfo systemIme = createFakeInputMethodInfo( + "SystemIme", "fake.latin", true /* isSystem */); + final InputMethodInfo nonSystemIme = createFakeInputMethodInfo("NonSystemIme", + "fake.voice0", false /* isSystem */); + final ArrayMap<String, InputMethodInfo> methodMap = new ArrayMap<>(); + methodMap.put(systemIme.getId(), systemIme); + + // Init InputMethodSettings for the owner user (userId=0), verify calls can get the + // corresponding user's context, contentResolver and the resources configuration. + InputMethodUtils.InputMethodSettings settings = new InputMethodUtils.InputMethodSettings( + ownerUserContext, methodMap, 0 /* userId */, true); + assertEquals(0, settings.getCurrentUserId()); + + settings.isShowImeWithHardKeyboardEnabled(); + verify(ownerUserContext.getContentResolver(), atLeastOnce()).getAttributionSource(); + + settings.getEnabledInputMethodSubtypeListLocked(nonSystemIme, true); + verify(ownerUserContext.getResources(), atLeastOnce()).getConfiguration(); + + // Calling switchCurrentUser to the secondary user (userId=10), verify calls can get the + // corresponding user's context, contentResolver and the resources configuration. + settings.switchCurrentUser(10 /* userId */, true); + assertEquals(10, settings.getCurrentUserId()); + + settings.isShowImeWithHardKeyboardEnabled(); + verify(TestContext.getSecondaryUserContext().getContentResolver(), + atLeastOnce()).getAttributionSource(); + + settings.getEnabledInputMethodSubtypeListLocked(nonSystemIme, true); + verify(TestContext.getSecondaryUserContext().getResources(), + atLeastOnce()).getConfiguration(); + } + private static IntArray createSubtypeHashCodeArrayFromStr(String subtypeHashCodesStr) { final IntArray subtypes = new IntArray(); final TextUtils.SimpleStringSplitter imeSubtypeSplitter = @@ -1236,6 +1283,63 @@ public class InputMethodUtilsTest { imeId, createSubtypeHashCodeArrayFromStr(enabledSubtypeHashCodesStr))); } + private static TestContext createMockContext(int userId) { + return new TestContext(InstrumentationRegistry.getInstrumentation() + .getTargetContext(), userId); + } + + private static class TestContext extends ContextWrapper { + private int mUserId; + private ContentResolver mResolver; + private Resources mResources; + + private static TestContext sSecondaryUserContext; + + TestContext(@NonNull Context context, int userId) { + super(context); + mUserId = userId; + mResolver = mock(MockContentResolver.class); + when(mResolver.acquireProvider(Settings.Secure.CONTENT_URI)).thenReturn( + mock(IContentProvider.class)); + mResources = mock(Resources.class); + + final Configuration configuration = new Configuration(); + if (userId == 0) { + configuration.setLocale(LOCALE_EN_US); + } else { + configuration.setLocale(LOCALE_FR_CA); + } + doReturn(configuration).when(mResources).getConfiguration(); + } + + @Override + public Context createContextAsUser(UserHandle user, int flags) { + if (user.getIdentifier() != UserHandle.USER_SYSTEM) { + return sSecondaryUserContext = new TestContext(this, user.getIdentifier()); + } + return this; + } + + @Override + public int getUserId() { + return mUserId; + } + + @Override + public ContentResolver getContentResolver() { + return mResolver; + } + + @Override + public Resources getResources() { + return mResources; + } + + static Context getSecondaryUserContext() { + return sSecondaryUserContext; + } + } + @Test public void updateEnabledImeStringTest() { // No change cases diff --git a/services/tests/servicestests/src/com/android/server/locksettings/BaseLockSettingsServiceTests.java b/services/tests/servicestests/src/com/android/server/locksettings/BaseLockSettingsServiceTests.java index 15eaf5d77ca6..4668e5d53c78 100644 --- a/services/tests/servicestests/src/com/android/server/locksettings/BaseLockSettingsServiceTests.java +++ b/services/tests/servicestests/src/com/android/server/locksettings/BaseLockSettingsServiceTests.java @@ -16,6 +16,9 @@ package com.android.server.locksettings; +import static android.app.admin.DevicePolicyManager.DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_FLAG; +import static android.provider.DeviceConfig.NAMESPACE_DEVICE_POLICY_MANAGER; + import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -47,6 +50,7 @@ import android.os.UserManager; import android.os.storage.IStorageManager; import android.os.storage.StorageManager; import android.provider.Settings; +import android.provider.DeviceConfig; import android.security.KeyStore; import androidx.test.InstrumentationRegistry; @@ -188,7 +192,11 @@ public abstract class BaseLockSettingsServiceTests { // Adding a fake Device Owner app which will enable escrow token support in LSS. when(mDevicePolicyManager.getDeviceOwnerComponentOnAnyUser()).thenReturn( new ComponentName("com.dummy.package", ".FakeDeviceOwner")); + // TODO(b/258213147): Remove + DeviceConfig.setProperty(NAMESPACE_DEVICE_POLICY_MANAGER, + DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_FLAG, "true", /* makeDefault= */ false); when(mUserManagerInternal.isDeviceManaged()).thenReturn(true); + when(mDeviceStateCache.isUserOrganizationManaged(anyInt())).thenReturn(true); when(mDeviceStateCache.isDeviceProvisioned()).thenReturn(true); mockBiometricsHardwareFingerprintsAndTemplates(PRIMARY_USER_ID); mockBiometricsHardwareFingerprintsAndTemplates(MANAGED_PROFILE_USER_ID); @@ -221,7 +229,10 @@ public abstract class BaseLockSettingsServiceTests { when(mUserManager.getProfileParent(eq(profileId))).thenReturn(PRIMARY_USER_INFO); when(mUserManager.isUserRunning(eq(profileId))).thenReturn(true); when(mUserManager.isUserUnlocked(eq(profileId))).thenReturn(true); + // TODO(b/258213147): Remove when(mUserManagerInternal.isUserManaged(eq(profileId))).thenReturn(true); + when(mDeviceStateCache.isUserOrganizationManaged(eq(profileId))) + .thenReturn(true); return userInfo; } diff --git a/services/tests/servicestests/src/com/android/server/locksettings/SyntheticPasswordTests.java b/services/tests/servicestests/src/com/android/server/locksettings/SyntheticPasswordTests.java index a441824c3982..b00467cf8637 100644 --- a/services/tests/servicestests/src/com/android/server/locksettings/SyntheticPasswordTests.java +++ b/services/tests/servicestests/src/com/android/server/locksettings/SyntheticPasswordTests.java @@ -28,6 +28,7 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.any; import static org.mockito.Mockito.atLeastOnce; @@ -36,8 +37,8 @@ import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import android.app.admin.PasswordMetrics; import android.app.PropertyInvalidatedCache; +import android.app.admin.PasswordMetrics; import android.os.RemoteException; import android.platform.test.annotations.Presubmit; @@ -400,6 +401,8 @@ public class SyntheticPasswordTests extends BaseLockSettingsServiceTests { @Test public void testEscrowTokenCannotBeActivatedOnUnmanagedUser() { byte[] token = "some-high-entropy-secure-token".getBytes(); + when(mDeviceStateCache.isUserOrganizationManaged(anyInt())).thenReturn(false); + // TODO(b/258213147): Remove when(mUserManagerInternal.isDeviceManaged()).thenReturn(false); when(mUserManagerInternal.isUserManaged(PRIMARY_USER_ID)).thenReturn(false); when(mDeviceStateCache.isDeviceProvisioned()).thenReturn(true); diff --git a/services/tests/servicestests/src/com/android/server/media/projection/OWNERS b/services/tests/servicestests/src/com/android/server/media/projection/OWNERS new file mode 100644 index 000000000000..832bcd9d70e6 --- /dev/null +++ b/services/tests/servicestests/src/com/android/server/media/projection/OWNERS @@ -0,0 +1 @@ +include /media/java/android/media/projection/OWNERS diff --git a/services/tests/servicestests/src/com/android/server/power/ThermalManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/power/ThermalManagerServiceTest.java index 3848babdc912..57f9f1831304 100644 --- a/services/tests/servicestests/src/com/android/server/power/ThermalManagerServiceTest.java +++ b/services/tests/servicestests/src/com/android/server/power/ThermalManagerServiceTest.java @@ -30,8 +30,8 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.content.Context; -import android.hardware.thermal.V2_0.TemperatureThreshold; -import android.hardware.thermal.V2_0.ThrottlingSeverity; +import android.hardware.thermal.TemperatureThreshold; +import android.hardware.thermal.ThrottlingSeverity; import android.os.CoolingDevice; import android.os.IBinder; import android.os.IPowerManager; diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsNoteTest.java b/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsNoteTest.java index e9c5b01dbe3a..5b51868631dd 100644 --- a/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsNoteTest.java +++ b/services/tests/servicestests/src/com/android/server/power/stats/BatteryStatsNoteTest.java @@ -359,6 +359,7 @@ public class BatteryStatsNoteTest extends TestCase { // map of ActivityManager process states and how long to simulate run time in each state Map<Integer, Integer> stateRuntimeMap = new HashMap<Integer, Integer>(); stateRuntimeMap.put(ActivityManager.PROCESS_STATE_TOP, 1111); + stateRuntimeMap.put(ActivityManager.PROCESS_STATE_BOUND_TOP, 7382); stateRuntimeMap.put(ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE, 1234); stateRuntimeMap.put(ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE, 2468); stateRuntimeMap.put(ActivityManager.PROCESS_STATE_TOP_SLEEPING, 7531); @@ -395,7 +396,8 @@ public class BatteryStatsNoteTest extends TestCase { actualRunTimeUs = uid.getProcessStateTime(BatteryStats.Uid.PROCESS_STATE_FOREGROUND_SERVICE, elapsedTimeUs, STATS_SINCE_CHARGED); - expectedRunTimeMs = stateRuntimeMap.get(ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE); + expectedRunTimeMs = stateRuntimeMap.get(ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) + + stateRuntimeMap.get(ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE); assertEquals(expectedRunTimeMs * 1000, actualRunTimeUs); actualRunTimeUs = uid.getProcessStateTime(BatteryStats.Uid.PROCESS_STATE_TOP_SLEEPING, @@ -405,8 +407,7 @@ public class BatteryStatsNoteTest extends TestCase { actualRunTimeUs = uid.getProcessStateTime(BatteryStats.Uid.PROCESS_STATE_FOREGROUND, elapsedTimeUs, STATS_SINCE_CHARGED); - expectedRunTimeMs = stateRuntimeMap.get(ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) - + stateRuntimeMap.get(ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE); + expectedRunTimeMs = stateRuntimeMap.get(ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND); assertEquals(expectedRunTimeMs * 1000, actualRunTimeUs); actualRunTimeUs = uid.getProcessStateTime(BatteryStats.Uid.PROCESS_STATE_BACKGROUND, @@ -414,7 +415,8 @@ public class BatteryStatsNoteTest extends TestCase { expectedRunTimeMs = stateRuntimeMap.get(ActivityManager.PROCESS_STATE_TRANSIENT_BACKGROUND) + stateRuntimeMap.get(ActivityManager.PROCESS_STATE_BACKUP) + stateRuntimeMap.get(ActivityManager.PROCESS_STATE_SERVICE) - + stateRuntimeMap.get(ActivityManager.PROCESS_STATE_RECEIVER); + + stateRuntimeMap.get(ActivityManager.PROCESS_STATE_RECEIVER) + + stateRuntimeMap.get(ActivityManager.PROCESS_STATE_BOUND_TOP); assertEquals(expectedRunTimeMs * 1000, actualRunTimeUs); actualRunTimeUs = uid.getProcessStateTime(BatteryStats.Uid.PROCESS_STATE_CACHED, diff --git a/services/tests/servicestests/src/com/android/server/power/stats/BatteryUsageStatsProviderTest.java b/services/tests/servicestests/src/com/android/server/power/stats/BatteryUsageStatsProviderTest.java index b313fa44575d..9d46e11515da 100644 --- a/services/tests/servicestests/src/com/android/server/power/stats/BatteryUsageStatsProviderTest.java +++ b/services/tests/servicestests/src/com/android/server/power/stats/BatteryUsageStatsProviderTest.java @@ -78,9 +78,9 @@ public class BatteryUsageStatsProviderTest { batteryUsageStats.getUidBatteryConsumers(); final UidBatteryConsumer uidBatteryConsumer = uidBatteryConsumers.get(0); assertThat(uidBatteryConsumer.getTimeInStateMs(UidBatteryConsumer.STATE_FOREGROUND)) - .isEqualTo(60 * MINUTE_IN_MS); + .isEqualTo(20 * MINUTE_IN_MS); assertThat(uidBatteryConsumer.getTimeInStateMs(UidBatteryConsumer.STATE_BACKGROUND)) - .isEqualTo(10 * MINUTE_IN_MS); + .isEqualTo(40 * MINUTE_IN_MS); assertThat(uidBatteryConsumer.getConsumedPower(BatteryConsumer.POWER_COMPONENT_AUDIO)) .isWithin(PRECISION).of(2.0); assertThat( @@ -121,40 +121,44 @@ public class BatteryUsageStatsProviderTest { private BatteryStatsImpl prepareBatteryStats() { BatteryStatsImpl batteryStats = mStatsRule.getBatteryStats(); + mStatsRule.setTime(10 * MINUTE_IN_MS, 10 * MINUTE_IN_MS); synchronized (batteryStats) { - batteryStats.noteActivityResumedLocked(APP_UID, - 10 * MINUTE_IN_MS, 10 * MINUTE_IN_MS); + batteryStats.noteActivityResumedLocked(APP_UID); } + + mStatsRule.setTime(10 * MINUTE_IN_MS, 10 * MINUTE_IN_MS); synchronized (batteryStats) { - batteryStats.noteUidProcessStateLocked(APP_UID, - ActivityManager.PROCESS_STATE_TOP, - 10 * MINUTE_IN_MS, 10 * MINUTE_IN_MS); + batteryStats.noteUidProcessStateLocked(APP_UID, ActivityManager.PROCESS_STATE_TOP); } + mStatsRule.setTime(30 * MINUTE_IN_MS, 30 * MINUTE_IN_MS); synchronized (batteryStats) { - batteryStats.noteActivityPausedLocked(APP_UID, - 30 * MINUTE_IN_MS, 30 * MINUTE_IN_MS); + batteryStats.noteActivityPausedLocked(APP_UID); } + mStatsRule.setTime(30 * MINUTE_IN_MS, 30 * MINUTE_IN_MS); synchronized (batteryStats) { batteryStats.noteUidProcessStateLocked(APP_UID, - ActivityManager.PROCESS_STATE_SERVICE, - 30 * MINUTE_IN_MS, 30 * MINUTE_IN_MS); + ActivityManager.PROCESS_STATE_SERVICE); } + mStatsRule.setTime(40 * MINUTE_IN_MS, 40 * MINUTE_IN_MS); synchronized (batteryStats) { batteryStats.noteUidProcessStateLocked(APP_UID, - ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE, - 40 * MINUTE_IN_MS, 40 * MINUTE_IN_MS); + ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE); } + mStatsRule.setTime(50 * MINUTE_IN_MS, 50 * MINUTE_IN_MS); synchronized (batteryStats) { batteryStats.noteUidProcessStateLocked(APP_UID, - ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE, - 50 * MINUTE_IN_MS, 50 * MINUTE_IN_MS); + ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE); } + mStatsRule.setTime(60 * MINUTE_IN_MS, 60 * MINUTE_IN_MS); synchronized (batteryStats) { batteryStats.noteUidProcessStateLocked(APP_UID, - ActivityManager.PROCESS_STATE_CACHED_EMPTY, - 80 * MINUTE_IN_MS, 80 * MINUTE_IN_MS); + ActivityManager.PROCESS_STATE_BOUND_TOP); + } + mStatsRule.setTime(70 * MINUTE_IN_MS, 70 * MINUTE_IN_MS); + synchronized (batteryStats) { + batteryStats.noteUidProcessStateLocked(APP_UID, + ActivityManager.PROCESS_STATE_CACHED_EMPTY); } - synchronized (batteryStats) { batteryStats.noteFlashlightOnLocked(APP_UID, 1000, 1000); } diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java index ee31748e24c7..d16e11ba6398 100644 --- a/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java @@ -62,11 +62,13 @@ import static com.android.server.wm.TaskFragment.EMBEDDING_DISALLOWED_NEW_TASK; import static com.android.server.wm.TaskFragment.EMBEDDING_DISALLOWED_UNTRUSTED_HOST; import static com.android.server.wm.WindowContainer.POSITION_BOTTOM; import static com.android.server.wm.WindowContainer.POSITION_TOP; +import static com.android.server.wm.WindowTestsBase.ActivityBuilder.DEFAULT_FAKE_UID; 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.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -1617,6 +1619,119 @@ public class ActivityStarterTests extends WindowTestsBase { assertNull(starter2.mMovedToTopActivity); } + /** + * Tests a task with specific display category exist in system and then launching another + * activity with the same affinity but without define the display category. Make sure the + * lunching activity is placed on the different task. + */ + @Test + public void testLaunchActivityWithoutDisplayCategory() { + final ActivityInfo info = new ActivityInfo(); + info.applicationInfo = new ApplicationInfo(); + info.taskAffinity = ActivityRecord.computeTaskAffinity("test", DEFAULT_FAKE_UID, + 0 /* launchMode */); + info.requiredDisplayCategory = "automotive"; + final Task task = new TaskBuilder(mSupervisor).setCreateActivity(true).setActivityInfo(info) + .build(); + + final ActivityRecord target = new ActivityBuilder(mAtm).setAffinity(info.taskAffinity) + .build(); + final ActivityStarter starter = prepareStarter(FLAG_ACTIVITY_NEW_TASK, false); + startActivityInner(starter, target, null /* source */, null /* options */, + null /* inTask */, null /* inTaskFragment */); + + assertNotEquals(task, target.getTask()); + } + + /** + * Tests a task with a specific display category exist in the system and then launches another + * activity with the different display category. Make sure the launching activity is not placed + * on the sourceRecord's task. + */ + @Test + public void testLaunchActivityWithDifferentDisplayCategory() { + final ActivityInfo info = new ActivityInfo(); + info.applicationInfo = new ApplicationInfo(); + info.taskAffinity = ActivityRecord.computeTaskAffinity("test", DEFAULT_FAKE_UID, + 0 /* launchMode */); + info.requiredDisplayCategory = "automotive"; + final Task task = new TaskBuilder(mSupervisor).setCreateActivity(true).setActivityInfo(info) + .build(); + + final ActivityRecord target = new ActivityBuilder(mAtm).setRequiredDisplayCategory("auto") + .setAffinity(info.taskAffinity).build(); + final ActivityStarter starter = prepareStarter(0, false); + startActivityInner(starter, target, task.getBottomMostActivity(), null /* options */, + null /* inTask */, null /* inTaskFragment */); + + assertNotEquals(task, target.getTask()); + } + + /** + * Tests a task with specific display category exist in system and then launching another + * activity with the same display category. Make sure the launching activity is placed on the + * same task. + */ + @Test + public void testLaunchActivityWithSameDisplayCategory() { + final ActivityInfo info = new ActivityInfo(); + info.applicationInfo = new ApplicationInfo(); + info.taskAffinity = ActivityRecord.computeTaskAffinity("test", DEFAULT_FAKE_UID, + 0 /* launchMode */); + info.requiredDisplayCategory = "automotive"; + final Task task = new TaskBuilder(mSupervisor).setCreateActivity(true).setActivityInfo(info) + .build(); + + final ActivityRecord target = new ActivityBuilder(mAtm) + .setRequiredDisplayCategory(info.requiredDisplayCategory) + .setAffinity(info.taskAffinity).build(); + final ActivityStarter starter = prepareStarter(0, false); + startActivityInner(starter, target, task.getBottomMostActivity(), null /* options */, + null /* inTask */, null /* inTaskFragment */); + + assertEquals(task, target.getTask()); + } + + /** + * Tests a task with specific display category exist in system and launching activity into the + * specific task within inTask attribute. Make sure the activity is not placed on the task since + * the display category is different. + */ + @Test + public void testLaunchActivityInTaskWithDisplayCategory() { + final ActivityInfo info = new ActivityInfo(); + info.applicationInfo = new ApplicationInfo(); + info.requiredDisplayCategory = "automotive"; + final Task inTask = new TaskBuilder(mSupervisor).setActivityInfo(info).build(); + inTask.inRecents = true; + + final ActivityStarter starter = prepareStarter(0, false); + final ActivityRecord target = new ActivityBuilder(mAtm).build(); + startActivityInner(starter, target, null /* source */, null /* options */, inTask, + null /* inTaskFragment */); + + assertNotEquals(inTask, target.getTask()); + } + + /** + * Tests a task without a specific display category exist in the system and launches activity + * with display category into the task within the inTask attribute. Make sure the activity is + * not placed on the task since the display category is different. + */ + @Test + public void testLaunchDisplayCategoryActivityInTask() { + final Task inTask = new TaskBuilder(mSupervisor).build(); + inTask.inRecents = true; + + final ActivityStarter starter = prepareStarter(0, false); + final ActivityRecord target = new ActivityBuilder(mAtm).setRequiredDisplayCategory("auto") + .build(); + startActivityInner(starter, target, null /* source */, null /* options */, inTask, + null /* inTaskFragment */); + + assertNotEquals(inTask, target.getTask()); + } + private static void startActivityInner(ActivityStarter starter, ActivityRecord target, ActivityRecord source, ActivityOptions options, Task inTask, TaskFragment inTaskFragment) { diff --git a/services/tests/wmtests/src/com/android/server/wm/BackNavigationControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/BackNavigationControllerTests.java index 3bce860b8720..1b77c95358ad 100644 --- a/services/tests/wmtests/src/com/android/server/wm/BackNavigationControllerTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/BackNavigationControllerTests.java @@ -20,24 +20,23 @@ import static android.content.pm.ApplicationInfo.PRIVATE_FLAG_EXT_ENABLE_ON_BACK import static android.view.WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW; import static android.window.BackNavigationInfo.typeToString; +import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn; + import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.annotation.NonNull; import android.annotation.Nullable; -import android.hardware.HardwareBuffer; import android.os.RemoteException; import android.platform.test.annotations.Presubmit; import android.view.WindowManager; @@ -48,7 +47,6 @@ import android.window.IOnBackInvokedCallback; import android.window.OnBackInvokedCallback; import android.window.OnBackInvokedCallbackInfo; import android.window.OnBackInvokedDispatcher; -import android.window.TaskSnapshot; import android.window.WindowOnBackInvokedDispatcher; import com.android.server.LocalServices; @@ -67,6 +65,7 @@ public class BackNavigationControllerTests extends WindowTestsBase { private BackNavigationController mBackNavigationController; private WindowManagerInternal mWindowManagerInternal; private BackAnimationAdapter mBackAnimationAdapter; + private Task mRootHomeTask; @Before public void setUp() throws Exception { @@ -76,6 +75,7 @@ public class BackNavigationControllerTests extends WindowTestsBase { LocalServices.addService(WindowManagerInternal.class, mWindowManagerInternal); mBackNavigationController.setWindowManager(mWm); mBackAnimationAdapter = mock(BackAnimationAdapter.class); + mRootHomeTask = initHomeActivity(); } @Test @@ -101,7 +101,8 @@ public class BackNavigationControllerTests extends WindowTestsBase { ActivityRecord recordA = createActivityRecord(taskA); Mockito.doNothing().when(recordA).reparentSurfaceControl(any(), any()); - withSystemCallback(createTopTaskWithActivity()); + final Task topTask = createTopTaskWithActivity(); + withSystemCallback(topTask); BackNavigationInfo backNavigationInfo = startBackNavigation(); assertWithMessage("BackNavigationInfo").that(backNavigationInfo).isNotNull(); assertThat(typeToString(backNavigationInfo.getType())) @@ -111,6 +112,20 @@ public class BackNavigationControllerTests extends WindowTestsBase { verify(mBackNavigationController).scheduleAnimationLocked( eq(BackNavigationInfo.TYPE_CROSS_TASK), any(), eq(mBackAnimationAdapter), any()); + + // reset drawning status + topTask.forAllWindows(w -> { + makeWindowVisibleAndDrawn(w); + }, true); + setupKeyguardOccluded(); + backNavigationInfo = startBackNavigation(); + assertThat(typeToString(backNavigationInfo.getType())) + .isEqualTo(typeToString(BackNavigationInfo.TYPE_CALLBACK)); + + doReturn(true).when(recordA).canShowWhenLocked(); + backNavigationInfo = startBackNavigation(); + assertThat(typeToString(backNavigationInfo.getType())) + .isEqualTo(typeToString(BackNavigationInfo.TYPE_CROSS_TASK)); } @Test @@ -137,6 +152,20 @@ public class BackNavigationControllerTests extends WindowTestsBase { assertThat(backNavigationInfo.getOnBackInvokedCallback()).isEqualTo(callback); assertThat(typeToString(backNavigationInfo.getType())) .isEqualTo(typeToString(BackNavigationInfo.TYPE_CROSS_ACTIVITY)); + + // reset drawing status + testCase.recordFront.forAllWindows(w -> { + makeWindowVisibleAndDrawn(w); + }, true); + setupKeyguardOccluded(); + backNavigationInfo = startBackNavigation(); + assertThat(typeToString(backNavigationInfo.getType())) + .isEqualTo(typeToString(BackNavigationInfo.TYPE_CALLBACK)); + + doReturn(true).when(testCase.recordBack).canShowWhenLocked(); + backNavigationInfo = startBackNavigation(); + assertThat(typeToString(backNavigationInfo.getType())) + .isEqualTo(typeToString(BackNavigationInfo.TYPE_CROSS_ACTIVITY)); } @Test @@ -164,12 +193,17 @@ public class BackNavigationControllerTests extends WindowTestsBase { @Test public void preparesForBackToHome() { - Task task = createTopTaskWithActivity(); - withSystemCallback(task); + final Task topTask = createTopTaskWithActivity(); + withSystemCallback(topTask); BackNavigationInfo backNavigationInfo = startBackNavigation(); assertThat(typeToString(backNavigationInfo.getType())) .isEqualTo(typeToString(BackNavigationInfo.TYPE_RETURN_TO_HOME)); + + setupKeyguardOccluded(); + backNavigationInfo = startBackNavigation(); + assertThat(typeToString(backNavigationInfo.getType())) + .isEqualTo(typeToString(BackNavigationInfo.TYPE_CALLBACK)); } @Test @@ -302,14 +336,22 @@ public class BackNavigationControllerTests extends WindowTestsBase { }; } - @NonNull - private TaskSnapshotController createMockTaskSnapshotController() { - TaskSnapshotController taskSnapshotController = mock(TaskSnapshotController.class); - TaskSnapshot taskSnapshot = mock(TaskSnapshot.class); - when(taskSnapshot.getHardwareBuffer()).thenReturn(mock(HardwareBuffer.class)); - when(taskSnapshotController.getSnapshot(anyInt(), anyInt(), anyBoolean(), anyBoolean())) - .thenReturn(taskSnapshot); - return taskSnapshotController; + private Task initHomeActivity() { + final Task task = mDisplayContent.getDefaultTaskDisplayArea().getRootHomeTask(); + task.forAllLeafTasks((t) -> { + if (t.getTopMostActivity() == null) { + final ActivityRecord r = createActivityRecord(t); + Mockito.doNothing().when(t).reparentSurfaceControl(any(), any()); + Mockito.doNothing().when(r).reparentSurfaceControl(any(), any()); + } + }, true); + return task; + } + + private void setupKeyguardOccluded() { + final KeyguardController kc = mRootHomeTask.mTaskSupervisor.getKeyguardController(); + doReturn(true).when(kc).isKeyguardLocked(anyInt()); + doReturn(true).when(kc).isDisplayOccluded(anyInt()); } @NonNull diff --git a/services/tests/wmtests/src/com/android/server/wm/InsetsPolicyTest.java b/services/tests/wmtests/src/com/android/server/wm/InsetsPolicyTest.java index fd2a1d1c352f..c7971bc7911f 100644 --- a/services/tests/wmtests/src/com/android/server/wm/InsetsPolicyTest.java +++ b/services/tests/wmtests/src/com/android/server/wm/InsetsPolicyTest.java @@ -37,6 +37,8 @@ import static android.view.WindowManager.LayoutParams.TYPE_NOTIFICATION_SHADE; import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR; import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL; +import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -46,7 +48,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import android.app.StatusBarManager; @@ -265,7 +266,8 @@ public class InsetsPolicyTest extends WindowTestsBase { final WindowState navBar = addNavigationBar(); navBar.setHasSurface(true); navBar.getControllableInsetProvider().setServerVisible(true); - final InsetsPolicy policy = spy(mDisplayContent.getInsetsPolicy()); + final InsetsPolicy policy = mDisplayContent.getInsetsPolicy(); + spyOn(policy); doNothing().when(policy).startAnimation(anyBoolean(), any()); // Make both system bars invisible. @@ -302,12 +304,15 @@ public class InsetsPolicyTest extends WindowTestsBase { addStatusBar().getControllableInsetProvider().getSource().setVisible(false); addNavigationBar().getControllableInsetProvider().setServerVisible(true); - final InsetsPolicy policy = spy(mDisplayContent.getInsetsPolicy()); + final InsetsPolicy policy = mDisplayContent.getInsetsPolicy(); + spyOn(policy); doNothing().when(policy).startAnimation(anyBoolean(), any()); policy.updateBarControlTarget(mAppWindow); policy.showTransient(new int[]{ITYPE_STATUS_BAR, ITYPE_NAVIGATION_BAR}, true /* isGestureOnSystemBar */); waitUntilWindowAnimatorIdle(); + assertTrue(policy.isTransient(ITYPE_STATUS_BAR)); + assertFalse(policy.isTransient(ITYPE_NAVIGATION_BAR)); final InsetsSourceControl[] controls = mDisplayContent.getInsetsStateController().getControlsForDispatch(mAppWindow); @@ -335,7 +340,8 @@ public class InsetsPolicyTest extends WindowTestsBase { navBarSource.setVisible(false); mAppWindow.mAboveInsetsState.addSource(navBarSource); mAppWindow.mAboveInsetsState.addSource(statusBarSource); - final InsetsPolicy policy = spy(mDisplayContent.getInsetsPolicy()); + final InsetsPolicy policy = mDisplayContent.getInsetsPolicy(); + spyOn(policy); doNothing().when(policy).startAnimation(anyBoolean(), any()); policy.updateBarControlTarget(mAppWindow); policy.showTransient(new int[]{ITYPE_STATUS_BAR, ITYPE_NAVIGATION_BAR}, @@ -383,7 +389,8 @@ public class InsetsPolicyTest extends WindowTestsBase { final WindowState app = addWindow(TYPE_APPLICATION, "app"); final WindowState app2 = addWindow(TYPE_APPLICATION, "app"); - final InsetsPolicy policy = spy(mDisplayContent.getInsetsPolicy()); + final InsetsPolicy policy = mDisplayContent.getInsetsPolicy(); + spyOn(policy); doNothing().when(policy).startAnimation(anyBoolean(), any()); policy.updateBarControlTarget(app); policy.showTransient(new int[]{ITYPE_STATUS_BAR, ITYPE_NAVIGATION_BAR}, 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 834302e82507..d5c15794cc28 100644 --- a/services/tests/wmtests/src/com/android/server/wm/TaskFragmentOrganizerControllerTest.java +++ b/services/tests/wmtests/src/com/android/server/wm/TaskFragmentOrganizerControllerTest.java @@ -19,9 +19,16 @@ package com.android.server.wm; import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD; import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED; import static android.view.Display.DEFAULT_DISPLAY; +import static android.view.WindowManager.TRANSIT_CHANGE; +import static android.view.WindowManager.TRANSIT_CLOSE; +import static android.view.WindowManager.TRANSIT_NONE; +import static android.view.WindowManager.TRANSIT_OPEN; import static android.window.TaskFragmentOrganizer.KEY_ERROR_CALLBACK_OP_TYPE; import static android.window.TaskFragmentOrganizer.KEY_ERROR_CALLBACK_THROWABLE; -import static android.window.TaskFragmentOrganizer.getTransitionType; +import static android.window.TaskFragmentOrganizer.TASK_FRAGMENT_TRANSIT_CHANGE; +import static android.window.TaskFragmentOrganizer.TASK_FRAGMENT_TRANSIT_CLOSE; +import static android.window.TaskFragmentOrganizer.TASK_FRAGMENT_TRANSIT_NONE; +import static android.window.TaskFragmentOrganizer.TASK_FRAGMENT_TRANSIT_OPEN; import static android.window.TaskFragmentTransaction.TYPE_ACTIVITY_REPARENTED_TO_TASK; import static android.window.TaskFragmentTransaction.TYPE_TASK_FRAGMENT_APPEARED; import static android.window.TaskFragmentTransaction.TYPE_TASK_FRAGMENT_ERROR; @@ -358,7 +365,6 @@ public class TaskFragmentOrganizerControllerTest extends WindowTestsBase { assertActivityReparentedToTaskTransaction(task.mTaskId, activity.intent, activity.token); // Notify organizer if there is any embedded in the Task. - clearInvocations(mOrganizer); final TaskFragment taskFragment = new TaskFragmentBuilder(mAtm) .setParentTask(task) .setOrganizer(mOrganizer) @@ -367,11 +373,14 @@ public class TaskFragmentOrganizerControllerTest extends WindowTestsBase { DEFAULT_TASK_FRAGMENT_ORGANIZER_PROCESS_NAME); activity.reparent(taskFragment, POSITION_TOP); activity.mLastTaskFragmentOrganizerBeforePip = null; + + // Clear invocations now because there will be another transaction for the TaskFragment + // change above, triggered by the reparent. We only want to test onActivityReparentedToTask + // here. + clearInvocations(mOrganizer); mController.onActivityReparentedToTask(activity); mController.dispatchPendingEvents(); - // There will not be TaskFragmentParentInfoChanged because Task visible request is changed - // before the organized TaskFragment is added to the Task. assertActivityReparentedToTaskTransaction(task.mTaskId, activity.intent, activity.token); } @@ -553,10 +562,9 @@ public class TaskFragmentOrganizerControllerTest extends WindowTestsBase { @Test public void testApplyTransaction_enforceHierarchyChange_createTaskFragment() { final ActivityRecord ownerActivity = createActivityRecord(mDisplayContent); - final IBinder fragmentToken = new Binder(); // Allow organizer to create TaskFragment and start/reparent activity to TaskFragment. - createTaskFragmentFromOrganizer(mTransaction, ownerActivity, fragmentToken); + createTaskFragmentFromOrganizer(mTransaction, ownerActivity, mFragmentToken); mTransaction.startActivityInTaskFragment( mFragmentToken, null /* callerToken */, new Intent(), null /* activityOptions */); mTransaction.reparentActivityToTaskFragment(mFragmentToken, mock(IBinder.class)); @@ -565,7 +573,8 @@ public class TaskFragmentOrganizerControllerTest extends WindowTestsBase { assertApplyTransactionAllowed(mTransaction); // Successfully created a TaskFragment. - final TaskFragment taskFragment = mWindowOrganizerController.getTaskFragment(fragmentToken); + final TaskFragment taskFragment = mWindowOrganizerController.getTaskFragment( + mFragmentToken); assertNotNull(taskFragment); assertEquals(ownerActivity.getTask(), taskFragment.getTask()); } @@ -581,7 +590,8 @@ public class TaskFragmentOrganizerControllerTest extends WindowTestsBase { mWindowOrganizerController.mLaunchTaskFragments.put(mFragmentToken, mTaskFragment); mTransaction.startActivityInTaskFragment( mFragmentToken, ownerActivity.token, new Intent(), null /* activityOptions */); - mOrganizer.applyTransaction(mTransaction); + mOrganizer.applyTransaction(mTransaction, TASK_FRAGMENT_TRANSIT_OPEN, + false /* shouldApplyIndependently */); // Not allowed because TaskFragment is not organized by the caller organizer. assertApplyTransactionDisallowed(mTransaction); @@ -602,7 +612,8 @@ public class TaskFragmentOrganizerControllerTest extends WindowTestsBase { .build(); mWindowOrganizerController.mLaunchTaskFragments.put(mFragmentToken, mTaskFragment); mTransaction.reparentActivityToTaskFragment(mFragmentToken, activity.token); - mOrganizer.applyTransaction(mTransaction); + mOrganizer.applyTransaction(mTransaction, TASK_FRAGMENT_TRANSIT_CHANGE, + false /* shouldApplyIndependently */); // Not allowed because TaskFragment is not organized by the caller organizer. assertApplyTransactionDisallowed(mTransaction); @@ -628,7 +639,8 @@ public class TaskFragmentOrganizerControllerTest extends WindowTestsBase { .build(); mWindowOrganizerController.mLaunchTaskFragments.put(fragmentToken2, taskFragment2); mTransaction.setAdjacentTaskFragments(mFragmentToken, fragmentToken2, null /* params */); - mOrganizer.applyTransaction(mTransaction); + mOrganizer.applyTransaction(mTransaction, TASK_FRAGMENT_TRANSIT_CHANGE, + false /* shouldApplyIndependently */); // Not allowed because TaskFragments are not organized by the caller organizer. assertApplyTransactionDisallowed(mTransaction); @@ -661,7 +673,8 @@ public class TaskFragmentOrganizerControllerTest extends WindowTestsBase { .build(); mWindowOrganizerController.mLaunchTaskFragments.put(mFragmentToken, mTaskFragment); mTransaction.requestFocusOnTaskFragment(mFragmentToken); - mOrganizer.applyTransaction(mTransaction); + mOrganizer.applyTransaction(mTransaction, TASK_FRAGMENT_TRANSIT_CHANGE, + false /* shouldApplyIndependently */); // Not allowed because TaskFragment is not organized by the caller organizer. assertApplyTransactionDisallowed(mTransaction); @@ -704,6 +717,40 @@ public class TaskFragmentOrganizerControllerTest extends WindowTestsBase { } @Test + public void testApplyTransaction_createTaskFragment_withPairedPrimaryFragmentToken() { + final Task task = createTask(mDisplayContent); + mTaskFragment = new TaskFragmentBuilder(mAtm) + .setParentTask(task) + .setFragmentToken(mFragmentToken) + .createActivityCount(1) + .build(); + mWindowOrganizerController.mLaunchTaskFragments.put(mFragmentToken, mTaskFragment); + final ActivityRecord activityOnTop = createActivityRecord(task); + final int uid = Binder.getCallingUid(); + activityOnTop.info.applicationInfo.uid = uid; + activityOnTop.getTask().effectiveUid = uid; + final IBinder fragmentToken1 = new Binder(); + final TaskFragmentCreationParams params = new TaskFragmentCreationParams.Builder( + mOrganizerToken, fragmentToken1, activityOnTop.token) + .setPairedPrimaryFragmentToken(mFragmentToken) + .build(); + mTransaction.setTaskFragmentOrganizer(mIOrganizer); + mTransaction.createTaskFragment(params); + assertApplyTransactionAllowed(mTransaction); + + // Successfully created a TaskFragment. + final TaskFragment taskFragment = mWindowOrganizerController.getTaskFragment( + fragmentToken1); + assertNotNull(taskFragment); + // The new TaskFragment should be positioned right above the paired TaskFragment. + assertEquals(task.mChildren.indexOf(mTaskFragment) + 1, + task.mChildren.indexOf(taskFragment)); + // The top activity should remain on top. + assertEquals(task.mChildren.indexOf(taskFragment) + 1, + task.mChildren.indexOf(activityOnTop)); + } + + @Test public void testApplyTransaction_enforceHierarchyChange_reparentChildren() { doReturn(true).when(mTaskFragment).isAttached(); @@ -729,7 +776,8 @@ public class TaskFragmentOrganizerControllerTest extends WindowTestsBase { final ActivityRecord activity = createActivityRecord(task); // Skip manipulate the SurfaceControl. doNothing().when(activity).setDropInputMode(anyInt()); - mOrganizer.applyTransaction(mTransaction); + mOrganizer.applyTransaction(mTransaction, TASK_FRAGMENT_TRANSIT_CHANGE, + false /* shouldApplyIndependently */); mTaskFragment = new TaskFragmentBuilder(mAtm) .setParentTask(task) .setFragmentToken(mFragmentToken) @@ -830,8 +878,8 @@ public class TaskFragmentOrganizerControllerTest extends WindowTestsBase { // Allow organizer to create TaskFragment and start/reparent activity to TaskFragment. createTaskFragmentFromOrganizer(mTransaction, ownerActivity, fragmentToken); - mController.onTransactionHandled(new Binder(), mTransaction, - getTransitionType(mTransaction), false /* shouldApplyIndependently */); + mController.onTransactionHandled(new Binder(), mTransaction, TASK_FRAGMENT_TRANSIT_CHANGE, + false /* shouldApplyIndependently */); // Nothing should happen as the organizer is not registered. assertNull(mWindowOrganizerController.getTaskFragment(fragmentToken)); @@ -1379,12 +1427,31 @@ public class TaskFragmentOrganizerControllerTest extends WindowTestsBase { final IBinder transactionToken = tokenCaptor.getValue(); final WindowContainerTransaction wct = wctCaptor.getValue(); wct.setTaskFragmentOrganizer(mIOrganizer); - mController.onTransactionHandled(transactionToken, wct, getTransitionType(wct), + mController.onTransactionHandled(transactionToken, wct, TASK_FRAGMENT_TRANSIT_CHANGE, false /* shouldApplyIndependently */); verify(mTransitionController).continueTransitionReady(); } + @Test + public void testWindowOrganizerApplyTransaction_throwException() { + // Not allow to use #applyTransaction(WindowContainerTransaction). + assertThrows(RuntimeException.class, () -> mOrganizer.applyTransaction(mTransaction)); + + // Allow to use the overload method. + mOrganizer.applyTransaction(mTransaction, TASK_FRAGMENT_TRANSIT_CHANGE, + false /* shouldApplyIndependently */); + } + + @Test + public void testTaskFragmentTransitionType() { + // 1-1 relationship with WindowManager.TransitionType + assertEquals(TRANSIT_NONE, TASK_FRAGMENT_TRANSIT_NONE); + assertEquals(TRANSIT_OPEN, TASK_FRAGMENT_TRANSIT_OPEN); + assertEquals(TRANSIT_CLOSE, TASK_FRAGMENT_TRANSIT_CLOSE); + assertEquals(TRANSIT_CHANGE, TASK_FRAGMENT_TRANSIT_CHANGE); + } + /** * Creates a {@link TaskFragment} with the {@link WindowContainerTransaction}. Calls * {@link WindowOrganizerController#applyTransaction(WindowContainerTransaction)} to apply the @@ -1406,13 +1473,14 @@ public class TaskFragmentOrganizerControllerTest extends WindowTestsBase { /** Asserts that applying the given transaction will throw a {@link SecurityException}. */ private void assertApplyTransactionDisallowed(WindowContainerTransaction t) { assertThrows(SecurityException.class, () -> - mController.applyTransaction(t, getTransitionType(t), + mController.applyTransaction(t, TASK_FRAGMENT_TRANSIT_CHANGE, false /* shouldApplyIndependently */)); } /** Asserts that applying the given transaction will not throw any exception. */ private void assertApplyTransactionAllowed(WindowContainerTransaction t) { - mController.applyTransaction(t, getTransitionType(t), false /* shouldApplyIndependently */); + mController.applyTransaction(t, TASK_FRAGMENT_TRANSIT_CHANGE, + false /* shouldApplyIndependently */); } /** Asserts that there will be a transaction for TaskFragment appeared. */ diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskFragmentTest.java b/services/tests/wmtests/src/com/android/server/wm/TaskFragmentTest.java index 8fda1917d0b5..8ac7ceb7c3ac 100644 --- a/services/tests/wmtests/src/com/android/server/wm/TaskFragmentTest.java +++ b/services/tests/wmtests/src/com/android/server/wm/TaskFragmentTest.java @@ -107,18 +107,49 @@ public class TaskFragmentTest extends WindowTestsBase { } @Test + public void testShouldStartChangeTransition_relativePositionChange() { + mockSurfaceFreezerSnapshot(mTaskFragment.mSurfaceFreezer); + final Rect startBounds = new Rect(0, 0, 500, 1000); + final Rect endBounds = new Rect(500, 0, 1000, 1000); + mTaskFragment.setBounds(startBounds); + mTaskFragment.updateRelativeEmbeddedBounds(); + doReturn(true).when(mTaskFragment).isVisible(); + doReturn(true).when(mTaskFragment).isVisibleRequested(); + + // Do not resize, just change the relative position. + final Rect relStartBounds = new Rect(mTaskFragment.getRelativeEmbeddedBounds()); + mTaskFragment.setBounds(endBounds); + mTaskFragment.updateRelativeEmbeddedBounds(); + spyOn(mDisplayContent.mTransitionController); + + // For Shell transition, we don't want to take snapshot when the bounds are not resized + doReturn(true).when(mDisplayContent.mTransitionController) + .isShellTransitionsEnabled(); + assertFalse(mTaskFragment.shouldStartChangeTransition(startBounds, relStartBounds)); + + // For legacy transition, we want to request a change transition even if it is just relative + // bounds change. + doReturn(false).when(mDisplayContent.mTransitionController) + .isShellTransitionsEnabled(); + assertTrue(mTaskFragment.shouldStartChangeTransition(startBounds, relStartBounds)); + } + + @Test public void testStartChangeTransition_resetSurface() { mockSurfaceFreezerSnapshot(mTaskFragment.mSurfaceFreezer); final Rect startBounds = new Rect(0, 0, 1000, 1000); final Rect endBounds = new Rect(500, 500, 1000, 1000); mTaskFragment.setBounds(startBounds); + mTaskFragment.updateRelativeEmbeddedBounds(); doReturn(true).when(mTaskFragment).isVisible(); doReturn(true).when(mTaskFragment).isVisibleRequested(); clearInvocations(mTransaction); + final Rect relStartBounds = new Rect(mTaskFragment.getRelativeEmbeddedBounds()); mTaskFragment.deferOrganizedTaskFragmentSurfaceUpdate(); mTaskFragment.setBounds(endBounds); - assertTrue(mTaskFragment.shouldStartChangeTransition(startBounds)); + mTaskFragment.updateRelativeEmbeddedBounds(); + assertTrue(mTaskFragment.shouldStartChangeTransition(startBounds, relStartBounds)); mTaskFragment.initializeChangeTransition(startBounds); mTaskFragment.continueOrganizedTaskFragmentSurfaceUpdate(); @@ -157,17 +188,20 @@ public class TaskFragmentTest extends WindowTestsBase { final Rect startBounds = new Rect(0, 0, 1000, 1000); final Rect endBounds = new Rect(500, 500, 1000, 1000); mTaskFragment.setBounds(startBounds); + mTaskFragment.updateRelativeEmbeddedBounds(); doReturn(true).when(mTaskFragment).isVisible(); doReturn(true).when(mTaskFragment).isVisibleRequested(); + final Rect relStartBounds = new Rect(mTaskFragment.getRelativeEmbeddedBounds()); final DisplayPolicy displayPolicy = mDisplayContent.getDisplayPolicy(); displayPolicy.screenTurnedOff(); assertFalse(mTaskFragment.okToAnimate()); mTaskFragment.setBounds(endBounds); + mTaskFragment.updateRelativeEmbeddedBounds(); - assertFalse(mTaskFragment.shouldStartChangeTransition(startBounds)); + assertFalse(mTaskFragment.shouldStartChangeTransition(startBounds, relStartBounds)); } /** @@ -540,8 +574,8 @@ public class TaskFragmentTest extends WindowTestsBase { tf1.setBounds(600, 0, 1200, 1000); final ActivityRecord activity0 = tf0.getTopMostActivity(); final ActivityRecord activity1 = tf1.getTopMostActivity(); - doReturn(true).when(activity0).isVisibleRequested(); - doReturn(true).when(activity1).isVisibleRequested(); + activity0.setVisibleRequested(true); + activity1.setVisibleRequested(true); assertEquals(SCREEN_ORIENTATION_UNSPECIFIED, tf0.getOrientation(SCREEN_ORIENTATION_UNSET)); assertEquals(SCREEN_ORIENTATION_UNSPECIFIED, tf1.getOrientation(SCREEN_ORIENTATION_UNSET)); diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskTests.java index 74d78842c7ac..19e3246cf02c 100644 --- a/services/tests/wmtests/src/com/android/server/wm/TaskTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/TaskTests.java @@ -1493,7 +1493,6 @@ public class TaskTests extends WindowTestsBase { public void testReorderActivityToFront() { final TaskFragmentOrganizer organizer = new TaskFragmentOrganizer(Runnable::run); final Task task = new TaskBuilder(mSupervisor).setCreateActivity(true).build(); - doNothing().when(task).onActivityVisibleRequestedChanged(); final ActivityRecord activity = task.getTopMostActivity(); final TaskFragment fragment = createTaskFragmentWithEmbeddedActivity(task, organizer); diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowContainerTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowContainerTests.java index 50fcafca5273..98a28cfbe22c 100644 --- a/services/tests/wmtests/src/com/android/server/wm/WindowContainerTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/WindowContainerTests.java @@ -869,6 +869,28 @@ public class WindowContainerTests extends WindowTestsBase { } @Test + public void testOnDisplayChanged_cleanupChanging() { + final Task task = createTask(mDisplayContent); + spyOn(task.mSurfaceFreezer); + mDisplayContent.mChangingContainers.add(task); + + // Don't remove the changing transition of this window when it is still the old display. + // This happens on display info changed. + task.onDisplayChanged(mDisplayContent); + + assertTrue(mDisplayContent.mChangingContainers.contains(task)); + verify(task.mSurfaceFreezer, never()).unfreeze(any()); + + // Remove the changing transition of this window when it is moved or reparented from the old + // display. + final DisplayContent newDc = createNewDisplay(); + task.onDisplayChanged(newDc); + + assertFalse(mDisplayContent.mChangingContainers.contains(task)); + verify(task.mSurfaceFreezer).unfreeze(any()); + } + + @Test public void testHandleCompleteDeferredRemoval() { final DisplayContent displayContent = createNewDisplay(); // Do not reparent activity to default display when removing the display. diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java index 435c39c94dc8..69e3244af1b6 100644 --- a/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/WindowStateTests.java @@ -413,6 +413,16 @@ public class WindowStateTests extends WindowTestsBase { } @Test + public void testCanAffectSystemUiFlags_starting() { + final WindowState app = createWindow(null, TYPE_APPLICATION_STARTING, "app"); + app.mActivityRecord.setVisible(true); + app.mStartingData = new SnapshotStartingData(mWm, null, 0); + assertFalse(app.canAffectSystemUiFlags()); + app.mStartingData = new SplashScreenStartingData(mWm, 0, 0); + assertTrue(app.canAffectSystemUiFlags()); + } + + @Test public void testCanAffectSystemUiFlags_disallow() { final WindowState app = createWindow(null, TYPE_APPLICATION, "app"); app.mActivityRecord.setVisible(true); 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 019b14db161c..4d3141438607 100644 --- a/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java +++ b/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java @@ -1017,6 +1017,7 @@ class WindowTestsBase extends SystemServiceTestsBase { private ActivityInfo.WindowLayout mWindowLayout; private boolean mVisible = true; private ActivityOptions mLaunchIntoPipOpts; + private String mRequiredDisplayCategory; ActivityBuilder(ActivityTaskManagerService service) { mService = service; @@ -1157,6 +1158,11 @@ class WindowTestsBase extends SystemServiceTestsBase { return this; } + ActivityBuilder setRequiredDisplayCategory(String requiredDisplayCategory) { + mRequiredDisplayCategory = requiredDisplayCategory; + return this; + } + ActivityRecord build() { SystemServicesTestRule.checkHoldsLock(mService.mGlobalLock); try { @@ -1201,6 +1207,9 @@ class WindowTestsBase extends SystemServiceTestsBase { aInfo.configChanges |= mConfigChanges; aInfo.taskAffinity = mAffinity; aInfo.windowLayout = mWindowLayout; + if (mRequiredDisplayCategory != null) { + aInfo.requiredDisplayCategory = mRequiredDisplayCategory; + } if (mCreateTask) { mTask = new TaskBuilder(mService.mTaskSupervisor) diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/DspTrustedHotwordDetectorSession.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/DspTrustedHotwordDetectorSession.java new file mode 100644 index 000000000000..2812264e989c --- /dev/null +++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/DspTrustedHotwordDetectorSession.java @@ -0,0 +1,254 @@ +/* + * 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.voiceinteraction; + +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_ERROR_EXCEPTION; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_PROCESS_RESTARTED_EXCEPTION; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_REJECTED_EXCEPTION; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECTED; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECT_TIMEOUT; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECTED; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECTED_FROM_RESTART; + +import android.annotation.NonNull; +import android.content.Context; +import android.hardware.soundtrigger.SoundTrigger; +import android.media.permission.Identity; +import android.os.PersistableBundle; +import android.os.RemoteException; +import android.os.SharedMemory; +import android.service.voice.AlwaysOnHotwordDetector; +import android.service.voice.HotwordDetectedResult; +import android.service.voice.HotwordDetectionService; +import android.service.voice.HotwordDetector; +import android.service.voice.HotwordRejectedResult; +import android.service.voice.IDspHotwordDetectionCallback; +import android.util.Slog; + +import com.android.internal.annotations.GuardedBy; +import com.android.internal.app.IHotwordRecognitionStatusCallback; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Locale; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * A class that provides Dsp trusted hotword detector to communicate with the {@link + * HotwordDetectionService}. + * + * This class can handle the hotword detection which detector is created by using + * {@link android.service.voice.VoiceInteractionService#createAlwaysOnHotwordDetector(String, + * Locale, PersistableBundle, SharedMemory, AlwaysOnHotwordDetector.Callback)}. + */ +final class DspTrustedHotwordDetectorSession extends HotwordDetectorSession { + private static final String TAG = "DspTrustedHotwordDetectorSession"; + + // The validation timeout value is 3 seconds for onDetect of DSP trigger event. + private static final long VALIDATION_TIMEOUT_MILLIS = 3000; + // Write the onDetect timeout metric when it takes more time than MAX_VALIDATION_TIMEOUT_MILLIS. + private static final long MAX_VALIDATION_TIMEOUT_MILLIS = 4000; + + @GuardedBy("mLock") + private ScheduledFuture<?> mCancellationKeyPhraseDetectionFuture; + + @GuardedBy("mLock") + private boolean mValidatingDspTrigger = false; + + DspTrustedHotwordDetectorSession( + @NonNull HotwordDetectionConnection.ServiceConnection remoteHotwordDetectionService, + @NonNull Object lock, @NonNull Context context, + @NonNull IHotwordRecognitionStatusCallback callback, int voiceInteractionServiceUid, + Identity voiceInteractorIdentity, + @NonNull ScheduledExecutorService scheduledExecutorService, boolean logging) { + super(remoteHotwordDetectionService, lock, context, callback, voiceInteractionServiceUid, + voiceInteractorIdentity, scheduledExecutorService, logging); + } + + @SuppressWarnings("GuardedBy") + void detectFromDspSourceLocked(SoundTrigger.KeyphraseRecognitionEvent recognitionEvent, + IHotwordRecognitionStatusCallback externalCallback) { + if (DEBUG) { + Slog.d(TAG, "detectFromDspSourceLocked"); + } + + AtomicBoolean timeoutDetected = new AtomicBoolean(false); + // TODO: consider making this a non-anonymous class. + IDspHotwordDetectionCallback internalCallback = new IDspHotwordDetectionCallback.Stub() { + @Override + public void onDetected(HotwordDetectedResult result) throws RemoteException { + if (DEBUG) { + Slog.d(TAG, "onDetected"); + } + synchronized (mLock) { + if (mCancellationKeyPhraseDetectionFuture != null) { + mCancellationKeyPhraseDetectionFuture.cancel(true); + } + if (timeoutDetected.get()) { + return; + } + HotwordMetricsLogger.writeKeyphraseTriggerEvent( + HotwordDetector.DETECTOR_TYPE_TRUSTED_HOTWORD_DSP, + HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECTED); + if (!mValidatingDspTrigger) { + Slog.i(TAG, "Ignoring #onDetected due to a process restart"); + HotwordMetricsLogger.writeKeyphraseTriggerEvent( + HotwordDetector.DETECTOR_TYPE_TRUSTED_HOTWORD_DSP, + METRICS_KEYPHRASE_TRIGGERED_DETECT_UNEXPECTED_CALLBACK); + return; + } + mValidatingDspTrigger = false; + try { + enforcePermissionsForDataDelivery(); + enforceExtraKeyphraseIdNotLeaked(result, recognitionEvent); + } catch (SecurityException e) { + Slog.i(TAG, "Ignoring #onDetected due to a SecurityException", e); + HotwordMetricsLogger.writeKeyphraseTriggerEvent( + HotwordDetector.DETECTOR_TYPE_TRUSTED_HOTWORD_DSP, + METRICS_KEYPHRASE_TRIGGERED_DETECT_SECURITY_EXCEPTION); + externalCallback.onError(CALLBACK_ONDETECTED_GOT_SECURITY_EXCEPTION); + return; + } + saveProximityValueToBundle(result); + HotwordDetectedResult newResult; + try { + newResult = mHotwordAudioStreamCopier.startCopyingAudioStreams(result); + } catch (IOException e) { + externalCallback.onError(CALLBACK_ONDETECTED_STREAM_COPY_ERROR); + return; + } + externalCallback.onKeyphraseDetected(recognitionEvent, newResult); + Slog.i(TAG, "Egressed " + HotwordDetectedResult.getUsageSize(newResult) + + " bits from hotword trusted process"); + if (mDebugHotwordLogging) { + Slog.i(TAG, "Egressed detected result: " + newResult); + } + } + } + + @Override + public void onRejected(HotwordRejectedResult result) throws RemoteException { + if (DEBUG) { + Slog.d(TAG, "onRejected"); + } + synchronized (mLock) { + if (mCancellationKeyPhraseDetectionFuture != null) { + mCancellationKeyPhraseDetectionFuture.cancel(true); + } + if (timeoutDetected.get()) { + return; + } + HotwordMetricsLogger.writeKeyphraseTriggerEvent( + HotwordDetector.DETECTOR_TYPE_TRUSTED_HOTWORD_DSP, + HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECTED); + if (!mValidatingDspTrigger) { + Slog.i(TAG, "Ignoring #onRejected due to a process restart"); + HotwordMetricsLogger.writeKeyphraseTriggerEvent( + HotwordDetector.DETECTOR_TYPE_TRUSTED_HOTWORD_DSP, + METRICS_KEYPHRASE_TRIGGERED_REJECT_UNEXPECTED_CALLBACK); + return; + } + mValidatingDspTrigger = false; + externalCallback.onRejected(result); + if (mDebugHotwordLogging && result != null) { + Slog.i(TAG, "Egressed rejected result: " + result); + } + } + } + }; + + mValidatingDspTrigger = true; + mRemoteHotwordDetectionService.run(service -> { + // We use the VALIDATION_TIMEOUT_MILLIS to inform that the client needs to invoke + // the callback before timeout value. In order to reduce the latency impact between + // server side and client side, we need to use another timeout value + // MAX_VALIDATION_TIMEOUT_MILLIS to monitor it. + mCancellationKeyPhraseDetectionFuture = mScheduledExecutorService.schedule( + () -> { + // TODO: avoid allocate every time + timeoutDetected.set(true); + Slog.w(TAG, "Timed out on #detectFromDspSource"); + HotwordMetricsLogger.writeKeyphraseTriggerEvent( + HotwordDetector.DETECTOR_TYPE_TRUSTED_HOTWORD_DSP, + HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECT_TIMEOUT); + try { + externalCallback.onError(CALLBACK_DETECT_TIMEOUT); + } catch (RemoteException e) { + Slog.w(TAG, "Failed to report onError status: ", e); + HotwordMetricsLogger.writeDetectorEvent( + HotwordDetector.DETECTOR_TYPE_TRUSTED_HOTWORD_DSP, + HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_ERROR_EXCEPTION, + mVoiceInteractionServiceUid); + } + }, + MAX_VALIDATION_TIMEOUT_MILLIS, + TimeUnit.MILLISECONDS); + service.detectFromDspSource( + recognitionEvent, + recognitionEvent.getCaptureFormat(), + VALIDATION_TIMEOUT_MILLIS, + internalCallback); + }); + } + + @Override + @SuppressWarnings("GuardedBy") + void informRestartProcessLocked() { + // TODO(b/244598068): Check HotwordAudioStreamManager first + Slog.v(TAG, "informRestartProcessLocked"); + if (mValidatingDspTrigger) { + // We're restarting the process while it's processing a DSP trigger, so report a + // rejection. This also allows the Interactor to startRecognition again + try { + mCallback.onRejected(new HotwordRejectedResult.Builder().build()); + HotwordMetricsLogger.writeKeyphraseTriggerEvent( + HotwordDetector.DETECTOR_TYPE_TRUSTED_HOTWORD_DSP, + HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECTED_FROM_RESTART); + } catch (RemoteException e) { + Slog.w(TAG, "Failed to call #rejected"); + HotwordMetricsLogger.writeDetectorEvent( + HotwordDetector.DETECTOR_TYPE_TRUSTED_HOTWORD_DSP, + HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_REJECTED_EXCEPTION, + mVoiceInteractionServiceUid); + } + mValidatingDspTrigger = false; + } + mUpdateStateAfterStartFinished.set(false); + + try { + mCallback.onProcessRestarted(); + } catch (RemoteException e) { + Slog.w(TAG, "Failed to communicate #onProcessRestarted", e); + HotwordMetricsLogger.writeDetectorEvent( + HotwordDetector.DETECTOR_TYPE_TRUSTED_HOTWORD_DSP, + HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_PROCESS_RESTARTED_EXCEPTION, + mVoiceInteractionServiceUid); + } + + mPerformingExternalSourceHotwordDetection = false; + closeExternalAudioStreamLocked("process restarted"); + } + + @SuppressWarnings("GuardedBy") + public void dumpLocked(String prefix, PrintWriter pw) { + super.dumpLocked(prefix, pw); + pw.print(prefix); pw.print("mValidatingDspTrigger="); pw.println(mValidatingDspTrigger); + } +} diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java index 2ac25b65a082..2a4d4a15afdf 100644 --- a/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java +++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java @@ -16,67 +16,27 @@ package com.android.server.voiceinteraction; -import static android.Manifest.permission.CAPTURE_AUDIO_HOTWORD; -import static android.Manifest.permission.RECORD_AUDIO; -import static android.service.attention.AttentionService.PROXIMITY_UNKNOWN; -import static android.service.voice.HotwordDetectionService.AUDIO_SOURCE_EXTERNAL; -import static android.service.voice.HotwordDetectionService.AUDIO_SOURCE_MICROPHONE; -import static android.service.voice.HotwordDetectionService.ENABLE_PROXIMITY_RESULT; -import static android.service.voice.HotwordDetectionService.INITIALIZATION_STATUS_SUCCESS; -import static android.service.voice.HotwordDetectionService.INITIALIZATION_STATUS_UNKNOWN; -import static android.service.voice.HotwordDetectionService.KEY_INITIALIZATION_STATUS; - -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_ERROR; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_SUCCESS; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_UNKNOWN_NO_VALUE; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_UNKNOWN_OVER_MAX_CUSTOM_VALUE; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_UNKNOWN_TIMEOUT; import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTION_SERVICE_RESTARTED__REASON__AUDIO_SERVICE_DIED; import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTION_SERVICE_RESTARTED__REASON__SCHEDULE; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__APP_REQUEST_UPDATE_STATE; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_ERROR_EXCEPTION; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_PROCESS_RESTARTED_EXCEPTION; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_REJECTED_EXCEPTION; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_STATUS_REPORTED_EXCEPTION; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_UPDATE_STATE_AFTER_TIMEOUT; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__CALL_UPDATE_STATE_EXCEPTION; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__EXTERNAL_SOURCE_DETECTED; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__EXTERNAL_SOURCE_DETECT_SECURITY_EXCEPTION; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__EXTERNAL_SOURCE_REJECTED; import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__ON_CONNECTED; import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__ON_DISCONNECTED; import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__REQUEST_BIND_SERVICE; import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__REQUEST_BIND_SERVICE_FAIL; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__REQUEST_UPDATE_STATE; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__START_EXTERNAL_SOURCE_DETECTION; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__START_SOFTWARE_DETECTION; import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__DETECTOR_TYPE__NORMAL_DETECTOR; import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__DETECTOR_TYPE__TRUSTED_DETECTOR_DSP; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECTED; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECT_SECURITY_EXCEPTION; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECT_TIMEOUT; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECT_UNEXPECTED_CALLBACK; import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__KEYPHRASE_TRIGGER; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECTED; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECTED_FROM_RESTART; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECT_UNEXPECTED_CALLBACK; -import static com.android.server.voiceinteraction.SoundTriggerSessionPermissionsDecorator.enforcePermissionForPreflight; import android.annotation.NonNull; import android.annotation.Nullable; -import android.app.AppOpsManager; -import android.attention.AttentionManagerInternal; import android.content.ComponentName; import android.content.ContentCaptureOptions; import android.content.Context; import android.content.Intent; -import android.content.PermissionChecker; import android.hardware.soundtrigger.IRecognitionStatusCallback; import android.hardware.soundtrigger.SoundTrigger; import android.media.AudioFormat; import android.media.AudioManagerInternal; import android.media.permission.Identity; -import android.media.permission.PermissionUtil; import android.os.Binder; import android.os.Bundle; import android.os.IBinder; @@ -87,41 +47,27 @@ import android.os.RemoteException; import android.os.ServiceManager; import android.os.SharedMemory; import android.provider.DeviceConfig; -import android.service.voice.HotwordDetectedResult; import android.service.voice.HotwordDetectionService; import android.service.voice.HotwordDetector; -import android.service.voice.HotwordRejectedResult; -import android.service.voice.IDspHotwordDetectionCallback; import android.service.voice.IHotwordDetectionService; import android.service.voice.IMicrophoneHotwordDetectionVoiceInteractionCallback; import android.service.voice.VoiceInteractionManagerInternal.HotwordDetectionServiceIdentity; import android.speech.IRecognitionServiceManager; -import android.text.TextUtils; -import android.util.Pair; import android.util.Slog; import android.view.contentcapture.IContentCaptureManager; import com.android.internal.annotations.GuardedBy; import com.android.internal.app.IHotwordRecognitionStatusCallback; -import com.android.internal.infra.AndroidFuture; import com.android.internal.infra.ServiceConnector; import com.android.server.LocalServices; import com.android.server.pm.permission.PermissionManagerServiceInternal; -import java.io.Closeable; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; import java.io.PrintWriter; -import java.time.Duration; import java.time.Instant; -import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; /** @@ -132,63 +78,15 @@ final class HotwordDetectionConnection { static final boolean DEBUG = false; private static final String KEY_RESTART_PERIOD_IN_SECONDS = "restart_period_in_seconds"; - // TODO: These constants need to be refined. - // The validation timeout value is 3 seconds for onDetect of DSP trigger event. - private static final long VALIDATION_TIMEOUT_MILLIS = 3000; - // Write the onDetect timeout metric when it takes more time than MAX_VALIDATION_TIMEOUT_MILLIS. - private static final long MAX_VALIDATION_TIMEOUT_MILLIS = 4000; - private static final long MAX_UPDATE_TIMEOUT_MILLIS = 30000; - private static final long EXTERNAL_HOTWORD_CLEANUP_MILLIS = 2000; - private static final Duration MAX_UPDATE_TIMEOUT_DURATION = - Duration.ofMillis(MAX_UPDATE_TIMEOUT_MILLIS); private static final long RESET_DEBUG_HOTWORD_LOGGING_TIMEOUT_MILLIS = 60 * 60 * 1000; // 1 hour private static final int MAX_ISOLATED_PROCESS_NUMBER = 10; - // The error codes are used for onError callback - private static final int HOTWORD_DETECTION_SERVICE_DIED = -1; - private static final int CALLBACK_ONDETECTED_GOT_SECURITY_EXCEPTION = -2; - private static final int CALLBACK_DETECT_TIMEOUT = -3; - private static final int CALLBACK_ONDETECTED_STREAM_COPY_ERROR = -4; - - // Hotword metrics - private static final int METRICS_INIT_UNKNOWN_TIMEOUT = - HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_UNKNOWN_TIMEOUT; - private static final int METRICS_INIT_UNKNOWN_NO_VALUE = - HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_UNKNOWN_NO_VALUE; - private static final int METRICS_INIT_UNKNOWN_OVER_MAX_CUSTOM_VALUE = - HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_UNKNOWN_OVER_MAX_CUSTOM_VALUE; - private static final int METRICS_INIT_CALLBACK_STATE_ERROR = - HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_ERROR; - private static final int METRICS_INIT_CALLBACK_STATE_SUCCESS = - HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_SUCCESS; - - private static final int METRICS_KEYPHRASE_TRIGGERED_DETECT_SECURITY_EXCEPTION = - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECT_SECURITY_EXCEPTION; - private static final int METRICS_KEYPHRASE_TRIGGERED_DETECT_UNEXPECTED_CALLBACK = - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECT_UNEXPECTED_CALLBACK; - private static final int METRICS_KEYPHRASE_TRIGGERED_REJECT_UNEXPECTED_CALLBACK = - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECT_UNEXPECTED_CALLBACK; - - private static final int METRICS_EXTERNAL_SOURCE_DETECTED = - HOTWORD_DETECTOR_EVENTS__EVENT__EXTERNAL_SOURCE_DETECTED; - private static final int METRICS_EXTERNAL_SOURCE_REJECTED = - HOTWORD_DETECTOR_EVENTS__EVENT__EXTERNAL_SOURCE_REJECTED; - private static final int METRICS_EXTERNAL_SOURCE_DETECT_SECURITY_EXCEPTION = - HOTWORD_DETECTOR_EVENTS__EVENT__EXTERNAL_SOURCE_DETECT_SECURITY_EXCEPTION; - private static final int METRICS_CALLBACK_ON_STATUS_REPORTED_EXCEPTION = - HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_STATUS_REPORTED_EXCEPTION; - - private final Executor mAudioCopyExecutor = Executors.newCachedThreadPool(); // TODO: This may need to be a Handler(looper) private final ScheduledExecutorService mScheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); - private final AppOpsManager mAppOpsManager; - private final HotwordAudioStreamCopier mHotwordAudioStreamCopier; @Nullable private final ScheduledFuture<?> mCancellationTaskFuture; - private final AtomicBoolean mUpdateStateAfterStartFinished = new AtomicBoolean(false); private final IBinder.DeathRecipient mAudioServerDeathRecipient = this::audioServerDied; - private final @NonNull ServiceConnectionFactory mServiceConnectionFactory; - private final IHotwordRecognitionStatusCallback mCallback; + @NonNull private final ServiceConnectionFactory mServiceConnectionFactory; private final int mDetectorType; /** * Time after which each HotwordDetectionService process is stopped and replaced by a new one. @@ -201,35 +99,22 @@ final class HotwordDetectionConnection { final ComponentName mDetectionComponentName; final int mUser; final Context mContext; - - @Nullable AttentionManagerInternal mAttentionManagerInternal = null; - - final AttentionManagerInternal.ProximityUpdateCallbackInternal mProximityCallbackInternal = - this::setProximityValue; - - volatile HotwordDetectionServiceIdentity mIdentity; - private IMicrophoneHotwordDetectionVoiceInteractionCallback mSoftwareCallback; private Instant mLastRestartInstant; - private ScheduledFuture<?> mCancellationKeyPhraseDetectionFuture; private ScheduledFuture<?> mDebugHotwordLoggingTimeoutFuture = null; /** Identity used for attributing app ops when delivering data to the Interactor. */ @GuardedBy("mLock") @Nullable private final Identity mVoiceInteractorIdentity; - @GuardedBy("mLock") - private ParcelFileDescriptor mCurrentAudioSink; - @GuardedBy("mLock") - private boolean mValidatingDspTrigger = false; - @GuardedBy("mLock") - private boolean mPerformingSoftwareHotwordDetection; - private @NonNull ServiceConnection mRemoteHotwordDetectionService; + @NonNull private ServiceConnection mRemoteHotwordDetectionService; private IBinder mAudioFlinger; + @GuardedBy("mLock") private boolean mDebugHotwordLogging = false; + @GuardedBy("mLock") - private double mProximityMeters = PROXIMITY_UNKNOWN; + private final HotwordDetectorSession mHotwordDetectorSession; HotwordDetectionConnection(Object lock, Context context, int voiceInteractionServiceUid, Identity voiceInteractorIdentity, ComponentName serviceName, int userId, @@ -244,13 +129,8 @@ final class HotwordDetectionConnection { mContext = context; mVoiceInteractionServiceUid = voiceInteractionServiceUid; mVoiceInteractorIdentity = voiceInteractorIdentity; - mAppOpsManager = mContext.getSystemService(AppOpsManager.class); - mHotwordAudioStreamCopier = new HotwordAudioStreamCopier(mAppOpsManager, detectorType, - mVoiceInteractorIdentity.uid, mVoiceInteractorIdentity.packageName, - mVoiceInteractorIdentity.attributionTag); mDetectionComponentName = serviceName; mUser = userId; - mCallback = callback; mDetectorType = detectorType; mReStartPeriodSeconds = DeviceConfig.getInt(DeviceConfig.NAMESPACE_VOICE_INTERACTION, KEY_RESTART_PERIOD_IN_SECONDS, 0); @@ -259,17 +139,21 @@ final class HotwordDetectionConnection { initAudioFlingerLocked(); mServiceConnectionFactory = new ServiceConnectionFactory(intent, bindInstantServiceAllowed); - mRemoteHotwordDetectionService = mServiceConnectionFactory.createLocked(); - if (ENABLE_PROXIMITY_RESULT) { - mAttentionManagerInternal = LocalServices.getService(AttentionManagerInternal.class); - if (mAttentionManagerInternal != null) { - mAttentionManagerInternal.onStartProximityUpdates(mProximityCallbackInternal); - } - } - mLastRestartInstant = Instant.now(); - updateStateAfterProcessStart(options, sharedMemory); + + if (detectorType == HotwordDetector.DETECTOR_TYPE_TRUSTED_HOTWORD_DSP) { + mHotwordDetectorSession = new DspTrustedHotwordDetectorSession( + mRemoteHotwordDetectionService, mLock, mContext, callback, + mVoiceInteractionServiceUid, mVoiceInteractorIdentity, + mScheduledExecutorService, mDebugHotwordLogging); + } else { + mHotwordDetectorSession = new SoftwareTrustedHotwordDetectorSession( + mRemoteHotwordDetectionService, mLock, mContext, callback, + mVoiceInteractionServiceUid, mVoiceInteractorIdentity, + mScheduledExecutorService, mDebugHotwordLogging); + } + mHotwordDetectorSession.initialize(options, sharedMemory); if (mReStartPeriodSeconds <= 0) { mCancellationTaskFuture = null; @@ -320,106 +204,11 @@ final class HotwordDetectionConnection { } } - private void updateStateAfterProcessStart( - PersistableBundle options, SharedMemory sharedMemory) { - if (DEBUG) { - Slog.d(TAG, "updateStateAfterProcessStart"); - } - mRemoteHotwordDetectionService.postAsync(service -> { - AndroidFuture<Void> future = new AndroidFuture<>(); - IRemoteCallback statusCallback = new IRemoteCallback.Stub() { - @Override - public void sendResult(Bundle bundle) throws RemoteException { - if (DEBUG) { - Slog.d(TAG, "updateState finish"); - } - future.complete(null); - if (mUpdateStateAfterStartFinished.getAndSet(true)) { - Slog.w(TAG, "call callback after timeout"); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_UPDATE_STATE_AFTER_TIMEOUT, - mVoiceInteractionServiceUid); - return; - } - Pair<Integer, Integer> statusResultPair = getInitStatusAndMetricsResult(bundle); - int status = statusResultPair.first; - int initResultMetricsResult = statusResultPair.second; - try { - mCallback.onStatusReported(status); - HotwordMetricsLogger.writeServiceInitResultEvent(mDetectorType, - initResultMetricsResult); - } catch (RemoteException e) { - Slog.w(TAG, "Failed to report initialization status: " + e); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - METRICS_CALLBACK_ON_STATUS_REPORTED_EXCEPTION, - mVoiceInteractionServiceUid); - } - } - }; - try { - service.updateState(options, sharedMemory, statusCallback); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__REQUEST_UPDATE_STATE, - mVoiceInteractionServiceUid); - } catch (RemoteException e) { - // TODO: (b/181842909) Report an error to voice interactor - Slog.w(TAG, "Failed to updateState for HotwordDetectionService", e); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__CALL_UPDATE_STATE_EXCEPTION, - mVoiceInteractionServiceUid); - } - return future.orTimeout(MAX_UPDATE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); - }).whenComplete((res, err) -> { - if (err instanceof TimeoutException) { - Slog.w(TAG, "updateState timed out"); - if (mUpdateStateAfterStartFinished.getAndSet(true)) { - return; - } - try { - mCallback.onStatusReported(INITIALIZATION_STATUS_UNKNOWN); - HotwordMetricsLogger.writeServiceInitResultEvent(mDetectorType, - METRICS_INIT_UNKNOWN_TIMEOUT); - } catch (RemoteException e) { - Slog.w(TAG, "Failed to report initialization status UNKNOWN", e); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - METRICS_CALLBACK_ON_STATUS_REPORTED_EXCEPTION, - mVoiceInteractionServiceUid); - } - } else if (err != null) { - Slog.w(TAG, "Failed to update state: " + err); - } else { - // NOTE: so far we don't need to take any action. - } - }); - } - - private static Pair<Integer, Integer> getInitStatusAndMetricsResult(Bundle bundle) { - if (bundle == null) { - return new Pair<>(INITIALIZATION_STATUS_UNKNOWN, METRICS_INIT_UNKNOWN_NO_VALUE); - } - int status = bundle.getInt(KEY_INITIALIZATION_STATUS, INITIALIZATION_STATUS_UNKNOWN); - if (status > HotwordDetectionService.getMaxCustomInitializationStatus()) { - return new Pair<>(INITIALIZATION_STATUS_UNKNOWN, - status == INITIALIZATION_STATUS_UNKNOWN - ? METRICS_INIT_UNKNOWN_NO_VALUE - : METRICS_INIT_UNKNOWN_OVER_MAX_CUSTOM_VALUE); - } - // TODO: should guard against negative here - int metricsResult = status == INITIALIZATION_STATUS_SUCCESS - ? METRICS_INIT_CALLBACK_STATE_SUCCESS - : METRICS_INIT_CALLBACK_STATE_ERROR; - return new Pair<>(status, metricsResult); - } - - private boolean isBound() { - synchronized (mLock) { - return mRemoteHotwordDetectionService.isBound(); - } - } - + @SuppressWarnings("GuardedBy") void cancelLocked() { Slog.v(TAG, "cancelLocked"); clearDebugHotwordLoggingTimeoutLocked(); + mHotwordDetectorSession.destroyLocked(); mDebugHotwordLogging = false; mRemoteHotwordDetectionService.unbind(); LocalServices.getService(PermissionManagerServiceInternal.class) @@ -434,118 +223,32 @@ final class HotwordDetectionConnection { if (mAudioFlinger != null) { mAudioFlinger.unlinkToDeath(mAudioServerDeathRecipient, /* flags= */ 0); } - if (mAttentionManagerInternal != null) { - mAttentionManagerInternal.onStopProximityUpdates(mProximityCallbackInternal); - } } + @SuppressWarnings("GuardedBy") void updateStateLocked(PersistableBundle options, SharedMemory sharedMemory) { - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__APP_REQUEST_UPDATE_STATE, - mVoiceInteractionServiceUid); - - // Prevent doing the init late, so restart is handled equally to a clean process start. - // TODO(b/191742511): this logic needs a test - if (!mUpdateStateAfterStartFinished.get() - && Instant.now().minus(MAX_UPDATE_TIMEOUT_DURATION).isBefore(mLastRestartInstant)) { - Slog.v(TAG, "call updateStateAfterProcessStart"); - updateStateAfterProcessStart(options, sharedMemory); - } else { - mRemoteHotwordDetectionService.run( - service -> service.updateState(options, sharedMemory, null /* callback */)); - } + mHotwordDetectorSession.updateStateLocked(options, sharedMemory, mLastRestartInstant); } + /** + * This method is only used by SoftwareHotwordDetector. + */ void startListeningFromMic( AudioFormat audioFormat, IMicrophoneHotwordDetectionVoiceInteractionCallback callback) { if (DEBUG) { Slog.d(TAG, "startListeningFromMic"); } - mSoftwareCallback = callback; - synchronized (mLock) { - if (mPerformingSoftwareHotwordDetection) { - Slog.i(TAG, "Hotword validation is already in progress, ignoring."); + if (!(mHotwordDetectorSession instanceof SoftwareTrustedHotwordDetectorSession)) { + Slog.d(TAG, "It is not a software detector"); return; } - mPerformingSoftwareHotwordDetection = true; - - startListeningFromMicLocked(); + ((SoftwareTrustedHotwordDetectorSession) mHotwordDetectorSession) + .startListeningFromMicLocked(audioFormat, callback); } } - private void startListeningFromMicLocked() { - // TODO: consider making this a non-anonymous class. - IDspHotwordDetectionCallback internalCallback = new IDspHotwordDetectionCallback.Stub() { - @Override - public void onDetected(HotwordDetectedResult result) throws RemoteException { - if (DEBUG) { - Slog.d(TAG, "onDetected"); - } - synchronized (mLock) { - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECTED); - if (!mPerformingSoftwareHotwordDetection) { - Slog.i(TAG, "Hotword detection has already completed"); - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - METRICS_KEYPHRASE_TRIGGERED_DETECT_UNEXPECTED_CALLBACK); - return; - } - mPerformingSoftwareHotwordDetection = false; - try { - enforcePermissionsForDataDelivery(); - } catch (SecurityException e) { - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - METRICS_KEYPHRASE_TRIGGERED_DETECT_SECURITY_EXCEPTION); - mSoftwareCallback.onError(); - return; - } - saveProximityValueToBundle(result); - HotwordDetectedResult newResult; - try { - newResult = mHotwordAudioStreamCopier.startCopyingAudioStreams(result); - } catch (IOException e) { - // TODO: Write event - mSoftwareCallback.onError(); - return; - } - mSoftwareCallback.onDetected(newResult, null, null); - Slog.i(TAG, "Egressed " + HotwordDetectedResult.getUsageSize(newResult) - + " bits from hotword trusted process"); - if (mDebugHotwordLogging) { - Slog.i(TAG, "Egressed detected result: " + newResult); - } - } - } - - @Override - public void onRejected(HotwordRejectedResult result) throws RemoteException { - if (DEBUG) { - Slog.wtf(TAG, "onRejected"); - } - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECTED); - // onRejected isn't allowed here, and we are not expecting it. - } - }; - - mRemoteHotwordDetectionService.run( - service -> service.detectFromMicrophoneSource( - null, - AUDIO_SOURCE_MICROPHONE, - null, - null, - internalCallback)); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__START_SOFTWARE_DETECTION, - mVoiceInteractionServiceUid); - } - public void startListeningFromExternalSource( ParcelFileDescriptor audioStream, AudioFormat audioFormat, @@ -554,37 +257,26 @@ final class HotwordDetectionConnection { if (DEBUG) { Slog.d(TAG, "startListeningFromExternalSource"); } - - handleExternalSourceHotwordDetection( - audioStream, - audioFormat, - options, - callback); + synchronized (mLock) { + mHotwordDetectorSession.startListeningFromExternalSourceLocked(audioStream, audioFormat, + options, callback); + } } + /** + * This method is only used by SoftwareHotwordDetector. + */ void stopListening() { if (DEBUG) { Slog.d(TAG, "stopListening"); } synchronized (mLock) { - stopListeningLocked(); - } - } - - private void stopListeningLocked() { - if (!mPerformingSoftwareHotwordDetection) { - Slog.i(TAG, "Hotword detection is not running"); - return; - } - mPerformingSoftwareHotwordDetection = false; - - mRemoteHotwordDetectionService.run(IHotwordDetectionService::stopDetection); - - if (mCurrentAudioSink != null) { - Slog.i(TAG, "Closing audio stream to hotword detector: stopping requested"); - bestEffortClose(mCurrentAudioSink); + if (!(mHotwordDetectorSession instanceof SoftwareTrustedHotwordDetectorSession)) { + Slog.d(TAG, "It is not a software detector"); + return; + } + ((SoftwareTrustedHotwordDetectorSession) mHotwordDetectorSession).stopListeningLocked(); } - mCurrentAudioSink = null; } void triggerHardwareRecognitionEventForTestLocked( @@ -596,130 +288,18 @@ final class HotwordDetectionConnection { detectFromDspSource(event, callback); } - void detectFromDspSource(SoundTrigger.KeyphraseRecognitionEvent recognitionEvent, + private void detectFromDspSource(SoundTrigger.KeyphraseRecognitionEvent recognitionEvent, IHotwordRecognitionStatusCallback externalCallback) { if (DEBUG) { Slog.d(TAG, "detectFromDspSource"); } - - AtomicBoolean timeoutDetected = new AtomicBoolean(false); - // TODO: consider making this a non-anonymous class. - IDspHotwordDetectionCallback internalCallback = new IDspHotwordDetectionCallback.Stub() { - @Override - public void onDetected(HotwordDetectedResult result) throws RemoteException { - if (DEBUG) { - Slog.d(TAG, "onDetected"); - } - synchronized (mLock) { - if (mCancellationKeyPhraseDetectionFuture != null) { - mCancellationKeyPhraseDetectionFuture.cancel(true); - } - if (timeoutDetected.get()) { - return; - } - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECTED); - if (!mValidatingDspTrigger) { - Slog.i(TAG, "Ignoring #onDetected due to a process restart"); - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - METRICS_KEYPHRASE_TRIGGERED_DETECT_UNEXPECTED_CALLBACK); - return; - } - mValidatingDspTrigger = false; - try { - enforcePermissionsForDataDelivery(); - enforceExtraKeyphraseIdNotLeaked(result, recognitionEvent); - } catch (SecurityException e) { - Slog.i(TAG, "Ignoring #onDetected due to a SecurityException", e); - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - METRICS_KEYPHRASE_TRIGGERED_DETECT_SECURITY_EXCEPTION); - externalCallback.onError(CALLBACK_ONDETECTED_GOT_SECURITY_EXCEPTION); - return; - } - saveProximityValueToBundle(result); - HotwordDetectedResult newResult; - try { - newResult = mHotwordAudioStreamCopier.startCopyingAudioStreams(result); - } catch (IOException e) { - // TODO: Write event - externalCallback.onError(CALLBACK_ONDETECTED_STREAM_COPY_ERROR); - return; - } - externalCallback.onKeyphraseDetected(recognitionEvent, newResult); - Slog.i(TAG, "Egressed " + HotwordDetectedResult.getUsageSize(newResult) - + " bits from hotword trusted process"); - if (mDebugHotwordLogging) { - Slog.i(TAG, "Egressed detected result: " + newResult); - } - } - } - - @Override - public void onRejected(HotwordRejectedResult result) throws RemoteException { - if (DEBUG) { - Slog.d(TAG, "onRejected"); - } - synchronized (mLock) { - if (mCancellationKeyPhraseDetectionFuture != null) { - mCancellationKeyPhraseDetectionFuture.cancel(true); - } - if (timeoutDetected.get()) { - return; - } - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECTED); - if (!mValidatingDspTrigger) { - Slog.i(TAG, "Ignoring #onRejected due to a process restart"); - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - METRICS_KEYPHRASE_TRIGGERED_REJECT_UNEXPECTED_CALLBACK); - return; - } - mValidatingDspTrigger = false; - externalCallback.onRejected(result); - if (mDebugHotwordLogging && result != null) { - Slog.i(TAG, "Egressed rejected result: " + result); - } - } - } - }; - synchronized (mLock) { - mValidatingDspTrigger = true; - mRemoteHotwordDetectionService.run(service -> { - // We use the VALIDATION_TIMEOUT_MILLIS to inform that the client needs to invoke - // the callback before timeout value. In order to reduce the latency impact between - // server side and client side, we need to use another timeout value - // MAX_VALIDATION_TIMEOUT_MILLIS to monitor it. - mCancellationKeyPhraseDetectionFuture = mScheduledExecutorService.schedule( - () -> { - // TODO: avoid allocate every time - timeoutDetected.set(true); - Slog.w(TAG, "Timed out on #detectFromDspSource"); - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECT_TIMEOUT); - try { - externalCallback.onError(CALLBACK_DETECT_TIMEOUT); - } catch (RemoteException e) { - Slog.w(TAG, "Failed to report onError status: ", e); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_ERROR_EXCEPTION, - mVoiceInteractionServiceUid); - } - }, - MAX_VALIDATION_TIMEOUT_MILLIS, - TimeUnit.MILLISECONDS); - service.detectFromDspSource( - recognitionEvent, - recognitionEvent.getCaptureFormat(), - VALIDATION_TIMEOUT_MILLIS, - internalCallback); - }); + if (!(mHotwordDetectorSession instanceof DspTrustedHotwordDetectorSession)) { + Slog.d(TAG, "It is not a Dsp detector"); + return; + } + ((DspTrustedHotwordDetectorSession) mHotwordDetectorSession).detectFromDspSourceLocked( + recognitionEvent, externalCallback); } } @@ -730,10 +310,12 @@ final class HotwordDetectionConnection { } } + @SuppressWarnings("GuardedBy") void setDebugHotwordLoggingLocked(boolean logging) { Slog.v(TAG, "setDebugHotwordLoggingLocked: " + logging); clearDebugHotwordLoggingTimeoutLocked(); mDebugHotwordLogging = logging; + mHotwordDetectorSession.setDebugHotwordLoggingLocked(logging); if (logging) { // Reset mDebugHotwordLogging to false after one hour @@ -741,6 +323,7 @@ final class HotwordDetectionConnection { Slog.v(TAG, "Timeout to reset mDebugHotwordLogging to false"); synchronized (mLock) { mDebugHotwordLogging = false; + mHotwordDetectorSession.setDebugHotwordLoggingLocked(false); } }, RESET_DEBUG_HOTWORD_LOGGING_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } @@ -753,60 +336,23 @@ final class HotwordDetectionConnection { } } + @SuppressWarnings("GuardedBy") private void restartProcessLocked() { // TODO(b/244598068): Check HotwordAudioStreamManager first Slog.v(TAG, "Restarting hotword detection process"); ServiceConnection oldConnection = mRemoteHotwordDetectionService; HotwordDetectionServiceIdentity previousIdentity = mIdentity; - // TODO(volnov): this can be done after connect() has been successful. - if (mValidatingDspTrigger) { - // We're restarting the process while it's processing a DSP trigger, so report a - // rejection. This also allows the Interactor to startReco again - try { - mCallback.onRejected(new HotwordRejectedResult.Builder().build()); - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECTED_FROM_RESTART); - } catch (RemoteException e) { - Slog.w(TAG, "Failed to call #rejected"); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_REJECTED_EXCEPTION, - mVoiceInteractionServiceUid); - } - mValidatingDspTrigger = false; - } - - mUpdateStateAfterStartFinished.set(false); mLastRestartInstant = Instant.now(); - // Recreate connection to reset the cache. mRemoteHotwordDetectionService = mServiceConnectionFactory.createLocked(); - Slog.v(TAG, "Started the new process, issuing #onProcessRestarted"); - try { - mCallback.onProcessRestarted(); - } catch (RemoteException e) { - Slog.w(TAG, "Failed to communicate #onProcessRestarted", e); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_PROCESS_RESTARTED_EXCEPTION, - mVoiceInteractionServiceUid); - } - - // Restart listening from microphone if the hotword process has been restarted. - if (mPerformingSoftwareHotwordDetection) { - Slog.i(TAG, "Process restarted: calling startRecognition() again"); - startListeningFromMicLocked(); - } - - if (mCurrentAudioSink != null) { - Slog.i(TAG, "Closing external audio stream to hotword detector: process restarted"); - bestEffortClose(mCurrentAudioSink); - mCurrentAudioSink = null; - } - + Slog.v(TAG, "Started the new process, dispatching processRestarted to detector"); + mHotwordDetectorSession.updateRemoteHotwordDetectionServiceLocked( + mRemoteHotwordDetectionService); + mHotwordDetectorSession.informRestartProcessLocked(); if (DEBUG) { - Slog.i(TAG, "#onProcessRestarted called, unbinding from the old process"); + Slog.i(TAG, "processRestarted is dispatched done, unbinding from the old process"); } oldConnection.ignoreConnectionStatusEvents(); oldConnection.unbind(); @@ -816,7 +362,6 @@ final class HotwordDetectionConnection { } static final class SoundTriggerCallback extends IRecognitionStatusCallback.Stub { - private SoundTrigger.KeyphraseRecognitionEvent mRecognitionEvent; private final HotwordDetectionConnection mHotwordDetectionConnection; private final IHotwordRecognitionStatusCallback mExternalCallback; @@ -837,7 +382,6 @@ final class HotwordDetectionConnection { HotwordMetricsLogger.writeKeyphraseTriggerEvent( HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__DETECTOR_TYPE__TRUSTED_DETECTOR_DSP, HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__KEYPHRASE_TRIGGER); - mRecognitionEvent = recognitionEvent; mHotwordDetectionConnection.detectFromDspSource( recognitionEvent, mExternalCallback); } else { @@ -872,160 +416,18 @@ final class HotwordDetectionConnection { } public void dump(String prefix, PrintWriter pw) { - pw.print(prefix); pw.print("mReStartPeriodSeconds="); pw.println(mReStartPeriodSeconds); - pw.print(prefix); - pw.print("mBound=" + mRemoteHotwordDetectionService.isBound()); - pw.print(", mValidatingDspTrigger=" + mValidatingDspTrigger); - pw.print(", mPerformingSoftwareHotwordDetection=" + mPerformingSoftwareHotwordDetection); - pw.print(", mRestartCount=" + mServiceConnectionFactory.mRestartCount); - pw.print(", mLastRestartInstant=" + mLastRestartInstant); - pw.println(", mDetectorType=" + HotwordDetector.detectorTypeToString(mDetectorType)); - } - - private void handleExternalSourceHotwordDetection( - ParcelFileDescriptor audioStream, - AudioFormat audioFormat, - @Nullable PersistableBundle options, - IMicrophoneHotwordDetectionVoiceInteractionCallback callback) { - if (DEBUG) { - Slog.d(TAG, "#handleExternalSourceHotwordDetection"); - } - InputStream audioSource = new ParcelFileDescriptor.AutoCloseInputStream(audioStream); - - Pair<ParcelFileDescriptor, ParcelFileDescriptor> clientPipe = createPipe(); - if (clientPipe == null) { - // TODO: Need to propagate as unknown error or something? - return; - } - ParcelFileDescriptor serviceAudioSink = clientPipe.second; - ParcelFileDescriptor serviceAudioSource = clientPipe.first; - synchronized (mLock) { - mCurrentAudioSink = serviceAudioSink; + pw.print(prefix); pw.print("mReStartPeriodSeconds="); pw.println(mReStartPeriodSeconds); + pw.print(prefix); pw.print("mBound="); + pw.println(mRemoteHotwordDetectionService.isBound()); + pw.print(prefix); pw.print("mRestartCount="); + pw.println(mServiceConnectionFactory.mRestartCount); + pw.print(prefix); pw.print("mLastRestartInstant="); pw.println(mLastRestartInstant); + pw.print(prefix); pw.print("mDetectorType="); + pw.println(HotwordDetector.detectorTypeToString(mDetectorType)); + pw.print(prefix); pw.println("HotwordDetectorSession"); + mHotwordDetectorSession.dumpLocked(prefix, pw); } - - mAudioCopyExecutor.execute(() -> { - try (InputStream source = audioSource; - OutputStream fos = - new ParcelFileDescriptor.AutoCloseOutputStream(serviceAudioSink)) { - - byte[] buffer = new byte[1024]; - while (true) { - int bytesRead = source.read(buffer, 0, 1024); - - if (bytesRead < 0) { - Slog.i(TAG, "Reached end of stream for external hotword"); - break; - } - - // TODO: First write to ring buffer to make sure we don't lose data if the next - // statement fails. - // ringBuffer.append(buffer, bytesRead); - fos.write(buffer, 0, bytesRead); - } - } catch (IOException e) { - Slog.w(TAG, "Failed supplying audio data to validator", e); - - try { - callback.onError(); - } catch (RemoteException ex) { - Slog.w(TAG, "Failed to report onError status: " + ex); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_ERROR_EXCEPTION, - mVoiceInteractionServiceUid); - } - } finally { - synchronized (mLock) { - mCurrentAudioSink = null; - } - } - }); - - // TODO: handle cancellations well - // TODO: what if we cancelled and started a new one? - mRemoteHotwordDetectionService.run( - service -> { - service.detectFromMicrophoneSource( - serviceAudioSource, - // TODO: consider making a proxy callback + copy of audio format - AUDIO_SOURCE_EXTERNAL, - audioFormat, - options, - new IDspHotwordDetectionCallback.Stub() { - @Override - public void onRejected(HotwordRejectedResult result) - throws RemoteException { - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - METRICS_EXTERNAL_SOURCE_REJECTED, - mVoiceInteractionServiceUid); - mScheduledExecutorService.schedule( - () -> { - bestEffortClose(serviceAudioSink, audioSource); - }, - EXTERNAL_HOTWORD_CLEANUP_MILLIS, - TimeUnit.MILLISECONDS); - - callback.onRejected(result); - - if (result != null) { - Slog.i(TAG, "Egressed 'hotword rejected result' " - + "from hotword trusted process"); - if (mDebugHotwordLogging) { - Slog.i(TAG, "Egressed detected result: " + result); - } - } - } - - @Override - public void onDetected(HotwordDetectedResult triggerResult) - throws RemoteException { - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - METRICS_EXTERNAL_SOURCE_DETECTED, - mVoiceInteractionServiceUid); - mScheduledExecutorService.schedule( - () -> { - bestEffortClose(serviceAudioSink, audioSource); - }, - EXTERNAL_HOTWORD_CLEANUP_MILLIS, - TimeUnit.MILLISECONDS); - - try { - enforcePermissionsForDataDelivery(); - } catch (SecurityException e) { - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - METRICS_EXTERNAL_SOURCE_DETECT_SECURITY_EXCEPTION, - mVoiceInteractionServiceUid); - callback.onError(); - return; - } - HotwordDetectedResult newResult; - try { - newResult = - mHotwordAudioStreamCopier.startCopyingAudioStreams( - triggerResult); - } catch (IOException e) { - // TODO: Write event - callback.onError(); - return; - } - callback.onDetected(newResult, null /* audioFormat */, - null /* audioStream */); - Slog.i(TAG, "Egressed " - + HotwordDetectedResult.getUsageSize(newResult) - + " bits from hotword trusted process"); - if (mDebugHotwordLogging) { - Slog.i(TAG, - "Egressed detected result: " + newResult); - } - } - }); - - // A copy of this has been created and passed to the hotword validator - bestEffortClose(serviceAudioSource); - }); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__START_EXTERNAL_SOURCE_DETECTION, - mVoiceInteractionServiceUid); } private class ServiceConnectionFactory { @@ -1054,7 +456,7 @@ final class HotwordDetectionConnection { } } - private class ServiceConnection extends ServiceConnector.Impl<IHotwordDetectionService> { + class ServiceConnection extends ServiceConnector.Impl<IHotwordDetectionService> { private final Object mLock = new Object(); private final Intent mIntent; @@ -1109,21 +511,16 @@ final class HotwordDetectionConnection { @Override public void binderDied() { super.binderDied(); + Slog.w(TAG, "binderDied"); synchronized (mLock) { if (!mRespectServiceConnectionStatusChanged) { Slog.v(TAG, "Ignored #binderDied event"); return; } - - Slog.w(TAG, "binderDied"); - try { - mCallback.onError(HOTWORD_DETECTION_SERVICE_DIED); - } catch (RemoteException e) { - Slog.w(TAG, "Failed to report onError status: " + e); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_ERROR_EXCEPTION, - mVoiceInteractionServiceUid); - } + } + synchronized (HotwordDetectionConnection.this.mLock) { + mHotwordDetectorSession.reportErrorLocked( + HotwordDetectorSession.HOTWORD_DETECTION_SERVICE_DIED); } } @@ -1168,18 +565,6 @@ final class HotwordDetectionConnection { } } - private static Pair<ParcelFileDescriptor, ParcelFileDescriptor> createPipe() { - ParcelFileDescriptor[] fileDescriptors; - try { - fileDescriptors = ParcelFileDescriptor.createPipe(); - } catch (IOException e) { - Slog.e(TAG, "Failed to create audio stream pipe", e); - return null; - } - - return Pair.create(fileDescriptors[0], fileDescriptors[1]); - } - private static void updateAudioFlinger(ServiceConnection connection, IBinder audioFlinger) { // TODO: Consider using a proxy that limits the exposed API surface. connection.run(service -> service.updateAudioFlinger(audioFlinger)); @@ -1241,85 +626,4 @@ final class HotwordDetectionConnection { } }); } - - private void saveProximityValueToBundle(HotwordDetectedResult result) { - synchronized (mLock) { - if (result != null && mProximityMeters != PROXIMITY_UNKNOWN) { - result.setProximity(mProximityMeters); - } - } - } - - private void setProximityValue(double proximityMeters) { - synchronized (mLock) { - mProximityMeters = proximityMeters; - } - } - - private static void bestEffortClose(Closeable... closeables) { - for (Closeable closeable : closeables) { - bestEffortClose(closeable); - } - } - - private static void bestEffortClose(Closeable closeable) { - try { - closeable.close(); - } catch (IOException e) { - if (DEBUG) { - Slog.w(TAG, "Failed closing", e); - } - } - } - - // TODO: Share this code with SoundTriggerMiddlewarePermission. - private void enforcePermissionsForDataDelivery() { - Binder.withCleanCallingIdentity(() -> { - enforcePermissionForPreflight(mContext, mVoiceInteractorIdentity, RECORD_AUDIO); - int hotwordOp = AppOpsManager.strOpToOp(AppOpsManager.OPSTR_RECORD_AUDIO_HOTWORD); - mAppOpsManager.noteOpNoThrow(hotwordOp, - mVoiceInteractorIdentity.uid, mVoiceInteractorIdentity.packageName, - mVoiceInteractorIdentity.attributionTag, OP_MESSAGE); - enforcePermissionForDataDelivery(mContext, mVoiceInteractorIdentity, - CAPTURE_AUDIO_HOTWORD, OP_MESSAGE); - }); - } - - /** - * Throws a {@link SecurityException} iff the given identity has given permission to receive - * data. - * - * @param context A {@link Context}, used for permission checks. - * @param identity The identity to check. - * @param permission The identifier of the permission we want to check. - * @param reason The reason why we're requesting the permission, for auditing purposes. - */ - private static void enforcePermissionForDataDelivery(@NonNull Context context, - @NonNull Identity identity, - @NonNull String permission, @NonNull String reason) { - final int status = PermissionUtil.checkPermissionForDataDelivery(context, identity, - permission, reason); - if (status != PermissionChecker.PERMISSION_GRANTED) { - throw new SecurityException( - TextUtils.formatSimple("Failed to obtain permission %s for identity %s", - permission, - SoundTriggerSessionPermissionsDecorator.toString(identity))); - } - } - - private static void enforceExtraKeyphraseIdNotLeaked(HotwordDetectedResult result, - SoundTrigger.KeyphraseRecognitionEvent recognitionEvent) { - // verify the phrase ID in HotwordDetectedResult is not exposing extra phrases - // the DSP did not detect - for (SoundTrigger.KeyphraseRecognitionExtra keyphrase : recognitionEvent.keyphraseExtras) { - if (keyphrase.getKeyphraseId() == result.getHotwordPhraseId()) { - return; - } - } - throw new SecurityException("Ignoring #onDetected due to trusted service " - + "sharing a keyphrase ID which the DSP did not detect"); - } - - private static final String OP_MESSAGE = - "Providing hotword detection result to VoiceInteractionService"; } diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectorSession.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectorSession.java new file mode 100644 index 000000000000..f9f43c9ba49a --- /dev/null +++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectorSession.java @@ -0,0 +1,666 @@ +/* + * 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.voiceinteraction; + +import static android.Manifest.permission.CAPTURE_AUDIO_HOTWORD; +import static android.Manifest.permission.RECORD_AUDIO; +import static android.service.attention.AttentionService.PROXIMITY_UNKNOWN; +import static android.service.voice.HotwordDetectionService.AUDIO_SOURCE_EXTERNAL; +import static android.service.voice.HotwordDetectionService.ENABLE_PROXIMITY_RESULT; +import static android.service.voice.HotwordDetectionService.INITIALIZATION_STATUS_SUCCESS; +import static android.service.voice.HotwordDetectionService.INITIALIZATION_STATUS_UNKNOWN; +import static android.service.voice.HotwordDetectionService.KEY_INITIALIZATION_STATUS; + +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_ERROR; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_SUCCESS; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_UNKNOWN_NO_VALUE; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_UNKNOWN_OVER_MAX_CUSTOM_VALUE; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_UNKNOWN_TIMEOUT; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__APP_REQUEST_UPDATE_STATE; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_ERROR_EXCEPTION; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_STATUS_REPORTED_EXCEPTION; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_UPDATE_STATE_AFTER_TIMEOUT; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__CALL_UPDATE_STATE_EXCEPTION; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__EXTERNAL_SOURCE_DETECTED; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__EXTERNAL_SOURCE_DETECT_SECURITY_EXCEPTION; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__EXTERNAL_SOURCE_REJECTED; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__REQUEST_UPDATE_STATE; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__START_EXTERNAL_SOURCE_DETECTION; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECT_SECURITY_EXCEPTION; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECT_UNEXPECTED_CALLBACK; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECT_UNEXPECTED_CALLBACK; +import static com.android.server.voiceinteraction.SoundTriggerSessionPermissionsDecorator.enforcePermissionForPreflight; + +import android.annotation.NonNull; +import android.annotation.Nullable; +import android.app.AppOpsManager; +import android.attention.AttentionManagerInternal; +import android.content.Context; +import android.content.PermissionChecker; +import android.hardware.soundtrigger.SoundTrigger; +import android.media.AudioFormat; +import android.media.permission.Identity; +import android.media.permission.PermissionUtil; +import android.os.Binder; +import android.os.Bundle; +import android.os.IRemoteCallback; +import android.os.ParcelFileDescriptor; +import android.os.PersistableBundle; +import android.os.RemoteException; +import android.os.SharedMemory; +import android.service.voice.HotwordDetectedResult; +import android.service.voice.HotwordDetectionService; +import android.service.voice.HotwordDetector; +import android.service.voice.HotwordRejectedResult; +import android.service.voice.IDspHotwordDetectionCallback; +import android.service.voice.IMicrophoneHotwordDetectionVoiceInteractionCallback; +import android.text.TextUtils; +import android.util.Pair; +import android.util.Slog; + +import com.android.internal.annotations.GuardedBy; +import com.android.internal.app.IHotwordRecognitionStatusCallback; +import com.android.internal.infra.AndroidFuture; +import com.android.server.LocalServices; + +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.time.Duration; +import java.time.Instant; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * A class that provides trusted hotword detector to communicate with the {@link + * HotwordDetectionService}. + * + * This class provides the methods to do initialization with the {@link HotwordDetectionService} + * and handle external source detection. It also provides the methods to check if we can egress + * the data from the {@link HotwordDetectionService}. + * + * The subclass should override the {@link #informRestartProcessLocked()} to handle the trusted + * process restart. + */ +abstract class HotwordDetectorSession { + private static final String TAG = "HotwordDetectorSession"; + static final boolean DEBUG = false; + + private static final String OP_MESSAGE = + "Providing hotword detection result to VoiceInteractionService"; + + // The error codes are used for onError callback + static final int HOTWORD_DETECTION_SERVICE_DIED = -1; + static final int CALLBACK_ONDETECTED_GOT_SECURITY_EXCEPTION = -2; + static final int CALLBACK_DETECT_TIMEOUT = -3; + static final int CALLBACK_ONDETECTED_STREAM_COPY_ERROR = -4; + + // TODO: These constants need to be refined. + private static final long MAX_UPDATE_TIMEOUT_MILLIS = 30000; + private static final long EXTERNAL_HOTWORD_CLEANUP_MILLIS = 2000; + private static final Duration MAX_UPDATE_TIMEOUT_DURATION = + Duration.ofMillis(MAX_UPDATE_TIMEOUT_MILLIS); + + // Hotword metrics + private static final int METRICS_INIT_UNKNOWN_TIMEOUT = + HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_UNKNOWN_TIMEOUT; + private static final int METRICS_INIT_UNKNOWN_NO_VALUE = + HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_UNKNOWN_NO_VALUE; + private static final int METRICS_INIT_UNKNOWN_OVER_MAX_CUSTOM_VALUE = + HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_UNKNOWN_OVER_MAX_CUSTOM_VALUE; + private static final int METRICS_INIT_CALLBACK_STATE_ERROR = + HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_ERROR; + private static final int METRICS_INIT_CALLBACK_STATE_SUCCESS = + HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_SUCCESS; + + static final int METRICS_KEYPHRASE_TRIGGERED_DETECT_SECURITY_EXCEPTION = + HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECT_SECURITY_EXCEPTION; + static final int METRICS_KEYPHRASE_TRIGGERED_DETECT_UNEXPECTED_CALLBACK = + HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECT_UNEXPECTED_CALLBACK; + static final int METRICS_KEYPHRASE_TRIGGERED_REJECT_UNEXPECTED_CALLBACK = + HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECT_UNEXPECTED_CALLBACK; + + private static final int METRICS_EXTERNAL_SOURCE_DETECTED = + HOTWORD_DETECTOR_EVENTS__EVENT__EXTERNAL_SOURCE_DETECTED; + private static final int METRICS_EXTERNAL_SOURCE_REJECTED = + HOTWORD_DETECTOR_EVENTS__EVENT__EXTERNAL_SOURCE_REJECTED; + private static final int EXTERNAL_SOURCE_DETECT_SECURITY_EXCEPTION = + HOTWORD_DETECTOR_EVENTS__EVENT__EXTERNAL_SOURCE_DETECT_SECURITY_EXCEPTION; + private static final int METRICS_CALLBACK_ON_STATUS_REPORTED_EXCEPTION = + HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_STATUS_REPORTED_EXCEPTION; + + private final Executor mAudioCopyExecutor = Executors.newCachedThreadPool(); + // TODO: This may need to be a Handler(looper) + final ScheduledExecutorService mScheduledExecutorService; + private final AppOpsManager mAppOpsManager; + final HotwordAudioStreamCopier mHotwordAudioStreamCopier; + final AtomicBoolean mUpdateStateAfterStartFinished = new AtomicBoolean(false); + final IHotwordRecognitionStatusCallback mCallback; + + final Object mLock; + final int mVoiceInteractionServiceUid; + final Context mContext; + + @Nullable AttentionManagerInternal mAttentionManagerInternal = null; + + final AttentionManagerInternal.ProximityUpdateCallbackInternal mProximityCallbackInternal = + this::setProximityValue; + + /** Identity used for attributing app ops when delivering data to the Interactor. */ + @Nullable + private final Identity mVoiceInteractorIdentity; + @GuardedBy("mLock") + ParcelFileDescriptor mCurrentAudioSink; + @GuardedBy("mLock") + @NonNull HotwordDetectionConnection.ServiceConnection mRemoteHotwordDetectionService; + boolean mDebugHotwordLogging = false; + @GuardedBy("mLock") + private double mProximityMeters = PROXIMITY_UNKNOWN; + @GuardedBy("mLock") + private boolean mInitialized = false; + @GuardedBy("mLock") + private boolean mDestroyed = false; + @GuardedBy("mLock") + boolean mPerformingExternalSourceHotwordDetection; + + HotwordDetectorSession( + @NonNull HotwordDetectionConnection.ServiceConnection remoteHotwordDetectionService, + @NonNull Object lock, @NonNull Context context, + @NonNull IHotwordRecognitionStatusCallback callback, int voiceInteractionServiceUid, + Identity voiceInteractorIdentity, + @NonNull ScheduledExecutorService scheduledExecutorService, boolean logging) { + mRemoteHotwordDetectionService = remoteHotwordDetectionService; + mLock = lock; + mContext = context; + mCallback = callback; + mVoiceInteractionServiceUid = voiceInteractionServiceUid; + mVoiceInteractorIdentity = voiceInteractorIdentity; + mAppOpsManager = mContext.getSystemService(AppOpsManager.class); + mHotwordAudioStreamCopier = new HotwordAudioStreamCopier(mAppOpsManager, getDetectorType(), + mVoiceInteractorIdentity.uid, mVoiceInteractorIdentity.packageName, + mVoiceInteractorIdentity.attributionTag); + mScheduledExecutorService = scheduledExecutorService; + mDebugHotwordLogging = logging; + + if (ENABLE_PROXIMITY_RESULT) { + mAttentionManagerInternal = LocalServices.getService(AttentionManagerInternal.class); + if (mAttentionManagerInternal != null) { + mAttentionManagerInternal.onStartProximityUpdates(mProximityCallbackInternal); + } + } + } + + @SuppressWarnings("GuardedBy") + private void updateStateAfterProcessStartLocked(PersistableBundle options, + SharedMemory sharedMemory) { + if (DEBUG) { + Slog.d(TAG, "updateStateAfterProcessStartLocked"); + } + AndroidFuture<Void> voidFuture = mRemoteHotwordDetectionService.postAsync(service -> { + AndroidFuture<Void> future = new AndroidFuture<>(); + IRemoteCallback statusCallback = new IRemoteCallback.Stub() { + @Override + public void sendResult(Bundle bundle) throws RemoteException { + if (DEBUG) { + Slog.d(TAG, "updateState finish"); + } + future.complete(null); + if (mUpdateStateAfterStartFinished.getAndSet(true)) { + Slog.w(TAG, "call callback after timeout"); + HotwordMetricsLogger.writeDetectorEvent(getDetectorType(), + HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_UPDATE_STATE_AFTER_TIMEOUT, + mVoiceInteractionServiceUid); + return; + } + Pair<Integer, Integer> statusResultPair = getInitStatusAndMetricsResult(bundle); + int status = statusResultPair.first; + int initResultMetricsResult = statusResultPair.second; + try { + mCallback.onStatusReported(status); + HotwordMetricsLogger.writeServiceInitResultEvent(getDetectorType(), + initResultMetricsResult); + } catch (RemoteException e) { + Slog.w(TAG, "Failed to report initialization status: " + e); + HotwordMetricsLogger.writeDetectorEvent(getDetectorType(), + METRICS_CALLBACK_ON_STATUS_REPORTED_EXCEPTION, + mVoiceInteractionServiceUid); + } + } + }; + try { + service.updateState(options, sharedMemory, statusCallback); + HotwordMetricsLogger.writeDetectorEvent(getDetectorType(), + HOTWORD_DETECTOR_EVENTS__EVENT__REQUEST_UPDATE_STATE, + mVoiceInteractionServiceUid); + } catch (RemoteException e) { + // TODO: (b/181842909) Report an error to voice interactor + Slog.w(TAG, "Failed to updateState for HotwordDetectionService", e); + HotwordMetricsLogger.writeDetectorEvent(getDetectorType(), + HOTWORD_DETECTOR_EVENTS__EVENT__CALL_UPDATE_STATE_EXCEPTION, + mVoiceInteractionServiceUid); + } + return future.orTimeout(MAX_UPDATE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + }).whenComplete((res, err) -> { + if (err instanceof TimeoutException) { + Slog.w(TAG, "updateState timed out"); + if (mUpdateStateAfterStartFinished.getAndSet(true)) { + return; + } + try { + mCallback.onStatusReported(INITIALIZATION_STATUS_UNKNOWN); + HotwordMetricsLogger.writeServiceInitResultEvent(getDetectorType(), + METRICS_INIT_UNKNOWN_TIMEOUT); + } catch (RemoteException e) { + Slog.w(TAG, "Failed to report initialization status UNKNOWN", e); + HotwordMetricsLogger.writeDetectorEvent(getDetectorType(), + METRICS_CALLBACK_ON_STATUS_REPORTED_EXCEPTION, + mVoiceInteractionServiceUid); + } + } else if (err != null) { + Slog.w(TAG, "Failed to update state: " + err); + } + }); + if (voidFuture == null) { + Slog.w(TAG, "Failed to create AndroidFuture"); + } + } + + private static Pair<Integer, Integer> getInitStatusAndMetricsResult(Bundle bundle) { + if (bundle == null) { + return new Pair<>(INITIALIZATION_STATUS_UNKNOWN, METRICS_INIT_UNKNOWN_NO_VALUE); + } + int status = bundle.getInt(KEY_INITIALIZATION_STATUS, INITIALIZATION_STATUS_UNKNOWN); + if (status > HotwordDetectionService.getMaxCustomInitializationStatus()) { + return new Pair<>(INITIALIZATION_STATUS_UNKNOWN, + status == INITIALIZATION_STATUS_UNKNOWN + ? METRICS_INIT_UNKNOWN_NO_VALUE + : METRICS_INIT_UNKNOWN_OVER_MAX_CUSTOM_VALUE); + } + // TODO: should guard against negative here + int metricsResult = status == INITIALIZATION_STATUS_SUCCESS + ? METRICS_INIT_CALLBACK_STATE_SUCCESS + : METRICS_INIT_CALLBACK_STATE_ERROR; + return new Pair<>(status, metricsResult); + } + + @SuppressWarnings("GuardedBy") + void updateStateLocked(PersistableBundle options, SharedMemory sharedMemory, + Instant lastRestartInstant) { + HotwordMetricsLogger.writeDetectorEvent(getDetectorType(), + HOTWORD_DETECTOR_EVENTS__EVENT__APP_REQUEST_UPDATE_STATE, + mVoiceInteractionServiceUid); + // Prevent doing the init late, so restart is handled equally to a clean process start. + // TODO(b/191742511): this logic needs a test + if (!mUpdateStateAfterStartFinished.get() && Instant.now().minus( + MAX_UPDATE_TIMEOUT_DURATION).isBefore(lastRestartInstant)) { + Slog.v(TAG, "call updateStateAfterProcessStartLocked"); + updateStateAfterProcessStartLocked(options, sharedMemory); + } else { + mRemoteHotwordDetectionService.run( + service -> service.updateState(options, sharedMemory, /* callback= */ null)); + } + } + + void startListeningFromExternalSourceLocked( + ParcelFileDescriptor audioStream, + AudioFormat audioFormat, + @Nullable PersistableBundle options, + IMicrophoneHotwordDetectionVoiceInteractionCallback callback) { + if (DEBUG) { + Slog.d(TAG, "startListeningFromExternalSourceLocked"); + } + + handleExternalSourceHotwordDetectionLocked( + audioStream, + audioFormat, + options, + callback); + } + + @SuppressWarnings("GuardedBy") + private void handleExternalSourceHotwordDetectionLocked( + ParcelFileDescriptor audioStream, + AudioFormat audioFormat, + @Nullable PersistableBundle options, + IMicrophoneHotwordDetectionVoiceInteractionCallback callback) { + if (DEBUG) { + Slog.d(TAG, "#handleExternalSourceHotwordDetectionLocked"); + } + if (mPerformingExternalSourceHotwordDetection) { + Slog.i(TAG, "Hotword validation is already in progress for external source."); + return; + } + + InputStream audioSource = new ParcelFileDescriptor.AutoCloseInputStream(audioStream); + + Pair<ParcelFileDescriptor, ParcelFileDescriptor> clientPipe = createPipe(); + if (clientPipe == null) { + // TODO: Need to propagate as unknown error or something? + return; + } + ParcelFileDescriptor serviceAudioSink = clientPipe.second; + ParcelFileDescriptor serviceAudioSource = clientPipe.first; + + mCurrentAudioSink = serviceAudioSink; + mPerformingExternalSourceHotwordDetection = true; + + mAudioCopyExecutor.execute(() -> { + try (InputStream source = audioSource; + OutputStream fos = + new ParcelFileDescriptor.AutoCloseOutputStream(serviceAudioSink)) { + + byte[] buffer = new byte[1024]; + while (true) { + int bytesRead = source.read(buffer, 0, 1024); + + if (bytesRead < 0) { + Slog.i(TAG, "Reached end of stream for external hotword"); + break; + } + + // TODO: First write to ring buffer to make sure we don't lose data if the next + // statement fails. + // ringBuffer.append(buffer, bytesRead); + fos.write(buffer, 0, bytesRead); + } + } catch (IOException e) { + Slog.w(TAG, "Failed supplying audio data to validator", e); + + try { + callback.onError(); + } catch (RemoteException ex) { + Slog.w(TAG, "Failed to report onError status: " + ex); + HotwordMetricsLogger.writeDetectorEvent(getDetectorType(), + HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_ERROR_EXCEPTION, + mVoiceInteractionServiceUid); + } + } finally { + synchronized (mLock) { + mPerformingExternalSourceHotwordDetection = false; + closeExternalAudioStreamLocked("start external source"); + } + } + }); + + // TODO: handle cancellations well + // TODO: what if we cancelled and started a new one? + mRemoteHotwordDetectionService.run( + service -> { + service.detectFromMicrophoneSource( + serviceAudioSource, + // TODO: consider making a proxy callback + copy of audio format + AUDIO_SOURCE_EXTERNAL, + audioFormat, + options, + new IDspHotwordDetectionCallback.Stub() { + @Override + public void onRejected(HotwordRejectedResult result) + throws RemoteException { + synchronized (mLock) { + mPerformingExternalSourceHotwordDetection = false; + HotwordMetricsLogger.writeDetectorEvent(getDetectorType(), + METRICS_EXTERNAL_SOURCE_REJECTED, + mVoiceInteractionServiceUid); + mScheduledExecutorService.schedule( + () -> { + bestEffortClose(serviceAudioSink, audioSource); + }, + EXTERNAL_HOTWORD_CLEANUP_MILLIS, + TimeUnit.MILLISECONDS); + + callback.onRejected(result); + + if (result != null) { + Slog.i(TAG, "Egressed 'hotword rejected result' " + + "from hotword trusted process"); + if (mDebugHotwordLogging) { + Slog.i(TAG, "Egressed detected result: " + result); + } + } + } + } + + @Override + public void onDetected(HotwordDetectedResult triggerResult) + throws RemoteException { + synchronized (mLock) { + mPerformingExternalSourceHotwordDetection = false; + HotwordMetricsLogger.writeDetectorEvent(getDetectorType(), + METRICS_EXTERNAL_SOURCE_DETECTED, + mVoiceInteractionServiceUid); + mScheduledExecutorService.schedule( + () -> { + bestEffortClose(serviceAudioSink, audioSource); + }, + EXTERNAL_HOTWORD_CLEANUP_MILLIS, + TimeUnit.MILLISECONDS); + + try { + enforcePermissionsForDataDelivery(); + } catch (SecurityException e) { + HotwordMetricsLogger.writeDetectorEvent( + getDetectorType(), + EXTERNAL_SOURCE_DETECT_SECURITY_EXCEPTION, + mVoiceInteractionServiceUid); + callback.onError(); + return; + } + HotwordDetectedResult newResult; + try { + newResult = mHotwordAudioStreamCopier + .startCopyingAudioStreams(triggerResult); + } catch (IOException e) { + // TODO: Write event + callback.onError(); + return; + } + callback.onDetected(newResult, null /* audioFormat */, + null /* audioStream */); + Slog.i(TAG, "Egressed " + + HotwordDetectedResult.getUsageSize(newResult) + + " bits from hotword trusted process"); + if (mDebugHotwordLogging) { + Slog.i(TAG, + "Egressed detected result: " + newResult); + } + } + } + }); + + // A copy of this has been created and passed to the hotword validator + bestEffortClose(serviceAudioSource); + }); + HotwordMetricsLogger.writeDetectorEvent(getDetectorType(), + HOTWORD_DETECTOR_EVENTS__EVENT__START_EXTERNAL_SOURCE_DETECTION, + mVoiceInteractionServiceUid); + } + + void initialize(@Nullable PersistableBundle options, @Nullable SharedMemory sharedMemory) { + synchronized (mLock) { + if (mInitialized || mDestroyed) { + return; + } + updateStateAfterProcessStartLocked(options, sharedMemory); + mInitialized = true; + } + } + + @SuppressWarnings("GuardedBy") + void destroyLocked() { + mDestroyed = true; + mDebugHotwordLogging = false; + mRemoteHotwordDetectionService = null; + if (mAttentionManagerInternal != null) { + mAttentionManagerInternal.onStopProximityUpdates(mProximityCallbackInternal); + } + } + + void setDebugHotwordLoggingLocked(boolean logging) { + Slog.v(TAG, "setDebugHotwordLoggingLocked: " + logging); + mDebugHotwordLogging = logging; + } + + @SuppressWarnings("GuardedBy") + void updateRemoteHotwordDetectionServiceLocked( + @NonNull HotwordDetectionConnection.ServiceConnection remoteHotwordDetectionService) { + mRemoteHotwordDetectionService = remoteHotwordDetectionService; + } + + void reportErrorLocked(int status) { + try { + mCallback.onError(status); + } catch (RemoteException e) { + Slog.w(TAG, "Failed to report onError status: " + e); + HotwordMetricsLogger.writeDetectorEvent(getDetectorType(), + HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_ERROR_EXCEPTION, + mVoiceInteractionServiceUid); + } + } + + /** + * Called when the trusted process is restarted. + */ + abstract void informRestartProcessLocked(); + + private static Pair<ParcelFileDescriptor, ParcelFileDescriptor> createPipe() { + ParcelFileDescriptor[] fileDescriptors; + try { + fileDescriptors = ParcelFileDescriptor.createPipe(); + } catch (IOException e) { + Slog.e(TAG, "Failed to create audio stream pipe", e); + return null; + } + + return Pair.create(fileDescriptors[0], fileDescriptors[1]); + } + + void saveProximityValueToBundle(HotwordDetectedResult result) { + synchronized (mLock) { + if (result != null && mProximityMeters != PROXIMITY_UNKNOWN) { + result.setProximity(mProximityMeters); + } + } + } + + private void setProximityValue(double proximityMeters) { + synchronized (mLock) { + mProximityMeters = proximityMeters; + } + } + + @SuppressWarnings("GuardedBy") + void closeExternalAudioStreamLocked(String reason) { + if (mCurrentAudioSink != null) { + Slog.i(TAG, "Closing external audio stream to hotword detector: " + reason); + bestEffortClose(mCurrentAudioSink); + mCurrentAudioSink = null; + } + } + + private static void bestEffortClose(Closeable... closeables) { + for (Closeable closeable : closeables) { + bestEffortClose(closeable); + } + } + + private static void bestEffortClose(Closeable closeable) { + try { + closeable.close(); + } catch (IOException e) { + if (DEBUG) { + Slog.w(TAG, "Failed closing", e); + } + } + } + + // TODO: Share this code with SoundTriggerMiddlewarePermission. + void enforcePermissionsForDataDelivery() { + Binder.withCleanCallingIdentity(() -> { + synchronized (mLock) { + enforcePermissionForPreflight(mContext, mVoiceInteractorIdentity, RECORD_AUDIO); + int hotwordOp = AppOpsManager.strOpToOp(AppOpsManager.OPSTR_RECORD_AUDIO_HOTWORD); + mAppOpsManager.noteOpNoThrow(hotwordOp, + mVoiceInteractorIdentity.uid, mVoiceInteractorIdentity.packageName, + mVoiceInteractorIdentity.attributionTag, OP_MESSAGE); + enforcePermissionForDataDelivery(mContext, mVoiceInteractorIdentity, + CAPTURE_AUDIO_HOTWORD, OP_MESSAGE); + } + }); + } + + /** + * Throws a {@link SecurityException} if the given identity has no permission to receive data. + * + * @param context A {@link Context}, used for permission checks. + * @param identity The identity to check. + * @param permission The identifier of the permission we want to check. + * @param reason The reason why we're requesting the permission, for auditing purposes. + */ + private static void enforcePermissionForDataDelivery(@NonNull Context context, + @NonNull Identity identity, @NonNull String permission, @NonNull String reason) { + final int status = PermissionUtil.checkPermissionForDataDelivery(context, identity, + permission, reason); + if (status != PermissionChecker.PERMISSION_GRANTED) { + throw new SecurityException( + TextUtils.formatSimple("Failed to obtain permission %s for identity %s", + permission, + SoundTriggerSessionPermissionsDecorator.toString(identity))); + } + } + + static void enforceExtraKeyphraseIdNotLeaked(HotwordDetectedResult result, + SoundTrigger.KeyphraseRecognitionEvent recognitionEvent) { + // verify the phrase ID in HotwordDetectedResult is not exposing extra phrases + // the DSP did not detect + for (SoundTrigger.KeyphraseRecognitionExtra keyphrase : recognitionEvent.keyphraseExtras) { + if (keyphrase.getKeyphraseId() == result.getHotwordPhraseId()) { + return; + } + } + throw new SecurityException("Ignoring #onDetected due to trusted service " + + "sharing a keyphrase ID which the DSP did not detect"); + } + + private int getDetectorType() { + if (this instanceof DspTrustedHotwordDetectorSession) { + return HotwordDetector.DETECTOR_TYPE_TRUSTED_HOTWORD_DSP; + } else if (this instanceof SoftwareTrustedHotwordDetectorSession) { + return HotwordDetector.DETECTOR_TYPE_TRUSTED_HOTWORD_SOFTWARE; + } + Slog.v(TAG, "Unexpected detector type"); + return -1; + } + + @SuppressWarnings("GuardedBy") + public void dumpLocked(String prefix, PrintWriter pw) { + pw.print(prefix); pw.print("mCallback="); pw.println(mCallback); + pw.print(prefix); pw.print("mUpdateStateAfterStartFinished="); + pw.println(mUpdateStateAfterStartFinished); + pw.print(prefix); pw.print("mInitialized="); pw.println(mInitialized); + pw.print(prefix); pw.print("mDestroyed="); pw.println(mDestroyed); + pw.print(prefix); pw.print("DetectorType="); + pw.println(HotwordDetector.detectorTypeToString(getDetectorType())); + pw.print(prefix); pw.print("mPerformingExternalSourceHotwordDetection="); + pw.println(mPerformingExternalSourceHotwordDetection); + } +} diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/SoftwareTrustedHotwordDetectorSession.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/SoftwareTrustedHotwordDetectorSession.java new file mode 100644 index 000000000000..693068958568 --- /dev/null +++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/SoftwareTrustedHotwordDetectorSession.java @@ -0,0 +1,214 @@ +/* + * 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.voiceinteraction; + +import static android.service.voice.HotwordDetectionService.AUDIO_SOURCE_MICROPHONE; + +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_PROCESS_RESTARTED_EXCEPTION; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__START_SOFTWARE_DETECTION; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECTED; +import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECTED; + +import android.annotation.NonNull; +import android.content.Context; +import android.media.AudioFormat; +import android.media.permission.Identity; +import android.os.PersistableBundle; +import android.os.RemoteException; +import android.os.SharedMemory; +import android.service.voice.HotwordDetectedResult; +import android.service.voice.HotwordDetectionService; +import android.service.voice.HotwordDetector; +import android.service.voice.HotwordRejectedResult; +import android.service.voice.IDspHotwordDetectionCallback; +import android.service.voice.IHotwordDetectionService; +import android.service.voice.IMicrophoneHotwordDetectionVoiceInteractionCallback; +import android.util.Slog; + +import com.android.internal.annotations.GuardedBy; +import com.android.internal.app.IHotwordRecognitionStatusCallback; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.concurrent.ScheduledExecutorService; + +/** + * A class that provides software trusted hotword detector to communicate with the {@link + * HotwordDetectionService}. + * + * This class can handle the hotword detection which detector is created by using + * {@link android.service.voice.VoiceInteractionService#createHotwordDetector(PersistableBundle, + * SharedMemory, HotwordDetector.Callback)}. + */ +final class SoftwareTrustedHotwordDetectorSession extends HotwordDetectorSession { + private static final String TAG = "SoftwareTrustedHotwordDetectorSession"; + + private IMicrophoneHotwordDetectionVoiceInteractionCallback mSoftwareCallback; + @GuardedBy("mLock") + private boolean mPerformingSoftwareHotwordDetection; + + SoftwareTrustedHotwordDetectorSession( + @NonNull HotwordDetectionConnection.ServiceConnection remoteHotwordDetectionService, + @NonNull Object lock, @NonNull Context context, + @NonNull IHotwordRecognitionStatusCallback callback, int voiceInteractionServiceUid, + Identity voiceInteractorIdentity, + @NonNull ScheduledExecutorService scheduledExecutorService, boolean logging) { + super(remoteHotwordDetectionService, lock, context, callback, voiceInteractionServiceUid, + voiceInteractorIdentity, scheduledExecutorService, logging); + } + + @SuppressWarnings("GuardedBy") + void startListeningFromMicLocked( + AudioFormat audioFormat, + IMicrophoneHotwordDetectionVoiceInteractionCallback callback) { + if (DEBUG) { + Slog.d(TAG, "startListeningFromMicLocked"); + } + mSoftwareCallback = callback; + + if (mPerformingSoftwareHotwordDetection) { + Slog.i(TAG, "Hotword validation is already in progress, ignoring."); + return; + } + mPerformingSoftwareHotwordDetection = true; + + startListeningFromMicLocked(); + } + + @SuppressWarnings("GuardedBy") + private void startListeningFromMicLocked() { + // TODO: consider making this a non-anonymous class. + IDspHotwordDetectionCallback internalCallback = new IDspHotwordDetectionCallback.Stub() { + @Override + public void onDetected(HotwordDetectedResult result) throws RemoteException { + if (DEBUG) { + Slog.d(TAG, "onDetected"); + } + synchronized (mLock) { + HotwordMetricsLogger.writeKeyphraseTriggerEvent( + HotwordDetector.DETECTOR_TYPE_TRUSTED_HOTWORD_SOFTWARE, + HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECTED); + if (!mPerformingSoftwareHotwordDetection) { + Slog.i(TAG, "Hotword detection has already completed"); + HotwordMetricsLogger.writeKeyphraseTriggerEvent( + HotwordDetector.DETECTOR_TYPE_TRUSTED_HOTWORD_SOFTWARE, + METRICS_KEYPHRASE_TRIGGERED_DETECT_UNEXPECTED_CALLBACK); + return; + } + mPerformingSoftwareHotwordDetection = false; + try { + enforcePermissionsForDataDelivery(); + } catch (SecurityException e) { + HotwordMetricsLogger.writeKeyphraseTriggerEvent( + HotwordDetector.DETECTOR_TYPE_TRUSTED_HOTWORD_SOFTWARE, + METRICS_KEYPHRASE_TRIGGERED_DETECT_SECURITY_EXCEPTION); + mSoftwareCallback.onError(); + return; + } + saveProximityValueToBundle(result); + HotwordDetectedResult newResult; + try { + newResult = mHotwordAudioStreamCopier.startCopyingAudioStreams(result); + } catch (IOException e) { + // TODO: Write event + mSoftwareCallback.onError(); + return; + } + mSoftwareCallback.onDetected(newResult, null, null); + Slog.i(TAG, "Egressed " + HotwordDetectedResult.getUsageSize(newResult) + + " bits from hotword trusted process"); + if (mDebugHotwordLogging) { + Slog.i(TAG, "Egressed detected result: " + newResult); + } + } + } + + @Override + public void onRejected(HotwordRejectedResult result) throws RemoteException { + if (DEBUG) { + Slog.wtf(TAG, "onRejected"); + } + HotwordMetricsLogger.writeKeyphraseTriggerEvent( + HotwordDetector.DETECTOR_TYPE_TRUSTED_HOTWORD_SOFTWARE, + HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECTED); + // onRejected isn't allowed here, and we are not expecting it. + } + }; + + mRemoteHotwordDetectionService.run( + service -> service.detectFromMicrophoneSource( + null, + AUDIO_SOURCE_MICROPHONE, + null, + null, + internalCallback)); + HotwordMetricsLogger.writeDetectorEvent( + HotwordDetector.DETECTOR_TYPE_TRUSTED_HOTWORD_SOFTWARE, + HOTWORD_DETECTOR_EVENTS__EVENT__START_SOFTWARE_DETECTION, + mVoiceInteractionServiceUid); + } + + @SuppressWarnings("GuardedBy") + void stopListeningLocked() { + if (DEBUG) { + Slog.d(TAG, "stopListeningLocked"); + } + if (!mPerformingSoftwareHotwordDetection) { + Slog.i(TAG, "Hotword detection is not running"); + return; + } + mPerformingSoftwareHotwordDetection = false; + + mRemoteHotwordDetectionService.run(IHotwordDetectionService::stopDetection); + + closeExternalAudioStreamLocked("stopping requested"); + } + + @Override + @SuppressWarnings("GuardedBy") + void informRestartProcessLocked() { + // TODO(b/244598068): Check HotwordAudioStreamManager first + Slog.v(TAG, "informRestartProcessLocked"); + mUpdateStateAfterStartFinished.set(false); + + try { + mCallback.onProcessRestarted(); + } catch (RemoteException e) { + Slog.w(TAG, "Failed to communicate #onProcessRestarted", e); + HotwordMetricsLogger.writeDetectorEvent( + HotwordDetector.DETECTOR_TYPE_TRUSTED_HOTWORD_SOFTWARE, + HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_PROCESS_RESTARTED_EXCEPTION, + mVoiceInteractionServiceUid); + } + + // Restart listening from microphone if the hotword process has been restarted. + if (mPerformingSoftwareHotwordDetection) { + Slog.i(TAG, "Process restarted: calling startRecognition() again"); + startListeningFromMicLocked(); + } + + mPerformingExternalSourceHotwordDetection = false; + closeExternalAudioStreamLocked("process restarted"); + } + + @SuppressWarnings("GuardedBy") + public void dumpLocked(String prefix, PrintWriter pw) { + super.dumpLocked(prefix, pw); + pw.print(prefix); pw.print("mPerformingSoftwareHotwordDetection="); + pw.println(mPerformingSoftwareHotwordDetection); + } +} diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/TrustedHotwordDetectorSession.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/TrustedHotwordDetectorSession.java deleted file mode 100644 index 02f5889cc520..000000000000 --- a/services/voiceinteraction/java/com/android/server/voiceinteraction/TrustedHotwordDetectorSession.java +++ /dev/null @@ -1,1325 +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. - */ - -package com.android.server.voiceinteraction; - -import static android.Manifest.permission.CAPTURE_AUDIO_HOTWORD; -import static android.Manifest.permission.RECORD_AUDIO; -import static android.service.attention.AttentionService.PROXIMITY_UNKNOWN; -import static android.service.voice.HotwordDetectionService.AUDIO_SOURCE_EXTERNAL; -import static android.service.voice.HotwordDetectionService.AUDIO_SOURCE_MICROPHONE; -import static android.service.voice.HotwordDetectionService.ENABLE_PROXIMITY_RESULT; -import static android.service.voice.HotwordDetectionService.INITIALIZATION_STATUS_SUCCESS; -import static android.service.voice.HotwordDetectionService.INITIALIZATION_STATUS_UNKNOWN; -import static android.service.voice.HotwordDetectionService.KEY_INITIALIZATION_STATUS; - -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_ERROR; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_SUCCESS; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_UNKNOWN_NO_VALUE; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_UNKNOWN_OVER_MAX_CUSTOM_VALUE; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_UNKNOWN_TIMEOUT; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTION_SERVICE_RESTARTED__REASON__AUDIO_SERVICE_DIED; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTION_SERVICE_RESTARTED__REASON__SCHEDULE; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__APP_REQUEST_UPDATE_STATE; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_ERROR_EXCEPTION; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_PROCESS_RESTARTED_EXCEPTION; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_REJECTED_EXCEPTION; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_STATUS_REPORTED_EXCEPTION; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_UPDATE_STATE_AFTER_TIMEOUT; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__CALL_UPDATE_STATE_EXCEPTION; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__EXTERNAL_SOURCE_DETECTED; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__EXTERNAL_SOURCE_DETECT_SECURITY_EXCEPTION; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__EXTERNAL_SOURCE_REJECTED; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__ON_CONNECTED; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__ON_DISCONNECTED; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__REQUEST_BIND_SERVICE; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__REQUEST_BIND_SERVICE_FAIL; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__REQUEST_UPDATE_STATE; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__START_EXTERNAL_SOURCE_DETECTION; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_EVENTS__EVENT__START_SOFTWARE_DETECTION; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__DETECTOR_TYPE__NORMAL_DETECTOR; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__DETECTOR_TYPE__TRUSTED_DETECTOR_DSP; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECTED; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECT_SECURITY_EXCEPTION; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECT_TIMEOUT; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECT_UNEXPECTED_CALLBACK; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__KEYPHRASE_TRIGGER; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECTED; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECTED_FROM_RESTART; -import static com.android.internal.util.FrameworkStatsLog.HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECT_UNEXPECTED_CALLBACK; -import static com.android.server.voiceinteraction.SoundTriggerSessionPermissionsDecorator.enforcePermissionForPreflight; - -import android.annotation.NonNull; -import android.annotation.Nullable; -import android.app.AppOpsManager; -import android.attention.AttentionManagerInternal; -import android.content.ComponentName; -import android.content.ContentCaptureOptions; -import android.content.Context; -import android.content.Intent; -import android.content.PermissionChecker; -import android.hardware.soundtrigger.IRecognitionStatusCallback; -import android.hardware.soundtrigger.SoundTrigger; -import android.media.AudioFormat; -import android.media.AudioManagerInternal; -import android.media.permission.Identity; -import android.media.permission.PermissionUtil; -import android.os.Binder; -import android.os.Bundle; -import android.os.IBinder; -import android.os.IRemoteCallback; -import android.os.ParcelFileDescriptor; -import android.os.PersistableBundle; -import android.os.RemoteException; -import android.os.ServiceManager; -import android.os.SharedMemory; -import android.provider.DeviceConfig; -import android.service.voice.HotwordDetectedResult; -import android.service.voice.HotwordDetectionService; -import android.service.voice.HotwordDetector; -import android.service.voice.HotwordRejectedResult; -import android.service.voice.IDspHotwordDetectionCallback; -import android.service.voice.IHotwordDetectionService; -import android.service.voice.IMicrophoneHotwordDetectionVoiceInteractionCallback; -import android.service.voice.VoiceInteractionManagerInternal.HotwordDetectionServiceIdentity; -import android.speech.IRecognitionServiceManager; -import android.text.TextUtils; -import android.util.Pair; -import android.util.Slog; -import android.view.contentcapture.IContentCaptureManager; - -import com.android.internal.annotations.GuardedBy; -import com.android.internal.app.IHotwordRecognitionStatusCallback; -import com.android.internal.infra.AndroidFuture; -import com.android.internal.infra.ServiceConnector; -import com.android.server.LocalServices; -import com.android.server.pm.permission.PermissionManagerServiceInternal; - -import java.io.Closeable; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.time.Duration; -import java.time.Instant; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Function; - -/** - * A class that provides the communication with the HotwordDetectionService. - */ -final class TrustedHotwordDetectorSession { - private static final String TAG = "TrustedHotwordDetectorSession"; - static final boolean DEBUG = false; - - private static final String KEY_RESTART_PERIOD_IN_SECONDS = "restart_period_in_seconds"; - // TODO: These constants need to be refined. - // The validation timeout value is 3 seconds for onDetect of DSP trigger event. - private static final long VALIDATION_TIMEOUT_MILLIS = 3000; - // Write the onDetect timeout metric when it takes more time than MAX_VALIDATION_TIMEOUT_MILLIS. - private static final long MAX_VALIDATION_TIMEOUT_MILLIS = 4000; - private static final long MAX_UPDATE_TIMEOUT_MILLIS = 30000; - private static final long EXTERNAL_HOTWORD_CLEANUP_MILLIS = 2000; - private static final Duration MAX_UPDATE_TIMEOUT_DURATION = - Duration.ofMillis(MAX_UPDATE_TIMEOUT_MILLIS); - private static final long RESET_DEBUG_HOTWORD_LOGGING_TIMEOUT_MILLIS = 60 * 60 * 1000; // 1 hour - private static final int MAX_ISOLATED_PROCESS_NUMBER = 10; - - // The error codes are used for onError callback - private static final int HOTWORD_DETECTION_SERVICE_DIED = -1; - private static final int CALLBACK_ONDETECTED_GOT_SECURITY_EXCEPTION = -2; - private static final int CALLBACK_DETECT_TIMEOUT = -3; - private static final int CALLBACK_ONDETECTED_STREAM_COPY_ERROR = -4; - - // Hotword metrics - private static final int METRICS_INIT_UNKNOWN_TIMEOUT = - HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_UNKNOWN_TIMEOUT; - private static final int METRICS_INIT_UNKNOWN_NO_VALUE = - HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_UNKNOWN_NO_VALUE; - private static final int METRICS_INIT_UNKNOWN_OVER_MAX_CUSTOM_VALUE = - HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_UNKNOWN_OVER_MAX_CUSTOM_VALUE; - private static final int METRICS_INIT_CALLBACK_STATE_ERROR = - HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_ERROR; - private static final int METRICS_INIT_CALLBACK_STATE_SUCCESS = - HOTWORD_DETECTION_SERVICE_INIT_RESULT_REPORTED__RESULT__CALLBACK_INIT_STATE_SUCCESS; - - private static final int METRICS_KEYPHRASE_TRIGGERED_DETECT_SECURITY_EXCEPTION = - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECT_SECURITY_EXCEPTION; - private static final int METRICS_KEYPHRASE_TRIGGERED_DETECT_UNEXPECTED_CALLBACK = - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECT_UNEXPECTED_CALLBACK; - private static final int METRICS_KEYPHRASE_TRIGGERED_REJECT_UNEXPECTED_CALLBACK = - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECT_UNEXPECTED_CALLBACK; - - private static final int METRICS_EXTERNAL_SOURCE_DETECTED = - HOTWORD_DETECTOR_EVENTS__EVENT__EXTERNAL_SOURCE_DETECTED; - private static final int METRICS_EXTERNAL_SOURCE_REJECTED = - HOTWORD_DETECTOR_EVENTS__EVENT__EXTERNAL_SOURCE_REJECTED; - private static final int METRICS_EXTERNAL_SOURCE_DETECT_SECURITY_EXCEPTION = - HOTWORD_DETECTOR_EVENTS__EVENT__EXTERNAL_SOURCE_DETECT_SECURITY_EXCEPTION; - private static final int METRICS_CALLBACK_ON_STATUS_REPORTED_EXCEPTION = - HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_STATUS_REPORTED_EXCEPTION; - - private final Executor mAudioCopyExecutor = Executors.newCachedThreadPool(); - // TODO: This may need to be a Handler(looper) - private final ScheduledExecutorService mScheduledExecutorService = - Executors.newSingleThreadScheduledExecutor(); - private final AppOpsManager mAppOpsManager; - private final HotwordAudioStreamCopier mHotwordAudioStreamCopier; - @Nullable private final ScheduledFuture<?> mCancellationTaskFuture; - private final AtomicBoolean mUpdateStateAfterStartFinished = new AtomicBoolean(false); - private final IBinder.DeathRecipient mAudioServerDeathRecipient = this::audioServerDied; - private final @NonNull ServiceConnectionFactory mServiceConnectionFactory; - private final IHotwordRecognitionStatusCallback mCallback; - private final int mDetectorType; - /** - * Time after which each HotwordDetectionService process is stopped and replaced by a new one. - * 0 indicates no restarts. - */ - private final int mReStartPeriodSeconds; - - final Object mLock; - final int mVoiceInteractionServiceUid; - final ComponentName mDetectionComponentName; - final int mUser; - final Context mContext; - - @Nullable AttentionManagerInternal mAttentionManagerInternal = null; - - final AttentionManagerInternal.ProximityUpdateCallbackInternal mProximityCallbackInternal = - this::setProximityValue; - - - volatile HotwordDetectionServiceIdentity mIdentity; - private IMicrophoneHotwordDetectionVoiceInteractionCallback mSoftwareCallback; - private Instant mLastRestartInstant; - - private ScheduledFuture<?> mCancellationKeyPhraseDetectionFuture; - private ScheduledFuture<?> mDebugHotwordLoggingTimeoutFuture = null; - - /** Identity used for attributing app ops when delivering data to the Interactor. */ - @GuardedBy("mLock") - @Nullable - private final Identity mVoiceInteractorIdentity; - @GuardedBy("mLock") - private ParcelFileDescriptor mCurrentAudioSink; - @GuardedBy("mLock") - private boolean mValidatingDspTrigger = false; - @GuardedBy("mLock") - private boolean mPerformingSoftwareHotwordDetection; - private @NonNull ServiceConnection mRemoteHotwordDetectionService; - private IBinder mAudioFlinger; - private boolean mDebugHotwordLogging = false; - @GuardedBy("mLock") - private double mProximityMeters = PROXIMITY_UNKNOWN; - - TrustedHotwordDetectorSession(Object lock, Context context, int voiceInteractionServiceUid, - Identity voiceInteractorIdentity, ComponentName serviceName, int userId, - boolean bindInstantServiceAllowed, @Nullable PersistableBundle options, - @Nullable SharedMemory sharedMemory, - @NonNull IHotwordRecognitionStatusCallback callback, int detectorType) { - if (callback == null) { - Slog.w(TAG, "Callback is null while creating connection"); - throw new IllegalArgumentException("Callback is null while creating connection"); - } - mLock = lock; - mContext = context; - mVoiceInteractionServiceUid = voiceInteractionServiceUid; - mVoiceInteractorIdentity = voiceInteractorIdentity; - mAppOpsManager = mContext.getSystemService(AppOpsManager.class); - mHotwordAudioStreamCopier = new HotwordAudioStreamCopier(mAppOpsManager, detectorType, - mVoiceInteractorIdentity.uid, mVoiceInteractorIdentity.packageName, - mVoiceInteractorIdentity.attributionTag); - mDetectionComponentName = serviceName; - mUser = userId; - mCallback = callback; - mDetectorType = detectorType; - mReStartPeriodSeconds = DeviceConfig.getInt(DeviceConfig.NAMESPACE_VOICE_INTERACTION, - KEY_RESTART_PERIOD_IN_SECONDS, 0); - final Intent intent = new Intent(HotwordDetectionService.SERVICE_INTERFACE); - intent.setComponent(mDetectionComponentName); - initAudioFlingerLocked(); - - mServiceConnectionFactory = new ServiceConnectionFactory(intent, bindInstantServiceAllowed); - - mRemoteHotwordDetectionService = mServiceConnectionFactory.createLocked(); - if (ENABLE_PROXIMITY_RESULT) { - mAttentionManagerInternal = LocalServices.getService(AttentionManagerInternal.class); - if (mAttentionManagerInternal != null) { - mAttentionManagerInternal.onStartProximityUpdates(mProximityCallbackInternal); - } - } - - mLastRestartInstant = Instant.now(); - updateStateAfterProcessStart(options, sharedMemory); - - if (mReStartPeriodSeconds <= 0) { - mCancellationTaskFuture = null; - } else { - // TODO: we need to be smarter here, e.g. schedule it a bit more often, - // but wait until the current session is closed. - mCancellationTaskFuture = mScheduledExecutorService.scheduleAtFixedRate(() -> { - Slog.v(TAG, "Time to restart the process, TTL has passed"); - synchronized (mLock) { - restartProcessLocked(); - HotwordMetricsLogger.writeServiceRestartEvent(mDetectorType, - HOTWORD_DETECTION_SERVICE_RESTARTED__REASON__SCHEDULE); - } - }, mReStartPeriodSeconds, mReStartPeriodSeconds, TimeUnit.SECONDS); - } - } - - private void initAudioFlingerLocked() { - if (DEBUG) { - Slog.d(TAG, "initAudioFlingerLocked"); - } - mAudioFlinger = ServiceManager.waitForService("media.audio_flinger"); - if (mAudioFlinger == null) { - throw new IllegalStateException("Service media.audio_flinger wasn't found."); - } - if (DEBUG) { - Slog.d(TAG, "Obtained audio_flinger binder."); - } - try { - mAudioFlinger.linkToDeath(mAudioServerDeathRecipient, /* flags= */ 0); - } catch (RemoteException e) { - Slog.w(TAG, "Audio server died before we registered a DeathRecipient; retrying init.", - e); - initAudioFlingerLocked(); - } - } - - private void audioServerDied() { - Slog.w(TAG, "Audio server died; restarting the HotwordDetectionService."); - synchronized (mLock) { - // TODO: Check if this needs to be scheduled on a different thread. - initAudioFlingerLocked(); - // We restart the process instead of simply sending over the new binder, to avoid race - // conditions with audio reading in the service. - restartProcessLocked(); - HotwordMetricsLogger.writeServiceRestartEvent(mDetectorType, - HOTWORD_DETECTION_SERVICE_RESTARTED__REASON__AUDIO_SERVICE_DIED); - } - } - - private void updateStateAfterProcessStart( - PersistableBundle options, SharedMemory sharedMemory) { - if (DEBUG) { - Slog.d(TAG, "updateStateAfterProcessStart"); - } - mRemoteHotwordDetectionService.postAsync(service -> { - AndroidFuture<Void> future = new AndroidFuture<>(); - IRemoteCallback statusCallback = new IRemoteCallback.Stub() { - @Override - public void sendResult(Bundle bundle) throws RemoteException { - if (DEBUG) { - Slog.d(TAG, "updateState finish"); - } - future.complete(null); - if (mUpdateStateAfterStartFinished.getAndSet(true)) { - Slog.w(TAG, "call callback after timeout"); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_UPDATE_STATE_AFTER_TIMEOUT, - mVoiceInteractionServiceUid); - return; - } - Pair<Integer, Integer> statusResultPair = getInitStatusAndMetricsResult(bundle); - int status = statusResultPair.first; - int initResultMetricsResult = statusResultPair.second; - try { - mCallback.onStatusReported(status); - HotwordMetricsLogger.writeServiceInitResultEvent(mDetectorType, - initResultMetricsResult); - } catch (RemoteException e) { - Slog.w(TAG, "Failed to report initialization status: " + e); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - METRICS_CALLBACK_ON_STATUS_REPORTED_EXCEPTION, - mVoiceInteractionServiceUid); - } - } - }; - try { - service.updateState(options, sharedMemory, statusCallback); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__REQUEST_UPDATE_STATE, - mVoiceInteractionServiceUid); - } catch (RemoteException e) { - // TODO: (b/181842909) Report an error to voice interactor - Slog.w(TAG, "Failed to updateState for HotwordDetectionService", e); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__CALL_UPDATE_STATE_EXCEPTION, - mVoiceInteractionServiceUid); - } - return future.orTimeout(MAX_UPDATE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); - }).whenComplete((res, err) -> { - if (err instanceof TimeoutException) { - Slog.w(TAG, "updateState timed out"); - if (mUpdateStateAfterStartFinished.getAndSet(true)) { - return; - } - try { - mCallback.onStatusReported(INITIALIZATION_STATUS_UNKNOWN); - HotwordMetricsLogger.writeServiceInitResultEvent(mDetectorType, - METRICS_INIT_UNKNOWN_TIMEOUT); - } catch (RemoteException e) { - Slog.w(TAG, "Failed to report initialization status UNKNOWN", e); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - METRICS_CALLBACK_ON_STATUS_REPORTED_EXCEPTION, - mVoiceInteractionServiceUid); - } - } else if (err != null) { - Slog.w(TAG, "Failed to update state: " + err); - } else { - // NOTE: so far we don't need to take any action. - } - }); - } - - private static Pair<Integer, Integer> getInitStatusAndMetricsResult(Bundle bundle) { - if (bundle == null) { - return new Pair<>(INITIALIZATION_STATUS_UNKNOWN, METRICS_INIT_UNKNOWN_NO_VALUE); - } - int status = bundle.getInt(KEY_INITIALIZATION_STATUS, INITIALIZATION_STATUS_UNKNOWN); - if (status > HotwordDetectionService.getMaxCustomInitializationStatus()) { - return new Pair<>(INITIALIZATION_STATUS_UNKNOWN, - status == INITIALIZATION_STATUS_UNKNOWN - ? METRICS_INIT_UNKNOWN_NO_VALUE - : METRICS_INIT_UNKNOWN_OVER_MAX_CUSTOM_VALUE); - } - // TODO: should guard against negative here - int metricsResult = status == INITIALIZATION_STATUS_SUCCESS - ? METRICS_INIT_CALLBACK_STATE_SUCCESS - : METRICS_INIT_CALLBACK_STATE_ERROR; - return new Pair<>(status, metricsResult); - } - - private boolean isBound() { - synchronized (mLock) { - return mRemoteHotwordDetectionService.isBound(); - } - } - - void cancelLocked() { - Slog.v(TAG, "cancelLocked"); - clearDebugHotwordLoggingTimeoutLocked(); - mDebugHotwordLogging = false; - mRemoteHotwordDetectionService.unbind(); - LocalServices.getService(PermissionManagerServiceInternal.class) - .setHotwordDetectionServiceProvider(null); - if (mIdentity != null) { - removeServiceUidForAudioPolicy(mIdentity.getIsolatedUid()); - } - mIdentity = null; - if (mCancellationTaskFuture != null) { - mCancellationTaskFuture.cancel(/* may interrupt */ true); - } - if (mAudioFlinger != null) { - mAudioFlinger.unlinkToDeath(mAudioServerDeathRecipient, /* flags= */ 0); - } - if (mAttentionManagerInternal != null) { - mAttentionManagerInternal.onStopProximityUpdates(mProximityCallbackInternal); - } - } - - void updateStateLocked(PersistableBundle options, SharedMemory sharedMemory) { - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__APP_REQUEST_UPDATE_STATE, - mVoiceInteractionServiceUid); - - // Prevent doing the init late, so restart is handled equally to a clean process start. - // TODO(b/191742511): this logic needs a test - if (!mUpdateStateAfterStartFinished.get() - && Instant.now().minus(MAX_UPDATE_TIMEOUT_DURATION).isBefore(mLastRestartInstant)) { - Slog.v(TAG, "call updateStateAfterProcessStart"); - updateStateAfterProcessStart(options, sharedMemory); - } else { - mRemoteHotwordDetectionService.run( - service -> service.updateState(options, sharedMemory, null /* callback */)); - } - } - - void startListeningFromMic( - AudioFormat audioFormat, - IMicrophoneHotwordDetectionVoiceInteractionCallback callback) { - if (DEBUG) { - Slog.d(TAG, "startListeningFromMic"); - } - mSoftwareCallback = callback; - - synchronized (mLock) { - if (mPerformingSoftwareHotwordDetection) { - Slog.i(TAG, "Hotword validation is already in progress, ignoring."); - return; - } - mPerformingSoftwareHotwordDetection = true; - - startListeningFromMicLocked(); - } - } - - private void startListeningFromMicLocked() { - // TODO: consider making this a non-anonymous class. - IDspHotwordDetectionCallback internalCallback = new IDspHotwordDetectionCallback.Stub() { - @Override - public void onDetected(HotwordDetectedResult result) throws RemoteException { - if (DEBUG) { - Slog.d(TAG, "onDetected"); - } - synchronized (mLock) { - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECTED); - if (!mPerformingSoftwareHotwordDetection) { - Slog.i(TAG, "Hotword detection has already completed"); - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - METRICS_KEYPHRASE_TRIGGERED_DETECT_UNEXPECTED_CALLBACK); - return; - } - mPerformingSoftwareHotwordDetection = false; - try { - enforcePermissionsForDataDelivery(); - } catch (SecurityException e) { - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - METRICS_KEYPHRASE_TRIGGERED_DETECT_SECURITY_EXCEPTION); - mSoftwareCallback.onError(); - return; - } - saveProximityValueToBundle(result); - HotwordDetectedResult newResult; - try { - newResult = mHotwordAudioStreamCopier.startCopyingAudioStreams(result); - } catch (IOException e) { - // TODO: Write event - mSoftwareCallback.onError(); - return; - } - mSoftwareCallback.onDetected(newResult, null, null); - Slog.i(TAG, "Egressed " + HotwordDetectedResult.getUsageSize(newResult) - + " bits from hotword trusted process"); - if (mDebugHotwordLogging) { - Slog.i(TAG, "Egressed detected result: " + newResult); - } - } - } - - @Override - public void onRejected(HotwordRejectedResult result) throws RemoteException { - if (DEBUG) { - Slog.wtf(TAG, "onRejected"); - } - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECTED); - // onRejected isn't allowed here, and we are not expecting it. - } - }; - - mRemoteHotwordDetectionService.run( - service -> service.detectFromMicrophoneSource( - null, - AUDIO_SOURCE_MICROPHONE, - null, - null, - internalCallback)); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__START_SOFTWARE_DETECTION, - mVoiceInteractionServiceUid); - } - - public void startListeningFromExternalSource( - ParcelFileDescriptor audioStream, - AudioFormat audioFormat, - @Nullable PersistableBundle options, - IMicrophoneHotwordDetectionVoiceInteractionCallback callback) { - if (DEBUG) { - Slog.d(TAG, "startListeningFromExternalSource"); - } - - handleExternalSourceHotwordDetection( - audioStream, - audioFormat, - options, - callback); - } - - void stopListening() { - if (DEBUG) { - Slog.d(TAG, "stopListening"); - } - synchronized (mLock) { - stopListeningLocked(); - } - } - - private void stopListeningLocked() { - if (!mPerformingSoftwareHotwordDetection) { - Slog.i(TAG, "Hotword detection is not running"); - return; - } - mPerformingSoftwareHotwordDetection = false; - - mRemoteHotwordDetectionService.run(IHotwordDetectionService::stopDetection); - - if (mCurrentAudioSink != null) { - Slog.i(TAG, "Closing audio stream to hotword detector: stopping requested"); - bestEffortClose(mCurrentAudioSink); - } - mCurrentAudioSink = null; - } - - void triggerHardwareRecognitionEventForTestLocked( - SoundTrigger.KeyphraseRecognitionEvent event, - IHotwordRecognitionStatusCallback callback) { - if (DEBUG) { - Slog.d(TAG, "triggerHardwareRecognitionEventForTestLocked"); - } - detectFromDspSource(event, callback); - } - - private void detectFromDspSource(SoundTrigger.KeyphraseRecognitionEvent recognitionEvent, - IHotwordRecognitionStatusCallback externalCallback) { - if (DEBUG) { - Slog.d(TAG, "detectFromDspSource"); - } - - AtomicBoolean timeoutDetected = new AtomicBoolean(false); - // TODO: consider making this a non-anonymous class. - IDspHotwordDetectionCallback internalCallback = new IDspHotwordDetectionCallback.Stub() { - @Override - public void onDetected(HotwordDetectedResult result) throws RemoteException { - if (DEBUG) { - Slog.d(TAG, "onDetected"); - } - synchronized (mLock) { - if (mCancellationKeyPhraseDetectionFuture != null) { - mCancellationKeyPhraseDetectionFuture.cancel(true); - } - if (timeoutDetected.get()) { - return; - } - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECTED); - if (!mValidatingDspTrigger) { - Slog.i(TAG, "Ignoring #onDetected due to a process restart"); - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - METRICS_KEYPHRASE_TRIGGERED_DETECT_UNEXPECTED_CALLBACK); - return; - } - mValidatingDspTrigger = false; - try { - enforcePermissionsForDataDelivery(); - enforceExtraKeyphraseIdNotLeaked(result, recognitionEvent); - } catch (SecurityException e) { - Slog.i(TAG, "Ignoring #onDetected due to a SecurityException", e); - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - METRICS_KEYPHRASE_TRIGGERED_DETECT_SECURITY_EXCEPTION); - externalCallback.onError(CALLBACK_ONDETECTED_GOT_SECURITY_EXCEPTION); - return; - } - saveProximityValueToBundle(result); - HotwordDetectedResult newResult; - try { - newResult = mHotwordAudioStreamCopier.startCopyingAudioStreams(result); - } catch (IOException e) { - // TODO: Write event - externalCallback.onError(CALLBACK_ONDETECTED_STREAM_COPY_ERROR); - return; - } - externalCallback.onKeyphraseDetected(recognitionEvent, newResult); - Slog.i(TAG, "Egressed " + HotwordDetectedResult.getUsageSize(newResult) - + " bits from hotword trusted process"); - if (mDebugHotwordLogging) { - Slog.i(TAG, "Egressed detected result: " + newResult); - } - } - } - - @Override - public void onRejected(HotwordRejectedResult result) throws RemoteException { - if (DEBUG) { - Slog.d(TAG, "onRejected"); - } - synchronized (mLock) { - if (mCancellationKeyPhraseDetectionFuture != null) { - mCancellationKeyPhraseDetectionFuture.cancel(true); - } - if (timeoutDetected.get()) { - return; - } - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECTED); - if (!mValidatingDspTrigger) { - Slog.i(TAG, "Ignoring #onRejected due to a process restart"); - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - METRICS_KEYPHRASE_TRIGGERED_REJECT_UNEXPECTED_CALLBACK); - return; - } - mValidatingDspTrigger = false; - externalCallback.onRejected(result); - if (mDebugHotwordLogging && result != null) { - Slog.i(TAG, "Egressed rejected result: " + result); - } - } - } - }; - - synchronized (mLock) { - mValidatingDspTrigger = true; - mRemoteHotwordDetectionService.run(service -> { - // We use the VALIDATION_TIMEOUT_MILLIS to inform that the client needs to invoke - // the callback before timeout value. In order to reduce the latency impact between - // server side and client side, we need to use another timeout value - // MAX_VALIDATION_TIMEOUT_MILLIS to monitor it. - mCancellationKeyPhraseDetectionFuture = mScheduledExecutorService.schedule( - () -> { - // TODO: avoid allocate every time - timeoutDetected.set(true); - Slog.w(TAG, "Timed out on #detectFromDspSource"); - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__DETECT_TIMEOUT); - try { - externalCallback.onError(CALLBACK_DETECT_TIMEOUT); - } catch (RemoteException e) { - Slog.w(TAG, "Failed to report onError status: ", e); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_ERROR_EXCEPTION, - mVoiceInteractionServiceUid); - } - }, - MAX_VALIDATION_TIMEOUT_MILLIS, - TimeUnit.MILLISECONDS); - service.detectFromDspSource( - recognitionEvent, - recognitionEvent.getCaptureFormat(), - VALIDATION_TIMEOUT_MILLIS, - internalCallback); - }); - } - } - - void forceRestart() { - Slog.v(TAG, "Requested to restart the service internally. Performing the restart"); - synchronized (mLock) { - restartProcessLocked(); - } - } - - void setDebugHotwordLoggingLocked(boolean logging) { - Slog.v(TAG, "setDebugHotwordLoggingLocked: " + logging); - clearDebugHotwordLoggingTimeoutLocked(); - mDebugHotwordLogging = logging; - - if (logging) { - // Reset mDebugHotwordLogging to false after one hour - mDebugHotwordLoggingTimeoutFuture = mScheduledExecutorService.schedule(() -> { - Slog.v(TAG, "Timeout to reset mDebugHotwordLogging to false"); - synchronized (mLock) { - mDebugHotwordLogging = false; - } - }, RESET_DEBUG_HOTWORD_LOGGING_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); - } - } - - private void clearDebugHotwordLoggingTimeoutLocked() { - if (mDebugHotwordLoggingTimeoutFuture != null) { - mDebugHotwordLoggingTimeoutFuture.cancel(/* mayInterruptIfRunning= */true); - mDebugHotwordLoggingTimeoutFuture = null; - } - } - - private void restartProcessLocked() { - // TODO(b/244598068): Check HotwordAudioStreamManager first - Slog.v(TAG, "Restarting hotword detection process"); - ServiceConnection oldConnection = mRemoteHotwordDetectionService; - HotwordDetectionServiceIdentity previousIdentity = mIdentity; - - // TODO(volnov): this can be done after connect() has been successful. - if (mValidatingDspTrigger) { - // We're restarting the process while it's processing a DSP trigger, so report a - // rejection. This also allows the Interactor to startReco again - try { - mCallback.onRejected(new HotwordRejectedResult.Builder().build()); - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - mDetectorType, - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__REJECTED_FROM_RESTART); - } catch (RemoteException e) { - Slog.w(TAG, "Failed to call #rejected"); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_REJECTED_EXCEPTION, - mVoiceInteractionServiceUid); - } - mValidatingDspTrigger = false; - } - - mUpdateStateAfterStartFinished.set(false); - mLastRestartInstant = Instant.now(); - - // Recreate connection to reset the cache. - mRemoteHotwordDetectionService = mServiceConnectionFactory.createLocked(); - - Slog.v(TAG, "Started the new process, issuing #onProcessRestarted"); - try { - mCallback.onProcessRestarted(); - } catch (RemoteException e) { - Slog.w(TAG, "Failed to communicate #onProcessRestarted", e); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_PROCESS_RESTARTED_EXCEPTION, - mVoiceInteractionServiceUid); - } - - // Restart listening from microphone if the hotword process has been restarted. - if (mPerformingSoftwareHotwordDetection) { - Slog.i(TAG, "Process restarted: calling startRecognition() again"); - startListeningFromMicLocked(); - } - - if (mCurrentAudioSink != null) { - Slog.i(TAG, "Closing external audio stream to hotword detector: process restarted"); - bestEffortClose(mCurrentAudioSink); - mCurrentAudioSink = null; - } - - if (DEBUG) { - Slog.i(TAG, "#onProcessRestarted called, unbinding from the old process"); - } - oldConnection.ignoreConnectionStatusEvents(); - oldConnection.unbind(); - if (previousIdentity != null) { - removeServiceUidForAudioPolicy(previousIdentity.getIsolatedUid()); - } - } - - static final class SoundTriggerCallback extends IRecognitionStatusCallback.Stub { - private SoundTrigger.KeyphraseRecognitionEvent mRecognitionEvent; - private final HotwordDetectionConnection mHotwordDetectionConnection; - private final IHotwordRecognitionStatusCallback mExternalCallback; - - SoundTriggerCallback(IHotwordRecognitionStatusCallback callback, - HotwordDetectionConnection connection) { - mHotwordDetectionConnection = connection; - mExternalCallback = callback; - } - - @Override - public void onKeyphraseDetected(SoundTrigger.KeyphraseRecognitionEvent recognitionEvent) - throws RemoteException { - if (DEBUG) { - Slog.d(TAG, "onKeyphraseDetected recognitionEvent : " + recognitionEvent); - } - final boolean useHotwordDetectionService = mHotwordDetectionConnection != null; - if (useHotwordDetectionService) { - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__DETECTOR_TYPE__TRUSTED_DETECTOR_DSP, - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__KEYPHRASE_TRIGGER); - mRecognitionEvent = recognitionEvent; - mHotwordDetectionConnection.detectFromDspSource( - recognitionEvent, mExternalCallback); - } else { - HotwordMetricsLogger.writeKeyphraseTriggerEvent( - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__DETECTOR_TYPE__NORMAL_DETECTOR, - HOTWORD_DETECTOR_KEYPHRASE_TRIGGERED__RESULT__KEYPHRASE_TRIGGER); - mExternalCallback.onKeyphraseDetected(recognitionEvent, null); - } - } - - @Override - public void onGenericSoundTriggerDetected( - SoundTrigger.GenericRecognitionEvent recognitionEvent) - throws RemoteException { - mExternalCallback.onGenericSoundTriggerDetected(recognitionEvent); - } - - @Override - public void onError(int status) throws RemoteException { - mExternalCallback.onError(status); - } - - @Override - public void onRecognitionPaused() throws RemoteException { - mExternalCallback.onRecognitionPaused(); - } - - @Override - public void onRecognitionResumed() throws RemoteException { - mExternalCallback.onRecognitionResumed(); - } - } - - public void dump(String prefix, PrintWriter pw) { - pw.print(prefix); pw.print("mReStartPeriodSeconds="); pw.println(mReStartPeriodSeconds); - pw.print(prefix); - pw.print("mBound=" + mRemoteHotwordDetectionService.isBound()); - pw.print(", mValidatingDspTrigger=" + mValidatingDspTrigger); - pw.print(", mPerformingSoftwareHotwordDetection=" + mPerformingSoftwareHotwordDetection); - pw.print(", mRestartCount=" + mServiceConnectionFactory.mRestartCount); - pw.print(", mLastRestartInstant=" + mLastRestartInstant); - pw.println(", mDetectorType=" + HotwordDetector.detectorTypeToString(mDetectorType)); - } - - private void handleExternalSourceHotwordDetection( - ParcelFileDescriptor audioStream, - AudioFormat audioFormat, - @Nullable PersistableBundle options, - IMicrophoneHotwordDetectionVoiceInteractionCallback callback) { - if (DEBUG) { - Slog.d(TAG, "#handleExternalSourceHotwordDetection"); - } - InputStream audioSource = new ParcelFileDescriptor.AutoCloseInputStream(audioStream); - - Pair<ParcelFileDescriptor, ParcelFileDescriptor> clientPipe = createPipe(); - if (clientPipe == null) { - // TODO: Need to propagate as unknown error or something? - return; - } - ParcelFileDescriptor serviceAudioSink = clientPipe.second; - ParcelFileDescriptor serviceAudioSource = clientPipe.first; - - synchronized (mLock) { - mCurrentAudioSink = serviceAudioSink; - } - - mAudioCopyExecutor.execute(() -> { - try (InputStream source = audioSource; - OutputStream fos = - new ParcelFileDescriptor.AutoCloseOutputStream(serviceAudioSink)) { - - byte[] buffer = new byte[1024]; - while (true) { - int bytesRead = source.read(buffer, 0, 1024); - - if (bytesRead < 0) { - Slog.i(TAG, "Reached end of stream for external hotword"); - break; - } - - // TODO: First write to ring buffer to make sure we don't lose data if the next - // statement fails. - // ringBuffer.append(buffer, bytesRead); - fos.write(buffer, 0, bytesRead); - } - } catch (IOException e) { - Slog.w(TAG, "Failed supplying audio data to validator", e); - - try { - callback.onError(); - } catch (RemoteException ex) { - Slog.w(TAG, "Failed to report onError status: " + ex); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_ERROR_EXCEPTION, - mVoiceInteractionServiceUid); - } - } finally { - synchronized (mLock) { - mCurrentAudioSink = null; - } - } - }); - - // TODO: handle cancellations well - // TODO: what if we cancelled and started a new one? - mRemoteHotwordDetectionService.run( - service -> { - service.detectFromMicrophoneSource( - serviceAudioSource, - // TODO: consider making a proxy callback + copy of audio format - AUDIO_SOURCE_EXTERNAL, - audioFormat, - options, - new IDspHotwordDetectionCallback.Stub() { - @Override - public void onRejected(HotwordRejectedResult result) - throws RemoteException { - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - METRICS_EXTERNAL_SOURCE_REJECTED, - mVoiceInteractionServiceUid); - mScheduledExecutorService.schedule( - () -> { - bestEffortClose(serviceAudioSink, audioSource); - }, - EXTERNAL_HOTWORD_CLEANUP_MILLIS, - TimeUnit.MILLISECONDS); - - callback.onRejected(result); - - if (result != null) { - Slog.i(TAG, "Egressed 'hotword rejected result' " - + "from hotword trusted process"); - if (mDebugHotwordLogging) { - Slog.i(TAG, "Egressed detected result: " + result); - } - } - } - - @Override - public void onDetected(HotwordDetectedResult triggerResult) - throws RemoteException { - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - METRICS_EXTERNAL_SOURCE_DETECTED, - mVoiceInteractionServiceUid); - mScheduledExecutorService.schedule( - () -> { - bestEffortClose(serviceAudioSink, audioSource); - }, - EXTERNAL_HOTWORD_CLEANUP_MILLIS, - TimeUnit.MILLISECONDS); - - try { - enforcePermissionsForDataDelivery(); - } catch (SecurityException e) { - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - METRICS_EXTERNAL_SOURCE_DETECT_SECURITY_EXCEPTION, - mVoiceInteractionServiceUid); - callback.onError(); - return; - } - HotwordDetectedResult newResult; - try { - newResult = - mHotwordAudioStreamCopier.startCopyingAudioStreams( - triggerResult); - } catch (IOException e) { - // TODO: Write event - callback.onError(); - return; - } - callback.onDetected(newResult, null /* audioFormat */, - null /* audioStream */); - Slog.i(TAG, "Egressed " - + HotwordDetectedResult.getUsageSize(newResult) - + " bits from hotword trusted process"); - if (mDebugHotwordLogging) { - Slog.i(TAG, - "Egressed detected result: " + newResult); - } - } - }); - - // A copy of this has been created and passed to the hotword validator - bestEffortClose(serviceAudioSource); - }); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__START_EXTERNAL_SOURCE_DETECTION, - mVoiceInteractionServiceUid); - } - - private class ServiceConnectionFactory { - private final Intent mIntent; - private final int mBindingFlags; - - private int mRestartCount = 0; - - ServiceConnectionFactory(@NonNull Intent intent, boolean bindInstantServiceAllowed) { - mIntent = intent; - mBindingFlags = bindInstantServiceAllowed ? Context.BIND_ALLOW_INSTANT : 0; - } - - ServiceConnection createLocked() { - ServiceConnection connection = - new ServiceConnection(mContext, mIntent, mBindingFlags, mUser, - IHotwordDetectionService.Stub::asInterface, - mRestartCount++ % MAX_ISOLATED_PROCESS_NUMBER); - connection.connect(); - - updateAudioFlinger(connection, mAudioFlinger); - updateContentCaptureManager(connection); - updateSpeechService(connection); - updateServiceIdentity(connection); - return connection; - } - } - - private class ServiceConnection extends ServiceConnector.Impl<IHotwordDetectionService> { - private final Object mLock = new Object(); - - private final Intent mIntent; - private final int mBindingFlags; - private final int mInstanceNumber; - - private boolean mRespectServiceConnectionStatusChanged = true; - private boolean mIsBound = false; - private boolean mIsLoggedFirstConnect = false; - - ServiceConnection(@NonNull Context context, - @NonNull Intent intent, int bindingFlags, int userId, - @Nullable Function<IBinder, IHotwordDetectionService> binderAsInterface, - int instanceNumber) { - super(context, intent, bindingFlags, userId, binderAsInterface); - this.mIntent = intent; - this.mBindingFlags = bindingFlags; - this.mInstanceNumber = instanceNumber; - } - - @Override // from ServiceConnector.Impl - protected void onServiceConnectionStatusChanged(IHotwordDetectionService service, - boolean connected) { - if (DEBUG) { - Slog.d(TAG, "onServiceConnectionStatusChanged connected = " + connected); - } - synchronized (mLock) { - if (!mRespectServiceConnectionStatusChanged) { - Slog.v(TAG, "Ignored onServiceConnectionStatusChanged event"); - return; - } - mIsBound = connected; - - if (!connected) { - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__ON_DISCONNECTED, - mVoiceInteractionServiceUid); - } else if (!mIsLoggedFirstConnect) { - mIsLoggedFirstConnect = true; - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__ON_CONNECTED, - mVoiceInteractionServiceUid); - } - } - } - - @Override - protected long getAutoDisconnectTimeoutMs() { - return -1; - } - - @Override - public void binderDied() { - super.binderDied(); - synchronized (mLock) { - if (!mRespectServiceConnectionStatusChanged) { - Slog.v(TAG, "Ignored #binderDied event"); - return; - } - - Slog.w(TAG, "binderDied"); - try { - mCallback.onError(HOTWORD_DETECTION_SERVICE_DIED); - } catch (RemoteException e) { - Slog.w(TAG, "Failed to report onError status: " + e); - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__CALLBACK_ON_ERROR_EXCEPTION, - mVoiceInteractionServiceUid); - } - } - } - - @Override - protected boolean bindService( - @NonNull android.content.ServiceConnection serviceConnection) { - try { - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__REQUEST_BIND_SERVICE, - mVoiceInteractionServiceUid); - boolean bindResult = mContext.bindIsolatedService( - mIntent, - Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE | mBindingFlags, - "hotword_detector_" + mInstanceNumber, - mExecutor, - serviceConnection); - if (!bindResult) { - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__REQUEST_BIND_SERVICE_FAIL, - mVoiceInteractionServiceUid); - } - return bindResult; - } catch (IllegalArgumentException e) { - HotwordMetricsLogger.writeDetectorEvent(mDetectorType, - HOTWORD_DETECTOR_EVENTS__EVENT__REQUEST_BIND_SERVICE_FAIL, - mVoiceInteractionServiceUid); - Slog.wtf(TAG, "Can't bind to the hotword detection service!", e); - return false; - } - } - - boolean isBound() { - synchronized (mLock) { - return mIsBound; - } - } - - void ignoreConnectionStatusEvents() { - synchronized (mLock) { - mRespectServiceConnectionStatusChanged = false; - } - } - } - - private static Pair<ParcelFileDescriptor, ParcelFileDescriptor> createPipe() { - ParcelFileDescriptor[] fileDescriptors; - try { - fileDescriptors = ParcelFileDescriptor.createPipe(); - } catch (IOException e) { - Slog.e(TAG, "Failed to create audio stream pipe", e); - return null; - } - - return Pair.create(fileDescriptors[0], fileDescriptors[1]); - } - - private static void updateAudioFlinger(ServiceConnection connection, IBinder audioFlinger) { - // TODO: Consider using a proxy that limits the exposed API surface. - connection.run(service -> service.updateAudioFlinger(audioFlinger)); - } - - private static void updateContentCaptureManager(ServiceConnection connection) { - IBinder b = ServiceManager - .getService(Context.CONTENT_CAPTURE_MANAGER_SERVICE); - IContentCaptureManager binderService = IContentCaptureManager.Stub.asInterface(b); - connection.run( - service -> service.updateContentCaptureManager(binderService, - new ContentCaptureOptions(null))); - } - - private static void updateSpeechService(ServiceConnection connection) { - IBinder b = ServiceManager.getService(Context.SPEECH_RECOGNITION_SERVICE); - IRecognitionServiceManager binderService = IRecognitionServiceManager.Stub.asInterface(b); - connection.run(service -> { - service.updateRecognitionServiceManager(binderService); - }); - } - - private void updateServiceIdentity(ServiceConnection connection) { - connection.run(service -> service.ping(new IRemoteCallback.Stub() { - @Override - public void sendResult(Bundle bundle) throws RemoteException { - // TODO: Exit if the service has been unbound already (though there's a very low - // chance this happens). - if (DEBUG) { - Slog.d(TAG, "updating hotword UID " + Binder.getCallingUid()); - } - // TODO: Have the provider point to the current state stored in - // VoiceInteractionManagerServiceImpl. - final int uid = Binder.getCallingUid(); - LocalServices.getService(PermissionManagerServiceInternal.class) - .setHotwordDetectionServiceProvider(() -> uid); - mIdentity = new HotwordDetectionServiceIdentity(uid, mVoiceInteractionServiceUid); - addServiceUidForAudioPolicy(uid); - } - })); - } - - private void addServiceUidForAudioPolicy(int uid) { - mScheduledExecutorService.execute(() -> { - AudioManagerInternal audioManager = - LocalServices.getService(AudioManagerInternal.class); - if (audioManager != null) { - audioManager.addAssistantServiceUid(uid); - } - }); - } - - private void removeServiceUidForAudioPolicy(int uid) { - mScheduledExecutorService.execute(() -> { - AudioManagerInternal audioManager = - LocalServices.getService(AudioManagerInternal.class); - if (audioManager != null) { - audioManager.removeAssistantServiceUid(uid); - } - }); - } - - private void saveProximityValueToBundle(HotwordDetectedResult result) { - synchronized (mLock) { - if (result != null && mProximityMeters != PROXIMITY_UNKNOWN) { - result.setProximity(mProximityMeters); - } - } - } - - private void setProximityValue(double proximityMeters) { - synchronized (mLock) { - mProximityMeters = proximityMeters; - } - } - - private static void bestEffortClose(Closeable... closeables) { - for (Closeable closeable : closeables) { - bestEffortClose(closeable); - } - } - - private static void bestEffortClose(Closeable closeable) { - try { - closeable.close(); - } catch (IOException e) { - if (DEBUG) { - Slog.w(TAG, "Failed closing", e); - } - } - } - - // TODO: Share this code with SoundTriggerMiddlewarePermission. - private void enforcePermissionsForDataDelivery() { - Binder.withCleanCallingIdentity(() -> { - enforcePermissionForPreflight(mContext, mVoiceInteractorIdentity, RECORD_AUDIO); - int hotwordOp = AppOpsManager.strOpToOp(AppOpsManager.OPSTR_RECORD_AUDIO_HOTWORD); - mAppOpsManager.noteOpNoThrow(hotwordOp, - mVoiceInteractorIdentity.uid, mVoiceInteractorIdentity.packageName, - mVoiceInteractorIdentity.attributionTag, OP_MESSAGE); - enforcePermissionForDataDelivery(mContext, mVoiceInteractorIdentity, - CAPTURE_AUDIO_HOTWORD, OP_MESSAGE); - }); - } - - /** - * Throws a {@link SecurityException} iff the given identity has given permission to receive - * data. - * - * @param context A {@link Context}, used for permission checks. - * @param identity The identity to check. - * @param permission The identifier of the permission we want to check. - * @param reason The reason why we're requesting the permission, for auditing purposes. - */ - private static void enforcePermissionForDataDelivery(@NonNull Context context, - @NonNull Identity identity, - @NonNull String permission, @NonNull String reason) { - final int status = PermissionUtil.checkPermissionForDataDelivery(context, identity, - permission, reason); - if (status != PermissionChecker.PERMISSION_GRANTED) { - throw new SecurityException( - TextUtils.formatSimple("Failed to obtain permission %s for identity %s", - permission, - SoundTriggerSessionPermissionsDecorator.toString(identity))); - } - } - - private static void enforceExtraKeyphraseIdNotLeaked(HotwordDetectedResult result, - SoundTrigger.KeyphraseRecognitionEvent recognitionEvent) { - // verify the phrase ID in HotwordDetectedResult is not exposing extra phrases - // the DSP did not detect - for (SoundTrigger.KeyphraseRecognitionExtra keyphrase : recognitionEvent.keyphraseExtras) { - if (keyphrase.getKeyphraseId() == result.getHotwordPhraseId()) { - return; - } - } - throw new SecurityException("Ignoring #onDetected due to trusted service " - + "sharing a keyphrase ID which the DSP did not detect"); - } - - private static final String OP_MESSAGE = - "Providing hotword detection result to VoiceInteractionService"; -} diff --git a/telephony/common/com/android/internal/telephony/TelephonyPermissions.java b/telephony/common/com/android/internal/telephony/TelephonyPermissions.java index 1ba997f4c334..fdf694303dbc 100644 --- a/telephony/common/com/android/internal/telephony/TelephonyPermissions.java +++ b/telephony/common/com/android/internal/telephony/TelephonyPermissions.java @@ -743,11 +743,23 @@ public final class TelephonyPermissions { /** * Given a list of permissions, check to see if the caller has at least one of them granted. If - * not, check to see if the caller has carrier privileges. If the caller does not have any of + * not, check to see if the caller has carrier privileges. If the caller does not have any of * these permissions, throw a SecurityException. */ public static void enforceAnyPermissionGrantedOrCarrierPrivileges(Context context, int subId, int uid, String message, String... permissions) { + enforceAnyPermissionGrantedOrCarrierPrivileges( + context, subId, uid, false, message, permissions); + } + + /** + * Given a list of permissions, check to see if the caller has at least one of them granted. If + * not, check to see if the caller has carrier privileges on the specified subscription (or any + * subscription if {@code allowCarrierPrivilegeOnAnySub} is {@code true}. If the caller does not + * have any of these permissions, throw a {@link SecurityException}. + */ + public static void enforceAnyPermissionGrantedOrCarrierPrivileges(Context context, int subId, + int uid, boolean allowCarrierPrivilegeOnAnySub, String message, String... permissions) { if (permissions.length == 0) return; boolean isGranted = false; for (String perm : permissions) { @@ -758,7 +770,12 @@ public final class TelephonyPermissions { } if (isGranted) return; - if (checkCarrierPrivilegeForSubId(context, subId)) return; + + if (allowCarrierPrivilegeOnAnySub) { + if (checkCarrierPrivilegeForAnySubId(context, Binder.getCallingUid())) return; + } else { + if (checkCarrierPrivilegeForSubId(context, subId)) return; + } StringBuilder b = new StringBuilder(message); b.append(": Neither user "); @@ -769,7 +786,8 @@ public final class TelephonyPermissions { b.append(" or "); b.append(permissions[i]); } - b.append(" or carrier privileges"); + b.append(" or carrier privileges. subId=" + subId + ", allowCarrierPrivilegeOnAnySub=" + + allowCarrierPrivilegeOnAnySub); throw new SecurityException(b.toString()); } diff --git a/telephony/java/android/telephony/CellSignalStrengthNr.java b/telephony/java/android/telephony/CellSignalStrengthNr.java index 297940e9c8c6..03519a364a36 100644 --- a/telephony/java/android/telephony/CellSignalStrengthNr.java +++ b/telephony/java/android/telephony/CellSignalStrengthNr.java @@ -155,6 +155,16 @@ public final class CellSignalStrengthNr extends CellSignalStrength implements Pa */ private int mParametersUseForLevel; + /** + * Timing advance value for a one way trip from cell to device in microseconds. + * Approximate distance is calculated using 300m/us * timingAdvance. + * + * Reference: 3GPP TS 36.213 section 4.2.3. + * + * Range: [0, 1282] + */ + private int mTimingAdvance; + /** @hide */ public CellSignalStrengthNr() { setDefaultValues(); @@ -169,10 +179,11 @@ public final class CellSignalStrengthNr extends CellSignalStrength implements Pa * @param ssRsrp SS reference signal received power. * @param ssRsrq SS reference signal received quality. * @param ssSinr SS signal-to-noise and interference ratio. + * @param timingAdvance Timing advance. * @hide */ public CellSignalStrengthNr(int csiRsrp, int csiRsrq, int csiSinr, int csiCqiTableIndex, - List<Byte> csiCqiReport, int ssRsrp, int ssRsrq, int ssSinr) { + List<Byte> csiCqiReport, int ssRsrp, int ssRsrq, int ssSinr, int timingAdvance) { mCsiRsrp = inRangeOrUnavailable(csiRsrp, -156, -31); mCsiRsrq = inRangeOrUnavailable(csiRsrq, -20, -3); mCsiSinr = inRangeOrUnavailable(csiSinr, -23, 23); @@ -183,6 +194,7 @@ public final class CellSignalStrengthNr extends CellSignalStrength implements Pa mSsRsrp = inRangeOrUnavailable(ssRsrp, -156, -31); mSsRsrq = inRangeOrUnavailable(ssRsrq, -43, 20); mSsSinr = inRangeOrUnavailable(ssSinr, -23, 40); + mTimingAdvance = inRangeOrUnavailable(timingAdvance, 0, 1282); updateLevel(null, null); } @@ -198,7 +210,7 @@ public final class CellSignalStrengthNr extends CellSignalStrength implements Pa public CellSignalStrengthNr( int csiRsrp, int csiRsrq, int csiSinr, int ssRsrp, int ssRsrq, int ssSinr) { this(csiRsrp, csiRsrq, csiSinr, CellInfo.UNAVAILABLE, Collections.emptyList(), - ssRsrp, ssRsrq, ssSinr); + ssRsrp, ssRsrq, ssSinr, CellInfo.UNAVAILABLE); } /** @@ -302,6 +314,22 @@ public final class CellSignalStrengthNr extends CellSignalStrength implements Pa return mCsiCqiReport; } + /** + * Get the timing advance value for a one way trip from cell to device for NR in microseconds. + * {@link android.telephony.CellInfo#UNAVAILABLE} is reported when there is no + * active RRC connection. + * + * Reference: 3GPP TS 36.213 section 4.2.3. + * Range: 0 us to 1282 us. + * + * @return the NR timing advance if available or + * {@link android.telephony.CellInfo#UNAVAILABLE} if unavailable. + */ + @IntRange(from = 0, to = 1282) + public int getTimingAdvanceMicros() { + return mTimingAdvance; + } + @Override public int describeContents() { return 0; @@ -319,6 +347,7 @@ public final class CellSignalStrengthNr extends CellSignalStrength implements Pa dest.writeInt(mSsRsrq); dest.writeInt(mSsSinr); dest.writeInt(mLevel); + dest.writeInt(mTimingAdvance); } private CellSignalStrengthNr(Parcel in) { @@ -331,6 +360,7 @@ public final class CellSignalStrengthNr extends CellSignalStrength implements Pa mSsRsrq = in.readInt(); mSsSinr = in.readInt(); mLevel = in.readInt(); + mTimingAdvance = in.readInt(); } /** @hide */ @@ -346,6 +376,7 @@ public final class CellSignalStrengthNr extends CellSignalStrength implements Pa mSsSinr = CellInfo.UNAVAILABLE; mLevel = SIGNAL_STRENGTH_NONE_OR_UNKNOWN; mParametersUseForLevel = USE_SSRSRP; + mTimingAdvance = CellInfo.UNAVAILABLE; } /** {@inheritDoc} */ @@ -495,6 +526,7 @@ public final class CellSignalStrengthNr extends CellSignalStrength implements Pa mSsSinr = s.mSsSinr; mLevel = s.mLevel; mParametersUseForLevel = s.mParametersUseForLevel; + mTimingAdvance = s.mTimingAdvance; } /** @hide */ @@ -506,7 +538,7 @@ public final class CellSignalStrengthNr extends CellSignalStrength implements Pa @Override public int hashCode() { return Objects.hash(mCsiRsrp, mCsiRsrq, mCsiSinr, mCsiCqiTableIndex, - mCsiCqiReport, mSsRsrp, mSsRsrq, mSsSinr, mLevel); + mCsiCqiReport, mSsRsrp, mSsRsrq, mSsSinr, mLevel, mTimingAdvance); } private static final CellSignalStrengthNr sInvalid = new CellSignalStrengthNr(); @@ -525,7 +557,7 @@ public final class CellSignalStrengthNr extends CellSignalStrength implements Pa && mCsiCqiTableIndex == o.mCsiCqiTableIndex && mCsiCqiReport.equals(o.mCsiCqiReport) && mSsRsrp == o.mSsRsrp && mSsRsrq == o.mSsRsrq && mSsSinr == o.mSsSinr - && mLevel == o.mLevel; + && mLevel == o.mLevel && mTimingAdvance == o.mTimingAdvance; } return false; } @@ -543,6 +575,7 @@ public final class CellSignalStrengthNr extends CellSignalStrength implements Pa .append(" ssSinr = " + mSsSinr) .append(" level = " + mLevel) .append(" parametersUseForLevel = " + mParametersUseForLevel) + .append(" timingAdvance = " + mTimingAdvance) .append(" }") .toString(); } diff --git a/telephony/java/android/telephony/SubscriptionManager.java b/telephony/java/android/telephony/SubscriptionManager.java index 5244f415e8e2..9b566fbeb0bb 100644 --- a/telephony/java/android/telephony/SubscriptionManager.java +++ b/telephony/java/android/telephony/SubscriptionManager.java @@ -754,6 +754,15 @@ public class SubscriptionManager { /** Indicates that data roaming is disabled for a subscription */ public static final int DATA_ROAMING_DISABLE = SimInfo.DATA_ROAMING_DISABLE; + /** @hide */ + @Retention(RetentionPolicy.SOURCE) + @IntDef(prefix = {"DATA_ROAMING_"}, + value = { + DATA_ROAMING_ENABLE, + DATA_ROAMING_DISABLE + }) + public @interface DataRoamingMode {} + /** * TelephonyProvider column name for subscription carrier id. * @see TelephonyManager#getSimCarrierId() @@ -2605,37 +2614,6 @@ public class SubscriptionManager { } /** - * Returns a constant indicating the state of sim for the slot index. - * - * @param slotIndex - * - * {@See TelephonyManager#SIM_STATE_UNKNOWN} - * {@See TelephonyManager#SIM_STATE_ABSENT} - * {@See TelephonyManager#SIM_STATE_PIN_REQUIRED} - * {@See TelephonyManager#SIM_STATE_PUK_REQUIRED} - * {@See TelephonyManager#SIM_STATE_NETWORK_LOCKED} - * {@See TelephonyManager#SIM_STATE_READY} - * {@See TelephonyManager#SIM_STATE_NOT_READY} - * {@See TelephonyManager#SIM_STATE_PERM_DISABLED} - * {@See TelephonyManager#SIM_STATE_CARD_IO_ERROR} - * - * {@hide} - */ - public static int getSimStateForSlotIndex(int slotIndex) { - int simState = TelephonyManager.SIM_STATE_UNKNOWN; - - try { - ISub iSub = TelephonyManager.getSubscriptionService(); - if (iSub != null) { - simState = iSub.getSimStateForSlotIndex(slotIndex); - } - } catch (RemoteException ex) { - } - - return simState; - } - - /** * Store properties associated with SubscriptionInfo in database * @param subId Subscription Id of Subscription * @param propKey Column name in database associated with SubscriptionInfo @@ -3726,10 +3704,15 @@ public class SubscriptionManager { } /** - * DO NOT USE. - * This API is designed for features that are not finished at this point. Do not call this API. + * Check if a subscription is active. + * + * @param subscriptionId The subscription id to check. + * + * @return {@code true} if the subscription is active. + * + * @throws IllegalArgumentException if the provided slot index is invalid. + * * @hide - * TODO b/135547512: further clean up */ @SystemApi @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE) @@ -3750,8 +3733,12 @@ public class SubscriptionManager { * Set the device to device status sharing user preference for a subscription ID. The setting * app uses this method to indicate with whom they wish to share device to device status * information. - * @param sharing the status sharing preference - * @param subscriptionId the unique Subscription ID in database + * + * @param subscriptionId the unique Subscription ID in database. + * @param sharing the status sharing preference. + * + * @throws IllegalArgumentException if the subscription does not exist, or the sharing + * preference is invalid. */ @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE) public void setDeviceToDeviceStatusSharingPreference(int subscriptionId, @@ -3782,8 +3769,12 @@ public class SubscriptionManager { * Set the list of contacts that allow device to device status sharing for a subscription ID. * The setting app uses this method to indicate with whom they wish to share device to device * status information. - * @param contacts The list of contacts that allow device to device status sharing - * @param subscriptionId The unique Subscription ID in database + * + * @param subscriptionId The unique Subscription ID in database. + * @param contacts The list of contacts that allow device to device status sharing. + * + * @throws IllegalArgumentException if the subscription does not exist, or contacts is + * {@code null}. */ @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE) public void setDeviceToDeviceStatusSharingContacts(int subscriptionId, @@ -3813,16 +3804,24 @@ public class SubscriptionManager { } /** - * DO NOT USE. - * This API is designed for features that are not finished at this point. Do not call this API. + * Get the active subscription id by logical SIM slot index. + * + * @param slotIndex The logical SIM slot index. + * @return The active subscription id. + * + * @throws IllegalArgumentException if the provided slot index is invalid. + * * @hide - * TODO b/135547512: further clean up */ @SystemApi @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public int getEnabledSubscriptionId(int slotIndex) { int subId = INVALID_SUBSCRIPTION_ID; + if (!isValidSlotIndex(slotIndex)) { + throw new IllegalArgumentException("Invalid slot index " + slotIndex); + } + try { ISub iSub = TelephonyManager.getSubscriptionService(); if (iSub != null) { @@ -3864,12 +3863,12 @@ public class SubscriptionManager { /** * Get active data subscription id. Active data subscription refers to the subscription * currently chosen to provide cellular internet connection to the user. This may be - * different from getDefaultDataSubscriptionId(). Eg. Opportunistics data + * different from getDefaultDataSubscriptionId(). * - * See {@link PhoneStateListener#onActiveDataSubscriptionIdChanged(int)} for the details. + * @return Active data subscription id if any is chosen, or {@link #INVALID_SUBSCRIPTION_ID} if + * not. * - * @return Active data subscription id if any is chosen, or - * SubscriptionManager.INVALID_SUBSCRIPTION_ID if not. + * @see TelephonyCallback.ActiveDataSubscriptionIdListener */ public static int getActiveDataSubscriptionId() { if (isSubscriptionManagerServiceEnabled()) { diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java index 3024b896d1cf..851697a0f25d 100644 --- a/telephony/java/android/telephony/TelephonyManager.java +++ b/telephony/java/android/telephony/TelephonyManager.java @@ -71,7 +71,6 @@ import android.os.PersistableBundle; import android.os.RemoteException; import android.os.ResultReceiver; import android.os.SystemProperties; -import android.os.UserHandle; import android.os.WorkSource; import android.provider.Settings.SettingNotFoundException; import android.service.carrier.CarrierIdentifier; @@ -127,7 +126,6 @@ import com.android.internal.telephony.IccLogicalChannelRequest; import com.android.internal.telephony.OperatorInfo; import com.android.internal.telephony.PhoneConstants; import com.android.internal.telephony.RILConstants; -import com.android.internal.telephony.SmsApplication; import com.android.telephony.Rlog; import java.io.IOException; @@ -3558,7 +3556,7 @@ public class TelephonyManager { "state as absent"); return SIM_STATE_ABSENT; } - return SubscriptionManager.getSimStateForSlotIndex(slotIndex); + return getSimStateForSlotIndex(slotIndex); } /** @@ -3705,9 +3703,7 @@ public class TelephonyManager { @Deprecated public @SimState int getSimApplicationState(int physicalSlotIndex) { int activePort = getFirstActivePortIndex(physicalSlotIndex); - int simState = - SubscriptionManager.getSimStateForSlotIndex(getLogicalSlotIndex(physicalSlotIndex, - activePort)); + int simState = getSimStateForSlotIndex(getLogicalSlotIndex(physicalSlotIndex, activePort)); return getSimApplicationStateFromSimState(simState); } @@ -3733,9 +3729,7 @@ public class TelephonyManager { @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION) public @SimState int getSimApplicationState(int physicalSlotIndex, int portIndex) { - int simState = - SubscriptionManager.getSimStateForSlotIndex(getLogicalSlotIndex(physicalSlotIndex, - portIndex)); + int simState = getSimStateForSlotIndex(getLogicalSlotIndex(physicalSlotIndex, portIndex)); return getSimApplicationStateFromSimState(simState); } @@ -3804,7 +3798,7 @@ public class TelephonyManager { */ @RequiresFeature(PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION) public @SimState int getSimState(int slotIndex) { - int simState = SubscriptionManager.getSimStateForSlotIndex(slotIndex); + int simState = getSimStateForSlotIndex(slotIndex); if (simState == SIM_STATE_LOADED) { simState = SIM_STATE_READY; } @@ -17747,4 +17741,30 @@ public class TelephonyManager { } return null; } + + /** + * Returns a constant indicating the state of sim for the slot index. + * + * @param slotIndex Logical SIM slot index. + * + * @see TelephonyManager.SimState + * + * @hide + */ + @SimState + public static int getSimStateForSlotIndex(int slotIndex) { + try { + ITelephony telephony = ITelephony.Stub.asInterface( + TelephonyFrameworkInitializer + .getTelephonyServiceManager() + .getTelephonyServiceRegisterer() + .get()); + if (telephony != null) { + return telephony.getSimStateForSlotIndex(slotIndex); + } + } catch (RemoteException e) { + Log.e(TAG, "Error in getSimStateForSlotIndex: " + e); + } + return TelephonyManager.SIM_STATE_UNKNOWN; + } } diff --git a/telephony/java/android/telephony/data/ApnSetting.java b/telephony/java/android/telephony/data/ApnSetting.java index fa3f15d0e2ca..554beb9a35ba 100644 --- a/telephony/java/android/telephony/data/ApnSetting.java +++ b/telephony/java/android/telephony/data/ApnSetting.java @@ -1286,7 +1286,7 @@ public class ApnSetting implements Parcelable { && xorEqualsInt(this.mMmsProxyPort, other.mMmsProxyPort)) && xorEqualsString(this.mUser, other.mUser) && xorEqualsString(this.mPassword, other.mPassword) - && xorEqualsInt(this.mAuthType, other.mAuthType) + && Objects.equals(this.mAuthType, other.mAuthType) && !typeSameAny(this, other) && Objects.equals(this.mOperatorNumeric, other.mOperatorNumeric) && Objects.equals(this.mProtocol, other.mProtocol) diff --git a/telephony/java/android/telephony/ims/aidl/IImsRegistration.aidl b/telephony/java/android/telephony/ims/aidl/IImsRegistration.aidl index 4fd904041365..219c9c88d825 100644 --- a/telephony/java/android/telephony/ims/aidl/IImsRegistration.aidl +++ b/telephony/java/android/telephony/ims/aidl/IImsRegistration.aidl @@ -31,4 +31,5 @@ interface IImsRegistration { oneway void triggerFullNetworkRegistration(int sipCode, String sipReason); oneway void triggerUpdateSipDelegateRegistration(); oneway void triggerSipDelegateDeregistration(); + oneway void triggerDeregistration(int reason); } diff --git a/telephony/java/android/telephony/ims/feature/MmTelFeature.java b/telephony/java/android/telephony/ims/feature/MmTelFeature.java index d776928965e5..8184424fef26 100644 --- a/telephony/java/android/telephony/ims/feature/MmTelFeature.java +++ b/telephony/java/android/telephony/ims/feature/MmTelFeature.java @@ -700,6 +700,7 @@ public class MmTelFeature extends ImsFeature { throw new IllegalStateException("Session is not available."); } try { + c.setDefaultExecutor(MmTelFeature.this.mExecutor); listener.onIncomingCall(c.getServiceImpl(), extras); } catch (RemoteException e) { throw new RuntimeException(e); diff --git a/telephony/java/android/telephony/ims/stub/ImsRegistrationImplBase.java b/telephony/java/android/telephony/ims/stub/ImsRegistrationImplBase.java index 6fc1cc828a2c..b69eb6f3d6ce 100644 --- a/telephony/java/android/telephony/ims/stub/ImsRegistrationImplBase.java +++ b/telephony/java/android/telephony/ims/stub/ImsRegistrationImplBase.java @@ -104,6 +104,73 @@ public class ImsRegistrationImplBase { // yet. private static final int REGISTRATION_STATE_UNKNOWN = -1; + /** @hide */ + @Retention(RetentionPolicy.SOURCE) + @IntDef( + prefix = {"REASON_"}, + value = { + REASON_UNKNOWN, + REASON_SIM_REMOVED, + REASON_SIM_REFRESH, + REASON_ALLOWED_NETWORK_TYPES_CHANGED, + REASON_NON_IMS_CAPABLE_NETWORK, + REASON_RADIO_POWER_OFF, + REASON_HANDOVER_FAILED, + REASON_VOPS_NOT_SUPPORTED, + }) + public @interface ImsDeregistrationReason{} + + /** + * Unspecified reason. + * @hide + */ + public static final int REASON_UNKNOWN = 0; + + /** + * Since SIM is removed, the credentials for IMS service is also removed. + * @hide + */ + public static final int REASON_SIM_REMOVED = 1; + + /** + * Detach from the network shall be performed due to the SIM refresh. IMS service should be + * deregistered before that procedure. + * @hide + */ + public static final int REASON_SIM_REFRESH = 2; + + /** + * The allowed network types have changed, resulting in a network type + * that does not support IMS. + * @hide + */ + public static final int REASON_ALLOWED_NETWORK_TYPES_CHANGED = 3; + + /** + * The device camped on a network that does not support IMS. + * @hide + */ + public static final int REASON_NON_IMS_CAPABLE_NETWORK = 4; + + /** + * IMS service should be deregistered from the network before turning off the radio. + * @hide + */ + public static final int REASON_RADIO_POWER_OFF = 5; + + /** + * Since the handover is failed or not allowed, the data service for IMS shall be + * disconnected. + * @hide + */ + public static final int REASON_HANDOVER_FAILED = 6; + + /** + * The network is changed to a network that does not support voice over IMS. + * @hide + */ + public static final int REASON_VOPS_NOT_SUPPORTED = 7; + private Executor mExecutor; /** @@ -182,6 +249,12 @@ public class ImsRegistrationImplBase { .triggerSipDelegateDeregistration(), "triggerSipDelegateDeregistration"); } + @Override + public void triggerDeregistration(@ImsDeregistrationReason int reason) { + executeMethodAsyncNoException(() -> ImsRegistrationImplBase.this + .triggerDeregistration(reason), "triggerDeregistration"); + } + // Call the methods with a clean calling identity on the executor and wait indefinitely for // the future to return. private void executeMethodAsync(Runnable r, String errorLogName) throws RemoteException { @@ -303,6 +376,19 @@ public class ImsRegistrationImplBase { // Stub implementation, ImsService should implement this } + /** + * Requests IMS stack to perform graceful IMS deregistration before radio performing + * network detach in the events of SIM remove, refresh or and so on. The radio waits for + * the IMS deregistration, which will be notified by telephony via + * {@link android.hardware.radio.ims.IRadioIms#updateImsRegistrationInfo()}, + * or a certain timeout interval to start the network detach procedure. + * + * @param reason the reason why the deregistration is triggered. + * @hide + */ + public void triggerDeregistration(@ImsDeregistrationReason int reason) { + // Stub Implementation, can be overridden by ImsService + } /** * Notify the framework that the device is connected to the IMS network. diff --git a/telephony/java/com/android/internal/telephony/ISub.aidl b/telephony/java/com/android/internal/telephony/ISub.aidl index e9cea6843a82..280d25950228 100644 --- a/telephony/java/com/android/internal/telephony/ISub.aidl +++ b/telephony/java/com/android/internal/telephony/ISub.aidl @@ -274,11 +274,6 @@ interface ISub { boolean isSubscriptionEnabled(int subId); int getEnabledSubscriptionId(int slotIndex); - /** - * Get the SIM state for the slot index - * @return SIM state as the ordinal of IccCardConstants.State - */ - int getSimStateForSlotIndex(int slotIndex); boolean isActiveSubId(int subId, String callingPackage, String callingFeatureId); diff --git a/telephony/java/com/android/internal/telephony/ITelephony.aidl b/telephony/java/com/android/internal/telephony/ITelephony.aidl index 616ea50e4185..7ede4abd1dc2 100644 --- a/telephony/java/com/android/internal/telephony/ITelephony.aidl +++ b/telephony/java/com/android/internal/telephony/ITelephony.aidl @@ -2628,5 +2628,12 @@ interface ITelephony { * {@code null} if the functionality is not supported. * @hide */ - ComponentName getDefaultRespondViaMessageApplication(int subId, boolean updateIfNeeded); + ComponentName getDefaultRespondViaMessageApplication(int subId, boolean updateIfNeeded); + + /** + * Get the SIM state for the logical SIM slot index. + * + * @param slotIndex Logical SIM slot index. + */ + int getSimStateForSlotIndex(int slotIndex); } diff --git a/tests/FlickerTests/src/com/android/server/wm/flicker/BaseTest.kt b/tests/FlickerTests/src/com/android/server/wm/flicker/BaseTest.kt index c100a9ce0b97..a4609f7510e3 100644 --- a/tests/FlickerTests/src/com/android/server/wm/flicker/BaseTest.kt +++ b/tests/FlickerTests/src/com/android/server/wm/flicker/BaseTest.kt @@ -174,14 +174,18 @@ constructor( open fun cujCompleted() { entireScreenCovered() - navBarLayerIsVisibleAtStartAndEnd() - navBarWindowIsAlwaysVisible() - taskBarLayerIsVisibleAtStartAndEnd() - taskBarWindowIsAlwaysVisible() statusBarLayerIsVisibleAtStartAndEnd() statusBarLayerPositionAtStartAndEnd() statusBarWindowIsAlwaysVisible() visibleLayersShownMoreThanOneConsecutiveEntry() visibleWindowsShownMoreThanOneConsecutiveEntry() + + if (flicker.scenario.isTablet) { + taskBarLayerIsVisibleAtStartAndEnd() + taskBarWindowIsAlwaysVisible() + } else { + navBarLayerIsVisibleAtStartAndEnd() + navBarWindowIsAlwaysVisible() + } } } diff --git a/tests/utils/testutils/java/com/android/internal/util/test/BroadcastInterceptingContext.java b/tests/utils/testutils/java/com/android/internal/util/test/BroadcastInterceptingContext.java index 133c1767c9b4..cc3781a0bfb3 100644 --- a/tests/utils/testutils/java/com/android/internal/util/test/BroadcastInterceptingContext.java +++ b/tests/utils/testutils/java/com/android/internal/util/test/BroadcastInterceptingContext.java @@ -246,6 +246,12 @@ public class BroadcastInterceptingContext extends ContextWrapper { } @Override + public void sendBroadcastAsUser(Intent intent, UserHandle user, + String receiverPermission, Bundle options) { + sendBroadcast(intent); + } + + @Override public void sendStickyBroadcast(Intent intent) { sendBroadcast(intent); } diff --git a/tools/lint/global/checks/src/main/java/com/google/android/lint/aidl/EnforcePermissionDetector.kt b/tools/lint/global/checks/src/main/java/com/google/android/lint/aidl/EnforcePermissionDetector.kt index bba819cd9096..bcef9171aa3c 100644 --- a/tools/lint/global/checks/src/main/java/com/google/android/lint/aidl/EnforcePermissionDetector.kt +++ b/tools/lint/global/checks/src/main/java/com/google/android/lint/aidl/EnforcePermissionDetector.kt @@ -114,6 +114,13 @@ class EnforcePermissionDetector : Detector(), SourceCodeScanner { val overridingName = "${overridingClass.name}.${overridingMethod.name}" val overriddenName = "${overriddenClass.name}.${overriddenMethod.name}" if (overridingAnnotation == null) { + if (shouldIgnoreGeneratedMethod( + context, + overriddenClass = overriddenClass, + overridingClass = overridingClass) + ) { + return + } val msg = "The method $overridingName overrides the method $overriddenName which " + "is annotated with @EnforcePermission. The same annotation must be used " + "on $overridingName" @@ -215,6 +222,39 @@ class EnforcePermissionDetector : Detector(), SourceCodeScanner { } } + /** + * since this lint runs globally, it will also run against generated + * test code e.g. + * system/tools/aidl/tests/golden_output/aidl-test-interface-permission-java-source/gen/android/aidl/tests/permission/IProtected.java + * system/tools/aidl/tests/golden_output/aidl-test-interface-permission-java-source/gen/android/aidl/tests/permission/IProtectedInterface.java + * we do not want to report errors against generated `Stub` and `Proxy` classes in those files + */ + private fun shouldIgnoreGeneratedMethod( + context: JavaContext, + overriddenClass: PsiClass, + overridingClass: PsiClass, + + ): Boolean { + if (isInterfaceAndExtendsIInterface(overriddenClass) && + context.evaluator.isStatic(overridingClass)) { + if (overridingClass.name == "Default") return true + if (overridingClass.name == "Proxy") { + val shouldBeStub = overridingClass.parent as? PsiClass ?: return false + return shouldBeStub.name == "Stub" && + context.evaluator.isAbstract(shouldBeStub) && + context.evaluator.isStatic(shouldBeStub) && + shouldBeStub.extendsList?.referenceElements + ?.any { it.qualifiedName == BINDER_CLASS } == true + } + } + return false + } + + private fun isInterfaceAndExtendsIInterface(overriddenClass: PsiClass): Boolean = + overriddenClass.isInterface && + overriddenClass.extendsList?.referenceElements + ?.any { it.qualifiedName == IINTERFACE_INTERFACE } == true + companion object { val EXPLANATION = """ The @EnforcePermission annotation is used to indicate that the underlying binder code diff --git a/tools/lint/global/checks/src/main/java/com/google/android/lint/aidl/EnforcePermissionHelperDetector.kt b/tools/lint/global/checks/src/main/java/com/google/android/lint/aidl/EnforcePermissionHelperDetector.kt index 3c2ea1db0ad6..c1e47e906e22 100644 --- a/tools/lint/global/checks/src/main/java/com/google/android/lint/aidl/EnforcePermissionHelperDetector.kt +++ b/tools/lint/global/checks/src/main/java/com/google/android/lint/aidl/EnforcePermissionHelperDetector.kt @@ -28,8 +28,8 @@ import com.android.tools.lint.detector.api.SourceCodeScanner import com.intellij.psi.PsiElement import org.jetbrains.uast.UBlockExpression import org.jetbrains.uast.UDeclarationsExpression -import org.jetbrains.uast.UExpression import org.jetbrains.uast.UElement +import org.jetbrains.uast.UExpression import org.jetbrains.uast.UMethod class EnforcePermissionHelperDetector : Detector(), SourceCodeScanner { @@ -40,6 +40,7 @@ class EnforcePermissionHelperDetector : Detector(), SourceCodeScanner { private inner class AidlStubHandler(val context: JavaContext) : UElementHandler() { override fun visitMethod(node: UMethod) { + if (context.evaluator.isAbstract(node)) return if (!node.hasAnnotation(ANNOTATION_ENFORCE_PERMISSION)) return val targetExpression = "super.${node.name}$HELPER_SUFFIX()" diff --git a/tools/lint/global/checks/src/test/java/com/google/android/lint/aidl/EnforcePermissionDetectorCodegenTest.kt b/tools/lint/global/checks/src/test/java/com/google/android/lint/aidl/EnforcePermissionDetectorCodegenTest.kt new file mode 100644 index 000000000000..f2930d9faac7 --- /dev/null +++ b/tools/lint/global/checks/src/test/java/com/google/android/lint/aidl/EnforcePermissionDetectorCodegenTest.kt @@ -0,0 +1,557 @@ +/* + * 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.google.android.lint.aidl + +import com.android.tools.lint.checks.infrastructure.LintDetectorTest +import com.android.tools.lint.checks.infrastructure.TestFile +import com.android.tools.lint.checks.infrastructure.TestLintTask +import com.android.tools.lint.detector.api.Detector +import com.android.tools.lint.detector.api.Issue + +@Suppress("UnstableApiUsage") +class EnforcePermissionDetectorCodegenTest : LintDetectorTest() { + override fun getDetector(): Detector = EnforcePermissionDetector() + + override fun getIssues(): List<Issue> = listOf( + EnforcePermissionDetector.ISSUE_MISSING_ENFORCE_PERMISSION, + EnforcePermissionDetector.ISSUE_MISMATCHING_ENFORCE_PERMISSION + ) + + override fun lint(): TestLintTask = super.lint().allowMissingSdk(true) + + fun test_generated_IProtected() { + lint().files( + java( + """ + /* + * This file is auto-generated. DO NOT MODIFY. + */ + package android.aidl.tests.permission; + public interface IProtected extends android.os.IInterface + { + /** Default implementation for IProtected. */ + public static class Default implements android.aidl.tests.permission.IProtected + { + @Override public void PermissionProtected() throws android.os.RemoteException + { + } + @Override public void MultiplePermissionsAll() throws android.os.RemoteException + { + } + @Override public void MultiplePermissionsAny() throws android.os.RemoteException + { + } + @Override public void NonManifestPermission() throws android.os.RemoteException + { + } + // Used by the integration tests to dynamically set permissions that are considered granted. + @Override public void SetGranted(java.util.List<java.lang.String> permissions) throws android.os.RemoteException + { + } + @Override + public android.os.IBinder asBinder() { + return null; + } + } + /** Local-side IPC implementation stub class. */ + public static abstract class Stub extends android.os.Binder implements android.aidl.tests.permission.IProtected + { + private final android.os.PermissionEnforcer mEnforcer; + /** Construct the stub using the Enforcer provided. */ + public Stub(android.os.PermissionEnforcer enforcer) + { + this.attachInterface(this, DESCRIPTOR); + if (enforcer == null) { + throw new IllegalArgumentException("enforcer cannot be null"); + } + mEnforcer = enforcer; + } + @Deprecated + /** Default constructor. */ + public Stub() { + this(android.os.PermissionEnforcer.fromContext( + android.app.ActivityThread.currentActivityThread().getSystemContext())); + } + /** + * Cast an IBinder object into an android.aidl.tests.permission.IProtected interface, + * generating a proxy if needed. + */ + public static android.aidl.tests.permission.IProtected asInterface(android.os.IBinder obj) + { + if ((obj==null)) { + return null; + } + android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR); + if (((iin!=null)&&(iin instanceof android.aidl.tests.permission.IProtected))) { + return ((android.aidl.tests.permission.IProtected)iin); + } + return new android.aidl.tests.permission.IProtected.Stub.Proxy(obj); + } + @Override public android.os.IBinder asBinder() + { + return this; + } + /** @hide */ + public static java.lang.String getDefaultTransactionName(int transactionCode) + { + switch (transactionCode) + { + case TRANSACTION_PermissionProtected: + { + return "PermissionProtected"; + } + case TRANSACTION_MultiplePermissionsAll: + { + return "MultiplePermissionsAll"; + } + case TRANSACTION_MultiplePermissionsAny: + { + return "MultiplePermissionsAny"; + } + case TRANSACTION_NonManifestPermission: + { + return "NonManifestPermission"; + } + case TRANSACTION_SetGranted: + { + return "SetGranted"; + } + default: + { + return null; + } + } + } + /** @hide */ + public java.lang.String getTransactionName(int transactionCode) + { + return this.getDefaultTransactionName(transactionCode); + } + @Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException + { + java.lang.String descriptor = DESCRIPTOR; + if (code >= android.os.IBinder.FIRST_CALL_TRANSACTION && code <= android.os.IBinder.LAST_CALL_TRANSACTION) { + data.enforceInterface(descriptor); + } + switch (code) + { + case INTERFACE_TRANSACTION: + { + reply.writeString(descriptor); + return true; + } + } + switch (code) + { + case TRANSACTION_PermissionProtected: + { + this.PermissionProtected(); + reply.writeNoException(); + break; + } + case TRANSACTION_MultiplePermissionsAll: + { + this.MultiplePermissionsAll(); + reply.writeNoException(); + break; + } + case TRANSACTION_MultiplePermissionsAny: + { + this.MultiplePermissionsAny(); + reply.writeNoException(); + break; + } + case TRANSACTION_NonManifestPermission: + { + this.NonManifestPermission(); + reply.writeNoException(); + break; + } + case TRANSACTION_SetGranted: + { + java.util.List<java.lang.String> _arg0; + _arg0 = data.createStringArrayList(); + data.enforceNoDataAvail(); + this.SetGranted(_arg0); + reply.writeNoException(); + break; + } + default: + { + return super.onTransact(code, data, reply, flags); + } + } + return true; + } + private static class Proxy implements android.aidl.tests.permission.IProtected + { + private android.os.IBinder mRemote; + Proxy(android.os.IBinder remote) + { + mRemote = remote; + } + @Override public android.os.IBinder asBinder() + { + return mRemote; + } + public java.lang.String getInterfaceDescriptor() + { + return DESCRIPTOR; + } + @Override public void PermissionProtected() throws android.os.RemoteException + { + android.os.Parcel _data = android.os.Parcel.obtain(asBinder()); + android.os.Parcel _reply = android.os.Parcel.obtain(); + try { + _data.writeInterfaceToken(DESCRIPTOR); + boolean _status = mRemote.transact(Stub.TRANSACTION_PermissionProtected, _data, _reply, 0); + _reply.readException(); + } + finally { + _reply.recycle(); + _data.recycle(); + } + } + @Override public void MultiplePermissionsAll() throws android.os.RemoteException + { + android.os.Parcel _data = android.os.Parcel.obtain(asBinder()); + android.os.Parcel _reply = android.os.Parcel.obtain(); + try { + _data.writeInterfaceToken(DESCRIPTOR); + boolean _status = mRemote.transact(Stub.TRANSACTION_MultiplePermissionsAll, _data, _reply, 0); + _reply.readException(); + } + finally { + _reply.recycle(); + _data.recycle(); + } + } + @Override public void MultiplePermissionsAny() throws android.os.RemoteException + { + android.os.Parcel _data = android.os.Parcel.obtain(asBinder()); + android.os.Parcel _reply = android.os.Parcel.obtain(); + try { + _data.writeInterfaceToken(DESCRIPTOR); + boolean _status = mRemote.transact(Stub.TRANSACTION_MultiplePermissionsAny, _data, _reply, 0); + _reply.readException(); + } + finally { + _reply.recycle(); + _data.recycle(); + } + } + @Override public void NonManifestPermission() throws android.os.RemoteException + { + android.os.Parcel _data = android.os.Parcel.obtain(asBinder()); + android.os.Parcel _reply = android.os.Parcel.obtain(); + try { + _data.writeInterfaceToken(DESCRIPTOR); + boolean _status = mRemote.transact(Stub.TRANSACTION_NonManifestPermission, _data, _reply, 0); + _reply.readException(); + } + finally { + _reply.recycle(); + _data.recycle(); + } + } + // Used by the integration tests to dynamically set permissions that are considered granted. + @Override public void SetGranted(java.util.List<java.lang.String> permissions) throws android.os.RemoteException + { + android.os.Parcel _data = android.os.Parcel.obtain(asBinder()); + android.os.Parcel _reply = android.os.Parcel.obtain(); + try { + _data.writeInterfaceToken(DESCRIPTOR); + _data.writeStringList(permissions); + boolean _status = mRemote.transact(Stub.TRANSACTION_SetGranted, _data, _reply, 0); + _reply.readException(); + } + finally { + _reply.recycle(); + _data.recycle(); + } + } + } + static final int TRANSACTION_PermissionProtected = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0); + /** Helper method to enforce permissions for PermissionProtected */ + protected void PermissionProtected_enforcePermission() throws SecurityException { + android.content.AttributionSource source = new android.content.AttributionSource(getCallingUid(), null, null); + mEnforcer.enforcePermission(android.Manifest.permission.READ_PHONE_STATE, source); + } + static final int TRANSACTION_MultiplePermissionsAll = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1); + /** Helper method to enforce permissions for MultiplePermissionsAll */ + protected void MultiplePermissionsAll_enforcePermission() throws SecurityException { + android.content.AttributionSource source = new android.content.AttributionSource(getCallingUid(), null, null); + mEnforcer.enforcePermissionAllOf(new String[]{android.Manifest.permission.INTERNET, android.Manifest.permission.VIBRATE}, source); + } + static final int TRANSACTION_MultiplePermissionsAny = (android.os.IBinder.FIRST_CALL_TRANSACTION + 2); + /** Helper method to enforce permissions for MultiplePermissionsAny */ + protected void MultiplePermissionsAny_enforcePermission() throws SecurityException { + android.content.AttributionSource source = new android.content.AttributionSource(getCallingUid(), null, null); + mEnforcer.enforcePermissionAnyOf(new String[]{android.Manifest.permission.INTERNET, android.Manifest.permission.VIBRATE}, source); + } + static final int TRANSACTION_NonManifestPermission = (android.os.IBinder.FIRST_CALL_TRANSACTION + 3); + /** Helper method to enforce permissions for NonManifestPermission */ + protected void NonManifestPermission_enforcePermission() throws SecurityException { + android.content.AttributionSource source = new android.content.AttributionSource(getCallingUid(), null, null); + mEnforcer.enforcePermission(android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, source); + } + static final int TRANSACTION_SetGranted = (android.os.IBinder.FIRST_CALL_TRANSACTION + 4); + /** @hide */ + public int getMaxTransactionId() + { + return 4; + } + } + + @android.annotation.EnforcePermission(android.Manifest.permission.READ_PHONE_STATE) + public void PermissionProtected() throws android.os.RemoteException; + @android.annotation.EnforcePermission(allOf = {android.Manifest.permission.INTERNET, android.Manifest.permission.VIBRATE}) + public void MultiplePermissionsAll() throws android.os.RemoteException; + @android.annotation.EnforcePermission(anyOf = {android.Manifest.permission.INTERNET, android.Manifest.permission.VIBRATE}) + public void MultiplePermissionsAny() throws android.os.RemoteException; + @android.annotation.EnforcePermission(android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK) + public void NonManifestPermission() throws android.os.RemoteException; + // Used by the integration tests to dynamically set permissions that are considered granted. + @android.annotation.RequiresNoPermission + public void SetGranted(java.util.List<java.lang.String> permissions) throws android.os.RemoteException; + } + """ + ).indented(), + *stubs + ) + .run() + .expectClean() + } + + fun test_generated_IProtectedInterface() { + lint().files( + java( + """ + /* + * This file is auto-generated. DO NOT MODIFY. + */ + package android.aidl.tests.permission; + public interface IProtectedInterface extends android.os.IInterface + { + /** Default implementation for IProtectedInterface. */ + public static class Default implements android.aidl.tests.permission.IProtectedInterface + { + @Override public void Method1() throws android.os.RemoteException + { + } + @Override public void Method2() throws android.os.RemoteException + { + } + @Override + public android.os.IBinder asBinder() { + return null; + } + } + /** Local-side IPC implementation stub class. */ + public static abstract class Stub extends android.os.Binder implements android.aidl.tests.permission.IProtectedInterface + { + private final android.os.PermissionEnforcer mEnforcer; + /** Construct the stub using the Enforcer provided. */ + public Stub(android.os.PermissionEnforcer enforcer) + { + this.attachInterface(this, DESCRIPTOR); + if (enforcer == null) { + throw new IllegalArgumentException("enforcer cannot be null"); + } + mEnforcer = enforcer; + } + @Deprecated + /** Default constructor. */ + public Stub() { + this(android.os.PermissionEnforcer.fromContext( + android.app.ActivityThread.currentActivityThread().getSystemContext())); + } + /** + * Cast an IBinder object into an android.aidl.tests.permission.IProtectedInterface interface, + * generating a proxy if needed. + */ + public static android.aidl.tests.permission.IProtectedInterface asInterface(android.os.IBinder obj) + { + if ((obj==null)) { + return null; + } + android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR); + if (((iin!=null)&&(iin instanceof android.aidl.tests.permission.IProtectedInterface))) { + return ((android.aidl.tests.permission.IProtectedInterface)iin); + } + return new android.aidl.tests.permission.IProtectedInterface.Stub.Proxy(obj); + } + @Override public android.os.IBinder asBinder() + { + return this; + } + /** @hide */ + public static java.lang.String getDefaultTransactionName(int transactionCode) + { + switch (transactionCode) + { + case TRANSACTION_Method1: + { + return "Method1"; + } + case TRANSACTION_Method2: + { + return "Method2"; + } + default: + { + return null; + } + } + } + /** @hide */ + public java.lang.String getTransactionName(int transactionCode) + { + return this.getDefaultTransactionName(transactionCode); + } + @Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException + { + java.lang.String descriptor = DESCRIPTOR; + if (code >= android.os.IBinder.FIRST_CALL_TRANSACTION && code <= android.os.IBinder.LAST_CALL_TRANSACTION) { + data.enforceInterface(descriptor); + } + switch (code) + { + case INTERFACE_TRANSACTION: + { + reply.writeString(descriptor); + return true; + } + } + switch (code) + { + case TRANSACTION_Method1: + { + this.Method1(); + reply.writeNoException(); + break; + } + case TRANSACTION_Method2: + { + this.Method2(); + reply.writeNoException(); + break; + } + default: + { + return super.onTransact(code, data, reply, flags); + } + } + return true; + } + private static class Proxy implements android.aidl.tests.permission.IProtectedInterface + { + private android.os.IBinder mRemote; + Proxy(android.os.IBinder remote) + { + mRemote = remote; + } + @Override public android.os.IBinder asBinder() + { + return mRemote; + } + public java.lang.String getInterfaceDescriptor() + { + return DESCRIPTOR; + } + @Override public void Method1() throws android.os.RemoteException + { + android.os.Parcel _data = android.os.Parcel.obtain(asBinder()); + android.os.Parcel _reply = android.os.Parcel.obtain(); + try { + _data.writeInterfaceToken(DESCRIPTOR); + boolean _status = mRemote.transact(Stub.TRANSACTION_Method1, _data, _reply, 0); + _reply.readException(); + } + finally { + _reply.recycle(); + _data.recycle(); + } + } + @Override public void Method2() throws android.os.RemoteException + { + android.os.Parcel _data = android.os.Parcel.obtain(asBinder()); + android.os.Parcel _reply = android.os.Parcel.obtain(); + try { + _data.writeInterfaceToken(DESCRIPTOR); + boolean _status = mRemote.transact(Stub.TRANSACTION_Method2, _data, _reply, 0); + _reply.readException(); + } + finally { + _reply.recycle(); + _data.recycle(); + } + } + } + static final int TRANSACTION_Method1 = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0); + /** Helper method to enforce permissions for Method1 */ + protected void Method1_enforcePermission() throws SecurityException { + android.content.AttributionSource source = new android.content.AttributionSource(getCallingUid(), null, null); + mEnforcer.enforcePermission(android.Manifest.permission.ACCESS_FINE_LOCATION, source); + } + static final int TRANSACTION_Method2 = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1); + /** Helper method to enforce permissions for Method2 */ + protected void Method2_enforcePermission() throws SecurityException { + android.content.AttributionSource source = new android.content.AttributionSource(getCallingUid(), null, null); + mEnforcer.enforcePermission(android.Manifest.permission.ACCESS_FINE_LOCATION, source); + } + /** @hide */ + public int getMaxTransactionId() + { + return 1; + } + } + + @android.annotation.EnforcePermission(android.Manifest.permission.ACCESS_FINE_LOCATION) + public void Method1() throws android.os.RemoteException; + @android.annotation.EnforcePermission(android.Manifest.permission.ACCESS_FINE_LOCATION) + public void Method2() throws android.os.RemoteException; + } + """ + ).indented(), + *stubs + ) + .run() + .expectClean() + } + + /* Stubs */ + + private val manifestPermissionStub: TestFile = java( + """ + package android.Manifest; + class permission { + public static final String READ_PHONE_STATE = "android.permission.READ_PHONE_STATE"; + public static final String INTERNET = "android.permission.INTERNET"; + } + """ + ).indented() + + private val enforcePermissionAnnotationStub: TestFile = java( + """ + package android.annotation; + public @interface EnforcePermission {} + """ + ).indented() + + private val stubs = arrayOf(manifestPermissionStub, enforcePermissionAnnotationStub) +} diff --git a/tools/lint/global/checks/src/test/java/com/google/android/lint/aidl/EnforcePermissionDetectorTest.kt b/tools/lint/global/checks/src/test/java/com/google/android/lint/aidl/EnforcePermissionDetectorTest.kt index 3c1d1e8e8a59..618bbcc99656 100644 --- a/tools/lint/global/checks/src/test/java/com/google/android/lint/aidl/EnforcePermissionDetectorTest.kt +++ b/tools/lint/global/checks/src/test/java/com/google/android/lint/aidl/EnforcePermissionDetectorTest.kt @@ -189,6 +189,28 @@ must be used on IBar.Stub. Did you forget to annotate the AIDL definition? \ 1 errors, 0 warnings""".addLineContinuation()) } + fun testDetectIssuesMissingAnnotationOnMethodWhenClassIsCalledDefault() { + lint().files(java( + """ + package test.pkg; + public class Default extends IFooMethod.Stub { + public void testMethod() {} + } + """).indented(), + *stubs + ) + .run() + .expect( + """ + src/test/pkg/Default.java:3: Error: The method Default.testMethod \ + overrides the method Stub.testMethod which is annotated with @EnforcePermission. The same annotation must be used on Default.testMethod [MissingEnforcePermissionAnnotation] + public void testMethod() {} + ~~~~~~~~~~ + 1 errors, 0 warnings + """.addLineContinuation() + ) + } + /* Stubs */ // A service with permission annotation on the class. diff --git a/tools/lint/global/checks/src/test/java/com/google/android/lint/aidl/EnforcePermissionHelperDetectorCodegenTest.kt b/tools/lint/global/checks/src/test/java/com/google/android/lint/aidl/EnforcePermissionHelperDetectorCodegenTest.kt new file mode 100644 index 000000000000..5a63bb4084d2 --- /dev/null +++ b/tools/lint/global/checks/src/test/java/com/google/android/lint/aidl/EnforcePermissionHelperDetectorCodegenTest.kt @@ -0,0 +1,557 @@ +/* + * 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.google.android.lint.aidl + +import com.android.tools.lint.checks.infrastructure.LintDetectorTest +import com.android.tools.lint.checks.infrastructure.TestFile +import com.android.tools.lint.checks.infrastructure.TestLintTask +import com.android.tools.lint.checks.infrastructure.TestMode +import com.android.tools.lint.detector.api.Detector +import com.android.tools.lint.detector.api.Issue + +@Suppress("UnstableApiUsage") +class EnforcePermissionHelperDetectorCodegenTest : LintDetectorTest() { + override fun getDetector(): Detector = EnforcePermissionHelperDetector() + + override fun getIssues(): List<Issue> = listOf( + EnforcePermissionHelperDetector.ISSUE_ENFORCE_PERMISSION_HELPER + ) + + override fun lint(): TestLintTask = super.lint().allowMissingSdk(true) + + fun test_generated_IProtected() { + lint().testModes(TestMode.DEFAULT).files( + java( + """ + /* + * This file is auto-generated. DO NOT MODIFY. + */ + package android.aidl.tests.permission; + public interface IProtected extends android.os.IInterface + { + /** Default implementation for IProtected. */ + public static class Default implements android.aidl.tests.permission.IProtected + { + @Override public void PermissionProtected() throws android.os.RemoteException + { + } + @Override public void MultiplePermissionsAll() throws android.os.RemoteException + { + } + @Override public void MultiplePermissionsAny() throws android.os.RemoteException + { + } + @Override public void NonManifestPermission() throws android.os.RemoteException + { + } + // Used by the integration tests to dynamically set permissions that are considered granted. + @Override public void SetGranted(java.util.List<java.lang.String> permissions) throws android.os.RemoteException + { + } + @Override + public android.os.IBinder asBinder() { + return null; + } + } + /** Local-side IPC implementation stub class. */ + public static abstract class Stub extends android.os.Binder implements android.aidl.tests.permission.IProtected + { + private final android.os.PermissionEnforcer mEnforcer; + /** Construct the stub using the Enforcer provided. */ + public Stub(android.os.PermissionEnforcer enforcer) + { + this.attachInterface(this, DESCRIPTOR); + if (enforcer == null) { + throw new IllegalArgumentException("enforcer cannot be null"); + } + mEnforcer = enforcer; + } + @Deprecated + /** Default constructor. */ + public Stub() { + this(android.os.PermissionEnforcer.fromContext( + android.app.ActivityThread.currentActivityThread().getSystemContext())); + } + /** + * Cast an IBinder object into an android.aidl.tests.permission.IProtected interface, + * generating a proxy if needed. + */ + public static android.aidl.tests.permission.IProtected asInterface(android.os.IBinder obj) + { + if ((obj==null)) { + return null; + } + android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR); + if (((iin!=null)&&(iin instanceof android.aidl.tests.permission.IProtected))) { + return ((android.aidl.tests.permission.IProtected)iin); + } + return new android.aidl.tests.permission.IProtected.Stub.Proxy(obj); + } + @Override public android.os.IBinder asBinder() + { + return this; + } + /** @hide */ + public static java.lang.String getDefaultTransactionName(int transactionCode) + { + switch (transactionCode) + { + case TRANSACTION_PermissionProtected: + { + return "PermissionProtected"; + } + case TRANSACTION_MultiplePermissionsAll: + { + return "MultiplePermissionsAll"; + } + case TRANSACTION_MultiplePermissionsAny: + { + return "MultiplePermissionsAny"; + } + case TRANSACTION_NonManifestPermission: + { + return "NonManifestPermission"; + } + case TRANSACTION_SetGranted: + { + return "SetGranted"; + } + default: + { + return null; + } + } + } + /** @hide */ + public java.lang.String getTransactionName(int transactionCode) + { + return this.getDefaultTransactionName(transactionCode); + } + @Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException + { + java.lang.String descriptor = DESCRIPTOR; + if (code >= android.os.IBinder.FIRST_CALL_TRANSACTION && code <= android.os.IBinder.LAST_CALL_TRANSACTION) { + data.enforceInterface(descriptor); + } + switch (code) + { + case INTERFACE_TRANSACTION: + { + reply.writeString(descriptor); + return true; + } + } + switch (code) + { + case TRANSACTION_PermissionProtected: + { + this.PermissionProtected(); + reply.writeNoException(); + break; + } + case TRANSACTION_MultiplePermissionsAll: + { + this.MultiplePermissionsAll(); + reply.writeNoException(); + break; + } + case TRANSACTION_MultiplePermissionsAny: + { + this.MultiplePermissionsAny(); + reply.writeNoException(); + break; + } + case TRANSACTION_NonManifestPermission: + { + this.NonManifestPermission(); + reply.writeNoException(); + break; + } + case TRANSACTION_SetGranted: + { + java.util.List<java.lang.String> _arg0; + _arg0 = data.createStringArrayList(); + data.enforceNoDataAvail(); + this.SetGranted(_arg0); + reply.writeNoException(); + break; + } + default: + { + return super.onTransact(code, data, reply, flags); + } + } + return true; + } + private static class Proxy implements android.aidl.tests.permission.IProtected + { + private android.os.IBinder mRemote; + Proxy(android.os.IBinder remote) + { + mRemote = remote; + } + @Override public android.os.IBinder asBinder() + { + return mRemote; + } + public java.lang.String getInterfaceDescriptor() + { + return DESCRIPTOR; + } + @Override public void PermissionProtected() throws android.os.RemoteException + { + android.os.Parcel _data = android.os.Parcel.obtain(asBinder()); + android.os.Parcel _reply = android.os.Parcel.obtain(); + try { + _data.writeInterfaceToken(DESCRIPTOR); + boolean _status = mRemote.transact(Stub.TRANSACTION_PermissionProtected, _data, _reply, 0); + _reply.readException(); + } + finally { + _reply.recycle(); + _data.recycle(); + } + } + @Override public void MultiplePermissionsAll() throws android.os.RemoteException + { + android.os.Parcel _data = android.os.Parcel.obtain(asBinder()); + android.os.Parcel _reply = android.os.Parcel.obtain(); + try { + _data.writeInterfaceToken(DESCRIPTOR); + boolean _status = mRemote.transact(Stub.TRANSACTION_MultiplePermissionsAll, _data, _reply, 0); + _reply.readException(); + } + finally { + _reply.recycle(); + _data.recycle(); + } + } + @Override public void MultiplePermissionsAny() throws android.os.RemoteException + { + android.os.Parcel _data = android.os.Parcel.obtain(asBinder()); + android.os.Parcel _reply = android.os.Parcel.obtain(); + try { + _data.writeInterfaceToken(DESCRIPTOR); + boolean _status = mRemote.transact(Stub.TRANSACTION_MultiplePermissionsAny, _data, _reply, 0); + _reply.readException(); + } + finally { + _reply.recycle(); + _data.recycle(); + } + } + @Override public void NonManifestPermission() throws android.os.RemoteException + { + android.os.Parcel _data = android.os.Parcel.obtain(asBinder()); + android.os.Parcel _reply = android.os.Parcel.obtain(); + try { + _data.writeInterfaceToken(DESCRIPTOR); + boolean _status = mRemote.transact(Stub.TRANSACTION_NonManifestPermission, _data, _reply, 0); + _reply.readException(); + } + finally { + _reply.recycle(); + _data.recycle(); + } + } + // Used by the integration tests to dynamically set permissions that are considered granted. + @Override public void SetGranted(java.util.List<java.lang.String> permissions) throws android.os.RemoteException + { + android.os.Parcel _data = android.os.Parcel.obtain(asBinder()); + android.os.Parcel _reply = android.os.Parcel.obtain(); + try { + _data.writeInterfaceToken(DESCRIPTOR); + _data.writeStringList(permissions); + boolean _status = mRemote.transact(Stub.TRANSACTION_SetGranted, _data, _reply, 0); + _reply.readException(); + } + finally { + _reply.recycle(); + _data.recycle(); + } + } + } + static final int TRANSACTION_PermissionProtected = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0); + /** Helper method to enforce permissions for PermissionProtected */ + protected void PermissionProtected_enforcePermission() throws SecurityException { + android.content.AttributionSource source = new android.content.AttributionSource(getCallingUid(), null, null); + mEnforcer.enforcePermission(android.Manifest.permission.READ_PHONE_STATE, source); + } + static final int TRANSACTION_MultiplePermissionsAll = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1); + /** Helper method to enforce permissions for MultiplePermissionsAll */ + protected void MultiplePermissionsAll_enforcePermission() throws SecurityException { + android.content.AttributionSource source = new android.content.AttributionSource(getCallingUid(), null, null); + mEnforcer.enforcePermissionAllOf(new String[]{android.Manifest.permission.INTERNET, android.Manifest.permission.VIBRATE}, source); + } + static final int TRANSACTION_MultiplePermissionsAny = (android.os.IBinder.FIRST_CALL_TRANSACTION + 2); + /** Helper method to enforce permissions for MultiplePermissionsAny */ + protected void MultiplePermissionsAny_enforcePermission() throws SecurityException { + android.content.AttributionSource source = new android.content.AttributionSource(getCallingUid(), null, null); + mEnforcer.enforcePermissionAnyOf(new String[]{android.Manifest.permission.INTERNET, android.Manifest.permission.VIBRATE}, source); + } + static final int TRANSACTION_NonManifestPermission = (android.os.IBinder.FIRST_CALL_TRANSACTION + 3); + /** Helper method to enforce permissions for NonManifestPermission */ + protected void NonManifestPermission_enforcePermission() throws SecurityException { + android.content.AttributionSource source = new android.content.AttributionSource(getCallingUid(), null, null); + mEnforcer.enforcePermission(android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, source); + } + static final int TRANSACTION_SetGranted = (android.os.IBinder.FIRST_CALL_TRANSACTION + 4); + /** @hide */ + public int getMaxTransactionId() + { + return 4; + } + } + + @android.annotation.EnforcePermission(android.Manifest.permission.READ_PHONE_STATE) + public void PermissionProtected() throws android.os.RemoteException; + @android.annotation.EnforcePermission(allOf = {android.Manifest.permission.INTERNET, android.Manifest.permission.VIBRATE}) + public void MultiplePermissionsAll() throws android.os.RemoteException; + @android.annotation.EnforcePermission(anyOf = {android.Manifest.permission.INTERNET, android.Manifest.permission.VIBRATE}) + public void MultiplePermissionsAny() throws android.os.RemoteException; + @android.annotation.EnforcePermission(android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK) + public void NonManifestPermission() throws android.os.RemoteException; + // Used by the integration tests to dynamically set permissions that are considered granted. + @android.annotation.RequiresNoPermission + public void SetGranted(java.util.List<java.lang.String> permissions) throws android.os.RemoteException; + } + """ + ).indented(), + *stubs + ) + .run() + .expectClean() + } + + fun test_generated_IProtectedInterface() { + lint().files( + java( + """ + /* + * This file is auto-generated. DO NOT MODIFY. + */ + package android.aidl.tests.permission; + public interface IProtectedInterface extends android.os.IInterface + { + /** Default implementation for IProtectedInterface. */ + public static class Default implements android.aidl.tests.permission.IProtectedInterface + { + @Override public void Method1() throws android.os.RemoteException + { + } + @Override public void Method2() throws android.os.RemoteException + { + } + @Override + public android.os.IBinder asBinder() { + return null; + } + } + /** Local-side IPC implementation stub class. */ + public static abstract class Stub extends android.os.Binder implements android.aidl.tests.permission.IProtectedInterface + { + private final android.os.PermissionEnforcer mEnforcer; + /** Construct the stub using the Enforcer provided. */ + public Stub(android.os.PermissionEnforcer enforcer) + { + this.attachInterface(this, DESCRIPTOR); + if (enforcer == null) { + throw new IllegalArgumentException("enforcer cannot be null"); + } + mEnforcer = enforcer; + } + @Deprecated + /** Default constructor. */ + public Stub() { + this(android.os.PermissionEnforcer.fromContext( + android.app.ActivityThread.currentActivityThread().getSystemContext())); + } + /** + * Cast an IBinder object into an android.aidl.tests.permission.IProtectedInterface interface, + * generating a proxy if needed. + */ + public static android.aidl.tests.permission.IProtectedInterface asInterface(android.os.IBinder obj) + { + if ((obj==null)) { + return null; + } + android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR); + if (((iin!=null)&&(iin instanceof android.aidl.tests.permission.IProtectedInterface))) { + return ((android.aidl.tests.permission.IProtectedInterface)iin); + } + return new android.aidl.tests.permission.IProtectedInterface.Stub.Proxy(obj); + } + @Override public android.os.IBinder asBinder() + { + return this; + } + /** @hide */ + public static java.lang.String getDefaultTransactionName(int transactionCode) + { + switch (transactionCode) + { + case TRANSACTION_Method1: + { + return "Method1"; + } + case TRANSACTION_Method2: + { + return "Method2"; + } + default: + { + return null; + } + } + } + /** @hide */ + public java.lang.String getTransactionName(int transactionCode) + { + return this.getDefaultTransactionName(transactionCode); + } + @Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException + { + java.lang.String descriptor = DESCRIPTOR; + if (code >= android.os.IBinder.FIRST_CALL_TRANSACTION && code <= android.os.IBinder.LAST_CALL_TRANSACTION) { + data.enforceInterface(descriptor); + } + switch (code) + { + case INTERFACE_TRANSACTION: + { + reply.writeString(descriptor); + return true; + } + } + switch (code) + { + case TRANSACTION_Method1: + { + this.Method1(); + reply.writeNoException(); + break; + } + case TRANSACTION_Method2: + { + this.Method2(); + reply.writeNoException(); + break; + } + default: + { + return super.onTransact(code, data, reply, flags); + } + } + return true; + } + private static class Proxy implements android.aidl.tests.permission.IProtectedInterface + { + private android.os.IBinder mRemote; + Proxy(android.os.IBinder remote) + { + mRemote = remote; + } + @Override public android.os.IBinder asBinder() + { + return mRemote; + } + public java.lang.String getInterfaceDescriptor() + { + return DESCRIPTOR; + } + @Override public void Method1() throws android.os.RemoteException + { + android.os.Parcel _data = android.os.Parcel.obtain(asBinder()); + android.os.Parcel _reply = android.os.Parcel.obtain(); + try { + _data.writeInterfaceToken(DESCRIPTOR); + boolean _status = mRemote.transact(Stub.TRANSACTION_Method1, _data, _reply, 0); + _reply.readException(); + } + finally { + _reply.recycle(); + _data.recycle(); + } + } + @Override public void Method2() throws android.os.RemoteException + { + android.os.Parcel _data = android.os.Parcel.obtain(asBinder()); + android.os.Parcel _reply = android.os.Parcel.obtain(); + try { + _data.writeInterfaceToken(DESCRIPTOR); + boolean _status = mRemote.transact(Stub.TRANSACTION_Method2, _data, _reply, 0); + _reply.readException(); + } + finally { + _reply.recycle(); + _data.recycle(); + } + } + } + static final int TRANSACTION_Method1 = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0); + /** Helper method to enforce permissions for Method1 */ + protected void Method1_enforcePermission() throws SecurityException { + android.content.AttributionSource source = new android.content.AttributionSource(getCallingUid(), null, null); + mEnforcer.enforcePermission(android.Manifest.permission.ACCESS_FINE_LOCATION, source); + } + static final int TRANSACTION_Method2 = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1); + /** Helper method to enforce permissions for Method2 */ + protected void Method2_enforcePermission() throws SecurityException { + android.content.AttributionSource source = new android.content.AttributionSource(getCallingUid(), null, null); + mEnforcer.enforcePermission(android.Manifest.permission.ACCESS_FINE_LOCATION, source); + } + /** @hide */ + public int getMaxTransactionId() + { + return 1; + } + } + + @android.annotation.EnforcePermission(android.Manifest.permission.ACCESS_FINE_LOCATION) + public void Method1() throws android.os.RemoteException; + @android.annotation.EnforcePermission(android.Manifest.permission.ACCESS_FINE_LOCATION) + public void Method2() throws android.os.RemoteException; + } + """ + ).indented(), + *stubs + ) + .run() + .expectClean() + } + + /* Stubs */ + + private val manifestPermissionStub: TestFile = java( + """ + package android.Manifest; + class permission { + public static final String READ_PHONE_STATE = "android.permission.READ_PHONE_STATE"; + public static final String INTERNET = "android.permission.INTERNET"; + } + """ + ).indented() + + private val enforcePermissionAnnotationStub: TestFile = java( + """ + package android.annotation; + public @interface EnforcePermission {} + """ + ).indented() + + private val stubs = arrayOf(manifestPermissionStub, enforcePermissionAnnotationStub) +} diff --git a/tools/lint/global/checks/src/test/java/com/google/android/lint/aidl/EnforcePermissionHelperDetectorTest.kt b/tools/lint/global/checks/src/test/java/com/google/android/lint/aidl/EnforcePermissionHelperDetectorTest.kt index 31e484628a04..4799184b0e23 100644 --- a/tools/lint/global/checks/src/test/java/com/google/android/lint/aidl/EnforcePermissionHelperDetectorTest.kt +++ b/tools/lint/global/checks/src/test/java/com/google/android/lint/aidl/EnforcePermissionHelperDetectorTest.kt @@ -150,6 +150,31 @@ class EnforcePermissionHelperDetectorTest : LintDetectorTest() { .expectClean() } + fun testInterfaceDefaultMethod_wouldStillReport() { + lint().files( + java( + """ + public interface IProtected extends android.os.IInterface { + @android.annotation.EnforcePermission(android.Manifest.permission.READ_PHONE_STATE) + default void PermissionProtected() throws android.os.RemoteException { + String foo = "bar"; + } + } + """ + ).indented(), + *stubs + ) + .run() + .expect( + """ + src/IProtected.java:2: Error: Method must start with super.PermissionProtected_enforcePermission() [MissingEnforcePermissionHelper] + @android.annotation.EnforcePermission(android.Manifest.permission.READ_PHONE_STATE) + ^ + 1 errors, 0 warnings + """ + ) + } + companion object { val stubs = arrayOf(aidlStub, contextStub, binderStub) } |