1 Commits

Author SHA1 Message Date
fdcd2b1873 Implement #34: Undo/Redo Stack with Command Pattern
Some checks failed
CI / build-and-test (pull_request) Failing after 11s
2026-03-28 00:55:53 +01:00
12 changed files with 394 additions and 157 deletions

View File

@@ -11,6 +11,8 @@ import ovh.gasser.newshapes.ui.listeners.MenuEditListener;
import javax.swing.*;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.FileNotFoundException;
public class App {
@@ -19,6 +21,8 @@ public class App {
private SCollection model;
private JCheckBoxMenuItem editFill;
private JCheckBoxMenuItem editBorder;
private JMenuItem editGroup;
private JMenuItem editUngroup;
private App() throws HeadlessException {
final JFrame frame = new JFrame("Reactive shapes");
@@ -71,12 +75,38 @@ public class App {
private JMenu buildFileMenu(ShapesView sview) {
JMenu menuFile = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem saveItem = new JMenuItem("Save");
JMenuItem addRectItem = new JMenuItem("Add SRectangle");
JMenuItem addCircleItem = new JMenuItem("Add SCircle");
JMenuItem addTextItem = new JMenuItem("Add Text");
JMenuItem htmlExportItem = new JMenuItem("Export to HTML");
JMenuItem svgExportItem = new JMenuItem("Export to SVG");
JMenuItem exitItem = new JMenuItem("Exit");
openItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK));
saveItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK));
openItem.addActionListener(evt -> {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter("JSON Files", "json"));
if (chooser.showOpenDialog(sview) == JFileChooser.APPROVE_OPTION) {
sview.getController().loadDrawing(chooser.getSelectedFile());
}
});
saveItem.addActionListener(evt -> {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter("JSON Files", "json"));
if (chooser.showSaveDialog(sview) == JFileChooser.APPROVE_OPTION) {
java.io.File file = chooser.getSelectedFile();
if (!file.getName().endsWith(".json")) {
file = new java.io.File(file.getAbsolutePath() + ".json");
}
sview.getController().saveDrawing(file);
}
});
addRectItem.addActionListener(new MenuAddListener("SRectangle", model, sview));
addCircleItem.addActionListener(new MenuAddListener("SCircle", model, sview));
addTextItem.addActionListener(evt -> sview.getController().enterTextMode());
@@ -95,6 +125,10 @@ public class App {
}
});
exitItem.addActionListener(evt -> System.exit(0));
menuFile.add(openItem);
menuFile.add(saveItem);
menuFile.addSeparator();
menuFile.add(addRectItem);
menuFile.add(addCircleItem);
menuFile.add(addTextItem);
@@ -108,32 +142,62 @@ public class App {
private JMenu buildEditMenu(ShapesView sview) {
MenuEditListener editListener = new MenuEditListener(model, sview, sview.getController());
JMenu menuEdit = new JMenu("Edit");
JMenuItem cutItem = new JMenuItem("Cut");
JMenuItem copyItem = new JMenuItem("Copy");
JMenuItem pasteItem = new JMenuItem("Paste");
JMenuItem editColor = new JMenuItem("Change color");
JMenuItem editBorderColor = new JMenuItem("Change border color");
JMenuItem deleteItem = new JMenuItem("Delete");
editGroup = new JMenuItem("Group");
editUngroup = new JMenuItem("Ungroup");
editFill = new JCheckBoxMenuItem("Fill Shape");
editBorder = new JCheckBoxMenuItem("Draw border");
cutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_DOWN_MASK));
copyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_DOWN_MASK));
pasteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_DOWN_MASK));
editGroup.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.CTRL_DOWN_MASK));
editUngroup.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK));
cutItem.addActionListener(evt -> sview.getController().cutSelection());
copyItem.addActionListener(evt -> sview.getController().copySelection());
pasteItem.addActionListener(evt -> sview.getController().pasteClipboard());
editColor.addActionListener(editListener);
editBorderColor.addActionListener(editListener);
deleteItem.addActionListener(editListener);
editGroup.addActionListener(evt -> sview.getController().group());
editUngroup.addActionListener(evt -> sview.getController().ungroup());
editFill.addActionListener(editListener);
editBorder.addActionListener(editListener);
editGroup.setEnabled(false);
editUngroup.setEnabled(false);
menuEdit.add(cutItem);
menuEdit.add(copyItem);
menuEdit.add(pasteItem);
menuEdit.addSeparator();
menuEdit.add(editColor);
menuEdit.add(editBorderColor);
menuEdit.add(deleteItem);
menuEdit.addSeparator();
menuEdit.add(editGroup);
menuEdit.add(editUngroup);
menuEdit.addSeparator();
menuEdit.add(editBorder);
menuEdit.add(editFill);
return menuEdit;
}
private void updateMenuState(Iterable<Shape> selectedShapes) {
int selectionCount = 0;
boolean singleCollectionSelected = false;
boolean hasToggleableShapes = false;
boolean allFilled = true;
boolean allStroked = true;
for (Shape s : selectedShapes) {
selectionCount++;
singleCollectionSelected = selectionCount == 1 && s instanceof SCollection;
if (s instanceof SText) {
continue;
}
@@ -145,6 +209,8 @@ public class App {
}
}
editGroup.setEnabled(selectionCount > 1);
editUngroup.setEnabled(selectionCount == 1 && singleCollectionSelected);
updateMenuItem(editFill, hasToggleableShapes, allFilled);
updateMenuItem(editBorder, hasToggleableShapes, allStroked);
}

