java.awt.font.TextAttribute Java Examples

The following examples show how to use java.awt.font.TextAttribute. 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: KerningLeak.java    From jdk8u-jdk with GNU General Public License v2.0 7 votes vote down vote up
private static void leak() {
    Map<TextAttribute, Object> textAttributes = new HashMap<>();
    textAttributes.put(TextAttribute.FAMILY, "Sans Serif");
    textAttributes.put(TextAttribute.SIZE, 12);
    textAttributes.put(TextAttribute.KERNING, TextAttribute.KERNING_ON);
    Font font = Font.getFont(textAttributes);
    JLabel label = new JLabel();
    int dummy = 0;
    for (int i = 0; i < 500; i++) {
        if (i % 10 == 0) System.out.println("Starting iter " + (i+1));
        for (int j = 0; j <1000; j++) {
            FontMetrics fm = label.getFontMetrics(font);
            dummy += SwingUtilities.computeStringWidth(fm, Integer.toString(j));
        }
    }
    System.out.println("done " + dummy);
}
 
Example #2
Source File: ParagraphView.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Set the cached properties from the attributes.
 */
protected void setPropertiesFromAttributes() {
    AttributeSet attr = getAttributes();
    if (attr != null) {
        setParagraphInsets(attr);
        Integer a = (Integer)attr.getAttribute(StyleConstants.Alignment);
        int alignment;
        if (a == null) {
            Document doc = getElement().getDocument();
            Object o = doc.getProperty(TextAttribute.RUN_DIRECTION);
            if ((o != null) && o.equals(TextAttribute.RUN_DIRECTION_RTL)) {
                alignment = StyleConstants.ALIGN_RIGHT;
            } else {
                alignment = StyleConstants.ALIGN_LEFT;
            }
        } else {
            alignment = a.intValue();
        }
        setJustification(alignment);
        setLineSpacing(StyleConstants.getLineSpacing(attr));
        setFirstLineIndent(StyleConstants.getFirstLineIndent(attr));
    }
}
 
Example #3
Source File: AbstractDocument.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * A convenience method for storing up a property value.  It is
 * equivalent to:
 * <pre>
 * getDocumentProperties().put(key, value);
 * </pre>
 * If <code>value</code> is <code>null</code> this method will
 * remove the property.
 *
 * @param key the non-<code>null</code> key
 * @param value the property value
 * @see #getDocumentProperties
 */
public final void putProperty(Object key, Object value) {
    if (value != null) {
        getDocumentProperties().put(key, value);
    } else {
        getDocumentProperties().remove(key);
    }
    if( key == TextAttribute.RUN_DIRECTION
        && Boolean.TRUE.equals(getProperty(I18NProperty)) )
    {
        //REMIND - this needs to flip on the i18n property if run dir
        //is rtl and the i18n property is not already on.
        writeLock();
        try {
            DefaultDocumentEvent e
                = new DefaultDocumentEvent(0, getLength(),
                                           DocumentEvent.EventType.INSERT);
            updateBidi( e );
        } finally {
            writeUnlock();
        }
    }
}
 
Example #4
Source File: SwingUtilities2.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the width of the passed in String.
 * If the passed String is {@code null}, returns zero.
 *
 * @param c JComponent that will display the string, may be null
 * @param fm FontMetrics used to measure the String width
 * @param string String to get the width of
 * @param useFPAPI use floating point API
 */
public static float stringWidth(JComponent c, FontMetrics fm, String string,
        boolean useFPAPI){
    if (string == null || string.isEmpty()) {
        return 0;
    }
    boolean needsTextLayout = ((c != null) &&
            (c.getClientProperty(TextAttribute.NUMERIC_SHAPING) != null));
    if (needsTextLayout) {
        synchronized(charsBufferLock) {
            int length = syncCharsBuffer(string);
            needsTextLayout = isComplexLayout(charsBuffer, 0, length);
        }
    }
    if (needsTextLayout) {
        TextLayout layout = createTextLayout(c, string,
                                fm.getFont(), fm.getFontRenderContext());
        return layout.getAdvance();
    } else {
        return getFontStringWidth(string, fm, useFPAPI);
    }
}
 
