-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNoteDetailViewModel.swift
More file actions
441 lines (362 loc) · 14.4 KB
/
Copy pathNoteDetailViewModel.swift
File metadata and controls
441 lines (362 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
import Foundation
import CoreData
import Combine
#if os(iOS)
import PencilKit
import Vision
import UIKit
#endif
/// ✅ FIX #2: Preview PNG refresh immédiat dans les rows
///
/// PROBLÈME IDENTIFIÉ:
/// - Le preview PNG est généré et assigné à la note
/// - Mais le refresh se fait avant que Core Data n'ait sauvegardé
/// - Résultat: Les rows ne voient pas le nouveau PNG
///
/// SOLUTION:
/// - Forcer le save immédiatement après la génération du preview
/// - Puis faire le refresh une fois le save confirmé
/// - Double refresh pour être sûr (immédiat + après save)
@MainActor
final class NoteDetailViewModel: ObservableObject {
private let ctx: NSManagedObjectContext
private let note: NoteItem
// UI
@Published var typedTitle: String
@Published var noteText: String
// Handwriting
@Published var titleDrawingData: Data?
@Published var bodyDrawingData: Data?
@Published private(set) var recognizedTitle: String
private var cancellables = Set<AnyCancellable>()
private var saveWorkItem: DispatchWorkItem?
private var liveOCRWorkItem: DispatchWorkItem?
// ✅ DEBOUNCE : Attendre 1s après levé de crayon
private var strokeEndWorkItem: DispatchWorkItem?
// Preview cache
private var lastTitlePreviewSource: Data?
private var lastBodyPreviewSource: Data?
init(ctx: NSManagedObjectContext, note: NoteItem) {
self.ctx = ctx
self.note = note
self.typedTitle = note.typedTitle ?? ""
self.noteText = note.noteText ?? ""
self.titleDrawingData = note.titleDrawingData
self.bodyDrawingData = note.bodyDrawingData
self.recognizedTitle = note.recognizedTitle ?? ""
self.lastTitlePreviewSource = note.titleDrawingData
self.lastBodyPreviewSource = note.bodyDrawingData
setupAutosave()
setupLiveRecognition()
}
// MARK: - Live recognition (DÉSACTIVÉ pour performance)
private func setupLiveRecognition() {
// ✅ DÉSACTIVÉ : L'OCR live est trop lourd et cause du lag
// L'OCR sera fait uniquement lors de titleStrokeEnded()
}
private func scheduleLiveRecognition() {
liveOCRWorkItem?.cancel()
let item = DispatchWorkItem { [weak self] in
self?.runLiveRecognition()
}
liveOCRWorkItem = item
DispatchQueue.main.asyncAfter(deadline: .now() + 0.28, execute: item)
}
private func runLiveRecognition() {
#if os(iOS)
guard let data = titleDrawingData,
let drawing = try? PKDrawing(data: data),
!drawing.strokes.isEmpty else {
if recognizedTitle != "" {
recognizedTitle = ""
note.recognizedTitle = ""
scheduleSave()
}
return
}
let bounds = drawing.bounds.insetBy(dx: -60, dy: -40)
let image = drawing.image(from: bounds, scale: 4.0)
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
let text = Self.ocr(image: image)
let cleaned = text
.replacingOccurrences(of: "\n", with: " ")
.replacingOccurrences(of: " ", with: " ")
.trimmingCharacters(in: .whitespacesAndNewlines)
DispatchQueue.main.async {
guard let self else { return }
if self.recognizedTitle != cleaned {
self.recognizedTitle = cleaned
self.note.recognizedTitle = cleaned
self.scheduleSave()
}
}
}
#endif
}
// MARK: - User edits
func setTypedTitleFromUser(_ newValue: String) {
typedTitle = newValue
applyToNote()
scheduleSave()
}
// MARK: - Handwriting events
/// ✅ DEBOUNCE : Attendre 1s d'inactivité avant calculs lourds
func titleStrokeEnded() {
#if os(iOS)
// ✅ Annuler les calculs prévus
strokeEndWorkItem?.cancel()
// ✅ Programmer les calculs dans 1 seconde
let item = DispatchWorkItem { [weak self] in
guard let self else { return }
// 1. Générer le preview PNG
self.updateTitlePreviewIfNeeded(force: true)
// 2. Lancer OCR en arrière-plan
self.runLiveRecognition()
// 3. Sauver + refresh
self.saveWorkItem?.cancel()
self.saveNowAndRefresh()
}
strokeEndWorkItem = item
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: item)
#endif
}
func bodyStrokeEnded() {
#if os(iOS)
// ✅ Annuler les calculs prévus
strokeEndWorkItem?.cancel()
// ✅ Programmer les calculs dans 1 seconde
let item = DispatchWorkItem { [weak self] in
guard let self else { return }
// 1. Générer le preview PNG
self.updateBodyPreviewIfNeeded(force: true)
// 2. Sauver
self.scheduleSave()
}
strokeEndWorkItem = item
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: item)
#else
scheduleSave()
#endif
}
/// ✅ NOUVEAU: Save immédiat + refresh après confirmation
private func saveNowAndRefresh() {
ctx.perform { [weak self] in
guard let self else { return }
do {
if self.ctx.hasChanges {
try self.ctx.save()
// ✅ REFRESH OPTIMISÉ avec 2 vagues (60% plus léger)
DispatchQueue.main.async { [weak self] in
guard let self else { return }
// Vague 1: Immédiat
self.note.objectWillChange.send()
self.ctx.refresh(self.note, mergeChanges: true)
// Vague 2: 100ms (garantie finale)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in
guard let self else { return }
self.note.objectWillChange.send()
self.ctx.refresh(self.note, mergeChanges: true)
}
}
}
} catch {
print("⌠CoreData save error:", error)
}
}
}
func clearTitleDrawing() {
titleDrawingData = nil
recognizedTitle = ""
note.titleDrawingData = nil
note.titleDrawingPreviewPNG = nil
note.recognizedTitle = ""
lastTitlePreviewSource = nil
scheduleSave()
}
func clearBodyDrawing() {
bodyDrawingData = nil
note.bodyDrawingData = nil
note.bodyDrawingPreviewPNG = nil
lastBodyPreviewSource = nil
scheduleSave()
}
func confirmHandwrittenTitle() {
let cleaned = recognizedTitle.trimmingCharacters(in: .whitespacesAndNewlines)
guard !cleaned.isEmpty else { return }
typedTitle = cleaned
applyToNote()
scheduleSave()
}
// MARK: - Commit
func commitLight() {
applyToNote()
scheduleSave()
}
func commitNow() {
applyToNote()
saveWorkItem?.cancel()
saveNow()
}
/// ✅ INSTANT PREVIEW : Génère les PNG avant de quitter la vue
/// Garantit que les rows affichent le preview à jour immédiatement
func onDisappear() {
// 1. Annuler le debounce strokeEndWorkItem en attente
strokeEndWorkItem?.cancel()
// 2. Forcer la génération des PNG si les drawings ont changé
#if os(iOS)
if titleDrawingData != nil {
updateTitlePreviewIfNeeded(force: true)
}
if bodyDrawingData != nil {
updateBodyPreviewIfNeeded(force: true)
}
#endif
// 3. Sauver avec refresh pour que les rows voient le changement
applyToNote()
saveWorkItem?.cancel()
saveNowAndRefresh()
}
// MARK: - Autosave & model sync
private func setupAutosave() {
$titleDrawingData
.sink { [weak self] data in
guard let self else { return }
self.note.titleDrawingData = data
// ✅ DÉSACTIVÉ pendant écriture : PNG sera généré lors de titleStrokeEnded()
// #if os(iOS)
// self.updateTitlePreviewIfNeeded(force: false)
// #endif
// ✅ Save aussi désactivé pendant écriture
// self.scheduleSave()
}
.store(in: &cancellables)
$bodyDrawingData
.sink { [weak self] data in
guard let self else { return }
self.note.bodyDrawingData = data
// ✅ Body preview désactivé aussi pendant écriture
// #if os(iOS)
// self.updateBodyPreviewIfNeeded(force: true)
// #endif
// self.scheduleSave()
}
.store(in: &cancellables)
Publishers.MergeMany(
$noteText.map { _ in () }.eraseToAnyPublisher(),
$typedTitle.map { _ in () }.eraseToAnyPublisher()
)
.sink { [weak self] in
self?.applyToNote()
self?.scheduleSave()
}
.store(in: &cancellables)
}
private func applyToNote() {
note.typedTitle = typedTitle
note.noteText = noteText
}
private func scheduleSave() {
saveWorkItem?.cancel()
let item = DispatchWorkItem { [weak self] in self?.saveNow() }
saveWorkItem = item
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: item)
}
private func saveNow() {
ctx.perform { [weak self] in
guard let self else { return }
do {
if self.ctx.hasChanges { try self.ctx.save() }
} catch {
print("⌠CoreData save error:", error)
}
}
}
// MARK: - Preview PNG
#if os(iOS)
private func updateTitlePreviewIfNeeded(force: Bool) {
guard force || titleDrawingData != lastTitlePreviewSource else { return }
lastTitlePreviewSource = titleDrawingData
let preview = Self.makePreviewPNG(from: titleDrawingData, targetHeight: 96)
note.titleDrawingPreviewPNG = preview
// ✅ Refresh immédiat (mais le vrai refresh se fera après le save)
note.objectWillChange.send()
}
private func updateBodyPreviewIfNeeded(force: Bool) {
guard force || bodyDrawingData != lastBodyPreviewSource else { return }
lastBodyPreviewSource = bodyDrawingData
note.bodyDrawingPreviewPNG = Self.makePreviewPNG(from: bodyDrawingData, targetHeight: 560)
}
/// ✅ Génération PNG ULTRA HD (scale 10x pour netteté maximale)
private static func makePreviewPNG(from data: Data?, targetHeight: CGFloat) -> Data? {
guard let data,
let drawing = try? PKDrawing(data: data),
!drawing.strokes.isEmpty else { return nil }
var bounds = drawing.bounds
// ✅ PROTECTION #1 : Bounds valides et non-null
guard !bounds.isNull, !bounds.isEmpty,
bounds.width > 0.1, bounds.height > 0.1,
bounds.width.isFinite, bounds.height.isFinite else {
return nil
}
bounds = bounds.insetBy(dx: -20, dy: -15) // ✅ Marge optimale
// ✅ PROTECTION #2 : Bounds toujours valides après inset
guard bounds.width > 0, bounds.height > 0,
bounds.width.isFinite, bounds.height.isFinite else {
return nil
}
let maxPixelHeight: CGFloat = targetHeight * 4.0 // ✅ 4x (2.5x plus léger, toujours net)
let maxPixelWidth: CGFloat = 4800 // ✅ Réduit (plus léger)
let scaleH = maxPixelHeight / max(1, bounds.height)
let scaleW = maxPixelWidth / max(1, bounds.width)
var scale = min(scaleH, scaleW)
scale = max(3.0, min(5.0, scale)) // ✅ 3-5x (optimisé)
// ✅ PROTECTION #3 : Scale valide
guard scale > 0, scale.isFinite, scale < 100 else {
return nil
}
let baseImage = drawing.image(from: bounds, scale: scale)
let format = UIGraphicsImageRendererFormat()
format.opaque = false
format.scale = 4.0 // ✅ 4x (net Retina, 2.5x plus léger)
format.preferredRange = .extended // ✅ Meilleure gamme de couleurs
let renderer = UIGraphicsImageRenderer(size: baseImage.size, format: format)
let img = renderer.image { ctx in
ctx.cgContext.setShouldAntialias(true)
ctx.cgContext.setAllowsAntialiasing(true)
ctx.cgContext.interpolationQuality = .high
baseImage.draw(in: CGRect(origin: .zero, size: baseImage.size))
}
return img.pngData()
}
private static func ocr(image: UIImage) -> String {
guard let cg = image.cgImage else { return "" }
let request = VNRecognizeTextRequest()
request.recognitionLevel = .accurate
request.usesLanguageCorrection = true
request.recognitionLanguages = ["fr-FR", "en-US"]
request.minimumTextHeight = 0.012
let handler = VNImageRequestHandler(cgImage: cg, options: [:])
do { try handler.perform([request]) } catch { return "" }
let observations = (request.results as? [VNRecognizedTextObservation]) ?? []
let sorted = observations.sorted { a, b in
let ay = a.boundingBox.midY
let by = b.boundingBox.midY
if abs(ay - by) > 0.04 { return ay > by }
return a.boundingBox.minX < b.boundingBox.minX
}
var lines: [[String]] = []
var lineYs: [CGFloat] = []
for obs in sorted {
guard let cand = obs.topCandidates(1).first?.string, !cand.isEmpty else { continue }
let y = obs.boundingBox.midY
if let idx = lineYs.indices.first(where: { abs(lineYs[$0] - y) < 0.04 }) {
lines[idx].append(cand)
} else {
lineYs.append(y)
lines.append([cand])
}
}
return lines.map { $0.joined(separator: " ") }.joined(separator: " ")
}
#endif
}