Java Code Examples for java.text.AttributedCharacterIterator

The following are top voted examples for showing how to use java.text.AttributedCharacterIterator. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: jdk8u-jdk   File: TextLine.java   Source Code and License 7 votes vote down vote up
static Font getFontAtCurrentPos(AttributedCharacterIterator aci) {

        Object value = aci.getAttribute(TextAttribute.FONT);
        if (value != null) {
            return (Font) value;
        }
        if (aci.getAttribute(TextAttribute.FAMILY) != null) {
            return Font.getFont(aci.getAttributes());
        }

        int ch = CodePointIterator.create(aci).next();
        if (ch != CodePointIterator.DONE) {
            FontResolver resolver = FontResolver.getInstance();
            return resolver.getFont(resolver.getFontIndex(ch), aci.getAttributes());
        }
        return null;
    }
 
Example 2
Project: Telejam   File: MarkdownTextWriter.java   Source Code and License 7 votes vote down vote up
@Override
public void write(Text text, Writer writer) throws IOException {
  AttributedCharacterIterator iterator = text.getIterator();

  Entry<Attribute, Object> lastAttribute = null;
  while (true) {
    if (iterator.getIndex() == iterator.getEndIndex()) {
      break;
    }

    Entry<Attribute, Object> entry = getAttribute(iterator);

    if (!Objects.equals(entry, lastAttribute)) {
      endEntity(lastAttribute, writer);
      beginEntity(entry, writer);
    }

    writer.write(iterator.current());

    lastAttribute = entry;
    iterator.next();
  }

  endEntity(lastAttribute, writer);
}
 
Example 3
Project: OpenJSharp   File: SwingUtilities2.java   Source Code and License 7 votes vote down vote up
private static AttributedCharacterIterator getTrimmedTrailingSpacesIterator
        (AttributedCharacterIterator iterator) {
    int curIdx = iterator.getIndex();

    char c = iterator.last();
    while(c != CharacterIterator.DONE && Character.isWhitespace(c)) {
        c = iterator.previous();
    }

    if (c != CharacterIterator.DONE) {
        int endIdx = iterator.getIndex();

        if (endIdx == iterator.getEndIndex() - 1) {
            iterator.setIndex(curIdx);
            return iterator;
        } else {
            AttributedString trimmedText = new AttributedString(iterator,
                    iterator.getBeginIndex(), endIdx + 1);
            return trimmedText.getIterator();
        }
    } else {
        return null;
    }
}
 
Example 4
Project: openjdk-jdk10   File: AttributedStringTest.java   Source Code and License 7 votes vote down vote up
private static final void checkIteratorText(AttributedCharacterIterator iterator, String expectedText) throws Exception {
    if (iterator.getEndIndex() - iterator.getBeginIndex() != expectedText.length()) {
        throwException(iterator, "text length doesn't match between original text and iterator");
    }

    char c = iterator.first();
    for (int i = 0; i < expectedText.length(); i++) {
        if (c != expectedText.charAt(i)) {
            throwException(iterator, "text content doesn't match between original text and iterator");
        }
        c = iterator.next();
    }
    if (c != CharacterIterator.DONE) {
        throwException(iterator, "iterator text doesn't end with DONE");
    }
}
 
Example 5
Project: Equella   File: FlatterSpinnerUI.java   Source Code and License 7 votes vote down vote up
/**
 * Selects the passed in field, returning true if it is found, false
 * otherwise.
 */
private boolean select(JFormattedTextField ftf, AttributedCharacterIterator iterator, DateFormat.Field field)
{
	int max = ftf.getDocument().getLength();

	iterator.first();
	do
	{
		Map<Attribute, Object> attrs = iterator.getAttributes();

		if( attrs != null && attrs.containsKey(field) )
		{
			int start = iterator.getRunStart(field);
			int end = iterator.getRunLimit(field);

			if( start != -1 && end != -1 && start <= max && end <= max )
			{
				ftf.select(start, end);
			}
			return true;
		}
	}
	while( iterator.next() != CharacterIterator.DONE );
	return false;
}
 
Example 6
Project: openjdk-jdk10   File: SwingUtilities2.java   Source Code and License 7 votes vote down vote up
private static AttributedCharacterIterator getTrimmedTrailingSpacesIterator
        (AttributedCharacterIterator iterator) {
    int curIdx = iterator.getIndex();

    char c = iterator.last();
    while(c != CharacterIterator.DONE && Character.isWhitespace(c)) {
        c = iterator.previous();
    }

    if (c != CharacterIterator.DONE) {
        int endIdx = iterator.getIndex();

        if (endIdx == iterator.getEndIndex() - 1) {
            iterator.setIndex(curIdx);
            return iterator;
        } else {
            AttributedString trimmedText = new AttributedString(iterator,
                    iterator.getBeginIndex(), endIdx + 1);
            return trimmedText.getIterator();
        }
    } else {
        return null;
    }
}
 
Example 7
Project: openjdk-jdk10   File: TextLine.java   Source Code and License 7 votes vote down vote up
static Font getFontAtCurrentPos(AttributedCharacterIterator aci) {

        Object value = aci.getAttribute(TextAttribute.FONT);
        if (value != null) {
            return (Font) value;
        }
        if (aci.getAttribute(TextAttribute.FAMILY) != null) {
            return Font.getFont(aci.getAttributes());
        }

        int ch = CodePointIterator.create(aci).next();
        if (ch != CodePointIterator.DONE) {
            FontResolver resolver = FontResolver.getInstance();
            return resolver.getFont(resolver.getFontIndex(ch), aci.getAttributes());
        }
        return null;
    }
 
Example 8
Project: incubator-netbeans   File: AttributedCharacters.java   Source Code and License 6 votes vote down vote up
public Object getAttribute(AttributedCharacterIterator.Attribute att) {
    if (att == TextAttribute.FONT) {
        return fonts[getIndex()];
    } else if (att == TextAttribute.FOREGROUND) {
        return colors[getIndex()];
    } else {
        return null;
    }
}
 
