예제 #1
0
  @NotNull
  public static String getHtmlWithFonts(@NotNull String input, int style, @NotNull Font baseFont) {
    int start = baseFont.canDisplayUpTo(input);
    if (start == -1) return input;

    Font font = null;
    StringBuilder result = new StringBuilder();
    for (int i = start; i < input.length(); i++) {
      char c = input.charAt(i);
      if (baseFont.canDisplay(c)) {
        if (font != null) result.append("</font>");
        result.append(c);
        font = null;
      } else if (font != null && font.canDisplay(c)) {
        result.append(c);
      } else {
        if (font != null) result.append("</font>");
        font = getFontAbleToDisplay(c, baseFont.getSize(), style, baseFont.getFamily());
        if (font != baseFont) result.append("<font face=\"").append(font.getFamily()).append("\">");
        result.append(c);
      }
    }
    if (font != null) result.append("</font>");

    return result.toString();
  }
예제 #2
0
 // {{{ parseHighlightStyle()
 SyntaxStyle parseHighlightStyle(String style) {
   Font f = (resultTree != null) ? resultTree.getFont() : UIManager.getFont("Tree.font");
   SyntaxStyle s;
   try {
     s = SyntaxUtilities.parseStyle(style, f.getFamily(), f.getSize(), true, null);
   } catch (Exception e) {
     style = "color:#000000";
     s = SyntaxUtilities.parseStyle(style, f.getFamily(), f.getSize(), true);
   }
   return s;
 } // }}}
 private static void fillStyledFontMap() {
   Font[] allFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
   for (Font font : allFonts) {
     String name = font.getName();
     Integer style = null;
     if (!SystemInfo.isAppleJvm) {
       style =
           FONT_NAME_TO_STYLE.get(
               name); // workaround with explicit fontName->style mapping doesn't work on Apple JVM
     }
     if (style == null) {
       if (!Patches.JDK_MAC_FONT_STYLE_BUG) continue;
       style = getFontStyle(name);
     }
     if (style != Font.PLAIN) {
       String familyName = font.getFamily();
       Pair<String, Integer>[] entry = ourStyledFontMap.get(familyName);
       if (entry == null) {
         //noinspection unchecked
         entry = new Pair[4];
         for (int i = 1; i < 4; i++) {
           entry[i] = Pair.create(familyName, i);
         }
         ourStyledFontMap.put(familyName, entry);
       }
       entry[style] = Pair.create(name, Font.PLAIN);
     }
   }
 }
예제 #4
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>");
 }
예제 #5
0
  private void sizeListValueChanged(ListSelectionEvent e) {
    int size = Integer.parseInt((String) sizeList.getSelectedValue());

    font = new Font(font.getFamily(), font.getStyle(), size);

    previewLabel.setFont(font);
  }
예제 #6
0
 public void setSelectedFont(Font font) {
   selectedFont = font;
   family = font.getFamily();
   style = font.getStyle();
   size = font.getSize();
   preview.setFont(font);
 }
예제 #7
0
 private static File findFileForFont(Font font, final boolean matchStyle) {
   final String normalizedFamilyName =
       font.getFamily().toLowerCase(Locale.getDefault()).replace(" ", "");
   final int fontStyle = font.getStyle();
   File[] files =
       new File(System.getProperty("user.home"), "Library/Fonts")
           .listFiles(
               new FilenameFilter() {
                 @Override
                 public boolean accept(File file, String name) {
                   String normalizedName = name.toLowerCase(Locale.getDefault());
                   return normalizedName.startsWith(normalizedFamilyName)
                       && (normalizedName.endsWith(".otf") || normalizedName.endsWith(".ttf"))
                       && (!matchStyle
                           || fontStyle == ComplementaryFontsRegistry.getFontStyle(name));
                 }
               });
   if (files == null || files.length == 0) return null;
   // to make sure results are predictable we return first file in alphabetical order
   return Collections.min(
       Arrays.asList(files),
       new Comparator<File>() {
         @Override
         public int compare(File file1, File file2) {
           return file1.getName().compareTo(file2.getName());
         }
       });
 }
