This repository has been archived on 2022-02-11. You can view files and clone it, but cannot push or open issues or pull requests.
undo-redo/src/main/java/dev/kske/undoredo/ChangeManager.java

105 lines
2.0 KiB
Java

package dev.kske.undoredo;
import java.util.*;
/**
* A change manager keeps track of subsequent changes and allows un- and redoing them. A specific
* change can be marked using {@link #mark()} to keep track of a saved state in the application that
* uses the manager.
*
* @param <C> the change type to store in this change manager
* @author Maximilian K&auml;fer
* @since 0.0.1
*/
public final class ChangeManager<C extends Change> {
private final List<C> changes = new LinkedList<>();
private int index;
private int markedIndex;
/**
* Applies the given change and appends it to the change list.
*
* @param change the change to add
* @since 0.0.1
*/
public void addChange(C change) {
change.apply();
changes.add(change);
}
/**
* Undoes the current change.
*
* @return whether an action was performed
* @since 0.1.0
*/
public boolean undo() {
if (isUndoAvailable()) {
changes.get(index).invert().apply();
--index;
return true;
}
return false;
}
/**
* Applies the change that was undone before.
*
* @return whether an action was performed
* @since 0.0.1
*/
public boolean redo() {
if (isRedoAvailable()) {
changes.get(index + 1).apply();
++index;
return true;
}
return false;
}
/**
* Marks the current change.
*
* @since 0.0.1
*/
public void mark() {
markedIndex = index;
}
/**
* @return whether the current change is marked
* @since 0.0.1
*/
public boolean isAtMarkedIndex() {
return markedIndex == index;
}
/**
* @return whether a change is present that can be undone
* @since 0.0.1
*/
public boolean isUndoAvailable() {
return index > 0;
}
/**
* @return whether a change is present that can be redone
* @since 0.0.1
*/
public boolean isRedoAvailable() {
return index < changes.size() - 1;
}
/**
* Provides an unmodifiable view of the changes stored in this change manager.
*
* @return all stored changes
* @since 0.0.1
*/
public List<C> getChanges() {
return Collections.unmodifiableList(changes);
}
}