Example 9
Project: incubator-netbeans   File: AttributedCharacters.java   Source Code and License 6 votes vote down vote up
public Map<AttributedCharacterIterator.Attribute,Object> getAttributes() {
    Map<AttributedCharacterIterator.Attribute,Object> m = new HashMap<AttributedCharacterIterator.Attribute,Object>(1);
    m.put(TextAttribute.FONT, fonts[getIndex()]);
    m.put(TextAttribute.FOREGROUND, colors[getIndex()]);

    return m;
}
 
Example 10
Project: incubator-netbeans   File: AttributedCharacters.java   Source Code and License 6 votes vote down vote up
public int getRunLimit(AttributedCharacterIterator.Attribute att) {
    if ((att != TextAttribute.FONT) && (att != TextAttribute.FOREGROUND)) {
        return getEndIndex(); // undefined attribute
    }

    return getRunLimit();
}
 
Example 11
Project: openjdk-jdk10   File: TextLine.java   Source Code and License 6 votes vote down vote up
/**
 * Create a TextLine from the text.  chars is just the text in the iterator.
 */
public static TextLine standardCreateTextLine(FontRenderContext frc,
                                              AttributedCharacterIterator text,
                                              char[] chars,
                                              float[] baselineOffsets) {

    StyledParagraph styledParagraph = new StyledParagraph(text, chars);
    Bidi bidi = new Bidi(text);
    if (bidi.isLeftToRight()) {
        bidi = null;
    }
    int layoutFlags = 0; // no extra info yet, bidi determines run and line direction
    TextLabelFactory factory = new TextLabelFactory(frc, chars, bidi, layoutFlags);

    boolean isDirectionLTR = true;
    if (bidi != null) {
        isDirectionLTR = bidi.baseIsLeftToRight();
    }
    return createLineFromText(chars, styledParagraph, factory, isDirectionLTR, baselineOffsets);
}
 
Example 12
Project: incubator-netbeans   File: ComponentLine.java   Source Code and License 6 votes vote down vote up
ComponentLine(AttributedCharacterIterator it, Font defaultFont, Color defaultColor) {
    for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
        Font font = (Font) it.getAttribute(TextAttribute.FONT);
        Color color = (Color) it.getAttribute(TextAttribute.FOREGROUND);
        mySymbols.add(new Symbol(c, createFont(font, defaultFont), createColor(color, defaultColor)));
    }
    checkSpaces(defaultFont, defaultColor);
}
 
Example 13
Project: jdk8u-jdk   File: TextLayoutStrategy.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the index of the first character following the run
 * with respect to the given attribute containing the current character.
 */
public int getRunLimit(AttributedCharacterIterator.Attribute attribute) {
    if (attribute instanceof TextAttribute) {
        int pos = toModelPosition(getIndex());
        int i = v.getViewIndex(pos, Position.Bias.Forward);
        if (attribute == TextAttribute.FONT) {
            return toIteratorIndex(getFontBoundary(i, 1));
        }
    }
    return getEndIndex();
}
 
Example 14
Project: openjdk-jdk10   File: TextLine.java   Source Code and License 6 votes vote down vote up
/**
 * When this returns, the ACI's current position will be at the start of the
 * first run which does NOT contain a GraphicAttribute.  If no such run exists
 * the ACI's position will be at the end, and this method will return false.
 */
static boolean advanceToFirstFont(AttributedCharacterIterator aci) {

    for (char ch = aci.first();
         ch != CharacterIterator.DONE;
         ch = aci.setIndex(aci.getRunLimit()))
    {

        if (aci.getAttribute(TextAttribute.CHAR_REPLACEMENT) == null) {
            return true;
        }
    }

    return false;
}
 
Example 15
Project: incubator-netbeans   File: ComposedTextHighlighting.java   Source Code and License 6 votes vote down vote up
private AttributeSet translateAttributes(Map<AttributedCharacterIterator.Attribute, ?> source) {
    for(AttributedCharacterIterator.Attribute sourceKey : source.keySet()) {
        Object sourceValue = source.get(sourceKey);
        
        // Ignore any non-input method related highlights
        if (!(sourceValue instanceof InputMethodHighlight)) {
            continue;
        }
        
        InputMethodHighlight imh = (InputMethodHighlight) sourceValue;
        
        if (imh.isSelected()) {
            return highlightInverse;
        } else {
            return highlightUnderlined;
        }
    }
    
    LOG.fine("No translation for " + source);
    return SimpleAttributeSet.EMPTY;
}
 
Example 16
Project: Telejam   File: Text.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> List<Map.Entry<String, T>> getEntitiesWithValues(TextEntity entity) {
  AttributedCharacterIterator iterator = getIterator();
  List<Map.Entry<String, T>> entities = new ArrayList<>();
  StringBuilder builder = new StringBuilder();

  Map<AttributedCharacterIterator.Attribute, T> last = Collections.emptyMap();
  while (iterator.getIndex() != iterator.getEndIndex()) {
    Map<AttributedCharacterIterator.Attribute, T> curr =
        (Map<AttributedCharacterIterator.Attribute, T>) iterator.getAttributes();
    if (curr.containsKey(entity)) {
      builder.append(iterator.current());
    } else {
      if (last.containsKey(entity)) {
        entities.add(
            new AbstractMap.SimpleImmutableEntry<>(builder.toString(), last.get(entity))
        );
        builder.setLength(0);
      }
    }
    last = curr;

    iterator.next();
  }
  if (last.containsKey(entity)) {
    entities.add(
        new AbstractMap.SimpleImmutableEntry<>(builder.toString(), last.get(entity))
    );
  }

  return entities;
}
 
Example 17
Project: openjdk-jdk10   File: TextLayout.java   Source Code and License 6 votes vote down vote up
/**
 * Constructs a {@code TextLayout} from an iterator over styled text.
 * <p>
 * The iterator must specify a single paragraph of text because an
 * entire paragraph is required for the bidirectional
 * algorithm.
 * @param text the styled text to display
 * @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} and user space.
 */
