aboutsummaryrefslogtreecommitdiff
path: root/shadows/framework/src/main/java/org/robolectric/shadows/ShadowNativeFont.java
blob: c643f6782a8fa86b899a3ed3cb0f83c95eef833f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package org.robolectric.shadows;

import static android.os.Build.VERSION_CODES.P;
import static android.os.Build.VERSION_CODES.Q;
import static android.os.Build.VERSION_CODES.R;
import static android.os.Build.VERSION_CODES.S;
import static android.os.Build.VERSION_CODES.TIRAMISU;
import static org.robolectric.util.reflector.Reflector.reflector;

import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.fonts.Font;
import android.util.TypedValue;
import com.google.common.base.Ascii;
import com.google.common.base.Preconditions;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.robolectric.annotation.InDevelopment;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import org.robolectric.nativeruntime.DefaultNativeRuntimeLoader;
import org.robolectric.nativeruntime.FontBuilderNatives;
import org.robolectric.nativeruntime.FontNatives;
import org.robolectric.shadows.ShadowNativeFont.Picker;
import org.robolectric.util.reflector.Accessor;
import org.robolectric.util.reflector.ForType;
import org.robolectric.versioning.AndroidVersions.U;
import org.robolectric.versioning.AndroidVersions.V;

/** Shadow for {@link Font} that is backed by native code */
@Implements(
    value = Font.class,
    minSdk = P,
    shadowPicker = Picker.class,
    isInAndroidSdk = false,
    callNativeMethodsByDefault = true)
public class ShadowNativeFont {

  /**
   * {@link android.graphics.fonts.Font} invokes its own native methods in its static initializer.
   * This must be deferred starting in Android V.
   */
  @Implementation(minSdk = V.SDK_INT)
  @InDevelopment
  protected static void __staticInitializer__() {}

  @Implementation(minSdk = S, maxSdk = U.SDK_INT)
  protected static long nGetMinikinFontPtr(long font) {
    return FontNatives.nGetMinikinFontPtr(font);
  }

  @Implementation(minSdk = S, maxSdk = U.SDK_INT)
  protected static long nCloneFont(long font) {
    return FontNatives.nCloneFont(font);
  }

  @Implementation(minSdk = S, maxSdk = U.SDK_INT)
  protected static ByteBuffer nNewByteBuffer(long font) {
    return FontNatives.nNewByteBuffer(font);
  }

  @Implementation(minSdk = S, maxSdk = U.SDK_INT)
  protected static long nGetBufferAddress(long font) {
    return FontNatives.nGetBufferAddress(font);
  }

  @Implementation(minSdk = S, maxSdk = U.SDK_INT)
  protected static int nGetSourceId(long font) {
    return FontNatives.nGetSourceId(font);
  }

  @Implementation(minSdk = S, maxSdk = U.SDK_INT)
  protected static long nGetReleaseNativeFont() {
    DefaultNativeRuntimeLoader.injectAndLoad();
    return FontNatives.nGetReleaseNativeFont();
  }

  @Implementation(minSdk = S, maxSdk = U.SDK_INT)
  protected static float nGetGlyphBounds(long font, int glyphId, long paint, RectF rect) {
    return FontNatives.nGetGlyphBounds(font, glyphId, paint, rect);
  }

  @Implementation(minSdk = S, maxSdk = U.SDK_INT)
  protected static float nGetFontMetrics(long font, long paint, Paint.FontMetrics metrics) {
    return FontNatives.nGetFontMetrics(font, paint, metrics);
  }

  @Implementation(minSdk = S, maxSdk = U.SDK_INT)
  protected static String nGetFontPath(long fontPtr) {
    return FontNatives.nGetFontPath(fontPtr);
  }

  @Implementation(minSdk = S, maxSdk = U.SDK_INT)
  protected static String nGetLocaleList(long familyPtr) {
    return FontNatives.nGetLocaleList(familyPtr);
  }