Example #5
Source File: Utilities.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Draws the given composed text passed from an input method.
 *
 * @param view View hosting text
 * @param attr the attributes containing the composed text
 * @param g  the graphics context
 * @param x  the X origin
 * @param y  the Y origin
 * @param p0 starting offset in the composed text to be rendered
 * @param p1 ending offset in the composed text to be rendered
 * @return  the new insertion position
 */
static int drawComposedText(View view, AttributeSet attr, Graphics g,
                            int x, int y, int p0, int p1)
                                 throws BadLocationException {
    Graphics2D g2d = (Graphics2D)g;
    AttributedString as = (AttributedString)attr.getAttribute(
        StyleConstants.ComposedTextAttribute);
    as.addAttribute(TextAttribute.FONT, g.getFont());

    if (p0 >= p1)
        return x;

    AttributedCharacterIterator aci = as.getIterator(null, p0, p1);
    return x + (int)SwingUtilities2.drawString(
                         getJComponent(view), g2d,aci,x,y);
}
 
Example #6
Source File: OptionsMap.java    From gate-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * If the object stored under key is a Font then returns its value
 * otherwise returns null.
 * @param key key associated to the value to retrieve
 * @return the associated font
 */
public Font getFont(Object key) {
  try {
    String stringValue = (String) get(key);
    if (stringValue == null) { return null; }
    StringTokenizer strTok = new StringTokenizer(stringValue, "#", false);
    String family = strTok.nextToken();
    int size = Integer.parseInt(strTok.nextToken());
    boolean italic = Boolean.valueOf(strTok.nextToken());
    boolean bold = Boolean.valueOf(strTok.nextToken());
    HashMap<TextAttribute, Serializable> fontAttrs =
      new HashMap<TextAttribute, Serializable>();
    fontAttrs.put(TextAttribute.FAMILY, family);
    fontAttrs.put(TextAttribute.SIZE, (float) size);
    if(bold) fontAttrs.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD);
    else fontAttrs.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_REGULAR);
    if(italic) fontAttrs.put(
      TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE);
    else fontAttrs.put(TextAttribute.POSTURE, TextAttribute.POSTURE_REGULAR);
    return new Font(fontAttrs);
  } catch (Exception e) {
    return null;
  }
}
 
Example #7
Source File: JRXlsMetadataExporter.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 #8
Source File: KerningLeak.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private static void leak() {
    Map<TextAttribute, Object> textAttributes = new HashMap<>();
    textAttributes.put(TextAttribute.FAMILY, "Sans Serif");
    textAttributes.put(TextAttribute.SIZE, 12);
    textAttributes.put(TextAttribute.KERNING, TextAttribute.KERNING_ON);
    Font font = Font.getFont(textAttributes);
    JLabel label = new JLabel();
    int dummy = 0;
    for (int i = 0; i < 500; i++) {
        if (i % 10 == 0) System.out.println("Starting iter " + (i+1));
        for (int j = 0; j <1000; j++) {
            FontMetrics fm = label.getFontMetrics(font);
            dummy += SwingUtilities.computeStringWidth(fm, Integer.toString(j));
        }
    }
    System.out.println("done " + dummy);
}
 
Example #9
Source File: ParagraphView.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Set the cached properties from the attributes.
 */
