Java Code Examples for java.text.AttributedCharacterIterator#getRunLimit()

The following examples show how to use java.text.AttributedCharacterIterator#getRunLimit() . 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: DateTimeFormatConstructor.java    From es6draft with MIT License 6 votes vote down vote up
/**
 * 12.1.6 PartitionDateTimePattern ( dateTimeFormat, x )
 * 
 * @param dateTimeFormat
 *            the date format object
 * @param date
 *            the date object
 * @return the formatted date-time object
 */
private static List<Map.Entry<String, String>> PartitionDateTimePattern(DateTimeFormatObject dateTimeFormat,
        Date date) {
    ArrayList<Map.Entry<String, String>> parts = new ArrayList<>();
    DateFormat dateFormat = dateTimeFormat.getDateFormat();
    AttributedCharacterIterator iterator = dateFormat.formatToCharacterIterator(date);
    StringBuilder sb = new StringBuilder();
    for (char ch = iterator.first(); ch != CharacterIterator.DONE; ch = iterator.next()) {
        sb.append(ch);
        if (iterator.getIndex() + 1 == iterator.getRunLimit()) {
            Iterator<Attribute> keyIterator = iterator.getAttributes().keySet().iterator();
            String key;
            if (keyIterator.hasNext()) {
                key = fieldToString((DateFormat.Field) keyIterator.next());
            } else {
                key = "literal";
            }
            String value = sb.toString();
            sb.setLength(0);
            parts.add(new AbstractMap.SimpleImmutableEntry<>(key, value));
        }
    }
    return parts;
}
 
Example 2
Source File: JRXlsExporter.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected HSSFRichTextString getRichTextString(JRStyledText styledText, short forecolor, JRFont defaultFont, Locale locale)
{
	String text = styledText.getText();
	HSSFRichTextString richTextStr = new HSSFRichTextString(text);
	int runLimit = 0;
	AttributedCharacterIterator iterator = styledText.getAttributedString().getIterator();

	while(runLimit < styledText.length() && (runLimit = iterator.getRunLimit()) <= styledText.length())
	{
		Map<Attribute,Object> attributes = iterator.getAttributes();
		JRFont runFont = attributes.isEmpty()? defaultFont : new JRBaseFont(attributes);
		short runForecolor = attributes.get(TextAttribute.FOREGROUND) != null ? 
				getWorkbookColor((Color)attributes.get(TextAttribute.FOREGROUND)).getIndex() :
				forecolor;
		HSSFFont font = getLoadedFont(runFont, runForecolor, attributes, locale);
		richTextStr.applyFont(iterator.getIndex(), runLimit, font);
		iterator.setIndex(runLimit);
	}
	return richTextStr;
}
 
Example 3
Source File: TextLayout.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs a <code>TextLayout</code> 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</code> 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 4
Source File: JRPdfExporter.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 *
 */
protected Phrase getPhrase(AttributedString as, String text, JRPrintText textElement)
{
	Phrase phrase = new Phrase();
	int runLimit = 0;

	AttributedCharacterIterator iterator = as.getIterator();
	Locale locale = getTextLocale(textElement);
	 
	boolean firstChunk = true;
	while(runLimit < text.length() && (runLimit = iterator.getRunLimit()) <= text.length())
	{
		Map<Attribute,Object> attributes = iterator.getAttributes();
		Chunk chunk = getChunk(attributes, text.substring(iterator.getIndex(), runLimit), locale);
		
		if (firstChunk)
		{
			// only set anchor + bookmark for the first chunk in the text
			setAnchor(chunk, textElement, textElement);
		}
		
		JRPrintHyperlink hyperlink = textElement;
		if (hyperlink.getHyperlinkTypeValue() == HyperlinkTypeEnum.NONE)
		{
			hyperlink = (JRPrintHyperlink)attributes.get(JRTextAttribute.HYPERLINK);
		}
		
		setHyperlinkInfo(chunk, hyperlink);
		phrase.add(chunk);

		iterator.setIndex(runLimit);
		firstChunk = false;
	}

	return phrase;
}
 
Example 5
Source File: NumberFormatConstructor.java    From es6draft with MIT License 5 votes vote down vote up
/**
 * PartitionNumberPattern(numberFormat, x)
 * 
 * @param numberFormatObj
 *            the number format object
 * @param x
 *            the number value
 * @return the formatted number object
 */
