Search in sources :

Example 81 with AttributedString

use of java.text.AttributedString in project poi by apache.

the class DrawTextParagraph method getAttributedString.

protected AttributedString getAttributedString(Graphics2D graphics, StringBuilder text) {
    List<AttributedStringData> attList = new ArrayList<AttributedStringData>();
    if (text == null) {
        text = new StringBuilder();
    }
    PlaceableShape<?, ?> ps = getParagraphShape();
    DrawFontManager fontHandler = (DrawFontManager) graphics.getRenderingHint(Drawable.FONT_HANDLER);
    @SuppressWarnings("unchecked") Map<String, String> fontMap = (Map<String, String>) graphics.getRenderingHint(Drawable.FONT_MAP);
    @SuppressWarnings("unchecked") Map<String, String> fallbackMap = (Map<String, String>) graphics.getRenderingHint(Drawable.FONT_FALLBACK);
    for (TextRun run : paragraph) {
        String runText = getRenderableText(graphics, run);
        // skip empty runs
        if (runText.isEmpty()) {
            continue;
        }
        // user can pass an custom object to convert fonts
        String mappedFont = run.getFontFamily();
        String fallbackFont = Font.SANS_SERIF;
        if (mappedFont == null) {
            mappedFont = paragraph.getDefaultFontFamily();
        }
        if (mappedFont == null) {
            mappedFont = Font.SANS_SERIF;
        }
        if (fontHandler != null) {
            String font = fontHandler.getRendererableFont(mappedFont, run.getPitchAndFamily());
            if (font != null) {
                mappedFont = font;
            }
            font = fontHandler.getFallbackFont(mappedFont, run.getPitchAndFamily());
            if (font != null) {
                fallbackFont = font;
            }
        } else {
            mappedFont = getFontWithFallback(fontMap, mappedFont);
            fallbackFont = getFontWithFallback(fallbackMap, mappedFont);
        }
        runText = mapFontCharset(runText, mappedFont);
        int beginIndex = text.length();
        text.append(runText);
        int endIndex = text.length();
        attList.add(new AttributedStringData(TextAttribute.FAMILY, mappedFont, beginIndex, endIndex));
        PaintStyle fgPaintStyle = run.getFontColor();
        Paint fgPaint = new DrawPaint(ps).getPaint(graphics, fgPaintStyle);
        attList.add(new AttributedStringData(TextAttribute.FOREGROUND, fgPaint, beginIndex, endIndex));
        Double fontSz = run.getFontSize();
        if (fontSz == null) {
            fontSz = paragraph.getDefaultFontSize();
        }
        attList.add(new AttributedStringData(TextAttribute.SIZE, fontSz.floatValue(), beginIndex, endIndex));
        if (run.isBold()) {
            attList.add(new AttributedStringData(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, beginIndex, endIndex));
        }
        if (run.isItalic()) {
            attList.add(new AttributedStringData(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE, beginIndex, endIndex));
        }
        if (run.isUnderlined()) {
            attList.add(new AttributedStringData(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, beginIndex, endIndex));
            attList.add(new AttributedStringData(TextAttribute.INPUT_METHOD_UNDERLINE, TextAttribute.UNDERLINE_LOW_TWO_PIXEL, beginIndex, endIndex));
        }
        if (run.isStrikethrough()) {
            attList.add(new AttributedStringData(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON, beginIndex, endIndex));
        }
        if (run.isSubscript()) {
            attList.add(new AttributedStringData(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUB, beginIndex, endIndex));
        }
        if (run.isSuperscript()) {
            attList.add(new AttributedStringData(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER, beginIndex, endIndex));
        }
        Hyperlink<?, ?> hl = run.getHyperlink();
        if (hl != null) {
            attList.add(new AttributedStringData(HYPERLINK_HREF, hl.getAddress(), beginIndex, endIndex));
            attList.add(new AttributedStringData(HYPERLINK_LABEL, hl.getLabel(), beginIndex, endIndex));
        }
        int style = (run.isBold() ? Font.BOLD : 0) | (run.isItalic() ? Font.ITALIC : 0);
        Font f = new Font(mappedFont, style, (int) Math.rint(fontSz));
        // check for unsupported characters and add a fallback font for these
        char[] textChr = runText.toCharArray();
        int nextEnd = canDisplayUpTo(f, textChr, 0, textChr.length);
        int last = nextEnd;
        boolean isNextValid = (nextEnd == 0);
        while (nextEnd != -1 && nextEnd <= textChr.length) {
            if (isNextValid) {
                nextEnd = canDisplayUpTo(f, textChr, nextEnd, textChr.length);
                isNextValid = false;
            } else {
                if (nextEnd >= textChr.length || f.canDisplay(Character.codePointAt(textChr, nextEnd, textChr.length))) {
                    attList.add(new AttributedStringData(TextAttribute.FAMILY, fallbackFont, beginIndex + last, beginIndex + Math.min(nextEnd, textChr.length)));
                    if (nextEnd >= textChr.length) {
                        break;
                    }
                    last = nextEnd;
                    isNextValid = true;
                } else {
                    boolean isHS = Character.isHighSurrogate(textChr[nextEnd]);
                    nextEnd += (isHS ? 2 : 1);
                }
            }
        }
    }
    // We need this trick to correctly measure text
    if (text.length() == 0) {
        Double fontSz = paragraph.getDefaultFontSize();
        text.append(" ");
        attList.add(new AttributedStringData(TextAttribute.SIZE, fontSz.floatValue(), 0, 1));
    }
    AttributedString string = new AttributedString(text.toString());
    for (AttributedStringData asd : attList) {
        string.addAttribute(asd.attribute, asd.value, asd.beginIndex, asd.endIndex);
    }
    return string;
}
Also used : ArrayList(java.util.ArrayList) AttributedString(java.text.AttributedString) TextRun(org.apache.poi.sl.usermodel.TextRun) Paint(java.awt.Paint) Paint(java.awt.Paint) Font(java.awt.Font) AttributedString(java.text.AttributedString) PaintStyle(org.apache.poi.sl.usermodel.PaintStyle) Map(java.util.Map)