  @Implementation(minSdk = S, maxSdk = U.SDK_INT)
  protected static int nGetPackedStyle(long fontPtr) {
    return FontNatives.nGetPackedStyle(fontPtr);
  }

  @Implementation(minSdk = S, maxSdk = U.SDK_INT)
  protected static int nGetIndex(long fontPtr) {
    return FontNatives.nGetIndex(fontPtr);
  }

  @Implementation(minSdk = S, maxSdk = U.SDK_INT)
  protected static int nGetAxisCount(long fontPtr) {
    return FontNatives.nGetAxisCount(fontPtr);
  }

  @Implementation(minSdk = S, maxSdk = U.SDK_INT)
  protected static long nGetAxisInfo(long fontPtr, int i) {
    return FontNatives.nGetAxisInfo(fontPtr, i);
  }

  @Implementation(minSdk = S, maxSdk = U.SDK_INT)
  protected static long[] nGetAvailableFontSet() {
    return FontNatives.nGetAvailableFontSet();
  }

  /** Shadow for {@link Font.Builder} that is backed by native code */
  @Implements(
      value = Font.Builder.class,
      minSdk = P,
      shadowPicker = ShadowNativeFontBuilder.Picker.class,
      isInAndroidSdk = false,
      callNativeMethodsByDefault = true)
  public static class ShadowNativeFontBuilder {

    @RealObject Font.Builder realFontBuilder;

    @Implementation(minSdk = Q, maxSdk = Q)
    protected void __constructor__(AssetManager am, String path, boolean isAsset, int cookie) {
      // In Android Q, this method uses native methods that do not exist in later versions, so
      // they need to be re-implemented using logic from S.
      reflector(FontBuilderReflector.class, realFontBuilder).setWeight(-1);
      reflector(FontBuilderReflector.class, realFontBuilder).setItalic(-1);
      reflector(FontBuilderReflector.class, realFontBuilder).setLocaleList("");
      try {
        ByteBuffer buf = createBuffer(am, path, isAsset, cookie);
        reflector(FontBuilderReflector.class, realFontBuilder).setBuffer(buf);
      } catch (IOException e) {
        reflector(FontBuilderReflector.class, realFontBuilder).setException(e);
      }
    }

    @Implementation(minSdk = Q, maxSdk = Q)
    protected void __constructor__(Resources res, int resId) {
      // In Android Q, this method uses native methods that do not exist in later versions, so
      // they need to be re-implemented using logic from S.
      reflector(FontBuilderReflector.class, realFontBuilder).setWeight(-1);
      reflector(FontBuilderReflector.class, realFontBuilder).setItalic(-1);
      reflector(FontBuilderReflector.class, realFontBuilder).setLocaleList("");
      final TypedValue value = new TypedValue();
      res.getValue(resId, value, true);
      if (value.string == null) {
        reflector(FontBuilderReflector.class, realFontBuilder)
            .setException(new FileNotFoundException(resId + " not found"));
        return;
      }
      final String str = value.string.toString();
      if (Ascii.toLowerCase(str).endsWith(".xml")) {
        reflector(FontBuilderReflector.class, realFontBuilder)
            .setException(new FileNotFoundException(resId + " must be font file."));
        return;
      }
      try {
        ByteBuffer buf = createBuffer(res.getAssets(), str, false, value.assetCookie);
        reflector(FontBuilderReflector.class, realFontBuilder).setBuffer(buf);
      } catch (IOException e) {
        reflector(FontBuilderReflector.class, realFontBuilder).setException(e);
      }
    }

    @Implementation(minSdk = Q, maxSdk = U.SDK_INT)
    protected static long nInitBuilder() {
      DefaultNativeRuntimeLoader.injectAndLoad();
      return FontBuilderNatives.nInitBuilder();
    }

    @Implementation(minSdk = Q, maxSdk = U.SDK_INT)
    protected static void nAddAxis(long builderPtr, int tag, float value) {
      FontBuilderNatives.nAddAxis(builderPtr, tag, value);
    }

