Make on-screen keyboard settings support tab layout

Introduces following fragments for work flow.

- Add ProfileSelectKeyboardFragment which used to display
  personal/work fragment when user has work profile.
- Introduce UserAwareContext in AvailableVirtualKeyboardFragment
  to support personal/work user installed input methods handling.

Bug: 174360557
Bug: 197707782
Test: Manual test as bug video
Change-Id: I1019e375c5d42de7bc7c048d5d66e8e2f58acce8
diff --git a/res/xml/language_and_input.xml b/res/xml/language_and_input.xml
index 2055ab7..f33ef5c 100644
--- a/res/xml/language_and_input.xml
+++ b/res/xml/language_and_input.xml
@@ -91,13 +91,6 @@
         settings:searchable="false">
 
         <Preference
-            android:key="virtual_keyboards_for_work_pref"
-            android:title="@string/virtual_keyboards_for_work_title"
-            android:fragment="com.android.settings.inputmethod.AvailableVirtualKeyboardFragment"
-            settings:forWork="true"
-            settings:controller="com.android.settings.inputmethod.VirtualKeyboardForWorkPreferenceController" />
-
-        <Preference
             android:key="spellcheckers_settings_for_work_pref"
             android:title="@string/spellcheckers_settings_for_work_title"
             android:fragment="com.android.settings.inputmethod.SpellCheckersSettings"
diff --git a/src/com/android/settings/dashboard/profileselector/ProfileFragmentBridge.java b/src/com/android/settings/dashboard/profileselector/ProfileFragmentBridge.java
index 704d00b..b948e54 100644
--- a/src/com/android/settings/dashboard/profileselector/ProfileFragmentBridge.java
+++ b/src/com/android/settings/dashboard/profileselector/ProfileFragmentBridge.java
@@ -21,6 +21,7 @@
 import com.android.settings.accounts.AccountDashboardFragment;
 import com.android.settings.applications.manageapplications.ManageApplications;
 import com.android.settings.deviceinfo.StorageDashboardFragment;
+import com.android.settings.inputmethod.AvailableVirtualKeyboardFragment;
 import com.android.settings.location.LocationServices;
 import com.android.settings.location.RecentLocationAccessSeeAllFragment;
 
@@ -49,5 +50,7 @@
                 ProfileSelectLocationServicesFragment.class.getName());
         FRAGMENT_MAP.put(StorageDashboardFragment.class.getName(),
                 ProfileSelectStorageFragment.class.getName());
+        FRAGMENT_MAP.put(AvailableVirtualKeyboardFragment.class.getName(),
+                ProfileSelectKeyboardFragment.class.getName());
     }
 }
diff --git a/src/com/android/settings/dashboard/profileselector/ProfileSelectKeyboardFragment.java b/src/com/android/settings/dashboard/profileselector/ProfileSelectKeyboardFragment.java
new file mode 100644
index 0000000..c4386e6
--- /dev/null
+++ b/src/com/android/settings/dashboard/profileselector/ProfileSelectKeyboardFragment.java
@@ -0,0 +1,57 @@
+/*
+ * 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.settings.dashboard.profileselector;
+
+import android.os.Bundle;
+
+import androidx.fragment.app.Fragment;
+
+import com.android.settings.R;
+import com.android.settings.inputmethod.AvailableVirtualKeyboardFragment;
+
+/**
+ * When current user has work profile, this fragment used following fragments to represent the
+ * on-screen keyboard settings page.
+ *
+ * <p>{@link AvailableVirtualKeyboardFragment} used to show both of personal/work user installed
+ * IMEs.</p>
+ */
+public final class ProfileSelectKeyboardFragment extends ProfileSelectFragment {
+
+    @Override
+    protected int getPreferenceScreenResId() {
+        return R.xml.available_virtual_keyboard;
+    }
+
+    @Override
+    public Fragment[] getFragments() {
+        final Bundle personalOnly = new Bundle();
+        personalOnly.putInt(EXTRA_PROFILE, ProfileType.PERSONAL);
+        final Fragment personalFragment = new AvailableVirtualKeyboardFragment();
+        personalFragment.setArguments(personalOnly);
+
+        final Bundle workOnly = new Bundle();
+        workOnly.putInt(EXTRA_PROFILE, ProfileType.WORK);
+        final Fragment workFragment = new AvailableVirtualKeyboardFragment();
+        workFragment.setArguments(workOnly);
+
+        return new Fragment[]{
+                personalFragment,
+                workFragment
+        };
+    }
+}
diff --git a/src/com/android/settings/inputmethod/AvailableVirtualKeyboardFragment.java b/src/com/android/settings/inputmethod/AvailableVirtualKeyboardFragment.java
index 7523ae4..b083aef 100644
--- a/src/com/android/settings/inputmethod/AvailableVirtualKeyboardFragment.java
+++ b/src/com/android/settings/inputmethod/AvailableVirtualKeyboardFragment.java
@@ -16,18 +16,21 @@
 
 package com.android.settings.inputmethod;
 
-import android.app.Activity;
 import android.app.admin.DevicePolicyManager;
 import android.app.settings.SettingsEnums;
 import android.content.Context;
 import android.content.res.Configuration;
 import android.os.Bundle;
+import android.os.UserHandle;
+import android.os.UserManager;
 import android.provider.SearchIndexableResource;
 import android.view.inputmethod.InputMethodInfo;
 import android.view.inputmethod.InputMethodManager;
 
 import com.android.settings.R;
