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: nothing lost or doubled around a relaunch, the name clear of the clock, the clip still when unseen

Duarte Santosf95b2f259fd7
diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml
index 5278e25da..efcb25e66 100644
--- a/.github/workflows/ios.yml
+++ b/.github/workflows/ios.yml
@@ -156,9 +156,13 @@ jobs:
# What each screen costs: the app's CPU time over 20 s once it is up (the simulator's
# process, on the Mac). Always On (wrist down) should cost next to nothing.
cpu() { ps -o time= -p "$1" 2>/dev/null | awk -F'[:.]' '{ if (NF==3) print $1*60+$2+$3/100; else print 0 }'; }
- for spec in idle:idle set:set rest:rest hold:hold set-aod:set:-OpenGymWatchAOD rest-aod:rest:-OpenGymWatchAOD; do
- IFS=: read -r file screen flag <<< "$spec"
+ # set-noclip: the same screen without the animation, to tell what the animation costs.
+ for spec in idle:idle set:set set-noclip:set:noclip rest:rest hold:hold set-aod:set:-OpenGymWatchAOD set-aod-noclip:set:-OpenGymWatchAOD:noclip rest-aod:rest:-OpenGymWatchAOD; do
+ IFS=: read -r file screen flag noclip <<< "$spec"
+ if [ "$flag" = noclip ]; then flag=""; noclip=noclip; fi
+ KEEP=$CLIP; if [ -n "$noclip" ]; then CLIP=""; fi
if [ -n "$flag" ]; then shot "perf-$file" "$screen" "$flag"; else shot "perf-$file" "$screen"; fi
+ CLIP=$KEEP
a=$(cpu "$PID"); sleep 20; b=$(cpu "$PID")
echo "$size $file: $(node -e "console.log(((+process.argv[1]-+process.argv[2])/20*100).toFixed(1))" "$b" "$a")% CPU over 20 s" | tee -a build/watch/perf.txt
rm -f "build/watch/$size-perf-$file.png"
diff --git a/frontend/ios/App/Watch/OpenGymWatchApp.swift b/frontend/ios/App/Watch/OpenGymWatchApp.swift
index 45cb1cc2d..5509e9f60 100644
--- a/frontend/ios/App/Watch/OpenGymWatchApp.swift
+++ b/frontend/ios/App/Watch/OpenGymWatchApp.swift
@@ -46,6 +46,11 @@ final class WatchAppDelegate: NSObject, WKApplicationDelegate {
func handle(_ workoutConfiguration: HKWorkoutConfiguration) {
store.openedForWorkout()
}
+
+ /// Relaunched after being killed mid-workout: the Apple Health session watchOS kept running.
+ func handleActiveWorkoutRecovery() {
+ store.health.recover(workoutId: store.state.workout?.id)
+ }
}
/// CI's screenshots: the largest text size, or the screen as in Always On, when asked for.
@@ -274,9 +279,10 @@ struct ExercisePage: View {
@State private var target: CrownTarget = .reps
@State private var confirmSkip = false
@FocusState private var crownFocus: Bool
+ @Environment(\.dynamicTypeSize) private var typeSize
@ScaledMetric(relativeTo: .title) private var doneSizeScaled: CGFloat = 58
/// Large enough to hit, small enough to leave room for the numbers at the largest text sizes.
- private var doneSize: CGFloat { min(doneSizeScaled, 70) }
+ private var doneSize: CGFloat { min(doneSizeScaled, typeSize.isAccessibilitySize ? 62 : 70) }
var body: some View {
if let w = store.workout, w.entries.indices.contains(index) {
@@ -333,8 +339,8 @@ struct ExercisePage: View {
}
.padding(.horizontal, 4)
// The set's layout is fixed (crown, Done, dots on one screen): text grows up to a size
- // that still fits; the start screen and the summary scroll and grow all the way.
- .dynamicTypeSize(...DynamicTypeSize.accessibility2)
+ // that still fits on 41 mm; the start screen and the summary scroll and grow all the way.
+ .dynamicTypeSize(...DynamicTypeSize.accessibility1)
.onAppear {
if SessionStore.demoScreen == "weight" || store.crownStartsOnWeight { target = .weight }
if entry.isBodyweight && !store.crownStartsOnWeight { target = .reps }
@@ -351,18 +357,19 @@ struct ExercisePage: View {
@ViewBuilder private func header(_ entry: Entry) -> some View {
HStack(alignment: .top, spacing: 6) {
if let clip = store.clips[entry.id] {
- ClipView(clip: clip).frame(width: 30, height: 30)
+ ClipView(clip: clip, animating: index == store.entryIndex).frame(width: 30, height: 30)
}
Text(entry.name)
.font(.system(.footnote, design: .rounded).weight(.semibold))
- .lineLimit(2)
- .minimumScaleFactor(0.75)
+ // One line at the large sizes (shrunk to fit): two would push the page up into the clock.
+ .lineLimit(typeSize.isAccessibilitySize ? 1 : 2)
+ .minimumScaleFactor(0.6)
.frame(maxWidth: .infinity, alignment: .leading)
OfflineSign()
HeartRateBadge(health: store.health)
}
- // The top row shares the screen's top with the clock: it grows less than the numbers do.
- .dynamicTypeSize(...DynamicTypeSize.xxLarge)
+ // The top row sits just under the clock: it grows less than the numbers do.
+ .dynamicTypeSize(...DynamicTypeSize.xLarge)
}
/// Warm-up, the side up next, superset: what kind of set this is, above the numbers.
@@ -375,6 +382,7 @@ struct ExercisePage: View {
if side == "R" { Tag(text: Text("Right"), color: .cyan) }
if entry.group != nil { Tag(text: Text("Superset"), color: .purple) }
}
+ .dynamicTypeSize(...DynamicTypeSize.xLarge)
}
}
@@ -803,19 +811,32 @@ struct SummaryView: View {
/// with the wrist down.
struct ClipView: View {
let clip: ClipFrames
+ /// Only the exercise on screen moves; the pages next to it (kept alive by the pager) stand still.
+ var animating = true
@Environment(\.isLuminanceReduced) private var dimmed
var body: some View {
- TimelineView(.animation(minimumInterval: 1.0 / 12, paused: dimmed)) { ctx in
- let t = ctx.date.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: max(0.1, clip.duration))
- let i = dimmed ? 0 : min(clip.images.count - 1, Int(t / max(0.1, clip.duration) * Double(clip.images.count)))
- Image(uiImage: clip.images[i])
- .resizable()
- .scaledToFit()
- .clipShape(RoundedRectangle(cornerRadius: 6))
+ Group {
+ if dimmed || !animating || clip.images.count < 2 {
+ // Wrist down or off screen: one still frame, no timeline at all.
+ frame(clip.images[0])
+ } else {
+ TimelineView(.animation(minimumInterval: max(1.0 / 12, clip.duration / Double(clip.images.count)))) { ctx in
+ let t = ctx.date.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: max(0.1, clip.duration))
+ let i = min(clip.images.count - 1, Int(t / max(0.1, clip.duration) * Double(clip.images.count)))
+ frame(clip.images[i])
+ }
+ }
}
.accessibilityHidden(true)
}
+
+ private func frame(_ image: UIImage) -> some View {
+ Image(uiImage: image)
+ .resizable()
+ .scaledToFit()
+ .clipShape(RoundedRectangle(cornerRadius: 6))
+ }
}
/* ---------- Apple Health ---------- */
diff --git a/frontend/ios/App/Watch/SessionStore.swift b/frontend/ios/App/Watch/SessionStore.swift
index f4769c6d8..a248dbc47 100644
--- a/frontend/ios/App/Watch/SessionStore.swift
+++ b/frontend/ios/App/Watch/SessionStore.swift
@@ -96,7 +96,16 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
// Relaunched (mid-workout or not): the session as it was, then the latest from the phone.
state = saved
loadTargets()
- if let w = saved.workout { health.start(workoutId: w.id) }
+ // The Apple Health session of a workout that was running when the app was killed is
+ // recovered (WatchAppDelegate.handleActiveWorkoutRecovery); a new one starts only if
+ // none came back by then, so one workout never becomes two.
+ if let w = saved.workout {
+ workoutSeenAt = w.start.map { Date(timeIntervalSince1970: $0 / 1000) }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in
+ guard let self = self, self.state.workout?.id == w.id else { return }
+ self.health.start(workoutId: w.id)
+ }
+ }
}
health.onStatus = { [weak self] in self?.sendStatus() }
let center = UNUserNotificationCenter.current()
@@ -266,8 +275,10 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
}
let (next, event) = SessionCore.tick(state, entry: ei, set: si, side: side, w: tw, r: tr, sec: tsec,
at: now.timeIntervalSince1970 * 1000, id: UUID().uuidString, hr: hr)
- state = next
+ // Sent first, saved second: killed in between, the phone still has the tick (and the next
+ // snapshot brings it back here); the other way round the tick would be lost on the phone.
if let event = event { send(event: event) }
+ state = next
setStartedAt = now
picked[ei] = nil
let (to, rest) = SessionCore.next(after: state, entry: ei, set: si)
@@ -354,6 +365,7 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
let now = Date()
let (next, event) = SessionCore.start(state, session, wid: "watch-" + UUID().uuidString,
at: now.timeIntervalSince1970 * 1000, id: UUID().uuidString)
+ send(event: event)
state = next
picked = [:]
setStartedAt = now
@@ -361,7 +373,6 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
restAfter = nil
loadTargets()
health.start(workoutId: next.workout?.id)
- send(event: event)
summary = nil
Haptics.start()
}
@@ -378,8 +389,8 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
stopHold()
skipRest()
dropClips()
- state = next
send(event: ev)
+ state = next
Haptics.finished()
}
@@ -469,11 +480,35 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
guard !isDemo, WCSession.isSupported(),
let data = try? JSONSerialization.data(withJSONObject: event),
let json = String(data: data, encoding: .utf8) else { return }
+ transfer(json)
+ }
+
+ /// Events made before the session was up (a tap right after launch) wait here, saved, and go out
+ /// once it is: transferUserInfo before activation would lose them.
+ private static let outboxKey = "outbox"
+ private var outbox: [String] {
+ get { UserDefaults.standard.stringArray(forKey: SessionStore.outboxKey) ?? [] }
+ set { UserDefaults.standard.set(newValue, forKey: SessionStore.outboxKey) }
+ }
+
+ private func transfer(_ json: String, tries: Int = 0) {
+ let session = WCSession.default
+ guard session.activationState == .activated else {
+ outbox = Array((outbox + [json]).suffix(500))
+ return
+ }
// Queued by the system and delivered, in order, even when the phone app is not running.
- WCSession.default.transferUserInfo(["event": json])
+ session.transferUserInfo(["event": json, "tries": tries])
updateLink()
}
+ private func flushOutbox() {
+ let waiting = outbox
+ guard !waiting.isEmpty, WCSession.default.activationState == .activated else { return }
+ outbox = []
+ waiting.forEach { transfer($0) }
+ }
+
/// The phone in reach or not, and the events still on their way: the small "syncs later" sign.
private func updateLink() {
guard WCSession.isSupported() else { return }
@@ -489,7 +524,12 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
func sessionReachabilityDidChange(_ session: WCSession) { updateLink() }
func session(_ session: WCSession, didFinish userInfoTransfer: WCSessionUserInfoTransfer, error: Error?) {
- // A transfer that failed is queued again by the system; either way the count is new.
+ // A transfer that failed is not tried again by the system: sent again from here, a few
+ // times (the phone applies each event once, by its id, so a second copy does no harm).
+ if error != nil, let json = userInfoTransfer.userInfo["event"] as? String {
+ let tries = (userInfoTransfer.userInfo["tries"] as? Int) ?? 0
+ if tries < 3 { DispatchQueue.main.asyncAfter(deadline: .now() + 5) { self.transfer(json, tries: tries + 1) } }
+ }
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { self.updateLink() }
}
@@ -539,6 +579,7 @@ final class SessionStore: NSObject, ObservableObject, WCSessionDelegate, UNUserN
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) }
+ DispatchQueue.main.async { self.flushOutbox() }
sendStatus()
updateLink()
}
diff --git a/frontend/ios/App/Watch/WorkoutManager.swift b/frontend/ios/App/Watch/WorkoutManager.swift
index e298ac37b..ea5fa8283 100644
--- a/frontend/ios/App/Watch/WorkoutManager.swift
+++ b/frontend/ios/App/Watch/WorkoutManager.swift
@@ -128,6 +128,35 @@ final class WorkoutManager: NSObject, ObservableObject, HKWorkoutSessionDelegate
}
}
+ /// The app was killed (or crashed) with a workout session running: watchOS kept the session and
+ /// hands it back here, with everything it measured. Taken up as if never gone; a session this
+ /// launch started meanwhile is dropped (one workout in Apple Health, not two).
+ func recover(workoutId wid: String?) {
+ guard HKHealthStore.isHealthDataAvailable() else { return }
+ store.recoverActiveWorkoutSession { recovered, _ in
+ DispatchQueue.main.async {
+ guard let s = recovered else { return }
+ if let other = self.session, other !== s {
+ other.end()
+ self.builder?.discardWorkout()
+ }
+ let b = s.associatedWorkoutBuilder()
+ b.dataSource = HKLiveWorkoutDataSource(healthStore: self.store, workoutConfiguration: s.workoutConfiguration)
+ s.delegate = self
+ b.delegate = self
+ self.session = s
+ self.builder = b
+ self.wanted = true
+ if let wid = wid { self.workoutId = wid }
+ self.tagged = nil
+ self.tag()
+ if let q = self.query { self.store.stop(q) }
+ self.startQuery(from: s.startDate ?? Date())
+ self.running = true
+ }
+ }
+ }
+
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)