protected void setPropertiesFromAttributes() {
    AttributeSet attr = getAttributes();
    if (attr != null) {
        setParagraphInsets(attr);
        Integer a = (Integer)attr.getAttribute(StyleConstants.Alignment);
        int alignment;
        if (a == null) {
            Document doc = getElement().getDocument();
            Object o = doc.getProperty(TextAttribute.RUN_DIRECTION);
            if ((o != null) && o.equals(TextAttribute.RUN_DIRECTION_RTL)) {
                alignment = StyleConstants.ALIGN_RIGHT;
            } else {
                alignment = StyleConstants.ALIGN_LEFT;
            }
        } else {
            alignment = a.intValue();
        }
        setJustification(alignment);
        setLineSpacing(StyleConstants.getLineSpacing(attr));
        setFirstLineIndent(StyleConstants.getFirstLineIndent(attr));
    }
}
 
Example #10
Source File: GraphicsVisualContext.java    From CSSBox with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected Font createFont(String family, int size, CSSProperty.FontWeight weight,
        CSSProperty.FontStyle style, float spacing)
{
    Font base = createBaseFont(family, size, weight, style);
    Map<TextAttribute, Object> attributes = new HashMap<>(defaultFontAttributes);
    // add tracking when needed
    if (spacing >= 0.0001)
    {
        // TRACKING value is multiplied by font size in AWT. 
        // (0.75 has been empiricaly determined by comparing with other browsers) 
        final float tracking = spacing / getFontSize() * 0.75f;
        
        attributes.put(TextAttribute.TRACKING, tracking);
    }
    // derive the font when some attributes have been set
    if (attributes.isEmpty())
        return base;
    else
        return base.deriveFont(attributes);
}
 
Example #11
Source File: KerningLeak.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void leak() {
    Map<TextAttribute, Object> textAttributes = new HashMap<>();
    textAttributes.put(TextAttribute.FAMILY, "Sans Serif");
    textAttributes.put(TextAttribute.SIZE, 12);
    textAttributes.put(TextAttribute.KERNING, TextAttribute.KERNING_ON);
    Font font = Font.getFont(textAttributes);
    JLabel label = new JLabel();
    int dummy = 0;
    for (int i = 0; i < 500; i++) {
        if (i % 10 == 0) System.out.println("Starting iter " + (i+1));
        for (int j = 0; j <1000; j++) {
            FontMetrics fm = label.getFontMetrics(font);
            dummy += SwingUtilities.computeStringWidth(fm, Integer.toString(j));
        }
    }
    System.out.println("done " + dummy);
}
 
Example #12
Source File: LogAxis.java    From openstock with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example #13
Source File: ParagraphView.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Set the cached properties from the attributes.
 */
protected void setPropertiesFromAttributes() {
    AttributeSet attr = getAttributes();
    if (attr != null) {
        setParagraphInsets(attr);
        Integer a = (Integer)attr.getAttribute(StyleConstants.Alignment);
        int alignment;
        if (a == null) {
            Document doc = getElement().getDocument();
            Object o = doc.getProperty(TextAttribute.RUN_DIRECTION);
            if ((o != null) && o.equals(TextAttribute.RUN_DIRECTION_RTL)) {
                alignment = StyleConstants.ALIGN_RIGHT;
            } else {
                alignment = StyleConstants.ALIGN_LEFT;
            }
        } else {
            alignment = a.intValue();
        }
        setJustification(alignment);
        setLineSpacing(StyleConstants.getLineSpacing(attr));
        setFirstLineIndent(StyleConstants.getFirstLineIndent(attr));
    }
}
 
Example #14
Source File: ParagraphView.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Set the cached properties from the attributes.
 */
protected void setPropertiesFromAttributes() {
    AttributeSet attr = getAttributes();
    if (attr != null) {
        setParagraphInsets(attr);
        Integer a = (Integer)attr.getAttribute(StyleConstants.Alignment);
        int alignment;
        if (a == null) {
            Document doc = getElement().getDocument();
            Object o = doc.getProperty(TextAttribute.RUN_DIRECTION);
            if ((o != null) && o.equals(TextAttribute.RUN_DIRECTION_RTL)) {
                alignment = StyleConstants.ALIGN_RIGHT;
            } else {
                alignment = StyleConstants.ALIGN_LEFT;
            }
        } else {
            alignment = a.intValue();
        }
        setJustification(alignment);
        setLineSpacing(StyleConstants.getLineSpacing(attr));
        setFirstLineIndent(StyleConstants.getFirstLineIndent(attr));
    }
}
 