예제 #8
0
    @Override
    public void actionPerformed(ActionEvent e) {
      // TODO Auto-generated method stub

      Object source = e.getSource();
      if (source == ok) {
        response = APPLY_OPTION;
        this.setVisible(false);
      } else if (source == cancel) {
        response = CANCEL_OPTION;
        this.setVisible(false);
      } else if (source == sizeCombo) {
        // get the number from the source
        JComboBox number = (JComboBox) source;
        String numberItem = (String) number.getSelectedItem();
        Font temp = example.getFont();
        // then set the font
        int newSize = Integer.parseInt(numberItem);
        example.setFont(new Font(temp.getFamily(), temp.getStyle(), newSize));
      } else if (source == fontCombo) {
        JComboBox font = (JComboBox) source;
        String s = (String) font.getSelectedItem();
        Font tmp = example.getFont();
        example.setFont(new Font(s, tmp.getStyle(), tmp.getSize()));
      } else if (source == foreground) {
        Color tmp = JColorChooser.showDialog(this, "Choose text color", example.getForeground());
        MenuBar.shapeLBG.setBackground(tmp);
        if (tmp != null) example.setForeground(tmp);
      }
    }
예제 #9
0
  /**
   * @param message Message to show in dialog.
   * @param severity
   *     <p>HTML tag can be used to format and add links into message. &lt;html&gt; and &lt;body&gt;
   *     are automatic added
   */
  public static void showClickableMessage(String message, int severity) {
    JLabel l = new JLabel();
    Font font = l.getFont();
    StringBuilder html = new StringBuilder("");
    Logger.logDebug(message);
    html.append("<html><body style=\"" + "font-family:")
        .append(font.getFamily())
        .append(";")
        .append("font-weight:")
        .append(font.isBold() ? "bold" : "normal")
        .append(";")
        .append("font-size:")
        .append(font.getSize())
        .append("pt;")
        .append("\">");

    html.append(message).append(" ").append("</html>");

    JEditorPane ep = new JEditorPane("text/html", html.toString());
    ep.addHyperlinkListener(
        new HyperlinkListener() {
          @Override
          public void hyperlinkUpdate(HyperlinkEvent e) {
            if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
              OSUtils.browse(
                  e.getURL().toString()); // roll your own link launcher or use Desktop if J6+
            }
          }
        });
    ep.setEditable(false);
    Logger.logDebug("Displaying dialog");
    JOptionPane.showMessageDialog(LaunchFrame.getInstance(), ep, null, severity);
    Logger.logDebug("Returned from dialog");
  }
  @Override
  public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    Object source = e.getSource();

    if (source == ok) {
      userResponse = APPLY_OPTION;
      this.setVisible(false);
    } else if (source == cancel) {
      userResponse = CANCEL_OPTION;
      this.setVisible(false);
    } else if (source == fontCombo) {
      @SuppressWarnings("unchecked")
      JComboBox<String> cb = (JComboBox<String>) source;
      String s = (String) cb.getSelectedItem();
      Font tmp = example.getFont();
      example.setFont(new Font(s, tmp.getStyle(), tmp.getSize()));
    } else if (source == sizeCombo) {
      @SuppressWarnings("unchecked")
      JComboBox<String> cb = (JComboBox<String>) source;
      String s = (String) cb.getSelectedItem();
      int newSize = Integer.parseInt(s);
      Font tmp = example.getFont();
      example.setFont(new Font(tmp.getFamily(), tmp.getStyle(), newSize));
    } else if (source == foreground) {
      Color tmp = JColorChooser.showDialog(this, "Choose text color", example.getForeground());
      if (tmp != null) example.setForeground(tmp);
    }
  }
예제 #11
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;
  }
예제 #12
0
 public static void bumpUpFontSize(Component widget, int bumps) {
   if (!UserPreferences.readLocalePref()
       .equals("ko")) { // HACK!!!  refector with variable localeSupportsBold
     Font f = widget.getFont();
     widget.setFont(new Font(f.getFamily(), f.getStyle(), f.getSize() + bumps));
   }
 }
예제 #13
0
  /**
   * format a given Font to a string, following "Font.decode()" format, ie fontname-style-pointsize,
   * fontname-pointsize, fontname-style or fontname, where style is one of "BOLD", "ITALIC",
   * "BOLDITALIC" (default being PLAIN)
   */
  public static String formatFontAsProperties(Font font) {
    // jpicedt.Log.debug(new MiscUtilities(),"formatFontAsProperties","font="+font);
    String family = font.getFamily();
    /*
    System.out.println("family="+family);
    String faceName = font.getFontName();
    System.out.println("faceName="+faceName);
    String logicalName = font.getName();
    System.out.println("logicalName"+logicalName);
    String psName = font.getPSName();
    System.out.println("PSName="+psName);
    */

    StringBuffer buf = new StringBuffer(20);
    buf.append(family);
    buf.append("-");
    switch (font.getStyle()) {
      case Font.ITALIC:
        buf.append("ITALIC-");
        break;
      case Font.BOLD:
        buf.append("BOLD-");
        break;
      case Font.BOLD | Font.ITALIC:
        buf.append("BOLDITALIC-");
        break;
      default: // PLAIN -> nothing
    }
    buf.append(Integer.toString(font.getSize()));
    return buf.toString();
  }
