Examples of AttributedString


Examples of java.text.AttributedString

     */
    private AttributedCharacterIterator createModifiedACIForFontMatching
        (TextNode node, AttributedCharacterIterator aci) {

        aci.first();
        AttributedString as = null;
        int asOff = 0;
        int begin = aci.getBeginIndex();
        boolean moreChunks = true;
        int start, end   = aci.getRunStart(TEXT_COMPOUND_DELIMITER);
        while (moreChunks) {
            start = end;
            end = aci.getRunLimit(TEXT_COMPOUND_DELIMITER);
            int aciLength = end-start;

            Vector fontFamilies;
            fontFamilies = (Vector)aci.getAttributes().get(GVT_FONT_FAMILIES);

            if (fontFamilies == null ) {
                // no font families set this chunk so just increment...
                asOff += aciLength;
                moreChunks = (aci.setIndex(end) != aci.DONE);
                continue;
            }

            // resolve any unresolved font families in the list
            List resolvedFontFamilies = new ArrayList(fontFamilies.size());
            for (int i = 0; i < fontFamilies.size(); i++) {
                GVTFontFamily fontFamily = (GVTFontFamily)fontFamilies.get(i);
                if (fontFamily instanceof UnresolvedFontFamily) {
                    fontFamily = FontFamilyResolver.resolve
                        ((UnresolvedFontFamily)fontFamily);
                }
                if (fontFamily != null) // Add font family if resolved
                    resolvedFontFamilies.add(fontFamily);
            }

            // if could not resolve at least one of the fontFamilies
            // then use the default font
            if (resolvedFontFamilies.size() == 0) {
                resolvedFontFamilies.add(FontFamilyResolver.defaultFont);
            }

            // create a list of fonts of the correct size
            float fontSize = 12;
            Float fsFloat = (Float)aci.getAttributes().get(TextAttribute.SIZE);
            if (fsFloat != null) {
                fontSize = fsFloat.floatValue();
            }

            // now for each char or group of chars in the string,
            // find a font that can display it.
            boolean[] fontAssigned = new boolean[aciLength];

            if (as == null)
                as = new AttributedString(aci);

            GVTFont defaultFont = null;;
            int numSet=0;
            int firstUnset=start;
            boolean firstUnsetSet;
            for (int i = 0; i < resolvedFontFamilies.size(); i++) {
                // assign this font to all characters it can display if it has
                // not already been assigned
                int currentIndex = firstUnset;
                firstUnsetSet = false;
                aci.setIndex(currentIndex);

                GVTFontFamily ff;
                ff = ((GVTFontFamily)resolvedFontFamilies.get(i));
                GVTFont font = ff.deriveFont(fontSize, aci);
                if (defaultFont == null)
                    defaultFont = font;

                while (currentIndex < end) {
                    int displayUpToIndex = font.canDisplayUpTo
                        (aci, currentIndex, end);

                    Object altGlyphElement = aci.getAttributes().get(ALT_GLYPH_HANDLER);
                    if ( altGlyphElement != null ){
                        //found all the glyph to be displayed
                        //consider the font matching done
                        displayUpToIndex = -1;
                    }

                    if (displayUpToIndex == -1) {
                        // Can handle the whole thing...
                        displayUpToIndex = end;
                    }

                    if (displayUpToIndex <= currentIndex) {
                        if (!firstUnsetSet) {
                            firstUnset = currentIndex;
                            firstUnsetSet = true;
                        }
                        // couldn't display the current char
                        currentIndex++;
                    } else {
                        // could display some text, so for each
                        // char it can display, if char not already
                        // assigned a font, assign this font to it
                        int runStart = -1;
                        for (int j = currentIndex; j < displayUpToIndex; j++) {
                            if (fontAssigned[j - start]) {
                                if (runStart != -1) {
            // System.out.println("Font 1: " + font);
                                    as.addAttribute(GVT_FONT, font,
                                                    runStart-begin, j-begin);
                                    runStart=-1;
                                }
                            } else {
                                if (runStart == -1)
                                    runStart = j;
                            }
                            fontAssigned[j - start] = true;
                            numSet++;
                        }
                        if (runStart != -1) {
          // System.out.println("Font 2: " + font);
                            as.addAttribute(GVT_FONT, font,
                                            runStart-begin,
                                            displayUpToIndex-begin);
                        }

                        // set currentIndex to be one after the char
                        // that couldn't display
                        currentIndex = displayUpToIndex+1;
                    }
                }

                if (numSet == aciLength) // all chars have font set;
                    break;
            }

            // assign the first font to any chars haven't alreay been assigned
            int           runStart = -1;
            GVTFontFamily prevFF   = null;
            GVTFont       prevF    = defaultFont;
            for (int i = 0; i < aciLength; i++) {
                if (fontAssigned[i]) {
                    if (runStart != -1) {
      // System.out.println("Font 3: " + prevF);
                        as.addAttribute(GVT_FONT, prevF,
                                        runStart+asOff, i+asOff);
                        runStart = -1;
                        prevF  = null;
                        prevFF = null;
                    }
                } else {
                    char c = aci.setIndex(start+i);
                    GVTFontFamily fontFamily;
                    fontFamily = FontFamilyResolver.getFamilyThatCanDisplay(c);

                    if (runStart == -1) {
                        // Starting a new run...
                        runStart = i;
                        prevFF   = fontFamily;
                        if (prevFF == null)
                            prevF = defaultFont;
                        else
                            prevF = fontFamily.deriveFont(fontSize, aci);
                    } else if (prevFF != fontFamily) {
                        // Font family changed...
      // System.out.println("Font 4: " + prevF);
                        as.addAttribute(GVT_FONT, prevF,
                                        runStart+asOff, i+asOff);
                   
                        runStart = i;
                        prevFF = fontFamily;
                        if (prevFF == null)
                            prevF = defaultFont;
                        else
                            prevF = fontFamily.deriveFont(fontSize, aci);
                    }
                }
            }
            if (runStart != -1) {
    // System.out.println("Font 5: " + prevF);
                as.addAttribute(GVT_FONT, prevF,
                                runStart+asOff, aciLength+asOff);
      }

            asOff += aciLength;
            if (aci.setIndex(end) == aci.DONE) {
                moreChunks = false;
            }
            start = end;
        }
        if (as != null)
            return as.getIterator();

        // Didn't do anything return original ACI
        return aci;
    }