private static List<Map.Entry<String, String>> PartitionNumberPattern(NumberFormatObject numberFormat, double x) {
    if (x == -0.0) {
        // -0 is not considered to be negative, cf. step 3a
        x = +0.0;
    }
    ArrayList<Map.Entry<String, String>> parts = new ArrayList<>();
    NumberFormat numFormat = numberFormat.getNumberFormat();
    AttributedCharacterIterator iterator = numFormat.formatToCharacterIterator(x);
    StringBuilder sb = new StringBuilder();
    for (char ch = iterator.first(); ch != CharacterIterator.DONE; ch = iterator.next()) {
        sb.append(ch);
        if (iterator.getIndex() + 1 == iterator.getRunLimit()) {
            Iterator<Attribute> keyIterator = iterator.getAttributes().keySet().iterator();
            String key;
            if (keyIterator.hasNext()) {
                key = fieldToString((NumberFormat.Field) keyIterator.next(), x);
            } else {
                key = "literal";
            }
            String value = sb.toString();
            sb.setLength(0);
            parts.add(new AbstractMap.SimpleImmutableEntry<>(key, value));
        }
    }
    return parts;
}
 
Example 6
Source File: AttributedStringTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 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 7
Source File: AttributedStringTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static final void checkIteratorSubranges(AttributedCharacterIterator iterator, Set keys, int[] expectedLimits) throws Exception {
    int previous = 0;
    char c = iterator.first();
    for (int i = 0; i < expectedLimits.length; i++) {
         if (iterator.getRunStart(keys) != previous || iterator.getRunLimit(keys) != expectedLimits[i]) {
             throwException(iterator, "run boundaries are not as expected: " + iterator.getRunStart(keys) + ", " + iterator.getRunLimit(keys) + " for keys " + keys);
         }
         previous = expectedLimits[i];
         c = iterator.setIndex(previous);
    }
    if (c != CharacterIterator.DONE) {
        throwException(iterator, "iterator's run sequence doesn't end with DONE");
    }
}
 
Example 8
Source File: AttributedStringTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 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 9
Source File: AttributedStringSerializer.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Writes a serializable object description to the given object output stream.
 *
 * @param o      the to be serialized object.
 * @param stream the outputstream that should receive the object.
 * @throws IOException if an I/O error occured.
 */
public void writeObject( final Object o, final ObjectOutputStream stream ) throws IOException {
  final AttributedString as = (AttributedString) o;
  final AttributedCharacterIterator aci = as.getIterator();
  // build a plain string from aci
  // then write the string
  StringBuffer plainStr = new StringBuffer( 100 );
  char current = aci.first();
  while ( current != CharacterIterator.DONE ) {
    plainStr = plainStr.append( current );
    current = aci.next();
  }
  stream.writeObject( plainStr.toString() );

  // then write the attributes and limits for each run
  current = aci.first();
  final int begin = aci.getBeginIndex();
  while ( current != CharacterIterator.DONE ) {
    // write the current character - when the reader sees that this
    // is not CharacterIterator.DONE, it will know to read the
    // run limits and attributes
    stream.writeChar( current );

    // now write the limit, adjusted as if beginIndex is zero
    final int limit = aci.getRunLimit();
    stream.writeInt( limit - begin );

    // now write the attribute set
    final Map<AttributedCharacterIterator.Attribute, Object> atts =
      new HashMap<AttributedCharacterIterator.Attribute, Object>( aci.getAttributes() );
    stream.writeObject( atts );
    current = aci.setIndex( limit );
  }
  // write a character that signals to the reader that all runs
  // are done...
  stream.writeChar( CharacterIterator.DONE );

}
 
Example 10
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 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</code> 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 11
Source File: IMSC11ResourceConverterState.java    From ttt with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void populateText(Paragraph p, AttributedString as, boolean insertBreakBefore, Direction blockDirection) {
    if (as != null) {
        List<Serializable> content = p.getContent();
        if (insertBreakBefore)
            content.add(ttmlFactory.createBr(ttmlFactory.createBreak()));
        AttributedCharacterIterator aci = as.getIterator();
        aci.first();
        StringBuffer sb = new StringBuffer();
        while (aci.current() != CharacterIterator.DONE) {
            int i = aci.getRunStart();
            int e = aci.getRunLimit();
            Map<AttributedCharacterIterator.Attribute,Object> attributes = aci.getAttributes();
            while (i < e) {
                sb.append(aci.setIndex(i++));
            }
            String text = sb.toString();
            if (!text.isEmpty()) {
                if (!attributes.isEmpty()) {
                    populateAttributedText(content, text, attributes, blockDirection);
                } else {
                    content.add(text);
                }
            }
            sb.setLength(0);
            aci.setIndex(e);
        }
    }
}
 
