feat: reduce memory footprint

This commit is contained in:
dscyrescotti
2024-05-08 22:51:20 +07:00
parent 8fb98f4f76
commit 1f9c176eb0
17 changed files with 370 additions and 253 deletions
+32 -43
View File
@@ -7,45 +7,28 @@
import Combine
import MetalKit
import CoreData
import Foundation
protocol GraphicContextDelegate: AnyObject {
var didUpdate: PassthroughSubject<Void, Never> { get set }
}
@objc(GraphicContext)
class GraphicContext: NSManagedObject {
@NSManaged var id: UUID
@NSManaged var canvas: Canvas
@NSManaged var strokes: NSMutableOrderedSet
class GraphicContext: Codable {
var strokes: [Stroke] = []
var currentStroke: Stroke?
var previousStroke: Stroke?
var currentPoint: CGPoint?
var renderType: RenderType = .finished
var vertices: [ViewPortVertex] = []
var vertexCount: Int = 4
var vertexBuffer: MTLBuffer?
weak var delegate: GraphicContextDelegate?
init() {
override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {
super.init(entity: entity, insertInto: context)
setViewPortVertices()
}
enum CodingKeys: CodingKey {
case strokes
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.strokes = try container.decode([Stroke].self, forKey: .strokes)
setViewPortVertices()
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.strokes, forKey: .strokes)
}
func setViewPortVertices() {
vertexBuffer = nil
vertices = [
@@ -57,19 +40,17 @@ class GraphicContext: Codable {
}
func undoGraphic() {
guard !strokes.isEmpty else { return }
strokes.removeLast()
guard let stroke = strokes.lastObject as? Stroke else { return }
strokes.remove(stroke)
previousStroke = nil
delegate?.didUpdate.send()
}
func redoGraphic(for event: HistoryEvent) {
switch event {
case .stroke(let stroke):
strokes.append(stroke)
strokes.add(stroke)
previousStroke = nil
}
delegate?.didUpdate.send()
}
}
@@ -91,12 +72,15 @@ extension GraphicContext: Drawable {
extension GraphicContext {
func beginStroke(at point: CGPoint, pen: Pen) -> Stroke {
let stroke = Stroke(
color: pen.color,
style: pen.style,
thickness: pen.thickness
)
strokes.append(stroke)
let stroke = Stroke(context: Persistence.shared.viewContext)
stroke.id = UUID()
stroke.color = pen.color
stroke.style = pen.strokeStyle.rawValue
stroke.thickness = pen.thickness
stroke.createdAt = .now
stroke.strokeQuads = []
stroke.graphicContext = self
strokes.add(stroke)
currentStroke = stroke
currentPoint = point
currentStroke?.begin(at: point)
@@ -105,23 +89,28 @@ extension GraphicContext {
func appendStroke(with point: CGPoint) {
guard let currentStroke else { return }
guard let currentPoint, point.distance(to: currentPoint) > currentStroke.thickness * currentStroke.style.stepRate else { return }
guard let currentPoint, point.distance(to: currentPoint) > currentStroke.thickness * currentStroke.penStyle.anyPenStyle.stepRate else { return }
currentStroke.append(to: point)
self.currentPoint = point
}
func endStroke(at point: CGPoint) {
guard currentPoint != nil else { return }
currentStroke?.finish(at: point)
guard currentPoint != nil, let currentStroke else { return }
currentStroke.finish(at: point)
currentStroke.saveQuads()
do {
try Persistence.shared.viewContext.save()
} catch {
NSLog("[Memola] - \(error.localizedDescription)")
}
previousStroke = currentStroke
currentStroke = nil
self.currentStroke = nil
self.currentPoint = nil
delegate?.didUpdate.send()
}
func cancelStroke() {
if !strokes.isEmpty {
strokes.removeLast()
if let stroke = strokes.lastObject {
strokes.remove(stroke)
}
currentStroke = nil
currentPoint = nil
+17 -66
View File
@@ -10,92 +10,43 @@ import CoreData
import MetalKit
import Foundation
final class Canvas: NSObject, ObservableObject, Identifiable, Codable, GraphicContextDelegate {
let size: CGSize
@objc(Canvas)
class Canvas: NSManagedObject, Identifiable {
@NSManaged var id: UUID
@NSManaged var width: CGFloat
@NSManaged var height: CGFloat
@NSManaged var memo: Memo
@NSManaged var graphicContext: GraphicContext
let gridContext = GridContext()
let viewPortContext = ViewPortContext()
let maximumZoomScale: CGFloat = 25
let minimumZoomScale: CGFloat = 3.1
var transform: simd_float4x4 = .init()
var uniformsBuffer: MTLBuffer?
let gridContext = GridContext()
var graphicContext = GraphicContext()
let viewPortContext = ViewPortContext()
var clipBounds: CGRect = .zero
var zoomScale: CGFloat = .zero
weak var memo: Memo?
var graphicLoader: (() throws -> GraphicContext)?
var uniformsBuffer: MTLBuffer?
@Published var state: State = .initial
lazy var didUpdate = PassthroughSubject<Void, Never>()
var size: CGSize { CGSize(width: width, height: height) }
var hasValidStroke: Bool {
if let currentStroke = graphicContext.currentStroke {
return Date.now.timeIntervalSince(currentStroke.createdAt) * 1000 > 80
}
return false
}
init(size: CGSize = .init(width: 4_000, height: 4_000)) {
self.size = size
}
enum CodingKeys: CodingKey {
case size
case graphicContext
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.size = try container.decode(CGSize.self, forKey: .size)
self.graphicLoader = { try container.decode(GraphicContext.self, forKey: .graphicContext) }
}
}
// MARK: - Actions
extension Canvas {
func load() {
guard let graphicLoader else { return }
Task(priority: .high) { [unowned self, graphicLoader] in
await MainActor.run {
self.state = .loading
}
do {
let graphicContext = try graphicLoader()
graphicContext.delegate = self
await MainActor.run {
self.graphicContext = graphicContext
self.state = .loaded
}
} catch {
NSLog("[Memola] - \(error.localizedDescription)")
await MainActor.run {
self.state = .failed
}
}
state = .loading
graphicContext.strokes.forEach {
($0 as? Stroke)?.loadVertices()
}
}
func save(on managedObjectContext: NSManagedObjectContext) async {
guard let memo else { return }
do {
memo.data = try JSONEncoder().encode(self)
memo.updatedAt = Date()
try managedObjectContext.save()
} catch {
NSLog("[Memola] - \(error.localizedDescription)")
}
}
func listen(on managedObjectContext: NSManagedObjectContext) {
// Task(priority: .utility) { [unowned self] in
// for await _ in didUpdate.throttle(for: 500, scheduler: DispatchQueue.global(qos: .utility), latest: false).values {
// await save(on: managedObjectContext)
// }
// }
state = .loaded
}
}
@@ -148,7 +99,7 @@ extension Canvas {
}
func getNewlyAddedStroke() -> Stroke? {
graphicContext.strokes.last
graphicContext.strokes.lastObject as? Stroke
}
}
+19 -29
View File
@@ -2,31 +2,27 @@
// Quad.swift
// Memola
//
// Created by Dscyre Scotti on 5/4/24.
// Created by Dscyre Scotti on 5/8/24.
//
import MetalKit
import Foundation
class Quad {
struct Quad: Codable {
var origin: CGPoint
var color: [CGFloat]
var size: CGFloat
var rotation: CGFloat
var vertices: [QuadVertex] = []
var shape: QuadShape
var vertexBuffer: MTLBuffer?
var vertexCount: Int = 0
init(origin: CGPoint, size: CGFloat, color: [CGFloat], rotation: CGFloat, shape: Shape = .rounded) {
init(origin: CGPoint, size: CGFloat, color: [CGFloat], rotation: CGFloat, shape: QuadShape = .rounded) {
self.origin = origin
self.size = size
self.color = color
self.rotation = rotation
generateVertices(shape)
self.shape = shape
}
func generateVertices(_ shape: Shape) {
func generateVertices(_ shape: QuadShape) -> [QuadVertex] {
switch shape {
case .rounded:
generateRoundedQuad()
@@ -39,9 +35,9 @@ class Quad {
}
}
func generateRoundedQuad() {
func generateRoundedQuad() -> [QuadVertex] {
let halfSize = size * 0.5
vertices = [
return [
QuadVertex(x: origin.x - halfSize, y: origin.y - halfSize, textCoord: CGPoint(x: 0, y: 0), color: color, origin: origin, rotation: rotation),
QuadVertex(x: origin.x + halfSize, y: origin.y - halfSize, textCoord: CGPoint(x: 1, y: 0), color: color, origin: origin, rotation: rotation),
QuadVertex(x: origin.x - halfSize, y: origin.y + halfSize, textCoord: CGPoint(x: 0, y: 1), color: color, origin: origin, rotation: rotation),
@@ -49,13 +45,12 @@ class Quad {
QuadVertex(x: origin.x - halfSize, y: origin.y + halfSize, textCoord: CGPoint(x: 0, y: 1), color: color, origin: origin, rotation: rotation),
QuadVertex(x: origin.x + halfSize, y: origin.y + halfSize, textCoord: CGPoint(x: 1, y: 1), color: color, origin: origin, rotation: rotation)
]
vertexCount = vertices.count
}
func generateSquaredQuad() {
func generateSquaredQuad() -> [QuadVertex] {
let vHalfSize = size * 0.5
let hHalfSize = size * 0.15
vertices = [
return [
QuadVertex(x: origin.x - hHalfSize, y: origin.y - vHalfSize, textCoord: CGPoint(x: 0, y: 0), color: color, origin: origin, rotation: rotation),
QuadVertex(x: origin.x + hHalfSize, y: origin.y - vHalfSize, textCoord: CGPoint(x: 1, y: 0), color: color, origin: origin, rotation: rotation),
QuadVertex(x: origin.x - hHalfSize, y: origin.y + vHalfSize, textCoord: CGPoint(x: 0, y: 1), color: color, origin: origin, rotation: rotation),
@@ -63,13 +58,12 @@ class Quad {
QuadVertex(x: origin.x - hHalfSize, y: origin.y + vHalfSize, textCoord: CGPoint(x: 0, y: 1), color: color, origin: origin, rotation: rotation),
QuadVertex(x: origin.x + hHalfSize, y: origin.y + vHalfSize, textCoord: CGPoint(x: 1, y: 1), color: color, origin: origin, rotation: rotation)
]
vertexCount = vertices.count
}
func generateCalligraphicQuad(vFactor: CGFloat, hFactor: CGFloat) {
func generateCalligraphicQuad(vFactor: CGFloat, hFactor: CGFloat) -> [QuadVertex] {
let vHalfSize = size * vFactor * 0.5
let hHalfSize = size * hFactor * 0.5
vertices = [
return [
QuadVertex(x: origin.x - hHalfSize, y: origin.y - vHalfSize, textCoord: CGPoint(x: 0, y: 0), color: color, origin: origin, rotation: rotation),
QuadVertex(x: origin.x + hHalfSize, y: origin.y - vHalfSize, textCoord: CGPoint(x: 1, y: 0), color: color, origin: origin, rotation: rotation),
QuadVertex(x: origin.x - hHalfSize, y: origin.y + vHalfSize, textCoord: CGPoint(x: 0, y: 1), color: color, origin: origin, rotation: rotation),
@@ -77,14 +71,13 @@ class Quad {
QuadVertex(x: origin.x - hHalfSize, y: origin.y + vHalfSize, textCoord: CGPoint(x: 0, y: 1), color: color, origin: origin, rotation: rotation),
QuadVertex(x: origin.x + hHalfSize, y: origin.y + vHalfSize, textCoord: CGPoint(x: 1, y: 1), color: color, origin: origin, rotation: rotation)
]
vertexCount = vertices.count
}
func generateTrapezoidQuad(topFactor: CGFloat, bottomFactor: CGFloat, heightFactor: CGFloat) {
func generateTrapezoidQuad(topFactor: CGFloat, bottomFactor: CGFloat, heightFactor: CGFloat) -> [QuadVertex] {
let vHalfSize = size * heightFactor * 0.5
let hTopHalfSize = size * topFactor * 0.5
let hBottomHalfSize = size * bottomFactor * 0.5
vertices = [
return [
QuadVertex(x: origin.x - hTopHalfSize, y: origin.y - vHalfSize, textCoord: CGPoint(x: 0, y: 0), color: color, origin: origin, rotation: rotation),
QuadVertex(x: origin.x + hBottomHalfSize, y: origin.y - vHalfSize, textCoord: CGPoint(x: 1, y: 0), color: color, origin: origin, rotation: rotation),
QuadVertex(x: origin.x - hTopHalfSize, y: origin.y + vHalfSize, textCoord: CGPoint(x: 0, y: 1), color: color, origin: origin, rotation: rotation),
@@ -92,15 +85,12 @@ class Quad {
QuadVertex(x: origin.x - hTopHalfSize, y: origin.y + vHalfSize, textCoord: CGPoint(x: 0, y: 1), color: color, origin: origin, rotation: rotation),
QuadVertex(x: origin.x + hBottomHalfSize, y: origin.y + vHalfSize, textCoord: CGPoint(x: 1, y: 1), color: color, origin: origin, rotation: rotation)
]
vertexCount = vertices.count
}
}
extension Quad {
enum Shape {
case rounded
case squared
case calligraphic(CGFloat, CGFloat)
case trapezoid(topFactor: CGFloat, bottomFactor: CGFloat, heightFactor: CGFloat)
}
enum QuadShape: Codable {
case rounded
case squared
case calligraphic(CGFloat, CGFloat)
case trapezoid(topFactor: CGFloat, bottomFactor: CGFloat, heightFactor: CGFloat)
}
@@ -0,0 +1,18 @@
//
// StrokeQuad.swift
// Memola
//
// Created by Dscyre Scotti on 5/4/24.
//
import MetalKit
import Foundation
class StrokeQuad: NSObject, Codable {
var quad: Quad
init(quad: Quad) {
self.quad = quad
}
}
@@ -27,7 +27,7 @@ struct SolidPointStrokeGenerator: StrokeGenerator {
let control = CGPoint.middle(p1: start, p2: end)
addCurve(from: start, to: end, by: control, on: stroke)
case 3:
discardPoints(upto: stroke.vertexIndex, on: stroke)
discardVertices(upto: stroke.vertexIndex, on: stroke)
let index = stroke.keyPoints.count - 1
var start = stroke.keyPoints[index - 2]
var end = CGPoint.middle(p1: stroke.keyPoints[index - 2], p2: stroke.keyPoints[index - 1])
@@ -62,7 +62,7 @@ struct SolidPointStrokeGenerator: StrokeGenerator {
}
private func smoothOutPath(on stroke: Stroke) {
discardPoints(upto: stroke.vertexIndex, on: stroke)
discardVertices(upto: stroke.vertexIndex, on: stroke)
adjustPreviousKeyPoint(on: stroke)
switch stroke.keyPoints.count {
case 4:
@@ -106,7 +106,8 @@ struct SolidPointStrokeGenerator: StrokeGenerator {
rotation = CGFloat.random(in: 0...360) * .pi / 180
}
let quad = Quad(origin: point, size: stroke.thickness, color: stroke.color, rotation: rotation)
stroke.vertices.append(contentsOf: quad.vertices)
stroke._quads.append(quad)
stroke.vertices.append(contentsOf: quad.generateVertices(quad.shape))
stroke.vertexCount = stroke.vertices.endIndex
}
@@ -115,9 +116,9 @@ struct SolidPointStrokeGenerator: StrokeGenerator {
let factor: CGFloat
switch configuration.granularity {
case .automatic:
factor = min(6, 1 / (stroke.thickness * 10 / 500))
factor = min(3.5, 1 / (stroke.thickness * 10 / 300))
case .fixed:
factor = 1 / (stroke.thickness * stroke.style.stepRate)
factor = 1 / (stroke.thickness * stroke.penStyle.anyPenStyle.stepRate)
case .none:
factor = 1 / (stroke.thickness * 10 / 500)
}
@@ -134,7 +135,7 @@ struct SolidPointStrokeGenerator: StrokeGenerator {
#warning("TODO: remove later")
private func addLine(from start: CGPoint, to end: CGPoint, on stroke: Stroke) {
let distance = end.distance(to: start)
let segments = max(distance / stroke.style.stepRate, 2)
let segments = max(distance / stroke.penStyle.anyPenStyle.stepRate, 2)
for i in 0..<Int(segments) {
let i = CGFloat(i)
let x = start.x + (end.x - start.x) * (i / segments)
@@ -144,13 +145,15 @@ struct SolidPointStrokeGenerator: StrokeGenerator {
}
}
private func discardPoints(upto index: Int, on stroke: Stroke) {
private func discardVertices(upto index: Int, on stroke: Stroke) {
if index < 0 {
stroke.vertices.removeAll()
stroke._quads.removeAll()
} else {
let count = stroke.vertices.endIndex
let dropCount = count - (max(0, index) + 1)
stroke.vertices.removeLast(dropCount)
stroke._quads.removeLast(dropCount / 6)
}
}
}
+50 -58
View File
@@ -6,24 +6,35 @@
//
import MetalKit
import CoreData
import Foundation
class Stroke: Codable {
var color: [CGFloat]
var style: any PenStyle
var thickness: CGFloat
@objc(Stroke)
class Stroke: NSManagedObject {
@NSManaged var id: UUID
@NSManaged var color: [CGFloat]
@NSManaged var style: Int16
@NSManaged var createdAt: Date
@NSManaged var thickness: CGFloat
@NSManaged var strokeQuads: Array<StrokeQuad>
@NSManaged var graphicContext: GraphicContext?
var angle: CGFloat = 0
var penStyle: Style {
Style(rawValue: style) ?? .marker
}
var quadIndex: Int = -1
var vertexIndex: Int = -1
var keyPoints: [CGPoint] = []
var thicknessFactor: CGFloat = 0.7
var vertices: [QuadVertex] = []
var _quads: [Quad] = []
var vertexBuffer: MTLBuffer?
var vertexCount: Int = 0
let createdAt: Date = Date()
var texture: MTLTexture?
var isEmpty: Bool {
@@ -31,73 +42,38 @@ class Stroke: Codable {
}
var isEraserPenStyle: Bool {
style is EraserPenStyle
}
init(color: [CGFloat], style: any PenStyle, thickness: CGFloat) {
self.color = color
self.style = style
self.thickness = thickness
}
enum CodingKeys: CodingKey {
case color
case style
case thickness
case vertices
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
color = try container.decode([CGFloat].self, forKey: .color)
let style: String = try container.decode(String.self, forKey: .style)
thickness = try container.decode(CGFloat.self, forKey: .thickness)
vertices = try container.decode([QuadVertex].self, forKey: .vertices)
vertexCount = vertices.count
switch style {
case "marker":
self.style = .marker
case "eraser":
self.style = .eraser
default:
throw DecodingError.valueNotFound(PenStyle.self, .init(codingPath: [CodingKeys.style], debugDescription: "There is no pen style called `\(style)`."))
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(color, forKey: .color)
try container.encode(thickness, forKey: .thickness)
try container.encode(vertices, forKey: .vertices)
let styleName: String
switch style {
case is MarkerPenStyle:
styleName = "marker"
case is EraserPenStyle:
styleName = "eraser"
default:
fatalError()
}
try container.encode(styleName, forKey: .style)
penStyle == .eraser
}
func begin(at point: CGPoint) {
style.generator.begin(at: point, on: self)
penStyle.anyPenStyle.generator.begin(at: point, on: self)
}
func append(to point: CGPoint) {
style.generator.append(to: point, on: self)
penStyle.anyPenStyle.generator.append(to: point, on: self)
}
func finish(at point: CGPoint) {
style.generator.finish(at: point, on: self)
penStyle.anyPenStyle.generator.finish(at: point, on: self)
keyPoints.removeAll()
}
func loadVertices() {
vertices = strokeQuads
.flatMap { $0.quad.generateVertices($0.quad.shape) }
vertexCount = vertices.endIndex
}
func saveQuads() {
strokeQuads = _quads.map(StrokeQuad.init)
_quads.removeAll()
}
}
extension Stroke: Drawable {
func prepare(device: MTLDevice) {
if texture == nil {
texture = style.loadTexture(on: device)
texture = penStyle.anyPenStyle.loadTexture(on: device)
}
vertexBuffer = device.makeBuffer(bytes: &vertices, length: MemoryLayout<QuadVertex>.stride * vertexCount, options: .cpuCacheModeWriteCombined)
}
@@ -110,3 +86,19 @@ extension Stroke: Drawable {
renderEncoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: vertexCount)
}
}
extension Stroke {
enum Style: Int16 {
case marker
case eraser
var anyPenStyle: any PenStyle {
switch self {
case .marker:
return MarkerPenStyle.marker
case .eraser:
return EraserPenStyle.eraser
}
}
}
}
@@ -45,7 +45,8 @@ class GraphicRenderPass: RenderPass {
if renderer.redrawsGraphicRender {
canvas.setGraphicRenderType(.finished)
for stroke in graphicContext.strokes {
for stroke in graphicContext.strokes.array {
guard let stroke = stroke as? Stroke else { continue }
if graphicContext.previousStroke === stroke || graphicContext.currentStroke === stroke {
continue
}
+12 -1
View File
@@ -9,7 +9,7 @@ import SwiftUI
import Foundation
class Pen: NSObject, ObservableObject, Identifiable {
@Published var style: PenStyle
@Published var style: any PenStyle
@Published var color: [CGFloat]
@Published var thickness: CGFloat
@@ -18,6 +18,17 @@ class Pen: NSObject, ObservableObject, Identifiable {
self.color = color
self.thickness = thickness
}
var strokeStyle: Stroke.Style {
switch style {
case is MarkerPenStyle:
return .marker
case is EraserPenStyle:
return .eraser
default:
return .marker
}
}
}
extension Pen {
+1 -1
View File
@@ -8,8 +8,8 @@
import SwiftUI
struct CanvasView: UIViewControllerRepresentable {
let canvas: Canvas
@EnvironmentObject var tool: Tool
@EnvironmentObject var canvas: Canvas
@EnvironmentObject var history: History
func makeUIViewController(context: Context) -> CanvasViewController {
@@ -15,6 +15,7 @@ class Memo: NSManagedObject {
@NSManaged var data: Data
@NSManaged var createdAt: Date
@NSManaged var updatedAt: Date
@NSManaged var canvas: Canvas
}
extension Memo: Identifiable { }
+8 -13
View File
@@ -14,10 +14,10 @@ struct MemoView: View {
@StateObject var tool = Tool()
@StateObject var history = History()
@EnvironmentObject var canvas: Canvas
let canvas: Canvas
var body: some View {
CanvasView()
CanvasView(canvas: canvas)
.ignoresSafeArea()
.overlay(alignment: .bottomTrailing) {
PenToolView()
@@ -53,9 +53,6 @@ struct MemoView: View {
.environmentObject(tool)
.environmentObject(canvas)
.environmentObject(history)
.task {
canvas.listen(on: managedObjectContext)
}
}
var historyTool: some View {
@@ -91,15 +88,13 @@ struct MemoView: View {
}
func closeMemo() {
Task(priority: .high) {
await MainActor.run {
canvas.state = .closing
}
await canvas.save(on: managedObjectContext)
await MainActor.run {
canvas.state = .closed
dismiss()
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
NSLog("[Memola] - \(error.localizedDescription)")
}
}
dismiss()
}
}
+19 -15
View File
@@ -12,7 +12,7 @@ struct MemosView: View {
@FetchRequest(sortDescriptors: []) var memos: FetchedResults<Memo>
@State var canvas: Canvas?
@State var memo: Memo?
var body: some View {
NavigationStack {
@@ -29,9 +29,8 @@ struct MemosView: View {
}
}
}
.fullScreenCover(item: $canvas) { canvas in
MemoView()
.environmentObject(canvas)
.fullScreenCover(item: $memo) { memo in
MemoView(canvas: memo.canvas)
}
}
@@ -59,29 +58,34 @@ struct MemosView: View {
func createMemo(title: String) {
do {
let data = try JSONEncoder().encode(Canvas())
let memo = Memo(context: managedObjectContext)
memo.id = UUID()
memo.title = title
memo.data = data
memo.createdAt = .now
memo.updatedAt = .now
let canvas = Canvas(context: managedObjectContext)
canvas.id = UUID()
canvas.width = 4_000
canvas.height = 4_000
let graphicContext = GraphicContext(context: managedObjectContext)
graphicContext.id = UUID()
graphicContext.strokes = []
memo.canvas = canvas
canvas.memo = memo
canvas.graphicContext = graphicContext
graphicContext.canvas = canvas
try managedObjectContext.save()
openMemo(for: memo)
} catch {
NSLog("[SketchNote] - \(error.localizedDescription)")
NSLog("[Memola] - \(error.localizedDescription)")
}
}
func openMemo(for memo: Memo) {
do {
let data = memo.data
let canvas = try JSONDecoder().decode(Canvas.self, from: data)
canvas.memo = memo
self.canvas = canvas
} catch {
NSLog("[SketchNote] - \(error.localizedDescription)")
}
self.memo = memo
}
}
+6 -4
View File
@@ -13,12 +13,14 @@ class Persistence {
static let shared: Persistence = Persistence()
private init() { }
var viewContext: NSManagedObjectContext {
persistentContainer.viewContext
private init() {
QuadValueTransformer.register()
}
lazy var viewContext: NSManagedObjectContext = {
persistentContainer.viewContext
}()
lazy var persistentContainer: NSPersistentContainer = {
let persistentStore = NSPersistentStoreDescription()
persistentStore.shouldMigrateStoreAutomatically = true
@@ -0,0 +1,53 @@
//
// QuadValueTransformer.swift
// Memola
//
// Created by Dscyre Scotti on 5/8/24.
//
import CoreData
import Foundation
@objc(QuadValueTransformer)
class QuadValueTransformer: ValueTransformer {
static let name = NSValueTransformerName(rawValue: String(describing: QuadValueTransformer.self))
override class func transformedValueClass() -> AnyClass {
StrokeQuad.self
}
override func transformedValue(_ value: Any?) -> Any? {
guard let quads = value as? [StrokeQuad] else {
assertionFailure("[Memola] - Failed to transform `[Quad]` to `Data`")
return nil
}
do {
let data = try JSONEncoder().encode(quads)
return data
} catch {
print(error.localizedDescription)
assertionFailure("[Memola] - Failed to transform `Quad` to `Data`")
return nil
}
}
override func reverseTransformedValue(_ value: Any?) -> Any? {
guard let data = value as? Data else {
assertionFailure("[Memola] - Failed to transform `Data` to `Quad`")
return nil
}
do {
let quads = try JSONDecoder().decode([StrokeQuad].self, from: data)
return quads
} catch {
print(error.localizedDescription)
assertionFailure("[Memola] - Failed to transform `Data` to `Quad`")
return nil
}
}
static func register() {
let transformer = QuadValueTransformer()
ValueTransformer.setValueTransformer(transformer, forName: name)
}
}
@@ -1,10 +1,31 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="22222" systemVersion="23B74" minimumToolsVersion="Automatic" sourceLanguage="Swift" usedWithSwiftData="YES" userDefinedModelVersionIdentifier="">
<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="22757" systemVersion="23B74" minimumToolsVersion="Automatic" sourceLanguage="Swift" userDefinedModelVersionIdentifier="">
<entity name="Canvas" representedClassName="Canvas" syncable="YES">
<attribute name="height" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES" customClassName="CGFloat"/>
<attribute name="id" attributeType="UUID" usesScalarValueType="NO"/>
<attribute name="width" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES" customClassName="CGFloat"/>
<relationship name="graphicContext" maxCount="1" deletionRule="Cascade" destinationEntity="GraphicContext" inverseName="canvas" inverseEntity="GraphicContext"/>
<relationship name="memo" maxCount="1" deletionRule="Deny" destinationEntity="Memo" inverseName="canvas" inverseEntity="Memo"/>
</entity>
<entity name="GraphicContext" representedClassName="GraphicContext" syncable="YES">
<attribute name="id" attributeType="UUID" usesScalarValueType="NO"/>
<relationship name="canvas" optional="YES" maxCount="1" deletionRule="Nullify" destinationEntity="Canvas" inverseName="graphicContext" inverseEntity="Canvas"/>
<relationship name="strokes" toMany="YES" deletionRule="Cascade" ordered="YES" destinationEntity="Stroke" inverseName="graphicContext" inverseEntity="Stroke"/>
</entity>
<entity name="Memo" representedClassName="Memo" syncable="YES">
<attribute name="createdAt" attributeType="Date" usesScalarValueType="NO"/>
<attribute name="data" attributeType="Binary" allowsExternalBinaryDataStorage="YES"/>
<attribute name="id" attributeType="UUID" usesScalarValueType="NO"/>
<attribute name="title" attributeType="String"/>
<attribute name="updatedAt" attributeType="Date" usesScalarValueType="NO"/>
<relationship name="canvas" maxCount="1" deletionRule="Cascade" destinationEntity="Canvas" inverseName="memo" inverseEntity="Canvas"/>
</entity>
<entity name="Stroke" representedClassName="Stroke" syncable="YES">
<attribute name="color" attributeType="Transformable" valueTransformerName="NSSecureUnarchiveFromDataTransformer" customClassName="[CGFloat]"/>
<attribute name="createdAt" attributeType="Date" usesScalarValueType="NO"/>
<attribute name="id" attributeType="UUID" usesScalarValueType="NO"/>
<attribute name="strokeQuads" optional="YES" attributeType="Transformable" valueTransformerName="QuadValueTransformer" customClassName="[StrokeQuad]"/>
<attribute name="style" attributeType="Integer 16" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="thickness" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>
<relationship name="graphicContext" optional="YES" maxCount="1" deletionRule="Nullify" destinationEntity="GraphicContext" inverseName="strokes" inverseEntity="GraphicContext"/>
</entity>
</model>