GlyphList.java 18.7 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
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 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
 */

package sun.font;

import java.awt.Font;
import java.awt.font.GlyphVector;
import java.awt.font.FontRenderContext;
import sun.java2d.loops.FontInfo;

/*
 * This class represents a list of actual renderable glyphs.
 * It can be constructed from a number of text sources, representing
 * the various ways in which a programmer can ask a Graphics2D object
 * to render some text.  Once constructed, it provides a way of iterating
 * through the device metrics and graybits of the individual glyphs that
 * need to be rendered to the screen.
 *
 * Note that this class holds pointers to native data which must be
 * disposed.  It is not marked as finalizable since it is intended
 * to be very lightweight and finalization is a comparitively expensive
 * procedure.  The caller must specifically use try{} finally{} to
 * manually ensure that the object is disposed after use, otherwise
 * native data structures might be leaked.
 *
 * Here is a code sample for using this class:
 *
 * public void drawString(String str, FontInfo info, float x, float y) {
 *     GlyphList gl = GlyphList.getInstance();
 *     try {
 *         gl.setFromString(info, str, x, y);
 *         int strbounds[] = gl.getBounds();
 *         int numglyphs = gl.getNumGlyphs();
 *         for (int i = 0; i < numglyphs; i++) {
 *             gl.setGlyphIndex(i);
 *             int metrics[] = gl.getMetrics();
 *             byte bits[] = gl.getGrayBits();
 *             int glyphx = metrics[0];
 *             int glyphy = metrics[1];
 *             int glyphw = metrics[2];
 *             int glyphh = metrics[3];
 *             int off = 0;
 *             for (int j = 0; j < glyphh; j++) {
 *                 for (int i = 0; i < glyphw; i++) {
 *                     int dx = glyphx + i;
 *                     int dy = glyphy + j;
 *                     int alpha = bits[off++];
 *                     drawPixel(alpha, dx, dy);
 *                 }
 *             }
 *         }
 *     } finally {
 *         gl.dispose();
 *     }
 * }
 */
public final class GlyphList {
    private static final int MINGRAYLENGTH = 1024;
    private static final int MAXGRAYLENGTH = 8192;
    private static final int DEFAULT_LENGTH = 32;

    int glyphindex;
    int metrics[];
    byte graybits[];

    /* A reference to the strike is needed for the case when the GlyphList
     * may be added to a queue for batch processing, (e.g. OpenGL) and we need
     * to be completely certain that the strike is still valid when the glyphs
     * images are later referenced.  This does mean that if such code discards
     * GlyphList and places only the data it contains on the queue, that the
     * strike needs to be part of that data held by a strong reference.
     * In the cases of drawString() and drawChars(), this is a single strike,
     * although it may be a composite strike.  In the case of
     * drawGlyphVector() it may be a single strike, or a list of strikes.
     */
    Object strikelist; // hold multiple strikes during rendering of complex gv

    /* In normal usage, the same GlyphList will get recycled, so
     * it makes sense to allocate arrays that will get reused along with
     * it, rather than generating garbage. Garbage will be generated only
     * in MP envts where multiple threads are executing. Throughput should
     * still be higher in those cases.
     */
    int len = 0;
    int maxLen = 0;
    int maxPosLen = 0;
    int glyphData[];
    char chData[];
    long images[];
    float positions[];
    float x, y;
    float gposx, gposy;
    boolean usePositions;

    /* lcdRGBOrder is used only by LCD text rendering. Its here because
     * the Graphics may have a different hint value than the one used
     * by a GlyphVector, so it has to be stored here - and is obtained
     * from the right FontInfo. Another approach would have been to have
     * install a separate pipe for that case but that's a lot of extra
     * code when a simple boolean will suffice. The overhead to non-LCD
     * text is a redundant boolean assign per call.
     */
    boolean lcdRGBOrder;

    /*
     * lcdSubPixPos is used only by LCD text rendering. Its here because
     * the Graphics may have a different hint value than the one used
     * by a GlyphVector, so it has to be stored here - and is obtained
     * from the right FontInfo. Its also needed by the code which
     * calculates glyph positions which already needs to access this
     * GlyphList and would otherwise need the FontInfo.
     * This is true only if LCD text and fractional metrics hints
     * are selected on the graphics.
     * When this is true and the glyph positions as determined by the
     * advances are non-integral, it requests adjustment of the positions.
     * Setting this for surfaces which do not support it through accelerated
     * loops may cause a slow-down as software loops are invoked instead.
     */
    boolean lcdSubPixPos;

