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(Main.parent, pluginDownloadTask); 130 } 131 } 132 }); 133 } 134 } 135 136 @Override 137 public void uncaughtException(Thread t, Throwable e) { 138 handleException(e); 139 } 140 141 /** 142 * Handles the given throwable object 143 * @param t The throwable object 144 */ 145 public void handle(Throwable t) { 146 handleException(t); 147 } 148 149 /** 150 * Handles the given exception 151 * @param e the exception 152 */ 153 public static void handleException(final Throwable e) { 154 if (handlingInProgress || suppressExceptionDialogs) 155 return; // we do not handle secondary exceptions, this gets too messy 156 if (bugReporterThread != null && bugReporterThread.isAlive()) 157 return; 158 handlingInProgress = true; 159 exceptionCounter++; 160 try { 161 Main.error(e); 162 if (Main.parent != null) { 163 if (e instanceof OutOfMemoryError) { 164 // do not translate the string, as translation may raise an exception 165 JOptionPane.showMessageDialog(Main.parent, "JOSM is out of memory. " + 166 "Strange things may happen.\nPlease restart JOSM with the -Xmx###M option,\n" + 167 "where ### is the number of MB assigned to JOSM (e.g. 256).\n" + 168 "Currently, " + Runtime.getRuntime().maxMemory()/1024/1024 + " MB are available to JOSM.", 169 "Error", 170 JOptionPane.ERROR_MESSAGE 171 ); 172 return; 173 } 174 175 bugReporterThread = new BugReporterThread(e); 176 bugReporterThread.start(); 177 } 178 } finally { 179 handlingInProgress = false; 180 } 181 } 182 183 private static void askForBugReport(final Throwable e) { 184 try { 185 final int maxlen = 6000; 186 StringWriter stack = new StringWriter(); 187 e.printStackTrace(new PrintWriter(stack)); 188 189 String text = ShowStatusReportAction.getReportHeader() + stack.getBuffer().toString(); 190 String urltext = text.replaceAll("\r",""); 191 if (urltext.length() > maxlen) { 192 urltext = urltext.substring(0,maxlen); 193 int idx = urltext.lastIndexOf('\n'); 194 // cut whole line when not loosing too much 195 if (maxlen-idx < 200) { 196 urltext = urltext.substring(0,idx+1); 197 } 198 urltext += "...<snip>...\n"; 199 } 200 201 JPanel p = new JPanel(new GridBagLayout()); 202 p.add(new JMultilineLabel( 203 tr("You have encountered an error in JOSM. Before you file a bug report " + 204 "make sure you have updated to the latest version of JOSM here:")), 205 GBC.eol().fill(GridBagConstraints.HORIZONTAL)); 206 p.add(new UrlLabel(Main.getJOSMWebsite(),2), GBC.eop().insets(8,0,0,0)); 207 p.add(new JMultilineLabel( 208 tr("You should also update your plugins. If neither of those help please " + 209 "file a bug report in our bugtracker using this link:")), 210 GBC.eol().fill(GridBagConstraints.HORIZONTAL)); 211 p.add(getBugReportUrlLabel(urltext), GBC.eop().insets(8,0,0,0)); 212 p.add(new JMultilineLabel( 213 tr("There the error information provided below should already be " + 214 "filled in for you. Please include information on how to reproduce " + 215 "the error and try to supply as much detail as possible.")), 216 GBC.eop().fill(GridBagConstraints.HORIZONTAL)); 217 p.add(new JMultilineLabel( 218 tr("Alternatively, if that does not work you can manually fill in the information " + 219 "below at this URL:")), GBC.eol().fill(GridBagConstraints.HORIZONTAL)); 220 p.add(new UrlLabel(Main.getJOSMWebsite()+"/newticket",2), GBC.eop().insets(8,0,0,0)); 221 222 // Wiki formatting for manual copy-paste 223 text = "{{{\n"+text+"}}}"; 224 225 if (Utils.copyToClipboard(text)) { 226 p.add(new JLabel(tr("(The text has already been copied to your clipboard.)")), 227 GBC.eop().fill(GridBagConstraints.HORIZONTAL)); 228 } 229 230 JosmTextArea info = new JosmTextArea(text, 18, 60); 231 info.setCaretPosition(0); 232 info.setEditable(false); 233 p.add(new JScrollPane(info), GBC.eop().fill()); 234 235 for (Component c: p.getComponents()) { 236 if (c instanceof JMultilineLabel) { 237 ((JMultilineLabel)c).setMaxWidth(400); 238 } 239 } 240 241 JOptionPane.showMessageDialog(Main.parent, p, tr("You have encountered a bug in JOSM"), JOptionPane.ERROR_MESSAGE); 242 } catch (Exception e1) { 243 Main.error(e1); 244 } 245 } 246 247 /** 248 * Determines if an exception is currently being handled 249 * @return {@code true} if an exception is currently being handled, {@code false} otherwise 250 */ 251 public static boolean exceptionHandlingInProgress() { 252 return handlingInProgress; 253 } 254 255 /** 256 * Replies the URL to create a JOSM bug report with the given debug text 257 * @param debugText The debug text to provide us 258 * @return The URL to create a JOSM bug report with the given debug text 259 * @since 5849 260 */ 261 public static URL getBugReportUrl(String debugText) { 262 try ( 263 ByteArrayOutputStream out = new ByteArrayOutputStream(); 264 GZIPOutputStream gzip = new GZIPOutputStream(out) 265 ) { 266 gzip.write(debugText.getBytes(StandardCharsets.UTF_8)); 267 gzip.finish(); 268 269 return new URL(Main.getJOSMWebsite()+"/josmticket?" + 270 "gdata="+Base64.encode(ByteBuffer.wrap(out.toByteArray()), true)); 271 } catch (IOException e) { 272 Main.error(e); 273 return null; 274 } 275 } 276 277 /** 278 * Replies the URL label to create a JOSM bug report with the given debug text 279 * @param debugText The debug text to provide us 280 * @return The URL label to create a JOSM bug report with the given debug text 281 * @since 5849 282 */ 283 public static final UrlLabel getBugReportUrlLabel(String debugText) { 284 URL url = getBugReportUrl(debugText); 285 if (url != null) { 286 return new UrlLabel(url.toString(), Main.getJOSMWebsite()+"/josmticket?...", 2); 287 } 288 return null; 289 } 290}