public TextLayout(AttributedCharacterIterator text, FontRenderContext frc) {

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

    int start = text.getBeginIndex();
    int limit = text.getEndIndex();
    if (start == limit) {
        throw new IllegalArgumentException("Zero length iterator passed to TextLayout constructor.");
    }

    int len = limit - start;
    text.first();
    char[] chars = new char[len];
    int n = 0;
    for (char c = text.first();
         c != CharacterIterator.DONE;
         c = text.next())
    {
        chars[n++] = c;
    }

    text.first();
    if (text.getRunLimit() == limit) {

        Map<? extends Attribute, ?> attributes = text.getAttributes();
        Font font = singleFont(chars, 0, len, attributes);
        if (font != null) {
            fastInit(chars, font, attributes, frc);
            return;
        }
    }

    standardInit(text, chars, frc);
}
 
Example 18
Project: brModelo   File: DesenhadorDeTexto.java   Source Code and License 6 votes vote down vote up
private LineBreakMeasurer[] getLineBreakMeasurers(Graphics2D g) {
    if (lbmTexto == null && (Texto != null && !Texto.equals(""))) {
        lbmTexto = new LineBreakMeasurer[Textos.length];
        for (int i = 0; i < lbmTexto.length; i++) {
            String tmp = Textos[i].isEmpty()? " " : Textos[i];
            AttributedString attribString = new AttributedString(tmp);
            attribString.addAttribute(TextAttribute.FONT, getFont());
            //attribString.addAttribute(TextAttribute.FONT, getFont());
            AttributedCharacterIterator attribCharIterator = attribString.getIterator();
            //FontRenderContext frc = new FontRenderContext(null, true, false);
            FontRenderContext frc = g.getFontRenderContext();
            lbmTexto[i] = new LineBreakMeasurer(attribCharIterator, frc);
        }
    }
    return lbmTexto;
}
 
Example 19
Project: fitnotifications   File: ScientificNumberFormatter.java   Source Code and License 6 votes vote down vote up
static void append(
        AttributedCharacterIterator iterator,
        int start,
        int limit,
        StringBuilder result) {
    int oldIndex = iterator.getIndex();
    iterator.setIndex(start);
    for (int i = start; i < limit; i++) {
        result.append(iterator.current());
        iterator.next();
    }
    iterator.setIndex(oldIndex);
}
 
Example 20
Project: fitnotifications   File: ScientificNumberFormatter.java   Source Code and License 6 votes vote down vote up
@Override
String format(
        AttributedCharacterIterator iterator,
        String preExponent) {
    int copyFromOffset = 0;
    StringBuilder result = new StringBuilder();
    for (
            iterator.first();
            iterator.current() != CharacterIterator.DONE;
        ) {
        Map<Attribute, Object> attributeSet = iterator.getAttributes();
        if (attributeSet.containsKey(NumberFormat.Field.EXPONENT_SYMBOL)) {
            append(
                    iterator,
                    copyFromOffset,
                    iterator.getRunStart(NumberFormat.Field.EXPONENT_SYMBOL),
                    result);
            copyFromOffset = iterator.getRunLimit(NumberFormat.Field.EXPONENT_SYMBOL);
            iterator.setIndex(copyFromOffset);
            result.append(preExponent);
            result.append(beginMarkup);
        } else if (attributeSet.containsKey(NumberFormat.Field.EXPONENT)) {
            int limit = iterator.getRunLimit(NumberFormat.Field.EXPONENT);
            append(
                    iterator,
                    copyFromOffset,
                    limit,
                    result);
            copyFromOffset = limit;
            iterator.setIndex(copyFromOffset);
            result.append(endMarkup);
        } else {
            iterator.next();
        }
    }
    append(iterator, copyFromOffset, iterator.getEndIndex(), result);
    return result.toString();
}
 
Example 21
Project: fitnotifications   File: ScientificNumberFormatter.java   Source Code and License 6 votes vote down vote up
private static void copyAsSuperscript(
        AttributedCharacterIterator iterator, int start, int limit, StringBuilder result) {
    int oldIndex = iterator.getIndex();
    iterator.setIndex(start);
    while (iterator.getIndex() < limit) {
        int aChar = char32AtAndAdvance(iterator);
        int digit = UCharacter.digit(aChar);
        if (digit < 0) {
            throw new IllegalArgumentException();
        }
        result.append(SUPERSCRIPT_DIGITS[digit]);
    }
    iterator.setIndex(oldIndex);
}
 
Example 22
Project: fitnotifications   File: TimeZoneFormat.java   Source Code and License 6 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @stable ICU 49
 */
@Override
public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
    StringBuffer toAppendTo = new StringBuffer();
    FieldPosition pos = new FieldPosition(0);
    toAppendTo = format(obj, toAppendTo, pos);

    // supporting only DateFormat.Field.TIME_ZONE
    AttributedString as = new AttributedString(toAppendTo.toString());
    as.addAttribute(DateFormat.Field.TIME_ZONE, DateFormat.Field.TIME_ZONE);

    return as.getIterator();
}
 
Example 23
Project: pdfbox-graphics2d   File: PdfBoxGraphics2D.java   Source Code and License 6 votes vote down vote up
private void drawStringUsingShapes(AttributedCharacterIterator iterator, float x, float y) {
	Stroke originalStroke = stroke;
	Paint originalPaint = paint;
	TextLayout textLayout = new TextLayout(iterator, getFontRenderContext());
	textLayout.draw(this, x, y);
	paint = originalPaint;
	stroke = originalStroke;
}
 
Example 24
Project: OpenJSharp   File: TextLine.java   Source Code and License 6 votes vote down vote up
/**
 * When this returns, the ACI's current position will be at the start of the
 * first run which does NOT contain a GraphicAttribute.  If no such run exists
 * the ACI's position will be at the end, and this method will return false.
 */
static boolean advanceToFirstFont(AttributedCharacterIterator aci) {

    for (char ch = aci.first();
         ch != CharacterIterator.DONE;
         ch = aci.setIndex(aci.getRunLimit()))
    {

        if (aci.getAttribute(TextAttribute.CHAR_REPLACEMENT) == null) {
            return true;
        }
    }

    return false;
}
 
Example 25
Project: openjdk-jdk10   File: BidiBase.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("serial")
private static AttributedCharacterIterator.Attribute
    getTextAttribute(String name)
{
    if (jafa == null) {
        // fake attribute
        return new AttributedCharacterIterator.Attribute(name) { };
    } else {
        return (AttributedCharacterIterator.Attribute)jafa.getTextAttributeConstant(name);
    }
}
 