Example #15
Source File: KerningLeak.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void leak() {
    Map<TextAttribute, Object> textAttributes = new HashMap<>();
    textAttributes.put(TextAttribute.FAMILY, "Sans Serif");
    textAttributes.put(TextAttribute.SIZE, 12);
    textAttributes.put(TextAttribute.KERNING, TextAttribute.KERNING_ON);
    Font font = Font.getFont(textAttributes);
    JLabel label = new JLabel();
    int dummy = 0;
    for (int i = 0; i < 500; i++) {
        if (i % 10 == 0) System.out.println("Starting iter " + (i+1));
        for (int j = 0; j <1000; j++) {
            FontMetrics fm = label.getFontMetrics(font);
            dummy += SwingUtilities.computeStringWidth(fm, Integer.toString(j));
        }
    }
    System.out.println("done " + dummy);
}
 
Example #16
Source File: RendererSettings.java    From mil-sym-java with Apache License 2.0 6 votes vote down vote up
/**
     * get font object used for labels
     * @return Font object
     */
    public Font getLabelFont()
    {
        try
        {
            Map<TextAttribute, Object> map = new HashMap<TextAttribute, Object>();
//            map.put(TextAttribute.FONT, _ModifierFontName);
//            map.put(TextAttribute.SIZE, _ModifierFontSize);
//            map.put(TextAttribute.WEIGHT, _ModifierFontType);
            map.put(TextAttribute.KERNING, _ModifierFontKerning);
            map.put(TextAttribute.TRACKING, _ModifierFontTracking);
            
            Font temp = new Font(_ModifierFontName, _ModifierFontType, _ModifierFontSize);
                    
            return temp.deriveFont(map);
        }
        catch(Exception exc)
        {
            String message = "font creation error, returning \"" + _ModifierFontName + "\" font, " + _ModifierFontSize + "pt. Check font name and type.";
            ErrorLogger.LogMessage("RendererSettings", "getLabelFont", message);
            ErrorLogger.LogMessage("RendererSettings", "getLabelFont", exc.getMessage());
            return new Font("arial", Font.BOLD, 12);
        }
    }
 
Example #17
Source File: AbstractDocument.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Performs the actual work of inserting the text; it is assumed the
 * caller has obtained a write lock before invoking this.
 */
private void handleInsertString(int offs, String str, AttributeSet a)
        throws BadLocationException {
    if ((str == null) || (str.length() == 0)) {
        return;
    }
    UndoableEdit u = data.insertString(offs, str);
    DefaultDocumentEvent e =
        new DefaultDocumentEvent(offs, str.length(), DocumentEvent.EventType.INSERT);
    if (u != null) {
        e.addEdit(u);
    }

    // see if complex glyph layout support is needed
    if( getProperty(I18NProperty).equals( Boolean.FALSE ) ) {
        // if a default direction of right-to-left has been specified,
        // we want complex layout even if the text is all left to right.
        Object d = getProperty(TextAttribute.RUN_DIRECTION);
        if ((d != null) && (d.equals(TextAttribute.RUN_DIRECTION_RTL))) {
            putProperty( I18NProperty, Boolean.TRUE);
        } else {
            char[] chars = str.toCharArray();
            if (SwingUtilities2.isComplexLayout(chars, 0, chars.length)) {
                putProperty( I18NProperty, Boolean.TRUE);
            }
        }
    }

    insertUpdate(e, a);
    // Mark the edit as done.
    e.end();
    fireInsertUpdate(e);
    // only fire undo if Content implementation supports it
    // undo for the composed text is not supported for now
    if (u != null && (a == null || !a.isDefined(StyleConstants.ComposedTextAttribute))) {
        fireUndoableEditUpdate(new UndoableEditEvent(this, e));
    }
}
 
