• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2013 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;
18 
19 import com.android.ide.common.rendering.api.LayoutLog;
20 import com.android.layoutlib.bridge.Bridge;
21 
22 import android.annotation.NonNull;
23 import android.annotation.Nullable;
24 import android.graphics.Paint_Delegate.FontInfo;
25 import android.icu.lang.UScriptRun;
26 import android.icu.text.Bidi;
27 import android.icu.text.BidiRun;
28 
29 import java.awt.Font;
30 import java.awt.Graphics2D;
31 import java.awt.Toolkit;
32 import java.awt.font.FontRenderContext;
33 import java.awt.font.GlyphVector;
34 import java.awt.geom.AffineTransform;
35 import java.awt.geom.Rectangle2D;
36 import java.util.Arrays;
37 import java.util.LinkedList;
38 import java.util.List;
39 
40 /**
41  * Render the text by breaking it into various scripts and using the right font for each script.
42  * Can be used to measure the text without actually drawing it.
43  */
44 @SuppressWarnings("deprecation")
45 public class BidiRenderer {
46     private static final String JETBRAINS_VENDOR_ID = "JetBrains s.r.o";
47     private static final String JAVA_VENDOR = System.getProperty("java.vendor");
48     /** When scaleX is bigger than this, we need to apply the workaround for http://b.android.com/211659 */
49     private static final double SCALEX_WORKAROUND_LIMIT = 9;
50 
51     private static class ScriptRun {
52         private final int start;
53         private final int limit;
54         private final Font font;
55 
ScriptRun(int start, int limit, @NonNull Font font)56         private ScriptRun(int start, int limit, @NonNull Font font) {
57             this.start = start;
58             this.limit = limit;
59             this.font = font;
60         }
61     }
62 
63     private final Graphics2D mGraphics;
64     private final Paint_Delegate mPaint;
65     private char[] mText;
66     // Bounds of the text drawn so far.
67     private RectF mBounds;
68     private float mBaseline;
69     private final Bidi mBidi = new Bidi();
70 
71 
72     /**
73      * @param graphics May be null.
74      * @param paint The Paint to use to get the fonts. Should not be null.
75      * @param text Unidirectional text. Should not be null.
76      */
BidiRenderer(Graphics2D graphics, Paint_Delegate paint, char[] text)77     public BidiRenderer(Graphics2D graphics, Paint_Delegate paint, char[] text) {
78         assert (paint != null);
79         mGraphics = graphics;
80         mPaint = paint;
81         mText = text;
82         mBounds = new RectF();
83     }
84 
85     /**
86      *
87      * @param x The x-coordinate of the left edge of where the text should be drawn on the given
88      *            graphics.
89      * @param y The y-coordinate at which to draw the text on the given mGraphics.
90      *
91      */
setRenderLocation(float x, float y)92     public BidiRenderer setRenderLocation(float x, float y) {
93         mBounds.set(x, y, x, y);
94         mBaseline = y;
95         return this;
96     }
97 
98     /**
99      * Perform Bidi Analysis on the text and then render it.
100      * <p/>
101      * To skip the analysis and render unidirectional text, see {@link
102      * #renderText(int, int, boolean, float[], int, boolean)}
103      */
renderText(int start, int limit, int bidiFlags, float[] advances, int advancesIndex, boolean draw)104     public RectF renderText(int start, int limit, int bidiFlags, float[] advances,
105             int advancesIndex, boolean draw) {
106         mBidi.setPara(Arrays.copyOfRange(mText, start, limit), (byte)getIcuFlags(bidiFlags), null);
107         mText = mBidi.getText();
108         for (int i = 0; i < mBidi.countRuns(); i++) {
109             BidiRun visualRun = mBidi.getVisualRun(i);
110             boolean isRtl = visualRun.getDirection() == Bidi.RTL;
111             renderText(visualRun.getStart(), visualRun.getLimit(), isRtl, advances,
112                     advancesIndex, draw);
113         }
114         return mBounds;
115     }
116 
117     /**
118      * Render unidirectional text.
119      * <p/>
120      * This method can also be used to measure the width of the text without actually drawing it.
121      * <p/>
122      * @param start index of the first character
123      * @param limit index of the first character that should not be rendered.
124      * @param isRtl is the text right-to-left
125      * @param advances If not null, then advances for each character to be rendered are returned
126      *            here.
127      * @param advancesIndex index into advances from where the advances need to be filled.
128      * @param draw If true and {@code graphics} is not null, draw the rendered text on the graphics
129      *            at the given co-ordinates
130      * @return A rectangle specifying the bounds of the text drawn.
131      */
renderText(int start, int limit, boolean isRtl, float[] advances, int advancesIndex, boolean draw)132     public RectF renderText(int start, int limit, boolean isRtl, float[] advances,
133             int advancesIndex, boolean draw) {
134         // We break the text into scripts and then select font based on it and then render each of
135         // the script runs.
136         for (ScriptRun run : getScriptRuns(mText, start, limit, mPaint.getFonts())) {
137             int flag = Font.LAYOUT_NO_LIMIT_CONTEXT | Font.LAYOUT_NO_START_CONTEXT;
138             flag |= isRtl ? Font.LAYOUT_RIGHT_TO_LEFT : Font.LAYOUT_LEFT_TO_RIGHT;
139             renderScript(run.start, run.limit, run.font, flag, advances, advancesIndex, draw);
140             advancesIndex += run.limit - run.start;
141         }
142         return mBounds;
143     }
144 
145     /**
146      * Render a script run to the right of the bounds passed. Use the preferred font to render as
147      * much as possible. This also implements a fallback mechanism to render characters that cannot
148      * be drawn using the preferred font.
149      */
renderScript(int start, int limit, Font preferredFont, int flag, float[] advances, int advancesIndex, boolean draw)150     private void renderScript(int start, int limit, Font preferredFont, int flag,
151             float[] advances, int advancesIndex, boolean draw) {
152         if (mPaint.getFonts().size() == 0 || preferredFont == null) {
153             return;
154         }
155 
156         while (start < limit) {
157             int canDisplayUpTo = preferredFont.canDisplayUpTo(mText, start, limit);
158             if (canDisplayUpTo == -1) {
159                 // We can draw all characters in the text.
160                 render(start, limit, preferredFont, flag, advances, advancesIndex, draw);
161                 return;
162             }
163             if (canDisplayUpTo > start) {
164                 // We can draw something.
165                 render(start, canDisplayUpTo, preferredFont, flag, advances, advancesIndex, draw);
166                 advancesIndex += canDisplayUpTo - start;
167                 start = canDisplayUpTo;
168             } else {
169                 // We can display everything with the preferred font. Search for the font that
170                 // allows us to display the maximum number of chars
171                 List<FontInfo> fontInfos = mPaint.getFonts();
172                 Font bestFont = null;
173                 int highestUpTo = canDisplayUpTo;
174                 //noinspection ForLoopReplaceableByForEach
175                 for (int i = 0; i < fontInfos.size(); i++) {
176                     Font font = fontInfos.get(i).mFont;
177 
178                     if (preferredFont == font) {
179                         // We know this font won't work since we've already tested it at the
180                         // beginning of the loop
181                         continue;
182                     }
183 
184                     if (font == null) {
185                         logFontWarning();
186                         continue;
187                     }
188 
189                     canDisplayUpTo = font.canDisplayUpTo(mText, start, limit);
190                     if (canDisplayUpTo == -1) {
191                         // This font can dis
192                         highestUpTo = limit;
193                         bestFont = font;
194                         break;
195                     } else if (canDisplayUpTo > highestUpTo) {
196                         highestUpTo = canDisplayUpTo;
197                         bestFont = font;
198                         // Keep searching in case there is a font that allows to display even
199                         // more text
200                     }
201                 }
202 
203                 if (bestFont != null) {
204                     render(start, highestUpTo, bestFont, flag, advances, advancesIndex, draw);
205                     advancesIndex += highestUpTo - start;
206                     start = highestUpTo;
207                 } else {
208                     int charCount = Character.isHighSurrogate(mText[start]) ? 2 : 1;
209 
210                     // No font can display this char. Use the preferred font and skip this char.
211                     // The char will most probably appear as a box or a blank space. We could,
212                     // probably, use some heuristics and break the character into the base
213                     // character and diacritics and then draw it, but it's probably not worth the
214                     // effort.
215                     render(start, start + charCount, preferredFont, flag, advances, advancesIndex,
216                             draw);
217                     start += charCount;
218                     advancesIndex += charCount;
219                 }
220             }
221         }
222     }
223 
logFontWarning()224     private static void logFontWarning() {
225         Bridge.getLog().fidelityWarning(LayoutLog.TAG_BROKEN,
226                 "Some fonts could not be loaded. The rendering may not be perfect.", null, null);
227     }
228 
229     /**
230      * Renders the text to the right of the bounds with the given font.
231      * @param font The font to render the text with.
232      */
render(int start, int limit, Font font, int flag, float[] advances, int advancesIndex, boolean draw)233     private void render(int start, int limit, Font font, int flag, float[] advances,
234             int advancesIndex, boolean draw) {
235         FontRenderContext frc = mGraphics != null ? mGraphics.getFontRenderContext() :
236                     Toolkit.getDefaultToolkit().getFontMetrics(font).getFontRenderContext();
237 
238         boolean frcIsAntialiased = frc.isAntiAliased();
239         boolean useAntialiasing = mPaint.isAntiAliased();
240 
241         if (frcIsAntialiased) {
242             if (!useAntialiasing) {
243                 // The context has antialiasing enabled but the paint does not. We need to
244                 // disable it
245                 frc = new FontRenderContext(font.getTransform(), false,
246                         frc.usesFractionalMetrics());
247             } else {
248                 // In this case both the paint and the context antialising match but we need
249                 // to check for a bug in the JDK
250                 // Workaround for http://b.android.com/211659 (disable antialiasing)
251                 if (font.isTransformed()) {
252                     AffineTransform transform = font.getTransform();
253                     if (transform.getScaleX() >= SCALEX_WORKAROUND_LIMIT &&
254                             JETBRAINS_VENDOR_ID.equals(JAVA_VENDOR)) {
255                         frc = new FontRenderContext(transform, false, frc.usesFractionalMetrics());
256                     }
257                 }
258             }
259         } else if (useAntialiasing) {
260             // The context does not have antialiasing enabled but the paint does. We need to
261             // enable it unless we need to avoid the JDK bug
262 
263             AffineTransform transform = font.getTransform();
264             // Workaround for http://b.android.com/211659 (disable antialiasing)
265             if (transform.getScaleX() < SCALEX_WORKAROUND_LIMIT ||
266                     !JETBRAINS_VENDOR_ID.equals(JAVA_VENDOR)) {
267                 frc = new FontRenderContext(font.getTransform(), true, frc.usesFractionalMetrics());
268             }
269         }
270 
271         GlyphVector gv = font.layoutGlyphVector(frc, mText, start, limit, flag);
272         int ng = gv.getNumGlyphs();
273         int[] ci = gv.getGlyphCharIndices(0, ng, null);
274         if (advances != null) {
275             for (int i = 0; i < ng; i++) {
276                 if (mText[ci[i]] == '\uFEFF') {
277                     // Workaround for bug in JetBrains JDK
278                     // where the character \uFEFF is associated a glyph with non-zero width
279                     continue;
280                 }
281                 int adv_idx = advancesIndex + ci[i];
282                 advances[adv_idx] += gv.getGlyphMetrics(i).getAdvanceX();
283             }
284         }
285         if (draw && mGraphics != null) {
286             mGraphics.drawGlyphVector(gv, mBounds.right, mBaseline);
287         }
288 
289         // Update the bounds.
290         Rectangle2D awtBounds = gv.getLogicalBounds();
291         // If the width of the bounds is zero, no text had been drawn earlier. Hence, use the
292         // coordinates from the bounds as an offset.
293         if (Math.abs(mBounds.right - mBounds.left) == 0) {
294             mBounds = awtRectToAndroidRect(awtBounds, mBounds.right, mBaseline, mBounds);
295         } else {
296             mBounds.union(awtRectToAndroidRect(awtBounds, mBounds.right, mBaseline, null));
297         }
298     }
299 
300     // --- Static helper methods ---
301 
awtRectToAndroidRect(Rectangle2D awtRec, float offsetX, float offsetY, @Nullable RectF destination)302     private static RectF awtRectToAndroidRect(Rectangle2D awtRec, float offsetX, float offsetY,
303             @Nullable RectF destination) {
304         float left = (float) awtRec.getX();
305         float top = (float) awtRec.getY();
306         float right = (float) (left + awtRec.getWidth());
307         float bottom = (float) (top + awtRec.getHeight());
308         if (destination != null) {
309             destination.set(left, top, right, bottom);
310         } else {
311             destination = new RectF(left, top, right, bottom);
312         }
313         destination.offset(offsetX, offsetY);
314         return destination;
315     }
316 
getScriptRuns(char[] text, int start, int limit, List<FontInfo> fonts)317     private static List<ScriptRun> getScriptRuns(char[] text, int start, int limit, List<FontInfo> fonts) {
318         LinkedList<ScriptRun> scriptRuns = new LinkedList<>();
319 
320         int count = limit - start;
321         UScriptRun uScriptRun = new UScriptRun(text, start, count);
322         while (uScriptRun.next()) {
323             int scriptStart = uScriptRun.getScriptStart();
324             int scriptLimit = uScriptRun.getScriptLimit();
325             ScriptRun run = new ScriptRun(
326                     scriptStart, scriptLimit,
327                     getScriptFont(text, scriptStart, scriptLimit, fonts));
328             scriptRuns.add(run);
329         }
330         return scriptRuns;
331     }
332 
333     // TODO: Replace this method with one which returns the font based on the scriptCode.
334     @NonNull
getScriptFont(char[] text, int start, int limit, List<FontInfo> fonts)335     private static Font getScriptFont(char[] text, int start, int limit, List<FontInfo> fonts) {
336         if (fonts.isEmpty()) {
337             logFontWarning();
338             // Fallback font in case no font can be loaded
339             return Font.getFont(Font.SERIF);
340         }
341 
342         // From all the fonts, select the one that can display the highest number of characters
343         Font bestFont = fonts.get(0).mFont;
344         int bestFontCount = 0;
345         for (FontInfo fontInfo : fonts) {
346             int count = fontInfo.mFont.canDisplayUpTo(text, start, limit);
347             if (count == -1) {
348                 // This font can display everything, return this one
349                 return fontInfo.mFont;
350             }
351 
352             if (count > bestFontCount) {
353                 bestFontCount = count;
354                 bestFont = fontInfo.mFont;
355             }
356         }
357 
358         return bestFont;
359     }
360 
getIcuFlags(int bidiFlag)361     private static int getIcuFlags(int bidiFlag) {
362         switch (bidiFlag) {
363             case Paint.BIDI_LTR:
364             case Paint.BIDI_FORCE_LTR:
365                 return Bidi.DIRECTION_LEFT_TO_RIGHT;
366             case Paint.BIDI_RTL:
367             case Paint.BIDI_FORCE_RTL:
368                 return Bidi.DIRECTION_RIGHT_TO_LEFT;
369             case Paint.BIDI_DEFAULT_LTR:
370                 return Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT;
371             case Paint.BIDI_DEFAULT_RTL:
372                 return Bidi.DIRECTION_DEFAULT_RIGHT_TO_LEFT;
373             default:
374                 assert false;
375                 return Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT;
376         }
377     }
378 }
379