// ==========================================================================
// $Id: FontSelectionDialog.java,v 1.2 2002/09/09 20:12:30 hitoshi Exp $
// FontSelectionDialog
// ==========================================================================
// Copyright (C) 2002 Yamauchi, Hitoshi
//
//   Max-Planck-Institut fuer Informatik AG4
//   Stuhlsatzenhausweg 85, 66123 Saarbruecken
//   http://www.mpi-sb.mpg.de/
// 
// This software can be redistributed only under GNU copyleft.
//
// @author Yamauchi Hitoshi »³Æâ ÀÆ
// ==========================================================================
// $Revision: 1.2 $
// $Date: 2002/09/09 20:12:30 $
// $Author: hitoshi $
// ==========================================================================
package de.mpg.mpisb.timerclock;

import  java.awt.*;
import  javax.swing.*;

/**
 * FontSelectionDialog
 * @author  Yamauchi Hitoshi
 */
public class FontSelectionDialog extends javax.swing.JDialog {
    /** A return status code - returned if Cancel button has been pressed */
    public static final int RET_CANCEL = 0;
    /** A return status code - returned if OK button has been pressed */
    public static final int RET_OK = 1;

    /** Creates new form OkCancelDialog */
    public FontSelectionDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
	initAfterInit();
    }

    /** @return the return status of this dialog - one of RET_OK or RET_CANCEL */
    public int getReturnStatus() {
        return returnStatus;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() {//GEN-BEGIN:initComponents
        buttonPanel = new javax.swing.JPanel();
        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        mMainPanel = new javax.swing.JPanel();
        mSelectFontPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        mFontNameCB = new javax.swing.JComboBox();
        mItalicCBtn = new javax.swing.JCheckBox();
        mBoldCBtn = new javax.swing.JCheckBox();
        jLabel2 = new javax.swing.JLabel();
        mSizeCB = new javax.swing.JComboBox();
        
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                closeDialog(evt);
            }
        });
        
        buttonPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));
        
        okButton.setText("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });
        
        buttonPanel.add(okButton);
        
        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });
        
        buttonPanel.add(cancelButton);
        
        getContentPane().add(buttonPanel, java.awt.BorderLayout.SOUTH);
        
        mMainPanel.setLayout(new java.awt.BorderLayout());
        
        mSelectFontPanel.setLayout(new java.awt.GridBagLayout());
        java.awt.GridBagConstraints gridBagConstraints1;
        
        mSelectFontPanel.setBorder(new javax.swing.border.TitledBorder("Select Font"));
        jLabel1.setText("Font Name");
        gridBagConstraints1 = new java.awt.GridBagConstraints();
        gridBagConstraints1.gridx = 0;
        gridBagConstraints1.gridy = 0;
        gridBagConstraints1.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints1.ipadx = 6;
        mSelectFontPanel.add(jLabel1, gridBagConstraints1);
        
        mFontNameCB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mFontNameCBActionPerformed(evt);
            }
        });
        
        gridBagConstraints1 = new java.awt.GridBagConstraints();
        gridBagConstraints1.gridx = 1;
        gridBagConstraints1.gridy = 0;
        gridBagConstraints1.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints1.insets = new java.awt.Insets(0, 0, 0, 10);
        mSelectFontPanel.add(mFontNameCB, gridBagConstraints1);
        
        mItalicCBtn.setText("italic");
        mItalicCBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mItalicCBtnActionPerformed(evt);
            }
        });
        
        gridBagConstraints1 = new java.awt.GridBagConstraints();
        gridBagConstraints1.gridx = 2;
        gridBagConstraints1.gridy = 0;
        gridBagConstraints1.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints1.insets = new java.awt.Insets(0, 10, 0, 10);
        mSelectFontPanel.add(mItalicCBtn, gridBagConstraints1);
        
        mBoldCBtn.setText("bold");
        mBoldCBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mBoldCBtnActionPerformed(evt);
            }
        });
        
        gridBagConstraints1 = new java.awt.GridBagConstraints();
        gridBagConstraints1.gridx = 3;
        gridBagConstraints1.gridy = 0;
        gridBagConstraints1.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints1.ipady = 10;
        gridBagConstraints1.insets = new java.awt.Insets(0, 10, 0, 10);
        mSelectFontPanel.add(mBoldCBtn, gridBagConstraints1);
        
        jLabel2.setText("Size");
        gridBagConstraints1 = new java.awt.GridBagConstraints();
        gridBagConstraints1.ipadx = 5;
        mSelectFontPanel.add(jLabel2, gridBagConstraints1);
        
        mSizeCB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mSizeCBActionPerformed(evt);
            }
        });
        
        gridBagConstraints1 = new java.awt.GridBagConstraints();
        gridBagConstraints1.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints1.ipadx = 6;
        mSelectFontPanel.add(mSizeCB, gridBagConstraints1);
        
        mMainPanel.add(mSelectFontPanel, java.awt.BorderLayout.NORTH);
        
        getContentPane().add(mMainPanel, java.awt.BorderLayout.CENTER);
        
        pack();
    }//GEN-END:initComponents

    private void mSizeCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mSizeCBActionPerformed
      // Add your handling code here:
      this.updateFont();
    }//GEN-LAST:event_mSizeCBActionPerformed

    private void mBoldCBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mBoldCBtnActionPerformed
      // Add your handling code here:
      this.updateFont();
    }//GEN-LAST:event_mBoldCBtnActionPerformed

    private void mItalicCBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mItalicCBtnActionPerformed
      // Add your handling code here:
      this.updateFont();
    }//GEN-LAST:event_mItalicCBtnActionPerformed

    private void mFontNameCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mFontNameCBActionPerformed
      // Add your handling code here:
      this.updateFont();
    }//GEN-LAST:event_mFontNameCBActionPerformed

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
      doClose(RET_OK);
    }//GEN-LAST:event_okButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
      doClose(RET_CANCEL);
    }//GEN-LAST:event_cancelButtonActionPerformed

    /** Closes the dialog */
    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
        doClose(RET_CANCEL);
    }//GEN-LAST:event_closeDialog

    private void doClose(int retStatus) {
        returnStatus = retStatus;
        setVisible(false);
        dispose();
    }

  /**
   * initialize after GUI component initialize
   */
  public void initAfterInit()
  {
    this.mInitOK = false;
    
    // font name
    java.awt.GraphicsEnvironment gEnv = 
      java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment();
    String envfonts[] = gEnv.getAvailableFontFamilyNames();
    int defaultfnIdx = -1;

    // lookup default font name 
    for(int i = 0; i < envfonts.length; i++ ) 
    {
      if(DEFAULT_FONTNAME.equals(envfonts[i]))
      {
	defaultfnIdx = i;
      }
    }

    this.mFontNameVec = new java.util.Vector();
    if(defaultfnIdx < 0)
    {
      // can not found the DEFAULT_FONTNAME, set it first
      this.mFontNameVec.add(DEFAULT_FONTNAME);      
      this.mFontNameCB.addItem(DEFAULT_FONTNAME);
      defaultfnIdx = 0;
    }

    for(int i = 0; i < envfonts.length; i++ ) 
    {
      this.mFontNameVec.add(envfonts[i]);
      this.mFontNameCB.addItem(envfonts[i]);
    }
    this.mFontNameCB.setSelectedIndex(defaultfnIdx);      


    // size
    final int start = 6;
    final int num   = 70;
    this.mFontSizeAry = new int [num];
    for(int i = 0; i < num; i++ ) 
    {
      int p = start + i;
      this.mFontSizeAry[i] = p;
      this.mSizeCB.addItem(new Integer(p));
    }
    this.mSizeCB.setSelectedIndex(18 - start);    

    // font display panel
    this.mMainPanel.add(this.getFontPanel(), java.awt.BorderLayout.CENTER);
    this.pack();

    this.mInitOK = true;
  }

  // 
  private FontPanel getFontPanel()
  {
    this.mFontDispPanel = new FontPanel();    
    this.mFontDispPanel.setBorder(new javax.swing.border.TitledBorder("Sample Font"));
    this.mFontDispPanel.setMinimumSize(new java.awt.Dimension(20, 100));
    this.mFontDispPanel.setPreferredSize(new java.awt.Dimension(20, 100));
    return(this.mFontDispPanel);
  }

  /** 
   * get selected font name 
   */
  public String getSelectedFontName()
  {
    return((String)(this.mFontNameVec.get(this.mFontNameCB.getSelectedIndex())));
  }
  /** 
   * is italic
   */
  public boolean isItalic()
  {
    return(this.mItalicCBtn.isSelected());
  }
  /** 
   * is bold
   */
  public boolean isBold()
  {
    return(this.mBoldCBtn.isSelected());
  }
  /** 
   * get style
   */
  public int getStyle(boolean isItalic, boolean isBold)
  {
    if((!(isItalic)) && (!(isBold)))
    {
      return(Font.PLAIN);
    }
    else
    {
      return((isItalic ? Font.ITALIC : 0) + 
	     (isBold   ? Font.BOLD   : 0));
    }
  }
  /** 
   * get selected font style
   */
  public int getSelectedFontStyle()
  {
    return(this.getStyle(this.isItalic(), this.isBold()));    
  }

  /** 
   * get selected size
   */
  public int getSelectedFontSize()
  {
    return(this.mFontSizeAry[this.mSizeCB.getSelectedIndex()]);
  }


  /** 
   * set current font
   */
  public void setCurrentFont(String fname, boolean isItalic, boolean isBold, int size)
  {
    for(int i = 0; i < this.mFontNameVec.size(); i++)
    {
      if(fname.equals((String)(this.mFontNameVec.get(i))))
      {
	this.mFontNameCB.setSelectedIndex(i);
	break;
      }
    }
    
    this.mItalicCBtn.setSelected(isItalic);    
    this.mBoldCBtn.setSelected(isBold);    

    for(int i = 0; i < this.mFontSizeAry.length; i++)
    {
      if(this.mFontSizeAry[i] == size)
      {
	this.mSizeCB.setSelectedIndex(i);
	break;
      }
    }
    updateFont();
  }

  /** 
   * set current font
   */
  public void setCurrentFont(String fname, int fontstyle, int size)
  {
    boolean it = ((fontstyle & Font.ITALIC) > 0) ? true : false;
    boolean bd = ((fontstyle & Font.BOLD)   > 0) ? true : false;  
    this.setCurrentFont(fname, it, bd, size);
  }


  /*
   * update font
   */
  private void updateFont()
  {
    if(this.mInitOK)
    {
      this.mFontDispPanel.changeFont(this.getSelectedFontName(),
				     this.getSelectedFontStyle(),
				     this.getSelectedFontSize());
    }
    repaint();
  }

  /*
   * font display panel
   */
  class FontPanel extends JPanel 
  {
    public FontPanel()
    { 
      this.mCurFont = new Font(DEFAULT_FONTNAME, Font.PLAIN, 18);
    }

    // Resets thisFont to the currently selected fontname, size and style attributes.
    public void changeFont(String fontname, int fontstate, int size)
    {
      this.mCurFont = new Font(fontname, fontstate, size);
      repaint();
    }
    
    // paint component
    // public void paintComponent (Graphics g) 
    public void draw(Graphics g) 
    {
      // super.paintComponent(g);
      Graphics2D g2 = (Graphics2D)g;
      int w = this.getWidth();
      int h = this.getHeight();
      g2.setColor(Color.black);
      g2.setFont(this.mCurFont);
      FontMetrics metrics = g2.getFontMetrics();
      int width  = metrics.stringWidth(FONT_TEST_STR);
      int height = metrics.getHeight();
      // Message.verboseOut("DEBUG: w = " + w + ", h = " + h + "\n");
      g2.drawString(FONT_TEST_STR, w/2 - width/2, h - height/2);
    }

    public void paint(Graphics g)
    {
      // Message.verboseOut("DEBUG: draw\n");
      this.draw(g);
    }
    // private 
    private Font mCurFont;
  }

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) 
  {
    FontSelectionDialog fsd = new FontSelectionDialog(new javax.swing.JFrame(), true);
    fsd.setCurrentFont("TimesRoman", true, false, 24);
    fsd.show();
    if(fsd.getReturnStatus() == RET_OK)
    {
      System.out.println("OK");
      System.out.println("Fontname = " + fsd.getSelectedFontName() +
			 ", italic = " + fsd.isItalic() + 
			 ", bold = "   + fsd.isBold()   + 
			 ", size = "   + fsd.getSelectedFontSize());
    }
    else
    {
      System.out.println("Cancel");
    }
  }

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JPanel buttonPanel;
  private javax.swing.JButton okButton;
  private javax.swing.JButton cancelButton;
  private javax.swing.JPanel mMainPanel;
  private javax.swing.JPanel mSelectFontPanel;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JComboBox mFontNameCB;
  private javax.swing.JCheckBox mItalicCBtn;
  private javax.swing.JCheckBox mBoldCBtn;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JComboBox mSizeCB;
  // End of variables declaration//GEN-END:variables

  private int returnStatus = RET_CANCEL;
  private java.util.Vector mFontNameVec = null;
  private int [] mFontSizeAry = null;
  private String DEFAULT_FONTNAME = "TimesRoman";
  private String FONT_TEST_STR = "ABC abc : Pick me!";
  private FontPanel mFontDispPanel;
  private boolean   mInitOK = false;
}