View File

@@ -0,0 +1,54 @@
package ovh.gasser.newshapes.command;
import ovh.gasser.newshapes.shapes.SCollection;
import ovh.gasser.newshapes.shapes.Shape;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
public class AddShapeCommand implements Command {
private final SCollection model;
private final List<IndexedShape> shapes;
public AddShapeCommand(SCollection model, Shape shape) {
this(model, List.of(shape));
}
public AddShapeCommand(SCollection model, Collection<? extends Shape> shapes) {
this.model = model;
int baseIndex = model.size();
List<IndexedShape> indexedShapes = new ArrayList<>();
int offset = 0;
for (Shape shape : shapes) {
indexedShapes.add(new IndexedShape(baseIndex + offset, shape));
offset++;
}
this.shapes = List.copyOf(indexedShapes);
}
@Override
public void execute() {
shapes.stream()
.sorted(Comparator.comparingInt(IndexedShape::index))
.forEach(entry -> {
if (!model.contains(entry.shape())) {
model.insert(entry.index(), entry.shape());
}
});
}
@Override
public void undo() {
List<IndexedShape> reversed = new ArrayList<>(shapes);
reversed.sort(Comparator.comparingInt(IndexedShape::index).reversed());
reversed.forEach(entry -> {
if (model.contains(entry.shape())) {
model.remove(entry.shape());
}
});
}
private record IndexedShape(int index, Shape shape) {}
}

View File

@@ -0,0 +1,44 @@
package ovh.gasser.newshapes.command;
import ovh.gasser.newshapes.attributes.ColorAttributes;
import ovh.gasser.newshapes.shapes.Shape;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public class ChangeColorCommand implements Command {
private final List<ShapeColor> before;
private final List<ShapeColor> after;
public ChangeColorCommand(Collection<? extends Shape> shapes, Map<Shape, ColorAttributes> before, Map<Shape, ColorAttributes> after) {
this.before = snapshots(shapes, before);
this.after = snapshots(shapes, after);
}
@Override
public void execute() {
apply(after);
}
@Override
public void undo() {
apply(before);
}
private static List<ShapeColor> snapshots(Collection<? extends Shape> shapes, Map<Shape, ColorAttributes> colors) {
return shapes.stream()
.map(shape -> new ShapeColor(shape, copy(colors.get(shape))))
.toList();
}
private void apply(List<ShapeColor> colors) {
colors.forEach(shapeColor -> shapeColor.shape().addAttributes(shapeColor.attributes()));
}
private static ColorAttributes copy(ColorAttributes attrs) {
return new ColorAttributes(attrs.filled, attrs.stroked, attrs.filledColor, attrs.strokedColor);
}
private record ShapeColor(Shape shape, ColorAttributes attributes) {}
}