Example 82 with AttributedString

use of java.text.AttributedString in project poi by apache.

the class DrawTextParagraph method tab2space.

/**
     * Replace a tab with the effective number of white spaces.
     */
private String tab2space(TextRun tr) {
    AttributedString string = new AttributedString(" ");
    String fontFamily = tr.getFontFamily();
    if (fontFamily == null) {
        fontFamily = "Lucida Sans";
    }
    string.addAttribute(TextAttribute.FAMILY, fontFamily);
    Double fs = tr.getFontSize();
    if (fs == null) {
        fs = 12d;
    }
    string.addAttribute(TextAttribute.SIZE, fs.floatValue());
    TextLayout l = new TextLayout(string.getIterator(), new FontRenderContext(null, true, true));
    double wspace = l.getAdvance();
    Double tabSz = paragraph.getDefaultTabSize();
    if (tabSz == null) {
        tabSz = wspace * 4;
    }
    int numSpaces = (int) Math.ceil(tabSz / wspace);
    StringBuilder buf = new StringBuilder();
    for (int i = 0; i < numSpaces; i++) {
        buf.append(' ');
    }
    return buf.toString();
}
Also used : AttributedString(java.text.AttributedString) AttributedString(java.text.AttributedString) FontRenderContext(java.awt.font.FontRenderContext) Paint(java.awt.Paint) TextLayout(java.awt.font.TextLayout)

Example 83 with AttributedString

use of java.text.AttributedString in project poi by apache.

the class DrawTextParagraph method breakText.

/**
     * break text into lines, each representing a line of text that fits in the wrapping width
     *
     * @param graphics The drawing context for computing text-lengths.
     */