View Full Code Here

Examples of java.text.AttributedString

     * value.
     */
    protected void computeLayoutedText(BridgeContext ctx,
                                       Element e,
                                       GraphicsNode node) {
        AttributedString as = buildAttributedString(ctx, e);
        addGlyphPositionAttributes(as, e, ctx);
        if (ctx.isDynamic()) {
            layoutedText = new AttributedString(as.getIterator());
        }
        TextNode tn = (TextNode)node;
        tn.setAttributedCharacterIterator(as.getIterator());
        TextDecoration textDecoration =
            getTextDecoration(e, tn, new TextDecoration(), ctx);
        addPaintAttributes(as, e, tn, textDecoration, ctx);
        tn.setAttributedCharacterIterator(as.getIterator());
    }
View Full Code Here

Examples of java.text.AttributedString

        case SVGCSSEngine.STROKE_DASHOFFSET_INDEX:
        case SVGCSSEngine.TEXT_DECORATION_INDEX: {
            if (!hasNewACI) {
                hasNewACI = true;
                TextNode tn = (TextNode)node;
                AttributedString as;

                TextDecoration parentDecoration;

                if ( cssProceedElement == e ){
                    parentDecoration = new TextDecoration();
                    as = new AttributedString(layoutedText.getIterator());
                }
                else{
                    //if a child CSS property has changed, then
                    //retrieve the parent text decoration
                    //and only update the section of the AtrtibutedString of
                    //the child
                    parentDecoration = getParentTextDecoration
                        (tn.getAttributedCharacterIterator(),
                         cssProceedElement);
                    as = new AttributedString
                        (tn.getAttributedCharacterIterator());
                }
                tn.setAttributedCharacterIterator(as.getIterator());
                TextDecoration textDecoration = getTextDecoration
                    (cssProceedElement, tn, parentDecoration, ctx);
                addPaintAttributes
                    (as, cssProceedElement, tn, textDecoration, ctx);
                tn.setAttributedCharacterIterator(as.getIterator());
            }
            break;
        }
        case SVGCSSEngine.TEXT_RENDERING_INDEX: {
            RenderingHints hints = node.getRenderingHints();
View Full Code Here

Examples of java.text.AttributedString

         * buffer.
         */
        public AttributedString toAttributedString() {
            switch (count) {
            case 0:
                return new AttributedString(" ");
            case 1:
                return new AttributedString((String)strings.get(0),
                                            (Map)attributes.get(0));
            }

            StringBuffer sb = new StringBuffer();
            Iterator it = strings.iterator();
            while (it.hasNext()) {
                sb.append((String)it.next());
            }

            AttributedString result = new AttributedString(sb.toString());

            // Set the attributes

            Iterator sit = strings.iterator();
            Iterator ait = attributes.iterator();
            int idx = 0;
            while (sit.hasNext()) {
                String s = (String)sit.next();
                int nidx = idx + s.length();
                Map m = (Map)ait.next();
                Iterator kit = m.keySet().iterator();
                Iterator vit = m.values().iterator();
                while (kit.hasNext()) {
                    Attribute attr = (Attribute)kit.next();
                    Object val = vit.next();
                    result.addAttribute(attr, val, idx, nidx);
                }
                idx = nidx;
            }

            return result;
View Full Code Here

Examples of java.text.AttributedString

        this.frc = frc;
        this.chunkStart = chunkStart;
        aci.first();
        int   numChars    = aci.getEndIndex()-aci.getBeginIndex();
        AttributedString as;

         // Ideally we would do a 'quick' check on chars and
         // attributes to decide if we really need to do bidi or not.
        boolean needsBIDI = true;

        if (false) {
            // Believe it or not this is much slower than the else case
            // but the two are exactly equivilent (including the stripping
            // of null keys/values).
            as = new AttributedString(aci);
        } else {
            StringBuffer strB = new StringBuffer();
            char c = aci.first();
            for (int i = 0; i < numChars; i++) {
                strB.append(c);
                c = aci.next();
            }
            as = new AttributedString(strB.toString());
            int start=aci.getBeginIndex();
            int end  =aci.getEndIndex();
            int index = start;
            while (index < end) {
                aci.setIndex(index);
                Map attrMap = aci.getAttributes();
                int extent  = aci.getRunLimit();
                Map destMap = new HashMap(attrMap.size());
                Iterator i  = attrMap.keySet().iterator();
                while (i.hasNext()) {
                    // Font doesn't like getting attribute sets with
                    // null keys or values so we strip them here.
                    Object key = i.next();
                    if (key == null) continue;
                    Object value = attrMap.get(key);
                    if (value == null) continue;
                    destMap.put(key, value);
                }
                // System.out.println("Run: " + (index-start) + "->" +
                //                    (extent-start) + " of " + numChars);
                as.addAttributes (destMap, index-start, extent-start);
                index = extent;
            }
        }

        // We Just want it to do BIDI for us...
        // In 1.4 we might be able to use the BIDI class...
        TextLayout tl = new TextLayout(as.getIterator(), frc);

        int[] charIndices = new int[numChars];
        int[] charLevels  = new int[numChars];

        int runStart   = 0;
        int currBiDi   = tl.getCharacterLevel(0);
        charIndices[0] = 0;
        charLevels [0] = currBiDi;
        int maxBiDi    = currBiDi;

        for (int i = 1; i < numChars; i++) {
            int newBiDi = tl.getCharacterLevel(i);
            charIndices[i] = i;
            charLevels [i] = newBiDi;

            if (newBiDi != currBiDi) {
                as.addAttribute
                    (GVTAttributedCharacterIterator.TextAttribute.BIDI_LEVEL,
                     new Integer(currBiDi), runStart, i);
                runStart = i;
                currBiDi  = newBiDi;
                if (newBiDi > maxBiDi) maxBiDi = newBiDi;
            }
        }
        as.addAttribute
            (GVTAttributedCharacterIterator.TextAttribute.BIDI_LEVEL,
             new Integer(currBiDi), runStart, numChars);

        if ((runStart == 0) && (currBiDi==0)) {
            // This avoids all the mucking about we need to do when
            // bidi is actually performed for cases where it
            // is not actually needed.
            this.aci = this.reorderedACI = as.getIterator();
            newCharOrder = new int[numChars];
            for (int i=0; i<numChars; i++)
                newCharOrder[i] = chunkStart+i;
            return;
        }

        this.aci = as.getIterator();

        //  work out the new character order
        newCharOrder = doBidiReorder(charIndices, charLevels,
                                           numChars, maxBiDi);

        // construct the string in the new order
        StringBuffer reorderedString = new StringBuffer();
        char c;
        for (int i = 0; i < numChars; i++) {
            c = this.aci.setIndex(newCharOrder[i]);

            // check for mirrored char
            int bidiLevel = tl.getCharacterLevel(newCharOrder[i]);
            if ((bidiLevel & 0x01) != 0) {
                // bidi level is odd so writing dir is right to left
                // So get the mirror version of the char if there
                // is one.
                c = (char)mirrorChar(c);
            }

            reorderedString.append(c);
        }

        // construct the reordered ACI
        AttributedString reorderedAS
            = new AttributedString(reorderedString.toString());
        Map [] attrs = new Map[numChars];
        int start=this.aci.getBeginIndex();
        int end  =this.aci.getEndIndex();
        int index = start;
        while (index < end) {
            this.aci.setIndex(index);
            Map attrMap = this.aci.getAttributes();
            int extent = this.aci.getRunLimit();
            for (int i=index; i<extent; i++)
                attrs[i-start] = attrMap;
            index = extent;
        }

        runStart=0;
        Map prevAttrMap = attrs[newCharOrder[0]];
        for (int i = 1; i < numChars; i++) {
            Map attrMap = attrs[newCharOrder[i]];
            if (attrMap != prevAttrMap) {
                // Change in attrs set last run...
                reorderedAS.addAttributes(prevAttrMap, runStart, i);
                prevAttrMap = attrMap;
                runStart = i;
            }
        }
        reorderedAS.addAttributes(prevAttrMap, runStart, numChars);

        // transfer any position atttributes to the new first char
        this.aci.first();
        Float x = (Float) this.aci.getAttribute
            (GVTAttributedCharacterIterator.TextAttribute.X);
        Float y = (Float) this.aci.getAttribute
            (GVTAttributedCharacterIterator.TextAttribute.Y);

        if (x != null && !x.isNaN()) {
            reorderedAS.addAttribute
                (GVTAttributedCharacterIterator.TextAttribute.X,
                 new Float(Float.NaN), newCharOrder[0], newCharOrder[0]+1);
            reorderedAS.addAttribute
                (GVTAttributedCharacterIterator.TextAttribute.X, x, 0, 1);
        }
        if (y != null && !y.isNaN()) {
            reorderedAS.addAttribute
                (GVTAttributedCharacterIterator.TextAttribute.Y,
                 new Float(Float.NaN), newCharOrder[0], newCharOrder[0]+1);
            reorderedAS.addAttribute
                (GVTAttributedCharacterIterator.TextAttribute.Y, y, 0, 1);
        }

        // assign arabic form attributes to any arabic chars in the string
        reorderedAS = ArabicTextHandler.assignArabicForms(reorderedAS);

        // Shift the values to match the source text string...
        for (int i=0; i<newCharOrder.length; i++) {
            newCharOrder[i] += chunkStart;
        }
        reorderedACI = reorderedAS.getIterator();
    }
View Full Code Here

Examples of java.text.AttributedString

     * @param element the text element
     */
    protected AttributedString buildAttributedString(BridgeContext ctx,
                                                     Element element) {
        List rgns = getRegions(ctx, element);
        AttributedString ret = getFlowDiv(ctx, element);
        ret.addAttribute(FLOW_REGIONS, rgns, 0, 1);
        return ret;
    }
View Full Code Here

Examples of java.text.AttributedString

            }
        }

        // Layer in the PARAGRAPH/LINE_BREAK Attributes so we can
        // break up text chunks.
        AttributedString ret = asb.toAttributedString();

        // Note: The Working Group (in conjunction with XHTML working
        // group) has decided that multiple line elements collapse.
        int prevLN = 0;
        int lnCount = 0;
        Iterator lnIter = lnLocs.iterator();
        while (lnIter.hasNext()) {
            int nextLN = ((Integer)lnIter.next()).intValue();
            if (nextLN == prevLN) continue;

            ret.addAttribute(FLOW_LINE_BREAK,
                             new Object(),
                             prevLN, nextLN);
            // System.out.println("Attr: [" + prevLN + "," + nextLN + "]");
            prevLN  = nextLN;
        }

        int start=0;
        int end;
        List emptyPara = null;
        for (int i=0; i<paraElems.size(); i++, start=end) {
            Element elem = (Element)paraElems.get(i);
            end  = ((Integer)paraEnds.get(i)).intValue();
            if (start == end) {
                if (emptyPara == null)
                    emptyPara = new LinkedList();
                emptyPara.add(makeMarginInfo(elem));
                continue;
            }
            // System.out.println("Para: [" + start + ", " + end + "]");
            ret.addAttribute(FLOW_PARAGRAPH, makeMarginInfo(elem), start, end);
            if (emptyPara != null) {
                ret.addAttribute(FLOW_EMPTY_PARAGRAPH, emptyPara, start, end);
                emptyPara = null;
            }
        }

        return ret;