    @Implementation(minSdk = S, maxSdk = U.SDK_INT)
    protected static long nBuild(
        long builderPtr,
        ByteBuffer buffer,
        String filePath,
        String localeList,
        int weight,
        boolean italic,
        int ttcIndex) {
      return FontBuilderNatives.nBuild(
          builderPtr, buffer, filePath, localeList, weight, italic, ttcIndex);
    }

    @Implementation(minSdk = Q, maxSdk = R)
    protected static long nBuild(
        long builderPtr,
        ByteBuffer buffer,
        String filePath,
        int weight,
        boolean italic,
        int ttcIndex) {
      return nBuild(builderPtr, buffer, filePath, "", weight, italic, ttcIndex);
    }

    @Implementation(minSdk = Q, maxSdk = TIRAMISU)
    protected static long nGetReleaseNativeFont() {
      // Starting in S, nGetReleaseNativeFont was moved from Font.Builder to Font, and despite
      // existing in S, Font.Builder.nGetReleaseNativeFont does not get registered with a native
      // method.
      DefaultNativeRuntimeLoader.injectAndLoad();
      return FontNatives.nGetReleaseNativeFont();
    }

    @Implementation(minSdk = S, maxSdk = U.SDK_INT)
    protected static long nClone(
        long fontPtr, long builderPtr, int weight, boolean italic, int ttcIndex) {
      return FontBuilderNatives.nClone(fontPtr, builderPtr, weight, italic, ttcIndex);
    }

    /**
     * The Android implementation attempts to call {@link java.nio.ByteBuffer#array()} on a direct
     * byte buffer. This is supported in Libcore but not the JVM. Use an implementation that copies
     * the data from the asset into a direct buffer.
     */
    @Implementation(minSdk = R)
    protected static ByteBuffer createBuffer(
        AssetManager am, String path, boolean isAsset, int cookie) throws IOException {
      return assetToBuffer(am, path, isAsset, cookie);
    }

    /** RNG does not support native assets */
    @Implementation(minSdk = Q, maxSdk = Q)
    protected static long nGetReleaseNativeAssetFunc() {
      return 0;
    }

    @ForType(Font.Builder.class)
    interface FontBuilderReflector {
      @Accessor("mBuffer")
      void setBuffer(ByteBuffer buffer);

      @Accessor("mException")
      void setException(IOException e);

      @Accessor("mWeight")
      void setWeight(int weight);

      @Accessor("mItalic")
      void setItalic(int italic);

      @Accessor("mLocaleList")
      void setLocaleList(String localeList);
    }

    /** Shadow picker for {@link Font.Builder}. */
    public static final class Picker extends GraphicsShadowPicker<Object> {
      public Picker() {
        super(ShadowFontBuilder.class, ShadowNativeFontBuilder.class);
      }
    }
  }

  static ByteBuffer assetToBuffer(AssetManager am, String path, boolean isAsset, int cookie)
      throws IOException {
    Preconditions.checkNotNull(am, "assetManager can not be null");
    Preconditions.checkNotNull(path, "path can not be null");
    try (InputStream assetStream =
        isAsset
            ? am.open(path, AssetManager.ACCESS_BUFFER)
            : am.openNonAsset(cookie, path, AssetManager.ACCESS_BUFFER)) {
      int capacity = assetStream.available();
      ByteBuffer buffer = ByteBuffer.allocateDirect(capacity);
      buffer.order(ByteOrder.nativeOrder());
      byte[] buf = new byte[8 * 1024]; // 8k
      int bytesRead;
      while ((bytesRead = assetStream.read(buf)) != -1) {
        buffer.put(buf, 0, bytesRead);
      }
      if (assetStream.read() != -1) {
        throw new IOException("Unable to access full contents of " + path);
      }
      return buffer;
    }
  }

  /** Shadow picker for {@link Font}. */
  public static final class Picker extends GraphicsShadowPicker<Object> {
    public Picker() {
      super(ShadowFont.class, ShadowNativeFont.class);
    }
  }
}