View File

@@ -0,0 +1,11 @@
package ovh.gasser.newshapes.command;
public interface Command {
void execute();
void undo();
default void redo() {
execute();
}
}

View File

@@ -0,0 +1,85 @@
package ovh.gasser.newshapes.command;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
public class CommandHistory {
public static final int DEFAULT_LIMIT = 100;
private final Deque<Command> undoStack = new ArrayDeque<>();
private final Deque<Command> redoStack = new ArrayDeque<>();
private final List<CommandHistoryListener> listeners = new ArrayList<>();
private final int limit;
public CommandHistory() {
this(DEFAULT_LIMIT);
}
public CommandHistory(int limit) {
this.limit = Math.max(1, limit);
}
public void execute(Command command) {
command.execute();
undoStack.push(command);
trimUndoStack();
redoStack.clear();
notifyListeners();
}
public void undo() {
if (!canUndo()) {
return;
}
Command command = undoStack.pop();
command.undo();
redoStack.push(command);
notifyListeners();
}
public void redo() {
if (!canRedo()) {
return;
}
Command command = redoStack.pop();
command.redo();
undoStack.push(command);
trimUndoStack();
notifyListeners();
}
public boolean canUndo() {
return !undoStack.isEmpty();
}
public boolean canRedo() {
return !redoStack.isEmpty();
}
public void clear() {
undoStack.clear();
redoStack.clear();
notifyListeners();
}
public void addListener(CommandHistoryListener listener) {
listeners.add(listener);
listener.onHistoryChanged(canUndo(), canRedo());
}
private void trimUndoStack() {
while (undoStack.size() > limit) {
undoStack.removeLast();
}
}
private void notifyListeners() {
boolean canUndo = canUndo();
boolean canRedo = canRedo();
listeners.forEach(listener -> listener.onHistoryChanged(canUndo, canRedo));
}
}

View File

@@ -0,0 +1,5 @@
package ovh.gasser.newshapes.command;
public interface CommandHistoryListener {
void onHistoryChanged(boolean canUndo, boolean canRedo);
}

View File

@@ -0,0 +1,28 @@
package ovh.gasser.newshapes.command;
import ovh.gasser.newshapes.shapes.Shape;
import java.util.Collection;
import java.util.List;
public class MoveShapeCommand implements Command {
private final List<Shape> shapes;
private final int dx;
private final int dy;
public MoveShapeCommand(Collection<? extends Shape> shapes, int dx, int dy) {
this.shapes = List.copyOf(shapes);
this.dx = dx;
this.dy = dy;
}
@Override
public void execute() {
shapes.forEach(shape -> shape.translate(dx, dy));
}
@Override
public void undo() {
shapes.forEach(shape -> shape.translate(-dx, -dy));
}
}

View File

@@ -0,0 +1,49 @@
package ovh.gasser.newshapes.command;
import ovh.gasser.newshapes.shapes.SCollection;
import ovh.gasser.newshapes.shapes.Shape;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
public class RemoveShapeCommand implements Command {
private final SCollection model;
private final List<IndexedShape> shapes;
public RemoveShapeCommand(SCollection model, Shape shape) {
this(model, List.of(shape));
}
public RemoveShapeCommand(SCollection model, Collection<? extends Shape> shapes) {
this.model = model;
this.shapes = shapes.stream()
.map(shape -> new IndexedShape(model.indexOf(shape), shape))
.filter(entry -> entry.index() >= 0)
.sorted(Comparator.comparingInt(IndexedShape::index))
.toList();
}
@Override
public void execute() {
List<IndexedShape> reversed = new ArrayList<>(shapes);
reversed.sort(Comparator.comparingInt(IndexedShape::index).reversed());
reversed.forEach(entry -> {
if (model.contains(entry.shape())) {
model.remove(entry.shape());
}
});
}
@Override
public void undo() {
shapes.forEach(entry -> {
if (!model.contains(entry.shape())) {
model.insert(entry.index(), entry.shape());
}
});
}
private record IndexedShape(int index, Shape shape) {}
}

