1 /*
   2  * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 /*
  26  *
  27  * (C) Copyright IBM Corp. 1998-2003 - All Rights Reserved
  28  */
  29 
  30 package sun.font;
  31 
  32 import java.awt.Font;
  33 import java.awt.Graphics2D;
  34 import java.awt.Rectangle;
  35 import java.awt.Shape;
  36 
  37 import java.awt.font.FontRenderContext;
  38 import java.awt.font.GlyphJustificationInfo;
  39 import java.awt.font.GlyphMetrics;
  40 import java.awt.font.LineMetrics;
  41 import java.awt.font.TextAttribute;
  42 
  43 import java.awt.geom.AffineTransform;
  44 import java.awt.geom.Point2D;
  45 import java.awt.geom.Rectangle2D;
  46 
  47 import java.util.Map;
  48 
  49 /**
  50  * Default implementation of ExtendedTextLabel.
  51  */
  52 
  53 // {jbr} I made this class package-private to keep the
  54 // Decoration.Label API package-private.
  55 
  56 /* public */
  57 class ExtendedTextSourceLabel extends ExtendedTextLabel implements Decoration.Label {
  58 
  59   TextSource source;
  60   private Decoration decorator;
  61 
  62   // caches
  63   private Font font;
  64   private AffineTransform baseTX;
  65   private CoreMetrics cm;
  66 
  67   Rectangle2D lb;
  68   Rectangle2D ab;
  69   Rectangle2D vb;
  70   Rectangle2D ib;
  71   StandardGlyphVector gv;
  72   float[] charinfo;
  73 
  74   /**
  75    * Create from a TextSource.
  76    */
  77   public ExtendedTextSourceLabel(TextSource source, Decoration decorator) {
  78     this.source = source;
  79     this.decorator = decorator;
  80     finishInit();
  81   }
  82 
  83   /**
  84    * Create from a TextSource, optionally using cached data from oldLabel starting at the offset.
  85    * If present oldLabel must have been created from a run of text that includes the text used in
  86    * the new label.  Start in source corresponds to logical character offset in oldLabel.
  87    */
  88   public ExtendedTextSourceLabel(TextSource source, ExtendedTextSourceLabel oldLabel, int offset) {
  89     // currently no optimization.
  90     this.source = source;
  91     this.decorator = oldLabel.decorator;
  92     finishInit();
  93   }
  94 
  95   private void finishInit() {
  96     font = source.getFont();
  97 
  98     Map<TextAttribute, ?> atts = font.getAttributes();
  99     baseTX = AttributeValues.getBaselineTransform(atts);
 100     if (baseTX == null){
 101         cm = source.getCoreMetrics();
 102     } else {
 103       AffineTransform charTX = AttributeValues.getCharTransform(atts);
 104       if (charTX == null) {
 105           charTX = new AffineTransform();
 106       }
 107       font = font.deriveFont(charTX);
 108 
 109       LineMetrics lm = font.getLineMetrics(source.getChars(), source.getStart(),
 110           source.getStart() + source.getLength(), source.getFRC());
 111       cm = CoreMetrics.get(lm);
 112     }
 113   }
 114 
 115 
 116   // TextLabel API
 117 
 118   public Rectangle2D getLogicalBounds() {
 119     return getLogicalBounds(0, 0);
 120   }
 121 
 122   public Rectangle2D getLogicalBounds(float x, float y) {
 123     if (lb == null) {
 124       lb = createLogicalBounds();
 125     }
 126     return new Rectangle2D.Float((float)(lb.getX() + x),
 127                                  (float)(lb.getY() + y),
 128                                  (float)lb.getWidth(),
 129                                  (float)lb.getHeight());
 130   }
 131 
 132     public float getAdvance() {
 133         if (lb == null) {
 134             lb = createLogicalBounds();
 135         }
 136         return (float)lb.getWidth();
 137     }
 138 
 139   public Rectangle2D getVisualBounds(float x, float y) {
 140     if (vb == null) {
 141       vb = decorator.getVisualBounds(this);
 142     }
 143     return new Rectangle2D.Float((float)(vb.getX() + x),
 144                                  (float)(vb.getY() + y),
 145                                  (float)vb.getWidth(),
 146                                  (float)vb.getHeight());
 147   }
 148 
 149   public Rectangle2D getAlignBounds(float x, float y) {
 150     if (ab == null) {
 151       ab = createAlignBounds();
 152     }
 153     return new Rectangle2D.Float((float)(ab.getX() + x),
 154                                  (float)(ab.getY() + y),
 155                                  (float)ab.getWidth(),
 156                                  (float)ab.getHeight());
 157 
 158   }
 159 
 160   public Rectangle2D getItalicBounds(float x, float y) {
 161     if (ib == null) {
 162       ib = createItalicBounds();
 163     }
 164     return new Rectangle2D.Float((float)(ib.getX() + x),
 165                                  (float)(ib.getY() + y),
 166                                  (float)ib.getWidth(),
 167                                  (float)ib.getHeight());
 168 
 169   }
 170 
 171   public Rectangle getPixelBounds(FontRenderContext frc, float x, float y) {
 172       return getGV().getPixelBounds(frc, x, y);
 173   }
 174 
 175   public boolean isSimple() {
 176       return decorator == Decoration.getPlainDecoration() &&
 177              baseTX == null;
 178   }
 179 
 180   public AffineTransform getBaselineTransform() {
 181       return baseTX; // passing internal object, caller must not modify!
 182   }
 183 
 184   public Shape handleGetOutline(float x, float y) {
 185     return getGV().getOutline(x, y);
 186   }
 187 
 188   public Shape getOutline(float x, float y) {
 189     return decorator.getOutline(this, x, y);
 190   }
 191 
 192   public void handleDraw(Graphics2D g, float x, float y) {
 193     g.drawGlyphVector(getGV(), x, y);
 194   }
 195 
 196   public void draw(Graphics2D g, float x, float y) {
 197     decorator.drawTextAndDecorations(this, g, x, y);
 198   }
 199 
 200   /**
 201    * The logical bounds extends from the origin of the glyphvector to the
 202    * position at which a following glyphvector's origin should be placed.
 203    * We always assume glyph vectors are rendered from left to right, so
 204    * the origin is always to the left.
 205    * <p> On a left-to-right run, combining marks and 'ligatured away'
 206    * characters are to the right of their base characters.  The charinfo
 207    * array will record the character positions for these 'missing' characters
 208    * as being at the origin+advance of the base glyph, with zero advance.
 209    * (This is not necessarily the same as the glyph position, for example,
 210    * an umlaut glyph may have a position to the left of this point, it depends
 211    * on whether the font was designed so that such glyphs overhang to the left
 212    * of their origin, or whether it presumes some kind of kerning to position
 213    * the glyphs).  Anyway, the left of the bounds is the origin of the first
 214    * logical (leftmost) character, and the right is the origin + advance of the
 215    * last logical (rightmost) character.
 216    * <p> On a right-to-left run, these special characters are to the left
 217    * of their base characters.  Again, since 'glyph position' has been abstracted
 218    * away, we can use the origin of the leftmost character, and the origin +
 219    * advance of the rightmost character.
 220    * <p> On a mixed run (hindi) we can't rely on the first logical character
 221    * being the leftmost character.  However we can again rely on the leftmost
 222    * character origin and the rightmost character + advance.
 223    */
 224   protected Rectangle2D createLogicalBounds() {
 225     return getGV().getLogicalBounds();
 226   }
 227 
 228   public Rectangle2D handleGetVisualBounds() {
 229     return getGV().getVisualBounds();
 230   }
 231 
 232   /**
 233    * Like createLogicalBounds except ignore leading and logically trailing white space.
 234    * this assumes logically trailing whitespace is also visually trailing.
 235    * Whitespace is anything that has a zero visual width, regardless of its advance.
 236    * <p> We make the same simplifying assumptions as in createLogicalBounds, namely
 237    * that we can rely on the charinfo to shield us from any glyph positioning oddities
 238    * in the font that place the glyph for a character at other than the pos + advance
 239    * of the character to its left.  So we no longer need to skip chars with zero
 240    * advance, as their bounds (right and left) are already correct.
 241    */
 242   protected Rectangle2D createAlignBounds() {
 243     float[] info = getCharinfo();
 244 
 245     float al = 0f;
 246     float at = -cm.ascent;
 247     float aw = 0f;
 248     float ah = cm.ascent + cm.descent;
 249 
 250     if (charinfo == null || charinfo.length == 0) {
 251         return new Rectangle2D.Float(al, at, aw, ah);
 252     }
 253 
 254     boolean lineIsLTR = (source.getLayoutFlags() & 0x8) == 0;
 255     int rn = info.length - numvals;
 256     if (lineIsLTR) {
 257       while (rn > 0 && info[rn+visw] == 0) {
 258         rn -= numvals;
 259       }
 260     }
 261 
 262     if (rn >= 0) {
 263       int ln = 0;
 264       while (ln < rn && ((info[ln+advx] == 0) || (!lineIsLTR && info[ln+visw] == 0))) {
 265         ln += numvals;
 266       }
 267 
 268       al = Math.max(0f, info[ln+posx]);
 269       aw = info[rn+posx] + info[rn+advx] - al;
 270     }
 271 
 272     /*
 273       boolean lineIsLTR = source.lineIsLTR();
 274       int rn = info.length - numvals;
 275       while (rn > 0 && ((info[rn+advx] == 0) || (lineIsLTR && info[rn+visw] == 0))) {
 276       rn -= numvals;
 277       }
 278 
 279       if (rn >= 0) {
 280       int ln = 0;
 281       while (ln < rn && ((info[ln+advx] == 0) || (!lineIsLTR && info[ln+visw] == 0))) {
 282       ln += numvals;
 283       }
 284 
 285       al = Math.max(0f, info[ln+posx]);
 286       aw = info[rn+posx] + info[rn+advx] - al;
 287       }
 288       */
 289 
 290     return new Rectangle2D.Float(al, at, aw, ah);
 291   }
 292 
 293   public Rectangle2D createItalicBounds() {
 294     float ia = cm.italicAngle;
 295 
 296     Rectangle2D lb = getLogicalBounds();
 297     float l = (float)lb.getMinX();
 298     float t = -cm.ascent;
 299     float r = (float)lb.getMaxX();
 300     float b = cm.descent;
 301     if (ia != 0) {
 302         if (ia > 0) {
 303             l -= ia * (b - cm.ssOffset);
 304             r -= ia * (t - cm.ssOffset);
 305         } else {
 306             l -= ia * (t - cm.ssOffset);
 307             r -= ia * (b - cm.ssOffset);
 308         }
 309     }
 310     return new Rectangle2D.Float(l, t, r - l, b - t);
 311   }
 312 
 313   private final StandardGlyphVector getGV() {
 314     if (gv == null) {
 315       gv = createGV();
 316     }
 317 
 318     return gv;
 319   }
 320 
 321   protected StandardGlyphVector createGV() {
 322     FontRenderContext frc = source.getFRC();
 323     int flags = source.getLayoutFlags();
 324     char[] context = source.getChars();
 325     int start = source.getStart();
 326     int length = source.getLength();
 327 
 328     GlyphLayout gl = GlyphLayout.get(null); // !!! no custom layout engines
 329     gv = gl.layout(font, frc, context, start, length, flags, null); // ??? use textsource
 330     GlyphLayout.done(gl);
 331 
 332     return gv;
 333   }
 334 
 335   // ExtendedTextLabel API
 336 
 337   private static final int posx = 0,
 338     posy = 1,
 339     advx = 2,
 340     advy = 3,
 341     visx = 4,
 342     visy = 5,
 343     visw = 6,
 344     vish = 7;
 345   private static final int numvals = 8;
 346 
 347   public int getNumCharacters() {
 348     return source.getLength();
 349   }
 350 
 351   public CoreMetrics getCoreMetrics() {
 352     return cm;
 353   }
 354 
 355   public float getCharX(int index) {
 356     validate(index);
 357     float[] charinfo = getCharinfo();
 358     int idx = l2v(index) * numvals + posx;
 359     if (charinfo == null || idx >= charinfo.length) {
 360         return 0f;
 361     } else {
 362         return charinfo[idx];
 363     }
 364   }
 365 
 366   public float getCharY(int index) {
 367     validate(index);
 368     float[] charinfo = getCharinfo();
 369     int idx = l2v(index) * numvals + posy;
 370     if (charinfo == null || idx >= charinfo.length) {
 371         return 0f;
 372     } else {
 373         return charinfo[idx];
 374     }
 375   }
 376 
 377   public float getCharAdvance(int index) {
 378     validate(index);
 379     float[] charinfo = getCharinfo();
 380     int idx = l2v(index) * numvals + advx;
 381     if (charinfo == null || idx >= charinfo.length) {
 382         return 0f;
 383     } else {
 384         return charinfo[idx];
 385     }
 386   }
 387 
 388   public Rectangle2D handleGetCharVisualBounds(int index) {
 389     validate(index);
 390     float[] charinfo = getCharinfo();
 391     index = l2v(index) * numvals;
 392     if (charinfo == null || (index+vish) >= charinfo.length) {
 393         return new Rectangle2D.Float();
 394     }
 395     return new Rectangle2D.Float(
 396                                  charinfo[index + visx],
 397                                  charinfo[index + visy],
 398                                  charinfo[index + visw],
 399                                  charinfo[index + vish]);
 400   }
 401 
 402   public Rectangle2D getCharVisualBounds(int index, float x, float y) {
 403 
 404     Rectangle2D bounds = decorator.getCharVisualBounds(this, index);
 405     if (x != 0 || y != 0) {
 406         bounds.setRect(bounds.getX()+x,
 407                        bounds.getY()+y,
 408                        bounds.getWidth(),
 409                        bounds.getHeight());
 410     }
 411     return bounds;
 412   }
 413 
 414   private void validate(int index) {
 415     if (index < 0) {
 416       throw new IllegalArgumentException("index " + index + " < 0");
 417     } else if (index >= source.getLength()) {
 418       throw new IllegalArgumentException("index " + index + " < " + source.getLength());
 419     }
 420   }
 421 
 422   /*
 423     public int hitTestChar(float x, float y) {
 424     // !!! return index of char hit, for swing
 425     // result is negative for trailing-edge hits
 426     // no italics so no problem at margins.
 427     // for now, ignore y since we assume horizontal text
 428 
 429     // find non-combining char origin to right of x
 430     float[] charinfo = getCharinfo();
 431 
 432     int n = 0;
 433     int e = source.getLength();
 434     while (n < e && charinfo[n + advx] != 0 && charinfo[n + posx] > x) {
 435     n += numvals;
 436     }
 437     float rightx = n < e ? charinfo[n+posx] : charinfo[e - numvals + posx] + charinfo[e - numvals + advx];
 438 
 439     // find non-combining char to left of that char
 440     n -= numvals;
 441     while (n >= 0 && charinfo[n+advx] == 0) {
 442     n -= numvals;
 443     }
 444     float leftx = n >= 0 ? charinfo[n+posx] : 0;
 445     float lefta = n >= 0 ? charinfo[n+advx] : 0;
 446 
 447     n /= numvals;
 448 
 449     boolean left = true;
 450     if (x < leftx + lefta / 2f) {
 451     // left of prev char
 452     } else if (x < (leftx + lefta + rightx) / 2f) {
 453     // right of prev char
 454     left = false;
 455     } else {
 456     // left of follow char
 457     n += 1;
 458     }
 459 
 460     if ((source.getLayoutFlags() & 0x1) != 0) {
 461     n = getNumCharacters() - 1 - n;
 462     left = !left;
 463     }
 464 
 465     return left ? n : -n;
 466     }
 467     */
 468 
 469   public int logicalToVisual(int logicalIndex) {
 470     validate(logicalIndex);
 471     return l2v(logicalIndex);
 472   }
 473 
 474   public int visualToLogical(int visualIndex) {
 475     validate(visualIndex);
 476     return v2l(visualIndex);
 477   }
 478 
 479   public int getLineBreakIndex(int start, float width) {
 480     float[] charinfo = getCharinfo();
 481     int length = source.getLength();
 482     --start;
 483     while (width >= 0 && ++start < length) {
 484       int cidx = l2v(start) * numvals + advx;
 485       if (cidx >= charinfo.length) {
 486           break; // layout bailed for some reason
 487       }
 488       float adv = charinfo[cidx];
 489       width -= adv;
 490     }
 491 
 492     return start;
 493   }
 494 
 495   public float getAdvanceBetween(int start, int limit) {
 496     float a = 0f;
 497 
 498     float[] charinfo = getCharinfo();
 499     --start;
 500     while (++start < limit) {
 501       int cidx = l2v(start) * numvals + advx;
 502       if (cidx >= charinfo.length) {
 503           break; // layout bailed for some reason
 504       }
 505       a += charinfo[cidx];
 506     }
 507 
 508     return a;
 509   }
 510 
 511   public boolean caretAtOffsetIsValid(int offset) {
 512       // REMIND: improve this implementation
 513 
 514       // Ligature formation can either be done in logical order,
 515       // with the ligature glyph logically preceding the null
 516       // chars;  or in visual order, with the ligature glyph to
 517       // the left of the null chars.  This method's implementation
 518       // must reflect which strategy is used.
 519 
 520       if (offset == 0 || offset == source.getLength()) {
 521           return true;
 522       }
 523       char c = source.getChars()[source.getStart() + offset];
 524       if (c == '\t' || c == '\n' || c == '\r') { // hack
 525           return true;
 526       }
 527       int v = l2v(offset);
 528 
 529       // If ligatures are always to the left, do this stuff:
 530       //if (!(source.getLayoutFlags() & 0x1) == 0) {
 531       //    v += 1;
 532       //    if (v == source.getLength()) {
 533       //        return true;
 534       //    }
 535       //}
 536 
 537       int idx = v * numvals + advx;
 538       float[] charinfo = getCharinfo();
 539       if (charinfo == null || idx >= charinfo.length) {
 540           return false;
 541       } else {
 542           return charinfo[idx] != 0;
 543       }
 544   }
 545 
 546   private final float[] getCharinfo() {
 547     if (charinfo == null) {
 548       charinfo = createCharinfo();
 549     }
 550     return charinfo;
 551   }
 552 
 553   private static final boolean DEBUG = FontUtilities.debugFonts();
 554 /*
 555 * This takes the glyph info record obtained from the glyph vector and converts it into a similar record
 556 * adjusted to represent character data instead.  For economy we don't use glyph info records in this processing.
 557 *
 558 * Here are some constraints:
 559 * - there can be more glyphs than characters (glyph insertion, perhaps based on normalization, has taken place)
 560 * - there can be fewer glyphs than characters
 561 *   Some layout engines may insert 0xffff glyphs for characters ligaturized away, but
 562 *   not all do, and it cannot be relied upon.
 563 * - each glyph maps to a single character, when multiple glyphs exist for a character they all map to it, but
 564 *   no two characters map to the same glyph
 565 * - multiple glyphs mapping to the same character need not be in sequence (thai, tamil have split characters)
 566 * - glyphs may be arbitrarily reordered (Indic reorders glyphs)
 567 * - all glyphs share the same bidi level
 568 * - all glyphs share the same horizontal (or vertical) baseline
 569 * - combining marks visually follow their base character in the glyph array-- i.e. in an rtl gv they are
 570 *   to the left of their base character-- and have zero advance.
 571 *
 572 * The output maps this to character positions, and therefore caret positions, via the following assumptions:
 573 * - zero-advance glyphs do not contribute to the advance of their character (i.e. position is ignored), conversely
 574 *   if a glyph is to contribute to the advance of its character it must have a non-zero (float) advance
 575 * - no carets can appear between a zero width character and its preceding character, where 'preceding' is
 576 *   defined logically.
 577 * - no carets can appear within a split character
 578 * - no carets can appear within a local reordering (i.e. Indic reordering, or non-adjacent split characters)
 579 * - all characters lie on the same baseline, and it is either horizontal or vertical
 580 * - the charinfo is in uniform ltr or rtl order (visual order), since local reorderings and split characters are removed
 581 *
 582 * The algorithm works in the following way:
 583 * 1) we scan the glyphs ltr or rtl based on the bidi run direction
 584 * 2) Since the may be fewer glyphs than chars we cannot work in place.
 585 *    A new array is allocated for output.
 586 *    a) if the line is ltr, we start writing at position 0 until we finish, there may be leftver space
 587 *    b) if the line is rtl and 1-1, we start writing at position numChars/glyphs - 1 until we finish at 0
 588 *    c) otherwise if we don't finish at 0, we have to copy the data down
 589 * 3) we consume clusters in the following way:
 590 *    a) the first element is always consumed
 591 *    b) subsequent elements are consumed if:
 592 *       i) their advance is zero
 593 *       ii) their character index <= the character index of any character seen in this cluster
 594 *       iii) the minimum character index seen in this cluster isn't adjacent to the previous cluster
 595 *    c) character data is written as follows for horizontal lines (x/y and w/h are exchanged on vertical lines)
 596 *       i) the x position is the position of the leftmost glyph whose advance is not zero
 597 *       ii)the y position is the baseline
 598 *       iii) the x advance is the distance to the maximum x + adv of all glyphs whose advance is not zero
 599 *       iv) the y advance is the baseline
 600 *       v) vis x,y,w,h tightly encloses the vis x,y,w,h of all the glyphs with nonzero w and h
 601 * 4) In the future, we can make some simple optimizations to avoid copying if we know some things:
 602 *    a) if the mapping is 1-1, unidirectional, and there are no zero-adv glyphs, we just return the glyphinfo
 603 *    b) if the mapping is 1-1, unidirectional, we just adjust the remaining glyphs to originate at right/left of the base
 604 *    c) if the mapping is 1-1, we compute the base position and advance as we go, then go back to adjust the remaining glyphs
 605 *    d) otherwise we keep separate track of the write position as we do (c) since no glyph in the cluster may be in the
 606 *    position we are writing.
 607 *    e) most clusters are simply the single base glyph in the same position as its character, so we try to avoid
 608 *    copying its data unnecessarily.
 609 * 5) the glyph vector ought to provide access to these 'global' attributes to enable these optimizations.  A single
 610 *    int with flags set is probably ok, we could also provide accessors for each attribute.  This doesn't map to
 611 *    the GlyphMetrics flags very well, so I won't attempt to keep them similar.  It might be useful to add those
 612 *    in addition to these.
 613 *    int FLAG_HAS_ZERO_ADVANCE_GLYPHS = 1; // set if there are zero-advance glyphs
 614 *    int FLAG_HAS_NONUNIFORM_ORDER = 2; // set if some glyphs are rearranged out of character visual order
 615 *    int FLAG_HAS_SPLIT_CHARACTERS = 4; // set if multiple glyphs per character
 616 *    int getDescriptionFlags(); // return an int containing the above flags
 617 *    boolean hasZeroAdvanceGlyphs();
 618 *    boolean hasNonuniformOrder();
 619 *    boolean hasSplitCharacters();
 620 *    The optimized cases in (4) correspond to values 0, 1, 3, and 7 returned by getDescriptionFlags().
 621 */
 622   protected float[] createCharinfo() {
 623     StandardGlyphVector gv = getGV();
 624     float[] glyphinfo = null;
 625     try {
 626         glyphinfo = gv.getGlyphInfo();
 627     }
 628     catch (Exception e) {
 629         if (DEBUG) {
 630             System.err.println(source);
 631             e.printStackTrace();
 632         }
 633         glyphinfo = new float[gv.getNumGlyphs() * numvals];
 634     }
 635 
 636     int numGlyphs = gv.getNumGlyphs();
 637     if (numGlyphs == 0) {
 638         return glyphinfo;
 639     }
 640     int[] indices = gv.getGlyphCharIndices(0, numGlyphs, null);
 641     float[] charInfo = new float[source.getLength() * numvals];
 642 
 643     if (DEBUG) {
 644       System.err.println("number of glyphs: " + numGlyphs);
 645       System.err.println("glyphinfo.len: " + glyphinfo.length);
 646       System.err.println("indices.len: " + indices.length);
 647       for (int i = 0; i < numGlyphs; ++i) {
 648         System.err.println("g: " + i +
 649             "  v: " + gv.getGlyphCode(i) +
 650             ", x: " + glyphinfo[i*numvals+posx] +
 651             ", a: " + glyphinfo[i*numvals+advx] +
 652             ", n: " + indices[i]);
 653       }
 654     }
 655 
 656     int minIndex = indices[0];  // smallest index seen this cluster
 657     int maxIndex = minIndex;    // largest index seen this cluster
 658     int cp = 0;                 // character position
 659     int cc = 0;
 660     int gp = 0;                 // glyph position
 661     int gx = 0;                 // glyph index (visual)
 662     int gxlimit = numGlyphs;    // limit of gx, when we reach this we're done
 663     int pdelta = numvals;       // delta for incrementing positions
 664     int xdelta = 1;             // delta for incrementing indices
 665 
 666     boolean rtl = (source.getLayoutFlags() & 0x1) == 1;
 667     if (rtl) {
 668         minIndex = indices[numGlyphs - 1];
 669         maxIndex = minIndex;
 670         cp = charInfo.length - numvals;
 671         gp = glyphinfo.length - numvals;
 672         gx = numGlyphs - 1;
 673         gxlimit = -1;
 674         pdelta = -numvals;
 675         xdelta = -1;
 676     }
 677 
 678     /*
 679     // to support vertical, use 'ixxxx' indices and swap horiz and vertical components
 680     if (source.isVertical()) {
 681         iposx = posy;
 682         iposy = posx;
 683         iadvx = advy;
 684         iadvy = advx;
 685         ivisx = visy;
 686         ivisy = visx;
 687         ivish = visw;
 688         ivisw = vish;
 689     } else {
 690         // use standard values
 691     }
 692     */
 693 
 694     // use intermediates to reduce array access when we need to
 695     float cposl = 0, cposr = 0, cvisl = 0, cvist = 0, cvisr = 0, cvisb = 0;
 696     float baseline = 0;
 697 
 698     while (gx != gxlimit) {
 699         // start of new cluster
 700         int clusterExtraGlyphs = 0;
 701 
 702         minIndex = indices[gx];
 703         maxIndex = minIndex;
 704 
 705         cposl = glyphinfo[gp + posx];
 706         cposr = cposl + glyphinfo[gp + advx];
 707         cvisl = glyphinfo[gp + visx];
 708         cvist = glyphinfo[gp + visy];
 709         cvisr = cvisl + glyphinfo[gp + visw];
 710         cvisb = cvist + glyphinfo[gp + vish];
 711 
 712         // advance to next glyph
 713         gx += xdelta;
 714         gp += pdelta;
 715 
 716         while (gx != gxlimit &&
 717                ((glyphinfo[gp + advx] == 0) ||
 718                (indices[gx] <= maxIndex) ||
 719                (maxIndex - minIndex > clusterExtraGlyphs))) {
 720 
 721             ++clusterExtraGlyphs; // have an extra glyph in this cluster
 722             if (DEBUG) {
 723                 System.err.println("gp=" +gp +" adv=" + glyphinfo[gp + advx] +
 724                                    " gx="+ gx+ " i[gx]="+indices[gx] +
 725                                    " clusterExtraGlyphs="+clusterExtraGlyphs);
 726             }
 727 
 728             // adjust advance only if new glyph has non-zero advance
 729             float radvx = glyphinfo[gp + advx];
 730             if (radvx != 0) {
 731                 float rposx = glyphinfo[gp + posx];
 732                 cposl = Math.min(cposl, rposx);
 733                 cposr = Math.max(cposr, rposx + radvx);
 734             }
 735 
 736             // adjust visible bounds only if new glyph has non-empty bounds
 737             float rvisw = glyphinfo[gp + visw];
 738             if (rvisw != 0) {
 739                 float rvisx = glyphinfo[gp + visx];
 740                 float rvisy = glyphinfo[gp + visy];
 741                 cvisl = Math.min(cvisl, rvisx);
 742                 cvist = Math.min(cvist, rvisy);
 743                 cvisr = Math.max(cvisr, rvisx + rvisw);
 744                 cvisb = Math.max(cvisb, rvisy + glyphinfo[gp + vish]);
 745             }
 746 
 747             // adjust min, max index
 748             minIndex = Math.min(minIndex, indices[gx]);
 749             maxIndex = Math.max(maxIndex, indices[gx]);
 750 
 751             // get ready to examine next glyph
 752             gx += xdelta;
 753             gp += pdelta;
 754         }
 755         // done with cluster, gx and gp are set for next glyph
 756 
 757         if (DEBUG) {
 758             System.err.println("minIndex = " + minIndex + ", maxIndex = " + maxIndex);
 759         }
 760 
 761         // save adjustments to the base character and do common adjustments.
 762         charInfo[cp + posx] = cposl;
 763         charInfo[cp + posy] = baseline;
 764         charInfo[cp + advx] = cposr - cposl;
 765         charInfo[cp + advy] = 0;
 766         charInfo[cp + visx] = cvisl;
 767         charInfo[cp + visy] = cvist;
 768         charInfo[cp + visw] = cvisr - cvisl;
 769         charInfo[cp + vish] = cvisb - cvist;
 770         cc++;
 771 
 772         /* We may have consumed multiple glyphs for this char position.
 773          * Map those extra consumed glyphs to char positions that would follow
 774          * up to the index prior to that which begins the next cluster.
 775          * If we have reached the last glyph (reached gxlimit) then we need to
 776          * map remaining unmapped chars to the same location as the last one.
 777          */
 778         int tgt;
 779         if (gx == gxlimit) {
 780            tgt = charInfo.length / numvals;
 781         } else {
 782            tgt = indices[gx];
 783         }
 784         if (DEBUG) {
 785            System.err.println("gx=" + gx + " gxlimit=" + gxlimit +
 786                               " charInfo.len=" + charInfo.length +
 787                               " tgt=" + tgt + " cc=" + cc + " cp=" + cp);
 788         }
 789         while (cc < tgt) {
 790             if (rtl) {
 791                 // if rtl, characters to left of base, else to right.  reuse cposr.
 792                 cposr = cposl;
 793             }
 794             cvisr -= cvisl; // reuse, convert to deltas.
 795             cvisb -= cvist;
 796 
 797             cp += pdelta;
 798 
 799             if (cp < 0 || cp >= charInfo.length) {
 800                 if (DEBUG)  {
 801                     System.err.println("Error : cp=" + cp +
 802                                        " charInfo.length=" + charInfo.length);
 803                 }
 804                 break;
 805             }
 806 
 807             if (DEBUG) {
 808                 System.err.println("Insert charIndex " + cc + " at pos="+cp);
 809             }
 810             charInfo[cp + posx] = cposr;
 811             charInfo[cp + posy] = baseline;
 812             charInfo[cp + advx] = 0;
 813             charInfo[cp + advy] = 0;
 814             charInfo[cp + visx] = cvisl;
 815             charInfo[cp + visy] = cvist;
 816             charInfo[cp + visw] = cvisr;
 817             charInfo[cp + vish] = cvisb;
 818             cc++;
 819         }
 820         cp += pdelta; // reset for new cluster
 821     }
 822 
 823     if (DEBUG) {
 824         char[] chars = source.getChars();
 825         int start = source.getStart();
 826         int length = source.getLength();
 827         System.err.println("char info for " + length + " characters");
 828 
 829         for (int i = 0; i < length * numvals;) {
 830             System.err.println(" ch: " + Integer.toHexString(chars[start + v2l(i / numvals)]) +
 831                                " x: " + charInfo[i++] +
 832                                " y: " + charInfo[i++] +
 833                                " xa: " + charInfo[i++] +
 834                                " ya: " + charInfo[i++] +
 835                                " l: " + charInfo[i++] +
 836                                " t: " + charInfo[i++] +
 837                                " w: " + charInfo[i++] +
 838                                " h: " + charInfo[i++]);
 839       }
 840     }
 841     return charInfo;
 842   }
 843 
 844   /**
 845    * Map logical character index to visual character index.
 846    * <p>
 847    * This ignores hindi reordering.  @see createCharinfo
 848    */
 849   protected int l2v(int index) {
 850     return (source.getLayoutFlags() & 0x1) == 0 ? index : source.getLength() - 1 - index;
 851   }
 852 
 853   /**
 854    * Map visual character index to logical character index.
 855    * <p>
 856    * This ignores hindi reordering.  @see createCharinfo
 857    */
 858   protected int v2l(int index) {
 859     return (source.getLayoutFlags() & 0x1) == 0 ? index : source.getLength() - 1 - index;
 860   }
 861 
 862   public TextLineComponent getSubset(int start, int limit, int dir) {
 863     return new ExtendedTextSourceLabel(source.getSubSource(start, limit-start, dir), decorator);
 864   }
 865 
 866   public String toString() {
 867     if (true) {
 868         return source.toString(TextSource.WITHOUT_CONTEXT);
 869     }
 870     StringBuilder sb = new StringBuilder();
 871     sb.append(super.toString());
 872     sb.append("[source:");
 873     sb.append(source.toString(TextSource.WITHOUT_CONTEXT));
 874     sb.append(", lb:");
 875     sb.append(lb);
 876     sb.append(", ab:");
 877     sb.append(ab);
 878     sb.append(", vb:");
 879     sb.append(vb);
 880     sb.append(", gv:");
 881     sb.append(gv);
 882     sb.append(", ci: ");
 883     if (charinfo == null) {
 884       sb.append("null");
 885     } else {
 886       sb.append(charinfo[0]);
 887       for (int i = 1; i < charinfo.length;) {
 888         sb.append(i % numvals == 0 ? "; " : ", ");
 889         sb.append(charinfo[i]);
 890       }
 891     }
 892     sb.append("]");
 893 
 894     return sb.toString();
 895   }
 896 
 897   //public static ExtendedTextLabel create(TextSource source) {
 898   //  return new ExtendedTextSourceLabel(source);
 899   //}
 900 
 901   public int getNumJustificationInfos() {
 902     return getGV().getNumGlyphs();
 903   }
 904 
 905 
 906   public void getJustificationInfos(GlyphJustificationInfo[] infos, int infoStart, int charStart, int charLimit) {
 907     // This simple implementation only uses spaces for justification.
 908     // Since regular characters aren't justified, we don't need to deal with
 909     // special infos for combining marks or ligature substitution glyphs.
 910     // added character justification for kanjii only 2/22/98
 911 
 912     StandardGlyphVector gv = getGV();
 913 
 914     float[] charinfo = getCharinfo();
 915 
 916     float size = gv.getFont().getSize2D();
 917 
 918     GlyphJustificationInfo nullInfo =
 919       new GlyphJustificationInfo(0,
 920                                  false, GlyphJustificationInfo.PRIORITY_NONE, 0, 0,
 921                                  false, GlyphJustificationInfo.PRIORITY_NONE, 0, 0);
 922 
 923     GlyphJustificationInfo spaceInfo =
 924       new GlyphJustificationInfo(size,
 925                                  true, GlyphJustificationInfo.PRIORITY_WHITESPACE, 0, size,
 926                                  true, GlyphJustificationInfo.PRIORITY_WHITESPACE, 0, size / 4f);
 927 
 928     GlyphJustificationInfo kanjiInfo =
 929       new GlyphJustificationInfo(size,
 930                                  true, GlyphJustificationInfo.PRIORITY_INTERCHAR, size, size,
 931                                  false, GlyphJustificationInfo.PRIORITY_NONE, 0, 0);
 932 
 933     char[] chars = source.getChars();
 934     int offset = source.getStart();
 935 
 936     // assume data is 1-1 and either all rtl or all ltr, for now
 937 
 938     int numGlyphs = gv.getNumGlyphs();
 939     int minGlyph = 0;
 940     int maxGlyph = numGlyphs;
 941     boolean ltr = (source.getLayoutFlags() & 0x1) == 0;
 942     if (charStart != 0 || charLimit != source.getLength()) {
 943       if (ltr) {
 944         minGlyph = charStart;
 945         maxGlyph = charLimit;
 946       } else {
 947         minGlyph = numGlyphs - charLimit;
 948         maxGlyph = numGlyphs - charStart;
 949       }
 950     }
 951 
 952     for (int i = 0; i < numGlyphs; ++i) {
 953       GlyphJustificationInfo info = null;
 954       if (i >= minGlyph && i < maxGlyph) {
 955         if (charinfo[i * numvals + advx] == 0) { // combining marks don't justify
 956           info = nullInfo;
 957         } else {
 958           int ci = v2l(i); // 1-1 assumption again
 959           char c = chars[offset + ci];
 960           if (Character.isWhitespace(c)) {
 961             info = spaceInfo;
 962             // CJK, Hangul, CJK Compatibility areas
 963           } else if (c >= 0x4e00 &&
 964                      (c < 0xa000) ||
 965                      (c >= 0xac00 && c < 0xd7b0) ||
 966                      (c >= 0xf900 && c < 0xfb00)) {
 967             info = kanjiInfo;
 968           } else {
 969             info = nullInfo;
 970           }
 971         }
 972       }
 973       infos[infoStart + i] = info;
 974     }
 975   }
 976 
 977   public TextLineComponent applyJustificationDeltas(float[] deltas, int deltaStart, boolean[] flags) {
 978 
 979     // when we justify, we need to adjust the charinfo since spaces
 980     // change their advances.  preserve the existing charinfo.
 981 
 982     float[] newCharinfo = getCharinfo().clone();
 983 
 984     // we only push spaces, so never need to rejustify
 985     flags[0] = false;
 986 
 987     // preserve the existing gv.
 988 
 989     StandardGlyphVector newgv = (StandardGlyphVector)getGV().clone();
 990     float[] newPositions = newgv.getGlyphPositions(null);
 991     int numGlyphs = newgv.getNumGlyphs();
 992 
 993     /*
 994     System.out.println("oldgv: " + getGV() + ", newgv: " + newgv);
 995     System.out.println("newpositions: " + newPositions);
 996     for (int i = 0; i < newPositions.length; i += 2) {
 997       System.out.println("[" + (i/2) + "] " + newPositions[i] + ", " + newPositions[i+1]);
 998     }
 999 
1000     System.out.println("deltas: " + deltas + " start: " + deltaStart);
1001     for (int i = deltaStart; i < deltaStart + numGlyphs; i += 2) {
1002       System.out.println("[" + (i/2) + "] " + deltas[i] + ", " + deltas[i+1]);
1003     }
1004     */
1005 
1006     char[] chars = source.getChars();
1007     int offset = source.getStart();
1008 
1009     // accumulate the deltas to adjust positions and advances.
1010     // handle whitespace by modifying advance,
1011     // handle everything else by modifying position before and after
1012 
1013     float deltaPos = 0;
1014     for (int i = 0; i < numGlyphs; ++i) {
1015       if (Character.isWhitespace(chars[offset + v2l(i)])) {
1016         newPositions[i*2] += deltaPos;
1017 
1018         float deltaAdv = deltas[deltaStart + i*2] + deltas[deltaStart + i*2 + 1];
1019 
1020         newCharinfo[i * numvals + posx] += deltaPos;
1021         newCharinfo[i * numvals + visx] += deltaPos;
1022         newCharinfo[i * numvals + advx] += deltaAdv;
1023 
1024         deltaPos += deltaAdv;
1025       } else {
1026         deltaPos += deltas[deltaStart + i*2];
1027 
1028         newPositions[i*2] += deltaPos;
1029         newCharinfo[i * numvals + posx] += deltaPos;
1030         newCharinfo[i * numvals + visx] += deltaPos;
1031 
1032         deltaPos += deltas[deltaStart + i*2 + 1];
1033       }
1034     }
1035     newPositions[numGlyphs * 2] += deltaPos;
1036 
1037     newgv.setGlyphPositions(newPositions);
1038 
1039     /*
1040     newPositions = newgv.getGlyphPositions(null);
1041     System.out.println(">> newpositions: " + newPositions);
1042     for (int i = 0; i < newPositions.length; i += 2) {
1043       System.out.println("[" + (i/2) + "] " + newPositions[i] + ", " + newPositions[i+1]);
1044     }
1045     */
1046 
1047     ExtendedTextSourceLabel result = new ExtendedTextSourceLabel(source, decorator);
1048     result.gv = newgv;
1049     result.charinfo = newCharinfo;
1050 
1051     return result;
1052   }
1053 }