Example #18
Source File: AdvancedTextSettingsPanel.java    From Pixelitor with GNU General Public License v3.0 5 votes vote down vote up
public void updateFontAttributesMap(Map<TextAttribute, Object> map) {
    Boolean strikeThroughSetting = Boolean.FALSE;
    if (strikeThroughCB.isSelected()) {
        strikeThroughSetting = STRIKETHROUGH_ON;
    }
    map.put(STRIKETHROUGH, strikeThroughSetting);

    Integer kerningSetting = 0;
    if (kerningCB.isSelected()) {
        kerningSetting = KERNING_ON;
    }
    map.put(KERNING, kerningSetting);

    Integer ligaturesSetting = 0;
    if (ligaturesCB.isSelected()) {
        ligaturesSetting = LIGATURES_ON;
    }
    map.put(LIGATURES, ligaturesSetting);

    Integer underlineSetting = -1;
    if (underlineCB.isSelected()) {
        underlineSetting = UNDERLINE_ON;
    }
    map.put(UNDERLINE, underlineSetting);

    Float tracking = trackingParam.getPercentageValF();
    map.put(TRACKING, tracking);
}
 
Example #19
Source File: BatikAWTFontFamily.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public GVTFont deriveFont(float size, Map attrs) 
{
	if (font != null)
		return new AWTGVTFont(font, size);

	String fontFamilyName = fontFace.getFamilyName();
	if (
		fontFamilyName.startsWith("'")
		&& fontFamilyName.endsWith("'")
		)
	{
		fontFamilyName = fontFamilyName.substring(1, fontFamilyName.length() - 1);
	}

	// svg font-family could have locale suffix because it is needed in svg measured by phantomjs;
	int localeSeparatorPos = fontFamilyName.lastIndexOf(HtmlFontFamily.LOCALE_SEPARATOR);
	if (localeSeparatorPos > 0)
	{
		fontFamilyName = fontFamilyName.substring(0, localeSeparatorPos);
	}

	Font awtFont = 
		FontUtil.getInstance(jasperReportsContext).getAwtFontFromBundles(
			true,
			fontFamilyName,
			(TextAttribute.WEIGHT_BOLD.equals(attrs.get(TextAttribute.WEIGHT)) ? Font.BOLD : Font.PLAIN)
			| (TextAttribute.POSTURE_OBLIQUE.equals(attrs.get(TextAttribute.POSTURE)) ? Font.ITALIC : Font.PLAIN),
			size, 
			null,//FIXMEBATIK locale 
			true
			);
	
	if (awtFont != null)
	{
		return new AWTGVTFont(awtFont);
	}

	return super.deriveFont(size, attrs);
}
 
Example #20
Source File: AttributeValues.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private Object i_get(EAttribute a) {
    switch (a) {
    case EFAMILY: return family;
    case EWEIGHT: return Float.valueOf(weight);
    case EWIDTH: return Float.valueOf(width);
    case EPOSTURE: return Float.valueOf(posture);
    case ESIZE: return Float.valueOf(size);
    case ETRANSFORM:
        return transform == null
            ? TransformAttribute.IDENTITY
            : new TransformAttribute(transform);
    case ESUPERSCRIPT: return Integer.valueOf(superscript);
    case EFONT: return font;
    case ECHAR_REPLACEMENT: return charReplacement;
    case EFOREGROUND: return foreground;
    case EBACKGROUND: return background;
    case EUNDERLINE: return Integer.valueOf(underline);
    case ESTRIKETHROUGH: return Boolean.valueOf(strikethrough);
    case ERUN_DIRECTION: {
        switch (runDirection) {
            // todo: figure out a way to indicate this value
            // case -1: return Integer.valueOf(runDirection);
        case 0: return TextAttribute.RUN_DIRECTION_LTR;
        case 1: return TextAttribute.RUN_DIRECTION_RTL;
        default: return null;
        }
    } // not reachable
    case EBIDI_EMBEDDING: return Integer.valueOf(bidiEmbedding);
    case EJUSTIFICATION: return Float.valueOf(justification);
    case EINPUT_METHOD_HIGHLIGHT: return imHighlight;
    case EINPUT_METHOD_UNDERLINE: return Integer.valueOf(imUnderline);
    case ESWAP_COLORS: return Boolean.valueOf(swapColors);
    case ENUMERIC_SHAPING: return numericShaping;
    case EKERNING: return Integer.valueOf(kerning);
    case ELIGATURES: return Integer.valueOf(ligatures);
    case ETRACKING: return Float.valueOf(tracking);
    default: throw new InternalError();
    }
}
 
