1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package android.provider;
17 
18 import android.annotation.IntDef;
19 import android.annotation.IntRange;
20 import android.annotation.NonNull;
21 import android.annotation.Nullable;
22 import android.content.ContentResolver;
23 import android.content.ContentUris;
24 import android.content.Context;
25 import android.content.pm.PackageInfo;
26 import android.content.pm.PackageManager;
27 import android.content.pm.PackageManager.NameNotFoundException;
28 import android.content.pm.ProviderInfo;
29 import android.content.pm.Signature;
30 import android.database.Cursor;
31 import android.graphics.Typeface;
32 import android.graphics.fonts.Font;
33 import android.graphics.fonts.FontFamily;
34 import android.graphics.fonts.FontStyle;
35 import android.graphics.fonts.FontVariationAxis;
36 import android.net.Uri;
37 import android.os.CancellationSignal;
38 import android.os.Handler;
39 import android.os.HandlerThread;
40 import android.os.ParcelFileDescriptor;
41 import android.os.Process;
42 import android.util.Log;
43 import android.util.LruCache;
44 
45 import com.android.internal.annotations.GuardedBy;
46 import com.android.internal.annotations.VisibleForTesting;
47 import com.android.internal.util.Preconditions;
48 
49 import java.io.FileInputStream;
50 import java.io.IOException;
51 import java.lang.annotation.Retention;
52 import java.lang.annotation.RetentionPolicy;
53 import java.nio.ByteBuffer;
54 import java.nio.channels.FileChannel;
55 import java.util.ArrayList;
56 import java.util.Arrays;
57 import java.util.Collections;
58 import java.util.Comparator;
59 import java.util.HashMap;
60 import java.util.List;
61 import java.util.Map;
62 import java.util.Set;
63 import java.util.concurrent.TimeUnit;
64 import java.util.concurrent.atomic.AtomicBoolean;
65 import java.util.concurrent.atomic.AtomicReference;
66 import java.util.concurrent.locks.Condition;
67 import java.util.concurrent.locks.Lock;
68 import java.util.concurrent.locks.ReentrantLock;
69 
70 /**
71  * Utility class to deal with Font ContentProviders.
72  */
73 public class FontsContract {
74     private static final String TAG = "FontsContract";
75 
76     /**
77      * Defines the constants used in a response from a Font Provider. The cursor returned from the
78      * query should have the ID column populated with the content uri ID for the resulting font.
79      * This should point to a real file or shared memory, as the client will mmap the given file
80      * descriptor. Pipes, sockets and other non-mmap-able file descriptors will fail to load in the
81      * client application.
82      */
83     public static final class Columns implements BaseColumns {
84 
85         // Do not instantiate.
Columns()86         private Columns() {}
87 
88         /**
89          * Constant used to request data from a font provider. The cursor returned from the query
90          * may populate this column with a long for the font file ID. The client will request a file
91          * descriptor to "file/FILE_ID" with this ID immediately under the top-level content URI. If
92          * not present, the client will request a file descriptor to the top-level URI with the
93          * given base font ID. Note that several results may return the same file ID, e.g. for TTC
94          * files with different indices.
95          */
96         public static final String FILE_ID = "file_id";
97         /**
98          * Constant used to request data from a font provider. The cursor returned from the query
99          * should have this column populated with an int for the ttc index for the resulting font.
100          */
101         public static final String TTC_INDEX = "font_ttc_index";
102         /**
103          * Constant used to request data from a font provider. The cursor returned from the query
104          * may populate this column with the font variation settings String information for the
105          * font.
106          */
107         public static final String VARIATION_SETTINGS = "font_variation_settings";
108         /**
109          * Constant used to request data from a font provider. The cursor returned from the query
110          * should have this column populated with the int weight for the resulting font. This value
111          * should be between 100 and 900. The most common values are 400 for regular weight and 700
112          * for bold weight.
113          */
114         public static final String WEIGHT = "font_weight";
115         /**
116          * Constant used to request data from a font provider. The cursor returned from the query
117          * should have this column populated with the int italic for the resulting font. This should
118          * be 0 for regular style and 1 for italic.
119          */
120         public static final String ITALIC = "font_italic";
121         /**
122          * Constant used to request data from a font provider. The cursor returned from the query
123          * should have this column populated to indicate the result status of the
124          * query. This will be checked before any other data in the cursor. Possible values are
125          * {@link #RESULT_CODE_OK}, {@link #RESULT_CODE_FONT_NOT_FOUND},
126          * {@link #RESULT_CODE_MALFORMED_QUERY} and {@link #RESULT_CODE_FONT_UNAVAILABLE} for system
127          * defined values. You may also define your own values in the 0x000010000..0xFFFF0000 range.
128          * If not present, {@link #RESULT_CODE_OK} will be assumed.
129          */
130         public static final String RESULT_CODE = "result_code";
131 
132         /**
133          * Constant used to represent a result was retrieved successfully. The given fonts will be
134          * attempted to retrieve immediately via
135          * {@link android.content.ContentProvider#openFile(Uri, String)}. See {@link #RESULT_CODE}.
136          */
137         public static final int RESULT_CODE_OK = 0;
138         /**
139          * Constant used to represent a result was not found. See {@link #RESULT_CODE}.
140          */
141         public static final int RESULT_CODE_FONT_NOT_FOUND = 1;
142         /**
143          * Constant used to represent a result was found, but cannot be provided at this moment. Use
144          * this to indicate, for example, that a font needs to be fetched from the network. See
145          * {@link #RESULT_CODE}.
146          */
147         public static final int RESULT_CODE_FONT_UNAVAILABLE = 2;
148         /**
149          * Constant used to represent that the query was not in a supported format by the provider.
150          * See {@link #RESULT_CODE}.
151          */
152         public static final int RESULT_CODE_MALFORMED_QUERY = 3;
153     }
154 
155     private static final Object sLock = new Object();
156     @GuardedBy("sLock")
157     private static Handler sHandler;
158     @GuardedBy("sLock")
159     private static HandlerThread sThread;
160     @GuardedBy("sLock")
161     private static Set<String> sInQueueSet;
162 
163     private volatile static Context sContext;  // set once in setApplicationContextForResources
164 
165     private static final LruCache<String, Typeface> sTypefaceCache = new LruCache<>(16);
166 
FontsContract()167     private FontsContract() {
168     }
169 
170     /** @hide */
setApplicationContextForResources(Context context)171     public static void setApplicationContextForResources(Context context) {
172         sContext = context.getApplicationContext();
173     }
174 
175     /**
176      * Object represent a font entry in the family returned from {@link #fetchFonts}.
177      */
178     public static class FontInfo {
179         private final Uri mUri;
180         private final int mTtcIndex;
181         private final FontVariationAxis[] mAxes;
182         private final int mWeight;
183         private final boolean mItalic;
184         private final int mResultCode;
185 
186         /**
187          * Creates a Font with all the information needed about a provided font.
188          * @param uri A URI associated to the font file.
189          * @param ttcIndex If providing a TTC_INDEX file, the index to point to. Otherwise, 0.
190          * @param axes If providing a variation font, the settings for it. May be null.
191          * @param weight An integer that indicates the font weight.
192          * @param italic A boolean that indicates the font is italic style or not.
193          * @param resultCode A boolean that indicates the font contents is ready.
194          */
195         /** @hide */
FontInfo(@onNull Uri uri, @IntRange(from = 0) int ttcIndex, @Nullable FontVariationAxis[] axes, @IntRange(from = 1, to = 1000) int weight, boolean italic, int resultCode)196         public FontInfo(@NonNull Uri uri, @IntRange(from = 0) int ttcIndex,
197                 @Nullable FontVariationAxis[] axes, @IntRange(from = 1, to = 1000) int weight,
198                 boolean italic, int resultCode) {
199             mUri = Preconditions.checkNotNull(uri);
200             mTtcIndex = ttcIndex;
201             mAxes = axes;
202             mWeight = weight;
203             mItalic = italic;
204             mResultCode = resultCode;
205         }
206 
207         /**
208          * Returns a URI associated to this record.
209          */
getUri()210         public @NonNull Uri getUri() {
211             return mUri;
212         }
213 
214         /**
215          * Returns the index to be used to access this font when accessing a TTC file.
216          */
getTtcIndex()217         public @IntRange(from = 0) int getTtcIndex() {
218             return mTtcIndex;
219         }
220 
221         /**
222          * Returns the list of axes associated to this font.
223          */
getAxes()224         public @Nullable FontVariationAxis[] getAxes() {
225             return mAxes;
226         }
227 
228         /**
229          * Returns the weight value for this font.
230          */
getWeight()231         public @IntRange(from = 1, to = 1000) int getWeight() {
232             return mWeight;
233         }
234 
235         /**
236          * Returns whether this font is italic.
237          */
isItalic()238         public boolean isItalic() {
239             return mItalic;
240         }
241 
242         /**
243          * Returns result code.
244          *
245          * {@link FontsContract.Columns#RESULT_CODE}
246          */
getResultCode()247         public int getResultCode() {
248             return mResultCode;
249         }
250     }
251 
252     /**
253      * Object returned from {@link #fetchFonts}.
254      */
255     public static class FontFamilyResult {
256         /**
257          * Constant represents that the font was successfully retrieved. Note that when this value
258          * is set and {@link #getFonts} returns an empty array, it means there were no fonts
259          * matching the given query.
260          */
261         public static final int STATUS_OK = 0;
262 
263         /**
264          * Constant represents that the given certificate was not matched with the provider's
265          * signature. {@link #getFonts} returns null if this status was set.
266          */
267         public static final int STATUS_WRONG_CERTIFICATES = 1;
268 
269         /**
270          * Constant represents that the provider returns unexpected data. {@link #getFonts} returns
271          * null if this status was set. For example, this value is set when the font provider
272          * gives invalid format of variation settings.
273          */
274         public static final int STATUS_UNEXPECTED_DATA_PROVIDED = 2;
275 
276         /**
277          * Constant represents that the fetching font data was rejected by system. This happens if
278          * the passed context is restricted.
279          */
280         public static final int STATUS_REJECTED = 3;
281 
282         /** @hide */
283         @IntDef(prefix = { "STATUS_" }, value = {
284                 STATUS_OK,
285                 STATUS_WRONG_CERTIFICATES,
286                 STATUS_UNEXPECTED_DATA_PROVIDED
287         })
288         @Retention(RetentionPolicy.SOURCE)
289         @interface FontResultStatus {}
290 
291         private final @FontResultStatus int mStatusCode;
292         private final FontInfo[] mFonts;
293 
294         /** @hide */
FontFamilyResult(@ontResultStatus int statusCode, @Nullable FontInfo[] fonts)295         public FontFamilyResult(@FontResultStatus int statusCode, @Nullable FontInfo[] fonts) {
296             mStatusCode = statusCode;
297             mFonts = fonts;
298         }
299 
getStatusCode()300         public @FontResultStatus int getStatusCode() {
301             return mStatusCode;
302         }
303 
getFonts()304         public @NonNull FontInfo[] getFonts() {
305             return mFonts;
306         }
307     }
308 
309     private static final int THREAD_RENEWAL_THRESHOLD_MS = 10000;
310 
311     private static final long SYNC_FONT_FETCH_TIMEOUT_MS = 500;
312 
313     // We use a background thread to post the content resolving work for all requests on. This
314     // thread should be quit/stopped after all requests are done.
315     // TODO: Factor out to other class. Consider to switch MessageQueue.IdleHandler.
316     private static final Runnable sReplaceDispatcherThreadRunnable = new Runnable() {
317         @Override
318         public void run() {
319             synchronized (sLock) {
320                 if (sThread != null) {
321                     sThread.quitSafely();
322                     sThread = null;
323                     sHandler = null;
324                 }
325             }
326         }
327     };
328 
329     /** @hide */
getFontSync(FontRequest request)330     public static Typeface getFontSync(FontRequest request) {
331         final String id = request.getIdentifier();
332         Typeface cachedTypeface = sTypefaceCache.get(id);
333         if (cachedTypeface != null) {
334             return cachedTypeface;
335         }
336 
337         // Unfortunately the typeface is not available at this time, but requesting from the font
338         // provider takes too much time. For now, request the font data to ensure it is in the cache
339         // next time and return.
340         synchronized (sLock) {
341             if (sHandler == null) {
342                 sThread = new HandlerThread("fonts", Process.THREAD_PRIORITY_BACKGROUND);
343                 sThread.start();
344                 sHandler = new Handler(sThread.getLooper());
345             }
346             final Lock lock = new ReentrantLock();
347             final Condition cond = lock.newCondition();
348             final AtomicReference<Typeface> holder = new AtomicReference<>();
349             final AtomicBoolean waiting = new AtomicBoolean(true);
350             final AtomicBoolean timeout = new AtomicBoolean(false);
351 
352             sHandler.post(() -> {
353                 try {
354                     FontFamilyResult result = fetchFonts(sContext, null, request);
355                     if (result.getStatusCode() == FontFamilyResult.STATUS_OK) {
356                         Typeface typeface = buildTypeface(sContext, null, result.getFonts());
357                         if (typeface != null) {
358                             sTypefaceCache.put(id, typeface);
359                         }
360                         holder.set(typeface);
361                     }
362                 } catch (NameNotFoundException e) {
363                     // Ignore.
364                 }
365                 lock.lock();
366                 try {
367                     if (!timeout.get()) {
368                       waiting.set(false);
369                       cond.signal();
370                     }
371                 } finally {
372                     lock.unlock();
373                 }
374             });
375             sHandler.removeCallbacks(sReplaceDispatcherThreadRunnable);
376             sHandler.postDelayed(sReplaceDispatcherThreadRunnable, THREAD_RENEWAL_THRESHOLD_MS);
377 
378             long remaining = TimeUnit.MILLISECONDS.toNanos(SYNC_FONT_FETCH_TIMEOUT_MS);
379             lock.lock();
380             try {
381                 if (!waiting.get()) {
382                     return holder.get();
383                 }
384                 for (;;) {
385                     try {
386                         remaining = cond.awaitNanos(remaining);
387                     } catch (InterruptedException e) {
388                         // do nothing.
389                     }
390                     if (!waiting.get()) {
391                         return holder.get();
392                     }
393                     if (remaining <= 0) {
394                         timeout.set(true);
395                         Log.w(TAG, "Remote font fetch timed out: " +
396                                 request.getProviderAuthority() + "/" + request.getQuery());
397                         return null;
398                     }
399                 }
400             } finally {
401                 lock.unlock();
402             }
403         }
404     }
405 
406     /**
407      * Interface used to receive asynchronously fetched typefaces.
408      */
409     public static class FontRequestCallback {
410         /**
411          * Constant returned by {@link #onTypefaceRequestFailed(int)} signaling that the given
412          * provider was not found on the device.
413          */
414         public static final int FAIL_REASON_PROVIDER_NOT_FOUND = -1;
415         /**
416          * Constant returned by {@link #onTypefaceRequestFailed(int)} signaling that the given
417          * provider must be authenticated and the given certificates do not match its signature.
418          */
419         public static final int FAIL_REASON_WRONG_CERTIFICATES = -2;
420         /**
421          * Constant returned by {@link #onTypefaceRequestFailed(int)} signaling that the font
422          * returned by the provider was not loaded properly.
423          */
424         public static final int FAIL_REASON_FONT_LOAD_ERROR = -3;
425         /**
426          * Constant returned by {@link #onTypefaceRequestFailed(int)} signaling that the font
427          * provider did not return any results for the given query.
428          */
429         public static final int FAIL_REASON_FONT_NOT_FOUND = Columns.RESULT_CODE_FONT_NOT_FOUND;
430         /**
431          * Constant returned by {@link #onTypefaceRequestFailed(int)} signaling that the font
432          * provider found the queried font, but it is currently unavailable.
433          */
434         public static final int FAIL_REASON_FONT_UNAVAILABLE = Columns.RESULT_CODE_FONT_UNAVAILABLE;
435         /**
436          * Constant returned by {@link #onTypefaceRequestFailed(int)} signaling that the given
437          * query was not supported by the provider.
438          */
439         public static final int FAIL_REASON_MALFORMED_QUERY = Columns.RESULT_CODE_MALFORMED_QUERY;
440 
441         /** @hide */
442         @IntDef(prefix = { "FAIL_" }, value = {
443                 FAIL_REASON_PROVIDER_NOT_FOUND,
444                 FAIL_REASON_FONT_LOAD_ERROR,
445                 FAIL_REASON_FONT_NOT_FOUND,
446                 FAIL_REASON_FONT_UNAVAILABLE,
447                 FAIL_REASON_MALFORMED_QUERY
448         })
449         @Retention(RetentionPolicy.SOURCE)
450         @interface FontRequestFailReason {}
451 
FontRequestCallback()452         public FontRequestCallback() {}
453 
454         /**
455          * Called then a Typeface request done via {@link #requestFonts} is complete. Note that this
456          * method will not be called if {@link #onTypefaceRequestFailed(int)} is called instead.
457          * @param typeface  The Typeface object retrieved.
458          */
onTypefaceRetrieved(Typeface typeface)459         public void onTypefaceRetrieved(Typeface typeface) {}
460 
461         /**
462          * Called when a Typeface request done via {@link #requestFonts}} fails.
463          * @param reason One of {@link #FAIL_REASON_PROVIDER_NOT_FOUND},
464          *               {@link #FAIL_REASON_FONT_NOT_FOUND},
465          *               {@link #FAIL_REASON_FONT_LOAD_ERROR},
466          *               {@link #FAIL_REASON_FONT_UNAVAILABLE} or
467          *               {@link #FAIL_REASON_MALFORMED_QUERY} if returned by the system. May also be
468          *               a positive value greater than 0 defined by the font provider as an
469          *               additional error code. Refer to the provider's documentation for more
470          *               information on possible returned error codes.
471          */
onTypefaceRequestFailed(@ontRequestFailReason int reason)472         public void onTypefaceRequestFailed(@FontRequestFailReason int reason) {}
473     }
474 
475     /**
476      * Create a typeface object given a font request. The font will be asynchronously fetched,
477      * therefore the result is delivered to the given callback. See {@link FontRequest}.
478      * Only one of the methods in callback will be invoked, depending on whether the request
479      * succeeds or fails. These calls will happen on the caller thread.
480      *
481      * Note that the result Typeface may be cached internally and the same instance will be returned
482      * the next time you call this method with the same request. If you want to bypass this cache,
483      * use {@link #fetchFonts} and {@link #buildTypeface} instead.
484      *
485      * @param context A context to be used for fetching from font provider.
486      * @param request A {@link FontRequest} object that identifies the provider and query for the
487      *                request. May not be null.
488      * @param handler A handler to be processed the font fetching.
489      * @param cancellationSignal A signal to cancel the operation in progress, or null if none. If
490      *                           the operation is canceled, then {@link
491      *                           android.os.OperationCanceledException} will be thrown.
492      * @param callback A callback that will be triggered when results are obtained. May not be null.
493      */
requestFonts(@onNull Context context, @NonNull FontRequest request, @NonNull Handler handler, @Nullable CancellationSignal cancellationSignal, @NonNull FontRequestCallback callback)494     public static void requestFonts(@NonNull Context context, @NonNull FontRequest request,
495             @NonNull Handler handler, @Nullable CancellationSignal cancellationSignal,
496             @NonNull FontRequestCallback callback) {
497 
498         final Handler callerThreadHandler = new Handler();
499         final Typeface cachedTypeface = sTypefaceCache.get(request.getIdentifier());
500         if (cachedTypeface != null) {
501             callerThreadHandler.post(() -> callback.onTypefaceRetrieved(cachedTypeface));
502             return;
503         }
504 
505         handler.post(() -> {
506             FontFamilyResult result;
507             try {
508                 result = fetchFonts(context, cancellationSignal, request);
509             } catch (NameNotFoundException e) {
510                 callerThreadHandler.post(() -> callback.onTypefaceRequestFailed(
511                         FontRequestCallback.FAIL_REASON_PROVIDER_NOT_FOUND));
512                 return;
513             }
514 
515             // Same request might be dispatched during fetchFonts. Check the cache again.
516             final Typeface anotherCachedTypeface = sTypefaceCache.get(request.getIdentifier());
517             if (anotherCachedTypeface != null) {
518                 callerThreadHandler.post(() -> callback.onTypefaceRetrieved(anotherCachedTypeface));
519                 return;
520             }
521 
522             if (result.getStatusCode() != FontFamilyResult.STATUS_OK) {
523                 switch (result.getStatusCode()) {
524                     case FontFamilyResult.STATUS_WRONG_CERTIFICATES:
525                         callerThreadHandler.post(() -> callback.onTypefaceRequestFailed(
526                                 FontRequestCallback.FAIL_REASON_WRONG_CERTIFICATES));
527                         return;
528                     case FontFamilyResult.STATUS_UNEXPECTED_DATA_PROVIDED:
529                         callerThreadHandler.post(() -> callback.onTypefaceRequestFailed(
530                                 FontRequestCallback.FAIL_REASON_FONT_LOAD_ERROR));
531                         return;
532                     default:
533                         // fetchFont returns unexpected status type. Fallback to load error.
534                         callerThreadHandler.post(() -> callback.onTypefaceRequestFailed(
535                                 FontRequestCallback.FAIL_REASON_FONT_LOAD_ERROR));
536                         return;
537                 }
538             }
539 
540             final FontInfo[] fonts = result.getFonts();
541             if (fonts == null || fonts.length == 0) {
542                 callerThreadHandler.post(() -> callback.onTypefaceRequestFailed(
543                         FontRequestCallback.FAIL_REASON_FONT_NOT_FOUND));
544                 return;
545             }
546             for (final FontInfo font : fonts) {
547                 if (font.getResultCode() != Columns.RESULT_CODE_OK) {
548                     // We proceed if all font entry is ready to use. Otherwise report the first
549                     // error.
550                     final int resultCode = font.getResultCode();
551                     if (resultCode < 0) {
552                         // Negative values are reserved for internal errors. Fallback to load error.
553                         callerThreadHandler.post(() -> callback.onTypefaceRequestFailed(
554                                 FontRequestCallback.FAIL_REASON_FONT_LOAD_ERROR));
555                     } else {
556                         callerThreadHandler.post(() -> callback.onTypefaceRequestFailed(
557                                 resultCode));
558                     }
559                     return;
560                 }
561             }
562 
563             final Typeface typeface = buildTypeface(context, cancellationSignal, fonts);
564             if (typeface == null) {
565                 // Something went wrong during reading font files. This happens if the given font
566                 // file is an unsupported font type.
567                 callerThreadHandler.post(() -> callback.onTypefaceRequestFailed(
568                         FontRequestCallback.FAIL_REASON_FONT_LOAD_ERROR));
569                 return;
570             }
571 
572             sTypefaceCache.put(request.getIdentifier(), typeface);
573             callerThreadHandler.post(() -> callback.onTypefaceRetrieved(typeface));
574         });
575     }
576 
577     /**
578      * Fetch fonts given a font request.
579      *
580      * @param context A {@link Context} to be used for fetching fonts.
581      * @param cancellationSignal A signal to cancel the operation in progress, or null if none. If
582      *                           the operation is canceled, then {@link
583      *                           android.os.OperationCanceledException} will be thrown when the
584      *                           query is executed.
585      * @param request A {@link FontRequest} object that identifies the provider and query for the
586      *                request.
587      *
588      * @return {@link FontFamilyResult}
589      *
590      * @throws NameNotFoundException If requested package or authority was not found in system.
591      */
fetchFonts( @onNull Context context, @Nullable CancellationSignal cancellationSignal, @NonNull FontRequest request)592     public static @NonNull FontFamilyResult fetchFonts(
593             @NonNull Context context, @Nullable CancellationSignal cancellationSignal,
594             @NonNull FontRequest request) throws NameNotFoundException {
595         if (context.isRestricted()) {
596             // TODO: Should we allow if the peer process is system or myself?
597             return new FontFamilyResult(FontFamilyResult.STATUS_REJECTED, null);
598         }
599         ProviderInfo providerInfo = getProvider(context.getPackageManager(), request);
600         if (providerInfo == null) {
601             return new FontFamilyResult(FontFamilyResult.STATUS_WRONG_CERTIFICATES, null);
602 
603         }
604         try {
605             FontInfo[] fonts = getFontFromProvider(
606                     context, request, providerInfo.authority, cancellationSignal);
607             return new FontFamilyResult(FontFamilyResult.STATUS_OK, fonts);
608         } catch (IllegalArgumentException e) {
609             return new FontFamilyResult(FontFamilyResult.STATUS_UNEXPECTED_DATA_PROVIDED, null);
610         }
611     }
612 
613     /**
614      * Build a Typeface from an array of {@link FontInfo}
615      *
616      * Results that are marked as not ready will be skipped.
617      *
618      * @param context A {@link Context} that will be used to fetch the font contents.
619      * @param cancellationSignal A signal to cancel the operation in progress, or null if none. If
620      *                           the operation is canceled, then {@link
621      *                           android.os.OperationCanceledException} will be thrown.
622      * @param fonts An array of {@link FontInfo} to be used to create a Typeface.
623      * @return A Typeface object. Returns null if typeface creation fails.
624      */
buildTypeface(@onNull Context context, @Nullable CancellationSignal cancellationSignal, @NonNull FontInfo[] fonts)625     public static Typeface buildTypeface(@NonNull Context context,
626             @Nullable CancellationSignal cancellationSignal, @NonNull FontInfo[] fonts) {
627         if (context.isRestricted()) {
628             // TODO: Should we allow if the peer process is system or myself?
629             return null;
630         }
631         final Map<Uri, ByteBuffer> uriBuffer =
632                 prepareFontData(context, fonts, cancellationSignal);
633         if (uriBuffer.isEmpty()) {
634             return null;
635         }
636 
637         FontFamily.Builder familyBuilder = null;
638         for (FontInfo fontInfo : fonts) {
639             final ByteBuffer buffer = uriBuffer.get(fontInfo.getUri());
640             if (buffer == null) {
641                 continue;
642             }
643             try {
644                 final Font font = new Font.Builder(buffer)
645                         .setWeight(fontInfo.getWeight())
646                         .setSlant(fontInfo.isItalic()
647                                 ? FontStyle.FONT_SLANT_ITALIC : FontStyle.FONT_SLANT_UPRIGHT)
648                         .setTtcIndex(fontInfo.getTtcIndex())
649                         .setFontVariationSettings(fontInfo.getAxes())
650                         .build();
651                 if (familyBuilder == null) {
652                     familyBuilder = new FontFamily.Builder(font);
653                 } else {
654                     familyBuilder.addFont(font);
655                 }
656             } catch (IllegalArgumentException e) {
657                 // To be a compatible behavior with API28 or before, catch IllegalArgumentExcetpion
658                 // thrown by native code and returns null.
659                 return null;
660             } catch (IOException e) {
661                 continue;
662             }
663         }
664         if (familyBuilder == null) {
665             return null;
666         }
667 
668         final FontFamily family = familyBuilder.build();
669 
670         final FontStyle normal = new FontStyle(FontStyle.FONT_WEIGHT_NORMAL,
671                 FontStyle.FONT_SLANT_UPRIGHT);
672         Font bestFont = family.getFont(0);
673         int bestScore = normal.getMatchScore(bestFont.getStyle());
674         for (int i = 1; i < family.getSize(); ++i) {
675             final Font candidate = family.getFont(i);
676             final int score = normal.getMatchScore(candidate.getStyle());
677             if (score < bestScore) {
678                 bestFont = candidate;
679                 bestScore = score;
680             }
681         }
682         return new Typeface.CustomFallbackBuilder(family).setStyle(bestFont.getStyle()).build();
683     }
684 
685     /**
686      * A helper function to create a mapping from {@link Uri} to {@link ByteBuffer}.
687      *
688      * Skip if the file contents is not ready to be read.
689      *
690      * @param context A {@link Context} to be used for resolving content URI in
691      *                {@link FontInfo}.
692      * @param fonts An array of {@link FontInfo}.
693      * @return A map from {@link Uri} to {@link ByteBuffer}.
694      */
prepareFontData(Context context, FontInfo[] fonts, CancellationSignal cancellationSignal)695     private static Map<Uri, ByteBuffer> prepareFontData(Context context, FontInfo[] fonts,
696             CancellationSignal cancellationSignal) {
697         final HashMap<Uri, ByteBuffer> out = new HashMap<>();
698         final ContentResolver resolver = context.getContentResolver();
699 
700         for (FontInfo font : fonts) {
701             if (font.getResultCode() != Columns.RESULT_CODE_OK) {
702                 continue;
703             }
704 
705             final Uri uri = font.getUri();
706             if (out.containsKey(uri)) {
707                 continue;
708             }
709 
710             ByteBuffer buffer = null;
711             try (final ParcelFileDescriptor pfd =
712                     resolver.openFileDescriptor(uri, "r", cancellationSignal)) {
713                 if (pfd != null) {
714                     try (final FileInputStream fis =
715                             new FileInputStream(pfd.getFileDescriptor())) {
716                         final FileChannel fileChannel = fis.getChannel();
717                         final long size = fileChannel.size();
718                         buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, size);
719                     } catch (IOException e) {
720                         // ignore
721                     }
722                 }
723             } catch (IOException e) {
724                 // ignore
725             }
726 
727             // TODO: try other approach?, e.g. read all contents instead of mmap.
728 
729             out.put(uri, buffer);
730         }
731         return Collections.unmodifiableMap(out);
732     }
733 
734     /** @hide */
735     @VisibleForTesting
getProvider( PackageManager packageManager, FontRequest request)736     public static @Nullable ProviderInfo getProvider(
737             PackageManager packageManager, FontRequest request) throws NameNotFoundException {
738         String providerAuthority = request.getProviderAuthority();
739         ProviderInfo info = packageManager.resolveContentProvider(providerAuthority, 0);
740         if (info == null) {
741             throw new NameNotFoundException("No package found for authority: " + providerAuthority);
742         }
743 
744         if (!info.packageName.equals(request.getProviderPackage())) {
745             throw new NameNotFoundException("Found content provider " + providerAuthority
746                     + ", but package was not " + request.getProviderPackage());
747         }
748         // Trust system apps without signature checks
749         if (info.applicationInfo.isSystemApp()) {
750             return info;
751         }
752 
753         List<byte[]> signatures;
754         PackageInfo packageInfo = packageManager.getPackageInfo(info.packageName,
755                 PackageManager.GET_SIGNATURES);
756         signatures = convertToByteArrayList(packageInfo.signatures);
757         Collections.sort(signatures, sByteArrayComparator);
758 
759         List<List<byte[]>> requestCertificatesList = request.getCertificates();
760         for (int i = 0; i < requestCertificatesList.size(); ++i) {
761             // Make a copy so we can sort it without modifying the incoming data.
762             List<byte[]> requestSignatures = new ArrayList<>(requestCertificatesList.get(i));
763             Collections.sort(requestSignatures, sByteArrayComparator);
764             if (equalsByteArrayList(signatures, requestSignatures)) {
765                 return info;
766             }
767         }
768         return null;
769     }
770 
771     private static final Comparator<byte[]> sByteArrayComparator = (l, r) -> {
772         if (l.length != r.length) {
773             return l.length - r.length;
774         }
775         for (int i = 0; i < l.length; ++i) {
776             if (l[i] != r[i]) {
777                 return l[i] - r[i];
778             }
779         }
780         return 0;
781     };
782 
equalsByteArrayList( List<byte[]> signatures, List<byte[]> requestSignatures)783     private static boolean equalsByteArrayList(
784             List<byte[]> signatures, List<byte[]> requestSignatures) {
785         if (signatures.size() != requestSignatures.size()) {
786             return false;
787         }
788         for (int i = 0; i < signatures.size(); ++i) {
789             if (!Arrays.equals(signatures.get(i), requestSignatures.get(i))) {
790                 return false;
791             }
792         }
793         return true;
794     }
795 
convertToByteArrayList(Signature[] signatures)796     private static List<byte[]> convertToByteArrayList(Signature[] signatures) {
797         List<byte[]> shas = new ArrayList<>();
798         for (int i = 0; i < signatures.length; ++i) {
799             shas.add(signatures[i].toByteArray());
800         }
801         return shas;
802     }
803 
804     /** @hide */
805     @VisibleForTesting
getFontFromProvider( Context context, FontRequest request, String authority, CancellationSignal cancellationSignal)806     public static @NonNull FontInfo[] getFontFromProvider(
807             Context context, FontRequest request, String authority,
808             CancellationSignal cancellationSignal) {
809         ArrayList<FontInfo> result = new ArrayList<>();
810         final Uri uri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
811                 .authority(authority)
812                 .build();
813         final Uri fileBaseUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
814                 .authority(authority)
815                 .appendPath("file")
816                 .build();
817         try (Cursor cursor = context.getContentResolver().query(uri, new String[] { Columns._ID,
818                         Columns.FILE_ID, Columns.TTC_INDEX, Columns.VARIATION_SETTINGS,
819                         Columns.WEIGHT, Columns.ITALIC, Columns.RESULT_CODE },
820                 "query = ?", new String[] { request.getQuery() }, null, cancellationSignal);) {
821             // TODO: Should we restrict the amount of fonts that can be returned?
822             // TODO: Write documentation explaining that all results should be from the same family.
823             if (cursor != null && cursor.getCount() > 0) {
824                 final int resultCodeColumnIndex = cursor.getColumnIndex(Columns.RESULT_CODE);
825                 result = new ArrayList<>();
826                 final int idColumnIndex = cursor.getColumnIndexOrThrow(Columns._ID);
827                 final int fileIdColumnIndex = cursor.getColumnIndex(Columns.FILE_ID);
828                 final int ttcIndexColumnIndex = cursor.getColumnIndex(Columns.TTC_INDEX);
829                 final int vsColumnIndex = cursor.getColumnIndex(Columns.VARIATION_SETTINGS);
830                 final int weightColumnIndex = cursor.getColumnIndex(Columns.WEIGHT);
831                 final int italicColumnIndex = cursor.getColumnIndex(Columns.ITALIC);
832                 while (cursor.moveToNext()) {
833                     int resultCode = resultCodeColumnIndex != -1
834                             ? cursor.getInt(resultCodeColumnIndex) : Columns.RESULT_CODE_OK;
835                     final int ttcIndex = ttcIndexColumnIndex != -1
836                             ? cursor.getInt(ttcIndexColumnIndex) : 0;
837                     final String variationSettings = vsColumnIndex != -1
838                             ? cursor.getString(vsColumnIndex) : null;
839 
840                     Uri fileUri;
841                     if (fileIdColumnIndex == -1) {
842                         long id = cursor.getLong(idColumnIndex);
843                         fileUri = ContentUris.withAppendedId(uri, id);
844                     } else {
845                         long id = cursor.getLong(fileIdColumnIndex);
846                         fileUri = ContentUris.withAppendedId(fileBaseUri, id);
847                     }
848                     int weight;
849                     boolean italic;
850                     if (weightColumnIndex != -1 && italicColumnIndex != -1) {
851                         weight = cursor.getInt(weightColumnIndex);
852                         italic = cursor.getInt(italicColumnIndex) == 1;
853                     } else {
854                         weight = Typeface.Builder.NORMAL_WEIGHT;
855                         italic = false;
856                     }
857                     FontVariationAxis[] axes =
858                             FontVariationAxis.fromFontVariationSettings(variationSettings);
859                     result.add(new FontInfo(fileUri, ttcIndex, axes, weight, italic, resultCode));
860                 }
861             }
862         }
863         return result.toArray(new FontInfo[0]);
864     }
865 }
866