Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

iPhone: widget extension, Live Activity and Apple Health, native side

Duarte Santos16e791efd67c
diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml
index c7e51e0e0..61722ec9e 100644
--- a/.github/workflows/ios.yml
+++ b/.github/workflows/ios.yml
@@ -45,6 +45,9 @@ jobs:
# The asset pack downloader extension, until the project with it is committed (does nothing then).
- run: ruby ios/ci/add-asset-downloader.rb
working-directory: frontend
+ # The widgets and the Live Activity's extension, likewise until it is committed.
+ - run: ruby ios/ci/add-widgets.rb
+ working-directory: frontend
- name: Build for the simulator
working-directory: frontend/ios/App
run: |
@@ -77,6 +80,23 @@ jobs:
cat build/console.log | grep -v "^\s*$" | head -200
if grep -q "not implemented on ios" build/console.log; then echo "::error::a plugin the page uses is missing on iOS"; exit 1; fi
grep -q "RestAlert" build/console.log || { echo "::error::the page never reached the RestAlert plugin"; exit 1; }
+ echo "$UDID" > build/udid.txt
+ # The widgets and the Live Activity as pictures, light and dark (App/WidgetPreview.swift draws
+ # them with made-up data): nobody can put a widget on a simulator's Home Screen without a Mac.
+ - name: Draw the widgets
+ working-directory: frontend/ios/App
+ run: |
+ UDID=$(cat build/udid.txt)
+ xcrun simctl terminate "$UDID" ch.opengym.app 2>/dev/null || true
+ xcrun simctl launch "$UDID" ch.opengym.app -OpenGymWidgetPreview
+ DATA=$(xcrun simctl get_app_container "$UDID" ch.opengym.app data)
+ for i in $(seq 60); do test -f "$DATA/Documents/widget-preview/done.txt" && break; sleep 2; done
+ mkdir -p build/widgets
+ cp "$DATA"/Documents/widget-preview/*.png build/widgets/ 2>/dev/null || true
+ ls -la build/widgets
+ test -f "$DATA/Documents/widget-preview/done.txt" || { echo "::error::the widget pictures were never drawn"; exit 1; }
+ # The extension really is in the app, with its own Info.plist.
+ test -f build/dd/Build/Products/Debug-iphonesimulator/App.app/PlugIns/OpenGymWidgets.appex/Info.plist || { echo "::error::no widget extension in the app"; exit 1; }
- uses: actions/upload-artifact@v6
if: always()
with:
@@ -85,6 +105,7 @@ jobs:
frontend/ios/App/build/xcodebuild.log
frontend/ios/App/build/console.log
frontend/ios/App/build/first-screen.png
+ frontend/ios/App/build/widgets
retention-days: 7
# A walk through the app in the simulator (ios/App/AppUITests): a rest that ends while the app
@@ -108,6 +129,9 @@ jobs:
working-directory: frontend
- run: ruby ios/ci/add-asset-downloader.rb
working-directory: frontend
+ # The widgets and the Live Activity's extension, likewise until it is committed.
+ - run: ruby ios/ci/add-widgets.rb
+ working-directory: frontend
- run: ruby ios/ci/add-ui-tests.rb
working-directory: frontend
- name: Run the UI tests
@@ -159,6 +183,9 @@ jobs:
working-directory: frontend
- run: ruby ios/ci/add-asset-downloader.rb
working-directory: frontend
+ # The widgets and the Live Activity's extension, likewise until it is committed.
+ - run: ruby ios/ci/add-widgets.rb
+ working-directory: frontend
- name: Archive, unsigned
working-directory: frontend/ios/App
run: |
diff --git a/frontend/ios/App/App.xcodeproj/project.pbxproj b/frontend/ios/App/App.xcodeproj/project.pbxproj
index 4f02ee15d..68ebdc869 100644
--- a/frontend/ios/App/App.xcodeproj/project.pbxproj
+++ b/frontend/ios/App/App.xcodeproj/project.pbxproj
@@ -24,6 +24,12 @@
AA0300000000000000000002 /* DeviceAuthPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0300000000000000000001 /* DeviceAuthPlugin.swift */; };
AA0400000000000000000002 /* AnimationPacksPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0400000000000000000001 /* AnimationPacksPlugin.swift */; };
AA0300000000000000000004 /* NudgeCheckPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0300000000000000000003 /* NudgeCheckPlugin.swift */; };
+ AA0500000000000000000002 /* AppleHealthPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0500000000000000000001 /* AppleHealthPlugin.swift */; };
+ AA0500000000000000000004 /* WidgetBridgePlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0500000000000000000003 /* WidgetBridgePlugin.swift */; };
+ AA0500000000000000000006 /* LiveActivityPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0500000000000000000005 /* LiveActivityPlugin.swift */; };
+ AA0500000000000000000008 /* WorkoutActivity.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0500000000000000000007 /* WorkoutActivity.swift */; };
+ AA0500000000000000000010 /* WidgetViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0500000000000000000009 /* WidgetViews.swift */; };
+ AA0500000000000000000012 /* WidgetPreview.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0500000000000000000011 /* WidgetPreview.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
@@ -49,6 +55,12 @@
AA0400000000000000000001 /* AnimationPacksPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AnimationPacksPlugin.swift; sourceTree = "<group>"; };
AA0400000000000000000003 /* App.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = App.entitlements; sourceTree = "<group>"; };
AA0300000000000000000003 /* NudgeCheckPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NudgeCheckPlugin.swift; sourceTree = "<group>"; };
+ AA0500000000000000000001 /* AppleHealthPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppleHealthPlugin.swift; sourceTree = "<group>"; };
+ AA0500000000000000000003 /* WidgetBridgePlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetBridgePlugin.swift; sourceTree = "<group>"; };
+ AA0500000000000000000005 /* LiveActivityPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LiveActivityPlugin.swift; sourceTree = "<group>"; };
+ AA0500000000000000000007 /* WorkoutActivity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkoutActivity.swift; sourceTree = "<group>"; };
+ AA0500000000000000000009 /* WidgetViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetViews.swift; sourceTree = "<group>"; };
+ AA0500000000000000000011 /* WidgetPreview.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetPreview.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -103,6 +115,12 @@
AA0400000000000000000001 /* AnimationPacksPlugin.swift */,
AA0400000000000000000003 /* App.entitlements */,
AA0300000000000000000003 /* NudgeCheckPlugin.swift */,
+ AA0500000000000000000001 /* AppleHealthPlugin.swift */,
+ AA0500000000000000000003 /* WidgetBridgePlugin.swift */,
+ AA0500000000000000000005 /* LiveActivityPlugin.swift */,
+ AA0500000000000000000007 /* WorkoutActivity.swift */,
+ AA0500000000000000000009 /* WidgetViews.swift */,
+ AA0500000000000000000011 /* WidgetPreview.swift */,
AA0200000000000000000007 /* PrivacyInfo.xcprivacy */,
504EC30B1FED79650016851F /* Main.storyboard */,
504EC30E1FED79650016851F /* Assets.xcassets */,
@@ -248,6 +266,12 @@
AA0300000000000000000002 /* DeviceAuthPlugin.swift in Sources */,
AA0400000000000000000002 /* AnimationPacksPlugin.swift in Sources */,
AA0300000000000000000004 /* NudgeCheckPlugin.swift in Sources */,
+ AA0500000000000000000002 /* AppleHealthPlugin.swift in Sources */,
+ AA0500000000000000000004 /* WidgetBridgePlugin.swift in Sources */,
+ AA0500000000000000000006 /* LiveActivityPlugin.swift in Sources */,
+ AA0500000000000000000008 /* WorkoutActivity.swift in Sources */,
+ AA0500000000000000000010 /* WidgetViews.swift in Sources */,
+ AA0500000000000000000012 /* WidgetPreview.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -392,6 +416,13 @@
IPHONEOS_DEPLOYMENT_TARGET = 15.5;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
MARKETING_VERSION = 1.4.2;
+ OTHER_LDFLAGS = (
+ "$(inherited)",
+ "-weak_framework",
+ ActivityKit,
+ "-weak_framework",
+ AppIntents,
+ );
OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\"";
PRODUCT_BUNDLE_IDENTIFIER = ch.opengym.app;
PRODUCT_NAME = "$(TARGET_NAME)";
@@ -413,6 +444,13 @@
IPHONEOS_DEPLOYMENT_TARGET = 15.5;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
MARKETING_VERSION = 1.4.2;
+ OTHER_LDFLAGS = (
+ "$(inherited)",
+ "-weak_framework",
+ ActivityKit,
+ "-weak_framework",
+ AppIntents,
+ );
PRODUCT_BUNDLE_IDENTIFIER = ch.opengym.app;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "";
diff --git a/frontend/ios/App/App/App.entitlements b/frontend/ios/App/App/App.entitlements
index 02dde9497..645063c6b 100644
--- a/frontend/ios/App/App/App.entitlements
+++ b/frontend/ios/App/App/App.entitlements
@@ -2,6 +2,10 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyLists-1.0.dtd">
<plist version="1.0">
<dict>
+ <key>com.apple.developer.healthkit</key>
+ <true/>
+ <key>com.apple.developer.healthkit.access</key>
+ <array/>
<key>com.apple.security.application-groups</key>
<array>
<string>group.ch.opengym.app</string>
diff --git a/frontend/ios/App/App/AppleHealthPlugin.swift b/frontend/ios/App/App/AppleHealthPlugin.swift
new file mode 100644
index 000000000..a4e277aac
--- /dev/null
+++ b/frontend/ios/App/App/AppleHealthPlugin.swift
@@ -0,0 +1,172 @@
+import Capacitor
+import Foundation
+import HealthKit
+import UIKit
+
+/**
+ * Apple Health on the iPhone, the same calls as HealthConnectPlugin.java (lib/health-sync.js):
+ * finished workouts and weigh-ins go to Apple Health, each with a sync identifier of its own
+ * ('opengym-w-<id>', 'opengym-bw-<day>'), so writing one again replaces it and removing finds
+ * exactly what openGym wrote. It asks to read the heart rate and the body weight too, for the
+ * Apple Watch app's workout session, and keeps the switch where the watch link reads it
+ * (App Group "healthEnabled").
+ *
+ * A workout the Apple Watch app already saved for the same session (same sync identifier, the
+ * watch as its source) is left as it is: it has the heart rate in it, and a second copy would count
+ * the session twice.
+ */
+@objc(AppleHealthPlugin)
+public class AppleHealthPlugin: CAPPlugin, CAPBridgedPlugin {
+ public let identifier = "AppleHealthPlugin"
+ public let jsName = "AppleHealth"
+ public let pluginMethods: [CAPPluginMethod] = [
+ CAPPluginMethod(name: "status", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "requestPermissions", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "write", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "remove", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "openSettings", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "setEnabled", returnType: CAPPluginReturnPromise),
+ ]
+
+ static let enabledKey = "healthEnabled"
+ private let store = HKHealthStore()
+ private var bodyMass: HKQuantityType { HKQuantityType.quantityType(forIdentifier: .bodyMass)! }
+
+ private var shareTypes: Set<HKSampleType> { [HKObjectType.workoutType(), bodyMass] }
+ private var readTypes: Set<HKObjectType> {
+ var types: Set<HKObjectType> = [HKObjectType.workoutType(), bodyMass]
+ if let hr = HKObjectType.quantityType(forIdentifier: .heartRate) { types.insert(hr) }
+ return types
+ }
+
+ /// Saving workouts is what the switch is about; weigh-ins follow when allowed too.
+ private var granted: Bool { store.authorizationStatus(for: HKObjectType.workoutType()) == .sharingAuthorized }
+
+ @objc func status(_ call: CAPPluginCall) {
+ guard HKHealthStore.isHealthDataAvailable() else {
+ call.resolve(["status": "unsupported", "granted": false])
+ return
+ }
+ call.resolve(["status": "available", "granted": granted])
+ }
+
+ @objc func requestPermissions(_ call: CAPPluginCall) {
+ guard HKHealthStore.isHealthDataAvailable() else { call.resolve(["granted": false]); return }
+ store.requestAuthorization(toShare: shareTypes, read: readTypes) { _, _ in
+ call.resolve(["granted": self.granted])
+ }
+ }
+
+ @objc func setEnabled(_ call: CAPPluginCall) {
+ OpenGymGroup.defaults.set(call.getBool("on") ?? false, forKey: AppleHealthPlugin.enabledKey)
+ call.resolve()
+ }
+
+ @objc func openSettings(_ call: CAPPluginCall) {
+ DispatchQueue.main.async {
+ if let url = URL(string: "x-apple-health://") { UIApplication.shared.open(url) }
+ call.resolve()
+ }
+ }
+
+ @objc func write(_ call: CAPPluginCall) {
+ let sessions = (call.getArray("sessions") as? [[String: Any]]) ?? []
+ let weights = (call.getArray("weights") as? [[String: Any]]) ?? []
+ Task {
+ do {
+ guard self.granted else { throw HKError(.errorAuthorizationDenied) }
+ for s in sessions { try await self.saveSession(s) }
+ if self.store.authorizationStatus(for: self.bodyMass) == .sharingAuthorized {
+ let samples = weights.compactMap { self.weightSample($0) }
+ if !samples.isEmpty { try await self.store.save(samples) }
+ }
+ call.resolve()
+ } catch {
+ self.fail(call, error)
+ }
+ }
+ }
+
+ @objc func remove(_ call: CAPPluginCall) {
+ let sessions = (call.getArray("sessions") as? [String]) ?? []
+ let weights = (call.getArray("weights") as? [String]) ?? []
+ Task {
+ do {
+ if !sessions.isEmpty { try await self.delete(HKObjectType.workoutType(), ids: sessions) }
+ if !weights.isEmpty { try await self.delete(self.bodyMass, ids: weights) }
+ call.resolve()
+ } catch {
+ self.fail(call, error)
+ }
+ }
+ }
+
+ private func fail(_ call: CAPPluginCall, _ error: Error) {
+ if let hk = error as? HKError, hk.code == .errorAuthorizationDenied || hk.code == .errorAuthorizationNotDetermined {
+ call.reject("Apple Health permission not granted", "permission")
+ } else if !HKHealthStore.isHealthDataAvailable() {
+ call.reject("Apple Health is not available", "unavailable")
+ } else {
+ call.reject(error.localizedDescription, "failed")
+ }
+ }
+
+ /// Each write a newer version than the last, so Apple Health replaces the one it has.
+ private func syncMetadata(_ id: String) -> [String: Any] {
+ [HKMetadataKeySyncIdentifier: id, HKMetadataKeySyncVersion: NSNumber(value: Int64(Date().timeIntervalSince1970 * 1000))]
+ }
+
+ private static let activityTypes: [String: HKWorkoutActivityType] = [
+ "strength_training": .traditionalStrengthTraining, "walking": .walking, "running": .running,
+ "biking_stationary": .cycling, "elliptical": .elliptical, "stair_climbing_machine": .stairClimbing,
+ "other_workout": .other,
+ ]
+
+ private func saveSession(_ s: [String: Any]) async throws {
+ guard let id = s["id"] as? String,
+ let startMs = (s["start"] as? NSNumber)?.doubleValue, let endMs = (s["end"] as? NSNumber)?.doubleValue, endMs > startMs else { return }
+ if try await watchSaved(id) { return }
+ let config = HKWorkoutConfiguration()
+ config.activityType = AppleHealthPlugin.activityTypes[(s["type"] as? String) ?? ""] ?? .other
+ config.locationType = .indoor
+ let builder = HKWorkoutBuilder(healthStore: store, configuration: config, device: .local())
+ let start = Date(timeIntervalSince1970: startMs / 1000), end = Date(timeIntervalSince1970: endMs / 1000)
+ try await builder.beginCollection(at: start)
+ var meta = syncMetadata(id)
+ if let title = s["title"] as? String, !title.isEmpty { meta["OpenGymTitle"] = title }
+ try await builder.addMetadata(meta)
+ try await builder.endCollection(at: end)
+ _ = try await builder.finishWorkout()
+ }
+
+ /// Whether another app of ours (the Apple Watch app) saved this session already.
+ private func watchSaved(_ id: String) async throws -> Bool {
+ let predicate = HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeySyncIdentifier, allowedValues: [id])
+ let samples: [HKSample] = try await withCheckedThrowingContinuation { cont in
+ let q = HKSampleQuery(sampleType: HKObjectType.workoutType(), predicate: predicate, limit: 5, sortDescriptors: nil) { _, found, error in
+ // Not allowed to read workouts: nothing to compare with, the write goes ahead.
+ if error != nil { cont.resume(returning: []) } else { cont.resume(returning: found ?? []) }
+ }
+ store.execute(q)
+ }
+ let me = Bundle.main.bundleIdentifier ?? ""
+ return samples.contains { $0.sourceRevision.source.bundleIdentifier != me }
+ }
+
+ private func weightSample(_ w: [String: Any]) -> HKQuantitySample? {
+ guard let id = w["id"] as? String, let time = (w["time"] as? NSNumber)?.doubleValue,
+ let kg = (w["kg"] as? NSNumber)?.doubleValue, kg > 0 else { return nil }
+ let at = Date(timeIntervalSince1970: time / 1000)
+ return HKQuantitySample(type: bodyMass, quantity: HKQuantity(unit: .gramUnit(with: .kilo), doubleValue: kg),
+ start: at, end: at, metadata: syncMetadata(id))
+ }
+
+ private func delete(_ type: HKObjectType, ids: [String]) async throws {
+ let predicate = HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeySyncIdentifier, allowedValues: ids)
+ try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Void, Error>) in
+ store.deleteObjects(of: type, predicate: predicate) { _, _, error in
+ if let error = error { cont.resume(throwing: error) } else { cont.resume() }
+ }
+ }
+ }
+}
diff --git a/frontend/ios/App/App/Info.plist b/frontend/ios/App/App/Info.plist
index 579309aeb..31b868638 100644
--- a/frontend/ios/App/App/Info.plist
+++ b/frontend/ios/App/App/Info.plist
@@ -92,6 +92,12 @@
<array>
<string>fetch</string>
</array>
+ <key>NSSupportsLiveActivities</key>
+ <true/>
+ <key>NSHealthShareUsageDescription</key>
+ <string>Used to show your heart rate on your Apple Watch while you train, next to each set.</string>
+ <key>NSHealthUpdateUsageDescription</key>
+ <string>Used to save your finished workouts and weigh-ins to Apple Health, when you switch it on.</string>
<key>NSFaceIDUsageDescription</key>
<string>Used to make sure it’s really you before your account is deleted.</string>
</dict>
diff --git a/frontend/ios/App/App/LiveActivityPlugin.swift b/frontend/ios/App/App/LiveActivityPlugin.swift
new file mode 100644
index 000000000..2a2bef559
--- /dev/null
+++ b/frontend/ios/App/App/LiveActivityPlugin.swift
@@ -0,0 +1,98 @@
+import ActivityKit
+import Capacitor
+import Foundation
+
+/**
+ * The running workout's Live Activity, for the page (lib/live-activity.js). The page sends the
+ * whole activity whenever it changes; this starts it for a new workout, updates it for the same
+ * one, and ends it with the workout. The Done button's taps (WorkoutActivity.swift DoneSetIntent)
+ * wait in LiveActivityQueue until the page drains and acknowledges them; a "liveActivityEvent"
+ * tells a page that is awake that one came in.
+ *
+ * iOS 17 and later (the interactive Done button); earlier, status says unsupported and the page
+ * sends nothing.
+ */
+@objc(LiveActivityPlugin)
+public class LiveActivityPlugin: CAPPlugin, CAPBridgedPlugin {
+ public let identifier = "LiveActivityPlugin"
+ public let jsName = "LiveActivity"
+ public let pluginMethods: [CAPPluginMethod] = [
+ CAPPluginMethod(name: "status", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "update", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "end", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "drain", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "ack", returnType: CAPPluginReturnPromise),
+ ]
+
+ override public func load() {
+ NotificationCenter.default.addObserver(self, selector: #selector(queued), name: LiveActivityQueue.didChange, object: nil)
+ }
+
+ deinit {
+ NotificationCenter.default.removeObserver(self)
+ }
+
+ @objc private func queued() {
+ notifyListeners("liveActivityEvent", data: [:])
+ }
+
+ @objc func status(_ call: CAPPluginCall) {
+ if #available(iOS 17.0, *) {
+ call.resolve(["supported": ActivityAuthorizationInfo().areActivitiesEnabled])
+ } else {
+ call.resolve(["supported": false])
+ }
+ }
+
+ @objc func update(_ call: CAPPluginCall) {
+ guard #available(iOS 17.0, *) else { call.resolve(["shown": false]); return }
+ let decoder = JSONDecoder()
+ guard let a = call.getString("attributes")?.data(using: .utf8),
+ let s = call.getString("state")?.data(using: .utf8),
+ let attributes = try? decoder.decode(WorkoutActivityAttributes.self, from: a),
+ let state = try? decoder.decode(WorkoutActivityAttributes.ContentState.self, from: s) else {
+ call.reject("attributes and state are required")
+ return
+ }
+ Task {
+ let content = ActivityContent(state: state, staleDate: nil)
+ let all = Activity<WorkoutActivityAttributes>.activities
+ // Another workout's activity (a session that ended while the app was gone) goes first.
+ for other in all where other.attributes.wid != attributes.wid {
+ await other.end(nil, dismissalPolicy: .immediate)
+ }
+ if let mine = all.first(where: { $0.attributes.wid == attributes.wid && $0.activityState == .active }) {
+ await mine.update(content)
+ call.resolve(["shown": true])
+ return
+ }
+ do {
+ _ = try Activity.request(attributes: attributes, content: content, pushType: nil)
+ call.resolve(["shown": true])
+ } catch {
+ // Switched off in Settings, or the app is not in front: the next change tries again.
+ call.resolve(["shown": false])
+ }
+ }
+ }
+
+ @objc func end(_ call: CAPPluginCall) {
+ guard #available(iOS 17.0, *) else { call.resolve(); return }
+ Task {
+ for activity in Activity<WorkoutActivityAttributes>.activities {
+ await activity.end(nil, dismissalPolicy: .immediate)
+ }
+ call.resolve()
+ }
+ }
+
+ @objc func drain(_ call: CAPPluginCall) {
+ call.resolve(["events": LiveActivityQueue.all()])
+ }
+
+ @objc func ack(_ call: CAPPluginCall) {
+ let ids = (call.getArray("ids") as? [String]) ?? []
+ LiveActivityQueue.remove(ids: Set(ids))
+ call.resolve()
+ }
+}
diff --git a/frontend/ios/App/App/MainViewController.swift b/frontend/ios/App/App/MainViewController.swift
index 46cf0e14b..ecd4edea0 100644
--- a/frontend/ios/App/App/MainViewController.swift
+++ b/frontend/ios/App/App/MainViewController.swift
@@ -14,6 +14,10 @@ class MainViewController: CAPBridgeViewController {
bridge?.registerPluginInstance(DeviceAuthPlugin())
bridge?.registerPluginInstance(AnimationPacksPlugin())
bridge?.registerPluginInstance(NudgeCheckPlugin())
+ bridge?.registerPluginInstance(AppleHealthPlugin())
+ bridge?.registerPluginInstance(WidgetBridgePlugin())
+ bridge?.registerPluginInstance(LiveActivityPlugin())
+ WidgetPreview.runIfAsked()
// After loadView has finished: the view is the web view only once it has.
if ProcessInfo.processInfo.arguments.contains(MainViewController.pendingProbeArgument) {
DispatchQueue.main.async { [weak self] in self?.showPendingProbe() }
diff --git a/frontend/ios/App/App/WidgetBridgePlugin.swift b/frontend/ios/App/App/WidgetBridgePlugin.swift
new file mode 100644
index 000000000..c80a6b656
--- /dev/null
+++ b/frontend/ios/App/App/WidgetBridgePlugin.swift
@@ -0,0 +1,37 @@
+import Capacitor
+import Foundation
+import WidgetKit
+
+/**
+ * Hands the Home Screen and Lock Screen widgets what they show (lib/widgets.js builds it): a small
+ * JSON file in the App Group, which the widget extension reads (OpenGymWidgets), and a nudge to
+ * WidgetKit to draw them again. The page only writes when something the widgets show changed.
+ */
+@objc(WidgetBridgePlugin)
+public class WidgetBridgePlugin: CAPPlugin, CAPBridgedPlugin {
+ public let identifier = "WidgetBridgePlugin"
+ public let jsName = "WidgetBridge"
+ public let pluginMethods: [CAPPluginMethod] = [
+ CAPPluginMethod(name: "write", returnType: CAPPluginReturnPromise),
+ ]
+
+ static let fileName = "widget.json"
+
+ @objc func write(_ call: CAPPluginCall) {
+ guard let json = call.getString("json"), let data = json.data(using: .utf8) else {
+ call.reject("json is required")
+ return
+ }
+ guard let dir = OpenGymGroup.container else {
+ call.reject("no App Group")
+ return
+ }
+ do {
+ try data.write(to: dir.appendingPathComponent(WidgetBridgePlugin.fileName), options: .atomic)
+ WidgetCenter.shared.reloadAllTimelines()
+ call.resolve()
+ } catch {
+ call.reject("could not write the widget data")
+ }
+ }
+}
diff --git a/frontend/ios/App/App/WidgetPreview.swift b/frontend/ios/App/App/WidgetPreview.swift
new file mode 100644
index 000000000..54794f454
--- /dev/null
+++ b/frontend/ios/App/App/WidgetPreview.swift
@@ -0,0 +1,114 @@
+import SwiftUI
+import UIKit
+
+/**
+ * For CI only (.github/workflows/ios.yml): started with -OpenGymWidgetPreview, the app draws the
+ * widgets and the Live Activity (WidgetViews.swift, the same views the widget extension shows)
+ * with made-up data into PNG files in Documents/widget-preview, light and dark, and writes
+ * done.txt when it is through. Nobody without a Mac can put a widget on a simulator's Home
+ * Screen, so this is how a change to them is seen. Never runs otherwise: nothing but the CI step
+ * passes the argument.
+ */
+enum WidgetPreview {
+ static let argument = "-OpenGymWidgetPreview"
+
+ static func runIfAsked() {
+ guard ProcessInfo.processInfo.arguments.contains(argument) else { return }
+ if #available(iOS 17.0, *) {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1) { render() }
+ }
+ }
+
+ @available(iOS 17.0, *)
+ private static func decode<T: Decodable>(_ type: T.Type, _ json: String) -> T? {
+ try? JSONDecoder().decode(type, from: Data(json.utf8))
+ }
+
+ @available(iOS 17.0, *)
+ private static func snapshot(today: String, active: String = "null") -> WidgetSnapshot? {
+ decode(WidgetSnapshot.self, """
+ {"v":1,"today":"\(today)","weekFrom":"\(today)","weekUntil":"9999-12-31","unit":"kg","accent":"#30d158","ink":"#000000",
+ "days":[{"iso":"\(today)","weekday":"Wednesday","name":"Push Day","count":5,"done":false,"exercises":[
+ {"name":"Barbell Bench Press","line":"4 × 6 · 80 kg"},{"name":"Overhead Press","line":"3 × 8 · 45 kg"},
+ {"name":"Incline Dumbbell Press","line":"3 × 10 · 26 kg"},{"name":"Lateral Raise","line":"3 × 15 · 10 kg"},
+ {"name":"Triceps Pushdown","line":"3 × 12 · 30 kg"}]},
+ {"iso":"9999-12-30","weekday":"Friday","name":"Leg Day","count":4}],
+ "week":{"done":2,"planned":4},"streak":7,"lastPR":{"name":"Barbell Squat","value":"120 kg","d":"\(today)"},
+ "active":\(active),
+ "labels":{"today":"Today","restDay":"Rest day","upNext":"Up next","thisWeek":"This week","weekStreak":"Week streak",
+ "streak":"7 week streak","lastPR":"Last PR","done":"Done","running":"Workout running"}}
+ """)
+ }
+
+ @available(iOS 17.0, *)
+ private static func live(rest: Bool) -> (WorkoutActivityAttributes, WorkoutActivityAttributes.ContentState)? {
+ let end = (Date().timeIntervalSince1970 + 75) * 1000
+ guard let a = decode(WorkoutActivityAttributes.self, """
+ {"v":1,"wid":"preview","start":null,"accent":"#30d158","ink":"#000000",
+ "labels":{"done":"Done","rest":"Rest","next":"Up next","allDone":"All sets done","restOver":"Rest’s over. Next set!"}}
+ """), let s = decode(WorkoutActivityAttributes.ContentState.self, """
+ {"name":"Push Day","cur":{"exId":"0025","entryIdx":0,"setIdx":2,"exName":"Barbell Bench Press","setLine":"Set 3 of 4",
+ "target":"80 kg × 6","restAfter":120},"ahead":[],"restEndsAt":\(rest ? String(end) : "null"),"restLeft":null,
+ "restTotal":\(rest ? "120" : "null"),"done":6,"total":17}
+ """) else { return nil }
+ return (a, s)
+ }
+
+ @available(iOS 17.0, *)
+ @MainActor
+ private static func render() {
+ let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
+ let dir = docs.appendingPathComponent("widget-preview")
+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ let now = Date()
+ let today = WidgetModel.isoDay(now)
+ let plan = WidgetModel(snap: snapshot(today: today), date: now)
+ let restDay = WidgetModel(snap: snapshot(today: today).map { var s = $0; s.days.removeFirst(); return s }, date: now)
+ let running = WidgetModel(snap: snapshot(today: today, active: #"{"id":"a","name":"Push Day","start":\#((now.timeIntervalSince1970 - 1500) * 1000),"done":6,"total":17}"#), date: now)
+ let empty = WidgetModel(snap: nil, date: now)
+
+ func save<V: View>(_ name: String, _ size: CGSize, dark: Bool, radius: CGFloat = 22, padding: CGFloat = 16, @ViewBuilder _ view: () -> V) {
+ let framed = view()
+ .padding(padding)
+ .frame(width: size.width, height: size.height)
+ .background(Color(UIColor.systemBackground))
+ .clipShape(RoundedRectangle(cornerRadius: radius, style: .continuous))
+ .environment(\.colorScheme, dark ? .dark : .light)
+ let r = ImageRenderer(content: framed)
+ r.scale = 3
+ if let data = r.uiImage?.pngData() {
+ try? data.write(to: dir.appendingPathComponent("\(name)-\(dark ? "dark" : "light").png"))
+ }
+ }
+
+ for dark in [false, true] {
+ save("small-plan", CGSize(width: 170, height: 170), dark: dark) { SmallWidgetView(model: plan) }
+ save("small-rest-day", CGSize(width: 170, height: 170), dark: dark) { SmallWidgetView(model: restDay) }
+ save("small-running", CGSize(width: 170, height: 170), dark: dark) { SmallWidgetView(model: running) }
+ save("small-empty", CGSize(width: 170, height: 170), dark: dark) { SmallWidgetView(model: empty) }
+ save("medium", CGSize(width: 364, height: 170), dark: dark) { MediumWidgetView(model: plan) }
+ save("large", CGSize(width: 364, height: 382), dark: dark) { LargeWidgetView(model: plan) }
+ if case let (a, s)? = live(rest: false) {
+ save("live-lock", CGSize(width: 370, height: 150), dark: dark, radius: 24, padding: 0) { LiveLockView(attributes: a, state: s) }
+ }
+ if case let (a, s)? = live(rest: true) {
+ save("live-lock-resting", CGSize(width: 370, height: 150), dark: dark, radius: 24, padding: 0) { LiveLockView(attributes: a, state: s) }
+ }
+ }
+ // The Lock Screen's accessories and the Dynamic Island are drawn light on dark.
+ save("lock-rect", CGSize(width: 172, height: 76), dark: true, radius: 12, padding: 6) { NextRectView(model: plan) }
+ save("lock-circle", CGSize(width: 76, height: 76), dark: true, radius: 38, padding: 0) { StreakCircleView(model: plan) }
+ save("lock-inline", CGSize(width: 260, height: 30), dark: true, radius: 6, padding: 4) { NextInlineView(model: plan) }
+ if case let (a, s)? = live(rest: true) {
+ save("island-compact", CGSize(width: 250, height: 37), dark: true, radius: 18.5, padding: 8) {
+ HStack {
+ Image(systemName: "dumbbell.fill").foregroundStyle(Color(hex: a.accent) ?? .green)
+ Spacer()
+ LiveCompactTrailing(attributes: a, state: s)
+ }
+ }
+ save("island-minimal", CGSize(width: 37, height: 37), dark: true, radius: 18.5, padding: 2) { LiveMinimal(attributes: a, state: s) }
+ }
+ try? "done".write(to: dir.appendingPathComponent("done.txt"), atomically: true, encoding: .utf8)
+ }
+}
diff --git a/frontend/ios/App/App/WidgetViews.swift b/frontend/ios/App/App/WidgetViews.swift
new file mode 100644
index 000000000..95b9bee6b
--- /dev/null
+++ b/frontend/ios/App/App/WidgetViews.swift
@@ -0,0 +1,484 @@
+import SwiftUI
+import UIKit
+import WidgetKit
+
+/*
+ * What the Home Screen and Lock Screen widgets and the workout's Live Activity look like.
+ * Compiled into the widget extension, which shows them (OpenGymWidgets), and into the app, which
+ * only draws them into pictures for CI when started with -OpenGymWidgetPreview
+ * (WidgetPreview.swift). Text and SF Symbols only: no exercise animations or pictures (Gym visual
+ * licence). The words come from the page in the app's language (lib/widgets.js).
+ */
+
+// MARK: - the snapshot (lib/widgets.js buildWidgetSnapshot)
+
+@available(iOS 17.0, *)
+struct WidgetSnapshot: Codable {
+ struct Exercise: Codable, Hashable { var name: String; var line: String? }
+ struct Day: Codable, Hashable {
+ var iso: String
+ var weekday: String?
+ var name: String?
+ var count: Int?
+ var exercises: [Exercise]?
+ var done: Bool?
+ }
+ struct Week: Codable { var done: Int; var planned: Int }
+ struct PR: Codable { var name: String; var value: String?; var d: String? }
+ struct Active: Codable { var id: String?; var name: String?; var start: Double?; var done: Int; var total: Int }
+ struct Labels: Codable {
+ var today: String?
+ var restDay: String?
+ var upNext: String?
+ var thisWeek: String?
+ var weekStreak: String?
+ var streak: String?
+ var lastPR: String?
+ var done: String?
+ var running: String?
+ }
+
+ var v: Int
+ var today: String
+ var weekFrom: String?
+ var weekUntil: String?
+ var accent: String?
+ var ink: String?
+ var days: [Day]
+ var week: Week?
+ var streak: Int?
+ var lastPR: PR?
+ var active: Active?
+ var labels: Labels?
+
+ static func load() -> WidgetSnapshot? {
+ guard let url = OpenGymGroup.container?.appendingPathComponent("widget.json"),
+ let data = try? Data(contentsOf: url) else { return nil }
+ return try? JSONDecoder().decode(WidgetSnapshot.self, from: data)
+ }
+}
+
+/// The snapshot as of one moment: the day it is then, the next day with a plan, this week.
+@available(iOS 17.0, *)
+struct WidgetModel {
+ let snap: WidgetSnapshot?
+ let date: Date
+
+ static func isoDay(_ d: Date) -> String {
+ let c = Calendar.current.dateComponents([.year, .month, .day], from: d)
+ return String(format: "%04d-%02d-%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0)
+ }
+
+ var iso: String { WidgetModel.isoDay(date) }
+ var labels: WidgetSnapshot.Labels { snap?.labels ?? WidgetSnapshot.Labels() }
+ var day: WidgetSnapshot.Day? { snap?.days.first { $0.iso == iso } }
+ var next: WidgetSnapshot.Day? { snap?.days.first { $0.iso > iso && $0.name != nil } }
+ /// A workout running now; one from a day gone by is stale (the app ends it when it opens).
+ var active: WidgetSnapshot.Active? { snap?.today == iso ? snap?.active : nil }
+ var weekDone: Int {
+ guard let w = snap?.week else { return 0 }
+ if let until = snap?.weekUntil, iso >= until { return 0 }
+ return w.done
+ }
+ var weekPlanned: Int { snap?.week?.planned ?? 0 }
+ var streak: Int { snap?.streak ?? 0 }
+ var accent: Color { Color(hex: snap?.accent) ?? Color(red: 0.19, green: 0.82, blue: 0.35) }
+}
+
+@available(iOS 17.0, *)
+extension Color {
+ func darker(_ by: CGFloat) -> Color {
+ var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
+ UIColor(self).getRed(&r, green: &g, blue: &b, alpha: &a)
+ return Color(red: r * (1 - by), green: g * (1 - by), blue: b * (1 - by))
+ }
+
+ init?(hex: String?) {
+ guard let hex = hex, hex.count == 7, hex.hasPrefix("#"), let n = UInt32(hex.dropFirst(), radix: 16) else { return nil }
+ self.init(red: Double((n >> 16) & 255) / 255, green: Double((n >> 8) & 255) / 255, blue: Double(n & 255) / 255)
+ }
+}
+
+/// The accent, a shade darker on a light background so it still reads there.
+@available(iOS 17.0, *)
+struct AccentText: ViewModifier {
+ @Environment(\.colorScheme) private var scheme
+ let color: Color
+ func body(content: Content) -> some View {
+ content.foregroundStyle(scheme == .light ? color.darker(0.28) : color)
+ }
+}
+
+@available(iOS 17.0, *)
+extension View {
+ func accentText(_ color: Color) -> some View { modifier(AccentText(color: color)) }
+}
+
+// MARK: - pieces
+
+/// A slim bar in the accent (drawn by SwiftUI itself, so it also renders into CI's pictures).
+@available(iOS 17.0, *)
+struct ProgressBar: View {
+ let value: Double
+ let accent: Color
+
+ var body: some View {
+ GeometryReader { g in
+ ZStack(alignment: .leading) {
+ Capsule().fill(accent.opacity(0.22))
+ Capsule().fill(accent).frame(width: max(6, g.size.width * min(1, max(0, value))))
+ }
+ }
+ .frame(height: 6)
+ }
+}
+
+@available(iOS 17.0, *)
+struct WeekRing: View {
+ let done: Int
+ let planned: Int
+ let accent: Color
+ var size: CGFloat = 56
+
+ var body: some View {
+ let frac = planned > 0 ? min(1, Double(done) / Double(planned)) : (done > 0 ? 1 : 0)
+ ZStack {
+ Circle().stroke(accent.opacity(0.22), lineWidth: size / 7)
+ Circle().trim(from: 0, to: frac)
+ .stroke(accent, style: StrokeStyle(lineWidth: size / 7, lineCap: .round))
+ .rotationEffect(.degrees(-90))
+ Text(planned > 0 ? "\(done)/\(planned)" : "\(done)")
+ .font(.system(size: size / 4, weight: .bold, design: .rounded))
+ .monospacedDigit()
+ .minimumScaleFactor(0.6)
+ }
+ .frame(width: size, height: size)
+ }
+}
+
+@available(iOS 17.0, *)
+struct TodayHeader: View {
+ let model: WidgetModel
+
+ var body: some View {
+ HStack(spacing: 5) {
+ Image(systemName: "dumbbell.fill").font(.caption2.weight(.bold)).accentText(model.accent)
+ Text((model.active != nil ? model.labels.running : model.labels.today) ?? "Today")
+ .font(.caption2.weight(.semibold))
+ .textCase(.uppercase)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ Spacer(minLength: 0)
+ }
+ }
+}
+
+/// Today in a few lines: the running workout, today's plan, or the rest day and what comes next.
+@available(iOS 17.0, *)
+struct TodayBlock: View {
+ let model: WidgetModel
+ var big = false
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 3) {
+ if let a = model.active {
+ Text(a.name ?? "").font(big ? .title2.weight(.bold) : .headline).lineLimit(2).minimumScaleFactor(0.8)
+ if let start = a.start {
+ Text(Date(timeIntervalSince1970: start / 1000), style: .timer)
+ .font(.title3.weight(.semibold)).monospacedDigit().accentText(model.accent)
+ }
+ ProgressBar(value: Double(a.done) / Double(max(1, a.total)), accent: model.accent)
+ } else if let d = model.day, let name = d.name {
+ Text(name).font(big ? .title2.weight(.bold) : .title3.weight(.bold)).lineLimit(2).minimumScaleFactor(0.75)
+ if d.done == true {
+ Label(model.labels.done ?? "Done", systemImage: "checkmark.circle.fill")
+ .font(.caption.weight(.semibold)).accentText(model.accent)
+ } else if let n = d.count, n > 0 {
+ Label("\(n)", systemImage: "list.bullet").font(.caption).foregroundStyle(.secondary)
+ }
+ } else {
+ Text(model.labels.restDay ?? "Rest day").font(big ? .title2.weight(.bold) : .title3.weight(.bold)).lineLimit(1).minimumScaleFactor(0.75)
+ if let n = model.next {
+ Text("\(model.labels.upNext ?? "Up next"): \(n.weekday ?? "")")
+ .font(.caption).foregroundStyle(.secondary).lineLimit(1)
+ Text(n.name ?? "").font(.caption.weight(.semibold)).lineLimit(1)
+ }
+ }
+ }
+ }
+}
+
+@available(iOS 17.0, *)
+struct StreakLine: View {
+ let model: WidgetModel
+ var body: some View {
+ Label {
+ Text(model.labels.streak ?? "\(model.streak)").lineLimit(1).minimumScaleFactor(0.7)
+ } icon: {
+ Image(systemName: "flame.fill").foregroundStyle(.orange)
+ }
+ .font(.caption.weight(.semibold))
+ }
+}
+
+// MARK: - the widgets
+
+/// Placeholder before the app wrote anything.
+@available(iOS 17.0, *)
+struct WidgetEmpty: View {
+ var body: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ Image(systemName: "dumbbell.fill").font(.title3).foregroundStyle(.secondary)
+ Text("Open openGym once to see your plan here.").font(.caption).foregroundStyle(.secondary)
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
+ }
+}
+
+@available(iOS 17.0, *)
+struct SmallWidgetView: View {
+ let model: WidgetModel
+ var body: some View {
+ if model.snap == nil { WidgetEmpty() } else {
+ VStack(alignment: .leading, spacing: 0) {
+ TodayHeader(model: model)
+ Spacer(minLength: 4)
+ TodayBlock(model: model)
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
+ }
+ }
+}
+
+@available(iOS 17.0, *)
+struct MediumWidgetView: View {
+ let model: WidgetModel
+ var body: some View {
+ if model.snap == nil { WidgetEmpty() } else {
+ HStack(alignment: .top, spacing: 14) {
+ SmallWidgetView(model: model)
+ VStack(spacing: 8) {
+ Text(model.labels.thisWeek ?? "This week").font(.caption2.weight(.semibold)).textCase(.uppercase).foregroundStyle(.secondary).lineLimit(1)
+ WeekRing(done: model.weekDone, planned: model.weekPlanned, accent: model.accent)
+ StreakLine(model: model)
+ }
+ .frame(width: 112)
+ }
+ }
+ }
+}
+
+@available(iOS 17.0, *)
+struct LargeWidgetView: View {
+ let model: WidgetModel
+ var body: some View {
+ if model.snap == nil { WidgetEmpty() } else {
+ VStack(alignment: .leading, spacing: 10) {
+ HStack(alignment: .top) {
+ VStack(alignment: .leading, spacing: 4) {
+ TodayHeader(model: model)
+ TodayBlock(model: model, big: true)
+ }
+ Spacer(minLength: 8)
+ WeekRing(done: model.weekDone, planned: model.weekPlanned, accent: model.accent, size: 50)
+ }
+ if model.active == nil, let list = model.day?.exercises, !list.isEmpty {
+ VStack(alignment: .leading, spacing: 6) {
+ ForEach(Array(list.enumerated()), id: \.offset) { _, ex in
+ HStack(spacing: 8) {
+ Circle().fill(model.accent).frame(width: 6, height: 6)
+ Text(ex.name).font(.subheadline).lineLimit(1)
+ Spacer(minLength: 6)
+ Text(ex.line ?? "").font(.caption).foregroundStyle(.secondary).lineLimit(1)
+ }
+ }
+ }
+ }
+ Spacer(minLength: 0)
+ Divider()
+ HStack(alignment: .center) {
+ StreakLine(model: model)
+ Spacer(minLength: 8)
+ if let pr = model.snap?.lastPR {
+ Label {
+ VStack(alignment: .trailing, spacing: 0) {
+ Text(model.labels.lastPR ?? "Last PR").font(.caption2).foregroundStyle(.secondary)
+ Text([pr.name, pr.value ?? ""].filter { !$0.isEmpty }.joined(separator: " · "))
+ .font(.caption.weight(.semibold)).lineLimit(1)
+ }
+ } icon: {
+ Image(systemName: "trophy.fill").foregroundStyle(.yellow)
+ }
+ }
+ }
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
+ }
+ }
+}
+
+/// Lock Screen, round: the streak.
+@available(iOS 17.0, *)
+struct StreakCircleView: View {
+ let model: WidgetModel
+ var body: some View {
+ ZStack {
+ Circle().fill(.fill.tertiary)
+ VStack(spacing: -1) {
+ Image(systemName: "flame.fill").font(.system(size: 13, weight: .bold)).widgetAccentable()
+ Text("\(model.streak)").font(.system(size: 22, weight: .bold, design: .rounded)).minimumScaleFactor(0.5)
+ }
+ }
+ .accessibilityLabel(model.labels.streak ?? "\(model.streak)")
+ }
+}
+
+/// Lock Screen, wide: the next workout (or the one running).
+@available(iOS 17.0, *)
+struct NextRectView: View {
+ let model: WidgetModel
+ var body: some View {
+ VStack(alignment: .leading, spacing: 1) {
+ if let a = model.active {
+ Text(model.labels.running ?? "").font(.caption.weight(.semibold)).widgetAccentable().lineLimit(1)
+ Text(a.name ?? "").font(.headline).lineLimit(1)
+ if let start = a.start { Text(Date(timeIntervalSince1970: start / 1000), style: .timer).font(.caption).monospacedDigit() }
+ } else if let d = model.day, let name = d.name, d.done != true {
+ Label(model.labels.today ?? "Today", systemImage: "dumbbell.fill").font(.caption.weight(.semibold)).widgetAccentable().lineLimit(1)
+ Text(name).font(.headline).lineLimit(2)
+ } else if let n = model.next {
+ Label("\(model.labels.upNext ?? "Up next") · \(n.weekday ?? "")", systemImage: "calendar").font(.caption.weight(.semibold)).widgetAccentable().lineLimit(1)
+ Text(n.name ?? "").font(.headline).lineLimit(2)
+ } else {
+ Label(model.labels.restDay ?? "Rest day", systemImage: "moon.zzz.fill").font(.headline).lineLimit(1)
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+}
+
+@available(iOS 17.0, *)
+struct NextInlineView: View {
+ let model: WidgetModel
+ var body: some View {
+ if let a = model.active {
+ Label(a.name ?? "", systemImage: "dumbbell.fill")
+ } else if let d = model.day, let name = d.name, d.done != true {
+ Label("\(model.labels.today ?? "Today"): \(name)", systemImage: "dumbbell.fill")
+ } else if let n = model.next {
+ Label("\(n.weekday ?? ""): \(n.name ?? "")", systemImage: "calendar")
+ } else {
+ Label(model.labels.restDay ?? "Rest day", systemImage: "moon.zzz.fill")
+ }
+ }
+}
+
+// MARK: - the Live Activity
+
+@available(iOS 17.0, *)
+struct LiveRest: View {
+ let attributes: WorkoutActivityAttributes
+ let state: WorkoutActivityAttributes.ContentState
+ var font: Font = .title2
+
+ var body: some View {
+ let accent = Color(hex: attributes.accent) ?? .green
+ if let range = state.restRange {
+ Text(timerInterval: range, countsDown: true)
+ .font(font.weight(.bold)).monospacedDigit()
+ .multilineTextAlignment(.trailing)
+ .foregroundStyle(accent)
+ } else if let left = state.restLeft {
+ Label(String(format: "%d:%02d", Int(left) / 60, Int(left) % 60), systemImage: "pause.fill")
+ .font(font.weight(.bold)).monospacedDigit()
+ .foregroundStyle(.secondary)
+ }
+ }
+}
+
+@available(iOS 17.0, *)
+struct LiveDoneButton: View {
+ let attributes: WorkoutActivityAttributes
+ let cur: WorkoutActivityAttributes.SetInfo
+
+ var body: some View {
+ Button(intent: DoneSetIntent(wid: attributes.wid, exId: cur.exId, entryIdx: cur.entryIdx, setIdx: cur.setIdx)) {
+ Label(attributes.labels.done, systemImage: "checkmark")
+ .font(.subheadline.weight(.semibold))
+ .foregroundStyle(Color(hex: attributes.ink) ?? .black)
+ }
+ .buttonStyle(.borderedProminent)
+ .tint(Color(hex: attributes.accent) ?? .green)
+ }
+}
+
+/// The Lock Screen's (and a watch Smart Stack's, through the compact views) workout.
+@available(iOS 17.0, *)
+struct LiveLockView: View {
+ let attributes: WorkoutActivityAttributes
+ let state: WorkoutActivityAttributes.ContentState
+
+ var body: some View {
+ let accent = Color(hex: attributes.accent) ?? .green
+ VStack(alignment: .leading, spacing: 10) {
+ HStack(alignment: .top, spacing: 10) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(state.cur?.exName ?? attributes.labels.allDone).font(.headline).lineLimit(1)
+ if let c = state.cur {
+ Text([c.setLine, c.target].filter { !$0.isEmpty }.joined(separator: " · "))
+ .font(.subheadline).foregroundStyle(.secondary).lineLimit(1)
+ } else {
+ Text(state.name).font(.subheadline).foregroundStyle(.secondary).lineLimit(1)
+ }
+ }
+ Spacer(minLength: 6)
+ if state.restRange != nil || state.restLeft != nil {
+ VStack(alignment: .trailing, spacing: 0) {
+ Text(attributes.labels.rest).font(.caption2.weight(.semibold)).textCase(.uppercase).foregroundStyle(.secondary)
+ LiveRest(attributes: attributes, state: state).frame(maxWidth: 96, alignment: .trailing)
+ }
+ }
+ }
+ HStack(spacing: 10) {
+ ProgressBar(value: Double(state.done) / Double(max(1, state.total)), accent: accent)
+ Text("\(state.done)/\(state.total)").font(.caption.weight(.semibold)).monospacedDigit().foregroundStyle(.secondary)
+ if let c = state.cur { LiveDoneButton(attributes: attributes, cur: c) }
+ }
+ }
+ .padding(16)
+ }
+}
+
+/// The Dynamic Island's small sides: the rest counting down, or how far along the session is.
+@available(iOS 17.0, *)
+struct LiveCompactTrailing: View {
+ let attributes: WorkoutActivityAttributes
+ let state: WorkoutActivityAttributes.ContentState
+
+ var body: some View {
+ if state.restRange != nil || state.restLeft != nil {
+ LiveRest(attributes: attributes, state: state, font: .caption).frame(width: 46)
+ } else {
+ Text("\(state.done)/\(state.total)").font(.caption.weight(.bold)).monospacedDigit()
+ .foregroundStyle(Color(hex: attributes.accent) ?? .green)
+ }
+ }
+}
+
+@available(iOS 17.0, *)
+struct LiveMinimal: View {
+ let attributes: WorkoutActivityAttributes
+ let state: WorkoutActivityAttributes.ContentState
+
+ var body: some View {
+ if let range = state.restRange {
+ Text(timerInterval: range, countsDown: true, showsHours: false)
+ .font(.caption2.weight(.bold)).monospacedDigit()
+ .multilineTextAlignment(.center)
+ .foregroundStyle(Color(hex: attributes.accent) ?? .green)
+ .frame(width: 34)
+ } else {
+ Image(systemName: "dumbbell.fill").foregroundStyle(Color(hex: attributes.accent) ?? .green)
+ }
+ }
+}
diff --git a/frontend/ios/App/App/WorkoutActivity.swift b/frontend/ios/App/App/WorkoutActivity.swift
new file mode 100644
index 000000000..af60c3fcc
--- /dev/null
+++ b/frontend/ios/App/App/WorkoutActivity.swift
@@ -0,0 +1,186 @@
+import ActivityKit
+import AppIntents
+import Foundation
+import UserNotifications
+
+/*
+ * The running workout's Live Activity: what it carries, and its Done button. Compiled into both
+ * the app and the widget extension (ios/ci/add-widgets.rb): the extension draws it
+ * (OpenGymWidgets/LiveActivityWidget.swift), the app starts and updates it for the page
+ * (LiveActivityPlugin.swift, lib/live-activity.js) and runs the Done button's intent.
+ *
+ * The page sends both halves as JSON; the field names are lib/live-activity.js buildLiveActivity's.
+ * Text only: no exercise animations or pictures (Gym visual licence).
+ */
+
+/// The App Group the app, the widget extension and the asset pack downloader share.
+enum OpenGymGroup {
+ static let id = "group.ch.opengym.app"
+ static var defaults: UserDefaults { UserDefaults(suiteName: id) ?? .standard }
+ static var container: URL? { FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: id) }
+}
+
+@available(iOS 16.1, *)
+struct WorkoutActivityAttributes: ActivityAttributes {
+ struct Labels: Codable, Hashable {
+ var done: String
+ var rest: String
+ var next: String
+ var allDone: String
+ var restOver: String
+ }
+
+ /// One set as the activity shows it, with the rest that follows it.
+ struct SetInfo: Codable, Hashable {
+ var exId: String
+ var entryIdx: Int
+ var setIdx: Int
+ var exName: String
+ var setLine: String
+ var target: String
+ var restAfter: Int
+ }
+
+ struct ContentState: Codable, Hashable {
+ var name: String
+ /// The set to do now; nil once every set is ticked.
+ var cur: SetInfo?
+ /// The few sets after it, so Done can move on while the page sleeps.
+ var ahead: [SetInfo]
+ /// A running rest's end, in milliseconds since 1970.
+ var restEndsAt: Double?
+ /// A paused rest's seconds left.
+ var restLeft: Double?
+ var restTotal: Double?
+ var done: Int
+ var total: Int
+
+ /// The running rest as a range Text(timerInterval:) can count down, or nil.
+ var restRange: ClosedRange<Date>? {
+ guard let end = restEndsAt else { return nil }
+ let until = Date(timeIntervalSince1970: end / 1000)
+ let from = until.addingTimeInterval(-max(1, restTotal ?? 1))
+ return from...until
+ }
+ }
+
+ var v: Int
+ var wid: String
+ var start: Double?
+ var accent: String
+ var ink: String
+ var labels: Labels
+}
+
+/**
+ * The Done taps the page has not applied yet, oldest first, in the App Group. The intent adds to
+ * it, LiveActivityPlugin hands it to the page and takes out what the page acknowledged.
+ */
+enum LiveActivityQueue {
+ static let key = "liveActivityEvents"
+ static let didChange = Notification.Name("OpenGymLiveActivityEvent")
+ private static let lock = NSLock()
+
+ static func all() -> [[String: Any]] {
+ lock.lock(); defer { lock.unlock() }
+ return read()
+ }
+
+ static func append(_ event: [String: Any]) {
+ lock.lock(); defer { lock.unlock() }
+ var list = read()
+ list.append(event)
+ // A queue nobody drained for a long time keeps its newest taps, not every one ever made.
+ if list.count > 200 { list.removeFirst(list.count - 200) }
+ write(list)
+ }
+
+ static func remove(ids: Set<String>) {
+ lock.lock(); defer { lock.unlock() }
+ write(read().filter { !ids.contains(($0["id"] as? String) ?? "") })
+ }
+
+ private static func read() -> [[String: Any]] {
+ guard let data = OpenGymGroup.defaults.data(forKey: key),
+ let list = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] else { return [] }
+ return list
+ }
+
+ private static func write(_ list: [[String: Any]]) {
+ if let data = try? JSONSerialization.data(withJSONObject: list) {
+ OpenGymGroup.defaults.set(data, forKey: key)
+ }
+ }
+}
+
+/**
+ * The Live Activity's Done. iOS runs it in the app, whether the page is awake or not: the tap is
+ * queued for the page (which ticks the set through the workout screen's own tick, once), and the
+ * activity moves on to the next set and its rest right away, with the rest-over notification the
+ * page would have booked. When the page applies the tap it sends its own state, which wins.
+ */
+@available(iOS 17.0, *)
+struct DoneSetIntent: LiveActivityIntent {
+ static let title: LocalizedStringResource = "Done"
+ static let isDiscoverable = false
+
+ @Parameter(title: "Workout") var wid: String
+ @Parameter(title: "Exercise") var exId: String
+ @Parameter(title: "Entry") var entryIdx: Int
+ @Parameter(title: "Set") var setIdx: Int
+
+ init() {}
+
+ init(wid: String, exId: String, entryIdx: Int, setIdx: Int) {
+ self.wid = wid
+ self.exId = exId
+ self.entryIdx = entryIdx
+ self.setIdx = setIdx
+ }
+
+ func perform() async throws -> some IntentResult {
+ await LiveActivityTick.tick(wid: wid, exId: exId, entryIdx: entryIdx, setIdx: setIdx)
+ return .result()
+ }
+}
+
+@available(iOS 17.0, *)
+enum LiveActivityTick {
+ static let restRequestId = "opengym.rest" // RestAlertPlugin.requestId: the page's own replaces it
+
+ static func tick(wid: String, exId: String, entryIdx: Int, setIdx: Int, now: Date = Date()) async {
+ guard let activity = Activity<WorkoutActivityAttributes>.activities.first(where: { $0.attributes.wid == wid }) else { return }
+ let state = activity.content.state
+ // A button from a state already moved on (two quick taps): that set is ticked already.
+ guard let cur = state.cur, cur.exId == exId, cur.entryIdx == entryIdx, cur.setIdx == setIdx else { return }
+ LiveActivityQueue.append([
+ "id": UUID().uuidString, "type": "setDone", "wid": wid, "exId": exId,
+ "entryIdx": entryIdx, "setIdx": setIdx, "at": (now.timeIntervalSince1970 * 1000).rounded(),
+ ])
+ var next = state
+ next.cur = state.ahead.first
+ next.ahead = Array(state.ahead.dropFirst())
+ next.done = min(state.total, state.done + 1)
+ next.restLeft = nil
+ if cur.restAfter > 0, next.cur != nil {
+ let end = now.addingTimeInterval(TimeInterval(cur.restAfter))
+ next.restEndsAt = end.timeIntervalSince1970 * 1000
+ next.restTotal = Double(cur.restAfter)
+ bookRestOver(at: end, title: activity.attributes.labels.restOver)
+ } else {
+ next.restEndsAt = nil
+ next.restTotal = nil
+ }
+ await activity.update(ActivityContent(state: next, staleDate: nil))
+ NotificationCenter.default.post(name: LiveActivityQueue.didChange, object: nil)
+ }
+
+ private static func bookRestOver(at: Date, title: String) {
+ let content = UNMutableNotificationContent()
+ content.title = title
+ content.sound = .default
+ content.interruptionLevel = .active
+ let trigger = UNTimeIntervalNotificationTrigger(timeInterval: max(1, at.timeIntervalSinceNow), repeats: false)
+ UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: restRequestId, content: content, trigger: trigger))
+ }
+}
diff --git a/frontend/ios/App/OpenGymWidgets/Info.plist b/frontend/ios/App/OpenGymWidgets/Info.plist
new file mode 100644
index 000000000..249760268
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/Info.plist
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>en</string>
+ <key>CFBundleDisplayName</key>
+ <string>openGym</string>
+ <key>CFBundleExecutable</key>
+ <string>$(EXECUTABLE_NAME)</string>
+ <key>CFBundleIdentifier</key>
+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>$(PRODUCT_NAME)</string>
+ <key>CFBundlePackageType</key>
+ <string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
+ <key>CFBundleShortVersionString</key>
+ <string>$(MARKETING_VERSION)</string>
+ <key>CFBundleVersion</key>
+ <string>$(CURRENT_PROJECT_VERSION)</string>
+ <key>NSExtension</key>
+ <dict>
+ <key>NSExtensionPointIdentifier</key>
+ <string>com.apple.widgetkit-extension</string>
+ </dict>
+</dict>
+</plist>
diff --git a/frontend/ios/App/OpenGymWidgets/LiveActivityWidget.swift b/frontend/ios/App/OpenGymWidgets/LiveActivityWidget.swift
new file mode 100644
index 000000000..ccc55c3bd
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/LiveActivityWidget.swift
@@ -0,0 +1,54 @@
+import ActivityKit
+import SwiftUI
+import WidgetKit
+
+/*
+ * The running workout on the Lock Screen and in the Dynamic Island (and, through the compact
+ * views, in an Apple Watch's Smart Stack). The app starts and updates it (LiveActivityPlugin.swift);
+ * its Done button is WorkoutActivity.swift's DoneSetIntent. The views are App/WidgetViews.swift's.
+ */
+struct WorkoutLiveActivity: Widget {
+ var body: some WidgetConfiguration {
+ ActivityConfiguration(for: WorkoutActivityAttributes.self) { context in
+ LiveLockView(attributes: context.attributes, state: context.state)
+ .activitySystemActionForegroundColor(Color(hex: context.attributes.accent) ?? .green)
+ } dynamicIsland: { context in
+ let accent = Color(hex: context.attributes.accent) ?? .green
+ return DynamicIsland {
+ DynamicIslandExpandedRegion(.leading) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(context.state.cur?.exName ?? context.attributes.labels.allDone)
+ .font(.headline).lineLimit(1)
+ if let c = context.state.cur {
+ Text(c.setLine).font(.caption).foregroundStyle(.secondary).lineLimit(1)
+ }
+ }
+ .padding(.leading, 4)
+ }
+ DynamicIslandExpandedRegion(.trailing) {
+ if context.state.restRange != nil || context.state.restLeft != nil {
+ LiveRest(attributes: context.attributes, state: context.state, font: .title3)
+ .frame(maxWidth: 80, alignment: .trailing)
+ .padding(.trailing, 4)
+ } else if let c = context.state.cur {
+ Text(c.target).font(.subheadline.weight(.semibold)).lineLimit(1).padding(.trailing, 4)
+ }
+ }
+ DynamicIslandExpandedRegion(.bottom) {
+ HStack(spacing: 10) {
+ ProgressBar(value: Double(context.state.done) / Double(max(1, context.state.total)), accent: accent)
+ Text("\(context.state.done)/\(context.state.total)").font(.caption.weight(.semibold)).monospacedDigit()
+ if let c = context.state.cur { LiveDoneButton(attributes: context.attributes, cur: c) }
+ }
+ }
+ } compactLeading: {
+ Image(systemName: "dumbbell.fill").foregroundStyle(accent)
+ } compactTrailing: {
+ LiveCompactTrailing(attributes: context.attributes, state: context.state)
+ } minimal: {
+ LiveMinimal(attributes: context.attributes, state: context.state)
+ }
+ .keylineTint(accent)
+ }
+ }
+}
diff --git a/frontend/ios/App/OpenGymWidgets/OpenGymWidgets.entitlements b/frontend/ios/App/OpenGymWidgets/OpenGymWidgets.entitlements
new file mode 100644
index 000000000..02dde9497
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/OpenGymWidgets.entitlements
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyLists-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>com.apple.security.application-groups</key>
+ <array>
+ <string>group.ch.opengym.app</string>
+ </array>
+</dict>
+</plist>
diff --git a/frontend/ios/App/OpenGymWidgets/OpenGymWidgets.swift b/frontend/ios/App/OpenGymWidgets/OpenGymWidgets.swift
new file mode 100644
index 000000000..71fe85fd6
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/OpenGymWidgets.swift
@@ -0,0 +1,96 @@
+import SwiftUI
+import WidgetKit
+
+/*
+ * openGym's widgets (the widget extension, ios/ci/add-widgets.rb): today's workout on the Home
+ * Screen in three sizes and on the Lock Screen, the streak on the Lock Screen, and the running
+ * workout's Live Activity (LiveActivityWidget.swift). What they show is the snapshot the app writes
+ * to the App Group (WidgetBridgePlugin.swift, lib/widgets.js); the views are in
+ * App/WidgetViews.swift, which the app compiles too for its CI pictures.
+ */
+@main
+struct OpenGymWidgets: WidgetBundle {
+ var body: some Widget {
+ TodayWidget()
+ StreakWidget()
+ WorkoutLiveActivity()
+ }
+}
+
+struct SnapshotEntry: TimelineEntry {
+ let date: Date
+ let snapshot: WidgetSnapshot?
+}
+
+/// The snapshot as it is, with an entry for each coming midnight: the snapshot carries the next
+/// week's plan, so the widget turns the page by itself while the app stays closed.
+struct SnapshotProvider: TimelineProvider {
+ func placeholder(in context: Context) -> SnapshotEntry {
+ SnapshotEntry(date: Date(), snapshot: WidgetSnapshot.load())
+ }
+
+ func getSnapshot(in context: Context, completion: @escaping (SnapshotEntry) -> Void) {
+ completion(SnapshotEntry(date: Date(), snapshot: WidgetSnapshot.load()))
+ }
+
+ func getTimeline(in context: Context, completion: @escaping (Timeline<SnapshotEntry>) -> Void) {
+ let snap = WidgetSnapshot.load()
+ var entries = [SnapshotEntry(date: Date(), snapshot: snap)]
+ let cal = Calendar.current
+ var day = cal.startOfDay(for: Date())
+ for _ in 0..<7 {
+ guard let next = cal.date(byAdding: .day, value: 1, to: day) else { break }
+ day = next
+ entries.append(SnapshotEntry(date: day, snapshot: snap))
+ }
+ completion(Timeline(entries: entries, policy: .atEnd))
+ }
+}
+
+struct TodayWidgetView: View {
+ @Environment(\.widgetFamily) private var family
+ let entry: SnapshotEntry
+
+ var body: some View {
+ let model = WidgetModel(snap: entry.snapshot, date: entry.date)
+ Group {
+ switch family {
+ case .systemMedium: MediumWidgetView(model: model)
+ case .systemLarge: LargeWidgetView(model: model)
+ case .accessoryRectangular: NextRectView(model: model)
+ case .accessoryInline: NextInlineView(model: model)
+ default: SmallWidgetView(model: model)
+ }
+ }
+ .containerBackground(for: .widget) {
+ if family == .accessoryRectangular || family == .accessoryInline {
+ Color.clear
+ } else {
+ Color(UIColor.systemBackground)
+ }
+ }
+ }
+}
+
+struct TodayWidget: Widget {
+ var body: some WidgetConfiguration {
+ StaticConfiguration(kind: "OpenGymToday", provider: SnapshotProvider()) { entry in
+ TodayWidgetView(entry: entry)
+ }
+ .configurationDisplayName("Today’s workout")
+ .description("Your plan for today, the week ahead and your streak.")
+ .supportedFamilies([.systemSmall, .systemMedium, .systemLarge, .accessoryRectangular, .accessoryInline])
+ }
+}
+
+struct StreakWidget: Widget {
+ var body: some WidgetConfiguration {
+ StaticConfiguration(kind: "OpenGymStreak", provider: SnapshotProvider()) { entry in
+ StreakCircleView(model: WidgetModel(snap: entry.snapshot, date: entry.date))
+ .containerBackground(for: .widget) { Color.clear }
+ }
+ .configurationDisplayName("Streak")
+ .description("Weeks in a row with a workout.")
+ .supportedFamilies([.accessoryCircular])
+ }
+}
diff --git a/frontend/ios/App/OpenGymWidgets/ar.lproj/Localizable.strings b/frontend/ios/App/OpenGymWidgets/ar.lproj/Localizable.strings
new file mode 100644
index 000000000..81e42b608
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/ar.lproj/Localizable.strings
@@ -0,0 +1,6 @@
+/* Written by ios/ci/widget-strings.mjs: change it there. */
+"Today’s workout" = "تمرين اليوم";
+"Your plan for today, the week ahead and your streak." = "خطتك لليوم والأسبوع القادم وسلسلتك.";
+"Streak" = "السلسلة";
+"Weeks in a row with a workout." = "أسابيع متتالية فيها تمرين.";
+"Open openGym once to see your plan here." = "افتح openGym مرة واحدة لترى خطتك هنا.";
diff --git a/frontend/ios/App/OpenGymWidgets/bn.lproj/Localizable.strings b/frontend/ios/App/OpenGymWidgets/bn.lproj/Localizable.strings
new file mode 100644
index 000000000..38b1a8141
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/bn.lproj/Localizable.strings
@@ -0,0 +1,6 @@
+/* Written by ios/ci/widget-strings.mjs: change it there. */
+"Today’s workout" = "আজকের ওয়ার্কআউট";
+"Your plan for today, the week ahead and your streak." = "আজকের প্ল্যান, সামনের সপ্তাহ আর আপনার স্ট্রিক।";
+"Streak" = "স্ট্রিক";
+"Weeks in a row with a workout." = "টানা যত সপ্তাহে ওয়ার্কআউট হয়েছে।";
+"Open openGym once to see your plan here." = "আপনার প্ল্যান এখানে দেখতে openGym একবার খুলুন।";
diff --git a/frontend/ios/App/OpenGymWidgets/de.lproj/Localizable.strings b/frontend/ios/App/OpenGymWidgets/de.lproj/Localizable.strings
new file mode 100644
index 000000000..a3417ebcd
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/de.lproj/Localizable.strings
@@ -0,0 +1,6 @@
+/* Written by ios/ci/widget-strings.mjs: change it there. */
+"Today’s workout" = "Heutiges Training";
+"Your plan for today, the week ahead and your streak." = "Dein Plan für heute, die Woche und deine Serie.";
+"Streak" = "Serie";
+"Weeks in a row with a workout." = "Wochen in Folge mit Training.";
+"Open openGym once to see your plan here." = "Öffne openGym einmal, dann siehst du hier deinen Plan.";
diff --git a/frontend/ios/App/OpenGymWidgets/es.lproj/Localizable.strings b/frontend/ios/App/OpenGymWidgets/es.lproj/Localizable.strings
new file mode 100644
index 000000000..ac7f3b5a4
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/es.lproj/Localizable.strings
@@ -0,0 +1,6 @@
+/* Written by ios/ci/widget-strings.mjs: change it there. */
+"Today’s workout" = "Entreno de hoy";
+"Your plan for today, the week ahead and your streak." = "Tu plan de hoy, la semana que viene y tu racha.";
+"Streak" = "Racha";
+"Weeks in a row with a workout." = "Semanas seguidas con entreno.";
+"Open openGym once to see your plan here." = "Abre openGym una vez para ver aquí tu plan.";
diff --git a/frontend/ios/App/OpenGymWidgets/fr.lproj/Localizable.strings b/frontend/ios/App/OpenGymWidgets/fr.lproj/Localizable.strings
new file mode 100644
index 000000000..370334791
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/fr.lproj/Localizable.strings
@@ -0,0 +1,6 @@
+/* Written by ios/ci/widget-strings.mjs: change it there. */
+"Today’s workout" = "Séance du jour";
+"Your plan for today, the week ahead and your streak." = "Ton programme du jour, la semaine à venir et ta série.";
+"Streak" = "Série";
+"Weeks in a row with a workout." = "Semaines d’affilée avec une séance.";
+"Open openGym once to see your plan here." = "Ouvre openGym une fois pour voir ton programme ici.";
diff --git a/frontend/ios/App/OpenGymWidgets/hi.lproj/Localizable.strings b/frontend/ios/App/OpenGymWidgets/hi.lproj/Localizable.strings
new file mode 100644
index 000000000..9c2babf4f
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/hi.lproj/Localizable.strings
@@ -0,0 +1,6 @@
+/* Written by ios/ci/widget-strings.mjs: change it there. */
+"Today’s workout" = "आज का वर्कआउट";
+"Your plan for today, the week ahead and your streak." = "आज का प्लान, आने वाला हफ़्ता और आपकी स्ट्रीक।";
+"Streak" = "स्ट्रीक";
+"Weeks in a row with a workout." = "लगातार हफ़्ते जिनमें वर्कआउट हुआ।";
+"Open openGym once to see your plan here." = "अपना प्लान यहाँ देखने के लिए openGym एक बार खोलें।";
diff --git a/frontend/ios/App/OpenGymWidgets/hu.lproj/Localizable.strings b/frontend/ios/App/OpenGymWidgets/hu.lproj/Localizable.strings
new file mode 100644
index 000000000..1649a2d36
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/hu.lproj/Localizable.strings
@@ -0,0 +1,6 @@
+/* Written by ios/ci/widget-strings.mjs: change it there. */
+"Today’s workout" = "Mai edzés";
+"Your plan for today, the week ahead and your streak." = "A mai terved, a hét és a sorozatod.";
+"Streak" = "Sorozat";
+"Weeks in a row with a workout." = "Egymást követő hetek edzéssel.";
+"Open openGym once to see your plan here." = "Nyisd meg egyszer az openGymet, és itt látod a terved.";
diff --git a/frontend/ios/App/OpenGymWidgets/it.lproj/Localizable.strings b/frontend/ios/App/OpenGymWidgets/it.lproj/Localizable.strings
new file mode 100644
index 000000000..d40d0b035
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/it.lproj/Localizable.strings
@@ -0,0 +1,6 @@
+/* Written by ios/ci/widget-strings.mjs: change it there. */
+"Today’s workout" = "Allenamento di oggi";
+"Your plan for today, the week ahead and your streak." = "Il tuo piano di oggi, la settimana e la tua serie.";
+"Streak" = "Serie";
+"Weeks in a row with a workout." = "Settimane di fila con un allenamento.";
+"Open openGym once to see your plan here." = "Apri openGym una volta per vedere qui il tuo piano.";
diff --git a/frontend/ios/App/OpenGymWidgets/ko.lproj/Localizable.strings b/frontend/ios/App/OpenGymWidgets/ko.lproj/Localizable.strings
new file mode 100644
index 000000000..4250340e7
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/ko.lproj/Localizable.strings
@@ -0,0 +1,6 @@
+/* Written by ios/ci/widget-strings.mjs: change it there. */
+"Today’s workout" = "오늘의 운동";
+"Your plan for today, the week ahead and your streak." = "오늘의 계획, 다가오는 한 주, 연속 기록.";
+"Streak" = "연속 기록";
+"Weeks in a row with a workout." = "운동한 주가 연속으로 이어진 횟수.";
+"Open openGym once to see your plan here." = "openGym을 한 번 열면 여기에서 계획을 볼 수 있어요.";
diff --git a/frontend/ios/App/OpenGymWidgets/pl.lproj/Localizable.strings b/frontend/ios/App/OpenGymWidgets/pl.lproj/Localizable.strings
new file mode 100644
index 000000000..aee76f24e
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/pl.lproj/Localizable.strings
@@ -0,0 +1,6 @@
+/* Written by ios/ci/widget-strings.mjs: change it there. */
+"Today’s workout" = "Dzisiejszy trening";
+"Your plan for today, the week ahead and your streak." = "Twój plan na dziś, nadchodzący tydzień i twoja seria.";
+"Streak" = "Seria";
+"Weeks in a row with a workout." = "Tygodnie z rzędu z treningiem.";
+"Open openGym once to see your plan here." = "Otwórz openGym raz, a zobaczysz tu swój plan.";
diff --git a/frontend/ios/App/OpenGymWidgets/pt-BR.lproj/Localizable.strings b/frontend/ios/App/OpenGymWidgets/pt-BR.lproj/Localizable.strings
new file mode 100644
index 000000000..1707af872
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/pt-BR.lproj/Localizable.strings
@@ -0,0 +1,6 @@
+/* Written by ios/ci/widget-strings.mjs: change it there. */
+"Today’s workout" = "Treino de hoje";
+"Your plan for today, the week ahead and your streak." = "Seu plano de hoje, a semana e sua sequência.";
+"Streak" = "Sequência";
+"Weeks in a row with a workout." = "Semanas seguidas com treino.";
+"Open openGym once to see your plan here." = "Abra o openGym uma vez para ver seu plano aqui.";
diff --git a/frontend/ios/App/OpenGymWidgets/pt-PT.lproj/Localizable.strings b/frontend/ios/App/OpenGymWidgets/pt-PT.lproj/Localizable.strings
new file mode 100644
index 000000000..1bb69556a
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/pt-PT.lproj/Localizable.strings
@@ -0,0 +1,6 @@
+/* Written by ios/ci/widget-strings.mjs: change it there. */
+"Today’s workout" = "Treino de hoje";
+"Your plan for today, the week ahead and your streak." = "O teu plano de hoje, a semana e a tua sequência.";
+"Streak" = "Sequência";
+"Weeks in a row with a workout." = "Semanas seguidas com treino.";
+"Open openGym once to see your plan here." = "Abre o openGym uma vez para veres aqui o teu plano.";
diff --git a/frontend/ios/App/OpenGymWidgets/ru.lproj/Localizable.strings b/frontend/ios/App/OpenGymWidgets/ru.lproj/Localizable.strings
new file mode 100644
index 000000000..50dfd7065
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/ru.lproj/Localizable.strings
@@ -0,0 +1,6 @@
+/* Written by ios/ci/widget-strings.mjs: change it there. */
+"Today’s workout" = "Тренировка на сегодня";
+"Your plan for today, the week ahead and your streak." = "Ваш план на сегодня, неделю вперёд и ваша серия.";
+"Streak" = "Серия";
+"Weeks in a row with a workout." = "Недели подряд с тренировкой.";
+"Open openGym once to see your plan here." = "Откройте openGym один раз, и здесь появится ваш план.";
diff --git a/frontend/ios/App/OpenGymWidgets/th.lproj/Localizable.strings b/frontend/ios/App/OpenGymWidgets/th.lproj/Localizable.strings
new file mode 100644
index 000000000..f0100d180
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/th.lproj/Localizable.strings
@@ -0,0 +1,6 @@
+/* Written by ios/ci/widget-strings.mjs: change it there. */
+"Today’s workout" = "การฝึกวันนี้";
+"Your plan for today, the week ahead and your streak." = "แผนวันนี้ สัปดาห์ข้างหน้า และสถิติต่อเนื่องของคุณ";
+"Streak" = "ต่อเนื่อง";
+"Weeks in a row with a workout." = "จำนวนสัปดาห์ติดต่อกันที่มีการฝึก";
+"Open openGym once to see your plan here." = "เปิด openGym สักครั้งเพื่อดูแผนของคุณที่นี่";
diff --git a/frontend/ios/App/OpenGymWidgets/tr.lproj/Localizable.strings b/frontend/ios/App/OpenGymWidgets/tr.lproj/Localizable.strings
new file mode 100644
index 000000000..610c09581
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/tr.lproj/Localizable.strings
@@ -0,0 +1,6 @@
+/* Written by ios/ci/widget-strings.mjs: change it there. */
+"Today’s workout" = "Bugünün antrenmanı";
+"Your plan for today, the week ahead and your streak." = "Bugünkü planın, önündeki hafta ve serin.";
+"Streak" = "Seri";
+"Weeks in a row with a workout." = "Antrenmanlı art arda haftalar.";
+"Open openGym once to see your plan here." = "Planını burada görmek için openGym’i bir kez aç.";
diff --git a/frontend/ios/App/OpenGymWidgets/uk.lproj/Localizable.strings b/frontend/ios/App/OpenGymWidgets/uk.lproj/Localizable.strings
new file mode 100644
index 000000000..cea3ef024
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/uk.lproj/Localizable.strings
@@ -0,0 +1,6 @@
+/* Written by ios/ci/widget-strings.mjs: change it there. */
+"Today’s workout" = "Тренування на сьогодні";
+"Your plan for today, the week ahead and your streak." = "Твій план на сьогодні, тиждень наперед і твоя серія.";
+"Streak" = "Серія";
+"Weeks in a row with a workout." = "Тижні поспіль із тренуванням.";
+"Open openGym once to see your plan here." = "Відкрий openGym один раз, і тут з’явиться твій план.";
diff --git a/frontend/ios/App/OpenGymWidgets/zh-Hans.lproj/Localizable.strings b/frontend/ios/App/OpenGymWidgets/zh-Hans.lproj/Localizable.strings
new file mode 100644
index 000000000..c921a67e6
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/zh-Hans.lproj/Localizable.strings
@@ -0,0 +1,6 @@
+/* Written by ios/ci/widget-strings.mjs: change it there. */
+"Today’s workout" = "今日训练";
+"Your plan for today, the week ahead and your streak." = "今天的计划、接下来一周和你的连续纪录。";
+"Streak" = "连续纪录";
+"Weeks in a row with a workout." = "连续有训练的周数。";
+"Open openGym once to see your plan here." = "打开一次 openGym,就能在这里看到你的计划。";
diff --git a/frontend/ios/App/OpenGymWidgets/zh-Hant.lproj/Localizable.strings b/frontend/ios/App/OpenGymWidgets/zh-Hant.lproj/Localizable.strings
new file mode 100644
index 000000000..d7fa85edf
--- /dev/null
+++ b/frontend/ios/App/OpenGymWidgets/zh-Hant.lproj/Localizable.strings
@@ -0,0 +1,6 @@
+/* Written by ios/ci/widget-strings.mjs: change it there. */
+"Today’s workout" = "今日訓練";
+"Your plan for today, the week ahead and your streak." = "今天的計畫、接下來一週和你的連續紀錄。";
+"Streak" = "連續紀錄";
+"Weeks in a row with a workout." = "連續有訓練的週數。";
+"Open openGym once to see your plan here." = "打開一次 openGym,就能在這裡看到你的計畫。";
diff --git a/frontend/ios/ci/add-widgets.rb b/frontend/ios/ci/add-widgets.rb
new file mode 100644
index 000000000..986a1ba3b
--- /dev/null
+++ b/frontend/ios/ci/add-widgets.rb
@@ -0,0 +1,81 @@
+# Adds the widget extension (ios/App/OpenGymWidgets: the Home Screen and Lock Screen widgets and
+# the workout's Live Activity) to App.xcodeproj and embeds it in the app (App.app/PlugIns), in the
+# style of add-asset-downloader.rb. Two files of the app are compiled into it too: what the Live
+# Activity carries and its Done button (App/WorkoutActivity.swift) and the views
+# (App/WidgetViews.swift), which the app also draws for CI's pictures (App/WidgetPreview.swift).
+# Running it again changes nothing. Until the project with it is committed, CI runs it before
+# every build (.github/workflows/ios.yml).
+#
+# ruby frontend/ios/ci/add-widgets.rb
+#
+# App Store Connect needs, before a signed build: the bundle id ch.opengym.app.widgets with the
+# App Group group.ch.opengym.app, and an App Store provisioning profile for it, which the release
+# script signs the extension with (scripts/ios/finish-ipa.sh, WIDGETS_PROFILE).
+require 'xcodeproj'
+
+NAME = 'OpenGymWidgets'
+BUNDLE_ID = 'ch.opengym.app.widgets'
+SHARED = %w[WorkoutActivity.swift WidgetViews.swift].freeze
+
+dir = File.expand_path('../App', __dir__)
+proj = Xcodeproj::Project.open(File.join(dir, 'App.xcodeproj'))
+app = proj.targets.find { |t| t.name == 'App' }
+abort 'no App target' unless app
+if proj.targets.any? { |t| t.name == NAME }
+ puts "#{NAME} is already in the project"
+ exit 0
+end
+
+# A WidgetKit extension: an ordinary app extension (com.apple.widgetkit-extension in its Info.plist).
+ext = proj.new_target(:app_extension, NAME, :ios, '17.0')
+
+group = proj.main_group.new_group(NAME, NAME)
+sources = Dir.children(File.join(dir, NAME)).select { |f| f.end_with?('.swift') }.sort
+ext.add_file_references(sources.map { |f| group.new_file(f) })
+# The shared files, by the references the app's own group already has.
+app_group = proj.main_group.children.find { |g| g.respond_to?(:path) && g.path == 'App' }
+abort 'no App group' unless app_group
+shared = SHARED.map do |f|
+ ref = app_group.files.find { |r| r.path == f }
+ abort "App/#{f} is not in the project" unless ref
+ ref
+end
+ext.add_file_references(shared)
+group.new_file('Info.plist')
+group.new_file("#{NAME}.entitlements")
+# The gallery's words in every language the app speaks (ios/ci/widget-strings.mjs).
+Dir.children(File.join(dir, NAME)).select { |f| f.end_with?('.lproj') }.sort.each do |lproj|
+ ref = group.new_file(lproj)
+ ref.last_known_file_type = 'folder'
+ ext.add_resources([ref])
+end
+
+app_settings = app.build_configurations.first.build_settings
+ext.build_configurations.each do |c|
+ s = c.build_settings
+ s['PRODUCT_NAME'] = '$(TARGET_NAME)'
+ s['PRODUCT_BUNDLE_IDENTIFIER'] = BUNDLE_ID
+ s['INFOPLIST_FILE'] = "#{NAME}/Info.plist"
+ s['GENERATE_INFOPLIST_FILE'] = 'NO'
+ s['CODE_SIGN_ENTITLEMENTS'] = "#{NAME}/#{NAME}.entitlements"
+ s['CODE_SIGN_STYLE'] = 'Automatic'
+ s['SWIFT_VERSION'] = '5.0'
+ s['IPHONEOS_DEPLOYMENT_TARGET'] = '17.0'
+ s['TARGETED_DEVICE_FAMILY'] = '1,2'
+ s['SKIP_INSTALL'] = 'YES'
+ s['APPLICATION_EXTENSION_API_ONLY'] = 'YES'
+ s['ENABLE_PREVIEWS'] = 'NO'
+ s['MARKETING_VERSION'] = app_settings['MARKETING_VERSION']
+ s['CURRENT_PROJECT_VERSION'] = app_settings['CURRENT_PROJECT_VERSION']
+ s['LD_RUNPATH_SEARCH_PATHS'] = ['$(inherited)', '@executable_path/Frameworks', '@executable_path/../../Frameworks']
+end
+
+# Built before the app, and copied into App.app/PlugIns.
+app.add_dependency(ext)
+embed = app.new_copy_files_build_phase('Embed Foundation Extensions')
+embed.symbol_dst_subfolder_spec = :plug_ins
+file = embed.add_file_reference(ext.product_reference, true)
+file.settings = { 'ATTRIBUTES' => ['RemoveHeadersOnCopy'] }
+
+proj.save
+puts "added #{NAME} (#{BUNDLE_ID}), embedded in App"
diff --git a/frontend/ios/ci/widget-strings.mjs b/frontend/ios/ci/widget-strings.mjs
new file mode 100644
index 000000000..5a55cc6d5
--- /dev/null
+++ b/frontend/ios/ci/widget-strings.mjs
@@ -0,0 +1,72 @@
+#!/usr/bin/env node
+// Writes the widget extension's own strings (ios/App/OpenGymWidgets/<lang>.lproj/
+// Localizable.strings) in every language the app speaks: the names and descriptions iOS shows in
+// its widget gallery, and the line a widget shows before the app ever wrote anything. Everything
+// else a widget says comes from the app, in the app's language (lib/widgets.js). Run it after
+// changing the phrases below, and commit what it writes:
+//
+// node frontend/ios/ci/widget-strings.mjs
+import { writeFileSync, mkdirSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const out = join(dirname(fileURLToPath(import.meta.url)), '..', 'App', 'OpenGymWidgets')
+const LPROJ = ['de', 'fr', 'es', 'it', 'pt-PT', 'pt-BR', 'pl', 'hu', 'tr', 'ru', 'uk', 'ar', 'hi', 'bn', 'th', 'ko', 'zh-Hans', 'zh-Hant']
+
+// The Swift source's key → its words per .lproj.
+export const STRINGS = {
+ 'Today’s workout': {
+ de: 'Heutiges Training', fr: 'Séance du jour', es: 'Entreno de hoy', it: 'Allenamento di oggi', 'pt-PT': 'Treino de hoje', 'pt-BR': 'Treino de hoje',
+ pl: 'Dzisiejszy trening', hu: 'Mai edzés', tr: 'Bugünün antrenmanı', ru: 'Тренировка на сегодня', uk: 'Тренування на сьогодні', ar: 'تمرين اليوم',
+ hi: 'आज का वर्कआउट', bn: 'আজকের ওয়ার্কআউট', th: 'การฝึกวันนี้', ko: '오늘의 운동', 'zh-Hans': '今日训练', 'zh-Hant': '今日訓練',
+ },
+ 'Your plan for today, the week ahead and your streak.': {
+ de: 'Dein Plan für heute, die Woche und deine Serie.', fr: 'Ton programme du jour, la semaine à venir et ta série.',
+ es: 'Tu plan de hoy, la semana que viene y tu racha.', it: 'Il tuo piano di oggi, la settimana e la tua serie.',
+ 'pt-PT': 'O teu plano de hoje, a semana e a tua sequência.', 'pt-BR': 'Seu plano de hoje, a semana e sua sequência.',
+ pl: 'Twój plan na dziś, nadchodzący tydzień i twoja seria.', hu: 'A mai terved, a hét és a sorozatod.',
+ tr: 'Bugünkü planın, önündeki hafta ve serin.', ru: 'Ваш план на сегодня, неделю вперёд и ваша серия.',
+ uk: 'Твій план на сьогодні, тиждень наперед і твоя серія.', ar: 'خطتك لليوم والأسبوع القادم وسلسلتك.',
+ hi: 'आज का प्लान, आने वाला हफ़्ता और आपकी स्ट्रीक।', bn: 'আজকের প্ল্যান, সামনের সপ্তাহ আর আপনার স্ট্রিক।',
+ th: 'แผนวันนี้ สัปดาห์ข้างหน้า และสถิติต่อเนื่องของคุณ', ko: '오늘의 계획, 다가오는 한 주, 연속 기록.',
+ 'zh-Hans': '今天的计划、接下来一周和你的连续纪录。', 'zh-Hant': '今天的計畫、接下來一週和你的連續紀錄。',
+ },
+ 'Streak': {
+ de: 'Serie', fr: 'Série', es: 'Racha', it: 'Serie', 'pt-PT': 'Sequência', 'pt-BR': 'Sequência', pl: 'Seria', hu: 'Sorozat', tr: 'Seri',
+ ru: 'Серия', uk: 'Серія', ar: 'السلسلة', hi: 'स्ट्रीक', bn: 'স্ট্রিক', th: 'ต่อเนื่อง', ko: '연속 기록', 'zh-Hans': '连续纪录', 'zh-Hant': '連續紀錄',
+ },
+ 'Weeks in a row with a workout.': {
+ de: 'Wochen in Folge mit Training.', fr: 'Semaines d’affilée avec une séance.', es: 'Semanas seguidas con entreno.',
+ it: 'Settimane di fila con un allenamento.', 'pt-PT': 'Semanas seguidas com treino.', 'pt-BR': 'Semanas seguidas com treino.',
+ pl: 'Tygodnie z rzędu z treningiem.', hu: 'Egymást követő hetek edzéssel.', tr: 'Antrenmanlı art arda haftalar.',
+ ru: 'Недели подряд с тренировкой.', uk: 'Тижні поспіль із тренуванням.', ar: 'أسابيع متتالية فيها تمرين.',
+ hi: 'लगातार हफ़्ते जिनमें वर्कआउट हुआ।', bn: 'টানা যত সপ্তাহে ওয়ার্কআউট হয়েছে।', th: 'จำนวนสัปดาห์ติดต่อกันที่มีการฝึก',
+ ko: '운동한 주가 연속으로 이어진 횟수.', 'zh-Hans': '连续有训练的周数。', 'zh-Hant': '連續有訓練的週數。',
+ },
+ 'Open openGym once to see your plan here.': {
+ de: 'Öffne openGym einmal, dann siehst du hier deinen Plan.', fr: 'Ouvre openGym une fois pour voir ton programme ici.',
+ es: 'Abre openGym una vez para ver aquí tu plan.', it: 'Apri openGym una volta per vedere qui il tuo piano.',
+ 'pt-PT': 'Abre o openGym uma vez para veres aqui o teu plano.', 'pt-BR': 'Abra o openGym uma vez para ver seu plano aqui.',
+ pl: 'Otwórz openGym raz, a zobaczysz tu swój plan.', hu: 'Nyisd meg egyszer az openGymet, és itt látod a terved.',
+ tr: 'Planını burada görmek için openGym’i bir kez aç.', ru: 'Откройте openGym один раз, и здесь появится ваш план.',
+ uk: 'Відкрий openGym один раз, і тут з’явиться твій план.', ar: 'افتح openGym مرة واحدة لترى خطتك هنا.',
+ hi: 'अपना प्लान यहाँ देखने के लिए openGym एक बार खोलें।', bn: 'আপনার প্ল্যান এখানে দেখতে openGym একবার খুলুন।',
+ th: 'เปิด openGym สักครั้งเพื่อดูแผนของคุณที่นี่', ko: 'openGym을 한 번 열면 여기에서 계획을 볼 수 있어요.',
+ 'zh-Hans': '打开一次 openGym,就能在这里看到你的计划。', 'zh-Hant': '打開一次 openGym,就能在這裡看到你的計畫。',
+ },
+}
+
+const esc = s => s.replaceAll('\\', '\\\\').replaceAll('"', '\\"')
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ for (const l of LPROJ) {
+ const lines = ['/* Written by ios/ci/widget-strings.mjs: change it there. */']
+ for (const [k, tr] of Object.entries(STRINGS)) {
+ if (!tr[l]) throw new Error(`${k}: no ${l}`)
+ lines.push(`"${esc(k)}" = "${esc(tr[l])}";`)
+ }
+ const dir = join(out, `${l}.lproj`)
+ mkdirSync(dir, { recursive: true })
+ writeFileSync(join(dir, 'Localizable.strings'), lines.join('\n') + '\n')
+ }
+ console.log(`wrote ${LPROJ.length} languages to ${out}`)
+}
diff --git a/scripts/ios/finish-ipa.sh b/scripts/ios/finish-ipa.sh
index 0603e735f..0a0f11756 100755
--- a/scripts/ios/finish-ipa.sh
+++ b/scripts/ios/finish-ipa.sh
@@ -11,6 +11,7 @@
# Usage:
# scripts/ios/finish-ipa.sh <App-unsigned.ipa> <dist.p12> <p12-password-file> <profile.mobileprovision> [out.ipa]
# EXT_PROFILE=<extension.mobileprovision> ... once the IPA carries the asset pack downloader
+# WIDGETS_PROFILE=<widgets.mobileprovision> ... once it carries the widget extension
#
# Before: the phone build with the app's animations, from the same commit as the IPA:
# cd frontend && VITE_CLIP_EXT=webp APP_MEDIA_DIR=/mnt/backup-hdd/opengym-media/build-appwebp npm run build:mobile
@@ -60,6 +61,10 @@ p = plistlib.load(open(sys.argv[1], 'rb'))
e = dict(p['Entitlements'])
e['get-task-allow'] = False
assert e['application-identifier'].endswith('.ch.opengym.app'), e['application-identifier']
+# Apple Health (AppleHealthPlugin.swift) needs HealthKit on the app id and in the profile; without
+# it the app still works, and Settings → Apple Health reports that it could not write.
+if not e.get('com.apple.developer.healthkit'):
+ print('WARNING: the app profile has no HealthKit: Apple Health will not work in this build')
plistlib.dump(e, open(sys.argv[2], 'wb'))
print('profile:', p['Name'], '| team', p['TeamIdentifier'][0], '| expires', p['ExpirationDate'])
PY
@@ -86,8 +91,29 @@ PY
EXT_SIGN=(--entitlements-xml-file "Extensions/AnimationPacksDownloader.appex/AnimationPacksDownloader:$WORK/ext-entitlements.plist")
fi
+# The widget extension (the widgets and the workout's Live Activity, ios/App/OpenGymWidgets): its
+# own App Store profile, given as WIDGETS_PROFILE, for ch.opengym.app.widgets with the App Group.
+WIDGETS="$APP/PlugIns/OpenGymWidgets.appex"
+WIDGETS_SIGN=()
+if [ -d "$WIDGETS" ]; then
+ [ -n "${WIDGETS_PROFILE:-}" ] || { echo "the IPA carries OpenGymWidgets.appex: set WIDGETS_PROFILE to its App Store profile" >&2; exit 1; }
+ cp "$WIDGETS_PROFILE" "$WIDGETS/embedded.mobileprovision"
+ openssl smime -inform der -verify -noverify -in "$WIDGETS_PROFILE" -out "$WORK/widgets-profile.plist" 2>/dev/null
+ python3 - "$WORK/widgets-profile.plist" "$WORK/widgets-entitlements.plist" <<'PY'
+import plistlib, sys
+p = plistlib.load(open(sys.argv[1], 'rb'))
+e = dict(p['Entitlements'])
+e['get-task-allow'] = False
+assert e['application-identifier'].endswith('.ch.opengym.app.widgets'), e['application-identifier']
+assert 'group.ch.opengym.app' in e.get('com.apple.security.application-groups', []), 'the widgets profile has no App Group'
+plistlib.dump(e, open(sys.argv[2], 'wb'))
+print('widgets profile:', p['Name'], '| expires', p['ExpirationDate'])
+PY
+ WIDGETS_SIGN=(--entitlements-xml-file "PlugIns/OpenGymWidgets.appex/OpenGymWidgets:$WORK/widgets-entitlements.plist")
+fi
+
"$RCODESIGN" sign --p12-file "$P12" --p12-password-file "$P12PASS" \
- --entitlements-xml-file "App:$WORK/entitlements.plist" "${EXT_SIGN[@]}" "$APP"
+ --entitlements-xml-file "App:$WORK/entitlements.plist" "${EXT_SIGN[@]}" "${WIDGETS_SIGN[@]}" "$APP"
(cd "$WORK/ipa" && rm -f "$OUT" && python3 -m zipfile -c "$OUT" Payload)
echo "signed: $OUT ($(du -h "$OUT" | cut -f1), $CLIPS animations)"