Example 12
Source File: TranslatableComponentRenderer.java    From adventure with MIT License 5 votes vote down vote up
@Override
protected @NonNull Component renderTranslatable(final @NonNull TranslatableComponent component, final @NonNull C context) {
  final /* @Nullable */ MessageFormat format = this.translation(context, component.key());
  if(format == null) {
    return component;
  }

  final List<Component> args = component.args();

  final TextComponent.Builder builder = TextComponent.builder();
  this.mergeStyle(component, builder, context);

  // no arguments makes this render very simple
  if(args.isEmpty()) {
    return builder.content(format.format(null, new StringBuffer(), null).toString()).build();
  }

  final Object[] nulls = new Object[args.size()];
  final StringBuffer sb = format.format(nulls, new StringBuffer(), null);
  final AttributedCharacterIterator it = format.formatToCharacterIterator(nulls);

  while(it.getIndex() < it.getEndIndex()) {
    final int end = it.getRunLimit();
    final Integer index = (Integer) it.getAttribute(MessageFormat.Field.ARGUMENT);
    if(index != null) {
      builder.append(this.render(args.get(index), context));
    } else {
      builder.append(TextComponent.of(sb.substring(it.getIndex(), end)));
    }
    it.setIndex(end);
  }

  return this.deepRender(component, builder, context);
}
 
Example 13
Source File: AttributedStringTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static final void checkIteratorSubranges(AttributedCharacterIterator iterator, Set keys, int[] expectedLimits) throws Exception {
    int previous = 0;
    char c = iterator.first();
    for (int i = 0; i < expectedLimits.length; i++) {
         if (iterator.getRunStart(keys) != previous || iterator.getRunLimit(keys) != expectedLimits[i]) {
             throwException(iterator, "run boundaries are not as expected: " + iterator.getRunStart(keys) + ", " + iterator.getRunLimit(keys) + " for keys " + keys);
         }
         previous = expectedLimits[i];
         c = iterator.setIndex(previous);
    }
    if (c != CharacterIterator.DONE) {
        throwException(iterator, "iterator's run sequence doesn't end with DONE");
    }
}
 
Example 14
Source File: TextLayout.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * Constructs a <code>TextLayout</code> 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</code> 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 15
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 16
Source File: CDateTime.java    From nebula with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * This is the only way that text is set to the text box.<br>
 * The selection of the text in the text box is also set here (the active
 * field is selected) as well as if a field is being edited, it's "edit
 * text" is inserted for display. The <code>getSelection</code> property of
 * CDateTime remains unchanged.
 * 
 * @param async
 *            If true, this operation will be performed asynchronously (for
 *            changes to text selection)
 */
private void updateText(boolean async) {
	// TODO: save previous state and only update on changes...?

	String buffer = hasSelection() ? df.format(getSelection())
			: getNullText();

	int s0 = 0;
	int s1 = 0;

	if (!hasSelection()) {
		s0 = 0;
		s1 = buffer.length();
	} else if (activeField >= 0 && activeField < field.length) {
		AttributedCharacterIterator aci = df
				.formatToCharacterIterator(getSelection());
		for (char c = aci.first(); c != CharacterIterator.DONE; c = aci
				.next()) {
			if (aci.getAttribute(field[activeField]) != null) {
				s0 = aci.getRunStart();
				s1 = aci.getRunLimit();
				if (editField != null) {
					String str = editField.toString();
					buffer = buffer.substring(0, s0) + str
							+ buffer.substring(s1);
					int oldS1 = s1;
					s1 = s0 + str.length();
					textSelectionOffset.x = Math.min(oldS1, s1);
					textSelectionOffset.y = oldS1 - s0 - str.length();
				} else {
					textSelectionOffset.x = buffer.length() + 1;
					textSelectionOffset.y = 0;
				}
				break;
			}
		}
	} else {
		setActiveField(FIELD_NONE);
	}

	final String string = buffer;
	final int selStart = s0;
	final int selEnd = s1;

	Runnable runnable = () -> {
		if (text != null && !text.isDisposed()) {
			if (!string.equals(text.getText())) {
				text.getControl().removeListener(SWT.Verify, textListener);
				text.setText(string);
				text.getControl().addListener(SWT.Verify, textListener);
			}
			if ((text.getControl().getStyle() & SWT.READ_ONLY) == 0) {
				text.getControl().setSelection(selStart, selEnd);
			}
		}
	};

	if (async) {
		getDisplay().asyncExec(runnable);
	} else {
		getDisplay().syncExec(runnable);
	}
}
 