Example 26
Project: OpenJSharp   File: SunGraphics2D.java   Source Code and License 6 votes vote down vote up
public void drawString(AttributedCharacterIterator iterator,
                       float x, float y) {
    if (iterator == null) {
        throw new NullPointerException("AttributedCharacterIterator is null");
    }
    if (iterator.getBeginIndex() == iterator.getEndIndex()) {
        return; /* nothing to draw */
    }
    TextLayout tl = new TextLayout(iterator, getFontRenderContext());
    tl.draw(this, x, y);
}
 
Example 27
Project: openjdk-jdk10   File: InputMethodContext.java   Source Code and License 6 votes vote down vote up
public void dispatchInputMethodEvent(int id,
            AttributedCharacterIterator text, int committedCharacterCount,
            TextHitInfo caret, TextHitInfo visiblePosition) {
    // We need to record the client component as the source so
    // that we have correct information if we later have to break up this
    // event into key events.
    Component source;

    source = getClientComponent();
    if (source != null) {
        InputMethodEvent event = new InputMethodEvent(source,
                id, text, committedCharacterCount, caret, visiblePosition);

        if (haveActiveClient() && !useBelowTheSpotInput()) {
            source.dispatchEvent(event);
        } else {
            getCompositionAreaHandler(true).processInputMethodEvent(event);
        }
    }
}
 
Example 28
Project: openjdk-jdk10   File: AttributedStringTest.java   Source Code and License 6 votes vote down vote up
private static final void checkIteratorSubranges(AttributedCharacterIterator iterator, Attribute key, int[] expectedLimits) throws Exception {
    int previous = 0;
    char c = iterator.first();
    for (int i = 0; i < expectedLimits.length; i++) {
         if (iterator.getRunStart(key) != previous || iterator.getRunLimit(key) != expectedLimits[i]) {
             throwException(iterator, "run boundaries are not as expected: " + iterator.getRunStart(key) + ", " + iterator.getRunLimit(key) + " for key " + key);
         }
         previous = expectedLimits[i];
         c = iterator.setIndex(previous);
    }
    if (c != CharacterIterator.DONE) {
        throwException(iterator, "iterator's run sequence doesn't end with DONE");
    }
}
 
Example 29
Project: OpenJSharp   File: InputMethodContext.java   Source Code and License 6 votes vote down vote up
public void dispatchInputMethodEvent(int id,
            AttributedCharacterIterator text, int committedCharacterCount,
            TextHitInfo caret, TextHitInfo visiblePosition) {
    // We need to record the client component as the source so
    // that we have correct information if we later have to break up this
    // event into key events.
    Component source;

    source = getClientComponent();
    if (source != null) {
        InputMethodEvent event = new InputMethodEvent(source,
                id, text, committedCharacterCount, caret, visiblePosition);

        if (haveActiveClient() && !useBelowTheSpotInput()) {
            source.dispatchEvent(event);
        } else {
            getCompositionAreaHandler(true).processInputMethodEvent(event);
        }
    }
}
 
Example 30
Project: FreeCol   File: FreeColToolTipUI.java   Source Code and License 6 votes vote down vote up
@Override
public Dimension getPreferredSize(JComponent c) {
    String tipText = ((JToolTip)c).getTipText();
    if (tipText == null || tipText.isEmpty()) {
        return new Dimension(0, 0);
    }

    float x = 0f;
    float y = 0f;
    for (String line : lineBreak.split(tipText)) {
        if (line.isEmpty()) {
            y += LEADING;
            continue;
        }
        AttributedCharacterIterator styledText
            = new AttributedString(line).getIterator();
        LineBreakMeasurer measurer = new LineBreakMeasurer(styledText, frc);

        while (measurer.getPosition() < styledText.getEndIndex()) {

            TextLayout layout = measurer.nextLayout(maximumWidth);

            x = Math.max(x, layout.getVisibleAdvance());
            y += layout.getAscent() + layout.getDescent() + layout.getLeading();

        }
    }
    return new Dimension((int) (x + 2 * margin),
                         (int) (y + 2 * margin));

}
 
Example 31
Project: jdk8u-jdk   File: PathGraphics.java   Source Code and License 5 votes vote down vote up
public void drawString(AttributedCharacterIterator iterator,
                       float x, float y) {
    if (iterator == null) {
        throw
            new NullPointerException("attributedcharacteriterator is null");
    }
    TextLayout layout =
        new TextLayout(iterator, getFontRenderContext());
    layout.draw(this, x, y);
}
 
Example 32
Project: incubator-netbeans   File: AttributedCharacters.java   Source Code and License 5 votes vote down vote up
public Set<AttributedCharacterIterator.Attribute> getAllAttributeKeys() {
    if (singleton == null) {
        Set<AttributedCharacterIterator.Attribute> l = new HashSet<AttributedCharacterIterator.Attribute>(4);
        l.add(TextAttribute.FONT);
        l.add(TextAttribute.FOREGROUND);
        singleton = Collections.unmodifiableSet(l);
    }

    return singleton;
}
 
Example 33
Project: incubator-netbeans   File: AttributedCharacters.java   Source Code and License 5 votes vote down vote up
public int getRunStart(AttributedCharacterIterator.Attribute att) {
    if ((att != TextAttribute.FONT) && (att != TextAttribute.FOREGROUND)) {
        return 0; // undefined attribute
    }

    return getRunStart();
}
 
Example 34
Project: incubator-netbeans   File: Editor.java   Source Code and License 5 votes vote down vote up
AttributedCharacterIterator[] getIterators() {
    AttributedCharacterIterator[] iterators = new AttributedCharacterIterator[myCharactersList.size()];

    for (int i = 0; i < myCharactersList.size(); i++) {
        iterators[i] = myCharactersList.get(i).iterator();
    }
    return iterators;
}
 
Example 35
Project: incubator-netbeans   File: NbEditorDocument.java   Source Code and License 5 votes vote down vote up
public AttributedCharacterIterator[] getIterators() {
    int cnt = acl.size();
    AttributedCharacterIterator[] acis = new AttributedCharacterIterator[cnt];
    for (int i = 0; i < cnt; i++) {
        AttributedCharacters ac = (AttributedCharacters)acl.get(i);
        acis[i] = ac.iterator();
    }
    return acis;
}
 
