Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 48 additions & 68 deletions app/src/main/java/com/leanbitlab/lwidget/AwidgetProvider.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Bundle
import android.util.Log
import android.widget.RemoteViews
import com.leanbitlab.lwidget.calendar.CalendarFetcher
import com.leanbitlab.lwidget.render.WidgetRenderer
import com.leanbitlab.lwidget.stats.SystemStatsFetcher
import com.leanbitlab.lwidget.tasks.TasksFetcher
Expand All @@ -19,9 +20,9 @@ import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import java.time.LocalDate
import java.util.concurrent.atomic.AtomicBoolean

enum class UpdateMode {
Expand All @@ -33,6 +34,8 @@ class AwidgetProvider : AppWidgetProvider() {
private val receiverScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)

override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
// Safety net for the one-shot refresh alarm: onUpdate also runs on the 30-minute updatePeriodMillis
scheduleWork(context)
StepCounterService.startServiceIfEnabled(context)
runAsync("onUpdate") {
for (appWidgetId in appWidgetIds) {
Expand Down Expand Up @@ -121,7 +124,12 @@ class AwidgetProvider : AppWidgetProvider() {
val globalPrefs = context.getSharedPreferences("com.leanbitlab.lwidget.PREFS", Context.MODE_PRIVATE)
val current = FallbackPreferences(widgetPrefs, globalPrefs).getInt("events_page", 0)
widgetPrefs.edit().putInt("events_page", if (current == 1) 0 else 1).apply()
updateAppWidget(context, AppWidgetManager.getInstance(context), widgetId, UpdateMode.EVENTS_PAGE)
val appWidgetManager = AppWidgetManager.getInstance(context)
updateAppWidget(context, appWidgetManager, widgetId, UpdateMode.EVENTS_PAGE)
// Once the switch animation is done, replace the cached setDisplayedChild with a full render
// (page by visibility); else every later partial update would replay the animation.
delay(PAGE_SWITCH_SETTLE_MS)
updateAppWidget(context, appWidgetManager, widgetId, UpdateMode.FULL)
}
return
}
Expand Down Expand Up @@ -154,6 +162,8 @@ class AwidgetProvider : AppWidgetProvider() {
appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.FULL) }
}
intent.action == ACTION_BATTERY_UPDATE -> {
// Re-arm the one-shot refresh (also pushes it back while the service keeps us fresh)
if (appWidgetIds.isNotEmpty()) scheduleWork(context)
appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.TICK) }
}
intent.action == StepCounterService.ACTION_STEP_UPDATE -> {
Expand All @@ -180,16 +190,7 @@ class AwidgetProvider : AppWidgetProvider() {

private fun cancelWork(context: Context) {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, AwidgetProvider::class.java).apply {
action = ACTION_BATTERY_UPDATE
}
val pendingIntent = PendingIntent.getBroadcast(
context,
500,
intent,
PendingIntent.FLAG_IMMUTABLE
)
alarmManager.cancel(pendingIntent)
alarmManager.cancel(refreshAlarmIntent(context))
}

companion object {
Expand All @@ -199,31 +200,45 @@ class AwidgetProvider : AppWidgetProvider() {
/** goAsync() broadcasts must finish well inside the ~10s system limit. */
private const val ASYNC_BUDGET_MS = 8_000L

/** Longer than the Events/Tasks page animation (events_page_in: 150 ms offset + 170 ms). */
private const val PAGE_SWITCH_SETTLE_MS = 600L

/** The refresh alarm's intent; scheduleWork and cancelWork must build the same one. */
private fun refreshAlarmIntent(context: Context): PendingIntent = PendingIntent.getBroadcast(
context,
500,
Intent(context, AwidgetProvider::class.java).apply { action = ACTION_BATTERY_UPDATE },
PendingIntent.FLAG_IMMUTABLE
)

const val DEFAULT_INTERVAL_MINUTES = 5f
private const val CHARGING_INTERVAL_MS = 60_000L
private const val ALARM_WINDOW_MS = 60_000L

/** Time to the next refresh: one minute while charging (the level moves fast and power is free), else the user's interval. */
internal fun refreshIntervalMillis(context: Context): Long {
val battery = context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
if (battery?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) == BatteryManager.BATTERY_STATUS_CHARGING) {
return CHARGING_INTERVAL_MS
}
val prefs = context.getSharedPreferences("com.leanbitlab.lwidget.PREFS", Context.MODE_PRIVATE)
val intervalMinutes = prefs.getFloat("update_interval", DEFAULT_INTERVAL_MINUTES)
return (intervalMinutes * 60f * 1000f).toLong().coerceAtLeast(60_000L)
}

/**
* (Re)schedules the periodic refresh. setInexactRepeating replaces any existing alarm
* for the same PendingIntent, so this is safe to call whenever the interval changes.
* Arms the next refresh. Without the keep-alive service this timer is the only thing that updates
* battery, so it is a one-shot alarm re-armed on every battery update: the widget is at most one
* interval old. An inexact repeating alarm slipped up to 75% of an interval each cycle.
* RTC never wakes the phone, so the timer costs nothing while it sleeps.
*/
fun scheduleWork(context: Context) {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, AwidgetProvider::class.java).apply {
action = ACTION_BATTERY_UPDATE
}
val pendingIntent = PendingIntent.getBroadcast(
context,
500,
intent,
PendingIntent.FLAG_IMMUTABLE
)

val prefs = context.getSharedPreferences("com.leanbitlab.lwidget.PREFS", Context.MODE_PRIVATE)
val intervalMinutes = prefs.getFloat("update_interval", 15f)
val intervalMillis = (intervalMinutes * 60f * 1000f).toLong().coerceAtLeast(60000L)

alarmManager.setInexactRepeating(
alarmManager.setWindow(
AlarmManager.RTC,
System.currentTimeMillis() + intervalMillis,
intervalMillis,
pendingIntent
System.currentTimeMillis() + refreshIntervalMillis(context),
ALARM_WINDOW_MS,
refreshAlarmIntent(context)
)
}

Expand All @@ -236,41 +251,6 @@ class AwidgetProvider : AppWidgetProvider() {
const val PERMISSION_READ_TASKS_ORG = TasksFetcher.PERMISSION_READ_TASKS_ORG
const val PERMISSION_READ_TASKS_ASTRID = TasksFetcher.PERMISSION_READ_TASKS_ASTRID

data class EventInfo(
val id: Long,
val title: String,
val begin: Long,
val end: Long,
val isLocal: Boolean,
val isAllDay: Boolean = false
)

@Suppress("UnusedPrivateMember")
private fun getFormatter(pattern: String) = CalendarFetcher.getFormatter(pattern)

internal fun isEventRelevant(event: EventInfo, now: Long, today: LocalDate): Boolean {
val mapped = CalendarFetcher.EventInfo(event.id, event.title, event.begin, event.end, event.isLocal, event.isAllDay)
return CalendarFetcher.isEventRelevant(mapped, now, today)
}

internal fun formatEventTimeText(
context: Context,
event: EventInfo,
today: LocalDate = LocalDate.now(),
showDayAbbr: Boolean = true,
is24Hour: Boolean = false
): String {
val mapped = CalendarFetcher.EventInfo(event.id, event.title, event.begin, event.end, event.isLocal, event.isAllDay)
return CalendarFetcher.formatEventTimeText(context, mapped, today, showDayAbbr, is24Hour)
}

internal fun calculateDailySteps(
totalSteps: Float,
baselineSteps: Float,
savedDate: String,
today: String = LocalDate.now().toString()
): Int = SystemStatsFetcher.calculateDailySteps(totalSteps, baselineSteps, savedDate, today)

fun buildAppWidgetRemoteViews(context: Context, appWidgetId: Int, mode: UpdateMode = UpdateMode.FULL): RemoteViews =
WidgetRenderer.buildRemoteViews(context, appWidgetId, mode)

Expand Down
24 changes: 16 additions & 8 deletions app/src/main/java/com/leanbitlab/lwidget/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ class MainActivity : AppCompatActivity() {
else -> !isSystemInNightMode
}

val useDynamicColors = prefs.getBoolean("use_dynamic_colors", true)
val useDynamicColors = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S && prefs.getBoolean("use_dynamic_colors", true)
val bgColorIdx = prefs.getInt("bg_color_idx", 0)
val bgOpacity = prefs.getFloat("bg_opacity", 85f)
val textPrimaryIdx = prefs.getInt("text_color_primary_idx", 0)
Expand Down Expand Up @@ -321,8 +321,6 @@ class MainActivity : AppCompatActivity() {
ContextCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_GRANTED
if (hasActivityPerm) {
prefs.edit().putBoolean("show_steps", true).apply()
val globalPrefs = getSharedPreferences("com.leanbitlab.lwidget.PREFS", Context.MODE_PRIVATE)
globalPrefs.edit().putBoolean("show_steps", true).apply()
val stepsToggle = findViewById<View>(R.id.row_steps_toggle)
stepsToggle?.findViewById<com.google.android.material.switchmaterial.SwitchMaterial>(R.id.row_switch)?.isChecked = true
findViewById<View>(R.id.row_steps_size)?.visibility = View.VISIBLE
Expand Down Expand Up @@ -436,7 +434,7 @@ class MainActivity : AppCompatActivity() {
bindNestedCard(R.id.header_changelog, "", R.id.content_changelog, "section_changelog_expanded", R.id.chevron_changelog)

// Advanced Section
bindSlider(R.id.row_update_interval, getString(R.string.row_update_interval), "update_interval", 15f, 1f, 60f, "m") {
bindSlider(R.id.row_update_interval, getString(R.string.row_update_interval), "update_interval", AwidgetProvider.DEFAULT_INTERVAL_MINUTES, 1f, 60f, "m") {
// The repeating alarm only reads the interval when scheduled, so reschedule it now
val ids = AppWidgetManager.getInstance(this).getAppWidgetIds(ComponentName(this, AwidgetProvider::class.java))
if (ids.isNotEmpty()) AwidgetProvider.scheduleWork(this)
Expand All @@ -452,11 +450,11 @@ class MainActivity : AppCompatActivity() {
tvVersion.text = getString(R.string.changelog_version, versionName)

findViewById<View>(R.id.tv_website_link)?.setOnClickListener {
CustomTabsIntent.Builder().build().launchUrl(this@MainActivity, android.net.Uri.parse("https://leanbitlab.github.io/LeanBitLab/"))
openUrl("https://leanbitlab.github.io/LeanBitLab/")
}

findViewById<View>(R.id.tv_github_link).setOnClickListener {
CustomTabsIntent.Builder().build().launchUrl(this@MainActivity, android.net.Uri.parse("https://github.com/LeanBitLab/Lwidget"))
openUrl("https://github.com/LeanBitLab/Lwidget")
}

listOf(
Expand All @@ -467,12 +465,12 @@ class MainActivity : AppCompatActivity() {
R.id.tv_youtube_link to "https://www.youtube.com/@LeanBitLab"
).forEach { (id, url) ->
findViewById<View>(id).setOnClickListener {
CustomTabsIntent.Builder().build().launchUrl(this@MainActivity, android.net.Uri.parse(url))
openUrl(url)
}
}

findViewById<View>(R.id.tv_privacy_policy).setOnClickListener {
CustomTabsIntent.Builder().build().launchUrl(this@MainActivity, android.net.Uri.parse("https://github.com/LeanBitLab/Lwidget/wiki/Privacy-Policy"))
openUrl("https://github.com/LeanBitLab/Lwidget/wiki/Privacy-Policy")
}
}

Expand Down Expand Up @@ -525,3 +523,13 @@ class MainActivity : AppCompatActivity() {
}

private const val WIDGET_UPDATE_DEBOUNCE_MS = 120L

/** Opens [url] in a Custom Tab; logs instead of crashing when no browser can handle it. */
internal fun MainActivity.openUrl(url: String) {
try {
CustomTabsIntent.Builder().build().launchUrl(this, android.net.Uri.parse(url))
} catch (e: Exception) {
// No browser (ActivityNotFoundException) or a handler that refuses us (SecurityException)
Log.w("MainActivity", "Could not open $url", e)
}
}
39 changes: 9 additions & 30 deletions app/src/main/java/com/leanbitlab/lwidget/SettingsAccordion.kt
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,6 @@ internal fun MainActivity.bindFoldedSection(
boldRowId: Int? = null,
isContent: Boolean = false,
subSettingsContainerId: Int? = null,
validateToggle: ((Boolean) -> Boolean)? = null,
onChanged: ((Boolean) -> Unit)? = null
): SwitchMaterial {
val header = findViewById<View>(headerId)
Expand Down Expand Up @@ -160,14 +159,6 @@ internal fun MainActivity.bindFoldedSection(

// Internal listener - handles visibility with animation
toggleSwitch.setOnCheckedChangeListener { _, isChecked ->
if (isChecked && !checkLimit()) {
toggleSwitch.isChecked = false
return@setOnCheckedChangeListener
}
if (validateToggle?.invoke(isChecked) == false) {
toggleSwitch.isChecked = !isChecked
return@setOnCheckedChangeListener
}
prefs.edit().putBoolean(prefShowKey, isChecked).apply()
subSettings?.alpha = if (isChecked) 1.0f else 0.4f
updateToggleCardStyle(toggleCard, isChecked)
Expand Down Expand Up @@ -213,8 +204,8 @@ internal fun MainActivity.bindFoldedSection(
}
}

// Selector row setup (skip world clock timezone - uses custom search layout)
if (selectorRowId != null && selectorOptions != null && prefSelectorKey != null && prefSelectorKey != "world_clock_zone_str") {
// Selector row setup (the world clock time zone uses bindTimezoneSearch instead)
if (selectorRowId != null && selectorOptions != null && prefSelectorKey != null) {
val selectorRowInner = findViewById<View>(selectorRowId)
val autoCompleteTextView = selectorRowInner.findViewById<AutoCompleteTextView>(R.id.row_value)
val selectorLabel = selectorRowInner.findViewById<TextView>(R.id.row_label)
Expand All @@ -223,25 +214,13 @@ internal fun MainActivity.bindFoldedSection(
val adapter = android.widget.ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, selectorOptions)
autoCompleteTextView.setAdapter(adapter)

if (prefSelectorKey == "world_clock_zone_str") {
val currentVal = prefs.getString(prefSelectorKey, "UTC") ?: "UTC"
autoCompleteTextView.setText(currentVal, false)
autoCompleteTextView.setOnItemClickListener { _, _, position, _ ->
val selected = selectorOptions.getOrElse(position) { "UTC" }
prefs.edit().putString(prefSelectorKey, selected).apply()
updateWidget()
selectorRowInner.clearFocus()
autoCompleteTextView.clearFocus()
}
} else {
val currentIdx = prefs.getInt(prefSelectorKey, defSelectorIdx)
autoCompleteTextView.setText(selectorOptions.getOrElse(currentIdx) { selectorOptions[defSelectorIdx] }, false)
autoCompleteTextView.setOnItemClickListener { _, _, position, _ ->
prefs.edit().putInt(prefSelectorKey, position).apply()
updateWidget()
selectorRowInner.clearFocus()
autoCompleteTextView.clearFocus()
}
val currentIdx = prefs.getInt(prefSelectorKey, defSelectorIdx)
autoCompleteTextView.setText(selectorOptions.getOrElse(currentIdx) { selectorOptions[defSelectorIdx] }, false)
autoCompleteTextView.setOnItemClickListener { _, _, position, _ ->
prefs.edit().putInt(prefSelectorKey, position).apply()
updateWidget()
selectorRowInner.clearFocus()
autoCompleteTextView.clearFocus()
}

// Clear focus/dropdown shade when dismissed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ internal fun MainActivity.setupThemeSection(colorOptions: List<String>) {
outlineSliderRow.visibility = if (prefs.getInt("outline_color_idx", 0) == 2) View.VISIBLE else View.GONE

// Apply initial dynamic colors visibility
updateColorVisibility(prefs.getBoolean("use_dynamic_colors", true))
updateColorVisibility(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S && prefs.getBoolean("use_dynamic_colors", true))

// Font selector
bindSelector(R.id.row_font, getString(R.string.section_font), "font_style", listOf(
Expand Down
32 changes: 1 addition & 31 deletions app/src/main/java/com/leanbitlab/lwidget/SettingsBinders.kt
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,6 @@ internal fun MainActivity.bindToggle(
if (buttonView.isPressed) {
buttonView.performHapticFeedback(android.view.HapticFeedbackConstants.CLOCK_TICK)
}
if (isChecked && !checkLimit()) {
switch.isChecked = false
return@setOnCheckedChangeListener
}
prefs.edit().putBoolean(prefShowKey, isChecked).apply()
onChanged?.invoke(isChecked)
updateWidget()
Expand Down Expand Up @@ -101,15 +97,7 @@ internal fun MainActivity.bindSelector(
val adapter = android.widget.ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, options)
autoCompleteTextView.setAdapter(adapter)

if (prefKey == "world_clock_zone_str") {
val currentVal = prefs.getString(prefKey, "UTC") ?: "UTC"
autoCompleteTextView.setText(currentVal, false)
autoCompleteTextView.setOnItemClickListener { _, _, position, _ ->
val selected = options.getOrElse(position) { "UTC" }
prefs.edit().putString(prefKey, selected).apply()
updateWidget()
}
} else if (prefKey == "clock_app_package" || prefKey == "calendar_app_package") {
if (prefKey == "clock_app_package" || prefKey == "calendar_app_package") {
val appPackages = if (prefKey == "clock_app_package") clockAppPackages else calendarAppPackages
val currentVal = prefs.getString(prefKey, "default") ?: "default"
val currentIdx = appPackages.indexOf(currentVal).coerceAtLeast(0)
Expand Down Expand Up @@ -233,24 +221,6 @@ internal fun MainActivity.updateFeatureRowVisibility(switch: SwitchMaterial, isC
}
}

internal fun MainActivity.checkLimit(): Boolean {
// Subset Limit: items in the right-side widget column
val subsetCount = contentSwitches.count {
it.isChecked && (it.tag in listOf("battery", "weather_condition", "temp", "data", "storage", "ram", "steps", "screen_time"))
}

if (subsetCount > 8) {
com.google.android.material.snackbar.Snackbar.make(
findViewById(R.id.fab_update),
getString(R.string.error_max_subset_items),
com.google.android.material.snackbar.Snackbar.LENGTH_SHORT
).show()
return false
}

return true
}

internal fun MainActivity.updateToggleAvailability() {
// Limit removed
// Ensure all are enabled
Expand Down
Loading
Loading