importCottonFacesimportCottonKitimportSwiftUI/// Native commands may request these OS effects; only the platform performs/// them. The core does not report a permission it cannot grant.publicenumRecordPlatformAction: Decodable, Hashable, Sendable {case shareFile(URL)case requestNotifications, openNotificationSettingscase pickFile(RecordFilePick)case openFlow(RecordKeptFlow)/// "Re-key this device" (`DeviceRekey`): the app mints the successor key.case rekeyDevice/// A book's read act (`reader.open`): the reader opens it, at `at` when/// the act names a place.case openReader(ReaderOpening)/// A list's Set picture from Photos (`open_picker`, picker `photos`):/// the photo picker opens and the picture picked is the list's own/// (`ListPicture`).case pickListPicture(group: String)/// Keep everything turned on (`keep_songs`): every song not on this phone/// comes down (`SongKeeper`), and what the act said is said.case keepSongs(said: String?)/// An album's Find details (`find_details`): the phone's lookups/// (`MusicLookup`).case findDetails(table: String, id: String)/// A song's, an album's or an artist's Play, Shuffle, Play next and Add/// to queue, a film's or a series' episode's Play (`shell.player`): the/// instrument of the kind playing plays what the core answered/// (`Players`).case play(PlayerAnswer)/// Cotton Cinemas' Keep everything turned on (`keep_films`): every film/// and episode not on this phone comes down (`FilmKeeper`), and what the/// act said is said.case keepFilms(said: String?)/// A library's Export library (`export_open`): the open bundle of `kit`/// laid, zipped and handed to the share sheet (`LibraryExport`), named/// after its tool (`name`).case exportOpen(kit: String, name: String)/// A scene's Write (`open_writer`): Cotton Story writes its scenes in/// its own screens (`Story/Ink`), so nothing outside them opens one.case openWriter(scene: String)privateenumName: String, Decodable {case shareFile = "share_file"case requestNotifications = "request_notifications"case openNotificationSettings = "open_notification_settings"case pickFile = "pick_file"case openFlow = "open_flow"case rekeyDevice = "rekey_device"case openReader = "open_reader"case openPicker = "open_picker"case keepSongs = "keep_songs"case findDetails = "find_details"case playcase keepFilms = "keep_films"case exportOpen = "export_open"case openWriter = "open_writer" }publicinit(from decoder: Decoder) throws {self = trySelf.action(Name(from: decoder), decoder: decoder) }staticfunc fromAnswer(_ decoder: Decoder) throws -> Self? {structPlatform: Decodable { let platform_action: Name? }guardlet name = tryPlatform(from: decoder).platform_action else { returnnil }returntry action(name, decoder: decoder) }privatestaticfunc action(_ name: Name, decoder: Decoder) throws -> Self {switch name {case .shareFile:structFile: Decodable { let path: String }return .shareFile(URL(fileURLWithPath: tryFile(from: decoder).path))case .requestNotifications: return .requestNotificationscase .openNotificationSettings: return .openNotificationSettingscase .pickFile: return .pickFile(tryRecordFilePick(from: decoder))case .openFlow: return .openFlow(tryRecordKeptFlow(from: decoder))case .rekeyDevice: return .rekeyDevicecase .openReader:structOpening: Decodable { let id: String; let at: String?; let table: String? }let opening = tryOpening(from: decoder)return .openReader(ReaderOpening(id: opening.id, at: opening.at, table: opening.table ?? "book"))case .openPicker:structPicker: Decodable { let picker: String; let group: String? }let picker = tryPicker(from: decoder)guard picker.picker == "photos", let group = picker.group else {throwDecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "open_picker opens a list's photo picker alone, not \(picker.picker)")) }return .pickListPicture(group: group)case .keepSongs:structSaid: Decodable { let said: String? }return .keepSongs(said: trySaid(from: decoder).said)case .findDetails:structNamed: Decodable { let table: String; let id: String }let named = tryNamed(from: decoder)return .findDetails(table: named.table, id: named.id)case .play:return .play(tryPlayerAnswer(from: decoder))case .keepFilms:structSaid: Decodable { let said: String? }return .keepFilms(said: trySaid(from: decoder).said)case .exportOpen:structLibrary: Decodable { let kit: String; let name: String }let library = tryLibrary(from: decoder)return .exportOpen(kit: library.kit, name: library.name)case .openWriter:structScene: Decodable { let scene: String }return .openWriter(scene: tryScene(from: decoder).scene) } }}@MainActorenumRecordPlatformEffects { @discardableResultstaticfunc perform(_ action: RecordPlatformAction, authority: any NotificationSettingsAuthority = SystemNotificationSettingsAuthority(), nativeFlow: (@MainActor (RecordKeptFlow) async -> Bool)? = nil, rekey: (@MainActor () async -> Bool)? = nil, reader: ReaderPresenter? = nil) async -> Bool {switch action {case .openReader(let opening):guardlet reader else { returnfalse } reader.open(opening)case .shareFile(let url):ShareSheet.present(url)case .pickListPicture(let group):awaitListPicture.shared.pick(for: group)case .keepSongs(let said): #if os(iOS)awaitSongKeeper.shared.keepEverything(said: said) #endifcase .findDetails(let table, let id):awaitMusicLookup.shared.findDetails(table: table, id: id)case .play(let answer): #if os(iOS)Players.took(answer) #elsereturnfalse #endifcase .keepFilms(let said): #if os(iOS)awaitFilmKeeper.shared.keepEverything(said: said) #elsereturnfalse #endifcase .exportOpen(let kit, let name):awaitLibraryExport.shared.export(kit: kit, name: name)case .openWriter:returnfalsecase .rekeyDevice:guardlet rekey else { returnfalse }returnawait rekey()case .openFlow(let flow):guardlet nativeFlow else { returnfalse }returnawait nativeFlow(flow)case .pickFile: returnfalse// Requires a captured native continuation.case .requestNotifications:ifawait authority.read() == .undetermined { _ = await authority.ask() }// The existing permission-change listener registers and reports// the actual OS answer through the device push path.case .openNotificationSettings: authority.openSystemSettings() }returntrue }}/// A native flow requests platform work, never claims an engine change.publicstructRecordKeptFlow: Decodable, Hashable, Sendable {publicenumFlow: String, Decodable, Hashable, Sendable {case leaveDatabase, reportProblem, vaultUnlock/// This device's own Sign in, Sign out and Erase (`device.json`): the/// personal object's session, which the app's root runs/// (`PersonalSessionFlows`) wherever the device's card is opened.case signIn, signOut, eraseThisDevice/// This device's Share ink: the ink the phone kept (`InkCapture`),/// handed to the share sheet by the app's root.case shareInk/// A film's, a season's and an episode's Keep on phone and Remove/// download (`film.json`, `film_season.json`, `film_episode.json`):/// their files come down or go (`FilmKeeper`), the root's to run/// wherever the card is opened.case keepFilm, removeFilmDownload/// A podcast episode's Keep on phone and Remove download/// (`episode.json`): its audio file comes down or goes/// (`EpisodeKeeper`), the root's to run wherever the card is opened.case keepEpisode, removeEpisodeDownload/// A book's Keep on phone and Remove download (`book.json`): its/// file comes down into the media store or this copy goes/// (`BookKeeper`), the root's to run wherever the card is opened.case keepBook, removeBookDownload/// A book's Add file (`book.json`): the document picker for its EPUB/// or PDF, which the root raises and hands to the intake.case addBookFile/// A song's and an album's Keep on phone and Remove download/// (`song.json`, `music_album.json`): their files come down or go/// (`SongKeeper`), the root's to run wherever the card is opened.case keepSong, removeSongDownload, keepAlbum, removeAlbumDownloadvar kept: KeptFlow { KeptFlow(rawValue: rawValue)! }/// This device's own acts, the app's root's to run wherever its card/// is opened.var session: Bool { [.signIn, .signOut, .eraseThisDevice, .shareInk].contains(self) }/// A film's own acts, the root's too.var film: Bool { [.keepFilm, .removeFilmDownload, .keepEpisode, .removeEpisodeDownload, .keepBook, .removeBookDownload, .addBookFile, .keepSong, .removeSongDownload, .keepAlbum, .removeAlbumDownload].contains(self) } }publicstructOrigin: Decodable, Hashable, Sendable {publiclet table: Stringpubliclet id: String }publiclet flow: Flowpubliclet origin: Originpubliclet database: String?func matches(table: String?, id: String?) -> Bool { origin.table == table && origin.id == (id ?? "new") }}extensionEnvironmentValues { @Entry var nativeKeptFlow: (@MainActor (RecordKeptFlow) async -> Bool)? = nil/// The app's "Re-key this device" (`DeviceRekey.start`), set once at the root. @Entry var rekeyThisDevice: (@MainActor () async -> Bool)? = nil}