Java Code Examples for java.text.AttributedString#addAttribute()

The following examples show how to use java.text.AttributedString#addAttribute() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FormattedCharacterBuffer.java    From binnavi with Apache License 2.0 6 votes vote down vote up
/** Returns the AttributedString to be drawn, skipping the first skip characters. */
private AttributedString getAttributedStringForLine(int lineIndex, int skip) {
  String newLine = new String(charBuffer, (numberOfColumnsInBuffer * lineIndex) + skip,
      numberOfColumnsInBuffer - skip);
  AttributedString attributedString = new AttributedString(newLine);

  int lineStart = (lineIndex * numberOfColumnsInBuffer) + skip;
  for (int index = 0; index < numberOfColumnsInBuffer - skip; index++) {
    attributedString.addAttribute(java.awt.font.TextAttribute.FONT,
        perCharFonts[lineStart + index], index, index + 1);
    attributedString.addAttribute(java.awt.font.TextAttribute.BACKGROUND,
        perCharBackgroundColor[lineStart + index], index, index + 1);
    attributedString.addAttribute(java.awt.font.TextAttribute.FOREGROUND,
        perCharForegroundColor[lineStart + index], index, index + 1);
  }
  return attributedString;
}
 
Example 2
Source File: CodePointInputMethod.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Send the composed text to the client.
 */
private void sendComposedText() {
    AttributedString as = new AttributedString(buffer.toString());
    as.addAttribute(TextAttribute.INPUT_METHOD_HIGHLIGHT,
            InputMethodHighlight.SELECTED_RAW_TEXT_HIGHLIGHT);
    context.dispatchInputMethodEvent(
            InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
            as.getIterator(), 0,
            TextHitInfo.leading(insertionPoint), null);
}
 
Example 3
Source File: SheetUtil.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Copy text attributes from the supplied Font to Java2D AttributedString
 */
private static void copyAttributes(Font font, AttributedString str, @SuppressWarnings("SameParameterValue") int startIdx, int endIdx) {
    str.addAttribute(TextAttribute.FAMILY, font.getFontName(), startIdx, endIdx);
    str.addAttribute(TextAttribute.SIZE, (float)font.getFontHeightInPoints());
    if (font.getBold()) str.addAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, startIdx, endIdx);
    if (font.getItalic() ) str.addAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE, startIdx, endIdx);
    if (font.getUnderline() == Font.U_SINGLE ) str.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, startIdx, endIdx);
}
 
Example 4
Source File: LumenUtils.java    From radiance with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static int getMultilineTextHeight(Font font, String text,
        int availableWidth) {
    AttributedString attributedDescription = new AttributedString(text);
    if (text.length() == 0)
        return 0;

    attributedDescription.addAttribute(TextAttribute.FONT, font);
    FontRenderContext frc = new FontRenderContext(new AffineTransform(),
            false, false);
    LineBreakMeasurer lineBreakMeasurer = new LineBreakMeasurer(
            attributedDescription.getIterator(), frc);
    int currOffset = 0;
    int lineCount = 0;
    while (true) {
        TextLayout tl = lineBreakMeasurer.nextLayout(availableWidth);
        if (tl == null)
            break;

        int charCount = tl.getCharacterCount();

        lineCount++;
        currOffset += charCount;
    }

    LineMetrics lm = font.getLineMetrics("", frc);
    float height = lm.getHeight() + (lineCount - 1) * lm.getAscent();

    return (int) height;
}
 
Example 5
Source File: CodePointInputMethod.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Send the composed text to the client.
 */
private void sendComposedText() {
    AttributedString as = new AttributedString(buffer.toString());
    as.addAttribute(TextAttribute.INPUT_METHOD_HIGHLIGHT,
            InputMethodHighlight.SELECTED_RAW_TEXT_HIGHLIGHT);
    context.dispatchInputMethodEvent(
            InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
            as.getIterator(), 0,
            TextHitInfo.leading(insertionPoint), null);
}
 
