Merge "Prepare switching font loading to system server."
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index 2211807..d9c0c71 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -85,6 +85,7 @@
 import android.graphics.Bitmap;
 import android.graphics.Canvas;
 import android.graphics.HardwareRenderer;
+import android.graphics.Typeface;
 import android.hardware.display.DisplayManagerGlobal;
 import android.inputmethodservice.InputMethodService;
 import android.media.MediaFrameworkInitializer;
@@ -117,6 +118,7 @@
 import android.os.RemoteCallback;
 import android.os.RemoteException;
 import android.os.ServiceManager;
+import android.os.SharedMemory;
 import android.os.StatsFrameworkInitializer;
 import android.os.StatsServiceManager;
 import android.os.StrictMode;
@@ -844,6 +846,8 @@
 
         long[] disabledCompatChanges;
 
+        SharedMemory mSerializedSystemFontMap;
+
         @Override
         public String toString() {
             return "AppBindData{appInfo=" + appInfo + "}";
@@ -1054,7 +1058,8 @@
                 boolean isRestrictedBackupMode, boolean persistent, Configuration config,
                 CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
                 String buildSerial, AutofillOptions autofillOptions,
-                ContentCaptureOptions contentCaptureOptions, long[] disabledCompatChanges) {
+                ContentCaptureOptions contentCaptureOptions, long[] disabledCompatChanges,
+                SharedMemory serializedSystemFontMap) {
             if (services != null) {
                 if (false) {
                     // Test code to make sure the app could see the passed-in services.
@@ -1103,6 +1108,7 @@
             data.autofillOptions = autofillOptions;
             data.contentCaptureOptions = contentCaptureOptions;
             data.disabledCompatChanges = disabledCompatChanges;
+            data.mSerializedSystemFontMap = serializedSystemFontMap;
             sendMessage(H.BIND_APPLICATION, data);
         }
 
@@ -6411,6 +6417,13 @@
          */
         LocaleList.setDefault(data.config.getLocales());
 
+        try {
+            Typeface.setSystemFontMap(data.mSerializedSystemFontMap);
+        } catch (IOException | ErrnoException e) {
+            Slog.e(TAG, "Failed to parse serialized system font map");
+            Typeface.loadPreinstalledSystemFontMap();
+        }
+
         synchronized (mResourcesManager) {
             /*
              * Update the system configuration since its preloaded and might not
diff --git a/core/java/android/app/IApplicationThread.aidl b/core/java/android/app/IApplicationThread.aidl
index 22ca42e..890e957 100644
--- a/core/java/android/app/IApplicationThread.aidl
+++ b/core/java/android/app/IApplicationThread.aidl
@@ -43,6 +43,7 @@
 import android.os.ParcelFileDescriptor;
 import android.os.PersistableBundle;
 import android.os.RemoteCallback;
+import android.os.SharedMemory;
 
 import com.android.internal.app.IVoiceInteractor;
 import com.android.internal.content.ReferrerIntent;
@@ -75,7 +76,8 @@
             boolean restrictedBackupMode, boolean persistent, in Configuration config,
             in CompatibilityInfo compatInfo, in Map services,
             in Bundle coreSettings, in String buildSerial, in AutofillOptions autofillOptions,
-            in ContentCaptureOptions contentCaptureOptions, in long[] disabledCompatChanges);
+            in ContentCaptureOptions contentCaptureOptions, in long[] disabledCompatChanges,
+            in SharedMemory serializedSystemFontMap);
     void runIsolatedEntryPoint(in String entryPoint, in String[] entryPointArgs);
     void scheduleExit();
     void scheduleServiceArgs(IBinder token, in ParceledListSlice args);
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 2357f36..02a9300 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -964,6 +964,9 @@
      * @hide
      */
     public static void preloadFontCache() {
+        if (Typeface.ENABLE_LAZY_TYPEFACE_INITIALIZATION) {
+            return;
+        }
         Paint p = new Paint();
         p.setAntiAlias(true);
         // Ensure that the Typeface is loaded here.
diff --git a/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java b/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java
index 5871e2e..7e99298 100644
--- a/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java
+++ b/core/tests/coretests/src/android/app/servertransaction/TransactionParcelTests.java
@@ -52,6 +52,7 @@
 import android.os.PersistableBundle;
 import android.os.RemoteCallback;
 import android.os.RemoteException;
+import android.os.SharedMemory;
 import android.platform.test.annotations.Presubmit;
 import android.view.DisplayAdjustments.FixedRotationAdjustments;
 import android.view.DisplayCutout;
@@ -440,7 +441,8 @@
                 IUiAutomationConnection iUiAutomationConnection, int i, boolean b, boolean b1,
                 boolean b2, boolean b3, Configuration configuration,
                 CompatibilityInfo compatibilityInfo, Map map, Bundle bundle1, String s1,
-                AutofillOptions ao, ContentCaptureOptions co, long[] disableCompatChanges)
+                AutofillOptions ao, ContentCaptureOptions co, long[] disableCompatChanges,
+                SharedMemory serializedSystemFontMap)
                 throws RemoteException {
         }
 
diff --git a/graphics/java/android/graphics/Typeface.java b/graphics/java/android/graphics/Typeface.java
index 36ef0a4..24987da 100644
--- a/graphics/java/android/graphics/Typeface.java
+++ b/graphics/java/android/graphics/Typeface.java
@@ -81,6 +81,9 @@
 
     private static String TAG = "Typeface";
 
+    /** @hide */
+    public static final boolean ENABLE_LAZY_TYPEFACE_INITIALIZATION = false;
+
     private static final NativeAllocationRegistry sRegistry =
             NativeAllocationRegistry.createMalloced(
             Typeface.class.getClassLoader(), nativeGetReleaseFunc());
@@ -1329,7 +1332,9 @@
     }
 
     static {
-        loadPreinstalledSystemFontMap();
+        if (!ENABLE_LAZY_TYPEFACE_INITIALIZATION) {
+            loadPreinstalledSystemFontMap();
+        }
     }
 
     @Override
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index df1081e..da6e7ff 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -252,6 +252,7 @@
 import android.os.RemoteException;
 import android.os.ResultReceiver;
 import android.os.ServiceManager;
+import android.os.SharedMemory;
 import android.os.ShellCallback;
 import android.os.StrictMode;
 import android.os.SystemClock;
@@ -348,6 +349,7 @@
 import com.android.server.compat.PlatformCompat;
 import com.android.server.contentcapture.ContentCaptureManagerInternal;
 import com.android.server.firewall.IntentFirewall;
+import com.android.server.graphics.fonts.FontManagerInternal;
 import com.android.server.job.JobSchedulerInternal;
 import com.android.server.pm.Installer;
 import com.android.server.pm.permission.PermissionManagerServiceInternal;
@@ -4358,6 +4360,11 @@
                             app.info.packageName);
                 }
             }
