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; }
@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); }
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; } }
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"); } }
/** * 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; }
public Object getAttribute(AttributedCharacterIterator.Attribute att) { if (att == TextAttribute.FONT) { return fonts[getIndex()]; } else if (att == TextAttribute.FOREGROUND) { return colors[getIndex()]; } else { return null; } }
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; }
public int getRunLimit(AttributedCharacterIterator.Attribute att) { if ((att != TextAttribute.FONT) && (att != TextAttribute.FOREGROUND)) { return getEndIndex(); // undefined attribute } return getRunLimit(); }
/** * 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); }
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); }
/** * 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(); }
/** * 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; }
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; }
@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; }
/** * 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); }
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; }
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); }
@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(); }
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); }
/** * {@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(); }
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; }
@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); } }
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); }
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); } } }
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"); } }
@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)); }
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); }
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; }
public int getRunStart(AttributedCharacterIterator.Attribute att) { if ((att != TextAttribute.FONT) && (att != TextAttribute.FOREGROUND)) { return 0; // undefined attribute } return getRunStart(); }
AttributedCharacterIterator[] getIterators() { AttributedCharacterIterator[] iterators = new AttributedCharacterIterator[myCharactersList.size()]; for (int i = 0; i < myCharactersList.size(); i++) { iterators[i] = myCharactersList.get(i).iterator(); } return iterators; }
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; }
/** * 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; }
/** * 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); } }
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; }
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(); }
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); } } }