Example #21
Source File: javax_swing_plaf_FontUIResource.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
protected FontUIResource getObject() {
    return new FontUIResource(
            new Font(
                    Collections.singletonMap(
                            TextAttribute.STRIKETHROUGH,
                            TextAttribute.STRIKETHROUGH_ON)));
}
 
Example #22
Source File: Font.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the keys of all the attributes supported by this
 * <code>Font</code>.  These attributes can be used to derive other
 * fonts.
 * @return an array containing the keys of all the attributes
 *          supported by this <code>Font</code>.
 * @since 1.2
 */
public Attribute[] getAvailableAttributes() {
    // FONT is not supported by Font

    Attribute attributes[] = {
        TextAttribute.FAMILY,
        TextAttribute.WEIGHT,
        TextAttribute.WIDTH,
        TextAttribute.POSTURE,
        TextAttribute.SIZE,
        TextAttribute.TRANSFORM,
        TextAttribute.SUPERSCRIPT,
        TextAttribute.CHAR_REPLACEMENT,
        TextAttribute.FOREGROUND,
        TextAttribute.BACKGROUND,
        TextAttribute.UNDERLINE,
        TextAttribute.STRIKETHROUGH,
        TextAttribute.RUN_DIRECTION,
        TextAttribute.BIDI_EMBEDDING,
        TextAttribute.JUSTIFICATION,
        TextAttribute.INPUT_METHOD_HIGHLIGHT,
        TextAttribute.INPUT_METHOD_UNDERLINE,
        TextAttribute.SWAP_COLORS,
        TextAttribute.NUMERIC_SHAPING,
        TextAttribute.KERNING,
        TextAttribute.LIGATURES,
        TextAttribute.TRACKING,
    };

    return attributes;
}
 
Example #23
Source File: AttributeValues.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static NumericShaper getNumericShaping(Map<?, ?> map) {
    if (map != null) {
        if (map instanceof AttributeMap &&
            ((AttributeMap) map).getValues() != null) {
            return ((AttributeMap)map).getValues().numericShaping;
        }
        Object obj = map.get(TextAttribute.NUMERIC_SHAPING);
        if (obj != null && obj instanceof NumericShaper) {
            return (NumericShaper)obj;
        }
    }
    return DEFAULT.numericShaping;
}
 
Example #24
Source File: DefaultStyledDocument.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets attributes for a paragraph.
 * <p>
 * This method is thread safe, although most Swing methods
 * are not. Please see
 * <A HREF="https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html">Concurrency
 * in Swing</A> for more information.
 *
 * @param offset the offset into the paragraph &gt;= 0
 * @param length the number of characters affected &gt;= 0
 * @param s the attributes
 * @param replace whether to replace existing attributes, or merge them
 */
