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