001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.progress;
003
004import java.util.ArrayList;
005import java.util.List;
006
007import org.openstreetmap.josm.gui.progress.ProgressMonitor.CancelListener;
008
009/**
010 * A handler that notifies all listeners that a given operation was canceled.
011 */
012public class CancelHandler {
013
014    private boolean isCanceled;
015    private final List<CancelListener> listeners = new ArrayList<>();
016
017    /**
018     * Cancels the operation. This call is ignored if the operation was already canceled.
019     */
020    public synchronized void cancel() {
021        if (!isCanceled) {
022            isCanceled = true;
023            for (CancelListener listener:listeners) {
024                listener.operationCanceled();
025            }
026        }
027    }
028
029    /**
030     * Checks if the operation was canceled
031     * @return <code>true</code> if {@link #cancel()} was called.
032     */
033    public synchronized boolean isCanceled() {
034        return isCanceled;
035    }
036
037    /**
038     * Adds a new cancel listener
039     * @param listener The listener to add
040     */
041    public synchronized void addCancelListener(CancelListener listener) {
042        listeners.add(listener);
043    }
044
045    /**
046     * Removes a cancel listener
047     * @param listener The listener to remove
048     */
049    public synchronized void removeCancelListener(CancelListener listener) {
050        listeners.remove(listener);
051    }
052
053}