001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools.bugreport;
003
004import java.util.ArrayList;
005import java.util.LinkedList;
006import java.util.Objects;
007import java.util.concurrent.CopyOnWriteArrayList;
008import java.util.function.Predicate;
009
010import org.openstreetmap.josm.tools.Logging;
011
012/**
013 * This class handles the display of the bug report dialog.
014 * @author Michael Zangl
015 * @since 10819
016 */
017public class BugReportQueue {
018
019    /**
020     * The fallback bug report handler if none is set. Prints the stacktrace on standard error stream.
021     * @since 12770
022     */
023    public static final BugReportHandler FALLBACK_BUGREPORT_HANDLER = (e, index) -> {
024        e.printStackTrace();
025        return BugReportQueue.SuppressionMode.NONE;
026    };
027
028    private static final BugReportQueue INSTANCE = new BugReportQueue();
029
030    private final LinkedList<ReportedException> reportsToDisplay = new LinkedList<>();
031    private boolean suppressAllMessages;
032    private final ArrayList<ReportedException> suppressFor = new ArrayList<>();
033    private Thread displayThread;
034    private BugReportHandler bugReportHandler = FALLBACK_BUGREPORT_HANDLER;
035    private final CopyOnWriteArrayList<Predicate<ReportedException>> handlers = new CopyOnWriteArrayList<>();
036    private int displayedErrors;
037
038    private boolean inReportDialog;
039
040    /**
041     * Class that handles reporting a bug to the user.
042     */
043    @FunctionalInterface
044    public interface BugReportHandler {
045        /**
046         * Handle the bug report for a given exception
047         * @param e The exception to display
048         * @param exceptionCounter A counter of how many exceptions have already been worked on
049         * @return The new suppression status
050         */
051        SuppressionMode handle(ReportedException e, int exceptionCounter);
052    }
053
054    /**
055     * The suppression mode that should be used after the dialog was closed.
056     */
057    public enum SuppressionMode {
058        /**
059         * Suppress no dialogs.
060         */
061        NONE,
062        /**
063         * Suppress only the ones that are for the same error
064         */
065        SAME,
066        /**
067         * Suppress all report dialogs
068         */
069        ALL
070    }
071
072    /**
073     * Submit a new error to be displayed
074     * @param report The error to display
075     */
076    public synchronized void submit(ReportedException report) {
077        Logging.logWithStackTrace(Logging.LEVEL_ERROR, "Handled by bug report queue", report.getCause());
078        if (suppressAllMessages || suppressFor.stream().anyMatch(report::isSame)) {
079            Logging.info("User requested to skip error " + report);
080        } else if (reportsToDisplay.size() > 100 || reportsToDisplay.stream().filter(report::isSame).count() >= 10) {
081            Logging.warn("Too many errors. Dropping " + report);
082        } else {
083            reportsToDisplay.add(report);
084            if (displayThread == null) {
085                displayThread = new Thread(new BugReportDisplayRunnable(), "bug-report-display");
086                displayThread.start();
087            }
088            notifyAll();
089        }
090    }
091
092    private final class BugReportDisplayRunnable implements Runnable {
093
094        private volatile boolean running = true;
095
096        @Override
097        public void run() {
098            try {
099                while (running) {
100                    ReportedException e = getNext();
101                    handleDialogResult(e, displayFor(e));
102                }
103            } catch (InterruptedException e) {
104                displayFor(BugReport.intercept(e));
105                Thread.currentThread().interrupt();
106            }
107        }
108    }
109
110    private synchronized void handleDialogResult(ReportedException e, SuppressionMode suppress) {
111        if (suppress == SuppressionMode.ALL) {
112            suppressAllMessages = true;
113            reportsToDisplay.clear();
114        } else if (suppress == SuppressionMode.SAME) {
115            suppressFor.add(e);
116            reportsToDisplay.removeIf(e::isSame);
117        }
118        displayedErrors++;
119        inReportDialog = false;
120    }
121
122    private synchronized ReportedException getNext() throws InterruptedException {
123        while (reportsToDisplay.isEmpty()) {
124            wait();
125        }
126        inReportDialog = true;
127        return reportsToDisplay.removeFirst();
128    }
129
130    private SuppressionMode displayFor(ReportedException e) {
131        if (handlers.stream().anyMatch(p -> p.test(e))) {
132            Logging.trace("Intercepted by handler.");
133            return SuppressionMode.NONE;
134        }
135        return bugReportHandler.handle(e, getDisplayedErrors());
136    }
137
138    private synchronized int getDisplayedErrors() {
139        return displayedErrors;
140    }
141
142    /**
143     * Check if the dialog is shown. Should only be used for e.g. debugging.
144     * @return <code>true</code> if the exception handler is still showing the exception to the user.
145     */
146    public synchronized boolean exceptionHandlingInProgress() {
147        return !reportsToDisplay.isEmpty() || inReportDialog;
148    }
149
150    /**
151     * Sets the {@link BugReportHandler} for this queue.
152     * @param bugReportHandler the handler in charge of displaying the bug report. Must not be null
153     * @since 12770
154     */
155    public void setBugReportHandler(BugReportHandler bugReportHandler) {
156        this.bugReportHandler = Objects.requireNonNull(bugReportHandler, "bugReportHandler");
157    }
158
159    /**
160     * Allows you to peek or even intercept the bug reports.
161     * @param handler The handler. It can return false to stop all further handling of the exception.
162     * @since 10886
163     */
164    public void addBugReportHandler(Predicate<ReportedException> handler) {
165        handlers.add(handler);
166    }
167
168    /**
169     * Gets the global bug report queue
170     * @return The queue
171     * @since 10886
172     */
173    public static BugReportQueue getInstance() {
174        return INSTANCE;
175    }
176}