-import com.android.settings.SettingsPreferenceFragment;
+import com.android.settings.Utils;
+import com.android.settings.dashboard.DashboardFragment;
+import com.android.settings.dashboard.profileselector.ProfileSelectFragment;
 import com.android.settings.search.BaseSearchIndexProvider;
 import com.android.settingslib.inputmethod.InputMethodAndSubtypeUtilCompat;
 import com.android.settingslib.inputmethod.InputMethodPreference;
@@ -38,23 +41,41 @@
 import java.util.ArrayList;
 import java.util.List;
 
+/**
+ * The fragment for on-screen keyboard settings which used to display user installed IMEs.
+ *
+ * TODO(b/207452897): Add test for AvailableVirtualKeyboardFragment
+ */
 @SearchIndexable
-public final class AvailableVirtualKeyboardFragment extends SettingsPreferenceFragment
+public final class AvailableVirtualKeyboardFragment extends DashboardFragment
         implements InputMethodPreference.OnSavePreferenceListener {
+    private static final String TAG = "AvailableVirtualKeyboardFragment";
 
     private final ArrayList<InputMethodPreference> mInputMethodPreferenceList = new ArrayList<>();
     private InputMethodSettingValuesWrapper mInputMethodSettingValues;
-    private InputMethodManager mImm;
-    private DevicePolicyManager mDpm;
+    private Context mUserAwareContext;
+    private int mUserId;
 
     @Override
     public void onCreatePreferences(Bundle bundle, String s) {
         addPreferencesFromResource(R.xml.available_virtual_keyboard);
-        Activity activity = getActivity();
+        mInputMethodSettingValues = InputMethodSettingValuesWrapper.getInstance(mUserAwareContext);
+    }
 
-        mInputMethodSettingValues = InputMethodSettingValuesWrapper.getInstance(activity);
-        mImm = activity.getSystemService(InputMethodManager.class);
-        mDpm = activity.getSystemService(DevicePolicyManager.class);
+    @Override
+    public void onAttach(Context context) {
+        super.onAttach(context);
+        final int profileType = getArguments().getInt(ProfileSelectFragment.EXTRA_PROFILE);
+        if (profileType == ProfileSelectFragment.ProfileType.WORK) {
+            final UserManager userManager = UserManager.get(context);
+            final UserHandle workUser = Utils.getManagedProfile(userManager);
+            // get work userId
+            mUserId = Utils.getManagedProfileId(userManager, UserHandle.myUserId());
+            mUserAwareContext = context.createContextAsUser(workUser, 0);
+        } else {
+            mUserId = UserHandle.myUserId();
+            mUserAwareContext = context;
+        }
     }
 
     @Override
@@ -67,11 +88,24 @@
     }
 
     @Override
+    protected int getPreferenceScreenResId() {
+        return R.xml.available_virtual_keyboard;
+    }
+
+    @Override
+    protected String getLogTag() {
+        return TAG;
+    }
+
+    @Override
     public void onSaveInputMethodPreference(final InputMethodPreference pref) {
         final boolean hasHardwareKeyboard = getResources().getConfiguration().keyboard
                 == Configuration.KEYBOARD_QWERTY;
-        InputMethodAndSubtypeUtilCompat.saveInputMethodSubtypeList(this, getContentResolver(),
-                mImm.getInputMethodList(), hasHardwareKeyboard);
+        InputMethodAndSubtypeUtilCompat.saveInputMethodSubtypeListForUser(this,
+                mUserAwareContext.getContentResolver(),
+                getContext().getSystemService(
+                        InputMethodManager.class).getInputMethodListAsUser(mUserId),
+                hasHardwareKeyboard, mUserId);
         // Update input method settings and preference list.
         mInputMethodSettingValues.refreshAllInputMethodAndSubtypes();
         for (final InputMethodPreference p : mInputMethodPreferenceList) {
@@ -88,10 +122,12 @@
         mInputMethodSettingValues.refreshAllInputMethodAndSubtypes();
         // Clear existing "InputMethodPreference"s
         mInputMethodPreferenceList.clear();
-        List<String> permittedList = mDpm.getPermittedInputMethodsForCurrentUser();
-        final Context context = getPrefContext();
+        final List<String> permittedList = mUserAwareContext.getSystemService(
+                DevicePolicyManager.class).getPermittedInputMethods();
+        final Context prefContext = getPrefContext();
         final List<InputMethodInfo> imis = mInputMethodSettingValues.getInputMethodList();
-        final List<InputMethodInfo> enabledImis = mImm.getEnabledInputMethodList();
+        final List<InputMethodInfo> enabledImis = getContext().getSystemService(
+                InputMethodManager.class).getEnabledInputMethodListAsUser(mUserId);
         final int numImis = (imis == null ? 0 : imis.size());
         for (int i = 0; i < numImis; ++i) {
             final InputMethodInfo imi = imis.get(i);
@@ -101,12 +137,12 @@
             // allowed by organization. Doing so will allow the user to disable the input method and
             // remain complaint with the organization's policy. Once disabled, the input method
             // cannot be re-enabled because it is not in the permitted list.
-            final boolean isAllowedByOrganization = permittedList == null
+            final boolean isAllowedByOrganization = permittedList.isEmpty()
                     || permittedList.contains(imi.getPackageName())
                     || enabledImis.contains(imi);
-            final InputMethodPreference pref = new InputMethodPreference(
-                    context, imi, isAllowedByOrganization, this);
-            pref.setIcon(imi.loadIcon(context.getPackageManager()));
+            final InputMethodPreference pref = new InputMethodPreference(prefContext, imi,
+                    isAllowedByOrganization, this, mUserId);
+            pref.setIcon(imi.loadIcon(mUserAwareContext.getPackageManager()));
             mInputMethodPreferenceList.add(pref);
         }
         final Collator collator = Collator.getInstance();