Repository Public
1// SP Lecture Studio2// File: Apps/LectureStudio/Shared/App/AppModel.swift3// Description: Application state: the lecture library on disk, project lifecycle (create, open, duplicate, rename, archive, trash) and open sessions.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import Observation9import SwiftUI10import LectureCore11import LectureStorage12import LecturePDF1314struct AppAlert: Identifiable { let id = UUID(); var title: String; var message: String }1516@MainActor @Observable17final class AppModel {18 let settings: AppSettings19 private(set) var library: Library20 var items: [LectureStorage.LibraryItem] = []21 var trashed: [LectureStorage.LibraryItem] = []22 var unreadable: [URL] = []23 var query = ""24 var selectedID: UUID?25 var alert: AppAlert?26 var isBusy = false27 var totalBytes: Int64 = 028 var freeBytes: Int64 = 029 /// One live session per open project (shared by the main window, extra windows and the presentation window).30 private var sessions: [UUID: ProjectSession] = [:]3132 init(settings: AppSettings? = nil, root: URL? = nil) {33 self.settings = settings ?? AppSettings()34 let base = root ?? Self.defaultRoot()35 // The library folder is created on first launch; failure here would mean the container is unusable.36 library = (try? Library(root: base)) ?? (try! Library(root: FileManager.default.temporaryDirectory.appendingPathComponent("Lectures")))37 refresh()38 }3940 /// iOS: Documents/Lectures (visible in the Files app). macOS: Application Support/Lectures inside the sandbox container.41 static func defaultRoot() -> URL {42 #if os(iOS)43 let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]44 #else45 let dir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]46 #endif47 // Tests point the app at a scratch library: an absolute path, or a folder name inside the app container.48 if let override = ProcessInfo.processInfo.environment["LECTURE_LIBRARY_ROOT"] ?? UserDefaults.standard.string(forKey: "LectureLibraryRoot"), !override.isEmpty {49 return override.hasPrefix("/") ? URL(fileURLWithPath: override) : dir.appendingPathComponent(override, isDirectory: true).appendingPathComponent("Lectures", isDirectory: true)50 }51 return dir.appendingPathComponent("Lectures", isDirectory: true)52 }5354 var exportsRoot: URL { library.root.deletingLastPathComponent().appendingPathComponent("Exports", isDirectory: true) }5556 func refresh() {57 let scan = library.scan()58 items = scan.items; unreadable = scan.unreadable59 trashed = library.trashedProjects()60 totalBytes = scan.items.reduce(0) { $0 + $1.byteCount }61 freeBytes = ProjectPackage.freeDiskSpace(at: library.root)62 if let id = selectedID, !items.contains(where: { $0.id == id }) { selectedID = nil }63 }6465 var visibleItems: [LectureStorage.LibraryItem] {66 items.filter { ($0.manifest.archived == settings.stored.showArchived) && Library.matches($0, query: query) }67 }68 var recentItems: [LectureStorage.LibraryItem] { Array(items.filter { !$0.manifest.archived }.prefix(4)) }69 var archivedCount: Int { items.filter(\.manifest.archived).count }7071 func item(_ id: UUID?) -> LectureStorage.LibraryItem? { items.first { $0.id == id } }7273 // MARK: Creation / import7475 /// Creates a lecture from a PDF picked by the user (copied into the project; the original is left untouched).76 @discardableResult77 func createLecture(fromPDF url: URL, title: String? = nil, courseCode: String = "", sessionNumber: Int? = nil, date: Date = Date()) -> UUID? {78 let scoped = url.startAccessingSecurityScopedResource()79 defer { if scoped { url.stopAccessingSecurityScopedResource() } }80 do {81 let pages = try SlideDocument.pageCount(of: url)82 let name = title?.trimmingCharacters(in: .whitespaces).isEmpty == false ? title! : url.deletingPathExtension().lastPathComponent83 let pkg = try library.create(title: name, courseCode: courseCode, sessionNumber: sessionNumber, lectureDate: date, pdf: url, pdfPageCount: pages)84 refresh()85 let id = try pkg.loadManifest().id86 selectedID = id87 return id88 } catch SlideDocumentError.locked {89 alert = AppAlert(title: String(localized: "PDF protégé"), message: String(localized: "Ce PDF est protégé par un mot de passe. Retirez la protection, puis importez-le de nouveau."))90 } catch {91 alert = AppAlert(title: String(localized: "Importation impossible"), message: String(localized: "Ce fichier n'a pas pu être lu comme un PDF.") + "\n" + String(describing: error))92 }93 return nil94 }9596 /// Imports a `.slecture` package or a `.slecture.zip` archive (always as a copy).97 func importProject(from url: URL) {98 let scoped = url.startAccessingSecurityScopedResource()99 defer { if scoped { url.stopAccessingSecurityScopedResource() } }100 do {101 let pkg = try library.importProject(from: url)102 refresh(); selectedID = try pkg.loadManifest().id103 } catch {104 alert = AppAlert(title: String(localized: "Importation impossible"), message: String(describing: error))105 }106 }107108 /// Routes a file opened from Finder / Files / the share sheet.109 func open(url: URL) {110 let ext = url.pathExtension.lowercased()111 if ext == "pdf" { createLecture(fromPDF: url) }112 else if ext == ProjectLayout.packageExtension || ext == "zip" { importProject(from: url) }113 }114115 // MARK: Sessions116117 func session(for id: UUID) -> ProjectSession? {118 if let s = sessions[id] { return s }119 guard let item = item(id) else { return nil }120 do {121 let s = try ProjectSession(package: item.package, settings: settings)122 s.onManifestChanged = { [weak self] in self?.refreshSoon() }123 sessions[id] = s124 return s125 } catch {126 alert = AppAlert(title: String(localized: "Ouverture impossible"), message: Self.describe(error))127 return nil128 }129 }130131 func isRecording(_ id: UUID) -> Bool { sessions[id]?.recState != .idle && sessions[id] != nil }132 var anyRecording: Bool { sessions.values.contains { $0.recState != .idle } }133134 private var refreshPending = false135 private func refreshSoon() {136 guard !refreshPending else { return }137 refreshPending = true138 DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in self?.refreshPending = false; self?.refresh() }139 }140141 private func closeSession(_ id: UUID) -> Bool {142 if let s = sessions[id] {143 guard s.recState == .idle else {144 alert = AppAlert(title: String(localized: "Enregistrement en cours"), message: String(localized: "Arrêtez l'enregistrement avant de modifier ce projet."))145 return false146 }147 s.close(); sessions[id] = nil148 }149 return true150 }151152 static func describe(_ error: Error) -> String {153 if let e = error as? StorageError {154 switch e {155 case .newerSchema: return String(localized: "Ce projet a été créé avec une version plus récente de l'application. Mettez l'application à jour pour l'ouvrir.")156 case .pdfMissing: return String(localized: "Le PDF de ce projet est introuvable dans le paquet.")157 default: return e.description158 }159 }160 return String(describing: error)161 }162163 // MARK: Library operations164165 func duplicate(_ item: LectureStorage.LibraryItem) {166 do { let copy = try library.duplicate(item.package, titleSuffix: String(localized: "(copie)")); refresh(); selectedID = try copy.loadManifest().id }167 catch { alert = AppAlert(title: String(localized: "Duplication impossible"), message: String(describing: error)) }168 }169170 func rename(_ item: LectureStorage.LibraryItem, to title: String) {171 let t = title.trimmingCharacters(in: .whitespacesAndNewlines)172 guard !t.isEmpty, closeSession(item.id) else { return }173 do { _ = try library.rename(item.package, to: t); refresh() } catch { alert = AppAlert(title: String(localized: "Renommage impossible"), message: String(describing: error)) }174 }175176 func updateMetadata(_ item: LectureStorage.LibraryItem, _ change: (inout ProjectManifest) -> Void) {177 if let s = sessions[item.id] { s.updateManifest(change); refresh(); return }178 guard var m = try? item.package.loadManifest() else { return }179 change(&m); try? item.package.saveManifest(m); refresh()180 }181182 func setArchived(_ item: LectureStorage.LibraryItem, _ archived: Bool) {183 updateMetadata(item) { $0.archived = archived }184 if selectedID == item.id { selectedID = nil }185 }186187 /// Moves a project to the library trash (recoverable until the trash is emptied).188 func trash(_ item: LectureStorage.LibraryItem) {189 guard closeSession(item.id) else { return }190 do { try library.moveToTrash(item.package); refresh() } catch { alert = AppAlert(title: String(localized: "Suppression impossible"), message: String(describing: error)) }191 }192193 func restore(_ item: LectureStorage.LibraryItem) { _ = try? library.restoreFromTrash(item.package); refresh() }194 func emptyTrash() { try? library.emptyTrash(); refresh() }195}196