import Foundation import Darwin import AppIntents /// What the widget shows; written by the app into the shared app-group container. struct NowSnapshot: Codable, Equatable { var title = "" var artist = "" var album = "" var playing = false var position: Double = 0 var duration: Double = 0 var at: Double = 0 // when `position` was sampled (epoch seconds) var hasArt = false var artVersion = 0 var favourite = false var shuffle = false var repeatMode = 0 var palette: [UInt32] = [] // primary, onPrimary, primaryC, onPrimaryC, secondaryC, onSecondaryC, surface, surfaceHigh, onSurface, onSurfaceVar var dark = true var lyrics: [Double] = [] // line start times (synced only) var lyricText: [String] = [] var plainLyric = "" // first unsynced lines when lyrics aren't timed var widgetFPS = 15 static let group = "group.com.mulberry.player" static let kind = "MulberryPlayer" static let lyricsKind = "MulberryLyrics" static let shapeKind = "MulberryShape" static var container: URL { if let u = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group) { return u } // Jailbreak installs without a group container: fall back to a shared world-readable folder. let u = URL(fileURLWithPath: "/var/mobile/Library/Mulberry", isDirectory: true) try? FileManager.default.createDirectory(at: u, withIntermediateDirectories: true) return u } static var file: URL { container.appendingPathComponent("now.json") } static var artFile: URL { container.appendingPathComponent("art.jpg") } static func load() -> NowSnapshot { guard let d = try? Data(contentsOf: file), let s = try? JSONDecoder().decode(NowSnapshot.self, from: d) else { return NowSnapshot() } return s } func save() { if let d = try? JSONEncoder().encode(self) { try? d.write(to: NowSnapshot.file, options: .atomic) } } /// Position at a given time, extrapolated while playing. func position(at date: Date) -> Double { guard playing else { return position } return min(duration > 0 ? duration : .infinity, position + date.timeIntervalSince1970 - at) } func lyricIndex(at date: Date) -> Int { let t = position(at: date) var ans = -1 for (i, s) in lyrics.enumerated() where s <= t + 0.15 { ans = i } return ans } } // MARK: Widget buttons (iOS 17 interactive widgets) // One parameterless AudioPlaybackIntent per button, like FlacBox. AudioPlaybackIntent runs in the app's process. // build.sh generates Metadata.appintents for these (tools/gen-appintents.py); without it iOS drops the widget. enum MulberryCommand: String { case toggle, next, previous, shuffle, repeatMode, favourite, back10, forward10 } /// The app installs a handler at launch; inside the widget extension it stays nil. enum IntentRouter { @MainActor static var handler: ((MulberryCommand) -> Void)? static func run(_ c: MulberryCommand) async { let handled = await MainActor.run { () -> Bool in guard let h = IntentRouter.handler else { return false } h(c) return true } // Running inside the widget extension: send the system media command (what the Lock Screen controls do), // and also tell the app directly via a Darwin notification. if !handled { mediaRemote(c) post(c) } } /// MRMediaRemoteSendCommand from the private MediaRemote framework, looked up at runtime. static func mediaRemote(_ c: MulberryCommand) { let cmd: UInt32 switch c { case .toggle: cmd = 2 // kMRTogglePlayPause case .next: cmd = 4 // kMRNextTrack case .previous: cmd = 5 // kMRPreviousTrack default: return } guard let h = dlopen("/System/Library/PrivateFrameworks/MediaRemote.framework/MediaRemote", RTLD_LAZY), let f = dlsym(h, "MRMediaRemoteSendCommand") else { return } typealias Send = @convention(c) (UInt32, CFDictionary?) -> Bool _ = unsafeBitCast(f, to: Send.self)(cmd, nil) } static func name(_ c: MulberryCommand) -> String { "com.mulberry.player.cmd." + c.rawValue } static func post(_ c: MulberryCommand) { CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), CFNotificationName(name(c) as CFString), nil, nil, true) } /// App side: act on commands posted by the widget extension. @MainActor static func listen() { let center = CFNotificationCenterGetDarwinNotifyCenter() for c in [MulberryCommand.toggle, .next, .previous, .shuffle, .repeatMode, .favourite, .back10, .forward10] { CFNotificationCenterAddObserver(center, nil, { _, _, name, _, _ in guard let raw = name?.rawValue as String?, let cmd = MulberryCommand(rawValue: String(raw.dropFirst("com.mulberry.player.cmd.".count))) else { return } DispatchQueue.main.async { IntentRouter.handler?(cmd) } }, name(c) as CFString, nil, .deliverImmediately) } } } @available(iOS 17.0, *) struct PlayPauseIntent: AudioPlaybackIntent { static var title: LocalizedStringResource = "Play or pause" init() {} func perform() async throws -> some IntentResult { await IntentRouter.run(.toggle); return .result() } } @available(iOS 17.0, *) struct NextTrackIntent: AudioPlaybackIntent { static var title: LocalizedStringResource = "Next track" init() {} func perform() async throws -> some IntentResult { await IntentRouter.run(.next); return .result() } } @available(iOS 17.0, *) struct PreviousTrackIntent: AudioPlaybackIntent { static var title: LocalizedStringResource = "Previous track" init() {} func perform() async throws -> some IntentResult { await IntentRouter.run(.previous); return .result() } } @available(iOS 17.0, *) struct ShuffleIntent: AudioPlaybackIntent { static var title: LocalizedStringResource = "Shuffle" init() {} func perform() async throws -> some IntentResult { await IntentRouter.run(.shuffle); return .result() } } @available(iOS 17.0, *) struct RepeatIntent: AudioPlaybackIntent { static var title: LocalizedStringResource = "Repeat" init() {} func perform() async throws -> some IntentResult { await IntentRouter.run(.repeatMode); return .result() } } @available(iOS 17.0, *) struct SkipBackIntent: AudioPlaybackIntent { static var title: LocalizedStringResource = "Back 10 seconds" init() {} func perform() async throws -> some IntentResult { await IntentRouter.run(.back10); return .result() } } @available(iOS 17.0, *) struct SkipForwardIntent: AudioPlaybackIntent { static var title: LocalizedStringResource = "Forward 10 seconds" init() {} func perform() async throws -> some IntentResult { await IntentRouter.run(.forward10); return .result() } } @available(iOS 17.0, *) struct FavouriteIntent: AudioPlaybackIntent { static var title: LocalizedStringResource = "Favourite" init() {} func perform() async throws -> some IntentResult { await IntentRouter.run(.favourite); return .result() } }