+            SharedMemory serializedSystemFontMap = null;
+            final FontManagerInternal fm = LocalServices.getService(FontManagerInternal.class);
+            if (fm != null) {
+                serializedSystemFontMap = fm.getSerializedSystemFontMap();
+            }
 
             checkTime(startTime, "attachApplicationLocked: immediately before bindApplication");
             bindApplicationTimeMillis = SystemClock.elapsedRealtime();
@@ -4383,7 +4390,7 @@
                         app.compat, getCommonServicesLocked(app.isolated),
                         mCoreSettingsObserver.getCoreSettingsLocked(),
                         buildSerial, autofillOptions, contentCaptureOptions,
-                        app.mDisabledCompatChanges);
+                        app.mDisabledCompatChanges, serializedSystemFontMap);
             } else {
                 thread.bindApplication(processName, appInfo, providerList, null, profilerInfo,
                         null, null, null, testMode,
@@ -4393,7 +4400,7 @@
                         app.compat, getCommonServicesLocked(app.isolated),
                         mCoreSettingsObserver.getCoreSettingsLocked(),
                         buildSerial, autofillOptions, contentCaptureOptions,
-                        app.mDisabledCompatChanges);
+                        app.mDisabledCompatChanges, serializedSystemFontMap);
             }
             if (profilerInfo != null) {
                 profilerInfo.closeFd();
diff --git a/services/core/java/com/android/server/graphics/fonts/FontManagerInternal.java b/services/core/java/com/android/server/graphics/fonts/FontManagerInternal.java
new file mode 100644
index 0000000..e4b7b03
--- /dev/null
+++ b/services/core/java/com/android/server/graphics/fonts/FontManagerInternal.java
@@ -0,0 +1,27 @@
+/*
+ * 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.
+ */
+
+package com.android.server.graphics.fonts;
+
+import android.annotation.Nullable;
+import android.os.SharedMemory;
+
+/** Local interface for {@link FontManagerService}. */
+public interface FontManagerInternal {
+
+    /** Returns a SharedMemory in which the system font map is serialized. */
+    @Nullable SharedMemory getSerializedSystemFontMap();
+}
diff --git a/services/core/java/com/android/server/graphics/fonts/FontManagerService.java b/services/core/java/com/android/server/graphics/fonts/FontManagerService.java
new file mode 100644
index 0000000..22921ad
--- /dev/null
+++ b/services/core/java/com/android/server/graphics/fonts/FontManagerService.java
@@ -0,0 +1,85 @@
+/*
+ * 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.
+ */
+
+package com.android.server.graphics.fonts;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.content.Context;
+import android.graphics.Typeface;
+import android.os.SharedMemory;
+import android.system.ErrnoException;
+import android.util.Slog;
+
+import com.android.internal.annotations.GuardedBy;
+import com.android.server.LocalServices;
+import com.android.server.SystemService;
+
+import java.io.IOException;
+
+/** A service for managing system fonts. */
+// TODO(b/173619554): Add API to update fonts.
+public final class FontManagerService {
+
+    private static final String TAG = "FontManagerService";
+
+    /** Class to manage FontManagerService's lifecycle. */
+    public static final class Lifecycle extends SystemService {
+        private final FontManagerService mService;
+
+        public Lifecycle(@NonNull Context context) {
+            super(context);
+            mService = new FontManagerService();
+        }
+
+        @Override
+        public void onStart() {
+            LocalServices.addService(FontManagerInternal.class,
+                    new FontManagerInternal() {
+                        @Override
+                        @Nullable
+                        public SharedMemory getSerializedSystemFontMap() {
+                            return mService.getSerializedSystemFontMap();
+                        }
+                    });
+        }
+    }
+
+    @GuardedBy("this")
+    @Nullable
+    private SharedMemory mSerializedSystemFontMap = null;
+
+    @Nullable
+    private SharedMemory getSerializedSystemFontMap() {
+        synchronized (FontManagerService.this) {
+            if (mSerializedSystemFontMap == null) {
+                mSerializedSystemFontMap = createSerializedSystemFontMapLocked();
+            }
+            return mSerializedSystemFontMap;
+        }
+    }
+
+    @Nullable
+    private SharedMemory createSerializedSystemFontMapLocked() {
+        // TODO(b/173619554): use updated fonts.
+        try {
+            return Typeface.serializeFontMap(Typeface.getSystemFontMap());
+        } catch (IOException | ErrnoException e) {
+            Slog.e(TAG, "Failed to serialize SystemServer system font map", e);
+        }
+        return null;
+    }
+}
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 10b3265..6525e11 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -47,6 +47,7 @@
 import android.database.sqlite.SQLiteCompatibilityWalFlags;
 import android.database.sqlite.SQLiteGlobal;
 import android.graphics.GraphicsStatsService;
+import android.graphics.Typeface;
 import android.hardware.display.DisplayManagerInternal;
 import android.net.ConnectivityManager;
 import android.net.ConnectivityModuleConnector;
@@ -120,6 +121,7 @@
 import com.android.server.dreams.DreamManagerService;
 import com.android.server.emergency.EmergencyAffordanceService;
 import com.android.server.gpu.GpuService;
+import com.android.server.graphics.fonts.FontManagerService;
 import com.android.server.hdmi.HdmiControlService;
 import com.android.server.incident.IncidentCompanionService;
 import com.android.server.input.InputManagerService;
@@ -673,6 +675,11 @@
             SystemServerInitThreadPool tp = SystemServerInitThreadPool.start();
             mDumper.addDumpable(tp);
 
+            // Load preinstalled system fonts for system server, so that WindowManagerService, etc
+            // can start using Typeface. Note that fonts are required not only for text rendering,
+            // but also for some text operations (e.g. TextUtils.makeSafeForPresentation()).
+            Typeface.loadPreinstalledSystemFontMap();
+
             // Attach JVMTI agent if this is a debuggable build and the system property is set.
             if (Build.IS_DEBUGGABLE) {
                 // Property is of the form "library_path=parameters".
@@ -1604,6 +1611,10 @@
             }
             t.traceEnd();
 
+            t.traceBegin("StartFontManagerService");
+            mSystemServiceManager.startService(FontManagerService.Lifecycle.class);
+            t.traceEnd();
+
             t.traceBegin("StartTextServicesManager");
             mSystemServiceManager.startService(TextServicesManagerService.Lifecycle.class);
             t.traceEnd();