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.LinkedList; 37 import java.util.List; 38 39 /** 40 * Render the text by breaking it into various scripts and using the right font for each script. 41 * Can be used to measure the text without actually drawing it. 42 */ 43 @SuppressWarnings("deprecation") 44 public class BidiRenderer { 45 private static String JAVA_VENDOR = System.getProperty("java.vendor"); 46 47 private static class ScriptRun { 48 private final int start; 49 private final int limit; 50 private final Font font; 51 ScriptRun(int start, int limit, @NonNull Font font)52 private ScriptRun(int start, int limit, @NonNull Font font) { 53 this.start = start; 54 this.limit = limit; 55 this.font = font; 56 } 57 } 58 59 private final Graphics2D mGraphics; 60 private final Paint_Delegate mPaint; 61 private char[] mText; 62 // Bounds of the text drawn so far. 63 private RectF mBounds; 64 private float mBaseline; 65 66 /** 67 * @param graphics May be null. 68 * @param paint The Paint to use to get the fonts. Should not be null. 69 * @param text Unidirectional text. Should not be null. 70 */ BidiRenderer(Graphics2D graphics, Paint_Delegate paint, char[] text)71 public BidiRenderer(Graphics2D graphics, Paint_Delegate paint, char[] text) { 72 assert (paint != null); 73 mGraphics = graphics; 74 mPaint = paint; 75 mText = text; 76 mBounds = new RectF(); 77 } 78 79 /** 80 * 81 * @param x The x-coordinate of the left edge of where the text should be drawn on the given 82 * graphics. 83 * @param y The y-coordinate at which to draw the text on the given mGraphics. 84 * 85 */ setRenderLocation(float x, float y)86 public BidiRenderer setRenderLocation(float x, float y) { 87 mBounds.set(x, y, x, y); 88 mBaseline = y; 89 return this; 90 } 91 92 /** 93 * Perform Bidi Analysis on the text and then render it. 94 * <p/> 95 * To skip the analysis and render unidirectional text, see {@link 96 * #renderText(int, int, boolean, float[], int, boolean)} 97 */ renderText(int start, int limit, int bidiFlags, float[] advances, int advancesIndex, boolean draw)98 public RectF renderText(int start, int limit, int bidiFlags, float[] advances, 99 int advancesIndex, boolean draw) { 100 Bidi bidi = new Bidi(mText, start, null, 0, limit - start, getIcuFlags(bidiFlags)); 101 mText = bidi.getText(); 102 for (int i = 0; i < bidi.countRuns(); i++) { 103 BidiRun visualRun = bidi.getVisualRun(i); 104 boolean isRtl = visualRun.getDirection() == Bidi.RTL; 105 renderText(visualRun.getStart(), visualRun.getLimit(), isRtl, advances, 106 advancesIndex, draw); 107 } 108 return mBounds; 109 } 110 111 /** 112 * Render unidirectional text. 113 * <p/> 114 * This method can also be used to measure the width of the text without actually drawing it. 115 * <p/> 116 * @param start index of the first character 117 * @param limit index of the first character that should not be rendered. 118 * @param isRtl is the text right-to-left 119 * @param advances If not null, then advances for each character to be rendered are returned 120 * here. 121 * @param advancesIndex index into advances from where the advances need to be filled. 122 * @param draw If true and {@code graphics} is not null, draw the rendered text on the graphics 123 * at the given co-ordinates 124 * @return A rectangle specifying the bounds of the text drawn. 125 */ renderText(int start, int limit, boolean isRtl, float[] advances, int advancesIndex, boolean draw)126 public RectF renderText(int start, int limit, boolean isRtl, float[] advances, 127 int advancesIndex, boolean draw) { 128 // We break the text into scripts and then select font based on it and then render each of 129 // the script runs. 130 for (ScriptRun run : getScriptRuns(mText, start, limit, mPaint.getFonts())) { 131 int flag = Font.LAYOUT_NO_LIMIT_CONTEXT | Font.LAYOUT_NO_START_CONTEXT; 132 flag |= isRtl ? Font.LAYOUT_RIGHT_TO_LEFT : Font.LAYOUT_LEFT_TO_RIGHT; 133 renderScript(run.start, run.limit, run.font, flag, advances, advancesIndex, draw); 134 advancesIndex += run.limit - run.start; 135 } 136 return mBounds; 137 } 138 139 /** 140 * Render a script run to the right of the bounds passed. Use the preferred font to render as 141 * much as possible. This also implements a fallback mechanism to render characters that cannot 142 * be drawn using the preferred font. 143 */ renderScript(int start, int limit, Font preferredFont, int flag, float[] advances, int advancesIndex, boolean draw)144 private void renderScript(int start, int limit, Font preferredFont, int flag, 145 float[] advances, int advancesIndex, boolean draw) { 146 if (mPaint.getFonts().size() == 0 || preferredFont == null) { 147 return; 148 } 149 150 while (start < limit) { 151 boolean foundFont = false; 152 int canDisplayUpTo = preferredFont.canDisplayUpTo(mText, start, limit); 153 if (canDisplayUpTo == -1) { 154 // We can draw all characters in the text. 155 render(start, limit, preferredFont, flag, advances, advancesIndex, draw); 156 return; 157 } 158 if (canDisplayUpTo > start) { 159 // We can draw something. 160 render(start, canDisplayUpTo, preferredFont, flag, advances, advancesIndex, draw); 161 advancesIndex += canDisplayUpTo - start; 162 start = canDisplayUpTo; 163 } 164 165 // The current character cannot be drawn with the preferred font. Cycle through all the 166 // fonts to check which one can draw it. 167 int charCount = Character.isHighSurrogate(mText[start]) ? 2 : 1; 168 List<FontInfo> fontInfos = mPaint.getFonts(); 169 //noinspection ForLoopReplaceableByForEach (avoid iterator allocation) 170 for (int i = 0; i < fontInfos.size(); i++) { 171 Font font = fontInfos.get(i).mFont; 172 if (font == null) { 173 logFontWarning(); 174 continue; 175 } 176 canDisplayUpTo = font.canDisplayUpTo(mText, start, start + charCount); 177 if (canDisplayUpTo == -1) { 178 render(start, start+charCount, font, flag, advances, advancesIndex, draw); 179 start += charCount; 180 advancesIndex += charCount; 181 foundFont = true; 182 break; 183 } 184 } 185 if (!foundFont) { 186 // No font can display this char. Use the preferred font. The char will most 187 // probably appear as a box or a blank space. We could, probably, use some 188 // heuristics and break the character into the base character and diacritics and 189 // then draw it, but it's probably not worth the effort. 190 render(start, start + charCount, preferredFont, flag, advances, advancesIndex, 191 draw); 192 start += charCount; 193 advancesIndex += charCount; 194 } 195 } 196 } 197 logFontWarning()198 private static void logFontWarning() { 199 Bridge.getLog().fidelityWarning(LayoutLog.TAG_BROKEN, 200 "Some fonts could not be loaded. The rendering may not be perfect. " + 201 "Try running the IDE with JRE 7.", null, null); 202 } 203 204 /** 205 * Renders the text to the right of the bounds with the given font. 206 * @param font The font to render the text with. 207 */ render(int start, int limit, Font font, int flag, float[] advances, int advancesIndex, boolean draw)208 private void render(int start, int limit, Font font, int flag, float[] advances, 209 int advancesIndex, boolean draw) { 210 211 FontRenderContext frc; 212 if (mGraphics != null) { 213 frc = mGraphics.getFontRenderContext(); 214 } else { 215 frc = Toolkit.getDefaultToolkit().getFontMetrics(font).getFontRenderContext(); 216 217 // Metrics obtained this way don't have anti-aliasing set. So, 218 // we create a new FontRenderContext with anti-aliasing set. 219 AffineTransform transform = font.getTransform(); 220 if (mPaint.isAntiAliased() && 221 // Workaround for http://b.android.com/211659 222 (transform.getScaleX() <= 9.9 || 223 !"JetBrains s.r.o".equals(JAVA_VENDOR))) { 224 frc = new FontRenderContext(transform, true, frc.usesFractionalMetrics()); 225 } 226 } 227 GlyphVector gv = font.layoutGlyphVector(frc, mText, start, limit, flag); 228 int ng = gv.getNumGlyphs(); 229 int[] ci = gv.getGlyphCharIndices(0, ng, null); 230 if (advances != null) { 231 for (int i = 0; i < ng; i++) { 232 int adv_idx = advancesIndex + ci[i]; 233 advances[adv_idx] += gv.getGlyphMetrics(i).getAdvanceX(); 234 } 235 } 236 if (draw && mGraphics != null) { 237 mGraphics.drawGlyphVector(gv, mBounds.right, mBaseline); 238 } 239 240 // Update the bounds. 241 Rectangle2D awtBounds = gv.getLogicalBounds(); 242 // If the width of the bounds is zero, no text had been drawn earlier. Hence, use the 243 // coordinates from the bounds as an offset. 244 if (Math.abs(mBounds.right - mBounds.left) == 0) { 245 mBounds = awtRectToAndroidRect(awtBounds, mBounds.right, mBaseline, mBounds); 246 } else { 247 mBounds.union(awtRectToAndroidRect(awtBounds, mBounds.right, mBaseline, null)); 248 } 249 } 250 251 // --- Static helper methods --- 252 awtRectToAndroidRect(Rectangle2D awtRec, float offsetX, float offsetY, @Nullable RectF destination)253 private static RectF awtRectToAndroidRect(Rectangle2D awtRec, float offsetX, float offsetY, 254 @Nullable RectF destination) { 255 float left = (float) awtRec.getX(); 256 float top = (float) awtRec.getY(); 257 float right = (float) (left + awtRec.getWidth()); 258 float bottom = (float) (top + awtRec.getHeight()); 259 if (destination != null) { 260 destination.set(left, top, right, bottom); 261 } else { 262 destination = new RectF(left, top, right, bottom); 263 } 264 destination.offset(offsetX, offsetY); 265 return destination; 266 } 267 getScriptRuns(char[] text, int start, int limit, List<FontInfo> fonts)268 private static List<ScriptRun> getScriptRuns(char[] text, int start, int limit, List<FontInfo> fonts) { 269 LinkedList<ScriptRun> scriptRuns = new LinkedList<>(); 270 271 int count = limit - start; 272 UScriptRun uScriptRun = new UScriptRun(text, start, count); 273 while (uScriptRun.next()) { 274 int scriptStart = uScriptRun.getScriptStart(); 275 int scriptLimit = uScriptRun.getScriptLimit(); 276 ScriptRun run = new ScriptRun( 277 scriptStart, scriptLimit, 278 getScriptFont(text, scriptStart, scriptLimit, fonts)); 279 scriptRuns.add(run); 280 } 281 return scriptRuns; 282 } 283 284 // TODO: Replace this method with one which returns the font based on the scriptCode. 285 @NonNull getScriptFont(char[] text, int start, int limit, List<FontInfo> fonts)286 private static Font getScriptFont(char[] text, int start, int limit, List<FontInfo> fonts) { 287 for (FontInfo fontInfo : fonts) { 288 if (fontInfo.mFont == null) { 289 logFontWarning(); 290 continue; 291 } 292 if (fontInfo.mFont.canDisplayUpTo(text, start, limit) == -1) { 293 return fontInfo.mFont; 294 } 295 } 296 297 return fonts.get(0).mFont; 298 } 299 getIcuFlags(int bidiFlag)300 private static int getIcuFlags(int bidiFlag) { 301 switch (bidiFlag) { 302 case Paint.BIDI_LTR: 303 case Paint.BIDI_FORCE_LTR: 304 return Bidi.DIRECTION_LEFT_TO_RIGHT; 305 case Paint.BIDI_RTL: 306 case Paint.BIDI_FORCE_RTL: 307 return Bidi.DIRECTION_RIGHT_TO_LEFT; 308 case Paint.BIDI_DEFAULT_LTR: 309 return Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT; 310 case Paint.BIDI_DEFAULT_RTL: 311 return Bidi.DIRECTION_DEFAULT_RIGHT_TO_LEFT; 312 default: 313 assert false; 314 return Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT; 315 } 316 } 317 } 318