diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 5cd3e00..dc808a8 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -15,6 +15,78 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="false"
android:theme="@style/Theme.Remaining">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
= dao.getEnabledAccounts()
+ suspend fun getAccountSummaries(): List {
+ val snapshots = dao.getLatestSnapshots().associateBy { it.accountId }
+ return dao.getAccounts().map { account -> account.toSummary(snapshots[account.id]) }
+ }
+
@OptIn(ExperimentalCoroutinesApi::class)
fun observeAccountDetail(accountId: String): Flow {
val summaryFlow = combine(
diff --git a/app/src/main/java/net/rodakot/remaining/data/RemainingDao.kt b/app/src/main/java/net/rodakot/remaining/data/RemainingDao.kt
index ce27bd1..b63754f 100644
--- a/app/src/main/java/net/rodakot/remaining/data/RemainingDao.kt
+++ b/app/src/main/java/net/rodakot/remaining/data/RemainingDao.kt
@@ -12,6 +12,9 @@ interface RemainingDao {
@Query("SELECT * FROM accounts ORDER BY serviceType, displayName")
fun observeAccounts(): Flow>
+ @Query("SELECT * FROM accounts ORDER BY serviceType, displayName")
+ suspend fun getAccounts(): List
+
@Query("SELECT * FROM accounts WHERE id = :accountId")
fun observeAccount(accountId: String): Flow
@@ -94,6 +97,19 @@ interface RemainingDao {
)
fun observeLatestSnapshots(): Flow>
+ @Query(
+ """
+ SELECT * FROM usage_snapshots
+ WHERE capturedAt = (
+ SELECT MAX(innerSnapshot.capturedAt)
+ FROM usage_snapshots AS innerSnapshot
+ WHERE innerSnapshot.accountId = usage_snapshots.accountId
+ )
+ ORDER BY capturedAt DESC
+ """
+ )
+ suspend fun getLatestSnapshots(): List
+
@Query(
"""
SELECT * FROM usage_snapshots
diff --git a/app/src/main/java/net/rodakot/remaining/refresh/AccountRefreshWorker.kt b/app/src/main/java/net/rodakot/remaining/refresh/AccountRefreshWorker.kt
index f4353ce..018c93f 100644
--- a/app/src/main/java/net/rodakot/remaining/refresh/AccountRefreshWorker.kt
+++ b/app/src/main/java/net/rodakot/remaining/refresh/AccountRefreshWorker.kt
@@ -4,6 +4,7 @@ import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import net.rodakot.remaining.RemainingApplication
+import net.rodakot.remaining.widget.RemainingWidgetUpdater
class AccountRefreshWorker(
appContext: Context,
@@ -16,6 +17,7 @@ class AccountRefreshWorker(
accountId = accountId,
notify = true
)
+ RemainingWidgetUpdater.updateAll(applicationContext)
return when {
result.success -> Result.success()
result.retryable -> Result.retry()
diff --git a/app/src/main/java/net/rodakot/remaining/ui/RemainingApp.kt b/app/src/main/java/net/rodakot/remaining/ui/RemainingApp.kt
index 58c4249..1d44b91 100644
--- a/app/src/main/java/net/rodakot/remaining/ui/RemainingApp.kt
+++ b/app/src/main/java/net/rodakot/remaining/ui/RemainingApp.kt
@@ -35,6 +35,7 @@ import net.rodakot.remaining.ui.screens.AccountDetailScreen
import net.rodakot.remaining.ui.screens.AddAccountScreen
import net.rodakot.remaining.ui.screens.DashboardScreen
import net.rodakot.remaining.ui.screens.SettingsScreen
+import net.rodakot.remaining.ui.screens.WidgetGalleryScreen
@Composable
fun RemainingApp(
@@ -99,6 +100,7 @@ fun RemainingApp(
SettingsScreen(
settings = state.settings,
onBack = { navController.popBackStack() },
+ onOpenWidgets = { navController.navigate(Route.Widgets) },
onThemeChanged = viewModel::updateTheme,
onNotificationsChanged = viewModel::updateNotifications,
onDefaultRefreshChanged = { interval: RefreshInterval ->
@@ -106,6 +108,12 @@ fun RemainingApp(
}
)
}
+ composable(Route.Widgets) {
+ WidgetGalleryScreen(
+ accounts = state.accounts,
+ onBack = { navController.popBackStack() }
+ )
+ }
}
}
@@ -160,6 +168,7 @@ private object Route {
const val Dashboard = "dashboard"
const val AddAccount = "add_account"
const val Settings = "settings"
+ const val Widgets = "widgets"
const val AccountId = "accountId"
const val Detail = "detail/{$AccountId}"
diff --git a/app/src/main/java/net/rodakot/remaining/ui/RemainingViewModel.kt b/app/src/main/java/net/rodakot/remaining/ui/RemainingViewModel.kt
index 2b4f2d2..09172fe 100644
--- a/app/src/main/java/net/rodakot/remaining/ui/RemainingViewModel.kt
+++ b/app/src/main/java/net/rodakot/remaining/ui/RemainingViewModel.kt
@@ -19,6 +19,7 @@ import net.rodakot.remaining.domain.RefreshException
import net.rodakot.remaining.domain.RefreshInterval
import net.rodakot.remaining.domain.ServiceType
import net.rodakot.remaining.domain.ThemePreference
+import net.rodakot.remaining.widget.RemainingWidgetUpdater
data class CaptchaUiState(
val accountId: String,
@@ -68,6 +69,7 @@ class RemainingViewModel(
if (request.serviceType != ServiceType.TCI) {
container.accountRepository.refreshAccount(account.id, notify = false)
}
+ RemainingWidgetUpdater.updateAll(container.appContext)
"Account added."
}.onSuccess(::showMessage)
.onFailure { showMessage(it.userMessage()) }
@@ -79,6 +81,7 @@ class RemainingViewModel(
viewModelScope.launch {
setAccountBusy(accountId, true)
val result = container.accountRepository.refreshAccount(accountId, notify = false)
+ RemainingWidgetUpdater.updateAll(container.appContext)
showMessage(result.message ?: if (result.success) "Account refreshed." else "Refresh failed.")
setAccountBusy(accountId, false)
}
@@ -93,6 +96,7 @@ class RemainingViewModel(
captcha = CaptchaUiState(accountId, challenge.imageBytes),
message = null
)
+ RemainingWidgetUpdater.updateAll(container.appContext)
}.onFailure { showMessage(it.userMessage()) }
setAccountBusy(accountId, false)
}
@@ -112,6 +116,7 @@ class RemainingViewModel(
captcha = captcha.captchaText.trim(),
notify = false
)
+ RemainingWidgetUpdater.updateAll(container.appContext)
actionState.value = actionState.value.copy(captcha = null)
showMessage(result.message ?: if (result.success) "TCI account signed in." else "Captcha failed.")
setAccountBusy(captcha.accountId, false)
@@ -146,6 +151,7 @@ class RemainingViewModel(
} else {
container.refreshScheduler.cancel(account.id)
}
+ RemainingWidgetUpdater.updateAll(container.appContext)
showMessage("Account settings updated.")
}
}
@@ -154,6 +160,7 @@ class RemainingViewModel(
viewModelScope.launch {
container.refreshScheduler.cancel(accountId)
container.accountRepository.deleteAccount(accountId)
+ RemainingWidgetUpdater.updateAll(container.appContext)
showMessage("Account deleted.")
}
}
diff --git a/app/src/main/java/net/rodakot/remaining/ui/screens/SettingsScreen.kt b/app/src/main/java/net/rodakot/remaining/ui/screens/SettingsScreen.kt
index 71689af..cb14a5b 100644
--- a/app/src/main/java/net/rodakot/remaining/ui/screens/SettingsScreen.kt
+++ b/app/src/main/java/net/rodakot/remaining/ui/screens/SettingsScreen.kt
@@ -12,6 +12,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
+import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
@@ -40,6 +41,7 @@ import net.rodakot.remaining.ui.components.SectionHeader
fun SettingsScreen(
settings: AppSettings,
onBack: () -> Unit,
+ onOpenWidgets: () -> Unit,
onThemeChanged: (ThemePreference) -> Unit,
onNotificationsChanged: (Boolean) -> Unit,
onDefaultRefreshChanged: (RefreshInterval) -> Unit
@@ -79,6 +81,16 @@ fun SettingsScreen(
.padding(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 24.dp),
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
+ ModernPanel {
+ SectionHeader(
+ title = "Home widgets",
+ subtitle = "Add chart-first widgets for quota, risk, provider mix, and refresh timing."
+ )
+ Button(onClick = onOpenWidgets, modifier = Modifier.fillMaxWidth()) {
+ Text("Open widget gallery")
+ }
+ }
+
ModernPanel {
SectionHeader(
title = "Appearance",
diff --git a/app/src/main/java/net/rodakot/remaining/ui/screens/WidgetGalleryScreen.kt b/app/src/main/java/net/rodakot/remaining/ui/screens/WidgetGalleryScreen.kt
new file mode 100644
index 0000000..eb75a23
--- /dev/null
+++ b/app/src/main/java/net/rodakot/remaining/ui/screens/WidgetGalleryScreen.kt
@@ -0,0 +1,175 @@
+package net.rodakot.remaining.ui.screens
+
+import android.appwidget.AppWidgetManager
+import android.os.Build
+import androidx.compose.foundation.Image
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.automirrored.filled.ArrowBack
+import androidx.compose.material3.Button
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.Surface
+import androidx.compose.material3.Text
+import androidx.compose.material3.TopAppBar
+import androidx.compose.material3.TopAppBarDefaults
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import net.rodakot.remaining.data.AccountSummary
+import net.rodakot.remaining.ui.components.ModernPanel
+import net.rodakot.remaining.ui.components.RemainingBackground
+import net.rodakot.remaining.ui.components.SectionHeader
+import net.rodakot.remaining.widget.RemainingWidgetRenderer
+import net.rodakot.remaining.widget.RemainingWidgetStats
+import net.rodakot.remaining.widget.RemainingWidgetType
+
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun WidgetGalleryScreen(
+ accounts: List,
+ onBack: () -> Unit
+) {
+ val context = LocalContext.current
+ val canPin = remember {
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
+ AppWidgetManager.getInstance(context).isRequestPinAppWidgetSupported
+ }
+
+ RemainingBackground {
+ Scaffold(
+ containerColor = Color.Transparent,
+ topBar = {
+ TopAppBar(
+ colors = TopAppBarDefaults.topAppBarColors(
+ containerColor = Color.Transparent,
+ scrolledContainerColor = Color.Transparent
+ ),
+ title = {
+ Column {
+ Text("Widget Gallery", fontWeight = FontWeight.Bold)
+ Text(
+ "Pick a chart for your home screen",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ },
+ navigationIcon = {
+ IconButton(onClick = onBack) {
+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
+ }
+ }
+ )
+ }
+ ) { padding ->
+ LazyColumn(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(padding),
+ contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 24.dp),
+ verticalArrangement = Arrangement.spacedBy(14.dp)
+ ) {
+ item {
+ ModernPanel {
+ SectionHeader(
+ title = "Designed for decisions",
+ subtitle = "These widgets use charts, heatmaps, timelines, and provider statistics. They update from your saved account snapshots and open the app when tapped."
+ )
+ if (!canPin) {
+ Text(
+ "Your launcher does not support one-tap widget pinning. Long-press the home screen, choose Widgets, then select Remaining.",
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ style = MaterialTheme.typography.bodySmall
+ )
+ }
+ }
+ }
+ items(RemainingWidgetType.entries, key = { it.name }) { type ->
+ WidgetPreviewCard(
+ type = type,
+ accounts = accounts,
+ canPin = canPin,
+ onPin = {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ AppWidgetManager.getInstance(context).requestPinAppWidget(
+ type.componentName(context),
+ null,
+ null
+ )
+ }
+ }
+ )
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun WidgetPreviewCard(
+ type: RemainingWidgetType,
+ accounts: List,
+ canPin: Boolean,
+ onPin: () -> Unit
+) {
+ val context = LocalContext.current
+ val data = remember(accounts) { RemainingWidgetStats.fromSummaries(accounts) }
+ val preview = remember(type, data) {
+ RemainingWidgetRenderer.render(context, type, data, densityOverride = 1.15f)
+ }
+ ModernPanel {
+ SectionHeader(title = type.title, subtitle = type.subtitle)
+ Image(
+ bitmap = preview.asImageBitmap(),
+ contentDescription = "${type.title} preview",
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(previewHeight(type))
+ )
+ Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
+ Button(
+ onClick = onPin,
+ enabled = canPin,
+ modifier = Modifier.weight(1f)
+ ) {
+ Text("Add to Home screen")
+ }
+ Surface(
+ shape = RoundedCornerShape(8.dp)
+ ) {
+ Text(
+ "${type.widthDp} x ${type.heightDp} dp",
+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
+ style = MaterialTheme.typography.labelMedium
+ )
+ }
+ }
+ }
+}
+
+private fun previewHeight(type: RemainingWidgetType) =
+ when (type) {
+ RemainingWidgetType.COMPACT_SIGNAL -> 118.dp
+ RemainingWidgetType.WATCHLIST,
+ RemainingWidgetType.ACCOUNT_MATRIX -> 184.dp
+ else -> 156.dp
+ }
diff --git a/app/src/main/java/net/rodakot/remaining/widget/RemainingWidgetProvider.kt b/app/src/main/java/net/rodakot/remaining/widget/RemainingWidgetProvider.kt
new file mode 100644
index 0000000..16efed4
--- /dev/null
+++ b/app/src/main/java/net/rodakot/remaining/widget/RemainingWidgetProvider.kt
@@ -0,0 +1,117 @@
+package net.rodakot.remaining.widget
+
+import android.app.PendingIntent
+import android.appwidget.AppWidgetManager
+import android.appwidget.AppWidgetProvider
+import android.content.Context
+import android.content.Intent
+import android.view.View
+import android.widget.RemoteViews
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import net.rodakot.remaining.MainActivity
+import net.rodakot.remaining.R
+import net.rodakot.remaining.RemainingApplication
+
+abstract class BaseRemainingWidgetProvider(
+ private val type: RemainingWidgetType
+) : AppWidgetProvider() {
+ override fun onUpdate(
+ context: Context,
+ appWidgetManager: AppWidgetManager,
+ appWidgetIds: IntArray
+ ) {
+ val pendingResult = goAsync()
+ RemainingWidgetUpdater.update(
+ context = context,
+ appWidgetManager = appWidgetManager,
+ appWidgetIds = appWidgetIds,
+ type = type,
+ onFinished = pendingResult::finish
+ )
+ }
+
+ override fun onAppWidgetOptionsChanged(
+ context: Context,
+ appWidgetManager: AppWidgetManager,
+ appWidgetId: Int,
+ newOptions: android.os.Bundle
+ ) {
+ onUpdate(context, appWidgetManager, intArrayOf(appWidgetId))
+ }
+}
+
+class CommandCenterWidgetProvider : BaseRemainingWidgetProvider(RemainingWidgetType.COMMAND_CENTER)
+class ProviderMixWidgetProvider : BaseRemainingWidgetProvider(RemainingWidgetType.PROVIDER_MIX)
+class WatchlistWidgetProvider : BaseRemainingWidgetProvider(RemainingWidgetType.WATCHLIST)
+class RefreshTimelineWidgetProvider : BaseRemainingWidgetProvider(RemainingWidgetType.REFRESH_TIMELINE)
+class AccountMatrixWidgetProvider : BaseRemainingWidgetProvider(RemainingWidgetType.ACCOUNT_MATRIX)
+class CompactSignalWidgetProvider : BaseRemainingWidgetProvider(RemainingWidgetType.COMPACT_SIGNAL)
+
+object RemainingWidgetUpdater {
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ fun updateAll(context: Context) {
+ val appWidgetManager = AppWidgetManager.getInstance(context)
+ RemainingWidgetType.entries.forEach { type ->
+ val ids = appWidgetManager.getAppWidgetIds(type.componentName(context))
+ if (ids.isNotEmpty()) {
+ update(context, appWidgetManager, ids, type)
+ }
+ }
+ }
+
+ fun update(
+ context: Context,
+ appWidgetManager: AppWidgetManager,
+ appWidgetIds: IntArray,
+ type: RemainingWidgetType,
+ onFinished: (() -> Unit)? = null
+ ) {
+ scope.launch {
+ runCatching {
+ val data = loadData(context)
+ val bitmap = RemainingWidgetRenderer.render(context, type, data, densityOverride = 1.6f)
+ appWidgetIds.forEach { widgetId ->
+ val views = RemoteViews(context.packageName, R.layout.remaining_widget_chart)
+ views.setViewVisibility(R.id.remaining_widget_image, View.VISIBLE)
+ views.setViewVisibility(R.id.remaining_widget_fallback, View.GONE)
+ views.setImageViewBitmap(R.id.remaining_widget_image, bitmap)
+ views.setContentDescription(R.id.remaining_widget_image, "${type.title}: ${data.focusTitle}")
+ views.setOnClickPendingIntent(R.id.remaining_widget_root, openAppIntent(context, widgetId))
+ appWidgetManager.updateAppWidget(widgetId, views)
+ }
+ }.onFailure {
+ appWidgetIds.forEach { widgetId ->
+ val views = RemoteViews(context.packageName, R.layout.remaining_widget_chart)
+ views.setViewVisibility(R.id.remaining_widget_image, View.GONE)
+ views.setViewVisibility(R.id.remaining_widget_fallback, View.VISIBLE)
+ views.setTextViewText(R.id.remaining_widget_fallback, "Open Remaining")
+ views.setOnClickPendingIntent(R.id.remaining_widget_root, openAppIntent(context, widgetId))
+ appWidgetManager.updateAppWidget(widgetId, views)
+ }
+ }
+ onFinished?.invoke()
+ }
+ }
+
+ private suspend fun loadData(context: Context): WidgetDashboardData {
+ val application = context.applicationContext as RemainingApplication
+ val summaries = application.container.accountRepository.getAccountSummaries()
+ return RemainingWidgetStats.fromSummaries(summaries)
+ }
+
+ private fun openAppIntent(context: Context, requestCode: Int): PendingIntent {
+ val intent = Intent(context, MainActivity::class.java).apply {
+ flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
+ }
+ return PendingIntent.getActivity(
+ context,
+ requestCode,
+ intent,
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
+ )
+ }
+}
diff --git a/app/src/main/java/net/rodakot/remaining/widget/RemainingWidgetRenderer.kt b/app/src/main/java/net/rodakot/remaining/widget/RemainingWidgetRenderer.kt
new file mode 100644
index 0000000..cf56746
--- /dev/null
+++ b/app/src/main/java/net/rodakot/remaining/widget/RemainingWidgetRenderer.kt
@@ -0,0 +1,431 @@
+package net.rodakot.remaining.widget
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.Color
+import android.graphics.LinearGradient
+import android.graphics.Paint
+import android.graphics.RectF
+import android.graphics.Shader
+import android.graphics.SweepGradient
+import android.graphics.Typeface
+import net.rodakot.remaining.domain.AccountStatus
+import net.rodakot.remaining.domain.ServiceType
+import java.text.DateFormat
+import java.util.Date
+import java.util.Locale
+import kotlin.math.PI
+import kotlin.math.cos
+import kotlin.math.max
+import kotlin.math.min
+import kotlin.math.sin
+
+object RemainingWidgetRenderer {
+ fun render(
+ context: Context,
+ type: RemainingWidgetType,
+ data: WidgetDashboardData,
+ densityOverride: Float? = null
+ ): Bitmap {
+ val density = densityOverride ?: context.resources.displayMetrics.density
+ val bitmap = Bitmap.createBitmap(
+ (type.widthDp * density).toInt(),
+ (type.heightDp * density).toInt(),
+ Bitmap.Config.ARGB_8888
+ )
+ WidgetCanvas(Canvas(bitmap), bitmap.width.toFloat(), bitmap.height.toFloat(), density, data)
+ .draw(type)
+ return bitmap
+ }
+}
+
+private class WidgetCanvas(
+ private val canvas: Canvas,
+ private val width: Float,
+ private val height: Float,
+ private val density: Float,
+ private val data: WidgetDashboardData
+) {
+ private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ color = TEXT
+ typeface = Typeface.create("sans-serif", Typeface.NORMAL)
+ }
+ private val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG)
+ private val strokePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ strokeCap = Paint.Cap.ROUND
+ }
+ private val r = 18f.dp
+ private val pad = 18f.dp
+
+ fun draw(type: RemainingWidgetType) {
+ drawBackground()
+ if (!data.hasAccounts) {
+ drawEmpty(type)
+ return
+ }
+ when (type) {
+ RemainingWidgetType.COMMAND_CENTER -> drawCommandCenter()
+ RemainingWidgetType.PROVIDER_MIX -> drawProviderMix()
+ RemainingWidgetType.WATCHLIST -> drawWatchlist()
+ RemainingWidgetType.REFRESH_TIMELINE -> drawTimeline()
+ RemainingWidgetType.ACCOUNT_MATRIX -> drawAccountMatrix()
+ RemainingWidgetType.COMPACT_SIGNAL -> drawCompact()
+ }
+ }
+
+ private fun drawBackground() {
+ fillPaint.shader = LinearGradient(
+ 0f,
+ 0f,
+ width,
+ height,
+ intArrayOf(Color.rgb(5, 32, 27), Color.rgb(9, 21, 18), Color.rgb(8, 18, 25)),
+ floatArrayOf(0f, 0.58f, 1f),
+ Shader.TileMode.CLAMP
+ )
+ canvas.drawRoundRect(RectF(0f, 0f, width, height), r, r, fillPaint)
+ fillPaint.shader = LinearGradient(
+ 0f,
+ height,
+ width,
+ 0f,
+ Color.argb(70, 152, 247, 199),
+ Color.TRANSPARENT,
+ Shader.TileMode.CLAMP
+ )
+ canvas.drawRoundRect(RectF(1.5f.dp, 1.5f.dp, width - 1.5f.dp, height - 1.5f.dp), r, r, fillPaint)
+ fillPaint.shader = null
+ strokePaint.color = Color.argb(95, 142, 235, 255)
+ strokePaint.strokeWidth = 1.2f.dp
+ canvas.drawRoundRect(RectF(1.2f.dp, 1.2f.dp, width - 1.2f.dp, height - 1.2f.dp), r, r, strokePaint)
+ }
+
+ private fun drawEmpty(type: RemainingWidgetType) {
+ title(type.title, "Add accounts, refresh them, then this widget becomes a live chart.")
+ drawRing(
+ cx = width - 78f.dp,
+ cy = height / 2f + 6f.dp,
+ radius = min(58f.dp, height * 0.34f),
+ progress = 0.64f,
+ value = "Ready",
+ label = "widgets"
+ )
+ drawPill(
+ RectF(pad, height - 46f.dp, width - pad, height - 16f.dp),
+ "Open Remaining to connect your first account",
+ PRIMARY
+ )
+ }
+
+ private fun drawCommandCenter() {
+ title("Command Center", "Updated ${data.generatedAt.shortTime()}")
+ text(data.focusTitle, pad, 76f.dp, 23f, TEXT, Typeface.BOLD)
+ wrapped(data.focusDetail, pad, 103f.dp, width * 0.52f, 12.5f, MUTED, 2)
+ drawRing(
+ cx = width - 78f.dp,
+ cy = 82f.dp,
+ radius = 57f.dp,
+ progress = data.quotaProgress,
+ value = data.quotaPercentLabel,
+ label = "available"
+ )
+ drawBar(
+ x = pad,
+ y = height - 67f.dp,
+ w = width - pad * 2f,
+ h = 9f.dp,
+ progress = data.quotaProgress ?: 0f,
+ color = PRIMARY
+ )
+ statBox(pad, height - 44f.dp, (width - pad * 2f - 8f.dp) / 2f, "Tracked left", data.totalRemainingLabel)
+ statBox(width / 2f + 4f.dp, height - 44f.dp, (width - pad * 2f - 8f.dp) / 2f, "Ratio data", data.quotaCoverageLabel)
+ }
+
+ private fun drawProviderMix() {
+ title("Provider Mix", "Quota share and service issues")
+ var x = pad
+ val y = 64f.dp
+ val barW = width - pad * 2f
+ val barH = 18f.dp
+ data.providers.forEach { provider ->
+ val segment = barW * provider.share
+ fillPaint.color = provider.serviceType.widgetColor()
+ canvas.drawRoundRect(RectF(x, y, min(x + segment, pad + barW), y + barH), 8f.dp, 8f.dp, fillPaint)
+ x += segment
+ }
+ strokePaint.color = Color.argb(70, 255, 255, 255)
+ strokePaint.strokeWidth = 1f.dp
+ canvas.drawRoundRect(RectF(pad, y, pad + barW, y + barH), 8f.dp, 8f.dp, strokePaint)
+ var rowY = 102f.dp
+ data.providers.take(3).forEach { provider ->
+ val color = provider.serviceType.widgetColor()
+ fillPaint.color = Color.argb(42, Color.red(color), Color.green(color), Color.blue(color))
+ canvas.drawRoundRect(RectF(pad, rowY - 14f.dp, width - pad, rowY + 24f.dp), 10f.dp, 10f.dp, fillPaint)
+ drawDot(pad + 12f.dp, rowY + 3f.dp, 6f.dp, color)
+ text(provider.serviceType.shortName, pad + 28f.dp, rowY + 7f.dp, 14f, TEXT, Typeface.BOLD)
+ text(provider.remainingLabel, pad + 90f.dp, rowY + 7f.dp, 14f, TEXT, Typeface.BOLD)
+ val issue = if (provider.issueCount == 0) "healthy" else "${provider.issueCount} issue"
+ text(issue, width - pad - 68f.dp, rowY + 7f.dp, 12f, if (provider.issueCount == 0) PRIMARY else ERROR, Typeface.BOLD)
+ rowY += 45f.dp
+ }
+ }
+
+ private fun drawWatchlist() {
+ title("Watchlist Heatmap", "Risk signals across every account")
+ val metrics = listOf(
+ "Action" to data.health.needsAction,
+ "Low" to data.health.lowData,
+ "Expiry" to data.health.expiringSoon,
+ "Stale" to data.health.stale,
+ "Off" to data.health.disabled
+ )
+ val cellW = (width - pad * 2f - 12f.dp * 4f) / 5f
+ metrics.forEachIndexed { index, metric ->
+ val x = pad + index * (cellW + 12f.dp)
+ val intensity = (metric.second / max(1f, data.accounts.size.toFloat())).coerceIn(0f, 1f)
+ val color = heatColor(intensity)
+ fillPaint.color = Color.argb(45 + (intensity * 120).toInt(), Color.red(color), Color.green(color), Color.blue(color))
+ canvas.drawRoundRect(RectF(x, 58f.dp, x + cellW, 112f.dp), 10f.dp, 10f.dp, fillPaint)
+ text(metric.second.toString(), x + 10f.dp, 83f.dp, 20f, TEXT, Typeface.BOLD)
+ text(metric.first, x + 10f.dp, 103f.dp, 10f, MUTED, Typeface.BOLD)
+ }
+ var y = 147f.dp
+ data.topWatch.take(3).forEach { account ->
+ accountRiskRow(account, y)
+ y += 28f.dp
+ }
+ }
+
+ private fun drawTimeline() {
+ title("Refresh Timeline", data.nextRefreshLabel)
+ val accounts = data.accounts.take(4)
+ val topY = 68f.dp
+ val lineX = pad + 6f.dp
+ strokePaint.color = Color.argb(70, 142, 235, 255)
+ strokePaint.strokeWidth = 2f.dp
+ canvas.drawLine(lineX, topY - 8f.dp, lineX, height - 26f.dp, strokePaint)
+ accounts.forEachIndexed { index, account ->
+ val y = topY + index * 30f.dp
+ drawDot(lineX, y, 5f.dp, account.serviceType.widgetColor())
+ text(account.name, lineX + 17f.dp, y + 4f.dp, 13f, TEXT, Typeface.BOLD)
+ text(account.nextRefreshAt?.shortTime() ?: "No schedule", width - pad - 82f.dp, y + 4f.dp, 12f, MUTED, Typeface.BOLD)
+ drawBar(
+ x = lineX + 17f.dp,
+ y = y + 12f.dp,
+ w = width - pad * 2f - 34f.dp,
+ h = 5f.dp,
+ progress = account.progress ?: 0.18f,
+ color = account.serviceType.widgetColor()
+ )
+ }
+ }
+
+ private fun drawAccountMatrix() {
+ title("Account Matrix", "Quota, service, status, and risk")
+ val rowTop = 58f.dp
+ val rows = data.accounts.take(5)
+ rows.forEachIndexed { index, account ->
+ val y = rowTop + index * 31f.dp
+ text(account.name.take(16), pad, y + 9f.dp, 13f, TEXT, Typeface.BOLD)
+ drawBar(
+ x = pad + 132f.dp,
+ y = y,
+ w = width - pad * 2f - 188f.dp,
+ h = 10f.dp,
+ progress = account.progress ?: 0.10f,
+ color = account.serviceType.widgetColor()
+ )
+ drawRiskCell(width - pad - 44f.dp, y - 4f.dp, account.riskScore)
+ }
+ text("Risk", width - pad - 47f.dp, height - 18f.dp, 10f, MUTED, Typeface.BOLD)
+ }
+
+ private fun drawCompact() {
+ text("Remaining", pad, 30f.dp, 16f, TEXT, Typeface.BOLD)
+ text(data.focusTitle, pad, 52f.dp, 13f, MUTED, Typeface.BOLD)
+ drawRing(width - 52f.dp, 50f.dp, 35f.dp, data.quotaProgress, data.quotaPercentLabel, "")
+ val chartX = pad
+ val chartY = height - 35f.dp
+ val barW = (width - pad * 2f) / max(1, data.accounts.take(8).size)
+ data.accounts.take(8).forEachIndexed { index, account ->
+ val progress = account.progress ?: (0.15f + index * 0.05f).coerceAtMost(0.8f)
+ val h = progress * 30f.dp
+ fillPaint.color = account.serviceType.widgetColor()
+ canvas.drawRoundRect(
+ RectF(chartX + index * barW + 2f.dp, chartY + 30f.dp - h, chartX + (index + 1) * barW - 2f.dp, chartY + 30f.dp),
+ 4f.dp,
+ 4f.dp,
+ fillPaint
+ )
+ }
+ }
+
+ private fun title(title: String, subtitle: String) {
+ text(title, pad, 31f.dp, 17f, TEXT, Typeface.BOLD)
+ text(subtitle, pad, 51f.dp, 11f, MUTED, Typeface.NORMAL)
+ }
+
+ private fun statBox(x: Float, y: Float, w: Float, label: String, value: String) {
+ fillPaint.color = Color.argb(70, 20, 38, 34)
+ canvas.drawRoundRect(RectF(x, y, x + w, y + 36f.dp), 10f.dp, 10f.dp, fillPaint)
+ strokePaint.color = Color.argb(38, 255, 255, 255)
+ strokePaint.strokeWidth = 1f.dp
+ canvas.drawRoundRect(RectF(x, y, x + w, y + 36f.dp), 10f.dp, 10f.dp, strokePaint)
+ text(label, x + 10f.dp, y + 15f.dp, 10f, MUTED, Typeface.BOLD)
+ text(value, x + 10f.dp, y + 29f.dp, 13f, TEXT, Typeface.BOLD)
+ }
+
+ private fun accountRiskRow(account: WidgetAccount, y: Float) {
+ val color = riskColor(account.riskScore)
+ fillPaint.color = Color.argb(34, Color.red(color), Color.green(color), Color.blue(color))
+ canvas.drawRoundRect(RectF(pad, y - 15f.dp, width - pad, y + 11f.dp), 8f.dp, 8f.dp, fillPaint)
+ drawDot(pad + 12f.dp, y - 2f.dp, 5f.dp, color)
+ text(account.name, pad + 26f.dp, y + 3f.dp, 12f, TEXT, Typeface.BOLD)
+ text(account.riskLabel, width - pad - 100f.dp, y + 3f.dp, 11f, color, Typeface.BOLD)
+ }
+
+ private fun drawRiskCell(x: Float, y: Float, risk: Int) {
+ val color = riskColor(risk)
+ fillPaint.color = Color.argb(50, Color.red(color), Color.green(color), Color.blue(color))
+ canvas.drawRoundRect(RectF(x, y, x + 44f.dp, y + 22f.dp), 8f.dp, 8f.dp, fillPaint)
+ text(if (risk == 0) "OK" else risk.toString(), x + 11f.dp, y + 15f.dp, 11f, color, Typeface.BOLD)
+ }
+
+ private fun drawRing(
+ cx: Float,
+ cy: Float,
+ radius: Float,
+ progress: Float?,
+ value: String,
+ label: String
+ ) {
+ val stroke = max(8f.dp, radius * 0.17f)
+ strokePaint.shader = null
+ strokePaint.color = Color.argb(45, 255, 255, 255)
+ strokePaint.strokeWidth = stroke
+ canvas.drawArc(RectF(cx - radius, cy - radius, cx + radius, cy + radius), 135f, 270f, false, strokePaint)
+ strokePaint.shader = SweepGradient(cx, cy, intArrayOf(PRIMARY, CYAN, PRIMARY), null)
+ strokePaint.strokeWidth = stroke
+ canvas.drawArc(
+ RectF(cx - radius, cy - radius, cx + radius, cy + radius),
+ 135f,
+ 270f * (progress ?: 0.62f),
+ false,
+ strokePaint
+ )
+ strokePaint.shader = null
+ text(value, cx, cy + 4f.dp, if (radius < 42f.dp) 13f else 20f, TEXT, Typeface.BOLD, Paint.Align.CENTER)
+ if (label.isNotBlank()) {
+ text(label, cx, cy + 22f.dp, 10f, MUTED, Typeface.BOLD, Paint.Align.CENTER)
+ }
+ }
+
+ private fun drawBar(x: Float, y: Float, w: Float, h: Float, progress: Float, color: Int) {
+ fillPaint.shader = null
+ fillPaint.color = Color.argb(42, 255, 255, 255)
+ canvas.drawRoundRect(RectF(x, y, x + w, y + h), h / 2f, h / 2f, fillPaint)
+ val fillW = (w * progress.coerceIn(0.04f, 1f))
+ fillPaint.shader = LinearGradient(x, y, x + fillW, y, color, CYAN, Shader.TileMode.CLAMP)
+ canvas.drawRoundRect(RectF(x, y, x + fillW, y + h), h / 2f, h / 2f, fillPaint)
+ fillPaint.shader = null
+ }
+
+ private fun drawPill(rect: RectF, label: String, color: Int) {
+ fillPaint.color = color
+ canvas.drawRoundRect(rect, rect.height() / 2f, rect.height() / 2f, fillPaint)
+ text(label, rect.centerX(), rect.centerY() + 4f.dp, 12f, Color.rgb(3, 45, 32), Typeface.BOLD, Paint.Align.CENTER)
+ }
+
+ private fun drawDot(cx: Float, cy: Float, radius: Float, color: Int) {
+ fillPaint.color = color
+ canvas.drawCircle(cx, cy, radius, fillPaint)
+ }
+
+ private fun wrapped(
+ value: String,
+ x: Float,
+ y: Float,
+ maxWidth: Float,
+ size: Float,
+ color: Int,
+ maxLines: Int
+ ) {
+ textPaint.textSize = size.dp
+ textPaint.color = color
+ textPaint.typeface = Typeface.create("sans-serif", Typeface.NORMAL)
+ var line = ""
+ var baseline = y
+ var lines = 0
+ value.split(" ").forEach { word ->
+ val candidate = if (line.isBlank()) word else "$line $word"
+ if (textPaint.measureText(candidate) > maxWidth && line.isNotBlank()) {
+ canvas.drawText(line, x, baseline, textPaint)
+ baseline += size.dp * 1.24f
+ lines++
+ line = word
+ if (lines == maxLines - 1) return@forEach
+ } else {
+ line = candidate
+ }
+ }
+ if (line.isNotBlank() && lines < maxLines) {
+ canvas.drawText(line, x, baseline, textPaint)
+ }
+ }
+
+ private fun text(
+ value: String,
+ x: Float,
+ y: Float,
+ size: Float,
+ color: Int,
+ style: Int,
+ align: Paint.Align = Paint.Align.LEFT
+ ) {
+ textPaint.shader = null
+ textPaint.color = color
+ textPaint.textSize = size.dp
+ textPaint.textAlign = align
+ textPaint.typeface = Typeface.create("sans-serif", style)
+ canvas.drawText(value, x, y, textPaint)
+ }
+
+ private val Float.dp: Float
+ get() = this * density
+
+ private fun Long.shortTime(): String =
+ DateFormat.getTimeInstance(DateFormat.SHORT, Locale.US).format(Date(this))
+
+ private fun ServiceType.widgetColor(): Int =
+ when (this) {
+ ServiceType.MCI -> Color.rgb(0, 174, 205)
+ ServiceType.JAHAN_NAMA -> Color.rgb(124, 92, 255)
+ ServiceType.TCI -> Color.rgb(0, 168, 107)
+ }
+
+ private fun riskColor(risk: Int): Int =
+ when {
+ risk >= 75 -> ERROR
+ risk >= 55 -> AMBER
+ risk >= 25 -> CYAN
+ else -> PRIMARY
+ }
+
+ private fun heatColor(value: Float): Int {
+ val angle = value * PI
+ val red = (80 + sin(angle) * 160).toInt().coerceIn(80, 255)
+ val green = (230 - value * 80).toInt().coerceIn(130, 230)
+ return Color.rgb(red, green, 120)
+ }
+
+ companion object {
+ private val TEXT = Color.rgb(231, 244, 236)
+ private val MUTED = Color.rgb(178, 201, 192)
+ private val PRIMARY = Color.rgb(142, 245, 195)
+ private val CYAN = Color.rgb(126, 232, 246)
+ private val AMBER = Color.rgb(255, 209, 102)
+ private val ERROR = Color.rgb(255, 107, 122)
+ }
+}
diff --git a/app/src/main/java/net/rodakot/remaining/widget/RemainingWidgetStats.kt b/app/src/main/java/net/rodakot/remaining/widget/RemainingWidgetStats.kt
new file mode 100644
index 0000000..02e6ee8
--- /dev/null
+++ b/app/src/main/java/net/rodakot/remaining/widget/RemainingWidgetStats.kt
@@ -0,0 +1,217 @@
+package net.rodakot.remaining.widget
+
+import net.rodakot.remaining.data.AccountSummary
+import net.rodakot.remaining.domain.AccountStatus
+import net.rodakot.remaining.domain.ServiceType
+import net.rodakot.remaining.domain.asTrafficDisplay
+import net.rodakot.remaining.ui.components.remainingProgress
+import java.text.DateFormat
+import java.util.Date
+import java.util.Locale
+import kotlin.math.roundToInt
+
+data class WidgetDashboardData(
+ val generatedAt: Long,
+ val accounts: List,
+ val providers: List,
+ val totalRemainingLabel: String,
+ val quotaPercentLabel: String,
+ val quotaProgress: Float?,
+ val quotaCoverageLabel: String,
+ val focusTitle: String,
+ val focusDetail: String,
+ val health: WidgetHealth,
+ val nextRefreshLabel: String
+) {
+ val hasAccounts: Boolean = accounts.isNotEmpty()
+ val topWatch: List = accounts.sortedByDescending { it.riskScore }.take(5)
+}
+
+data class WidgetAccount(
+ val id: String,
+ val name: String,
+ val serviceType: ServiceType,
+ val status: AccountStatus,
+ val enabled: Boolean,
+ val remainingLabel: String,
+ val remainingBytes: Long?,
+ val totalBytes: Long?,
+ val progress: Float?,
+ val riskScore: Int,
+ val riskLabel: String,
+ val lastSuccessAt: Long?,
+ val nextRefreshAt: Long?,
+ val expiresAtText: String?
+)
+
+data class WidgetProviderStat(
+ val serviceType: ServiceType,
+ val accountCount: Int,
+ val issueCount: Int,
+ val remainingLabel: String,
+ val share: Float
+)
+
+data class WidgetHealth(
+ val needsAction: Int,
+ val lowData: Int,
+ val expiringSoon: Int,
+ val stale: Int,
+ val disabled: Int
+)
+
+object RemainingWidgetStats {
+ fun fromSummaries(
+ summaries: List,
+ now: Long = System.currentTimeMillis()
+ ): WidgetDashboardData {
+ val quotaAccounts = summaries.filter {
+ it.remainingBytes != null && it.totalBytes != null && it.totalBytes > 0L
+ }
+ val quotaRemaining = quotaAccounts.mapNotNull { it.remainingBytes }.takeIf { it.isNotEmpty() }?.sum()
+ val quotaTotal = quotaAccounts.mapNotNull { it.totalBytes }.takeIf { it.isNotEmpty() }?.sum()
+ val totalRemaining = summaries.mapNotNull { it.remainingBytes }.takeIf { it.isNotEmpty() }?.sum()
+ val widgetAccounts = summaries.map { it.toWidgetAccount(now) }
+ .sortedWith(compareByDescending { it.riskScore }.thenBy { it.name.lowercase(Locale.US) })
+ val providers = buildProviderStats(summaries, totalRemaining)
+ val health = WidgetHealth(
+ needsAction = summaries.count { it.needsAction() },
+ lowData = summaries.count { it.isLowData() },
+ expiringSoon = summaries.count { it.isExpiringSoon(now) },
+ stale = summaries.count { it.isStale(now) },
+ disabled = summaries.count { !it.enabled }
+ )
+ val focus = buildFocus(widgetAccounts)
+ val nextRefresh = summaries
+ .mapNotNull { account -> account.nextRefreshAt?.let { account to it } }
+ .filter { it.first.enabled }
+ .minByOrNull { it.second }
+
+ val progress = remainingProgress(quotaRemaining, quotaTotal)
+ return WidgetDashboardData(
+ generatedAt = now,
+ accounts = widgetAccounts,
+ providers = providers,
+ totalRemainingLabel = totalRemaining?.asTrafficDisplay() ?: "Waiting",
+ quotaPercentLabel = progress?.let { "${(it * 100f).roundToInt()}%" } ?: "--",
+ quotaProgress = progress,
+ quotaCoverageLabel = "${quotaAccounts.size}/${summaries.size}",
+ focusTitle = focus.first,
+ focusDetail = focus.second,
+ health = health,
+ nextRefreshLabel = nextRefresh?.let {
+ "${it.first.displayName} · ${it.second.shortTime()}"
+ } ?: "No scheduled refresh"
+ )
+ }
+
+ private fun AccountSummary.toWidgetAccount(now: Long): WidgetAccount {
+ val risk = riskScore(now)
+ return WidgetAccount(
+ id = id,
+ name = displayName,
+ serviceType = serviceType,
+ status = status,
+ enabled = enabled,
+ remainingLabel = remainingDisplay,
+ remainingBytes = remainingBytes,
+ totalBytes = totalBytes,
+ progress = remainingProgress(remainingBytes, totalBytes),
+ riskScore = risk,
+ riskLabel = riskLabel(now),
+ lastSuccessAt = lastSuccessAt,
+ nextRefreshAt = nextRefreshAt,
+ expiresAtText = expiresAtText
+ )
+ }
+
+ private fun buildProviderStats(
+ summaries: List,
+ totalRemaining: Long?
+ ): List =
+ ServiceType.entries.mapNotNull { serviceType ->
+ val accounts = summaries.filter { it.serviceType == serviceType }
+ if (accounts.isEmpty()) return@mapNotNull null
+ val remaining = accounts.mapNotNull { it.remainingBytes }.takeIf { it.isNotEmpty() }?.sum()
+ WidgetProviderStat(
+ serviceType = serviceType,
+ accountCount = accounts.size,
+ issueCount = accounts.count { it.needsAction() || !it.enabled },
+ remainingLabel = remaining?.asTrafficDisplay() ?: "No quota",
+ share = if (remaining != null && totalRemaining != null && totalRemaining > 0L) {
+ (remaining.toFloat() / totalRemaining.toFloat()).coerceIn(0.05f, 1f)
+ } else {
+ 0.05f
+ }
+ )
+ }
+
+ private fun buildFocus(accounts: List): Pair {
+ val urgent = accounts.firstOrNull { it.riskScore >= 60 }
+ if (urgent != null) {
+ return urgent.riskLabel to "${urgent.name} · ${urgent.remainingLabel}"
+ }
+ val lowest = accounts.filter { it.remainingBytes != null }.minByOrNull { it.remainingBytes ?: Long.MAX_VALUE }
+ if (lowest != null) {
+ return "Lowest balance" to "${lowest.name} · ${lowest.remainingLabel}"
+ }
+ return "Ready for data" to "Refresh accounts to unlock charts"
+ }
+
+ private fun AccountSummary.riskScore(now: Long): Int =
+ listOf(
+ when (status) {
+ AccountStatus.CAPTCHA_REQUIRED -> 90
+ AccountStatus.ERROR -> 84
+ AccountStatus.NEEDS_AUTH -> 78
+ AccountStatus.REFRESHING -> 20
+ AccountStatus.DISABLED -> 18
+ AccountStatus.ACTIVE -> 0
+ },
+ if (isLowData()) 72 else 0,
+ if (isExpiringSoon(now)) 64 else 0,
+ if (isStale(now)) 48 else 0,
+ if (!enabled) 22 else 0
+ ).max()
+
+ private fun AccountSummary.riskLabel(now: Long): String =
+ when {
+ status == AccountStatus.CAPTCHA_REQUIRED -> "Captcha needed"
+ status == AccountStatus.ERROR -> "Refresh failing"
+ status == AccountStatus.NEEDS_AUTH -> "Sign-in needed"
+ isLowData() -> "Low data"
+ isExpiringSoon(now) -> "Expiring soon"
+ isStale(now) -> "Stale refresh"
+ !enabled -> "Disabled"
+ else -> "Healthy"
+ }
+
+ private fun AccountSummary.needsAction(): Boolean =
+ status == AccountStatus.ERROR ||
+ status == AccountStatus.CAPTCHA_REQUIRED ||
+ status == AccountStatus.NEEDS_AUTH
+
+ private fun AccountSummary.isLowData(): Boolean {
+ val remaining = remainingBytes ?: return false
+ return remaining <= lowDataThresholdMb * BYTES_PER_MB
+ }
+
+ private fun AccountSummary.isExpiringSoon(now: Long): Boolean {
+ val expiry = expiresAtMillis ?: return false
+ return expiry <= now + expiryThresholdDays * MILLIS_PER_DAY
+ }
+
+ private fun AccountSummary.isStale(now: Long): Boolean {
+ if (!enabled || status == AccountStatus.CAPTCHA_REQUIRED) return false
+ val lastSuccess = lastSuccessAt ?: return true
+ val allowedAge = refreshInterval.minutes * MILLIS_PER_MINUTE * 2
+ return now - lastSuccess > allowedAge
+ }
+
+ private fun Long.shortTime(): String =
+ DateFormat.getTimeInstance(DateFormat.SHORT, Locale.US).format(Date(this))
+
+ private const val BYTES_PER_MB = 1024L * 1024L
+ private const val MILLIS_PER_MINUTE = 60_000L
+ private const val MILLIS_PER_DAY = 24L * 60L * 60L * 1000L
+}
diff --git a/app/src/main/java/net/rodakot/remaining/widget/RemainingWidgetType.kt b/app/src/main/java/net/rodakot/remaining/widget/RemainingWidgetType.kt
new file mode 100644
index 0000000..474816a
--- /dev/null
+++ b/app/src/main/java/net/rodakot/remaining/widget/RemainingWidgetType.kt
@@ -0,0 +1,69 @@
+package net.rodakot.remaining.widget
+
+import android.content.ComponentName
+import android.content.Context
+import net.rodakot.remaining.R
+
+enum class RemainingWidgetType(
+ val title: String,
+ val subtitle: String,
+ val widthDp: Int,
+ val heightDp: Int,
+ val providerClass: Class
+) {
+ COMMAND_CENTER(
+ title = "Command Center",
+ subtitle = "Overall quota ring, health counters, and the next best action.",
+ widthDp = 360,
+ heightDp = 190,
+ providerClass = CommandCenterWidgetProvider::class.java
+ ),
+ PROVIDER_MIX(
+ title = "Provider Mix",
+ subtitle = "Provider-level quota share, issue concentration, and service balance.",
+ widthDp = 360,
+ heightDp = 190,
+ providerClass = ProviderMixWidgetProvider::class.java
+ ),
+ WATCHLIST(
+ title = "Watchlist Heatmap",
+ subtitle = "A high-signal risk board for captcha, auth, low data, expiry, and stale refreshes.",
+ widthDp = 360,
+ heightDp = 230,
+ providerClass = WatchlistWidgetProvider::class.java
+ ),
+ REFRESH_TIMELINE(
+ title = "Refresh Timeline",
+ subtitle = "Next refresh rhythm and freshness bars for active accounts.",
+ widthDp = 360,
+ heightDp = 190,
+ providerClass = RefreshTimelineWidgetProvider::class.java
+ ),
+ ACCOUNT_MATRIX(
+ title = "Account Matrix",
+ subtitle = "Account-by-account chart grid for remaining data, status, and risk.",
+ widthDp = 360,
+ heightDp = 230,
+ providerClass = AccountMatrixWidgetProvider::class.java
+ ),
+ COMPACT_SIGNAL(
+ title = "Signal Strip",
+ subtitle = "A compact chart strip for launchers with limited space.",
+ widthDp = 260,
+ heightDp = 120,
+ providerClass = CompactSignalWidgetProvider::class.java
+ );
+
+ fun componentName(context: Context): ComponentName =
+ ComponentName(context, providerClass)
+
+ val appWidgetInfoRes: Int
+ get() = when (this) {
+ COMMAND_CENTER -> R.xml.widget_command_center
+ PROVIDER_MIX -> R.xml.widget_provider_mix
+ WATCHLIST -> R.xml.widget_watchlist
+ REFRESH_TIMELINE -> R.xml.widget_refresh_timeline
+ ACCOUNT_MATRIX -> R.xml.widget_account_matrix
+ COMPACT_SIGNAL -> R.xml.widget_compact_signal
+ }
+}
diff --git a/app/src/main/res/layout/remaining_widget_chart.xml b/app/src/main/res/layout/remaining_widget_chart.xml
new file mode 100644
index 0000000..cdada0d
--- /dev/null
+++ b/app/src/main/res/layout/remaining_widget_chart.xml
@@ -0,0 +1,25 @@
+
+
+
+
+
+
+
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 04a9420..04f46bf 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -1,3 +1,18 @@
Remaining
+ Remaining usage widget
+ Open Remaining
+
+ Remaining Command Center
+ Overall quota ring, health counters, and next action.
+ Remaining Provider Mix
+ Provider-level quota share and service health chart.
+ Remaining Watchlist Heatmap
+ Risk heatmap for captcha, auth, low data, expiry, and stale refreshes.
+ Remaining Refresh Timeline
+ Freshness and next-refresh timeline across active accounts.
+ Remaining Account Matrix
+ Account-by-account quota, status, and risk matrix.
+ Remaining Signal Strip
+ Compact chart strip for small home-screen spaces.
diff --git a/app/src/main/res/xml/widget_account_matrix.xml b/app/src/main/res/xml/widget_account_matrix.xml
new file mode 100644
index 0000000..d08ed97
--- /dev/null
+++ b/app/src/main/res/xml/widget_account_matrix.xml
@@ -0,0 +1,13 @@
+
+
diff --git a/app/src/main/res/xml/widget_command_center.xml b/app/src/main/res/xml/widget_command_center.xml
new file mode 100644
index 0000000..cb181bb
--- /dev/null
+++ b/app/src/main/res/xml/widget_command_center.xml
@@ -0,0 +1,13 @@
+
+
diff --git a/app/src/main/res/xml/widget_compact_signal.xml b/app/src/main/res/xml/widget_compact_signal.xml
new file mode 100644
index 0000000..57e210d
--- /dev/null
+++ b/app/src/main/res/xml/widget_compact_signal.xml
@@ -0,0 +1,13 @@
+
+
diff --git a/app/src/main/res/xml/widget_provider_mix.xml b/app/src/main/res/xml/widget_provider_mix.xml
new file mode 100644
index 0000000..ef897b8
--- /dev/null
+++ b/app/src/main/res/xml/widget_provider_mix.xml
@@ -0,0 +1,13 @@
+
+
diff --git a/app/src/main/res/xml/widget_refresh_timeline.xml b/app/src/main/res/xml/widget_refresh_timeline.xml
new file mode 100644
index 0000000..001e4e9
--- /dev/null
+++ b/app/src/main/res/xml/widget_refresh_timeline.xml
@@ -0,0 +1,13 @@
+
+
diff --git a/app/src/main/res/xml/widget_watchlist.xml b/app/src/main/res/xml/widget_watchlist.xml
new file mode 100644
index 0000000..33fb26a
--- /dev/null
+++ b/app/src/main/res/xml/widget_watchlist.xml
@@ -0,0 +1,13 @@
+
+