예제 #14
0
 private void updateWithFont(Font aFont) {
   fontNameList.setSelectedValue(aFont.getFamily(), true);
   fontStyleList.setSelectedValue(fontStyle(aFont), true);
   fontSizeList.setSelectedValue("" + aFont.getSize(), true);
   previewLabel.setFont(aFont);
   previewLabel.setText(fontDescription(aFont));
 }
예제 #15
0
 public void setFontSize(int fontSize) {
   estabilishOwnFont();
   setFont(
       getFrame()
           .getController()
           .getFontThroughMap(new Font(font.getFamily(), font.getStyle(), fontSize)));
 }
예제 #16
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()));
 }
예제 #17
0
 public static void makeEmphasized(Component widget) {
   // Set to bold amd add color
   Font font = widget.getFont();
   if (!UserPreferences.readLocalePref()
       .equals("ko")) // HACK!!!  refector with variable localeSupportsBold
   widget.setFont(new Font(font.getFamily(), Font.BOLD, font.getSize()));
   widget.setForeground(UIProperties.emphasisColor);
 }
예제 #18
0
 private void resetStyles() {
   doc.setParagraphAttributes(0, doc.getLength(), plainStyle, true);
   StyleConstants.setFontSize(fontSizeStyle, 14);
   Font f = plainFont;
   StyleConstants.setFontFamily(fontSizeStyle, f.getFamily());
   doc.setParagraphAttributes(0, doc.getLength(), fontSizeStyle, false);
   setupFont();
 }
예제 #19
0
 public void toggleItalic() {
   estabilishOwnFont();
   setFont(
       getFrame()
           .getController()
           .getFontThroughMap(
               new Font(font.getFamily(), font.getStyle() ^ Font.ITALIC, font.getSize())));
 }
예제 #20
0
 /** @param args command line params */
 public static void main(String[] args) {
   try {
     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
     f = UIManager.getDefaults().getFont("TabbedPane.font");
     f = new Font(f.getFamily(), Font.BOLD, f.getSize());
   } catch (Exception x) {
   }
   new TestProgram().start();
 }
예제 #21
0
 /**
  * Get a supported monospace font.
  *
  * @return font
  */
 public static Font getMonospaceFont() {
   for (String fontName : monospaceFontNames) {
     Font font = Font.decode(fontName + "-11");
     if (!font.getFamily().equalsIgnoreCase("Dialog")) {
       return font;
     }
   }
   return new Font("Monospace", Font.PLAIN, 11);
 }
예제 #22
0
    public Shuttle(Graphics2D g, Element root) {
      this.g = g;

      Font font = g.getFont();
      this.fontSize = font.getSize();
      this.fontFamily = font.getFamily();
      this.svgRoot = root;
      this.node = root;
      this.transform = new AffineTransform(g.getTransform());
      this.clip = g.getClip();
    }
예제 #23
0
 /**
  * Sets the default font for an HTML document (e.g., in a tool tip displaying HTML). This is here
  * because when rendering HTML, {@code setFont()} is not honored.
  *
  * @param doc The document to modify.
  * @param font The font to use.
  * @param fg The default foreground color.
  */
 public static void setFont(HTMLDocument doc, Font font, Color fg) {
   doc.getStyleSheet()
       .addRule(
           "body { font-family: "
               + font.getFamily()
               + "; font-size: "
               + font.getSize()
               + "pt"
               + "; color: "
               + getHexString(fg)
               + "; }");
 }
예제 #24
0
  private void _applyFontStyleForSelection(Font font) {
    StyledDocument doc = mTextEditor.getStyledDocument();
    MutableAttributeSet attrs = mTextEditor.getInputAttributes();
    StyleConstants.setFontFamily(attrs, font.getFamily());
    StyleConstants.setFontSize(attrs, font.getSize());
    StyleConstants.setBold(attrs, ((font.getStyle() & Font.BOLD) != 0));
    StyleConstants.setItalic(attrs, ((font.getStyle() & Font.ITALIC) != 0));
    StyleConstants.setUnderline(attrs, ((font.getStyle() & Font.CENTER_BASELINE) != 0));

    int start = mTextEditor.getSelectionStart();
    int end = mTextEditor.getSelectionEnd();
    doc.setCharacterAttributes(start, (end - start), attrs, false);
  }