public void setParagraphAttributes(int offset, int length, AttributeSet s,
                                   boolean replace) {
    try {
        writeLock();
        DefaultDocumentEvent changes =
            new DefaultDocumentEvent(offset, length, DocumentEvent.EventType.CHANGE);

        AttributeSet sCopy = s.copyAttributes();

        // PENDING(prinz) - this assumes a particular element structure
        Element section = getDefaultRootElement();
        int index0 = section.getElementIndex(offset);
        int index1 = section.getElementIndex(offset + ((length > 0) ? length - 1 : 0));
        boolean isI18N = Boolean.TRUE.equals(getProperty(I18NProperty));
        boolean hasRuns = false;
        for (int i = index0; i <= index1; i++) {
            Element paragraph = section.getElement(i);
            MutableAttributeSet attr = (MutableAttributeSet) paragraph.getAttributes();
            changes.addEdit(new AttributeUndoableEdit(paragraph, sCopy, replace));
            if (replace) {
                attr.removeAttributes(attr);
            }
            attr.addAttributes(s);
            if (isI18N && !hasRuns) {
                hasRuns = (attr.getAttribute(TextAttribute.RUN_DIRECTION) != null);
            }
        }

        if (hasRuns) {
            updateBidi( changes );
        }

        changes.end();
        fireChangedUpdate(changes);
        fireUndoableEditUpdate(new UndoableEditEvent(this, changes));
    } finally {
        writeUnlock();
    }
}
 
Example #25
Source File: AttributeValues.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static float getJustification(Map<?, ?> map) {
    if (map != null) {
        if (map instanceof AttributeMap &&
            ((AttributeMap) map).getValues() != null) {
            return ((AttributeMap)map).getValues().justification;
        }
        Object obj = map.get(TextAttribute.JUSTIFICATION);
        if (obj != null && obj instanceof Number) {
            return max(0, min(1, ((Number)obj).floatValue()));
        }
    }
    return DEFAULT.justification;
}
 
Example #26
Source File: AttributeValues.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private Object i_get(EAttribute a) {
    switch (a) {
    case EFAMILY: return family;
    case EWEIGHT: return Float.valueOf(weight);
    case EWIDTH: return Float.valueOf(width);
    case EPOSTURE: return Float.valueOf(posture);
    case ESIZE: return Float.valueOf(size);
    case ETRANSFORM:
        return transform == null
            ? TransformAttribute.IDENTITY
            : new TransformAttribute(transform);
    case ESUPERSCRIPT: return Integer.valueOf(superscript);
    case EFONT: return font;
    case ECHAR_REPLACEMENT: return charReplacement;
    case EFOREGROUND: return foreground;
    case EBACKGROUND: return background;
    case EUNDERLINE: return Integer.valueOf(underline);
    case ESTRIKETHROUGH: return Boolean.valueOf(strikethrough);
    case ERUN_DIRECTION: {
        switch (runDirection) {
            // todo: figure out a way to indicate this value
            // case -1: return Integer.valueOf(runDirection);
        case 0: return TextAttribute.RUN_DIRECTION_LTR;
        case 1: return TextAttribute.RUN_DIRECTION_RTL;
        default: return null;
        }
    } // not reachable
    case EBIDI_EMBEDDING: return Integer.valueOf(bidiEmbedding);
    case EJUSTIFICATION: return Float.valueOf(justification);
    case EINPUT_METHOD_HIGHLIGHT: return imHighlight;
    case EINPUT_METHOD_UNDERLINE: return Integer.valueOf(imUnderline);
    case ESWAP_COLORS: return Boolean.valueOf(swapColors);
    case ENUMERIC_SHAPING: return numericShaping;
    case EKERNING: return Integer.valueOf(kerning);
    case ELIGATURES: return Integer.valueOf(ligatures);
    case ETRACKING: return Float.valueOf(tracking);
    default: throw new InternalError();
    }
}
 
Example #27
Source File: Font.java    From Java8CN with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the keys of all the attributes supported by this
 * <code>Font</code>.  These attributes can be used to derive other
 * fonts.
 * @return an array containing the keys of all the attributes
 *          supported by this <code>Font</code>.
 * @since 1.2
 */
