Improve ConfigItems and fix some related bugs
[nikiroo-utils.git] / src / be / nikiroo / utils / ui / ConfigItem.java
1 package be.nikiroo.utils.ui;
2
3 import java.awt.BorderLayout;
4 import java.awt.Cursor;
5 import java.awt.Dimension;
6 import java.awt.event.ActionEvent;
7 import java.awt.event.ActionListener;
8 import java.awt.event.MouseAdapter;
9 import java.awt.event.MouseEvent;
10 import java.awt.image.BufferedImage;
11 import java.io.IOException;
12 import java.util.ArrayList;
13 import java.util.List;
14
15 import javax.swing.BoxLayout;
16 import javax.swing.ImageIcon;
17 import javax.swing.JButton;
18 import javax.swing.JComponent;
19 import javax.swing.JLabel;
20 import javax.swing.JOptionPane;
21 import javax.swing.JPanel;
22 import javax.swing.JTextField;
23
24 import be.nikiroo.utils.Image;
25 import be.nikiroo.utils.StringUtils;
26 import be.nikiroo.utils.StringUtils.Alignment;
27 import be.nikiroo.utils.resources.Bundle;
28 import be.nikiroo.utils.resources.MetaInfo;
29
30 /**
31 * A graphical item that reflect a configuration option from the given
32 * {@link Bundle}.
33 * <p>
34 * This graphical item can be edited, and the result will be saved back into the
35 * linked {@link MetaInfo}; you still have to save the {@link MetaInfo} should
36 * you wish to, of course.
37 *
38 * @author niki
39 *
40 * @param <E>
41 * the type of {@link Bundle} to edit
42 */
43 public class ConfigItem<E extends Enum<E>> extends JPanel {
44 private static final long serialVersionUID = 1L;
45
46 private static int minimumHeight = -1;
47
48 /** A small (?) blue in PNG, base64 encoded. */
49 private static String infoImage64 = //
50 ""
51 + "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBI"
52 + "WXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4wURFRg6IrtcdgAAATdJREFUOMvtkj8sQ1EUxr9z/71G"
53 + "m1RDogYxq7WDDYMYTSajSG4n6YRYzSaSLibWbiaDIGwdiLIYDFKDNJEgKu969xi8UNHy7H7LPcN3"
54 + "v/Odcy+hG9oOIeIcBCJS9MAvlZtOMtHxsrFrJHGqe0RVGnHAHpcIbPlng8BS3HmKBJYzabGUzcrJ"
55 + "XK+ckIrqANYR2JEv2nYDEVck0WKGfHzyq82Go+btxoX3XAcAIqTj8wPqOH6mtMeM4bGCLhyfhTMA"
56 + "qlLhKHqujCfaweCAmV0p50dPzsNpEKpK01V/n55HIvTnfDC2odKlfeYadZN/T+AqDACUsnkhqaU1"
57 + "LRIVuX1x7ciuSWQxVIrunONrfq3dI6oh+T94Z8453vEem/HTqT8ZpFJ0qDXtGkPbAGAMeSRngQCA"
58 + "eUvgn195AwlZWyvjtQdhAAAAAElFTkSuQmCC";
59
60 /** The original value before current changes. */
61 private Object orig;
62 private List<Integer> dirtyBits;
63
64 protected MetaInfo<E> info;
65
66 private JComponent field;
67 private List<JComponent> fields = new ArrayList<JComponent>();
68
69 /**
70 * Create a new {@link ConfigItem} for the given {@link MetaInfo}.
71 *
72 * @param info
73 * the {@link MetaInfo}
74 * @param nhgap
75 * negative horisontal gap in pixel to use for the label, i.e.,
76 * the step lock sized labels will start smaller by that amount
77 * (the use case would be to align controls that start at a
78 * different horisontal position)
79 */
80 public ConfigItem(MetaInfo<E> info, int nhgap) {
81 this(info, true);
82
83 ConfigItem<E> configItem;
84 switch (info.getFormat()) {
85 case BOOLEAN:
86 configItem = new ConfigItemBoolean<E>(info);
87 break;
88 case COLOR:
89 configItem = new ConfigItemColor<E>(info);
90 break;
91 case FILE:
92 configItem = new ConfigItemBrowse<E>(info, false);
93 break;
94 case DIRECTORY:
95 configItem = new ConfigItemBrowse<E>(info, true);
96 break;
97 case COMBO_LIST:
98 configItem = new ConfigItemCombobox<E>(info, true);
99 break;
100 case FIXED_LIST:
101 configItem = new ConfigItemCombobox<E>(info, false);
102 break;
103 case INT:
104 configItem = new ConfigItemInteger<E>(info);
105 break;
106 case PASSWORD:
107 configItem = new ConfigItemPassword<E>(info);
108 break;
109 case STRING:
110 case LOCALE: // TODO?
111 default:
112 configItem = new ConfigItemString<E>(info);
113 break;
114 }
115
116 if (info.isArray()) {
117 this.setLayout(new BorderLayout());
118 add(label(nhgap), BorderLayout.WEST);
119
120 final JPanel main = new JPanel();
121 main.setLayout(new BoxLayout(main, BoxLayout.Y_AXIS));
122 int size = info.getListSize(false);
123 for (int i = 0; i < size; i++) {
124 JComponent field = configItem.createComponent(i);
125 main.add(field);
126 }
127
128 // TODO: image
129 final JButton add = new JButton("+");
130 final ConfigItem<E> fconfigItem = configItem;
131 add.addActionListener(new ActionListener() {
132 @Override
133 public void actionPerformed(ActionEvent e) {
134 JComponent field = fconfigItem
135 .createComponent(fconfigItem.info
136 .getListSize(false));
137 main.add(field);
138
139 // TODO this doesn't woooooorkk
140 add.invalidate();
141 field.invalidate();
142 main.invalidate();
143 ConfigItem.this.repaint();
144 ConfigItem.this.validate();
145 ConfigItem.this.repaint();
146 }
147 });
148
149 JPanel tmp = new JPanel(new BorderLayout());
150 tmp.add(add, BorderLayout.WEST);
151
152 JPanel mainPlus = new JPanel(new BorderLayout());
153 mainPlus.add(main, BorderLayout.CENTER);
154 mainPlus.add(tmp, BorderLayout.SOUTH);
155
156 add(mainPlus, BorderLayout.CENTER);
157 } else {
158 this.setLayout(new BorderLayout());
159 add(label(nhgap), BorderLayout.WEST);
160
161 JComponent field = configItem.createComponent(-1);
162 add(field, BorderLayout.CENTER);
163 }
164 }
165
166 /**
167 * Prepare a new {@link ConfigItem} instance, linked to the given
168 * {@link MetaInfo}.
169 *
170 * @param info
171 * the info
172 * @param autoDirtyHandling
173 * TRUE to automatically manage the setDirty/Save operations,
174 * FALSE if you want to do it yourself via
175 * {@link ConfigItem#setDirtyItem(int)}
176 */
177 protected ConfigItem(MetaInfo<E> info, boolean autoDirtyHandling) {
178 this.info = info;
179 if (!autoDirtyHandling) {
180 dirtyBits = new ArrayList<Integer>();
181 }
182 }
183
184 /**
185 * Create an empty graphical component to be used later by
186 * {@link ConfigItem#getField(int)}.
187 * <p>
188 * Note that {@link ConfigItem#reload(int)} will be called after it was
189 * created.
190 *
191 * @param item
192 * the item number to get for an array of values, or -1 to get
193 * the whole value (has no effect if {@link MetaInfo#isArray()}
194 * is FALSE)
195 *
196 * @return the graphical component
197 */
198 protected JComponent createField(@SuppressWarnings("unused") int item) {
199 // Not used by the main class, only the sublasses
200 return null;
201 }
202
203 /**
204 * Get the information from the {@link MetaInfo} in the subclass preferred
205 * format.
206 *
207 * @param item
208 * the item number to get for an array of values, or -1 to get
209 * the whole value (has no effect if {@link MetaInfo#isArray()}
210 * is FALSE)
211 *
212 * @return the information in the subclass preferred format
213 */
214 protected Object getFromInfo(@SuppressWarnings("unused") int item) {
215 // Not used by the main class, only the subclasses
216 return null;
217 }
218
219 /**
220 * Set the value to the {@link MetaInfo}.
221 *
222 * @param value
223 * the value in the subclass preferred format
224 * @param item
225 * the item number to get for an array of values, or -1 to get
226 * the whole value (has no effect if {@link MetaInfo#isArray()}
227 * is FALSE)
228 */
229 protected void setToInfo(@SuppressWarnings("unused") Object value,
230 @SuppressWarnings("unused") int item) {
231 // Not used by the main class, only the subclasses
232 }
233
234 /**
235 * @param item
236 * the item number to get for an array of values, or -1 to get
237 * the whole value (has no effect if {@link MetaInfo#isArray()}
238 * is FALSE)
239 *
240 * @return
241 */
242 protected Object getFromField(@SuppressWarnings("unused") int item) {
243 // Not used by the main class, only the subclasses
244 return null;
245 }
246
247 /**
248 * Set the value (in the subclass preferred format) into the field.
249 *
250 * @param value
251 * the value in the subclass preferred format
252 * @param item
253 * the item number to get for an array of values, or -1 to get
254 * the whole value (has no effect if {@link MetaInfo#isArray()}
255 * is FALSE)
256 */
257 protected void setToField(@SuppressWarnings("unused") Object value,
258 @SuppressWarnings("unused") int item) {
259 // Not used by the main class, only the subclasses
260 }
261
262 /**
263 * Create a new field for the given graphical component at the given index
264 * (note that the component is usually created by
265 * {@link ConfigItem#createField(int)}).
266 *
267 * @param item
268 * the item number to get for an array of values, or -1 to get
269 * the whole value (has no effect if {@link MetaInfo#isArray()}
270 * is FALSE)
271 * @param field
272 * the graphical component
273 */
274 private void setField(int item, JComponent field) {
275 if (item < 0) {
276 this.field = field;
277 return;
278 }
279
280 for (int i = fields.size(); i <= item; i++) {
281 fields.add(null);
282 }
283
284 fields.set(item, field);
285 }
286
287 /**
288 * Retrieve the associated graphical component that was created with
289 * {@link ConfigItem#createField(int)}.
290 *
291 * @param item
292 * the item number to get for an array of values, or -1 to get
293 * the whole value (has no effect if {@link MetaInfo#isArray()}
294 * is FALSE)
295 *
296 * @return the graphical component
297 */
298 protected JComponent getField(int item) {
299 if (item < 0) {
300 return field;
301 }
302
303 if (item < fields.size()) {
304 return fields.get(item);
305 }
306
307 return null;
308 }
309
310 /**
311 * Manually specify that the given item is "dirty" and thus should be saved
312 * when asked.
313 * <p>
314 * Has no effect if the class is using automatic dirty handling (see
315 * {@link ConfigItem#ConfigItem(MetaInfo, boolean)}).
316 *
317 * @param item
318 * the item number to get for an array of values, or -1 to get
319 * the whole value (has no effect if {@link MetaInfo#isArray()}
320 * is FALSE)
321 */
322 protected void setDirtyItem(int item) {
323 if (dirtyBits != null) {
324 dirtyBits.add(item);
325 }
326 }
327
328 /**
329 * Check if the value changed since the last load/save into the linked
330 * {@link MetaInfo}.
331 * <p>
332 * Note that we consider NULL and an Empty {@link String} to be equals.
333 *
334 * @param value
335 * the value to test
336 *
337 * @return TRUE if it has
338 */
339 protected boolean hasValueChanged(Object value) {
340 // We consider "" and NULL to be equals
341 return !orig.equals(value == null ? "" : value);
342 }
343
344 /**
345 * Reload the values to what they currently are in the {@link MetaInfo}.
346 *
347 * @param item
348 * the item number to get for an array of values, or -1 to get
349 * the whole value (has no effect if {@link MetaInfo#isArray()}
350 * is FALSE)
351 */
352 protected void reload(int item) {
353 Object value = getFromInfo(item);
354 setToField(value, item);
355
356 // We consider "" and NULL to be equals
357 orig = (value == null ? "" : value);
358 }
359
360 /**
361 * If the item has been modified, set the {@link MetaInfo} to dirty then
362 * modify it to, reflect the changes so it can be saved later.
363 * <p>
364 * This method does <b>not</b> call {@link MetaInfo#save(boolean)}.
365 *
366 * @param item
367 * the item number to get for an array of values, or -1 to get
368 * the whole value (has no effect if {@link MetaInfo#isArray()}
369 * is FALSE)
370 */
371 protected void save(int item) {
372 Object value = getFromField(item);
373
374 boolean dirty = false;
375 if (dirtyBits != null) {
376 dirty = dirtyBits.remove((Integer) item);
377 } else {
378 // We consider "" and NULL to be equals
379 dirty = hasValueChanged(value);
380 }
381
382 if (dirty) {
383 info.setDirty();
384 setToInfo(value, item);
385 orig = (value == null ? "" : value);
386 }
387 }
388
389 /**
390 *
391 * @param item
392 * the item number to get for an array of values, or -1 to get
393 * the whole value (has no effect if {@link MetaInfo#isArray()}
394 * is FALSE)
395 * @param addTo
396 * @param nhgap
397 */
398 protected JComponent createComponent(final int item) {
399 setField(item, createField(item));
400 reload(item);
401
402 info.addReloadedListener(new Runnable() {
403 @Override
404 public void run() {
405 reload(item);
406 }
407 });
408 info.addSaveListener(new Runnable() {
409 @Override
410 public void run() {
411 save(item);
412 }
413 });
414
415 JComponent field = getField(item);
416 setPreferredSize(field);
417
418 return field;
419 }
420
421 /**
422 * Create a label which width is constrained in lock steps.
423 *
424 * @param nhgap
425 * negative horisontal gap in pixel to use for the label, i.e.,
426 * the step lock sized labels will start smaller by that amount
427 * (the use case would be to align controls that start at a
428 * different horisontal position)
429 *
430 * @return the label
431 */
432 protected JComponent label(int nhgap) {
433 final JLabel label = new JLabel(info.getName());
434
435 Dimension ps = label.getPreferredSize();
436 if (ps == null) {
437 ps = label.getSize();
438 }
439
440 ps.height = Math.max(ps.height, getMinimumHeight());
441
442 int w = ps.width;
443 int step = 150;
444 for (int i = 2 * step - nhgap; i < 10 * step; i += step) {
445 if (w < i) {
446 w = i;
447 break;
448 }
449 }
450
451 final Runnable showInfo = new Runnable() {
452 @Override
453 public void run() {
454 StringBuilder builder = new StringBuilder();
455 String text = (info.getDescription().replace("\\n", "\n"))
456 .trim();
457 for (String line : StringUtils.justifyText(text, 80,
458 Alignment.LEFT)) {
459 if (builder.length() > 0) {
460 builder.append("\n");
461 }
462 builder.append(line);
463 }
464 text = builder.toString();
465 JOptionPane.showMessageDialog(ConfigItem.this, text,
466 info.getName(), JOptionPane.INFORMATION_MESSAGE);
467 }
468 };
469
470 JLabel help = new JLabel("");
471 help.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
472 try {
473 Image img = new Image(infoImage64);
474 try {
475 BufferedImage bImg = ImageUtilsAwt.fromImage(img);
476 help.setIcon(new ImageIcon(bImg));
477 } finally {
478 img.close();
479 }
480 } catch (IOException e) {
481 // This is an hard-coded image, should not happen
482 help.setText("?");
483 }
484
485 help.addMouseListener(new MouseAdapter() {
486 @Override
487 public void mouseClicked(MouseEvent e) {
488 showInfo.run();
489 }
490 });
491
492 JPanel pane2 = new JPanel(new BorderLayout());
493 pane2.add(help, BorderLayout.WEST);
494 pane2.add(new JLabel(" "), BorderLayout.CENTER);
495
496 JPanel contentPane = new JPanel(new BorderLayout());
497 contentPane.add(label, BorderLayout.WEST);
498 contentPane.add(pane2, BorderLayout.CENTER);
499
500 ps.width = w + 30; // 30 for the (?) sign
501 contentPane.setSize(ps);
502 contentPane.setPreferredSize(ps);
503
504 JPanel pane = new JPanel(new BorderLayout());
505 pane.add(contentPane, BorderLayout.NORTH);
506
507 return pane;
508 }
509
510 protected void setPreferredSize(JComponent field) {
511 int height = Math
512 .max(getMinimumHeight(), field.getMinimumSize().height);
513 setPreferredSize(new Dimension(200, height));
514 }
515
516 static private int getMinimumHeight() {
517 if (minimumHeight < 0) {
518 minimumHeight = new JTextField("Test").getMinimumSize().height;
519 }
520
521 return minimumHeight;
522 }
523 }