Example 6
Source File: AxisTest.java    From ECG-Viewer with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks that serialization works, particularly with the attributed label.
 */
@Test
public void testSerialization() {
    Axis a1 = new CategoryAxis("Test");
    AttributedString label = new AttributedString("Axis Label");
    label.addAttribute(TextAttribute.SUPERSCRIPT, 
            TextAttribute.SUPERSCRIPT_SUB, 1, 4);
    a1.setAttributedLabel(label);
    Axis a2 = (Axis) TestUtilities.serialised(a1);
    assertEquals(a1, a2);
}
 
Example 7
Source File: MultiIconSimpleColoredComponent.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private TextLayout createAndCacheTextLayout(int fragmentIndex, Font basefont, FontRenderContext fontRenderContext) {
  String text = myFragments.get(fragmentIndex);
  AttributedString string = new AttributedString(text);
  int start = 0;
  int end = text.length();
  AttributedCharacterIterator it = string.getIterator(new AttributedCharacterIterator.Attribute[0], start, end);
  Font currentFont = basefont;
  int currentIndex = start;
  for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
    Font font = basefont;
    // TODO(jacobr): SuitableFontProvider is a private class so we can't
    // easily use it. How important is supporting this use case?
    /*
    if (!font.canDisplay(c)) {
      for (SuitableFontProvider provider : SuitableFontProvider.EP_NAME.getExtensions()) {
        font = provider.getFontAbleToDisplay(c, basefont.getSize(), basefont.getStyle(), basefont.getFamily());
        if (font != null) break;
      }
    }
    */
    int i = it.getIndex();
    if (!Comparing.equal(currentFont, font)) {
      if (i > currentIndex) {
        string.addAttribute(TextAttribute.FONT, currentFont, currentIndex, i);
      }
      currentFont = font;
      currentIndex = i;
    }
  }
  if (currentIndex < end) {
    string.addAttribute(TextAttribute.FONT, currentFont, currentIndex, end);
  }
  TextLayout layout = new TextLayout(string.getIterator(), fontRenderContext);
  if (fragmentIndex >= myLayouts.size()) {
    myLayouts.addAll(Collections.nCopies(fragmentIndex - myLayouts.size() + 1, null));
  }
  myLayouts.set(fragmentIndex, layout);
  myLayoutFont = getBaseFont();
  return layout;
}
 
Example 8
Source File: MonkeyCanvas.java    From CXTouch with GNU General Public License v3.0 5 votes vote down vote up
@Override
        public void inputMethodTextChanged(InputMethodEvent e) {
            int committedCharacterCount = e.getCommittedCharacterCount();
            AttributedCharacterIterator text = e.getText();
            composedText = null;
            char c;
            if (text != null) {
                if (committedCharacterCount > 0) {
                    int toCopy = committedCharacterCount;
                    c = text.first();
                    StringBuilder sb = new StringBuilder();
                    while (toCopy-- > 0) {
                        sb.append(c);
                        c = text.next();
                    }
                    inputListener.type(sb.toString());
                }

                if (text.getEndIndex()
                        - (text.getBeginIndex() + committedCharacterCount) > 0) {
                    composedTextString = new AttributedString(text, text
                            .getBeginIndex()
                            + committedCharacterCount, text.getEndIndex(),
                            IM_ATTRIBUTES);
                    composedTextString.addAttribute(TextAttribute.FONT, getFont());
                    composedText = composedTextString.getIterator();
                    //TODO The code below need be extended
//                    System.out.print(composedText.first());
//                    while (composedText.getIndex() < composedText.getEndIndex()) {
//                        System.out.print(composedText.next());
//                    }
                }
            }
            e.consume();
        }
 
Example 9
Source File: AxisTest.java    From SIMVA-SoS with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that serialization works, particularly with the attributed label.
 */
@Test
public void testSerialization() {
    Axis a1 = new CategoryAxis("Test");
    AttributedString label = new AttributedString("Axis Label");
    label.addAttribute(TextAttribute.SUPERSCRIPT, 
            TextAttribute.SUPERSCRIPT_SUB, 1, 4);
    a1.setAttributedLabel(label);
    Axis a2 = (Axis) TestUtilities.serialised(a1);
    assertEquals(a1, a2);
}
 
