001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.Component;
007import java.awt.Dialog.ModalityType;
008import java.awt.GraphicsEnvironment;
009import java.awt.event.ActionEvent;
010import java.awt.event.KeyEvent;
011import java.awt.event.WindowAdapter;
012import java.awt.event.WindowEvent;
013import java.util.ArrayList;
014import java.util.Collection;
015import java.util.HashSet;
016import java.util.List;
017
018import javax.swing.AbstractAction;
019import javax.swing.Action;
020import javax.swing.Icon;
021import javax.swing.JButton;
022import javax.swing.JComponent;
023import javax.swing.JDialog;
024import javax.swing.JOptionPane;
025import javax.swing.KeyStroke;
026import javax.swing.event.ChangeEvent;
027import javax.swing.event.ChangeListener;
028
029import org.openstreetmap.josm.gui.help.HelpBrowser;
030import org.openstreetmap.josm.gui.help.HelpUtil;
031import org.openstreetmap.josm.gui.util.GuiHelper;
032import org.openstreetmap.josm.gui.widgets.JMultilineLabel;
033import org.openstreetmap.josm.tools.ImageProvider;
034import org.openstreetmap.josm.tools.InputMapUtils;
035import org.openstreetmap.josm.tools.WindowGeometry;
036
037public final class HelpAwareOptionPane {
038
039    private HelpAwareOptionPane() {
040        // Hide default constructor for utils classes
041    }
042
043    public static class ButtonSpec {
044        public final String text;
045        public final Icon icon;
046        public final String tooltipText;
047        public final String helpTopic;
048        private boolean enabled;
049
050        private final Collection<ChangeListener> listeners = new HashSet<>();
051
052        /**
053         * Constructs a new {@code ButtonSpec}.
054         * @param text the button text
055         * @param icon the icon to display. Can be null
056         * @param tooltipText the tooltip text. Can be null.
057         * @param helpTopic the help topic. Can be null.
058         */
059        public ButtonSpec(String text, Icon icon, String tooltipText, String helpTopic) {
060            this(text, icon, tooltipText, helpTopic, true);
061        }
062
063        /**
064         * Constructs a new {@code ButtonSpec}.
065         * @param text the button text
066         * @param icon the icon to display. Can be null
067         * @param tooltipText the tooltip text. Can be null.
068         * @param helpTopic the help topic. Can be null.
069         * @param enabled the enabled status
070         * @since 5951
071         */
072        public ButtonSpec(String text, Icon icon, String tooltipText, String helpTopic, boolean enabled) {
073            this.text = text;
074            this.icon = icon;
075            this.tooltipText = tooltipText;
076            this.helpTopic = helpTopic;
077            setEnabled(enabled);
078        }
079
080        /**
081         * Determines if this button spec is enabled
082         * @return {@code true} if this button spec is enabled, {@code false} otherwise
083         * @since 6051
084         */
085        public final boolean isEnabled() {
086            return enabled;
087        }
088
089        /**
090         * Enables or disables this button spec, depending on the value of the parameter {@code b}.
091         * @param enabled if {@code true}, this button spec is enabled; otherwise this button spec is disabled
092         * @since 6051
093         */
094        public final void setEnabled(boolean enabled) {
095            if (this.enabled != enabled) {
096                this.enabled = enabled;
097                ChangeEvent event = new ChangeEvent(this);
098                for (ChangeListener listener : listeners) {
099                    listener.stateChanged(event);
100                }
101            }
102        }
103
104        private boolean addChangeListener(ChangeListener listener) {
105            return listener != null && listeners.add(listener);
106        }
107    }
108
109    private static class DefaultAction extends AbstractAction {
110        private final JDialog dialog;
111        private final JOptionPane pane;
112        private final int value;
113
114        DefaultAction(JDialog dialog, JOptionPane pane, int value) {
115            this.dialog = dialog;
116            this.pane = pane;
117            this.value = value;
118        }
119
120        @Override
121        public void actionPerformed(ActionEvent e) {
122            pane.setValue(value);
123            dialog.setVisible(false);
124        }
125    }
126
127    /**
128     * Creates the list buttons to be displayed in the option pane dialog.
129     *
130     * @param options the option. If null, just creates an OK button and a help button
131     * @param helpTopic the help topic. The context sensitive help of all buttons is equal
132     * to the context sensitive help of the whole dialog
133     * @return the list of buttons
134     */
135    private static List<JButton> createOptionButtons(ButtonSpec[] options, String helpTopic) {
136        List<JButton> buttons = new ArrayList<>();
137        if (options == null) {
138            JButton b = new JButton(tr("OK"));
139            b.setIcon(ImageProvider.get("ok"));
140            b.setToolTipText(tr("Click to close the dialog"));
141            b.setFocusable(true);
142            buttons.add(b);
143        } else {
144            for (final ButtonSpec spec: options) {
145                final JButton b = new JButton(spec.text);
146                b.setIcon(spec.icon);
147                b.setToolTipText(spec.tooltipText == null ? "" : spec.tooltipText);
148                if (helpTopic != null) {
149                    HelpUtil.setHelpContext(b, helpTopic);
150                }
151                b.setFocusable(true);
152                b.setEnabled(spec.isEnabled());
153                spec.addChangeListener(new ChangeListener() {
154                    @Override public void stateChanged(ChangeEvent e) {
155                        b.setEnabled(spec.isEnabled());
156                    }
157                });
158                buttons.add(b);
159            }
160        }
161        return buttons;
162    }
163
164    /**
165     * Creates the help button
166     *
167     * @param helpTopic the help topic
168     * @return the help button
169     */
170    private static JButton createHelpButton(final String helpTopic) {
171        JButton b = new JButton(tr("Help"));
172        b.setIcon(ImageProvider.get("help"));
173        b.setToolTipText(tr("Show help information"));
174        HelpUtil.setHelpContext(b, helpTopic);
175        Action a = new AbstractAction() {
176            @Override
177            public void actionPerformed(ActionEvent e) {
178                HelpBrowser.setUrlForHelpTopic(helpTopic);
179            }
180        };
181        b.addActionListener(a);
182        InputMapUtils.enableEnter(b);
183        return b;
184    }
185
186    /**
187     * Displays an option dialog which is aware of a help context. If <code>helpTopic</code> isn't null,
188     * the dialog includes a "Help" button and launches the help browser if the user presses F1. If the
189     * user clicks on the "Help" button the option dialog remains open and JOSM launches the help
190     * browser.
191     *
192     * <code>helpTopic</code> is the trailing part of a JOSM online help URL, i.e. the part after the leading
193     * <code>https://josm.openstreetmap.de/wiki/Help</code>. It should start with a leading '/' and it
194     * may include an anchor after a '#'.
195     *
196     * <strong>Examples</strong>
197     * <ul>
198     *    <li>/Dialogs/RelationEditor</li>
199     *    <li>/Dialogs/RelationEditor#ConflictInData</li>
200     * </ul>
201     *
202     * In addition, the option buttons display JOSM icons, similar to ExtendedDialog.
203     *
204     * @param parentComponent the parent component
205     * @param msg the message
206     * @param title the title
207     * @param messageType the message type (see {@link JOptionPane})
208     * @param icon the icon to display. Can be null.
209     * @param options the list of options to display. Can be null.
210     * @param defaultOption the default option. Can be null.
211     * @param helpTopic the help topic. Can be null.
212     * @return the index of the selected option or {@link JOptionPane#CLOSED_OPTION}
213     */
214    public static int showOptionDialog(Component parentComponent, Object msg, String title, int messageType,
215            Icon icon, final ButtonSpec[] options, final ButtonSpec defaultOption, final String helpTopic)  {
216        final List<JButton> buttons = createOptionButtons(options, helpTopic);
217        if (helpTopic != null) {
218            buttons.add(createHelpButton(helpTopic));
219        }
220
221        JButton defaultButton = null;
222        if (options != null && defaultOption != null) {
223            for (int i = 0; i < options.length; i++) {
224                if (options[i] == defaultOption) {
225                    defaultButton = buttons.get(i);
226                    break;
227                }
228            }
229        }
230
231        if (msg instanceof String) {
232            msg = new JMultilineLabel((String) msg, true);
233        }
234
235        final JOptionPane pane = new JOptionPane(
236                msg,
237                messageType,
238                JOptionPane.DEFAULT_OPTION,
239                icon,
240                buttons.toArray(),
241                defaultButton
242        );
243
244        if (!GraphicsEnvironment.isHeadless()) {
245            doShowOptionDialog(parentComponent, title, options, defaultOption, helpTopic, buttons, pane);
246        }
247        return pane.getValue() instanceof Integer ? (Integer) pane.getValue() : JOptionPane.OK_OPTION;
248    }
249
250    private static void doShowOptionDialog(Component parentComponent, String title, final ButtonSpec[] options,
251            final ButtonSpec defaultOption, final String helpTopic, final List<JButton> buttons,
252            final JOptionPane pane) {
253        final JDialog dialog = new JDialog(
254                JOptionPane.getFrameForComponent(parentComponent),
255                title,
256                ModalityType.DOCUMENT_MODAL
257        );
258        dialog.setContentPane(pane);
259        dialog.addWindowListener(new WindowAdapter() {
260            @Override
261            public void windowClosing(WindowEvent e) {
262                pane.setValue(JOptionPane.CLOSED_OPTION);
263                super.windowClosed(e);
264            }
265
266            @Override
267            public void windowOpened(WindowEvent e) {
268                if (defaultOption != null && options != null && options.length > 0) {
269                    int i;
270                    for (i = 0; i < options.length; i++) {
271                        if (options[i] == defaultOption) {
272                            break;
273                        }
274                    }
275                    if (i >= options.length) {
276                        buttons.get(0).requestFocusInWindow();
277                    }
278                    buttons.get(i).requestFocusInWindow();
279                } else {
280                    buttons.get(0).requestFocusInWindow();
281                }
282            }
283        });
284        dialog.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
285                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "close");
286        dialog.getRootPane().getActionMap().put("close", new AbstractAction() {
287            @Override
288            public void actionPerformed(ActionEvent e) {
289                pane.setValue(JOptionPane.CLOSED_OPTION);
290                dialog.setVisible(false);
291            }
292        });
293
294        if (options != null) {
295            for (int i = 0; i < options.length; i++) {
296                final DefaultAction action = new DefaultAction(dialog, pane, i);
297                buttons.get(i).addActionListener(action);
298                buttons.get(i).getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter");
299                buttons.get(i).getActionMap().put("enter", action);
300            }
301        } else {
302            final DefaultAction action = new DefaultAction(dialog, pane, 0);
303            buttons.get(0).addActionListener(action);
304            buttons.get(0).getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter");
305            buttons.get(0).getActionMap().put("enter", action);
306        }
307
308        dialog.pack();
309        WindowGeometry.centerOnScreen(dialog.getSize()).applySafe(dialog);
310        if (helpTopic != null) {
311            HelpUtil.setHelpContext(dialog.getRootPane(), helpTopic);
312        }
313        dialog.setVisible(true);
314    }
315
316    /**
317     * Displays an option dialog which is aware of a help context.
318     *
319     * @param parentComponent the parent component
320     * @param msg the message
321     * @param title the title
322     * @param messageType the message type (see {@link JOptionPane})
323     * @param helpTopic the help topic. Can be null.
324     * @return the index of the selected option or {@link JOptionPane#CLOSED_OPTION}
325     * @see #showOptionDialog(Component, Object, String, int, Icon, ButtonSpec[], ButtonSpec, String)
326     */
327    public static int showOptionDialog(Component parentComponent, Object msg, String title, int messageType, String helpTopic)  {
328        return showOptionDialog(parentComponent, msg, title, messageType, null, null, null, helpTopic);
329    }
330
331    /**
332     * Run it in Event Dispatch Thread.
333     * This version does not return anything, so it is more like {@code showMessageDialog}.
334     *
335     * It can be used, when you need to show a message dialog from a worker thread,
336     * e.g. from {@code PleaseWaitRunnable}.
337     *
338     * @param parentComponent the parent component
339     * @param msg the message
340     * @param title the title
341     * @param messageType the message type (see {@link JOptionPane})
342     * @param helpTopic the help topic. Can be null.
343     */
344    public static void showMessageDialogInEDT(final Component parentComponent, final Object msg, final String title,
345            final int messageType, final String helpTopic)  {
346        GuiHelper.runInEDT(new Runnable() {
347            @Override
348            public void run() {
349                showOptionDialog(parentComponent, msg, title, messageType, null, null, null, helpTopic);
350            }
351        });
352    }
353}