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 AttributedString getComposedTextAttribute(DocumentEvent e) { if (e instanceof BaseDocumentEvent) { AttributeSet attribs = ((BaseDocumentEvent) e).getChangeAttributes(); if (attribs != null) { Object value = attribs.getAttribute(StyleConstants.ComposedTextAttribute); if (value instanceof AttributedString) { return (AttributedString) value; } } } return null; }
/** * {@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(); }
/** * Constructs a <code>TextLayout</code> from a <code>String</code> * and an attribute set. * <p> * All the text is styled using the provided attributes. * <p> * <code>string</code> must specify a single paragraph of text because an * entire paragraph is required for the bidirectional algorithm. * @param string the text to display * @param attributes the attributes used to style the text * @param frc contains information about a graphics device which is needed * to measure the text correctly. * Text measurements can vary slightly depending on the * device resolution, and attributes such as antialiasing. This * parameter does not specify a translation between the * <code>TextLayout</code> and user space. */ public TextLayout(String string, Map<? extends Attribute,?> attributes, FontRenderContext frc) { if (string == null) { throw new IllegalArgumentException("Null string passed to TextLayout constructor."); } if (attributes == null) { throw new IllegalArgumentException("Null map passed to TextLayout constructor."); } if (string.length() == 0) { throw new IllegalArgumentException("Zero length string passed to TextLayout constructor."); } char[] text = string.toCharArray(); Font font = singleFont(text, 0, text.length, attributes); if (font != null) { fastInit(text, font, attributes, frc); } else { AttributedString as = new AttributedString(string, attributes); standardInit(as.getIterator(), text, frc); } }
/** * Dispatches committed text from XIM to the awt event queue. This * method is invoked from the event handler in canvas.c in the * AWT Toolkit thread context and thus inside the AWT Lock. * @param str committed text * @param long when */ // NOTE: This method may be called by privileged threads. // This functionality is implemented in a package-private method // to insure that it cannot be overridden by client subclasses. // DO NOT INVOKE CLIENT CODE ON THIS THREAD! void dispatchCommittedText(String str, long when) { if (str == null) return; if (composedText == null) { AttributedString attrstr = new AttributedString(str); postInputMethodEvent(InputMethodEvent.INPUT_METHOD_TEXT_CHANGED, attrstr.getIterator(), str.length(), null, null, when); } else { // if there is composed text, wait until the preedit // callback is invoked. committedText = str; } }
/** * Flushes composed and committed text held in this context. * This method is invoked in the AWT Toolkit (X event loop) thread context * and thus inside the AWT Lock. */ // NOTE: This method may be called by privileged threads. // This functionality is implemented in a package-private method // to insure that it cannot be overridden by client subclasses. // DO NOT INVOKE CLIENT CODE ON THIS THREAD! void flushText() { String flush = (committedText != null ? committedText : ""); if (composedText != null) { flush += composedText.toString(); } if (!flush.equals("")) { AttributedString attrstr = new AttributedString(flush); postInputMethodEvent(InputMethodEvent.INPUT_METHOD_TEXT_CHANGED, attrstr.getIterator(), flush.length(), null, null, EventQueue.getMostRecentEventTime()); composedText = null; committedText = null; } }
/** * Gets a lazy list of raw data in frames with the given stream, starting at * this frame and extending backwards over previous frames. The data is * coloured according to time difference with a given time, and control * codes are coloured red and translated into a human-readable form. * @param relativeTime The time, relative to the start of the ttyrec, to * colour the data relative to. * @param stream The stream from which the raw data should be returned. * @return A lazy list of raw data from frames with the given stream. */ public Iterable<AttributedString> getRawDataIterator(final double relativeTime, final int stream) { return () -> new Iterator<AttributedString>() { int lastSeqNumber = seqNumber; public boolean hasNext() { return hasNextAnnotation( relativeTime, lastSeqNumber, stream); } public AttributedString next() { AttributedStringAndNumber asan = nextAnnotation( relativeTime, lastSeqNumber, stream); lastSeqNumber = asan.getN(); return asan.getA(); } public void remove() { throw new UnsupportedOperationException( "Attempt to modify an immutable list"); } }; }
/** * Constructs a {@code TextLayout} from a {@code String} * and an attribute set. * <p> * All the text is styled using the provided attributes. * <p> * {@code string} must specify a single paragraph of text because an * entire paragraph is required for the bidirectional algorithm. * @param string the text to display * @param attributes the attributes used to style the text * @param frc contains information about a graphics device which is needed * to measure the text correctly. * Text measurements can vary slightly depending on the * device resolution, and attributes such as antialiasing. This * parameter does not specify a translation between the * {@code TextLayout} and user space. */ public TextLayout(String string, Map<? extends Attribute,?> attributes, FontRenderContext frc) { if (string == null) { throw new IllegalArgumentException("Null string passed to TextLayout constructor."); } if (attributes == null) { throw new IllegalArgumentException("Null map passed to TextLayout constructor."); } if (string.length() == 0) { throw new IllegalArgumentException("Zero length string passed to TextLayout constructor."); } char[] text = string.toCharArray(); Font font = singleFont(text, 0, text.length, attributes); if (font != null) { fastInit(text, font, attributes, frc); } else { AttributedString as = new AttributedString(string, attributes); standardInit(as.getIterator(), text, frc); } }
/** * Dispatches committed text from XIM to the awt event queue. This * method is invoked from the event handler in canvas.c in the * AWT Toolkit thread context and thus inside the AWT Lock. * @param str committed text * @param when when */ // NOTE: This method may be called by privileged threads. // This functionality is implemented in a package-private method // to insure that it cannot be overridden by client subclasses. // DO NOT INVOKE CLIENT CODE ON THIS THREAD! void dispatchCommittedText(String str, long when) { if (str == null) return; if (composedText == null) { AttributedString attrstr = new AttributedString(str); postInputMethodEvent(InputMethodEvent.INPUT_METHOD_TEXT_CHANGED, attrstr.getIterator(), str.length(), null, null, when); } else { // if there is composed text, wait until the preedit // callback is invoked. committedText = str; } }
public static void main(String[] args) { // Create a new AttributedString with one attribute. Hashtable attributes = new Hashtable(); attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD); AttributedString origString = new AttributedString("Hello world.", attributes); // Create an iterator over part of the AttributedString. AttributedCharacterIterator iter = origString.getIterator(null, 4, 6); // Attempt to create a new AttributedString from the iterator. // This will throw IllegalArgumentException. AttributedString newString = new AttributedString(iter); // Without the exception this would get executed. System.out.println("DONE"); }
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; }
@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)); }
protected void dumpACIWord(AttributedString as) { if (as == null) return; StringBuffer chars = new StringBuffer(); StringBuffer brkStr = new StringBuffer(); AttributedCharacterIterator aci = as.getIterator(); AttributedCharacterIterator.Attribute WORD_LIMIT = TextLineBreaks.WORD_LIMIT; for (char ch = aci.current(); ch!=AttributedCharacterIterator.DONE; ch = aci.next()) { chars.append( ch ).append( ' ' ).append( ' ' ); int w = ((Integer)aci.getAttribute(WORD_LIMIT)).intValue(); brkStr.append( w ).append( ' ' ); if (w < 10) { // for small values append another ' ' brkStr.append( ' ' ); } } System.out.println( chars.toString() ); System.out.println( brkStr.toString() ); }
public void decorateAttributedString(Graphics2D g2, AttributedString attributedWord, ChangeableAttributedString newAttrString) { Color oldColor = g2.getColor(); Composite oldComp = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(alphaCompositeType)); for (int j = 0; j < attributedWord.getIterator().getEndIndex(); j++) { g2.setColor(holesColorGenerator.getNextColor()); Rectangle2D bounds = newAttrString.getBounds(j).getFrame(); double circleMaxSize = (double) bounds.getWidth() / 2; for (int i = 0; i < numberOfHolesPerGlyph.intValue(); i++) { double circleSize = circleMaxSize * (1 + myRandom.nextDouble()) / 2; double circlex = bounds.getMinX() + bounds.getWidth() * circleXRatio * myRandom.nextDouble(); double circley = bounds.getMinY() - bounds.getHeight() * circleYRatio * myRandom.nextDouble(); Ellipse2D circle = new Ellipse2D.Double(circlex, circley, circleSize, circleSize); g2.fill(circle); } } g2.setColor(oldColor); g2.setComposite(oldComp); }
/** * Creates a tick label for the specified value based on the current * tick unit (used for formatting the exponent). * * @param value the value. * * @return The label. * * @since 1.0.18 */ protected AttributedString createTickLabel(double value) { if (this.numberFormatOverride != null) { return new AttributedString( this.numberFormatOverride.format(value)); } else { String baseStr = this.baseSymbol; if (baseStr == null) { baseStr = this.baseFormatter.format(this.base); } double logy = calculateLog(value); String exponentStr = getTickUnit().valueToString(logy); AttributedString as = new AttributedString(baseStr + exponentStr); as.addAttributes(getTickLabelFont().getAttributes(), 0, (baseStr + exponentStr).length()); as.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER, baseStr.length(), baseStr.length() + exponentStr.length()); return as; } }
/** * @see com.octo.captcha.component.image.textpaster.AbstractTextPaster#pasteText(java.awt.image.BufferedImage, java.text.AttributedString) */ public BufferedImage pasteText(final BufferedImage background, final AttributedString attributedWord) throws CaptchaException { BufferedImage out = copyBackground(background); Graphics2D g2d = pasteBackgroundAndSetTextColor(out, background); g2d.setRenderingHints(renderingHints); g2d.translate(10, background.getHeight() / 2); AttributedCharacterIterator iterator = attributedWord.getIterator(); while (iterator.getIndex() != iterator.getEndIndex()) { AttributedString character = new AttributedString(String.valueOf(iterator.current())); character.addAttribute(TextAttribute.FONT, iterator.getAttribute(TextAttribute.FONT)); pasteCharacter(g2d, character); iterator.next(); } g2d.dispose(); return out; }
/** * Given an attributed string and the graphics environment it lives in, pull it apart into its components. * * @param g2 graphics * @param aString attributed String */ protected ChangeableAttributedString(Graphics2D g2, AttributedString aString, int kerning) { this.kerning = kerning; AttributedCharacterIterator iter = aString.getIterator(); int n = iter.getEndIndex(); aStrings = new AttributedString[n]; bounds = new Rectangle2D[n]; metrics = new LineMetrics[n]; for (int i = iter.getBeginIndex(); i < iter.getEndIndex(); i++) { iter.setIndex(i); aStrings[i] = new AttributedString(iter, i, i + 1); Font font = (Font) iter.getAttribute(TextAttribute.FONT); if (font != null) { g2.setFont(font); // needed for getFont, -and- getFontRenderContext } final FontRenderContext frc = g2.getFontRenderContext(); bounds[i] = g2.getFont().getStringBounds(iter, i, i + 1, frc); metrics[i] = g2.getFont().getLineMetrics((new Character(iter.current())).toString(), frc); } }
@NotNull @Override public AttributedCharacterIterator getCommittedText(int beginIndex, int endIndex, AttributedCharacterIterator.Attribute[] attributes) { int composedStartIndex = 0; int composedEndIndex = 0; if (composedText != null) { composedStartIndex = composedTextRange.getStartOffset(); composedEndIndex = composedTextRange.getEndOffset(); } String committed; if (beginIndex < composedStartIndex) { if (endIndex <= composedStartIndex) { committed = getText(beginIndex, endIndex - beginIndex); } else { int firstPartLength = composedStartIndex - beginIndex; committed = getText(beginIndex, firstPartLength) + getText(composedEndIndex, endIndex - beginIndex - firstPartLength); } } else { committed = getText(beginIndex + composedEndIndex - composedStartIndex, endIndex - beginIndex); } return new AttributedString(committed).getIterator(); }
/** * Tests the serialization of an {@link AttributedString}. */ public void testAttributedStringSerialization2() { AttributedString s1 = new AttributedString("ABC"); AttributedString s2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeAttributedString(s1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); s2 = SerialUtilities.readAttributedString(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(AttributedStringUtilities.equal(s1, s2)); }
/** * Tests the serialization of an {@link AttributedString}. */ public void testAttributedStringSerialization3() { AttributedString s1 = new AttributedString("ABC"); s1.addAttribute(TextAttribute.LANGUAGE, "English"); AttributedString s2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeAttributedString(s1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); s2 = SerialUtilities.readAttributedString(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(AttributedStringUtilities.equal(s1, s2)); }
protected void setAttributes(AttributedString string, AttributedCharacterIterator attributes, int stringOffset) { for (char c = attributes.first(); c != CharacterIterator.DONE; c = attributes.next()) { for (Iterator<Map.Entry<Attribute,Object>> it = attributes.getAttributes().entrySet().iterator(); it.hasNext();) { Map.Entry<Attribute,Object> attributeEntry = it.next(); AttributedCharacterIterator.Attribute attribute = attributeEntry.getKey(); if (attributes.getRunStart(attribute) == attributes.getIndex()) { Object attributeValue = attributeEntry.getValue(); string.addAttribute( attribute, attributeValue, attributes.getIndex() + stringOffset, attributes.getRunLimit(attribute) + stringOffset ); } } } }
/** * Draws a string such that the specified anchor point is aligned to the * given (x, y) location. * * @param text the text. * @param g2 the graphics device. * @param x the x coordinate (Java 2D). * @param y the y coordinate (Java 2D). * @param anchor the anchor location. * * @return The text bounds (adjusted for the text position). */ public static Rectangle2D drawAlignedString(String text, Graphics2D g2, float x, float y, TextAnchor anchor) { Rectangle2D textBounds = new Rectangle2D.Double(); float[] adjust = deriveTextBoundsAnchorOffsets(g2, text, anchor, textBounds); // adjust text bounds to match string position textBounds.setRect(x + adjust[0], y + adjust[1] + adjust[2], textBounds.getWidth(), textBounds.getHeight()); if (!drawStringsWithFontAttributes) { g2.drawString(text, x + adjust[0], y + adjust[1]); } else { AttributedString as = new AttributedString(text, g2.getFont().getAttributes()); g2.drawString(as.getIterator(), x + adjust[0], y + adjust[1]); } return textBounds; }
protected AttributedString getAttributedString(Graphics2D g2d, String sr, WMFFont wmffont) { AttributedString ats = new AttributedString(sr); Font font = g2d.getFont(); ats.addAttribute(TextAttribute.SIZE, new Float(font.getSize2D())); ats.addAttribute(TextAttribute.FONT, font); if (wmfFont.underline != 0) ats.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); if (wmfFont.italic != 0) ats.addAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE); else ats.addAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_REGULAR); if (wmfFont.weight > 400) ats.addAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD); else ats.addAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_REGULAR); return ats; }
/** * Draws the attributed string at {@code (textX, textY)}, rotated by * the specified angle about {@code (rotateX, rotateY)}. * * @param text the attributed string ({@code null} not permitted). * @param g2 the graphics output target. * @param textX the x-coordinate for the text. * @param textY the y-coordinate for the text. * @param angle the rotation angle (in radians). * @param rotateX the x-coordinate for the rotation point. * @param rotateY the y-coordinate for the rotation point. * * @since 1.0.16 */ public static void drawRotatedString(AttributedString text, Graphics2D g2, float textX, float textY, double angle, float rotateX, float rotateY) { Args.nullNotPermitted(text, "text"); AffineTransform saved = g2.getTransform(); AffineTransform rotate = AffineTransform.getRotateInstance(angle, rotateX, rotateY); g2.transform(rotate); TextLayout tl = new TextLayout(text.getIterator(), g2.getFontRenderContext()); tl.draw(g2, textX, textY); g2.setTransform(saved); }
protected void addChildPaintAttributes(AttributedString as, Element element, TextNode node, TextPaintInfo parentPI, BridgeContext ctx) { // Add Paint attributres for children of text element for (Node child = getFirstChild(element); child != null; child = getNextSibling(child)) { if (child.getNodeType() != Node.ELEMENT_NODE) { continue; } Element childElement = (Element)child; if (isTextChild(childElement)) { TextPaintInfo pi = getTextPaintInfo(childElement, node, parentPI, ctx); addPaintAttributes(as, childElement, node, pi, ctx); } } }
protected void addChildGlyphPositionAttributes(AttributedString as, Element element, BridgeContext ctx) { // Add Paint attributres for children of text element for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) { if (child.getNodeType() != Node.ELEMENT_NODE) { continue; } String cNS = child.getNamespaceURI(); if ((!getNamespaceURI().equals(cNS)) && (!SVG_NAMESPACE_URI.equals(cNS))) { continue; } String ln = child.getLocalName(); if (ln.equals(BATIK_EXT_FLOW_PARA_TAG) || ln.equals(BATIK_EXT_FLOW_REGION_BREAK_TAG) || ln.equals(BATIK_EXT_FLOW_LINE_TAG) || ln.equals(BATIK_EXT_FLOW_SPAN_TAG) || ln.equals(SVG_A_TAG) || ln.equals(SVG_TREF_TAG)) { addGlyphPositionAttributes(as, (Element)child, ctx); } } }
@Override public void render(final Graphics2D g) { if (this.displayedText == null || this.displayedText.isEmpty() || !Game.getRenderEngine().canRender(this.entity)) { return; } final Point2D location = Game.getCamera().getViewPortLocation(this.entity); RenderEngine.renderImage(g, this.bubble, new Point2D.Double(location.getX() + this.entity.getWidth() / 2.0 - this.textBoxWidth / 2.0 - PADDING, location.getY() - this.height - PADDING)); g.setColor(SPEAK_FONT_COLOR); final FontRenderContext frc = g.getFontRenderContext(); final String text = this.displayedText; final AttributedString styledText = new AttributedString(text); styledText.addAttribute(TextAttribute.FONT, this.font); final AttributedCharacterIterator iterator = styledText.getIterator(); final LineBreakMeasurer measurer = new LineBreakMeasurer(iterator, frc); measurer.setPosition(0); final float x = (float) Game.getCamera().getViewPortLocation(this.entity).getX() + this.entity.getWidth() / 2.0f - this.textBoxWidth / 2.0f; float y = (float) Game.getCamera().getViewPortLocation(this.entity).getY() - this.height; while (measurer.getPosition() < text.length()) { final TextLayout layout = measurer.nextLayout(this.textBoxWidth); y += layout.getAscent(); final float dx = layout.isLeftToRight() ? 0 : this.textBoxWidth - layout.getAdvance(); layout.draw(g, x + dx, y); y += layout.getDescent() + layout.getLeading(); } }
protected void drawStringToGraphics(Graphics g, String s, Font font, boolean strike) { if (g != null) { if (!strike){ g.drawString(s, drawX, drawY); }else{ Graphics2D g2 = ((Graphics2D)g); AttributedString strikeText = new AttributedString(s); strikeText.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON); strikeText.addAttribute(TextAttribute.FONT, g.getFont()); g2.drawString(strikeText.getIterator(), drawX, drawY); } } drawX += getWidth(s, font); }