    /* This scheme creates a singleton GlyphList which is checked out
     * for use. Callers who find its checked out create one that after use
     * is discarded. This means that in a MT-rendering environment,
     * there's no need to synchronise except for that one instance.
     * Fewer threads will then need to synchronise, perhaps helping
     * throughput on a MP system. If for some reason the reusable
     * GlyphList is checked out for a long time (or never returned?) then
     * we would end up always creating new ones. That situation should not
     * occur and if if did, it would just lead to some extra garbage being
     * created.
     */
    private static GlyphList reusableGL = new GlyphList();
    private static boolean inUse;


    void ensureCapacity(int len) {
      /* Note len must not be -ve! only setFromChars should be capable
       * of passing down a -ve len, and this guards against it.
       */
        if (len < 0) {
          len = 0;
        }
        if (usePositions && len > maxPosLen) {
            positions = new float[len * 2 + 2];
            maxPosLen = len;
        }

        if (maxLen == 0 || len > maxLen) {
            glyphData = new int[len];
            chData = new char[len];
            images = new long[len];
            maxLen = len;
        }
    }

    private GlyphList() {
//         ensureCapacity(DEFAULT_LENGTH);
    }

//     private GlyphList(int arraylen) {
//          ensureCapacity(arraylen);
//     }

    public static GlyphList getInstance() {
        /* The following heuristic is that if the reusable instance is
         * in use, it probably still will be in a micro-second, so avoid
         * synchronising on the class and just allocate a new instance.
         * The cost is one extra boolean test for the normal case, and some
         * small number of cases where we allocate an extra object when
         * in fact the reusable one would be freed very soon.
         */
        if (inUse) {
            return new GlyphList();
        } else {
            synchronized(GlyphList.class) {
                if (inUse) {
                    return new GlyphList();
                } else {
                    inUse = true;
                    return reusableGL;
                }
            }
        }
    }

    /* In some cases the caller may be able to estimate the size of
     * array needed, and it will usually be long enough. This avoids
     * the unnecessary reallocation that occurs if our default
     * values are too small. This is useful because this object
     * will be discarded so the re-allocation overhead is high.
     */
//     public static GlyphList getInstance(int sz) {
//      if (inUse) {
//          return new GlyphList(sz);
//      } else {
//          synchronized(GlyphList.class) {
//              if (inUse) {
//                  return new GlyphList();
//              } else {
//                  inUse = true;
//                  return reusableGL;
//              }
//          }
//      }
//     }

    /* GlyphList is in an invalid state until setFrom* method is called.
     * After obtaining a new GlyphList it is the caller's responsibility
     * that one of these methods is executed before handing off the
     * GlyphList
     */

    public boolean setFromString(FontInfo info, String str, float x, float y) {
        this.x = x;
        this.y = y;
        this.strikelist = info.fontStrike;
        this.lcdRGBOrder = info.lcdRGBOrder;
        this.lcdSubPixPos = info.lcdSubPixPos;
        len = str.length();
        ensureCapacity(len);
        str.getChars(0, len, chData, 0);
        return mapChars(info, len);
    }

    public boolean setFromChars(FontInfo info, char[] chars, int off, int alen,
                                float x, float y) {
        this.x = x;
        this.y = y;
        this.strikelist = info.fontStrike;
        this.lcdRGBOrder = info.lcdRGBOrder;
        this.lcdSubPixPos = info.lcdSubPixPos;
        len = alen;
        if (alen < 0) {
            len = 0;
        } else {
            len = alen;
        }
        ensureCapacity(len);
        System.arraycopy(chars, off, chData, 0, len);
        return mapChars(info, len);
    }

    private final boolean mapChars(FontInfo info, int len) {
        /* REMIND.Is it worthwhile for the iteration to convert
         * chars to glyph ids to directly map to images?
         */
        if (info.font2D.getMapper().charsToGlyphsNS(len, chData, glyphData)) {
            return false;
        }
        info.fontStrike.getGlyphImagePtrs(glyphData, images, len);
        glyphindex = -1;
        return true;
    }


