Compare commits

...
10 Commits
Author SHA1 Message Date
Meghdad 219dc926f8 release 2026-06-23 06:49:30 +03:30
Meghdad d3a928e110 ready check 2026-06-23 06:40:11 +03:30
Meghdad c01c2de6f1 add Remaining Account Chart Tile widget 2026-06-23 06:30:31 +03:30
Meghdad 250129ca21 fix Account Spotlight widget 2026-06-23 06:11:51 +03:30
Meghdad 463d315f99 add Account Spotlight widget: 2026-06-23 02:39:58 +03:30
Meghdad 5193fda3bf Implement a full widget system. 2026-06-23 02:28:07 +03:30
Meghdad f5971f2fb2 update the dashboard 2026-06-23 01:55:43 +03:30
Meghdad 74f70ae3e7 redesign app 2026-06-23 01:40:25 +03:30
Meghdad af0ec12caf Fixed the TCI number parser 2026-06-23 01:09:35 +03:30
Meghdad 19b91b9963 update TciConnector.kt 2026-06-23 01:04:12 +03:30
49 changed files with 4414 additions and 402 deletions

No files matched your search

+26 -13
View File
@@ -1,15 +1,28 @@
*.iml # macOS
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store .DS_Store
/build
/captures # Gradle and Android build output
.externalNativeBuild .gradle/
.cxx build/
*/build/
.externalNativeBuild/
.cxx/
captures/
# Local SDK, signing, and machine-specific files
local.properties local.properties
*.iml
*.jks
*.keystore
keystore.properties
# Android Studio local state
.idea/caches/
.idea/libraries/
.idea/modules.xml
.idea/workspace.xml
.idea/navEditor.xml
.idea/assetWizardSettings.xml
.idea/deploymentTargetSelector.xml
.idea/deviceManager.xml
.idea/shelf/
-11
View File
@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="deploymentTargetSelector">
<selectionStates>
<SelectionState runConfigName="app">
<option name="selectionMode" value="DROPDOWN" />
<DialogSelection />
</SelectionState>
</selectionStates>
</component>
</project>
-13
View File
@@ -1,13 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DeviceTable">
<option name="columnSorters">
<list>
<ColumnSorterState>
<option name="column" value="Name" />
<option name="order" value="ASCENDING" />
</ColumnSorterState>
</list>
</option>
</component>
</project>
+67
View File
@@ -0,0 +1,67 @@
# Remaining
Remaining is an Android quota tracker for Iranian mobile and internet services. It stores account credentials locally, refreshes usage data in the background, and presents quota, expiry, refresh, and risk signals in the app and home-screen widgets.
## Features
- Tracks MCI, Jahan Nama / Webotel, and TCI Internet accounts.
- Shows remaining traffic, package details, expiry risk, stale refreshes, captcha needs, and authentication errors.
- Supports manual refresh, configurable background refresh intervals, low-data alerts, and app-wide theme settings.
- Includes multiple home-screen widgets for account spotlight, provider mix, watchlist, refresh timeline, compact signal, and account matrix views.
- Encrypts saved passwords, tokens, cookies, and session payloads with Android Keystore-backed AES-GCM.
This project is not affiliated with MCI, TCI, Jahan Nama, Webotel, or their parent companies.
## Requirements
- Android Studio or the Android SDK command line tools.
- JDK 17 or newer.
- Android SDK platform for compile SDK 37.
## Build
From the repository root:
```sh
./gradlew :app:assembleDebug
```
Run local unit tests:
```sh
./gradlew :app:testDebugUnitTest
```
Run Android lint:
```sh
./gradlew :app:lintDebug
```
The first build may download Gradle, Android Gradle Plugin, Kotlin, Compose, Room, WorkManager, OkHttp, jsoup, and test dependencies.
## Project Structure
- `app/src/main/java/net/rodakot/remaining/connectors`: provider-specific network clients and parsers.
- `app/src/main/java/net/rodakot/remaining/data`: Room entities, DAO, settings, and account repository.
- `app/src/main/java/net/rodakot/remaining/refresh`: WorkManager scheduling and notifications.
- `app/src/main/java/net/rodakot/remaining/security`: local credential encryption.
- `app/src/main/java/net/rodakot/remaining/ui`: Compose app, screens, theme, and UI helpers.
- `app/src/main/java/net/rodakot/remaining/widget`: AppWidget providers, renderers, and widget configuration.
- `docs`: observed provider API notes used by the connectors.
## Privacy And Security
- Credentials and session artifacts are stored only on the device and encrypted through Android Keystore.
- App backup is disabled in the manifest, and backup/data-extraction rules exclude app data.
- Do not commit `local.properties`, keystores, signing configs, real account credentials, API tokens, or generated build output.
- The provider API documentation contains placeholders only. Replace examples with sanitized values if you update those docs.
## Publishing Checklist
Before pushing this repository publicly:
- Choose a license and add a `LICENSE` file if you want others to reuse or contribute to the code.
- Review package name, app name, icon, and screenshots for your intended public identity.
- Keep release signing material outside Git and document release signing separately if needed.
- Run `./gradlew :app:testDebugUnitTest :app:lintDebug :app:assembleDebug`.
+21
View File
@@ -1,9 +1,18 @@
import java.util.Properties
plugins { plugins {
alias(libs.plugins.android.application) alias(libs.plugins.android.application)
alias(libs.plugins.legacy.kapt) alias(libs.plugins.legacy.kapt)
alias(libs.plugins.kotlin.compose) alias(libs.plugins.kotlin.compose)
} }
val keystorePropertiesFile = rootProject.file("keystore.properties")
val keystoreProperties = Properties().apply {
if (keystorePropertiesFile.isFile) {
keystorePropertiesFile.inputStream().use(::load)
}
}
android { android {
namespace = "net.rodakot.remaining" namespace = "net.rodakot.remaining"
compileSdk { compileSdk {
@@ -20,8 +29,20 @@ android {
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
} }
signingConfigs {
create("release") {
storeFile = rootProject.file(keystoreProperties.getProperty("storeFile", ""))
storePassword = keystoreProperties.getProperty("storePassword")
keyAlias = keystoreProperties.getProperty("keyAlias")
keyPassword = keystoreProperties.getProperty("keyPassword")
}
}
buildTypes { buildTypes {
release { release {
if (keystorePropertiesFile.isFile) {
signingConfig = signingConfigs.getByName("release")
}
optimization { optimization {
enable = false enable = false
} }
@@ -1,24 +0,0 @@
package net.rodakot.remaining
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("net.rodakot.remaining", appContext.packageName)
}
}
+105 -1
View File
@@ -15,10 +15,114 @@
android:roundIcon="@mipmap/ic_launcher_round" android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="false" android:supportsRtl="false"
android:theme="@style/Theme.Remaining"> android:theme="@style/Theme.Remaining">
<receiver
android:name=".widget.CommandCenterWidgetProvider"
android:exported="true"
android:label="@string/widget_command_center_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/widget_command_center" />
</receiver>
<receiver
android:name=".widget.ProviderMixWidgetProvider"
android:exported="true"
android:label="@string/widget_provider_mix_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/widget_provider_mix" />
</receiver>
<receiver
android:name=".widget.WatchlistWidgetProvider"
android:exported="true"
android:label="@string/widget_watchlist_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/widget_watchlist" />
</receiver>
<receiver
android:name=".widget.RefreshTimelineWidgetProvider"
android:exported="true"
android:label="@string/widget_refresh_timeline_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/widget_refresh_timeline" />
</receiver>
<receiver
android:name=".widget.AccountMatrixWidgetProvider"
android:exported="true"
android:label="@string/widget_account_matrix_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_matrix" />
</receiver>
<receiver
android:name=".widget.CompactSignalWidgetProvider"
android:exported="true"
android:label="@string/widget_compact_signal_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
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>
<receiver
android:name=".widget.AccountChartTileWidgetProvider"
android:exported="true"
android:label="@string/widget_account_chart_tile_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_chart_tile" />
</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 <activity
android:name=".MainActivity" android:name=".MainActivity"
android:exported="true" android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.Remaining.Starting" android:theme="@style/Theme.Remaining.Starting"
android:windowSoftInputMode="adjustResize"> android:windowSoftInputMode="adjustResize">
<intent-filter> <intent-filter>
@@ -11,7 +11,7 @@ import net.rodakot.remaining.refresh.RefreshScheduler
import net.rodakot.remaining.security.SecretCipher import net.rodakot.remaining.security.SecretCipher
class AppContainer(context: Context) { class AppContainer(context: Context) {
private val appContext = context.applicationContext val appContext: Context = context.applicationContext
private val database = AppDatabase.getInstance(appContext) private val database = AppDatabase.getInstance(appContext)
private val httpClient = HttpClients.default() private val httpClient = HttpClients.default()
@@ -5,6 +5,7 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import net.rodakot.remaining.widget.RemainingWidgetUpdater
class RemainingApplication : Application() { class RemainingApplication : Application() {
lateinit var container: AppContainer lateinit var container: AppContainer
@@ -20,6 +21,7 @@ class RemainingApplication : Application() {
container.refreshScheduler.rescheduleAll( container.refreshScheduler.rescheduleAll(
container.accountRepository.getEnabledAccounts() container.accountRepository.getEnabledAccounts()
) )
RemainingWidgetUpdater.updateAll(this@RemainingApplication)
} }
} }
} }
@@ -26,7 +26,7 @@ class TciConnector : ServiceConnector {
): CaptchaChallenge = withContext(Dispatchers.IO) { ): CaptchaChallenge = withContext(Dispatchers.IO) {
val cookieJar = MutableCookieJar(TciCookieCodec.decode(secret.cookieJar)) val cookieJar = MutableCookieJar(TciCookieCodec.decode(secret.cookieJar))
val client = HttpClients.withCookieJar(cookieJar) val client = HttpClients.withCookieJar(cookieJar)
val panelHtml = client.newCall(browserGet("$BASE_URL/panel")).execute().use { response -> val panelHtml = client.newCall(browserGet(PANEL_URL)).execute().use { response ->
if (!response.isSuccessful) { if (!response.isSuccessful) {
throw response.toRefreshException("TCI panel request failed") throw response.toRefreshException("TCI panel request failed")
} }
@@ -70,7 +70,7 @@ class TciConnector : ServiceConnector {
secret secret
} }
val panelHtml = client.newCall(browserGet("$BASE_URL/panel")).execute().use { response -> val panelHtml = client.newCall(browserGet(PANEL_URL)).execute().use { response ->
if (!response.isSuccessful) { if (!response.isSuccessful) {
throw response.toRefreshException("TCI panel request failed") throw response.toRefreshException("TCI panel request failed")
} }
@@ -148,12 +148,14 @@ class TciConnector : ServiceConnector {
private fun okhttp3.Response.toRefreshException(prefix: String): RefreshException { private fun okhttp3.Response.toRefreshException(prefix: String): RefreshException {
val errorCode = when (code) { val errorCode = when (code) {
401, 403 -> RefreshErrorCode.SESSION_EXPIRED 401, 403 -> RefreshErrorCode.SESSION_EXPIRED
else -> RefreshErrorCode.NETWORK in 500..599 -> RefreshErrorCode.INVALID_RESPONSE
else -> RefreshErrorCode.PARSER_CHANGED
} }
return RefreshException(errorCode, "$prefix (${this.code}).") return RefreshException(errorCode, "$prefix (${this.code}).")
} }
companion object { companion object {
private const val BASE_URL = "https://internet.tci.ir" private const val BASE_URL = "https://internet.tci.ir"
private const val PANEL_URL = "$BASE_URL/panel/"
} }
} }
@@ -14,7 +14,15 @@ data class TciLoginPage(
) )
object TciHtmlParser { object TciHtmlParser {
private const val RESERVED_TRAFFIC_LABEL = "میزان ترافیک رزرو شما" private val TRAFFIC_LABELS = listOf(
"میزان ترافیک رزرو شما",
"ترافیک رزرو شما",
"حجم باقیمانده",
"حجم باقی مانده",
"حجم باقی‌مانده",
"ترافیک باقی مانده",
"ترافیک باقی‌مانده"
)
fun isAuthenticated(html: String): Boolean { fun isAuthenticated(html: String): Boolean {
val lower = html.lowercase(Locale.US) val lower = html.lowercase(Locale.US)
@@ -40,18 +48,8 @@ object TciHtmlParser {
fun parseReservedTraffic(html: String): UsageSnapshotDraft { fun parseReservedTraffic(html: String): UsageSnapshotDraft {
val document = Jsoup.parse(html) val document = Jsoup.parse(html)
val candidateTexts = document.select("h5, h4, h3, div, span") val match = trafficTextCandidates(document)
.filter { it.text().contains(RESERVED_TRAFFIC_LABEL) } .firstNotNullOfOrNull { text -> TRAFFIC_REGEX.find(text) }
.flatMap { element ->
listOfNotNull(element.text(), element.parent()?.text())
}
.ifEmpty { listOf(document.text()) }
val match = candidateTexts
.asSequence()
.map { normalizeDigits(it) }
.mapNotNull { TRAFFIC_REGEX.find(it) }
.firstOrNull()
?: throw RefreshException( ?: throw RefreshException(
RefreshErrorCode.PARSER_CHANGED, RefreshErrorCode.PARSER_CHANGED,
"TCI reserved traffic value was not found." "TCI reserved traffic value was not found."
@@ -74,6 +72,44 @@ object TciHtmlParser {
) )
} }
private fun trafficTextCandidates(document: org.jsoup.nodes.Document): Sequence<String> =
sequence {
val labeledElements = document.select("h5, h4, h3, div, span, li, td, p")
.filter { element -> containsTrafficLabel(element.text()) }
labeledElements.forEach { element ->
textAfterTrafficLabel(element.text())?.let { yield(it) }
var sibling = element.nextElementSibling()
repeat(4) {
val currentSibling = sibling ?: return@repeat
yield(normalizeForSearch(currentSibling.text()))
sibling = currentSibling.nextElementSibling()
}
element.parent()?.text()?.let { parentText ->
textAfterTrafficLabel(parentText)?.let { yield(it) }
}
}
textAfterTrafficLabel(document.text())?.let { yield(it) }
}
private fun containsTrafficLabel(value: String): Boolean {
val normalized = normalizeForSearch(value)
return TRAFFIC_LABELS.any { normalized.contains(normalizeForSearch(it)) }
}
private fun textAfterTrafficLabel(value: String): String? {
val normalized = normalizeForSearch(value)
val label = TRAFFIC_LABELS
.map(::normalizeForSearch)
.filter { normalized.contains(it) }
.maxByOrNull { normalized.indexOf(it) }
?: return null
return normalized.substring(normalized.indexOf(label) + label.length)
}
fun normalizeDigits(value: String): String = fun normalizeDigits(value: String): String =
buildString(value.length) { buildString(value.length) {
value.forEach { char -> value.forEach { char ->
@@ -96,5 +132,11 @@ object TciHtmlParser {
} }
} }
private val TRAFFIC_REGEX = Regex("""(\d+(?:\.\d+)?)\s*(گیگابایت|مگابایت|GB|MB)""", RegexOption.IGNORE_CASE) private fun normalizeForSearch(value: String): String =
normalizeDigits(value)
.replace('\u200c', ' ')
.replace(Regex("\\s+"), " ")
.trim()
private val TRAFFIC_REGEX = Regex("""(\d+(?:\.\d+)?)\s*(گیگابایت|گیگ|مگابایت|مگ|GB|MB)""", RegexOption.IGNORE_CASE)
} }
@@ -38,6 +38,12 @@ data class RefreshRunResult(
val message: String? = null val message: String? = null
) )
data class AccountWidgetDetail(
val summary: AccountSummary,
val snapshots: List<UsageSnapshotEntity>,
val packages: List<UsagePackageEntity>
)
class AccountRepository( class AccountRepository(
private val dao: RemainingDao, private val dao: RemainingDao,
private val cipher: SecretCipher, private val cipher: SecretCipher,
@@ -58,6 +64,23 @@ class AccountRepository(
suspend fun getEnabledAccounts(): List<AccountEntity> = dao.getEnabledAccounts() suspend fun getEnabledAccounts(): List<AccountEntity> = dao.getEnabledAccounts()
suspend fun getAccountSummaries(): List<AccountSummary> {
val snapshots = dao.getLatestSnapshots().associateBy { it.accountId }
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) @OptIn(ExperimentalCoroutinesApi::class)
fun observeAccountDetail(accountId: String): Flow<AccountDetail?> { fun observeAccountDetail(accountId: String): Flow<AccountDetail?> {
val summaryFlow = combine( val summaryFlow = combine(
@@ -12,6 +12,9 @@ interface RemainingDao {
@Query("SELECT * FROM accounts ORDER BY serviceType, displayName") @Query("SELECT * FROM accounts ORDER BY serviceType, displayName")
fun observeAccounts(): Flow<List<AccountEntity>> fun observeAccounts(): Flow<List<AccountEntity>>
@Query("SELECT * FROM accounts ORDER BY serviceType, displayName")
suspend fun getAccounts(): List<AccountEntity>
@Query("SELECT * FROM accounts WHERE id = :accountId") @Query("SELECT * FROM accounts WHERE id = :accountId")
fun observeAccount(accountId: String): Flow<AccountEntity?> fun observeAccount(accountId: String): Flow<AccountEntity?>
@@ -94,6 +97,19 @@ interface RemainingDao {
) )
fun observeLatestSnapshots(): Flow<List<UsageSnapshotEntity>> fun observeLatestSnapshots(): Flow<List<UsageSnapshotEntity>>
@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<UsageSnapshotEntity>
@Query( @Query(
""" """
SELECT * FROM usage_snapshots SELECT * FROM usage_snapshots
@@ -114,9 +130,22 @@ interface RemainingDao {
) )
suspend fun getLatestSnapshot(accountId: String): UsageSnapshotEntity? 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") @Query("SELECT * FROM usage_packages WHERE snapshotId = :snapshotId")
fun observePackages(snapshotId: String): Flow<List<UsagePackageEntity>> 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) @Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertSnapshot(snapshot: UsageSnapshotEntity) suspend fun insertSnapshot(snapshot: UsageSnapshotEntity)
@@ -4,6 +4,7 @@ import android.content.Context
import androidx.work.CoroutineWorker import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters import androidx.work.WorkerParameters
import net.rodakot.remaining.RemainingApplication import net.rodakot.remaining.RemainingApplication
import net.rodakot.remaining.widget.RemainingWidgetUpdater
class AccountRefreshWorker( class AccountRefreshWorker(
appContext: Context, appContext: Context,
@@ -16,6 +17,7 @@ class AccountRefreshWorker(
accountId = accountId, accountId = accountId,
notify = true notify = true
) )
RemainingWidgetUpdater.updateAll(applicationContext)
return when { return when {
result.success -> Result.success() result.success -> Result.success()
result.retryable -> Result.retry() result.retryable -> Result.retry()
@@ -14,7 +14,6 @@ import kotlin.math.absoluteValue
class NotificationHelper(private val context: Context) { class NotificationHelper(private val context: Context) {
fun ensureChannel() { fun ensureChannel() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val channel = NotificationChannel( val channel = NotificationChannel(
CHANNEL_ID, CHANNEL_ID,
"Account alerts", "Account alerts",
@@ -37,8 +36,12 @@ class NotificationHelper(private val context: Context) {
.setPriority(NotificationCompat.PRIORITY_DEFAULT) .setPriority(NotificationCompat.PRIORITY_DEFAULT)
.build() .build()
try {
NotificationManagerCompat.from(context) NotificationManagerCompat.from(context)
.notify(accountId.hashCode().absoluteValue, notification) .notify(accountId.hashCode().absoluteValue, notification)
} catch (exception: SecurityException) {
// Notification permission may be revoked between the check and notify().
}
} }
private fun canPostNotifications(): Boolean { private fun canPostNotifications(): Boolean {
@@ -3,6 +3,7 @@ package net.rodakot.remaining.ui
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
@@ -19,6 +20,7 @@ import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
@@ -33,6 +35,7 @@ import net.rodakot.remaining.ui.screens.AccountDetailScreen
import net.rodakot.remaining.ui.screens.AddAccountScreen import net.rodakot.remaining.ui.screens.AddAccountScreen
import net.rodakot.remaining.ui.screens.DashboardScreen import net.rodakot.remaining.ui.screens.DashboardScreen
import net.rodakot.remaining.ui.screens.SettingsScreen import net.rodakot.remaining.ui.screens.SettingsScreen
import net.rodakot.remaining.ui.screens.WidgetGalleryScreen
@Composable @Composable
fun RemainingApp( fun RemainingApp(
@@ -50,7 +53,10 @@ fun RemainingApp(
} }
} }
Scaffold(snackbarHost = { SnackbarHost(snackbarHostState) }) { outerPadding -> Scaffold(
containerColor = Color.Transparent,
snackbarHost = { SnackbarHost(snackbarHostState) }
) { outerPadding ->
NavHost( NavHost(
navController = navController, navController = navController,
startDestination = Route.Dashboard, startDestination = Route.Dashboard,
@@ -94,6 +100,7 @@ fun RemainingApp(
SettingsScreen( SettingsScreen(
settings = state.settings, settings = state.settings,
onBack = { navController.popBackStack() }, onBack = { navController.popBackStack() },
onOpenWidgets = { navController.navigate(Route.Widgets) },
onThemeChanged = viewModel::updateTheme, onThemeChanged = viewModel::updateTheme,
onNotificationsChanged = viewModel::updateNotifications, onNotificationsChanged = viewModel::updateNotifications,
onDefaultRefreshChanged = { interval: RefreshInterval -> onDefaultRefreshChanged = { interval: RefreshInterval ->
@@ -101,17 +108,25 @@ fun RemainingApp(
} }
) )
} }
composable(Route.Widgets) {
WidgetGalleryScreen(
accounts = state.accounts,
onBack = { navController.popBackStack() }
)
}
} }
} }
state.action.captcha?.let { captcha -> state.action.captcha?.let { captcha ->
AlertDialog( AlertDialog(
onDismissRequest = viewModel::dismissCaptcha, onDismissRequest = viewModel::dismissCaptcha,
title = { Text("TCI captcha") }, shape = RoundedCornerShape(8.dp),
containerColor = MaterialTheme.colorScheme.surfaceContainerHigh,
title = { Text("TCI captcha required") },
text = { text = {
Column { Column {
Text( Text(
"Enter the captcha shown by TCI. This signs in the saved account session.", "Enter the code shown by TCI to refresh this saved account session.",
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
CaptchaImage( CaptchaImage(
@@ -153,6 +168,7 @@ private object Route {
const val Dashboard = "dashboard" const val Dashboard = "dashboard"
const val AddAccount = "add_account" const val AddAccount = "add_account"
const val Settings = "settings" const val Settings = "settings"
const val Widgets = "widgets"
const val AccountId = "accountId" const val AccountId = "accountId"
const val Detail = "detail/{$AccountId}" const val Detail = "detail/{$AccountId}"
@@ -19,6 +19,7 @@ import net.rodakot.remaining.domain.RefreshException
import net.rodakot.remaining.domain.RefreshInterval import net.rodakot.remaining.domain.RefreshInterval
import net.rodakot.remaining.domain.ServiceType import net.rodakot.remaining.domain.ServiceType
import net.rodakot.remaining.domain.ThemePreference import net.rodakot.remaining.domain.ThemePreference
import net.rodakot.remaining.widget.RemainingWidgetUpdater
data class CaptchaUiState( data class CaptchaUiState(
val accountId: String, val accountId: String,
@@ -68,6 +69,7 @@ class RemainingViewModel(
if (request.serviceType != ServiceType.TCI) { if (request.serviceType != ServiceType.TCI) {
container.accountRepository.refreshAccount(account.id, notify = false) container.accountRepository.refreshAccount(account.id, notify = false)
} }
RemainingWidgetUpdater.updateAll(container.appContext)
"Account added." "Account added."
}.onSuccess(::showMessage) }.onSuccess(::showMessage)
.onFailure { showMessage(it.userMessage()) } .onFailure { showMessage(it.userMessage()) }
@@ -79,6 +81,7 @@ class RemainingViewModel(
viewModelScope.launch { viewModelScope.launch {
setAccountBusy(accountId, true) setAccountBusy(accountId, true)
val result = container.accountRepository.refreshAccount(accountId, notify = false) val result = container.accountRepository.refreshAccount(accountId, notify = false)
RemainingWidgetUpdater.updateAll(container.appContext)
showMessage(result.message ?: if (result.success) "Account refreshed." else "Refresh failed.") showMessage(result.message ?: if (result.success) "Account refreshed." else "Refresh failed.")
setAccountBusy(accountId, false) setAccountBusy(accountId, false)
} }
@@ -93,6 +96,7 @@ class RemainingViewModel(
captcha = CaptchaUiState(accountId, challenge.imageBytes), captcha = CaptchaUiState(accountId, challenge.imageBytes),
message = null message = null
) )
RemainingWidgetUpdater.updateAll(container.appContext)
}.onFailure { showMessage(it.userMessage()) } }.onFailure { showMessage(it.userMessage()) }
setAccountBusy(accountId, false) setAccountBusy(accountId, false)
} }
@@ -112,6 +116,7 @@ class RemainingViewModel(
captcha = captcha.captchaText.trim(), captcha = captcha.captchaText.trim(),
notify = false notify = false
) )
RemainingWidgetUpdater.updateAll(container.appContext)
actionState.value = actionState.value.copy(captcha = null) actionState.value = actionState.value.copy(captcha = null)
showMessage(result.message ?: if (result.success) "TCI account signed in." else "Captcha failed.") showMessage(result.message ?: if (result.success) "TCI account signed in." else "Captcha failed.")
setAccountBusy(captcha.accountId, false) setAccountBusy(captcha.accountId, false)
@@ -146,6 +151,7 @@ class RemainingViewModel(
} else { } else {
container.refreshScheduler.cancel(account.id) container.refreshScheduler.cancel(account.id)
} }
RemainingWidgetUpdater.updateAll(container.appContext)
showMessage("Account settings updated.") showMessage("Account settings updated.")
} }
} }
@@ -154,6 +160,7 @@ class RemainingViewModel(
viewModelScope.launch { viewModelScope.launch {
container.refreshScheduler.cancel(accountId) container.refreshScheduler.cancel(accountId)
container.accountRepository.deleteAccount(accountId) container.accountRepository.deleteAccount(accountId)
RemainingWidgetUpdater.updateAll(container.appContext)
showMessage("Account deleted.") showMessage("Account deleted.")
} }
} }
@@ -1,15 +1,25 @@
package net.rodakot.remaining.ui.components package net.rodakot.remaining.ui.components
import android.graphics.BitmapFactory import android.graphics.BitmapFactory
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image import androidx.compose.foundation.Image
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.LinearProgressIndicator
@@ -20,36 +30,149 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import net.rodakot.remaining.domain.AccountStatus import net.rodakot.remaining.domain.AccountStatus
import net.rodakot.remaining.domain.ServiceType
import java.text.DateFormat import java.text.DateFormat
import java.util.Date import java.util.Date
import java.util.Locale import java.util.Locale
@Composable @Composable
fun StatusChip(status: AccountStatus, modifier: Modifier = Modifier) { fun RemainingBackground(
val color = when (status) { modifier: Modifier = Modifier,
AccountStatus.ACTIVE -> Color(0xFF3DDC84) content: @Composable BoxScope.() -> Unit
AccountStatus.REFRESHING -> Color(0xFF64B5F6) ) {
AccountStatus.CAPTCHA_REQUIRED -> Color(0xFFFFC857) val colorScheme = MaterialTheme.colorScheme
AccountStatus.NEEDS_AUTH -> Color(0xFFFF9F1C) Box(
AccountStatus.ERROR -> Color(0xFFFF5A5F) modifier = modifier
AccountStatus.DISABLED -> MaterialTheme.colorScheme.outline .fillMaxSize()
.background(
Brush.verticalGradient(
listOf(
colorScheme.background,
colorScheme.surfaceContainerLow,
colorScheme.background
)
)
)
) {
Canvas(modifier = Modifier.fillMaxSize()) {
drawRect(
brush = Brush.linearGradient(
colors = listOf(
colorScheme.primary.copy(alpha = 0.18f),
Color.Transparent,
colorScheme.secondary.copy(alpha = 0.12f)
),
start = Offset.Zero,
end = Offset(size.width, size.height)
)
)
drawLine(
color = colorScheme.primary.copy(alpha = 0.16f),
start = Offset(0f, size.height * 0.18f),
end = Offset(size.width, size.height * 0.04f),
strokeWidth = 2.dp.toPx()
)
drawLine(
color = colorScheme.secondary.copy(alpha = 0.10f),
start = Offset(0f, size.height * 0.88f),
end = Offset(size.width, size.height * 0.72f),
strokeWidth = 2.dp.toPx()
)
} }
content()
}
}
@Composable
fun ModernPanel(
modifier: Modifier = Modifier,
contentPadding: PaddingValues = PaddingValues(16.dp),
content: @Composable ColumnScope.() -> Unit
) {
Surface(
modifier = modifier,
shape = RoundedCornerShape(8.dp),
color = MaterialTheme.colorScheme.surfaceContainer.copy(alpha = 0.92f),
contentColor = MaterialTheme.colorScheme.onSurface,
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.55f)),
shadowElevation = 0.dp,
tonalElevation = 0.dp
) {
Column(
modifier = Modifier.padding(contentPadding),
verticalArrangement = Arrangement.spacedBy(12.dp),
content = content
)
}
}
@Composable
fun SectionHeader(
title: String,
modifier: Modifier = Modifier,
subtitle: String? = null
) {
Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
subtitle?.let {
Text(
it,
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall
)
}
}
}
@Composable
fun ServiceBadge(
serviceType: ServiceType,
modifier: Modifier = Modifier,
label: String = serviceType.shortName
) {
val color = serviceType.accentColor()
Surface( Surface(
modifier = modifier, modifier = modifier,
color = color.copy(alpha = 0.16f), color = color.copy(alpha = 0.16f),
contentColor = color, contentColor = color,
shape = RoundedCornerShape(8.dp) shape = RoundedCornerShape(8.dp),
border = BorderStroke(1.dp, color.copy(alpha = 0.30f))
) {
Text(
text = label,
style = MaterialTheme.typography.labelMedium,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp)
)
}
}
@Composable
fun StatusChip(status: AccountStatus, modifier: Modifier = Modifier) {
val color = status.accentColor()
Surface(
modifier = modifier,
color = color.copy(alpha = 0.16f),
contentColor = color,
shape = RoundedCornerShape(8.dp),
border = BorderStroke(1.dp, color.copy(alpha = 0.30f))
) { ) {
Text( Text(
text = status.displayName, text = status.displayName,
style = MaterialTheme.typography.labelMedium, style = MaterialTheme.typography.labelMedium,
fontWeight = FontWeight.SemiBold, fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 10.dp, vertical = 5.dp) modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp)
) )
} }
} }
@@ -62,20 +185,10 @@ fun UsageBar(
modifier: Modifier = Modifier modifier: Modifier = Modifier
) { ) {
val progress = remember(remainingBytes, totalBytes) { val progress = remember(remainingBytes, totalBytes) {
if (remainingBytes == null || totalBytes == null || totalBytes <= 0L) { remainingProgress(remainingBytes, totalBytes)
null
} else {
(remainingBytes.toFloat() / totalBytes.toFloat()).coerceIn(0f, 1f)
} }
} Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(7.dp)) {
Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(6.dp)) { QuotaBar(progress = progress)
LinearProgressIndicator(
progress = { progress ?: 0.62f },
modifier = Modifier
.fillMaxWidth()
.height(8.dp),
trackColor = MaterialTheme.colorScheme.surfaceVariant
)
Text( Text(
text = totalDisplay?.let { "Total $it" } ?: "Total quota not reported", text = totalDisplay?.let { "Total $it" } ?: "Total quota not reported",
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
@@ -85,15 +198,103 @@ fun UsageBar(
} }
@Composable @Composable
fun MetricPill(label: String, value: String, modifier: Modifier = Modifier) { fun QuotaBar(progress: Float?, modifier: Modifier = Modifier) {
val colorScheme = MaterialTheme.colorScheme
val shape = RoundedCornerShape(8.dp)
Box( Box(
modifier = modifier modifier = modifier
.background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(8.dp)) .fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 10.dp) .height(10.dp)
.clip(shape)
.background(colorScheme.surfaceContainerHighest.copy(alpha = 0.70f))
.border(1.dp, colorScheme.outlineVariant.copy(alpha = 0.35f), shape)
) { ) {
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { if (progress != null) {
Text(label, color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.labelSmall) Box(
Text(value, fontWeight = FontWeight.SemiBold, style = MaterialTheme.typography.titleSmall) modifier = Modifier
.fillMaxHeight()
.fillMaxWidth(progress)
.background(
Brush.horizontalGradient(
listOf(colorScheme.primary, colorScheme.secondary)
)
)
)
} else {
LinearProgressIndicator(
progress = { 0.28f },
modifier = Modifier.fillMaxSize(),
color = colorScheme.outline,
trackColor = Color.Transparent
)
}
}
}
@Composable
fun MetricPill(label: String, value: String, modifier: Modifier = Modifier) {
Surface(
modifier = modifier,
shape = RoundedCornerShape(8.dp),
color = MaterialTheme.colorScheme.surfaceContainerHighest.copy(alpha = 0.60f),
contentColor = MaterialTheme.colorScheme.onSurface,
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f))
) {
Column(
modifier = Modifier.padding(horizontal = 12.dp, vertical = 11.dp),
verticalArrangement = Arrangement.spacedBy(3.dp)
) {
Text(
label,
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.labelSmall
)
Text(value, fontWeight = FontWeight.Bold, style = MaterialTheme.typography.titleSmall)
}
}
}
@Composable
fun QuotaRing(
progress: Float?,
label: String,
value: String,
modifier: Modifier = Modifier,
accent: Color = MaterialTheme.colorScheme.primary
) {
val trackColor = MaterialTheme.colorScheme.surfaceContainerHighest
Box(modifier = modifier, contentAlignment = Alignment.Center) {
Canvas(modifier = Modifier.fillMaxSize()) {
val stroke = Stroke(width = 13.dp.toPx(), cap = StrokeCap.Round)
drawArc(
color = trackColor,
startAngle = 135f,
sweepAngle = 270f,
useCenter = false,
style = stroke
)
drawArc(
brush = Brush.sweepGradient(listOf(accent, Color(0xFF8EEBFF), accent)),
startAngle = 135f,
sweepAngle = 270f * (progress ?: 0.64f),
useCenter = false,
style = stroke
)
}
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
value,
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onSurface,
textAlign = TextAlign.Center
)
Text(
label,
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.labelMedium,
textAlign = TextAlign.Center
)
} }
} }
} }
@@ -122,8 +323,19 @@ fun InfoRow(label: String, value: String, modifier: Modifier = Modifier) {
horizontalArrangement = Arrangement.SpaceBetween, horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
Text(label, color = MaterialTheme.colorScheme.onSurfaceVariant) Text(
Text(value, fontWeight = FontWeight.Medium) label,
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodyMedium
)
Spacer(modifier = Modifier.size(16.dp))
Text(
value,
fontWeight = FontWeight.SemiBold,
style = MaterialTheme.typography.bodyMedium,
textAlign = TextAlign.End,
modifier = Modifier.weight(1f, fill = false)
)
} }
} }
@@ -132,3 +344,22 @@ fun Long?.formatTimestamp(): String =
DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.US) DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.US)
.format(Date(it)) .format(Date(it))
} ?: "Never" } ?: "Never"
fun remainingProgress(remainingBytes: Long?, totalBytes: Long?): Float? =
if (remainingBytes == null || totalBytes == null || totalBytes <= 0L) {
null
} else {
(remainingBytes.toFloat() / totalBytes.toFloat()).coerceIn(0f, 1f)
}
fun ServiceType.accentColor(): Color = Color(accentArgb)
fun AccountStatus.accentColor(): Color =
when (this) {
AccountStatus.ACTIVE -> Color(0xFF56E39F)
AccountStatus.REFRESHING -> Color(0xFF8EEBFF)
AccountStatus.CAPTCHA_REQUIRED -> Color(0xFFFFD166)
AccountStatus.NEEDS_AUTH -> Color(0xFFFF8A65)
AccountStatus.ERROR -> Color(0xFFFF6B7A)
AccountStatus.DISABLED -> Color(0xFF93A39A)
}
@@ -1,12 +1,18 @@
package net.rodakot.remaining.ui.screens package net.rodakot.remaining.ui.screens
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
@@ -15,8 +21,6 @@ import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
@@ -25,26 +29,41 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch import androidx.compose.material3.Switch
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import net.rodakot.remaining.data.AccountDetail import net.rodakot.remaining.data.AccountDetail
import net.rodakot.remaining.data.AccountSummary import net.rodakot.remaining.data.AccountSummary
import net.rodakot.remaining.data.UsagePackageEntity import net.rodakot.remaining.data.UsagePackageEntity
import net.rodakot.remaining.domain.AccountStatus import net.rodakot.remaining.domain.AccountStatus
import net.rodakot.remaining.domain.RefreshInterval import net.rodakot.remaining.domain.RefreshInterval
import net.rodakot.remaining.domain.asTrafficDisplay
import net.rodakot.remaining.ui.components.InfoRow import net.rodakot.remaining.ui.components.InfoRow
import net.rodakot.remaining.ui.components.MetricPill
import net.rodakot.remaining.ui.components.ModernPanel
import net.rodakot.remaining.ui.components.QuotaRing
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.StatusChip
import net.rodakot.remaining.ui.components.UsageBar import net.rodakot.remaining.ui.components.UsageBar
import net.rodakot.remaining.ui.components.accentColor
import net.rodakot.remaining.ui.components.formatTimestamp import net.rodakot.remaining.ui.components.formatTimestamp
import net.rodakot.remaining.ui.components.remainingProgress
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
@@ -58,10 +77,29 @@ fun AccountDetailScreen(
onDelete: (String) -> Unit onDelete: (String) -> Unit
) { ) {
val account = detail?.summary val account = detail?.summary
RemainingBackground {
Scaffold( Scaffold(
containerColor = Color.Transparent,
topBar = { topBar = {
TopAppBar( TopAppBar(
title = { Text(account?.displayName ?: "Account") }, colors = TopAppBarDefaults.topAppBarColors(
containerColor = Color.Transparent,
scrolledContainerColor = Color.Transparent
),
title = {
Column {
Text(account?.displayName ?: "Account", maxLines = 1, overflow = TextOverflow.Ellipsis)
account?.let {
Text(
it.serviceType.displayName,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}
},
navigationIcon = { navigationIcon = {
IconButton(onClick = onBack) { IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
@@ -77,7 +115,7 @@ fun AccountDetailScreen(
) )
} }
) { padding -> ) { padding ->
if (account == null) { if (detail == null) {
Column( Column(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
@@ -85,20 +123,28 @@ fun AccountDetailScreen(
.padding(24.dp), .padding(24.dp),
verticalArrangement = Arrangement.Center verticalArrangement = Arrangement.Center
) { ) {
ModernPanel(modifier = Modifier.fillMaxWidth()) {
Text("Account not found", style = MaterialTheme.typography.titleLarge) Text("Account not found", style = MaterialTheme.typography.titleLarge)
Text(
"This account may have been removed.",
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
} }
} else { } else {
val currentAccount = detail.summary
AccountDetailContent( AccountDetailContent(
modifier = Modifier.padding(padding), modifier = Modifier.padding(padding),
detail = detail, detail = detail,
busy = busy, busy = busy,
onRefresh = { onRefresh(account.id) }, onRefresh = { onRefresh(currentAccount.id) },
onPrepareCaptcha = { onPrepareCaptcha(account.id) }, onPrepareCaptcha = { onPrepareCaptcha(currentAccount.id) },
onSaveSettings = onSaveSettings onSaveSettings = onSaveSettings
) )
} }
} }
} }
}
@Composable @Composable
private fun AccountDetailContent( private fun AccountDetailContent(
@@ -112,69 +158,51 @@ private fun AccountDetailContent(
val account = detail.summary val account = detail.summary
LazyColumn( LazyColumn(
modifier = modifier.fillMaxSize(), modifier = modifier.fillMaxSize(),
contentPadding = PaddingValues(16.dp), contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 24.dp),
verticalArrangement = Arrangement.spacedBy(14.dp) verticalArrangement = Arrangement.spacedBy(14.dp)
) { ) {
item { item {
Card( AccountHero(
shape = RoundedCornerShape(8.dp), account = account,
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer) busy = busy,
) { onRefresh = onRefresh,
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) { onPrepareCaptcha = onPrepareCaptcha
Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) { )
Column(modifier = Modifier.weight(1f)) {
Text(account.serviceType.displayName, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(account.remainingDisplay, style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
} }
StatusChip(account.status) item {
} ModernPanel {
UsageBar(account.remainingBytes, account.totalBytes, account.totalDisplay) SectionHeader(
account.lastErrorMessage?.let { title = "Refresh health",
Text(it, color = MaterialTheme.colorScheme.error) subtitle = "The timestamps below show scheduler state and last successful data capture."
)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
MetricPill("Interval", account.refreshInterval.displayName, Modifier.weight(1f))
MetricPill("Next", account.nextRefreshAt.formatTimestamp(), Modifier.weight(1f))
} }
InfoRow("Login", account.loginIdentifier) InfoRow("Login", account.loginIdentifier)
InfoRow("Refresh interval", account.refreshInterval.displayName)
account.expiresAtText?.let { InfoRow("Package expiry", it) } account.expiresAtText?.let { InfoRow("Package expiry", it) }
InfoRow("Last refresh", account.lastRefreshAt.formatTimestamp()) InfoRow("Last refresh", account.lastRefreshAt.formatTimestamp())
InfoRow("Last success", account.lastSuccessAt.formatTimestamp()) InfoRow("Last success", account.lastSuccessAt.formatTimestamp())
InfoRow("Next refresh", account.nextRefreshAt.formatTimestamp())
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Button(
onClick = onRefresh,
enabled = !busy && account.enabled,
modifier = Modifier.weight(1f)
) {
Icon(Icons.Default.Refresh, contentDescription = null)
Text(if (busy) "Refreshing" else "Refresh", modifier = Modifier.padding(start = 8.dp))
}
if (account.status == AccountStatus.CAPTCHA_REQUIRED) {
OutlinedButton(
onClick = onPrepareCaptcha,
enabled = !busy,
modifier = Modifier.weight(1f)
) {
Text("Captcha")
} }
} }
}
}
}
}
item { item {
AccountSettingsCard(account, onSaveSettings) AccountSettingsPanel(account, onSaveSettings)
} }
item { item {
Text("Packages", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) SectionHeader(
title = "Packages",
subtitle = if (detail.packages.isEmpty()) "No package details reported yet." else "${detail.packages.size} package record${if (detail.packages.size == 1) "" else "s"}"
)
} }
if (detail.packages.isEmpty()) { if (detail.packages.isEmpty()) {
item { item {
ModernPanel {
Text( Text(
"No package details reported yet.", "Refresh this account to import package-level usage data.",
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
} }
}
} else { } else {
items(detail.packages, key = { it.id }) { item -> items(detail.packages, key = { it.id }) { item ->
PackageRow(item) PackageRow(item)
@@ -183,9 +211,105 @@ private fun AccountDetailContent(
} }
} }
@Composable
private fun AccountHero(
account: AccountSummary,
busy: Boolean,
onRefresh: () -> Unit,
onPrepareCaptcha: () -> Unit
) {
val accent = account.serviceType.accentColor()
val progress = remainingProgress(account.remainingBytes, account.totalBytes)
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(8.dp),
color = Color.Transparent,
contentColor = MaterialTheme.colorScheme.onSurface,
border = BorderStroke(1.dp, accent.copy(alpha = 0.35f))
) {
Box(
modifier = Modifier
.background(
Brush.linearGradient(
listOf(
accent.copy(alpha = 0.24f),
MaterialTheme.colorScheme.surfaceContainer.copy(alpha = 0.94f),
MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.45f)
)
)
)
.padding(18.dp)
) {
Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
Row(verticalAlignment = Alignment.Top, modifier = Modifier.fillMaxWidth()) {
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
ServiceBadge(account.serviceType)
StatusChip(if (busy) AccountStatus.REFRESHING else account.status)
}
Text(
account.remainingDisplay,
style = MaterialTheme.typography.displaySmall,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onSurface
)
Text(
"Available balance for ${account.displayName}",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodyMedium
)
}
Spacer(modifier = Modifier.width(12.dp))
QuotaRing(
progress = progress,
value = account.remainingDisplay,
label = "remaining",
accent = accent,
modifier = Modifier.size(132.dp)
)
}
UsageBar(
remainingBytes = account.remainingBytes,
totalBytes = account.totalBytes,
totalDisplay = account.totalDisplay
)
account.lastErrorMessage?.let {
Surface(
shape = RoundedCornerShape(8.dp),
color = MaterialTheme.colorScheme.error.copy(alpha = 0.12f),
contentColor = MaterialTheme.colorScheme.error,
modifier = Modifier.fillMaxWidth()
) {
Text(it, modifier = Modifier.padding(10.dp), style = MaterialTheme.typography.bodySmall)
}
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Button(
onClick = onRefresh,
enabled = !busy && account.enabled,
modifier = Modifier.weight(1f)
) {
Icon(Icons.Default.Refresh, contentDescription = null, modifier = Modifier.size(18.dp))
Text(if (busy) "Refreshing" else "Refresh now", modifier = Modifier.padding(start = 8.dp))
}
if (account.status == AccountStatus.CAPTCHA_REQUIRED) {
OutlinedButton(
onClick = onPrepareCaptcha,
enabled = !busy,
modifier = Modifier.weight(1f)
) {
Text("Solve captcha")
}
}
}
}
}
}
}
@Composable @Composable
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
private fun AccountSettingsCard( private fun AccountSettingsPanel(
account: AccountSummary, account: AccountSummary,
onSaveSettings: (AccountSummary, RefreshInterval, Boolean, Long, Int, Boolean) -> Unit onSaveSettings: (AccountSummary, RefreshInterval, Boolean, Long, Int, Boolean) -> Unit
) { ) {
@@ -195,20 +319,24 @@ private fun AccountSettingsCard(
var thresholdMb by rememberSaveable(account.id) { mutableStateOf(account.lowDataThresholdMb.toString()) } var thresholdMb by rememberSaveable(account.id) { mutableStateOf(account.lowDataThresholdMb.toString()) }
var expiryDays by rememberSaveable(account.id) { mutableStateOf(account.expiryThresholdDays.toString()) } var expiryDays by rememberSaveable(account.id) { mutableStateOf(account.expiryThresholdDays.toString()) }
Card( ModernPanel {
shape = RoundedCornerShape(8.dp), SectionHeader(
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer) title = "Automation",
) { subtitle = "Tune background refresh and warning thresholds for this account."
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) { )
Text("Account settings", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) ToggleRow(
Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) { title = "Account enabled",
Column(Modifier.weight(1f)) { description = "Pause refreshes without deleting credentials.",
Text("Enabled", fontWeight = FontWeight.Medium) checked = enabled,
Text("Background refresh is paused when disabled.", color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodySmall) onCheckedChange = { enabled = it }
} )
Switch(checked = enabled, onCheckedChange = { enabled = it }) ToggleRow(
} title = "Alerts",
Text("Refresh interval", fontWeight = FontWeight.Medium) description = "Notify for low data, expiry, captcha, and failed refreshes.",
checked = alertsEnabled,
onCheckedChange = { alertsEnabled = it }
)
Text("Refresh interval", fontWeight = FontWeight.SemiBold)
RefreshInterval.entries.chunked(2).forEach { rowOptions -> RefreshInterval.entries.chunked(2).forEach { rowOptions ->
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) { Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
rowOptions.forEach { option -> rowOptions.forEach { option ->
@@ -221,28 +349,26 @@ private fun AccountSettingsCard(
) )
} }
if (rowOptions.size == 1) { if (rowOptions.size == 1) {
Column(Modifier.weight(1f)) {} Spacer(Modifier.weight(1f))
} }
} }
} }
Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) { Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Text("Alerts", fontWeight = FontWeight.Medium)
Switch(checked = alertsEnabled, onCheckedChange = { alertsEnabled = it })
}
OutlinedTextField( OutlinedTextField(
value = thresholdMb, value = thresholdMb,
onValueChange = { thresholdMb = it.filter(Char::isDigit) }, onValueChange = { thresholdMb = it.filter(Char::isDigit) },
label = { Text("Low data threshold (MB)") }, label = { Text("Low data MB") },
singleLine = true, singleLine = true,
modifier = Modifier.fillMaxWidth() modifier = Modifier.weight(1f)
) )
OutlinedTextField( OutlinedTextField(
value = expiryDays, value = expiryDays,
onValueChange = { expiryDays = it.filter(Char::isDigit) }, onValueChange = { expiryDays = it.filter(Char::isDigit) },
label = { Text("Expiry warning threshold (days)") }, label = { Text("Expiry days") },
singleLine = true, singleLine = true,
modifier = Modifier.fillMaxWidth() modifier = Modifier.weight(1f)
) )
}
Button( Button(
onClick = { onClick = {
onSaveSettings( onSaveSettings(
@@ -256,30 +382,63 @@ private fun AccountSettingsCard(
}, },
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
) { ) {
Text("Save settings") Text("Save automation")
}
} }
} }
} }
@Composable @Composable
private fun PackageRow(item: UsagePackageEntity) { private fun ToggleRow(
Card( title: String,
shape = RoundedCornerShape(8.dp), description: String,
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerLow) checked: Boolean,
onCheckedChange: (Boolean) -> Unit
) { ) {
Column(Modifier.padding(14.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { Row(
Text(item.name, fontWeight = FontWeight.SemiBold) modifier = Modifier.fillMaxWidth(),
Text(item.remainingDisplay, style = MaterialTheme.typography.titleMedium) horizontalArrangement = Arrangement.SpaceBetween,
item.expiresAtText?.let { verticalAlignment = Alignment.CenterVertically
Text("Expires: $it", color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodySmall) ) {
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(title, fontWeight = FontWeight.SemiBold)
Text(
description,
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall
)
}
Switch(checked = checked, onCheckedChange = onCheckedChange)
}
}
@Composable
private fun PackageRow(item: UsagePackageEntity) {
ModernPanel(contentPadding = PaddingValues(14.dp)) {
Row(verticalAlignment = Alignment.Top, modifier = Modifier.fillMaxWidth()) {
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(item.name, fontWeight = FontWeight.Bold, style = MaterialTheme.typography.titleMedium)
Text(item.remainingDisplay, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold)
} }
item.statusText?.let { item.statusText?.let {
Text(it, color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodySmall) Surface(
shape = RoundedCornerShape(8.dp),
color = MaterialTheme.colorScheme.surfaceContainerHighest,
contentColor = MaterialTheme.colorScheme.onSurfaceVariant
) {
Text(it, style = MaterialTheme.typography.labelSmall, modifier = Modifier.padding(horizontal = 9.dp, vertical = 6.dp))
}
}
}
UsageBar(
remainingBytes = item.remainingBytes,
totalBytes = item.totalBytes,
totalDisplay = item.totalBytes?.asTrafficDisplay()
)
item.expiresAtText?.let {
InfoRow("Expires", it)
} }
item.detail?.takeIf { it.isNotBlank() }?.let { item.detail?.takeIf { it.isNotBlank() }?.let {
Text(it, color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodySmall) Text(it, color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodySmall)
} }
} }
} }
}
@@ -1,12 +1,17 @@
package net.rodakot.remaining.ui.screens package net.rodakot.remaining.ui.screens
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
@@ -22,15 +27,19 @@ import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch import androidx.compose.material3.Switch
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.input.VisualTransformation
@@ -38,6 +47,11 @@ import androidx.compose.ui.unit.dp
import net.rodakot.remaining.data.CreateAccountRequest import net.rodakot.remaining.data.CreateAccountRequest
import net.rodakot.remaining.domain.RefreshInterval import net.rodakot.remaining.domain.RefreshInterval
import net.rodakot.remaining.domain.ServiceType import net.rodakot.remaining.domain.ServiceType
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.ui.components.ServiceBadge
import net.rodakot.remaining.ui.components.accentColor
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
@@ -60,16 +74,62 @@ fun AddAccountScreen(
var expiryDays by rememberSaveable { mutableStateOf("3") } var expiryDays by rememberSaveable { mutableStateOf("3") }
val canSave = username.isNotBlank() && password.isNotBlank() && !saving val canSave = username.isNotBlank() && password.isNotBlank() && !saving
RemainingBackground {
Scaffold( Scaffold(
containerColor = Color.Transparent,
topBar = { topBar = {
TopAppBar( TopAppBar(
title = { Text("Add account") }, colors = TopAppBarDefaults.topAppBarColors(
containerColor = Color.Transparent,
scrolledContainerColor = Color.Transparent
),
title = {
Column {
Text("Connect account", fontWeight = FontWeight.Bold)
Text(
service.displayName,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
},
navigationIcon = { navigationIcon = {
IconButton(onClick = onBack) { IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
} }
} }
) )
},
bottomBar = {
Surface(
color = MaterialTheme.colorScheme.surfaceContainer.copy(alpha = 0.94f),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.50f))
) {
Button(
onClick = {
onCreateAccount(
CreateAccountRequest(
serviceType = service,
displayName = displayName.trim(),
loginIdentifier = username.trim(),
password = password,
refreshIntervalMinutes = interval.minutes,
alertsEnabled = alertsEnabled,
lowDataThresholdMb = thresholdMb.toLongOrNull()?.coerceAtLeast(1) ?: 1024,
expiryThresholdDays = expiryDays.toIntOrNull()?.coerceAtLeast(1) ?: 3
)
)
onBack()
},
enabled = canSave,
contentPadding = PaddingValues(vertical = 14.dp),
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Text(if (saving) "Saving" else "Save and start tracking")
}
}
} }
) { padding -> ) { padding ->
Column( Column(
@@ -77,40 +137,39 @@ fun AddAccountScreen(
.fillMaxSize() .fillMaxSize()
.padding(padding) .padding(padding)
.verticalScroll(rememberScrollState()) .verticalScroll(rememberScrollState())
.padding(16.dp), .padding(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 24.dp),
verticalArrangement = Arrangement.spacedBy(18.dp) verticalArrangement = Arrangement.spacedBy(14.dp)
) { ) {
SectionTitle("Service") ModernPanel {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) { SectionHeader(
title = "Choose service",
subtitle = "Each provider keeps its own login method and refresh behavior."
)
ServiceType.entries.forEach { option -> ServiceType.entries.forEach { option ->
FilterChip( ServiceOption(
option = option,
selected = service == option, selected = service == option,
onClick = { service = option }, onSelected = { service = option }
label = { Text(option.shortName) },
shape = RoundedCornerShape(8.dp)
) )
} }
} }
Text(
text = when (service) {
ServiceType.MCI -> "Use your My MCI phone number and password."
ServiceType.JAHAN_NAMA -> "Use your Webotel/Jahan Nama username and password."
ServiceType.TCI -> "TCI needs a manual captcha after the account is saved."
},
color = MaterialTheme.colorScheme.onSurfaceVariant
)
SectionTitle("Credentials") ModernPanel {
SectionHeader(
title = "Credentials",
subtitle = service.helperText()
)
OutlinedTextField( OutlinedTextField(
value = displayName, value = displayName,
onValueChange = { displayName = it }, onValueChange = { displayName = it },
label = { Text("Display name") }, label = { Text("Display name") },
placeholder = { Text("${service.shortName} home line") },
singleLine = true, singleLine = true,
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
) )
OutlinedTextField( OutlinedTextField(
value = username, value = username,
onValueChange = { username = it.trim() }, onValueChange = { username = it },
label = { Text(if (service == ServiceType.MCI) "Phone number" else "Username") }, label = { Text(if (service == ServiceType.MCI) "Phone number" else "Username") },
singleLine = true, singleLine = true,
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
@@ -131,74 +190,105 @@ fun AddAccountScreen(
}, },
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
) )
}
SectionTitle("Refresh") ModernPanel {
SectionHeader(
title = "Refresh rhythm",
subtitle = "Shorter intervals update faster and use more background work."
)
PresetChips( PresetChips(
options = RefreshInterval.entries, options = RefreshInterval.entries,
selected = interval, selected = interval,
label = { it.displayName }, label = { it.displayName },
onSelected = { interval = it } onSelected = { interval = it }
) )
}
SectionTitle("Alerts") ModernPanel {
Row( Row(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) { ) {
Column(modifier = Modifier.weight(1f)) { SectionHeader(
Text("Enable account alerts", fontWeight = FontWeight.Medium) title = "Alerts",
Text( subtitle = "Low data, failed refreshes, and captcha requests.",
"Low data, failed refreshes, and captcha requests", modifier = Modifier.weight(1f)
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall
) )
}
Switch(checked = alertsEnabled, onCheckedChange = { alertsEnabled = it }) Switch(checked = alertsEnabled, onCheckedChange = { alertsEnabled = it })
} }
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
OutlinedTextField( OutlinedTextField(
value = thresholdMb, value = thresholdMb,
onValueChange = { thresholdMb = it.filter(Char::isDigit) }, onValueChange = { thresholdMb = it.filter(Char::isDigit) },
label = { Text("Low data threshold (MB)") }, label = { Text("Low data MB") },
singleLine = true, singleLine = true,
modifier = Modifier.fillMaxWidth() modifier = Modifier.weight(1f)
) )
OutlinedTextField( OutlinedTextField(
value = expiryDays, value = expiryDays,
onValueChange = { expiryDays = it.filter(Char::isDigit) }, onValueChange = { expiryDays = it.filter(Char::isDigit) },
label = { Text("Expiry warning threshold (days)") }, label = { Text("Expiry days") },
singleLine = true, singleLine = true,
modifier = Modifier.fillMaxWidth() modifier = Modifier.weight(1f)
) )
}
Button( }
onClick = {
onCreateAccount(
CreateAccountRequest(
serviceType = service,
displayName = displayName.trim(),
loginIdentifier = username.trim(),
password = password,
refreshIntervalMinutes = interval.minutes,
alertsEnabled = alertsEnabled,
lowDataThresholdMb = thresholdMb.toLongOrNull()?.coerceAtLeast(1) ?: 1024,
expiryThresholdDays = expiryDays.toIntOrNull()?.coerceAtLeast(1) ?: 3
)
)
onBack()
},
enabled = canSave,
contentPadding = PaddingValues(vertical = 14.dp),
modifier = Modifier.fillMaxWidth()
) {
Text(if (saving) "Saving" else "Save account")
} }
} }
} }
} }
@Composable @Composable
private fun SectionTitle(text: String) { private fun ServiceOption(
Text(text, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) option: ServiceType,
selected: Boolean,
onSelected: () -> Unit
) {
val accent = option.accentColor()
Surface(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onSelected),
shape = RoundedCornerShape(8.dp),
color = if (selected) accent.copy(alpha = 0.16f) else MaterialTheme.colorScheme.surfaceContainerHigh.copy(alpha = 0.62f),
contentColor = MaterialTheme.colorScheme.onSurface,
border = BorderStroke(
1.dp,
if (selected) accent.copy(alpha = 0.72f) else MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.50f)
)
) {
Row(
modifier = Modifier.padding(13.dp),
verticalAlignment = Alignment.CenterVertically
) {
ServiceBadge(option)
Spacer(modifier = Modifier.width(12.dp))
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(option.displayName, fontWeight = FontWeight.Bold)
Text(
option.helperText(),
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall
)
}
if (selected) {
Surface(
shape = RoundedCornerShape(8.dp),
color = accent,
contentColor = Color.White
) {
Text(
"Selected",
style = MaterialTheme.typography.labelSmall,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 5.dp)
)
}
}
}
}
} }
@Composable @Composable
@@ -222,9 +312,16 @@ private fun <T> PresetChips(
) )
} }
if (rowOptions.size == 1) { if (rowOptions.size == 1) {
Column(modifier = Modifier.weight(1f)) {} Spacer(modifier = Modifier.weight(1f))
} }
} }
} }
} }
} }
private fun ServiceType.helperText(): String =
when (this) {
ServiceType.MCI -> "Use your My MCI phone number and password."
ServiceType.JAHAN_NAMA -> "Use your Webotel/Jahan Nama username and password."
ServiceType.TCI -> "TCI needs a manual captcha after the account is saved."
}
@@ -1,13 +1,20 @@
package net.rodakot.remaining.ui.screens package net.rodakot.remaining.ui.screens
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
@@ -25,22 +32,36 @@ import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import net.rodakot.remaining.data.AccountSummary import net.rodakot.remaining.data.AccountSummary
import net.rodakot.remaining.domain.AccountStatus import net.rodakot.remaining.domain.AccountStatus
import net.rodakot.remaining.domain.ServiceType
import net.rodakot.remaining.domain.asTrafficDisplay import net.rodakot.remaining.domain.asTrafficDisplay
import net.rodakot.remaining.ui.RemainingUiState import net.rodakot.remaining.ui.RemainingUiState
import net.rodakot.remaining.ui.components.MetricPill 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.QuotaRing
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.StatusChip
import net.rodakot.remaining.ui.components.UsageBar import net.rodakot.remaining.ui.components.UsageBar
import net.rodakot.remaining.ui.components.accentColor
import net.rodakot.remaining.ui.components.formatTimestamp import net.rodakot.remaining.ui.components.formatTimestamp
import net.rodakot.remaining.ui.components.remainingProgress
import java.util.Locale
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
@@ -52,14 +73,22 @@ fun DashboardScreen(
onPrepareCaptcha: (String) -> Unit, onPrepareCaptcha: (String) -> Unit,
onOpenSettings: () -> Unit onOpenSettings: () -> Unit
) { ) {
val insights = buildDashboardInsights(state.accounts, System.currentTimeMillis())
RemainingBackground {
Scaffold( Scaffold(
containerColor = Color.Transparent,
topBar = { topBar = {
TopAppBar( TopAppBar(
colors = TopAppBarDefaults.topAppBarColors(
containerColor = Color.Transparent,
scrolledContainerColor = Color.Transparent
),
title = { title = {
Column { Column {
Text("Remaining", fontWeight = FontWeight.Bold) Text("Remaining", fontWeight = FontWeight.Bold)
Text( Text(
"Usage across all accounts", insights.topBarSummary,
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
@@ -88,13 +117,39 @@ fun DashboardScreen(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
.padding(padding), .padding(padding),
contentPadding = PaddingValues(16.dp), contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 24.dp),
verticalArrangement = Arrangement.spacedBy(14.dp) verticalArrangement = Arrangement.spacedBy(14.dp)
) { ) {
item { item {
OverviewCard(accounts = state.accounts) CommandCenterCard(
insights = insights,
onOpenAccount = onOpenAccount,
onRefreshAccount = onRefreshAccount,
onPrepareCaptcha = onPrepareCaptcha
)
} }
items(state.accounts, key = { it.id }) { account -> item {
SignalGrid(insights = insights)
}
item {
WatchlistPanel(
watchItems = insights.watchItems,
onOpenAccount = onOpenAccount,
onRefreshAccount = onRefreshAccount,
onPrepareCaptcha = onPrepareCaptcha
)
}
item {
ProviderBreakdown(providerStats = insights.providerStats)
}
item {
SectionHeader(
title = "Accounts by priority",
subtitle = "Sorted by action needed, low data, expiry, and refresh freshness.",
modifier = Modifier.padding(top = 4.dp)
)
}
items(insights.sortedAccounts, key = { it.id }) { account ->
AccountCard( AccountCard(
account = account, account = account,
busy = state.action.busyAccountIds.contains(account.id), busy = state.action.busyAccountIds.contains(account.id),
@@ -107,74 +162,339 @@ fun DashboardScreen(
} }
} }
} }
}
@Composable @Composable
private fun EmptyDashboard(modifier: Modifier = Modifier, onAddAccount: () -> Unit) { private fun EmptyDashboard(modifier: Modifier = Modifier, onAddAccount: () -> Unit) {
Column( Column(
modifier = modifier.padding(24.dp), modifier = modifier.padding(24.dp),
verticalArrangement = Arrangement.Center verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) { ) {
ModernPanel(
modifier = Modifier.fillMaxWidth(),
contentPadding = PaddingValues(22.dp)
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(18.dp),
modifier = Modifier.fillMaxWidth()
) {
QuotaRing(
progress = null,
label = "dashboard",
value = "Ready",
modifier = Modifier.size(156.dp)
)
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text( Text(
"Track every service account in one dashboard.", "Your usage command center",
style = MaterialTheme.typography.headlineSmall, style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.Bold fontWeight = FontWeight.Bold
) )
Text( Text(
"Add MCI, Jahan Nama/Webotel, or TCI accounts, then choose how often each one refreshes.", "Connect MCI, Webotel, or TCI and the dashboard will show quota risk, stale refreshes, expiry warnings, and the next useful action.",
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 10.dp, bottom = 22.dp) style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(top = 8.dp)
) )
Button(onClick = onAddAccount) { }
Button(onClick = onAddAccount, modifier = Modifier.fillMaxWidth()) {
Icon(Icons.Default.Add, contentDescription = null) Icon(Icons.Default.Add, contentDescription = null)
Text("Add account", modifier = Modifier.padding(start = 8.dp)) Text("Connect first account", modifier = Modifier.padding(start = 8.dp))
}
}
} }
} }
} }
@Composable @Composable
private fun OverviewCard(accounts: List<AccountSummary>) { private fun CommandCenterCard(
val totalRemaining = remember(accounts) { insights: DashboardInsights,
accounts.mapNotNull { it.remainingBytes }.sum() onOpenAccount: (String) -> Unit,
} onRefreshAccount: (String) -> Unit,
val issueCount = accounts.count { onPrepareCaptcha: (String) -> Unit
it.status == AccountStatus.ERROR || ) {
it.status == AccountStatus.CAPTCHA_REQUIRED || val focus = insights.focus
it.status == AccountStatus.NEEDS_AUTH Surface(
} modifier = Modifier.fillMaxWidth(),
val nextRefresh = accounts.mapNotNull { it.nextRefreshAt }.minOrNull() shape = RoundedCornerShape(8.dp),
color = Color.Transparent,
Column( contentColor = MaterialTheme.colorScheme.onSurface,
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.30f))
) {
Box(
modifier = Modifier modifier = Modifier
.fillMaxWidth()
.background( .background(
Brush.linearGradient( Brush.linearGradient(
colors = listOf( listOf(
MaterialTheme.colorScheme.primaryContainer, MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.88f),
MaterialTheme.colorScheme.secondaryContainer MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.62f),
MaterialTheme.colorScheme.surfaceContainer.copy(alpha = 0.94f)
) )
),
RoundedCornerShape(8.dp)
) )
.padding(16.dp), )
verticalArrangement = Arrangement.spacedBy(14.dp) .padding(18.dp)
) { ) {
Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text( Text(
"Dashboard", "Today’s focus",
style = MaterialTheme.typography.titleLarge, color = MaterialTheme.colorScheme.onPrimaryContainer,
style = MaterialTheme.typography.labelLarge
)
Text(
focus.title,
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.Bold, fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onPrimaryContainer color = MaterialTheme.colorScheme.onSurface
)
Text(
focus.message,
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodyMedium
) )
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
MetricPill("Remaining", totalRemaining.asTrafficDisplay(), Modifier.weight(1f))
MetricPill("Accounts", accounts.size.toString(), Modifier.weight(1f))
} }
Spacer(modifier = Modifier.width(12.dp))
QuotaRing(
progress = insights.quotaProgress,
value = insights.availablePercentLabel,
label = "available",
modifier = Modifier.size(132.dp)
)
}
QuotaBar(progress = insights.quotaProgress)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
MetricPill("Needs action", issueCount.toString(), Modifier.weight(1f)) MetricPill("Tracked left", insights.totalRemaining?.asTrafficDisplay() ?: "Unknown", Modifier.weight(1f))
MetricPill("Next refresh", nextRefresh.formatTimestamp(), Modifier.weight(1f)) MetricPill("Ratio data", insights.quotaCoverageLabel, Modifier.weight(1f))
}
focus.account?.let { account ->
FocusActionButton(
focus = focus,
account = account,
onOpenAccount = onOpenAccount,
onRefreshAccount = onRefreshAccount,
onPrepareCaptcha = onPrepareCaptcha
)
}
}
} }
} }
} }
@Composable
private fun FocusActionButton(
focus: DashboardFocus,
account: AccountSummary,
onOpenAccount: (String) -> Unit,
onRefreshAccount: (String) -> Unit,
onPrepareCaptcha: (String) -> Unit
) {
Button(
onClick = {
when (focus.action) {
FocusAction.CAPTCHA -> onPrepareCaptcha(account.id)
FocusAction.REFRESH -> onRefreshAccount(account.id)
FocusAction.OPEN -> onOpenAccount(account.id)
}
},
enabled = account.enabled || focus.action != FocusAction.REFRESH,
modifier = Modifier.fillMaxWidth()
) {
Text(focus.actionLabel)
}
}
@Composable
private fun SignalGrid(insights: DashboardInsights) {
ModernPanel {
SectionHeader(
title = "Health signals",
subtitle = "Counts that should change your next action, not vanity totals."
)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
MetricPill("Needs action", insights.attentionCount.toString(), Modifier.weight(1f))
MetricPill("Low data", insights.lowDataAccounts.size.toString(), Modifier.weight(1f))
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
MetricPill("Expiring soon", insights.expiringAccounts.size.toString(), Modifier.weight(1f))
MetricPill("Stale refresh", insights.staleAccounts.size.toString(), Modifier.weight(1f))
}
insights.nextRefreshAccount?.let {
Text(
"Next scheduled refresh: ${it.displayName} · ${it.nextRefreshAt.formatTimestamp()}",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall
)
}
}
}
@Composable
private fun WatchlistPanel(
watchItems: List<WatchItem>,
onOpenAccount: (String) -> Unit,
onRefreshAccount: (String) -> Unit,
onPrepareCaptcha: (String) -> Unit
) {
ModernPanel {
SectionHeader(
title = "Watchlist",
subtitle = if (watchItems.isEmpty()) {
"No account needs immediate attention."
} else {
"The most important account-level issues, ordered by urgency."
}
)
if (watchItems.isEmpty()) {
Surface(
shape = RoundedCornerShape(8.dp),
color = MaterialTheme.colorScheme.primary.copy(alpha = 0.12f),
contentColor = MaterialTheme.colorScheme.primary,
modifier = Modifier.fillMaxWidth()
) {
Text(
"All clear. Your connected accounts are healthy enough for now.",
modifier = Modifier.padding(12.dp),
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold
)
}
} else {
watchItems.take(4).forEach { item ->
WatchItemRow(
item = item,
onOpenAccount = onOpenAccount,
onRefreshAccount = onRefreshAccount,
onPrepareCaptcha = onPrepareCaptcha
)
}
}
}
}
@Composable
private fun WatchItemRow(
item: WatchItem,
onOpenAccount: (String) -> Unit,
onRefreshAccount: (String) -> Unit,
onPrepareCaptcha: (String) -> Unit
) {
val account = item.account
val accent = item.type.color()
Surface(
modifier = Modifier
.fillMaxWidth()
.clickable { onOpenAccount(account.id) },
shape = RoundedCornerShape(8.dp),
color = MaterialTheme.colorScheme.surfaceContainerHigh.copy(alpha = 0.62f),
contentColor = MaterialTheme.colorScheme.onSurface,
border = BorderStroke(1.dp, accent.copy(alpha = 0.34f))
) {
Column(
modifier = Modifier.padding(12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Row(verticalAlignment = Alignment.Top, modifier = Modifier.fillMaxWidth()) {
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text(item.title, fontWeight = FontWeight.Bold, style = MaterialTheme.typography.titleSmall)
Text(
item.detail,
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall
)
}
Spacer(modifier = Modifier.width(8.dp))
ServiceBadge(account.serviceType)
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
Text(
account.displayName,
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.weight(1f),
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
when (item.type) {
WatchType.CAPTCHA -> OutlinedButton(onClick = { onPrepareCaptcha(account.id) }) {
Text("Captcha")
}
WatchType.STALE -> OutlinedButton(
onClick = { onRefreshAccount(account.id) },
enabled = account.enabled
) {
Text("Refresh")
}
else -> OutlinedButton(onClick = { onOpenAccount(account.id) }) {
Text("Open")
}
}
}
}
}
}
@Composable
private fun ProviderBreakdown(providerStats: List<ProviderStat>) {
ModernPanel {
SectionHeader(
title = "Provider breakdown",
subtitle = "Where your known quota and service issues are concentrated."
)
providerStats.forEach { stat ->
ProviderRow(stat)
}
}
}
@Composable
private fun ProviderRow(stat: ProviderStat) {
val accent = stat.serviceType.accentColor()
Column(verticalArrangement = Arrangement.spacedBy(7.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
ServiceBadge(stat.serviceType)
Spacer(modifier = Modifier.width(10.dp))
Column(modifier = Modifier.weight(1f)) {
Text(stat.serviceType.displayName, fontWeight = FontWeight.SemiBold)
Text(
"${stat.accountCount} account${if (stat.accountCount == 1) "" else "s"} · ${stat.remainingLabel}",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall
)
}
if (stat.issueCount > 0) {
Surface(
shape = RoundedCornerShape(8.dp),
color = MaterialTheme.colorScheme.error.copy(alpha = 0.12f),
contentColor = MaterialTheme.colorScheme.error
) {
Text(
"${stat.issueCount} issue${if (stat.issueCount == 1) "" else "s"}",
style = MaterialTheme.typography.labelSmall,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 5.dp)
)
}
}
}
Box(
modifier = Modifier
.fillMaxWidth()
.height(8.dp)
.background(MaterialTheme.colorScheme.surfaceContainerHighest, RoundedCornerShape(8.dp))
) {
Box(
modifier = Modifier
.fillMaxWidth(stat.quotaShare)
.height(8.dp)
.background(accent, RoundedCornerShape(8.dp))
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
private fun AccountCard( private fun AccountCard(
account: AccountSummary, account: AccountSummary,
@@ -183,54 +503,123 @@ private fun AccountCard(
onRefresh: () -> Unit, onRefresh: () -> Unit,
onPrepareCaptcha: () -> Unit onPrepareCaptcha: () -> Unit
) { ) {
val accent = account.serviceType.accentColor()
val signals = accountSignals(account, System.currentTimeMillis())
Card( Card(
onClick = onOpen, onClick = onOpen,
shape = RoundedCornerShape(8.dp), shape = RoundedCornerShape(8.dp),
colors = CardDefaults.cardColors( colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceContainer containerColor = MaterialTheme.colorScheme.surfaceContainer.copy(alpha = 0.92f),
) contentColor = MaterialTheme.colorScheme.onSurface
),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f))
) { ) {
Column(modifier = Modifier.fillMaxWidth()) {
Box(
modifier = Modifier
.fillMaxWidth()
.height(4.dp)
.background(accent)
)
Column( Column(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(16.dp), .padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp) verticalArrangement = Arrangement.spacedBy(13.dp)
) { ) {
Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) { Row(
Column(modifier = Modifier.weight(1f)) { horizontalArrangement = Arrangement.SpaceBetween,
Text(account.displayName, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) verticalAlignment = Alignment.Top,
modifier = Modifier.fillMaxWidth()
) {
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(7.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
ServiceBadge(account.serviceType)
if (!account.enabled) {
StatusChip(AccountStatus.DISABLED)
}
}
Text( Text(
"${account.serviceType.displayName} • ${account.loginIdentifier}", account.displayName,
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onSurface,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
Text(
account.loginIdentifier,
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis
) )
} }
StatusChip(account.status) Spacer(modifier = Modifier.width(10.dp))
StatusChip(if (busy) AccountStatus.REFRESHING else account.status)
} }
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { Row(verticalAlignment = Alignment.Bottom, modifier = Modifier.fillMaxWidth()) {
Text("Remaining", color = MaterialTheme.colorScheme.onSurfaceVariant) Column(modifier = Modifier.weight(1f)) {
Text(account.remainingDisplay, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold) Text(
"Remaining",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.labelMedium
)
Text(
account.remainingDisplay,
style = MaterialTheme.typography.headlineMedium,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onSurface
)
} }
Surface(
shape = RoundedCornerShape(8.dp),
color = accent.copy(alpha = 0.13f),
contentColor = accent
) {
Text(
account.refreshInterval.displayName,
style = MaterialTheme.typography.labelSmall,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 9.dp, vertical = 6.dp)
)
}
}
UsageBar( UsageBar(
remainingBytes = account.remainingBytes, remainingBytes = account.remainingBytes,
totalBytes = account.totalBytes, totalBytes = account.totalBytes,
totalDisplay = account.totalDisplay totalDisplay = account.totalDisplay
) )
if (signals.isNotEmpty()) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
signals.take(2).forEach {
SignalPill(signal = it, modifier = Modifier.weight(1f))
}
}
}
account.lastErrorMessage?.let { account.lastErrorMessage?.let {
Surface(
shape = RoundedCornerShape(8.dp),
color = MaterialTheme.colorScheme.error.copy(alpha = 0.12f),
contentColor = MaterialTheme.colorScheme.error,
modifier = Modifier.fillMaxWidth()
) {
Text( Text(
it, it,
color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall,
style = MaterialTheme.typography.bodySmall modifier = Modifier.padding(10.dp)
) )
} }
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
FilledTonalButton( FilledTonalButton(
onClick = onRefresh, onClick = onRefresh,
enabled = !busy && account.enabled, enabled = !busy && account.enabled,
modifier = Modifier.weight(1f) modifier = Modifier.weight(1f)
) { ) {
Icon(Icons.Default.Refresh, contentDescription = null) Icon(Icons.Default.Refresh, contentDescription = null, modifier = Modifier.size(18.dp))
Text(if (busy) "Refreshing" else "Refresh", modifier = Modifier.padding(start = 8.dp)) Text(if (busy) "Refreshing" else "Refresh", modifier = Modifier.padding(start = 8.dp))
} }
if (account.status == AccountStatus.CAPTCHA_REQUIRED) { if (account.status == AccountStatus.CAPTCHA_REQUIRED) {
@@ -247,11 +636,344 @@ private fun AccountCard(
} }
} }
} }
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
MetricPill("Last success", account.lastSuccessAt.formatTimestamp(), Modifier.weight(1f))
MetricPill("Next", account.nextRefreshAt.formatTimestamp(), Modifier.weight(1f))
}
}
}
}
}
@Composable
private fun SignalPill(signal: AccountSignal, modifier: Modifier = Modifier) {
val color = signal.type.color()
Surface(
modifier = modifier,
shape = RoundedCornerShape(8.dp),
color = color.copy(alpha = 0.12f),
contentColor = color,
border = BorderStroke(1.dp, color.copy(alpha = 0.30f))
) {
Text( Text(
"Last success: ${account.lastSuccessAt.formatTimestamp()}", signal.label,
color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.labelSmall,
style = MaterialTheme.typography.bodySmall fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp),
maxLines = 1,
overflow = TextOverflow.Ellipsis
) )
} }
} }
private data class DashboardInsights(
val totalRemaining: Long?,
val totalQuota: Long?,
val quotaProgress: Float?,
val knownQuotaAccounts: Int,
val attentionCount: Int,
val lowDataAccounts: List<AccountSummary>,
val expiringAccounts: List<AccountSummary>,
val staleAccounts: List<AccountSummary>,
val nextRefreshAccount: AccountSummary?,
val providerStats: List<ProviderStat>,
val watchItems: List<WatchItem>,
val sortedAccounts: List<AccountSummary>,
val focus: DashboardFocus
) {
val topBarSummary: String =
if (attentionCount > 0) {
"$attentionCount account${if (attentionCount == 1) "" else "s"} need attention"
} else {
"${sortedAccounts.size} account${if (sortedAccounts.size == 1) "" else "s"} monitored"
} }
val quotaCoverageLabel: String =
"$knownQuotaAccounts/${sortedAccounts.size} accounts"
val availablePercentLabel: String =
quotaProgress?.let { "${String.format(Locale.US, "%.0f", it * 100f)}%" } ?: "Unknown"
}
private data class DashboardFocus(
val title: String,
val message: String,
val account: AccountSummary?,
val action: FocusAction,
val actionLabel: String
)
private enum class FocusAction {
CAPTCHA,
REFRESH,
OPEN
}
private data class ProviderStat(
val serviceType: ServiceType,
val accountCount: Int,
val issueCount: Int,
val remainingBytes: Long?,
val quotaShare: Float
) {
val remainingLabel: String = remainingBytes?.asTrafficDisplay() ?: "unknown quota"
}
private data class WatchItem(
val account: AccountSummary,
val title: String,
val detail: String,
val type: WatchType
)
private data class AccountSignal(
val label: String,
val type: WatchType
)
private enum class WatchType {
ERROR,
CAPTCHA,
AUTH,
LOW_DATA,
EXPIRY,
STALE,
DISABLED
}
private fun buildDashboardInsights(accounts: List<AccountSummary>, now: Long): DashboardInsights {
val knownRemaining = accounts.mapNotNull { it.remainingBytes }
val totalRemaining = knownRemaining.takeIf { it.isNotEmpty() }?.sum()
val quotaAccounts = accounts.filter {
it.remainingBytes != null && it.totalBytes != null && it.totalBytes > 0L
}
val quotaRemaining = quotaAccounts.mapNotNull { it.remainingBytes }.takeIf { it.isNotEmpty() }?.sum()
val totalQuota = quotaAccounts.mapNotNull { it.totalBytes }.takeIf { it.isNotEmpty() }?.sum()
val lowDataAccounts = accounts.filter { it.isLowData() }
val expiringAccounts = accounts.filter { it.isExpiringSoon(now) }
val staleAccounts = accounts.filter { it.isStale(now) }
val issueAccounts = accounts.filter { it.needsUserAction() || !it.enabled }
val nextRefreshAccount = accounts
.filter { it.enabled }
.mapNotNull { account -> account.nextRefreshAt?.let { account to it } }
.minByOrNull { it.second }
?.first
val providerStats = buildProviderStats(accounts, totalRemaining)
val watchItems = accounts
.flatMap { account -> accountWatchItems(account, now) }
.sortedByDescending { it.type.priority }
val sortedAccounts = accounts.sortedWith(
compareByDescending<AccountSummary> { accountPriority(it, now) }
.thenBy { it.displayName.lowercase(Locale.US) }
)
return DashboardInsights(
totalRemaining = totalRemaining,
totalQuota = totalQuota,
quotaProgress = remainingProgress(quotaRemaining, totalQuota),
knownQuotaAccounts = quotaAccounts.size,
attentionCount = issueAccounts.size,
lowDataAccounts = lowDataAccounts,
expiringAccounts = expiringAccounts,
staleAccounts = staleAccounts,
nextRefreshAccount = nextRefreshAccount,
providerStats = providerStats,
watchItems = watchItems,
sortedAccounts = sortedAccounts,
focus = buildFocus(
accounts = accounts,
watchItems = watchItems,
nextRefreshAccount = nextRefreshAccount,
quotaProgress = remainingProgress(quotaRemaining, totalQuota)
)
)
}
private fun buildProviderStats(accounts: List<AccountSummary>, totalRemaining: Long?): List<ProviderStat> =
ServiceType.entries.mapNotNull { serviceType ->
val serviceAccounts = accounts.filter { it.serviceType == serviceType }
if (serviceAccounts.isEmpty()) return@mapNotNull null
val remaining = serviceAccounts.mapNotNull { it.remainingBytes }.takeIf { it.isNotEmpty() }?.sum()
ProviderStat(
serviceType = serviceType,
accountCount = serviceAccounts.size,
issueCount = serviceAccounts.count { it.needsUserAction() || !it.enabled },
remainingBytes = remaining,
quotaShare = if (remaining != null && totalRemaining != null && totalRemaining > 0L) {
(remaining.toFloat() / totalRemaining.toFloat()).coerceIn(0.04f, 1f)
} else {
0.04f
}
)
}
private fun buildFocus(
accounts: List<AccountSummary>,
watchItems: List<WatchItem>,
nextRefreshAccount: AccountSummary?,
quotaProgress: Float?
): DashboardFocus {
val urgent = watchItems.firstOrNull()
if (urgent != null) {
val action = when (urgent.type) {
WatchType.CAPTCHA -> FocusAction.CAPTCHA
WatchType.STALE -> FocusAction.REFRESH
else -> FocusAction.OPEN
}
return DashboardFocus(
title = urgent.title,
message = "${urgent.account.displayName}: ${urgent.detail}",
account = urgent.account,
action = action,
actionLabel = when (action) {
FocusAction.CAPTCHA -> "Solve captcha"
FocusAction.REFRESH -> "Refresh ${urgent.account.displayName}"
FocusAction.OPEN -> "Open ${urgent.account.displayName}"
}
)
}
val lowest = accounts
.filter { it.remainingBytes != null }
.minByOrNull { it.remainingBytes ?: Long.MAX_VALUE }
if (lowest != null) {
return DashboardFocus(
title = "Lowest balance: ${lowest.remainingDisplay}",
message = "${lowest.displayName} has the least remaining quota. Known quota-ratio availability is ${quotaProgress?.let { "${String.format(Locale.US, "%.0f", it * 100f)}%" } ?: "unknown"}.",
account = lowest,
action = FocusAction.OPEN,
actionLabel = "Review lowest balance"
)
}
return DashboardFocus(
title = "Waiting for first usage snapshot",
message = nextRefreshAccount?.let {
"Next scheduled refresh is ${it.displayName} at ${it.nextRefreshAt.formatTimestamp()}."
} ?: "Refresh an account to populate quota, expiry, and health signals.",
account = nextRefreshAccount,
action = FocusAction.REFRESH,
actionLabel = nextRefreshAccount?.let { "Refresh ${it.displayName}" } ?: "Refresh account"
)
}
private fun accountWatchItems(account: AccountSummary, now: Long): List<WatchItem> {
val items = mutableListOf<WatchItem>()
when (account.status) {
AccountStatus.CAPTCHA_REQUIRED -> items += WatchItem(
account = account,
title = "Captcha blocks refresh",
detail = "Manual captcha is required before this account can update.",
type = WatchType.CAPTCHA
)
AccountStatus.NEEDS_AUTH -> items += WatchItem(
account = account,
title = "Sign-in required",
detail = "Credentials or session need attention.",
type = WatchType.AUTH
)
AccountStatus.ERROR -> items += WatchItem(
account = account,
title = "Refresh is failing",
detail = account.lastErrorMessage ?: "The last refresh failed.",
type = WatchType.ERROR
)
AccountStatus.ACTIVE,
AccountStatus.REFRESHING,
AccountStatus.DISABLED -> Unit
}
if (!account.enabled) {
items += WatchItem(
account = account,
title = "Account disabled",
detail = "Background refresh and alerts are paused.",
type = WatchType.DISABLED
)
}
if (account.isLowData()) {
items += WatchItem(
account = account,
title = "Low data threshold hit",
detail = "${account.remainingDisplay} is at or below ${account.lowDataThresholdMb} MB.",
type = WatchType.LOW_DATA
)
}
if (account.isExpiringSoon(now)) {
items += WatchItem(
account = account,
title = "Package expires soon",
detail = account.expiresAtText ?: "Package expiry is inside the warning window.",
type = WatchType.EXPIRY
)
}
if (account.isStale(now)) {
items += WatchItem(
account = account,
title = "Usage data is stale",
detail = "Last success: ${account.lastSuccessAt.formatTimestamp()}.",
type = WatchType.STALE
)
}
return items
}
private fun accountSignals(account: AccountSummary, now: Long): List<AccountSignal> =
buildList {
if (account.status == AccountStatus.CAPTCHA_REQUIRED) add(AccountSignal("Captcha", WatchType.CAPTCHA))
if (account.status == AccountStatus.ERROR) add(AccountSignal("Refresh failing", WatchType.ERROR))
if (account.status == AccountStatus.NEEDS_AUTH) add(AccountSignal("Sign-in needed", WatchType.AUTH))
if (!account.enabled) add(AccountSignal("Disabled", WatchType.DISABLED))
if (account.isLowData()) add(AccountSignal("Low data", WatchType.LOW_DATA))
if (account.isExpiringSoon(now)) add(AccountSignal("Expires soon", WatchType.EXPIRY))
if (account.isStale(now)) add(AccountSignal("Stale", WatchType.STALE))
}
private fun accountPriority(account: AccountSummary, now: Long): Int =
accountWatchItems(account, now).maxOfOrNull { it.type.priority } ?: 0
private fun AccountSummary.needsUserAction(): 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 val WatchType.priority: Int
get() = when (this) {
WatchType.CAPTCHA -> 70
WatchType.ERROR -> 65
WatchType.AUTH -> 60
WatchType.LOW_DATA -> 50
WatchType.EXPIRY -> 45
WatchType.STALE -> 30
WatchType.DISABLED -> 10
}
private fun WatchType.color(): Color =
when (this) {
WatchType.CAPTCHA -> Color(0xFFFFD166)
WatchType.ERROR -> Color(0xFFFF6B7A)
WatchType.AUTH -> Color(0xFFFF9F6E)
WatchType.LOW_DATA -> Color(0xFFFFD166)
WatchType.EXPIRY -> Color(0xFFFFB86B)
WatchType.STALE -> Color(0xFF8EEBFF)
WatchType.DISABLED -> Color(0xFF93A39A)
}
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
@@ -3,6 +3,7 @@ package net.rodakot.remaining.ui.screens
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
@@ -11,6 +12,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
@@ -20,27 +22,49 @@ import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch import androidx.compose.material3.Switch
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import net.rodakot.remaining.data.AppSettings import net.rodakot.remaining.data.AppSettings
import net.rodakot.remaining.domain.RefreshInterval import net.rodakot.remaining.domain.RefreshInterval
import net.rodakot.remaining.domain.ThemePreference import net.rodakot.remaining.domain.ThemePreference
import net.rodakot.remaining.ui.components.ModernPanel
import net.rodakot.remaining.ui.components.RemainingBackground
import net.rodakot.remaining.ui.components.SectionHeader
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun SettingsScreen( fun SettingsScreen(
settings: AppSettings, settings: AppSettings,
onBack: () -> Unit, onBack: () -> Unit,
onOpenWidgets: () -> Unit,
onThemeChanged: (ThemePreference) -> Unit, onThemeChanged: (ThemePreference) -> Unit,
onNotificationsChanged: (Boolean) -> Unit, onNotificationsChanged: (Boolean) -> Unit,
onDefaultRefreshChanged: (RefreshInterval) -> Unit onDefaultRefreshChanged: (RefreshInterval) -> Unit
) { ) {
RemainingBackground {
Scaffold( Scaffold(
containerColor = Color.Transparent,
topBar = { topBar = {
TopAppBar( TopAppBar(
title = { Text("Settings") }, colors = TopAppBarDefaults.topAppBarColors(
containerColor = Color.Transparent,
scrolledContainerColor = Color.Transparent
),
title = {
Column {
Text("Settings", fontWeight = FontWeight.Bold)
Text(
"App-wide defaults",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
},
navigationIcon = { navigationIcon = {
IconButton(onClick = onBack) { IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
@@ -54,42 +78,53 @@ fun SettingsScreen(
.fillMaxSize() .fillMaxSize()
.padding(padding) .padding(padding)
.verticalScroll(rememberScrollState()) .verticalScroll(rememberScrollState())
.padding(16.dp), .padding(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 24.dp),
verticalArrangement = Arrangement.spacedBy(18.dp) verticalArrangement = Arrangement.spacedBy(14.dp)
) { ) {
Text("Appearance", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) ModernPanel {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) { 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",
subtitle = "Choose a stable theme or follow the device setting."
)
ThemePreference.entries.forEach { option -> ThemePreference.entries.forEach { option ->
FilterChip( FilterChip(
selected = settings.themePreference == option, selected = settings.themePreference == option,
onClick = { onThemeChanged(option) }, onClick = { onThemeChanged(option) },
label = { Text(option.displayName) }, label = { Text(option.displayName) },
modifier = Modifier.weight(1f), modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(8.dp) shape = RoundedCornerShape(8.dp)
) )
} }
} }
Text("Notifications", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) ModernPanel {
Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) { SettingSwitchRow(
Column(Modifier.weight(1f)) { title = "Global alerts",
Text("Global alerts", fontWeight = FontWeight.Medium) description = "Controls refresh failures, captcha-needed alerts, and low-data alerts.",
Text(
"Controls refresh failures, captcha-needed alerts, and low-data alerts.",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall
)
}
Switch(
checked = settings.notificationsEnabled, checked = settings.notificationsEnabled,
onCheckedChange = onNotificationsChanged onCheckedChange = onNotificationsChanged
) )
} }
Text("New accounts", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) ModernPanel {
SectionHeader(
title = "New account defaults",
subtitle = "These settings apply to accounts you connect later."
)
Text( Text(
"Default refresh interval", "Default refresh interval",
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall
) )
RefreshInterval.entries.chunked(2).forEach { rowOptions -> RefreshInterval.entries.chunked(2).forEach { rowOptions ->
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) { Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
@@ -103,10 +138,36 @@ fun SettingsScreen(
) )
} }
if (rowOptions.size == 1) { if (rowOptions.size == 1) {
Column(Modifier.weight(1f)) {} Spacer(Modifier.weight(1f))
} }
} }
} }
} }
} }
} }
}
}
@Composable
private fun SettingSwitchRow(
title: String,
description: String,
checked: Boolean,
onCheckedChange: (Boolean) -> Unit
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text(title, fontWeight = FontWeight.SemiBold)
Text(
description,
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall
)
}
Switch(checked = checked, onCheckedChange = onCheckedChange)
}
}
@@ -0,0 +1,336 @@
package net.rodakot.remaining.ui.screens
import android.appwidget.AppWidgetManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
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.layout.size
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.Alignment
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.AccountChartTileWidgetProvider
import net.rodakot.remaining.widget.AccountSpotlightWidgetProvider
import net.rodakot.remaining.widget.AccountWidgetConfigureActivity
import net.rodakot.remaining.widget.EXTRA_ACCOUNT_WIDGET_PROVIDER
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<AccountSummary>,
onBack: () -> Unit
) {
val context = LocalContext.current
val canPin = remember {
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
)
}
}
}
item {
AccountChartTilePreviewCard(
accounts = accounts,
canPin = canPin,
onPin = {
AppWidgetManager.getInstance(context).requestPinAppWidget(
ComponentName(context, AccountChartTileWidgetProvider::class.java),
null,
accountWidgetConfigureCallback(
context,
AccountChartTileWidgetProvider::class.java.name,
ACCOUNT_CHART_TILE_CONFIGURE_REQUEST
)
)
}
)
}
item {
AccountSpotlightPreviewCard(
accounts = accounts,
canPin = canPin,
onPin = {
AppWidgetManager.getInstance(context).requestPinAppWidget(
ComponentName(context, AccountSpotlightWidgetProvider::class.java),
null,
accountWidgetConfigureCallback(
context,
AccountSpotlightWidgetProvider::class.java.name,
ACCOUNT_SPOTLIGHT_CONFIGURE_REQUEST
)
)
}
)
}
items(RemainingWidgetType.entries, key = { it.name }) { type ->
WidgetPreviewCard(
type = type,
accounts = accounts,
canPin = canPin,
onPin = {
AppWidgetManager.getInstance(context).requestPinAppWidget(
type.componentName(context),
null,
null
)
}
)
}
}
}
}
}
@Composable
private fun AccountChartTilePreviewCard(
accounts: List<AccountSummary>,
canPin: Boolean,
onPin: () -> Unit
) {
val context = LocalContext.current
val data = remember(accounts) {
RemainingWidgetStats.accountSpotlightPreview(accounts.firstOrNull())
}
val preview = remember(data) {
RemainingWidgetRenderer.renderAccountChartTile(context, data, densityOverride = 1.5f)
}
ModernPanel {
SectionHeader(
title = "Account Chart Tile",
subtitle = "A 1x1 selected-account widget with no visible text: quota ring, trend sparkline, risk pulse, and package bars."
)
Row(
horizontalArrangement = Arrangement.spacedBy(14.dp),
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth()
) {
Image(
bitmap = preview.asImageBitmap(),
contentDescription = "Account Chart Tile preview",
modifier = Modifier.size(112.dp)
)
Column(
verticalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.weight(1.2f)
) {
Button(
onClick = onPin,
enabled = canPin,
modifier = Modifier.fillMaxWidth()
) {
Text("Add and choose account")
}
Surface(shape = RoundedCornerShape(8.dp)) {
Text(
"1 x 1 / no text",
modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
style = MaterialTheme.typography.labelMedium
)
}
}
}
}
}
@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,
accounts: List<AccountSummary>,
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
}
private fun accountWidgetConfigureCallback(
context: Context,
providerClassName: String,
requestCode: Int
): PendingIntent {
val intent = Intent(context, AccountWidgetConfigureActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
putExtra(EXTRA_ACCOUNT_WIDGET_PROVIDER, providerClassName)
}
val mutabilityFlag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.FLAG_MUTABLE
} else {
0
}
return PendingIntent.getActivity(
context,
requestCode,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or mutabilityFlag
)
}
private const val ACCOUNT_SPOTLIGHT_CONFIGURE_REQUEST = 45_901
private const val ACCOUNT_CHART_TILE_CONFIGURE_REQUEST = 45_902
@@ -2,17 +2,22 @@ package net.rodakot.remaining.ui.theme
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
val Blue80 = Color(0xFF8FD8FF) val SignalGreen80 = Color(0xFF98F7C7)
val Green80 = Color(0xFF8FE7B0) val Cyan80 = Color(0xFF8EEBFF)
val Amber80 = Color(0xFFFFD66B) val Rose80 = Color(0xFFFF9DB2)
val Blue40 = Color(0xFF006B8F) val SignalGreen40 = Color(0xFF006C54)
val Green40 = Color(0xFF006C46) val Cyan40 = Color(0xFF00677A)
val Amber40 = Color(0xFF765A00) val Rose40 = Color(0xFF9C2945)
val DarkBackground = Color(0xFF0D1117) val DarkBackground = Color(0xFF070B0A)
val DarkSurface = Color(0xFF151B23) val DarkSurface = Color(0xFF101613)
val DarkSurfaceVariant = Color(0xFF222B36) val DarkSurfaceLow = Color(0xFF0C110F)
val LightBackground = Color(0xFFF7F9FC) val DarkSurfaceHigh = Color(0xFF17211D)
val DarkSurfaceVariant = Color(0xFF22302B)
val LightBackground = Color(0xFFF7FBF5)
val LightSurface = Color(0xFFFFFFFF) val LightSurface = Color(0xFFFFFFFF)
val LightSurfaceVariant = Color(0xFFE8EEF5) val LightSurfaceLow = Color(0xFFEDF6EF)
val LightSurfaceHigh = Color(0xFFE4F1E8)
val LightSurfaceVariant = Color(0xFFDDEBE1)
@@ -7,24 +7,67 @@ import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
private val DarkColorScheme = darkColorScheme( private val DarkColorScheme = darkColorScheme(
primary = Blue80, primary = SignalGreen80,
secondary = Green80, onPrimary = Color(0xFF003826),
tertiary = Amber80, primaryContainer = Color(0xFF0A3F31),
onPrimaryContainer = Color(0xFFC7FFE6),
secondary = Cyan80,
onSecondary = Color(0xFF003640),
secondaryContainer = Color(0xFF0B3D46),
onSecondaryContainer = Color(0xFFC5F6FF),
tertiary = Rose80,
onTertiary = Color(0xFF5A0B1F),
tertiaryContainer = Color(0xFF5D1C2B),
onTertiaryContainer = Color(0xFFFFD9E0),
background = DarkBackground, background = DarkBackground,
onBackground = Color(0xFFE2EEE7),
surface = DarkSurface, surface = DarkSurface,
surfaceVariant = DarkSurfaceVariant onSurface = Color(0xFFE5EEE9),
surfaceVariant = DarkSurfaceVariant,
onSurfaceVariant = Color(0xFFB7C8C0),
surfaceContainerLowest = DarkBackground,
surfaceContainerLow = DarkSurfaceLow,
surfaceContainer = DarkSurface,
surfaceContainerHigh = DarkSurfaceHigh,
surfaceContainerHighest = Color(0xFF1C2823),
outline = Color(0xFF7B9188),
outlineVariant = Color(0xFF31453D),
error = Color(0xFFFF8A9A),
onError = Color(0xFF5F0717)
) )
private val LightColorScheme = lightColorScheme( private val LightColorScheme = lightColorScheme(
primary = Blue40, primary = SignalGreen40,
secondary = Green40, onPrimary = Color.White,
tertiary = Amber40, primaryContainer = Color(0xFFC9F5DF),
onPrimaryContainer = Color(0xFF002116),
secondary = Cyan40,
onSecondary = Color.White,
secondaryContainer = Color(0xFFC4F3FF),
onSecondaryContainer = Color(0xFF001F26),
tertiary = Rose40,
onTertiary = Color.White,
tertiaryContainer = Color(0xFFFFD9E0),
onTertiaryContainer = Color(0xFF3F0011),
background = LightBackground, background = LightBackground,
onBackground = Color(0xFF17211C),
surface = LightSurface, surface = LightSurface,
surfaceVariant = LightSurfaceVariant onSurface = Color(0xFF17211C),
surfaceVariant = LightSurfaceVariant,
onSurfaceVariant = Color(0xFF53635B),
surfaceContainerLowest = Color.White,
surfaceContainerLow = LightSurfaceLow,
surfaceContainer = LightSurface,
surfaceContainerHigh = LightSurfaceHigh,
surfaceContainerHighest = Color(0xFFD8E8DD),
outline = Color(0xFF72857B),
outlineVariant = Color(0xFFC2D4C8),
error = Color(0xFFBA1A1A),
onError = Color.White
) )
@Composable @Composable
@@ -8,6 +8,13 @@ import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with // Set of Material typography styles to start with
val Typography = Typography( val Typography = Typography(
displaySmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Bold,
fontSize = 34.sp,
lineHeight = 38.sp,
letterSpacing = 0.sp
),
headlineMedium = TextStyle( headlineMedium = TextStyle(
fontFamily = FontFamily.Default, fontFamily = FontFamily.Default,
fontWeight = FontWeight.Bold, fontWeight = FontWeight.Bold,
@@ -15,6 +22,13 @@ val Typography = Typography(
lineHeight = 34.sp, lineHeight = 34.sp,
letterSpacing = 0.sp letterSpacing = 0.sp
), ),
headlineSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Bold,
fontSize = 24.sp,
lineHeight = 30.sp,
letterSpacing = 0.sp
),
titleLarge = TextStyle( titleLarge = TextStyle(
fontFamily = FontFamily.Default, fontFamily = FontFamily.Default,
fontWeight = FontWeight.Bold, fontWeight = FontWeight.Bold,
@@ -29,11 +43,46 @@ val Typography = Typography(
lineHeight = 22.sp, lineHeight = 22.sp,
letterSpacing = 0.sp letterSpacing = 0.sp
), ),
titleSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.SemiBold,
fontSize = 14.sp,
lineHeight = 20.sp,
letterSpacing = 0.sp
),
bodyLarge = TextStyle( bodyLarge = TextStyle(
fontFamily = FontFamily.Default, fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal, fontWeight = FontWeight.Normal,
fontSize = 16.sp, fontSize = 16.sp,
lineHeight = 24.sp, lineHeight = 24.sp,
letterSpacing = 0.sp letterSpacing = 0.sp
),
bodyMedium = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 14.sp,
lineHeight = 20.sp,
letterSpacing = 0.sp
),
labelLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.SemiBold,
fontSize = 14.sp,
lineHeight = 20.sp,
letterSpacing = 0.sp
),
labelMedium = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.SemiBold,
fontSize = 12.sp,
lineHeight = 16.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.SemiBold,
fontSize = 11.sp,
lineHeight = 14.sp,
letterSpacing = 0.sp
) )
) )
@@ -0,0 +1,58 @@
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
private var providerClassName: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setResult(Activity.RESULT_CANCELED)
providerClassName = intent?.getStringExtra(EXTRA_ACCOUNT_WIDGET_PROVIDER)
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.updateConfiguredAccountWidget(
context = this@AccountWidgetConfigureActivity,
appWidgetManager = AppWidgetManager.getInstance(this@AccountWidgetConfigureActivity),
appWidgetId = appWidgetId,
providerClassName = providerClassName
)
val result = Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
setResult(Activity.RESULT_OK, result)
finish()
}
)
}
}
}
}
}
const val EXTRA_ACCOUNT_WIDGET_PROVIDER = "net.rodakot.remaining.widget.EXTRA_ACCOUNT_WIDGET_PROVIDER"
@@ -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()
}
}
@@ -0,0 +1,352 @@
package net.rodakot.remaining.widget
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Build
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)
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))
}
}
class AccountChartTileWidgetProvider : AppWidgetProvider() {
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
val pendingResult = goAsync()
RemainingWidgetUpdater.updateAccountChartTiles(
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)
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)
}
}
val spotlightIds = appWidgetManager.getAppWidgetIds(
ComponentName(context, AccountSpotlightWidgetProvider::class.java)
)
if (spotlightIds.isNotEmpty()) {
updateAccountSpotlights(context, appWidgetManager, spotlightIds)
}
val tileIds = appWidgetManager.getAppWidgetIds(
ComponentName(context, AccountChartTileWidgetProvider::class.java)
)
if (tileIds.isNotEmpty()) {
updateAccountChartTiles(context, appWidgetManager, tileIds)
}
}
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()
}
}
fun updateAccountSpotlights(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray,
onFinished: (() -> Unit)? = null
) {
scope.launch {
appWidgetIds.forEach { widgetId ->
runCatching {
val data = loadAccountData(context, widgetId)
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,
if (data.account == null) {
openConfigureIntent(
context,
widgetId,
mutable = false,
providerClassName = AccountSpotlightWidgetProvider::class.java.name
)
} else {
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,
openConfigureIntent(
context,
widgetId,
mutable = false,
providerClassName = AccountSpotlightWidgetProvider::class.java.name
)
)
appWidgetManager.updateAppWidget(widgetId, views)
}
}
onFinished?.invoke()
}
}
fun updateAccountChartTiles(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray,
onFinished: (() -> Unit)? = null
) {
scope.launch {
appWidgetIds.forEach { widgetId ->
runCatching {
val data = loadAccountData(context, widgetId)
val bitmap = RemainingWidgetRenderer.renderAccountChartTile(context, data, densityOverride = 1.8f)
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 chart tile: ${it.name}" } ?: "Account chart tile"
)
views.setOnClickPendingIntent(
R.id.remaining_widget_root,
if (data.account == null) {
openConfigureIntent(
context,
widgetId,
mutable = false,
providerClassName = AccountChartTileWidgetProvider::class.java.name
)
} else {
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.VISIBLE)
views.setViewVisibility(R.id.remaining_widget_fallback, View.GONE)
runCatching {
val bitmap = RemainingWidgetRenderer.renderAccountChartTile(
context,
RemainingWidgetStats.accountSpotlight(null),
densityOverride = 1.8f
)
views.setImageViewBitmap(R.id.remaining_widget_image, bitmap)
}
views.setOnClickPendingIntent(
R.id.remaining_widget_root,
openConfigureIntent(
context,
widgetId,
mutable = false,
providerClassName = AccountChartTileWidgetProvider::class.java.name
)
)
appWidgetManager.updateAppWidget(widgetId, views)
}
}
onFinished?.invoke()
}
}
fun updateConfiguredAccountWidget(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetId: Int,
providerClassName: String? = null
) {
val resolvedProvider = providerClassName ?: appWidgetManager.getAppWidgetInfo(appWidgetId)?.provider?.className
when (resolvedProvider) {
AccountChartTileWidgetProvider::class.java.name -> {
updateAccountChartTiles(context, appWidgetManager, intArrayOf(appWidgetId))
}
else -> {
updateAccountSpotlights(context, appWidgetManager, intArrayOf(appWidgetId))
}
}
}
private suspend fun loadData(context: Context): WidgetDashboardData {
val application = context.applicationContext as RemainingApplication
val summaries = application.container.accountRepository.getAccountSummaries()
return RemainingWidgetStats.fromSummaries(summaries)
}
private suspend fun loadAccountData(context: Context, widgetId: Int): AccountSpotlightData {
val application = context.applicationContext as RemainingApplication
val accountId = AccountWidgetStore.get(context, widgetId)
val detail = accountId?.let { application.container.accountRepository.getAccountWidgetDetail(it) }
return RemainingWidgetStats.accountSpotlight(detail)
}
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
)
}
fun openConfigureIntent(
context: Context,
requestCode: Int,
mutable: Boolean,
providerClassName: String? = null
): PendingIntent {
val intent = Intent(context, AccountWidgetConfigureActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, requestCode)
providerClassName?.let { putExtra(EXTRA_ACCOUNT_WIDGET_PROVIDER, it) }
}
val mutabilityFlag = if (mutable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.FLAG_MUTABLE
} else {
PendingIntent.FLAG_IMMUTABLE
}
return PendingIntent.getActivity(
context,
requestCode,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or mutabilityFlag
)
}
}
@@ -0,0 +1,907 @@
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.Path
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
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,
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
}
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
}
fun renderAccountChartTile(
context: Context,
data: AccountSpotlightData,
densityOverride: Float? = null
): Bitmap {
val density = densityOverride ?: context.resources.displayMetrics.density
val bitmap = Bitmap.createBitmap(
(ACCOUNT_CHART_TILE_WIDTH_DP * density).toInt(),
(ACCOUNT_CHART_TILE_HEIGHT_DP * density).toInt(),
Bitmap.Config.ARGB_8888
)
AccountChartTileCanvas(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
const val ACCOUNT_CHART_TILE_WIDTH_DP = 112
const val ACCOUNT_CHART_TILE_HEIGHT_DP = 112
}
private class AccountChartTileCanvas(
private val canvas: Canvas,
private val width: Float,
private val height: Float,
private val density: Float,
private val data: AccountSpotlightData
) {
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 = 22f.dp
fun draw() {
drawBackground()
val account = data.account
if (account == null) {
drawOuterRing(0.70f, PRIMARY)
drawSparkline(listOf(0.28f, 0.54f, 0.40f, 0.66f, 0.58f, 0.76f), CYAN)
drawSignalDots(PRIMARY, CYAN, AMBER)
drawMiniBars(listOf(0.42f, 0.72f, 0.55f), PRIMARY)
return
}
val color = account.serviceType.widgetColor()
val risk = riskColor(account.riskScore)
val history = normalizedHistory(account)
drawProviderGlow(color)
drawOuterRing(account.progress ?: history.lastOrNull() ?: 0.56f, color)
drawRiskNeedle(account.riskScore, risk)
drawSparkline(history, color)
drawMiniBars(packageProgress(account, history), color)
drawSignalDots(color, risk, statusColor(account))
}
private fun drawBackground() {
fillPaint.shader = LinearGradient(
0f,
0f,
width,
height,
intArrayOf(Color.rgb(4, 27, 24), Color.rgb(8, 18, 20), Color.rgb(7, 22, 30)),
floatArrayOf(0f, 0.62f, 1f),
Shader.TileMode.CLAMP
)
canvas.drawRoundRect(RectF(0f, 0f, width, height), r, r, fillPaint)
fillPaint.shader = LinearGradient(
0f,
height,
width,
0f,
Color.argb(68, 126, 232, 246),
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(92, 142, 235, 255)
strokePaint.strokeWidth = 1.2f.dp
canvas.drawRoundRect(RectF(1.3f.dp, 1.3f.dp, width - 1.3f.dp, height - 1.3f.dp), r, r, strokePaint)
}
private fun drawProviderGlow(color: Int) {
fillPaint.shader = LinearGradient(
0f,
0f,
width,
height,
Color.argb(60, Color.red(color), Color.green(color), Color.blue(color)),
Color.TRANSPARENT,
Shader.TileMode.CLAMP
)
canvas.drawRoundRect(RectF(5f.dp, 5f.dp, width - 5f.dp, height - 5f.dp), 18f.dp, 18f.dp, fillPaint)
fillPaint.shader = null
}
private fun drawOuterRing(progress: Float, color: Int) {
val cx = width / 2f
val cy = height / 2f
val radius = min(width, height) * 0.34f
val stroke = 8.5f.dp
val arc = RectF(cx - radius, cy - radius, cx + radius, cy + radius)
strokePaint.shader = null
strokePaint.color = Color.argb(48, 255, 255, 255)
strokePaint.strokeWidth = stroke
canvas.drawArc(arc, 135f, 270f, false, strokePaint)
strokePaint.shader = SweepGradient(cx, cy, intArrayOf(color, CYAN, color), null)
canvas.drawArc(arc, 135f, 270f * progress.coerceIn(0.04f, 1f), false, strokePaint)
strokePaint.shader = null
}
private fun drawRiskNeedle(risk: Int, color: Int) {
val cx = width / 2f
val cy = height / 2f
val radius = min(width, height) * 0.42f
val angle = Math.toRadians((135f + 270f * (risk / 100f).coerceIn(0f, 1f)).toDouble())
val innerX = cx + cos(angle).toFloat() * (radius - 10f.dp)
val innerY = cy + sin(angle).toFloat() * (radius - 10f.dp)
val outerX = cx + cos(angle).toFloat() * radius
val outerY = cy + sin(angle).toFloat() * radius
strokePaint.shader = null
strokePaint.color = color
strokePaint.strokeWidth = 3f.dp
canvas.drawLine(innerX, innerY, outerX, outerY, strokePaint)
drawDot(outerX, outerY, 3.8f.dp, color)
}
private fun drawSparkline(values: List<Float>, color: Int) {
val chart = RectF(25f.dp, 39f.dp, width - 25f.dp, height - 37f.dp)
fillPaint.color = Color.argb(32, 255, 255, 255)
canvas.drawRoundRect(chart, 11f.dp, 11f.dp, fillPaint)
val points = values.takeIf { it.size >= 2 } ?: listOf(0.35f, 0.52f, 0.45f, 0.68f)
val linePath = Path()
val fillPath = Path()
points.forEachIndexed { index, value ->
val x = chart.left + index * (chart.width() / (points.size - 1).coerceAtLeast(1))
val y = chart.bottom - value.coerceIn(0.04f, 0.96f) * chart.height()
if (index == 0) {
linePath.moveTo(x, y)
fillPath.moveTo(x, chart.bottom)
fillPath.lineTo(x, y)
} else {
linePath.lineTo(x, y)
fillPath.lineTo(x, y)
}
}
fillPath.lineTo(chart.right, chart.bottom)
fillPath.close()
fillPaint.shader = LinearGradient(
chart.left,
chart.top,
chart.left,
chart.bottom,
Color.argb(72, Color.red(color), Color.green(color), Color.blue(color)),
Color.TRANSPARENT,
Shader.TileMode.CLAMP
)
canvas.drawPath(fillPath, fillPaint)
fillPaint.shader = null
strokePaint.shader = LinearGradient(chart.left, chart.top, chart.right, chart.bottom, color, CYAN, Shader.TileMode.CLAMP)
strokePaint.strokeWidth = 3.2f.dp
canvas.drawPath(linePath, strokePaint)
strokePaint.shader = null
}
private fun drawMiniBars(values: List<Float>, color: Int) {
val bars = values.take(4).ifEmpty { listOf(0.44f, 0.68f, 0.52f) }
val gap = 3f.dp
val x = 23f.dp
val y = height - 22f.dp
val w = (width - x * 2f - gap * (bars.size - 1)) / bars.size
bars.forEachIndexed { index, value ->
val left = x + index * (w + gap)
val progress = value.coerceIn(0.06f, 1f)
fillPaint.shader = null
fillPaint.color = Color.argb(42, 255, 255, 255)
canvas.drawRoundRect(RectF(left, y, left + w, y + 5f.dp), 3f.dp, 3f.dp, fillPaint)
fillPaint.shader = LinearGradient(left, y, left + w, y, color, CYAN, Shader.TileMode.CLAMP)
canvas.drawRoundRect(RectF(left, y, left + w * progress, y + 5f.dp), 3f.dp, 3f.dp, fillPaint)
fillPaint.shader = null
}
}
private fun drawSignalDots(first: Int, second: Int, third: Int) {
drawDot(17f.dp, 16f.dp, 5.4f.dp, first)
drawDot(width - 17f.dp, 16f.dp, 5.4f.dp, second)
drawDot(width - 17f.dp, height - 16f.dp, 4.4f.dp, third)
}
private fun normalizedHistory(account: WidgetAccount): List<Float> {
val values = data.history.mapNotNull { it.remainingBytes }
if (values.size >= 2) {
val minValue = values.min()
val maxValue = values.max()
val range = (maxValue - minValue).coerceAtLeast(1L)
return values.map { ((it - minValue).toFloat() / range.toFloat()).coerceIn(0.08f, 0.96f) }
}
val base = account.progress ?: 0.54f
return listOf(base * 0.62f, base * 0.86f, base * 0.74f, base * 1.12f, base * 0.96f)
.map { it.coerceIn(0.08f, 0.96f) }
}
private fun packageProgress(account: WidgetAccount, history: List<Float>): List<Float> =
data.packages.take(4).map { it.progress ?: 0.14f }.ifEmpty {
listOf(
account.progress ?: history.lastOrNull() ?: 0.55f,
history.getOrNull(history.lastIndex - 1) ?: 0.48f,
history.firstOrNull() ?: 0.38f
)
}
private fun statusColor(account: WidgetAccount): Int =
when {
!account.enabled -> Color.rgb(126, 137, 132)
account.status == AccountStatus.REFRESHING -> CYAN
account.status != AccountStatus.ACTIVE -> ERROR
account.riskScore >= 55 -> riskColor(account.riskScore)
else -> PRIMARY
}
private fun drawDot(cx: Float, cy: Float, radius: Float, color: Int) {
fillPaint.shader = null
fillPaint.color = color
canvas.drawCircle(cx, cy, radius, fillPaint)
}
private val Float.dp: Float
get() = this * density
}
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(
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)
}
}
@@ -0,0 +1,313 @@
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
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<WidgetAccount>,
val providers: List<WidgetProviderStat>,
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<WidgetAccount> = 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
)
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>,
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<WidgetAccount> { 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"
)
}
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(
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 UsagePackageEntity.toWidgetPackage(): WidgetPackageStat =
WidgetPackageStat(
name = name,
remainingLabel = remainingDisplay,
progress = remainingProgress(remainingBytes, totalBytes),
expiresAtText = expiresAtText
)
private fun buildProviderStats(
summaries: List<AccountSummary>,
totalRemaining: Long?
): List<WidgetProviderStat> =
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<WidgetAccount>): Pair<String, String> {
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 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
}
@@ -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<out BaseRemainingWidgetProvider>
) {
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
}
}
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/remaining_widget_root"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/remaining_widget_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="false"
android:contentDescription="@string/widget_content_description"
android:scaleType="fitXY" />
<TextView
android:id="@+id/remaining_widget_fallback"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="@string/widget_fallback"
android:textColor="@android:color/white"
android:textSize="16sp"
android:textStyle="bold"
android:visibility="gone" />
</FrameLayout>
-4
View File
@@ -2,8 +2,4 @@
<resources> <resources>
<color name="remaining_splash_background">#0D1117</color> <color name="remaining_splash_background">#0D1117</color>
<color name="remaining_splash_icon_background">#151B23</color> <color name="remaining_splash_icon_background">#151B23</color>
<color name="remaining_primary">#8FD8FF</color>
<color name="remaining_success">#3DDC84</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
</resources> </resources>
+19
View File
@@ -1,3 +1,22 @@
<resources> <resources>
<string name="app_name">Remaining</string> <string name="app_name">Remaining</string>
<string name="widget_content_description">Remaining usage widget</string>
<string name="widget_fallback">Open Remaining</string>
<string name="widget_command_center_name">Remaining Command Center</string>
<string name="widget_command_center_description">Overall quota ring, health counters, and next action.</string>
<string name="widget_provider_mix_name">Remaining Provider Mix</string>
<string name="widget_provider_mix_description">Provider-level quota share and service health chart.</string>
<string name="widget_watchlist_name">Remaining Watchlist Heatmap</string>
<string name="widget_watchlist_description">Risk heatmap for captcha, auth, low data, expiry, and stale refreshes.</string>
<string name="widget_refresh_timeline_name">Remaining Refresh Timeline</string>
<string name="widget_refresh_timeline_description">Freshness and next-refresh timeline across active accounts.</string>
<string name="widget_account_matrix_name">Remaining Account Matrix</string>
<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>
<string name="widget_account_chart_tile_name">Remaining Account Chart Tile</string>
<string name="widget_account_chart_tile_description">One-cell selected-account widget with only visual quota, trend, risk, and package signals.</string>
</resources> </resources>
+2 -11
View File
@@ -1,13 +1,4 @@
<?xml version="1.0" encoding="utf-8"?><!-- <?xml version="1.0" encoding="utf-8"?>
Sample backup rules file; uncomment and customize as necessary.
See https://developer.android.com/guide/topics/data/autobackup
for details.
Note: This file is ignored for devices older than API 31
See https://developer.android.com/about/versions/12/backup-restore
-->
<full-backup-content> <full-backup-content>
<!-- <exclude domain="root" path="." />
<include domain="sharedpref" path="."/>
<exclude domain="sharedpref" path="device.xml"/>
-->
</full-backup-content> </full-backup-content>
+3 -13
View File
@@ -1,19 +1,9 @@
<?xml version="1.0" encoding="utf-8"?><!-- <?xml version="1.0" encoding="utf-8"?>
Sample data extraction rules file; uncomment and customize as necessary.
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
for details.
-->
<data-extraction-rules> <data-extraction-rules>
<cloud-backup> <cloud-backup>
<!-- TODO: Use <include> and <exclude> to control what is backed up. <exclude domain="root" path="." />
<include .../>
<exclude .../>
-->
</cloud-backup> </cloud-backup>
<!--
<device-transfer> <device-transfer>
<include .../> <exclude domain="root" path="." />
<exclude .../>
</device-transfer> </device-transfer>
-->
</data-extraction-rules> </data-extraction-rules>
@@ -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_chart_tile_description"
android:initialLayout="@layout/remaining_widget_chart"
android:minResizeHeight="56dp"
android:minResizeWidth="56dp"
android:minHeight="72dp"
android:minWidth="72dp"
android:resizeMode="horizontal|vertical"
android:targetCellHeight="1"
android:targetCellWidth="1"
android:updatePeriodMillis="1800000"
android:widgetCategory="home_screen" />
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/widget_account_matrix_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" />
@@ -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" />
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/widget_command_center_description"
android:initialLayout="@layout/remaining_widget_chart"
android:minResizeHeight="140dp"
android:minResizeWidth="260dp"
android:minHeight="160dp"
android:minWidth="320dp"
android:resizeMode="horizontal|vertical"
android:targetCellHeight="2"
android:targetCellWidth="4"
android:updatePeriodMillis="1800000"
android:widgetCategory="home_screen" />
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/widget_compact_signal_description"
android:initialLayout="@layout/remaining_widget_chart"
android:minResizeHeight="90dp"
android:minResizeWidth="200dp"
android:minHeight="100dp"
android:minWidth="220dp"
android:resizeMode="horizontal|vertical"
android:targetCellHeight="1"
android:targetCellWidth="3"
android:updatePeriodMillis="1800000"
android:widgetCategory="home_screen" />
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/widget_provider_mix_description"
android:initialLayout="@layout/remaining_widget_chart"
android:minResizeHeight="140dp"
android:minResizeWidth="260dp"
android:minHeight="160dp"
android:minWidth="320dp"
android:resizeMode="horizontal|vertical"
android:targetCellHeight="2"
android:targetCellWidth="4"
android:updatePeriodMillis="1800000"
android:widgetCategory="home_screen" />
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/widget_refresh_timeline_description"
android:initialLayout="@layout/remaining_widget_chart"
android:minResizeHeight="140dp"
android:minResizeWidth="260dp"
android:minHeight="160dp"
android:minWidth="320dp"
android:resizeMode="horizontal|vertical"
android:targetCellHeight="2"
android:targetCellWidth="4"
android:updatePeriodMillis="1800000"
android:widgetCategory="home_screen" />
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/widget_watchlist_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" />
@@ -1,17 +0,0 @@
package net.rodakot.remaining
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
@@ -73,6 +73,42 @@ class ParserTest {
assertEquals("12.50 GB", snapshot.remainingDisplay) assertEquals("12.50 GB", snapshot.remainingDisplay)
} }
@Test
fun tciUsesTrafficValueAfterReservedTrafficLabel() {
val snapshot = TciHtmlParser.parseReservedTraffic(
"""
<html>
<body>
<div>
<h5>میزان ترافیک مصرفی شما ۸۸ گیگابایت</h5>
<h5>میزان ترافیک رزرو شما ۱۲٫۵ گیگابایت</h5>
</div>
</body>
</html>
""".trimIndent()
)
assertEquals("12.50 GB", snapshot.remainingDisplay)
}
@Test
fun tciReadsReservedTrafficFromFollowingSibling() {
val snapshot = TciHtmlParser.parseReservedTraffic(
"""
<html>
<body>
<div>
<h5>میزان ترافیک رزرو شما</h5>
<span>۷۵۰ مگابایت</span>
</div>
</body>
</html>
""".trimIndent()
)
assertEquals("750 MB", snapshot.remainingDisplay)
}
@Test @Test
fun trafficFormattingUsesMegabytesBelowOneGigabyte() { fun trafficFormattingUsesMegabytesBelowOneGigabyte() {
assertEquals("512 MB", (512L * 1024L * 1024L).asTrafficDisplay()) assertEquals("512 MB", (512L * 1024L * 1024L).asTrafficDisplay())
+2 -2
View File
@@ -14,7 +14,7 @@ curl 'https://my.mci.ir/api/idm/v1/auth' \
-H 'Referer: https://my.mci.ir' \ -H 'Referer: https://my.mci.ir' \
-H 'platform: WEB' \ -H 'platform: WEB' \
-H 'version: 1.29.0' \ -H 'version: 1.29.0' \
--data-raw '{"username":"9123456789","credential":"xxxx","credential_type":"PASSWORD"}' --data-raw '{"username":"YOUR_MCI_USERNAME","credential":"YOUR_PASSWORD","credential_type":"PASSWORD"}'
``` ```
### response ### response
@@ -46,7 +46,7 @@ curl 'https://my.mci.ir/api/idm/v1/auth' \
-H 'Referer: https://my.mci.ir' \ -H 'Referer: https://my.mci.ir' \
-H 'platform: WEB' \ -H 'platform: WEB' \
-H 'version: 1.29.0' \ -H 'version: 1.29.0' \
--data-raw '{"username":"9123456789","credential_type":"REFRESH_TOKEN","credential":"eyJhbG..."}' --data-raw '{"username":"YOUR_MCI_USERNAME","credential_type":"REFRESH_TOKEN","credential":"eyJhbG..."}'
``` ```
### response ### response