Example 36
Project: openjdk-jdk10   File: StyledParagraph.java   Source Code and License 5 votes vote down vote up
/**
 * Return a StyledParagraph reflecting the insertion of a single character
 * into the text.  This method will attempt to reuse the given paragraph,
 * but may create a new paragraph.
 * @param aci an iterator over the text.  The text should be the same as the
 *     text used to create (or most recently update) oldParagraph, with
 *     the exception of inserting a single character at insertPos.
 * @param chars the characters in aci
 * @param insertPos the index of the new character in aci
 * @param oldParagraph a StyledParagraph for the text in aci before the
 *     insertion
 */
public static StyledParagraph insertChar(AttributedCharacterIterator aci,
                                         char[] chars,
                                         int insertPos,
                                         StyledParagraph oldParagraph) {

    // If the styles at insertPos match those at insertPos-1,
    // oldParagraph will be reused.  Otherwise we create a new
    // paragraph.

    char ch = aci.setIndex(insertPos);
    int relativePos = Math.max(insertPos - aci.getBeginIndex() - 1, 0);

    Map<? extends Attribute, ?> attributes =
        addInputMethodAttrs(aci.getAttributes());
    Decoration d = Decoration.getDecoration(attributes);
    if (!oldParagraph.getDecorationAt(relativePos).equals(d)) {
        return new StyledParagraph(aci, chars);
    }
    Object f = getGraphicOrFont(attributes);
    if (f == null) {
        FontResolver resolver = FontResolver.getInstance();
        int fontIndex = resolver.getFontIndex(ch);
        f = resolver.getFont(fontIndex, attributes);
    }
    if (!oldParagraph.getFontOrGraphicAt(relativePos).equals(f)) {
        return new StyledParagraph(aci, chars);
    }

    // insert into existing paragraph
    oldParagraph.length += 1;
    if (oldParagraph.decorations != null) {
        insertInto(relativePos,
                   oldParagraph.decorationStarts,
                   oldParagraph.decorations.size());
    }
    if (oldParagraph.fonts != null) {
        insertInto(relativePos,
                   oldParagraph.fontStarts,
                   oldParagraph.fonts.size());
    }
    return oldParagraph;
}
 
Example 37
Project: openjdk-jdk10   File: StyledParagraph.java   Source Code and License 5 votes vote down vote up
/**
 * Create a new StyledParagraph over the given styled text.
 * @param aci an iterator over the text
 * @param chars the characters extracted from aci
 */
public StyledParagraph(AttributedCharacterIterator aci,
                       char[] chars) {

    int start = aci.getBeginIndex();
    int end = aci.getEndIndex();
    length = end - start;

    int index = start;
    aci.first();

    do {
        final int nextRunStart = aci.getRunLimit();
        final int localIndex = index-start;

        Map<? extends Attribute, ?> attributes = aci.getAttributes();
        attributes = addInputMethodAttrs(attributes);
        Decoration d = Decoration.getDecoration(attributes);
        addDecoration(d, localIndex);

        Object f = getGraphicOrFont(attributes);
        if (f == null) {
            addFonts(chars, attributes, localIndex, nextRunStart-start);
        }
        else {
            addFont(f, localIndex);
        }

        aci.setIndex(nextRunStart);
        index = nextRunStart;

    } while (index < end);

    // Add extra entries to starts arrays with the length
    // of the paragraph.  'this' is used as a dummy value
    // in the Vector.
    if (decorations != null) {
        decorationStarts = addToVector(this, length, decorations, decorationStarts);
    }
    if (fonts != null) {
        fontStarts = addToVector(this, length, fonts, fontStarts);
    }
}
 
Example 38
Project: jdk8u-jdk   File: CompositionAreaHandler.java   Source Code and License 5 votes vote down vote up
public AttributedCharacterIterator getSelectedText(Attribute[] attributes) {
    InputMethodRequests req = getClientInputMethodRequests();
    if(req != null) {
        return req.getSelectedText(attributes);
    }

    // we don't have access to the client component's text.
    return EMPTY_TEXT;
}
 
Example 39
Project: fitnotifications   File: DecimalFormat.java   Source Code and License 5 votes vote down vote up
AttributedCharacterIterator formatToCharacterIterator(Object obj, Unit unit) {
    if (!(obj instanceof Number))
        throw new IllegalArgumentException();
    Number number = (Number) obj;
    StringBuffer text = new StringBuffer();
    unit.writePrefix(text);
    attributes.clear();
    if (obj instanceof BigInteger) {
        format((BigInteger) number, text, new FieldPosition(0), true);
    } else if (obj instanceof java.math.BigDecimal) {
        format((java.math.BigDecimal) number, text, new FieldPosition(0)
                      , true);
    } else if (obj instanceof Double) {
        format(number.doubleValue(), text, new FieldPosition(0), true);
    } else if (obj instanceof Integer || obj instanceof Long) {
        format(number.longValue(), text, new FieldPosition(0), true);
    } else {
        throw new IllegalArgumentException();
    }
    unit.writeSuffix(text);
    AttributedString as = new AttributedString(text.toString());

    // add NumberFormat field attributes to the AttributedString
    for (int i = 0; i < attributes.size(); i++) {
        FieldPosition pos = attributes.get(i);
        Format.Field attribute = pos.getFieldAttribute();
        as.addAttribute(attribute, attribute, pos.getBeginIndex(), pos.getEndIndex());
    }

    // return the CharacterIterator from AttributedString
    return as.getIterator();
}
 
