001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.Component;
007import java.awt.GridBagConstraints;
008import java.awt.GridBagLayout;
009import java.io.ByteArrayOutputStream;
010import java.io.IOException;
011import java.io.PrintWriter;
012import java.io.StringWriter;
013import java.net.URL;
014import java.nio.ByteBuffer;
015import java.nio.charset.StandardCharsets;
016import java.util.zip.GZIPOutputStream;
017
018import javax.swing.JCheckBox;
019import javax.swing.JLabel;
020import javax.swing.JOptionPane;
021import javax.swing.JPanel;
022import javax.swing.JScrollPane;
023import javax.swing.SwingUtilities;
024
025import org.openstreetmap.josm.Main;
026import org.openstreetmap.josm.actions.ShowStatusReportAction;
027import org.openstreetmap.josm.data.Version;
028import org.openstreetmap.josm.gui.ExtendedDialog;
029import org.openstreetmap.josm.gui.preferences.plugin.PluginPreference;
030import org.openstreetmap.josm.gui.widgets.JMultilineLabel;
031import org.openstreetmap.josm.gui.widgets.JosmTextArea;
032import org.openstreetmap.josm.gui.widgets.UrlLabel;
033import org.openstreetmap.josm.plugins.PluginDownloadTask;
034import org.openstreetmap.josm.plugins.PluginHandler;
035
036/**
037 * An exception handler that asks the user to send a bug report.
038 *
039 * @author imi
040 */
041public final class BugReportExceptionHandler implements Thread.UncaughtExceptionHandler {
042
043    private static boolean handlingInProgress;
044    private static volatile BugReporterThread bugReporterThread;
045    private static int exceptionCounter;
046    private static boolean suppressExceptionDialogs;
047
048    private static class BugReporterThread extends Thread {
049
050        private final class BugReporterWorker implements Runnable {
051            private final PluginDownloadTask pluginDownloadTask;
052
053            private BugReporterWorker(PluginDownloadTask pluginDownloadTask) {
054                this.pluginDownloadTask = pluginDownloadTask;
055            }
056
057            @Override
058            public void run() {
059                // Then ask for submitting a bug report, for exceptions thrown from a plugin too, unless updated to a new version
060                if (pluginDownloadTask == null) {
061                    String[] buttonTexts = new String[] {tr("Do nothing"), tr("Report Bug")};
062                    String[] buttonIcons = new String[] {"cancel", "bug"};
063                    int defaultButtonIdx = 1;
064                    String message = tr("An unexpected exception occurred.<br>" +
065                            "This is always a coding error. If you are running the latest<br>" +
066                            "version of JOSM, please consider being kind and file a bug report."
067                            );
068                    // Check user is running current tested version, the error may already be fixed
069                    int josmVersion = Version.getInstance().getVersion();
070                    if (josmVersion != Version.JOSM_UNKNOWN_VERSION) {
071                        try {
072                            int latestVersion = Integer.parseInt(new WikiReader().
073                                    read(Main.getJOSMWebsite()+"/wiki/TestedVersion?format=txt").trim());
074                            if (latestVersion > josmVersion) {
075                                buttonTexts = new String[] {tr("Do nothing"), tr("Update JOSM"), tr("Report Bug")};
076                                buttonIcons = new String[] {"cancel", "download", "bug"};
077                                defaultButtonIdx = 2;
078                                message = tr("An unexpected exception occurred. This is always a coding error.<br><br>" +
079                                        "However, you are running an old version of JOSM ({0}),<br>" +
080                                        "instead of using the current tested version (<b>{1}</b>).<br><br>"+
081                                        "<b>Please update JOSM</b> before considering to file a bug report.",
082                                        String.valueOf(josmVersion), String.valueOf(latestVersion));
083                            }
084                        } catch (IOException | NumberFormatException e) {
085                            Main.warn("Unable to detect latest version of JOSM: "+e.getMessage());
086                        }
087                    }
088                    // Show dialog
089                    ExtendedDialog ed = new ExtendedDialog(Main.parent, tr("Unexpected Exception"), buttonTexts);
090                    ed.setButtonIcons(buttonIcons);
091                    ed.setIcon(JOptionPane.ERROR_MESSAGE);
092                    ed.setCancelButton(1);
093                    ed.setDefaultButton(defaultButtonIdx);
094                    JPanel pnl = new JPanel(new GridBagLayout());
095                    pnl.add(new JLabel("<html>" + message + "</html>"), GBC.eol());
096                    JCheckBox cbSuppress = null;
097                    if (exceptionCounter > 1) {
098                        cbSuppress = new JCheckBox(tr("Suppress further error dialogs for this session."));
099                        pnl.add(cbSuppress, GBC.eol());
100                    }
101                    ed.setContent(pnl);
102                    ed.setFocusOnDefaultButton(true);
103                    ed.showDialog();
104                    if (cbSuppress != null && cbSuppress.isSelected()) {
105                        suppressExceptionDialogs = true;
106                    }
107                    if (ed.getValue() <= 1) {
108                        // "Do nothing"
109                        return;
110                    } else if (ed.getValue() < buttonTexts.length) {
111                        // "Update JOSM"
112                        try {
113                            Main.platform.openUrl(Main.getJOSMWebsite());
114                        } catch (IOException e) {
115                            Main.warn("Unable to access JOSM website: "+e.getMessage());
116                        }
117                    } else {
118                        // "Report bug"
119                        askForBugReport(e);
120                    }
121                } else {
122                    // Ask for restart to install new plugin
123                    PluginPreference.notifyDownloadResults(
124                            Main.parent, pluginDownloadTask, !pluginDownloadTask.getDownloadedPlugins().isEmpty());
125                }
126            }
127        }
128
129        private final Throwable e;
130
131        /**
132         * Constructs a new {@code BugReporterThread}.
133         * @param t the exception
134         */
135        BugReporterThread(Throwable t) {
136            super("Bug Reporter");
137            this.e = t;
138        }
139
140        @Override
141        public void run() {
142            // Give the user a chance to deactivate the plugin which threw the exception (if it was thrown from a plugin)
143            SwingUtilities.invokeLater(new BugReporterWorker(PluginHandler.updateOrdisablePluginAfterException(e)));
144        }
145    }
146
147    @Override
148    public void uncaughtException(Thread t, Throwable e) {
149        handleException(e);
150    }
151
152    /**
153     * Handles the given throwable object
154     * @param t The throwable object
155     */
156    public void handle(Throwable t) {
157        handleException(t);
158    }
159
160    /**
161     * Handles the given exception
162     * @param e the exception
163     */
164    public static void handleException(final Throwable e) {
165        if (handlingInProgress || suppressExceptionDialogs)
166            return;                  // we do not handle secondary exceptions, this gets too messy
167        if (bugReporterThread != null && bugReporterThread.isAlive())
168            return;
169        handlingInProgress = true;
170        exceptionCounter++;
171        try {
172            Main.error(e);
173            if (Main.parent != null) {
174                if (e instanceof OutOfMemoryError) {
175                    // do not translate the string, as translation may raise an exception
176                    JOptionPane.showMessageDialog(Main.parent, "JOSM is out of memory. " +
177                            "Strange things may happen.\nPlease restart JOSM with the -Xmx###M option,\n" +
178                            "where ### is the number of MB assigned to JOSM (e.g. 256).\n" +
179                            "Currently, " + Runtime.getRuntime().maxMemory()/1024/1024 + " MB are available to JOSM.",
180                            "Error",
181                            JOptionPane.ERROR_MESSAGE
182                            );
183                    return;
184                }
185
186                bugReporterThread = new BugReporterThread(e);
187                bugReporterThread.start();
188            }
189        } finally {
190            handlingInProgress = false;
191        }
192    }
193
194    private static void askForBugReport(final Throwable e) {
195        try {
196            final int maxlen = 6000;
197            StringWriter stack = new StringWriter();
198            e.printStackTrace(new PrintWriter(stack));
199
200            String text = ShowStatusReportAction.getReportHeader() + stack.getBuffer().toString();
201            String urltext = text.replaceAll("\r", "");
202            if (urltext.length() > maxlen) {
203                urltext = urltext.substring(0, maxlen);
204                int idx = urltext.lastIndexOf('\n');
205                // cut whole line when not loosing too much
206                if (maxlen-idx < 200) {
207                    urltext = urltext.substring(0, idx+1);
208                }
209                urltext += "...<snip>...\n";
210            }
211
212            JPanel p = new JPanel(new GridBagLayout());
213            p.add(new JMultilineLabel(
214                    tr("You have encountered an error in JOSM. Before you file a bug report " +
215                            "make sure you have updated to the latest version of JOSM here:")),
216                            GBC.eol().fill(GridBagConstraints.HORIZONTAL));
217            p.add(new UrlLabel(Main.getJOSMWebsite(), 2), GBC.eop().insets(8, 0, 0, 0));
218            p.add(new JMultilineLabel(
219                    tr("You should also update your plugins. If neither of those help please " +
220                            "file a bug report in our bugtracker using this link:")),
221                            GBC.eol().fill(GridBagConstraints.HORIZONTAL));
222            p.add(getBugReportUrlLabel(urltext), GBC.eop().insets(8, 0, 0, 0));
223            p.add(new JMultilineLabel(
224                    tr("There the error information provided below should already be " +
225                            "filled in for you. Please include information on how to reproduce " +
226                            "the error and try to supply as much detail as possible.")),
227                            GBC.eop().fill(GridBagConstraints.HORIZONTAL));
228            p.add(new JMultilineLabel(
229                    tr("Alternatively, if that does not work you can manually fill in the information " +
230                            "below at this URL:")), GBC.eol().fill(GridBagConstraints.HORIZONTAL));
231            p.add(new UrlLabel(Main.getJOSMWebsite()+"/newticket", 2), GBC.eop().insets(8, 0, 0, 0));
232
233            // Wiki formatting for manual copy-paste
234            text = "{{{\n"+text+"}}}";
235
236            if (Utils.copyToClipboard(text)) {
237                p.add(new JLabel(tr("(The text has already been copied to your clipboard.)")),
238                        GBC.eop().fill(GridBagConstraints.HORIZONTAL));
239            }
240
241            JosmTextArea info = new JosmTextArea(text, 18, 60);
242            info.setCaretPosition(0);
243            info.setEditable(false);
244            p.add(new JScrollPane(info), GBC.eop().fill());
245
246            for (Component c: p.getComponents()) {
247                if (c instanceof JMultilineLabel) {
248                    ((JMultilineLabel) c).setMaxWidth(400);
249                }
250            }
251
252            JOptionPane.showMessageDialog(Main.parent, p, tr("You have encountered a bug in JOSM"), JOptionPane.ERROR_MESSAGE);
253        } catch (Exception e1) {
254            Main.error(e1);
255        }
256    }
257
258    /**
259     * Determines if an exception is currently being handled
260     * @return {@code true} if an exception is currently being handled, {@code false} otherwise
261     */
262    public static boolean exceptionHandlingInProgress() {
263        return handlingInProgress;
264    }
265
266    /**
267     * Replies the URL to create a JOSM bug report with the given debug text
268     * @param debugText The debug text to provide us
269     * @return The URL to create a JOSM bug report with the given debug text
270     * @since 5849
271     */
272    public static URL getBugReportUrl(String debugText) {
273        try (
274            ByteArrayOutputStream out = new ByteArrayOutputStream();
275            GZIPOutputStream gzip = new GZIPOutputStream(out)
276        ) {
277            gzip.write(debugText.getBytes(StandardCharsets.UTF_8));
278            gzip.finish();
279
280            return new URL(Main.getJOSMWebsite()+"/josmticket?" +
281                    "gdata="+Base64.encode(ByteBuffer.wrap(out.toByteArray()), true));
282        } catch (IOException e) {
283            Main.error(e);
284            return null;
285        }
286    }
287
288    /**
289     * Replies the URL label to create a JOSM bug report with the given debug text
290     * @param debugText The debug text to provide us
291     * @return The URL label to create a JOSM bug report with the given debug text
292     * @since 5849
293     */
294    public static UrlLabel getBugReportUrlLabel(String debugText) {
295        URL url = getBugReportUrl(debugText);
296        if (url != null) {
297            return new UrlLabel(url.toString(), Main.getJOSMWebsite()+"/josmticket?...", 2);
298        }
299        return null;
300    }
301}