public Attribute[] getAvailableAttributes() {
    // FONT is not supported by Font

    Attribute attributes[] = {
        TextAttribute.FAMILY,
        TextAttribute.WEIGHT,
        TextAttribute.WIDTH,
        TextAttribute.POSTURE,
        TextAttribute.SIZE,
        TextAttribute.TRANSFORM,
        TextAttribute.SUPERSCRIPT,
        TextAttribute.CHAR_REPLACEMENT,
        TextAttribute.FOREGROUND,
        TextAttribute.BACKGROUND,
        TextAttribute.UNDERLINE,
        TextAttribute.STRIKETHROUGH,
        TextAttribute.RUN_DIRECTION,
        TextAttribute.BIDI_EMBEDDING,
        TextAttribute.JUSTIFICATION,
        TextAttribute.INPUT_METHOD_HIGHLIGHT,
        TextAttribute.INPUT_METHOD_UNDERLINE,
        TextAttribute.SWAP_COLORS,
        TextAttribute.NUMERIC_SHAPING,
        TextAttribute.KERNING,
        TextAttribute.LIGATURES,
        TextAttribute.TRACKING,
    };

    return attributes;
}
 
Example #28
Source File: AttributeValues.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static NumericShaper getNumericShaping(Map<?, ?> map) {
    if (map != null) {
        if (map instanceof AttributeMap &&
            ((AttributeMap) map).getValues() != null) {
            return ((AttributeMap)map).getValues().numericShaping;
        }
        Object obj = map.get(TextAttribute.NUMERIC_SHAPING);
        if (obj != null && obj instanceof NumericShaper) {
            return (NumericShaper)obj;
        }
    }
    return DEFAULT.numericShaping;
}
 
Example #29
Source File: AttributeValues.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static float getJustification(Map<?, ?> map) {
    if (map != null) {
        if (map instanceof AttributeMap &&
            ((AttributeMap) map).getValues() != null) {
            return ((AttributeMap)map).getValues().justification;
        }
        Object obj = map.get(TextAttribute.JUSTIFICATION);
        if (obj != null && obj instanceof Number) {
            return max(0, min(1, ((Number)obj).floatValue()));
        }
    }
    return DEFAULT.justification;
}
 
Example #30
Source File: MultiIconSimpleColoredComponent.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private TextLayout createAndCacheTextLayout(int fragmentIndex, Font basefont, FontRenderContext fontRenderContext) {
  String text = myFragments.get(fragmentIndex);
  AttributedString string = new AttributedString(text);
  int start = 0;
  int end = text.length();
  AttributedCharacterIterator it = string.getIterator(new AttributedCharacterIterator.Attribute[0], start, end);
  Font currentFont = basefont;
  int currentIndex = start;
  for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
    Font font = basefont;
    // TODO(jacobr): SuitableFontProvider is a private class so we can't
    // easily use it. How important is supporting this use case?
    /*
    if (!font.canDisplay(c)) {
      for (SuitableFontProvider provider : SuitableFontProvider.EP_NAME.getExtensions()) {
        font = provider.getFontAbleToDisplay(c, basefont.getSize(), basefont.getStyle(), basefont.getFamily());
        if (font != null) break;
      }
    }
    */
    int i = it.getIndex();
    if (!Comparing.equal(currentFont, font)) {
      if (i > currentIndex) {
        string.addAttribute(TextAttribute.FONT, currentFont, currentIndex, i);
      }
      currentFont = font;
      currentIndex = i;
    }
  }
  if (currentIndex < end) {
    string.addAttribute(TextAttribute.FONT, currentFont, currentIndex, end);
  }
  TextLayout layout = new TextLayout(string.getIterator(), fontRenderContext);
  if (fragmentIndex >= myLayouts.size()) {
    myLayouts.addAll(Collections.nCopies(fragmentIndex - myLayouts.size() + 1, null));
  }
  myLayouts.set(fragmentIndex, layout);
  myLayoutFont = getBaseFont();
  return layout;
}