    public void setFromGlyphVector(FontInfo info, GlyphVector gv,
                                   float x, float y) {
        this.x = x;
        this.y = y;
        this.lcdRGBOrder = info.lcdRGBOrder;
        this.lcdSubPixPos = info.lcdSubPixPos;
        /* A GV may be rendered in different Graphics. It is possible it is
         * used for one case where LCD text is available, and another where
         * it is not. Pass in the "info". to ensure get a suitable one.
         */
        StandardGlyphVector sgv = StandardGlyphVector.getStandardGV(gv, info);
        // call before ensureCapacity :-
        usePositions = sgv.needsPositions(info.devTx);
        len = sgv.getNumGlyphs();
        ensureCapacity(len);
        strikelist = sgv.setupGlyphImages(images,
                                          usePositions ? positions : null,
                                          info.devTx);
        glyphindex = -1;
    }

    public int[] getBounds() {
        /* We co-opt the 5 element array that holds per glyph metrics in order
         * to return the bounds. So a caller must copy the data out of the
         * array before calling any other methods on this GlyphList
         */
        if (glyphindex >= 0) {
            throw new InternalError("calling getBounds after setGlyphIndex");
        }
        if (metrics == null) {
            metrics = new int[5];
        }
        /* gposx and gposy are used to accumulate the advance.
         * Add 0.5f for consistent rounding to pixel position. */
        gposx = x + 0.5f;
        gposy = y + 0.5f;
        fillBounds(metrics);
        return metrics;
    }

    /* This method now assumes "state", so must be called 0->len
     * The metrics it returns are accumulated on the fly
     * So it could be renamed "nextGlyph()".
     * Note that a laid out GlyphVector which has assigned glyph positions
     * doesn't have this stricture..
     */
    public void setGlyphIndex(int i) {
        glyphindex = i;
P
prr 已提交
326 327 328 329 330 331 332 333
        if (images[i] == 0L) {
           metrics[0] = (int)gposx;
           metrics[1] = (int)gposy;
           metrics[2] = 0;
           metrics[3] = 0;
           metrics[4] = 0;
           return;
        }
D
duke 已提交
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
        float gx =
            StrikeCache.unsafe.getFloat(images[i]+StrikeCache.topLeftXOffset);
        float gy =
            StrikeCache.unsafe.getFloat(images[i]+StrikeCache.topLeftYOffset);

        if (usePositions) {
            metrics[0] = (int)Math.floor(positions[(i<<1)]   + gposx + gx);
            metrics[1] = (int)Math.floor(positions[(i<<1)+1] + gposy + gy);
        } else {
            metrics[0] = (int)Math.floor(gposx + gx);
            metrics[1] = (int)Math.floor(gposy + gy);
            /* gposx and gposy are used to accumulate the advance */
            gposx += StrikeCache.unsafe.getFloat
                (images[i]+StrikeCache.xAdvanceOffset);
            gposy += StrikeCache.unsafe.getFloat
                (images[i]+StrikeCache.yAdvanceOffset);
        }
        metrics[2] =
            StrikeCache.unsafe.getChar(images[i]+StrikeCache.widthOffset);
        metrics[3] =
            StrikeCache.unsafe.getChar(images[i]+StrikeCache.heightOffset);
        metrics[4] =
            StrikeCache.unsafe.getChar(images[i]+StrikeCache.rowBytesOffset);
    }

    public int[] getMetrics() {
        return metrics;
    }

    public byte[] getGrayBits() {
        int len = metrics[4] * metrics[3];
        if (graybits == null) {
            graybits = new byte[Math.max(len, MINGRAYLENGTH)];
        } else {
            if (len > graybits.length) {
                graybits = new byte[len];
            }
        }
P
prr 已提交
372 373 374
        if (images[glyphindex] == 0L) {
            return graybits;
        }
375 376
        long pixelDataAddress =
            StrikeCache.unsafe.getAddress(images[glyphindex] +
D
duke 已提交
377
                                          StrikeCache.pixelDataOffset);
378

D
duke 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
        if (pixelDataAddress == 0L) {
            return graybits;
        }
        /* unsafe is supposed to be fast, but I doubt if this loop can beat
         * a native call which does a getPrimitiveArrayCritical and a
         * memcpy for the typical amount of image data (30-150 bytes)
         * Consider a native method if there is a performance problem (which
         * I haven't seen so far).
         */
        for (int i=0; i<len; i++) {
            graybits[i] = StrikeCache.unsafe.getByte(pixelDataAddress+i);
        }
        return graybits;
    }

