1 /* 2 * Copyright (C) 2018 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 17 package android.graphics.fonts; 18 19 import com.android.layoutlib.bridge.impl.DelegateManager; 20 import com.android.tools.layoutlib.annotations.LayoutlibDelegate; 21 22 import android.annotation.NonNull; 23 import android.content.res.AssetManager; 24 25 import java.io.IOException; 26 import java.io.InputStream; 27 import java.nio.ByteBuffer; 28 import java.nio.ByteOrder; 29 import java.nio.channels.Channels; 30 import java.nio.channels.ReadableByteChannel; 31 32 /** 33 * Delegate implementing the native methods of android.graphics.fonts.Font$Builder 34 * <p> 35 * Through the layoutlib_create tool, the original native methods of Font$Builder have been 36 * replaced by calls to methods of the same name in this delegate class. 37 * <p> 38 * This class behaves like the original native implementation, but in Java, keeping previously 39 * native data into its own objects and mapping them to int that are sent back and forth between it 40 * and the original Font$Builder class. 41 * 42 * @see DelegateManager 43 */ 44 public class Font_Builder_Delegate { 45 46 @LayoutlibDelegate createBuffer(@onNull AssetManager am, @NonNull String path, boolean isAsset, int cookie)47 /*package*/ static ByteBuffer createBuffer(@NonNull AssetManager am, @NonNull String path, 48 boolean isAsset, int cookie) throws IOException { 49 50 if (path.isBlank()) { 51 return null; 52 } 53 54 try (InputStream assetStream = isAsset ? am.open(path, AssetManager.ACCESS_BUFFER) 55 : am.openNonAsset(cookie, path, AssetManager.ACCESS_BUFFER)) { 56 57 int capacity = assetStream.available(); 58 ByteBuffer buffer = ByteBuffer.allocateDirect(capacity); 59 buffer.order(ByteOrder.nativeOrder()); 60 ReadableByteChannel channel = Channels.newChannel(assetStream); 61 channel.read(buffer); 62 63 if (assetStream.read() != -1) { 64 throw new IOException("Unable to access full contents of " + path); 65 } 66 67 return buffer; 68 } 69 } 70 } 71