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 null); 228 } 229 230 /** 231 * Renders the text to the right of the bounds with the given font. 232 * @param font The font to render the text with. 233 */ render(int start, int limit, Font font, int flag, float[] advances, int advancesIndex, boolean draw)234 private void render(int start, int limit, Font font, int flag, float[] advances, 235 int advancesIndex, boolean draw) { 236 FontRenderContext frc = mGraphics != null ? mGraphics.getFontRenderContext() : 237 Toolkit.getDefaultToolkit().getFontMetrics(font).getFontRenderContext(); 238 239 boolean frcIsAntialiased = frc.isAntiAliased(); 240 boolean useAntialiasing = mPaint.isAntiAliased(); 241 242 if (frcIsAntialiased) { 243 if (!useAntialiasing) { 244 // The context has antialiasing enabled but the paint does not. We need to 245 // disable it 246 frc = new FontRenderContext(font.getTransform(), false, 247 frc.usesFractionalMetrics()); 248 } else { 249 // In this case both the paint and the context antialising match but we need 250 // to check for a bug in the JDK 251 // Workaround for http://b.android.com/211659 (disable antialiasing) 252 if (font.isTransformed()) { 253 AffineTransform transform = font.getTransform(); 254 if (transform.getScaleX() >= SCALEX_WORKAROUND_LIMIT && 255 JETBRAINS_VENDOR_ID.equals(JAVA_VENDOR)) { 256 frc = new FontRenderContext(transform, false, frc.usesFractionalMetrics()); 257 } 258 } 259 } 260 } else if (useAntialiasing) { 261 // The context does not have antialiasing enabled but the paint does. We need to 262 // enable it unless we need to avoid the JDK bug 263 264 AffineTransform transform = font.getTransform(); 265 // Workaround for http://b.android.com/211659 (disable antialiasing) 266 if (transform.getScaleX() < SCALEX_WORKAROUND_LIMIT || 267 !JETBRAINS_VENDOR_ID.equals(JAVA_VENDOR)) { 268 frc = new FontRenderContext(font.getTransform(), true, frc.usesFractionalMetrics()); 269 } 270 } 271 272 GlyphVector gv = font.layoutGlyphVector(frc, mText, start, limit, flag); 273 int ng = gv.getNumGlyphs(); 274 int[] ci = gv.getGlyphCharIndices(0, ng, null); 275 if (advances != null) { 276 for (int i = 0; i < ng; i++) { 277 if (mText[ci[i]] == '\uFEFF') { 278 // Workaround for bug in JetBrains JDK 279 // where the character \uFEFF is associated a glyph with non-zero width 280 continue; 281 } 282 int adv_idx = advancesIndex + ci[i]; 283 advances[adv_idx] += gv.getGlyphMetrics(i).getAdvanceX(); 284 } 285 } 286 if (draw && mGraphics != null) { 287 mGraphics.drawGlyphVector(gv, mBounds.right, mBaseline); 288 } 289 290 // Update the bounds. 291 Rectangle2D awtBounds = gv.getLogicalBounds(); 292 // If the width of the bounds is zero, no text had been drawn earlier. Hence, use the 293 // coordinates from the bounds as an offset. 294 if (Math.abs(mBounds.right - mBounds.left) == 0) { 295 mBounds = awtRectToAndroidRect(awtBounds, mBounds.right, mBaseline, mBounds); 296 } else { 297 mBounds.union(awtRectToAndroidRect(awtBounds, mBounds.right, mBaseline, null)); 298 } 299 } 300 301 // --- Static helper methods --- 302 awtRectToAndroidRect(Rectangle2D awtRec, float offsetX, float offsetY, @Nullable RectF destination)303 private static RectF awtRectToAndroidRect(Rectangle2D awtRec, float offsetX, float offsetY, 304 @Nullable RectF destination) { 305 float left = (float) awtRec.getX(); 306 float top = (float) awtRec.getY(); 307 float right = (float) (left + awtRec.getWidth()); 308 float bottom = (float) (top + awtRec.getHeight()); 309 if (destination != null) { 310 destination.set(left, top, right, bottom); 311 } else { 312 destination = new RectF(left, top, right, bottom); 313 } 314 destination.offset(offsetX, offsetY); 315 return destination; 316 } 317 getScriptRuns(char[] text, int start, int limit, List<FontInfo> fonts)318 private static List<ScriptRun> getScriptRuns(char[] text, int start, int limit, List<FontInfo> fonts) { 319 LinkedList<ScriptRun> scriptRuns = new LinkedList<>(); 320 321 int count = limit - start; 322 UScriptRun uScriptRun = new UScriptRun(text, start, count); 323 while (uScriptRun.next()) { 324 int scriptStart = uScriptRun.getScriptStart(); 325 int scriptLimit = uScriptRun.getScriptLimit(); 326 ScriptRun run = new ScriptRun( 327 scriptStart, scriptLimit, 328 getScriptFont(text, scriptStart, scriptLimit, fonts)); 329 scriptRuns.add(run); 330 } 331 return scriptRuns; 332 } 333 334 // TODO: Replace this method with one which returns the font based on the scriptCode. 335 @NonNull getScriptFont(char[] text, int start, int limit, List<FontInfo> fonts)336 private static Font getScriptFont(char[] text, int start, int limit, List<FontInfo> fonts) { 337 if (fonts.isEmpty()) { 338 logFontWarning(); 339 // Fallback font in case no font can be loaded 340 return Font.getFont(Font.SERIF); 341 } 342 343 // From all the fonts, select the one that can display the highest number of characters 344 Font bestFont = fonts.get(0).mFont; 345 int bestFontCount = 0; 346 for (FontInfo fontInfo : fonts) { 347 int count = fontInfo.mFont.canDisplayUpTo(text, start, limit); 348 if (count == -1) { 349 // This font can display everything, return this one 350 return fontInfo.mFont; 351 } 352 353 if (count > bestFontCount) { 354 bestFontCount = count; 355 bestFont = fontInfo.mFont; 356 } 357 } 358 359 return bestFont; 360 } 361 getIcuFlags(int bidiFlag)362 private static int getIcuFlags(int bidiFlag) { 363 switch (bidiFlag) { 364 case Paint.BIDI_LTR: 365 case Paint.BIDI_FORCE_LTR: 366 return Bidi.DIRECTION_LEFT_TO_RIGHT; 367 case Paint.BIDI_RTL: 368 case Paint.BIDI_FORCE_RTL: 369 return Bidi.DIRECTION_RIGHT_TO_LEFT; 370 case Paint.BIDI_DEFAULT_LTR: 371 return Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT; 372 case Paint.BIDI_DEFAULT_RTL: 373 return Bidi.DIRECTION_DEFAULT_RIGHT_TO_LEFT; 374 default: 375 assert false; 376 return Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT; 377 } 378 } 379 } 380