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