fix config item '+' repaint
[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 main.revalidate();
140 main.repaint();
141 }
142 });
143
144 JPanel tmp = new JPanel(new BorderLayout());
145 tmp.add(add, BorderLayout.WEST);
146
147 JPanel mainPlus = new JPanel(new BorderLayout());
148 mainPlus.add(main, BorderLayout.CENTER);
149 mainPlus.add(tmp, BorderLayout.SOUTH);
150
151 add(mainPlus, BorderLayout.CENTER);
152 } else {
153 this.setLayout(new BorderLayout());
154 add(label(nhgap), BorderLayout.WEST);
155
156 JComponent field = configItem.createComponent(-1);
157 add(field, BorderLayout.CENTER);
158 }
159 }
160
161 /**
162 * Prepare a new {@link ConfigItem} instance, linked to the given
163 * {@link MetaInfo}.
164 *
165 * @param info
166 * the info
167 * @param autoDirtyHandling
168 * TRUE to automatically manage the setDirty/Save operations,
169 * FALSE if you want to do it yourself via
170 * {@link ConfigItem#setDirtyItem(int)}
171 */
172 protected ConfigItem(MetaInfo<E> info, boolean autoDirtyHandling) {
173 this.info = info;
174 if (!autoDirtyHandling) {
175 dirtyBits = new ArrayList<Integer>();
176 }
177 }
178
179 /**
180 * Create an empty graphical component to be used later by
181 * {@link ConfigItem#getField(int)}.
182 * <p>
183 * Note that {@link ConfigItem#reload(int)} will be called after it was
184 * created.
185 *
186 * @param item
187 * the item number to get for an array of values, or -1 to get
188 * the whole value (has no effect if {@link MetaInfo#isArray()}
189 * is FALSE)
190 *
191 * @return the graphical component
192 */
193 protected JComponent createField(@SuppressWarnings("unused") int item) {
194 // Not used by the main class, only the sublasses
195 return null;
196 }
197
198 /**
199 * Get the information from the {@link MetaInfo} in the subclass preferred
200 * format.
201 *
202 * @param item
203 * the item number to get for an array of values, or -1 to get
204 * the whole value (has no effect if {@link MetaInfo#isArray()}
205 * is FALSE)
206 *
207 * @return the information in the subclass preferred format
208 */
209 protected Object getFromInfo(@SuppressWarnings("unused") int item) {
210 // Not used by the main class, only the subclasses
211 return null;
212 }
213
214 /**
215 * Set the value to the {@link MetaInfo}.
216 *
217 * @param value
218 * the value in the subclass preferred format
219 * @param item
220 * the item number to get for an array of values, or -1 to get
221 * the whole value (has no effect if {@link MetaInfo#isArray()}
222 * is FALSE)
223 */
224 protected void setToInfo(@SuppressWarnings("unused") Object value,
225 @SuppressWarnings("unused") int item) {
226 // Not used by the main class, only the subclasses
227 }
228
229 /**
230 * @param item
231 * the item number to get for an array of values, or -1 to get
232 * the whole value (has no effect if {@link MetaInfo#isArray()}
233 * is FALSE)
234 *
235 * @return
236 */
237 protected Object getFromField(@SuppressWarnings("unused") int item) {
238 // Not used by the main class, only the subclasses
239 return null;
240 }
241
242 /**
243 * Set the value (in the subclass preferred format) into the field.
244 *
245 * @param value
246 * the value in the subclass preferred format
247 * @param item
248 * the item number to get for an array of values, or -1 to get
249 * the whole value (has no effect if {@link MetaInfo#isArray()}
250 * is FALSE)
251 */
252 protected void setToField(@SuppressWarnings("unused") Object value,
253 @SuppressWarnings("unused") int item) {
254 // Not used by the main class, only the subclasses
255 }
256
257 /**
258 * Create a new field for the given graphical component at the given index
259 * (note that the component is usually created by
260 * {@link ConfigItem#createField(int)}).
261 *
262 * @param item
263 * the item number to get for an array of values, or -1 to get
264 * the whole value (has no effect if {@link MetaInfo#isArray()}
265 * is FALSE)
266 * @param field
267 * the graphical component
268 */
269 private void setField(int item, JComponent field) {
270 if (item < 0) {
271 this.field = field;
272 return;
273 }
274
275 for (int i = fields.size(); i <= item; i++) {
276 fields.add(null);
277 }
278
279 fields.set(item, field);
280 }
281
282 /**
283 * Retrieve the associated graphical component that was created with
284 * {@link ConfigItem#createField(int)}.
285 *
286 * @param item
287 * the item number to get for an array of values, or -1 to get
288 * the whole value (has no effect if {@link MetaInfo#isArray()}
289 * is FALSE)
290 *
291 * @return the graphical component
292 */
293 protected JComponent getField(int item) {
294 if (item < 0) {
295 return field;
296 }
297
298 if (item < fields.size()) {
299 return fields.get(item);
300 }
301
302 return null;
303 }
304
305 /**
306 * Manually specify that the given item is "dirty" and thus should be saved
307 * when asked.
308 * <p>
309 * Has no effect if the class is using automatic dirty handling (see
310 * {@link ConfigItem#ConfigItem(MetaInfo, boolean)}).
311 *
312 * @param item
313 * the item number to get for an array of values, or -1 to get
314 * the whole value (has no effect if {@link MetaInfo#isArray()}
315 * is FALSE)
316 */
317 protected void setDirtyItem(int item) {
318 if (dirtyBits != null) {
319 dirtyBits.add(item);
320 }
321 }
322
323 /**
324 * Check if the value changed since the last load/save into the linked
325 * {@link MetaInfo}.
326 * <p>
327 * Note that we consider NULL and an Empty {@link String} to be equals.
328 *
329 * @param value
330 * the value to test
331 *
332 * @return TRUE if it has
333 */
334 protected boolean hasValueChanged(Object value) {
335 // We consider "" and NULL to be equals
336 return !orig.equals(value == null ? "" : value);
337 }
338
339 /**
340 * Reload the values to what they currently are in the {@link MetaInfo}.
341 *
342 * @param item
343 * the item number to get for an array of values, or -1 to get
344 * the whole value (has no effect if {@link MetaInfo#isArray()}
345 * is FALSE)
346 */
347 protected void reload(int item) {
348 Object value = getFromInfo(item);
349 setToField(value, item);
350
351 // We consider "" and NULL to be equals
352 orig = (value == null ? "" : value);
353 }
354
355 /**
356 * If the item has been modified, set the {@link MetaInfo} to dirty then
357 * modify it to, reflect the changes so it can be saved later.
358 * <p>
359 * This method does <b>not</b> call {@link MetaInfo#save(boolean)}.
360 *
361 * @param item
362 * the item number to get for an array of values, or -1 to get
363 * the whole value (has no effect if {@link MetaInfo#isArray()}
364 * is FALSE)
365 */
366 protected void save(int item) {
367 Object value = getFromField(item);
368
369 boolean dirty = false;
370 if (dirtyBits != null) {
371 dirty = dirtyBits.remove((Integer) item);
372 } else {
373 // We consider "" and NULL to be equals
374 dirty = hasValueChanged(value);
375 }
376
377 if (dirty) {
378 info.setDirty();
379 setToInfo(value, item);
380 orig = (value == null ? "" : value);
381 }
382 }
383
384 /**
385 *
386 * @param item
387 * the item number to get for an array of values, or -1 to get
388 * the whole value (has no effect if {@link MetaInfo#isArray()}
389 * is FALSE)
390 * @param addTo
391 * @param nhgap
392 */
393 protected JComponent createComponent(final int item) {
394 setField(item, createField(item));
395 reload(item);
396
397 info.addReloadedListener(new Runnable() {
398 @Override
399 public void run() {
400 reload(item);
401 }
402 });
403 info.addSaveListener(new Runnable() {
404 @Override
405 public void run() {
406 save(item);
407 }
408 });
409
410 JComponent field = getField(item);
411 setPreferredSize(field);
412
413 return field;
414 }
415
416 /**
417 * Create a label which width is constrained in lock steps.
418 *
419 * @param nhgap
420 * negative horisontal gap in pixel to use for the label, i.e.,
421 * the step lock sized labels will start smaller by that amount
422 * (the use case would be to align controls that start at a
423 * different horisontal position)
424 *
425 * @return the label
426 */
427 protected JComponent label(int nhgap) {
428 final JLabel label = new JLabel(info.getName());
429
430 Dimension ps = label.getPreferredSize();
431 if (ps == null) {
432 ps = label.getSize();
433 }
434
435 ps.height = Math.max(ps.height, getMinimumHeight());
436
437 int w = ps.width;
438 int step = 150;
439 for (int i = 2 * step - nhgap; i < 10 * step; i += step) {
440 if (w < i) {
441 w = i;
442 break;
443 }
444 }
445
446 final Runnable showInfo = new Runnable() {
447 @Override
448 public void run() {
449 StringBuilder builder = new StringBuilder();
450 String text = (info.getDescription().replace("\\n", "\n"))
451 .trim();
452 for (String line : StringUtils.justifyText(text, 80,
453 Alignment.LEFT)) {
454 if (builder.length() > 0) {
455 builder.append("\n");
456 }
457 builder.append(line);
458 }
459 text = builder.toString();
460 JOptionPane.showMessageDialog(ConfigItem.this, text,
461 info.getName(), JOptionPane.INFORMATION_MESSAGE);
462 }
463 };
464
465 JLabel help = new JLabel("");
466 help.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
467 try {
468 Image img = new Image(infoImage64);
469 try {
470 BufferedImage bImg = ImageUtilsAwt.fromImage(img);
471 help.setIcon(new ImageIcon(bImg));
472 } finally {
473 img.close();
474 }
475 } catch (IOException e) {
476 // This is an hard-coded image, should not happen
477 help.setText("?");
478 }
479
480 help.addMouseListener(new MouseAdapter() {
481 @Override
482 public void mouseClicked(MouseEvent e) {
483 showInfo.run();
484 }
485 });
486
487 JPanel pane2 = new JPanel(new BorderLayout());
488 pane2.add(help, BorderLayout.WEST);
489 pane2.add(new JLabel(" "), BorderLayout.CENTER);
490
491 JPanel contentPane = new JPanel(new BorderLayout());
492 contentPane.add(label, BorderLayout.WEST);
493 contentPane.add(pane2, BorderLayout.CENTER);
494
495 ps.width = w + 30; // 30 for the (?) sign
496 contentPane.setSize(ps);
497 contentPane.setPreferredSize(ps);
498
499 JPanel pane = new JPanel(new BorderLayout());
500 pane.add(contentPane, BorderLayout.NORTH);
501
502 return pane;
503 }
504
505 protected void setPreferredSize(JComponent field) {
506 int height = Math
507 .max(getMinimumHeight(), field.getMinimumSize().height);
508 setPreferredSize(new Dimension(200, height));
509 }
510
511 static private int getMinimumHeight() {
512 if (minimumHeight < 0) {
513 minimumHeight = new JTextField("Test").getMinimumSize().height;
514 }
515
516 return minimumHeight;
517 }
518 }