source: josm/trunk/src/org/openstreetmap/josm/gui/ExtendedDialog.java@ 8399

Last change on this file since 8399 was 8399, checked in by Don-vip, 9 years ago

see #11397, see #11447 - partial revert of r8308 (SONARJAVA-1061: FP on S1948: no issue should be raised when using Collections of Serializable objects)

  • Property svn:eol-style set to native
File size: 23.1 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Component;
7import java.awt.Dimension;
8import java.awt.GridBagConstraints;
9import java.awt.GridBagLayout;
10import java.awt.Insets;
11import java.awt.Toolkit;
12import java.awt.event.ActionEvent;
13import java.awt.event.KeyEvent;
14import java.util.ArrayList;
15import java.util.Arrays;
16import java.util.Collections;
17import java.util.HashSet;
18import java.util.List;
19import java.util.Set;
20
21import javax.swing.AbstractAction;
22import javax.swing.Action;
23import javax.swing.Icon;
24import javax.swing.JButton;
25import javax.swing.JComponent;
26import javax.swing.JDialog;
27import javax.swing.JLabel;
28import javax.swing.JOptionPane;
29import javax.swing.JPanel;
30import javax.swing.JScrollBar;
31import javax.swing.JScrollPane;
32import javax.swing.KeyStroke;
33import javax.swing.UIManager;
34
35import org.openstreetmap.josm.Main;
36import org.openstreetmap.josm.gui.help.HelpBrowser;
37import org.openstreetmap.josm.gui.help.HelpUtil;
38import org.openstreetmap.josm.gui.util.GuiHelper;
39import org.openstreetmap.josm.gui.widgets.JMultilineLabel;
40import org.openstreetmap.josm.io.OnlineResource;
41import org.openstreetmap.josm.tools.GBC;
42import org.openstreetmap.josm.tools.ImageProvider;
43import org.openstreetmap.josm.tools.Utils;
44import org.openstreetmap.josm.tools.WindowGeometry;
45
46/**
47 * General configurable dialog window.
48 *
49 * If dialog is modal, you can use {@link #getValue()} to retrieve the
50 * button index. Note that the user can close the dialog
51 * by other means. This is usually equivalent to cancel action.
52 *
53 * For non-modal dialogs, {@link #buttonAction(int, ActionEvent)} can be overridden.
54 *
55 * There are various options, see below.
56 *
57 * Note: The button indices are counted from 1 and upwards.
58 * So for {@link #getValue()}, {@link #setDefaultButton(int)} and
59 * {@link #setCancelButton} the first button has index 1.
60 *
61 * Simple example:
62 * <pre>
63 * ExtendedDialog ed = new ExtendedDialog(
64 * Main.parent, tr("Dialog Title"),
65 * new String[] {tr("Ok"), tr("Cancel")});
66 * ed.setButtonIcons(new String[] {"ok", "cancel"}); // optional
67 * ed.setIcon(JOptionPane.WARNING_MESSAGE); // optional
68 * ed.setContent(tr("Really proceed? Interesting things may happen..."));
69 * ed.showDialog();
70 * if (ed.getValue() == 1) { // user clicked first button "Ok"
71 * // proceed...
72 * }
73 * </pre>
74 */
75public class ExtendedDialog extends JDialog {
76 private final boolean disposeOnClose;
77 private int result = 0;
78 public static final int DialogClosedOtherwise = 0;
79 private boolean toggleable = false;
80 private String rememberSizePref = "";
81 private transient WindowGeometry defaultWindowGeometry = null;
82 private String togglePref = "";
83 private int toggleValue = -1;
84 private ConditionalOptionPaneUtil.MessagePanel togglePanel;
85 private Component parent;
86 private Component content;
87 private final String[] bTexts;
88 private String[] bToolTipTexts;
89 private transient Icon[] bIcons;
90 private Set<Integer> cancelButtonIdx = Collections.emptySet();
91 private int defaultButtonIdx = 1;
92 protected JButton defaultButton = null;
93 private transient Icon icon;
94 private boolean modal;
95 private boolean focusOnDefaultButton = false;
96
97 /** true, if the dialog should include a help button */
98 private boolean showHelpButton;
99 /** the help topic */
100 private String helpTopic;
101
102 /**
103 * set to true if the content of the extended dialog should
104 * be placed in a {@link JScrollPane}
105 */
106 private boolean placeContentInScrollPane;
107
108 // For easy access when inherited
109 protected transient Insets contentInsets = new Insets(10,5,0,5);
110 protected List<JButton> buttons = new ArrayList<>();
111
112 /**
113 * This method sets up the most basic options for the dialog. Add more
114 * advanced features with dedicated methods.
115 * Possible features:
116 * <ul>
117 * <li><code>setButtonIcons</code></li>
118 * <li><code>setContent</code></li>
119 * <li><code>toggleEnable</code></li>
120 * <li><code>toggleDisable</code></li>
121 * <li><code>setToggleCheckboxText</code></li>
122 * <li><code>setRememberWindowGeometry</code></li>
123 * </ul>
124 *
125 * When done, call <code>showDialog</code> to display it. You can receive
126 * the user's choice using <code>getValue</code>. Have a look at this function
127 * for possible return values.
128 *
129 * @param parent The parent element that will be used for position and maximum size
130 * @param title The text that will be shown in the window titlebar
131 * @param buttonTexts String Array of the text that will appear on the buttons. The first button is the default one.
132 */
133 public ExtendedDialog(Component parent, String title, String[] buttonTexts) {
134 this(parent, title, buttonTexts, true, true);
135 }
136
137 /**
138 * Same as above but lets you define if the dialog should be modal.
139 * @param parent The parent element that will be used for position and maximum size
140 * @param title The text that will be shown in the window titlebar
141 * @param buttonTexts String Array of the text that will appear on the buttons. The first button is the default one.
142 * @param modal Set it to {@code true} if you want the dialog to be modal
143 */
144 public ExtendedDialog(Component parent, String title, String[] buttonTexts, boolean modal) {
145 this(parent, title, buttonTexts, modal, true);
146 }
147
148 public ExtendedDialog(Component parent, String title, String[] buttonTexts, boolean modal, boolean disposeOnClose) {
149 super(JOptionPane.getFrameForComponent(parent), title, modal ? ModalityType.DOCUMENT_MODAL : ModalityType.MODELESS);
150 this.parent = parent;
151 this.modal = modal;
152 bTexts = Utils.copyArray(buttonTexts);
153 if (disposeOnClose) {
154 setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
155 }
156 this.disposeOnClose = disposeOnClose;
157 }
158
159 /**
160 * Allows decorating the buttons with icons.
161 * @param buttonIcons The button icons
162 * @return {@code this}
163 */
164 public ExtendedDialog setButtonIcons(Icon[] buttonIcons) {
165 this.bIcons = Utils.copyArray(buttonIcons);
166 return this;
167 }
168
169 /**
170 * Convenience method to provide image names instead of images.
171 * @param buttonIcons The button icon names
172 * @return {@code this}
173 */
174 public ExtendedDialog setButtonIcons(String[] buttonIcons) {
175 bIcons = new Icon[buttonIcons.length];
176 for (int i=0; i<buttonIcons.length; ++i) {
177 bIcons[i] = ImageProvider.get(buttonIcons[i]);
178 }
179 return this;
180 }
181
182 /**
183 * Allows decorating the buttons with tooltips. Expects a String array with
184 * translated tooltip texts.
185 *
186 * @param toolTipTexts the tool tip texts. Ignored, if null.
187 * @return {@code this}
188 */
189 public ExtendedDialog setToolTipTexts(String[] toolTipTexts) {
190 this.bToolTipTexts = Utils.copyArray(toolTipTexts);
191 return this;
192 }
193
194 /**
195 * Sets the content that will be displayed in the message dialog.
196 *
197 * Note that depending on your other settings more UI elements may appear.
198 * The content is played on top of the other elements though.
199 *
200 * @param content Any element that can be displayed in the message dialog
201 * @return {@code this}
202 */
203 public ExtendedDialog setContent(Component content) {
204 return setContent(content, true);
205 }
206
207 /**
208 * Sets the content that will be displayed in the message dialog.
209 *
210 * Note that depending on your other settings more UI elements may appear.
211 * The content is played on top of the other elements though.
212 *
213 * @param content Any element that can be displayed in the message dialog
214 * @param placeContentInScrollPane if true, places the content in a JScrollPane
215 * @return {@code this}
216 */
217 public ExtendedDialog setContent(Component content, boolean placeContentInScrollPane) {
218 this.content = content;
219 this.placeContentInScrollPane = placeContentInScrollPane;
220 return this;
221 }
222
223 /**
224 * Sets the message that will be displayed. The String will be automatically
225 * wrapped if it is too long.
226 *
227 * Note that depending on your other settings more UI elements may appear.
228 * The content is played on top of the other elements though.
229 *
230 * @param message The text that should be shown to the user
231 * @return {@code this}
232 */
233 public ExtendedDialog setContent(String message) {
234 return setContent(string2label(message), false);
235 }
236
237 /**
238 * Decorate the dialog with an icon that is shown on the left part of
239 * the window area. (Similar to how it is done in {@link JOptionPane})
240 * @param icon The icon to display
241 * @return {@code this}
242 */
243 public ExtendedDialog setIcon(Icon icon) {
244 this.icon = icon;
245 return this;
246 }
247
248 /**
249 * Convenience method to allow values that would be accepted by {@link JOptionPane} as messageType.
250 * @param messageType The {@link JOptionPane} messageType
251 * @return {@code this}
252 */
253 public ExtendedDialog setIcon(int messageType) {
254 switch (messageType) {
255 case JOptionPane.ERROR_MESSAGE:
256 return setIcon(UIManager.getIcon("OptionPane.errorIcon"));
257 case JOptionPane.INFORMATION_MESSAGE:
258 return setIcon(UIManager.getIcon("OptionPane.informationIcon"));
259 case JOptionPane.WARNING_MESSAGE:
260 return setIcon(UIManager.getIcon("OptionPane.warningIcon"));
261 case JOptionPane.QUESTION_MESSAGE:
262 return setIcon(UIManager.getIcon("OptionPane.questionIcon"));
263 case JOptionPane.PLAIN_MESSAGE:
264 return setIcon(null);
265 default:
266 throw new IllegalArgumentException("Unknown message type!");
267 }
268 }
269
270 /**
271 * Show the dialog to the user. Call this after you have set all options
272 * for the dialog. You can retrieve the result using {@link #getValue()}.
273 * @return {@code this}
274 */
275 public ExtendedDialog showDialog() {
276 // Check if the user has set the dialog to not be shown again
277 if (toggleCheckState()) {
278 result = toggleValue;
279 return this;
280 }
281
282 setupDialog();
283 if (defaultButton != null) {
284 getRootPane().setDefaultButton(defaultButton);
285 }
286 // Don't focus the "do not show this again" check box, but the default button.
287 if (toggleable || focusOnDefaultButton) {
288 requestFocusToDefaultButton();
289 }
290 setVisible(true);
291 toggleSaveState();
292 return this;
293 }
294
295 /**
296 * Retrieve the user choice after the dialog has been closed.
297 *
298 * @return <ul> <li>The selected button. The count starts with 1.</li>
299 * <li>A return value of {@link #DialogClosedOtherwise} means the dialog has been closed otherwise.</li>
300 * </ul>
301 */
302 public int getValue() {
303 return result;
304 }
305
306 private boolean setupDone = false;
307
308 /**
309 * This is called by {@link #showDialog()}.
310 * Only invoke from outside if you need to modify the contentPane
311 */
312 public void setupDialog() {
313 if (setupDone)
314 return;
315 setupDone = true;
316
317 setupEscListener();
318
319 JButton button;
320 JPanel buttonsPanel = new JPanel(new GridBagLayout());
321
322 for (int i=0; i < bTexts.length; i++) {
323 final int final_i = i;
324 Action action = new AbstractAction(bTexts[i]) {
325 @Override public void actionPerformed(ActionEvent evt) {
326 buttonAction(final_i, evt);
327 }
328 };
329
330 button = new JButton(action);
331 if (i == defaultButtonIdx-1) {
332 defaultButton = button;
333 }
334 if(bIcons != null && bIcons[i] != null) {
335 button.setIcon(bIcons[i]);
336 }
337 if (bToolTipTexts != null && i < bToolTipTexts.length && bToolTipTexts[i] != null) {
338 button.setToolTipText(bToolTipTexts[i]);
339 }
340
341 buttonsPanel.add(button, GBC.std().insets(2,2,2,2));
342 buttons.add(button);
343 }
344 if (showHelpButton) {
345 buttonsPanel.add(new JButton(new HelpAction()), GBC.std().insets(2,2,2,2));
346 HelpUtil.setHelpContext(getRootPane(),helpTopic);
347 }
348
349 JPanel cp = new JPanel(new GridBagLayout());
350
351 GridBagConstraints gc = new GridBagConstraints();
352 gc.gridx = 0;
353 int y = 0;
354 gc.gridy = y++;
355 gc.weightx = 0.0;
356 gc.weighty = 0.0;
357
358 if (icon != null) {
359 JLabel iconLbl = new JLabel(icon);
360 gc.insets = new Insets(10,10,10,10);
361 gc.anchor = GridBagConstraints.NORTH;
362 gc.weighty = 1.0;
363 cp.add(iconLbl, gc);
364 gc.anchor = GridBagConstraints.CENTER;
365 gc.gridx = 1;
366 }
367
368 gc.fill = GridBagConstraints.BOTH;
369 gc.insets = contentInsets;
370 gc.weightx = 1.0;
371 gc.weighty = 1.0;
372 cp.add(content, gc);
373
374 gc.fill = GridBagConstraints.NONE;
375 gc.gridwidth = GridBagConstraints.REMAINDER;
376 gc.weightx = 0.0;
377 gc.weighty = 0.0;
378
379 if (toggleable) {
380 togglePanel = new ConditionalOptionPaneUtil.MessagePanel(null, ConditionalOptionPaneUtil.isInBulkOperation(togglePref));
381 gc.gridx = icon != null ? 1 : 0;
382 gc.gridy = y++;
383 gc.anchor = GridBagConstraints.LINE_START;
384 gc.insets = new Insets(5,contentInsets.left,5,contentInsets.right);
385 cp.add(togglePanel, gc);
386 }
387
388 gc.gridy = y++;
389 gc.anchor = GridBagConstraints.CENTER;
390 gc.insets = new Insets(5,5,5,5);
391 cp.add(buttonsPanel, gc);
392 if (placeContentInScrollPane) {
393 JScrollPane pane = new JScrollPane(cp);
394 pane.setBorder(null);
395 setContentPane(pane);
396 } else {
397 setContentPane(cp);
398 }
399 pack();
400
401 // Try to make it not larger than the parent window or at least not larger than 2/3 of the screen
402 Dimension d = getSize();
403 Dimension x = findMaxDialogSize();
404
405 boolean limitedInWidth = d.width > x.width;
406 boolean limitedInHeight = d.height > x.height;
407
408 if(x.width > 0 && d.width > x.width) {
409 d.width = x.width;
410 }
411 if(x.height > 0 && d.height > x.height) {
412 d.height = x.height;
413 }
414
415 // We have a vertical scrollbar and enough space to prevent a horizontal one
416 if(!limitedInWidth && limitedInHeight) {
417 d.width += new JScrollBar().getPreferredSize().width;
418 }
419
420 setSize(d);
421 setLocationRelativeTo(parent);
422 }
423
424 /**
425 * This gets performed whenever a button is clicked or activated
426 * @param buttonIndex the button index (first index is 0)
427 * @param evt the button event
428 */
429 protected void buttonAction(int buttonIndex, ActionEvent evt) {
430 result = buttonIndex+1;
431 setVisible(false);
432 }
433
434 /**
435 * Tries to find a good value of how large the dialog should be
436 * @return Dimension Size of the parent Component or 2/3 of screen size if not available
437 */
438 protected Dimension findMaxDialogSize() {
439 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
440 Dimension x = new Dimension(screenSize.width*2/3, screenSize.height*2/3);
441 if (parent != null) {
442 x = JOptionPane.getFrameForComponent(parent).getSize();
443 }
444 return x;
445 }
446
447 /**
448 * Makes the dialog listen to ESC keypressed
449 */
450 private void setupEscListener() {
451 Action actionListener = new AbstractAction() {
452 @Override
453 public void actionPerformed(ActionEvent actionEvent) {
454 // 0 means that the dialog has been closed otherwise.
455 // We need to set it to zero again, in case the dialog has been re-used
456 // and the result differs from its default value
457 result = ExtendedDialog.DialogClosedOtherwise;
458 setVisible(false);
459 }
460 };
461
462 getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
463 .put(KeyStroke.getKeyStroke("ESCAPE"), "ESCAPE");
464 getRootPane().getActionMap().put("ESCAPE", actionListener);
465 }
466
467 protected final void rememberWindowGeometry(WindowGeometry geometry) {
468 if (geometry != null) {
469 geometry.remember(rememberSizePref);
470 }
471 }
472
473 protected final WindowGeometry initWindowGeometry() {
474 return new WindowGeometry(rememberSizePref, defaultWindowGeometry);
475 }
476
477 /**
478 * Override setVisible to be able to save the window geometry if required
479 */
480 @Override
481 public void setVisible(boolean visible) {
482 if (visible) {
483 repaint();
484 }
485
486 // Ensure all required variables are available
487 if(rememberSizePref.length() != 0 && defaultWindowGeometry != null) {
488 if(visible) {
489 initWindowGeometry().applySafe(this);
490 } else if (isShowing()) { // should fix #6438, #6981, #8295
491 rememberWindowGeometry(new WindowGeometry(this));
492 }
493 }
494 super.setVisible(visible);
495
496 if (!visible && disposeOnClose) {
497 dispose();
498 }
499 }
500
501 /**
502 * Call this if you want the dialog to remember the geometry (size and position) set by the user.
503 * Set the pref to <code>null</code> or to an empty string to disable again.
504 * By default, it's disabled.
505 *
506 * Note: If you want to set the width of this dialog directly use the usual
507 * setSize, setPreferredSize, setMaxSize, setMinSize
508 *
509 * @param pref The preference to save the dimension to
510 * @param wg The default window geometry that should be used if no
511 * existing preference is found (only takes effect if
512 * <code>pref</code> is not null or empty
513 * @return {@code this}
514 */
515 public ExtendedDialog setRememberWindowGeometry(String pref, WindowGeometry wg) {
516 rememberSizePref = pref == null ? "" : pref;
517 defaultWindowGeometry = wg;
518 return this;
519 }
520
521 /**
522 * Calling this will offer the user a "Do not show again" checkbox for the
523 * dialog. Default is to not offer the choice; the dialog will be shown
524 * every time.
525 * Currently, this is not supported for non-modal dialogs.
526 * @param togglePref The preference to save the checkbox state to
527 * @return {@code this}
528 */
529 public ExtendedDialog toggleEnable(String togglePref) {
530 if (!modal) {
531 throw new IllegalStateException();
532 }
533 this.toggleable = true;
534 this.togglePref = togglePref;
535 return this;
536 }
537
538 /**
539 * Call this if you "accidentally" called toggleEnable. This doesn't need
540 * to be called for every dialog, as it's the default anyway.
541 * @return {@code this}
542 */
543 public ExtendedDialog toggleDisable() {
544 this.toggleable = false;
545 return this;
546 }
547
548 /**
549 * Sets the button that will react to ENTER.
550 * @param defaultButtonIdx The button index (starts to 1)
551 * @return {@code this}
552 */
553 public ExtendedDialog setDefaultButton(int defaultButtonIdx) {
554 this.defaultButtonIdx = defaultButtonIdx;
555 return this;
556 }
557
558 /**
559 * Used in combination with toggle:
560 * If the user presses 'cancel' the toggle settings are ignored and not saved to the pref
561 * @param cancelButtonIdx index of the button that stands for cancel, accepts multiple values
562 * @return {@code this}
563 */
564 public ExtendedDialog setCancelButton(Integer... cancelButtonIdx) {
565 this.cancelButtonIdx = new HashSet<>(Arrays.<Integer>asList(cancelButtonIdx));
566 return this;
567 }
568
569 /**
570 * Makes default button request initial focus or not.
571 * @param focus {@code true} to make default button request initial focus
572 * @since 7407
573 */
574 public void setFocusOnDefaultButton(boolean focus) {
575 focusOnDefaultButton = focus;
576 }
577
578 private void requestFocusToDefaultButton() {
579 if (defaultButton != null) {
580 GuiHelper.runInEDT(new Runnable() {
581 @Override
582 public void run() {
583 defaultButton.requestFocusInWindow();
584 }
585 });
586 }
587 }
588
589 /**
590 * This function returns true if the dialog has been set to "do not show again"
591 * @return true if dialog should not be shown again
592 */
593 public final boolean toggleCheckState() {
594 toggleable = togglePref != null && !togglePref.isEmpty();
595 toggleValue = ConditionalOptionPaneUtil.getDialogReturnValue(togglePref);
596 return toggleable && toggleValue != -1;
597 }
598
599 /**
600 * This function checks the state of the "Do not show again" checkbox and
601 * writes the corresponding pref.
602 */
603 private void toggleSaveState() {
604 if (!toggleable ||
605 togglePanel == null ||
606 cancelButtonIdx.contains(result) ||
607 result == ExtendedDialog.DialogClosedOtherwise)
608 return;
609 togglePanel.getNotShowAgain().store(togglePref, result);
610 }
611
612 /**
613 * Convenience function that converts a given string into a JMultilineLabel
614 * @param msg the message to display
615 * @return JMultilineLabel displaying {@code msg}
616 */
617 private static JMultilineLabel string2label(String msg) {
618 JMultilineLabel lbl = new JMultilineLabel(msg);
619 // Make it not wider than 1/2 of the screen
620 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
621 lbl.setMaxWidth(screenSize.width/2);
622 // Disable default Enter key binding to allow dialog's one (then enables to hit default button from here)
623 lbl.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), new Object());
624 return lbl;
625 }
626
627 /**
628 * Configures how this dialog support for context sensitive help.
629 * <ul>
630 * <li>if helpTopic is null, the dialog doesn't provide context sensitive help</li>
631 * <li>if helpTopic != null, the dialog redirect user to the help page for this helpTopic when
632 * the user clicks F1 in the dialog</li>
633 * <li>if showHelpButton is true, the dialog displays "Help" button (rightmost button in
634 * the button row)</li>
635 * </ul>
636 *
637 * @param helpTopic the help topic
638 * @param showHelpButton true, if the dialog displays a help button
639 * @return {@code this}
640 */
641 public ExtendedDialog configureContextsensitiveHelp(String helpTopic, boolean showHelpButton) {
642 this.helpTopic = helpTopic;
643 this.showHelpButton = showHelpButton;
644 return this;
645 }
646
647 class HelpAction extends AbstractAction {
648 public HelpAction() {
649 putValue(SHORT_DESCRIPTION, tr("Show help information"));
650 putValue(NAME, tr("Help"));
651 putValue(SMALL_ICON, ImageProvider.get("help"));
652 setEnabled(!Main.isOffline(OnlineResource.JOSM_WEBSITE));
653 }
654
655 @Override
656 public void actionPerformed(ActionEvent e) {
657 HelpBrowser.setUrlForHelpTopic(helpTopic);
658 }
659 }
660}
Note: See TracBrowser for help on using the repository browser.