    public long[] getImages() {
        return images;
    }

    public boolean usePositions() {
        return usePositions;
    }

    public float[] getPositions() {
        return positions;
    }

    public float getX() {
        return x;
    }

    public float getY() {
        return y;
    }

    public Object getStrike() {
        return strikelist;
    }

    public boolean isSubPixPos() {
        return lcdSubPixPos;
    }

    public boolean isRGBOrder() {
        return lcdRGBOrder;
    }

    /* There's a reference equality test overhead here, but it allows us
     * to avoid synchronizing for GL's that will just be GC'd. This
     * helps MP throughput.
     */
    public void dispose() {
        if (this == reusableGL) {
            if (graybits != null && graybits.length > MAXGRAYLENGTH) {
                graybits = null;
            }
            usePositions = false;
            strikelist = null; // remove reference to the strike list
            inUse = false;
        }
    }

    /* The value here is for use by the rendering engine as it reflects
     * the number of glyphs in the array to be blitted. Surrogates pairs
     * may have two slots (the second of these being a dummy entry of the
     * invisible glyph), whereas an application client would expect only
     * one glyph. In other words don't propagate this value up to client code.
     *
     * {dlf} an application client should have _no_ expectations about the
     * number of glyphs per char.  This ultimately depends on the font
     * technology and layout process used, which in general clients will
     * know nothing about.
     */
    public int getNumGlyphs() {
        return len;
    }

    /* We re-do all this work as we iterate through the glyphs
     * but it seems unavoidable without re-working the Java TextRenderers.
     */
    private void fillBounds(int[] bounds) {
        /* Faster to access local variables in the for loop? */
        int xOffset = StrikeCache.topLeftXOffset;
        int yOffset = StrikeCache.topLeftYOffset;
        int wOffset = StrikeCache.widthOffset;
        int hOffset = StrikeCache.heightOffset;
        int xAdvOffset = StrikeCache.xAdvanceOffset;
        int yAdvOffset = StrikeCache.yAdvanceOffset;

        if (len == 0) {
            bounds[0] = bounds[1] = bounds[2] = bounds[3] = 0;
            return;
        }
        float bx0, by0, bx1, by1;
        bx0 = by0 = Float.POSITIVE_INFINITY;
        bx1 = by1 = Float.NEGATIVE_INFINITY;

        int posIndex = 0;
        float glx = x + 0.5f;
        float gly = y + 0.5f;
        char gw, gh;
        float gx, gy, gx0, gy0, gx1, gy1;
        for (int i=0; i<len; i++) {
P
prr 已提交
482 483 484
            if (images[i] == 0L) {
                continue;
            }
D
duke 已提交
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
            gx = StrikeCache.unsafe.getFloat(images[i]+xOffset);
            gy = StrikeCache.unsafe.getFloat(images[i]+yOffset);
            gw = StrikeCache.unsafe.getChar(images[i]+wOffset);
            gh = StrikeCache.unsafe.getChar(images[i]+hOffset);

            if (usePositions) {
                gx0 = positions[posIndex++] + gx + glx;
                gy0 = positions[posIndex++] + gy + gly;
            } else {
                gx0 = glx + gx;
                gy0 = gly + gy;
                glx += StrikeCache.unsafe.getFloat(images[i]+xAdvOffset);
                gly += StrikeCache.unsafe.getFloat(images[i]+yAdvOffset);
            }
            gx1 = gx0 + gw;
            gy1 = gy0 + gh;
            if (bx0 > gx0) bx0 = gx0;
            if (by0 > gy0) by0 = gy0;
            if (bx1 < gx1) bx1 = gx1;
            if (by1 < gy1) by1 = gy1;
        }
        /* floor is safe and correct because all glyph widths, heights
         * and offsets are integers
         */
        bounds[0] = (int)Math.floor(bx0);
        bounds[1] = (int)Math.floor(by0);
        bounds[2] = (int)Math.floor(bx1);
        bounds[3] = (int)Math.floor(by1);
    }
}