Example 40
Project: fitnotifications   File: MessageFormat.java   Source Code and License 5 votes vote down vote up
public void formatAndAppend(Format formatter, Object arg) {
    if (attributes == null) {
        append(formatter.format(arg));
    } else {
        AttributedCharacterIterator formattedArg = formatter.formatToCharacterIterator(arg);
        int prevLength = length;
        append(formattedArg);
        // Copy all of the attributes from formattedArg to our attributes list.
        formattedArg.first();
        int start = formattedArg.getIndex();  // Should be 0 but might not be.
        int limit = formattedArg.getEndIndex();  // == start + length - prevLength
        int offset = prevLength - start;  // Adjust attribute indexes for the result string.
        while (start < limit) {
            Map<Attribute, Object> map = formattedArg.getAttributes();
            int runLimit = formattedArg.getRunLimit();
            if (map.size() != 0) {
                for (Map.Entry<Attribute, Object> entry : map.entrySet()) {
                   attributes.add(
                       new AttributeAndPosition(
                           entry.getKey(), entry.getValue(),
                           offset + start, offset + runLimit));
                }
            }
            start = runLimit;
            formattedArg.setIndex(start);
        }
    }
}
 
Example 41
Project: jdk8u-jdk   File: LineBreakMeasurer.java   Source Code and License 5 votes vote down vote up
/**
 * Constructs a <code>LineBreakMeasurer</code> for the specified text.
 *
 * @param text the text for which this <code>LineBreakMeasurer</code>
 *     produces <code>TextLayout</code> objects; the text must contain
 *     at least one character; if the text available through
 *     <code>iter</code> changes, further calls to this
 *     <code>LineBreakMeasurer</code> instance are undefined (except,
 *     in some cases, when <code>insertChar</code> or
 *     <code>deleteChar</code> are invoked afterward - see below)
 * @param breakIter the {@link BreakIterator} which defines line
 *     breaks
 * @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>LineBreakMeasurer</code> and user space
 * @throws IllegalArgumentException if the text has less than one character
 * @see LineBreakMeasurer#insertChar
 * @see LineBreakMeasurer#deleteChar
 */
public LineBreakMeasurer(AttributedCharacterIterator text,
                         BreakIterator breakIter,
                         FontRenderContext frc) {
    if (text.getEndIndex() - text.getBeginIndex() < 1) {
        throw new IllegalArgumentException("Text must contain at least one character.");
    }

    this.breakIter = breakIter;
    this.measurer = new TextMeasurer(text, frc);
    this.limit = text.getEndIndex();
    this.pos = this.start = text.getBeginIndex();

    charIter = new CharArrayIterator(measurer.getChars(), this.start);
    this.breakIter.setText(charIter);
}
 
Example 42
Project: OpenJSharp   File: DebugGraphics.java   Source Code and License 5 votes vote down vote up
/**
 * Overrides <code>Graphics.drawString</code>.
 */
public void drawString(AttributedCharacterIterator iterator, int x, int y) {
    DebugGraphicsInfo info = info();

    if (debugLog()) {
        info().log(toShortString() +
                   " Drawing text: \"" + iterator +
                   "\" at: " + new Point(x, y));
    }

    if (isDrawingBuffer()) {
        if (debugBuffered()) {
            Graphics debugGraphics = debugGraphics();

            debugGraphics.drawString(iterator, x, y);
            debugGraphics.dispose();
        }
    } else if (debugFlash()) {
        Color oldColor = getColor();
        int i, count = (info.flashCount * 2) - 1;

        for (i = 0; i < count; i++) {
            graphics.setColor((i % 2) == 0 ? info.flashColor
                              : oldColor);
            graphics.drawString(iterator, x, y);
            Toolkit.getDefaultToolkit().sync();
            sleep(info.flashTime);
        }
        graphics.setColor(oldColor);
    }
    graphics.drawString(iterator, x, y);
}
 
Example 43
Project: Equella   File: FlatterSpinnerUI.java   Source Code and License 5 votes vote down vote up
/**
 * If the spinner's editor is a DateEditor, this selects the field
 * associated with the value that is being incremented.
 */
private void select(JSpinner spinner)
{
	JComponent editor = spinner.getEditor();

	if( editor instanceof JSpinner.DateEditor )
	{
		JSpinner.DateEditor dateEditor = (JSpinner.DateEditor) editor;
		JFormattedTextField ftf = dateEditor.getTextField();
		Format format = dateEditor.getFormat();
		Object value = spinner.getValue();

		if( format != null && value != null )
		{
			SpinnerDateModel model = dateEditor.getModel();
			DateFormat.Field field = DateFormat.Field.ofCalendarField(model.getCalendarField());

			if( field != null )
			{
				try
				{
					AttributedCharacterIterator iterator = format.formatToCharacterIterator(value);
					if( !select(ftf, iterator, field) && field == DateFormat.Field.HOUR0 )
					{
						select(ftf, iterator, DateFormat.Field.HOUR1);
					}
				}
				catch( IllegalArgumentException iae )
				{
					// ??
				}
			}
		}
	}
}
 
Example 44
Project: lams   File: AbstractAttributedCharacterIteratorAttributeConverter.java   Source Code and License 5 votes vote down vote up
public AbstractAttributedCharacterIteratorAttributeConverter(final Class<? extends T> type) {
    super();
    if (!AttributedCharacterIterator.Attribute.class.isAssignableFrom(type)) {
        throw new IllegalArgumentException(type.getName()
            + " is not a "
            + AttributedCharacterIterator.Attribute.class.getName());
    }
    this.type = type;
    readResolve();
}
 
Example 45
Project: freecol   File: FreeColToolTipUI.java   Source Code and License 5 votes vote down vote up
@Override
public void paint(Graphics g, JComponent c) {
    if (c.isOpaque()) {
        ImageLibrary.drawTiledImage("image.background.FreeColToolTip", g, c, null);
    }

    g.setColor(Color.BLACK); // FIXME: find out why this is necessary

    Graphics2D graphics = (Graphics2D)g;
    float x = margin;
    float y = margin;
    for (String line : lineBreak.split(((JToolTip) c).getTipText())) {
        if (line.isEmpty()) {
            y += LEADING;
            continue;
        }
        AttributedCharacterIterator styledText =
            new AttributedString(line).getIterator();

        LineBreakMeasurer measurer = new LineBreakMeasurer(styledText, frc);

        while (measurer.getPosition() < styledText.getEndIndex()) {

            TextLayout layout = measurer.nextLayout(maximumWidth);

            y += (layout.getAscent());
            float dx = layout.isLeftToRight() ?
                0 : (maximumWidth - layout.getAdvance());

            layout.draw(graphics, x + dx, y);
            y += layout.getDescent() + layout.getLeading();
        }
    }
 }
 
