ConfigItem: better boolean, better help icon
[nikiroo-utils.git] / src / be / nikiroo / utils / ui / ConfigItem.java
index 691c6198319b24d71ea2710e6f96f7aa348a3c49..3185f1378d1884188cf01290852fb0ff9c2e7472 100644 (file)
@@ -1,21 +1,48 @@
 package be.nikiroo.utils.ui;
 
 import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Cursor;
 import java.awt.Dimension;
-import java.util.ArrayList;
-import java.util.List;
+import java.awt.Graphics2D;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.IOException;
 
+import javax.swing.Icon;
+import javax.swing.ImageIcon;
+import javax.swing.InputVerifier;
+import javax.swing.JButton;
+import javax.swing.JCheckBox;
+import javax.swing.JColorChooser;
+import javax.swing.JComboBox;
+import javax.swing.JComponent;
+import javax.swing.JFileChooser;
 import javax.swing.JLabel;
+import javax.swing.JOptionPane;
 import javax.swing.JPanel;
+import javax.swing.JPasswordField;
 import javax.swing.JTextField;
-import javax.swing.border.EmptyBorder;
+import javax.swing.plaf.basic.BasicArrowButton;
 
+import be.nikiroo.utils.Image;
+import be.nikiroo.utils.StringUtils;
+import be.nikiroo.utils.StringUtils.Alignment;
 import be.nikiroo.utils.resources.Bundle;