Example 17
Source File: SerialUtilities.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Serialises an <code>AttributedString</code> object.
 *
 * @param as  the attributed string object (<code>null</code> permitted).
 * @param stream  the output stream (<code>null</code> not permitted).
 *
 * @throws IOException if there is an I/O error.
 */
public static void writeAttributedString(AttributedString as,
        ObjectOutputStream stream) throws IOException {

    if (stream == null) {
        throw new IllegalArgumentException("Null 'stream' argument.");
    }
    if (as != null) {
        stream.writeBoolean(false);
        AttributedCharacterIterator aci = as.getIterator();
        // build a plain string from aci
        // then write the string
        StringBuffer plainStr = new StringBuffer();
        char current = aci.first();
        while (current != CharacterIterator.DONE) {
            plainStr = plainStr.append(current);
            current = aci.next();
        }
        stream.writeObject(plainStr.toString());

        // then write the attributes and limits for each run
        current = aci.first();
        int begin = aci.getBeginIndex();
        while (current != CharacterIterator.DONE) {
            // write the current character - when the reader sees that this
            // is not CharacterIterator.DONE, it will know to read the
            // run limits and attributes
            stream.writeChar(current);

            // now write the limit, adjusted as if beginIndex is zero
            int limit = aci.getRunLimit();
            stream.writeInt(limit - begin);

            // now write the attribute set
            Map atts = new HashMap(aci.getAttributes());
            stream.writeObject(atts);
            current = aci.setIndex(limit);
        }
        // write a character that signals to the reader that all runs
        // are done...
        stream.writeChar(CharacterIterator.DONE);
    }
    else {
        // write a flag that indicates a null
        stream.writeBoolean(true);
    }

}
 
Example 18
Source File: SerialUtilities.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Serialises an <code>AttributedString</code> object.
 *
 * @param as  the attributed string object (<code>null</code> permitted).
 * @param stream  the output stream (<code>null</code> not permitted).
 *
 * @throws IOException if there is an I/O error.
 */
public static void writeAttributedString(AttributedString as,
        ObjectOutputStream stream) throws IOException {

    if (stream == null) {
        throw new IllegalArgumentException("Null 'stream' argument.");
    }
    if (as != null) {
        stream.writeBoolean(false);
        AttributedCharacterIterator aci = as.getIterator();
        // build a plain string from aci
        // then write the string
        StringBuffer plainStr = new StringBuffer();
        char current = aci.first();
        while (current != CharacterIterator.DONE) {
            plainStr = plainStr.append(current);
            current = aci.next();
        }
        stream.writeObject(plainStr.toString());

        // then write the attributes and limits for each run
        current = aci.first();
        int begin = aci.getBeginIndex();
        while (current != CharacterIterator.DONE) {
            // write the current character - when the reader sees that this
            // is not CharacterIterator.DONE, it will know to read the
            // run limits and attributes
            stream.writeChar(current);

            // now write the limit, adjusted as if beginIndex is zero
            int limit = aci.getRunLimit();
            stream.writeInt(limit - begin);

            // now write the attribute set
            Map atts = new HashMap(aci.getAttributes());
            stream.writeObject(atts);
            current = aci.setIndex(limit);
        }
        // write a character that signals to the reader that all runs
        // are done...
        stream.writeChar(CharacterIterator.DONE);
    }
    else {
        // write a flag that indicates a null
        stream.writeBoolean(true);
    }

}
 
Example 19
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 20
Source File: StyledParagraph.java    From jdk1.8-source-analysis with Apache License 2.0 4 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);
    }
}