feat: implement undo and redo logic

This commit is contained in:
dscyrescotti
2024-06-17 01:33:10 +07:00
parent daef1670bc
commit f0b80f3171
5 changed files with 34 additions and 3 deletions

View File

@@ -70,6 +70,13 @@ final class GraphicContext: @unchecked Sendable {
}
}
previousElement = nil
case .photo(let photo):
tree.remove(photo.element, in: photo.photoBox)
withPersistence(\.backgroundContext) { [weak photo] context in
photo?.object?.element?.graphicContext = nil
try context.saveIfNeeded()
context.refreshAllObjects()
}
}
}
@@ -105,6 +112,13 @@ final class GraphicContext: @unchecked Sendable {
}
}
previousElement = nil
case .photo(let photo):
tree.insert(photo.element, in: photo.photoBox)
withPersistence(\.backgroundContext) { [weak self, weak photo] context in
photo?.object?.element?.graphicContext = self?.object
try context.saveIfNeeded()
context.refreshAllObjects()
}
}
}
}
@@ -304,7 +318,7 @@ extension GraphicContext {
// MARK: - Photo
extension GraphicContext {
func insertPhoto(at point: CGPoint, photoItem: PhotoItem) {
func insertPhoto(at point: CGPoint, photoItem: PhotoItem) -> Photo {
let size = photoItem.dimension
let origin = point
let bounds = [origin.x - size.width / 2, origin.y - size.height / 2, origin.x + size.width / 2, origin.y + size.height / 2]
@@ -331,6 +345,7 @@ extension GraphicContext {
try context.saveIfNeeded()
}
self.previousElement = .photo(photo)
return photo
}
}

View File

@@ -128,7 +128,7 @@ extension Canvas {
// MARK: - Photo
extension Canvas {
func insertPhoto(at point: CGPoint, photoItem: PhotoItem) {
func insertPhoto(at point: CGPoint, photoItem: PhotoItem) -> Photo {
graphicContext.insertPhoto(at: point, photoItem: photoItem)
}
}

View File

@@ -70,6 +70,20 @@ class History: ObservableObject {
try context.saveIfNeeded()
}
}
case .photo(let _photo):
if let url = _photo.bookmark?.getBookmarkURL() {
do {
try FileManager.default.removeItem(at: url)
} catch {
NSLog("[Memola] - \(error.localizedDescription)")
}
}
withPersistence(\.backgroundContext) { context in
if let photo = _photo.object {
context.delete(photo)
}
try context.saveIfNeeded()
}
}
}
redoStack.removeAll()

View File

@@ -9,4 +9,5 @@ import Foundation
enum HistoryEvent {
case stroke(any Stroke)
case photo(Photo)
}

View File

@@ -238,7 +238,8 @@ extension CanvasViewController {
tool.selectedPhotoItem = nil
}
let point = gesture.location(in: drawingView)
canvas.insertPhoto(at: point.muliply(by: drawingView.ratio), photoItem: photoItem)
let photo = canvas.insertPhoto(at: point.muliply(by: drawingView.ratio), photoItem: photoItem)
history.addUndo(.photo(photo))
drawingView.draw()
}
}