Skip to content

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

Add water, protein and calorie home screen widgets

InlitXec3962d7dd83
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index f0b8981..5cb3a28 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -119,6 +119,45 @@
android:resource="@xml/week_widget_info" />
</receiver>
+ <receiver
+ android:name=".WaterWidgetProvider"
+ android:exported="true">
+ <intent-filter>
+ <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
+ <action android:name="android.intent.action.TIME_SET" />
+ <action android:name="android.intent.action.TIMEZONE_CHANGED" />
+ </intent-filter>
+ <meta-data
+ android:name="android.appwidget.provider"
+ android:resource="@xml/water_widget_info" />
+ </receiver>
+
+ <receiver
+ android:name=".ProteinWidgetProvider"
+ android:exported="true">
+ <intent-filter>
+ <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
+ <action android:name="android.intent.action.TIME_SET" />
+ <action android:name="android.intent.action.TIMEZONE_CHANGED" />
+ </intent-filter>
+ <meta-data
+ android:name="android.appwidget.provider"
+ android:resource="@xml/protein_widget_info" />
+ </receiver>
+
+ <receiver
+ android:name=".KcalWidgetProvider"
+ android:exported="true">
+ <intent-filter>
+ <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
+ <action android:name="android.intent.action.TIME_SET" />
+ <action android:name="android.intent.action.TIMEZONE_CHANGED" />
+ </intent-filter>
+ <meta-data
+ android:name="android.appwidget.provider"
+ android:resource="@xml/kcal_widget_info" />
+ </receiver>
+
<receiver
android:name=".LiveActionReceiver"
android:exported="false" />
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 337f772..3f7ef31 100644
--- a/android/app/src/main/kotlin/com/gymmane/app/MainActivity.kt
+++ b/android/app/src/main/kotlin/com/gymmane/app/MainActivity.kt
@@ -24,6 +24,7 @@ import java.io.FileOutputStream
class MainActivity : FlutterActivity() {
private var incomingChannel: MethodChannel? = null
private var rotaryChannel: MethodChannel? = null
+ private var openChannel: MethodChannel? = null
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
@@ -90,6 +91,16 @@ class MainActivity : FlutterActivity() {
rotaryChannel = MethodChannel(messenger, "gymmane/rotary")
+ val open = MethodChannel(messenger, "gymmane/open")
+ open.setMethodCallHandler { call, result ->
+ if (call.method != "take") {
+ result.notImplemented()
+ return@setMethodCallHandler
+ }
+ result.success(takeOpen(intent))
+ }
+ openChannel = open
+
val live = MethodChannel(messenger, "gymmane/live")
live.setMethodCallHandler { call, result ->
when (call.method) {
@@ -142,6 +153,7 @@ class MainActivity : FlutterActivity() {
override fun cleanUpFlutterEngine(flutterEngine: FlutterEngine) {
rotaryChannel = null
+ openChannel = null
LiveNotifier.dart = null
HealthBridge.channel = null
if (isFinishing) LiveNotifier.cancel(this)
@@ -151,6 +163,11 @@ class MainActivity : FlutterActivity() {
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
+ val open = takeOpen(intent)
+ if (open != null) {
+ openChannel?.invokeMethod("open", open)
+ return
+ }
if (HealthBridge.takeUsage(intent)) {
HealthBridge.channel?.invokeMethod("usage", null)
return
@@ -159,6 +176,12 @@ class MainActivity : FlutterActivity() {
incomingChannel?.invokeMethod("incoming", text)
}
+ private fun takeOpen(intent: Intent?): String? {
+ val route = intent?.getStringExtra(OPEN_EXTRA) ?: return null
+ intent.removeExtra(OPEN_EXTRA)
+ return route
+ }
+
private fun takeIncoming(intent: Intent?): String? {
if (intent == null || intent.action == Intent.ACTION_VIEW_PERMISSION_USAGE) return null
val text = when (intent.action) {
diff --git a/android/app/src/main/kotlin/com/gymmane/app/NutritionWidgets.kt b/android/app/src/main/kotlin/com/gymmane/app/NutritionWidgets.kt
new file mode 100644
index 0000000..711b81f
--- /dev/null
+++ b/android/app/src/main/kotlin/com/gymmane/app/NutritionWidgets.kt
@@ -0,0 +1,371 @@
+package com.gymmane.app
+
+import android.app.PendingIntent
+import android.appwidget.AppWidgetManager
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.content.SharedPreferences
+import android.content.res.Configuration
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.graphics.Canvas
+import android.graphics.Color
+import android.graphics.Paint
+import android.graphics.RectF
+import android.graphics.Typeface
+import android.os.Build
+import android.os.Handler
+import android.os.Looper
+import android.os.SystemClock
+import android.os.VibrationEffect
+import android.os.Vibrator
+import android.os.VibratorManager
+import android.widget.RemoteViews
+import es.antonborri.home_widget.HomeWidgetPlugin
+import java.util.Calendar
+import java.util.Locale
+import kotlin.math.abs
+import kotlin.math.max
+import kotlin.math.min
+import kotlin.math.roundToInt
+
+const val OPEN_EXTRA = "gymmane_open"
+
+fun nutritionIntent(context: Context, code: Int): PendingIntent = PendingIntent.getActivity(
+ context,
+ code,
+ Intent(context, MainActivity::class.java)
+ .putExtra(OPEN_EXTRA, "nutrition")
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP),
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
+)
+
+abstract class VesselWidgetProvider(private val prefix: String, private val preview: Int) : DayWidgetProvider() {
+ override fun onReceive(context: Context, intent: Intent) {
+ if (intent.action == ACTION_ADD) {
+ val result = goAsync()
+ add(context) { result.finish() }
+ return
+ }
+ super.onReceive(context, intent)
+ }
+
+ override fun onUpdate(
+ context: Context,
+ appWidgetManager: AppWidgetManager,
+ appWidgetIds: IntArray,
+ widgetData: SharedPreferences
+ ) {
+ val state = State(widgetData)
+ val shown = widgetData.getInt("${prefix}_shown", -1)
+ val now = current(widgetData)
+ if (anims[prefix] != null && state.ready) {
+ animate(context, appWidgetIds, state, now, now) {}
+ } else if (shown in 0 until now && state.ready) {
+ animate(context, appWidgetIds, state, shown, now) {}
+ } else {
+ draw(context, appWidgetManager, appWidgetIds, state, level(state, now), now)
+ }
+ widgetData.edit().putInt("${prefix}_shown", now).apply()
+ scheduleNewDay(context)
+ }
+
+ private inner class State(val data: SharedPreferences) {
+ val on = data.getString("nutri_on", "0") == "1"
+ val goal = data.getString("${prefix}_goal", null)?.toIntOrNull() ?: 0
+ val step = data.getString("${prefix}_step", null)?.toIntOrNull() ?: 0
+ val mode = data.getString("${prefix}_mode", null) ?: "g"
+ val dec = data.getString("nutri_dec", null) ?: "."
+ val frames = data.getString("${prefix}_frames", null)
+ val count = data.getString("${prefix}_frames_n", null)?.toIntOrNull() ?: 0
+ val geo = data.getString("nutri_geo", null)?.split(',')?.mapNotNull { it.toFloatOrNull() } ?: emptyList()
+ val ready = on && frames != null && count > 0 && geo.size >= 9
+ val base = decode(data.getString("${prefix}_base", null))
+ val baseNight = decode(data.getString("${prefix}_base_night", null)) ?: base
+ private val cache = HashMap<Int, Bitmap?>()
+ private val small = HashMap<Boolean, Bitmap?>()
+
+ fun frame(i: Int): Bitmap? = cache.getOrPut(i) { decode("$frames$i.png") }
+
+ fun light(night: Boolean): Bitmap? = small.getOrPut(night) {
+ (if (night) baseNight else base)?.let {
+ Bitmap.createScaledBitmap(it, (it.width * LIGHT).roundToInt(), (it.height * LIGHT).roundToInt(), true)
+ }
+ }
+
+ fun color(key: String, night: Boolean, fallback: Int): Int {
+ val raw = data.getString(if (night) "${key}_night" else key, null) ?: data.getString(key, null)
+ return runCatching { Color.parseColor(raw) }.getOrDefault(fallback)
+ }
+ }
+
+ private fun decode(path: String?): Bitmap? = path?.let { runCatching { BitmapFactory.decodeFile(it) }.getOrNull() }
+
+ private fun current(data: SharedPreferences): Int {
+ val today = dayStamp(Calendar.getInstance())
+ val saved = if (data.getString("nutri_day", null) == today) {
+ data.getString("${prefix}_value", null)?.toIntOrNull() ?: 0
+ } else {
+ 0
+ }
+ val step = data.getString("${prefix}_step", null)?.toIntOrNull() ?: 0
+ val kind = if (prefix == "water") "w" else "s"
+ var extra = 0
+ for (item in data.getString(PENDING, null).orEmpty().split(';')) {
+ val p = item.split(',')
+ if (p.size != 3 || p[0] != kind) continue
+ val ms = p[1].toLongOrNull() ?: continue
+ if (dayStamp(Calendar.getInstance().apply { timeInMillis = ms }) != today) continue
+ extra += if (kind == "w") p[2].toIntOrNull() ?: 0 else step
+ }
+ return saved + extra
+ }
+
+ private fun level(state: State, value: Int): Float =
+ if (state.goal <= 0) 0f else (value.toFloat() / state.goal).coerceIn(0f, 1f)
+
+ private fun label(state: State, value: Int): String = when (state.mode) {
+ "L" -> {
+ val tenths = (value / 100.0).roundToInt()
+ if (tenths % 10 == 0) "${tenths / 10}" else String.format(Locale.ROOT, "%.1f", tenths / 10.0).replace(".", state.dec)
+ }
+ "oz" -> "${(value / 29.5735).roundToInt()}"
+ else -> "$value"
+ }
+
+ private fun compose(context: Context, state: State, night: Boolean, level: Float, value: Int, quick: Boolean = false): Bitmap? {
+ val base = (if (quick) state.light(night) else if (night) state.baseNight else state.base) ?: return null
+ if (!state.ready) return base
+ val out = base.copy(Bitmap.Config.ARGB_8888, true)
+ val canvas = Canvas(out)
+ val w = out.width.toFloat()
+ val h = out.height.toFloat()
+ val g = state.geo
+ val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
+ state.frame((level * state.count).roundToInt().coerceIn(0, state.count))?.let { frame ->
+ val top = g[1] * h
+ val height = g[2] * h
+ val width = height * frame.width / frame.height
+ canvas.drawBitmap(frame, null, RectF(g[0] * w, top, g[0] * w + width, top + height), paint)
+ }
+ val done = state.goal in 1..value
+ val tone = state.color("${prefix}_tone", night, Color.WHITE)
+ val doneTone = state.color("nutri_done", night, tone)
+ val text = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ typeface = font(context)
+ color = if (done) doneTone else state.color("nutri_text", night, Color.WHITE)
+ textSize = g[5] * h
+ }
+ val shown = label(state, value)
+ val room = g[6] * w
+ val wide = text.measureText(shown)
+ if (wide > room) text.textSize *= room / wide
+ canvas.drawText(shown, g[3] * w, g[4] * h, text)
+ val barX = g[3] * w
+ val barY = g[7] * h
+ val barH = g[8] * h
+ val fill = room * level
+ if (fill > 0.5f) {
+ val bar = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = if (done) doneTone else tone }
+ canvas.drawRoundRect(RectF(barX, barY, barX + max(fill, barH), barY + barH), barH / 2, barH / 2, bar)
+ }
+ return out
+ }
+
+ private fun views(context: Context, state: State, day: Bitmap?, night: Bitmap?): RemoteViews {
+ val target = javaClass
+ return RemoteViews(context.packageName, R.layout.widget_vessel).apply {
+ if (day == null && night == null) {
+ setImageViewResource(R.id.widget_image, preview)
+ setImageViewResource(R.id.widget_image_night, preview)
+ } else {
+ setImageViewBitmap(R.id.widget_image, day ?: night)
+ setImageViewBitmap(R.id.widget_image_night, night ?: day)
+ }
+ val open = nutritionIntent(context, prefix.hashCode())
+ val add = if (state.ready && state.step > 0) {
+ PendingIntent.getBroadcast(
+ context,
+ prefix.hashCode() + 1,
+ Intent(context, target).setAction(ACTION_ADD),
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
+ )
+ } else {
+ open
+ }
+ setOnClickPendingIntent(R.id.zone_open, open)
+ setOnClickPendingIntent(R.id.zone_add, add)
+ setOnClickPendingIntent(R.id.zone_add_low, add)
+ }
+ }
+
+ private fun draw(context: Context, manager: AppWidgetManager, ids: IntArray, state: State, level: Float, value: Int) {
+ val day = compose(context, state, false, level, value)
+ val night = compose(context, state, true, level, value)
+ val views = views(context, state, day, night)
+ ids.forEach { manager.updateAppWidget(it, views) }
+ }
+
+ private fun drawQuick(context: Context, manager: AppWidgetManager, ids: IntArray, state: State, level: Float, value: Int) {
+ val night = context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
+ val shown = compose(context, state, night, level, value, quick = true)
+ val views = views(context, state, shown, shown)
+ ids.forEach { manager.updateAppWidget(it, views) }
+ }
+
+ private fun add(context: Context, finish: () -> Unit) {
+ val data = HomeWidgetPlugin.getData(context)
+ val state = State(data)
+ if (!state.ready || state.step <= 0) {
+ finish()
+ return
+ }
+ val before = current(data)
+ val entry = if (prefix == "water") {
+ "w,${System.currentTimeMillis()},${state.step}"
+ } else {
+ "s,${System.currentTimeMillis()},${data.getString("${prefix}_food", null).orEmpty()}"
+ }
+ val pending = data.getString(PENDING, null).orEmpty()
+ data.edit()
+ .putString(PENDING, if (pending.isEmpty()) entry else "$pending;$entry")
+ .putInt("${prefix}_shown", before + state.step)
+ .commit()
+ tick(context)
+ val ids = AppWidgetManager.getInstance(context).getAppWidgetIds(ComponentName(context, javaClass))
+ animate(context, ids, state, before, before + state.step, finish)
+ }
+
+ private fun animate(context: Context, ids: IntArray, state: State, from: Int, to: Int, finish: () -> Unit) {
+ val manager = AppWidgetManager.getInstance(context.applicationContext)
+ val running = anims[prefix]
+ if (running != null) {
+ running.retarget(level(state, to), to)
+ running.finishes += finish
+ running.step = { level, value, last -> paint(context, manager, ids, state, level, value, last) }
+ return
+ }
+ if (abs(level(state, to) - level(state, from)) < 0.0005f && from == to) {
+ draw(context, manager, ids, state, level(state, to), to)
+ finish()
+ return
+ }
+ val anim = Anim(level(state, from), from, level(state, to), to)
+ anim.finishes += finish
+ anim.step = { level, value, last -> paint(context, manager, ids, state, level, value, last) }
+ anims[prefix] = anim
+ fun frame() {
+ val done = anim.advance()
+ if (!done) {
+ main.postDelayed({ frame() }, FRAME_MS)
+ } else {
+ anims.remove(prefix)
+ anim.finishes.forEach { it() }
+ }
+ }
+ frame()
+ }
+
+ private fun paint(context: Context, manager: AppWidgetManager, ids: IntArray, state: State, level: Float, value: Int, last: Boolean) {
+ if (last) draw(context, manager, ids, state, level, value) else drawQuick(context, manager, ids, state, level, value)
+ }
+
+ private class Anim(var fromLevel: Float, var fromValue: Int, var toLevel: Float, var toValue: Int) {
+ var start = SystemClock.uptimeMillis()
+ var level = fromLevel
+ var value = fromValue
+ val finishes = mutableListOf<() -> Unit>()
+ var step: (Float, Int, Boolean) -> Unit = { _, _, _ -> }
+
+ fun retarget(level: Float, value: Int) {
+ fromLevel = this.level
+ fromValue = this.value
+ toLevel = level
+ toValue = value
+ start = SystemClock.uptimeMillis()
+ }
+
+ fun advance(): Boolean {
+ val t = ((SystemClock.uptimeMillis() - start).toFloat() / DURATION).coerceIn(0f, 1f)
+ val ease = 1 + 2.2f * (t - 1) * (t - 1) * (t - 1) + 1.2f * (t - 1) * (t - 1)
+ level = (fromLevel + (toLevel - fromLevel) * ease).coerceIn(0f, 1f)
+ value = if (t >= 1f) toValue else fromValue + ((toValue - fromValue) * min(1f, t * 1.6f)).roundToInt()
+ step(level, value, t >= 1f)
+ return t >= 1f
+ }
+ }
+
+ @Suppress("DEPRECATION")
+ private fun tick(context: Context) {
+ runCatching {
+ val vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ (context.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager).defaultVibrator
+ } else {
+ context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
+ }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ vibrator.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_TICK))
+ } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ vibrator.vibrate(VibrationEffect.createOneShot(12, 80))
+ } else {
+ vibrator.vibrate(12)
+ }
+ }
+ }
+
+ companion object {
+ private const val ACTION_ADD = "com.gymmane.app.NUTRI_ADD"
+ private const val PENDING = "nutri_pending"
+ private const val DURATION = 720L
+ private const val FRAME_MS = 40L
+ private const val LIGHT = 0.6f
+ private val anims = HashMap<String, Anim>()
+ private val main = Handler(Looper.getMainLooper())
+ private var typeface: Typeface? = null
+
+ private fun font(context: Context): Typeface {
+ typeface?.let { return it }
+ val loaded = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ runCatching { context.resources.getFont(R.font.nunito_extrabold) }.getOrNull()
+ } else {
+ null
+ }
+ return (loaded ?: Typeface.create(Typeface.DEFAULT, Typeface.BOLD)).also { typeface = it }
+ }
+ }
+}
+
+class WaterWidgetProvider : VesselWidgetProvider("water", R.drawable.preview_water)
+
+class ProteinWidgetProvider : VesselWidgetProvider("protein", R.drawable.preview_protein)
+
+class KcalWidgetProvider : DayWidgetProvider() {
+ override fun onUpdate(
+ context: Context,
+ appWidgetManager: AppWidgetManager,
+ appWidgetIds: IntArray,
+ widgetData: SharedPreferences
+ ) {
+ val today = dayStamp(Calendar.getInstance())
+ val key = if (widgetData.getString("nutri_day", null) == today) "kcal_img" else "kcal_fresh_img"
+ appWidgetIds.forEach { widgetId ->
+ val views = RemoteViews(context.packageName, R.layout.widget_kcal).apply {
+ val day = widgetData.getString(key, null)?.let { BitmapFactory.decodeFile(it) }
+ val night = widgetData.getString("${key}_night", null)?.let { BitmapFactory.decodeFile(it) } ?: day
+ if (day == null) {
+ setImageViewResource(R.id.widget_image, R.drawable.preview_kcal)
+ setImageViewResource(R.id.widget_image_night, R.drawable.preview_kcal)
+ } else {
+ setImageViewBitmap(R.id.widget_image, day)
+ setImageViewBitmap(R.id.widget_image_night, night ?: day)
+ }
+ val open = nutritionIntent(context, 7301)
+ setOnClickPendingIntent(R.id.widget_image, open)
+ setOnClickPendingIntent(R.id.widget_image_night, open)
+ }
+ appWidgetManager.updateAppWidget(widgetId, views)
+ }
+ scheduleNewDay(context)
+ }
+}
diff --git a/android/app/src/main/res/drawable/preview_kcal.png b/android/app/src/main/res/drawable/preview_kcal.png
new file mode 100644
index 0000000..98ff5a0
Binary files /dev/null and b/android/app/src/main/res/drawable/preview_kcal.png differ
diff --git a/android/app/src/main/res/drawable/preview_protein.png b/android/app/src/main/res/drawable/preview_protein.png
new file mode 100644
index 0000000..61659a1
Binary files /dev/null and b/android/app/src/main/res/drawable/preview_protein.png differ
diff --git a/android/app/src/main/res/drawable/preview_water.png b/android/app/src/main/res/drawable/preview_water.png
new file mode 100644
index 0000000..68615a9
Binary files /dev/null and b/android/app/src/main/res/drawable/preview_water.png differ
diff --git a/android/app/src/main/res/layout-night/widget_kcal.xml b/android/app/src/main/res/layout-night/widget_kcal.xml
new file mode 100644
index 0000000..80f3587
--- /dev/null
+++ b/android/app/src/main/res/layout-night/widget_kcal.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent">
+
+ <ImageView
+ android:id="@+id/widget_image"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:adjustViewBounds="true"
+ android:scaleType="fitCenter"
+ android:visibility="gone"
+ android:contentDescription="GymMane" />
+
+ <ImageView
+ android:id="@+id/widget_image_night"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:adjustViewBounds="true"
+ android:scaleType="fitCenter"
+ android:visibility="visible"
+ android:contentDescription="GymMane" />
+</FrameLayout>
diff --git a/android/app/src/main/res/layout-night/widget_vessel.xml b/android/app/src/main/res/layout-night/widget_vessel.xml
new file mode 100644
index 0000000..648d1b9
--- /dev/null
+++ b/android/app/src/main/res/layout-night/widget_vessel.xml
@@ -0,0 +1,54 @@
+<?xml version="1.0" encoding="utf-8"?>
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent">
+
+ <ImageView
+ android:id="@+id/widget_image"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:adjustViewBounds="true"
+ android:scaleType="fitCenter"
+ android:visibility="gone"
+ android:contentDescription="GymMane" />
+
+ <ImageView
+ android:id="@+id/widget_image_night"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:adjustViewBounds="true"
+ android:scaleType="fitCenter"
+ android:visibility="visible"
+ android:contentDescription="GymMane" />
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:orientation="horizontal">
+
+ <FrameLayout
+ android:id="@+id/zone_add"
+ android:layout_width="0dp"
+ android:layout_height="match_parent"
+ android:layout_weight="45" />
+
+ <LinearLayout
+ android:layout_width="0dp"
+ android:layout_height="match_parent"
+ android:layout_weight="55"
+ android:orientation="vertical">
+
+ <FrameLayout
+ android:id="@+id/zone_open"
+ android:layout_width="match_parent"
+ android:layout_height="0dp"
+ android:layout_weight="72" />
+
+ <FrameLayout
+ android:id="@+id/zone_add_low"
+ android:layout_width="match_parent"
+ android:layout_height="0dp"
+ android:layout_weight="28" />
+ </LinearLayout>
+ </LinearLayout>
+</FrameLayout>
diff --git a/android/app/src/main/res/layout/widget_kcal.xml b/android/app/src/main/res/layout/widget_kcal.xml
new file mode 100644
index 0000000..8332aee
--- /dev/null
+++ b/android/app/src/main/res/layout/widget_kcal.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent">
+
+ <ImageView
+ android:id="@+id/widget_image"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:adjustViewBounds="true"
+ android:scaleType="fitCenter"
+ android:visibility="visible"
+ android:contentDescription="GymMane" />
+
+ <ImageView
+ android:id="@+id/widget_image_night"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:adjustViewBounds="true"
+ android:scaleType="fitCenter"
+ android:visibility="gone"
+ android:contentDescription="GymMane" />
+</FrameLayout>
diff --git a/android/app/src/main/res/layout/widget_vessel.xml b/android/app/src/main/res/layout/widget_vessel.xml
new file mode 100644
index 0000000..752095a
--- /dev/null
+++ b/android/app/src/main/res/layout/widget_vessel.xml
@@ -0,0 +1,54 @@
+<?xml version="1.0" encoding="utf-8"?>
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent">
+
+ <ImageView
+ android:id="@+id/widget_image"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:adjustViewBounds="true"
+ android:scaleType="fitCenter"
+ android:visibility="visible"
+ android:contentDescription="GymMane" />
+
+ <ImageView
+ android:id="@+id/widget_image_night"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:adjustViewBounds="true"
+ android:scaleType="fitCenter"
+ android:visibility="gone"
+ android:contentDescription="GymMane" />
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:orientation="horizontal">
+
+ <FrameLayout
+ android:id="@+id/zone_add"
+ android:layout_width="0dp"
+ android:layout_height="match_parent"
+ android:layout_weight="45" />
+
+ <LinearLayout
+ android:layout_width="0dp"
+ android:layout_height="match_parent"
+ android:layout_weight="55"
+ android:orientation="vertical">
+
+ <FrameLayout
+ android:id="@+id/zone_open"
+ android:layout_width="match_parent"
+ android:layout_height="0dp"
+ android:layout_weight="72" />
+
+ <FrameLayout
+ android:id="@+id/zone_add_low"
+ android:layout_width="match_parent"
+ android:layout_height="0dp"
+ android:layout_weight="28" />
+ </LinearLayout>
+ </LinearLayout>
+</FrameLayout>
diff --git a/android/app/src/main/res/xml/kcal_widget_info.xml b/android/app/src/main/res/xml/kcal_widget_info.xml
new file mode 100644
index 0000000..3ef8694
--- /dev/null
+++ b/android/app/src/main/res/xml/kcal_widget_info.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
+ android:minWidth="250dp"
+ android:minHeight="110dp"
+ android:targetCellWidth="4"
+ android:targetCellHeight="2"
+ android:updatePeriodMillis="0"
+ android:initialLayout="@layout/widget_kcal"
+ android:resizeMode="horizontal|vertical"
+ android:widgetCategory="home_screen"
+ android:previewImage="@drawable/preview_kcal" />
diff --git a/android/app/src/main/res/xml/protein_widget_info.xml b/android/app/src/main/res/xml/protein_widget_info.xml
new file mode 100644
index 0000000..cc77ac9
--- /dev/null
+++ b/android/app/src/main/res/xml/protein_widget_info.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
+ android:minWidth="110dp"
+ android:minHeight="110dp"
+ android:targetCellWidth="2"
+ android:targetCellHeight="2"
+ android:updatePeriodMillis="0"
+ android:initialLayout="@layout/widget_vessel"
+ android:resizeMode="horizontal|vertical"
+ android:widgetCategory="home_screen"
+ android:previewImage="@drawable/preview_protein" />
diff --git a/android/app/src/main/res/xml/water_widget_info.xml b/android/app/src/main/res/xml/water_widget_info.xml
new file mode 100644
index 0000000..4b210dc
--- /dev/null
+++ b/android/app/src/main/res/xml/water_widget_info.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
+ android:minWidth="110dp"
+ android:minHeight="110dp"
+ android:targetCellWidth="2"
+ android:targetCellHeight="2"
+ android:updatePeriodMillis="0"
+ android:initialLayout="@layout/widget_vessel"
+ android:resizeMode="horizontal|vertical"
+ android:widgetCategory="home_screen"
+ android:previewImage="@drawable/preview_water" />
diff --git a/lib/app/app_shell.dart b/lib/app/app_shell.dart
index a9607f8..b0304ae 100644
--- a/lib/app/app_shell.dart
+++ b/lib/app/app_shell.dart
@@ -34,6 +34,7 @@ import '../screens/tools_screen.dart';
import '../screens/train_screen.dart';
import '../services/health_steps.dart';
import '../services/incoming_share.dart';
+import '../services/nutrition_widgets.dart';
import '../state/fit_state.dart';
import '../theme/app_colors.dart';
import '../theme/app_theme.dart';
@@ -99,15 +100,24 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver {
fit.addListener(_restOver);
_queueCelebration();
IncomingShare.listen(_receive);
+ NutritionWidgets.listenOpen(_openFromWidget);
HealthSteps.listen(_showStepsInfo);
fit.refreshSteps();
WidgetsBinding.instance.addPostFrameCallback((_) async {
final text = await IncomingShare.take();
if (text != null) _receive(text);
+ await NutritionWidgets.takePending();
+ final open = await NutritionWidgets.takeOpen();
+ if (open != null) _openFromWidget(open);
if (await HealthSteps.takeUsage()) _showStepsInfo();
});
}
+ void _openFromWidget(String route) {
+ if (!mounted || !fit.onboarded || route != 'nutrition' || fit.isSessionActive) return;
+ if (fit.route != 'nutrition') fit.goNutrition();
+ }
+
void _showStepsInfo() {
if (!mounted || !fit.onboarded) return;
showStepsSheet(context);
@@ -225,6 +235,7 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver {
fit.persistNow();
}
if (state == AppLifecycleState.resumed) {
+ NutritionWidgets.takePending();
fit.refreshAlarmPermission();
fit.syncRest();
fit.refreshWidgets();
diff --git a/lib/main.dart b/lib/main.dart
index 8512e67..6e043d6 100644
--- a/lib/main.dart
+++ b/lib/main.dart
@@ -6,6 +6,7 @@ import 'app/gymmane_app.dart';
import 'services/alarm_store.dart';
import 'services/device_kind.dart';
import 'services/home_widget_bridge.dart';
+import 'services/nutrition_widgets.dart';
import 'services/live_workout.dart';
import 'services/local_store.dart';
import 'services/media_store.dart';
@@ -45,6 +46,7 @@ Future<void> main() async {
}
fit.onWidgetsShouldUpdate = HomeWidgetBridge.update;
+ NutritionWidgets.watch(HomeWidgetBridge.update);
runApp(const GymManeApp());
WidgetsBinding.instance.addPostFrameCallback((_) => HomeWidgetBridge.update());
diff --git a/lib/screens/nutrition/cards.dart b/lib/screens/nutrition/cards.dart
index 63b60f6..c3b90cc 100644
--- a/lib/screens/nutrition/cards.dart
+++ b/lib/screens/nutrition/cards.dart
@@ -747,15 +747,6 @@ Future<void> showWaterSheet(BuildContext context) => _sheet<void>(context, (cont
);
});
-Color _shakeColor(FoodItem? shake) {
- final name = foldText('${shake?.name ?? ''} ${FoodLibrary.byId(shake?.id ?? '')?.names['en'] ?? ''}');
- bool has(List<String> words) => words.any(name.contains);
- if (has(['choc', 'cacao', 'cocoa', 'kakao', 'coffee', 'cafe', 'mocha'])) return const Color(0xFF8A5A3C);
- if (has(['fresa', 'strawberr', 'berry', 'frutos rojos', 'erdbeer', 'fraise'])) return const Color(0xFFE3A7AE);
- if (has(['platano', 'banana', 'mango'])) return const Color(0xFFE6D08E);
- return const Color(0xFFE2D5BC);
-}
-
class _ShakeTile extends StatelessWidget {
const _ShakeTile();
@@ -790,7 +781,7 @@ class _ShakeTile extends StatelessWidget {
top: 0.407,
bottom: 0.975,
curve: 0.066,
- liquid: _shakeColor(shake),
+ liquid: shakeColor(shake),
texture: 'assets/img/shake-texture.webp',
),
),
diff --git a/lib/services/home_widget_bridge.dart b/lib/services/home_widget_bridge.dart
index 94e2cfa..844a87b 100644
--- a/lib/services/home_widget_bridge.dart
+++ b/lib/services/home_widget_bridge.dart
@@ -8,6 +8,7 @@ import 'package:home_widget/home_widget.dart';
import '../state/fit_state.dart';
import '../theme/app_colors.dart';
import '../widgets/home_widget_views.dart';
+import 'nutrition_widgets.dart';
class HomeWidgetBridge {
HomeWidgetBridge._();
@@ -189,6 +190,9 @@ class HomeWidgetBridge {
if (path != null) await HomeWidget.saveWidgetData<String>('${key}_night', path);
}
}
+ if (!_ios && NutritionWidgets.providers.any(wants)) {
+ await NutritionWidgets.paint(render: _render, wants: wants, day: day, night: night, framed: framed);
+ }
final now = DateTime.now();
if (everyone) _allPainted = today;
await HomeWidget.saveWidgetData<String>('today_stamp', _stamp(now));
@@ -217,6 +221,11 @@ class HomeWidgetBridge {
]) {
if (wants(android)) await _reload(android, ios);
}
+ if (!_ios) {
+ for (final android in NutritionWidgets.providers) {
+ if (wants(android)) await _reload(android, android);
+ }
+ }
} catch (e) {
debugPrint('HomeWidgetBridge.update falló: $e');
}
diff --git a/lib/services/nutrition_widgets.dart b/lib/services/nutrition_widgets.dart
new file mode 100644
index 0000000..9e6809f
--- /dev/null
+++ b/lib/services/nutrition_widgets.dart
@@ -0,0 +1,291 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter/widgets.dart';
+import 'package:home_widget/home_widget.dart';
+import 'package:path_provider/path_provider.dart';
+import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';
+
+import '../l10n/l10n.dart';
+import '../state/fit_state.dart';
+import '../theme/app_colors.dart';
+import '../widgets/home_widget_views.dart';
+import '../widgets/nutrition_art.dart';
+
+typedef WidgetRender = Future<void> Function(Widget view, String key, Size size);
+
+class NutritionWidgets {
+ NutritionWidgets._();
+
+ static const water = 'WaterWidgetProvider';
+ static const protein = 'ProteinWidgetProvider';
+ static const kcal = 'KcalWidgetProvider';
+ static const providers = [water, protein, kcal];
+ static const levels = 48;
+ static const kcalSize = Size(320, 150);
+ static const _pendingKey = 'nutri_pending';
+ static const _route = MethodChannel('gymmane/open');
+ static String _signature = '';
+
+ static String signature() {
+ final today = DateTime.now();
+ final g = fit.goalsFor(today);
+ final m = fit.totalOn(today);
+ return [
+ fit.nutritionBeta,
+ fit.waterOn(today),
+ m.kcal.round(),
+ m.protein.round(),
+ m.carbs.round(),
+ m.fat.round(),
+ g.kcal,
+ g.protein,
+ g.carbs,
+ g.fat,
+ g.waterMl,
+ g.glassMl,
+ fit.isLb,
+ fit.useKj,
+ fit.shakeFoodId,
+ fit.language,
+ today.day,
+ ].join('|');
+ }
+
+ static void watch(VoidCallback update) {
+ _signature = signature();
+ fit.addListener(() {
+ final next = signature();
+ if (next == _signature) return;
+ _signature = next;
+ update();
+ });
+ }
+
+ static Future<void> takePending() async {
+ if (kIsWeb || !Platform.isAndroid) return;
+ try {
+ final raw = await HomeWidget.getWidgetData<String>(_pendingKey);
+ if (raw == null || raw.isEmpty) return;
+ await HomeWidget.saveWidgetData<String>(_pendingKey, '');
+ fit.takeWidgetLog(raw);
+ } catch (e) {
+ debugPrint('NutritionWidgets.takePending falló: $e');
+ }
+ }
+
+ static void listenOpen(void Function(String route) onOpen) {
+ if (kIsWeb || !Platform.isAndroid) return;
+ _route.setMethodCallHandler((call) async {
+ final route = call.arguments;
+ if (call.method == 'open' && route is String) onOpen(route);
+ });
+ }
+
+ static Future<String?> takeOpen() async {
+ if (kIsWeb || !Platform.isAndroid) return null;
+ try {
+ return await _route.invokeMethod<String>('take');
+ } catch (_) {
+ return null;
+ }
+ }
+
+ static Future<void> paint({
+ required WidgetRender render,
+ required bool Function(String provider) wants,
+ required GymColors day,
+ required GymColors night,
+ required bool framed,
+ }) async {
+ final today = DateTime.now();
+ final g = fit.goalsFor(today);
+ final total = fit.totalOn(today);
+ final off = fit.nutritionBeta ? null : t.widgetNutritionOff;
+ await HomeWidget.saveWidgetData<String>('nutri_on', fit.nutritionBeta ? '1' : '0');
+ await HomeWidget.saveWidgetData<String>('nutri_day', _stamp(today));
+ await HomeWidget.saveWidgetData<String>('nutri_dec', decimalSeparator);
+ await HomeWidget.saveWidgetData<String>(
+ 'nutri_geo', VesselWidgetGeometry.fractions().map((v) => v.toStringAsFixed(5)).join(','));
+ await HomeWidget.saveWidgetData<String>('nutri_text', _hex(day.text));
+ await HomeWidget.saveWidgetData<String>('nutri_text_night', _hex(night.text));
+ await HomeWidget.saveWidgetData<String>('nutri_done', _hex(day.sage));
+ await HomeWidget.saveWidgetData<String>('nutri_done_night', _hex(night.sage));
+
+ if (wants(water)) {
+ await _both(
+ render,
+ (gc) => VesselWidgetView(
+ gc: gc,
+ title: t.waterLabel,
+ icon: PhosphorIconsFill.drop,
+ tone: gc.water,
+ goal: '/ ${fit.waterLabel(g.waterMl)}',
+ pill: '+ ${fit.waterLabel(g.glassMl)}',
+ message: off,
+ framed: framed,
+ ),
+ 'water_base',
+ VesselWidgetGeometry.size,
+ day,
+ night,
+ );
+ await _frames('water', VesselLook.water);
+ await _numbers('water', {
+ 'value': '${fit.waterOn(today)}',
+ 'goal': '${g.waterMl}',
+ 'step': '${g.glassMl}',
+ 'mode': fit.isLb ? 'oz' : 'L',
+ 'tone': _hex(day.water),
+ 'tone_night': _hex(night.water),
+ });
+ }
+
+ if (wants(protein)) {
+ final shake = fit.shakeFood;
+ final step = shake == null ? 0 : shake.macros.protein.round();
+ await _both(
+ render,
+ (gc) => VesselWidgetView(
+ gc: gc,
+ title: t.macroProtein,
+ icon: PhosphorIconsFill.lightning,
+ tone: gc.protein,
+ goal: '/ ${g.protein} g',
+ pill: shake == null ? t.widgetPickShake : '+ $step g',
+ message: off,
+ framed: framed,
+ ),
+ 'protein_base',
+ VesselWidgetGeometry.size,
+ day,
+ night,
+ );
+ await _frames('protein', VesselLook.shake(shakeColor(shake)));
+ await _numbers('protein', {
+ 'value': '${total.protein.round()}',
+ 'goal': '${g.protein}',
+ 'step': '$step',
+ 'food': shake?.id ?? '',
+ 'mode': 'g',
+ 'tone': _hex(day.protein),
+ 'tone_night': _hex(night.protein),
+ });
+ }
+
+ if (wants(kcal)) {
+ final kj = fit.useKj;
+ int energy(num kcal) => (kj ? kcal * 4.184 : kcal).round();
+ await _both(
+ render,
+ (gc) => KcalWidgetView(
+ gc: gc,
+ kcal: energy(total.kcal),
+ goal: energy(g.kcal),
+ protein: total.protein,
+ carbs: total.carbs,
+ fat: total.fat,
+ goals: (g.protein, g.carbs, g.fat),
+ unit: kj ? 'kJ' : 'kcal',
+ message: off,
+ size: kcalSize,
+ framed: framed,
+ ),
+ 'kcal_img',
+ kcalSize,
+ day,
+ night,
+ );
+ await _both(
+ render,
+ (gc) => KcalWidgetView(
+ gc: gc,
+ kcal: 0,
+ goal: energy(g.kcal),
+ protein: 0,
+ carbs: 0,
+ fat: 0,
+ goals: (g.protein, g.carbs, g.fat),
+ unit: kj ? 'kJ' : 'kcal',
+ message: off,
+ size: kcalSize,
+ framed: framed,
+ ),
+ 'kcal_fresh_img',
+ kcalSize,
+ day,
+ night,
+ );
+ }
+ }
+
+ static Future<void> _both(WidgetRender render, Widget Function(GymColors) build, String key, Size size,
+ GymColors day, GymColors night) async {
+ await render(build(day), key, size);
+ if (!identical(day, night)) {
+ await render(build(night), '${key}_night', size);
+ } else {
+ final path = await HomeWidget.getWidgetData<String>(key);
+ if (path != null) await HomeWidget.saveWidgetData<String>('${key}_night', path);
+ }
+ }
+
+ static Future<void> _numbers(String prefix, Map<String, String> values) async {
+ for (final e in values.entries) {
+ await HomeWidget.saveWidgetData<String>('${prefix}_${e.key}', e.value);
+ }
+ }
+
+ static Future<void> _frames(String prefix, VesselLook look) async {
+ final key = '${look.asset}|${look.liquid.toARGB32()}|$levels|2';
+ final dir = Directory('${(await getApplicationSupportDirectory()).path}/widget_frames');
+ final last = File('${dir.path}/${prefix}_$levels.png');
+ if (await HomeWidget.getWidgetData<String>('${prefix}_frames_key') == key && last.existsSync()) return;
+ dir.createSync(recursive: true);
+ final image = await _load(look.asset);
+ final mask = await _load(look.asset.replaceFirst('.webp', '-mask.webp'));
+ final texture = look.texture == null ? null : await _load(look.texture!);
+ const height = VesselWidgetGeometry.vesselHeight;
+ final size = Size(height * image.width / image.height, height);
+ const scale = 3.0;
+ for (var i = 0; i <= levels; i++) {
+ final picture = paintVesselFrame(
+ look: look,
+ image: image,
+ mask: mask,
+ texture: texture,
+ level: i / levels,
+ phase: (i * 0.071) % 1,
+ size: size,
+ scale: scale,
+ );
+ final frame = await picture.toImage((size.width * scale).ceil(), (size.height * scale).ceil());
+ picture.dispose();
+ final png = await frame.toByteData(format: ui.ImageByteFormat.png);
+ frame.dispose();
+ if (png == null) continue;
+ await File('${dir.path}/${prefix}_$i.png').writeAsBytes(png.buffer.asUint8List(), flush: true);
+ }
+ image.dispose();
+ mask.dispose();
+ texture?.dispose();
+ await HomeWidget.saveWidgetData<String>('${prefix}_frames', '${dir.path}/${prefix}_');
+ await HomeWidget.saveWidgetData<String>('${prefix}_frames_n', '$levels');
+ await HomeWidget.saveWidgetData<String>('${prefix}_frames_key', key);
+ }
+
+ static Future<ui.Image> _load(String asset) async {
+ final data = await rootBundle.load(asset);
+ final codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
+ final frame = await codec.getNextFrame();
+ codec.dispose();
+ return frame.image;
+ }
+
+ static String _stamp(DateTime d) =>
+ '${d.year.toString().padLeft(4, '0')}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}';
+
+ static String _hex(Color c) => '#${c.toARGB32().toRadixString(16).padLeft(8, '0').toUpperCase()}';
+}
diff --git a/lib/widgets/home_widget_views.dart b/lib/widgets/home_widget_views.dart
index e67289d..58bce8c 100644
--- a/lib/widgets/home_widget_views.dart
+++ b/lib/widgets/home_widget_views.dart
@@ -1,11 +1,13 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
+import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';
import '../l10n/l10n.dart';
import '../state/fit_state.dart';
import '../theme/app_colors.dart';
import 'body_map.dart';
+import 'nutrition_art.dart';
import 'ui_kit.dart';
const _kDisplay = 'Nunito';
@@ -503,3 +505,288 @@ class BodyWidgetView extends StatelessWidget {
);
}
}
+
+class VesselWidgetGeometry {
+ const VesselWidgetGeometry._();
+
+ static const size = Size(155, 155);
+ static const vesselLeft = 10.0;
+ static const vesselTop = 10.0;
+ static const vesselHeight = 136.0;
+ static const columnLeft = 70.0;
+ static const columnRight = 141.0;
+ static const valueBaseline = 82.0;
+ static const valueSize = 32.0;
+ static const barTop = 108.0;
+ static const barHeight = 6.0;
+ static const pillTop = 122.0;
+
+ static List<double> fractions() => [
+ vesselLeft / size.width,
+ vesselTop / size.height,
+ vesselHeight / size.height,
+ columnLeft / size.width,
+ valueBaseline / size.height,
+ valueSize / size.height,
+ (columnRight - columnLeft) / size.width,
+ barTop / size.height,
+ barHeight / size.height,
+ ];
+}
+
+class VesselWidgetView extends StatelessWidget {
+ const VesselWidgetView({
+ super.key,
+ required this.gc,
+ required this.title,
+ required this.icon,
+ required this.tone,
+ required this.goal,
+ required this.pill,
+ this.message,
+ this.framed = true,
+ });
+
+ final GymColors gc;
+ final String title;
+ final IconData icon;
+ final Color tone;
+ final String goal;
+ final String pill;
+ final String? message;
+ final bool framed;
+
+ @override
+ Widget build(BuildContext context) {
+ const g = VesselWidgetGeometry.size;
+ const left = VesselWidgetGeometry.columnLeft;
+ const width = VesselWidgetGeometry.columnRight - VesselWidgetGeometry.columnLeft;
+ final text = message;
+ return Container(
+ width: g.width,
+ height: g.height,
+ decoration: _card(gc, framed, 24),
+ child: Stack(children: [
+ Positioned(
+ left: -34,
+ top: 34,
+ child: Container(
+ width: 120,
+ height: 120,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ gradient: RadialGradient(colors: [tone.withValues(alpha: 0.18), tone.withValues(alpha: 0)]),
+ ),
+ ),
+ ),
+ Positioned(
+ left: left,
+ top: 16,
+ width: width,
+ child: Row(children: [
+ Icon(icon, size: 13, color: tone),
+ const SizedBox(width: 4),
+ Expanded(
+ child: FittedBox(
+ fit: BoxFit.scaleDown,
+ alignment: Alignment.centerLeft,
+ child: Text(title.toUpperCase(),
+ maxLines: 1,
+ style: TextStyle(
+ fontFamily: _kDisplay,
+ fontSize: 11,
+ fontWeight: FontWeight.w800,
+ letterSpacing: 1,
+ color: gc.textSecondary)),
+ ),
+ ),
+ ]),
+ ),
+ if (text != null)
+ Positioned(
+ left: left,
+ top: 40,
+ width: width,
+ bottom: 14,
+ child: Text(text,
+ maxLines: 5,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ fontFamily: _kBody, fontSize: 11, height: 1.3, fontWeight: FontWeight.w600, color: gc.textSecondary)),
+ )
+ else ...[
+ Positioned(
+ left: left,
+ top: VesselWidgetGeometry.valueBaseline + 4,
+ width: width,
+ child: FittedBox(
+ fit: BoxFit.scaleDown,
+ alignment: Alignment.centerLeft,
+ child: Text(goal,
+ maxLines: 1,
+ style: TextStyle(
+ fontFamily: _kBody, fontSize: 12, fontWeight: FontWeight.w700, color: gc.textSecondary)),
+ ),
+ ),
+ Positioned(
+ left: left,
+ top: VesselWidgetGeometry.barTop,
+ width: width,
+ height: VesselWidgetGeometry.barHeight,
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ color: gc.bgRaised2, borderRadius: BorderRadius.circular(VesselWidgetGeometry.barHeight)),
+ ),
+ ),
+ Positioned(
+ left: left,
+ top: VesselWidgetGeometry.pillTop,
+ width: width,
+ height: 22,
+ child: Container(
+ alignment: Alignment.center,
+ padding: const EdgeInsets.symmetric(horizontal: 6),
+ decoration: BoxDecoration(
+ color: tone.withValues(alpha: 0.16),
+ borderRadius: BorderRadius.circular(11),
+ ),
+ child: FittedBox(
+ fit: BoxFit.scaleDown,
+ child: Text(pill,
+ maxLines: 1,
+ style: TextStyle(fontFamily: _kDisplay, fontSize: 11.5, fontWeight: FontWeight.w800, color: tone)),
+ ),
+ ),
+ ),
+ ],
+ ]),
+ );
+ }
+}
+
+class KcalWidgetView extends StatelessWidget {
+ const KcalWidgetView({
+ super.key,
+ required this.gc,
+ required this.kcal,
+ required this.goal,
+ required this.protein,
+ required this.carbs,
+ required this.fat,
+ required this.goals,
+ required this.unit,
+ this.message,
+ this.size = const Size(320, 150),
+ this.framed = true,
+ });
+
+ final GymColors gc;
+ final int kcal;
+ final int goal;
+ final double protein, carbs, fat;
+ final (int, int, int) goals;
+ final String unit;
+ final String? message;
+ final Size size;
+ final bool framed;
+
+ @override
+ Widget build(BuildContext context) {
+ final left = goal - kcal;
+ final ring = size.height - 30;
+ final text = message;
+ Widget macro(IconData icon, String label, double value, int target, Color color) => Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(children: [
+ Icon(icon, size: 11, color: color),
+ const SizedBox(width: 4),
+ Expanded(
+ child: Text(sentenceCase(label),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ fontFamily: _kBody, fontSize: 10.5, fontWeight: FontWeight.w700, color: gc.textSecondary)),
+ ),
+ Text('${value.round()}',
+ style: TextStyle(fontFamily: _kDisplay, fontSize: 11, fontWeight: FontWeight.w800, color: gc.text)),
+ Text(' / $target g',
+ style: TextStyle(
+ fontFamily: _kBody, fontSize: 10, fontWeight: FontWeight.w600, color: gc.textTertiary)),
+ ]),
+ const SizedBox(height: 4),
+ MacroTrack(pct: target <= 0 ? 0 : value / target, color: color, height: 5),
+ ],
+ );
+ return Theme(
+ data: ThemeData(extensions: [gc]),
+ child: Container(
+ width: size.width,
+ height: size.height,
+ padding: const EdgeInsets.all(15),
+ decoration: _card(gc, framed, 24),
+ child: text != null
+ ? Center(
+ child: Text(text,
+ textAlign: TextAlign.center,
+ style: TextStyle(
+ fontFamily: _kBody, fontSize: 12, fontWeight: FontWeight.w600, color: gc.textSecondary)),
+ )
+ : Row(children: [
+ CalorieRing(
+ pct: goal <= 0 ? 0 : kcal / goal,
+ size: ring,
+ stroke: 10,
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
+ FittedBox(
+ fit: BoxFit.scaleDown,
+ child: Text('${left.abs()}',
+ style: TextStyle(
+ fontFamily: _kDisplay,
+ fontSize: 25,
+ height: 1.05,
+ fontWeight: FontWeight.w800,
+ color: left < 0 ? gc.danger : gc.text)),
+ ),
+ Text(left < 0 ? t.kcalOver : sentenceCase(t.kcalRemaining),
+ style: TextStyle(
+ fontFamily: _kBody, fontSize: 9.5, fontWeight: FontWeight.w700, color: gc.textSecondary)),
+ ]),
+ ),
+ const SizedBox(width: 16),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.baseline,
+ textBaseline: TextBaseline.alphabetic,
+ children: [
+ Icon(PhosphorIconsFill.fire, size: 15, color: gc.warn),
+ const SizedBox(width: 4),
+ Text('$kcal',
+ style: TextStyle(
+ fontFamily: _kDisplay, fontSize: 18, fontWeight: FontWeight.w800, color: gc.text)),
+ Flexible(
+ child: Text(' / $goal $unit',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ fontFamily: _kBody,
+ fontSize: 11,
+ fontWeight: FontWeight.w700,
+ color: gc.textTertiary)),
+ ),
+ ]),
+ macro(PhosphorIconsFill.egg, t.macroProtein, protein, goals.$1, gc.protein),
+ macro(PhosphorIconsFill.grains, t.macroCarbs, carbs, goals.$2, gc.carbs),
+ macro(PhosphorIconsFill.drop, t.macroFat, fat, goals.$3, gc.fat),
+ ],
+ ),
+ ),
+ ]),
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/nutrition_art.dart b/lib/widgets/nutrition_art.dart
index 9c2a655..d26edfd 100644
--- a/lib/widgets/nutrition_art.dart
+++ b/lib/widgets/nutrition_art.dart
@@ -1,12 +1,13 @@
import 'dart:io';
import 'dart:math' as math;
-import 'dart:ui' as ui show Image, PictureRecorder;
+import 'dart:ui' as ui show Image, Picture, PictureRecorder;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';
import '../models/nutrition.dart';
+import '../services/food_library.dart';
import '../services/media_store.dart';
import '../theme/app_colors.dart';
import '../theme/app_theme.dart';
@@ -492,6 +493,78 @@ class _PhotoVesselState extends State<PhotoVessel> with SingleTickerProviderStat
}
}
+Color shakeColor(FoodItem? shake) {
+ final name = foldText('${shake?.name ?? ''} ${FoodLibrary.byId(shake?.id ?? '')?.names['en'] ?? ''}');
+ bool has(List<String> words) => words.any(name.contains);
+ if (has(['choc', 'cacao', 'cocoa', 'kakao', 'coffee', 'cafe', 'mocha'])) return const Color(0xFF8A5A3C);
+ if (has(['fresa', 'strawberr', 'berry', 'frutos rojos', 'erdbeer', 'fraise'])) return const Color(0xFFE3A7AE);
+ if (has(['platano', 'banana', 'mango'])) return const Color(0xFFE6D08E);
+ return const Color(0xFFE2D5BC);
+}
+
+class VesselLook {
+ const VesselLook({
+ required this.asset,
+ required this.top,
+ required this.bottom,
+ required this.curve,
+ required this.liquid,
+ this.texture,
+ });
+
+ final String asset;
+ final double top;
+ final double bottom;
+ final double curve;
+ final Color liquid;
+ final String? texture;
+
+ static const water = VesselLook(
+ asset: 'assets/img/vessel-water.webp',
+ top: 0.269,
+ bottom: 0.989,
+ curve: 0.08,
+ liquid: Color(0xFF4FB4F2),
+ );
+
+ static VesselLook shake(Color liquid) => VesselLook(
+ asset: 'assets/img/vessel-shake.webp',
+ top: 0.407,
+ bottom: 0.975,
+ curve: 0.066,
+ liquid: liquid,
+ texture: 'assets/img/shake-texture.webp',
+ );
+}
+
+ui.Picture paintVesselFrame({
+ required VesselLook look,
+ required ui.Image image,
+ required ui.Image mask,
+ ui.Image? texture,
+ required double level,
+ required double phase,
+ required Size size,
+ double scale = 1,
+}) {
+ final recorder = ui.PictureRecorder();
+ final canvas = Canvas(recorder)..scale(scale);
+ final spin = ValueNotifier<double>(phase);
+ _VesselPainter(
+ image: image,
+ mask: mask,
+ texture: texture,
+ level: level.clamp(0.0, 1.0),
+ spin: spin,
+ top: look.top,
+ bottom: look.bottom,
+ curve: look.curve,
+ liquid: look.liquid,
+ ).paint(canvas, size);
+ spin.dispose();
+ return recorder.endRecording();
+}
+
class _VesselPainter extends CustomPainter {
_VesselPainter({
required this.image,
diff --git a/test/nutrition_beta_keys.txt b/test/nutrition_beta_keys.txt
index 86e2877..169e74e 100644
--- a/test/nutrition_beta_keys.txt
+++ b/test/nutrition_beta_keys.txt
@@ -105,3 +105,5 @@ waterDailyGoal
waterNone
waterOptions
weightLastLine
+widgetNutritionOff
+widgetPickShake