diff --git a/ios/App/App.xcodeproj/project.pbxproj b/ios/App/App.xcodeproj/project.pbxproj index 7625b2d..2aba279 100644 --- a/ios/App/App.xcodeproj/project.pbxproj +++ b/ios/App/App.xcodeproj/project.pbxproj @@ -7,8 +7,12 @@ objects = { /* Begin PBXBuildFile section */ + 2851A7EC448DEA6D3038A56F /* Snapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D8706633BFF338CAC59A616 /* Snapshot.swift */; }; 2FAD9763203C412B000D30F8 /* config.xml in Resources */ = {isa = PBXBuildFile; fileRef = 2FAD9762203C412B000D30F8 /* config.xml */; }; + 31D5C16A8513A24DBBA285AC /* GamesTableWidget.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = 6CAAC698C7DED542C814E5DD /* GamesTableWidget.appex */; }; + 372EDD1EA34C59218B54F415 /* MainViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C312694407775F06FDAC59A8 /* MainViewController.swift */; }; 4D22ABE92AF431CB00220026 /* CapApp-SPM in Frameworks */ = {isa = PBXBuildFile; productRef = 4D22ABE82AF431CB00220026 /* CapApp-SPM */; }; + 4D7AD78065319DAA4B934CEB /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EEBF06D841565A434D0E15A8 /* Foundation.framework */; }; 50379B232058CBB4000EE86E /* capacitor.config.json in Resources */ = {isa = PBXBuildFile; fileRef = 50379B222058CBB4000EE86E /* capacitor.config.json */; }; 504EC3081FED79650016851F /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 504EC3071FED79650016851F /* AppDelegate.swift */; }; 504EC30D1FED79650016851F /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC30B1FED79650016851F /* Main.storyboard */; }; @@ -16,9 +20,37 @@ 504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC3101FED79650016851F /* LaunchScreen.storyboard */; }; 50B271D11FEDC1A000F3C39B /* public in Resources */ = {isa = PBXBuildFile; fileRef = 50B271D01FEDC1A000F3C39B /* public */; }; 9582B6832FE993A70072D4E8 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9582B6822FE993A50072D4E8 /* SceneDelegate.swift */; }; + DE2ADC9BDC023FEF5ED903E3 /* GamesTableWidget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C6B13E1E4048D8F69559421 /* GamesTableWidget.swift */; }; + FAAD68B62AE1C223CE50C217 /* WidgetBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1AFC67C4F5A9A443A46310D9 /* WidgetBridge.swift */; }; /* End PBXBuildFile section */ +/* Begin PBXContainerItemProxy section */ + 5774AC4E57871B8452D42F46 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 504EC2FC1FED79650016851F /* Project object */; + proxyType = 1; + remoteGlobalIDString = 0588352B3DA4F03C258A5DA5; + remoteInfo = GamesTableWidget; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + E3CDC095EA52264637B4EB35 /* Embed App Extensions */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 13; + files = ( + 31D5C16A8513A24DBBA285AC /* GamesTableWidget.appex in Embed App Extensions */, + ); + name = "Embed App Extensions"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + /* Begin PBXFileReference section */ + 1AFC67C4F5A9A443A46310D9 /* WidgetBridge.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = WidgetBridge.swift; sourceTree = ""; }; + 2AB4FA25A4930857A81C0F16 /* App.entitlements */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.entitlements; name = App.entitlements; path = App/App.entitlements; sourceTree = ""; }; 2FAD9762203C412B000D30F8 /* config.xml */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = config.xml; sourceTree = ""; }; 50379B222058CBB4000EE86E /* capacitor.config.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = capacitor.config.json; sourceTree = ""; }; 504EC3041FED79650016851F /* App.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = App.app; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -28,8 +60,13 @@ 504EC3111FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 504EC3131FED79650016851F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 50B271D01FEDC1A000F3C39B /* public */ = {isa = PBXFileReference; lastKnownFileType = folder; path = public; sourceTree = ""; }; + 5D8706633BFF338CAC59A616 /* Snapshot.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Snapshot.swift; sourceTree = ""; }; + 6CAAC698C7DED542C814E5DD /* GamesTableWidget.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = GamesTableWidget.appex; sourceTree = BUILT_PRODUCTS_DIR; }; 9582B6822FE993A50072D4E8 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; 958DCC722DB07C7200EA8C5F /* debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = debug.xcconfig; path = ../debug.xcconfig; sourceTree = SOURCE_ROOT; }; + 9C6B13E1E4048D8F69559421 /* GamesTableWidget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = GamesTableWidget.swift; sourceTree = ""; }; + C312694407775F06FDAC59A8 /* MainViewController.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MainViewController.swift; sourceTree = ""; }; + EEBF06D841565A434D0E15A8 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS26.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -41,15 +78,43 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + C5490A46EA30B876DC5A2A48 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 4D7AD78065319DAA4B934CEB /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 321FB5B4E1442C996805C5CD /* Frameworks */ = { + isa = PBXGroup; + children = ( + 534A78DE5D4D578A422202DB /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + 32EA781D4BDD320BC13839CC /* GamesTableWidget */ = { + isa = PBXGroup; + children = ( + 5D8706633BFF338CAC59A616 /* Snapshot.swift */, + 9C6B13E1E4048D8F69559421 /* GamesTableWidget.swift */, + ); + name = GamesTableWidget; + path = GamesTableWidget; + sourceTree = ""; + }; 504EC2FB1FED79650016851F = { isa = PBXGroup; children = ( 958DCC722DB07C7200EA8C5F /* debug.xcconfig */, 504EC3061FED79650016851F /* App */, 504EC3051FED79650016851F /* Products */, + 321FB5B4E1442C996805C5CD /* Frameworks */, + 32EA781D4BDD320BC13839CC /* GamesTableWidget */, ); sourceTree = ""; }; @@ -57,6 +122,7 @@ isa = PBXGroup; children = ( 504EC3041FED79650016851F /* App.app */, + 6CAAC698C7DED542C814E5DD /* GamesTableWidget.appex */, ); name = Products; sourceTree = ""; @@ -73,13 +139,41 @@ 504EC3131FED79650016851F /* Info.plist */, 2FAD9762203C412B000D30F8 /* config.xml */, 50B271D01FEDC1A000F3C39B /* public */, + 1AFC67C4F5A9A443A46310D9 /* WidgetBridge.swift */, + C312694407775F06FDAC59A8 /* MainViewController.swift */, + 2AB4FA25A4930857A81C0F16 /* App.entitlements */, ); path = App; sourceTree = ""; }; + 534A78DE5D4D578A422202DB /* iOS */ = { + isa = PBXGroup; + children = ( + EEBF06D841565A434D0E15A8 /* Foundation.framework */, + ); + name = iOS; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ + 0588352B3DA4F03C258A5DA5 /* GamesTableWidget */ = { + isa = PBXNativeTarget; + buildConfigurationList = F5F48AFF81F2380A9EE2914C /* Build configuration list for PBXNativeTarget "GamesTableWidget" */; + buildPhases = ( + 665C91251742E4B59FFB0672 /* Sources */, + C5490A46EA30B876DC5A2A48 /* Frameworks */, + E94EF5566B24CFBEC3F79C06 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = GamesTableWidget; + productName = GamesTableWidget; + productReference = 6CAAC698C7DED542C814E5DD /* GamesTableWidget.appex */; + productType = "com.apple.product-type.app-extension"; + }; 504EC3031FED79650016851F /* App */ = { isa = PBXNativeTarget; buildConfigurationList = 504EC3161FED79650016851F /* Build configuration list for PBXNativeTarget "App" */; @@ -87,10 +181,12 @@ 504EC3001FED79650016851F /* Sources */, 504EC3011FED79650016851F /* Frameworks */, 504EC3021FED79650016851F /* Resources */, + E3CDC095EA52264637B4EB35 /* Embed App Extensions */, ); buildRules = ( ); dependencies = ( + BC24B699C44F99DD3B51A3F7 /* PBXTargetDependency */, ); name = App; packageProductDependencies = ( @@ -133,6 +229,7 @@ projectRoot = ""; targets = ( 504EC3031FED79650016851F /* App */, + 0588352B3DA4F03C258A5DA5 /* GamesTableWidget */, ); }; /* End PBXProject section */ @@ -151,6 +248,13 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + E94EF5566B24CFBEC3F79C06 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -160,11 +264,31 @@ files = ( 504EC3081FED79650016851F /* AppDelegate.swift in Sources */, 9582B6832FE993A70072D4E8 /* SceneDelegate.swift in Sources */, + FAAD68B62AE1C223CE50C217 /* WidgetBridge.swift in Sources */, + 372EDD1EA34C59218B54F415 /* MainViewController.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 665C91251742E4B59FFB0672 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2851A7EC448DEA6D3038A56F /* Snapshot.swift in Sources */, + DE2ADC9BDC023FEF5ED903E3 /* GamesTableWidget.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ +/* Begin PBXTargetDependency section */ + BC24B699C44F99DD3B51A3F7 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = GamesTableWidget; + target = 0588352B3DA4F03C258A5DA5 /* GamesTableWidget */; + targetProxy = 5774AC4E57871B8452D42F46 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + /* Begin PBXVariantGroup section */ 504EC30B1FED79650016851F /* Main.storyboard */ = { isa = PBXVariantGroup; @@ -185,6 +309,27 @@ /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ + 082199D6D28AAC0AAF83AA1D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_ENTITLEMENTS = GamesTableWidget/GamesTableWidget.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 742H5JJX37; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = GamesTableWidget/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.mrwd.gamestable.widget; + PRODUCT_NAME = GamesTableWidget; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; 504EC3141FED79650016851F /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 958DCC722DB07C7200EA8C5F /* debug.xcconfig */; @@ -299,8 +444,10 @@ baseConfigurationReference = 958DCC722DB07C7200EA8C5F /* debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_ENTITLEMENTS = App/App.entitlements; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 742H5JJX37; INFOPLIST_FILE = App/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 15.0; LD_RUNPATH_SEARCH_PATHS = ( @@ -321,8 +468,10 @@ isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_ENTITLEMENTS = App/App.entitlements; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 742H5JJX37; INFOPLIST_FILE = App/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 15.0; LD_RUNPATH_SEARCH_PATHS = ( @@ -338,6 +487,28 @@ }; name = Release; }; + 65E0533660C4BA30F9512E8A /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_ENTITLEMENTS = GamesTableWidget/GamesTableWidget.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 742H5JJX37; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = GamesTableWidget/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.mrwd.gamestable.widget; + PRODUCT_NAME = GamesTableWidget; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ @@ -359,6 +530,15 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + F5F48AFF81F2380A9EE2914C /* Build configuration list for PBXNativeTarget "GamesTableWidget" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 65E0533660C4BA30F9512E8A /* Release */, + 082199D6D28AAC0AAF83AA1D /* Debug */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; /* End XCConfigurationList section */ /* Begin XCLocalSwiftPackageReference section */ diff --git a/ios/App/App/App.entitlements b/ios/App/App/App.entitlements new file mode 100644 index 0000000..f94dfb0 --- /dev/null +++ b/ios/App/App/App.entitlements @@ -0,0 +1,10 @@ + + + + + com.apple.security.application-groups + + group.com.mrwd.gamestable + + + diff --git a/ios/App/App/MainViewController.swift b/ios/App/App/MainViewController.swift new file mode 100644 index 0000000..e30a6aa --- /dev/null +++ b/ios/App/App/MainViewController.swift @@ -0,0 +1,22 @@ +import Capacitor +import UIKit + +/** + * Exists for one line: registering the app's own plugin with the bridge. + * + * Plugins that ship as packages are discovered automatically; one that lives inside the + * app is not, and the only sign is a rejected call at runtime saying the plugin "is not + * implemented on ios" — the Swift compiles, the app builds, and nothing works. + * + * Registration happens in `viewDidLoad`, after `super`, because that is when the bridge + * exists. An earlier attempt used `capacitorDidLoad()`, which reads like the obvious + * hook and does not exist in this version of Capacitor — the override simply never ran, + * and the failure looked identical to not having written the plugin at all. Checking the + * shipped header for the symbol is what settled it. + */ +class MainViewController: CAPBridgeViewController { + override func viewDidLoad() { + super.viewDidLoad() + bridge?.registerPluginInstance(WidgetBridgePlugin()) + } +} diff --git a/ios/App/App/SceneDelegate.swift b/ios/App/App/SceneDelegate.swift index f352e1e..1432b9d 100644 --- a/ios/App/App/SceneDelegate.swift +++ b/ios/App/App/SceneDelegate.swift @@ -8,7 +8,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { guard let windowScene = scene as? UIWindowScene else { return } window = UIWindow(windowScene: windowScene) - window?.rootViewController = CAPBridgeViewController() + window?.rootViewController = MainViewController() window?.makeKeyAndVisible() SceneDelegateProxy.shared.scene(scene, willConnectTo: session, options: connectionOptions) diff --git a/ios/App/App/WidgetBridge.swift b/ios/App/App/WidgetBridge.swift new file mode 100644 index 0000000..4c5213e --- /dev/null +++ b/ios/App/App/WidgetBridge.swift @@ -0,0 +1,79 @@ +import Capacitor +import Foundation +import WidgetKit + +/** + * The one thing the web layer cannot do for itself: hand data to a process it does not + * control. + * + * The widgets live outside the app's container, so the snapshot goes into the shared + * App Group — as a string in `UserDefaults`, which is the right size of tool for a few + * kilobytes of JSON, and as poster files beside it because a widget cannot fetch images + * itself. + * + * Everything here is a write. The plugin exposes no way to read the group back into the + * web view, so a bug on this side cannot turn into a way out for the library. + */ +@objc(WidgetBridgePlugin) +public class WidgetBridgePlugin: CAPPlugin, CAPBridgedPlugin { + public let identifier = "WidgetBridgePlugin" + public let jsName = "WidgetBridge" + public let pluginMethods: [CAPPluginMethod] = [ + CAPPluginMethod(name: "write", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "cachePoster", returnType: CAPPluginReturnPromise), + ] + + private let suite = "group.com.mrwd.gamestable" + private let key = "widget-snapshot-v1" + + @objc func write(_ call: CAPPluginCall) { + guard let json = call.getString("json") else { + call.reject("json is required") + return + } + guard let defaults = UserDefaults(suiteName: suite) else { + // The App Group is missing from the entitlements — a build problem, not a + // runtime one, and worth saying plainly rather than failing quietly. + call.reject("app group \(suite) unavailable") + return + } + defaults.set(json, forKey: key) + WidgetCenter.shared.reloadAllTimelines() + call.resolve() + } + + /** + * Posters are copied into the group as files. The widget reads them straight off + * disk: WidgetKit renders on a tight budget and cannot wait for a download. + */ + @objc func cachePoster(_ call: CAPPluginCall) { + guard let name = call.getString("name"), let source = call.getString("url"), + let url = URL(string: source) else { + call.reject("name and url are required") + return + } + guard let dir = FileManager.default + .containerURL(forSecurityApplicationGroupIdentifier: suite)? + .appendingPathComponent("posters") else { + call.reject("app group \(suite) unavailable") + return + } + let destination = dir.appendingPathComponent(name) + if FileManager.default.fileExists(atPath: destination.path) { + call.resolve() + return + } + try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + URLSession.shared.dataTask(with: url) { data, _, _ in + guard let data, !data.isEmpty else { + // A missing poster is not worth failing a check-in over; the widget + // draws its placeholder and the next write tries again. + call.resolve() + return + } + try? data.write(to: destination) + WidgetCenter.shared.reloadAllTimelines() + call.resolve() + }.resume() + } +} diff --git a/ios/App/CapApp-SPM/Package.swift b/ios/App/CapApp-SPM/Package.swift index ee4a7b6..b866e95 100644 --- a/ios/App/CapApp-SPM/Package.swift +++ b/ios/App/CapApp-SPM/Package.swift @@ -4,7 +4,7 @@ import PackageDescription // DO NOT MODIFY THIS FILE - managed by Capacitor CLI commands let package = Package( name: "CapApp-SPM", - platforms: [.iOS(.v15)], + platforms: [.iOS(.v17)], products: [ .library( name: "CapApp-SPM", diff --git a/ios/App/GamesTableWidget/GamesTableWidget.entitlements b/ios/App/GamesTableWidget/GamesTableWidget.entitlements new file mode 100644 index 0000000..f94dfb0 --- /dev/null +++ b/ios/App/GamesTableWidget/GamesTableWidget.entitlements @@ -0,0 +1,10 @@ + + + + + com.apple.security.application-groups + + group.com.mrwd.gamestable + + + diff --git a/ios/App/GamesTableWidget/GamesTableWidget.swift b/ios/App/GamesTableWidget/GamesTableWidget.swift new file mode 100644 index 0000000..8059349 --- /dev/null +++ b/ios/App/GamesTableWidget/GamesTableWidget.swift @@ -0,0 +1,150 @@ +import SwiftUI +import WidgetKit + +/// Two widgets rather than one with a toggle: on the home screen a widget is chosen once +/// and then just sits there, so "what am I in the middle of" and "what is queued" are +/// two different things a person puts on the screen, not two modes of one thing. + +private struct SnapshotEntry: TimelineEntry { + let date: Date + let snapshot: WidgetSnapshot +} + +private struct Provider: TimelineProvider { + func placeholder(in context: Context) -> SnapshotEntry { + SnapshotEntry(date: Date(), snapshot: .empty) + } + + func getSnapshot(in context: Context, completion: @escaping (SnapshotEntry) -> Void) { + completion(SnapshotEntry(date: Date(), snapshot: SharedStore.read())) + } + + func getTimeline(in context: Context, completion: @escaping (Timeline) -> Void) { + // One entry, refreshed in an hour. The app also reloads timelines the moment the + // library changes, so this is only the floor for a phone that has not been + // opened — not the mechanism people actually see. + let entry = SnapshotEntry(date: Date(), snapshot: SharedStore.read()) + let next = Calendar.current.date(byAdding: .hour, value: 1, to: Date()) ?? Date() + completion(Timeline(entries: [entry], policy: .after(next))) + } +} + +private struct Cover: View { + let name: String? + + var body: some View { + Group { + if let name, let url = SharedStore.posterURL(name), + let data = try? Data(contentsOf: url), let image = UIImage(data: data) { + Image(uiImage: image).resizable().aspectRatio(contentMode: .fill) + } else { + // A grey block rather than an icon: at this size an icon reads as noise, + // and the row still lines up while the app fills the cache in. + Color.secondary.opacity(0.18) + } + } + // Game art is landscape, unlike a book cover or a poster. + .frame(width: 64, height: 36) + .clipShape(RoundedRectangle(cornerRadius: 5, style: .continuous)) + } +} + +private struct Row: View { + let entry: WidgetSnapshot.Entry + + private var detail: String { + var parts = [entry.status] + if let platform = entry.platform { parts.append(platform) } + if let hours = entry.hours, hours > 0 { parts.append("\(hours)h") } + return parts.joined(separator: " · ") + } + + var body: some View { + HStack(spacing: 9) { + Cover(name: entry.cover) + VStack(alignment: .leading, spacing: 2) { + Text(entry.title).font(.system(size: 13, weight: .semibold)).lineLimit(1) + Text(detail).font(.system(size: 11)).foregroundStyle(.secondary).lineLimit(1) + } + Spacer(minLength: 0) + if let score = entry.score { + Text("\(score)") + .font(.system(size: 11, weight: .bold)) + .padding(.horizontal, 5).padding(.vertical, 2) + .background(.green.opacity(0.22), in: RoundedRectangle(cornerRadius: 4)) + } + } + } +} + +private struct ListView: View { + let title: String + let entries: [WidgetSnapshot.Entry] + let emptyText: String + @Environment(\.widgetFamily) private var family + + private var limit: Int { family == .systemLarge ? 5 : 2 } + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + Text(title.uppercased()) + .font(.system(size: 11, weight: .bold)).kerning(0.6) + .foregroundStyle(.secondary) + if entries.isEmpty { + Text(emptyText).font(.system(size: 12)).foregroundStyle(.secondary) + Spacer(minLength: 0) + } else { + ForEach(entries.prefix(limit)) { entry in + // Each row opens its own game rather than just the app: tapping a + // specific title and landing on a generic screen is a small betrayal + // of the tap. + Link(destination: URL(string: "gamestable://game/\(entry.id)")!) { + Row(entry: entry) + } + } + Spacer(minLength: 0) + } + } + .padding(14) + } +} + +struct PlayingWidget: Widget { + var body: some WidgetConfiguration { + StaticConfiguration(kind: "GamesTablePlaying", provider: Provider()) { entry in + ListView( + title: "Playing", + entries: entry.snapshot.playing, + emptyText: "Nothing in progress. Start a game to see it here." + ) + .containerBackground(.fill.tertiary, for: .widget) + } + .configurationDisplayName("Playing") + .description("Games you are in the middle of, playing or watching.") + .supportedFamilies([.systemMedium, .systemLarge]) + } +} + +struct BacklogWidget: Widget { + var body: some WidgetConfiguration { + StaticConfiguration(kind: "GamesTableBacklog", provider: Provider()) { entry in + ListView( + title: "Backlog", + entries: entry.snapshot.backlog, + emptyText: "The backlog is empty." + ) + .containerBackground(.fill.tertiary, for: .widget) + } + .configurationDisplayName("Backlog") + .description("What is queued up to play or watch, longest waiting first.") + .supportedFamilies([.systemMedium, .systemLarge]) + } +} + +@main +struct GamesTableWidgets: WidgetBundle { + var body: some Widget { + PlayingWidget() + BacklogWidget() + } +} diff --git a/ios/App/GamesTableWidget/Info.plist b/ios/App/GamesTableWidget/Info.plist new file mode 100644 index 0000000..d9b073b --- /dev/null +++ b/ios/App/GamesTableWidget/Info.plist @@ -0,0 +1,11 @@ + + + + + NSExtension + + NSExtensionPointIdentifier + com.apple.widgetkit-extension + + + diff --git a/ios/App/GamesTableWidget/Snapshot.swift b/ios/App/GamesTableWidget/Snapshot.swift new file mode 100644 index 0000000..0275da4 --- /dev/null +++ b/ios/App/GamesTableWidget/Snapshot.swift @@ -0,0 +1,54 @@ +import Foundation + +/// What the app hands the widgets. +/// +/// The widget runs in its own process and cannot read the app's container, so the two +/// meet in an App Group. The app writes this structure as JSON whenever the library +/// changes; the widgets only ever read it. Nothing here is fetched from the network — +/// the app has already done that, and a widget that phoned home would break the promise +/// that the library never leaves the device. +struct WidgetSnapshot: Codable { + /// Games in progress — playing or watching, the two tracks side by side. + var playing: [Entry] + /// What is queued up: the backlog and the want-to-watch list. + var backlog: [Entry] + /// When the app last wrote this, so a stale widget can say so rather than lie. + var updatedAt: Date + + struct Entry: Codable, Identifiable { + var id: String + var title: String + /// The status as the app words it — "Playing", "Watching", "Want to play". + var status: String + var platform: String? + var hours: Int? + /// Critic score, absent when the catalogue has none. + var score: Int? + /// File name inside the App Group's caches, written by the app. + var cover: String? + } + + static let empty = WidgetSnapshot(playing: [], backlog: [], updatedAt: .distantPast) +} + +enum SharedStore { + /// Must match the App Group on both targets and `lib/widget.ts` in the web app. + static let suite = "group.com.mrwd.gamestable" + static let key = "widget-snapshot-v1" + + static func read() -> WidgetSnapshot { + guard let defaults = UserDefaults(suiteName: suite), + let raw = defaults.string(forKey: key), + let data = raw.data(using: .utf8) else { return .empty } + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .millisecondsSince1970 + return (try? decoder.decode(WidgetSnapshot.self, from: data)) ?? .empty + } + + /// Covers are files the app dropped in the group; the widget only reads. + static func posterURL(_ name: String) -> URL? { + guard let dir = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: suite) + else { return nil } + return dir.appendingPathComponent("posters").appendingPathComponent(name) + } +} diff --git a/scripts/add-widget-target.rb b/scripts/add-widget-target.rb new file mode 100644 index 0000000..62a4bf2 --- /dev/null +++ b/scripts/add-widget-target.rb @@ -0,0 +1,151 @@ +# Adds the WidgetKit extension target to the Capacitor-generated Xcode project. +# +# Capacitor regenerates very little of `ios/`, but the project file is still the kind of +# thing that gets recreated by hand or by a future `cap` command, so this exists as a +# script rather than as a one-off edit: run it again and it repairs the project instead +# of duplicating the target. +# +# gem install --user-install xcodeproj +# ruby scripts/add-widget-target.rb + +require 'xcodeproj' + +ROOT = File.expand_path('..', __dir__) +PROJECT = File.join(ROOT, 'ios/App/App.xcodeproj') +WIDGET = 'GamesTableWidget' +APP_GROUP = 'group.com.mrwd.gamestable' +BUNDLE_ID = 'com.mrwd.gamestable' +TEAM = '742H5JJX37' + +project = Xcodeproj::Project.open(PROJECT) +app = project.targets.find { |t| t.name == 'App' } or abort 'App target not found' + +# The bridge is a plugin inside the app, not part of the extension, and it has to be in +# the app target's sources or Capacitor never sees it. Compiled out, everything else +# still builds and the widget simply stays empty forever — so this runs on every +# invocation, including the early exit below. +app_group_node = project.main_group['App'] || project.main_group + +# The reference is added inside the `App` group, which already carries `App/` in its own +# path — so the name here is bare. Spelling it `App/WidgetBridge.swift` produces +# `App/App/WidgetBridge.swift` and a build that cannot find its own input. +%w[WidgetBridge.swift MainViewController.swift].each do |name| + next if app.source_build_phase.files_references.any? { |f| f.path == name } + ref = app_group_node.files.find { |f| f.path == name } || app_group_node.new_reference(name) + app.add_file_references([ref]) + puts "added #{name} to the App target" +end +project.save + +existing = app_group_node.files.select { |f| f.path&.end_with?('WidgetBridge.swift') } +wrong = existing.reject { |f| f.path == 'WidgetBridge.swift' } +wrong.each do |ref| + app.source_build_phase.remove_file_reference(ref) + ref.remove_from_project +end +puts "removed #{wrong.size} mis-pathed reference(s)" unless wrong.empty? + +unless app.source_build_phase.files_references.any? { |f| f.path == 'WidgetBridge.swift' } + ref = app_group_node.files.find { |f| f.path == 'WidgetBridge.swift' } || + app_group_node.new_reference('WidgetBridge.swift') + app.add_file_references([ref]) + project.save + puts 'added WidgetBridge.swift to the App target' +end + +if project.targets.any? { |t| t.name == WIDGET } + puts "#{WIDGET} target already present — nothing else to add" + exit +end + +# ---- entitlements ----------------------------------------------------------------- +# Both sides need the same App Group; without it the widget reads an empty container +# and silently shows nothing, which is the least debuggable failure of the whole +# feature. +def write_entitlements(path, group) + File.write(path, <<~XML) + + + + + com.apple.security.application-groups + + #{group} + + + + XML +end + +write_entitlements(File.join(ROOT, 'ios/App/App/App.entitlements'), APP_GROUP) +write_entitlements(File.join(ROOT, "ios/App/#{WIDGET}/#{WIDGET}.entitlements"), APP_GROUP) + +info_plist = File.join(ROOT, "ios/App/#{WIDGET}/Info.plist") +File.write(info_plist, <<~XML) + + + + + NSExtension + + NSExtensionPointIdentifier + com.apple.widgetkit-extension + + + +XML + +# ---- the target ------------------------------------------------------------------- +widget = project.new_target(:app_extension, WIDGET, :ios, '17.0') +group = project.new_group(WIDGET, "#{WIDGET}") + +%w[Snapshot.swift GamesTableWidget.swift].each do |name| + ref = group.new_reference(name) + widget.add_file_references([ref]) +end + +widget.build_configurations.each do |config| + s = config.build_settings + s['PRODUCT_BUNDLE_IDENTIFIER'] = "#{BUNDLE_ID}.widget" + s['PRODUCT_NAME'] = WIDGET + s['INFOPLIST_FILE'] = "#{WIDGET}/Info.plist" + s['CODE_SIGN_ENTITLEMENTS'] = "#{WIDGET}/#{WIDGET}.entitlements" + s['CODE_SIGN_STYLE'] = 'Automatic' + s['DEVELOPMENT_TEAM'] = TEAM + s['SWIFT_VERSION'] = '5.0' + s['TARGETED_DEVICE_FAMILY'] = '1,2' + s['SKIP_INSTALL'] = 'YES' + s['GENERATE_INFOPLIST_FILE'] = 'YES' + s['MARKETING_VERSION'] = '1.0' + s['CURRENT_PROJECT_VERSION'] = '1' +end + +# The app target has to carry the entitlement too, and embed the extension: an +# extension that is built but not embedded produces a perfectly green build and no +# widget in the picker. +app.build_configurations.each do |config| + config.build_settings['CODE_SIGN_ENTITLEMENTS'] = 'App/App.entitlements' + # Without a team in the project itself, Xcode's Signing & Capabilities editor refuses + # to load the capability list at all — "No development team is set", and App Groups + # cannot even be searched for. Passing the team on the xcodebuild command line is not + # enough, because the GUI never sees it. + config.build_settings['DEVELOPMENT_TEAM'] = TEAM + config.build_settings['CODE_SIGN_STYLE'] = 'Automatic' +end + +app.add_dependency(widget) +embed = app.build_phases.find { |p| p.respond_to?(:name) && p.name == 'Embed App Extensions' } +embed ||= project.new(Xcodeproj::Project::Object::PBXCopyFilesBuildPhase).tap do |phase| + phase.name = 'Embed App Extensions' + phase.symbol_dst_subfolder_spec = :plug_ins + app.build_phases << phase +end +embed.add_file_reference(widget.product_reference, true) + +# WidgetKit and SwiftUI are implicit in modern Xcode, but the entitlements file has to +# be visible in the app group for signing to pick it up. +app_group = project.main_group['App'] || project.main_group +app_group.new_reference('App/App.entitlements') unless app_group.files.any? { |f| f.path&.end_with?('App.entitlements') } + +project.save +puts "added #{WIDGET} target, App Group #{APP_GROUP}" diff --git a/src/App.tsx b/src/App.tsx index cbee0ef..20b9df8 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -6,6 +6,8 @@ import GameDetailPage from './pages/GameDetailPage' import ProfilePage from './pages/ProfilePage' import InsightsPage from './pages/InsightsPage' import { BottomNav, ConfirmHost, ScrollToTop, ToastHost } from './components/ui' +import { refreshWidgets } from './lib/widget' +import { useLibrary } from './store/library' import { watchSystemTheme } from './store/theme' import { beginSessionOnce, useStats } from './store/stats' import { SupportFab } from './components/Support' @@ -18,7 +20,16 @@ function Shell() { useEffect(() => { beginSessionOnce() - return watchSystemTheme() + // The widgets are fed from the same store the shelves read, so a subscription is + // enough: every status change pushes a fresh snapshot, and the app never has to + // remember to call this from each of those places. + void refreshWidgets() + const stopWidgets = useLibrary.subscribe(() => void refreshWidgets()) + const stopTheme = watchSystemTheme() + return () => { + stopWidgets() + stopTheme() + } }, []) useEffect(() => { diff --git a/src/lib/widget.ts b/src/lib/widget.ts new file mode 100644 index 0000000..01d6e01 --- /dev/null +++ b/src/lib/widget.ts @@ -0,0 +1,108 @@ +import { registerPlugin } from '@capacitor/core' +import { isNativeApp } from 'tables-core' +import type { GameStatus, TrackedGame } from './types' +import { useLibrary } from '../store/library' + +/** + * Feeding the home-screen widgets. + * + * The widgets run outside the app and cannot read its storage, so what they show is a + * snapshot the app pushes into a shared App Group. It is built from the same library the + * shelves read, so the two cannot drift apart. + * + * Nothing is sent anywhere. The App Group is on-device storage shared between two of our + * own processes; the library still never leaves the phone. + */ + +interface WidgetBridgePlugin { + write(options: { json: string }): Promise + cachePoster(options: { name: string; url: string }): Promise +} + +const WidgetBridge = registerPlugin('WidgetBridge') + +interface Entry { + id: string + title: string + status: string + platform?: string + hours?: number + score?: number + cover?: string +} + +/** Five rows fit a large widget and two a medium one; more would only be written. */ +const LIMIT = 5 + +/** + * The widget says the status in the app's own words. Both tracks appear together — a + * game being watched as a longplay is as much "in progress" as one being played, which + * is the whole point of the second track. + */ +const LABEL: Record = { + playing: 'Playing', + watching: 'Watching', + backlog: 'Want to play', + 'to-watch': 'Want to watch', + played: 'Played', + watched: 'Watched', + dropped: 'Dropped', +} + +/** Stable, filesystem-safe name: ids carry a source prefix and a colon. */ +function coverName(gameId: string): string { + return `game-${gameId.replace(/[^\w.-]/g, '-')}.jpg` +} + +function toEntry(game: TrackedGame): Entry { + return { + id: game.id, + title: game.title, + status: LABEL[game.status] ?? game.status, + platform: game.platform ?? game.platforms?.[0], + hours: game.hours, + score: game.metacritic ?? undefined, + cover: game.cover ? coverName(game.id) : undefined, + } +} + +export async function refreshWidgets(): Promise { + if (!isNativeApp()) return + try { + const { games } = useLibrary.getState() + const all = Object.values(games) + + // Most recently started first: the widget answers "what am I in the middle of". + const playing: Entry[] = all + .filter((g) => g.status === 'playing' || g.status === 'watching') + .sort((a, b) => (b.startedAt ?? b.addedAt) - (a.startedAt ?? a.addedAt)) + .slice(0, LIMIT) + .map(toEntry) + + // Oldest first: a backlog sorted newest-first buries the game that has been waiting + // two years under whatever was added yesterday — and that game is the point of a + // backlog. + const backlog: Entry[] = all + .filter((g) => g.status === 'backlog' || g.status === 'to-watch') + .sort((a, b) => a.addedAt - b.addedAt) + .slice(0, LIMIT) + .map(toEntry) + + await WidgetBridge.write({ + json: JSON.stringify({ playing, backlog, updatedAt: Date.now() }), + }) + + // Covers go over after the snapshot: the widget should get its text immediately and + // fill in pictures as they land, rather than wait for both. + for (const game of [...playing, ...backlog]) { + const url = games[game.id]?.cover + if (!game.cover || !url) continue + await WidgetBridge.cachePoster({ name: coverName(game.id), url }).catch(() => {}) + } + } catch (err) { + // A widget that fails to update is not a reason for anything in the app to break, + // but staying silent about it cost an hour once — so it says so where the device log + // can see it. + console.error('[widget] refresh failed', err) + } +}