View Full Code Here

Examples of java.text.AttributedString

     *  
     * @param column the column index
     * @param useMergedCells whether to use the contents of merged cells when calculating the width of the column
     */
    public void autoSizeColumn(short column, boolean useMergedCells) {
        AttributedString str;
        TextLayout layout;
        /**
         * Excel measures columns in units of 1/256th of a character width
         * but the docs say nothing about what particular character is used.
         * '0' looks to be a good choice.
         */
        char defaultChar = '0';
      
        /**
         * This is the multiple that the font height is scaled by when determining the
         * boundary of rotated text.
         */
        double fontHeightMultiple = 2.0;
      
        FontRenderContext frc = new FontRenderContext(null, true, true);

        HSSFWorkbook wb = new HSSFWorkbook(book);
        HSSFFont defaultFont = wb.getFontAt((short) 0);

        str = new AttributedString("" + defaultChar);
        copyAttributes(defaultFont, str, 0, 1);
        layout = new TextLayout(str.getIterator(), frc);
        int defaultCharWidth = (int)layout.getAdvance();

        double width = -1;
        rows:
        for (Iterator it = rowIterator(); it.hasNext();) {
            HSSFRow row = (HSSFRow) it.next();
            HSSFCell cell = row.getCell(column);

            if (cell == null) continue;

            int colspan = 1;
            for (int i = 0 ; i < getNumMergedRegions(); i++) {
                if (getMergedRegionAt(i).contains(row.getRowNum(), column)) {
                  if (!useMergedCells) {
                      // If we're not using merged cells, skip this one and move on to the next.
                    continue rows;
                  }
                  cell = row.getCell(getMergedRegionAt(i).getColumnFrom());
                  colspan = 1+ getMergedRegionAt(i).getColumnTo() - getMergedRegionAt(i).getColumnFrom();
                }
            }

            HSSFCellStyle style = cell.getCellStyle();
            HSSFFont font = wb.getFontAt(style.getFontIndex());

            if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                HSSFRichTextString rt = cell.getRichStringCellValue();
                String[] lines = rt.getString().split("\\n");
                for (int i = 0; i < lines.length; i++) {
                    String txt = lines[i] + defaultChar;
                    str = new AttributedString(txt);
                    copyAttributes(font, str, 0, txt.length());

                    if (rt.numFormattingRuns() > 0) {
                        for (int j = 0; j < lines[i].length(); j++) {
                            int idx = rt.getFontAtIndex(j);
                            if (idx != 0) {
                                HSSFFont fnt = wb.getFontAt((short) idx);
                                copyAttributes(fnt, str, j, j + 1);
                            }
                        }
                    }

                    layout = new TextLayout(str.getIterator(), frc);
                    if(style.getRotation() != 0){
                        /*
                         * Transform the text using a scale so that it's height is increased by a multiple of the leading,
                         * and then rotate the text before computing the bounds. The scale results in some whitespace around
                         * the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
                         * is added by the standard Excel autosize.
                         */
                        AffineTransform trans = new AffineTransform();
                        trans.concatenate(AffineTransform.getRotateInstance(style.getRotation()*2.0*Math.PI/360.0));
                        trans.concatenate(
                        AffineTransform.getScaleInstance(1, fontHeightMultiple)
                        );
                        width = Math.max(width, ((layout.getOutline(trans).getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention());
                    } else {
                        width = Math.max(width, ((layout.getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention());
                    }
                }
            } else {
                String sval = null;
                if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                    HSSFDataFormat dataformat = wb.createDataFormat();
                    short idx = style.getDataFormat();
                    String format = dataformat.getFormat(idx).replaceAll("\"", "");
                    double value = cell.getNumericCellValue();
                    try {
                        NumberFormat fmt;
                        if ("General".equals(format))
                            sval = "" + value;
                        else
                        {
                            fmt = new DecimalFormat(format);
                            sval = fmt.format(value);
                        }
                    } catch (Exception e) {
                        sval = "" + value;
                    }
                } else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
                    sval = String.valueOf(cell.getBooleanCellValue());
                }
                if(sval != null) {
                    String txt = sval + defaultChar;
                    str = new AttributedString(txt);
                    copyAttributes(font, str, 0, txt.length());

                    layout = new TextLayout(str.getIterator(), frc);
                    if(style.getRotation() != 0){
                        /*
                         * Transform the text using a scale so that it's height is increased by a multiple of the leading,
                         * and then rotate the text before computing the bounds. The scale results in some whitespace around
                         * the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
View Full Code Here

Examples of java.text.AttributedString

    // we clue the system in on the default direction of the run -
    // we do _not_ want to use the direction of the first character
    // in this text.
    Graphics2D g2 = (Graphics2D) g;

    AttributedString as  = new AttributedString(paintText);
    as.addAttribute(TextAttribute.FONT, g2.getFont());

    Object direction;
    if (context.getReadingDirection() == LocaleUtils.DIRECTION_LEFTTORIGHT)
      direction = TextAttribute.RUN_DIRECTION_LTR;
    else
      direction = TextAttribute.RUN_DIRECTION_RTL;

    as.addAttribute(TextAttribute.RUN_DIRECTION, direction);

    g2.drawString(as.getIterator(), x, y);

    //
    // paint the mnemonic if necessary
    //
    if ((mnemonicIndex >= 0) && (mnemonicIndex < paintText.length()))
    {
      TextLayout layout = new TextLayout(as.getIterator(),
                                         g2.getFontRenderContext());

      TextHitInfo leading = TextHitInfo.leading(mnemonicIndex);
      TextHitInfo trailing = TextHitInfo.trailing(mnemonicIndex);
View Full Code Here

Examples of java.text.AttributedString

     */
    public void buildGraphicsNode(BridgeContext ctx,
                                  Element e,
                                  GraphicsNode node) {
        e.normalize();
        AttributedString as = buildAttributedString(ctx, e);
        addGlyphPositionAttributes(as, e, ctx);
        if (ctx.isDynamic()) {
            layoutedText = new AttributedString(as.getIterator());
        }
        TextNode tn = (TextNode)node;
        tn.setAttributedCharacterIterator(as.getIterator());

        // now add the painting attributes, cannot do it before this because
        // some of the Paint objects need to know the bounds of the text
        // and this isn't know until the text node aci is set
        TextDecoration textDecoration =
            getTextDecoration(e, tn, new TextDecoration(), ctx);
        addPaintAttributes(as, e, tn, textDecoration, ctx);
        tn.setAttributedCharacterIterator(as.getIterator());

        //
        // DO NOT CALL super, 'opacity' is handle during addPaintAttributes()
        //

View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.