Example 10
Source File: SimpleColoredComponent.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private TextLayout createTextLayout(String text, Font basefont, FontRenderContext fontRenderContext) {
  if (StringUtil.isEmpty(text)) return null;
  AttributedString string = new AttributedString(text);
  int start = 0;
  int end = text.length();
  AttributedCharacterIterator it = string.getIterator(new AttributedCharacterIterator.Attribute[0], start, end);
  Font currentFont = basefont;
  int currentIndex = start;
  for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
    Font font = basefont;
    if (!font.canDisplay(c)) {
      for (SuitableFontProvider provider : SuitableFontProvider.EP_NAME.getExtensions()) {
        font = provider.getFontAbleToDisplay(c, basefont.getSize(), basefont.getStyle(), basefont.getFamily());
        if (font != null) break;
      }
    }
    int i = it.getIndex();
    if (!Comparing.equal(currentFont, font)) {
      if (i > currentIndex) {
        string.addAttribute(TextAttribute.FONT, currentFont, currentIndex, i);
      }
      currentFont = font;
      currentIndex = i;
    }
  }
  if (currentIndex < end) {
    string.addAttribute(TextAttribute.FONT, currentFont, currentIndex, end);
  }
  return new TextLayout(string.getIterator(), fontRenderContext);
}
 
Example 11
Source File: TextLayout.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a <code>TextLayout</code> from a <code>String</code>
 * and a {@link Font}.  All the text is styled using the specified
 * <code>Font</code>.
 * <p>
 * The <code>String</code> must specify a single paragraph of text,
 * because an entire paragraph is required for the bidirectional
 * algorithm.
 * @param string the text to display
 * @param font a <code>Font</code> used to style the text
 * @param frc contains information about a graphics device which is needed
 *       to measure the text correctly.
 *       Text measurements can vary slightly depending on the
 *       device resolution, and attributes such as antialiasing.  This
 *       parameter does not specify a translation between the
 *       <code>TextLayout</code> and user space.
 */
public TextLayout(String string, Font font, FontRenderContext frc) {

    if (font == null) {
        throw new IllegalArgumentException("Null font passed to TextLayout constructor.");
    }

    if (string == null) {
        throw new IllegalArgumentException("Null string passed to TextLayout constructor.");
    }

    if (string.length() == 0) {
        throw new IllegalArgumentException("Zero length string passed to TextLayout constructor.");
    }

    Map<? extends Attribute, ?> attributes = null;
    if (font.hasLayoutAttributes()) {
        attributes = font.getAttributes();
    }

    char[] text = string.toCharArray();
    if (sameBaselineUpTo(font, text, 0, text.length) == text.length) {
        fastInit(text, font, attributes, frc);
    } else {
        AttributedString as = attributes == null
            ? new AttributedString(string)
            : new AttributedString(string, attributes);
        as.addAttribute(TextAttribute.FONT, font);
        standardInit(as.getIterator(), text, frc);
    }
}
 