-import be.nikiroo.utils.resources.Meta;
+import be.nikiroo.utils.resources.Meta.Format;
+import be.nikiroo.utils.resources.MetaInfo;
 
 /**
  * A graphical item that reflect a configuration option from the given
  * {@link Bundle}.
+ * <p>
+ * This graphical item can be edited, and the result will be saved back into the
+ * linked {@link MetaInfo}; you still have to save the {@link MetaInfo} should
+ * you wish to, of course.
  * 
  * @author niki
  * 
@@ -24,92 +51,448 @@ import be.nikiroo.utils.resources.Meta;
  */
 public class ConfigItem<E extends Enum<E>> extends JPanel {
        private static final long serialVersionUID = 1L;
-       private Class<E> type;
-       private final Bundle<E> bundle;
-       private final E id;
 
-       private Meta meta;
-       private String value;
+       /** A small (?) blue in PNG, base64 encoded. */
+       private static String infoImage64 = //
+       ""
+                       + "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBI"
+                       + "WXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4wURFRg6IrtcdgAAATdJREFUOMvtkj8sQ1EUxr9z/71G"
+                       + "m1RDogYxq7WDDYMYTSajSG4n6YRYzSaSLibWbiaDIGwdiLIYDFKDNJEgKu969xi8UNHy7H7LPcN3"
+                       + "v/Odcy+hG9oOIeIcBCJS9MAvlZtOMtHxsrFrJHGqe0RVGnHAHpcIbPlng8BS3HmKBJYzabGUzcrJ"
+                       + "XK+ckIrqANYR2JEv2nYDEVck0WKGfHzyq82Go+btxoX3XAcAIqTj8wPqOH6mtMeM4bGCLhyfhTMA"
+                       + "qlLhKHqujCfaweCAmV0p50dPzsNpEKpK01V/n55HIvTnfDC2odKlfeYadZN/T+AqDACUsnkhqaU1"
+                       + "LRIVuX1x7ciuSWQxVIrunONrfq3dI6oh+T94Z8453vEem/HTqT8ZpFJ0qDXtGkPbAGAMeSRngQCA"
+                       + "eUvgn195AwlZWyvjtQdhAAAAAElFTkSuQmCC";
 
-       private JTextField valueField;
+       /**
+        * Create a new {@link ConfigItem} for the given {@link MetaInfo}.
+        * 
+        * @param info
+        *            the {@link MetaInfo}
+        */
+       public ConfigItem(MetaInfo<E> info) {
+               this.setLayout(new BorderLayout());
 
-       public ConfigItem(Class<E> type, Bundle<E> bundle, E id) {
-               this.type = type;
-               this.bundle = bundle;
-               this.id = id;
+               // TODO: support arrays
+               Format fmt = info.getFormat();
+               if (info.isArray()) {
+                       fmt = Format.STRING;
+               }
 
-               try {
-                       this.meta = type.getDeclaredField(id.name()).getAnnotation(
-                                       Meta.class);
-               } catch (NoSuchFieldException e) {
-               } catch (SecurityException e) {
+               switch (fmt) {
+               case BOOLEAN:
+                       addBooleanField(info);
+                       break;
+               case COLOR:
+                       addColorField(info);
+                       break;
+               case FILE:
+                       addBrowseField(info, false);
+                       break;
+               case DIRECTORY:
+                       addBrowseField(info, true);
+                       break;
+               case COMBO_LIST:
+                       addComboboxField(info, true);
+                       break;
+               case FIXED_LIST:
+                       addComboboxField(info, false);
+                       break;
+               case INT:
+                       addIntField(info);
+                       break;
+               case PASSWORD:
+                       addPasswordField(info);
+                       break;
+               case STRING:
+               case LOCALE: // TODO?
+               default:
+                       addStringField(info);
+                       break;
                }
+       }
 
-               this.setLayout(new BorderLayout());
-               this.setBorder(new EmptyBorder(2, 10, 2, 10));
+       private void addStringField(final MetaInfo<E> info) {
+               final JTextField field = new JTextField();
+               field.setToolTipText(info.getDescription());
+               field.setText(info.getString());
 
-               String tooltip = null;
-               if (bundle.getDescriptionBundle() != null) {
-                       tooltip = bundle.getDescriptionBundle().getString(id);
-                       if (tooltip != null && tooltip.trim().isEmpty()) {
-                               tooltip = null;
+               info.addReloadedListener(new Runnable() {
+                       @Override
+                       public void run() {
+                               field.setText(info.getString());
+                       }
+               });
+               info.addSaveListener(new Runnable() {
+                       @Override
+                       public void run() {
+                               info.setString(field.getText());
                        }
+               });
+
+               this.add(label(info), BorderLayout.WEST);
+               this.add(field, BorderLayout.CENTER);
+       }
+
+       private void addBooleanField(final MetaInfo<E> info) {
+               final JCheckBox field = new JCheckBox();
+               field.setToolTipText(info.getDescription());
+               Boolean state = info.getBoolean();
+               if (state == null) {
+                       info.getDefaultBoolean();
                }
 
-               String name = id.toString();
-               if (name.length() > 1) {
-                       name = name.substring(0, 1) + name.substring(1).toLowerCase();
-                       name = name.replace("_", " ");
+               // Should not happen!
+               if (state == null) {
+                       System.err
+                                       .println("No default value given for BOOLEAN parameter \""
+                                                       + info.getName() + "\", we consider it is FALSE");
+                       state = false;
                }
 
-               JLabel nameLabel = new JLabel(name);
-               nameLabel.setToolTipText(tooltip);
-               nameLabel.setPreferredSize(new Dimension(400, 0));
-               this.add(nameLabel, BorderLayout.WEST);
+               field.setSelected(state);
 
-               valueField = new JTextField();
-               valueField.setText(value);
+               info.addReloadedListener(new Runnable() {
+                       @Override
+                       public void run() {
+                               Boolean state = info.getBoolean();
+                               if (state == null) {
+                                       info.getDefaultBoolean();
+                               }
+                               if (state == null) {
+                                       state = false;
+                               }
 
-               reload();
-               this.add(valueField, BorderLayout.CENTER);
+                               field.setSelected(state);
+                       }
+               });
+               info.addSaveListener(new Runnable() {
+                       @Override
+                       public void run() {
+                               info.setBoolean(field.isSelected());
+                       }
+               });
+
+               this.add(label(info), BorderLayout.WEST);
+               this.add(field, BorderLayout.CENTER);
        }
 
-       /**
-        * Reload the value from the {@link Bundle}.
-        */
-       public void reload() {
-               value = bundle.getString(id);
-               valueField.setText(value);
+       private void addColorField(final MetaInfo<E> info) {
+               final JTextField field = new JTextField();
+               field.setToolTipText(info.getDescription());
+               field.setText(info.getString());
+
+               info.addReloadedListener(new Runnable() {
+                       @Override
+                       public void run() {
+                               field.setText(info.getString());
+                       }
+               });
+               info.addSaveListener(new Runnable() {
+                       @Override
+                       public void run() {
+                               info.setString(field.getText());
+                       }
+               });
+
+               this.add(label(info), BorderLayout.WEST);
+               JPanel pane = new JPanel(new BorderLayout());
+
+               final JButton colorWheel = new JButton();
+               colorWheel.setIcon(getIcon(17, info.getColor()));
+               colorWheel.addActionListener(new ActionListener() {
+                       @Override
+                       public void actionPerformed(ActionEvent e) {
+                               Color initialColor = new Color(info.getColor(), true);
+                               Color newColor = JColorChooser.showDialog(ConfigItem.this,
+                                               info.getName(), initialColor);
+                               if (newColor != null) {
+                                       info.setColor(newColor.getRGB());
+                                       field.setText(info.getString());
+                                       colorWheel.setIcon(getIcon(17, info.getColor()));
+                               }
+                       }
+               });
+               pane.add(colorWheel, BorderLayout.WEST);
+               pane.add(field, BorderLayout.CENTER);
+               this.add(pane, BorderLayout.CENTER);
+       }
+
+       private void addBrowseField(final MetaInfo<E> info, final boolean dir) {
+               final JTextField field = new JTextField();
+               field.setToolTipText(info.getDescription());
+               field.setText(info.getString());
+
+               info.addReloadedListener(new Runnable() {
+                       @Override
+                       public void run() {
+                               field.setText(info.getString());
+                       }
+               });
+               info.addSaveListener(new Runnable() {
+                       @Override
+                       public void run() {
+                               info.setString(field.getText());
+                       }
+               });
+
+               JButton browseButton = new JButton("...");
+               browseButton.addActionListener(new ActionListener() {
+                       @Override
+                       public void actionPerformed(ActionEvent e) {
+                               JFileChooser chooser = new JFileChooser();
+                               chooser.setCurrentDirectory(null);
+                               chooser.setFileSelectionMode(dir ? JFileChooser.DIRECTORIES_ONLY
+                                               : JFileChooser.FILES_ONLY);
+                               if (chooser.showOpenDialog(ConfigItem.this) == JFileChooser.APPROVE_OPTION) {
+                                       File file = chooser.getSelectedFile();
+                                       if (file != null) {
+                                               info.setString(file.getAbsolutePath());
+                                               field.setText(info.getString());
+                                       }
+                               }
+                       }
+               });
+
+               JPanel pane = new JPanel(new BorderLayout());
+               this.add(label(info), BorderLayout.WEST);
+               pane.add(browseButton, BorderLayout.WEST);
+               pane.add(field, BorderLayout.CENTER);
+               this.add(pane, BorderLayout.CENTER);
+       }
+
+       private void addComboboxField(final MetaInfo<E> info, boolean editable) {
+               // rawtypes for Java 1.6 (and 1.7 ?) support
+               @SuppressWarnings({ "rawtypes", "unchecked" })
+               final JComboBox field = new JComboBox(info.getAllowedValues());
+               field.setEditable(editable);
+               field.setSelectedItem(info.getString());
+
+               info.addReloadedListener(new Runnable() {
+                       @Override
+                       public void run() {
+                               field.setSelectedItem(info.getString());
+                       }
+               });
+               info.addSaveListener(new Runnable() {
+                       @Override
+                       public void run() {
+                               info.setString(field.getSelectedItem().toString());
+                       }
+               });
+
+               this.add(label(info), BorderLayout.WEST);
+               this.add(field, BorderLayout.CENTER);
+       }
+
+       private void addPasswordField(final MetaInfo<E> info) {
+               final JPasswordField field = new JPasswordField();
+               field.setToolTipText(info.getDescription());
+               field.setText(info.getString());
+
+               info.addReloadedListener(new Runnable() {
+                       @Override
+                       public void run() {
+                               field.setText(info.getString());
+                       }
+               });
+               info.addSaveListener(new Runnable() {
+                       @Override
+                       public void run() {
+                               info.setString(new String(field.getPassword()));
+                       }
+               });
+
+               this.add(label(info), BorderLayout.WEST);
+               this.add(field, BorderLayout.CENTER);
+       }
+
+       private void addIntField(final MetaInfo<E> info) {
+               final JTextField field = new JTextField();
+               field.setToolTipText(info.getDescription());
+               field.setText(info.getString());
+               field.setInputVerifier(new InputVerifier() {
+                       @Override
+                       public boolean verify(JComponent input) {
+                               String text = field.getText().trim();
+                               if (text.startsWith("-")) {
+                                       text = text.substring(1).trim();
+                               }
+
+                               return text.replaceAll("[0-9]", "").isEmpty();
+                       }
+               });
+
+               info.addReloadedListener(new Runnable() {
+                       @Override
+                       public void run() {
+                               field.setText(info.getString());
+                       }
+               });
+               info.addSaveListener(new Runnable() {
+                       @Override
+                       public void run() {
+                               info.setString(field.getText());
+                               Integer value = info.getInteger();
+                               if (value == null) {
+                                       info.setString("");
+                               } else {
+                                       info.setInteger(value);
+                               }
+                               field.setText(info.getString());
+                       }
+               });
+
+               JButton up = new BasicArrowButton(BasicArrowButton.NORTH);
+               JButton down = new BasicArrowButton(BasicArrowButton.SOUTH);
+
+               up.addActionListener(new ActionListener() {
+                       @Override
+                       public void actionPerformed(ActionEvent ae) {
+                               int value = 0;
+                               try {
+                                       value = Integer.parseInt(field.getText());
+                               } catch (NumberFormatException e) {
+                               }
+
+                               field.setText(Integer.toString(value + 1));
+                       }
+               });
+
+               down.addActionListener(new ActionListener() {
+                       @Override
+                       public void actionPerformed(ActionEvent ae) {
+                               int value = 0;
+                               try {
+                                       value = Integer.parseInt(field.getText());
+                               } catch (NumberFormatException e) {
+                               }
+
+                               field.setText(Integer.toString(value - 1));
+                       }
+               });
+
+               JPanel upDown = new JPanel(new BorderLayout());
+               upDown.add(up, BorderLayout.NORTH);
+               upDown.add(down, BorderLayout.SOUTH);
+
+               JPanel pane = new JPanel(new BorderLayout());
+               pane.add(upDown, BorderLayout.WEST);
+               pane.add(field, BorderLayout.CENTER);
+
+               this.add(label(info), BorderLayout.WEST);
+               this.add(pane, BorderLayout.CENTER);
        }
 
        /**
-        * Save the current value to the {@link Bundle}.
+        * Create a label which width is constrained in lock steps.
+        * 
+        * @param info
+        *            the {@link MetaInfo} for which we want to add a label
+        * 
+        * @return the label
         */
-       public void save() {
-               value = valueField.getText();
-               bundle.setString(id, value);
+       private JComponent label(final MetaInfo<E> info) {
+               final JLabel label = new JLabel(info.getName());
+
+               Dimension ps = label.getPreferredSize();
+               if (ps == null) {
+                       ps = label.getSize();
+               }
+
+               int w = ps.width;
+               int step = 150;
+               for (int i = 2 * step; i < 10 * step; i += step) {
+                       if (w < i) {
+                               w = i;
+                               break;
+                       }
+               }
+
+               final Runnable showInfo = new Runnable() {
+                       @Override
+                       public void run() {
+                               StringBuilder builder = new StringBuilder();
+                               String text = info.getDescription().replace("\\n", "\n");
+                               for (String line : StringUtils.justifyText(text, 80,
+                                               Alignment.LEFT)) {
+                                       if (builder.length() > 0) {
+                                               builder.append("\n");
+                                       }
+                                       builder.append(line);
+                               }
+                               text = builder.toString();
+                               JOptionPane.showMessageDialog(ConfigItem.this, text,
+                                               info.getName(), JOptionPane.INFORMATION_MESSAGE);
+                       }
+               };
+
+               JLabel help = new JLabel("");
+               help.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
+               try {
+                       Image img = new Image(infoImage64);
+                       try {
+                               BufferedImage bImg = ImageUtilsAwt.fromImage(img);
+                               help.setIcon(new ImageIcon(bImg));
+                       } finally {
+                               img.close();
+                       }
+               } catch (IOException e) {
+                       // This is an hard-coded image, should not happen
+                       help.setText("?");
+               }
+
+               help.addMouseListener(new MouseAdapter() {
+                       @Override
+                       public void mouseClicked(MouseEvent e) {
+                               showInfo.run();
+                       }
+               });
+
+               JPanel pane2 = new JPanel(new BorderLayout());
+               pane2.add(help, BorderLayout.WEST);
+               pane2.add(new JLabel(" "), BorderLayout.CENTER);
+
+               JPanel pane = new JPanel(new BorderLayout());
+               pane.add(label, BorderLayout.WEST);
+               pane.add(pane2, BorderLayout.CENTER);
+
+               ps.width = w + 30; // 30 for the (?) sign
+               pane.setSize(ps);
+               pane.setPreferredSize(ps);
+
+               return pane;
        }
 
        /**
-        * Create a list of {@link ConfigItem}, one for each of the item in the
-        * given {@link Bundle}.
+        * Return an {@link Icon} to use as a colour badge for the colour field
+        * controls.
         * 
-        * @param <E>
-        *            the type of {@link Bundle} to edit
-        * @param type
-        *            a class instance of the item type to work on
-        * @param bundle
-        *            the {@link Bundle} to sort through
+        * @param size
+        *            the size of the badge
+        * @param color
+        *            the colour of the badge
         * 
-        * @return the list
+        * @return the badge
         */
-       static public <E extends Enum<E>> List<ConfigItem<E>> getItems(
-                       Class<E> type, Bundle<E> bundle) {
-               List<ConfigItem<E>> list = new ArrayList<ConfigItem<E>>();
-               for (E id : type.getEnumConstants()) {
-                       list.add(new ConfigItem<E>(type, bundle, id));
+       private Icon getIcon(int size, int color) {
+               Color c = new Color(color, true);
+               int avg = (c.getRed() + c.getGreen() + c.getBlue()) / 3;
+               Color border = (avg >= 128 ? Color.BLACK : Color.WHITE);
+
+               BufferedImage img = new BufferedImage(size, size,
+                               BufferedImage.TYPE_4BYTE_ABGR);
+
+               Graphics2D g = img.createGraphics();
+               try {
+                       g.setColor(c);
+                       g.fillRect(0, 0, img.getWidth(), img.getHeight());
+                       g.setColor(border);
+                       g.drawRect(0, 0, img.getWidth() - 1, img.getHeight() - 1);
+               } finally {
+                       g.dispose();
                }
 
-               return list;
+               return new ImageIcon(img);
        }
 }