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.

Watch: sync that holds up, fast heart rate, clearer screens, a widget that helps

Duarte Santosebca1d1763b9
diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml
index 4d43d6a5e..26d75a6dd 100644
--- a/.github/workflows/ios.yml
+++ b/.github/workflows/ios.yml
@@ -48,6 +48,12 @@ jobs:
# The Apple Watch app (ios/App/Watch), added to the project for the run and embedded in App.app.
- run: ruby ios/ci/add-watch-app.rb
working-directory: frontend
+ # The watch's session logic and the animation codec, tested on the Mac (no simulator).
+ - name: WatchCore tests
+ working-directory: frontend/ios/App/WatchCore
+ run: |
+ set -o pipefail
+ swift test 2>&1 | tail -60
- name: Build for the simulator
working-directory: frontend/ios/App
run: |
@@ -103,9 +109,18 @@ jobs:
xcrun simctl boot "$UDID" || true
xcrun simctl bootstatus "$UDID" -b
xcrun simctl install "$UDID" "$APP"
+ # A synthetic clip (a square moving, made with ffmpeg for the tests; no exercise media)
+ # in the app's own container, to show the animation path renders.
+ DATA=$(xcrun simctl get_app_container "$UDID" ch.opengym.app.watchkitapp data 2>/dev/null || true)
+ CLIP=""
+ if [ -n "$DATA" ]; then mkdir -p "$DATA/tmp" && cp ../WatchCore/Tests/WatchCoreTests/Fixtures/synthetic-square.webp "$DATA/tmp/clip.webp" && CLIP="$DATA/tmp/clip.webp"; fi
for screen in idle empty set weight rest finish; do
xcrun simctl terminate "$UDID" ch.opengym.app.watchkitapp 2>/dev/null || true
- xcrun simctl launch "$UDID" ch.opengym.app.watchkitapp -OpenGymWatchDemo -OpenGymWatchScreen "$screen"
+ if [ "$screen" = set ] && [ -n "$CLIP" ]; then
+ xcrun simctl launch "$UDID" ch.opengym.app.watchkitapp -OpenGymWatchDemo -OpenGymWatchScreen "$screen" -OpenGymWatchDemoClip "$CLIP"
+ else
+ xcrun simctl launch "$UDID" ch.opengym.app.watchkitapp -OpenGymWatchDemo -OpenGymWatchScreen "$screen"
+ fi
sleep 6
xcrun simctl io "$UDID" screenshot "build/watch/$size-$screen.png"
done
diff --git a/frontend/ios/App/App.xcodeproj/project.pbxproj b/frontend/ios/App/App.xcodeproj/project.pbxproj
index f99f92a23..90439321f 100644
--- a/frontend/ios/App/App.xcodeproj/project.pbxproj
+++ b/frontend/ios/App/App.xcodeproj/project.pbxproj
@@ -25,6 +25,7 @@
AA0400000000000000000002 /* AnimationPacksPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0400000000000000000001 /* AnimationPacksPlugin.swift */; };
AA0300000000000000000004 /* NudgeCheckPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0300000000000000000003 /* NudgeCheckPlugin.swift */; };
AA0500000000000000000002 /* WatchBridgePlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0500000000000000000001 /* WatchBridgePlugin.swift */; };
+ AA0600000000000000000002 /* ClipCodec.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0600000000000000000001 /* ClipCodec.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
@@ -51,6 +52,7 @@
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 /* WatchBridgePlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchBridgePlugin.swift; sourceTree = "<group>"; };
+ AA0600000000000000000001 /* ClipCodec.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ClipCodec.swift; path = ../WatchCore/Sources/WatchCore/ClipCodec.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -106,6 +108,7 @@
AA0400000000000000000003 /* App.entitlements */,
AA0300000000000000000003 /* NudgeCheckPlugin.swift */,
AA0500000000000000000001 /* WatchBridgePlugin.swift */,
+ AA0600000000000000000001 /* ClipCodec.swift */,
AA0200000000000000000007 /* PrivacyInfo.xcprivacy */,
504EC30B1FED79650016851F /* Main.storyboard */,
504EC30E1FED79650016851F /* Assets.xcassets */,
@@ -252,6 +255,7 @@
AA0400000000000000000002 /* AnimationPacksPlugin.swift in Sources */,
AA0300000000000000000004 /* NudgeCheckPlugin.swift in Sources */,
AA0500000000000000000002 /* WatchBridgePlugin.swift in Sources */,
+ AA0600000000000000000002 /* ClipCodec.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
diff --git a/frontend/ios/App/App/WatchBridgePlugin.swift b/frontend/ios/App/App/WatchBridgePlugin.swift
index b5ef9913e..7d2a24e59 100644
--- a/frontend/ios/App/App/WatchBridgePlugin.swift
+++ b/frontend/ios/App/App/WatchBridgePlugin.swift
@@ -190,36 +190,10 @@ public class WatchBridgePlugin: CAPPlugin, CAPBridgedPlugin, WCSessionDelegate {
return out
}
+ /// An animated WebP or GIF, frame by frame with its delays (WatchCore ClipCodec, the same code
+ /// CI tests on a synthetic clip).
private static func gifFromImage(_ source: URL, to out: URL) -> URL? {
- guard let src = CGImageSourceCreateWithURL(source as CFURL, nil) else { return nil }
- let count = CGImageSourceGetCount(src)
- guard count > 0,
- let dest = CGImageDestinationCreateWithURL(out as CFURL, UTType.gif.identifier as CFString, count, nil) else { return nil }
- CGImageDestinationSetProperties(dest, [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: 0]] as CFDictionary)
- let thumb = [
- kCGImageSourceCreateThumbnailFromImageAlways as String: true,
- kCGImageSourceThumbnailMaxPixelSize as String: 160,
- kCGImageSourceCreateThumbnailWithTransform as String: true,
- ] as CFDictionary
- var added = 0
- for i in 0..<count {
- guard let img = CGImageSourceCreateThumbnailAtIndex(src, i, thumb) else { continue }
- let props = CGImageSourceCopyPropertiesAtIndex(src, i, nil) as? [String: Any]
- let webp = props?[kCGImagePropertyWebPDictionary as String] as? [String: Any]
- let gifp = props?[kCGImagePropertyGIFDictionary as String] as? [String: Any]
- let delay = (webp?[kCGImagePropertyWebPUnclampedDelayTime as String] as? Double)
- ?? (webp?[kCGImagePropertyWebPDelayTime as String] as? Double)
- ?? (gifp?[kCGImagePropertyGIFUnclampedDelayTime as String] as? Double)
- ?? (gifp?[kCGImagePropertyGIFDelayTime as String] as? Double) ?? 0.1
- let frame = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: delay > 0.01 ? delay : 0.1]] as CFDictionary
- CGImageDestinationAddImage(dest, img, frame)
- added += 1
- }
- guard added > 0, CGImageDestinationFinalize(dest) else {
- try? FileManager.default.removeItem(at: out)
- return nil
- }
- return out
+ ClipCodec.makeGif(from: source, to: out, maxPixels: 160) ? out : nil
}
/* ---------- the watch's side ---------- */
diff --git a/frontend/ios/App/Watch/Info.plist b/frontend/ios/App/Watch/Info.plist
index 6fe4555ff..a28cd9920 100644
--- a/frontend/ios/App/Watch/Info.plist
+++ b/frontend/ios/App/Watch/Info.plist
@@ -28,6 +28,17 @@
<array>
<string>workout-processing</string>
</array>
+ <key>CFBundleURLTypes</key>
+ <array>
+ <dict>
+ <key>CFBundleURLName</key>
+ <string>ch.opengym.app.watchkitapp</string>
+ <key>CFBundleURLSchemes</key>
+ <array>
+ <string>opengym-watch</string>
+ </array>
+ </dict>
+ </array>
<key>WKApplication</key>
<true/>
<key>WKCompanionAppBundleIdentifier</key>
diff --git a/frontend/ios/App/Watch/OpenGymWatchApp.swift b/frontend/ios/App/Watch/OpenGymWatchApp.swift
index ca0d607d9..189cbc215 100644
--- a/frontend/ios/App/Watch/OpenGymWatchApp.swift
+++ b/frontend/ios/App/Watch/OpenGymWatchApp.swift
@@ -52,6 +52,10 @@ struct RootView: View {
ExercisePager()
}
}
+ // The complication's Start: today's workout, when none runs yet.
+ .onOpenURL { url in
+ if url.host == "start", store.workout == nil, let today = store.ready?.today { store.start(today) }
+ }
.onChange(of: store.widgetState) { state in
guard !store.isDemo else { return }
state.write()
@@ -66,18 +70,25 @@ struct RoundButton: View {
let systemImage: String
let label: Text
var size: CGFloat = 76
+ /// The label under the button, said in words (on by default: "Done" under the check).
+ var caption = true
let action: () -> Void
+ @Environment(\.isLuminanceReduced) private var dimmed
var body: some View {
- Button(action: action) {
- Image(systemName: systemImage)
- .font(.system(size: size * 0.42, weight: .bold))
- .foregroundStyle(Color.black)
- .frame(width: size, height: size)
- .background(Circle().fill(Theme.accent))
+ VStack(spacing: 3) {
+ Button(action: action) {
+ Image(systemName: systemImage)
+ .font(.system(size: size * 0.42, weight: .bold))
+ .foregroundStyle(dimmed ? Theme.accent : Color.black)
+ .frame(width: size, height: size)
+ .background(Circle().fill(dimmed ? Color.clear : Theme.accent))
+ .overlay(Circle().stroke(Theme.accent, lineWidth: dimmed ? 2 : 0))
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel(label)
+ if caption { label.font(.caption2.weight(.semibold)).foregroundStyle(.secondary).lineLimit(1) }
}
- .buttonStyle(.plain)
- .accessibilityLabel(label)
}
}
@@ -104,8 +115,16 @@ struct EdgeButton: View {
struct IdleView: View {
@EnvironmentObject var store: SessionStore
+ @State private var debug = false
var body: some View {
+ content
+ // Hidden: a long press shows what arrived from the phone (animations, sync, heart rate).
+ .onLongPressGesture(minimumDuration: 2) { debug = true }
+ .sheet(isPresented: $debug) { DebugView() }
+ }
+
+ @ViewBuilder private var content: some View {
if let ready = store.ready, ready.today != nil || !ready.others.isEmpty {
ScrollView {
VStack(spacing: 10) {
@@ -116,7 +135,6 @@ struct IdleView: View {
.minimumScaleFactor(0.7)
.multilineTextAlignment(.center)
RoundButton(systemImage: "play.fill", label: Text("Start workout")) { store.start(today) }
- Text("Start workout").font(.footnote).foregroundStyle(.secondary)
}
if !ready.others.isEmpty {
VStack(spacing: 4) {
@@ -180,8 +198,9 @@ enum CrownTarget { case reps, weight }
struct ExercisePage: View {
@EnvironmentObject var store: SessionStore
let index: Int
- @State private var target: CrownTarget = SessionStore.demoScreen == "weight" ? .weight : .reps
+ @State private var target: CrownTarget = .reps
@FocusState private var crownFocus: Bool
+ @ScaledMetric(relativeTo: .title) private var doneSize: CGFloat = 58
var body: some View {
if let w = store.workout, w.entries.indices.contains(index) {
@@ -212,7 +231,7 @@ struct ExercisePage: View {
by: target == .weight ? store.weightStep : 1, sensitivity: .low,
isContinuous: false, isHapticFeedbackEnabled: true)
Spacer(minLength: 2)
- RoundButton(systemImage: "checkmark", label: Text("Done"), size: 62) { store.completeSet() }
+ RoundButton(systemImage: "checkmark", label: Text("Done"), size: doneSize) { store.completeSet() }
.disabled(!current)
Spacer(minLength: 4)
SetDots(entry: entry, current: si) { store.pick(set: $0, in: index) }
@@ -226,7 +245,10 @@ struct ExercisePage: View {
}
}
.padding(.horizontal, 4)
- .onAppear { if current { crownFocus = true } }
+ .onAppear {
+ if SessionStore.demoScreen == "weight" || store.crownStartsOnWeight { target = .weight }
+ if current { crownFocus = true }
+ }
.onChange(of: store.entryIndex) { ei in if ei == index { crownFocus = true } }
}
}
@@ -245,6 +267,7 @@ struct ExercisePage: View {
/// Weight × reps in big rounded numerals. The one the crown turns carries the crown symbol under
/// it; a tap on the other hands the crown to that one.
struct NumbersView: View {
+ @ScaledMetric(relativeTo: .largeTitle) private var size: CGFloat = 32
let weight: Double
let reps: Double
let unit: String
@@ -267,7 +290,7 @@ struct NumbersView: View {
private func value(_ text: String, suffix: String?, active: Bool, tap: @escaping () -> Void) -> some View {
VStack(spacing: 0) {
HStack(alignment: .firstTextBaseline, spacing: 2) {
- Text(verbatim: text).font(.system(size: 32, weight: .semibold, design: .rounded).monospacedDigit())
+ Text(verbatim: text).font(.system(size: size, weight: .semibold, design: .rounded).monospacedDigit())
if let s = suffix { Text(verbatim: s).font(.system(size: 12, weight: .medium, design: .rounded)).foregroundStyle(.secondary) }
}
Image(systemName: "digitalcrown.arrow.clockwise.fill")
@@ -318,7 +341,6 @@ struct FinishPage: View {
.lineLimit(2)
.multilineTextAlignment(.center)
RoundButton(systemImage: "flag.checkered", label: Text("Finish workout")) { confirming = true }
- Text("Finish workout").font(.footnote).foregroundStyle(.secondary)
}
.padding(.horizontal, 6)
.confirmationDialog("Finish workout?", isPresented: $confirming) {
@@ -333,6 +355,8 @@ struct FinishPage: View {
struct RestView: View {
@EnvironmentObject var store: SessionStore
let end: Date
+ @Environment(\.isLuminanceReduced) private var dimmed
+ @ScaledMetric(relativeTo: .largeTitle) private var countdownSize: CGFloat = 42
var body: some View {
// The ring and the countdown in it take the space above the two corner buttons, so nothing
@@ -351,13 +375,14 @@ struct RestView: View {
}
}
VStack(spacing: 1) {
+ Text("Rest").font(.caption2.weight(.semibold)).foregroundStyle(.secondary)
Text(timerInterval: Date()...end, countsDown: true)
- .font(.system(size: 44, weight: .semibold, design: .rounded).monospacedDigit())
+ .font(.system(size: countdownSize, weight: .semibold, design: .rounded).monospacedDigit())
.minimumScaleFactor(0.5)
.lineLimit(1)
.multilineTextAlignment(.center)
if let e = store.entry, let si = store.setIndex {
- Text(verbatim: "\(e.name) · \(si + 1)")
+ Text("Next: \(e.name), set \(si + 1)")
.font(.caption2)
.foregroundStyle(.secondary)
.lineLimit(1)
@@ -368,11 +393,13 @@ struct RestView: View {
}
.aspectRatio(1, contentMode: .fit)
.padding(.horizontal, 6)
+ // Always On: the countdown stays, the buttons go (nothing to tap with the wrist down).
HStack {
EdgeButton(systemImage: "goforward.15", label: Text("+15s")) { store.addRest(15) }
Spacer()
EdgeButton(systemImage: "forward.end.fill", label: Text("Skip")) { store.skipRest() }
}
+ .opacity(dimmed ? 0 : 1)
}
.ignoresSafeArea(edges: .bottom)
}
@@ -409,6 +436,12 @@ struct HeartRateBadge: View {
Text(verbatim: "\(Int(hr.rounded()))").font(.caption2.monospacedDigit())
}
.foregroundStyle(.red)
+ } else if health.measuring {
+ HStack(spacing: 2) {
+ Image(systemName: "heart").font(.system(size: 9))
+ Text("measuring").font(.caption2)
+ }
+ .foregroundStyle(.secondary)
}
}
}
@@ -432,3 +465,25 @@ struct HealthToggle: View {
.frame(minHeight: Theme.tap)
}
}
+
+/* ---------- hidden: what arrived from the phone ---------- */
+
+struct DebugView: View {
+ @EnvironmentObject var store: SessionStore
+
+ var body: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 4) {
+ Text(verbatim: "workout: \(store.workout?.id ?? "none")").font(.caption2)
+ Text(verbatim: "pending ticks: \(store.state.pending.count)").font(.caption2)
+ Text(verbatim: "started here: \(store.state.startedHere ?? "-")").font(.caption2)
+ Text(verbatim: "clips: \(store.clips.count)").font(.caption2)
+ Text(verbatim: "health: \(store.health.enabled ? "on" : "off"), \(store.health.running ? "running" : "idle")").font(.caption2)
+ Divider()
+ ForEach(Array(store.clipLog.reversed().enumerated()), id: \.offset) { pair in
+ Text(verbatim: pair.element).font(.system(size: 10)).foregroundStyle(.secondary)
+ }
+ }
+ }
+ }
+}
diff --git a/frontend/ios/App/Watch/SessionStore.swift b/frontend/ios/App/Watch/SessionStore.swift
index 5fe5d62b8..26d8ef78a 100644
--- a/frontend/ios/App/Watch/SessionStore.swift
+++ b/frontend/ios/App/Watch/SessionStore.swift
@@ -1,20 +1,19 @@
import Foundation
-import ImageIO
import UIKit
import UserNotifications
import WatchConnectivity
import WatchKit
/*
- * The watch's side of a workout. The phone sends a snapshot of the running session (frontend
- * lib/watch-sync.js through ios/App/App/WatchBridgePlugin.swift); from then on the watch runs it
- * by itself, because the phone's page sleeps once the phone is locked in a pocket. A set ticked
- * here goes back as an event with transferUserInfo, which iOS delivers even when the phone app is
- * not running, and the phone applies it through its own workout screen.
+ * The watch's side of a workout, around WatchCore's SessionCore (the session as plain data and
+ * every change to it as a pure, tested function; its header lists the sync cases). This class
+ * only feeds it what arrives (snapshots from the phone, taps), saves the result after every change
+ * so a relaunch mid-workout loses nothing, and sends the events it returns with transferUserInfo,
+ * which the system queues and delivers even when the phone app is not running.
*
* Exercise animations: never part of the watch app. The phone sends the running workout's own,
- * as small GIF files (WatchBridgePlugin.sendClips); they are kept here only while that workout runs
- * and deleted when it ends. Without them the page shows the exercise by name.
+ * as small GIF files (WatchBridgePlugin.sendClips); they are kept only while that workout runs and
+ * deleted when it ends. Without them the page shows the exercise by name.
*/
/// One animation, as frames to cycle through.
@@ -23,87 +22,26 @@ struct ClipFrames {
let duration: Double
}
-struct Snapshot: Codable {
- let v: Int
- let unit: String?
- let restSec: Double?
- let active: ActiveWorkout?
- let ready: Ready?
-}
-
-/// What the watch can start by itself: today's planned session and a few other routines.
-struct Ready: Codable, Equatable {
- let today: ReadySession?
- let others: [ReadySession]
-}
-
-struct ReadySession: Codable, Equatable {
- let routineIds: [String]
- let name: String
- let entries: [Entry]
-}
-
-struct ActiveWorkout: Codable, Equatable {
- let id: String?
- let name: String
- let unit: String
- let cur: Int
- let restSec: Double
- let rest: RestInfo?
- var entries: [Entry]
-}
-
-struct RestInfo: Codable, Equatable {
- let endsAt: Double
-}
-
-struct Entry: Codable, Equatable {
- let id: String
- let name: String
- let mode: String
- let restSec: Double?
- let last: String?
- var sets: [SetRow]
-}
-
-struct SetRow: Codable, Equatable {
- var w: Double?
- var r: Double?
- let sec: Double?
- var done: Bool
- let warmup: Bool
-}
-
final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserNotificationCenterDelegate {
- /// The session as the watch has it, kept across a relaunch of the watch app.
- @Published private(set) var workout: ActiveWorkout? {
- didSet {
- guard !isDemo else { return }
- let d = UserDefaults.standard
- if let w = workout, let data = try? JSONEncoder().encode(w) { d.set(data, forKey: SessionStore.localKey) } else { d.removeObject(forKey: SessionStore.localKey) }
- }
+ /// Everything the watch knows about the session, saved after every change.
+ @Published private(set) var state = SessionState() {
+ didSet { if !isDemo, state != oldValue { save() } }
}
- @Published private(set) var ready: Ready?
+
+ var workout: ActiveWorkout? { state.workout }
+ var ready: Ready? { state.ready }
+ var entryIndex: Int { state.entryIndex }
+ var unit: String { workout?.unit ?? state.unit }
+ var weightStep: Double { unit == "lb" ? 5 : 2.5 }
+ var restHaptics: Bool { state.settings.restHaptics ?? true }
+ var crownStartsOnWeight: Bool { state.settings.crown == "weight" }
+
/// Apple Health: the workout session, its heart rate, and the switch (WorkoutManager).
let health = WorkoutManager()
/// The running workout's animations, by exercise id, from the phone.
@Published private(set) var clips: [String: ClipFrames] = [:]
- private static var clipDir: URL {
- FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("clips")
- }
- /// When the set now up began: the end of the rest before it, or the start of the session.
- private var setStartedAt = Date()
- /// The rest running after a set, for that rest's heart rate once it is over.
- private var restAfter: (exId: String, entryIdx: Int, setIdx: Int, wid: String, from: Date)?
- private var unitDefault = "kg"
- private var restDefault: Double = 90
- /// A session started here that the phone has not reported back yet.
- private var startedHere: String? {
- didSet { if !isDemo { UserDefaults.standard.set(startedHere, forKey: SessionStore.startedKey) } }
- }
- private static let localKey = "localWorkout"
- private static let startedKey = "startedHere"
- @Published var entryIndex = 0
+ /// What happened to the animations, newest last (the hidden debug screen).
+ @Published private(set) var clipLog: [String] = []
@Published var weight: Double = 0
@Published var reps: Double = 0
@Published private(set) var restEndsAt: Date?
@@ -111,17 +49,25 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
/// A set picked by hand in an exercise (entry index → set index); otherwise the first not done.
@Published private var picked: [Int: Int] = [:]
- /// Sets ticked here that the phone has not confirmed yet ("exerciseId#setIndex"): a snapshot
- /// sent before the phone applied them must not untick them.
- private var pending = Set<String>()
+ /// When the set now up began: the end of the rest before it, or the start of the session.
+ private var setStartedAt = Date()
+ /// The rest running after a set, for that rest's heart rate once it is over.
+ private var restAfter: (exId: String, entryIdx: Int, setIdx: Int, wid: String, from: Date)?
private var restTimer: Timer?
- private static let savedKey = "snapshot"
+ private static let stateKey = "sessionState"
private static let restNotificationId = "opengym.rest"
+ private static var clipDir: URL {
+ FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("clips")
+ }
+
static let demoArgument = "-OpenGymWatchDemo"
/// CI screenshots: "-OpenGymWatchScreen rest" opens the demo on that screen.
- static var demoScreen: String? {
+ static var demoScreen: String? { argument("-OpenGymWatchScreen") }
+ /// CI: a synthetic clip (not exercise media) shown on the demo's first exercise.
+ static var demoClip: String? { argument("-OpenGymWatchDemoClip") }
+ private static func argument(_ name: String) -> String? {
let a = ProcessInfo.processInfo.arguments
- guard let i = a.firstIndex(of: "-OpenGymWatchScreen"), i + 1 < a.count else { return nil }
+ guard let i = a.firstIndex(of: name), i + 1 < a.count else { return nil }
return a[i + 1]
}
var isDemo: Bool { ProcessInfo.processInfo.arguments.contains(SessionStore.demoArgument) }
@@ -129,29 +75,14 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
override init() {
super.init()
if isDemo {
- if SessionStore.demoScreen != "empty" {
- apply(json: SessionStore.demoScreen == "idle" ? SessionStore.demoReadyJSON : SessionStore.demoJSON)
- }
- if SessionStore.demoScreen == "finish" {
- DispatchQueue.main.async { self.entryIndex = self.workout?.entries.count ?? 0 }
- }
- if SessionStore.demoScreen == "weight" {
- DispatchQueue.main.async { self.loadTargets() }
- }
- if SessionStore.demoScreen == "rest" {
- DispatchQueue.main.async { self.startRest(until: Date().addingTimeInterval(83), notify: false) }
- }
- } else {
- let d = UserDefaults.standard
- if let data = d.data(forKey: SessionStore.localKey), let w = try? JSONDecoder().decode(ActiveWorkout.self, from: data) {
- workout = w
- startedHere = d.string(forKey: SessionStore.startedKey)
- loadTargets()
- }
- if let saved = d.string(forKey: SessionStore.savedKey) { apply(json: saved) }
+ startDemo()
+ } else if let data = UserDefaults.standard.data(forKey: SessionStore.stateKey),
+ let saved = try? JSONDecoder().decode(SessionState.self, from: data) {
+ // Relaunched (mid-workout or not): the session as it was, then the latest from the phone.
+ state = saved
+ loadTargets()
+ if saved.workout != nil { health.start() }
}
- // The rest's end as a notification, also when the app is not in front (not in the demo:
- // the permission question would cover the screenshot).
let center = UNUserNotificationCenter.current()
center.delegate = self
if !isDemo { center.requestAuthorization(options: [.alert, .sound]) { _, _ in } }
@@ -161,6 +92,10 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
}
}
+ private func save() {
+ if let data = try? JSONEncoder().encode(state) { UserDefaults.standard.set(data, forKey: SessionStore.stateKey) }
+ }
+
/* ---------- what the views read ---------- */
var entry: Entry? {
@@ -168,48 +103,45 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
return w.entries[entryIndex]
}
- /// The set to do next in the current exercise (the one picked, or the first not done), or nil
- /// when they are all done.
var setIndex: Int? { setIndex(in: entryIndex) }
+ func setIndex(in ei: Int) -> Int? { SessionCore.setIndex(state, entry: ei, picked: picked[ei]) }
- func setIndex(in ei: Int) -> Int? {
- guard let w = workout, w.entries.indices.contains(ei) else { return nil }
- let sets = w.entries[ei].sets
- if let p = picked[ei], sets.indices.contains(p), !sets[p].done { return p }
- return sets.firstIndex(where: { !$0.done })
- }
+ var progress: (done: Int, total: Int) { SessionCore.progress(state) }
func pick(set si: Int, in ei: Int) {
picked[ei] = si
if ei == entryIndex { loadTargets() }
}
- /// Paging to another exercise (Digital Crown or a vertical swipe).
+ /// Paging to another exercise (a vertical swipe).
func show(entry ei: Int) {
- guard ei != entryIndex else { return }
- entryIndex = ei
+ guard ei != state.entryIndex else { return }
+ state.entryIndex = ei
loadTargets()
}
- var unit: String { workout?.unit ?? "kg" }
-
/// What the complications and the Smart Stack widget show (WidgetState).
var widgetState: WidgetState {
if let w = workout {
+ let p = progress
if let end = restEndsAt, end > Date() {
- return WidgetState(mode: "rest", title: entry?.name ?? w.name, detail: "", restEndsAt: end)
+ return WidgetState(mode: "rest", title: entry?.name ?? w.name, detail: "", restEndsAt: end, done: p.done, total: p.total)
}
if let e = entry, let si = setIndex {
let s = e.sets[si]
let numbers = "\(formatNumber(s.w ?? 0)) \(w.unit) × \(formatNumber(s.r ?? 0))"
- return WidgetState(mode: "set", title: e.name, detail: numbers, restEndsAt: nil)
+ let work = e.sets.filter { !$0.warmup }.count
+ return WidgetState(mode: "set", title: e.name, detail: numbers, restEndsAt: nil, done: p.done, total: p.total,
+ setLabel: "\(min(si + 1, max(1, work)))/\(max(1, work))")
}
- return WidgetState(mode: "set", title: w.name, detail: "", restEndsAt: nil)
+ return WidgetState(mode: "set", title: w.name, detail: "", restEndsAt: nil, done: p.done, total: p.total)
+ }
+ if let today = ready?.today {
+ let total = today.entries.flatMap { $0.sets }.filter { !$0.warmup }.count
+ return WidgetState(mode: "today", title: today.name, detail: "", restEndsAt: nil, done: 0, total: total)
}
- if let today = ready?.today { return WidgetState(mode: "today", title: today.name, detail: "", restEndsAt: nil) }
return .idle
}
- var weightStep: Double { unit == "lb" ? 5 : 2.5 }
/* ---------- snapshots from the phone ---------- */
@@ -217,39 +149,25 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
guard let data = json.data(using: .utf8),
let snap = try? JSONDecoder().decode(Snapshot.self, from: data) else { return }
DispatchQueue.main.async {
- self.ready = snap.ready
- if let u = snap.unit { self.unitDefault = u }
- if let r = snap.restSec, r > 0 { self.restDefault = r }
- UserDefaults.standard.set(json, forKey: SessionStore.savedKey)
- guard var next = snap.active else {
- // A session started here that the phone has not heard of yet stays.
- if self.workout != nil && self.workout?.id == self.startedHere { return }
- if self.workout != nil { self.health.end(save: true) }
+ let before = self.state
+ let next = SessionCore.applySnapshot(before, snap)
+ self.state = next
+ if before.workout != nil && next.workout == nil {
+ // Ended on the phone: the session here ends too.
+ self.health.end(save: true)
self.dropClips()
- self.workout = nil
- self.pending.removeAll()
self.skipRest()
- return
- }
- if next.id == self.startedHere { self.startedHere = nil }
- let sameWorkout = next.id != nil && next.id == self.workout?.id
- // Ticks made here and not yet on the phone stay ticked.
- for (ei, e) in next.entries.enumerated() {
- for (si, s) in e.sets.enumerated() {
- let key = "\(e.id)#\(si)"
- if s.done { self.pending.remove(key) } else if self.pending.contains(key) { next.entries[ei].sets[si].done = true }
- }
- }
- self.workout = next
- if !sameWorkout {
- self.entryIndex = next.cur
+ } else if next.workout != nil && next.workout?.id != before.workout?.id {
+ // A workout this watch picks up (the app opened mid-workout, or the phone started one).
self.setStartedAt = Date()
- if !self.isDemo { self.health.start() }
+ self.picked = [:]
+ self.health.start()
}
- if let rest = next.rest {
- self.startRest(until: Date(timeIntervalSince1970: rest.endsAt / 1000), notify: true)
+ if let rest = snap.active?.rest, next.workout?.id == snap.active?.id {
+ let end = Date(timeIntervalSince1970: rest.endsAt / 1000)
+ if end != self.restEndsAt { self.startRest(until: end, notify: true) }
}
- self.entryIndex = min(max(0, self.entryIndex), next.entries.count) // the last page is Finish
+ self.health.syncSetting(next.settings.health)
self.loadTargets()
}
}
@@ -265,94 +183,60 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
/* ---------- what the lifter does here ---------- */
func completeSet() {
- guard var w = workout, let e = entry, let si = setIndex else { return }
+ guard let w = workout, let e = entry, let si = setIndex else { return }
let ei = entryIndex
let now = Date()
let setFrom = setStartedAt
closeRest(at: now)
- w.entries[ei].sets[si].done = true
- w.entries[ei].sets[si].w = weight
- w.entries[ei].sets[si].r = reps
- pending.insert("\(e.id)#\(si)")
- workout = w
- var event: [String: Any] = [
- "id": UUID().uuidString,
- "type": "setDone",
- "wid": w.id ?? "",
- "exId": e.id,
- "entryIdx": ei,
- "setIdx": si,
- "w": weight,
- "r": reps,
- "at": now.timeIntervalSince1970 * 1000,
- ]
- if let hr = health.stats(from: setFrom, to: now) { event["hr"] = hr }
- send(event: event)
+ let hr = health.stats(from: setFrom, to: now)
+ let (next, event) = SessionCore.tick(state, entry: ei, set: si, w: weight, r: reps, at: now.timeIntervalSince1970 * 1000,
+ id: UUID().uuidString, hr: hr)
+ state = next
+ if let event = event { send(event: event) }
setStartedAt = now
WKInterfaceDevice.current().play(.success)
- let rest = e.restSec ?? w.restSec
picked[ei] = nil
+ let rest = e.restSec ?? w.restSec
if rest > 0 {
startRest(until: now.addingTimeInterval(rest), notify: true)
- // after startRest, which closes any rest before it
restAfter = (e.id, ei, si, w.id ?? "", now)
}
// On to the next exercise once this one is done.
- if setIndex == nil, let next = w.entries.indices.first(where: { $0 > ei && w.entries[$0].sets.contains(where: { !$0.done }) }) {
- entryIndex = next
+ if setIndex == nil, let w2 = workout,
+ let nextEi = w2.entries.indices.first(where: { $0 > ei && w2.entries[$0].sets.contains(where: { !$0.done }) }) {
+ state.entryIndex = nextEi
}
loadTargets()
}
- /// Starts a ready session here, the phone asleep or not: the watch's id and start time go to
- /// the phone, which starts the same session with them when it next runs.
+ /// Starts a ready session here, the phone asleep or not.
func start(_ session: ReadySession) {
- let id = "watch-" + UUID().uuidString
let now = Date()
- startedHere = id
- workout = ActiveWorkout(id: id, name: session.name, unit: unitDefault, cur: 0, restSec: restDefault, rest: nil, entries: session.entries)
- entryIndex = 0
+ let (next, event) = SessionCore.start(state, session, wid: "watch-" + UUID().uuidString,
+ at: now.timeIntervalSince1970 * 1000, id: UUID().uuidString)
+ state = next
picked = [:]
- pending.removeAll()
- loadTargets()
setStartedAt = now
restAfter = nil
+ loadTargets()
health.start()
- send(event: [
- "id": UUID().uuidString,
- "type": "start",
- "routineIds": session.routineIds,
- "wid": id,
- "at": now.timeIntervalSince1970 * 1000,
- ])
+ send(event: event)
WKInterfaceDevice.current().play(.start)
}
/// Finishes the session: the phone saves it with its own Finish and save.
func finish() {
- guard let w = workout else { return }
closeRest(at: Date())
+ let (next, event) = SessionCore.finish(state, at: Date().timeIntervalSince1970 * 1000, id: UUID().uuidString)
+ guard let ev = event else { return }
health.end(save: true)
- send(event: [
- "id": UUID().uuidString,
- "type": "finish",
- "wid": w.id ?? "",
- "at": Date().timeIntervalSince1970 * 1000,
- ])
skipRest()
dropClips()
- workout = nil
- startedHere = nil
- pending.removeAll()
+ state = next
+ send(event: ev)
WKInterfaceDevice.current().play(.stop)
}
- func move(by step: Int) {
- guard let w = workout, !w.entries.isEmpty else { return }
- entryIndex = min(max(0, entryIndex + step), w.entries.count - 1)
- loadTargets()
- }
-
func skipRest() {
closeRest(at: Date())
restTimer?.invalidate()
@@ -379,20 +263,20 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
restEndsAt = end
restStartedAt = Date()
restTimer = Timer.scheduledTimer(withTimeInterval: end.timeIntervalSinceNow, repeats: false) { [weak self] _ in
- SessionStore.restOverHaptics()
+ if self?.restHaptics ?? true { SessionStore.restOverHaptics() }
DispatchQueue.main.async {
self?.closeRest(at: Date())
self?.restEndsAt = nil
self?.restStartedAt = nil
}
}
- guard notify else { return }
+ guard notify, !isDemo else { return }
let content = UNMutableNotificationContent()
content.title = String(localized: "Rest’s over. Next set!")
if let e = entry, let si = setIndex {
content.body = String(localized: "\(e.name), set \(si + 1)")
}
- content.sound = .default
+ content.sound = restHaptics ? .default : nil
content.interruptionLevel = .timeSensitive
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: max(1, end.timeIntervalSinceNow), repeats: false)
center.add(UNNotificationRequest(identifier: SessionStore.restNotificationId, content: content, trigger: trigger))
@@ -406,13 +290,8 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
setStartedAt = end
guard let hr = health.stats(from: r.from, to: end) else { return }
send(event: [
- "id": UUID().uuidString,
- "type": "setHr",
- "wid": r.wid,
- "exId": r.exId,
- "entryIdx": r.entryIdx,
- "setIdx": r.setIdx,
- "restHr": hr,
+ "id": UUID().uuidString, "type": "setHr", "wid": r.wid, "exId": r.exId,
+ "entryIdx": r.entryIdx, "setIdx": r.setIdx, "restHr": hr,
])
}
@@ -424,60 +303,54 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { device.play(.notification) }
}
- /* ---------- notifications with the app in front ---------- */
-
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.banner, .sound])
}
private func send(event: [String: Any]) {
- guard WCSession.isSupported(),
+ guard !isDemo, WCSession.isSupported(),
let data = try? JSONSerialization.data(withJSONObject: event),
let json = String(data: data, encoding: .utf8) else { return }
- // Queued by the system and delivered even when the phone app is not running.
+ // Queued by the system and delivered, in order, even when the phone app is not running.
WCSession.default.transferUserInfo(["event": json])
}
/* ---------- the animations ---------- */
+ private func log(_ line: String) {
+ let stamp = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .medium)
+ DispatchQueue.main.async { self.clipLog = Array((self.clipLog + ["\(stamp) \(line)"]).suffix(30)) }
+ }
+
/// The workout is over: its animations go, from memory and from the disk.
func dropClips() {
clips = [:]
try? FileManager.default.removeItem(at: SessionStore.clipDir)
+ log("clips deleted")
}
- static func decode(_ url: URL) -> ClipFrames? {
- guard let src = CGImageSourceCreateWithURL(url as CFURL, nil) else { return nil }
- let count = CGImageSourceGetCount(src)
- guard count > 0 else { return nil }
- var images: [UIImage] = []
- var total = 0.0
- for i in 0..<count {
- guard let cg = CGImageSourceCreateImageAtIndex(src, i, nil) else { continue }
- images.append(UIImage(cgImage: cg))
- let props = CGImageSourceCopyPropertiesAtIndex(src, i, nil) as? [String: Any]
- let gif = props?[kCGImagePropertyGIFDictionary as String] as? [String: Any]
- let delay = (gif?[kCGImagePropertyGIFUnclampedDelayTime as String] as? Double) ?? (gif?[kCGImagePropertyGIFDelayTime as String] as? Double) ?? 0.1
- total += delay > 0.01 ? delay : 0.1
- }
- return images.isEmpty ? nil : ClipFrames(images: images, duration: total)
+ static func frames(of url: URL) -> ClipFrames? {
+ guard let f = ClipCodec.decode(url) else { return nil }
+ return ClipFrames(images: f.images.map { UIImage(cgImage: $0) }, duration: f.duration)
}
func session(_ session: WCSession, didReceive file: WCSessionFile) {
// The file is gone once this returns: moved into the cache now.
- guard let exId = file.metadata?["exId"] as? String else { return }
+ guard let exId = file.metadata?["exId"] as? String else { log("file without an exercise"); return }
let dir = SessionStore.clipDir
try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let dest = dir.appendingPathComponent(exId.replacingOccurrences(of: "/", with: "_") + ".gif")
try? FileManager.default.removeItem(at: dest)
- guard (try? FileManager.default.moveItem(at: file.fileURL, to: dest)) != nil,
- let frames = SessionStore.decode(dest) else { return }
+ guard (try? FileManager.default.moveItem(at: file.fileURL, to: dest)) != nil else { log("\(exId): could not keep the file"); return }
+ guard let frames = SessionStore.frames(of: dest) else { log("\(exId): could not decode"); return }
let wid = file.metadata?["wid"] as? String
+ log("\(exId): \(frames.images.count) frames, \(String(format: "%.1f", frames.duration)) s")
DispatchQueue.main.async {
// Only for the workout running here; a late file of an earlier one is dropped.
guard self.workout != nil, wid == nil || wid == self.workout?.id else {
try? FileManager.default.removeItem(at: dest)
+ self.log("\(exId): not for this workout, dropped")
return
}
self.clips[exId] = frames
@@ -487,6 +360,7 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
/* ---------- WCSessionDelegate ---------- */
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
+ // The phone's latest snapshot: also what a watch app opened mid-workout picks the session up from.
if let json = session.receivedApplicationContext["snapshot"] as? String { apply(json: json) }
}
@@ -498,7 +372,21 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
if let json = message["snapshot"] as? String { apply(json: json) }
}
- /* ---------- the demo the CI screenshot shows ---------- */
+ /* ---------- the demo the CI screenshots show (text only; a synthetic clip at most) ---------- */
+
+ private func startDemo() {
+ let screen = SessionStore.demoScreen
+ if screen != "empty" { apply(json: screen == "idle" ? SessionStore.demoReadyJSON : SessionStore.demoJSON) }
+ DispatchQueue.main.async {
+ if screen == "finish" { self.state.entryIndex = self.workout?.entries.count ?? 0 }
+ if screen == "rest" { self.startRest(until: Date().addingTimeInterval(83), notify: false) }
+ if let path = SessionStore.demoClip, let frames = SessionStore.frames(of: URL(fileURLWithPath: path)) {
+ self.clips["0025"] = frames
+ self.log("demo clip: \(frames.images.count) frames")
+ }
+ self.loadTargets()
+ }
+ }
static let demoReadyJSON = """
{"v":1,"unit":"kg","restSec":90,"active":null,"ready":{"today":{"routineIds":["r1"],"name":"Push day","entries":[
@@ -509,7 +397,7 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
static let demoJSON = """
{"v":1,"unit":"kg","restSec":90,"ready":null,"active":{"id":"demo","name":"Push day","unit":"kg","cur":0,"restSec":90,"rest":null,"entries":[
{"id":"0025","name":"Bench Press","mode":"reps","restSec":120,"last":"60 kg × 8, 60 kg × 8, 60 kg × 7","sets":[
- {"w":60,"r":8,"sec":null,"done":true,"warmup":false},{"w":62.5,"r":8,"sec":null,"done":false,"warmup":false},{"w":62.5,"r":8,"sec":null,"done":false,"warmup":false}]},
+ {"w":60,"r":8,"sec":null,"done":true,"warmup":false,"at":1},{"w":62.5,"r":8,"sec":null,"done":false,"warmup":false},{"w":62.5,"r":8,"sec":null,"done":false,"warmup":false}]},
{"id":"0426","name":"Overhead Press","mode":"reps","restSec":null,"last":null,"sets":[
{"w":40,"r":8,"sec":null,"done":false,"warmup":false},{"w":40,"r":8,"sec":null,"done":false,"warmup":false}]}]}}
"""
diff --git a/frontend/ios/App/Watch/WidgetState.swift b/frontend/ios/App/Watch/WidgetState.swift
index 6d5f0841a..db26e3453 100644
--- a/frontend/ios/App/Watch/WidgetState.swift
+++ b/frontend/ios/App/Watch/WidgetState.swift
@@ -15,6 +15,11 @@ struct WidgetState: Codable, Equatable {
var title: String
var detail: String
var restEndsAt: Date?
+ /// Work sets done and in all, today's session (the complications' ring).
+ var done: Int = 0
+ var total: Int = 0
+ /// "2/4": the set up next, of its exercise's work sets.
+ var setLabel: String = ""
var updatedAt: Date = .distantPast
static let idle = WidgetState(mode: "idle", title: "openGym", detail: "", restEndsAt: nil)
@@ -23,6 +28,7 @@ struct WidgetState: Codable, Equatable {
static func == (a: WidgetState, b: WidgetState) -> Bool {
a.mode == b.mode && a.title == b.title && a.detail == b.detail && a.restEndsAt == b.restEndsAt
+ && a.done == b.done && a.total == b.total && a.setLabel == b.setLabel
}
/// The state as written, unless it is about a session long gone (the app stopped without
diff --git a/frontend/ios/App/Watch/WorkoutManager.swift b/frontend/ios/App/Watch/WorkoutManager.swift
index 49c9fcd5a..cbb5d7879 100644
--- a/frontend/ios/App/Watch/WorkoutManager.swift
+++ b/frontend/ios/App/Watch/WorkoutManager.swift
@@ -2,11 +2,17 @@ import Foundation
import HealthKit
/*
- * Apple Health on the watch, behind the "Apple Health" switch (off until the lifter turns it on):
- * a strength-training workout session while the phone's workout runs, which shows the live heart
- * rate here and keeps the watch app running with the wrist down (so the rest still taps the wrist
- * on time), and the workout saved to Apple Health when it ends. Off, nothing of this runs and
- * nothing is asked.
+ * Apple Health on the watch, behind its switch (on the watch's start screen, and in the phone's
+ * Settings → Apple Watch, which wins when it is set): a strength-training workout session as soon
+ * as a workout starts here or is picked up from the phone, showing the live heart rate and keeping
+ * the watch app running with the wrist down (so the rest still taps the wrist on time), and the
+ * workout saved to Apple Health when it ends. Off, nothing of this runs and nothing is asked.
+ *
+ * The heart rate arrives two ways at once, whichever is first: the workout builder's statistics
+ * and an anchored query on heart-rate samples, which carry their own time (the sets' and rests'
+ * heart rates are worked out from those times). Until the first reading: "measuring".
+ * The permission is asked when the switch is turned on (or the phone turns it on), at the start
+ * screen, never in the middle of the first set.
*/
final class WorkoutManager: NSObject, ObservableObject, HKWorkoutSessionDelegate, HKLiveWorkoutBuilderDelegate {
static let enabledKey = "healthEnabled"
@@ -16,12 +22,18 @@ final class WorkoutManager: NSObject, ObservableObject, HKWorkoutSessionDelegate
}
@Published private(set) var heartRate: Double?
@Published private(set) var running = false
+ /// A session runs and no reading has come yet.
+ var measuring: Bool { running && heartRate == nil }
private let store = HKHealthStore()
private var session: HKWorkoutSession?
private var builder: HKLiveWorkoutBuilder?
- /// Every reading of the session, for the heart rate of each set and rest (SessionStore).
+ private var query: HKAnchoredObjectQuery?
+ /// Every reading of the session, by its own time, for each set's and rest's heart rate.
private var samples: [(Date, Double)] = []
+ private let bpm = HKUnit.count().unitDivided(by: .minute())
+ /// A workout to measure (started here or picked up), even before the permission answer.
+ private var wanted = false
/// { avg, max } over a stretch of the session, or nil without readings in it.
func stats(from start: Date, to end: Date) -> [String: Double]? {
@@ -42,8 +54,23 @@ final class WorkoutManager: NSObject, ObservableObject, HKWorkoutSessionDelegate
}
}
- /// A workout started on the phone: a session here, when the switch is on.
+ /// The phone's setting, when it sends one: on asks for the permission (once) right away.
+ func syncSetting(_ on: Bool?) {
+ guard let on = on, on != enabled else { return }
+ if on {
+ requestAuthorization { ok in
+ self.enabled = ok
+ if ok && self.wanted { self.start() }
+ }
+ } else {
+ enabled = false
+ end(save: true)
+ }
+ }
+
+ /// A workout started here or picked up from the phone: the session starts now.
func start() {
+ wanted = true
guard enabled, session == nil, HKHealthStore.isHealthDataAvailable() else { return }
let config = HKWorkoutConfiguration()
config.activityType = .traditionalStrengthTraining
@@ -57,9 +84,11 @@ final class WorkoutManager: NSObject, ObservableObject, HKWorkoutSessionDelegate
session = s
builder = b
samples = []
+ heartRate = nil
let now = Date()
s.startActivity(with: now)
b.beginCollection(withStart: now) { _, _ in }
+ startQuery(from: now)
running = true
} catch {
session = nil
@@ -67,8 +96,31 @@ final class WorkoutManager: NSObject, ObservableObject, HKWorkoutSessionDelegate
}
}
- /// The workout ended on the phone: saved to Apple Health, or dropped when `save` is false.
+ private func startQuery(from start: Date) {
+ guard let type = HKQuantityType.quantityType(forIdentifier: .heartRate) else { return }
+ let predicate = HKQuery.predicateForSamples(withStart: start, end: nil, options: .strictStartDate)
+ let handler: (HKAnchoredObjectQuery, [HKSample]?, [HKDeletedObject]?, HKQueryAnchor?, Error?) -> Void = { [weak self] _, added, _, _, _ in
+ guard let self = self else { return }
+ let readings = (added as? [HKQuantitySample] ?? []).map { ($0.endDate, $0.quantity.doubleValue(for: self.bpm)) }
+ guard !readings.isEmpty else { return }
+ DispatchQueue.main.async { self.add(readings) }
+ }
+ let q = HKAnchoredObjectQuery(type: type, predicate: predicate, anchor: nil, limit: HKObjectQueryNoLimit, resultsHandler: handler)
+ q.updateHandler = handler
+ query = q
+ store.execute(q)
+ }
+
+ private func add(_ readings: [(Date, Double)]) {
+ for r in readings where !samples.contains(where: { abs($0.0.timeIntervalSince(r.0)) < 0.5 }) { samples.append(r) }
+ samples.sort { $0.0 < $1.0 }
+ if let last = samples.last { heartRate = last.1 }
+ }
+
+ /// The workout ended: saved to Apple Health, or dropped when `save` is false.
func end(save: Bool) {
+ wanted = false
+ if let q = query { store.stop(q); query = nil }
guard let s = session, let b = builder else { return }
s.end()
b.endCollection(withEnd: Date()) { _, _ in
@@ -100,10 +152,8 @@ final class WorkoutManager: NSObject, ObservableObject, HKWorkoutSessionDelegate
guard let hrType = HKQuantityType.quantityType(forIdentifier: .heartRate),
collectedTypes.contains(hrType),
let stats = workoutBuilder.statistics(for: hrType),
- let value = stats.mostRecentQuantity()?.doubleValue(for: HKUnit.count().unitDivided(by: .minute())) else { return }
- DispatchQueue.main.async {
- self.heartRate = value
- self.samples.append((Date(), value))
- }
+ let value = stats.mostRecentQuantity()?.doubleValue(for: bpm) else { return }
+ let at = stats.mostRecentQuantityDateInterval()?.end ?? Date()
+ DispatchQueue.main.async { self.add([(at, value)]) }
}
}
diff --git a/frontend/ios/App/Watch/ar.lproj/Localizable.strings b/frontend/ios/App/Watch/ar.lproj/Localizable.strings
index 994340f34..e66aa0c52 100644
--- a/frontend/ios/App/Watch/ar.lproj/Localizable.strings
+++ b/frontend/ios/App/Watch/ar.lproj/Localizable.strings
@@ -16,5 +16,6 @@
"No workout running" = "لا يوجد تمرين جارٍ";
"Start one on your iPhone and it shows up here." = "ابدأ تمرينًا على iPhone وسيظهر هنا.";
"All sets done" = "اكتملت كل المجموعات";
+"measuring" = "جارٍ القياس …";
"Next: %@, set %lld" = "التالي: %@، المجموعة %lld";
"%@, set %lld" = "%@، المجموعة %lld";
diff --git a/frontend/ios/App/Watch/bn.lproj/Localizable.strings b/frontend/ios/App/Watch/bn.lproj/Localizable.strings
index f48211f69..76493c20f 100644
--- a/frontend/ios/App/Watch/bn.lproj/Localizable.strings
+++ b/frontend/ios/App/Watch/bn.lproj/Localizable.strings
@@ -16,5 +16,6 @@
"No workout running" = "কোনো ওয়ার্কআউট চলছে না";
"Start one on your iPhone and it shows up here." = "iPhone-এ একটি শুরু করুন, এখানে দেখা যাবে।";
"All sets done" = "সব সেট শেষ";
+"measuring" = "মাপা হচ্ছে …";
"Next: %@, set %lld" = "এরপর: %@, সেট %lld";
"%@, set %lld" = "%@, সেট %lld";
diff --git a/frontend/ios/App/Watch/de.lproj/Localizable.strings b/frontend/ios/App/Watch/de.lproj/Localizable.strings
index b725a8b87..2c18546d6 100644
--- a/frontend/ios/App/Watch/de.lproj/Localizable.strings
+++ b/frontend/ios/App/Watch/de.lproj/Localizable.strings
@@ -16,5 +16,6 @@
"No workout running" = "Kein Training läuft";
"Start one on your iPhone and it shows up here." = "Starte eins auf dem iPhone, dann taucht es hier auf.";
"All sets done" = "Alle Sätze erledigt";
+"measuring" = "misst …";
"Next: %@, set %lld" = "Als Nächstes: %@, Satz %lld";
"%@, set %lld" = "%@, Satz %lld";
diff --git a/frontend/ios/App/Watch/es.lproj/Localizable.strings b/frontend/ios/App/Watch/es.lproj/Localizable.strings
index 0717d6c43..abcd23339 100644
--- a/frontend/ios/App/Watch/es.lproj/Localizable.strings
+++ b/frontend/ios/App/Watch/es.lproj/Localizable.strings
@@ -16,5 +16,6 @@
"No workout running" = "Ningún entreno en curso";
"Start one on your iPhone and it shows up here." = "Empieza uno en tu iPhone y aparecerá aquí.";
"All sets done" = "Todas las series hechas";
+"measuring" = "midiendo …";
"Next: %@, set %lld" = "Siguiente: %@, serie %lld";
"%@, set %lld" = "%@, serie %lld";
diff --git a/frontend/ios/App/Watch/fr.lproj/Localizable.strings b/frontend/ios/App/Watch/fr.lproj/Localizable.strings
index 5aaca38a6..5d23e2e91 100644
--- a/frontend/ios/App/Watch/fr.lproj/Localizable.strings
+++ b/frontend/ios/App/Watch/fr.lproj/Localizable.strings
@@ -16,5 +16,6 @@
"No workout running" = "Aucune séance en cours";
"Start one on your iPhone and it shows up here." = "Lance-en une sur ton iPhone et elle apparaît ici.";
"All sets done" = "Toutes les séries faites";
+"measuring" = "mesure …";
"Next: %@, set %lld" = "Ensuite : %@, série %lld";
"%@, set %lld" = "%@, série %lld";
diff --git a/frontend/ios/App/Watch/hi.lproj/Localizable.strings b/frontend/ios/App/Watch/hi.lproj/Localizable.strings
index cba6c3c70..2b089dc2f 100644
--- a/frontend/ios/App/Watch/hi.lproj/Localizable.strings
+++ b/frontend/ios/App/Watch/hi.lproj/Localizable.strings
@@ -16,5 +16,6 @@
"No workout running" = "कोई वर्कआउट नहीं चल रहा";
"Start one on your iPhone and it shows up here." = "iPhone पर एक शुरू करें, यह यहाँ दिखेगा।";
"All sets done" = "सारे सेट पूरे";
+"measuring" = "माप रहा है …";
"Next: %@, set %lld" = "अगला: %@, सेट %lld";
"%@, set %lld" = "%@, सेट %lld";
diff --git a/frontend/ios/App/Watch/hu.lproj/Localizable.strings b/frontend/ios/App/Watch/hu.lproj/Localizable.strings
index 4d2aa62d9..1e278e81f 100644
--- a/frontend/ios/App/Watch/hu.lproj/Localizable.strings
+++ b/frontend/ios/App/Watch/hu.lproj/Localizable.strings
@@ -16,5 +16,6 @@
"No workout running" = "Nincs folyamatban edzés";
"Start one on your iPhone and it shows up here." = "Indíts egyet az iPhone-on, és itt megjelenik.";
"All sets done" = "Minden sorozat kész";
+"measuring" = "mérés …";
"Next: %@, set %lld" = "Következik: %@, %lld. sorozat";
"%@, set %lld" = "%@, %lld. sorozat";
diff --git a/frontend/ios/App/Watch/it.lproj/Localizable.strings b/frontend/ios/App/Watch/it.lproj/Localizable.strings
index 99e76a4bc..865144662 100644
--- a/frontend/ios/App/Watch/it.lproj/Localizable.strings
+++ b/frontend/ios/App/Watch/it.lproj/Localizable.strings
@@ -16,5 +16,6 @@
"No workout running" = "Nessun allenamento in corso";
"Start one on your iPhone and it shows up here." = "Avviane uno sull’iPhone e comparirà qui.";
"All sets done" = "Tutte le serie fatte";
+"measuring" = "misuro …";
"Next: %@, set %lld" = "Poi: %@, serie %lld";
"%@, set %lld" = "%@, serie %lld";
diff --git a/frontend/ios/App/Watch/ko.lproj/Localizable.strings b/frontend/ios/App/Watch/ko.lproj/Localizable.strings
index 50e5f387a..c33c0ad7d 100644
--- a/frontend/ios/App/Watch/ko.lproj/Localizable.strings
+++ b/frontend/ios/App/Watch/ko.lproj/Localizable.strings
@@ -16,5 +16,6 @@
"No workout running" = "진행 중인 운동이 없어요";
"Start one on your iPhone and it shows up here." = "iPhone에서 시작하면 여기에 나타나요.";
"All sets done" = "모든 세트 완료";
+"measuring" = "측정 중 …";
"Next: %@, set %lld" = "다음: %@, %lld세트";
"%@, set %lld" = "%@, %lld세트";
diff --git a/frontend/ios/App/Watch/pl.lproj/Localizable.strings b/frontend/ios/App/Watch/pl.lproj/Localizable.strings
index 74657ee1d..059a74f0f 100644
--- a/frontend/ios/App/Watch/pl.lproj/Localizable.strings
+++ b/frontend/ios/App/Watch/pl.lproj/Localizable.strings
@@ -16,5 +16,6 @@
"No workout running" = "Żaden trening nie trwa";
"Start one on your iPhone and it shows up here." = "Zacznij trening na iPhonie, a pojawi się tutaj.";
"All sets done" = "Wszystkie serie zrobione";
+"measuring" = "mierzę …";
"Next: %@, set %lld" = "Dalej: %@, seria %lld";
"%@, set %lld" = "%@, seria %lld";
diff --git a/frontend/ios/App/Watch/pt-BR.lproj/Localizable.strings b/frontend/ios/App/Watch/pt-BR.lproj/Localizable.strings
index 5b8c1f732..8dbf9953f 100644
--- a/frontend/ios/App/Watch/pt-BR.lproj/Localizable.strings
+++ b/frontend/ios/App/Watch/pt-BR.lproj/Localizable.strings
@@ -16,5 +16,6 @@
"No workout running" = "Nenhum treino em andamento";
"Start one on your iPhone and it shows up here." = "Comece um no iPhone e ele aparece aqui.";
"All sets done" = "Todas as séries feitas";
+"measuring" = "medindo …";
"Next: %@, set %lld" = "A seguir: %@, série %lld";
"%@, set %lld" = "%@, série %lld";
diff --git a/frontend/ios/App/Watch/pt-PT.lproj/Localizable.strings b/frontend/ios/App/Watch/pt-PT.lproj/Localizable.strings
index 059783671..90436d132 100644
--- a/frontend/ios/App/Watch/pt-PT.lproj/Localizable.strings
+++ b/frontend/ios/App/Watch/pt-PT.lproj/Localizable.strings
@@ -16,5 +16,6 @@
"No workout running" = "Nenhum treino a decorrer";
"Start one on your iPhone and it shows up here." = "Começa um no iPhone e ele aparece aqui.";
"All sets done" = "Todas as séries feitas";
+"measuring" = "a medir …";
"Next: %@, set %lld" = "A seguir: %@, série %lld";
"%@, set %lld" = "%@, série %lld";
diff --git a/frontend/ios/App/Watch/ru.lproj/Localizable.strings b/frontend/ios/App/Watch/ru.lproj/Localizable.strings
index b970487dd..8a1568d27 100644
--- a/frontend/ios/App/Watch/ru.lproj/Localizable.strings
+++ b/frontend/ios/App/Watch/ru.lproj/Localizable.strings
@@ -16,5 +16,6 @@
"No workout running" = "Тренировка не идёт";
"Start one on your iPhone and it shows up here." = "Начните её на iPhone, и она появится здесь.";
"All sets done" = "Все подходы сделаны";
+"measuring" = "измеряю …";
"Next: %@, set %lld" = "Далее: %@, подход %lld";
"%@, set %lld" = "%@, подход %lld";
diff --git a/frontend/ios/App/Watch/th.lproj/Localizable.strings b/frontend/ios/App/Watch/th.lproj/Localizable.strings
index 93ca6cdb2..ba503e6f0 100644
--- a/frontend/ios/App/Watch/th.lproj/Localizable.strings
+++ b/frontend/ios/App/Watch/th.lproj/Localizable.strings
@@ -16,5 +16,6 @@
"No workout running" = "ไม่มีการฝึกที่กำลังทำอยู่";
"Start one on your iPhone and it shows up here." = "เริ่มบน iPhone แล้วจะแสดงที่นี่";
"All sets done" = "ครบทุกเซ็ตแล้ว";
+"measuring" = "กำลังวัด …";
"Next: %@, set %lld" = "ถัดไป: %@ เซ็ต %lld";
"%@, set %lld" = "%@ เซ็ต %lld";
diff --git a/frontend/ios/App/Watch/tr.lproj/Localizable.strings b/frontend/ios/App/Watch/tr.lproj/Localizable.strings
index d83079ce2..cdf7fa998 100644
--- a/frontend/ios/App/Watch/tr.lproj/Localizable.strings
+++ b/frontend/ios/App/Watch/tr.lproj/Localizable.strings
@@ -16,5 +16,6 @@
"No workout running" = "Devam eden antrenman yok";
"Start one on your iPhone and it shows up here." = "iPhone’unda bir tane başlat, burada görünür.";
"All sets done" = "Tüm setler tamam";
+"measuring" = "ölçülüyor …";
"Next: %@, set %lld" = "Sıradaki: %@, set %lld";
"%@, set %lld" = "%@, set %lld";
diff --git a/frontend/ios/App/Watch/uk.lproj/Localizable.strings b/frontend/ios/App/Watch/uk.lproj/Localizable.strings
index 3c36c76a8..b0dcdedb1 100644
--- a/frontend/ios/App/Watch/uk.lproj/Localizable.strings
+++ b/frontend/ios/App/Watch/uk.lproj/Localizable.strings
@@ -16,5 +16,6 @@
"No workout running" = "Тренування не триває";
"Start one on your iPhone and it shows up here." = "Почни його на iPhone, і воно з’явиться тут.";
"All sets done" = "Усі підходи зроблено";
+"measuring" = "вимірюю …";
"Next: %@, set %lld" = "Далі: %@, підхід %lld";
"%@, set %lld" = "%@, підхід %lld";
diff --git a/frontend/ios/App/Watch/zh-Hans.lproj/Localizable.strings b/frontend/ios/App/Watch/zh-Hans.lproj/Localizable.strings
index 32252d7d2..ae30ec6cb 100644
--- a/frontend/ios/App/Watch/zh-Hans.lproj/Localizable.strings
+++ b/frontend/ios/App/Watch/zh-Hans.lproj/Localizable.strings
@@ -16,5 +16,6 @@
"No workout running" = "没有进行中的训练";
"Start one on your iPhone and it shows up here." = "在 iPhone 上开始,它就会出现在这里。";
"All sets done" = "所有组已完成";
+"measuring" = "测量中 …";
"Next: %@, set %lld" = "下一个:%@,第 %lld 组";
"%@, set %lld" = "%@,第 %lld 组";
diff --git a/frontend/ios/App/Watch/zh-Hant.lproj/Localizable.strings b/frontend/ios/App/Watch/zh-Hant.lproj/Localizable.strings
index fb8be807c..53cc7ed45 100644
--- a/frontend/ios/App/Watch/zh-Hant.lproj/Localizable.strings
+++ b/frontend/ios/App/Watch/zh-Hant.lproj/Localizable.strings
@@ -16,5 +16,6 @@
"No workout running" = "沒有進行中的訓練";
"Start one on your iPhone and it shows up here." = "在 iPhone 上開始,它就會出現在這裡。";
"All sets done" = "所有組已完成";
+"measuring" = "測量中 …";
"Next: %@, set %lld" = "下一個:%@,第 %lld 組";
"%@, set %lld" = "%@,第 %lld 組";
diff --git a/frontend/ios/App/WatchCore/Package.swift b/frontend/ios/App/WatchCore/Package.swift
new file mode 100644
index 000000000..d69be3fe5
--- /dev/null
+++ b/frontend/ios/App/WatchCore/Package.swift
@@ -0,0 +1,16 @@
+// swift-tools-version:5.9
+// The watch app's logic that has no UI: the session as the watch keeps it, how it is reconciled
+// with the phone's snapshots, and the animation codec. Compiled straight into the watch app (and
+// the codec into the iPhone app) by ios/ci/add-watch-app.rb; this package exists so CI can test it
+// with `swift test` on the Mac, no simulator needed.
+import PackageDescription
+
+let package = Package(
+ name: "WatchCore",
+ platforms: [.macOS(.v13), .watchOS(.v10), .iOS(.v15)],
+ products: [.library(name: "WatchCore", targets: ["WatchCore"])],
+ targets: [
+ .target(name: "WatchCore"),
+ .testTarget(name: "WatchCoreTests", dependencies: ["WatchCore"], resources: [.copy("Fixtures")]),
+ ]
+)
diff --git a/frontend/ios/App/WatchCore/Sources/WatchCore/ClipCodec.swift b/frontend/ios/App/WatchCore/Sources/WatchCore/ClipCodec.swift
new file mode 100644
index 000000000..66347e590
--- /dev/null
+++ b/frontend/ios/App/WatchCore/Sources/WatchCore/ClipCodec.swift
@@ -0,0 +1,76 @@
+import CoreGraphics
+import Foundation
+import ImageIO
+import UniformTypeIdentifiers
+
+/*
+ * Exercise animations for the watch, both ends (ImageIO only, so it builds on iOS, watchOS and the
+ * Mac that tests it):
+ *
+ * phone makeGif: the app's own clip (animated WebP, or a GIF) into a small looping GIF, frame by
+ * frame with each frame's own delay, scaled to `maxPixels`. The MP4 clips of other builds
+ * go through AVFoundation in WatchBridgePlugin and come out the same way.
+ * watch decode: that GIF back into frames and their total duration, to cycle on screen.
+ *
+ * Never a source of media itself: it converts what the phone already has for the running workout.
+ */
+enum ClipCodec {
+ struct Frames {
+ let images: [CGImage]
+ let delays: [Double]
+ var duration: Double { delays.reduce(0, +) }
+ }
+
+ static let minDelay = 0.02
+ static let fallbackDelay = 0.1
+
+ private static func delay(_ props: [String: Any]?) -> Double {
+ let webp = props?[kCGImagePropertyWebPDictionary as String] as? [String: Any]
+ let gif = props?[kCGImagePropertyGIFDictionary as String] as? [String: Any]
+ let d = (webp?[kCGImagePropertyWebPUnclampedDelayTime as String] as? Double)
+ ?? (webp?[kCGImagePropertyWebPDelayTime as String] as? Double)
+ ?? (gif?[kCGImagePropertyGIFUnclampedDelayTime as String] as? Double)
+ ?? (gif?[kCGImagePropertyGIFDelayTime as String] as? Double)
+ ?? fallbackDelay
+ return d >= minDelay ? d : fallbackDelay
+ }
+
+ /// Frames and delays of an animated (or still) image file, each scaled to `maxPixels` at most.
+ static func decode(_ url: URL, maxPixels: Int? = nil) -> Frames? {
+ guard let src = CGImageSourceCreateWithURL(url as CFURL, nil) else { return nil }
+ let count = CGImageSourceGetCount(src)
+ guard count > 0 else { return nil }
+ var images: [CGImage] = []
+ var delays: [Double] = []
+ let thumb: CFDictionary? = maxPixels.map {
+ [kCGImageSourceCreateThumbnailFromImageAlways as String: true,
+ kCGImageSourceThumbnailMaxPixelSize as String: $0,
+ kCGImageSourceCreateThumbnailWithTransform as String: true] as CFDictionary
+ }
+ for i in 0..<count {
+ let img = thumb != nil ? CGImageSourceCreateThumbnailAtIndex(src, i, thumb) : CGImageSourceCreateImageAtIndex(src, i, nil)
+ guard let image = img else { continue }
+ images.append(image)
+ delays.append(delay(CGImageSourceCopyPropertiesAtIndex(src, i, nil) as? [String: Any]))
+ }
+ return images.isEmpty ? nil : Frames(images: images, delays: delays)
+ }
+
+ /// Writes `frames` as a looping GIF. False when nothing could be written.
+ static func writeGif(_ frames: Frames, to out: URL) -> Bool {
+ guard let dest = CGImageDestinationCreateWithURL(out as CFURL, UTType.gif.identifier as CFString, frames.images.count, nil) else { return false }
+ CGImageDestinationSetProperties(dest, [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: 0]] as CFDictionary)
+ for (img, d) in zip(frames.images, frames.delays) {
+ CGImageDestinationAddImage(dest, img, [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: d]] as CFDictionary)
+ }
+ return CGImageDestinationFinalize(dest)
+ }
+
+ /// The phone's conversion: an animated WebP or GIF into a small looping GIF.
+ static func makeGif(from source: URL, to out: URL, maxPixels: Int = 160) -> Bool {
+ guard let frames = decode(source, maxPixels: maxPixels) else { return false }
+ if writeGif(frames, to: out) { return true }
+ try? FileManager.default.removeItem(at: out)
+ return false
+ }
+}
diff --git a/frontend/ios/App/WatchCore/Sources/WatchCore/Model.swift b/frontend/ios/App/WatchCore/Sources/WatchCore/Model.swift
new file mode 100644
index 000000000..9c68d95e9
--- /dev/null
+++ b/frontend/ios/App/WatchCore/Sources/WatchCore/Model.swift
@@ -0,0 +1,71 @@
+import Foundation
+
+/*
+ * What the phone sends the watch (frontend lib/watch-sync.js buildSnapshot), as the watch reads
+ * it. Plain data, no media. Every field the phone may leave out is optional, so an older or a
+ * newer phone never makes the watch fail to read a snapshot.
+ */
+
+struct Snapshot: Codable, Equatable {
+ var v: Int
+ var unit: String?
+ var restSec: Double?
+ var active: ActiveWorkout?
+ var ready: Ready?
+ var settings: WatchSettings?
+}
+
+/// What the watch can start by itself: today's planned session and a few other routines.
+struct Ready: Codable, Equatable {
+ var today: ReadySession?
+ var others: [ReadySession]
+}
+
+struct ReadySession: Codable, Equatable {
+ var routineIds: [String]
+ var name: String
+ var entries: [Entry]
+}
+
+struct ActiveWorkout: Codable, Equatable {
+ var id: String?
+ var name: String
+ var unit: String
+ var cur: Int
+ var restSec: Double
+ var rest: RestInfo?
+ var entries: [Entry]
+}
+
+struct RestInfo: Codable, Equatable {
+ var endsAt: Double
+}
+
+struct Entry: Codable, Equatable {
+ var id: String
+ var name: String
+ var mode: String
+ var restSec: Double?
+ var last: String?
+ var sets: [SetRow]
+}
+
+struct SetRow: Codable, Equatable {
+ var w: Double?
+ var r: Double?
+ var sec: Double?
+ var done: Bool
+ var warmup: Bool
+ /// When it was ticked (ms since 1970), on whichever side ticked it: the later tick wins.
+ var at: Double?
+}
+
+/// The phone's Settings → Apple Watch (frontend lib/watch-settings.js).
+struct WatchSettings: Codable, Equatable {
+ /// Apple Health workout session (live heart rate, saved workouts).
+ var health: Bool?
+ /// The wrist taps when a rest is over.
+ var restHaptics: Bool?
+ /// What the Digital Crown turns first on a set: "reps" or "weight".
+ var crown: String?
+}
diff --git a/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swift b/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swift
new file mode 100644
index 000000000..24483e6a2
--- /dev/null
+++ b/frontend/ios/App/WatchCore/Sources/WatchCore/SessionCore.swift
@@ -0,0 +1,166 @@
+import Foundation
+
+/*
+ * The session as the watch keeps it, and every change to it, as pure functions: the watch app's
+ * SessionStore only calls these, saves the state after each, and sends the events they return.
+ * Tested with `swift test` (Tests/WatchCoreTests), no watch needed.
+ *
+ * The sync, case by case (the phone's side: frontend lib/watch-sync.js):
+ *
+ * watch app never opened before the workout started on the phone
+ * the phone keeps its snapshot as the application context, which the watch reads when it
+ * launches (applySnapshot): it picks the running workout up where the phone has it.
+ * watch app killed and relaunched mid-workout
+ * the whole state is saved after every change and restored at launch; then the latest
+ * snapshot is applied over it, with the watch's own unconfirmed ticks kept (below).
+ * phone asleep, locked in a pocket, app killed, Bluetooth off, out of range
+ * the watch runs the session alone; each tick, start and finish is an event sent with
+ * transferUserInfo, which the system queues and delivers, in order, when it can; the phone
+ * applies each one once, by its id.
+ * a snapshot older than the watch's own ticks (sent before the phone applied them)
+ * a tick stays pending until a snapshot shows that set done at the tick's time or later;
+ * until then the snapshot's copy of that set is replaced by the watch's.
+ * the same set changed on both sides
+ * the later tick (`at`) wins, on both sides: here in applySnapshot, on the phone in the
+ * workout screen's watch handler.
+ * finished on the watch while the phone was away
+ * the workout leaves the watch at once; a snapshot that still shows it running (the phone
+ * has not heard yet) does not bring it back.
+ * finished on the phone while the watch was away
+ * a snapshot without it ends it here; ticks the watch made meanwhile are still sent, and
+ * the phone writes them into the saved workout.
+ * started on the watch while the phone was away
+ * kept until the phone reports it back running; a snapshot without it does not end it.
+ */
+
+struct PendingTick: Codable, Equatable {
+ var w: Double?
+ var r: Double?
+ var at: Double
+}
+
+struct SessionState: Codable, Equatable {
+ var workout: ActiveWorkout?
+ var ready: Ready?
+ var settings = WatchSettings()
+ var unit = "kg"
+ var restSec: Double = 90
+ /// A session started here that the phone has not reported back running yet.
+ var startedHere: String?
+ /// Sessions finished here that the phone may still report running for a while.
+ var finishedHere: [String] = []
+ /// Ticks made here, by "exerciseId#setIndex", until a snapshot shows them.
+ var pending: [String: PendingTick] = [:]
+ /// The exercise on screen.
+ var entryIndex = 0
+}
+
+typealias Event = [String: Any]
+
+enum SessionCore {
+ static func key(_ exId: String, _ si: Int) -> String { "\(exId)#\(si)" }
+
+ /// A snapshot from the phone, over what the watch has.
+ static func applySnapshot(_ s0: SessionState, _ snap: Snapshot) -> SessionState {
+ var s = s0
+ s.ready = snap.ready
+ if let u = snap.unit { s.unit = u }
+ if let r = snap.restSec, r > 0 { s.restSec = r }
+ if let st = snap.settings { s.settings = st }
+
+ // A session started here that the phone has not reported back yet stays, whatever it sends.
+ let unconfirmed = s.workout?.id != nil && s.workout?.id == s.startedHere
+ guard var next = snap.active, !(next.id.map { s.finishedHere.contains($0) } ?? false) else {
+ // No workout on the phone, or one the watch has finished already.
+ if unconfirmed { return s }
+ s.workout = nil
+ s.pending = [:]
+ return s
+ }
+ let same = next.id != nil && next.id == s.workout?.id
+ if next.id != nil && next.id == s.startedHere { s.startedHere = nil }
+ if !same && unconfirmed {
+ // The phone runs a different workout than the one started here and not yet confirmed:
+ // the watch keeps its own; the phone keeps its own (frontend: a start while another runs).
+ return s
+ }
+ if !same {
+ // Another workout (or the first one this watch sees): its own position, no old ticks.
+ s.pending = [:]
+ s.entryIndex = next.cur
+ }
+ // The watch's ticks the phone has not shown yet win; the later tick wins on a set both changed.
+ for (ei, e) in next.entries.enumerated() {
+ for (si, row) in e.sets.enumerated() {
+ let k = key(e.id, si)
+ guard let p = s.pending[k] else { continue }
+ if row.done && (row.at ?? .infinity) >= p.at {
+ s.pending[k] = nil // the phone has it (or a later change of its own)
+ } else {
+ next.entries[ei].sets[si].done = true
+ next.entries[ei].sets[si].w = p.w ?? row.w
+ next.entries[ei].sets[si].r = p.r ?? row.r
+ next.entries[ei].sets[si].at = p.at
+ }
+ }
+ }
+ s.entryIndex = min(max(0, s.entryIndex), next.entries.count) // the last page is Finish
+ s.workout = next
+ return s
+ }
+
+ /// A set ticked here: the state with it done, and the event for the phone.
+ static func tick(_ s0: SessionState, entry ei: Int, set si: Int, w: Double, r: Double, at: Double, id: String, hr: [String: Double]? = nil) -> (SessionState, Event?) {
+ guard var workout = s0.workout, workout.entries.indices.contains(ei), workout.entries[ei].sets.indices.contains(si) else { return (s0, nil) }
+ var s = s0
+ let e = workout.entries[ei]
+ workout.entries[ei].sets[si].done = true
+ workout.entries[ei].sets[si].w = w
+ workout.entries[ei].sets[si].r = r
+ workout.entries[ei].sets[si].at = at
+ s.workout = workout
+ s.pending[key(e.id, si)] = PendingTick(w: w, r: r, at: at)
+ var event: Event = [
+ "id": id, "type": "setDone", "wid": workout.id ?? "", "exId": e.id,
+ "entryIdx": ei, "setIdx": si, "w": w, "r": r, "at": at,
+ ]
+ if let hr = hr { event["hr"] = hr }
+ return (s, event)
+ }
+
+ /// A ready session started here.
+ static func start(_ s0: SessionState, _ session: ReadySession, wid: String, at: Double, id: String) -> (SessionState, Event) {
+ var s = s0
+ s.workout = ActiveWorkout(id: wid, name: session.name, unit: s.unit, cur: 0, restSec: s.restSec, rest: nil, entries: session.entries)
+ s.startedHere = wid
+ s.pending = [:]
+ s.entryIndex = 0
+ return (s, ["id": id, "type": "start", "routineIds": session.routineIds, "wid": wid, "at": at])
+ }
+
+ /// The session finished here.
+ static func finish(_ s0: SessionState, at: Double, id: String) -> (SessionState, Event?) {
+ guard let w = s0.workout else { return (s0, nil) }
+ var s = s0
+ s.workout = nil
+ s.pending = [:]
+ s.startedHere = nil
+ if let wid = w.id { s.finishedHere = Array((s.finishedHere + [wid]).suffix(5)) }
+ return (s, ["id": id, "type": "finish", "wid": w.id ?? "", "at": at])
+ }
+
+ /// The set to do next in an exercise: the one picked, or the first not done.
+ static func setIndex(_ s: SessionState, entry ei: Int, picked: Int? = nil) -> Int? {
+ guard let w = s.workout, w.entries.indices.contains(ei) else { return nil }
+ let sets = w.entries[ei].sets
+ if let p = picked, sets.indices.contains(p), !sets[p].done { return p }
+ return sets.firstIndex { !$0.done }
+ }
+
+ /// Sets done and sets in all, for the complication's ring.
+ static func progress(_ s: SessionState) -> (done: Int, total: Int) {
+ guard let w = s.workout else { return (0, 0) }
+ let all = w.entries.flatMap { $0.sets }.filter { !$0.warmup }
+ return (all.filter { $0.done }.count, all.count)
+ }
+}
diff --git a/frontend/ios/App/WatchCore/Tests/WatchCoreTests/ClipCodecTests.swift b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/ClipCodecTests.swift
new file mode 100644
index 000000000..b0e673753
--- /dev/null
+++ b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/ClipCodecTests.swift
@@ -0,0 +1,38 @@
+import XCTest
+@testable import WatchCore
+
+/// The animation path, end to end, on a synthetic clip (Fixtures/synthetic-square.webp: a green
+/// square moving across black, made with ffmpeg for this test; no exercise media anywhere):
+/// the phone's WebP → GIF conversion, then the watch's decoding of that GIF.
+final class ClipCodecTests: XCTestCase {
+ func fixture() throws -> URL {
+ try XCTUnwrap(Bundle.module.url(forResource: "synthetic-square", withExtension: "webp", subdirectory: "Fixtures"))
+ }
+
+ func testTheAnimatedWebPDecodesWithItsFramesAndDelays() throws {
+ let frames = try XCTUnwrap(ClipCodec.decode(try fixture()))
+ XCTAssertGreaterThan(frames.images.count, 5, "every frame of the animation")
+ XCTAssertEqual(frames.images.count, frames.delays.count)
+ XCTAssertEqual(frames.duration, 1.2, accuracy: 0.25)
+ XCTAssertNotEqual(frames.images.first?.dataProvider?.data as Data?, frames.images.last?.dataProvider?.data as Data?, "it moves")
+ }
+
+ func testThePhoneMakesASmallLoopingGifTheWatchReadsBack() throws {
+ let out = FileManager.default.temporaryDirectory.appendingPathComponent("clip-\(UUID().uuidString).gif")
+ defer { try? FileManager.default.removeItem(at: out) }
+ XCTAssertTrue(ClipCodec.makeGif(from: try fixture(), to: out, maxPixels: 120))
+ let back = try XCTUnwrap(ClipCodec.decode(out))
+ let source = try XCTUnwrap(ClipCodec.decode(try fixture()))
+ XCTAssertEqual(back.images.count, source.images.count)
+ XCTAssertLessThanOrEqual(back.images[0].width, 120)
+ XCTAssertEqual(back.duration, source.duration, accuracy: 0.1)
+ }
+
+ func testSomethingThatIsNotAnImageGivesNothing() throws {
+ let junk = FileManager.default.temporaryDirectory.appendingPathComponent("junk-\(UUID().uuidString).webp")
+ try Data("not an image".utf8).write(to: junk)
+ defer { try? FileManager.default.removeItem(at: junk) }
+ XCTAssertNil(ClipCodec.decode(junk))
+ XCTAssertFalse(ClipCodec.makeGif(from: junk, to: junk.appendingPathExtension("gif")))
+ }
+}
diff --git a/frontend/ios/App/WatchCore/Tests/WatchCoreTests/Fixtures/synthetic-square.webp b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/Fixtures/synthetic-square.webp
new file mode 100644
index 000000000..d222f6751
Binary files /dev/null and b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/Fixtures/synthetic-square.webp differ
diff --git a/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SessionCoreTests.swift b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SessionCoreTests.swift
new file mode 100644
index 000000000..62bf917fd
--- /dev/null
+++ b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/SessionCoreTests.swift
@@ -0,0 +1,115 @@
+import XCTest
+@testable import WatchCore
+
+/// The watch's session against the sync cases (SessionCore's header lists them).
+final class SessionCoreTests: XCTestCase {
+ func row(_ w: Double, _ r: Double, done: Bool = false, at: Double? = nil) -> SetRow {
+ SetRow(w: w, r: r, sec: nil, done: done, warmup: false, at: at)
+ }
+
+ func workout(_ id: String, sets: [SetRow], cur: Int = 0) -> ActiveWorkout {
+ ActiveWorkout(id: id, name: "Push", unit: "kg", cur: cur, restSec: 90, rest: nil,
+ entries: [Entry(id: "0025", name: "Bench Press", mode: "reps", restSec: nil, last: nil, sets: sets),
+ Entry(id: "0426", name: "Overhead Press", mode: "reps", restSec: nil, last: nil, sets: [row(40, 8)])])
+ }
+
+ func snap(_ w: ActiveWorkout?) -> Snapshot { Snapshot(v: 1, unit: "kg", restSec: 90, active: w, ready: nil, settings: nil) }
+
+ func testPicksUpAWorkoutRunningOnThePhoneWhenFirstOpened() {
+ let s = SessionCore.applySnapshot(SessionState(), snap(workout("p1", sets: [row(60, 8, done: true, at: 1), row(60, 8)], cur: 1)))
+ XCTAssertEqual(s.workout?.id, "p1")
+ XCTAssertEqual(s.entryIndex, 1)
+ XCTAssertEqual(SessionCore.setIndex(s, entry: 0), 1)
+ }
+
+ func testATickStaysUntilTheSnapshotShowsItAndTheLaterTickWins() {
+ var s = SessionCore.applySnapshot(SessionState(), snap(workout("p1", sets: [row(60, 8), row(60, 8)])))
+ let (t, event) = SessionCore.tick(s, entry: 0, set: 0, w: 62.5, r: 7, at: 1000, id: "e1")
+ s = t
+ XCTAssertEqual(event?["type"] as? String, "setDone")
+ XCTAssertEqual(event?["wid"] as? String, "p1")
+ // an older snapshot, sent before the phone applied the tick: the tick stays
+ s = SessionCore.applySnapshot(s, snap(workout("p1", sets: [row(60, 8), row(60, 8)])))
+ XCTAssertEqual(s.workout?.entries[0].sets[0], row(62.5, 7, done: true, at: 1000))
+ XCTAssertNotNil(s.pending["0025#0"])
+ // the phone changed that set itself earlier: the watch's later tick still wins
+ s = SessionCore.applySnapshot(s, snap(workout("p1", sets: [row(55, 5, done: true, at: 500), row(60, 8)])))
+ XCTAssertEqual(s.workout?.entries[0].sets[0].w, 62.5)
+ // the phone has applied it: confirmed, no longer pending
+ s = SessionCore.applySnapshot(s, snap(workout("p1", sets: [row(62.5, 7, done: true, at: 1000), row(60, 8)])))
+ XCTAssertNil(s.pending["0025#0"])
+ // a later change on the phone wins over the watch's tick
+ s = SessionCore.tick(s, entry: 0, set: 1, w: 60, r: 8, at: 2000, id: "e2").0
+ s = SessionCore.applySnapshot(s, snap(workout("p1", sets: [row(62.5, 7, done: true, at: 1000), row(65, 6, done: true, at: 3000)])))
+ XCTAssertEqual(s.workout?.entries[0].sets[1].w, 65)
+ XCTAssertNil(s.pending["0025#1"])
+ }
+
+ func testRelaunchRestoresTheSessionWithItsUnconfirmedTicks() throws {
+ var s = SessionCore.applySnapshot(SessionState(), snap(workout("p1", sets: [row(60, 8), row(60, 8)])))
+ s = SessionCore.tick(s, entry: 0, set: 0, w: 60, r: 8, at: 1000, id: "e1").0
+ let saved = try JSONEncoder().encode(s)
+ var back = try JSONDecoder().decode(SessionState.self, from: saved)
+ XCTAssertEqual(back, s)
+ // the latest context is the old snapshot: the tick survives
+ back = SessionCore.applySnapshot(back, snap(workout("p1", sets: [row(60, 8), row(60, 8)])))
+ XCTAssertTrue(back.workout?.entries[0].sets[0].done ?? false)
+ }
+
+ func testFinishedOnTheWatchStaysFinishedThoughThePhoneHasNotHeard() {
+ var s = SessionCore.applySnapshot(SessionState(), snap(workout("p1", sets: [row(60, 8)])))
+ let (f, event) = SessionCore.finish(s, at: 5000, id: "f1")
+ s = f
+ XCTAssertEqual(event?["type"] as? String, "finish")
+ XCTAssertNil(s.workout)
+ s = SessionCore.applySnapshot(s, snap(workout("p1", sets: [row(60, 8)])))
+ XCTAssertNil(s.workout, "a snapshot from before the phone applied the finish does not bring it back")
+ s = SessionCore.applySnapshot(s, snap(workout("p2", sets: [row(60, 8)])))
+ XCTAssertEqual(s.workout?.id, "p2", "the next workout does show")
+ }
+
+ func testFinishedOnThePhoneEndsItHere() {
+ var s = SessionCore.applySnapshot(SessionState(), snap(workout("p1", sets: [row(60, 8)])))
+ s = SessionCore.applySnapshot(s, snap(nil))
+ XCTAssertNil(s.workout)
+ XCTAssertTrue(s.pending.isEmpty)
+ }
+
+ func testStartedOnTheWatchStaysUntilThePhoneHasIt() {
+ let ready = ReadySession(routineIds: ["r1"], name: "Push", entries: workout("x", sets: [row(60, 8)]).entries)
+ var (s, event) = SessionCore.start(SessionState(), ready, wid: "watch-1", at: 100, id: "s1")
+ XCTAssertEqual(event["type"] as? String, "start")
+ XCTAssertEqual(event["wid"] as? String, "watch-1")
+ s = SessionCore.tick(s, entry: 0, set: 0, w: 60, r: 8, at: 200, id: "e1").0
+ s = SessionCore.applySnapshot(s, snap(nil))
+ XCTAssertEqual(s.workout?.id, "watch-1", "the phone has not heard of it yet")
+ s = SessionCore.applySnapshot(s, snap(workout("phone-other", sets: [row(1, 1)])))
+ XCTAssertEqual(s.workout?.id, "watch-1", "another workout on the phone does not replace it")
+ s = SessionCore.applySnapshot(s, snap(workout("watch-1", sets: [row(60, 8), row(40, 8)])))
+ XCTAssertNil(s.startedHere, "the phone runs it now")
+ XCTAssertTrue(s.workout?.entries[0].sets[0].done ?? false, "with the tick made before it heard")
+ }
+
+ func testAnotherWorkoutOnThePhoneStartsClean() {
+ var s = SessionCore.applySnapshot(SessionState(), snap(workout("p1", sets: [row(60, 8)])))
+ s = SessionCore.tick(s, entry: 0, set: 0, w: 60, r: 8, at: 1, id: "e1").0
+ s = SessionCore.applySnapshot(s, snap(workout("p2", sets: [row(70, 5)], cur: 1)))
+ XCTAssertEqual(s.workout?.id, "p2")
+ XCTAssertFalse(s.workout?.entries[0].sets[0].done ?? true, "an old tick never lands on another workout")
+ XCTAssertEqual(s.entryIndex, 1)
+ }
+
+ func testProgressCountsWorkSetsOnly() {
+ var w = workout("p1", sets: [row(60, 8, done: true, at: 1), row(60, 8)])
+ w.entries[0].sets.insert(SetRow(w: 20, r: 10, sec: nil, done: true, warmup: true, at: 1), at: 0)
+ let s = SessionCore.applySnapshot(SessionState(), snap(w))
+ XCTAssertEqual(SessionCore.progress(s).done, 1)
+ XCTAssertEqual(SessionCore.progress(s).total, 3)
+ }
+
+ func testReadsASnapshotWithFieldsItDoesNotKnowAndWithoutOptionalOnes() throws {
+ let json = #"{"v":1,"future":true,"active":{"id":"p1","name":"Push","unit":"kg","cur":0,"restSec":90,"entries":[{"id":"0025","name":"Bench","mode":"reps","sets":[{"w":60,"r":8,"done":false,"warmup":false,"hr":{"avg":1}}]}]}}"#
+ let snap = try JSONDecoder().decode(Snapshot.self, from: Data(json.utf8))
+ XCTAssertEqual(SessionCore.applySnapshot(SessionState(), snap).workout?.entries.first?.sets.count, 1)
+ }
+}
diff --git a/frontend/ios/App/WatchWidgets/OpenGymWidgets.swift b/frontend/ios/App/WatchWidgets/OpenGymWidgets.swift
index 10e130fbc..553947423 100644
--- a/frontend/ios/App/WatchWidgets/OpenGymWidgets.swift
+++ b/frontend/ios/App/WatchWidgets/OpenGymWidgets.swift
@@ -18,7 +18,7 @@ struct Entry: TimelineEntry {
switch state.mode {
case "rest": return TimelineEntryRelevance(score: 100)
case "set": return TimelineEntryRelevance(score: 60)
- case "today": return TimelineEntryRelevance(score: 10)
+ case "today": return TimelineEntryRelevance(score: 30)
default: return TimelineEntryRelevance(score: 0)
}
}
@@ -44,61 +44,98 @@ struct Provider: TimelineProvider {
}
}
+/// Work sets done of all today, as a ring (circular and corner complications).
+struct ProgressRing: View {
+ let done: Int
+ let total: Int
+
+ var body: some View {
+ Gauge(value: Double(done), in: 0...Double(max(total, 1))) {
+ Image(systemName: "dumbbell.fill")
+ } currentValueLabel: {
+ Text(verbatim: "\(done)")
+ }
+ .gaugeStyle(.accessoryCircularCapacity)
+ }
+}
+
struct WidgetView: View {
@Environment(\.widgetFamily) var family
let entry: Entry
var body: some View {
let s = entry.state
+ let resting = s.mode == "rest" && (s.restEndsAt.map { $0 > entry.date } ?? false)
switch family {
case .accessoryCircular:
- if s.mode == "rest", let end = s.restEndsAt, end > entry.date {
+ if resting, let end = s.restEndsAt {
ProgressView(timerInterval: entry.date...end, countsDown: true) {
Image(systemName: "timer")
} currentValueLabel: {
Text(timerInterval: entry.date...end, countsDown: true).monospacedDigit()
}
.progressViewStyle(.circular)
+ } else if s.mode == "today" {
+ ZStack {
+ AccessoryWidgetBackground()
+ Image(systemName: "play.fill").font(.title3)
+ }
+ } else if s.total > 0 {
+ ProgressRing(done: s.done, total: s.total)
} else {
ZStack {
AccessoryWidgetBackground()
- Image(systemName: s.mode == "today" ? "play.fill" : "dumbbell.fill").font(.title3)
+ Image(systemName: "dumbbell.fill").font(.title3)
}
}
case .accessoryInline:
- if s.mode == "rest", let end = s.restEndsAt, end > entry.date {
+ if resting, let end = s.restEndsAt {
Text(timerInterval: entry.date...end, countsDown: true)
+ } else if s.mode == "today" {
+ Text("Start workout")
} else {
- Text(verbatim: s.detail.isEmpty ? s.title : s.detail)
+ Text(verbatim: s.detail.isEmpty ? s.title : "\(s.setLabel) · \(s.detail)")
}
case .accessoryCorner:
- Image(systemName: s.mode == "rest" ? "timer" : "dumbbell.fill")
- .font(.title3)
- .widgetLabel {
- if s.mode == "rest", let end = s.restEndsAt, end > entry.date {
- Text(timerInterval: entry.date...end, countsDown: true)
- } else {
- Text(verbatim: s.title)
- }
+ Group {
+ if s.total > 0 && s.mode != "today" {
+ Text(verbatim: "\(s.done)")
+ .font(.title3.monospacedDigit())
+ } else {
+ Image(systemName: s.mode == "today" ? "play.fill" : "dumbbell.fill").font(.title3)
+ }
+ }
+ .widgetLabel {
+ if resting, let end = s.restEndsAt {
+ Text(timerInterval: entry.date...end, countsDown: true)
+ } else if s.total > 0 && s.mode != "today" {
+ Gauge(value: Double(s.done), in: 0...Double(max(s.total, 1))) { Text(verbatim: "") }
+ } else {
+ Text(verbatim: s.title)
}
+ }
default:
VStack(alignment: .leading, spacing: 2) {
- HStack(spacing: 4) {
- Image(systemName: s.mode == "rest" ? "timer" : s.mode == "today" ? "play.fill" : "dumbbell.fill")
- Text(verbatim: s.mode == "rest" ? s.title : "openGym").lineLimit(1)
- }
- .font(.caption2)
- .foregroundStyle(.secondary)
- if s.mode == "rest", let end = s.restEndsAt, end > entry.date {
+ if resting, let end = s.restEndsAt {
+ Label("Rest", systemImage: "timer").font(.caption2).foregroundStyle(.secondary)
Text(timerInterval: entry.date...end, countsDown: true)
.font(.system(.title2, design: .rounded).weight(.semibold).monospacedDigit())
- } else {
- Text(verbatim: s.title)
- .font(.system(.headline, design: .rounded))
- .lineLimit(1)
+ Text(verbatim: s.title).font(.caption2).lineLimit(1)
+ } else if s.mode == "today" {
+ Label("Start workout", systemImage: "play.fill").font(.caption2).foregroundStyle(.secondary)
+ Text(verbatim: s.title).font(.system(.headline, design: .rounded)).lineLimit(2)
+ } else if s.mode == "set" {
+ Text(verbatim: s.title).font(.system(.headline, design: .rounded)).lineLimit(1)
if !s.detail.isEmpty {
- Text(verbatim: s.detail).font(.system(.body, design: .rounded).monospacedDigit()).lineLimit(1)
+ Text(verbatim: s.setLabel.isEmpty ? s.detail : "\(s.setLabel) · \(s.detail)")
+ .font(.system(.body, design: .rounded).monospacedDigit()).lineLimit(1)
+ }
+ if s.total > 0 {
+ Gauge(value: Double(s.done), in: 0...Double(s.total)) { Text(verbatim: "") }
+ .gaugeStyle(.accessoryLinearCapacity)
}
+ } else {
+ Label("openGym", systemImage: "dumbbell.fill").font(.headline)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
@@ -112,6 +149,8 @@ struct OpenGymWidget: Widget {
StaticConfiguration(kind: "OpenGymWorkout", provider: Provider()) { entry in
WidgetView(entry: entry)
.containerBackground(.black, for: .widget)
+ // A tap on "Start" opens the watch app and starts today's workout.
+ .widgetURL(entry.state.mode == "today" ? URL(string: "opengym-watch://start") : URL(string: "opengym-watch://open"))
}
.configurationDisplayName("openGym")
.description("Your rest, your next set, or today's workout.")
diff --git a/frontend/ios/App/WatchWidgets/ar.lproj/Localizable.strings b/frontend/ios/App/WatchWidgets/ar.lproj/Localizable.strings
new file mode 100644
index 000000000..e66aa0c52
--- /dev/null
+++ b/frontend/ios/App/WatchWidgets/ar.lproj/Localizable.strings
@@ -0,0 +1,21 @@
+/* openGym on the Apple Watch, ar. Written by ios/ci/watch-strings.mjs: change that, not this. */
+
+"Today" = "اليوم";
+"Start workout" = "بدء التمرين";
+"Done" = "تم";
+"Warm-up" = "إحماء";
+"Reps" = "التكرارات";
+"Rest" = "راحة";
+"Skip" = "تخطّي";
+"Finish workout" = "إنهاء التمرين";
+"Finish workout?" = "إنهاء التمرين؟";
+"Finish and save" = "إنهاء وحفظ";
+"Cancel" = "إلغاء";
+"Rest’s over. Next set!" = "انتهت الراحة. المجموعة التالية!";
+"Last time: %@" = "المرة السابقة: %@";
+"No workout running" = "لا يوجد تمرين جارٍ";
+"Start one on your iPhone and it shows up here." = "ابدأ تمرينًا على iPhone وسيظهر هنا.";
+"All sets done" = "اكتملت كل المجموعات";
+"measuring" = "جارٍ القياس …";
+"Next: %@, set %lld" = "التالي: %@، المجموعة %lld";
+"%@, set %lld" = "%@، المجموعة %lld";
diff --git a/frontend/ios/App/WatchWidgets/bn.lproj/Localizable.strings b/frontend/ios/App/WatchWidgets/bn.lproj/Localizable.strings
new file mode 100644
index 000000000..76493c20f
--- /dev/null
+++ b/frontend/ios/App/WatchWidgets/bn.lproj/Localizable.strings
@@ -0,0 +1,21 @@
+/* openGym on the Apple Watch, bn. Written by ios/ci/watch-strings.mjs: change that, not this. */
+
+"Today" = "আজ";
+"Start workout" = "ওয়ার্কআউট শুরু করুন";
+"Done" = "সম্পন্ন";
+"Warm-up" = "ওয়ার্ম-আপ";
+"Reps" = "রেপ";
+"Rest" = "বিশ্রাম";
+"Skip" = "এড়িয়ে যান";
+"Finish workout" = "ওয়ার্কআউট শেষ করুন";
+"Finish workout?" = "ওয়ার্কআউট শেষ করবেন?";
+"Finish and save" = "শেষ করে সেভ করুন";
+"Cancel" = "বাতিল";
+"Rest’s over. Next set!" = "বিশ্রাম শেষ। পরের সেট!";
+"Last time: %@" = "গতবার: %@";
+"No workout running" = "কোনো ওয়ার্কআউট চলছে না";
+"Start one on your iPhone and it shows up here." = "iPhone-এ একটি শুরু করুন, এখানে দেখা যাবে।";
+"All sets done" = "সব সেট শেষ";
+"measuring" = "মাপা হচ্ছে …";
+"Next: %@, set %lld" = "এরপর: %@, সেট %lld";
+"%@, set %lld" = "%@, সেট %lld";
diff --git a/frontend/ios/App/WatchWidgets/de.lproj/Localizable.strings b/frontend/ios/App/WatchWidgets/de.lproj/Localizable.strings
new file mode 100644
index 000000000..2c18546d6
--- /dev/null
+++ b/frontend/ios/App/WatchWidgets/de.lproj/Localizable.strings
@@ -0,0 +1,21 @@
+/* openGym on the Apple Watch, de. Written by ios/ci/watch-strings.mjs: change that, not this. */
+
+"Today" = "Heute";
+"Start workout" = "Training starten";
+"Done" = "Fertig";
+"Warm-up" = "Aufwärmen";
+"Reps" = "Wdh.";
+"Rest" = "Pause";
+"Skip" = "Überspringen";
+"Finish workout" = "Training beenden";
+"Finish workout?" = "Training beenden?";
+"Finish and save" = "Beenden und speichern";
+"Cancel" = "Abbrechen";
+"Rest’s over. Next set!" = "Pause vorbei. Nächster Satz!";
+"Last time: %@" = "Letztes Mal: %@";
+"No workout running" = "Kein Training läuft";
+"Start one on your iPhone and it shows up here." = "Starte eins auf dem iPhone, dann taucht es hier auf.";
+"All sets done" = "Alle Sätze erledigt";
+"measuring" = "misst …";
+"Next: %@, set %lld" = "Als Nächstes: %@, Satz %lld";
+"%@, set %lld" = "%@, Satz %lld";
diff --git a/frontend/ios/App/WatchWidgets/es.lproj/Localizable.strings b/frontend/ios/App/WatchWidgets/es.lproj/Localizable.strings
new file mode 100644
index 000000000..abcd23339
--- /dev/null
+++ b/frontend/ios/App/WatchWidgets/es.lproj/Localizable.strings
@@ -0,0 +1,21 @@
+/* openGym on the Apple Watch, es. Written by ios/ci/watch-strings.mjs: change that, not this. */
+
+"Today" = "Hoy";
+"Start workout" = "Empezar entrenamiento";
+"Done" = "Listo";
+"Warm-up" = "Calentamiento";
+"Reps" = "Reps";
+"Rest" = "Descanso";
+"Skip" = "Saltar";
+"Finish workout" = "Terminar entrenamiento";
+"Finish workout?" = "¿Terminar entrenamiento?";
+"Finish and save" = "Terminar y guardar";
+"Cancel" = "Cancelar";
+"Rest’s over. Next set!" = "Se acabó el descanso. ¡Siguiente serie!";
+"Last time: %@" = "La última vez: %@";
+"No workout running" = "Ningún entreno en curso";
+"Start one on your iPhone and it shows up here." = "Empieza uno en tu iPhone y aparecerá aquí.";
+"All sets done" = "Todas las series hechas";
+"measuring" = "midiendo …";
+"Next: %@, set %lld" = "Siguiente: %@, serie %lld";
+"%@, set %lld" = "%@, serie %lld";
diff --git a/frontend/ios/App/WatchWidgets/fr.lproj/Localizable.strings b/frontend/ios/App/WatchWidgets/fr.lproj/Localizable.strings
new file mode 100644
index 000000000..5d23e2e91
--- /dev/null
+++ b/frontend/ios/App/WatchWidgets/fr.lproj/Localizable.strings
@@ -0,0 +1,21 @@
+/* openGym on the Apple Watch, fr. Written by ios/ci/watch-strings.mjs: change that, not this. */
+
+"Today" = "Aujourd'hui";
+"Start workout" = "Démarrer la séance";
+"Done" = "Terminé";
+"Warm-up" = "Échauffement";
+"Reps" = "Reps";
+"Rest" = "Repos";
+"Skip" = "Passer";
+"Finish workout" = "Terminer la séance";
+"Finish workout?" = "Terminer la séance ?";
+"Finish and save" = "Terminer et enregistrer";
+"Cancel" = "Annuler";
+"Rest’s over. Next set!" = "Repos terminé. Série suivante !";
+"Last time: %@" = "La dernière fois: %@";
+"No workout running" = "Aucune séance en cours";
+"Start one on your iPhone and it shows up here." = "Lance-en une sur ton iPhone et elle apparaît ici.";
+"All sets done" = "Toutes les séries faites";
+"measuring" = "mesure …";
+"Next: %@, set %lld" = "Ensuite : %@, série %lld";
+"%@, set %lld" = "%@, série %lld";
diff --git a/frontend/ios/App/WatchWidgets/hi.lproj/Localizable.strings b/frontend/ios/App/WatchWidgets/hi.lproj/Localizable.strings
new file mode 100644
index 000000000..2b089dc2f
--- /dev/null
+++ b/frontend/ios/App/WatchWidgets/hi.lproj/Localizable.strings
@@ -0,0 +1,21 @@
+/* openGym on the Apple Watch, hi. Written by ios/ci/watch-strings.mjs: change that, not this. */
+
+"Today" = "आज";
+"Start workout" = "वर्कआउट शुरू करें";
+"Done" = "हो गया";
+"Warm-up" = "वार्म-अप";
+"Reps" = "रेप्स";
+"Rest" = "आराम";
+"Skip" = "छोड़ें";
+"Finish workout" = "वर्कआउट समाप्त करें";
+"Finish workout?" = "वर्कआउट समाप्त करें?";
+"Finish and save" = "समाप्त करें और सहेजें";
+"Cancel" = "रद्द करें";
+"Rest’s over. Next set!" = "आराम खत्म। अगला सेट!";
+"Last time: %@" = "पिछली बार: %@";
+"No workout running" = "कोई वर्कआउट नहीं चल रहा";
+"Start one on your iPhone and it shows up here." = "iPhone पर एक शुरू करें, यह यहाँ दिखेगा।";
+"All sets done" = "सारे सेट पूरे";
+"measuring" = "माप रहा है …";
+"Next: %@, set %lld" = "अगला: %@, सेट %lld";
+"%@, set %lld" = "%@, सेट %lld";
diff --git a/frontend/ios/App/WatchWidgets/hu.lproj/Localizable.strings b/frontend/ios/App/WatchWidgets/hu.lproj/Localizable.strings
new file mode 100644
index 000000000..1e278e81f
--- /dev/null
+++ b/frontend/ios/App/WatchWidgets/hu.lproj/Localizable.strings
@@ -0,0 +1,21 @@
+/* openGym on the Apple Watch, hu. Written by ios/ci/watch-strings.mjs: change that, not this. */
+
+"Today" = "Ma";
+"Start workout" = "Edzés indítása";
+"Done" = "Kész";
+"Warm-up" = "Bemelegítés";
+"Reps" = "Ism.";
+"Rest" = "Pihenő";
+"Skip" = "Kihagyás";
+"Finish workout" = "Edzés befejezése";
+"Finish workout?" = "Befejezed az edzést?";
+"Finish and save" = "Befejezés és mentés";
+"Cancel" = "Mégse";
+"Rest’s over. Next set!" = "Vége a pihenőnek. Jöhet a következő sorozat!";
+"Last time: %@" = "Legutóbb: %@";
+"No workout running" = "Nincs folyamatban edzés";
+"Start one on your iPhone and it shows up here." = "Indíts egyet az iPhone-on, és itt megjelenik.";
+"All sets done" = "Minden sorozat kész";
+"measuring" = "mérés …";
+"Next: %@, set %lld" = "Következik: %@, %lld. sorozat";
+"%@, set %lld" = "%@, %lld. sorozat";
diff --git a/frontend/ios/App/WatchWidgets/it.lproj/Localizable.strings b/frontend/ios/App/WatchWidgets/it.lproj/Localizable.strings
new file mode 100644
index 000000000..865144662
--- /dev/null
+++ b/frontend/ios/App/WatchWidgets/it.lproj/Localizable.strings
@@ -0,0 +1,21 @@
+/* openGym on the Apple Watch, it. Written by ios/ci/watch-strings.mjs: change that, not this. */
+
+"Today" = "Oggi";
+"Start workout" = "Inizia allenamento";
+"Done" = "Fatto";
+"Warm-up" = "Riscaldamento";
+"Reps" = "Rip.";
+"Rest" = "Riposo";
+"Skip" = "Salta";
+"Finish workout" = "Termina allenamento";
+"Finish workout?" = "Terminare l’allenamento?";
+"Finish and save" = "Termina e salva";
+"Cancel" = "Annulla";
+"Rest’s over. Next set!" = "Riposo finito. Prossima serie!";
+"Last time: %@" = "L'ultima volta: %@";
+"No workout running" = "Nessun allenamento in corso";
+"Start one on your iPhone and it shows up here." = "Avviane uno sull’iPhone e comparirà qui.";
+"All sets done" = "Tutte le serie fatte";
+"measuring" = "misuro …";
+"Next: %@, set %lld" = "Poi: %@, serie %lld";
+"%@, set %lld" = "%@, serie %lld";
diff --git a/frontend/ios/App/WatchWidgets/ko.lproj/Localizable.strings b/frontend/ios/App/WatchWidgets/ko.lproj/Localizable.strings
new file mode 100644
index 000000000..c33c0ad7d
--- /dev/null
+++ b/frontend/ios/App/WatchWidgets/ko.lproj/Localizable.strings
@@ -0,0 +1,21 @@
+/* openGym on the Apple Watch, ko. Written by ios/ci/watch-strings.mjs: change that, not this. */
+
+"Today" = "오늘";
+"Start workout" = "운동 시작";
+"Done" = "완료";
+"Warm-up" = "워밍업";
+"Reps" = "횟수";
+"Rest" = "휴식";
+"Skip" = "건너뛰기";
+"Finish workout" = "운동 마치기";
+"Finish workout?" = "운동을 마칠까요?";
+"Finish and save" = "마치고 저장";
+"Cancel" = "취소";
+"Rest’s over. Next set!" = "휴식 끝. 다음 세트!";
+"Last time: %@" = "지난번: %@";
+"No workout running" = "진행 중인 운동이 없어요";
+"Start one on your iPhone and it shows up here." = "iPhone에서 시작하면 여기에 나타나요.";
+"All sets done" = "모든 세트 완료";
+"measuring" = "측정 중 …";
+"Next: %@, set %lld" = "다음: %@, %lld세트";
+"%@, set %lld" = "%@, %lld세트";
diff --git a/frontend/ios/App/WatchWidgets/pl.lproj/Localizable.strings b/frontend/ios/App/WatchWidgets/pl.lproj/Localizable.strings
new file mode 100644
index 000000000..059a74f0f
--- /dev/null
+++ b/frontend/ios/App/WatchWidgets/pl.lproj/Localizable.strings
@@ -0,0 +1,21 @@
+/* openGym on the Apple Watch, pl. Written by ios/ci/watch-strings.mjs: change that, not this. */
+
+"Today" = "Dziś";
+"Start workout" = "Zacznij trening";
+"Done" = "Gotowe";
+"Warm-up" = "Rozgrzewka";
+"Reps" = "Powt.";
+"Rest" = "Odpoczynek";
+"Skip" = "Pomiń";
+"Finish workout" = "Zakończ trening";
+"Finish workout?" = "Zakończyć trening?";
+"Finish and save" = "Zakończ i zapisz";
+"Cancel" = "Anuluj";
+"Rest’s over. Next set!" = "Koniec przerwy. Następna seria!";
+"Last time: %@" = "Ostatnio: %@";
+"No workout running" = "Żaden trening nie trwa";
+"Start one on your iPhone and it shows up here." = "Zacznij trening na iPhonie, a pojawi się tutaj.";
+"All sets done" = "Wszystkie serie zrobione";
+"measuring" = "mierzę …";
+"Next: %@, set %lld" = "Dalej: %@, seria %lld";
+"%@, set %lld" = "%@, seria %lld";
diff --git a/frontend/ios/App/WatchWidgets/pt-BR.lproj/Localizable.strings b/frontend/ios/App/WatchWidgets/pt-BR.lproj/Localizable.strings
new file mode 100644
index 000000000..8dbf9953f
--- /dev/null
+++ b/frontend/ios/App/WatchWidgets/pt-BR.lproj/Localizable.strings
@@ -0,0 +1,21 @@
+/* openGym on the Apple Watch, pt-BR. Written by ios/ci/watch-strings.mjs: change that, not this. */
+
+"Today" = "Hoje";
+"Start workout" = "Começar treino";
+"Done" = "Concluído";
+"Warm-up" = "Aquecimento";
+"Reps" = "Reps";
+"Rest" = "Descanso";
+"Skip" = "Pular";
+"Finish workout" = "Terminar treino";
+"Finish workout?" = "Terminar o treino?";
+"Finish and save" = "Terminar e salvar";
+"Cancel" = "Cancelar";
+"Rest’s over. Next set!" = "Acabou o descanso. Próxima série!";
+"Last time: %@" = "Da última vez: %@";
+"No workout running" = "Nenhum treino em andamento";
+"Start one on your iPhone and it shows up here." = "Comece um no iPhone e ele aparece aqui.";
+"All sets done" = "Todas as séries feitas";
+"measuring" = "medindo …";
+"Next: %@, set %lld" = "A seguir: %@, série %lld";
+"%@, set %lld" = "%@, série %lld";
diff --git a/frontend/ios/App/WatchWidgets/pt-PT.lproj/Localizable.strings b/frontend/ios/App/WatchWidgets/pt-PT.lproj/Localizable.strings
new file mode 100644
index 000000000..90436d132
--- /dev/null
+++ b/frontend/ios/App/WatchWidgets/pt-PT.lproj/Localizable.strings
@@ -0,0 +1,21 @@
+/* openGym on the Apple Watch, pt-PT. Written by ios/ci/watch-strings.mjs: change that, not this. */
+
+"Today" = "Hoje";
+"Start workout" = "Começar treino";
+"Done" = "Concluído";
+"Warm-up" = "Aquecimento";
+"Reps" = "Reps";
+"Rest" = "Descanso";
+"Skip" = "Saltar";
+"Finish workout" = "Terminar treino";
+"Finish workout?" = "Terminar o treino?";
+"Finish and save" = "Terminar e guardar";
+"Cancel" = "Cancelar";
+"Rest’s over. Next set!" = "Acabou o descanso. Próxima série!";
+"Last time: %@" = "Da última vez: %@";
+"No workout running" = "Nenhum treino a decorrer";
+"Start one on your iPhone and it shows up here." = "Começa um no iPhone e ele aparece aqui.";
+"All sets done" = "Todas as séries feitas";
+"measuring" = "a medir …";
+"Next: %@, set %lld" = "A seguir: %@, série %lld";
+"%@, set %lld" = "%@, série %lld";
diff --git a/frontend/ios/App/WatchWidgets/ru.lproj/Localizable.strings b/frontend/ios/App/WatchWidgets/ru.lproj/Localizable.strings
new file mode 100644
index 000000000..8a1568d27
--- /dev/null
+++ b/frontend/ios/App/WatchWidgets/ru.lproj/Localizable.strings
@@ -0,0 +1,21 @@
+/* openGym on the Apple Watch, ru. Written by ios/ci/watch-strings.mjs: change that, not this. */
+
+"Today" = "Сегодня";
+"Start workout" = "Начать тренировку";
+"Done" = "Готово";
+"Warm-up" = "Разминка";
+"Reps" = "Повт.";
+"Rest" = "Отдых";
+"Skip" = "Пропустить";
+"Finish workout" = "Завершить тренировку";
+"Finish workout?" = "Завершить тренировку?";
+"Finish and save" = "Завершить и сохранить";
+"Cancel" = "Отмена";
+"Rest’s over. Next set!" = "Отдых окончен. Следующий подход!";
+"Last time: %@" = "В прошлый раз: %@";
+"No workout running" = "Тренировка не идёт";
+"Start one on your iPhone and it shows up here." = "Начните её на iPhone, и она появится здесь.";
+"All sets done" = "Все подходы сделаны";
+"measuring" = "измеряю …";
+"Next: %@, set %lld" = "Далее: %@, подход %lld";
+"%@, set %lld" = "%@, подход %lld";
diff --git a/frontend/ios/App/WatchWidgets/th.lproj/Localizable.strings b/frontend/ios/App/WatchWidgets/th.lproj/Localizable.strings
new file mode 100644
index 000000000..ba503e6f0
--- /dev/null
+++ b/frontend/ios/App/WatchWidgets/th.lproj/Localizable.strings
@@ -0,0 +1,21 @@
+/* openGym on the Apple Watch, th. Written by ios/ci/watch-strings.mjs: change that, not this. */
+
+"Today" = "วันนี้";
+"Start workout" = "เริ่มออกกำลังกาย";
+"Done" = "เสร็จแล้ว";
+"Warm-up" = "วอร์มอัพ";
+"Reps" = "ครั้ง";
+"Rest" = "พัก";
+"Skip" = "ข้าม";
+"Finish workout" = "จบการออกกำลังกาย";
+"Finish workout?" = "จบการออกกำลังกายไหม?";
+"Finish and save" = "จบและบันทึก";
+"Cancel" = "ยกเลิก";
+"Rest’s over. Next set!" = "หมดเวลาพักแล้ว เซ็ตถัดไป!";
+"Last time: %@" = "ครั้งก่อน: %@";
+"No workout running" = "ไม่มีการฝึกที่กำลังทำอยู่";
+"Start one on your iPhone and it shows up here." = "เริ่มบน iPhone แล้วจะแสดงที่นี่";
+"All sets done" = "ครบทุกเซ็ตแล้ว";
+"measuring" = "กำลังวัด …";
+"Next: %@, set %lld" = "ถัดไป: %@ เซ็ต %lld";
+"%@, set %lld" = "%@ เซ็ต %lld";
diff --git a/frontend/ios/App/WatchWidgets/tr.lproj/Localizable.strings b/frontend/ios/App/WatchWidgets/tr.lproj/Localizable.strings
new file mode 100644
index 000000000..cdf7fa998
--- /dev/null
+++ b/frontend/ios/App/WatchWidgets/tr.lproj/Localizable.strings
@@ -0,0 +1,21 @@
+/* openGym on the Apple Watch, tr. Written by ios/ci/watch-strings.mjs: change that, not this. */
+
+"Today" = "Bugün";
+"Start workout" = "Antrenmana başla";
+"Done" = "Bitti";
+"Warm-up" = "Isınma";
+"Reps" = "Tekrar";
+"Rest" = "Dinlenme";
+"Skip" = "Atla";
+"Finish workout" = "Antrenmanı bitir";
+"Finish workout?" = "Antrenman bitirilsin mi?";
+"Finish and save" = "Bitir ve kaydet";
+"Cancel" = "İptal";
+"Rest’s over. Next set!" = "Dinlenme bitti. Sıradaki set!";
+"Last time: %@" = "Geçen sefer: %@";
+"No workout running" = "Devam eden antrenman yok";
+"Start one on your iPhone and it shows up here." = "iPhone’unda bir tane başlat, burada görünür.";
+"All sets done" = "Tüm setler tamam";
+"measuring" = "ölçülüyor …";
+"Next: %@, set %lld" = "Sıradaki: %@, set %lld";
+"%@, set %lld" = "%@, set %lld";
diff --git a/frontend/ios/App/WatchWidgets/uk.lproj/Localizable.strings b/frontend/ios/App/WatchWidgets/uk.lproj/Localizable.strings
new file mode 100644
index 000000000..b0dcdedb1
--- /dev/null
+++ b/frontend/ios/App/WatchWidgets/uk.lproj/Localizable.strings
@@ -0,0 +1,21 @@
+/* openGym on the Apple Watch, uk. Written by ios/ci/watch-strings.mjs: change that, not this. */
+
+"Today" = "Сьогодні";
+"Start workout" = "Почати тренування";
+"Done" = "Готово";
+"Warm-up" = "Розминка";
+"Reps" = "Повт.";
+"Rest" = "Відпочинок";
+"Skip" = "Пропустити";
+"Finish workout" = "Завершити тренування";
+"Finish workout?" = "Завершити тренування?";
+"Finish and save" = "Завершити й зберегти";
+"Cancel" = "Скасувати";
+"Rest’s over. Next set!" = "Відпочинок скінчився. Наступний підхід!";
+"Last time: %@" = "Минулого разу: %@";
+"No workout running" = "Тренування не триває";
+"Start one on your iPhone and it shows up here." = "Почни його на iPhone, і воно з’явиться тут.";
+"All sets done" = "Усі підходи зроблено";
+"measuring" = "вимірюю …";
+"Next: %@, set %lld" = "Далі: %@, підхід %lld";
+"%@, set %lld" = "%@, підхід %lld";
diff --git a/frontend/ios/App/WatchWidgets/zh-Hans.lproj/Localizable.strings b/frontend/ios/App/WatchWidgets/zh-Hans.lproj/Localizable.strings
new file mode 100644
index 000000000..ae30ec6cb
--- /dev/null
+++ b/frontend/ios/App/WatchWidgets/zh-Hans.lproj/Localizable.strings
@@ -0,0 +1,21 @@
+/* openGym on the Apple Watch, zh-Hans. Written by ios/ci/watch-strings.mjs: change that, not this. */
+
+"Today" = "今天";
+"Start workout" = "开始训练";
+"Done" = "完成";
+"Warm-up" = "热身";
+"Reps" = "次数";
+"Rest" = "休息";
+"Skip" = "跳过";
+"Finish workout" = "结束训练";
+"Finish workout?" = "结束训练?";
+"Finish and save" = "结束并保存";
+"Cancel" = "取消";
+"Rest’s over. Next set!" = "休息结束,下一组!";
+"Last time: %@" = "上次: %@";
+"No workout running" = "没有进行中的训练";
+"Start one on your iPhone and it shows up here." = "在 iPhone 上开始,它就会出现在这里。";
+"All sets done" = "所有组已完成";
+"measuring" = "测量中 …";
+"Next: %@, set %lld" = "下一个:%@,第 %lld 组";
+"%@, set %lld" = "%@,第 %lld 组";
diff --git a/frontend/ios/App/WatchWidgets/zh-Hant.lproj/Localizable.strings b/frontend/ios/App/WatchWidgets/zh-Hant.lproj/Localizable.strings
new file mode 100644
index 000000000..53cc7ed45
--- /dev/null
+++ b/frontend/ios/App/WatchWidgets/zh-Hant.lproj/Localizable.strings
@@ -0,0 +1,21 @@
+/* openGym on the Apple Watch, zh-Hant. Written by ios/ci/watch-strings.mjs: change that, not this. */
+
+"Today" = "今天";
+"Start workout" = "開始訓練";
+"Done" = "完成";
+"Warm-up" = "熱身組";
+"Reps" = "次數";
+"Rest" = "休息";
+"Skip" = "略過";
+"Finish workout" = "結束訓練";
+"Finish workout?" = "結束訓練?";
+"Finish and save" = "結束並儲存";
+"Cancel" = "取消";
+"Rest’s over. Next set!" = "休息結束,下一組!";
+"Last time: %@" = "上次: %@";
+"No workout running" = "沒有進行中的訓練";
+"Start one on your iPhone and it shows up here." = "在 iPhone 上開始,它就會出現在這裡。";
+"All sets done" = "所有組已完成";
+"measuring" = "測量中 …";
+"Next: %@, set %lld" = "下一個:%@,第 %lld 組";
+"%@, set %lld" = "%@,第 %lld 組";
diff --git a/frontend/ios/ci/add-watch-app.rb b/frontend/ios/ci/add-watch-app.rb
index ccb4f5f01..f8e3e38c1 100644
--- a/frontend/ios/ci/add-watch-app.rb
+++ b/frontend/ios/ci/add-watch-app.rb
@@ -30,6 +30,11 @@ watch = proj.new_target(:application, NAME, :watchos, '10.0')
group = proj.main_group.new_group(DIR, DIR)
sources = Dir.children(File.join(dir, DIR)).select { |f| f.end_with?('.swift') }.sort
watch.add_file_references(sources.map { |f| group.new_file(f) })
+# WatchCore (the session logic and the animation codec, tested with `swift test`), compiled in.
+CORE = 'WatchCore/Sources/WatchCore'
+cgroup = proj.main_group.new_group('WatchCore', CORE)
+core = Dir.children(File.join(dir, CORE)).select { |f| f.end_with?('.swift') }.sort.map { |f| cgroup.new_file(f) }
+watch.add_file_references(core)
group.new_file('Info.plist')
# The icon, from the iPhone app's (Watch/Assets.xcassets/AppIcon), and the strings in every language.
watch.add_resources([group.new_file('Assets.xcassets')])
@@ -81,6 +86,11 @@ wsources = Dir.children(File.join(dir, WIDGET_DIR)).select { |f| f.end_with?('.s
shared = group.files.find { |f| f.path == 'WidgetState.swift' }
widget.add_file_references(wsources + [shared].compact)
wgroup.new_file('Info.plist')
+Dir.children(File.join(dir, WIDGET_DIR)).select { |f| f.end_with?('.lproj') }.sort.each do |lproj|
+ ref = wgroup.new_file(lproj)
+ ref.last_known_file_type = 'folder'
+ widget.add_resources([ref])
+end
wgroup.new_file("#{WIDGET}.entitlements")
widget.add_system_framework('WidgetKit')
widget.add_system_framework('SwiftUI')
diff --git a/frontend/ios/ci/watch-strings.mjs b/frontend/ios/ci/watch-strings.mjs
index 6f645a869..3e314dc9d 100644
--- a/frontend/ios/ci/watch-strings.mjs
+++ b/frontend/ios/ci/watch-strings.mjs
@@ -11,6 +11,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url'
const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..')
const out = join(root, 'ios', 'App', 'Watch')
+const widgets = join(root, 'ios', 'App', 'WatchWidgets')
// app pack → watch .lproj
const LANGS = {
@@ -62,6 +63,11 @@ const OWN = {
tr: 'Tüm setler tamam', ru: 'Все подходы сделаны', uk: 'Усі підходи зроблено', ar: 'اكتملت كل المجموعات',
hi: 'सारे सेट पूरे', bn: 'সব সেট শেষ', th: 'ครบทุกเซ็ตแล้ว', ko: '모든 세트 완료', 'zh-Hans': '所有组已完成', 'zh-Hant': '所有組已完成',
},
+ 'measuring': {
+ de: 'misst …', fr: 'mesure …', es: 'midiendo …', it: 'misuro …', 'pt-PT': 'a medir …', 'pt-BR': 'medindo …', pl: 'mierzę …',
+ hu: 'mérés …', tr: 'ölçülüyor …', ru: 'измеряю …', uk: 'вимірюю …', ar: 'جارٍ القياس …', hi: 'माप रहा है …', bn: 'মাপা হচ্ছে …',
+ th: 'กำลังวัด …', ko: '측정 중 …', 'zh-Hans': '测量中 …', 'zh-Hant': '測量中 …',
+ },
'Next: %@, set %lld': {
de: 'Als Nächstes: %@, Satz %lld', fr: 'Ensuite : %@, série %lld', es: 'Siguiente: %@, serie %lld', it: 'Poi: %@, serie %lld',
'pt-PT': 'A seguir: %@, série %lld', 'pt-BR': 'A seguir: %@, série %lld', pl: 'Dalej: %@, seria %lld', hu: 'Következik: %@, %lld. sorozat',
@@ -117,6 +123,9 @@ for (const [pack, lproj] of Object.entries(LANGS)) {
for (const [k, tr] of Object.entries(OWN)) put(k, tr[lproj])
mkdirSync(join(out, `${lproj}.lproj`), { recursive: true })
writeFileSync(join(out, `${lproj}.lproj`, 'Localizable.strings'), lines.join('\n') + '\n')
+ // The widget says a few of the same words (Rest, Start workout).
+ mkdirSync(join(widgets, `${lproj}.lproj`), { recursive: true })
+ writeFileSync(join(widgets, `${lproj}.lproj`, 'Localizable.strings'), lines.join('\n') + '\n')
const plist = [`/* openGym on the Apple Watch, ${lproj}: Info.plist. Written by ios/ci/watch-strings.mjs. */`, '']
for (const [k, tr] of Object.entries(PLIST)) {
if (!tr[lproj] || /—/.test(tr[lproj])) { console.error(`${lproj}: ${k} missing or with an em dash`); problems++; continue }
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 83cc73924..21d5632c4 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -9,7 +9,8 @@ import { setLang, useLang, baseLang } from './lib/i18n.js'
import { effectiveLang } from './lib/default-lang.js'
import { setPlayOnSilent, setVibrate, setAlarmBuzzer, setNativeBuzzer } from './lib/sound.js'
import { buzzAsAlarm } from './lib/rest-alert.js'
-import { setNav, notePath, keyBefore } from './lib/nav.js'
+import { setNav, notePath, keyBefore, navToWorkout } from './lib/nav.js'
+import { workoutVolume } from './lib/history.js'
import { setSystemBarsLight } from './lib/system-bars.js'
import { initBackButton } from './lib/back.js'
import { installEdgeSwipeBack, BACK_PREVIEW_EVENT } from './lib/edge-swipe-back.js'
@@ -338,7 +339,11 @@ export default function App() {
// and start time, and no weigh-in question (the lifter is at the watch, not here).
const unbind = bindWatchAppActions({
start: (ids, opts) => beginWorkout(ids, null, opts),
- patchSet: (where, fields) => useStore.getState().update(s => { patchSetIn(s, where, fields, stampWorkout) }),
+ patchSet: (where, fields, opts = {}) => useStore.getState().update(s => {
+ patchSetIn(s, where, fields, stampWorkout, { ...opts, recount: w => { w.vol = workoutVolume(w) } })
+ }),
+ // Ticks from the watch are the workout screen's to apply: it opens, and drains the queue.
+ openWorkout: () => { if (!String(window.location.hash || '').startsWith('#/workout')) navToWorkout() },
})
return () => { gone = true; stop?.(); unbind() }
}, [])
diff --git a/frontend/src/lib/watch-sync.js b/frontend/src/lib/watch-sync.js
index cd1af228d..7418cbc8c 100644
--- a/frontend/src/lib/watch-sync.js
+++ b/frontend/src/lib/watch-sync.js
@@ -55,6 +55,8 @@ function watchEntry (e, H) {
last,
sets: (e.sets || []).map(s => ({
w: num(s.w), r: num(s.r), sec: num(s.sec), done: !!s.done, warmup: !!isWarmupRow(s),
+ // when it was ticked: of two ticks of the same set (phone and watch), the later wins
+ ...(num(s.at) ? { at: num(s.at) } : {}),
})),
}
}
@@ -157,6 +159,11 @@ function entryIndexOf (A, ev) {
* setDone { wid, exId, entryIdx, setIdx, w, r, at } the workout screen's own tick
* finish { wid, at } the workout screen's own Finish and save
* setHr { wid, exId, entryIdx, setIdx, hr?, restHr? } heart rate on a set (lib/heart-rate.js)
+ *
+ * A tick for a workout already saved (finished on the phone while the watch was away) is written
+ * into that saved workout, stamped so the next sync keeps it. A tick while the workout screen is
+ * not open opens it (appHandlers.openWorkout), and the queue drains once it is there. Of two
+ * changes of the same set, the later one (`at`) wins.
*/
export function applyEvents (events, getState) {
if (!Array.isArray(events)) return []
@@ -165,16 +172,29 @@ export function applyEvents (events, getState) {
for (const ev of events) {
if (!ev || typeof ev.id !== 'string') continue
if (applied.includes(ev.id)) { done.push(ev.id); continue }
- const A = getState()?.S?.active
+ const S = getState()?.S
+ const A = S?.active
const ours = A && Array.isArray(A.entries) && (!ev.wid || ev.wid === A.id)
+ // A workout finished on the phone while the watch was away: its later ticks still count.
+ const saved = !ours && ev.wid && Array.isArray(S?.workouts) ? S.workouts.find(w => w && w.id === ev.wid) : null
if (ev.type === 'start') {
if (!A) {
if (!appHandlers) break
appHandlers.start(Array.isArray(ev.routineIds) ? ev.routineIds : [], { id: ev.wid || null, start: num(ev.at) })
}
// A workout already running on the phone is kept; one with the watch's id is this one.
+ } else if (ev.type === 'setDone' && saved) {
+ if (!appHandlers) break
+ const fields = { done: true, ...(num(ev.w) != null ? { w: num(ev.w) } : {}), ...(num(ev.r) != null ? { r: num(ev.r) } : {}), ...(num(ev.at) ? { at: num(ev.at) } : {}) }
+ const hr = sanitizeHr(ev.hr)
+ if (hr) fields.hr = hr
+ appHandlers.patchSet({ wid: ev.wid, exId: ev.exId, entryIdx: ev.entryIdx, setIdx: ev.setIdx }, fields, { ifNewer: num(ev.at) })
} else if (ev.type === 'setDone' && ours) {
- if (!handlers) break
+ if (!handlers) {
+ // The tick is the workout screen's to apply: open it, and the queue drains when it binds.
+ if (appHandlers?.openWorkout) appHandlers.openWorkout()
+ break
+ }
const idx = entryIndexOf(A, ev)
const set = idx >= 0 ? A.entries[idx].sets?.[ev.setIdx] : null
if (set) handlers.setDone(idx, ev.setIdx, { w: num(ev.w), r: num(ev.r), at: num(ev.at), hr: sanitizeHr(ev.hr) })
@@ -190,7 +210,10 @@ export function applyEvents (events, getState) {
appHandlers.patchSet({ wid: ev.wid, exId: ev.exId, entryIdx: ev.entryIdx, setIdx: ev.setIdx }, fields)
}
} else if (ev.type === 'finish' && ours) {
- if (!handlers) break
+ if (!handlers) {
+ if (appHandlers?.openWorkout) appHandlers.openWorkout()
+ break
+ }
handlers.finish()
}
// Applied, or meaningless now (another workout, a set that is gone): either way it is done.
@@ -314,7 +337,7 @@ export function _resetWatchSync () { handlers = null; appHandlers = null; plugin
* (lib/sync-merge.js: of two copies of a workout the one edited last wins). Only these optional
* fields are ever added; nothing is removed or renamed.
*/
-export function patchSetIn (s, { wid, exId, entryIdx, setIdx }, fields, stamp) {
+export function patchSetIn (s, { wid, exId, entryIdx, setIdx }, fields, stamp, { ifNewer = null, recount = null } = {}) {
const find = w => {
if (!w || !Array.isArray(w.entries)) return null
const i = w.entries[entryIdx] && w.entries[entryIdx].id === exId ? entryIdx : w.entries.findIndex(e => e && e.id === exId)
@@ -328,7 +351,17 @@ export function patchSetIn (s, { wid, exId, entryIdx, setIdx }, fields, stamp) {
const w = (s.workouts || []).find(x => x && x.id === wid)
const set = find(w)
if (!set) return false
- Object.assign(set, fields)
+ // Two changes of the same set: the later one wins (a tick from the watch older than an edit
+ // made on the phone since keeps the phone's numbers; its heart rate still lands).
+ let f = fields
+ if (ifNewer != null && set.done && Number(set.at) > ifNewer) {
+ f = {}
+ if (fields.hr) f.hr = fields.hr
+ if (fields.restHr) f.restHr = fields.restHr
+ if (!Object.keys(f).length) return false
+ }
+ Object.assign(set, f)
+ if (recount) recount(w)
if (stamp) stamp(w)
return true
}
diff --git a/frontend/src/lib/watch-sync.test.js b/frontend/src/lib/watch-sync.test.js
index 078360a3b..a7862c70b 100644
--- a/frontend/src/lib/watch-sync.test.js
+++ b/frontend/src/lib/watch-sync.test.js
@@ -193,3 +193,44 @@ describe('the workout\'s animations for the watch', () => {
expect(clipsFor(state(), { 'anim-240-male': { state: 'downloading', dir: '/x' } })[0].path).toBeDefined()
})
})
+
+describe('the sync cases on the phone', () => {
+ it('a tick that waits for the workout screen opens it, and stays queued until it is there', () => {
+ const S = state()
+ const openWorkout = vi.fn()
+ bindWatchAppActions({ start: vi.fn(), patchSet: vi.fn(), openWorkout })
+ expect(applyEvents([{ id: 'q1', type: 'setDone', wid: 'w-1', exId: '0025', entryIdx: 0, setIdx: 1, w: 60, r: 8, at: 5 }], () => ({ S }))).toEqual([])
+ expect(openWorkout).toHaveBeenCalledTimes(1)
+ })
+
+ it('a tick for a workout the phone already saved goes into that saved workout', () => {
+ const S = { active: null, workouts: [{ id: 'w-old', entries: [{ id: '0025', sets: [{ w: 60, r: 8, done: false }] }] }] }
+ const patchSet = vi.fn()
+ bindWatchAppActions({ start: vi.fn(), patchSet })
+ expect(applyEvents([{ id: 'late', type: 'setDone', wid: 'w-old', exId: '0025', entryIdx: 0, setIdx: 0, w: 62.5, r: 7, at: 900, hr: { avg: 120, max: 140 } }], () => ({ S }))).toEqual(['late'])
+ expect(patchSet).toHaveBeenCalledWith({ wid: 'w-old', exId: '0025', entryIdx: 0, setIdx: 0 }, { done: true, w: 62.5, r: 7, at: 900, hr: { avg: 120, max: 140 } }, { ifNewer: 900 })
+ })
+
+ it('the snapshot carries when each set was ticked, for the later-tick-wins rule on the watch', () => {
+ const S = state()
+ S.active.entries[0].sets[0].at = 1234
+ expect(buildSnapshot(S).active.entries[0].sets[0].at).toBe(1234)
+ expect('at' in buildSnapshot(S).active.entries[0].sets[1]).toBe(false)
+ })
+})
+
+describe('patching a saved workout', () => {
+ it('the later change wins; the watch\'s heart rate lands either way; the volume is counted again', async () => {
+ const { patchSetIn } = await import('./watch-sync.js')
+ const s = { active: null, workouts: [{ id: 'w', vol: 0, entries: [{ id: '0025', sets: [{ w: 60, r: 8, done: true, at: 2000 }] }] }] }
+ const stamp = vi.fn(), recount = vi.fn(w => { w.vol = 1 })
+ // the phone's edit (at 2000) is later than the watch's tick (at 1000): numbers stay, hr lands
+ expect(patchSetIn(s, { wid: 'w', exId: '0025', entryIdx: 0, setIdx: 0 }, { done: true, w: 50, r: 5, at: 1000, hr: { avg: 110, max: 120 } }, stamp, { ifNewer: 1000, recount })).toBe(true)
+ expect(s.workouts[0].entries[0].sets[0]).toEqual({ w: 60, r: 8, done: true, at: 2000, hr: { avg: 110, max: 120 } })
+ // a later tick wins
+ patchSetIn(s, { wid: 'w', exId: '0025', entryIdx: 0, setIdx: 0 }, { done: true, w: 65, r: 6, at: 3000 }, stamp, { ifNewer: 3000, recount })
+ expect(s.workouts[0].entries[0].sets[0]).toMatchObject({ w: 65, r: 6, at: 3000 })
+ expect(recount).toHaveBeenCalledTimes(2)
+ expect(s.workouts[0].vol).toBe(1)
+ })
+})
diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx
index 1e61bab4f..0c6663d21 100644
--- a/frontend/src/views/Workout.jsx
+++ b/frontend/src/views/Workout.jsx
@@ -1788,8 +1788,14 @@ function ActiveWorkout({ onActionChange }) {
useEffect(() => bindWatchActions({
setDone: (idx, i, { w, r, at, hr }) => {
if (useStore.getState().S.active?.editingWorkoutId) return // a saved workout being edited is not the session
+ const now = useStore.getState().S.active?.entries?.[idx]?.sets?.[i]
+ // The same set ticked here after the watch did: the later tick wins, the heart rate still lands.
+ if (now?.done && at && Number(now.at) > at) {
+ if (hr) mutEntry(idx, en => { if (en.sets[i]) en.sets[i].hr = hr })
+ return
+ }
mutEntry(idx, en => { const set = en.sets[i]; if (!set) return; if (w != null) set.w = w; if (r != null) set.r = r })
- if (!useStore.getState().S.active?.entries?.[idx]?.sets?.[i]?.done) toggleRef.current(idx, i)
+ if (!now?.done) toggleRef.current(idx, i)
if (at || hr) mutEntry(idx, en => { const set = en.sets[i]; if (!set?.done) return; if (at) set.at = at; if (hr) set.hr = hr })
},
finish: () => { if (!useStore.getState().S.active?.editingWorkoutId) finishWorkoutNow() },
diff --git a/frontend/src/views/Workout.watch.test.jsx b/frontend/src/views/Workout.watch.test.jsx
index 0cda06d6c..fa487139f 100644
--- a/frontend/src/views/Workout.watch.test.jsx
+++ b/frontend/src/views/Workout.watch.test.jsx
@@ -69,3 +69,11 @@ describe('a set ticked on the watch', () => {
expect(S.workouts.at(-1).entries[0].sets[0]).toMatchObject({ w: 60, r: 8, done: true, at })
})
})
+
+describe('the same set on both sides', () => {
+ it('a tick from the watch older than the phone\'s own keeps the phone\'s numbers, and its heart rate lands', () => {
+ act(() => { useStore.getState().update(s => { Object.assign(s.active.entries[0].sets[0], { w: 70, r: 5, done: true, at: 5000 }) }) })
+ act(() => { applyEvents([{ id: 'old', type: 'setDone', wid: 'w-watch', exId: '0025', entryIdx: 0, setIdx: 0, w: 60, r: 8, at: 4000, hr: { avg: 120, max: 130 } }], () => useStore.getState()) })
+ expect(useStore.getState().S.active.entries[0].sets[0]).toMatchObject({ w: 70, r: 5, done: true, at: 5000, hr: { avg: 120, max: 130 } })
+ })
+})