Example 46
Project: pdfbox-graphics2d   File: PdfBoxGraphics2D.java   Source Code and License 5 votes vote down vote up
private void drawStringUsingText(AttributedCharacterIterator iterator, float x, float y) throws IOException,
		FontFormatException {
	contentStreamSaveState();

	AffineTransform tf = new AffineTransform(baseTransform);
	tf.concatenate(transform);
	tf.translate(x, y);
	contentStream.transform(new Matrix(tf));

	fontTextDrawer.drawText(iterator, fontDrawerEnv());

	contentStreamRestoreState();
}
 
Example 47
Project: openjdk-jdk10   File: CompositionAreaHandler.java   Source Code and License 5 votes vote down vote up
public AttributedCharacterIterator getCommittedText(int beginIndex,
                                                   int endIndex,
                                                   Attribute[] attributes) {
    InputMethodRequests req = getClientInputMethodRequests();
    if(req != null) {
        return req.getCommittedText(beginIndex, endIndex, attributes);
    }

    // we don't have access to the client component's text.
    return EMPTY_TEXT;
}
 
Example 48
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DFontTextDrawer.java   Source Code and License 5 votes vote down vote up
private boolean iterateRun(AttributedCharacterIterator iterator, StringBuilder sb) {
	sb.setLength(0);
	int charCount = iterator.getRunLimit() - iterator.getRunStart();
	while (charCount-- >= 0) {
		char c = iterator.current();
		iterator.next();
		if (c == AttributedCharacterIterator.DONE) {
			return false;
		} else {
			sb.append(c);
		}
	}
	return true;
}
 
Example 49
Project: FreeCol   File: FreeColToolTipUI.java   Source Code and License 5 votes vote down vote up
@Override
public void paint(Graphics g, JComponent c) {
    if (c.isOpaque()) {
        ImageLibrary.drawTiledImage("image.background.FreeColToolTip", g, c, null);
    }

    g.setColor(Color.BLACK); // FIXME: find out why this is necessary

    Graphics2D graphics = (Graphics2D)g;
    float x = margin;
    float y = margin;
    for (String line : lineBreak.split(((JToolTip) c).getTipText())) {
        if (line.isEmpty()) {
            y += LEADING;
            continue;
        }
        AttributedCharacterIterator styledText =
            new AttributedString(line).getIterator();

        LineBreakMeasurer measurer = new LineBreakMeasurer(styledText, frc);

        while (measurer.getPosition() < styledText.getEndIndex()) {

            TextLayout layout = measurer.nextLayout(maximumWidth);

            y += (layout.getAscent());
            float dx = layout.isLeftToRight() ?
                0 : (maximumWidth - layout.getAdvance());

            layout.draw(graphics, x + dx, y);
            y += layout.getDescent() + layout.getLeading();
        }
    }
 }
 
Example 50
Project: jdk8u-jdk   File: CompositionAreaHandler.java   Source Code and License 5 votes vote down vote up
public AttributedCharacterIterator cancelLatestCommittedText(Attribute[] attributes) {
    InputMethodRequests req = getClientInputMethodRequests();
    if(req != null) {
        return req.cancelLatestCommittedText(attributes);
    }

    // we don't have access to the client component's text.
    return null;
}
 
Example 51
Project: jdk8u-jdk   File: BidiBase.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("serial")
private static AttributedCharacterIterator.Attribute
    getTextAttribute(String name)
{
    if (clazz == null) {
        // fake attribute
        return new AttributedCharacterIterator.Attribute(name) { };
    } else {
        return (AttributedCharacterIterator.Attribute)getStaticField(clazz, name);
    }
}
 
Example 52
Project: OpenJSharp   File: StyledParagraph.java   Source Code and License 5 votes vote down vote up
/**
 * Return a StyledParagraph reflecting the insertion of a single character
 * into the text.  This method will attempt to reuse the given paragraph,
 * but may create a new paragraph.
 * @param aci an iterator over the text.  The text should be the same as the
 *     text used to create (or most recently update) oldParagraph, with
 *     the exception of deleting a single character at deletePos.
 * @param chars the characters in aci
 * @param deletePos the index where a character was removed
 * @param oldParagraph a StyledParagraph for the text in aci before the
 *     insertion
 */
public static StyledParagraph deleteChar(AttributedCharacterIterator aci,
                                         char[] chars,
                                         int deletePos,
                                         StyledParagraph oldParagraph) {

    // We will reuse oldParagraph unless there was a length-1 run
    // at deletePos.  We could do more work and check the individual
    // Font and Decoration runs, but we don't right now...
    deletePos -= aci.getBeginIndex();

    if (oldParagraph.decorations == null && oldParagraph.fonts == null) {
        oldParagraph.length -= 1;
        return oldParagraph;
    }

    if (oldParagraph.getRunLimit(deletePos) == deletePos+1) {
        if (deletePos == 0 || oldParagraph.getRunLimit(deletePos-1) == deletePos) {
            return new StyledParagraph(aci, chars);
        }
    }

    oldParagraph.length -= 1;
    if (oldParagraph.decorations != null) {
        deleteFrom(deletePos,
                   oldParagraph.decorationStarts,
                   oldParagraph.decorations.size());
    }
    if (oldParagraph.fonts != null) {
        deleteFrom(deletePos,
                   oldParagraph.fontStarts,
                   oldParagraph.fonts.size());
    }
    return oldParagraph;
}
 
Example 53
Project: openjdk-jdk10   File: getRunStartLimitTest.java   Source Code and License 5 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 54
Project: openjdk-jdk10   File: AttributedStringTest.java   Source Code and License 5 votes vote down vote up
private static final void checkIteratorAttributeKeys(AttributedCharacterIterator iterator, Attribute[] expectedKeys) throws Exception {
     Set iteratorKeys = iterator.getAllAttributeKeys();
     if (iteratorKeys.size() != expectedKeys.length) {
         throwException(iterator, "number of keys returned by iterator doesn't match expectation");
     }
     for (int i = 0; i < expectedKeys.length; i++) {
         if (!iteratorKeys.contains(expectedKeys[i])) {
             throwException(iterator, "expected key wasn't found in iterator's key set");
         }
     }
}
 
