Merge "Fix work profile issue" into udc-dev
diff --git a/res/xml/accounts_work_dashboard_settings_credman.xml b/res/xml/accounts_work_dashboard_settings_credman.xml
index 1529920..bb9976e 100644
--- a/res/xml/accounts_work_dashboard_settings_credman.xml
+++ b/res/xml/accounts_work_dashboard_settings_credman.xml
@@ -28,8 +28,8 @@
         android:title="@string/credman_chosen_app_title">
 
         <com.android.settings.widget.GearPreference
-            android:fragment="com.android.settings.applications.credentials.DefaultCombinedPicker"
-            android:key="default_credman_autofill_main"
+            android:fragment="com.android.settings.applications.credentials.DefaultCombinedPickerWork"
+            android:key="default_credman_autofill_main_work"
             android:title="@string/credman_chosen_app_title"
             settings:searchable="false">
             <extra
diff --git a/src/com/android/settings/accounts/AccountDashboardFragment.java b/src/com/android/settings/accounts/AccountDashboardFragment.java
index e4c2031..7816fd7 100644
--- a/src/com/android/settings/accounts/AccountDashboardFragment.java
+++ b/src/com/android/settings/accounts/AccountDashboardFragment.java
@@ -86,7 +86,7 @@
                     forceUpdatePreferences();
                 }
             };
-            cmpp.init(this, getFragmentManager(), getIntent(), delegate);
+            cmpp.init(this, getFragmentManager(), getIntent(), delegate, /*isWorkProfile=*/false);
         } else {
             getSettingsLifecycle().addObserver(use(PasswordsPreferenceController.class));
         }
diff --git a/src/com/android/settings/accounts/AccountPersonalDashboardFragment.java b/src/com/android/settings/accounts/AccountPersonalDashboardFragment.java
index 32c3c13..cd1cd5c 100644
--- a/src/com/android/settings/accounts/AccountPersonalDashboardFragment.java
+++ b/src/com/android/settings/accounts/AccountPersonalDashboardFragment.java
@@ -78,7 +78,7 @@
                     forceUpdatePreferences();
                 }
             };
-            cmpp.init(this, getFragmentManager(), getIntent(), delegate);
+            cmpp.init(this, getFragmentManager(), getIntent(), delegate, /*isWorkProfile=*/false);
         } else {
             getSettingsLifecycle().addObserver(use(PasswordsPreferenceController.class));
         }
diff --git a/src/com/android/settings/accounts/AccountWorkProfileDashboardFragment.java b/src/com/android/settings/accounts/AccountWorkProfileDashboardFragment.java
index 39146c7..f0da2fb 100644
--- a/src/com/android/settings/accounts/AccountWorkProfileDashboardFragment.java
+++ b/src/com/android/settings/accounts/AccountWorkProfileDashboardFragment.java
@@ -78,7 +78,7 @@
                     forceUpdatePreferences();
                 }
             };
-            cmpp.init(this, getFragmentManager(), getIntent(), delegate);
+            cmpp.init(this, getFragmentManager(), getIntent(), delegate, /*isWorkProfile=*/true);
         } else {
             getSettingsLifecycle().addObserver(use(PasswordsPreferenceController.class));
         }
diff --git a/src/com/android/settings/applications/credentials/CombinedProviderInfo.java b/src/com/android/settings/applications/credentials/CombinedProviderInfo.java
index 89a13ef..1fd3075 100644
--- a/src/com/android/settings/applications/credentials/CombinedProviderInfo.java
+++ b/src/com/android/settings/applications/credentials/CombinedProviderInfo.java
@@ -26,6 +26,7 @@
 import android.graphics.drawable.Drawable;
 import android.service.autofill.AutofillServiceInfo;
 import android.text.TextUtils;
+import android.util.IconDrawableFactory;
 
 import java.util.ArrayList;
 import java.util.Collections;
@@ -83,11 +84,12 @@
 
     /** Returns the app icon. */
     @Nullable
