Exemplo n.º 1
0
  public StringBuilder appendHTMLRepresentation(
      StringBuilder sb, RSyntaxTextArea textArea, boolean fontFamily, boolean tabsToSpaces) {

    SyntaxScheme colorScheme = textArea.getSyntaxScheme();
    Style scheme = colorScheme.getStyle(getType());
    Font font = textArea.getFontForTokenType(getType()); // scheme.font;

    if (font.isBold()) sb.append("<b>");
    if (font.isItalic()) sb.append("<em>");
    if (scheme.underline || isHyperlink()) sb.append("<u>");

    sb.append("<font");
    if (fontFamily) {
      sb.append(" face=\"").append(font.getFamily()).append("\"");
    }
    sb.append(" color=\"").append(getHTMLFormatForColor(scheme.foreground)).append("\">");

    // NOTE: Don't use getLexeme().trim() because whitespace tokens will
    // be turned into NOTHING.
    appendHtmlLexeme(textArea, sb, tabsToSpaces);

    sb.append("</font>");
    if (scheme.underline || isHyperlink()) sb.append("</u>");
    if (font.isItalic()) sb.append("</em>");
    if (font.isBold()) sb.append("</b>");

    return sb;
  }
Exemplo n.º 2
0
 static void printFont(PrintWriter html, Font font) {
   String style = "";
   if (font.isBold() && font.isItalic()) {
     style = "Bold & Italic";
   } else if (font.isBold()) {
     style = "Bold";
   } else if (font.isItalic()) {
     style = "Italic";
   }
   html.println("<td>Font: " + font.getFamily() + " " + font.getSize() + " " + style + "</td>");
   int w = 300, h = 30;
   BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
   Graphics2D g2 = img.createGraphics();
   Composite old = g2.getComposite();
   g2.setComposite(AlphaComposite.Clear);
   g2.fillRect(0, 0, w, h);
   g2.setComposite(old);
   g2.setColor(Color.BLACK);
   g2.setFont(font);
   g2.setRenderingHint(
       RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
   g2.drawString("The quick brown fox jumps over the lazy dog.", 5, 20);
   g2.dispose();
   html.println("<td>" + saveImage(img) + "</td>");
 }
 private String getFontStyle(final Font font) {
   if (font.isBold() && font.isItalic()) {
     return "bold-italic";
   }
   if (font.isBold()) {
     return "bold";
   }
   if (font.isItalic()) {
     return "italic";
   }
   return "plain";
 }
Exemplo n.º 4
0
 private static String fontStyle(Font aFont) {
   if (aFont == null) {
     return "null";
   }
   if (aFont.isBold() && aFont.isItalic()) {
     return BOLD_ITALIC;
   }
   if (aFont.isBold()) {
     return BOLD;
   }
   if (aFont.isItalic()) {
     return ITALIC;
   }
   return PLAIN;
 }
Exemplo n.º 5
0
  /**
   * Initializes the contents of the dialog from the given font object.
   *
   * @param font the font from which to read the properties.
   */
  public void setSelectedFont(final Font font) {
    if (font == null) {
      throw new NullPointerException();
    }
    this.boldCheck.setSelected(font.isBold());
    this.italicCheck.setSelected(font.isItalic());

    final String fontName = font.getName();
    ListModel model = this.fontlist.getModel();
    for (int i = 0; i < model.getSize(); i++) {
      if (fontName.equals(model.getElementAt(i))) {
        this.fontlist.setSelectedIndex(i);
        break;
      }
    }

    final String fontSize = String.valueOf(font.getSize());
    model = this.sizelist.getModel();
    for (int i = 0; i < model.getSize(); i++) {
      if (fontSize.equals(model.getElementAt(i))) {
        this.sizelist.setSelectedIndex(i);
        break;
      }
    }
  }
Exemplo n.º 6
0
 /**
  * Set the selected font to the given font.
  *
  * @param font Font.
  */
 public void setSelectedFont(Font font) {
   myFontFamilyComboBox.setSelectedItem(font.getFamily());
   int style = Font.PLAIN;
   if (font.isBold()) style += Font.BOLD;
   if (font.isItalic()) style += Font.ITALIC;
   myFontStyleComboBox.setSelectedIndex(style);
   myFontSizeSpinner.setValue(new Integer(font.getSize()));
 }
Exemplo n.º 7
0
  public Browser(String currentHref) {
    super();

    this.currentHref = currentHref;

    try {
      if (Bither.getMainFrame() != null) {
        Bither.getMainFrame().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
      }
      addHyperlinkListener(new ActivatedHyperlinkListener(Bither.getMainFrame(), this));

      loadingMessage = LocaliserUtils.getString("browser.loadingMessage");

      setEditable(false);
      setBackground(Themes.currentTheme.detailPanelBackground());

      String fontName = null;
      if (fontName == null || "".equals(fontName)) {
        fontName = ColorAndFontConstants.BITHER_DEFAULT_FONT_NAME;
      }
      // Add in san-serif as a fallback.
      fontName = fontName + ", san-serif";

      int fontSize = ColorAndFontConstants.BITHER_DEFAULT_FONT_SIZE;
      boolean isItalic = false;
      boolean isBold = false;
      Font adjustedFont = FontSizer.INSTANCE.getAdjustedDefaultFont();
      if (adjustedFont != null) {
        setFont(adjustedFont);
        fontSize = adjustedFont.getSize();
        isItalic = adjustedFont.isItalic();
        isBold = adjustedFont.isBold();
      }

      String fontCSS = "font-size:" + fontSize + "pt; font-family:" + fontName + ";";
      if (isItalic) {
        fontCSS = fontCSS + "font-style:italic;";
      } else {
        fontCSS = fontCSS + "font-style:normal;";
      }
      if (isBold) {
        fontCSS = fontCSS + "font-weight:bold;";
      } else {
        fontCSS = fontCSS + "font-weight:normal;";
      }

      HTMLEditorKit kit = new HTMLEditorKit();
      setEditorKit(kit);
      javax.swing.text.html.StyleSheet styleSheet = kit.getStyleSheet();
      styleSheet.addRule("body {" + fontCSS + "}");
      Document doc = kit.createDefaultDocument();
      setDocument(doc);

      log.debug("Trying to load '" + currentHref + "'...");
    } catch (Exception ex) {
      showUnableToLoadMessage(ex.getClass().getCanonicalName() + " " + ex.getMessage());
    }
  }
Exemplo n.º 8
0
 /** @see Object#toString() */
 public String toString() {
   return "[Font Data face='"
       + getName()
       + "' size="
       + size
       + " bold="
       + javaFont.isBold()
       + " italic="
       + javaFont.isItalic()
       + "]";
 }
Exemplo n.º 9
0
  @Override
  public void setFont(Font font) {
    if (font == null) font = txtSample.getFont();

    fontList.setSelectedValue(font.getName(), true);
    fontList.ensureIndexIsVisible(fontList.getSelectedIndex());
    sizeList.setSelectedValue("" + font.getSize(), true);
    sizeList.ensureIndexIsVisible(sizeList.getSelectedIndex());

    cbBold.setSelected(font.isBold());
    cbItalic.setSelected(font.isItalic());
  }
Exemplo n.º 10
0
  public static String encodeFont(Font font) {
    String editorFont = font.getFontName() + " ";
    if (font.isBold()) {
      editorFont += "bold ";
    }
    if (font.isItalic()) {
      editorFont += "italic ";
    }
    editorFont += font.getSize();

    return editorFont;
  }
Exemplo n.º 11
0
 public void setFont(Font a_font) {
   if (a_font != null && a_font != font) {
     font = a_font;
     baseStyle.clear();
     baseStyle.add(new AttributeRun(TextAttribute.FAMILY, font.getFamily()));
     baseStyle.add(new AttributeRun(TextAttribute.SIZE, font.getSize()));
     baseStyle.add(new AttributeRun(TextAttribute.WIDTH, TextAttribute.WIDTH_REGULAR));
     if (font.isBold())
       baseStyle.add(new AttributeRun(TextAttribute.WEIGHT, TextAttribute.WEIGHT_REGULAR));
     else baseStyle.add(new AttributeRun(TextAttribute.WEIGHT, TextAttribute.WEIGHT_REGULAR));
     if (font.isItalic())
       baseStyle.add(new AttributeRun(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE));
     else baseStyle.add(new AttributeRun(TextAttribute.POSTURE, TextAttribute.POSTURE_REGULAR));
     invalidText = true;
   }
 }
Exemplo n.º 12
0
  private static String getStyleName(Font font) {
    final StringBuilder sb = new StringBuilder();

    if (font.isPlain()) {
      sb.append("plain");
    } else {
      if (font.isBold()) {
        sb.append("bold");
      }
      if (font.isItalic()) {
        sb.append("italic");
      }
    }

    return sb.toString();
  }
Exemplo n.º 13
0
  @Override
  public String convertToString(Object srcData) throws Throwable {
    if (srcData == null) return null;
    if (!(srcData instanceof Font)) return null;

    Font fnt = (Font) srcData;
    String style = "";

    if (fnt.isBold()) style += " bold";
    if (fnt.isItalic()) style += " italic";
    if (fnt.isPlain()) style += " plain";

    String size = " " + Integer.toString(fnt.getSize());

    return fnt.getName() + style + size;
  }
Exemplo n.º 14
0
 /**
  * Returns the bounds for the character with the maximum bounds in the specified <code>Graphics
  * </code> context.
  *
  * @param context the specified <code>Graphics</code> context
  * @return a <code>Rectangle2D</code> that is the bounding box for the character with the maximum
  *     bounds.
  * @see java.awt.Font#getMaxCharBounds(java.awt.font.FontRenderContext)
  */
 public Rectangle2D getMaxCharBounds(final Graphics context) {
   final Font baseFont = getFont();
   final String name = baseFont.getName();
   final org.pentaho.reporting.libraries.fonts.registry.FontMetrics fontMetrics =
       metaData.getFontMetrics(
           name,
           baseFont.getSize2D(),
           baseFont.isBold(),
           baseFont.isItalic(),
           "UTF-8",
           false,
           false);
   return new Rectangle2D.Double(
       0,
       -StrictGeomUtility.toExternalValue(fontMetrics.getMaxAscent()),
       StrictGeomUtility.toExternalValue(fontMetrics.getMaxCharAdvance()),
       StrictGeomUtility.toExternalValue(
           fontMetrics.getMaxAscent() + fontMetrics.getMaxDescent() + fontMetrics.getLeading()));
 }
Exemplo n.º 15
0
  /**
   * Update the font in the default style of the document.
   *
   * @param font the new font to use or null to remove the font attribute from the document's style
   */
  private void updateFont(Font font) {
    StyledDocument doc = (StyledDocument) getComponent().getDocument();
    Style style = doc.getStyle(StyleContext.DEFAULT_STYLE);

    if (style == null) {
      return;
    }

    if (font == null) {
      style.removeAttribute(StyleConstants.FontFamily);
      style.removeAttribute(StyleConstants.FontSize);
      style.removeAttribute(StyleConstants.Bold);
      style.removeAttribute(StyleConstants.Italic);
    } else {
      StyleConstants.setFontFamily(style, font.getName());
      StyleConstants.setFontSize(style, font.getSize());
      StyleConstants.setBold(style, font.isBold());
      StyleConstants.setItalic(style, font.isItalic());
    }
  }
Exemplo n.º 16
0
 public FontChoice(Font font) {
   String[] fontList = Toolkit.getDefaultToolkit().getFontList();
   fontBox = new JComboBox();
   String fontFamily = font.getFamily();
   for (int i = 0; i < fontList.length; i++) {
     fontBox.addItem(fontList[i]);
     if (fontFamily.equals(fontList[i])) fontBox.setSelectedIndex(i);
   }
   // ! java bug fix
   if (fontFamily.equals("Times Roman")) fontBox.setSelectedItem("TimesRoman");
   //
   plainCheck = new JCheckBox("Plain?", font.isPlain());
   boldCheck = new JCheckBox("Bold?", font.isBold());
   italicCheck = new JCheckBox("Italic?", font.isItalic());
   //
   sizeBox = new JComboBox();
   int fontSize = font.getSize();
   int minFontSize = 3, maxFontSize = 60;
   for (int i = minFontSize; i < maxFontSize; i++) {
     sizeBox.addItem(new Integer(i).toString());
   }
   sizeBox.setSelectedIndex(font.getSize() - minFontSize);
   Dimension pSize = sizeBox.getPreferredSize();
   pSize.width = pSize.width * 2;
   sizeBox.setPreferredSize(pSize);
   //
   JPanel stylePanel = new JPanel();
   stylePanel.setLayout(new GridLayout(3, 1));
   stylePanel.add(plainCheck);
   stylePanel.add(boldCheck);
   stylePanel.add(italicCheck);
   stylePanel.setBorder(
       BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Styles"));
   //
   JPanel mPanel = this;
   mPanel.setLayout(new FlowLayout());
   mPanel.add(fontBox);
   mPanel.add(stylePanel);
   mPanel.add(sizeBox);
   mPanel.setBorder(BorderFactory.createEtchedBorder());
 }
Exemplo n.º 17
0
  @Override
  public void setFont(Font font) {
    if (font != null) {
      lastStringMeasured = null;

      this.font = font;
      fontGraphics.setFont(font);

      WFont f = new WFont();
      if (font.getFamily().equalsIgnoreCase("serif")) f.setFamily(GenericFamily.Serif);
      else if (font.getFamily().equalsIgnoreCase("sansserif")) f.setFamily(GenericFamily.SansSerif);
      else if (font.getFamily().equalsIgnoreCase("monospaced"))
        f.setFamily(GenericFamily.Monospace);

      if (font.isBold()) f.setWeight(Weight.Bold);
      if (font.isItalic()) f.setStyle(Style.Italic);

      f.setSize(Size.FixedSize, new WLength(font.getSize(), Unit.Point));

      painter.setFont(f);
    }
  }
Exemplo n.º 18
0
  /**
   * Apply a new font for the label.
   *
   * @param font new font to use.
   */
  public void setFont(Font font) {
    getLabel().setFont(font); // Set font so that getFont can be used direclty

    // Set the properties to the text (only for text label not for HTML or MATHML)
    if ((labelText != null)
        && !(labelText.startsWith(DOLLAR) && labelText.endsWith(DOLLAR))
        && !(labelText.startsWith("<") && labelText.endsWith(">"))) {
      // Now set the stylesheet because of text/html contents
      StyleSheet styleSheet = ((HTMLDocument) getLabel().getDocument()).getStyleSheet();
      styleSheet.addRule("body {font-family:" + font.getName() + ";}");
      styleSheet.addRule("body {font-size:" + font.getSize() + "pt;}");
      if (font.isBold()) {
        styleSheet.addRule("body {font-weight:bold;}");
      } else {
        styleSheet.addRule("body {font-weight:normal;}");
      }
      if (font.isItalic()) {
        styleSheet.addRule("body {font-style:italic;}");
      } else {
        styleSheet.addRule("body {font-style:normal;}");
      }
    }
  }
Exemplo n.º 19
0
 /**
  * Sets the font of the specified attribute.
  *
  * @param attr attribute to apply this font to
  * @param f the font to use
  */
 public static void setAttributeFont(MutableAttributeSet attr, Font f) {
   StyleConstants.setBold(attr, f.isBold());
   StyleConstants.setItalic(attr, f.isItalic());
   StyleConstants.setFontFamily(attr, f.getFamily());
   StyleConstants.setFontSize(attr, f.getSize());
 }
Exemplo n.º 20
0
 /**
  * Not really support for two tone styles, but a convience method to set all of the properties for
  * a single font.
  *
  * @param style Style being modified
  * @param font Font to add to the style.
  */
 public static final void setFont(Style style, Font font) {
   StyleConstants.setFontFamily(style, font.getFamily());
   StyleConstants.setFontSize(style, font.getSize());
   StyleConstants.setBold(style, font.isBold());
   StyleConstants.setItalic(style, font.isItalic());
 }
Exemplo n.º 21
0
  /** @see Graphics2D#drawString(String, float, float) */
  public void drawString(String s, float x, float y) {
    if (s.length() == 0) return;
    setFillPaint();
    if (onlyShapes) {
      drawGlyphVector(
          this.font.layoutGlyphVector(
              getFontRenderContext(),
              s.toCharArray(),
              0,
              s.length(),
              java.awt.Font.LAYOUT_LEFT_TO_RIGHT),
          x,
          y);
      //            Use the following line to compile in JDK 1.3
      //            drawGlyphVector(this.font.createGlyphVector(getFontRenderContext(), s), x, y);
    } else {
      boolean restoreTextRenderingMode = false;
      AffineTransform at = getTransform();
      AffineTransform at2 = getTransform();
      at2.translate(x, y);
      at2.concatenate(font.getTransform());
      setTransform(at2);
      AffineTransform inverse = this.normalizeMatrix();
      AffineTransform flipper = AffineTransform.getScaleInstance(1, -1);
      inverse.concatenate(flipper);
      double[] mx = new double[6];
      inverse.getMatrix(mx);
      cb.beginText();
      cb.setFontAndSize(baseFont, fontSize);
      // Check if we need to simulate an italic font.
      // When there are different fonts for italic, bold, italic bold
      // the font.getName() will be different from the font.getFontName()
      // value. When they are the same value then we are normally dealing
      // with a single font that has been made into an italic or bold
      // font.
      if (font.isItalic() && font.getFontName().equals(font.getName())) {
        float angle = baseFont.getFontDescriptor(BaseFont.ITALICANGLE, 1000);
        float angle2 = font.getItalicAngle();
        // We don't have an italic version of this font so we need
        // to set the font angle ourselves to produce an italic font.
        if (angle2 == 0) {
          // The JavaVM didn't have an angle setting for making
          // the font an italic font so use a default of
          // italic angle of 15 degrees.
          angle2 = 15.0f;
        } else {
          // This sign of the angle for Java and PDF seams
          // seams to be reversed.
          angle2 = -angle2;
        }
        if (angle == 0) {
          mx[2] = angle2 / 100.0f;
        }
      }
      cb.setTextMatrix(
          (float) mx[0], (float) mx[1], (float) mx[2], (float) mx[3], (float) mx[4], (float) mx[5]);
      Float fontTextAttributeWidth = (Float) font.getAttributes().get(TextAttribute.WIDTH);
      fontTextAttributeWidth =
          (fontTextAttributeWidth == null) ? TextAttribute.WIDTH_REGULAR : fontTextAttributeWidth;
      if (!TextAttribute.WIDTH_REGULAR.equals(fontTextAttributeWidth))
        cb.setHorizontalScaling(100.0f / fontTextAttributeWidth.floatValue());

      // Check if we need to simulate a bold font.
      // Do nothing if the BaseFont is already bold. This test is not foolproof but it will work
      // most of the times.
      if (baseFont.getPostscriptFontName().toLowerCase().indexOf("bold") < 0) {
        // Get the weight of the font so we can detect fonts with a weight
        // that makes them bold, but the Font.isBold() value is false.
        Float weight = (Float) font.getAttributes().get(TextAttribute.WEIGHT);
        if (weight == null) {
          weight = (font.isBold()) ? TextAttribute.WEIGHT_BOLD : TextAttribute.WEIGHT_REGULAR;
        }
        if ((font.isBold() || (weight.floatValue() >= TextAttribute.WEIGHT_SEMIBOLD.floatValue()))
            && (font.getFontName().equals(font.getName()))) {
          // Simulate a bold font.
          float strokeWidth =
              font.getSize2D()
                  * (weight.floatValue() - TextAttribute.WEIGHT_REGULAR.floatValue())
                  / 30f;
          if (strokeWidth != 1) {
            if (realPaint instanceof Color) {
              cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
              cb.setLineWidth(strokeWidth);
              Color color = (Color) realPaint;
              int alpha = color.getAlpha();
              if (alpha != currentStrokeGState) {
                currentStrokeGState = alpha;
                PdfGState gs = strokeGState[alpha];
                if (gs == null) {
                  gs = new PdfGState();
                  gs.setStrokeOpacity(alpha / 255f);
                  strokeGState[alpha] = gs;
                }
                cb.setGState(gs);
              }
              cb.setColorStroke(color);
              restoreTextRenderingMode = true;
            }
          }
        }
      }

      double width = 0;
      if (font.getSize2D() > 0) {
        float scale = 1000 / font.getSize2D();
        Font derivedFont = font.deriveFont(AffineTransform.getScaleInstance(scale, scale));
        width = derivedFont.getStringBounds(s, getFontRenderContext()).getWidth();
        if (derivedFont.isTransformed()) width /= scale;
      }
      // if the hyperlink flag is set add an action to the text
      Object url = getRenderingHint(HyperLinkKey.KEY_INSTANCE);
      if (url != null && !url.equals(HyperLinkKey.VALUE_HYPERLINKKEY_OFF)) {
        float scale = 1000 / font.getSize2D();
        Font derivedFont = font.deriveFont(AffineTransform.getScaleInstance(scale, scale));
        double height = derivedFont.getStringBounds(s, getFontRenderContext()).getHeight();
        if (derivedFont.isTransformed()) height /= scale;
        double leftX = cb.getXTLM();
        double leftY = cb.getYTLM();
        PdfAction action = new PdfAction(url.toString());
        cb.setAction(
            action,
            (float) leftX,
            (float) leftY,
            (float) (leftX + width),
            (float) (leftY + height));
      }
      if (s.length() > 1) {
        float adv = ((float) width - baseFont.getWidthPoint(s, fontSize)) / (s.length() - 1);
        cb.setCharacterSpacing(adv);
      }
      cb.showText(s);
      if (s.length() > 1) {
        cb.setCharacterSpacing(0);
      }
      if (!TextAttribute.WIDTH_REGULAR.equals(fontTextAttributeWidth)) cb.setHorizontalScaling(100);

      // Restore the original TextRenderingMode if needed.
      if (restoreTextRenderingMode) {
        cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
      }

      cb.endText();
      setTransform(at);
      if (underline) {
        // These two are supposed to be taken from the .AFM file
        // int UnderlinePosition = -100;
        int UnderlineThickness = 50;
        //
        double d = asPoints(UnderlineThickness, (int) fontSize);
        Stroke savedStroke = originalStroke;
        setStroke(new BasicStroke((float) d));
        y = (float) (y + asPoints(UnderlineThickness, (int) fontSize));
        Line2D line = new Line2D.Double(x, y, width + x, y);
        draw(line);
        setStroke(savedStroke);
      }
    }
  }
Exemplo n.º 22
0
 public boolean isItalic() {
   return font != null ? font.isItalic() : false;
 }
Exemplo n.º 23
0
  /**
   * Renders LaTeX equation using JLaTeXMath
   *
   * @param app
   * @param g2
   * @param x
   * @param y
   * @param text
   * @param font
   * @param serif
   * @param fgColor
   * @param bgColor
   * @return dimension of rendered equation
   */
  public final FormulaDimension drawEquationJLaTeXMath(
      Application app,
      GeoElement geo,
      Graphics2D g2,
      int x,
      int y,
      String text,
      Font font,
      boolean serif,
      Color fgColor,
      Color bgColor,
      boolean useCache,
      Integer maxWidth,
      Float lineSpace) {
    // TODO uncomment when \- works
    // text=addPossibleBreaks(text);

    int width = -1;
    int height = -1;
    int depth = 0;

    if (drawEquationJLaTeXMathFirstCall) { // first call

      drawEquationJLaTeXMathFirstCall = false;

      // initialise definitions
      if (initJLaTeXMath == null)
        initJLaTeXMath =
            new TeXFormula(
                "\\DeclareMathOperator{\\sech}{sech} \\DeclareMathOperator{\\csch}{csch} \\DeclareMathOperator{\\erf}{erf}");

      // make sure cache doesn't get too big
      JLaTeXMathCache.setMaxCachedObjects(100);

      Iterator<String> it = Unicode.getCharMapIterator();

      while (it.hasNext()) {
        String lang = it.next();
        Character ch = Unicode.getTestChar(lang);
        Font testFont = app.getFontCanDisplay(ch.toString(), true, Font.PLAIN, 12);
        if (testFont != null)
          TeXFormula.registerExternalFont(Character.UnicodeBlock.of(ch), testFont.getFontName());
        // Application.debug("LaTeX font registering: "+lang+" "+testFont.getFontName());

      }

      // Arabic is in standard Java fonts, so we don't need to search for a font
      TeXFormula.registerExternalFont(Character.UnicodeBlock.of('\u0681'), "Sans Serif", "Serif");

      try {
        WebStartAlphabetRegistration.register(AlphabetRegistration.JLM_GREEK);
        WebStartAlphabetRegistration.register(AlphabetRegistration.JLM_CYRILLIC);
        // URLAlphabetRegistration.register(new URL(app.getCodeBase()+"jlm_greek.jar"),
        // "greek",URLAlphabetRegistration.JLM_GREEK);
        // URLAlphabetRegistration.register(new URL(app.getCodeBase()+"jlm_cyrillic.jar"),
        // "cyrillic",URLAlphabetRegistration.JLM_CYRILLIC);
      } catch (Exception e) {
        e.printStackTrace();
      }
      LatexConvertorFactory factory = new LatexConvertorFactory(app.getKernel());
      DynamicAtom.setExternalConverterFactory(factory);
    }

    int style = 0;
    if (font.isBold()) style = style | TeXFormula.BOLD;
    if (font.isItalic()) style = style | TeXFormula.ITALIC;
    if (!serif) style = style | TeXFormula.SANSSERIF;

    // if we're exporting, we want to draw it full resolution
    // if it's a \jlmDynamic text, we don't want to add it to the cache
    if (app.exporting || text.indexOf("\\jlmDynamic") > -1 || !useCache) {

      // Application.debug("creating new icon for: "+text);
      TeXFormula formula;
      TeXIcon icon;

      try {
        formula = new TeXFormula(text);

        if (maxWidth == null)
          icon =
              formula.createTeXIcon(TeXConstants.STYLE_DISPLAY, font.getSize() + 3, style, fgColor);
        else
          icon =
              formula.createTeXIcon(
                  TeXConstants.STYLE_DISPLAY,
                  font.getSize() + 3,
                  TeXConstants.UNIT_CM,
                  maxWidth.intValue(),
                  TeXConstants.ALIGN_LEFT,
                  TeXConstants.UNIT_CM,
                  lineSpace.floatValue());
      } catch (MyError e) {
        // e.printStackTrace();
        // Application.debug("MyError LaTeX parse exception: "+e.getMessage()+"\n"+text);
        // Write error message to Graphics View

        formula = TeXFormula.getPartialTeXFormula(text);
        icon =
            formula.createTeXIcon(TeXConstants.STYLE_DISPLAY, font.getSize() + 3, style, fgColor);

        formula.createTeXIcon(
            TeXConstants.STYLE_DISPLAY,
            15,
            TeXConstants.UNIT_CM,
            4f,
            TeXConstants.ALIGN_LEFT,
            TeXConstants.UNIT_CM,
            0.5f);

        // Rectangle rec = drawMultiLineText(e.getMessage()+"\n"+text, x, y +
        // g2.getFont().getSize(), g2);
        // return new Dimension(rec.width, rec.height);
      } catch (Exception e) {
        // e.printStackTrace();
        // Application.debug("LaTeX parse exception: "+e.getMessage()+"\n"+text);
        // Write error message to Graphics View

        formula = TeXFormula.getPartialTeXFormula(text);
        icon =
            formula.createTeXIcon(TeXConstants.STYLE_DISPLAY, font.getSize() + 3, style, fgColor);

        // Rectangle rec = drawMultiLineText(e.getMessage()+"\n"+text, x, y +
        // g2.getFont().getSize(), g2);
        // return new Dimension(rec.width, rec.height);
      }
      icon.setInsets(new Insets(1, 1, 1, 1));

      jl.setForeground(fgColor);
      icon.paintIcon(jl, g2, x, y);
      return new FormulaDimension(icon.getIconWidth(), icon.getIconHeight(), icon.getIconDepth());
    }

    Object key = null;
    Image im = null;
    try {
      // if geoText != null then keep track of which key goes with the GeoText
      // so that we can remove it from the cache if it changes
      // eg for a (regular) dynamic LaTeX text eg "\sqrt{"+a+"}"
      if (geo == null)
        key =
            JLaTeXMathCache.getCachedTeXFormula(
                text,
                TeXConstants.STYLE_DISPLAY,
                style,
                font.getSize() + 3 /*font size*/,
                1 /* inset around the label*/,
                fgColor);
      else key = geo.getLaTeXCache().getCachedLaTeXKey(text, font.getSize() + 3, style, fgColor);

      im = JLaTeXMathCache.getCachedTeXFormulaImage(key);

      int ret[] = JLaTeXMathCache.getCachedTeXFormulaDimensions(key);
      width = ret[0];
      height = ret[1];
      depth = ret[2];

    } catch (Exception e) {
      // Application.debug("LaTeX parse exception: "+e.getMessage()+"\n"+text);
      // Write error message to Graphics View

      TeXFormula formula = TeXFormula.getPartialTeXFormula(text);
      im =
          formula.createBufferedImage(
              TeXConstants.STYLE_DISPLAY, font.getSize() + 3, Color.black, Color.white);

      // Rectangle rec = drawMultiLineText(e.getMessage()+"\n"+text, x, y + g2.getFont().getSize(),
      // g2);
      // return new Dimension(rec.width, rec.height);

    }

    g2.drawImage(im, x, y, null);

    if (width == -1) {
      width = im.getWidth(null);
    }
    if (height == -1) {
      height = im.getHeight(null);
    }

    return new FormulaDimension(width, height, depth);
  }
Exemplo n.º 24
0
  public void save(File outputBMFontFile) throws IOException, SlickException {
    File outputDir = outputBMFontFile.getParentFile();
    String outputName = outputBMFontFile.getName();
    if (outputName.endsWith(".fnt")) outputName = outputName.substring(0, outputName.length() - 4);

    unicodeFont.loadGlyphs();

    PrintStream out =
        new PrintStream(new FileOutputStream(new File(outputDir, outputName + ".fnt")));
    Font font = unicodeFont.getFont();
    int pageWidth = unicodeFont.getGlyphPageWidth();
    int pageHeight = unicodeFont.getGlyphPageHeight();
    out.println(
        "info face=\""
            + font.getFontName()
            + "\" size="
            + font.getSize()
            + " bold="
            + (font.isBold() ? 1 : 0)
            + " italic="
            + (font.isItalic() ? 1 : 0)
            + " charset=\"\" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1");
    out.println(
        "common lineHeight="
            + unicodeFont.getLineHeight()
            + " base=26 scaleW="
            + pageWidth
            + " scaleH="
            + pageHeight
            + " pages="
            + unicodeFont.getGlyphPages().size()
            + " packed=0");

    int pageIndex = 0, glyphCount = 0;
    for (Iterator pageIter = unicodeFont.getGlyphPages().iterator(); pageIter.hasNext(); ) {
      GlyphPage page = (GlyphPage) pageIter.next();
      String fileName;
      if (pageIndex == 0 && !pageIter.hasNext()) fileName = outputName + ".png";
      else fileName = outputName + (pageIndex + 1) + ".png";
      out.println("page id=" + pageIndex + " file=\"" + fileName + "\"");
      glyphCount += page.getGlyphs().size();
      pageIndex++;
    }

    out.println("chars count=" + glyphCount);

    // Always output space entry (codepoint 32).
    int[] glyphMetrics = getGlyphMetrics(font, 32);
    int xAdvance = glyphMetrics[1];
    out.println(
        "char id=32   x=0     y=0     width=0     height=0     xoffset=0     yoffset="
            + unicodeFont.getAscent()
            + "    xadvance="
            + xAdvance
            + "     page=0  chnl=0 ");

    pageIndex = 0;
    List allGlyphs = new ArrayList(512);
    for (Iterator pageIter = unicodeFont.getGlyphPages().iterator(); pageIter.hasNext(); ) {
      GlyphPage page = (GlyphPage) pageIter.next();
      for (Iterator glyphIter = page.getGlyphs().iterator(); glyphIter.hasNext(); ) {
        Glyph glyph = (Glyph) glyphIter.next();

        glyphMetrics = getGlyphMetrics(font, glyph.getCodePoint());
        int xOffset = glyphMetrics[0];
        xAdvance = glyphMetrics[1];

        out.println(
            "char id="
                + glyph.getCodePoint()
                + "   "
                + "x="
                + (int) (glyph.getImage().getTextureOffsetX() * pageWidth)
                + "     y="
                + (int) (glyph.getImage().getTextureOffsetY() * pageHeight)
                + "     width="
                + glyph.getWidth()
                + "     height="
                + glyph.getHeight()
                + "     xoffset="
                + xOffset
                + "     yoffset="
                + glyph.getYOffset()
                + "    xadvance="
                + xAdvance
                + "     page="
                + pageIndex
                + "  chnl=0 ");
      }
      allGlyphs.addAll(page.getGlyphs());
      pageIndex++;
    }

    String ttfFileRef = unicodeFont.getFontFile();
    if (ttfFileRef == null)
      Log.warn(
          "Kerning information could not be output because a TTF font file was not specified.");
    else {
      Kerning kerning = new Kerning();
      try {
        kerning.load(ResourceLoader.getResourceAsStream(ttfFileRef), font.getSize());
      } catch (IOException ex) {
        Log.warn("Unable to read kerning information from font: " + ttfFileRef);
      }

      Map glyphCodeToCodePoint = new HashMap();
      for (Iterator iter = allGlyphs.iterator(); iter.hasNext(); ) {
        Glyph glyph = (Glyph) iter.next();
        glyphCodeToCodePoint.put(
            new Integer(getGlyphCode(font, glyph.getCodePoint())),
            new Integer(glyph.getCodePoint()));
      }

      List kernings = new ArrayList(256);
      class KerningPair {
        public int firstCodePoint, secondCodePoint, offset;
      }
      for (Iterator iter1 = allGlyphs.iterator(); iter1.hasNext(); ) {
        Glyph firstGlyph = (Glyph) iter1.next();
        int firstGlyphCode = getGlyphCode(font, firstGlyph.getCodePoint());
        int[] values = kerning.getValues(firstGlyphCode);
        if (values == null) continue;
        for (int i = 0; i < values.length; i++) {
          Integer secondCodePoint =
              (Integer) glyphCodeToCodePoint.get(new Integer(values[i] & 0xffff));
          if (secondCodePoint == null) continue; // We may not be outputting the second character.
          int offset = values[i] >> 16;
          KerningPair pair = new KerningPair();
          pair.firstCodePoint = firstGlyph.getCodePoint();
          pair.secondCodePoint = secondCodePoint.intValue();
          pair.offset = offset;
          kernings.add(pair);
        }
      }
      out.println("kernings count=" + kerning.getCount());
      for (Iterator iter = kernings.iterator(); iter.hasNext(); ) {
        KerningPair pair = (KerningPair) iter.next();
        out.println(
            "kerning first="
                + pair.firstCodePoint
                + "  second="
                + pair.secondCodePoint
                + "  amount="
                + pair.offset);
      }
    }
    out.close();

    pageIndex = 0;
    ImageIOWriter imageWriter = new ImageIOWriter();
    for (Iterator pageIter = unicodeFont.getGlyphPages().iterator(); pageIter.hasNext(); ) {
      GlyphPage page = (GlyphPage) pageIter.next();
      String fileName;
      if (pageIndex == 0 && !pageIter.hasNext()) fileName = outputName + ".png";
      else fileName = outputName + (pageIndex + 1) + ".png";
      File imageOutputFile = new File(outputDir, fileName);
      FileOutputStream imageOutput = new FileOutputStream(imageOutputFile);
      try {
        imageWriter.saveImage(page.getImage(), "png", imageOutput, true);
      } finally {
        imageOutput.close();
      }
      // Flip output image.
      Image image = new ImageIcon(imageOutputFile.getAbsolutePath()).getImage();
      BufferedImage bufferedImage =
          new BufferedImage(
              image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
      Graphics g = bufferedImage.getGraphics();
      g.drawImage(image, 0, 0, null);
      AffineTransform tx = AffineTransform.getScaleInstance(-1, 1);
      tx.translate(0, -image.getHeight(null));
      AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
      bufferedImage = op.filter(bufferedImage, null);
      ImageIO.write(bufferedImage, "png", imageOutputFile);

      pageIndex++;
    }
  }