Skip to content

Offline gym log for Android. No account, no ads, no internet.

Follow the system theme, add a recovery view and let exercises leave the suggestions

InlitXbbd07e92a513
diff --git a/android/app/src/main/kotlin/com/gymmane/app/LiveNotifier.kt b/android/app/src/main/kotlin/com/gymmane/app/LiveNotifier.kt
new file mode 100644
index 0000000..061edbb
--- /dev/null
+++ b/android/app/src/main/kotlin/com/gymmane/app/LiveNotifier.kt
@@ -0,0 +1,287 @@
+package com.gymmane.app
+
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.content.res.ColorStateList
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.Paint
+import android.graphics.RectF
+import android.graphics.Typeface
+import android.graphics.drawable.Icon
+import android.os.Build
+import android.os.Handler
+import android.os.Looper
+import android.os.SystemClock
+import android.view.View
+import android.widget.RemoteViews
+import androidx.annotation.RequiresApi
+import io.flutter.plugin.common.MethodChannel
+import java.io.ByteArrayOutputStream
+
+object LiveNotifier {
+ private const val ID = 1003
+ private const val CHANNEL = "live_workout_v2"
+ private const val ACTION = "com.gymmane.app.LIVE_ACTION"
+ private const val FLASH_MS = 1600L
+
+ var dart: MethodChannel? = null
+
+ private val main = Handler(Looper.getMainLooper())
+ private var app: Context? = null
+ private var last: Map<*, *>? = null
+ private var font: Typeface? = null
+ private var flashId = -1
+ private var flashUntil = 0L
+ private val tick = Runnable { repost() }
+
+ fun update(ctx: Context, a: Map<*, *>) {
+ app = ctx.applicationContext
+ val fid = (a["flashId"] as? Number)?.toInt() ?: -1
+ if (fid != flashId) {
+ if (a["flash"] != null) flashUntil = System.currentTimeMillis() + FLASH_MS
+ flashId = fid
+ }
+ last = a
+ repost()
+ }
+
+ private fun repost() {
+ main.removeCallbacks(tick)
+ val ctx = app ?: return
+ val a = last ?: return
+ val nm = ctx.getSystemService(NotificationManager::class.java) ?: return
+ val now = System.currentTimeMillis()
+
+ val name = a["title"] as? String ?: "GymMane"
+ val detail = a["detail"] as? String ?: ""
+ val restLabel = a["restLabel"] as? String ?: ""
+ val next = a["next"] as? String
+ val resting = a["resting"] as? Boolean ?: false
+ val paused = a["paused"] as? Boolean ?: false
+ val restEnd = (a["restEnd"] as? Number)?.toLong() ?: 0L
+ val startedAt = (a["startedAt"] as? Number)?.toLong() ?: 0L
+ val index = (a["index"] as? Number)?.toInt() ?: 0
+ val total = (a["total"] as? Number)?.toInt() ?: 0
+ val segments = (a["segments"] as? List<*>)?.mapNotNull { (it as? Number)?.toInt() } ?: emptyList()
+ val done = (a["done"] as? List<*>)?.map { it == true } ?: emptyList()
+ val progress = (a["progress"] as? Number)?.toInt() ?: 0
+ val chip = a["chip"] as? String
+ val flash = if (now < flashUntil) a["flash"] as? String else null
+ val actions = (a["actions"] as? List<*>)?.mapNotNull { it as? Map<*, *> } ?: emptyList()
+ val accent = ctx.getColor(if (paused) R.color.live_pause else R.color.live_accent)
+ val green = ctx.getColor(R.color.live_done)
+ val left = if (resting) ((restEnd - now + 999) / 1000).coerceAtLeast(0) else 0L
+ val frozen = (a["elapsed"] as? Number)?.toLong() ?: 0L
+
+ val open = PendingIntent.getActivity(
+ ctx,
+ 0,
+ Intent(ctx, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
+ )
+ val b = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ ensureChannel(nm, a)
+ Notification.Builder(ctx, CHANNEL)
+ } else {
+ @Suppress("DEPRECATION")
+ Notification.Builder(ctx).setPriority(Notification.PRIORITY_LOW)
+ }
+ b.setSmallIcon(R.drawable.ic_stat_gymmane)
+ .setSubText(if (total > 0) "${index + 1}/$total" else null)
+ .setColor(accent)
+ .setOngoing(true)
+ .setOnlyAlertOnce(true)
+ .setCategory(Notification.CATEGORY_WORKOUT)
+ .setVisibility(Notification.VISIBILITY_PUBLIC)
+ .setContentIntent(open)
+
+ for ((i, act) in actions.withIndex()) {
+ val id = act["id"] as? String ?: continue
+ val label = act["label"] as? String ?: continue
+ val pi = PendingIntent.getBroadcast(
+ ctx,
+ 100 + i,
+ Intent(ctx, LiveActionReceiver::class.java).setAction("$ACTION.$id").putExtra("id", id),
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
+ )
+ b.addAction(Notification.Action.Builder(Icon.createWithResource(ctx, R.drawable.ic_stat_gymmane), label, pi).build())
+ }
+
+ if (Build.VERSION.SDK_INT >= 36) {
+ val countdown = resting && !paused
+ val elapsed = if (paused || startedAt <= 0) frozen else ((now - startedAt) / 1000).coerceAtLeast(0)
+ b.setContentTitle(name)
+ b.setContentText(if (countdown && restLabel.isNotEmpty()) "$restLabel · $detail" else detail)
+ b.setShowWhen(false)
+ val (fill, ink) = when {
+ flash != null -> R.color.live_done to R.color.live_on_done
+ paused -> R.color.live_pause to R.color.live_on_pause
+ countdown -> R.color.live_accent to R.color.live_on_accent
+ else -> R.color.live_idle to R.color.live_ink
+ }
+ b.setLargeIcon(badge(ctx, flash ?: clock(if (countdown) left else elapsed), ctx.getColor(fill), ctx.getColor(ink)))
+ val style = Notification.ProgressStyle()
+ .setStyledByProgress(true)
+ .setProgressTrackerIcon(Icon.createWithResource(ctx, R.drawable.ic_live_tracker))
+ val segs = segments.withIndex().filter { it.value > 0 }
+ if (segs.isNotEmpty()) {
+ style.setProgressSegments(segs.map {
+ val finished = done.getOrElse(it.index) { false } && !paused
+ Notification.ProgressStyle.Segment(it.value).setColor(if (finished) green else accent)
+ })
+ style.setProgress(progress.coerceIn(0, segs.sumOf { it.value }))
+ }
+ b.setStyle(style)
+ b.extras.putBoolean("android.requestPromotedOngoing", true)
+ val shortText = flash ?: if (countdown) clock(left) else chip
+ if (shortText != null) b.setShortCriticalText(shortText)
+ } else {
+ val clockAt = if (resting) restEnd else startedAt
+ val shown = if (flash != null) "$flash · $detail" else detail
+ b.setContentTitle(name).setContentText(shown)
+ b.setStyle(Notification.DecoratedCustomViewStyle())
+ b.setCustomContentView(views(ctx, R.layout.live_small, name, shown, null, resting, paused, clockAt, segments, progress, accent))
+ b.setCustomBigContentView(views(ctx, R.layout.live_big, name, shown, next, resting, paused, clockAt, segments, progress, accent))
+ }
+
+ nm.notify(ID, b.build())
+
+ var wait = Long.MAX_VALUE
+ if (Build.VERSION.SDK_INT >= 36 && !paused) {
+ if (resting && left > 0) {
+ wait = ((restEnd - now) % 1000L).let { if (it <= 0L) 1000L else it } + 15L
+ } else if (!resting && startedAt > 0) {
+ wait = 1000L - (now - startedAt).mod(1000L) + 15L
+ }
+ }
+ if (flashUntil > now) wait = minOf(wait, flashUntil - now + 15)
+ if (wait != Long.MAX_VALUE) main.postDelayed(tick, wait)
+ }
+
+ @RequiresApi(Build.VERSION_CODES.O)
+ private fun badge(ctx: Context, text: String, fill: Int, ink: Int): Icon {
+ val w = 320
+ val h = 180
+ val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
+ val c = Canvas(bmp)
+ val p = Paint(Paint.ANTI_ALIAS_FLAG)
+ val inset = 8f
+ val r = (h - inset * 2) / 2f
+ p.color = fill
+ c.drawRoundRect(RectF(inset, inset, w - inset, h - inset), r, r, p)
+ p.color = ink
+ p.typeface = font ?: runCatching { ctx.resources.getFont(R.font.nunito_extrabold) }.getOrNull().also { font = it }
+ p.textSize = h * 0.56f
+ val digit = (0..9).maxOf { p.measureText(it.toString()) }
+ fun width(ch: Char) = if (ch.isDigit()) digit else p.measureText(ch.toString())
+ var total = text.sumOf { width(it).toDouble() }.toFloat()
+ val room = (w - inset * 2) * 0.8f
+ if (total > room) {
+ val k = room / total
+ p.textSize *= k
+ total *= k
+ }
+ val cell = if (text.any { it.isDigit() }) (0..9).maxOf { p.measureText(it.toString()) } else 0f
+ val fm = p.fontMetrics
+ val y = h / 2f - (fm.ascent + fm.descent) / 2f
+ var x = (w - total) / 2f
+ p.textAlign = Paint.Align.CENTER
+ for (ch in text) {
+ val cw = if (ch.isDigit()) cell else p.measureText(ch.toString())
+ c.drawText(ch.toString(), x + cw / 2f, y, p)
+ x += cw
+ }
+ val out = ByteArrayOutputStream()
+ bmp.compress(Bitmap.CompressFormat.PNG, 100, out)
+ bmp.recycle()
+ val bytes = out.toByteArray()
+ return Icon.createWithData(bytes, 0, bytes.size)
+ }
+
+ private fun clock(seconds: Long): String {
+ val m = seconds / 60
+ val s = seconds % 60
+ return if (m >= 60) "${m / 60}:${(m % 60).toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}"
+ else "$m:${s.toString().padStart(2, '0')}"
+ }
+
+ private fun views(
+ ctx: Context,
+ layout: Int,
+ title: String,
+ detail: String,
+ next: String?,
+ resting: Boolean,
+ paused: Boolean,
+ clockAt: Long,
+ segments: List<Int>,
+ progress: Int,
+ accent: Int,
+ ): RemoteViews {
+ val v = RemoteViews(ctx.packageName, layout)
+ v.setTextViewText(R.id.live_title, title)
+ v.setTextViewText(R.id.live_detail, detail)
+ v.setTextColor(R.id.live_clock, accent)
+ if (!paused && clockAt > 0) {
+ val base = SystemClock.elapsedRealtime() + (clockAt - System.currentTimeMillis())
+ v.setViewVisibility(R.id.live_clock, View.VISIBLE)
+ v.setChronometer(R.id.live_clock, base, null, true)
+ v.setChronometerCountDown(R.id.live_clock, resting)
+ } else {
+ v.setViewVisibility(R.id.live_clock, View.GONE)
+ }
+ if (layout == R.layout.live_big) {
+ val max = segments.sum()
+ v.setViewVisibility(R.id.live_progress, if (max > 0) View.VISIBLE else View.GONE)
+ v.setProgressBar(R.id.live_progress, maxOf(max, 1), progress.coerceIn(0, maxOf(max, 1)), false)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ v.setColorStateList(R.id.live_progress, "setProgressTintList", ColorStateList.valueOf(accent))
+ }
+ v.setViewVisibility(R.id.live_next, if (next.isNullOrEmpty()) View.GONE else View.VISIBLE)
+ v.setTextViewText(R.id.live_next, next ?: "")
+ }
+ return v
+ }
+
+ @RequiresApi(Build.VERSION_CODES.O)
+ private fun ensureChannel(nm: NotificationManager, a: Map<*, *>) {
+ if (nm.getNotificationChannel(CHANNEL) != null) return
+ nm.deleteNotificationChannel("live_workout")
+ val ch = NotificationChannel(
+ CHANNEL,
+ a["channel"] as? String ?: "Workout",
+ NotificationManager.IMPORTANCE_DEFAULT,
+ ).apply {
+ description = a["channelWhy"] as? String
+ setSound(null, null)
+ enableVibration(false)
+ setShowBadge(false)
+ lockscreenVisibility = Notification.VISIBILITY_PUBLIC
+ }
+ nm.createNotificationChannel(ch)
+ }
+
+ fun cancel(ctx: Context) {
+ main.removeCallbacks(tick)
+ last = null
+ ctx.getSystemService(NotificationManager::class.java)?.cancel(ID)
+ }
+}
+
+class LiveActionReceiver : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ val id = intent.getStringExtra("id") ?: return
+ val dart = LiveNotifier.dart
+ if (dart == null) {
+ LiveNotifier.cancel(context)
+ return
+ }
+ dart.invokeMethod("action", id)
+ }
+}
diff --git a/android/app/src/main/kotlin/com/gymmane/app/MainActivity.kt b/android/app/src/main/kotlin/com/gymmane/app/MainActivity.kt
index d36f81c..8587e9c 100644
--- a/android/app/src/main/kotlin/com/gymmane/app/MainActivity.kt
+++ b/android/app/src/main/kotlin/com/gymmane/app/MainActivity.kt
@@ -1,9 +1,17 @@
package com.gymmane.app
import android.content.ContentValues
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.net.Uri
import android.os.Build
import android.os.Environment
+import android.os.VibrationEffect
+import android.os.Vibrator
+import android.os.VibratorManager
import android.provider.MediaStore
+import android.view.WindowManager
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
@@ -11,26 +19,145 @@ import java.io.File
import java.io.FileOutputStream
class MainActivity : FlutterActivity() {
+ private var incomingChannel: MethodChannel? = null
+
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
- MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "gymmane/gallery")
- .setMethodCallHandler { call, result ->
- if (call.method != "savePng") {
- result.notImplemented()
- return@setMethodCallHandler
- }
- val bytes = call.argument<ByteArray>("bytes")
- val name = call.argument<String>("name") ?: "gymmane.png"
- if (bytes == null) {
- result.error("no-bytes", "missing image", null)
- return@setMethodCallHandler
+ val messenger = flutterEngine.dartExecutor.binaryMessenger
+
+ MethodChannel(messenger, "gymmane/haptics").setMethodCallHandler { call, result ->
+ if (call.method != "buzz") {
+ result.notImplemented()
+ return@setMethodCallHandler
+ }
+ buzz()
+ result.success(null)
+ }
+
+ val incoming = MethodChannel(messenger, "gymmane/incoming")
+ incoming.setMethodCallHandler { call, result ->
+ if (call.method != "take") {
+ result.notImplemented()
+ return@setMethodCallHandler
+ }
+ result.success(takeIncoming(intent))
+ }
+ incomingChannel = incoming
+
+ MethodChannel(messenger, "gymmane/gallery").setMethodCallHandler { call, result ->
+ if (call.method != "savePng") {
+ result.notImplemented()
+ return@setMethodCallHandler
+ }
+ val bytes = call.argument<ByteArray>("bytes")
+ val name = call.argument<String>("name") ?: "gymmane.png"
+ if (bytes == null) {
+ result.error("no-bytes", "missing image", null)
+ return@setMethodCallHandler
+ }
+ try {
+ result.success(savePng(bytes, name))
+ } catch (e: Exception) {
+ result.error("save-failed", e.message, null)
+ }
+ }
+
+ MethodChannel(messenger, "gymmane/screen").setMethodCallHandler { call, result ->
+ if (call.method != "keepOn") {
+ result.notImplemented()
+ return@setMethodCallHandler
+ }
+ val on = call.argument<Boolean>("on") ?: false
+ if (on) {
+ window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ } else {
+ window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ }
+ result.success(null)
+ }
+
+ val live = MethodChannel(messenger, "gymmane/live")
+ live.setMethodCallHandler { call, result ->
+ when (call.method) {
+ "update" -> {
+ val args = call.arguments as? Map<*, *>
+ if (args != null) LiveNotifier.update(this, args)
+ result.success(null)
}
- try {
- result.success(savePng(bytes, name))
- } catch (e: Exception) {
- result.error("save-failed", e.message, null)
+ "end" -> {
+ LiveNotifier.cancel(this)
+ result.success(null)
}
+ else -> result.notImplemented()
+ }
+ }
+ LiveNotifier.dart = live
+
+ MethodChannel(messenger, "gymmane/device").setMethodCallHandler { call, result ->
+ if (call.method != "isWatch") {
+ result.notImplemented()
+ return@setMethodCallHandler
}
+ result.success(packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH))
+ }
+ }
+
+ override fun cleanUpFlutterEngine(flutterEngine: FlutterEngine) {
+ LiveNotifier.dart = null
+ if (isFinishing) LiveNotifier.cancel(this)
+ super.cleanUpFlutterEngine(flutterEngine)
+ }
+
+ override fun onNewIntent(intent: Intent) {
+ super.onNewIntent(intent)
+ setIntent(intent)
+ val text = takeIncoming(intent) ?: return
+ incomingChannel?.invokeMethod("incoming", text)
+ }
+
+ private fun takeIncoming(intent: Intent?): String? {
+ if (intent == null) return null
+ val text = when (intent.action) {
+ Intent.ACTION_VIEW -> intent.data?.let { readText(it) }
+ Intent.ACTION_SEND -> streamOf(intent)?.let { readText(it) }
+ ?: intent.getStringExtra(Intent.EXTRA_TEXT)
+ else -> null
+ }
+ intent.action = Intent.ACTION_MAIN
+ intent.data = null
+ return text
+ }
+
+ @Suppress("DEPRECATION")
+ private fun streamOf(intent: Intent): Uri? =
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ intent.getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java)
+ } else {
+ intent.getParcelableExtra(Intent.EXTRA_STREAM)
+ }
+
+ private fun readText(uri: Uri): String? = try {
+ contentResolver.openInputStream(uri)?.use { stream ->
+ val bytes = stream.readBytes()
+ if (bytes.size > 2_000_000) null else String(bytes, Charsets.UTF_8)
+ }
+ } catch (e: Exception) {
+ null
+ }
+
+ @Suppress("DEPRECATION")
+ private fun buzz() {
+ val vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ (getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager).defaultVibrator
+ } else {
+ getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
+ }
+ val pattern = longArrayOf(0, 350, 180, 350, 180, 600)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ vibrator.vibrate(VibrationEffect.createWaveform(pattern, -1))
+ } else {
+ vibrator.vibrate(pattern, -1)
+ }
}
private fun savePng(bytes: ByteArray, name: String): Boolean {
diff --git a/android/app/src/main/res/drawable-hdpi/ic_stat_gymmane.png b/android/app/src/main/res/drawable-hdpi/ic_stat_gymmane.png
new file mode 100644
index 0000000..9ce9f13
Binary files /dev/null and b/android/app/src/main/res/drawable-hdpi/ic_stat_gymmane.png differ
diff --git a/android/app/src/main/res/drawable-mdpi/ic_stat_gymmane.png b/android/app/src/main/res/drawable-mdpi/ic_stat_gymmane.png
new file mode 100644
index 0000000..dfccb5b
Binary files /dev/null and b/android/app/src/main/res/drawable-mdpi/ic_stat_gymmane.png differ
diff --git a/android/app/src/main/res/drawable-xhdpi/ic_stat_gymmane.png b/android/app/src/main/res/drawable-xhdpi/ic_stat_gymmane.png
new file mode 100644
index 0000000..fb74a69
Binary files /dev/null and b/android/app/src/main/res/drawable-xhdpi/ic_stat_gymmane.png differ
diff --git a/android/app/src/main/res/drawable-xxhdpi/ic_stat_gymmane.png b/android/app/src/main/res/drawable-xxhdpi/ic_stat_gymmane.png
new file mode 100644
index 0000000..af1b46b
Binary files /dev/null and b/android/app/src/main/res/drawable-xxhdpi/ic_stat_gymmane.png differ
diff --git a/android/app/src/main/res/drawable-xxxhdpi/ic_stat_gymmane.png b/android/app/src/main/res/drawable-xxxhdpi/ic_stat_gymmane.png
new file mode 100644
index 0000000..6713821
Binary files /dev/null and b/android/app/src/main/res/drawable-xxxhdpi/ic_stat_gymmane.png differ
diff --git a/android/app/src/main/res/drawable/ic_live_tracker.xml b/android/app/src/main/res/drawable/ic_live_tracker.xml
new file mode 100644
index 0000000..e554434
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_live_tracker.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-8"?>
+<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
+ <item>
+ <shape android:shape="oval">
+ <solid android:color="@color/live_accent" />
+ <size android:width="24dp" android:height="24dp" />
+ </shape>
+ </item>
+ <item android:bottom="4dp" android:left="4dp" android:right="4dp" android:top="4dp">
+ <bitmap
+ android:gravity="fill"
+ android:src="@drawable/ic_stat_gymmane"
+ android:tint="@color/live_on_accent" />
+ </item>
+</layer-list>
diff --git a/android/app/src/main/res/font/nunito_extrabold.ttf b/android/app/src/main/res/font/nunito_extrabold.ttf
new file mode 100644
index 0000000..baf48a9
Binary files /dev/null and b/android/app/src/main/res/font/nunito_extrabold.ttf differ
diff --git a/android/app/src/main/res/layout/live_big.xml b/android/app/src/main/res/layout/live_big.xml
new file mode 100644
index 0000000..7c1095a
--- /dev/null
+++ b/android/app/src/main/res/layout/live_big.xml
@@ -0,0 +1,68 @@
+<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="vertical">
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:gravity="center_vertical"
+ android:orientation="horizontal">
+
+ <LinearLayout
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:orientation="vertical">
+
+ <TextView
+ android:id="@+id/live_title"
+ style="@android:style/TextAppearance.Material.Notification.Title"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:ellipsize="end"
+ android:fontFamily="@font/nunito_extrabold"
+ android:maxLines="2"
+ android:textSize="17sp" />
+
+ <TextView
+ android:id="@+id/live_detail"
+ style="@android:style/TextAppearance.Material.Notification"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="2dp"
+ android:ellipsize="end"
+ android:singleLine="true" />
+ </LinearLayout>
+
+ <Chronometer
+ android:id="@+id/live_clock"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginStart="12dp"
+ android:fontFamily="@font/nunito_extrabold"
+ android:includeFontPadding="false"
+ android:textColor="@color/live_accent"
+ android:textSize="38sp" />
+ </LinearLayout>
+
+ <ProgressBar
+ android:id="@+id/live_progress"
+ style="@android:style/Widget.Material.ProgressBar.Horizontal"
+ android:layout_width="match_parent"
+ android:layout_height="6dp"
+ android:layout_marginTop="12dp"
+ android:progressBackgroundTint="@color/live_accent"
+ android:progressTint="@color/live_accent" />
+
+ <TextView
+ android:id="@+id/live_next"
+ style="@android:style/TextAppearance.Material.Notification"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="8dp"
+ android:ellipsize="end"
+ android:singleLine="true"
+ android:textSize="12sp" />
+</LinearLayout>
diff --git a/android/app/src/main/res/layout/live_small.xml b/android/app/src/main/res/layout/live_small.xml
new file mode 100644
index 0000000..2a98eae
--- /dev/null
+++ b/android/app/src/main/res/layout/live_small.xml
@@ -0,0 +1,47 @@
+<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:gravity="center_vertical"
+ android:orientation="horizontal">
+
+ <LinearLayout
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:orientation="vertical">
+
+ <TextView
+ android:id="@+id/live_title"
+ style="@android:style/TextAppearance.Material.Notification.Title"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:ellipsize="marquee"
+ android:focusable="true"
+ android:focusableInTouchMode="true"
+ android:fontFamily="@font/nunito_extrabold"
+ android:marqueeRepeatLimit="marquee_forever"
+ android:singleLine="true">
+
+ <requestFocus />
+ </TextView>
+
+ <TextView
+ android:id="@+id/live_detail"
+ style="@android:style/TextAppearance.Material.Notification"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:ellipsize="end"
+ android:singleLine="true" />
+ </LinearLayout>
+
+ <Chronometer
+ android:id="@+id/live_clock"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginStart="12dp"
+ android:fontFamily="@font/nunito_extrabold"
+ android:includeFontPadding="false"
+ android:textColor="@color/live_accent"
+ android:textSize="28sp" />
+</LinearLayout>
diff --git a/android/app/src/main/res/values-night/live.xml b/android/app/src/main/res/values-night/live.xml
new file mode 100644
index 0000000..aabe96a
--- /dev/null
+++ b/android/app/src/main/res/values-night/live.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <color name="live_accent">#D9A184</color>
+ <color name="live_on_accent">#FF0C0B0A</color>
+ <color name="live_done">#8FA377</color>
+ <color name="live_pause">#E0B15A</color>
+ <color name="live_ink">#FFFFFFFF</color>
+ <color name="live_idle">#FF2B2B2B</color>
+ <color name="live_on_pause">#FF0C0B0A</color>
+ <color name="live_on_done">#FF0C0B0A</color>
+</resources>
diff --git a/android/app/src/main/res/values/live.xml b/android/app/src/main/res/values/live.xml
new file mode 100644
index 0000000..f5f9fdc
--- /dev/null
+++ b/android/app/src/main/res/values/live.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <color name="live_accent">#9E4E27</color>
+ <color name="live_on_accent">#FFFFFFFF</color>
+ <color name="live_done">#3D7A52</color>
+ <color name="live_pause">#9A6A12</color>
+ <color name="live_ink">#FF1A1713</color>
+ <color name="live_idle">#FFECE8E3</color>
+ <color name="live_on_pause">#FFFFFFFF</color>
+ <color name="live_on_done">#FFFFFFFF</color>
+</resources>
diff --git a/lib/models/live_session.dart b/lib/models/live_session.dart
index 7ed9c43..b120ef9 100644
--- a/lib/models/live_session.dart
+++ b/lib/models/live_session.dart
@@ -1,21 +1,31 @@
import 'workout.dart';
class SessionSet {
- SessionSet(this.reps, this.weight, this.done, {this.kind = SetKind.normal, this.rpe});
+ SessionSet(this.reps, this.weight, this.done,
+ {this.kind = SetKind.normal, this.rpe, this.sec, this.km});
int reps;
double weight;
bool done;
SetKind kind;
double? rpe;
+ int? sec;
+ double? km;
bool get counts => kind != SetKind.warmup;
+ LoggedSet get logged => LoggedSet(reps, weight, kind: kind, rpe: rpe, sec: sec, km: km);
+
+ SessionSet copy({bool done = false}) =>
+ SessionSet(reps, weight, done, kind: kind, rpe: rpe, sec: sec, km: km);
+
Map<String, dynamic> toJson() => {
'r': reps,
'w': weight,
'd': done,
if (kind != SetKind.normal) 'k': kind.index,
if (rpe != null) 'e': rpe,
+ if (sec != null) 't': sec,
+ if (km != null) 'km': km,
};
factory SessionSet.fromJson(Map<String, dynamic> j) => SessionSet(
(j['r'] as num).toInt(),
@@ -23,6 +33,8 @@ class SessionSet {
j['d'] as bool? ?? false,
kind: setKindFrom(j['k']),
rpe: (j['e'] as num?)?.toDouble(),
+ sec: (j['t'] as num?)?.toInt(),
+ km: (j['km'] as num?)?.toDouble(),
);
}
diff --git a/lib/services/live_workout.dart b/lib/services/live_workout.dart
new file mode 100644
index 0000000..1fdbe43
--- /dev/null
+++ b/lib/services/live_workout.dart
@@ -0,0 +1,197 @@
+import 'dart:io' show Platform;
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+
+import '../l10n/l10n.dart';
+import '../state/fit_state.dart';
+import '../widgets/ui_kit.dart';
+
+class LiveWorkout {
+ LiveWorkout._();
+
+ static const _channel = MethodChannel('gymmane/live_activity');
+ static const _android = MethodChannel('gymmane/live');
+ static bool _listening = false;
+
+ static String _lastKey = '';
+ static bool _busy = false;
+ static bool _dirty = false;
+ static int _flashes = 0;
+ static DateTime? _flashAt;
+
+ static bool get _supported => !kIsWeb && (Platform.isAndroid || Platform.isIOS);
+
+ static Future<void> sync() async {
+ if (!_supported) return;
+ if (!_listening && Platform.isAndroid) {
+ _listening = true;
+ _android.setMethodCallHandler((call) async {
+ if (call.method == 'action') _act(call.arguments as String? ?? '');
+ });
+ }
+ if (_busy) {
+ _dirty = true;
+ return;
+ }
+ _busy = true;
+ try {
+ do {
+ _dirty = false;
+ await _push();
+ } while (_dirty);
+ } finally {
+ _busy = false;
+ }
+ }
+
+ static Future<void> _push() async {
+ final s = fit.session;
+ if (s == null || s.complete || s.manual) {
+ await end();
+ return;
+ }
+ final ex = fit.currentExercise;
+ final total = s.exercises.length;
+ final index = s.currentIndex.clamp(0, total == 0 ? 0 : total - 1);
+ final paused = fit.sessionPaused;
+ final restEnd = paused ? null : s.restEndsAt;
+ final resting = restEnd != null && s.restRemaining != null;
+
+ final name = ex == null ? 'GymMane' : t.catalogName(ex.id, ex.name);
+ String detail;
+ if (paused) {
+ detail = titleCase(t.paused);
+ } else if (ex == null) {
+ detail = '';
+ } else {
+ final pending = ex.sets.indexWhere((st) => !st.done);
+ if (pending < 0) {
+ detail = t.liveAllDone;
+ } else {
+ final st = ex.sets[pending];
+ final load = fit.isRepsOnly(ex.id)
+ ? '${st.reps} ${t.repsCol.toLowerCase()}'
+ : '${st.reps} × ${fit.weightLabel(st.weight)}';
+ detail = '${t.liveSet(pending + 1, ex.sets.length)} · $load';
+ }
+ }
+
+ final nextIdx = fit.pendingAfter(index) ?? (index + 1 < total ? index + 1 : null);
+ final nextEx = nextIdx == null ? null : s.exercises[nextIdx];
+ final nextName = nextEx == null ? null : t.catalogName(nextEx.id, nextEx.name);
+ var position = 0;
+ for (var i = 0; i < index; i++) {
+ position += s.exercises[i].sets.length;
+ }
+ final pendingIdx = ex?.sets.indexWhere((st) => !st.done) ?? -1;
+ position += pendingIdx < 0 ? (ex?.sets.length ?? 0) : pendingIdx;
+ final chip = ex == null || ex.sets.isEmpty
+ ? null
+ : '${pendingIdx < 0 ? ex.sets.length : pendingIdx + 1}/${ex.sets.length}';
+ final finished = [for (final e in s.exercises) e.sets.isNotEmpty && e.sets.every((st) => st.done)];
+ final flashing = _flashAt != null && DateTime.now().difference(_flashAt!) < const Duration(seconds: 2);
+ final actions = <(String, String)>[
+ if (paused)
+ ('pause', '▶ ${t.liveResume}')
+ else ...[
+ if (resting) ...[
+ ('add', '+15 s'),
+ ('skip', '${t.liveSkipRest} ›'),
+ ] else if (pendingIdx >= 0)
+ ('done', '✓ ${t.liveDoneSet}')
+ else if (nextEx != null)
+ ('next', '${t.liveNext} ›'),
+ ('pause', '❚❚ ${t.livePause}'),
+ ],
+ ];
+
+ final key = [
+ name, detail, index, total, resting ? restEnd.millisecondsSinceEpoch : 0, paused, position,
+ actions.length, finished.join(), _flashes, paused ? fit.sessionElapsed : 0,
+ ].join('|');
+ if (key == _lastKey) return;
+ _lastKey = key;
+
+ try {
+ if (Platform.isIOS) {
+ await _channel.invokeMethod<void>('update', {
+ 'exercise': name,
+ 'detail': detail,
+ 'index': index,
+ 'total': total,
+ 'restEnd': resting ? restEnd.millisecondsSinceEpoch : null,
+ 'restLabel': t.liveResting,
+ 'paused': paused,
+ });
+ return;
+ }
+ await _android.invokeMethod<void>('update', {
+ 'title': name,
+ 'detail': detail,
+ 'restLabel': t.liveResting,
+ 'next': nextName == null ? null : t.liveUpNext(nextName),
+ 'resting': resting,
+ 'paused': paused,
+ 'restEnd': resting ? restEnd.millisecondsSinceEpoch : 0,
+ 'startedAt': DateTime.now().millisecondsSinceEpoch - fit.sessionElapsed * 1000,
+ 'elapsed': fit.sessionElapsed,
+ 'index': index,
+ 'total': total,
+ 'segments': [for (final e in s.exercises) e.sets.length],
+ 'done': finished,
+ 'progress': position,
+ 'chip': paused ? '❚❚' : chip,
+ 'flash': flashing ? '+15 s' : null,
+ 'flashId': _flashes,
+ 'channel': t.liveChannel,
+ 'channelWhy': t.liveChannelWhy,
+ 'actions': [
+ for (final (id, label) in actions) {'id': id, 'label': label},
+ ],
+ });
+ } catch (e) {
+ _lastKey = '';
+ debugPrint('LiveWorkout no disponible: $e');
+ }
+ }
+
+ static void _act(String id) {
+ final s = fit.session;
+ if (s == null || s.complete) return;
+ switch (id) {
+ case 'done':
+ final ex = fit.currentExercise;
+ final pending = ex?.sets.indexWhere((st) => !st.done) ?? -1;
+ if (pending >= 0) fit.toggleSet(s.currentIndex, pending);
+ case 'pause':
+ fit.toggleSessionPause();
+ case 'add':
+ _flashes++;
+ _flashAt = DateTime.now();
+ fit.nudgeRest(15);
+ case 'skip':
+ fit.skipRest();
+ case 'next':
+ fit.goNextPending();
+ }
+ }
+
+ static Future<void> end() async {
+ if (!_supported) return;
+ final wasShown = _lastKey.isNotEmpty;
+ _lastKey = '';
+ try {
+ if (Platform.isIOS) {
+ await _channel.invokeMethod<void>('end');
+ } else if (wasShown || !_cleared) {
+ await _android.invokeMethod<void>('end');
+ }
+ _cleared = true;
+ } catch (e) {
+ debugPrint('LiveWorkout.end falló: $e');
+ }
+ }
+
+ static bool _cleared = false;
+}
diff --git a/lib/services/screen_awake.dart b/lib/services/screen_awake.dart
new file mode 100644
index 0000000..60c9ee1
--- /dev/null
+++ b/lib/services/screen_awake.dart
@@ -0,0 +1,20 @@
+import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+
+class ScreenAwake {
+ ScreenAwake._();
+
+ static const _channel = MethodChannel('gymmane/screen');
+ static bool? _last;
+
+ static Future<void> keepOn(bool on) async {
+ if (kIsWeb || _last == on) return;
+ _last = on;
+ try {
+ await _channel.invokeMethod<void>('keepOn', {'on': on});
+ } catch (e) {
+ _last = null;
+ debugPrint('ScreenAwake no disponible: $e');
+ }
+ }
+}