Example 55
Project: OpenJSharp   File: X11InputMethod.java   Source Code and License 5 votes vote down vote up
/**
 * Creates an input method event from the arguments given
 * and posts it on the AWT event queue. For arguments,
 * see InputMethodEvent. Called by input method.
 *
 * @see java.awt.event.InputMethodEvent#InputMethodEvent
 */
private void postInputMethodEvent(int id,
                                  AttributedCharacterIterator text,
                                  int committedCharacterCount,
                                  TextHitInfo caret,
                                  TextHitInfo visiblePosition,
                                  long when) {
    Component source = getClientComponent();
    if (source != null) {
        InputMethodEvent event = new InputMethodEvent(source,
            id, when, text, committedCharacterCount, caret, visiblePosition);
        SunToolkit.postEvent(SunToolkit.targetToAppContext(source), (AWTEvent)event);
    }
}
 
Example 56
Project: openjdk-jdk10   File: X11InputMethod.java   Source Code and License 5 votes vote down vote up
/**
 * Creates an input method event from the arguments given
 * and posts it on the AWT event queue. For arguments,
 * see InputMethodEvent. Called by input method.
 *
 * @see java.awt.event.InputMethodEvent#InputMethodEvent
 */
private void postInputMethodEvent(int id,
                                  AttributedCharacterIterator text,
                                  int committedCharacterCount,
                                  TextHitInfo caret,
                                  TextHitInfo visiblePosition,
                                  long when) {
    Component source = getClientComponent();
    if (source != null) {
        InputMethodEvent event = new InputMethodEvent(source,
            id, when, text, committedCharacterCount, caret, visiblePosition);
        SunToolkit.postEvent(SunToolkit.targetToAppContext(source), (AWTEvent)event);
    }
}
 
Example 57
Project: OpenJSharp   File: PathGraphics.java   Source Code and License 5 votes vote down vote up
public void drawString(AttributedCharacterIterator iterator,
                       float x, float y) {
    if (iterator == null) {
        throw
            new NullPointerException("attributedcharacteriterator is null");
    }
    TextLayout layout =
        new TextLayout(iterator, getFontRenderContext());
    layout.draw(this, x, y);
}
 
Example 58
Project: openjdk-jdk10   File: X11InputMethod.java   Source Code and License 5 votes vote down vote up
private void postInputMethodEvent(int id,
                                  AttributedCharacterIterator text,
                                  int committedCharacterCount,
                                  TextHitInfo caret,
                                  TextHitInfo visiblePosition) {
    postInputMethodEvent(id, text, committedCharacterCount,
                         caret, visiblePosition, EventQueue.getMostRecentEventTime());
}
 
Example 59
Project: openjdk-jdk10   File: DebugGraphics.java   Source Code and License 5 votes vote down vote up
/**
 * Overrides <code>Graphics.drawString</code>.
 */
public void drawString(AttributedCharacterIterator iterator, int x, int y) {
    DebugGraphicsInfo info = info();

    if (debugLog()) {
        info().log(toShortString() +
                   " Drawing text: \"" + iterator +
                   "\" at: " + new Point(x, y));
    }

    if (isDrawingBuffer()) {
        if (debugBuffered()) {
            Graphics debugGraphics = debugGraphics();

            debugGraphics.drawString(iterator, x, y);
            debugGraphics.dispose();
        }
    } else if (debugFlash()) {
        Color oldColor = getColor();
        int i, count = (info.flashCount * 2) - 1;

        for (i = 0; i < count; i++) {
            graphics.setColor((i % 2) == 0 ? info.flashColor
                              : oldColor);
            graphics.drawString(iterator, x, y);
            Toolkit.getDefaultToolkit().sync();
            sleep(info.flashTime);
        }
        graphics.setColor(oldColor);
    }
    graphics.drawString(iterator, x, y);
}
 
Example 60
Project: litiengine   File: SpeechBubble.java   Source Code and License 4 votes vote down vote up
private void createBubbleImage() {

    final BufferedImage img = ImageProcessing.getCompatibleImage(500, 500);
    final Graphics2D g = img.createGraphics();
    g.setFont(this.font);
    final int stringWidth = g.getFontMetrics().stringWidth(this.currentText);
    if (stringWidth < this.textBoxWidth) {
      this.textBoxWidth = stringWidth;
    }

    final FontRenderContext frc = g.getFontRenderContext();
    final AttributedString styledText = new AttributedString(this.currentText);
    styledText.addAttribute(TextAttribute.FONT, this.font);
    final AttributedCharacterIterator iterator = styledText.getIterator();
    final LineBreakMeasurer measurer = new LineBreakMeasurer(iterator, frc);
    measurer.setPosition(0);
    float y = 0;
    while (measurer.getPosition() < this.currentText.length()) {
      final TextLayout layout = measurer.nextLayout(this.textBoxWidth);
      y += layout.getAscent() + layout.getLeading() + 0.2;
    }

    final RoundRectangle2D bounds = new RoundRectangle2D.Double(0, 0, this.textBoxWidth + 2 * PADDING, y + 2 * PADDING, PADDING, PADDING);

    // Build a path
    final GeneralPath path = new GeneralPath();
    path.moveTo(bounds.getWidth() / 2.0 - TRIANGLE_SIZE / 2.0, bounds.getHeight());
    path.lineTo(bounds.getWidth() / 2.0, bounds.getHeight() + TRIANGLE_SIZE);
    path.lineTo(bounds.getWidth() / 2.0 + TRIANGLE_SIZE / 2.0, bounds.getHeight());
    path.closePath();

    final Area ar = new Area(bounds);
    ar.add(new Area(path));

    int width = ar.getBounds().width;
    this.height = ar.getBounds().height;
    g.setColor(SPEAK_BACKGROUNDCOLOR);
    g.fill(ar);

    g.setColor(SPEAK_BORDERCOLOR);
    g.draw(ar);
    g.dispose();

    this.bubble = ImageProcessing.crop(img, ImageProcessing.CROP_ALIGN_LEFT, ImageProcessing.CROP_VALIGN_TOP, width + 1, this.height + 1);
  }