-    public Drawable getAppIcon(@NonNull Context context) {
+    public Drawable getAppIcon(@NonNull Context context, int userId) {
+        IconDrawableFactory factory = IconDrawableFactory.newInstance(context);
         Drawable icon = null;
         ServiceInfo brandingService = getBrandingService();
         if (brandingService != null) {
-            icon = brandingService.loadIcon(context.getPackageManager());
+            icon = factory.getBadgedIcon(brandingService, getApplicationInfo(), userId);
         }
 
         // If the branding service gave us a icon then use that.
@@ -95,8 +97,8 @@
             return icon;
         }
 
-        // Otherwise fallback to the app label and then the package name.
-        return getApplicationInfo().loadIcon(context.getPackageManager());
+        // Otherwise fallback to the app icon and then the package name.
+        return factory.getBadgedIcon(getApplicationInfo(), userId);
     }
 
     /** Returns the app name. */
diff --git a/src/com/android/settings/applications/credentials/CredentialManagerPreferenceController.java b/src/com/android/settings/applications/credentials/CredentialManagerPreferenceController.java
index 9d86c58a..e906e48 100644
--- a/src/com/android/settings/applications/credentials/CredentialManagerPreferenceController.java
+++ b/src/com/android/settings/applications/credentials/CredentialManagerPreferenceController.java
@@ -41,6 +41,7 @@
 import android.os.Handler;
 import android.os.OutcomeReceiver;
 import android.os.UserHandle;
+import android.os.UserManager;
 import android.provider.Settings;
 import android.service.autofill.AutofillServiceInfo;
 import android.text.TextUtils;
@@ -110,6 +111,7 @@
     private @Nullable PreferenceScreen mPreferenceScreen = null;
 
     private boolean mVisibility = false;
+    private boolean mIsWorkProfile = false;
 
     public CredentialManagerPreferenceController(Context context, String preferenceKey) {
         super(context, preferenceKey);
@@ -169,14 +171,17 @@
      * @param fragmentManager the fragment manager to use
      * @param intent the intent used to start the activity
      * @param delegate the delegate to send results back to
+     * @param isWorkProfile whether this controller is under a work profile user
      */
     public void init(
             DashboardFragment fragment,
             FragmentManager fragmentManager,
             @Nullable Intent launchIntent,
-            @NonNull Delegate delegate) {
+            @NonNull Delegate delegate,
+            boolean isWorkProfile) {
         fragment.getSettingsLifecycle().addObserver(this);
         mFragmentManager = fragmentManager;
+        mIsWorkProfile = isWorkProfile;
         setDelegate(delegate);
         verifyReceivedIntent(launchIntent);
     }
@@ -420,7 +425,7 @@
                 continue;
             }
 
-            Drawable icon = combinedInfo.getAppIcon(context);
+            Drawable icon = combinedInfo.getAppIcon(context, getUser());
             CharSequence title = combinedInfo.getAppName(context);
 
             // Build the pref and add it to the output & group.
@@ -681,9 +686,12 @@
         return new ConfirmationDialogFragment(host, packageName, appName);
     }
 
-    private int getUser() {
-        UserHandle workUser = getWorkProfileUser();
-        return workUser != null ? workUser.getIdentifier() : UserHandle.myUserId();
+    protected int getUser() {
+        if (mIsWorkProfile) {
+            UserHandle workProfile = Utils.getManagedProfile(UserManager.get(mContext));
+            return workProfile.getIdentifier();
+        }
+        return UserHandle.myUserId();
     }
 
     /** Called when the dialog button is clicked. */
diff --git a/src/com/android/settings/applications/credentials/DefaultCombinedPicker.java b/src/com/android/settings/applications/credentials/DefaultCombinedPicker.java
index 6781b10..b8d104c 100644
--- a/src/com/android/settings/applications/credentials/DefaultCombinedPicker.java
+++ b/src/com/android/settings/applications/credentials/DefaultCombinedPicker.java
@@ -47,9 +47,7 @@
 import com.android.settingslib.widget.CandidateInfo;
 
 import java.util.ArrayList;
-import java.util.HashSet;
 import java.util.List;
-import java.util.Set;
 
 public class DefaultCombinedPicker extends DefaultAppPickerFragment {
 
@@ -65,6 +63,7 @@
     private DialogInterface.OnClickListener mCancelListener;
 
     private CredentialManager mCredentialManager;
+    private int mIntentSenderUserId = -1;
 
     @Override
     public void onCreate(Bundle savedInstanceState) {
@@ -79,9 +78,11 @@
                     };
             // If mCancelListener is not null, fragment is started from
             // ACTION_REQUEST_SET_AUTOFILL_SERVICE and we should always use the calling uid.
-            mUserId = UserHandle.myUserId();
+            mIntentSenderUserId = UserHandle.myUserId();
         }
 
+        getUser();
+
         mSettingsPackageMonitor.register(activity, activity.getMainLooper(), false);
         update();
     }
