Mulberry/ios/Widget/MulberryWidgets.swift
astar76 fd04376c75 Add Mulberry for iOS (1.0.6) under ios/
SwiftUI port of the Android app with the desktop feature set; built on Linux,
linked and signed on a jailbroken iPhone. History imported from the standalone repo.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 23:23:51 -05:00

364 lines
15 KiB
Swift

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import WidgetKit
import SwiftUI
import AppIntents
struct NowEntry: TimelineEntry {
let date: Date
let snap: NowSnapshot
let art: UIImage?
}
struct NowProvider: TimelineProvider {
func placeholder(in context: Context) -> NowEntry {
var s = NowSnapshot()
s.title = "Drive"; s.artist = "Incubus"; s.album = "Make Yourself"; s.duration = 232; s.position = 60
s.palette = Palette.fromSeed(0xE07A5F, dark: true).widgetColors
return NowEntry(date: Date(), snap: s, art: nil)
}
func getSnapshot(in context: Context, completion: @escaping (NowEntry) -> Void) {
let s = NowSnapshot.load()
completion(s.title.isEmpty ? placeholder(in: context) : NowEntry(date: Date(), snap: s, art: loadArt()))
}
func getTimeline(in context: Context, completion: @escaping (Timeline<NowEntry>) -> Void) {
let s = NowSnapshot.load()
let art = loadArt()
let now = Date()
var entries = [NowEntry(date: now, snap: s, art: art)]
if s.playing && s.duration > 0 {
// One entry per upcoming synced lyric line (up to 60), so the lyrics card follows the song.
let pos = s.position(at: now)
let end = now.addingTimeInterval(max(0, s.duration - pos))
for t in s.lyrics where t > pos && entries.count < 60 {
let d = now.addingTimeInterval(t - pos)
if d < end { entries.append(NowEntry(date: d, snap: s, art: art)) }
}
var done = s
done.playing = false
done.position = s.duration
entries.append(NowEntry(date: end.addingTimeInterval(1), snap: done, art: art))
completion(Timeline(entries: entries, policy: .after(end.addingTimeInterval(2))))
} else {
completion(Timeline(entries: entries, policy: .never))
}
}
private func loadArt() -> UIImage? {
guard let d = try? Data(contentsOf: NowSnapshot.artFile) else { return nil }
return UIImage(data: d)
}
}
extension Palette {
var widgetColors: [UInt32] {
[primary, onPrimary, primaryContainer, onPrimaryContainer, secondaryContainer, onSecondaryContainer, surface,
surfaceHigh, onSurface, onSurfaceVariant]
}
}
/// Colour lookup from the snapshot (falls back to the default palette).
struct WColors {
let c: [Color]
init(_ s: NowSnapshot) {
let raw = s.palette.count == 10 ? s.palette : Palette.fromSeed(Palette.defaultSeed, dark: s.dark).widgetColors
c = raw.map { Color(rgb: $0) }
}
var primary: Color { c[0] }
var onPrimary: Color { c[1] }
var primaryC: Color { c[2] }
var onPrimaryC: Color { c[3] }
var secondaryC: Color { c[4] }
var onSecondaryC: Color { c[5] }
var surface: Color { c[6] }
var surfaceHigh: Color { c[7] }
var onSurface: Color { c[8] }
var onSurfaceVar: Color { c[9] }
}
struct CookieShape: Shape {
var depth: CGFloat = 0.045
func path(in rect: CGRect) -> Path {
Shapes.cookie(center: CGPoint(x: rect.midX, y: rect.midY), radius: min(rect.width, rect.height) / 2, depth: depth, rotation: 0)
}
}
struct CoverCookie: View {
let art: UIImage?
let colors: WColors
var body: some View {
ZStack {
if let art { Image(uiImage: art).resizable().scaledToFill() }
else { colors.primaryC.overlay(Image(systemName: "music.note").font(.title2).foregroundColor(colors.onPrimaryC)) }
}
.clipShape(CookieShape())
}
}
/// Plain glyph button like FlacBox's widget. It's a link: iOS's AppIntents indexer (linkd) won't index
/// non-App Store apps, so Button(intent:) does nothing. The app runs the command and returns to the Home Screen.
struct GlyphButton: View {
let cmd: MulberryCommand
let icon: String
let size: CGFloat
let color: Color
var body: some View {
Link(destination: URL(string: "mulberry://cmd/" + cmd.rawValue)!) {
Image(systemName: icon)
.font(.system(size: size, weight: .semibold))
.foregroundColor(color)
.frame(maxWidth: .infinity, minHeight: size * 1.6)
.contentShape(Rectangle())
}
}
}
/// Previous / (−10) / Play / (+10) / Next row.
struct Controls: View {
let s: NowSnapshot
let col: WColors
var size: CGFloat = 26
var skips = true
var body: some View {
HStack(spacing: 0) {
GlyphButton(cmd: .previous, icon: "backward.fill", size: size, color: col.onSurface)
if skips { GlyphButton(cmd: .back10, icon: "gobackward.10", size: size * 0.9, color: col.onSurface) }
GlyphButton(cmd: .toggle, icon: s.playing ? "pause.fill" : "play.fill", size: size * 1.2, color: col.primary)
if skips { GlyphButton(cmd: .forward10, icon: "goforward.10", size: size * 0.9, color: col.onSurface) }
GlyphButton(cmd: .next, icon: "forward.fill", size: size, color: col.onSurface)
}
}
}
/// Progress that advances by itself while playing.
struct LiveProgress: View {
let s: NowSnapshot
let col: WColors
let date: Date
var showTimes = true
var body: some View {
let pos = s.position(at: date)
let start = date.addingTimeInterval(-pos)
let end = start.addingTimeInterval(max(1, s.duration))
VStack(spacing: 2) {
if s.playing && s.duration > 0 {
ProgressView(timerInterval: start...end, countsDown: false) { EmptyView() } currentValueLabel: { EmptyView() }
.tint(col.primary)
} else {
ProgressView(value: s.duration > 0 ? min(1, pos / s.duration) : 0).tint(col.primary)
}
if showTimes {
HStack {
if s.playing { Text(start, style: .timer).monospacedDigit() } else { Text(TimeFmt.string(pos)) }
Spacer()
Text(TimeFmt.string(s.duration))
}
.font(.system(size: 10).monospacedDigit())
.foregroundColor(col.onSurfaceVar)
}
}
}
}
/// Now Playing widget, laid out like FlacBox's (no progress bar or timer), in Mulberry's colours.
struct PlayerWidgetView: View {
let e: NowEntry
@Environment(\.widgetFamily) var family
var body: some View {
let s = e.snap, col = WColors(s)
Group {
switch family {
case .systemSmall: small(s, col)
case .systemLarge: large(s, col)
default: medium(s, col)
}
}
.widgetURL(URL(string: family == .systemSmall ? "mulberry://cmd/toggle" : "mulberry://nowplaying"))
.containerBackground(for: .widget) {
LinearGradient(colors: [Color(rgb: Palette.mix(s.palette.count == 10 ? s.palette[2] : 0x553355,
s.palette.count == 10 ? s.palette[7] : 0x222222, 0.45)),
col.surfaceHigh], startPoint: .topLeading, endPoint: .bottomTrailing)
}
}
private func title(_ s: NowSnapshot) -> String { s.title.isEmpty ? "Not playing" : s.title }
private func subtitle(_ s: NowSnapshot) -> String {
if s.title.isEmpty { return "Mulberry" }
return [s.artist, s.album].filter { !$0.isEmpty }.joined(separator: " • ")
}
private func heart(_ s: NowSnapshot, _ col: WColors) -> some View {
Link(destination: URL(string: "mulberry://cmd/favourite")!) {
Image(systemName: s.favourite ? "heart.fill" : "heart")
.font(.system(size: 22, weight: .regular))
.foregroundColor(s.favourite ? col.primary : col.onSurface)
.frame(width: 34, height: 34)
}
}
private func small(_ s: NowSnapshot, _ col: WColors) -> some View {
VStack(alignment: .leading, spacing: 4) {
CoverCookie(art: e.art, colors: col).frame(width: 54, height: 54)
Spacer(minLength: 2)
Text(title(s)).font(.system(size: 14, weight: .bold)).foregroundColor(col.onSurface).lineLimit(1)
Text(s.artist).font(.system(size: 12)).foregroundColor(col.onSurfaceVar).lineLimit(1)
Image(systemName: s.playing ? "pause.fill" : "play.fill")
.font(.system(size: 20, weight: .semibold)).foregroundColor(col.primary)
}
}
private func medium(_ s: NowSnapshot, _ col: WColors) -> some View {
VStack(spacing: 6) {
HStack(alignment: .top, spacing: 12) {
CoverCookie(art: e.art, colors: col).frame(width: 64, height: 64)
VStack(alignment: .leading, spacing: 2) {
Text(title(s)).font(.system(size: 18, weight: .bold)).foregroundColor(col.onSurface).lineLimit(1)
Text(subtitle(s)).font(.system(size: 14)).foregroundColor(col.onSurfaceVar).lineLimit(1)
}
Spacer(minLength: 0)
heart(s, col)
}
Spacer(minLength: 0)
Controls(s: s, col: col, size: 24)
}
}
private func large(_ s: NowSnapshot, _ col: WColors) -> some View {
VStack(spacing: 10) {
HStack(alignment: .top) {
CoverCookie(art: e.art, colors: col).frame(width: 150, height: 150)
Spacer(minLength: 0)
heart(s, col)
}
VStack(alignment: .leading, spacing: 3) {
Text(title(s)).font(.system(size: 22, weight: .bold)).foregroundColor(col.onSurface).lineLimit(2)
Text(subtitle(s)).font(.system(size: 16)).foregroundColor(col.onSurfaceVar).lineLimit(1)
}
.frame(maxWidth: .infinity, alignment: .leading)
Spacer(minLength: 0)
Controls(s: s, col: col, size: 30)
}
}
}
/// The lyrics card (Android widget's lower panel): the current synced line, with the next ones dimmed.
struct LyricsCard: View {
let e: NowEntry
let col: WColors
var lines = 2
var body: some View {
let s = e.snap
let i = s.lyricIndex(at: e.date)
VStack(alignment: .leading, spacing: 6) {
Image(systemName: "music.note").font(.caption).foregroundColor(col.primary)
if !s.lyrics.isEmpty {
let cur = i >= 0 ? s.lyricText[i] : (s.lyricText.first ?? "")
Text(cur.isEmpty ? "♪" : cur).font(.system(size: 17, weight: .bold)).foregroundColor(col.onSurface).lineLimit(2)
ForEach(Array(s.lyricText.dropFirst(i + 1).prefix(lines - 1).enumerated()), id: \.offset) { _, l in
Text(l.isEmpty ? "♪" : l).font(.system(size: 13)).foregroundColor(col.onSurfaceVar).lineLimit(1)
}
} else if !s.plainLyric.isEmpty {
Text(s.plainLyric).font(.system(size: 13)).foregroundColor(col.onSurfaceVar).lineLimit(lines + 1)
} else {
Text(s.title.isEmpty ? "Nothing playing" : s.title).font(.system(size: 16, weight: .bold)).foregroundColor(col.onSurface)
Text("No lyrics").font(.system(size: 13)).foregroundColor(col.onSurfaceVar)
}
Spacer(minLength: 0)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(12)
.background(RoundedRectangle(cornerRadius: 18, style: .continuous).fill(col.surface.opacity(0.55)))
}
}
struct LyricsWidgetView: View {
let e: NowEntry
var body: some View {
let col = WColors(e.snap)
LyricsCard(e: e, col: col, lines: 3)
.padding(-12)
.widgetURL(URL(string: "mulberry://nowplaying"))
.containerBackground(for: .widget) { col.surfaceHigh }
}
}
struct LockWidgetView: View {
let e: NowEntry
@Environment(\.widgetFamily) var family
var body: some View {
let s = e.snap
Group {
switch family {
case .accessoryCircular:
ZStack {
AccessoryWidgetBackground()
if s.playing && s.duration > 0 {
let start = e.date.addingTimeInterval(-s.position(at: e.date))
ProgressView(timerInterval: start...start.addingTimeInterval(s.duration), countsDown: false) { EmptyView() } currentValueLabel: {
Image(systemName: "pause.fill")
}
.progressViewStyle(.circular)
} else {
Image(systemName: "play.fill")
}
}
.widgetLabel(s.title)
case .accessoryInline:
Text(s.title.isEmpty ? "Mulberry" : "♪ \(s.title) · \(s.artist)")
default:
VStack(alignment: .leading, spacing: 1) {
if !s.lyrics.isEmpty, s.playing, case let i = s.lyricIndex(at: e.date), i >= 0 {
Text(s.lyricText[i].isEmpty ? "♪" : s.lyricText[i]).font(.headline).lineLimit(2)
Text("\(s.title) · \(s.artist)").font(.caption2).lineLimit(1).opacity(0.8)
} else {
Text(s.title.isEmpty ? "Nothing playing" : s.title).font(.headline).lineLimit(1)
Text(s.artist).font(.caption).lineLimit(1)
LiveProgress(s: s, col: WColors(s), date: e.date, showTimes: false)
}
}
}
}
.widgetURL(URL(string: "mulberry://nowplaying"))
.containerBackground(for: .widget) { Color.clear }
}
}
struct PlayerWidget: Widget {
var body: some WidgetConfiguration {
StaticConfiguration(kind: NowSnapshot.kind, provider: NowProvider()) { PlayerWidgetView(e: $0) }
.configurationDisplayName("Mulberry")
.description("What's playing, with controls.")
.supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
}
}
struct LyricsWidget: Widget {
var body: some WidgetConfiguration {
StaticConfiguration(kind: NowSnapshot.lyricsKind, provider: NowProvider()) { LyricsWidgetView(e: $0) }
.configurationDisplayName("Mulberry lyrics")
.description("The current line of synced lyrics.")
.supportedFamilies([.systemMedium, .systemSmall])
}
}
struct LockWidget: Widget {
var body: some WidgetConfiguration {
StaticConfiguration(kind: NowSnapshot.shapeKind, provider: NowProvider()) { LockWidgetView(e: $0) }
.configurationDisplayName("Mulberry")
.description("Now playing on the Lock Screen.")
.supportedFamilies([.accessoryRectangular, .accessoryCircular, .accessoryInline])
}
}
@main
struct MulberryWidgets: WidgetBundle {
var body: some Widget {
PlayerWidget()
LyricsWidget()
LockWidget()
}
}