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