jdoc
[fanfix.git] / src / be / nikiroo / utils / ui / ConfigItem.java
CommitLineData
d350b96b
NR
1package be.nikiroo.utils.ui;
2
3import java.awt.BorderLayout;
daf0fd5a 4import java.awt.Cursor;
c637d2e0 5import java.awt.Dimension;
424dcb0d
NR
6import java.awt.event.ActionEvent;
7import java.awt.event.ActionListener;
daf0fd5a
NR
8import java.awt.event.MouseAdapter;
9import java.awt.event.MouseEvent;
424dcb0d 10import java.awt.image.BufferedImage;
daf0fd5a 11import java.io.IOException;
d5026c09
NR
12import java.util.ArrayList;
13import java.util.List;
424dcb0d 14
d5026c09 15import javax.swing.BoxLayout;
424dcb0d
NR
16import javax.swing.ImageIcon;
17import javax.swing.JButton;
0877d6f5 18import javax.swing.JComponent;
8517b60c 19import javax.swing.JLabel;
0877d6f5 20import javax.swing.JOptionPane;
d350b96b
NR
21import javax.swing.JPanel;
22import javax.swing.JTextField;
d350b96b 23
daf0fd5a 24import be.nikiroo.utils.Image;
0877d6f5
NR
25import be.nikiroo.utils.StringUtils;
26import be.nikiroo.utils.StringUtils.Alignment;
d350b96b 27import be.nikiroo.utils.resources.Bundle;
9e834013 28import be.nikiroo.utils.resources.MetaInfo;
d350b96b
NR
29
30/**
31 * A graphical item that reflect a configuration option from the given
32 * {@link Bundle}.
76b51de9
NR
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.
d350b96b
NR
37 *
38 * @author niki
db31c358 39 *
d350b96b
NR
40 * @param <E>
41 * the type of {@link Bundle} to edit
42 */
43public class ConfigItem<E extends Enum<E>> extends JPanel {
44 private static final long serialVersionUID = 1L;
db31c358 45
e95f4fb6
NR
46 private static int minimumHeight = -1;
47
daf0fd5a
NR
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
fde375c1
NR
60 /** The original value before current changes. */
61 private Object orig;
d5026c09
NR
62 private List<Integer> dirtyBits;
63
64 protected MetaInfo<E> info;
65
66 private JComponent field;
67 private List<JComponent> fields = new ArrayList<JComponent>();
fde375c1 68
76b51de9
NR
69 /**
70 * Create a new {@link ConfigItem} for the given {@link MetaInfo}.
71 *
72 * @param info
73 * the {@link MetaInfo}
d18e136e
NR
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)
76b51de9 79 */
d18e136e 80 public ConfigItem(MetaInfo<E> info, int nhgap) {
d5026c09 81 this(info, true);
76b51de9 82
d5026c09
NR
83 ConfigItem<E> configItem;
84 switch (info.getFormat()) {
0877d6f5 85 case BOOLEAN:
d5026c09 86 configItem = new ConfigItemBoolean<E>(info);
0877d6f5
NR
87 break;
88 case COLOR:
d5026c09 89 configItem = new ConfigItemColor<E>(info);
0877d6f5
NR
90 break;
91 case FILE:
d5026c09 92 configItem = new ConfigItemBrowse<E>(info, false);
0877d6f5
NR
93 break;
94 case DIRECTORY:
d5026c09 95 configItem = new ConfigItemBrowse<E>(info, true);
0877d6f5
NR
96 break;
97 case COMBO_LIST:
d5026c09 98 configItem = new ConfigItemCombobox<E>(info, true);
0877d6f5
NR
99 break;
100 case FIXED_LIST:
d5026c09 101 configItem = new ConfigItemCombobox<E>(info, false);
0877d6f5
NR
102 break;
103 case INT:
d5026c09 104 configItem = new ConfigItemInteger<E>(info);
0877d6f5
NR
105 break;
106 case PASSWORD:
d5026c09 107 configItem = new ConfigItemPassword<E>(info);
0877d6f5
NR
108 break;
109 case STRING:
110 case LOCALE: // TODO?
111 default:
d5026c09 112 configItem = new ConfigItemString<E>(info);
0877d6f5
NR
113 break;
114 }
d350b96b 115
d5026c09
NR
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 }
fde375c1 127
d5026c09
NR
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 });
fde375c1 148
d5026c09
NR
149 JPanel tmp = new JPanel(new BorderLayout());
150 tmp.add(add, BorderLayout.WEST);
fde375c1 151
d5026c09
NR
152 JPanel mainPlus = new JPanel(new BorderLayout());
153 mainPlus.add(main, BorderLayout.CENTER);
154 mainPlus.add(tmp, BorderLayout.SOUTH);
fde375c1 155
d5026c09
NR
156 add(mainPlus, BorderLayout.CENTER);
157 } else {
158 this.setLayout(new BorderLayout());
159 add(label(nhgap), BorderLayout.WEST);
0877d6f5 160
d5026c09
NR
161 JComponent field = configItem.createComponent(-1);
162 add(field, BorderLayout.CENTER);
163 }
0877d6f5 164 }
9e834013 165
d5026c09
NR
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>();
0877d6f5 181 }
d5026c09 182 }
0877d6f5 183
d5026c09
NR
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 }
0877d6f5 202
d5026c09
NR
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 }
d18e136e 218
d5026c09
NR
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
0877d6f5
NR
232 }
233
d5026c09
NR
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 }
0877d6f5 246
d5026c09
NR
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 }
0877d6f5 261
d5026c09
NR
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 }
0877d6f5 279
d5026c09
NR
280 for (int i = fields.size(); i <= item; i++) {
281 fields.add(null);
282 }
d18e136e 283
d5026c09 284 fields.set(item, field);
0877d6f5
NR
285 }
286
d5026c09
NR
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 }
0877d6f5 302
d5026c09
NR
303 if (item < fields.size()) {
304 return fields.get(item);
305 }
d18e136e 306
d5026c09 307 return null;
0877d6f5
NR
308 }
309
d5026c09
NR
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 }
d18e136e 327
d5026c09
NR
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);
0877d6f5
NR
342 }
343
d5026c09
NR
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);
0877d6f5 355
d5026c09
NR
356 // We consider "" and NULL to be equals
357 orig = (value == null ? "" : value);
358 }
0877d6f5 359
d5026c09
NR
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 }
d18e136e 381
d5026c09
NR
382 if (dirty) {
383 info.setDirty();
384 setToInfo(value, item);
385 orig = (value == null ? "" : value);
386 }
0877d6f5
NR
387 }
388
d5026c09
NR
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);
0877d6f5
NR
401
402 info.addReloadedListener(new Runnable() {
403 @Override
404 public void run() {
d5026c09 405 reload(item);
0877d6f5
NR
406 }
407 });
408 info.addSaveListener(new Runnable() {
409 @Override
410 public void run() {
d5026c09 411 save(item);
0877d6f5
NR
412 }
413 });
9e834013 414
d5026c09 415 JComponent field = getField(item);
d18e136e 416 setPreferredSize(field);
d5026c09
NR
417
418 return field;
d350b96b 419 }
c637d2e0
NR
420
421 /**
422 * Create a label which width is constrained in lock steps.
423 *
d18e136e
NR
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)
c637d2e0
NR
429 *
430 * @return the label
431 */
d5026c09 432 protected JComponent label(int nhgap) {
0877d6f5 433 final JLabel label = new JLabel(info.getName());
c637d2e0
NR
434
435 Dimension ps = label.getPreferredSize();
436 if (ps == null) {
437 ps = label.getSize();
438 }
439
e95f4fb6
NR
440 ps.height = Math.max(ps.height, getMinimumHeight());
441
c637d2e0 442 int w = ps.width;
daf0fd5a 443 int step = 150;
d18e136e 444 for (int i = 2 * step - nhgap; i < 10 * step; i += step) {
c637d2e0
NR
445 if (w < i) {
446 w = i;
447 break;
448 }
449 }
450
daf0fd5a 451 final Runnable showInfo = new Runnable() {
0877d6f5 452 @Override
daf0fd5a 453 public void run() {
0877d6f5 454 StringBuilder builder = new StringBuilder();
d18e136e
NR
455 String text = (info.getDescription().replace("\\n", "\n"))
456 .trim();
0877d6f5
NR
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();
daf0fd5a
NR
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();
0877d6f5
NR
489 }
490 });
491
492 JPanel pane2 = new JPanel(new BorderLayout());
493 pane2.add(help, BorderLayout.WEST);
494 pane2.add(new JLabel(" "), BorderLayout.CENTER);
495
e95f4fb6
NR
496 JPanel contentPane = new JPanel(new BorderLayout());
497 contentPane.add(label, BorderLayout.WEST);
498 contentPane.add(pane2, BorderLayout.CENTER);
0877d6f5
NR
499
500 ps.width = w + 30; // 30 for the (?) sign
e95f4fb6
NR
501 contentPane.setSize(ps);
502 contentPane.setPreferredSize(ps);
503
504 JPanel pane = new JPanel(new BorderLayout());
505 pane.add(contentPane, BorderLayout.NORTH);
c637d2e0 506
0877d6f5 507 return pane;
c637d2e0 508 }
424dcb0d 509
d5026c09 510 protected void setPreferredSize(JComponent field) {
e95f4fb6
NR
511 int height = Math
512 .max(getMinimumHeight(), field.getMinimumSize().height);
d18e136e
NR
513 setPreferredSize(new Dimension(200, height));
514 }
e95f4fb6
NR
515
516 static private int getMinimumHeight() {
517 if (minimumHeight < 0) {
518 minimumHeight = new JTextField("Test").getMinimumSize().height;
519 }
520
521 return minimumHeight;
522 }
d350b96b 523}