Repository Public
1// SP Notes iOS2// File: WidgetShared/WidgetDataProvider.swift3// Description: Read-only access to the notes for the widgets and the note picker (App Intents). In the app process the app's own4// store is used (never a second connection in the same process); in the widget extension a read-only connection to5// the shared database is opened for the time of one query and closed again. A missing or unreadable database is an6// ordinary state (the app was never opened), never an error shown to the user. The `content` functions are what the7// widgets show: they answer `.locked` (no title, no preview, no task) while the app lock is on (`WidgetLock`).8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation12import os13import SPNotesCore1415/// A note as the widgets and the system pickers show it.16struct WidgetNote: Sendable, Equatable, Identifiable {17 var id: String18 var title: String19 var preview: String20 var updatedAt: Date21 var pinned = false2223 /// The server names a note without title "Untitled"; it is shown as « Sans titre » everywhere.24 static func displayTitle(_ title: String) -> String {25 title == "Untitled" || title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? String(localized: "Sans titre") : title26 }2728 init(id: String, title: String, preview: String, updatedAt: Date, pinned: Bool = false) {29 self.id = id30 self.title = title31 self.preview = preview32 self.updatedAt = updatedAt33 self.pinned = pinned34 }3536 init(_ summary: PageSummary) {37 self.init(id: summary.id, title: Self.displayTitle(summary.title), preview: summary.preview, updatedAt: summary.updatedAt, pinned: summary.pinned)38 }3940 var url: URL { DeepLink.note(id).url }41}4243/// What a widget has to show.44enum WidgetContent: Sendable, Equatable {45 /// The database cannot be read yet (the app was never opened on this device).46 case unavailable47 /// The database is readable and the list is empty.48 case empty49 /// The app lock is on: nothing of the notes is shown (2.0).50 case locked51 case notes([WidgetNote])5253 var notes: [WidgetNote] {54 if case .notes(let notes) = self { return notes }55 return []56 }57}5859/// Where the notes are read from in this process.60enum SharedNotesStore {61 typealias Provider = @Sendable () async throws -> NotesStore62 private static let provider = OSAllocatedUnfairLock<Provider?>(initialState: nil)6364 /// Called once by the app: every reader of this process then goes through the app's store.65 static func useAppStore(_ make: @escaping Provider) { provider.withLock { $0 = make } }6667 static var defaultDatabaseURL: URL {68 AppGroup.containerURL.appendingPathComponent("SPNotes", isDirectory: true).appendingPathComponent("notes.sqlite")69 }7071 struct Unavailable: Error {}7273 /// Runs `body` with a store. `databaseURL` forces a read-only connection to that file (widget extension, tests).74 static func read<T: Sendable>(databaseURL: URL? = nil, _ body: @Sendable (NotesStore) async throws -> T) async throws -> T {75 if databaseURL == nil, let make = provider.withLock({ $0 }) { return try await body(try await make()) }76 let url = databaseURL ?? defaultDatabaseURL77 guard FileManager.default.fileExists(atPath: url.path) else { throw Unavailable() }78 let store = try NotesStore(url: url, readOnly: true)79 do {80 let value = try await body(store)81 await store.close()82 return value83 } catch {84 await store.close()85 throw error86 }87 }88}8990struct WidgetDataProvider: Sendable {91 /// nil = the app's store in the app, the shared database in an extension.92 var databaseURL: URL?93 /// The mirrored app-lock setting (tests inject a throw-away suite).94 var lock = WidgetLock.shared9596 // MARK: what the widgets show (lock aware)9798 /// The list of a list widget; `.locked` — and nothing read — while the app lock is on.99 func content(_ kind: WidgetListKind, limit: Int) async -> WidgetContent {100 if lock.isEnabled { return .locked }101 return await list(kind == .recent ? .recent : .pinned, limit: limit)102 }103104 /// The chosen note of the configurable widget.105 func single(noteId: String?, textLength: Int) async -> SingleNoteState {106 if lock.isEnabled { return .locked }107 guard let noteId else { return .unconfigured }108 guard let note = await note(id: noteId, textLength: textLength) else { return .missing }109 return .note(note)110 }111112 // MARK: raw reads (no lock check: the app's own intents and the functions above)113114 /// Pages a widget can show and open: notes, not folders, not database rows.115 static func isNote(_ summary: PageSummary) -> Bool { !summary.isFolder && summary.type != "database" && summary.deletedAt == nil }116117 func list(_ list: SmartList, limit: Int) async -> WidgetContent {118 do {119 let notes = try await SharedNotesStore.read(databaseURL: databaseURL) { store in120 // Folders are filtered out afterwards: a little more is read so the widget is still full.121 try await store.summaries(list: list, limit: limit * 3 + 6).filter(Self.isNote).prefix(limit).map(WidgetNote.init)122 }123 return notes.isEmpty ? .empty : .notes(notes)124 } catch {125 return .unavailable126 }127 }128129 func recent(limit: Int) async -> WidgetContent { await list(.recent, limit: limit) }130 func pinned(limit: Int) async -> WidgetContent { await list(.pinned, limit: limit) }131132 /// One note with the beginning of its text (`preview` then holds up to `textLength` characters). nil when it is gone or in the trash.133 func note(id: String, textLength: Int = 600) async -> WidgetNote? {134 try? await SharedNotesStore.read(databaseURL: databaseURL) { store -> WidgetNote? in135 guard let page = try await store.page(id: id), page.deletedAt == nil else { return nil }136 let text = page.plainText.trimmingCharacters(in: .whitespacesAndNewlines)137 return WidgetNote(id: page.id, title: WidgetNote.displayTitle(page.title), preview: text.isEmpty ? page.preview : String(text.prefix(textLength)),138 updatedAt: page.updatedAt, pinned: page.pinned)139 }140 }141142 func notes(ids: [String]) async -> [WidgetNote] {143 (try? await SharedNotesStore.read(databaseURL: databaseURL) { store in144 var found: [WidgetNote] = []145 for id in ids { if let summary = try await store.summary(id: id), summary.deletedAt == nil { found.append(WidgetNote(summary)) } }146 return found147 }) ?? []148 }149150 func search(_ query: String, limit: Int = 20) async -> [WidgetNote] {151 (try? await SharedNotesStore.read(databaseURL: databaseURL) { store in152 try await store.search(query: query, limit: limit * 2).map(\.page).filter(Self.isNote).prefix(limit).map(WidgetNote.init)153 }) ?? []154 }155}156