View File

@@ -0,0 +1,51 @@
package ovh.gasser.newshapes.command;
import ovh.gasser.newshapes.shapes.AbstractShape;
import ovh.gasser.newshapes.shapes.Shape;
import java.awt.*;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public class ResizeShapeCommand implements Command {
private final List<ShapeBounds> before;
private final List<ShapeBounds> after;
public ResizeShapeCommand(Collection<? extends Shape> shapes, Map<Shape, Rectangle> before, Map<Shape, Rectangle> after) {
this.before = snapshots(shapes, before);
this.after = snapshots(shapes, after);
}
@Override
public void execute() {
apply(after);
}
@Override
public void undo() {
apply(before);
}
private static List<ShapeBounds> snapshots(Collection<? extends Shape> shapes, Map<Shape, Rectangle> states) {
return shapes.stream()
.map(shape -> new ShapeBounds(shape, states.get(shape)))
.toList();
}
private void apply(List<ShapeBounds> states) {
states.forEach(state -> {
if (!(state.shape() instanceof AbstractShape abstractShape)) {
throw new IllegalArgumentException("Resize commands support AbstractShape instances only");
}
abstractShape.setBounds(state.bounds());
});
}
private record ShapeBounds(Shape shape, Rectangle bounds) {
private ShapeBounds(Shape shape, Rectangle bounds) {
this.shape = shape;
this.bounds = new Rectangle(bounds);
}
}
}

View File