Example 12
Source File: getRunStartLimitTest.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        String text = "Hello world";
        AttributedString as = new AttributedString(text);

        // add non-Annotation attributes
        as.addAttribute(TextAttribute.WEIGHT,
                        TextAttribute.WEIGHT_LIGHT,
                        0,
                        3);
        as.addAttribute(TextAttribute.WEIGHT,
                        TextAttribute.WEIGHT_BOLD,
                        3,
                        5);
        as.addAttribute(TextAttribute.WEIGHT,
                        TextAttribute.WEIGHT_EXTRABOLD,
                        5,
                        text.length());

        // add Annotation attributes
        as.addAttribute(TextAttribute.WIDTH,
                        new Annotation(TextAttribute.WIDTH_EXTENDED),
                        0,
                        3);
        as.addAttribute(TextAttribute.WIDTH,
                        new Annotation(TextAttribute.WIDTH_CONDENSED),
                        3,
                        4);

        AttributedCharacterIterator aci = as.getIterator(null, 2, 4);

        aci.first();
        int runStart = aci.getRunStart();
        if (runStart != 2) {
            throw new Exception("1st run start is wrong. ("+runStart+" should be 2.)");
        }

        int runLimit = aci.getRunLimit();
        if (runLimit != 3) {
            throw new Exception("1st run limit is wrong. ("+runLimit+" should be 3.)");
        }

        Object value = aci.getAttribute(TextAttribute.WEIGHT);
        if (value != TextAttribute.WEIGHT_LIGHT) {
            throw new Exception("1st run attribute is wrong. ("
                                +value+" should be "+TextAttribute.WEIGHT_LIGHT+".)");
        }

        value = aci.getAttribute(TextAttribute.WIDTH);
        if (value != null) {
            throw new Exception("1st run annotation is wrong. ("
                                +value+" should be null.)");
        }

        aci.setIndex(runLimit);
        runStart = aci.getRunStart();
        if (runStart != 3) {
            throw new Exception("2nd run start is wrong. ("+runStart+" should be 3.)");
        }

        runLimit = aci.getRunLimit();
        if (runLimit != 4) {
            throw new Exception("2nd run limit is wrong. ("+runLimit+" should be 4.)");
        }
        value = aci.getAttribute(TextAttribute.WEIGHT);
        if (value != TextAttribute.WEIGHT_BOLD) {
            throw new Exception("2nd run attribute is wrong. ("
                                +value+" should be "+TextAttribute.WEIGHT_BOLD+".)");
        }

        value = aci.getAttribute(TextAttribute.WIDTH);
        if (!(value instanceof Annotation)
            || (((Annotation)value).getValue() !=  TextAttribute.WIDTH_CONDENSED)) {
            throw new Exception("2nd run annotation is wrong. (" + value + " should be "
                                + new Annotation(TextAttribute.WIDTH_CONDENSED)+".)");
        }
    }
 
Example 13
Source File: getRunStartLimitTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        String text = "Hello world";
        AttributedString as = new AttributedString(text);

        // add non-Annotation attributes
        as.addAttribute(TextAttribute.WEIGHT,
                        TextAttribute.WEIGHT_LIGHT,
                        0,
                        3);
        as.addAttribute(TextAttribute.WEIGHT,
                        TextAttribute.WEIGHT_BOLD,
                        3,
                        5);
        as.addAttribute(TextAttribute.WEIGHT,
                        TextAttribute.WEIGHT_EXTRABOLD,
                        5,
                        text.length());

        // add Annotation attributes
        as.addAttribute(TextAttribute.WIDTH,
                        new Annotation(TextAttribute.WIDTH_EXTENDED),
                        0,
                        3);
        as.addAttribute(TextAttribute.WIDTH,
                        new Annotation(TextAttribute.WIDTH_CONDENSED),
                        3,
                        4);

        AttributedCharacterIterator aci = as.getIterator(null, 2, 4);

        aci.first();
        int runStart = aci.getRunStart();
        if (runStart != 2) {
            throw new Exception("1st run start is wrong. ("+runStart+" should be 2.)");
        }

        int runLimit = aci.getRunLimit();
        if (runLimit != 3) {
            throw new Exception("1st run limit is wrong. ("+runLimit+" should be 3.)");
        }

        Object value = aci.getAttribute(TextAttribute.WEIGHT);
        if (value != TextAttribute.WEIGHT_LIGHT) {
            throw new Exception("1st run attribute is wrong. ("
                                +value+" should be "+TextAttribute.WEIGHT_LIGHT+".)");
        }

        value = aci.getAttribute(TextAttribute.WIDTH);
        if (value != null) {
            throw new Exception("1st run annotation is wrong. ("
                                +value+" should be null.)");
        }

        aci.setIndex(runLimit);
        runStart = aci.getRunStart();
        if (runStart != 3) {
            throw new Exception("2nd run start is wrong. ("+runStart+" should be 3.)");
        }

        runLimit = aci.getRunLimit();
        if (runLimit != 4) {
            throw new Exception("2nd run limit is wrong. ("+runLimit+" should be 4.)");
        }
        value = aci.getAttribute(TextAttribute.WEIGHT);
        if (value != TextAttribute.WEIGHT_BOLD) {
            throw new Exception("2nd run attribute is wrong. ("
                                +value+" should be "+TextAttribute.WEIGHT_BOLD+".)");
        }

        value = aci.getAttribute(TextAttribute.WIDTH);
        if (!(value instanceof Annotation)
            || (((Annotation)value).getValue() !=  TextAttribute.WIDTH_CONDENSED)) {
            throw new Exception("2nd run annotation is wrong. (" + value + " should be "
                                + new Annotation(TextAttribute.WIDTH_CONDENSED)+".)");
        }
    }
 
