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 boolean foundFont = false; 158 int canDisplayUpTo = preferredFont.canDisplayUpTo(mText, start, limit); 159 if (canDisplayUpTo == -1) { 160 // We can draw all characters in the text. 161 render(start, limit, preferredFont, flag, advances, advancesIndex, draw); 162 return; 163 } 164 if (canDisplayUpTo > start) { 165 // We can draw something. 166 render(start, canDisplayUpTo, preferredFont, flag, advances, advancesIndex, draw); 167 advancesIndex += canDisplayUpTo - start; 168 start = canDisplayUpTo; 169 } 170 171 // The current character cannot be drawn with the preferred font. Cycle through all the 172 // fonts to check which one can draw it. 173 int charCount = Character.isHighSurrogate(mText[start]) ? 2 : 1; 174 List<FontInfo> fontInfos = mPaint.getFonts(); 175 //noinspection ForLoopReplaceableByForEach (avoid iterator allocation) 176 for (int i = 0; i < fontInfos.size(); i++) { 177 Font font = fontInfos.get(i).mFont; 178 if (font == null) { 179 logFontWarning(); 180 continue; 181 } 182 canDisplayUpTo = font.canDisplayUpTo(mText, start, start + charCount); 183 if (canDisplayUpTo == -1) { 184 render(start, start+charCount, font, flag, advances, advancesIndex, draw); 185 start += charCount; 186 advancesIndex += charCount; 187 foundFont = true; 188 break; 189 } 190 } 191 if (!foundFont) { 192 // No font can display this char. Use the preferred font. The char will most 193 // probably appear as a box or a blank space. We could, probably, use some 194 // heuristics and break the character into the base character and diacritics and 195 // then draw it, but it's probably not worth the effort. 196 render(start, start + charCount, preferredFont, flag, advances, advancesIndex, 197 draw); 198 start += charCount; 199 advancesIndex += charCount; 200 } 201 } 202 } 203 logFontWarning()204 private static void logFontWarning() { 205 Bridge.getLog().fidelityWarning(LayoutLog.TAG_BROKEN, 206 "Some fonts could not be loaded. The rendering may not be perfect.", null, null); 207 } 208 209 /** 210 * Renders the text to the right of the bounds with the given font. 211 * @param font The font to render the text with. 212 */ render(int start, int limit, Font font, int flag, float[] advances, int advancesIndex, boolean draw)213 private void render(int start, int limit, Font font, int flag, float[] advances, 214 int advancesIndex, boolean draw) { 215 FontRenderContext frc = mGraphics != null ? mGraphics.getFontRenderContext() : 216 Toolkit.getDefaultToolkit().getFontMetrics(font).getFontRenderContext(); 217 218 boolean frcIsAntialiased = frc.isAntiAliased(); 219 boolean useAntialiasing = mPaint.isAntiAliased(); 220 221 if (frcIsAntialiased) { 222 if (!useAntialiasing) { 223 // The context has antialiasing enabled but the paint does not. We need to 224 // disable it 225 frc = new FontRenderContext(font.getTransform(), false, 226 frc.usesFractionalMetrics()); 227 } else { 228 // In this case both the paint and the context antialising match but we need 229 // to check for a bug in the JDK 230 // Workaround for http://b.android.com/211659 (disable antialiasing) 231 if (font.isTransformed()) { 232 AffineTransform transform = font.getTransform(); 233 if (transform.getScaleX() >= SCALEX_WORKAROUND_LIMIT && 234 JETBRAINS_VENDOR_ID.equals(JAVA_VENDOR)) { 235 frc = new FontRenderContext(transform, false, frc.usesFractionalMetrics()); 236 } 237 } 238 } 239 } else if (useAntialiasing) { 240 // The context does not have antialiasing enabled but the paint does. We need to 241 // enable it unless we need to avoid the JDK bug 242 243 AffineTransform transform = font.getTransform(); 244 // Workaround for http://b.android.com/211659 (disable antialiasing) 245 if (transform.getScaleX() < SCALEX_WORKAROUND_LIMIT || 246 !JETBRAINS_VENDOR_ID.equals(JAVA_VENDOR)) { 247 frc = new FontRenderContext(font.getTransform(), true, frc.usesFractionalMetrics()); 248 } 249 } 250 251 GlyphVector gv = font.layoutGlyphVector(frc, mText, start, limit, flag); 252 int ng = gv.getNumGlyphs(); 253 int[] ci = gv.getGlyphCharIndices(0, ng, null); 254 if (advances != null) { 255 for (int i = 0; i < ng; i++) { 256 if (mText[ci[i]] == '\uFEFF') { 257 // Workaround for bug in JetBrains JDK 258 // where the character \uFEFF is associated a glyph with non-zero width 259 continue; 260 } 261 int adv_idx = advancesIndex + ci[i]; 262 advances[adv_idx] += gv.getGlyphMetrics(i).getAdvanceX(); 263 } 264 } 265 if (draw && mGraphics != null) { 266 mGraphics.drawGlyphVector(gv, mBounds.right, mBaseline); 267 } 268 269 // Update the bounds. 270 Rectangle2D awtBounds = gv.getLogicalBounds(); 271 // If the width of the bounds is zero, no text had been drawn earlier. Hence, use the 272 // coordinates from the bounds as an offset. 273 if (Math.abs(mBounds.right - mBounds.left) == 0) { 274 mBounds = awtRectToAndroidRect(awtBounds, mBounds.right, mBaseline, mBounds); 275 } else { 276 mBounds.union(awtRectToAndroidRect(awtBounds, mBounds.right, mBaseline, null)); 277 } 278 } 279 280 // --- Static helper methods --- 281 awtRectToAndroidRect(Rectangle2D awtRec, float offsetX, float offsetY, @Nullable RectF destination)282 private static RectF awtRectToAndroidRect(Rectangle2D awtRec, float offsetX, float offsetY, 283 @Nullable RectF destination) { 284 float left = (float) awtRec.getX(); 285 float top = (float) awtRec.getY(); 286 float right = (float) (left + awtRec.getWidth()); 287 float bottom = (float) (top + awtRec.getHeight()); 288 if (destination != null) { 289 destination.set(left, top, right, bottom); 290 } else { 291 destination = new RectF(left, top, right, bottom); 292 } 293 destination.offset(offsetX, offsetY); 294 return destination; 295 } 296 getScriptRuns(char[] text, int start, int limit, List<FontInfo> fonts)297 private static List<ScriptRun> getScriptRuns(char[] text, int start, int limit, List<FontInfo> fonts) { 298 LinkedList<ScriptRun> scriptRuns = new LinkedList<>(); 299 300 int count = limit - start; 301 UScriptRun uScriptRun = new UScriptRun(text, start, count); 302 while (uScriptRun.next()) { 303 int scriptStart = uScriptRun.getScriptStart(); 304 int scriptLimit = uScriptRun.getScriptLimit(); 305 ScriptRun run = new ScriptRun( 306 scriptStart, scriptLimit, 307 getScriptFont(text, scriptStart, scriptLimit, fonts)); 308 scriptRuns.add(run); 309 } 310 return scriptRuns; 311 } 312 313 // TODO: Replace this method with one which returns the font based on the scriptCode. 314 @NonNull getScriptFont(char[] text, int start, int limit, List<FontInfo> fonts)315 private static Font getScriptFont(char[] text, int start, int limit, List<FontInfo> fonts) { 316 for (FontInfo fontInfo : fonts) { 317 if (fontInfo.mFont.canDisplayUpTo(text, start, limit) == -1) { 318 return fontInfo.mFont; 319 } 320 } 321 322 if (fonts.isEmpty()) { 323 logFontWarning(); 324 // Fallback font in case no font can be loaded 325 return Font.getFont(Font.SERIF); 326 } 327 328 return fonts.get(0).mFont; 329 } 330 getIcuFlags(int bidiFlag)331 private static int getIcuFlags(int bidiFlag) { 332 switch (bidiFlag) { 333 case Paint.BIDI_LTR: 334 case Paint.BIDI_FORCE_LTR: 335 return Bidi.DIRECTION_LEFT_TO_RIGHT; 336 case Paint.BIDI_RTL: 337 case Paint.BIDI_FORCE_RTL: 338 return Bidi.DIRECTION_RIGHT_TO_LEFT; 339 case Paint.BIDI_DEFAULT_LTR: 340 return Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT; 341 case Paint.BIDI_DEFAULT_RTL: 342 return Bidi.DIRECTION_DEFAULT_RIGHT_TO_LEFT; 343 default: 344 assert false; 345 return Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT; 346 } 347 } 348 } 349