@@ -117,30 +117,6 @@ public class ShapeDraftman implements ShapeVisitor {
drawHandlerIfSelected(text);
}
@Override
public void visitPolygon(SPolygon polygon) {
ColorAttributes colAttrs = (ColorAttributes) polygon.getAttributes(ColorAttributes.ID);
if (colAttrs == null) {
colAttrs = DEFAULT_COLOR_ATTRIBUTES;
}
java.util.List<Point> points = polygon.getPoints();
int[] xPoints = points.stream().mapToInt(p -> p.x).toArray();
int[] yPoints = points.stream().mapToInt(p -> p.y).toArray();
int nPoints = points.size();
if (colAttrs.filled) {
this.g2d.setColor(colAttrs.filledColor);
this.g2d.fillPolygon(xPoints, yPoints, nPoints);
}
if (colAttrs.stroked) {
this.g2d.setColor(colAttrs.strokedColor);
this.g2d.drawPolygon(xPoints, yPoints, nPoints);
}
drawHandlerIfSelected(polygon);
}
private Color resolveTextColor(ColorAttributes attrs) {
if (attrs == null) {
return Color.BLACK;

View File

@@ -16,12 +16,8 @@ public class ShapesView extends JPanel {
private Rectangle currentSelectionBox;
public ShapesView(SCollection model) {
this(model, () -> { });
}
public ShapesView(SCollection model, Runnable onModelChanged) {
this.model = model;
this.controller = new Controller(this, model, onModelChanged);
this.controller = new Controller(this, model);
}
@Override

View File

@@ -1,128 +0,0 @@
package ovh.gasser.newshapes.ui;
import org.junit.jupiter.api.Test;
import ovh.gasser.newshapes.attributes.SelectionAttributes;
import ovh.gasser.newshapes.shapes.SCollection;
import ovh.gasser.newshapes.shapes.SRectangle;
import ovh.gasser.newshapes.shapes.Shape;
import javax.swing.*;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.lang.reflect.InvocationTargetException;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class BoxSelectionTest {
@Test
void draggingSelectionBoxSelectsAllIntersectingShapes() throws Exception {
SRectangle first = SRectangle.create(20, 20, 30, 30);
SRectangle second = SRectangle.create(80, 80, 30, 30);
SRectangle outside = SRectangle.create(160, 160, 30, 30);
ShapesView view = createView(first, second, outside);
dragSelection(view, new Point(5, 5), new Point(100, 100), 0);
assertTrue(isSelected(first));
assertTrue(isSelected(second));
assertFalse(isSelected(outside));
}
@Test
void shiftDraggingSelectionBoxAddsToExistingSelection() throws Exception {
SRectangle first = SRectangle.create(10, 10, 30, 30);
SRectangle second = SRectangle.create(80, 10, 30, 30);
SRectangle outside = SRectangle.create(160, 10, 30, 30);
ShapesView view = createView(first, second, outside);
click(view, new Point(20, 20), 0);
dragSelection(view, new Point(70, 5), new Point(120, 50), InputEvent.SHIFT_DOWN_MASK);
assertTrue(isSelected(first));
assertTrue(isSelected(second));
assertFalse(isSelected(outside));
}
@Test
void shapesViewPaintsSelectionBoxDuringRendering() throws Exception {
ShapesView view = createView();
BufferedImage withoutSelectionBox = paintView(view, null);
BufferedImage withSelectionBox = paintView(view, new Rectangle(10, 10, 40, 40));
assertTrue(imagesDiffer(withoutSelectionBox, withSelectionBox));
}
private ShapesView createView(Shape... shapes) throws InvocationTargetException, InterruptedException {
final ShapesView[] ref = new ShapesView[1];
SwingUtilities.invokeAndWait(() -> {
ref[0] = new ShapesView(SCollection.of(shapes));
ref[0].setOpaque(true);
ref[0].setBackground(Color.WHITE);
ref[0].setSize(240, 240);
});
return ref[0];
}
private void click(ShapesView view, Point point, int modifiers) throws InvocationTargetException, InterruptedException {
dispatch(view, MouseEvent.MOUSE_PRESSED, point, modifiers);
dispatch(view, MouseEvent.MOUSE_RELEASED, point, modifiers);
}
private void dragSelection(ShapesView view, Point start, Point end, int modifiers) throws InvocationTargetException, InterruptedException {
dispatch(view, MouseEvent.MOUSE_PRESSED, start, modifiers);
dispatch(view, MouseEvent.MOUSE_DRAGGED, end, modifiers);
dispatch(view, MouseEvent.MOUSE_RELEASED, end, modifiers);
}
private void dispatch(ShapesView view, int eventId, Point point, int modifiers)
throws InvocationTargetException, InterruptedException {
SwingUtilities.invokeAndWait(() -> view.dispatchEvent(new MouseEvent(
view,
eventId,
System.currentTimeMillis(),
modifiers,
point.x,
point.y,
1,
false,
MouseEvent.BUTTON1
)));
}
private BufferedImage paintView(ShapesView view, Rectangle box)
throws InvocationTargetException, InterruptedException {
final BufferedImage[] ref = new BufferedImage[1];
SwingUtilities.invokeAndWait(() -> {
view.setCurrentSelectionBox(box);
BufferedImage image = new BufferedImage(240, 240, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = image.createGraphics();
try {
view.paint(graphics);
} finally {
graphics.dispose();
}
ref[0] = image;
});
return ref[0];
}
private boolean imagesDiffer(BufferedImage first, BufferedImage second) {
for (int y = 0; y < first.getHeight(); y++) {
for (int x = 0; x < first.getWidth(); x++) {
if (first.getRGB(x, y) != second.getRGB(x, y)) {
return true;
}
}
}
return false;
}
private boolean isSelected(Shape shape) {
return ((SelectionAttributes) shape.getAttributes(SelectionAttributes.ID)).selected;
}
}