@@ -167,7 +168,7 @@
                 Settings.Secure.getStringForUser(
                         getActivity().getContentResolver(),
                         Settings.Secure.AUTOFILL_SERVICE_SEARCH_URI,
-                        mUserId);
+                        getUser());
         if (TextUtils.isEmpty(searchUri)) {
             return null;
         }
@@ -177,7 +178,7 @@
         final Preference preference = new Preference(context);
         preference.setOnPreferenceClickListener(
                 p -> {
-                    context.startActivityAsUser(addNewServiceIntent, UserHandle.of(mUserId));
+                    context.startActivityAsUser(addNewServiceIntent, UserHandle.of(getUser()));
                     return true;
                 });
         preference.setTitle(R.string.print_menu_item_add_service);
@@ -212,17 +213,17 @@
     private List<CombinedProviderInfo> getAllProviders() {
         final Context context = getContext();
         final List<AutofillServiceInfo> autofillProviders =
-                AutofillServiceInfo.getAvailableServices(context, mUserId);
+                AutofillServiceInfo.getAvailableServices(context, getUser());
 
         final CredentialManager service = getCredentialProviderService();
         final List<CredentialProviderInfo> credManProviders = new ArrayList<>();
         if (service != null) {
             credManProviders.addAll(
                     service.getCredentialProviderServices(
-                            mUserId, CredentialManager.PROVIDER_FILTER_USER_PROVIDERS_ONLY));
+                            getUser(), CredentialManager.PROVIDER_FILTER_USER_PROVIDERS_ONLY));
         }
 
-        final String selectedAutofillProvider = getSelectedAutofillProvider(context, mUserId);
+        final String selectedAutofillProvider = getSelectedAutofillProvider(context, getUser());
         return CombinedProviderInfo.buildMergedList(
                 autofillProviders, credManProviders, selectedAutofillProvider);
     }
@@ -244,7 +245,7 @@
                         new DefaultAppInfo(
                                 context,
                                 mPm,
-                                mUserId,
+                                getUser(),
                                 cpi.getApplicationInfo(),
                                 cpi.getSettingsSubtitle(),
                                 true));
@@ -253,7 +254,7 @@
                         new DefaultAppInfo(
                                 context,
                                 mPm,
-                                mUserId,
+                                getUser(),
                                 brandingService,
                                 cpi.getSettingsSubtitle(),
                                 true));
@@ -350,7 +351,7 @@
         }
 
         Settings.Secure.putStringForUser(
-                getContext().getContentResolver(), AUTOFILL_SETTING, autofillProvider, mUserId);
+                getContext().getContentResolver(), AUTOFILL_SETTING, autofillProvider, getUser());
 
         final CredentialManager service = getCredentialProviderService();
         if (service == null) {
@@ -362,7 +363,7 @@
         final List<String> credManProviders = new ArrayList<>();
         for (CredentialProviderInfo cpi :
                 service.getCredentialProviderServices(
-                        mUserId, CredentialManager.PROVIDER_FILTER_USER_PROVIDERS_ONLY)) {
+                        getUser(), CredentialManager.PROVIDER_FILTER_USER_PROVIDERS_ONLY)) {
 
             if (cpi.isEnabled() && !cpi.isPrimary()) {
                 credManProviders.add(cpi.getServiceInfo().getComponentName().flattenToString());
@@ -379,7 +380,7 @@
         service.setEnabledProviders(
                 primaryCredManProviders,
                 credManProviders,
-                mUserId,
+                getUser(),
                 ContextCompat.getMainExecutor(getContext()),
                 new OutcomeReceiver<Void, SetEnabledProvidersException>() {
                     @Override
@@ -393,4 +394,11 @@
                     }
                 });
     }