Example 14
Source File: BidiEmbeddingTest.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
static void test1() {
    String target = "BACK WARDS";
    String str = "If this text is >" + target + "< the test passed.";
    int start = str.indexOf(target);
    int limit = start + target.length();

    System.out.println("start: " + start + " limit: " + limit);

    AttributedString astr = new AttributedString(str);
    astr.addAttribute(TextAttribute.BIDI_EMBEDDING,
                     new Integer(-1),
                     start,
                     limit);

    Bidi bidi = new Bidi(astr.getIterator());

    for (int i = 0; i < bidi.getRunCount(); ++i) {
        System.out.println("run " + i +
                           " from " + bidi.getRunStart(i) +
                           " to " + bidi.getRunLimit(i) +
                           " at level " + bidi.getRunLevel(i));
    }

    System.out.println(bidi);

    byte[] embs = new byte[str.length() + 3];
    for (int i = start + 1; i < limit + 1; ++i) {
        embs[i] = -1;
    }

    Bidi bidi2 = new Bidi(str.toCharArray(), 0, embs, 1, str.length(), Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
    for (int i = 0; i < bidi2.getRunCount(); ++i) {
        System.out.println("run " + i +
                           " from " + bidi2.getRunStart(i) +
                           " to " + bidi2.getRunLimit(i) +
                           " at level " + bidi2.getRunLevel(i));
    }

    System.out.println(bidi2 + "\n");

    if (bidi.getRunCount() != 3 || bidi2.getRunCount() != 3) {
        throw new Error("Bidi run count incorrect");
    } else {
        System.out.println("test1() passed.\n");
    }
}
 
Example 15
Source File: ProcessDiagramCanvas.java    From activiti-in-action-codes with Apache License 2.0 4 votes vote down vote up
protected void drawMultilineText(String text, int x, int y, int boxWidth, int boxHeight) {
    int availableHeight = boxHeight - ICON_SIZE - ICON_PADDING;

    // Create an attributed string based in input text
    AttributedString attributedString = new AttributedString(text);
    attributedString.addAttribute(TextAttribute.FONT, g.getFont());
    attributedString.addAttribute(TextAttribute.FOREGROUND, Color.black);

    AttributedCharacterIterator characterIterator = attributedString.getIterator();

    int width = boxWidth - (2 * TEXT_PADDING);

    int currentHeight = 0;
    // Prepare a list of lines of text we'll be drawing
    List<TextLayout> layouts = new ArrayList<TextLayout>();
    String lastLine = null;

    LineBreakMeasurer measurer = new LineBreakMeasurer(characterIterator, g.getFontRenderContext());

    TextLayout layout = null;
    while (measurer.getPosition() < characterIterator.getEndIndex() && currentHeight <= availableHeight) {

        int previousPosition = measurer.getPosition();

        // Request next layout
        layout = measurer.nextLayout(width);

        int height = ((Float) (layout.getDescent() + layout.getAscent() + layout.getLeading())).intValue();

        if (currentHeight + height > availableHeight) {
            // The line we're about to add should NOT be added anymore, append three dots to previous one instead
            // to indicate more text is truncated
            layouts.remove(layouts.size() - 1);

            if (lastLine.length() >= 4) {
                lastLine = lastLine.substring(0, lastLine.length() - 4) + "...";
            }
            layouts.add(new TextLayout(lastLine, g.getFont(), g.getFontRenderContext()));
        } else {
            layouts.add(layout);
            lastLine = text.substring(previousPosition, measurer.getPosition());
            currentHeight += height;
        }
    }


    int currentY = y + ICON_SIZE + ICON_PADDING + ((availableHeight - currentHeight) / 2);
    int currentX = 0;

    // Actually draw the lines
    for (TextLayout textLayout : layouts) {

        currentY += textLayout.getAscent();
        currentX = TEXT_PADDING + x + ((width - ((Double) textLayout.getBounds().getWidth()).intValue()) / 2);

        textLayout.draw(g, currentX, currentY);
        currentY += textLayout.getDescent() + textLayout.getLeading();
    }

}
 
Example 16
Source File: BidiEmbeddingTest.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
static void test1() {
    String target = "BACK WARDS";
    String str = "If this text is >" + target + "< the test passed.";
    int start = str.indexOf(target);
    int limit = start + target.length();

    System.out.println("start: " + start + " limit: " + limit);

    AttributedString astr = new AttributedString(str);
    astr.addAttribute(TextAttribute.BIDI_EMBEDDING,
                     new Integer(-1),
                     start,
                     limit);

    Bidi bidi = new Bidi(astr.getIterator());

    for (int i = 0; i < bidi.getRunCount(); ++i) {
        System.out.println("run " + i +
                           " from " + bidi.getRunStart(i) +
                           " to " + bidi.getRunLimit(i) +
                           " at level " + bidi.getRunLevel(i));
    }

    System.out.println(bidi);

    byte[] embs = new byte[str.length() + 3];
    for (int i = start + 1; i < limit + 1; ++i) {
        embs[i] = -1;
    }

    Bidi bidi2 = new Bidi(str.toCharArray(), 0, embs, 1, str.length(), Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
    for (int i = 0; i < bidi2.getRunCount(); ++i) {
        System.out.println("run " + i +
                           " from " + bidi2.getRunStart(i) +
                           " to " + bidi2.getRunLimit(i) +
                           " at level " + bidi2.getRunLevel(i));
    }

    System.out.println(bidi2 + "\n");

    if (bidi.getRunCount() != 3 || bidi2.getRunCount() != 3) {
        throw new Error("Bidi run count incorrect");
    } else {
        System.out.println("test1() passed.\n");
    }
}
 
Example 17
Source File: BidiEmbeddingTest.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
static void test1() {
    String target = "BACK WARDS";
    String str = "If this text is >" + target + "< the test passed.";
    int start = str.indexOf(target);
    int limit = start + target.length();

    System.out.println("start: " + start + " limit: " + limit);

    AttributedString astr = new AttributedString(str);
    astr.addAttribute(TextAttribute.BIDI_EMBEDDING,
                     new Integer(-1),
                     start,
                     limit);

    Bidi bidi = new Bidi(astr.getIterator());

    for (int i = 0; i < bidi.getRunCount(); ++i) {
        System.out.println("run " + i +
                           " from " + bidi.getRunStart(i) +
                           " to " + bidi.getRunLimit(i) +
                           " at level " + bidi.getRunLevel(i));
    }

    System.out.println(bidi);

    byte[] embs = new byte[str.length() + 3];
    for (int i = start + 1; i < limit + 1; ++i) {
        embs[i] = -1;
    }

    Bidi bidi2 = new Bidi(str.toCharArray(), 0, embs, 1, str.length(), Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
    for (int i = 0; i < bidi2.getRunCount(); ++i) {
        System.out.println("run " + i +
                           " from " + bidi2.getRunStart(i) +
                           " to " + bidi2.getRunLimit(i) +
                           " at level " + bidi2.getRunLevel(i));
    }

    System.out.println(bidi2 + "\n");

    if (bidi.getRunCount() != 3 || bidi2.getRunCount() != 3) {
        throw new Error("Bidi run count incorrect");
    } else {
        System.out.println("test1() passed.\n");
    }
}
 
Example 18
Source File: ProcessDiagramCanvas.java    From activiti-in-action-codes with Apache License 2.0 4 votes vote down vote up
protected void drawMultilineText(String text, int x, int y, int boxWidth, int boxHeight) {
    int availableHeight = boxHeight - ICON_SIZE - ICON_PADDING;

    // Create an attributed string based in input text
    AttributedString attributedString = new AttributedString(text);
    attributedString.addAttribute(TextAttribute.FONT, g.getFont());
    attributedString.addAttribute(TextAttribute.FOREGROUND, Color.black);

    AttributedCharacterIterator characterIterator = attributedString.getIterator();

    int width = boxWidth - (2 * TEXT_PADDING);

    int currentHeight = 0;
    // Prepare a list of lines of text we'll be drawing
    List<TextLayout> layouts = new ArrayList<TextLayout>();
    String lastLine = null;

    LineBreakMeasurer measurer = new LineBreakMeasurer(characterIterator, g.getFontRenderContext());

    TextLayout layout = null;
    while (measurer.getPosition() < characterIterator.getEndIndex() && currentHeight <= availableHeight) {

        int previousPosition = measurer.getPosition();

        // Request next layout
        layout = measurer.nextLayout(width);

        int height = ((Float) (layout.getDescent() + layout.getAscent() + layout.getLeading())).intValue();

        if (currentHeight + height > availableHeight) {
            // The line we're about to add should NOT be added anymore, append three dots to previous one instead
            // to indicate more text is truncated
            layouts.remove(layouts.size() - 1);

            if (lastLine.length() >= 4) {
                lastLine = lastLine.substring(0, lastLine.length() - 4) + "...";
            }
            layouts.add(new TextLayout(lastLine, g.getFont(), g.getFontRenderContext()));
        } else {
            layouts.add(layout);
            lastLine = text.substring(previousPosition, measurer.getPosition());
            currentHeight += height;
        }
    }


    int currentY = y + ICON_SIZE + ICON_PADDING + ((availableHeight - currentHeight) / 2);
    int currentX = 0;

    // Actually draw the lines
    for (TextLayout textLayout : layouts) {

        currentY += textLayout.getAscent();
        currentX = TEXT_PADDING + x + ((width - ((Double) textLayout.getBounds().getWidth()).intValue()) / 2);

        textLayout.draw(g, currentX, currentY);
        currentY += textLayout.getDescent() + textLayout.getLeading();
    }

}
 
Example 19
Source File: getRunStartLimitTest.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        String text = "Hello world";
        AttributedString as = new AttributedString(text);

        // add non-Annotation attributes
        as.addAttribute(TextAttribute.WEIGHT,
                        TextAttribute.WEIGHT_LIGHT,
                        0,
                        3);
        as.addAttribute(TextAttribute.WEIGHT,
                        TextAttribute.WEIGHT_BOLD,
                        3,
                        5);
        as.addAttribute(TextAttribute.WEIGHT,
                        TextAttribute.WEIGHT_EXTRABOLD,
                        5,
                        text.length());

        // add Annotation attributes
        as.addAttribute(TextAttribute.WIDTH,
                        new Annotation(TextAttribute.WIDTH_EXTENDED),
                        0,
                        3);
        as.addAttribute(TextAttribute.WIDTH,
                        new Annotation(TextAttribute.WIDTH_CONDENSED),
                        3,
                        4);

        AttributedCharacterIterator aci = as.getIterator(null, 2, 4);

        aci.first();
        int runStart = aci.getRunStart();
        if (runStart != 2) {
            throw new Exception("1st run start is wrong. ("+runStart+" should be 2.)");
        }

        int runLimit = aci.getRunLimit();
        if (runLimit != 3) {
            throw new Exception("1st run limit is wrong. ("+runLimit+" should be 3.)");
        }

        Object value = aci.getAttribute(TextAttribute.WEIGHT);
        if (value != TextAttribute.WEIGHT_LIGHT) {
            throw new Exception("1st run attribute is wrong. ("
                                +value+" should be "+TextAttribute.WEIGHT_LIGHT+".)");
        }

        value = aci.getAttribute(TextAttribute.WIDTH);
        if (value != null) {
            throw new Exception("1st run annotation is wrong. ("
                                +value+" should be null.)");
        }

        aci.setIndex(runLimit);
        runStart = aci.getRunStart();
        if (runStart != 3) {
            throw new Exception("2nd run start is wrong. ("+runStart+" should be 3.)");
        }

        runLimit = aci.getRunLimit();
        if (runLimit != 4) {
            throw new Exception("2nd run limit is wrong. ("+runLimit+" should be 4.)");
        }
        value = aci.getAttribute(TextAttribute.WEIGHT);
        if (value != TextAttribute.WEIGHT_BOLD) {
            throw new Exception("2nd run attribute is wrong. ("
                                +value+" should be "+TextAttribute.WEIGHT_BOLD+".)");
        }

        value = aci.getAttribute(TextAttribute.WIDTH);
        if (!(value instanceof Annotation)
            || (((Annotation)value).getValue() !=  TextAttribute.WIDTH_CONDENSED)) {
            throw new Exception("2nd run annotation is wrong. (" + value + " should be "
                                + new Annotation(TextAttribute.WIDTH_CONDENSED)+".)");
        }
    }
 
Example 20
Source File: ProcessDiagramCanvas.java    From activiti-in-action-codes with Apache License 2.0 4 votes vote down vote up
protected void drawMultilineText(String text, int x, int y, int boxWidth, int boxHeight) {
    int availableHeight = boxHeight - ICON_SIZE - ICON_PADDING;

    // Create an attributed string based in input text
    AttributedString attributedString = new AttributedString(text);
    attributedString.addAttribute(TextAttribute.FONT, g.getFont());
    attributedString.addAttribute(TextAttribute.FOREGROUND, Color.black);

    AttributedCharacterIterator characterIterator = attributedString.getIterator();

    int width = boxWidth - (2 * TEXT_PADDING);

    int currentHeight = 0;
    // Prepare a list of lines of text we'll be drawing
    List<TextLayout> layouts = new ArrayList<TextLayout>();
    String lastLine = null;

    LineBreakMeasurer measurer = new LineBreakMeasurer(characterIterator, g.getFontRenderContext());

    TextLayout layout = null;
    while (measurer.getPosition() < characterIterator.getEndIndex() && currentHeight <= availableHeight) {

        int previousPosition = measurer.getPosition();

        // Request next layout
        layout = measurer.nextLayout(width);

        int height = ((Float) (layout.getDescent() + layout.getAscent() + layout.getLeading())).intValue();

        if (currentHeight + height > availableHeight) {
            // The line we're about to add should NOT be added anymore, append three dots to previous one instead
            // to indicate more text is truncated
            layouts.remove(layouts.size() - 1);

            if (lastLine.length() >= 4) {
                lastLine = lastLine.substring(0, lastLine.length() - 4) + "...";
            }
            layouts.add(new TextLayout(lastLine, g.getFont(), g.getFontRenderContext()));
        } else {
            layouts.add(layout);
            lastLine = text.substring(previousPosition, measurer.getPosition());
            currentHeight += height;
        }
    }


    int currentY = y + ICON_SIZE + ICON_PADDING + ((availableHeight - currentHeight) / 2);
    int currentX = 0;

    // Actually draw the lines
    for (TextLayout textLayout : layouts) {

        currentY += textLayout.getAscent();
        currentX = TEXT_PADDING + x + ((width - ((Double) textLayout.getBounds().getWidth()).intValue()) / 2);

        textLayout.draw(g, currentX, currentY);
        currentY += textLayout.getDescent() + textLayout.getLeading();
    }

}