protected void breakText(Graphics2D graphics) {
    lines.clear();
    DrawFactory fact = DrawFactory.getInstance(graphics);
    StringBuilder text = new StringBuilder();
    AttributedString at = getAttributedString(graphics, text);
    boolean emptyParagraph = ("".equals(text.toString().trim()));
    AttributedCharacterIterator it = at.getIterator();
    LineBreakMeasurer measurer = new LineBreakMeasurer(it, graphics.getFontRenderContext());
    for (; ; ) {
        int startIndex = measurer.getPosition();
        // add a pixel to compensate rounding errors
        double wrappingWidth = getWrappingWidth(lines.size() == 0, graphics) + 1;
        // shape width can be smaller that the sum of insets (this was proved by a test file)
        if (wrappingWidth < 0) {
            wrappingWidth = 1;
        }
        int nextBreak = text.indexOf("\n", startIndex + 1);
        if (nextBreak == -1) {
            nextBreak = it.getEndIndex();
        }
        TextLayout layout = measurer.nextLayout((float) wrappingWidth, nextBreak, true);
        if (layout == null) {
            // layout can be null if the entire word at the current position
            // does not fit within the wrapping width. Try with requireNextWord=false.
            layout = measurer.nextLayout((float) wrappingWidth, nextBreak, false);
        }
        if (layout == null) {
            // exit if can't break any more
            break;
        }
        int endIndex = measurer.getPosition();
        // skip over new line breaks (we paint 'clear' text runs not starting or ending with \n)
        if (endIndex < it.getEndIndex() && text.charAt(endIndex) == '\n') {
            measurer.setPosition(endIndex + 1);
        }
        TextAlign hAlign = paragraph.getTextAlign();
        if (hAlign == TextAlign.JUSTIFY || hAlign == TextAlign.JUSTIFY_LOW) {
            layout = layout.getJustifiedLayout((float) wrappingWidth);
        }
        AttributedString str = (emptyParagraph) ? // we will not paint empty paragraphs
        null : new AttributedString(it, startIndex, endIndex);
        DrawTextFragment line = fact.getTextFragment(layout, str);
        lines.add(line);
        maxLineHeight = Math.max(maxLineHeight, line.getHeight());
        if (endIndex == it.getEndIndex()) {
            break;
        }
    }
    rawText = text.toString();
}
Also used : AttributedString(java.text.AttributedString) TextAlign(org.apache.poi.sl.usermodel.TextParagraph.TextAlign) LineBreakMeasurer(java.awt.font.LineBreakMeasurer) Paint(java.awt.Paint) AttributedCharacterIterator(java.text.AttributedCharacterIterator) TextLayout(java.awt.font.TextLayout)

Example 84 with AttributedString

use of java.text.AttributedString in project chipKIT32-MAX by chipKIT32.

the class CompositionTextManager method getTextLayout.

private TextLayout getTextLayout(AttributedCharacterIterator text, int committed_count) {
    AttributedString composed = new AttributedString(text, committed_count, text.getEndIndex());
    Font font = textArea.getPainter().getFont();
    FontRenderContext context = ((Graphics2D) (textArea.getPainter().getGraphics())).getFontRenderContext();
    composed.addAttribute(TextAttribute.FONT, font);
    TextLayout layout = new TextLayout(composed.getIterator(), context);
    return layout;
}
Also used : AttributedString(java.text.AttributedString) FontRenderContext(java.awt.font.FontRenderContext) Font(java.awt.Font) Graphics2D(java.awt.Graphics2D) TextLayout(java.awt.font.TextLayout)

Example 85 with AttributedString

use of java.text.AttributedString in project chipKIT32-MAX by chipKIT32.

the class CompositionTextManager method getCommittedText.

public AttributedCharacterIterator getCommittedText(int beginIndex, int endIndex) {
    int length = endIndex - beginIndex;
    String textAreaString = textArea.getText(beginIndex, length);
    return new AttributedString(textAreaString).getIterator();
}
Also used : AttributedString(java.text.AttributedString) AttributedString(java.text.AttributedString) Point(java.awt.Point)

Aggregations

AttributedString (java.text.AttributedString)85 AttributedCharacterIterator (java.text.AttributedCharacterIterator)37 TextLayout (java.awt.font.TextLayout)29 LineBreakMeasurer (java.awt.font.LineBreakMeasurer)16 FontRenderContext (java.awt.font.FontRenderContext)13 Font (java.awt.Font)10 Paint (java.awt.Paint)10 Point (java.awt.Point)10 Graphics2D (java.awt.Graphics2D)8 WeakHashMap (java.util.WeakHashMap)8 Color (java.awt.Color)4 Bidi (java.text.Bidi)4 ArrayList (java.util.ArrayList)4 TreeSet (java.util.TreeSet)4 Rectangle (java.awt.Rectangle)3 HashSet (java.util.HashSet)3 Dimension (java.awt.Dimension)2 Insets (java.awt.Insets)2 AffineTransform (java.awt.geom.AffineTransform)2 Rectangle2D (java.awt.geom.Rectangle2D)2