+
+    protected int getUser() {
+        if (mIntentSenderUserId >= 0) {
+            return mIntentSenderUserId;
+        }
+        return UserHandle.myUserId();
+    }
 }
diff --git a/src/com/android/settings/applications/credentials/DefaultCombinedPickerWork.java b/src/com/android/settings/applications/credentials/DefaultCombinedPickerWork.java
new file mode 100644
index 0000000..9808502
--- /dev/null
+++ b/src/com/android/settings/applications/credentials/DefaultCombinedPickerWork.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settings.applications.credentials;
+
+import android.os.UserHandle;
+import android.os.UserManager;
+
+import com.android.settings.Utils;
+
+public class DefaultCombinedPickerWork extends DefaultCombinedPicker {
+
+    @Override
+    protected int getUser() {
+        UserHandle workProfile = Utils.getManagedProfile(UserManager.get(getContext()));
+        return workProfile.getIdentifier();
+    }
+}
diff --git a/src/com/android/settings/applications/credentials/DefaultCombinedPreferenceController.java b/src/com/android/settings/applications/credentials/DefaultCombinedPreferenceController.java
index 64d4f0d..34881ab 100644
--- a/src/com/android/settings/applications/credentials/DefaultCombinedPreferenceController.java
+++ b/src/com/android/settings/applications/credentials/DefaultCombinedPreferenceController.java
@@ -24,6 +24,7 @@
 import android.content.pm.ServiceInfo;
 import android.credentials.CredentialManager;
 import android.credentials.CredentialProviderInfo;
+import android.os.UserHandle;
 import android.provider.Settings;
 import android.service.autofill.AutofillService;
 import android.service.autofill.AutofillServiceInfo;
@@ -75,13 +76,13 @@
             return null;
         }
         final AutofillSettingIntentProvider intentProvider =
-                new AutofillSettingIntentProvider(mContext, mUserId, info.getKey());
+                new AutofillSettingIntentProvider(mContext, getUser(), info.getKey());
         return intentProvider.getIntent();
     }
 
     @Override
     protected DefaultAppInfo getDefaultAppInfo() {
-        List<CombinedProviderInfo> providers = getAllProviders(mUserId);
+        List<CombinedProviderInfo> providers = getAllProviders(getUser());
         CombinedProviderInfo topProvider = CombinedProviderInfo.getTopProvider(providers);
         if (topProvider != null) {
             ServiceInfo brandingService = topProvider.getBrandingService();
@@ -89,7 +90,7 @@
                 return new DefaultAppInfo(
                         mContext,
                         mPackageManager,
-                        mUserId,
+                        getUser(),
                         topProvider.getApplicationInfo(),
                         topProvider.getSettingsSubtitle(),
                         true);
@@ -97,7 +98,7 @@
                 return new DefaultAppInfo(
                         mContext,
                         mPackageManager,
-                        mUserId,
+                        getUser(),
                         brandingService,
                         topProvider.getSettingsSubtitle(),
                         true);
@@ -178,4 +179,8 @@
             return null;
         }
     }
+
+    protected int getUser() {
+        return UserHandle.myUserId();
+    }
 }
diff --git a/src/com/android/settings/applications/credentials/DefaultWorkCombinedPreferenceController.java b/src/com/android/settings/applications/credentials/DefaultWorkCombinedPreferenceController.java
index 0990f3b..74bf9026 100644
--- a/src/com/android/settings/applications/credentials/DefaultWorkCombinedPreferenceController.java
+++ b/src/com/android/settings/applications/credentials/DefaultWorkCombinedPreferenceController.java
@@ -44,7 +44,7 @@
 
     @Override
     public String getPreferenceKey() {
-        return "default_autofill_work";
+        return "default_credman_autofill_main_work";
     }
 
     @Override
@@ -81,4 +81,9 @@
     protected void startActivity(Intent intent) {
         mContext.startActivityAsUser(intent, mUserHandle);
     }
+
+    @Override
+    protected int getUser() {
+        return mUserHandle.getIdentifier();
+    }
 }