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