add Account Spotlight widget:
This commit is contained in:
12 files changed
+773
No files matched your search
@@ -87,6 +87,27 @@
|
||||
android:resource="@xml/widget_compact_signal" />
|
||||
</receiver>
|
||||
|
||||
<receiver
|
||||
android:name=".widget.AccountSpotlightWidgetProvider"
|
||||
android:exported="true"
|
||||
android:label="@string/widget_account_spotlight_name">
|
||||
<intent-filter>
|
||||
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||
</intent-filter>
|
||||
<meta-data
|
||||
android:name="android.appwidget.provider"
|
||||
android:resource="@xml/widget_account_spotlight" />
|
||||
</receiver>
|
||||
|
||||
<activity
|
||||
android:name=".widget.AccountWidgetConfigureActivity"
|
||||
android:exported="true"
|
||||
android:theme="@style/Theme.Remaining">
|
||||
<intent-filter>
|
||||
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
|
||||
@@ -38,6 +38,12 @@ data class RefreshRunResult(
|
||||
val message: String? = null
|
||||
)
|
||||
|
||||
data class AccountWidgetDetail(
|
||||
val summary: AccountSummary,
|
||||
val snapshots: List<UsageSnapshotEntity>,
|
||||
val packages: List<UsagePackageEntity>
|
||||
)
|
||||
|
||||
class AccountRepository(
|
||||
private val dao: RemainingDao,
|
||||
private val cipher: SecretCipher,
|
||||
@@ -63,6 +69,18 @@ class AccountRepository(
|
||||
return dao.getAccounts().map { account -> account.toSummary(snapshots[account.id]) }
|
||||
}
|
||||
|
||||
suspend fun getAccountWidgetDetail(accountId: String): AccountWidgetDetail? {
|
||||
val account = dao.getAccount(accountId) ?: return null
|
||||
val latestSnapshot = dao.getLatestSnapshot(accountId)
|
||||
val snapshots = dao.getRecentSnapshots(accountId, limit = 8)
|
||||
val packages = latestSnapshot?.let { dao.getPackages(it.id) }.orEmpty()
|
||||
return AccountWidgetDetail(
|
||||
summary = account.toSummary(latestSnapshot),
|
||||
snapshots = snapshots.asReversed(),
|
||||
packages = packages
|
||||
)
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
fun observeAccountDetail(accountId: String): Flow<AccountDetail?> {
|
||||
val summaryFlow = combine(
|
||||
|
||||
@@ -130,9 +130,22 @@ interface RemainingDao {
|
||||
)
|
||||
suspend fun getLatestSnapshot(accountId: String): UsageSnapshotEntity?
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT * FROM usage_snapshots
|
||||
WHERE accountId = :accountId
|
||||
ORDER BY capturedAt DESC
|
||||
LIMIT :limit
|
||||
"""
|
||||
)
|
||||
suspend fun getRecentSnapshots(accountId: String, limit: Int): List<UsageSnapshotEntity>
|
||||
|
||||
@Query("SELECT * FROM usage_packages WHERE snapshotId = :snapshotId")
|
||||
fun observePackages(snapshotId: String): Flow<List<UsagePackageEntity>>
|
||||
|
||||
@Query("SELECT * FROM usage_packages WHERE snapshotId = :snapshotId")
|
||||
suspend fun getPackages(snapshotId: String): List<UsagePackageEntity>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertSnapshot(snapshot: UsageSnapshotEntity)
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package net.rodakot.remaining.ui.screens
|
||||
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.content.ComponentName
|
||||
import android.os.Build
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
@@ -41,6 +42,7 @@ 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
|
||||
import net.rodakot.remaining.widget.AccountSpotlightWidgetProvider
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
@@ -103,6 +105,21 @@ fun WidgetGalleryScreen(
|
||||
}
|
||||
}
|
||||
}
|
||||
item {
|
||||
AccountSpotlightPreviewCard(
|
||||
accounts = accounts,
|
||||
canPin = canPin,
|
||||
onPin = {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
AppWidgetManager.getInstance(context).requestPinAppWidget(
|
||||
ComponentName(context, AccountSpotlightWidgetProvider::class.java),
|
||||
null,
|
||||
null
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
items(RemainingWidgetType.entries, key = { it.name }) { type ->
|
||||
WidgetPreviewCard(
|
||||
type = type,
|
||||
@@ -124,6 +141,50 @@ fun WidgetGalleryScreen(
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AccountSpotlightPreviewCard(
|
||||
accounts: List<AccountSummary>,
|
||||
canPin: Boolean,
|
||||
onPin: () -> Unit
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val data = remember(accounts) {
|
||||
RemainingWidgetStats.accountSpotlightPreview(accounts.firstOrNull())
|
||||
}
|
||||
val preview = remember(data) {
|
||||
RemainingWidgetRenderer.renderAccountSpotlight(context, data, densityOverride = 1.15f)
|
||||
}
|
||||
ModernPanel {
|
||||
SectionHeader(
|
||||
title = "Account Spotlight",
|
||||
subtitle = "Choose one account when adding. Shows account quota ring, trend line, package bars, status, and refresh health."
|
||||
)
|
||||
Image(
|
||||
bitmap = preview.asImageBitmap(),
|
||||
contentDescription = "Account Spotlight preview",
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(184.dp)
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Button(
|
||||
onClick = onPin,
|
||||
enabled = canPin,
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Text("Add and choose account")
|
||||
}
|
||||
Surface(shape = RoundedCornerShape(8.dp)) {
|
||||
Text(
|
||||
"${RemainingWidgetRenderer.ACCOUNT_SPOTLIGHT_WIDTH_DP} x ${RemainingWidgetRenderer.ACCOUNT_SPOTLIGHT_HEIGHT_DP} dp",
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
style = MaterialTheme.typography.labelMedium
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WidgetPreviewCard(
|
||||
type: RemainingWidgetType,
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package net.rodakot.remaining.widget
|
||||
|
||||
import android.app.Activity
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import kotlinx.coroutines.launch
|
||||
import net.rodakot.remaining.RemainingApplication
|
||||
import net.rodakot.remaining.ui.theme.RemainingTheme
|
||||
|
||||
class AccountWidgetConfigureActivity : ComponentActivity() {
|
||||
private var appWidgetId: Int = AppWidgetManager.INVALID_APPWIDGET_ID
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setResult(Activity.RESULT_CANCELED)
|
||||
appWidgetId = intent?.extras?.getInt(
|
||||
AppWidgetManager.EXTRA_APPWIDGET_ID,
|
||||
AppWidgetManager.INVALID_APPWIDGET_ID
|
||||
) ?: AppWidgetManager.INVALID_APPWIDGET_ID
|
||||
if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
|
||||
lifecycleScope.launch {
|
||||
val application = application as RemainingApplication
|
||||
val accounts = application.container.accountRepository.getAccountSummaries()
|
||||
setContent {
|
||||
RemainingTheme(darkTheme = true, dynamicColor = false) {
|
||||
AccountWidgetConfigureScreen(
|
||||
accounts = accounts,
|
||||
onCancel = { finish() },
|
||||
onAccountSelected = { accountId ->
|
||||
AccountWidgetStore.save(this@AccountWidgetConfigureActivity, appWidgetId, accountId)
|
||||
RemainingWidgetUpdater.updateAccountSpotlights(
|
||||
context = this@AccountWidgetConfigureActivity,
|
||||
appWidgetManager = AppWidgetManager.getInstance(this@AccountWidgetConfigureActivity),
|
||||
appWidgetIds = intArrayOf(appWidgetId)
|
||||
)
|
||||
val result = Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
|
||||
setResult(Activity.RESULT_OK, result)
|
||||
finish()
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package net.rodakot.remaining.widget
|
||||
|
||||
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.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
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.OutlinedButton
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import net.rodakot.remaining.data.AccountSummary
|
||||
import net.rodakot.remaining.ui.components.MetricPill
|
||||
import net.rodakot.remaining.ui.components.ModernPanel
|
||||
import net.rodakot.remaining.ui.components.QuotaBar
|
||||
import net.rodakot.remaining.ui.components.RemainingBackground
|
||||
import net.rodakot.remaining.ui.components.SectionHeader
|
||||
import net.rodakot.remaining.ui.components.ServiceBadge
|
||||
import net.rodakot.remaining.ui.components.StatusChip
|
||||
import net.rodakot.remaining.ui.components.formatTimestamp
|
||||
import net.rodakot.remaining.ui.components.remainingProgress
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun AccountWidgetConfigureScreen(
|
||||
accounts: List<AccountSummary>,
|
||||
onCancel: () -> Unit,
|
||||
onAccountSelected: (String) -> Unit
|
||||
) {
|
||||
RemainingBackground {
|
||||
Scaffold(
|
||||
containerColor = Color.Transparent,
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
colors = TopAppBarDefaults.topAppBarColors(
|
||||
containerColor = Color.Transparent,
|
||||
scrolledContainerColor = Color.Transparent
|
||||
),
|
||||
title = {
|
||||
Column {
|
||||
Text("Choose Account", fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
"For Account Spotlight widget",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
},
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onCancel) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Cancel")
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
LazyColumn(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp)
|
||||
) {
|
||||
item {
|
||||
ModernPanel {
|
||||
SectionHeader(
|
||||
title = "Account Spotlight",
|
||||
subtitle = "This widget stays locked to one account and shows quota ring, trend, package split, status, and next refresh."
|
||||
)
|
||||
}
|
||||
}
|
||||
if (accounts.isEmpty()) {
|
||||
item {
|
||||
ModernPanel {
|
||||
Text("No accounts yet", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
"Open the app, connect an account, refresh it once, then add this widget again.",
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
OutlinedButton(onClick = onCancel, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("Close")
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
items(accounts, key = { it.id }) { account ->
|
||||
AccountChoice(account = account, onSelected = { onAccountSelected(account.id) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AccountChoice(
|
||||
account: AccountSummary,
|
||||
onSelected: () -> Unit
|
||||
) {
|
||||
ModernPanel {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
ServiceBadge(account.serviceType)
|
||||
StatusChip(account.status)
|
||||
}
|
||||
Text(
|
||||
account.displayName,
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
fontWeight = FontWeight.Bold,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
Text(
|
||||
account.remainingDisplay,
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
QuotaBar(
|
||||
progress = remainingProgress(account.remainingBytes, account.totalBytes),
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
MetricPill("Last success", account.lastSuccessAt.formatTimestamp(), Modifier.weight(1f))
|
||||
MetricPill("Next refresh", account.nextRefreshAt.formatTimestamp(), Modifier.weight(1f))
|
||||
}
|
||||
Button(
|
||||
onClick = onSelected,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(8.dp)
|
||||
) {
|
||||
Text("Use this account")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package net.rodakot.remaining.widget
|
||||
|
||||
import android.content.Context
|
||||
|
||||
object AccountWidgetStore {
|
||||
private const val PREFS = "remaining_account_widgets"
|
||||
private const val KEY_PREFIX = "account_"
|
||||
|
||||
fun save(context: Context, appWidgetId: Int, accountId: String) {
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
.edit()
|
||||
.putString(KEY_PREFIX + appWidgetId, accountId)
|
||||
.apply()
|
||||
}
|
||||
|
||||
fun get(context: Context, appWidgetId: Int): String? =
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
.getString(KEY_PREFIX + appWidgetId, null)
|
||||
|
||||
fun remove(context: Context, appWidgetIds: IntArray) {
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
.edit()
|
||||
.also { editor ->
|
||||
appWidgetIds.forEach { editor.remove(KEY_PREFIX + it) }
|
||||
}
|
||||
.apply()
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,35 @@ class RefreshTimelineWidgetProvider : BaseRemainingWidgetProvider(RemainingWidge
|
||||
class AccountMatrixWidgetProvider : BaseRemainingWidgetProvider(RemainingWidgetType.ACCOUNT_MATRIX)
|
||||
class CompactSignalWidgetProvider : BaseRemainingWidgetProvider(RemainingWidgetType.COMPACT_SIGNAL)
|
||||
|
||||
class AccountSpotlightWidgetProvider : AppWidgetProvider() {
|
||||
override fun onUpdate(
|
||||
context: Context,
|
||||
appWidgetManager: AppWidgetManager,
|
||||
appWidgetIds: IntArray
|
||||
) {
|
||||
val pendingResult = goAsync()
|
||||
RemainingWidgetUpdater.updateAccountSpotlights(
|
||||
context = context,
|
||||
appWidgetManager = appWidgetManager,
|
||||
appWidgetIds = appWidgetIds,
|
||||
onFinished = pendingResult::finish
|
||||
)
|
||||
}
|
||||
|
||||
override fun onDeleted(context: Context, appWidgetIds: IntArray) {
|
||||
AccountWidgetStore.remove(context, appWidgetIds)
|
||||
}
|
||||
|
||||
override fun onAppWidgetOptionsChanged(
|
||||
context: Context,
|
||||
appWidgetManager: AppWidgetManager,
|
||||
appWidgetId: Int,
|
||||
newOptions: android.os.Bundle
|
||||
) {
|
||||
onUpdate(context, appWidgetManager, intArrayOf(appWidgetId))
|
||||
}
|
||||
}
|
||||
|
||||
object RemainingWidgetUpdater {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
|
||||
@@ -61,6 +90,12 @@ object RemainingWidgetUpdater {
|
||||
update(context, appWidgetManager, ids, type)
|
||||
}
|
||||
}
|
||||
val accountIds = appWidgetManager.getAppWidgetIds(
|
||||
android.content.ComponentName(context, AccountSpotlightWidgetProvider::class.java)
|
||||
)
|
||||
if (accountIds.isNotEmpty()) {
|
||||
updateAccountSpotlights(context, appWidgetManager, accountIds)
|
||||
}
|
||||
}
|
||||
|
||||
fun update(
|
||||
@@ -97,6 +132,43 @@ object RemainingWidgetUpdater {
|
||||
}
|
||||
}
|
||||
|
||||
fun updateAccountSpotlights(
|
||||
context: Context,
|
||||
appWidgetManager: AppWidgetManager,
|
||||
appWidgetIds: IntArray,
|
||||
onFinished: (() -> Unit)? = null
|
||||
) {
|
||||
scope.launch {
|
||||
val application = context.applicationContext as RemainingApplication
|
||||
appWidgetIds.forEach { widgetId ->
|
||||
runCatching {
|
||||
val accountId = AccountWidgetStore.get(context, widgetId)
|
||||
val detail = accountId?.let { application.container.accountRepository.getAccountWidgetDetail(it) }
|
||||
val data = RemainingWidgetStats.accountSpotlight(detail)
|
||||
val bitmap = RemainingWidgetRenderer.renderAccountSpotlight(context, data, densityOverride = 1.6f)
|
||||
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,
|
||||
data.account?.let { "Account Spotlight: ${it.name}" } ?: "Account Spotlight"
|
||||
)
|
||||
views.setOnClickPendingIntent(R.id.remaining_widget_root, openAppIntent(context, widgetId))
|
||||
appWidgetManager.updateAppWidget(widgetId, views)
|
||||
}.onFailure {
|
||||
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, "Choose account")
|
||||
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()
|
||||
|
||||
@@ -21,6 +21,28 @@ import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.sin
|
||||
|
||||
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)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
object RemainingWidgetRenderer {
|
||||
fun render(
|
||||
context: Context,
|
||||
@@ -38,6 +60,226 @@ object RemainingWidgetRenderer {
|
||||
.draw(type)
|
||||
return bitmap
|
||||
}
|
||||
|
||||
fun renderAccountSpotlight(
|
||||
context: Context,
|
||||
data: AccountSpotlightData,
|
||||
densityOverride: Float? = null
|
||||
): Bitmap {
|
||||
val density = densityOverride ?: context.resources.displayMetrics.density
|
||||
val bitmap = Bitmap.createBitmap(
|
||||
(ACCOUNT_SPOTLIGHT_WIDTH_DP * density).toInt(),
|
||||
(ACCOUNT_SPOTLIGHT_HEIGHT_DP * density).toInt(),
|
||||
Bitmap.Config.ARGB_8888
|
||||
)
|
||||
AccountSpotlightCanvas(Canvas(bitmap), bitmap.width.toFloat(), bitmap.height.toFloat(), density, data)
|
||||
.draw()
|
||||
return bitmap
|
||||
}
|
||||
|
||||
const val ACCOUNT_SPOTLIGHT_WIDTH_DP = 360
|
||||
const val ACCOUNT_SPOTLIGHT_HEIGHT_DP = 230
|
||||
}
|
||||
|
||||
private class AccountSpotlightCanvas(
|
||||
private val canvas: Canvas,
|
||||
private val width: Float,
|
||||
private val height: Float,
|
||||
private val density: Float,
|
||||
private val data: AccountSpotlightData
|
||||
) {
|
||||
private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
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 pad = 18f.dp
|
||||
private val r = 18f.dp
|
||||
|
||||
fun draw() {
|
||||
drawBackground()
|
||||
val account = data.account
|
||||
if (account == null) {
|
||||
title("Account Spotlight", "Select an account after adding this widget")
|
||||
drawRing(width - 78f.dp, 92f.dp, 55f.dp, 0.64f, "Pick", "account", PRIMARY)
|
||||
drawPill(RectF(pad, height - 48f.dp, width - pad, height - 16f.dp), "Tap to choose account")
|
||||
return
|
||||
}
|
||||
|
||||
title(account.name, "${account.serviceType.displayName} · ${account.riskLabel}")
|
||||
drawRing(
|
||||
cx = width - 76f.dp,
|
||||
cy = 84f.dp,
|
||||
radius = 56f.dp,
|
||||
progress = account.progress,
|
||||
value = account.remainingLabel.compactTrafficLabel(),
|
||||
label = "remaining",
|
||||
color = account.serviceType.widgetColor()
|
||||
)
|
||||
text(account.remainingLabel, pad, 79f.dp, 24f, TEXT, Typeface.BOLD)
|
||||
text(data.freshnessLabel, pad, 101f.dp, 12f, MUTED, Typeface.BOLD)
|
||||
riskChip(account.riskLabel, pad, 114f.dp, account.riskScore)
|
||||
drawTrendChart(
|
||||
x = pad,
|
||||
y = 145f.dp,
|
||||
w = width * 0.56f,
|
||||
h = 54f.dp,
|
||||
points = data.history,
|
||||
color = account.serviceType.widgetColor()
|
||||
)
|
||||
text("Trend ${data.trendLabel}", pad, height - 16f.dp, 11f, MUTED, Typeface.BOLD)
|
||||
drawPackageBars(account)
|
||||
}
|
||||
|
||||
private fun drawBackground() {
|
||||
fillPaint.shader = LinearGradient(
|
||||
0f,
|
||||
0f,
|
||||
width,
|
||||
height,
|
||||
intArrayOf(Color.rgb(6, 31, 27), Color.rgb(9, 18, 17), Color.rgb(7, 20, 26)),
|
||||
null,
|
||||
Shader.TileMode.CLAMP
|
||||
)
|
||||
canvas.drawRoundRect(RectF(0f, 0f, width, height), r, r, fillPaint)
|
||||
fillPaint.shader = LinearGradient(
|
||||
0f,
|
||||
height,
|
||||
width,
|
||||
0f,
|
||||
Color.argb(78, 142, 235, 255),
|
||||
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.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 title(title: String, subtitle: String) {
|
||||
text(title.take(22), pad, 31f.dp, 17f, TEXT, Typeface.BOLD)
|
||||
text(subtitle.take(44), pad, 51f.dp, 11f, MUTED, Typeface.NORMAL)
|
||||
}
|
||||
|
||||
private fun drawTrendChart(
|
||||
x: Float,
|
||||
y: Float,
|
||||
w: Float,
|
||||
h: Float,
|
||||
points: List<WidgetHistoryPoint>,
|
||||
color: Int
|
||||
) {
|
||||
fillPaint.color = Color.argb(44, 20, 38, 34)
|
||||
canvas.drawRoundRect(RectF(x, y, x + w, y + h), 10f.dp, 10f.dp, fillPaint)
|
||||
strokePaint.shader = null
|
||||
strokePaint.color = Color.argb(38, 255, 255, 255)
|
||||
strokePaint.strokeWidth = 1f.dp
|
||||
canvas.drawRoundRect(RectF(x, y, x + w, y + h), 10f.dp, 10f.dp, strokePaint)
|
||||
|
||||
val values = points.mapNotNull { it.remainingBytes }
|
||||
if (values.size < 2) {
|
||||
text("Waiting for history", x + 12f.dp, y + 31f.dp, 12f, MUTED, Typeface.BOLD)
|
||||
return
|
||||
}
|
||||
val minValue = values.min()
|
||||
val maxValue = values.max()
|
||||
val range = (maxValue - minValue).coerceAtLeast(1L)
|
||||
val chartPoints = values.mapIndexed { index, value ->
|
||||
val px = x + 12f.dp + index * ((w - 24f.dp) / (values.size - 1).coerceAtLeast(1))
|
||||
val py = y + h - 12f.dp - ((value - minValue).toFloat() / range.toFloat()) * (h - 24f.dp)
|
||||
px to py
|
||||
}
|
||||
strokePaint.shader = LinearGradient(x, y, x + w, y, color, CYAN, Shader.TileMode.CLAMP)
|
||||
strokePaint.strokeWidth = 3f.dp
|
||||
chartPoints.zipWithNext().forEach { (a, b) ->
|
||||
canvas.drawLine(a.first, a.second, b.first, b.second, strokePaint)
|
||||
}
|
||||
strokePaint.shader = null
|
||||
chartPoints.forEach { drawDot(it.first, it.second, 3.2f.dp, color) }
|
||||
}
|
||||
|
||||
private fun drawPackageBars(account: WidgetAccount) {
|
||||
val x = width * 0.63f
|
||||
var y = 143f.dp
|
||||
text(data.packageLabel, x, y - 10f.dp, 11f, MUTED, Typeface.BOLD)
|
||||
val packages = data.packages.take(3)
|
||||
if (packages.isEmpty()) {
|
||||
drawBar(x, y, width - pad - x, 8f.dp, account.progress ?: 0.2f, account.serviceType.widgetColor())
|
||||
text("Account quota", x, y + 25f.dp, 11f, MUTED, Typeface.BOLD)
|
||||
return
|
||||
}
|
||||
packages.forEach { pkg ->
|
||||
text(pkg.name.take(13), x, y + 3f.dp, 10f, TEXT, Typeface.BOLD)
|
||||
drawBar(x, y + 10f.dp, width - pad - x, 7f.dp, pkg.progress ?: 0.18f, account.serviceType.widgetColor())
|
||||
y += 25f.dp
|
||||
}
|
||||
}
|
||||
|
||||
private fun riskChip(label: String, x: Float, y: Float, risk: Int) {
|
||||
val color = riskColor(risk)
|
||||
fillPaint.color = Color.argb(42, Color.red(color), Color.green(color), Color.blue(color))
|
||||
val rect = RectF(x, y, x + 128f.dp, y + 24f.dp)
|
||||
canvas.drawRoundRect(rect, 8f.dp, 8f.dp, fillPaint)
|
||||
text(label, x + 10f.dp, y + 16f.dp, 11f, color, Typeface.BOLD)
|
||||
}
|
||||
|
||||
private fun drawRing(cx: Float, cy: Float, radius: Float, progress: Float?, value: String, label: String, color: Int) {
|
||||
val stroke = 10f.dp
|
||||
strokePaint.shader = null
|
||||
strokePaint.color = Color.argb(42, 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(color, CYAN, color), null)
|
||||
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, 17f, TEXT, Typeface.BOLD, Paint.Align.CENTER)
|
||||
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)
|
||||
fillPaint.shader = LinearGradient(x, y, x + w, y, color, CYAN, Shader.TileMode.CLAMP)
|
||||
canvas.drawRoundRect(RectF(x, y, x + w * progress.coerceIn(0.05f, 1f), y + h), h / 2f, h / 2f, fillPaint)
|
||||
fillPaint.shader = null
|
||||
}
|
||||
|
||||
private fun drawPill(rect: RectF, label: String) {
|
||||
fillPaint.color = PRIMARY
|
||||
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 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 fun String.compactTrafficLabel(): String =
|
||||
take(12)
|
||||
|
||||
private val Float.dp: Float
|
||||
get() = this * density
|
||||
}
|
||||
|
||||
private class WidgetCanvas(
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package net.rodakot.remaining.widget
|
||||
|
||||
import net.rodakot.remaining.data.AccountSummary
|
||||
import net.rodakot.remaining.data.AccountWidgetDetail
|
||||
import net.rodakot.remaining.data.UsagePackageEntity
|
||||
import net.rodakot.remaining.data.UsageSnapshotEntity
|
||||
import net.rodakot.remaining.domain.AccountStatus
|
||||
import net.rodakot.remaining.domain.ServiceType
|
||||
import net.rodakot.remaining.domain.asTrafficDisplay
|
||||
@@ -60,6 +63,28 @@ data class WidgetHealth(
|
||||
val disabled: Int
|
||||
)
|
||||
|
||||
data class AccountSpotlightData(
|
||||
val generatedAt: Long,
|
||||
val account: WidgetAccount?,
|
||||
val history: List<WidgetHistoryPoint>,
|
||||
val packages: List<WidgetPackageStat>,
|
||||
val trendLabel: String,
|
||||
val freshnessLabel: String,
|
||||
val packageLabel: String
|
||||
)
|
||||
|
||||
data class WidgetHistoryPoint(
|
||||
val capturedAt: Long,
|
||||
val remainingBytes: Long?
|
||||
)
|
||||
|
||||
data class WidgetPackageStat(
|
||||
val name: String,
|
||||
val remainingLabel: String,
|
||||
val progress: Float?,
|
||||
val expiresAtText: String?
|
||||
)
|
||||
|
||||
object RemainingWidgetStats {
|
||||
fun fromSummaries(
|
||||
summaries: List<AccountSummary>,
|
||||
@@ -105,6 +130,58 @@ object RemainingWidgetStats {
|
||||
)
|
||||
}
|
||||
|
||||
fun accountFromSummary(
|
||||
summary: AccountSummary,
|
||||
now: Long = System.currentTimeMillis()
|
||||
): WidgetAccount = summary.toWidgetAccount(now)
|
||||
|
||||
fun accountSpotlight(
|
||||
detail: AccountWidgetDetail?,
|
||||
now: Long = System.currentTimeMillis()
|
||||
): AccountSpotlightData {
|
||||
val summary = detail?.summary
|
||||
val account = summary?.toWidgetAccount(now)
|
||||
val history = detail?.snapshots.orEmpty().map {
|
||||
WidgetHistoryPoint(
|
||||
capturedAt = it.capturedAt,
|
||||
remainingBytes = it.remainingBytes
|
||||
)
|
||||
}
|
||||
val packages = detail?.packages.orEmpty().map { it.toWidgetPackage() }
|
||||
return AccountSpotlightData(
|
||||
generatedAt = now,
|
||||
account = account,
|
||||
history = history,
|
||||
packages = packages,
|
||||
trendLabel = trendLabel(history),
|
||||
freshnessLabel = summary?.lastSuccessAt?.let { "Updated ${it.shortTime()}" } ?: "No successful refresh",
|
||||
packageLabel = if (packages.isEmpty()) "No package split" else "${packages.size} package${if (packages.size == 1) "" else "s"}"
|
||||
)
|
||||
}
|
||||
|
||||
fun accountSpotlightPreview(
|
||||
summary: AccountSummary?,
|
||||
now: Long = System.currentTimeMillis()
|
||||
): AccountSpotlightData {
|
||||
val account = summary?.toWidgetAccount(now)
|
||||
val remaining = summary?.remainingBytes
|
||||
val history = listOf(0.56f, 0.60f, 0.54f, 0.58f, 0.52f).mapIndexed { index, multiplier ->
|
||||
WidgetHistoryPoint(
|
||||
capturedAt = now - (4 - index) * MILLIS_PER_DAY,
|
||||
remainingBytes = remaining?.let { (it * multiplier).toLong() }
|
||||
)
|
||||
}
|
||||
return AccountSpotlightData(
|
||||
generatedAt = now,
|
||||
account = account,
|
||||
history = history,
|
||||
packages = emptyList(),
|
||||
trendLabel = trendLabel(history),
|
||||
freshnessLabel = summary?.lastSuccessAt?.let { "Updated ${it.shortTime()}" } ?: "Live account chart",
|
||||
packageLabel = "Package split appears after refresh"
|
||||
)
|
||||
}
|
||||
|
||||
private fun AccountSummary.toWidgetAccount(now: Long): WidgetAccount {
|
||||
val risk = riskScore(now)
|
||||
return WidgetAccount(
|
||||
@@ -125,6 +202,14 @@ object RemainingWidgetStats {
|
||||
)
|
||||
}
|
||||
|
||||
private fun UsagePackageEntity.toWidgetPackage(): WidgetPackageStat =
|
||||
WidgetPackageStat(
|
||||
name = name,
|
||||
remainingLabel = remainingDisplay,
|
||||
progress = remainingProgress(remainingBytes, totalBytes),
|
||||
expiresAtText = expiresAtText
|
||||
)
|
||||
|
||||
private fun buildProviderStats(
|
||||
summaries: List<AccountSummary>,
|
||||
totalRemaining: Long?
|
||||
@@ -211,6 +296,17 @@ object RemainingWidgetStats {
|
||||
private fun Long.shortTime(): String =
|
||||
DateFormat.getTimeInstance(DateFormat.SHORT, Locale.US).format(Date(this))
|
||||
|
||||
private fun trendLabel(history: List<WidgetHistoryPoint>): String {
|
||||
val first = history.firstOrNull { it.remainingBytes != null }?.remainingBytes
|
||||
val last = history.lastOrNull { it.remainingBytes != null }?.remainingBytes
|
||||
return when {
|
||||
first == null || last == null || history.size < 2 -> "Trend waiting"
|
||||
last > first -> "+${(last - first).asTrafficDisplay()}"
|
||||
last < first -> "-${(first - last).asTrafficDisplay()}"
|
||||
else -> "Flat"
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -15,4 +15,6 @@
|
||||
<string name="widget_account_matrix_description">Account-by-account quota, status, and risk matrix.</string>
|
||||
<string name="widget_compact_signal_name">Remaining Signal Strip</string>
|
||||
<string name="widget_compact_signal_description">Compact chart strip for small home-screen spaces.</string>
|
||||
<string name="widget_account_spotlight_name">Remaining Account Spotlight</string>
|
||||
<string name="widget_account_spotlight_description">Single-account quota ring, trend chart, package bars, and refresh health.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:configure="net.rodakot.remaining.widget.AccountWidgetConfigureActivity"
|
||||
android:description="@string/widget_account_spotlight_description"
|
||||
android:initialLayout="@layout/remaining_widget_chart"
|
||||
android:minResizeHeight="180dp"
|
||||
android:minResizeWidth="280dp"
|
||||
android:minHeight="200dp"
|
||||
android:minWidth="320dp"
|
||||
android:resizeMode="horizontal|vertical"
|
||||
android:targetCellHeight="3"
|
||||
android:targetCellWidth="4"
|
||||
android:updatePeriodMillis="1800000"
|
||||
android:widgetCategory="home_screen" />
|
||||
Reference in new issue
Block a user