예제 #25
0
  /** @see javax.swing.JPanel#updateUI() */
  @Override
  public void updateUI() {
    super.updateUI();

    if (feedItemDetail != null) {
      Font font = UIManager.getFont("Label.font");

      HTMLEditorKit kit = (HTMLEditorKit) feedItemDetail.getEditorKit();
      StyleSheet sheet = kit.getStyleSheet();
      sheet.addRule(
          "body {font-family: " + font.getFamily() + "; font-size: " + font.getSize() + "pt;}");
    }
  }
예제 #26
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);
    }
  }
예제 #27
0
  public static void loadCustomFonts(GameFileSystem fileSystem) {
    File folder =
        new File(
            ResourceManager.isCompleteIDEMode()
                ? fileSystem.getConfigFolder().getParentFile()
                : fileSystem.getPluginFolder(),
            "fonts");

    if (!folder.exists()) return;

    RFDHLog.printlnEx("Loading custom fonts...");
    for (File file : folder.listFiles()) {
      if (file.isFile() && file.getName().toLowerCase().endsWith("ttf")) {
        Font font = null;
        try {
          font = Font.createFont(Font.TRUETYPE_FONT, file);
        } catch (Throwable t) {
          RFDHLog.exception(
              "Couldn't load font file \""
                  + file.getAbsolutePath()
                  + "\". Message was: "
                  + t.getMessage());
        }

        if (font != null) {
          Font testFont = new Font(font.getName(), font.getStyle(), font.getSize());
          if (testFont.getName().equals(font.getName())
              && testFont.getFamily().equals(font.getFamily()))
            RFDHLog.exception(
                "Couldn't register font \"" + font.getName() + "\". It is already registered.");
          else if (GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(font))
            RFDHLog.printlnEx("    Loaded and registered custom font \"" + font.getName() + "\".");
          else RFDHLog.exception("Couldn't register font \"" + font.getName() + "\".");
        }
      }
    }
  }
예제 #28
0
  /** Returns the specified font, but with the style's bold, underline and italic flags applied. */
  public Font getStyledFont(Font font) {
    if (font == null) throw new NullPointerException("font param must not" + " be null");
    if (font.equals(lastFont)) return lastStyledFont;
    lastFont = font;

    lastStyledFont =
        new Font(
            font.getFamily(), (bold ? Font.BOLD : 0) | (italic ? Font.ITALIC : 0), font.getSize());
    if (underlined) {
      Map<TextAttribute, Object> attr = new Hashtable<TextAttribute, Object>();
      attr.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
      lastStyledFont = lastStyledFont.deriveFont(attr);
    }
    return lastStyledFont;
  }
예제 #29
0
 /** Returns the font metrics for the styled font. */
 public FontMetrics getFontMetrics(Font font, JComponent comp) {
   if (font == null) throw new NullPointerException("font param must not" + " be null");
   if (font.equals(lastFont) && fontMetrics != null) return fontMetrics;
   lastFont = font;
   lastStyledFont =
       new Font(
           font.getFamily(), (bold ? Font.BOLD : 0) | (italic ? Font.ITALIC : 0), font.getSize());
   if (underlined) {
     Map<TextAttribute, Object> attr = new Hashtable<TextAttribute, Object>();
     attr.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
     lastStyledFont = lastStyledFont.deriveFont(attr);
   }
   // fontMetrics = Toolkit.getDefaultToolkit().getFontMetrics(lastStyledFont);
   fontMetrics = comp.getFontMetrics(lastStyledFont);
   return fontMetrics;
 }
  /** Change the state of the text */
  @Override
  public void itemStateChanged(ItemEvent e) {
    // TODO Auto-generated method stub
    Object source = e.getSource();
    Font tmp = example.getFont();
    int style = tmp.getStyle();

    if (source == italic)
      if (italic.isSelected()) style = style | Font.ITALIC; // turn italic on
      else style = style & ~Font.ITALIC; // turn italic off
    else if (source == bold)
      if (bold.isSelected()) style = style | Font.BOLD; // turn bold on
      else style = style & ~Font.BOLD; // turn bold off

    example.setFont(new Font(tmp.getFamily(), style, tmp.getSize()));
  }