diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..62071c3
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,44 @@
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: ci-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ verify:
+ runs-on: ubuntu-latest
+ env:
+ GRADLE_OPTS: -Dorg.gradle.jvmargs="-Xmx4g -XX:MaxMetaspaceSize=1g -XX:+HeapDumpOnOutOfMemoryError"
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Check string resources
+ run: python3 scripts/check_strings.py
+
+ - name: Set up Java
+ uses: actions/setup-java@v4
+ with:
+ distribution: 'zulu'
+ java-version: '17'
+ cache: 'gradle'
+
+ - name: Make Gradle Wrapper Executable
+ run: chmod +x gradlew
+
+ - name: Unit tests
+ run: ./gradlew test
+
+ - name: Lint (fails on errors only)
+ run: ./gradlew lintDebug
+
+ - name: Build debug APK
+ run: ./gradlew assembleDebug
diff --git a/.gitignore b/.gitignore
index c5cf114..6890abe 100644
--- a/.gitignore
+++ b/.gitignore
@@ -63,7 +63,14 @@ GEMINI.md
.antigravitycli/
.antigravityignore
CLAUDE.md
+CLAUDE.local.md
.claude/
+.claudeignore
+.mcp.json
+.kilocode/
+.trae/
+.zed/
+.android/
.cline/
.clinerules
.clinerules/
diff --git a/README.md b/README.md
index 24fe5bc..171d2c0 100644
--- a/README.md
+++ b/README.md
@@ -35,16 +35,16 @@ You can download the latest release from the [Play Store](https://play.google.co
-  |
-  |
-  |
-  |
+  |
+  |
+  |
+  |
-  |
-  |
-  |
-  |
+  |
+  |
+  |
+  |
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 938637d..98be847 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -26,6 +26,7 @@ android {
testOptions {
unitTests.isReturnDefaultValues = true
+ unitTests.isIncludeAndroidResources = true
}
signingConfigs {
@@ -76,7 +77,9 @@ android {
}
lint {
disable += "MissingTranslation"
- abortOnError = false
+ // Lint currently has 0 errors; keep it that way. Warnings stay informational.
+ // checkReleaseBuilds stays off so release/F-Droid assemble never runs lint.
+ abortOnError = true
checkReleaseBuilds = false
}
}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 8450f92..29480b6 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -1,7 +1,6 @@
-
diff --git a/app/src/main/java/com/leanbitlab/lwidget/AwidgetProvider.kt b/app/src/main/java/com/leanbitlab/lwidget/AwidgetProvider.kt
index 336e678..8c0678e 100644
--- a/app/src/main/java/com/leanbitlab/lwidget/AwidgetProvider.kt
+++ b/app/src/main/java/com/leanbitlab/lwidget/AwidgetProvider.kt
@@ -14,11 +14,14 @@ import com.leanbitlab.lwidget.calendar.CalendarFetcher
import com.leanbitlab.lwidget.render.WidgetRenderer
import com.leanbitlab.lwidget.stats.SystemStatsFetcher
import com.leanbitlab.lwidget.tasks.TasksFetcher
+import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
+import kotlinx.coroutines.withTimeoutOrNull
import java.time.LocalDate
+import java.util.concurrent.atomic.AtomicBoolean
enum class UpdateMode {
FULL, TICK, CALENDAR_ONLY, TASKS_ONLY, ALARM_ONLY, STEPS_ONLY
@@ -30,17 +33,38 @@ class AwidgetProvider : AppWidgetProvider() {
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
StepCounterService.startServiceIfEnabled(context)
+ runAsync("onUpdate") {
+ for (appWidgetId in appWidgetIds) {
+ updateAppWidget(context, appWidgetManager, appWidgetId, UpdateMode.FULL)
+ }
+ }
+ }
+
+ /**
+ * Runs [block] off the main thread while holding the broadcast open via goAsync().
+ * The broadcast is always released within [ASYNC_BUDGET_MS], even if a data source hangs,
+ * so a slow calendar/tasks provider can never push the receiver past the system limit.
+ */
+ private fun runAsync(tag: String, block: suspend () -> Unit) {
val pendingResult = goAsync()
+ val finished = AtomicBoolean(false)
+ fun finishOnce() {
+ if (finished.compareAndSet(false, true)) pendingResult.finish()
+ }
receiverScope.launch {
- try {
- for (appWidgetId in appWidgetIds) {
- updateAppWidget(context, appWidgetManager, appWidgetId, UpdateMode.FULL)
+ val work = launch {
+ try {
+ block()
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Throwable) {
+ Log.e(TAG, "Error during $tag", e)
}
- } catch (e: Throwable) {
- Log.e(TAG, "Error during onUpdate", e)
- } finally {
- pendingResult.finish()
}
+ if (withTimeoutOrNull(ASYNC_BUDGET_MS) { work.join() } == null) {
+ Log.w(TAG, "$tag exceeded ${ASYNC_BUDGET_MS}ms; releasing broadcast")
+ }
+ finishOnce()
}
}
@@ -52,15 +76,8 @@ class AwidgetProvider : AppWidgetProvider() {
) {
super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions)
StepCounterService.startServiceIfEnabled(context)
- val pendingResult = goAsync()
- receiverScope.launch {
- try {
- updateAppWidget(context, appWidgetManager, appWidgetId, UpdateMode.FULL)
- } catch (e: Throwable) {
- Log.e(TAG, "Error during onAppWidgetOptionsChanged", e)
- } finally {
- pendingResult.finish()
- }
+ runAsync("onAppWidgetOptionsChanged") {
+ updateAppWidget(context, appWidgetManager, appWidgetId, UpdateMode.FULL)
}
}
@@ -112,39 +129,32 @@ class AwidgetProvider : AppWidgetProvider() {
AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED,
"nodomain.freeyourgadget.gadgetbridge.ACTION_GENERIC_WEATHER"
)) {
- val pendingResult = goAsync()
- receiverScope.launch {
- try {
- when {
- isBootOrReplaced || intent.action == Intent.ACTION_CONFIGURATION_CHANGED -> {
- scheduleWork(context)
- appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.FULL) }
- }
- intent.action == ACTION_BATTERY_UPDATE -> {
- appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.TICK) }
- }
- intent.action == StepCounterService.ACTION_STEP_UPDATE -> {
- appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.STEPS_ONLY) }
- }
- intent.action == AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED -> {
- appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.ALARM_ONLY) }
- }
- intent.action == Intent.ACTION_PROVIDER_CHANGED -> {
- val uri = intent.data
- if (uri != null && uri.authority == "org.tasks") {
- appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.TASKS_ONLY) }
- } else {
- appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.CALENDAR_ONLY) }
- }
- }
- intent.action == "nodomain.freeyourgadget.gadgetbridge.ACTION_GENERIC_WEATHER" -> {
- appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.FULL) }
+ runAsync("broadcast ${intent.action}") {
+ when {
+ isBootOrReplaced || intent.action == Intent.ACTION_CONFIGURATION_CHANGED -> {
+ scheduleWork(context)
+ appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.FULL) }
+ }
+ intent.action == ACTION_BATTERY_UPDATE -> {
+ appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.TICK) }
+ }
+ intent.action == StepCounterService.ACTION_STEP_UPDATE -> {
+ appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.STEPS_ONLY) }
+ }
+ intent.action == AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED -> {
+ appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.ALARM_ONLY) }
+ }
+ intent.action == Intent.ACTION_PROVIDER_CHANGED -> {
+ val uri = intent.data
+ if (uri != null && uri.authority == "org.tasks") {
+ appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.TASKS_ONLY) }
+ } else {
+ appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.CALENDAR_ONLY) }
}
}
- } catch (e: Throwable) {
- Log.e(TAG, "Error handling broadcast ${intent.action}", e)
- } finally {
- pendingResult.finish()
+ intent.action == "nodomain.freeyourgadget.gadgetbridge.ACTION_GENERIC_WEATHER" -> {
+ appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.FULL) }
+ }
}
}
}
@@ -192,6 +202,9 @@ class AwidgetProvider : AppWidgetProvider() {
private const val TAG = "WidgetLife"
+ /** goAsync() broadcasts must finish well inside the ~10s system limit. */
+ private const val ASYNC_BUDGET_MS = 8_000L
+
const val ACTION_NOOP = "com.leanbitlab.lwidget.ACTION_NOOP"
const val ACTION_BATTERY_UPDATE = SystemStatsFetcher.ACTION_BATTERY_UPDATE
const val PERMISSION_READ_TASKS_ORG = TasksFetcher.PERMISSION_READ_TASKS_ORG
diff --git a/app/src/main/java/com/leanbitlab/lwidget/MainActivity.kt b/app/src/main/java/com/leanbitlab/lwidget/MainActivity.kt
index 37501f6..4c4470b 100644
--- a/app/src/main/java/com/leanbitlab/lwidget/MainActivity.kt
+++ b/app/src/main/java/com/leanbitlab/lwidget/MainActivity.kt
@@ -55,69 +55,12 @@ import androidx.transition.AutoTransition
import androidx.transition.TransitionManager
import com.google.android.material.appbar.AppBarLayout
-// Data class for reorderable items
-data class ReorderItem(
- val key: String, // e.g. "show_battery"
- val label: String, // e.g. "Battery"
- var enabled: Boolean
-)
-
-// Adapter for reorder RecyclerView
-class ReorderAdapter(
- private val items: MutableList,
- private val onStartDrag: (RecyclerView.ViewHolder) -> Unit
-) : RecyclerView.Adapter() {
-
- class ViewHolder(val view: android.view.View) : RecyclerView.ViewHolder(view) {
- val handle: android.widget.ImageView = view.findViewById(R.id.reorder_handle)
- val name: TextView = view.findViewById(R.id.reorder_item_name)
- val status: TextView? = view.findViewById(R.id.reorder_item_status)
- }
-
- override fun onCreateViewHolder(parent: android.view.ViewGroup, viewType: Int): ViewHolder {
- val view = android.view.LayoutInflater.from(parent.context)
- .inflate(R.layout.settings_reorder_item, parent, false)
- return ViewHolder(view)
- }
-
- override fun onBindViewHolder(holder: ViewHolder, position: Int) {
- val item = items[position]
- holder.name.text = item.label
- if (item.enabled) {
- holder.view.alpha = 1.0f
- holder.status?.visibility = android.view.View.GONE
- } else {
- holder.view.alpha = 0.4f
- holder.status?.visibility = android.view.View.VISIBLE
- }
-
- holder.handle.setOnTouchListener { v, event ->
- if (event.actionMasked == MotionEvent.ACTION_DOWN) {
- v.performHapticFeedback(android.view.HapticFeedbackConstants.CONTEXT_CLICK)
- onStartDrag(holder)
- true
- } else {
- false
- }
- }
- }
-
- override fun getItemCount() = items.size
-
- fun moveItem(from: Int, to: Int) {
- if (from == to) return
- val item = items.removeAt(from)
- items.add(to, item)
- notifyItemMoved(from, to)
- }
-}
-
class MainActivity : AppCompatActivity() {
- private lateinit var prefs: SharedPreferences
- private val contentSwitches = mutableListOf()
- private var clockAppPackages = listOf("default")
- private var calendarAppPackages = listOf("default")
+ internal lateinit var prefs: SharedPreferences
+ internal val contentSwitches = mutableListOf()
+ internal var clockAppPackages = listOf("default")
+ internal var calendarAppPackages = listOf("default")
private var currentWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID
override fun onNewIntent(intent: Intent) {
@@ -160,28 +103,27 @@ class MainActivity : AppCompatActivity() {
val subtitleApp = findViewById(R.id.subtitle_app)
if (currentWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
- val labelText = "Widget #$currentWidgetId ▾"
- titleApp.text = "Lwidget #$currentWidgetId"
- subtitleApp.text = labelText
+ titleApp.text = getString(R.string.widget_title_numbered, currentWidgetId)
+ subtitleApp.text = getString(R.string.widget_selector_numbered, currentWidgetId)
} else {
- titleApp.text = "Lwidget"
- subtitleApp.text = "Default Settings ▾"
+ titleApp.text = getString(R.string.app_name)
+ subtitleApp.text = getString(R.string.widget_default_settings_selector)
}
subtitleApp.setOnClickListener {
val options = mutableListOf()
val optionIds = mutableListOf()
- options.add("Default Settings")
+ options.add(getString(R.string.widget_default_settings))
optionIds.add(AppWidgetManager.INVALID_APPWIDGET_ID)
ids.forEachIndexed { index, id ->
- options.add("Widget #${index + 1} (ID: $id)")
+ options.add(getString(R.string.widget_option_numbered, index + 1, id))
optionIds.add(id)
}
com.google.android.material.dialog.MaterialAlertDialogBuilder(this)
- .setTitle("Select Widget to Configure")
+ .setTitle(getString(R.string.widget_picker_title))
.setItems(options.toTypedArray()) { _, which ->
val selectedId = optionIds[which]
val newIntent = Intent(this, MainActivity::class.java).apply {
@@ -207,7 +149,7 @@ class MainActivity : AppCompatActivity() {
val versionName = try {
packageManager.getPackageInfo(packageName, 0).versionName
} catch (e: Exception) {
- "Unknown"
+ getString(R.string.version_unknown)
}
val tvVersion = findViewById(R.id.tv_changelog_version)
tvVersion.text = getString(R.string.changelog_version, versionName)
@@ -262,6 +204,8 @@ class MainActivity : AppCompatActivity() {
}
}
+ constrainContentWidth()
+
}
@android.annotation.SuppressLint("MissingPermission")
@@ -362,7 +306,7 @@ class MainActivity : AppCompatActivity() {
})
}
- private fun updateLivePreview() {
+ internal fun updateLivePreview() {
val previewContainer = findViewById(R.id.preview_container)
try {
val remoteViews = AwidgetProvider.Companion.buildAppWidgetRemoteViews(this, currentWidgetId, UpdateMode.FULL)
@@ -374,136 +318,10 @@ class MainActivity : AppCompatActivity() {
}
}
- private fun checkAllPermissions() {
- var widgetNeedsUpdate = false
-
- // Check Calendar
- val calMissing = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED
- if (prefs.getBoolean("show_events", false) && calMissing) {
- prefs.edit().putBoolean("show_events", false).apply()
- findViewById(R.id.row_events_toggle).findViewById(R.id.row_switch).isChecked = false
- findViewById(R.id.row_events_size).visibility = View.GONE
- widgetNeedsUpdate = true
- }
-
- // Check Tasks
- val tasksMissing = ContextCompat.checkSelfPermission(this, AwidgetProvider.PERMISSION_READ_TASKS_ORG) != PackageManager.PERMISSION_GRANTED
- if (prefs.getBoolean("show_tasks", false) && tasksMissing) {
- prefs.edit().putBoolean("show_tasks", false).apply()
- findViewById(R.id.row_tasks_toggle).findViewById(R.id.row_switch).isChecked = false
- findViewById(R.id.row_tasks_size).visibility = View.GONE
- widgetNeedsUpdate = true
- }
-
- // Check Steps
- var stepMissing = false
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q && ContextCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) != PackageManager.PERMISSION_GRANTED) {
- stepMissing = true
- }
- if (prefs.getBoolean("show_steps", false) && stepMissing) {
- prefs.edit().putBoolean("show_steps", false).apply()
- findViewById(R.id.row_steps_toggle).findViewById(R.id.row_switch).isChecked = false
- findViewById(R.id.row_steps_size).visibility = View.GONE
- widgetNeedsUpdate = true
- }
-
- // Check Screen Time
- val usageMissing = !hasUsageStatsPermission()
- if (prefs.getBoolean("show_screen_time", false) && usageMissing) {
- prefs.edit().putBoolean("show_screen_time", false).apply()
- findViewById(R.id.row_screen_time_toggle).findViewById(R.id.row_switch).isChecked = false
- findViewById(R.id.row_screen_time_size).visibility = View.GONE
- widgetNeedsUpdate = true
- }
-
- // Check Data Usage
- if (prefs.getBoolean("show_data_usage", false) && usageMissing) {
- prefs.edit().putBoolean("show_data_usage", false).apply()
- findViewById(R.id.row_data_toggle).findViewById(R.id.row_switch).isChecked = false
- findViewById(R.id.row_data_size).visibility = View.GONE
- widgetNeedsUpdate = true
- }
-
- // Check Breezy Weather
- val weatherMissing = !isAppInstalled("org.breezyweather") || ContextCompat.checkSelfPermission(this, "org.breezyweather.READ_PROVIDER") != PackageManager.PERMISSION_GRANTED
- if (prefs.getBoolean("show_weather_condition", false) && weatherMissing) {
- prefs.edit().putBoolean("show_weather_condition", false).apply()
- findViewById(R.id.row_weather_toggle).findViewById(R.id.row_switch).isChecked = false
- findViewById(R.id.row_weather_size).visibility = View.GONE
- widgetNeedsUpdate = true
- }
-
- if (widgetNeedsUpdate) {
- updateWidget()
- updateToggleAvailability()
- }
-
- // Update Permission Toggles
- updatePermissionToggle(R.id.row_perm_calendar, "Calendar Events", !calMissing) {
- if (calMissing) ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_CALENDAR), 100)
- else openAppSettings()
- }
- updatePermissionToggle(R.id.row_perm_tasks, "Tasks", !tasksMissing) {
- if (tasksMissing) ActivityCompat.requestPermissions(this, arrayOf(AwidgetProvider.PERMISSION_READ_TASKS_ORG), 101)
- else openAppSettings()
- }
- updatePermissionToggle(R.id.row_perm_steps, "Step Counter", !stepMissing) {
- if (stepMissing) {
- val neededPermissions = mutableListOf()
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
- neededPermissions.add(Manifest.permission.ACTIVITY_RECOGNITION)
- }
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
- neededPermissions.add(Manifest.permission.POST_NOTIFICATIONS)
- }
- ActivityCompat.requestPermissions(this, neededPermissions.toTypedArray(), 102)
- } else openAppSettings()
- }
- updatePermissionToggle(R.id.row_perm_data_usage, "Data Usage", !usageMissing) {
- try { startActivity(Intent(android.provider.Settings.ACTION_USAGE_ACCESS_SETTINGS)) } catch (e: Exception) { Log.w("MainActivity", "Failed to launch usage access settings", e) }
- }
- updatePermissionToggle(R.id.row_perm_screen_time, "Screen Time", !usageMissing) {
- try { startActivity(Intent(android.provider.Settings.ACTION_USAGE_ACCESS_SETTINGS)) } catch (e: Exception) { Log.w("MainActivity", "Failed to launch usage access settings", e) }
- }
- updatePermissionToggle(R.id.row_perm_weather, "Weather", !weatherMissing) {
- if (weatherMissing && !isAppInstalled("org.breezyweather")) {
- try {
- startActivity(Intent(Intent.ACTION_VIEW, android.net.Uri.parse("market://details?id=org.breezyweather")))
- } catch (e: Exception) { Log.w("MainActivity", "Failed to open market link for BreezyWeather", e)
- try {
- CustomTabsIntent.Builder().build().launchUrl(this@MainActivity, android.net.Uri.parse("https://f-droid.org/packages/org.breezyweather/"))
- } catch (e2: Exception) { Log.w("MainActivity", "Failed to launch custom tab for BreezyWeather", e2) }
- }
- } else if (weatherMissing) {
- ActivityCompat.requestPermissions(this, arrayOf("org.breezyweather.READ_PROVIDER"), 104)
- } else openAppSettings()
- }
- }
-
- private fun updatePermissionToggle(viewId: Int, label: String, isGranted: Boolean, onClick: () -> Unit) {
- val row = findViewById(viewId)
- if (row != null) {
- row.findViewById(R.id.row_label).text = label
- val switchView = row.findViewById(R.id.row_switch)
- switchView.setOnCheckedChangeListener(null)
- switchView.isChecked = isGranted
-
- row.setOnClickListener { onClick() }
- switchView.setOnClickListener {
- switchView.isChecked = isGranted // Revert instantly
- onClick()
- }
- }
- }
-
- private fun openAppSettings() {
- val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
- intent.data = android.net.Uri.parse("package:" + packageName)
- startActivity(intent)
- }
-
override fun onResume() {
super.onResume()
+ // onCreate returns early (first launch -> SetupActivity); nothing is bound in that case.
+ if (!::prefs.isInitialized) return
// Re-check permissions when returning (especially for Data Usage settings)
checkAllPermissions()
StepCounterService.startServiceIfEnabled(this)
@@ -548,560 +366,17 @@ class MainActivity : AppCompatActivity() {
updateToggleAvailability()
// Show Gadgetbridge module prompt
- com.google.android.material.dialog.MaterialAlertDialogBuilder(this)
- .setTitle("Important Step")
- .setMessage("If the weather doesn't show up on your widget soon:\n\nOpen Breezy Weather → Settings → External Modules → Enable 'Send Gadgetbridge Data' & toggle on 'Lwidget'.")
- .setPositiveButton("Got it", null)
- .show()
+ showWeatherSetupHint()
}
}
}
// ===== FOLDED SECTION HELPERS =====
- private val accordionViews = mutableMapOf()
- private val accordionHeaders = mutableMapOf()
- private val nestedViews = mutableMapOf()
- private val nestedHeaders = mutableMapOf()
-
- private fun toggleSectionExpansion(
- header: View,
- content: View,
- chevron: ImageView,
- prefKey: String,
- sectionKey: String? = null
- ) {
- val nestedScrollView = findViewById(R.id.nested_scroll_view)
- val nowExpanded = content.visibility != View.VISIBLE
-
- if (!nowExpanded && sectionKey != null) {
- collapseSectionNestedContent(sectionKey)
- }
-
- val parentViewGroup = (header.parent as? ViewGroup) ?: (nestedScrollView as? ViewGroup)
- if (parentViewGroup != null) {
- TransitionManager.beginDelayedTransition(
- parentViewGroup,
- AutoTransition().apply {
- duration = 220L
- interpolator = FastOutSlowInInterpolator()
- }
- )
- }
-
- content.visibility = if (nowExpanded) View.VISIBLE else View.GONE
- prefs.edit().putBoolean(prefKey, nowExpanded).apply()
-
- chevron.animate()
- .rotation(if (nowExpanded) 180f else 0f)
- .setDuration(220L)
- .setInterpolator(FastOutSlowInInterpolator())
- .start()
-
- if (nowExpanded && nestedScrollView != null) {
- header.postDelayed({
- if (!isDestroyed && !isFinishing) {
- val rect = android.graphics.Rect()
- header.getDrawingRect(rect)
- nestedScrollView.offsetDescendantRectToMyCoords(header, rect)
- val scrollY = nestedScrollView.scrollY
- val viewportHeight = nestedScrollView.height
- val headerTop = rect.top
- if (headerTop < scrollY || headerTop > scrollY + (viewportHeight * 0.65f)) {
- nestedScrollView.smoothScrollTo(0, headerTop.coerceAtLeast(0))
- }
- }
- }, 100L)
- }
- }
-
- private fun bindFoldedSection(
- headerId: Int, iconResId: Int?, title: String,
- contentId: Int,
- toggleRowId: Int,
- prefShowKey: String, defShow: Boolean,
- sizeRowId: Int? = null, prefSizeKey: String? = null,
- defSize: Float = 14f, minSize: Float = 10f, maxSize: Float = 72f,
- selectorRowId: Int? = null, selectorOptions: List? = null,
- prefSelectorKey: String? = null, defSelectorIdx: Int = 0,
- boldRowId: Int? = null,
- isContent: Boolean = false,
- subSettingsContainerId: Int? = null,
- validateToggle: ((Boolean) -> Boolean)? = null,
- onChanged: ((Boolean) -> Unit)? = null
- ): SwitchMaterial {
- val header = findViewById(headerId)
- val chevron = header.findViewById(R.id.header_chevron)
- val headerIcon = header.findViewById(R.id.header_icon)
- val headerTitle = header.findViewById(R.id.header_title)
- val content = findViewById(contentId)
-
- val sectionKey = prefShowKey.replace("show_", "")
- val expandedPrefKey = "section_${sectionKey}_expanded"
- accordionViews[expandedPrefKey] = content
- accordionHeaders[expandedPrefKey] = header
-
- headerTitle.text = title
- if (iconResId != null) {
- headerIcon.setImageResource(iconResId)
- headerIcon.visibility = View.VISIBLE
- } else {
- headerIcon.visibility = View.GONE
- }
-
- // Expand/collapse - read from prefs, apply visibility
- val isExpandedFromPrefs = prefs.getBoolean(expandedPrefKey, false)
- content.visibility = if (isExpandedFromPrefs) View.VISIBLE else View.GONE
- chevron.rotation = if (isExpandedFromPrefs) 180f else 0f
-
- // Header click: smooth expand/collapse with auto-scroll
- header.setOnClickListener {
- toggleSectionExpansion(header, content, chevron, expandedPrefKey, sectionKey)
- }
-
- // Toggle row
- val toggleRow = findViewById(toggleRowId)
- val toggleSwitch = toggleRow.findViewById(R.id.row_switch)
- val toggleLabel = toggleRow.findViewById(R.id.row_label)
- val toggleCard = toggleRow.findViewById(R.id.toggle_row_card)
- toggleLabel.text = "Enable"
-
- toggleSwitch.tag = prefShowKey
- if (isContent) contentSwitches.add(toggleSwitch)
-
- val isShown = prefs.getBoolean(prefShowKey, defShow)
- toggleSwitch.isChecked = isShown
-
- // Sub-settings alpha
- val subSettings = subSettingsContainerId?.let { findViewById(it) }
- subSettings?.alpha = if (isShown) 1.0f else 0.4f
- updateToggleCardStyle(toggleCard, isShown)
-
- // Child rows visibility
- val sizeRow = sizeRowId?.let { findViewById(it) }
- sizeRow?.visibility = if (isShown) View.VISIBLE else View.GONE
-
- val selectorRow = selectorRowId?.let { findViewById(it) }
- selectorRow?.visibility = if (isShown) View.VISIBLE else View.GONE
-
- val boldRow = boldRowId?.let { findViewById(it) }
- boldRow?.visibility = if (isShown) View.VISIBLE else View.GONE
-
- onChanged?.invoke(isShown)
-
- // 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)
-
- val parentViewGroup = (toggleRow.parent as? ViewGroup)
- if (parentViewGroup != null) {
- TransitionManager.beginDelayedTransition(
- parentViewGroup,
- AutoTransition().apply {
- duration = 180L
- }
- )
- }
-
- sizeRow?.visibility = if (isChecked) View.VISIBLE else View.GONE
- selectorRow?.visibility = if (isChecked) View.VISIBLE else View.GONE
- boldRow?.visibility = if (isChecked) View.VISIBLE else View.GONE
- onChanged?.invoke(isChecked)
- updateWidget()
- if (isContent) updateToggleAvailability()
- }
-
- // Size row setup
- if (sizeRowId != null && prefSizeKey != null) {
- val sizeRowInner = findViewById(sizeRowId)
- val slider = sizeRowInner.findViewById(R.id.row_slider)
- val valueLabel = sizeRowInner.findViewById(R.id.row_value)
- val sizeLabel = sizeRowInner.findViewById(R.id.row_label)
- sizeLabel.text = "Size"
-
- val currentSize = prefs.getFloat(prefSizeKey, defSize)
- slider.valueFrom = minSize
- slider.valueTo = maxSize
- slider.value = currentSize.coerceIn(minSize, maxSize)
- valueLabel.text = "${currentSize.toInt()}"
-
- slider.addOnChangeListener { _, value, fromUser ->
- if (fromUser) {
- valueLabel.text = "${value.toInt()}"
- prefs.edit().putFloat(prefSizeKey, value).apply()
- updateWidget()
- }
- }
- }
-
- // Selector row setup (skip world clock timezone - uses custom search layout)
- if (selectorRowId != null && selectorOptions != null && prefSelectorKey != null && prefSelectorKey != "world_clock_zone_str") {
- val selectorRowInner = findViewById(selectorRowId)
- val autoCompleteTextView = selectorRowInner.findViewById(R.id.row_value)
- val selectorLabel = selectorRowInner.findViewById(R.id.row_label)
- selectorLabel.text = title
-
- 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()
- }
- }
-
- // Clear focus/dropdown shade when dismissed
- autoCompleteTextView.setOnFocusChangeListener { _, hasFocus ->
- if (!hasFocus) {
- autoCompleteTextView.clearFocus()
- }
- }
- }
-
- return toggleSwitch
- }
-
- private fun updateToggleCardStyle(card: MaterialCardView?, enabled: Boolean) {
- if (card == null) return
- if (enabled) {
- card.setCardBackgroundColor(android.graphics.Color.TRANSPARENT)
- card.strokeWidth = (1f * resources.displayMetrics.density).toInt()
- card.setStrokeColor(android.content.res.ColorStateList.valueOf(
- com.google.android.material.color.MaterialColors.getColor(card, com.google.android.material.R.attr.colorPrimary)
- ))
- } else {
- card.setCardBackgroundColor(
- com.google.android.material.color.MaterialColors.getColor(card, com.google.android.material.R.attr.colorSurfaceContainerLow)
- )
- card.setStrokeColor(android.content.res.ColorStateList.valueOf(
- com.google.android.material.color.MaterialColors.getColor(card, com.google.android.material.R.attr.colorOutlineVariant)
- ))
- }
- }
-
- // Helper for callers who override the toggle listener to update row visibility
- private fun updateFeatureRowVisibility(switch: SwitchMaterial, isChecked: Boolean, vararg rowIds: Int) {
- val toggleRow = switch.parent as? View
- val toggleCard = toggleRow?.findViewById(R.id.toggle_row_card)
- updateToggleCardStyle(toggleCard, isChecked)
-
- val parentViewGroup = (toggleRow?.parent as? ViewGroup)
- if (parentViewGroup != null) {
- TransitionManager.beginDelayedTransition(
- parentViewGroup,
- AutoTransition().apply {
- duration = 180L
- }
- )
- }
-
- rowIds.forEach { id ->
- findViewById(id)?.visibility = if (isChecked) View.VISIBLE else View.GONE
- }
- }
-
- private fun bindTimezoneSearch(
- rowId: Int, zoneIds: List, prefKey: String, defaultVal: String
- ) {
- val row = findViewById(rowId)
- val searchEdit = row.findViewById(R.id.zone_search_edit)
- val listView = row.findViewById(R.id.zone_search_list)
-
- val currentVal = prefs.getString(prefKey, defaultVal) ?: defaultVal
- searchEdit.setText(currentVal)
-
- var filteredList: MutableList = mutableListOf()
- val filteredAdapter = android.widget.ArrayAdapter(this, android.R.layout.simple_list_item_1, filteredList)
-
- // Text watcher for filtering
- searchEdit.addTextChangedListener(object : android.text.TextWatcher {
- override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
- override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
- override fun afterTextChanged(s: android.text.Editable?) {
- val query = s?.toString()?.lowercase() ?: ""
- if (query.isEmpty()) {
- filteredList.clear()
- listView.visibility = View.GONE
- return
- }
- filteredList.clear()
- filteredList.addAll(zoneIds.filter { it.lowercase().contains(query) })
- filteredAdapter.notifyDataSetChanged()
- listView.visibility = if (filteredList.isEmpty()) View.GONE else View.VISIBLE
- }
- })
-
- listView.adapter = filteredAdapter
- listView.setOnItemClickListener { _, _, position, _ ->
- val selected = filteredList[position]
- searchEdit.setText(selected)
- listView.visibility = View.GONE
- searchEdit.clearFocus()
- prefs.edit().putString(prefKey, selected).apply()
- updateWidget()
- }
-
- // Intercept touch events so parent NestedScrollView doesn't steal them
- listView.setOnTouchListener { v, event ->
- v.parent.requestDisallowInterceptTouchEvent(true)
- false
- }
-
- // Show list on focus
- searchEdit.setOnFocusChangeListener { _, hasFocus ->
- if (hasFocus) {
- val query = searchEdit.text?.toString()?.lowercase() ?: ""
- if (query.isEmpty()) {
- filteredList.clear()
- filteredList.addAll(zoneIds)
- filteredAdapter.notifyDataSetChanged()
- listView.visibility = View.VISIBLE
- }
- }
- }
- }
-
- // Dismiss keyboard and collapse nested subsections when a parent section collapses
- private fun collapseSectionNestedContent(sectionKey: String) {
- // World clock timezone search
- if (sectionKey == "world_clock") {
- val worldClockZoneRow = findViewById(R.id.row_world_clock_zone)
- val searchEdit = worldClockZoneRow?.findViewById(R.id.zone_search_edit)
- val listView = worldClockZoneRow?.findViewById(R.id.zone_search_list)
- searchEdit?.clearFocus()
- listView?.visibility = View.GONE
- }
- // Appearance reorder section
- if (sectionKey == "appearance") {
- // collapse reorder too
- }
- // Appearance subsections
- if (sectionKey == "appearance") {
- val presetsContent = findViewById(R.id.content_appearance_presets)
- val outlineContent = findViewById(R.id.content_appearance_outline)
- val colorsContent = findViewById(R.id.content_appearance_colors)
- val themeContent = findViewById(R.id.content_appearance_theme)
- val fontContent = findViewById(R.id.content_appearance_font)
- val transparencyContent = findViewById(R.id.content_appearance_transparency)
- presetsContent?.visibility = View.GONE
- outlineContent?.visibility = View.GONE
- colorsContent?.visibility = View.GONE
- themeContent?.visibility = View.GONE
- fontContent?.visibility = View.GONE
- transparencyContent?.visibility = View.GONE
- prefs.edit()
- .putBoolean("section_appearance_presets_expanded", false)
- .putBoolean("section_appearance_outline_expanded", false)
- .putBoolean("section_appearance_colors_expanded", false)
- .putBoolean("section_appearance_theme_expanded", false)
- .putBoolean("section_appearance_font_expanded", false)
- .putBoolean("section_appearance_transparency_expanded", false)
- .apply()
- // Reset nested chevrons
- listOf(
- R.id.header_chevron_appearance_presets,
- R.id.header_chevron_appearance_outline,
- R.id.header_chevron_appearance_colors,
- R.id.header_chevron_appearance_theme,
- R.id.header_chevron_appearance_font,
- R.id.header_chevron_appearance_transparency
- ).forEach { id ->
- findViewById(id)?.rotation = 0f
- }
- }
- dismissKeyboard()
- }
-
- private fun dismissKeyboard() {
- val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager
- currentFocus?.let { imm?.hideSoftInputFromWindow(it.windowToken, 0) }
- }
-
- private fun bindReorderSection() {
- val defaultOrder = listOf(
- ReorderItem("show_battery", getString(R.string.section_battery), prefs.getBoolean("show_battery", true)),
- ReorderItem("show_temp", getString(R.string.section_temp), prefs.getBoolean("show_temp", false)),
- ReorderItem("show_weather_condition", getString(R.string.section_weather_condition), prefs.getBoolean("show_weather_condition", false)),
- ReorderItem("show_data_usage", getString(R.string.section_data_usage), prefs.getBoolean("show_data_usage", false)),
- ReorderItem("show_storage", getString(R.string.section_storage), prefs.getBoolean("show_storage", false)),
- ReorderItem("show_ram", getString(R.string.section_ram), prefs.getBoolean("show_ram", false)),
- ReorderItem("show_steps", getString(R.string.section_steps), prefs.getBoolean("show_steps", false)),
- ReorderItem("show_screen_time", getString(R.string.section_screen_time), prefs.getBoolean("show_screen_time", false))
- )
-
- val savedOrder = prefs.getString("widget_right_column_order", "")
- val items = if (savedOrder.isNullOrEmpty()) {
- defaultOrder.toMutableList()
- } else {
- val keys = savedOrder.split(",")
- val list = mutableListOf()
- keys.forEach { key ->
- val item = defaultOrder.find { it.key == key }
- if (item != null) list.add(item)
- else list.add(ReorderItem(key, key.replace("show_", "").replace("_", " ").replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.ROOT) else it.toString() }, prefs.getBoolean(key, false)))
- }
- // Add any new items not in saved order
- defaultOrder.forEach { default ->
- if (!list.any { it.key == default.key }) list.add(default)
- }
- list
- }
-
- val recyclerView = findViewById(R.id.reorder_recycler)
- var itemTouchHelper: ItemTouchHelper? = null
- var orderHasChanged = false
-
- val adapter = ReorderAdapter(
- items,
- onStartDrag = { viewHolder ->
- itemTouchHelper?.startDrag(viewHolder)
- }
- )
- recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
- recyclerView.adapter = adapter
- (recyclerView.itemAnimator as? androidx.recyclerview.widget.SimpleItemAnimator)?.supportsChangeAnimations = false
-
- val callback = object : androidx.recyclerview.widget.ItemTouchHelper.SimpleCallback(
- androidx.recyclerview.widget.ItemTouchHelper.UP or androidx.recyclerview.widget.ItemTouchHelper.DOWN, 0
- ) {
- override fun isLongPressDragEnabled(): Boolean = false
- override fun isItemViewSwipeEnabled(): Boolean = false
-
- override fun onMove(rv: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
- val fromPos = viewHolder.adapterPosition
- val toPos = target.adapterPosition
- if (fromPos != RecyclerView.NO_POSITION && toPos != RecyclerView.NO_POSITION && fromPos != toPos) {
- adapter.moveItem(fromPos, toPos)
- orderHasChanged = true
- rv.performHapticFeedback(android.view.HapticFeedbackConstants.CLOCK_TICK)
- }
- return true
- }
-
- override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {}
-
- override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
- super.onSelectedChanged(viewHolder, actionState)
- if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
- viewHolder?.itemView?.translationZ = 24f
- var parent = recyclerView.parent
- while (parent != null) {
- parent.requestDisallowInterceptTouchEvent(true)
- parent = parent.parent
- }
- }
- }
-
- override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
- super.clearView(recyclerView, viewHolder)
- viewHolder.itemView.translationZ = 0f
- var parent = recyclerView.parent
- while (parent != null) {
- parent.requestDisallowInterceptTouchEvent(false)
- parent = parent.parent
- }
- val pos = viewHolder.adapterPosition
- if (pos != RecyclerView.NO_POSITION && pos < items.size) {
- viewHolder.itemView.alpha = if (items[pos].enabled) 1.0f else 0.4f
- }
- if (orderHasChanged) {
- orderHasChanged = false
- val orderStr = items.joinToString(",") { it.key }
- prefs.edit().putString("widget_right_column_order", orderStr).apply()
- updateWidget()
- updateLivePreview()
- }
- }
-
- override fun interpolateOutOfBoundsScroll(
- recyclerView: RecyclerView,
- viewSize: Int,
- viewSizeOutOfBounds: Int,
- totalSize: Int,
- msSinceStartScroll: Long
- ): Int {
- val standardSpeed = super.interpolateOutOfBoundsScroll(
- recyclerView, viewSize, viewSizeOutOfBounds, totalSize, msSinceStartScroll
- )
- return if (standardSpeed != 0) standardSpeed / 2 else 0
- }
- }
- itemTouchHelper = ItemTouchHelper(callback).also {
- it.attachToRecyclerView(recyclerView)
- }
- }
-
- private fun bindNestedCard(
- headerId: Int, title: String, contentId: Int, sectionKey: String,
- chevronViewId: Int? = null
- ) {
- val header = findViewById(headerId)
- val content = findViewById(contentId)
- val chevronView = header.findViewById(
- chevronViewId ?: R.id.header_chevron
- )
-
- nestedViews[sectionKey] = content
- nestedHeaders[sectionKey] = header
-
- val isExpanded = prefs.getBoolean(sectionKey, false)
- content.visibility = if (isExpanded) View.VISIBLE else View.GONE
- chevronView.rotation = if (isExpanded) 180f else 0f
-
- header.setOnClickListener {
- toggleSectionExpansion(header, content, chevronView, sectionKey)
- }
- }
-
- private fun bindCategoryFoldable(headerId: Int, contentId: Int, title: String, iconResId: Int, prefKey: String) {
- accordionViews[prefKey] = findViewById(contentId)
- accordionHeaders[prefKey] = findViewById(headerId)
-
- val header = findViewById(headerId)
- header.findViewById(R.id.header_title).text = title
- val headerIcon = header.findViewById(R.id.header_icon)
- if (iconResId != 0) {
- headerIcon.setImageResource(iconResId)
- headerIcon.visibility = View.VISIBLE
- } else {
- headerIcon.visibility = View.GONE
- }
-
- val content = findViewById(contentId)
- val chevron = header.findViewById(R.id.header_chevron)
- val isExpanded = prefs.getBoolean(prefKey, false)
- content.visibility = if (isExpanded) View.VISIBLE else View.GONE
- chevron.rotation = if (isExpanded) 180f else 0f
-
- header.setOnClickListener {
- toggleSectionExpansion(header, content, chevron, prefKey)
- }
- }
+ internal val accordionViews = mutableMapOf()
+ internal val accordionHeaders = mutableMapOf()
+ internal val nestedViews = mutableMapOf()
+ internal val nestedHeaders = mutableMapOf()
private fun setupSections() {
contentSwitches.clear()
@@ -1137,1107 +412,27 @@ class MainActivity : AppCompatActivity() {
bindNestedCard(R.id.header_changelog, "", R.id.content_changelog, "section_changelog_expanded", R.id.chevron_changelog)
}
- private fun getInstalledClockApps(): Pair, List> {
- val labels = mutableListOf("Default")
- val packages = mutableListOf("default")
-
- val knownPackages = listOf(
- "com.android.deskclock",
- "com.google.android.deskclock",
- "com.simplemobiletools.clock",
- "org.fossify.clock",
- "com.sec.android.app.clockpackage",
- "com.huawei.deskclock",
- "com.coloros.alarmclock",
- "com.oneplus.deskclock",
- "com.htc.sec.android.app.clockpackage"
- )
-
- val pm = packageManager
-
- val alarmIntent = Intent(android.provider.AlarmClock.ACTION_SHOW_ALARMS)
- val resolveInfos = pm.queryIntentActivities(alarmIntent, PackageManager.MATCH_DEFAULT_ONLY)
-
- val foundPackages = mutableSetOf()
- for (info in resolveInfos) {
- val pkg = info.activityInfo.packageName
- foundPackages.add(pkg)
- }
-
- for (pkg in knownPackages) {
- if (isAppInstalled(pkg)) {
- foundPackages.add(pkg)
- }
- }
-
- for (pkg in foundPackages) {
- try {
- val appInfo = pm.getApplicationInfo(pkg, 0)
- val label = pm.getApplicationLabel(appInfo).toString()
- labels.add(label)
- packages.add(pkg)
- } catch (e: Exception) {
- // ignore
- }
- }
-
- return Pair(labels, packages)
- }
-
- private fun setupTimeSection(timeFormatOptions: List) {
- val (labels, packages) = getInstalledClockApps()
- clockAppPackages = packages
- val clockAppRow = findViewById(R.id.row_time_clock_app)
- // Time
- bindFoldedSection(
- R.id.header_time, R.drawable.ic_time, getString(R.string.section_time),
- R.id.content_time, R.id.row_time_toggle,
- "show_time", true,
- sizeRowId = R.id.row_time_size, prefSizeKey = "size_time", defSize = 56f, minSize = 12f, maxSize = 120f,
- selectorRowId = R.id.row_time_format, selectorOptions = timeFormatOptions, prefSelectorKey = "time_format_idx", defSelectorIdx = 0,
- isContent = true,
- onChanged = { isShown ->
- clockAppRow?.visibility = if (isShown) View.VISIBLE else View.GONE
- }
- )
+ private val updateHandler = android.os.Handler(android.os.Looper.getMainLooper())
+ private val deferredUpdate = Runnable { updateWidget() }
- bindSelector(
- R.id.row_time_clock_app,
- getString(R.string.section_time_clock_app),
- "clock_app_package",
- labels,
- 0
- )
- }
- private fun setupNextAlarmSection() {
- // Next Alarm
- bindFoldedSection(
- R.id.header_next_alarm, R.drawable.ic_alarm, getString(R.string.section_next_alarm),
- R.id.content_next_alarm, R.id.row_next_alarm_toggle,
- "show_next_alarm", true,
- sizeRowId = R.id.row_next_alarm_size, prefSizeKey = "size_next_alarm", defSize = 14f, minSize = 10f, maxSize = 24f,
- isContent = true
- )
+ /**
+ * Coalesces rapid updates (e.g. while dragging a slider) into one trailing updateWidget().
+ * updateWidget() rebuilds the preview, animates the FAB and re-renders the real widget, so
+ * running it on every slider tick is wasteful. Discrete actions should call updateWidget() directly.
+ */
+ internal fun scheduleWidgetUpdate(delayMs: Long = WIDGET_UPDATE_DEBOUNCE_MS) {
+ updateHandler.removeCallbacks(deferredUpdate)
+ updateHandler.postDelayed(deferredUpdate, delayMs)
}
- private fun setupWorldClockSection(zoneIds: List) {
- // World Clock
- bindFoldedSection(
- R.id.header_world_clock, R.drawable.ic_world, getString(R.string.section_world_clock),
- R.id.content_world_clock, R.id.row_world_clock_toggle,
- "show_world_clock", false,
- sizeRowId = R.id.row_world_clock_size, prefSizeKey = "size_world_clock", defSize = 18f, minSize = 10f, maxSize = 32f,
- isContent = true
- )
- bindTimezoneSearch(R.id.row_world_clock_zone, zoneIds, "world_clock_zone_str", "UTC")
- }
- private fun setupDateSection(dateFormatOptions: List) {
- // Date
- bindFoldedSection(
- R.id.header_date, R.drawable.ic_date, getString(R.string.section_date),
- R.id.content_date, R.id.row_date_toggle,
- "show_date", true,
- sizeRowId = R.id.row_date_size, prefSizeKey = "size_date", defSize = 16f, minSize = 10f, maxSize = 24f,
- selectorRowId = R.id.row_date_format, selectorOptions = dateFormatOptions, prefSelectorKey = "date_format_idx", defSelectorIdx = 0,
- isContent = true
- )
- }
- private fun setupBatterySection() {
- // Battery
- bindFoldedSection(
- R.id.header_battery, R.drawable.ic_battery, getString(R.string.section_battery),
- R.id.content_battery, R.id.row_battery_toggle,
- "show_battery", true,
- sizeRowId = R.id.row_battery_size, prefSizeKey = "size_battery", defSize = 32f, minSize = 10f, maxSize = 74f,
- boldRowId = R.id.row_battery_bold,
- isContent = true
- ).also { it.tag = "battery" }
- bindToggle(R.id.row_battery_bold, getString(R.string.row_bold_text), "bold_battery", true)
- }
- private fun setupTempSection() {
- // Temp
- val tempUnitOptions = listOf("Celsius (°C)", "Fahrenheit (°F)")
- bindFoldedSection(
- R.id.header_temp, R.drawable.ic_temp, getString(R.string.section_temp),
- R.id.content_temp, R.id.row_temp_toggle,
- "show_temp", false,
- sizeRowId = R.id.row_temp_size, prefSizeKey = "size_temp", defSize = 18f, minSize = 10f, maxSize = 74f,
- selectorRowId = R.id.row_temp_unit, selectorOptions = tempUnitOptions, prefSelectorKey = "temp_unit_idx", defSelectorIdx = 0,
- boldRowId = R.id.row_temp_bold,
- isContent = true
- ).also { it.tag = "temp" }
- bindToggle(R.id.row_temp_bold, getString(R.string.row_bold_text), "bold_temp", false)
- }
- private fun setupWeatherSection() {
- // Weather
- val weatherSwitch = bindFoldedSection(
- R.id.header_weather, R.drawable.ic_weather, getString(R.string.section_weather_condition),
- R.id.content_weather, R.id.row_weather_toggle,
- "show_weather_condition", false,
- sizeRowId = R.id.row_weather_size, prefSizeKey = "size_weather", defSize = 18f, minSize = 10f, maxSize = 74f,
- boldRowId = R.id.row_weather_bold,
- isContent = true
- ).also { it.tag = "weather_condition" }
- bindToggle(R.id.row_weather_bold, getString(R.string.row_bold_text), "bold_weather", false)
- // Override weather listener for Breezy Weather check
- weatherSwitch.setOnCheckedChangeListener { _, isChecked ->
- if (isChecked) {
- if (!isAppInstalled("org.breezyweather")) {
- weatherSwitch.isChecked = false
- com.google.android.material.snackbar.Snackbar.make(
- findViewById(R.id.fab_update),
- "Breezy Weather app (with DataBridge enabled) is required.",
- com.google.android.material.snackbar.Snackbar.LENGTH_LONG
- ).setAction("Install") {
- try {
- CustomTabsIntent.Builder().build().launchUrl(this@MainActivity, android.net.Uri.parse("https://github.com/breezy-weather/breezy-weather/releases"))
- } catch (e: Exception) { android.util.Log.e("MainActivity", "Exception caught", e) }
- }.show()
- return@setOnCheckedChangeListener
- }
- if (ContextCompat.checkSelfPermission(this, "org.breezyweather.READ_PROVIDER") != PackageManager.PERMISSION_GRANTED) {
- weatherSwitch.isChecked = false
- com.google.android.material.dialog.MaterialAlertDialogBuilder(this)
- .setTitle("Permission Clarification")
- .setMessage("To display the weather, Lwidget needs to read data from Breezy Weather.\n\nAndroid will now ask for 'Location' access. Please note: Lwidget DOES NOT access your location, nor does it have permission to access the internet. This is simply how Android categorizes Breezy Weather's data sharing permission.")
- .setPositiveButton("Continue") { _, _ ->
- ActivityCompat.requestPermissions(this, arrayOf("org.breezyweather.READ_PROVIDER"), 103)
- }
- .setNegativeButton("Cancel", null)
- .show()
- return@setOnCheckedChangeListener
- }
- if (!checkLimit()) {
- weatherSwitch.isChecked = false
- return@setOnCheckedChangeListener
- }
- }
- prefs.edit().putBoolean("show_weather_condition", isChecked).apply()
- updateFeatureRowVisibility(weatherSwitch, isChecked, R.id.row_weather_size, R.id.row_weather_bold)
- updateWidget()
- updateToggleAvailability()
- if (isChecked) {
- com.google.android.material.dialog.MaterialAlertDialogBuilder(this)
- .setTitle("Important Step")
- .setMessage("If the weather doesn't show up on your widget soon:\n\nOpen Breezy Weather → Settings → External Modules → Enable 'Send Gadgetbridge Data' & toggle on 'Lwidget'.")
- .setPositiveButton("Got it", null)
- .show()
- }
- }
+ override fun onDestroy() {
+ updateHandler.removeCallbacks(deferredUpdate)
+ super.onDestroy()
}
- private fun setupDataUsageSection() {
- // Data Usage
- val dataSwitch = bindFoldedSection(
- R.id.header_data, R.drawable.ic_data, getString(R.string.section_data_usage),
- R.id.content_data, R.id.row_data_toggle,
- "show_data_usage", false,
- sizeRowId = R.id.row_data_size, prefSizeKey = "size_data", defSize = 14f, minSize = 10f, maxSize = 74f,
- boldRowId = R.id.row_data_bold,
- isContent = true
- ).also { it.tag = "data" }
- bindToggle(R.id.row_data_bold, getString(R.string.row_bold_text), "bold_data_usage", false)
- dataSwitch.setOnCheckedChangeListener { _, isChecked ->
- if (isChecked) {
- if (!hasUsageStatsPermission()) {
- dataSwitch.isChecked = false
- try {
- startActivity(Intent(android.provider.Settings.ACTION_USAGE_ACCESS_SETTINGS))
- com.google.android.material.snackbar.Snackbar.make(
- findViewById(R.id.fab_update),
- getString(R.string.perm_usage_access_title),
- com.google.android.material.snackbar.Snackbar.LENGTH_LONG
- ).show()
- } catch (e: Exception) { android.util.Log.e("MainActivity", "Exception caught", e) }
- return@setOnCheckedChangeListener
- }
- if (!checkLimit()) {
- dataSwitch.isChecked = false
- return@setOnCheckedChangeListener
- }
- }
- prefs.edit().putBoolean("show_data_usage", isChecked).apply()
- updateFeatureRowVisibility(dataSwitch, isChecked, R.id.row_data_size, R.id.row_data_bold)
- updateWidget()
- updateToggleAvailability()
- checkAllPermissions()
- }
- }
- private fun setupRamSection() {
- // RAM
- bindFoldedSection(
- R.id.header_ram, R.drawable.ic_storage, getString(R.string.section_ram),
- R.id.content_ram, R.id.row_ram_toggle,
- "show_ram", false,
- sizeRowId = R.id.row_ram_size, prefSizeKey = "size_ram", defSize = 14f, minSize = 10f, maxSize = 74f,
- boldRowId = R.id.row_ram_bold,
- isContent = true
- ).also { it.tag = "ram" }
- bindToggle(R.id.row_ram_bold, getString(R.string.row_bold_text), "bold_ram", false)
- }
-
- private fun setupStorageSection() {
- // Storage
- bindFoldedSection(
- R.id.header_storage, R.drawable.ic_storage, getString(R.string.section_storage),
- R.id.content_storage, R.id.row_storage_toggle,
- "show_storage", false,
- sizeRowId = R.id.row_storage_size, prefSizeKey = "size_storage", defSize = 14f, minSize = 10f, maxSize = 74f,
- boldRowId = R.id.row_storage_bold,
- isContent = true
- ).also { it.tag = "storage" }
- bindToggle(R.id.row_storage_bold, getString(R.string.row_bold_text), "bold_storage", false)
- }
- private fun setupStepsSection() {
- // Steps
- val stepsSwitch = bindFoldedSection(
- R.id.header_steps, R.drawable.ic_steps, getString(R.string.section_steps),
- R.id.content_steps, R.id.row_steps_toggle,
- "show_steps", false,
- sizeRowId = R.id.row_steps_size, prefSizeKey = "size_steps", defSize = 14f, minSize = 10f, maxSize = 74f,
- boldRowId = R.id.row_steps_bold,
- isContent = true
- ).also { it.tag = "steps" }
- bindToggle(R.id.row_steps_bold, getString(R.string.row_bold_text), "bold_steps", false)
-
- stepsSwitch.setOnCheckedChangeListener { _, isChecked ->
- if (isChecked) {
- val hasActivityPerm = android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.Q ||
- ContextCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_GRANTED
- if (!hasActivityPerm) {
- val neededPermissions = mutableListOf(Manifest.permission.ACTIVITY_RECOGNITION)
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU &&
- ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
- neededPermissions.add(Manifest.permission.POST_NOTIFICATIONS)
- }
- ActivityCompat.requestPermissions(this, neededPermissions.toTypedArray(), 102)
- stepsSwitch.isChecked = false
- return@setOnCheckedChangeListener
- }
- if (!checkLimit()) {
- stepsSwitch.isChecked = false
- return@setOnCheckedChangeListener
- }
- }
- prefs.edit().putBoolean("show_steps", isChecked).apply()
- val globalPrefs = getSharedPreferences("com.leanbitlab.lwidget.PREFS", Context.MODE_PRIVATE)
- if (isChecked) {
- globalPrefs.edit().putBoolean("show_steps", true).apply()
- }
- val keepAlive = prefs.getBoolean("keep_alive", false)
- val serviceIntent = Intent(this, StepCounterService::class.java)
- if (isChecked) {
- val hasPermission = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
- ContextCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_GRANTED
- } else { true }
- if (hasPermission) {
- try {
- ContextCompat.startForegroundService(this, serviceIntent)
- } catch (e: Exception) {
- Log.e("MainActivity", "Failed to start StepCounterService", e)
- }
- } else {
- prefs.edit().putBoolean("show_steps", false).apply()
- updateWidget()
- updateToggleAvailability()
- checkAllPermissions()
- return@setOnCheckedChangeListener
- }
- } else if (!keepAlive && !StepCounterService.isStepOrKeepAliveEnabled(this)) {
- stopService(serviceIntent)
- }
- updateFeatureRowVisibility(stepsSwitch, isChecked, R.id.row_steps_size, R.id.row_steps_bold)
- updateWidget()
- updateToggleAvailability()
- checkAllPermissions()
- }
- }
- private fun setupScreenTimeSection() {
- // Screen Time
- val screenTimeSwitch = bindFoldedSection(
- R.id.header_screen_time, R.drawable.ic_time, getString(R.string.section_screen_time),
- R.id.content_screen_time, R.id.row_screen_time_toggle,
- "show_screen_time", false,
- sizeRowId = R.id.row_screen_time_size, prefSizeKey = "size_screen_time", defSize = 14f, minSize = 10f, maxSize = 74f,
- boldRowId = R.id.row_screen_time_bold,
- isContent = true
- ).also { it.tag = "screen_time" }
- bindToggle(R.id.row_screen_time_bold, getString(R.string.row_bold_text), "bold_screen_time", false)
-
- screenTimeSwitch.setOnCheckedChangeListener { _, isChecked ->
- if (isChecked) {
- if (!hasUsageStatsPermission()) {
- screenTimeSwitch.isChecked = false
- try {
- startActivity(Intent(android.provider.Settings.ACTION_USAGE_ACCESS_SETTINGS))
- com.google.android.material.snackbar.Snackbar.make(
- findViewById(R.id.fab_update),
- getString(R.string.perm_usage_access_title),
- com.google.android.material.snackbar.Snackbar.LENGTH_LONG
- ).show()
- } catch (e: Exception) { android.util.Log.e("MainActivity", "Failed to open Usage Access Settings", e) }
- return@setOnCheckedChangeListener
- }
- if (!checkLimit()) {
- screenTimeSwitch.isChecked = false
- return@setOnCheckedChangeListener
- }
- }
- prefs.edit().putBoolean("show_screen_time", isChecked).apply()
- updateFeatureRowVisibility(screenTimeSwitch, isChecked, R.id.row_screen_time_size, R.id.row_screen_time_bold)
- updateWidget()
- updateToggleAvailability()
- checkAllPermissions()
- }
- }
- private fun setupKeepAliveSection() {
- // Keep Alive (now inside Advanced section, not folded)
- bindToggle(R.id.row_keep_alive_toggle, getString(R.string.row_enable_keep_alive), "keep_alive", false) { isChecked ->
- prefs.edit().putBoolean("keep_alive", isChecked).apply()
- getSharedPreferences("com.leanbitlab.lwidget.PREFS", Context.MODE_PRIVATE)
- .edit().putBoolean("keep_alive", isChecked).apply()
-
- if (isChecked) {
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU &&
- ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), 105)
- }
- StepCounterService.startServiceIfEnabled(this)
- } else {
- if (!StepCounterService.isStepOrKeepAliveEnabled(this)) {
- stopService(Intent(this, StepCounterService::class.java))
- } else {
- StepCounterService.startServiceIfEnabled(this)
- }
- }
- }
- }
- private fun setupBatteryOptimizationSection() {
- val row = findViewById(R.id.row_battery_optimization_toggle)
- val tvTitle = row.findViewById(R.id.row_label)
- tvTitle.text = getString(R.string.row_battery_optimization)
- updateBatteryOptimizationSwitch()
- }
- private fun updateBatteryOptimizationSwitch() {
- val row = findViewById(R.id.row_battery_optimization_toggle) ?: return
- val switchOpt = row.findViewById(R.id.row_switch) ?: return
- val powerManager = getSystemService(Context.POWER_SERVICE) as android.os.PowerManager
- val isIgnoring = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
- powerManager.isIgnoringBatteryOptimizations(packageName)
- } else true
-
- switchOpt.setOnCheckedChangeListener(null)
- switchOpt.isChecked = isIgnoring
- switchOpt.setOnCheckedChangeListener { _, isChecked ->
- if (isChecked) {
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
- val isCurrentlyIgnoring = powerManager.isIgnoringBatteryOptimizations(packageName)
- if (!isCurrentlyIgnoring) {
- try {
- val intent = Intent(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply {
- data = android.net.Uri.parse("package:$packageName")
- }
- startActivity(intent)
- } catch (e: Exception) {
- try {
- val intent = Intent(android.provider.Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)
- startActivity(intent)
- } catch (ex: Exception) {
- ex.printStackTrace()
- }
- }
- }
- }
- } else {
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
- val isCurrentlyIgnoring = powerManager.isIgnoringBatteryOptimizations(packageName)
- if (isCurrentlyIgnoring) {
- try {
- val intent = Intent(android.provider.Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)
- startActivity(intent)
- } catch (e: Exception) {
- e.printStackTrace()
- }
- }
- }
- }
- }
- }
- private fun getInstalledCalendarApps(): Pair, List> {
- val labels = mutableListOf("Default")
- val packages = mutableListOf("default")
-
- val knownPackages = listOf(
- "org.fossify.calendar",
- "com.simplemobiletools.calendar",
- "com.google.android.calendar",
- "com.android.calendar",
- "com.samsung.android.calendar",
- "com.bbk.calendar",
- "com.miui.calendar",
- "com.huawei.calendar"
- )
-
- val pm = packageManager
- val calIntent = Intent(Intent.ACTION_VIEW).apply {
- data = android.net.Uri.parse("content://com.android.calendar/time")
- }
- val resolveInfos = pm.queryIntentActivities(calIntent, PackageManager.MATCH_DEFAULT_ONLY)
-
- val foundPackages = mutableSetOf()
- for (info in resolveInfos) {
- val pkg = info.activityInfo.packageName
- foundPackages.add(pkg)
- }
-
- for (pkg in knownPackages) {
- if (isAppInstalled(pkg)) {
- foundPackages.add(pkg)
- }
- }
-
- for (pkg in foundPackages) {
- try {
- val appInfo = pm.getApplicationInfo(pkg, 0)
- val label = pm.getApplicationLabel(appInfo).toString()
- labels.add(label)
- packages.add(pkg)
- } catch (e: Exception) {
- // ignore
- }
- }
-
- return Pair(labels, packages)
- }
-
- private fun setupEventsAndTasksSections() {
- val (calLabels, calPackages) = getInstalledCalendarApps()
- calendarAppPackages = calPackages
-
- val calAppRow = findViewById(R.id.row_events_calendar_app)
-
- // Events
- val eventsSwitch = bindFoldedSection(
- R.id.header_events, R.drawable.ic_events, getString(R.string.section_events),
- R.id.content_events, R.id.row_events_toggle,
- "show_events", false,
- sizeRowId = R.id.row_events_size, prefSizeKey = "size_events", defSize = 14f, minSize = 10f, maxSize = 18f,
- isContent = true,
- onChanged = { isShown ->
- calAppRow?.visibility = if (isShown) View.VISIBLE else View.GONE
- }
- )
-
- bindSelector(
- R.id.row_events_calendar_app,
- getString(R.string.section_events_calendar_app),
- "calendar_app_package",
- calLabels,
- 0
- )
-
- // Show day abbreviation in events (from issue #71)
- bindToggle(R.id.row_events_day_abbr, getString(R.string.row_show_day_abbr), "show_day_abbr_in_events", true)
-
- // Tasks
- val tasksSwitch = bindFoldedSection(
- R.id.header_tasks, R.drawable.ic_tasks, getString(R.string.section_tasks),
- R.id.content_tasks, R.id.row_tasks_toggle,
- "show_tasks", false,
- sizeRowId = R.id.row_tasks_size, prefSizeKey = "size_tasks", defSize = 14f, minSize = 10f, maxSize = 18f,
- isContent = true
- )
-
- // Mutual Exclusion: Events vs Tasks
- eventsSwitch.setOnCheckedChangeListener { _, isChecked ->
- if (isChecked) {
- if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_CALENDAR), 100)
- eventsSwitch.isChecked = false
- return@setOnCheckedChangeListener
- }
- if (checkLimit()) {
- tasksSwitch.isChecked = false
- prefs.edit().putBoolean("show_events", true).putBoolean("show_tasks", false).apply()
- updateFeatureRowVisibility(eventsSwitch, true, R.id.row_events_size, R.id.row_events_day_abbr, R.id.row_events_calendar_app)
- updateFeatureRowVisibility(tasksSwitch, false, R.id.row_tasks_size)
- updateWidget()
- updateToggleAvailability()
- checkAllPermissions()
- } else { eventsSwitch.isChecked = false }
- } else {
- prefs.edit().putBoolean("show_events", false).apply()
- updateFeatureRowVisibility(eventsSwitch, false, R.id.row_events_size, R.id.row_events_day_abbr, R.id.row_events_calendar_app)
- updateWidget()
- updateToggleAvailability()
- checkAllPermissions()
- }
- }
- tasksSwitch.setOnCheckedChangeListener { _, isChecked ->
- if (isChecked) {
- if (!isAppInstalled("org.tasks")) {
- tasksSwitch.isChecked = false
- com.google.android.material.snackbar.Snackbar.make(
- findViewById(R.id.fab_update),
- "Tasks.org app is required for this feature.",
- com.google.android.material.snackbar.Snackbar.LENGTH_LONG
- ).setAction("Install") {
- try {
- startActivity(Intent(Intent.ACTION_VIEW, android.net.Uri.parse("market://details?id=org.tasks")))
- } catch (e: Exception) {
- CustomTabsIntent.Builder().build().launchUrl(this@MainActivity, android.net.Uri.parse("https://play.google.com/store/apps/details?id=org.tasks"))
- }
- }.show()
- return@setOnCheckedChangeListener
- }
- if (ContextCompat.checkSelfPermission(this, AwidgetProvider.PERMISSION_READ_TASKS_ORG) != PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.requestPermissions(this, arrayOf(AwidgetProvider.PERMISSION_READ_TASKS_ORG), 101)
- }
- if (checkLimit()) {
- eventsSwitch.isChecked = false
- prefs.edit().putBoolean("show_tasks", true).putBoolean("show_events", false).apply()
- updateFeatureRowVisibility(tasksSwitch, true, R.id.row_tasks_size)
- updateFeatureRowVisibility(eventsSwitch, false, R.id.row_events_size, R.id.row_events_day_abbr, R.id.row_events_calendar_app)
- updateWidget()
- updateToggleAvailability()
- checkAllPermissions()
- } else { tasksSwitch.isChecked = false }
- } else {
- prefs.edit().putBoolean("show_tasks", false).apply()
- updateFeatureRowVisibility(tasksSwitch, false, R.id.row_tasks_size)
- updateWidget()
- updateToggleAvailability()
- checkAllPermissions()
- }
- }
- }
- private fun setupThemeSection(colorOptions: List) {
- // Appearance Sections
-
- // Appearance Subsections (nested cards)
- bindNestedCard(R.id.header_appearance_presets, getString(R.string.header_presets), R.id.content_appearance_presets, "section_appearance_presets_expanded", R.id.header_chevron_appearance_presets)
- setupPresetsSection()
- bindNestedCard(R.id.header_appearance_outline, getString(R.string.header_outline), R.id.content_appearance_outline, "section_appearance_outline_expanded", R.id.header_chevron_appearance_outline)
- bindNestedCard(R.id.header_appearance_colors, getString(R.string.header_colors), R.id.content_appearance_colors, "section_appearance_colors_expanded", R.id.header_chevron_appearance_colors)
- bindNestedCard(R.id.header_appearance_theme, getString(R.string.header_theme), R.id.content_appearance_theme, "section_appearance_theme_expanded", R.id.header_chevron_appearance_theme)
- bindNestedCard(R.id.header_appearance_font, getString(R.string.header_font), R.id.content_appearance_font, "section_appearance_font_expanded", R.id.header_chevron_appearance_font)
- bindNestedCard(R.id.header_appearance_transparency, getString(R.string.header_transparency), R.id.content_appearance_transparency, "section_appearance_transparency_expanded", R.id.header_chevron_appearance_transparency)
- bindNestedCard(R.id.header_appearance_padding, getString(R.string.header_padding), R.id.content_appearance_padding, "section_appearance_padding_expanded", R.id.header_chevron_appearance_padding)
-
- // Reorder section
- bindReorderSection()
-
- // Outline toggle
- bindToggle(R.id.row_outline_toggle, getString(R.string.row_show_outline), "show_outline", false) { _ ->
- updateWidget()
- }
-
- // Dynamic Colors toggle
- val rowDynamicColors = findViewById(R.id.row_dynamic_colors_toggle)
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
- rowDynamicColors.visibility = View.VISIBLE
- bindToggle(R.id.row_dynamic_colors_toggle, getString(R.string.row_dynamic_colors), "use_dynamic_colors", true) { isChecked ->
- updateColorVisibility(isChecked)
- if (isChecked) {
- prefs.edit()
- .putInt("text_color_primary_idx", 0)
- .putInt("text_color_secondary_idx", 0)
- .putInt("date_color_idx", 0)
- .putInt("outline_color_idx", 0)
- .putInt("bg_color_idx", 0)
- .apply()
- }
- }
- } else {
- rowDynamicColors.visibility = View.GONE
- }
-
- // Theme selector (Auto / Light / Dark)
- bindSelector(
- R.id.row_theme_mode, getString(R.string.row_theme_mode), "theme_mode",
- listOf(getString(R.string.theme_auto), getString(R.string.theme_light), getString(R.string.theme_dark)), 0
- ) { _ ->
- applyTheme()
- }
-
- // BG Transparency
- bindSlider(R.id.row_bg_transparency, getString(R.string.row_bg_opacity), "bg_opacity", 85f, 0f, 100f)
-
- // Widget Padding
- bindSlider(R.id.row_widget_padding, getString(R.string.row_widget_padding), "widget_padding", 24f, 0f, 48f, suffix = "dp")
-
- // Background Color
- val bgSliderRow = findViewById(R.id.row_bg_color_custom)
- bindSelector(R.id.row_bg_color, getString(R.string.section_bg_color), "bg_color_idx", colorOptions, 0) { idx ->
- bgSliderRow.visibility = if (idx == 2) View.VISIBLE else View.GONE
- if (idx != 2) updateWidget()
- }
- bindColorSliders(R.id.row_bg_color_custom, "bg_color")
- bgSliderRow.visibility = if (prefs.getInt("bg_color_idx", 0) == 2) View.VISIBLE else View.GONE
-
- // Text Color Primary
- val primarySliderRow = findViewById(R.id.row_text_color_primary_custom)
- bindSelector(R.id.row_text_color_primary, getString(R.string.section_text_color_primary), "text_color_primary_idx", colorOptions, 0) { idx ->
- primarySliderRow.visibility = if (idx == 2) View.VISIBLE else View.GONE
- if (idx != 2) updateWidget()
- }
- bindColorSliders(R.id.row_text_color_primary_custom, "text_color_primary")
- primarySliderRow.visibility = if (prefs.getInt("text_color_primary_idx", 0) == 2) View.VISIBLE else View.GONE
-
- // Text Color Secondary
- val secondarySliderRow = findViewById(R.id.row_text_color_secondary_custom)
- bindSelector(R.id.row_text_color_secondary, getString(R.string.section_text_color_secondary), "text_color_secondary_idx", colorOptions, 0) { idx ->
- secondarySliderRow.visibility = if (idx == 2) View.VISIBLE else View.GONE
- if (idx != 2) updateWidget()
- }
- bindColorSliders(R.id.row_text_color_secondary_custom, "text_color_secondary")
- secondarySliderRow.visibility = if (prefs.getInt("text_color_secondary_idx", 0) == 2) View.VISIBLE else View.GONE
-
- // Date Color
- val dateSliderRow = findViewById(R.id.row_date_color_custom)
- bindSelector(R.id.row_date_color, getString(R.string.section_date_color), "date_color_idx", colorOptions, 0) { idx ->
- dateSliderRow.visibility = if (idx == 2) View.VISIBLE else View.GONE
- if (idx != 2) updateWidget()
- }
- bindColorSliders(R.id.row_date_color_custom, "date_color")
- dateSliderRow.visibility = if (prefs.getInt("date_color_idx", 0) == 2) View.VISIBLE else View.GONE
-
- // Outline Color
- val outlineSliderRow = findViewById(R.id.row_outline_color_custom)
- bindSelector(R.id.row_outline_color, getString(R.string.section_outline_color), "outline_color_idx", colorOptions, 0) { idx ->
- outlineSliderRow.visibility = if (idx == 2) View.VISIBLE else View.GONE
- if (idx != 2) updateWidget()
- }
- bindColorSliders(R.id.row_outline_color_custom, "outline_color")
- 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))
-
- // Font selector
- bindSelector(R.id.row_font, getString(R.string.section_font), "font_style", listOf(
- getString(R.string.font_default), getString(R.string.font_serif), getString(R.string.font_monospace), getString(R.string.font_cursive),
- getString(R.string.font_condensed), getString(R.string.font_condensed_light), getString(R.string.font_light), getString(R.string.font_medium),
- getString(R.string.font_black), getString(R.string.font_thin), getString(R.string.font_smallcaps)
- ), 0)
-
- updateToggleAvailability()
- }
-
- private data class LanguageOption(val code: String, val displayName: String)
-
- private fun setupLanguageSection() {
- val languages = listOf(
- LanguageOption("", getString(R.string.lang_system_default)),
- LanguageOption("en", "English"),
- LanguageOption("es", "Español (Spanish)"),
- LanguageOption("zh", "简体中文 (Chinese)"),
- LanguageOption("hi", "हिन्दी (Hindi)"),
- LanguageOption("ar", "العربية (Arabic)"),
- LanguageOption("fr", "Français (French)"),
- LanguageOption("pt", "Português (Portuguese)"),
- LanguageOption("ru", "Русский (Russian)"),
- LanguageOption("de", "Deutsch (German)"),
- LanguageOption("ja", "日本語 (Japanese)"),
- LanguageOption("tr", "Türkçe (Turkish)")
- )
- val languageLabels = languages.map { it.displayName }
- val currentLocales = androidx.appcompat.app.AppCompatDelegate.getApplicationLocales()
- val currentTag = if (currentLocales.isEmpty) "" else currentLocales.get(0)?.language ?: ""
- val currentIdx = languages.indexOfFirst { it.code.equals(currentTag, ignoreCase = true) }.coerceAtLeast(0)
-
- val row = findViewById(R.id.row_app_language) ?: return
- val tvTitle = row.findViewById(R.id.row_label)
- val autoCompleteTextView = row.findViewById(R.id.row_value)
-
- tvTitle.text = getString(R.string.section_app_language)
- val adapter = android.widget.ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, languageLabels)
- autoCompleteTextView.setAdapter(adapter)
- autoCompleteTextView.setText(languageLabels[currentIdx], false)
-
- autoCompleteTextView.setOnItemClickListener { _, _, position, _ ->
- val selected = languages.getOrElse(position) { languages[0] }
- val localeList = if (selected.code.isEmpty()) {
- androidx.core.os.LocaleListCompat.getEmptyLocaleList()
- } else {
- androidx.core.os.LocaleListCompat.forLanguageTags(selected.code)
- }
- androidx.appcompat.app.AppCompatDelegate.setApplicationLocales(localeList)
- }
- }
-
- private fun setupPresetsSection() {
- data class Preset(
- val key: String,
- val label: String,
- val prefs: Map
- )
-
- val presets = listOf(
- // Minimal: just time+date, white text, fully transparent, thin font
- Preset("minimal", getString(R.string.preset_minimal), mapOf(
- "show_outline" to false, "bg_opacity" to 0f,
- "font_style" to 9, // Thin
- "use_dynamic_colors" to false,
- "text_color_primary_idx" to 2, "text_color_primary_r" to 255, "text_color_primary_g" to 255, "text_color_primary_b" to 255,
- "text_color_secondary_idx" to 2, "text_color_secondary_r" to 200, "text_color_secondary_g" to 200, "text_color_secondary_b" to 200,
- "date_color_idx" to 2, "date_color_r" to 180, "date_color_g" to 180, "date_color_b" to 190,
- "bold_battery" to false, "bold_temp" to false
- )),
- // Neon: cyan time, magenta date, dark bg, bold condensed font
- Preset("neon", getString(R.string.preset_neon), mapOf(
- "bold_battery" to true, "bold_temp" to true,
- "show_outline" to true, "bg_opacity" to 95f,
- "font_style" to 4, // Condensed
- "use_dynamic_colors" to false,
- "text_color_primary_idx" to 2, "text_color_primary_r" to 0, "text_color_primary_g" to 255, "text_color_primary_b" to 255,
- "text_color_secondary_idx" to 2, "text_color_secondary_r" to 0, "text_color_secondary_g" to 200, "text_color_secondary_b" to 200,
- "date_color_idx" to 2, "date_color_r" to 255, "date_color_g" to 0, "date_color_b" to 180,
- "outline_color_idx" to 2, "outline_color_r" to 0, "outline_color_g" to 200, "outline_color_b" to 255,
- "bg_color_idx" to 2, "bg_color_r" to 10, "bg_color_g" to 10, "bg_color_b" to 20
- )),
- // Cockpit: green on dark, monospace, info-heavy, terminal look
- Preset("cockpit", getString(R.string.preset_cockpit), mapOf(
- "bold_battery" to false, "bold_temp" to false,
- "bold_storage" to false, "bold_ram" to false, "bold_data_usage" to false,
- "show_outline" to true, "bg_opacity" to 90f,
- "font_style" to 2, // Monospace
- "use_dynamic_colors" to false,
- "text_color_primary_idx" to 2, "text_color_primary_r" to 0, "text_color_primary_g" to 255, "text_color_primary_b" to 65,
- "text_color_secondary_idx" to 2, "text_color_secondary_r" to 0, "text_color_secondary_g" to 180, "text_color_secondary_b" to 50,
- "date_color_idx" to 2, "date_color_r" to 0, "date_color_g" to 200, "date_color_b" to 80,
- "outline_color_idx" to 2, "outline_color_r" to 0, "outline_color_g" to 120, "outline_color_b" to 40,
- "bg_color_idx" to 2, "bg_color_r" to 5, "bg_color_g" to 15, "bg_color_b" to 5
- )),
- // Sunset: warm oranges/gold, serif font, elegant minimal
- Preset("sunset", getString(R.string.preset_sunset), mapOf(
- "bold_battery" to true,
- "show_outline" to false, "bg_opacity" to 70f,
- "font_style" to 1, // Serif
- "use_dynamic_colors" to false,
- "text_color_primary_idx" to 2, "text_color_primary_r" to 255, "text_color_primary_g" to 180, "text_color_primary_b" to 50,
- "text_color_secondary_idx" to 2, "text_color_secondary_r" to 230, "text_color_secondary_g" to 140, "text_color_secondary_b" to 60,
- "date_color_idx" to 2, "date_color_r" to 255, "date_color_g" to 120, "date_color_b" to 50,
- "bg_color_idx" to 2, "bg_color_r" to 30, "bg_color_g" to 15, "bg_color_b" to 8
- )),
- // Monochrome: white outline, all white text, medium font, classic layout
- Preset("monochrome", getString(R.string.preset_monochrome), mapOf(
- "bold_battery" to false,
- "show_outline" to true, "bg_opacity" to 50f,
- "font_style" to 7, // Medium
- "use_dynamic_colors" to false,
- "text_color_primary_idx" to 2, "text_color_primary_r" to 240, "text_color_primary_g" to 240, "text_color_primary_b" to 240,
- "text_color_secondary_idx" to 2, "text_color_secondary_r" to 170, "text_color_secondary_g" to 170, "text_color_secondary_b" to 170,
- "date_color_idx" to 2, "date_color_r" to 200, "date_color_g" to 200, "date_color_b" to 200,
- "outline_color_idx" to 2, "outline_color_r" to 100, "outline_color_g" to 100, "outline_color_b" to 100,
- "bg_color_idx" to 2, "bg_color_r" to 25, "bg_color_g" to 25, "bg_color_b" to 25
- )),
- // Snowfall: icy blues, light font, airy feel
- Preset("snowfall", getString(R.string.preset_snowfall), mapOf(
- "bold_temp" to false,
- "show_outline" to false, "bg_opacity" to 60f,
- "font_style" to 6, // Light
- "use_dynamic_colors" to false,
- "text_color_primary_idx" to 2, "text_color_primary_r" to 180, "text_color_primary_g" to 220, "text_color_primary_b" to 255,
- "text_color_secondary_idx" to 2, "text_color_secondary_r" to 130, "text_color_secondary_g" to 180, "text_color_secondary_b" to 230,
- "date_color_idx" to 2, "date_color_r" to 100, "date_color_g" to 170, "date_color_b" to 255,
- "bg_color_idx" to 2, "bg_color_r" to 10, "bg_color_g" to 20, "bg_color_b" to 40
- ))
- )
-
- val chipGroup = findViewById(R.id.preset_chip_group)
- chipGroup.removeAllViews()
- val activePreset = prefs.getString("active_preset", null)
-
- val primaryContainer = com.google.android.material.color.MaterialColors.getColor(
- chipGroup, com.google.android.material.R.attr.colorPrimaryContainer
- )
- val surfaceContainer = com.google.android.material.color.MaterialColors.getColor(
- chipGroup, com.google.android.material.R.attr.colorSurfaceContainerHighest
- )
- val onPrimaryContainer = com.google.android.material.color.MaterialColors.getColor(
- chipGroup, com.google.android.material.R.attr.colorOnPrimaryContainer
- )
- val onSurfaceVariant = com.google.android.material.color.MaterialColors.getColor(
- chipGroup, com.google.android.material.R.attr.colorOnSurfaceVariant
- )
-
- val chipBgStateList = android.content.res.ColorStateList(
- arrayOf(
- intArrayOf(android.R.attr.state_checked),
- intArrayOf(-android.R.attr.state_checked)
- ),
- intArrayOf(
- primaryContainer,
- surfaceContainer
- )
- )
-
- val chipTextStateList = android.content.res.ColorStateList(
- arrayOf(
- intArrayOf(android.R.attr.state_checked),
- intArrayOf(-android.R.attr.state_checked)
- ),
- intArrayOf(
- onPrimaryContainer,
- onSurfaceVariant
- )
- )
-
- val density = resources.displayMetrics.density
-
- for (preset in presets) {
- val chip = com.google.android.material.chip.Chip(this).apply {
- text = preset.label
- isCheckable = true
- isChecked = (preset.key == activePreset)
- isCheckedIconVisible = false
- shapeAppearanceModel = shapeAppearanceModel.toBuilder().setAllCornerSizes(14f * density).build()
- chipBackgroundColor = chipBgStateList
- setTextColor(chipTextStateList)
- chipStrokeWidth = 0f
- setEnsureMinTouchTargetSize(false)
- textSize = 13f
- typeface = android.graphics.Typeface.DEFAULT_BOLD
- setOnClickListener {
- val editor = prefs.edit()
- for ((k, v) in preset.prefs) {
- when (v) {
- is Boolean -> editor.putBoolean(k, v)
- is Float -> editor.putFloat(k, v)
- is Int -> editor.putInt(k, v)
- is String -> editor.putString(k, v)
- }
- }
- editor.putString("active_preset", preset.key)
- editor.apply()
- updateWidget()
- recreate()
- }
- }
- chipGroup.addView(chip)
- }
- }
-
- private fun bindToggle(
- viewId: Int, title: String, prefShowKey: String, defShow: Boolean,
- isContent: Boolean = false,
- onChanged: ((Boolean) -> Unit)? = null
- ) {
- val row = findViewById(viewId)
- val tvTitle = row.findViewById(R.id.row_label)
- val switch = row.findViewById(R.id.row_switch)
-
- tvTitle.text = title
- switch.tag = prefShowKey
- if (isContent) contentSwitches.add(switch)
-
- val isShown = prefs.getBoolean(prefShowKey, defShow)
- switch.isChecked = isShown
- onChanged?.invoke(isShown)
-
- switch.setOnCheckedChangeListener { _, isChecked ->
- if (isChecked && !checkLimit()) {
- switch.isChecked = false
- return@setOnCheckedChangeListener
- }
- prefs.edit().putBoolean(prefShowKey, isChecked).apply()
- onChanged?.invoke(isChecked)
- updateWidget()
- if (isContent) updateToggleAvailability()
- }
- }
-
-
- private fun bindSlider(
- viewId: Int, title: String, prefKey: String, defValue: Float,
- minValue: Float, maxValue: Float, suffix: String = "%"
- ) {
- val row = findViewById(viewId)
- val tvTitle = row.findViewById(R.id.row_label)
- val slider = row.findViewById(R.id.row_slider)
- val tvValue = row.findViewById(R.id.row_value)
-
- tvTitle.text = title
-
- val currentValue = prefs.getFloat(prefKey, defValue)
- slider.valueFrom = minValue
- slider.valueTo = maxValue
- slider.value = currentValue.coerceIn(minValue, maxValue)
- tvValue.text = "${currentValue.toInt()}$suffix"
-
- slider.addOnChangeListener { _, value, fromUser ->
- if (fromUser) {
- tvValue.text = "${value.toInt()}$suffix"
- prefs.edit().putFloat(prefKey, value).apply()
- updateWidget()
- }
- }
- }
-
- private fun bindSelector(
- viewId: Int, title: String, prefKey: String, options: List,
- defaultIdx: Int, onSelectionChanged: ((Int) -> Unit)? = null
- ) {
- val row = findViewById(viewId)
- val tvTitle = row.findViewById(R.id.row_label)
- val autoCompleteTextView = row.findViewById(R.id.row_value)
-
- tvTitle.text = title
-
- 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") {
- val appPackages = if (prefKey == "clock_app_package") clockAppPackages else calendarAppPackages
- val currentVal = prefs.getString(prefKey, "default") ?: "default"
- val currentIdx = appPackages.indexOf(currentVal).coerceAtLeast(0)
- autoCompleteTextView.setText(options.getOrElse(currentIdx) { options[0] }, false)
- autoCompleteTextView.setOnItemClickListener { _, _, position, _ ->
- val selected = appPackages.getOrElse(position) { "default" }
- prefs.edit().putString(prefKey, selected).apply()
- updateWidget()
- onSelectionChanged?.invoke(position)
- row.requestFocus()
- autoCompleteTextView.clearFocus()
- }
- } else {
- val currentIdx = prefs.getInt(prefKey, defaultIdx)
- autoCompleteTextView.setText(options.getOrElse(currentIdx) { options[defaultIdx] }, false)
- autoCompleteTextView.setOnItemClickListener { _, _, position, _ ->
- prefs.edit().putInt(prefKey, position).apply()
- updateWidget()
- onSelectionChanged?.invoke(position)
- row.requestFocus()
- autoCompleteTextView.clearFocus()
- }
- }
- }
-
- private fun bindColorSliders(viewId: Int, prefPrefix: String): View {
- val row = findViewById(viewId)
- val sliderRed = row.findViewById(R.id.slider_red)
- val sliderGreen = row.findViewById(R.id.slider_green)
- val sliderBlue = row.findViewById(R.id.slider_blue)
- val valRed = row.findViewById(R.id.val_red)
- val valGreen = row.findViewById(R.id.val_green)
- val valBlue = row.findViewById(R.id.val_blue)
- val preview = row.findViewById(R.id.color_preview)
-
- val r = prefs.getInt("${prefPrefix}_r", 255)
- val g = prefs.getInt("${prefPrefix}_g", 255)
- val b = prefs.getInt("${prefPrefix}_b", 255)
-
- fun updatePreview() {
- val color = android.graphics.Color.rgb(sliderRed.value.toInt(), sliderGreen.value.toInt(), sliderBlue.value.toInt())
- preview.backgroundTintList = android.content.res.ColorStateList.valueOf(color)
- valRed.text = sliderRed.value.toInt().toString()
- valGreen.text = sliderGreen.value.toInt().toString()
- valBlue.text = sliderBlue.value.toInt().toString()
- }
-
- sliderRed.value = r.toFloat()
- sliderGreen.value = g.toFloat()
- sliderBlue.value = b.toFloat()
- updatePreview()
-
- val listener = Slider.OnChangeListener { _, _, fromUser ->
- if (fromUser) {
- updatePreview()
- prefs.edit()
- .putInt("${prefPrefix}_r", sliderRed.value.toInt())
- .putInt("${prefPrefix}_g", sliderGreen.value.toInt())
- .putInt("${prefPrefix}_b", sliderBlue.value.toInt())
- .apply()
- updateWidget()
- }
- }
-
- sliderRed.addOnChangeListener(listener)
- sliderGreen.addOnChangeListener(listener)
- sliderBlue.addOnChangeListener(listener)
-
- return row
- }
-
- private fun updateColorVisibility(useDynamicColors: Boolean) {
- val manualColorIds = listOf(
- R.id.row_bg_color, R.id.row_bg_color_custom,
- R.id.row_text_color_primary, R.id.row_text_color_primary_custom,
- R.id.row_text_color_secondary, R.id.row_text_color_secondary_custom,
- R.id.row_date_color, R.id.row_date_color_custom,
- R.id.row_outline_color, R.id.row_outline_color_custom
- )
- manualColorIds.forEach { id ->
- findViewById(id).visibility = if (useDynamicColors) View.GONE else View.VISIBLE
- }
- }
-
- private fun applyTheme() {
- updateWidget()
- }
-
- private fun 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
- }
-
- // Check usage stats permission
- private fun hasUsageStatsPermission(): Boolean {
- val appOps = getSystemService(Context.APP_OPS_SERVICE) as android.app.AppOpsManager
- val opMode = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
- appOps.unsafeCheckOpNoThrow(android.app.AppOpsManager.OPSTR_GET_USAGE_STATS,
- android.os.Process.myUid(), packageName)
- } else {
- @Suppress("DEPRECATION")
- appOps.checkOpNoThrow(android.app.AppOpsManager.OPSTR_GET_USAGE_STATS,
- android.os.Process.myUid(), packageName)
- }
- return opMode == android.app.AppOpsManager.MODE_ALLOWED
- }
-
- private fun updateToggleAvailability() {
- // Limit removed
- // Ensure all are enabled
- for (switch in contentSwitches) {
- switch.isEnabled = true
- switch.alpha = 1.0f
- }
- }
-
- private fun isAppInstalled(packageName: String): Boolean {
- return try {
- packageManager.getPackageInfo(packageName, 0)
- true
- } catch (e: PackageManager.NameNotFoundException) {
- false
- }
- }
-
- private fun updateWidget() {
+ internal fun updateWidget() {
setupPreviewWallpaper()
updateLivePreview()
// Animation: Subtle Outline Shine
@@ -2265,140 +460,6 @@ class MainActivity : AppCompatActivity() {
sendBroadcast(intent)
}
- private fun setupGlobalSettingsSearch() {
- val searchInput = findViewById(R.id.search_settings_input) ?: return
- val headerNormal = findViewById(R.id.header_normal)
- val headerSearch = findViewById(R.id.header_search_mode)
- val btnSearchToggle = findViewById(R.id.btn_search_toggle)
- val btnSearchClose = findViewById(R.id.btn_search_close)
- val btnSearchClear = findViewById(R.id.btn_search_clear)
- val appBar = findViewById(R.id.app_bar)
-
- val tabContainers = listOf(
- findViewById(R.id.container_tab_style),
- findViewById(R.id.container_tab_content),
- findViewById(R.id.container_tab_layout),
- findViewById(R.id.container_tab_system)
- )
- val tabLayout = findViewById(R.id.tab_layout)
-
- fun closeSearch() {
- searchInput.setText("")
- val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager
- imm?.hideSoftInputFromWindow(searchInput.windowToken, 0)
- searchInput.clearFocus()
- headerSearch?.visibility = View.GONE
- headerNormal?.visibility = View.VISIBLE
- }
-
- fun openSearch() {
- headerNormal?.visibility = View.GONE
- headerSearch?.visibility = View.VISIBLE
- appBar?.setExpanded(true, true)
- searchInput.requestFocus()
- val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager
- imm?.showSoftInput(searchInput, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
- }
-
- btnSearchToggle?.setOnClickListener { openSearch() }
- btnSearchClose?.setOnClickListener { closeSearch() }
- btnSearchClear?.setOnClickListener { searchInput.setText("") }
-
- onBackPressedDispatcher.addCallback(this, object : androidx.activity.OnBackPressedCallback(true) {
- override fun handleOnBackPressed() {
- if (headerSearch?.visibility == View.VISIBLE) {
- closeSearch()
- } else {
- isEnabled = false
- onBackPressedDispatcher.onBackPressed()
- }
- }
- })
-
- searchInput.setOnFocusChangeListener { _, hasFocus ->
- if (hasFocus) {
- appBar?.setExpanded(true, true)
- }
- }
-
- val cardMap = mapOf(
- // Style Tab
- R.id.card_appearance_presets to listOf("presets", "themes", "minimal", "neon", "cockpit", "sunset", "monochrome", "snowfall"),
- R.id.card_appearance_outline to listOf("outline", "border", "stroke", "outline color", "stroke width"),
- R.id.card_appearance_colors to listOf("colors", "dynamic colors", "text color", "background color", "custom colors", "rgb"),
- R.id.card_appearance_theme to listOf("theme", "dark mode", "light mode", "system theme", "mode"),
- R.id.card_appearance_font to listOf("font", "typeface", "typography", "serif", "mono", "monospace", "cursive", "condensed", "thin", "light", "bold"),
- R.id.card_appearance_transparency to listOf("transparency", "opacity", "background opacity", "alpha"),
- R.id.card_appearance_padding to listOf("padding", "margin", "spacing", "inset"),
-
- // Content Tab
- R.id.card_time to listOf("time", "clock", "hour", "format", "12-hour", "24-hour", "clock app"),
- R.id.card_next_alarm to listOf("alarm", "next alarm", "upcoming alarm"),
- R.id.card_world_clock to listOf("world clock", "timezone", "time zone", "utc"),
- R.id.card_date to listOf("date", "calendar", "day", "month"),
- R.id.card_battery to listOf("battery", "percentage", "charging", "battery level"),
- R.id.card_temp to listOf("temperature", "temp", "battery temp", "celsius", "fahrenheit"),
- R.id.card_weather to listOf("weather", "forecast", "breezy", "condition", "breezy weather"),
- R.id.card_data to listOf("data", "data usage", "cellular", "wifi", "network"),
- R.id.card_storage to listOf("storage", "internal storage", "disk", "free space"),
- R.id.card_ram to listOf("ram", "memory", "free ram", "ram usage"),
- R.id.card_steps to listOf("steps", "step counter", "activity", "fitness", "pedometer", "walking"),
- R.id.card_screen_time to listOf("screen time", "usage", "digital wellbeing"),
- R.id.card_events to listOf("events", "calendar", "agenda", "calendar app", "schedule"),
- R.id.card_tasks to listOf("tasks", "tasks.org", "todo", "to-do", "task list"),
-
- // Layout Tab
- R.id.card_appearance_reorder to listOf("reorder", "order", "column", "layout", "arrange", "drag", "stack"),
-
- // System Tab
- R.id.card_language to listOf("language", "locale", "translation", "languages"),
- R.id.card_advanced to listOf("advanced", "keep alive", "battery optimization", "foreground service", "service", "backup", "export", "import"),
- R.id.card_permissions to listOf("permissions", "calendar permission", "usage stats", "activity recognition", "notifications"),
- R.id.card_about to listOf("about", "version", "github", "source code", "developer", "license", "privacy", "author"),
- R.id.card_changelog to listOf("changelog", "whats new", "updates", "history")
- )
-
- val headerLabels: List = listOfNotNull(
- findViewById(R.id.label_category_content),
- findViewById(R.id.label_category_stats)
- )
-
- searchInput.addTextChangedListener(object : android.text.TextWatcher {
- override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
- override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
- override fun afterTextChanged(s: android.text.Editable?) {
- val query = s?.toString()?.trim()?.lowercase() ?: ""
- val isSearching = query.isNotEmpty()
- btnSearchClear?.visibility = if (isSearching) View.VISIBLE else View.GONE
-
- if (isSearching) {
- // Make all tab containers visible so search shows matches across all categories
- tabContainers.forEach { container -> container?.visibility = View.VISIBLE }
- tabLayout?.visibility = View.GONE
-
- for ((cardId, keywords) in cardMap) {
- val card = findViewById(cardId) ?: continue
- val matches = keywords.any { it.contains(query) }
- card.visibility = if (matches) View.VISIBLE else View.GONE
- }
- headerLabels.forEach { label ->
- label.visibility = View.GONE
- }
- } else {
- // Restore tabs and active container
- tabLayout?.visibility = View.VISIBLE
- val selectedTab = tabLayout?.selectedTabPosition?.coerceIn(0, 3) ?: 0
- tabContainers.forEachIndexed { index, container ->
- container?.visibility = if (index == selectedTab) View.VISIBLE else View.GONE
- }
- for ((cardId, _) in cardMap) {
- findViewById(cardId)?.visibility = View.VISIBLE
- }
- headerLabels.forEach { label ->
- label.visibility = View.VISIBLE
- }
- }
- }
- })
- }
}
+
+private const val WIDGET_UPDATE_DEBOUNCE_MS = 120L
diff --git a/app/src/main/java/com/leanbitlab/lwidget/ReorderAdapter.kt b/app/src/main/java/com/leanbitlab/lwidget/ReorderAdapter.kt
new file mode 100644
index 0000000..6072433
--- /dev/null
+++ b/app/src/main/java/com/leanbitlab/lwidget/ReorderAdapter.kt
@@ -0,0 +1,116 @@
+/*
+ * Copyright (C) 2026 LeanBitLab
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+
+package com.leanbitlab.lwidget
+
+import android.view.MotionEvent
+import android.view.View
+import android.os.Bundle
+import androidx.core.view.AccessibilityDelegateCompat
+import androidx.core.view.ViewCompat
+import androidx.core.view.accessibility.AccessibilityNodeInfoCompat
+import android.widget.TextView
+import androidx.recyclerview.widget.RecyclerView
+
+// Data class for reorderable items
+data class ReorderItem(
+ val key: String, // e.g. "show_battery"
+ val label: String, // e.g. "Battery"
+ var enabled: Boolean
+)
+
+// Adapter for reorder RecyclerView
+class ReorderAdapter(
+ private val items: MutableList,
+ private val onStartDrag: (RecyclerView.ViewHolder) -> Unit,
+ private val onOrderChanged: () -> Unit = {}
+) : RecyclerView.Adapter() {
+
+ class ViewHolder(val view: android.view.View) : RecyclerView.ViewHolder(view) {
+ val handle: android.widget.ImageView = view.findViewById(R.id.reorder_handle)
+ val name: TextView = view.findViewById(R.id.reorder_item_name)
+ val status: TextView? = view.findViewById(R.id.reorder_item_status)
+ }
+
+ override fun onCreateViewHolder(parent: android.view.ViewGroup, viewType: Int): ViewHolder {
+ val view = android.view.LayoutInflater.from(parent.context)
+ .inflate(R.layout.settings_reorder_item, parent, false)
+ return ViewHolder(view)
+ }
+
+ override fun onBindViewHolder(holder: ViewHolder, position: Int) {
+ val item = items[position]
+ holder.name.text = item.label
+ if (item.enabled) {
+ holder.view.alpha = 1.0f
+ holder.status?.visibility = android.view.View.GONE
+ } else {
+ holder.view.alpha = 0.4f
+ holder.status?.visibility = android.view.View.VISIBLE
+ }
+
+ // Touch-drag has no keyboard/TalkBack equivalent, so expose explicit move actions.
+ ViewCompat.setAccessibilityDelegate(holder.view, object : AccessibilityDelegateCompat() {
+ override fun onInitializeAccessibilityNodeInfo(host: View, info: AccessibilityNodeInfoCompat) {
+ super.onInitializeAccessibilityNodeInfo(host, info)
+ val pos = holder.adapterPosition
+ if (pos == RecyclerView.NO_POSITION) return
+ if (pos > 0) {
+ info.addAction(AccessibilityNodeInfoCompat.AccessibilityActionCompat(
+ R.id.a11y_action_move_up, host.context.getString(R.string.a11y_move_up)))
+ }
+ if (pos < items.size - 1) {
+ info.addAction(AccessibilityNodeInfoCompat.AccessibilityActionCompat(
+ R.id.a11y_action_move_down, host.context.getString(R.string.a11y_move_down)))
+ }
+ }
+
+ override fun performAccessibilityAction(host: View, action: Int, args: Bundle?): Boolean {
+ val pos = holder.adapterPosition
+ if (pos == RecyclerView.NO_POSITION) return super.performAccessibilityAction(host, action, args)
+ val target = when (action) {
+ R.id.a11y_action_move_up -> pos - 1
+ R.id.a11y_action_move_down -> pos + 1
+ else -> return super.performAccessibilityAction(host, action, args)
+ }
+ if (target !in items.indices) return false
+ moveItem(pos, target)
+ onOrderChanged()
+ return true
+ }
+ })
+
+ holder.handle.setOnTouchListener { v, event ->
+ if (event.actionMasked == MotionEvent.ACTION_DOWN) {
+ v.performHapticFeedback(android.view.HapticFeedbackConstants.CONTEXT_CLICK)
+ onStartDrag(holder)
+ true
+ } else {
+ false
+ }
+ }
+ }
+
+ override fun getItemCount() = items.size
+
+ fun moveItem(from: Int, to: Int) {
+ if (from == to) return
+ val item = items.removeAt(from)
+ items.add(to, item)
+ notifyItemMoved(from, to)
+ }
+}
diff --git a/app/src/main/java/com/leanbitlab/lwidget/SettingsAccordion.kt b/app/src/main/java/com/leanbitlab/lwidget/SettingsAccordion.kt
new file mode 100644
index 0000000..83aeabe
--- /dev/null
+++ b/app/src/main/java/com/leanbitlab/lwidget/SettingsAccordion.kt
@@ -0,0 +1,420 @@
+/*
+ * Copyright (C) 2026 LeanBitLab
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+
+
+package com.leanbitlab.lwidget
+
+import android.content.Context
+import android.view.View
+import android.widget.AutoCompleteTextView
+import android.widget.ImageView
+import android.widget.ListView
+import android.widget.TextView
+import android.view.ViewGroup
+import com.google.android.material.card.MaterialCardView
+import com.google.android.material.slider.Slider
+import com.google.android.material.switchmaterial.SwitchMaterial
+import androidx.core.widget.NestedScrollView
+import androidx.interpolator.view.animation.FastOutSlowInInterpolator
+import androidx.transition.AutoTransition
+import androidx.transition.TransitionManager
+
+internal fun MainActivity.toggleSectionExpansion(
+ header: View,
+ content: View,
+ chevron: ImageView,
+ prefKey: String,
+ sectionKey: String? = null
+) {
+ val nestedScrollView = findViewById(R.id.nested_scroll_view)
+ val nowExpanded = content.visibility != View.VISIBLE
+
+ if (!nowExpanded && sectionKey != null) {
+ collapseSectionNestedContent(sectionKey)
+ }
+
+ val parentViewGroup = (header.parent as? ViewGroup) ?: (nestedScrollView as? ViewGroup)
+ if (parentViewGroup != null) {
+ TransitionManager.beginDelayedTransition(
+ parentViewGroup,
+ AutoTransition().apply {
+ duration = 220L
+ interpolator = FastOutSlowInInterpolator()
+ }
+ )
+ }
+
+ content.visibility = if (nowExpanded) View.VISIBLE else View.GONE
+ prefs.edit().putBoolean(prefKey, nowExpanded).apply()
+
+ chevron.animate()
+ .rotation(if (nowExpanded) 180f else 0f)
+ .setDuration(220L)
+ .setInterpolator(FastOutSlowInInterpolator())
+ .start()
+
+ if (nowExpanded && nestedScrollView != null) {
+ header.postDelayed({
+ if (!isDestroyed && !isFinishing) {
+ val rect = android.graphics.Rect()
+ header.getDrawingRect(rect)
+ nestedScrollView.offsetDescendantRectToMyCoords(header, rect)
+ val scrollY = nestedScrollView.scrollY
+ val viewportHeight = nestedScrollView.height
+ val headerTop = rect.top
+ if (headerTop < scrollY || headerTop > scrollY + (viewportHeight * 0.65f)) {
+ nestedScrollView.smoothScrollTo(0, headerTop.coerceAtLeast(0))
+ }
+ }
+ }, 100L)
+ }
+}
+
+internal fun MainActivity.bindFoldedSection(
+ headerId: Int, iconResId: Int?, title: String,
+ contentId: Int,
+ toggleRowId: Int,
+ prefShowKey: String, defShow: Boolean,
+ sizeRowId: Int? = null, prefSizeKey: String? = null,
+ defSize: Float = 14f, minSize: Float = 10f, maxSize: Float = 72f,
+ selectorRowId: Int? = null, selectorOptions: List? = null,
+ prefSelectorKey: String? = null, defSelectorIdx: Int = 0,
+ boldRowId: Int? = null,
+ isContent: Boolean = false,
+ subSettingsContainerId: Int? = null,
+ validateToggle: ((Boolean) -> Boolean)? = null,
+ onChanged: ((Boolean) -> Unit)? = null
+): SwitchMaterial {
+ val header = findViewById(headerId)
+ val chevron = header.findViewById(R.id.header_chevron)
+ val headerIcon = header.findViewById(R.id.header_icon)
+ val headerTitle = header.findViewById(R.id.header_title)
+ val content = findViewById(contentId)
+
+ val sectionKey = prefShowKey.replace("show_", "")
+ val expandedPrefKey = "section_${sectionKey}_expanded"
+ accordionViews[expandedPrefKey] = content
+ accordionHeaders[expandedPrefKey] = header
+
+ headerTitle.text = title
+ if (iconResId != null) {
+ headerIcon.setImageResource(iconResId)
+ headerIcon.visibility = View.VISIBLE
+ } else {
+ headerIcon.visibility = View.GONE
+ }
+
+ // Expand/collapse - read from prefs, apply visibility
+ val isExpandedFromPrefs = prefs.getBoolean(expandedPrefKey, false)
+ content.visibility = if (isExpandedFromPrefs) View.VISIBLE else View.GONE
+ chevron.rotation = if (isExpandedFromPrefs) 180f else 0f
+
+ // Header click: smooth expand/collapse with auto-scroll
+ header.setOnClickListener {
+ toggleSectionExpansion(header, content, chevron, expandedPrefKey, sectionKey)
+ }
+
+ // Toggle row
+ val toggleRow = findViewById(toggleRowId)
+ val toggleSwitch = toggleRow.findViewById(R.id.row_switch)
+ val toggleLabel = toggleRow.findViewById(R.id.row_label)
+ val toggleCard = toggleRow.findViewById(R.id.toggle_row_card)
+ toggleLabel.setText(R.string.label_enable)
+
+ toggleSwitch.tag = prefShowKey
+ if (isContent) contentSwitches.add(toggleSwitch)
+
+ val isShown = prefs.getBoolean(prefShowKey, defShow)
+ toggleSwitch.isChecked = isShown
+
+ // Sub-settings alpha
+ val subSettings = subSettingsContainerId?.let { findViewById(it) }
+ subSettings?.alpha = if (isShown) 1.0f else 0.4f
+ updateToggleCardStyle(toggleCard, isShown)
+
+ // Child rows visibility
+ val sizeRow = sizeRowId?.let { findViewById(it) }
+ sizeRow?.visibility = if (isShown) View.VISIBLE else View.GONE
+
+ val selectorRow = selectorRowId?.let { findViewById(it) }
+ selectorRow?.visibility = if (isShown) View.VISIBLE else View.GONE
+
+ val boldRow = boldRowId?.let { findViewById(it) }
+ boldRow?.visibility = if (isShown) View.VISIBLE else View.GONE
+
+ onChanged?.invoke(isShown)
+
+ // 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)
+
+ val parentViewGroup = (toggleRow.parent as? ViewGroup)
+ if (parentViewGroup != null) {
+ TransitionManager.beginDelayedTransition(
+ parentViewGroup,
+ AutoTransition().apply {
+ duration = 180L
+ }
+ )
+ }
+
+ sizeRow?.visibility = if (isChecked) View.VISIBLE else View.GONE
+ selectorRow?.visibility = if (isChecked) View.VISIBLE else View.GONE
+ boldRow?.visibility = if (isChecked) View.VISIBLE else View.GONE
+ onChanged?.invoke(isChecked)
+ updateWidget()
+ if (isContent) updateToggleAvailability()
+ }
+
+ // Size row setup
+ if (sizeRowId != null && prefSizeKey != null) {
+ val sizeRowInner = findViewById(sizeRowId)
+ val slider = sizeRowInner.findViewById(R.id.row_slider)
+ val valueLabel = sizeRowInner.findViewById(R.id.row_value)
+ val sizeLabel = sizeRowInner.findViewById(R.id.row_label)
+ sizeLabel.setText(R.string.label_size)
+
+ val currentSize = prefs.getFloat(prefSizeKey, defSize)
+ slider.valueFrom = minSize
+ slider.valueTo = maxSize
+ slider.value = currentSize.coerceIn(minSize, maxSize)
+ valueLabel.text = "${currentSize.toInt()}"
+
+ slider.addOnChangeListener { _, value, fromUser ->
+ if (fromUser) {
+ valueLabel.text = "${value.toInt()}"
+ prefs.edit().putFloat(prefSizeKey, value).apply()
+ scheduleWidgetUpdate()
+ }
+ }
+ }
+
+ // Selector row setup (skip world clock timezone - uses custom search layout)
+ if (selectorRowId != null && selectorOptions != null && prefSelectorKey != null && prefSelectorKey != "world_clock_zone_str") {
+ val selectorRowInner = findViewById(selectorRowId)
+ val autoCompleteTextView = selectorRowInner.findViewById(R.id.row_value)
+ val selectorLabel = selectorRowInner.findViewById(R.id.row_label)
+ selectorLabel.text = title
+
+ 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()
+ }
+ }
+
+ // Clear focus/dropdown shade when dismissed
+ autoCompleteTextView.setOnFocusChangeListener { _, hasFocus ->
+ if (!hasFocus) {
+ autoCompleteTextView.clearFocus()
+ }
+ }
+ }
+
+ return toggleSwitch
+}
+
+// Dismiss keyboard and collapse nested subsections when a parent section collapses
+internal fun MainActivity.collapseSectionNestedContent(sectionKey: String) {
+ // World clock timezone search
+ if (sectionKey == "world_clock") {
+ val worldClockZoneRow = findViewById(R.id.row_world_clock_zone)
+ val searchEdit = worldClockZoneRow?.findViewById(R.id.zone_search_edit)
+ val listView = worldClockZoneRow?.findViewById(R.id.zone_search_list)
+ searchEdit?.clearFocus()
+ listView?.visibility = View.GONE
+ }
+ // Appearance reorder section
+ if (sectionKey == "appearance") {
+ // collapse reorder too
+ }
+ // Appearance subsections
+ if (sectionKey == "appearance") {
+ val presetsContent = findViewById(R.id.content_appearance_presets)
+ val outlineContent = findViewById(R.id.content_appearance_outline)
+ val colorsContent = findViewById(R.id.content_appearance_colors)
+ val themeContent = findViewById(R.id.content_appearance_theme)
+ val fontContent = findViewById(R.id.content_appearance_font)
+ val transparencyContent = findViewById(R.id.content_appearance_transparency)
+ presetsContent?.visibility = View.GONE
+ outlineContent?.visibility = View.GONE
+ colorsContent?.visibility = View.GONE
+ themeContent?.visibility = View.GONE
+ fontContent?.visibility = View.GONE
+ transparencyContent?.visibility = View.GONE
+ prefs.edit()
+ .putBoolean("section_appearance_presets_expanded", false)
+ .putBoolean("section_appearance_outline_expanded", false)
+ .putBoolean("section_appearance_colors_expanded", false)
+ .putBoolean("section_appearance_theme_expanded", false)
+ .putBoolean("section_appearance_font_expanded", false)
+ .putBoolean("section_appearance_transparency_expanded", false)
+ .apply()
+ // Reset nested chevrons
+ listOf(
+ R.id.header_chevron_appearance_presets,
+ R.id.header_chevron_appearance_outline,
+ R.id.header_chevron_appearance_colors,
+ R.id.header_chevron_appearance_theme,
+ R.id.header_chevron_appearance_font,
+ R.id.header_chevron_appearance_transparency
+ ).forEach { id ->
+ findViewById(id)?.rotation = 0f
+ }
+ }
+ dismissKeyboard()
+}
+
+internal fun MainActivity.dismissKeyboard() {
+ val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager
+ currentFocus?.let { imm?.hideSoftInputFromWindow(it.windowToken, 0) }
+}
+
+internal fun MainActivity.bindNestedCard(
+ headerId: Int, title: String, contentId: Int, sectionKey: String,
+ chevronViewId: Int? = null
+) {
+ val header = findViewById(headerId)
+ val content = findViewById(contentId)
+ val chevronView = header.findViewById(
+ chevronViewId ?: R.id.header_chevron
+ )
+
+ nestedViews[sectionKey] = content
+ nestedHeaders[sectionKey] = header
+
+ val isExpanded = prefs.getBoolean(sectionKey, false)
+ content.visibility = if (isExpanded) View.VISIBLE else View.GONE
+ chevronView.rotation = if (isExpanded) 180f else 0f
+
+ header.setOnClickListener {
+ toggleSectionExpansion(header, content, chevronView, sectionKey)
+ }
+}
+
+internal fun MainActivity.bindCategoryFoldable(headerId: Int, contentId: Int, title: String, iconResId: Int, prefKey: String) {
+ accordionViews[prefKey] = findViewById(contentId)
+ accordionHeaders[prefKey] = findViewById(headerId)
+
+ val header = findViewById(headerId)
+ header.findViewById(R.id.header_title).text = title
+ val headerIcon = header.findViewById(R.id.header_icon)
+ if (iconResId != 0) {
+ headerIcon.setImageResource(iconResId)
+ headerIcon.visibility = View.VISIBLE
+ } else {
+ headerIcon.visibility = View.GONE
+ }
+
+ val content = findViewById(contentId)
+ val chevron = header.findViewById(R.id.header_chevron)
+ val isExpanded = prefs.getBoolean(prefKey, false)
+ content.visibility = if (isExpanded) View.VISIBLE else View.GONE
+ chevron.rotation = if (isExpanded) 180f else 0f
+
+ header.setOnClickListener {
+ toggleSectionExpansion(header, content, chevron, prefKey)
+ }
+}
+
+internal fun MainActivity.bindTimezoneSearch(
+ rowId: Int, zoneIds: List, prefKey: String, defaultVal: String
+) {
+ val row = findViewById(rowId)
+ val searchEdit = row.findViewById(R.id.zone_search_edit)
+ val listView = row.findViewById(R.id.zone_search_list)
+
+ val currentVal = prefs.getString(prefKey, defaultVal) ?: defaultVal
+ searchEdit.setText(currentVal)
+
+ var filteredList: MutableList = mutableListOf()
+ val filteredAdapter = android.widget.ArrayAdapter(this, android.R.layout.simple_list_item_1, filteredList)
+
+ // Text watcher for filtering
+ searchEdit.addTextChangedListener(object : android.text.TextWatcher {
+ override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
+ override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
+ override fun afterTextChanged(s: android.text.Editable?) {
+ val query = s?.toString()?.lowercase() ?: ""
+ if (query.isEmpty()) {
+ filteredList.clear()
+ listView.visibility = View.GONE
+ return
+ }
+ filteredList.clear()
+ filteredList.addAll(zoneIds.filter { it.lowercase().contains(query) })
+ filteredAdapter.notifyDataSetChanged()
+ listView.visibility = if (filteredList.isEmpty()) View.GONE else View.VISIBLE
+ }
+ })
+
+ listView.adapter = filteredAdapter
+ listView.setOnItemClickListener { _, _, position, _ ->
+ val selected = filteredList[position]
+ searchEdit.setText(selected)
+ listView.visibility = View.GONE
+ searchEdit.clearFocus()
+ prefs.edit().putString(prefKey, selected).apply()
+ updateWidget()
+ }
+
+ // Intercept touch events so parent NestedScrollView doesn't steal them
+ listView.setOnTouchListener { v, event ->
+ v.parent.requestDisallowInterceptTouchEvent(true)
+ false
+ }
+
+ // Show list on focus
+ searchEdit.setOnFocusChangeListener { _, hasFocus ->
+ if (hasFocus) {
+ val query = searchEdit.text?.toString()?.lowercase() ?: ""
+ if (query.isEmpty()) {
+ filteredList.clear()
+ filteredList.addAll(zoneIds)
+ filteredAdapter.notifyDataSetChanged()
+ listView.visibility = View.VISIBLE
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/leanbitlab/lwidget/SettingsAppearance.kt b/app/src/main/java/com/leanbitlab/lwidget/SettingsAppearance.kt
new file mode 100644
index 0000000..3694bc5
--- /dev/null
+++ b/app/src/main/java/com/leanbitlab/lwidget/SettingsAppearance.kt
@@ -0,0 +1,335 @@
+/*
+ * Copyright (C) 2026 LeanBitLab
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+
+
+package com.leanbitlab.lwidget
+
+import android.view.View
+import android.widget.AutoCompleteTextView
+import android.widget.TextView
+
+private data class LanguageOption(val code: String, val displayName: String)
+
+internal fun MainActivity.setupThemeSection(colorOptions: List) {
+ // Appearance Sections
+
+ // Appearance Subsections (nested cards)
+ bindNestedCard(R.id.header_appearance_presets, getString(R.string.header_presets), R.id.content_appearance_presets, "section_appearance_presets_expanded", R.id.header_chevron_appearance_presets)
+ setupPresetsSection()
+ bindNestedCard(R.id.header_appearance_outline, getString(R.string.header_outline), R.id.content_appearance_outline, "section_appearance_outline_expanded", R.id.header_chevron_appearance_outline)
+ bindNestedCard(R.id.header_appearance_colors, getString(R.string.header_colors), R.id.content_appearance_colors, "section_appearance_colors_expanded", R.id.header_chevron_appearance_colors)
+ bindNestedCard(R.id.header_appearance_theme, getString(R.string.header_theme), R.id.content_appearance_theme, "section_appearance_theme_expanded", R.id.header_chevron_appearance_theme)
+ bindNestedCard(R.id.header_appearance_font, getString(R.string.header_font), R.id.content_appearance_font, "section_appearance_font_expanded", R.id.header_chevron_appearance_font)
+ bindNestedCard(R.id.header_appearance_transparency, getString(R.string.header_transparency), R.id.content_appearance_transparency, "section_appearance_transparency_expanded", R.id.header_chevron_appearance_transparency)
+ bindNestedCard(R.id.header_appearance_padding, getString(R.string.header_padding), R.id.content_appearance_padding, "section_appearance_padding_expanded", R.id.header_chevron_appearance_padding)
+
+ // Reorder section
+ bindReorderSection()
+
+ // Outline toggle
+ bindToggle(R.id.row_outline_toggle, getString(R.string.row_show_outline), "show_outline", false) { _ ->
+ updateWidget()
+ }
+
+ // Dynamic Colors toggle
+ val rowDynamicColors = findViewById(R.id.row_dynamic_colors_toggle)
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
+ rowDynamicColors.visibility = View.VISIBLE
+ bindToggle(R.id.row_dynamic_colors_toggle, getString(R.string.row_dynamic_colors), "use_dynamic_colors", true) { isChecked ->
+ updateColorVisibility(isChecked)
+ if (isChecked) {
+ prefs.edit()
+ .putInt("text_color_primary_idx", 0)
+ .putInt("text_color_secondary_idx", 0)
+ .putInt("date_color_idx", 0)
+ .putInt("outline_color_idx", 0)
+ .putInt("bg_color_idx", 0)
+ .apply()
+ }
+ }
+ } else {
+ rowDynamicColors.visibility = View.GONE
+ }
+
+ // Theme selector (Auto / Light / Dark)
+ bindSelector(
+ R.id.row_theme_mode, getString(R.string.row_theme_mode), "theme_mode",
+ listOf(getString(R.string.theme_auto), getString(R.string.theme_light), getString(R.string.theme_dark)), 0
+ ) { _ ->
+ applyTheme()
+ }
+
+ // BG Transparency
+ bindSlider(R.id.row_bg_transparency, getString(R.string.row_bg_opacity), "bg_opacity", 85f, 0f, 100f)
+
+ // Widget Padding
+ bindSlider(R.id.row_widget_padding, getString(R.string.row_widget_padding), "widget_padding", 24f, 0f, 48f, suffix = "dp")
+
+ // Background Color
+ val bgSliderRow = findViewById(R.id.row_bg_color_custom)
+ bindSelector(R.id.row_bg_color, getString(R.string.section_bg_color), "bg_color_idx", colorOptions, 0) { idx ->
+ bgSliderRow.visibility = if (idx == 2) View.VISIBLE else View.GONE
+ if (idx != 2) updateWidget()
+ }
+ bindColorSliders(R.id.row_bg_color_custom, "bg_color")
+ bgSliderRow.visibility = if (prefs.getInt("bg_color_idx", 0) == 2) View.VISIBLE else View.GONE
+
+ // Text Color Primary
+ val primarySliderRow = findViewById(R.id.row_text_color_primary_custom)
+ bindSelector(R.id.row_text_color_primary, getString(R.string.section_text_color_primary), "text_color_primary_idx", colorOptions, 0) { idx ->
+ primarySliderRow.visibility = if (idx == 2) View.VISIBLE else View.GONE
+ if (idx != 2) updateWidget()
+ }
+ bindColorSliders(R.id.row_text_color_primary_custom, "text_color_primary")
+ primarySliderRow.visibility = if (prefs.getInt("text_color_primary_idx", 0) == 2) View.VISIBLE else View.GONE
+
+ // Text Color Secondary
+ val secondarySliderRow = findViewById(R.id.row_text_color_secondary_custom)
+ bindSelector(R.id.row_text_color_secondary, getString(R.string.section_text_color_secondary), "text_color_secondary_idx", colorOptions, 0) { idx ->
+ secondarySliderRow.visibility = if (idx == 2) View.VISIBLE else View.GONE
+ if (idx != 2) updateWidget()
+ }
+ bindColorSliders(R.id.row_text_color_secondary_custom, "text_color_secondary")
+ secondarySliderRow.visibility = if (prefs.getInt("text_color_secondary_idx", 0) == 2) View.VISIBLE else View.GONE
+
+ // Date Color
+ val dateSliderRow = findViewById(R.id.row_date_color_custom)
+ bindSelector(R.id.row_date_color, getString(R.string.section_date_color), "date_color_idx", colorOptions, 0) { idx ->
+ dateSliderRow.visibility = if (idx == 2) View.VISIBLE else View.GONE
+ if (idx != 2) updateWidget()
+ }
+ bindColorSliders(R.id.row_date_color_custom, "date_color")
+ dateSliderRow.visibility = if (prefs.getInt("date_color_idx", 0) == 2) View.VISIBLE else View.GONE
+
+ // Outline Color
+ val outlineSliderRow = findViewById(R.id.row_outline_color_custom)
+ bindSelector(R.id.row_outline_color, getString(R.string.section_outline_color), "outline_color_idx", colorOptions, 0) { idx ->
+ outlineSliderRow.visibility = if (idx == 2) View.VISIBLE else View.GONE
+ if (idx != 2) updateWidget()
+ }
+ bindColorSliders(R.id.row_outline_color_custom, "outline_color")
+ 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))
+
+ // Font selector
+ bindSelector(R.id.row_font, getString(R.string.section_font), "font_style", listOf(
+ getString(R.string.font_default), getString(R.string.font_serif), getString(R.string.font_monospace), getString(R.string.font_cursive),
+ getString(R.string.font_condensed), getString(R.string.font_condensed_light), getString(R.string.font_light), getString(R.string.font_medium),
+ getString(R.string.font_black), getString(R.string.font_thin), getString(R.string.font_smallcaps)
+ ), 0)
+
+ updateToggleAvailability()
+}
+
+internal fun MainActivity.setupLanguageSection() {
+ val languages = listOf(
+ LanguageOption("", getString(R.string.lang_system_default)),
+ LanguageOption("en", "English"),
+ LanguageOption("es", "Español (Spanish)"),
+ LanguageOption("zh", "简体中文 (Chinese)"),
+ LanguageOption("hi", "हिन्दी (Hindi)"),
+ LanguageOption("ar", "العربية (Arabic)"),
+ LanguageOption("fr", "Français (French)"),
+ LanguageOption("pt", "Português (Portuguese)"),
+ LanguageOption("ru", "Русский (Russian)"),
+ LanguageOption("de", "Deutsch (German)"),
+ LanguageOption("ja", "日本語 (Japanese)"),
+ LanguageOption("tr", "Türkçe (Turkish)")
+ )
+ val languageLabels = languages.map { it.displayName }
+ val currentLocales = androidx.appcompat.app.AppCompatDelegate.getApplicationLocales()
+ val currentTag = if (currentLocales.isEmpty) "" else currentLocales.get(0)?.language ?: ""
+ val currentIdx = languages.indexOfFirst { it.code.equals(currentTag, ignoreCase = true) }.coerceAtLeast(0)
+
+ val row = findViewById(R.id.row_app_language) ?: return
+ val tvTitle = row.findViewById(R.id.row_label)
+ val autoCompleteTextView = row.findViewById(R.id.row_value)
+
+ tvTitle.text = getString(R.string.section_app_language)
+ val adapter = android.widget.ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, languageLabels)
+ autoCompleteTextView.setAdapter(adapter)
+ autoCompleteTextView.setText(languageLabels[currentIdx], false)
+
+ autoCompleteTextView.setOnItemClickListener { _, _, position, _ ->
+ val selected = languages.getOrElse(position) { languages[0] }
+ val localeList = if (selected.code.isEmpty()) {
+ androidx.core.os.LocaleListCompat.getEmptyLocaleList()
+ } else {
+ androidx.core.os.LocaleListCompat.forLanguageTags(selected.code)
+ }
+ androidx.appcompat.app.AppCompatDelegate.setApplicationLocales(localeList)
+ }
+}
+
+internal fun MainActivity.setupPresetsSection() {
+ data class Preset(
+ val key: String,
+ val label: String,
+ val prefs: Map
+ )
+
+ val presets = listOf(
+ // Minimal: just time+date, white text, fully transparent, thin font
+ Preset("minimal", getString(R.string.preset_minimal), mapOf(
+ "show_outline" to false, "bg_opacity" to 0f,
+ "font_style" to 9, // Thin
+ "use_dynamic_colors" to false,
+ "text_color_primary_idx" to 2, "text_color_primary_r" to 255, "text_color_primary_g" to 255, "text_color_primary_b" to 255,
+ "text_color_secondary_idx" to 2, "text_color_secondary_r" to 200, "text_color_secondary_g" to 200, "text_color_secondary_b" to 200,
+ "date_color_idx" to 2, "date_color_r" to 180, "date_color_g" to 180, "date_color_b" to 190,
+ "bold_battery" to false, "bold_temp" to false
+ )),
+ // Neon: cyan time, magenta date, dark bg, bold condensed font
+ Preset("neon", getString(R.string.preset_neon), mapOf(
+ "bold_battery" to true, "bold_temp" to true,
+ "show_outline" to true, "bg_opacity" to 95f,
+ "font_style" to 4, // Condensed
+ "use_dynamic_colors" to false,
+ "text_color_primary_idx" to 2, "text_color_primary_r" to 0, "text_color_primary_g" to 255, "text_color_primary_b" to 255,
+ "text_color_secondary_idx" to 2, "text_color_secondary_r" to 0, "text_color_secondary_g" to 200, "text_color_secondary_b" to 200,
+ "date_color_idx" to 2, "date_color_r" to 255, "date_color_g" to 0, "date_color_b" to 180,
+ "outline_color_idx" to 2, "outline_color_r" to 0, "outline_color_g" to 200, "outline_color_b" to 255,
+ "bg_color_idx" to 2, "bg_color_r" to 10, "bg_color_g" to 10, "bg_color_b" to 20
+ )),
+ // Cockpit: green on dark, monospace, info-heavy, terminal look
+ Preset("cockpit", getString(R.string.preset_cockpit), mapOf(
+ "bold_battery" to false, "bold_temp" to false,
+ "bold_storage" to false, "bold_ram" to false, "bold_data_usage" to false,
+ "show_outline" to true, "bg_opacity" to 90f,
+ "font_style" to 2, // Monospace
+ "use_dynamic_colors" to false,
+ "text_color_primary_idx" to 2, "text_color_primary_r" to 0, "text_color_primary_g" to 255, "text_color_primary_b" to 65,
+ "text_color_secondary_idx" to 2, "text_color_secondary_r" to 0, "text_color_secondary_g" to 180, "text_color_secondary_b" to 50,
+ "date_color_idx" to 2, "date_color_r" to 0, "date_color_g" to 200, "date_color_b" to 80,
+ "outline_color_idx" to 2, "outline_color_r" to 0, "outline_color_g" to 120, "outline_color_b" to 40,
+ "bg_color_idx" to 2, "bg_color_r" to 5, "bg_color_g" to 15, "bg_color_b" to 5
+ )),
+ // Sunset: warm oranges/gold, serif font, elegant minimal
+ Preset("sunset", getString(R.string.preset_sunset), mapOf(
+ "bold_battery" to true,
+ "show_outline" to false, "bg_opacity" to 70f,
+ "font_style" to 1, // Serif
+ "use_dynamic_colors" to false,
+ "text_color_primary_idx" to 2, "text_color_primary_r" to 255, "text_color_primary_g" to 180, "text_color_primary_b" to 50,
+ "text_color_secondary_idx" to 2, "text_color_secondary_r" to 230, "text_color_secondary_g" to 140, "text_color_secondary_b" to 60,
+ "date_color_idx" to 2, "date_color_r" to 255, "date_color_g" to 120, "date_color_b" to 50,
+ "bg_color_idx" to 2, "bg_color_r" to 30, "bg_color_g" to 15, "bg_color_b" to 8
+ )),
+ // Monochrome: white outline, all white text, medium font, classic layout
+ Preset("monochrome", getString(R.string.preset_monochrome), mapOf(
+ "bold_battery" to false,
+ "show_outline" to true, "bg_opacity" to 50f,
+ "font_style" to 7, // Medium
+ "use_dynamic_colors" to false,
+ "text_color_primary_idx" to 2, "text_color_primary_r" to 240, "text_color_primary_g" to 240, "text_color_primary_b" to 240,
+ "text_color_secondary_idx" to 2, "text_color_secondary_r" to 170, "text_color_secondary_g" to 170, "text_color_secondary_b" to 170,
+ "date_color_idx" to 2, "date_color_r" to 200, "date_color_g" to 200, "date_color_b" to 200,
+ "outline_color_idx" to 2, "outline_color_r" to 100, "outline_color_g" to 100, "outline_color_b" to 100,
+ "bg_color_idx" to 2, "bg_color_r" to 25, "bg_color_g" to 25, "bg_color_b" to 25
+ )),
+ // Snowfall: icy blues, light font, airy feel
+ Preset("snowfall", getString(R.string.preset_snowfall), mapOf(
+ "bold_temp" to false,
+ "show_outline" to false, "bg_opacity" to 60f,
+ "font_style" to 6, // Light
+ "use_dynamic_colors" to false,
+ "text_color_primary_idx" to 2, "text_color_primary_r" to 180, "text_color_primary_g" to 220, "text_color_primary_b" to 255,
+ "text_color_secondary_idx" to 2, "text_color_secondary_r" to 130, "text_color_secondary_g" to 180, "text_color_secondary_b" to 230,
+ "date_color_idx" to 2, "date_color_r" to 100, "date_color_g" to 170, "date_color_b" to 255,
+ "bg_color_idx" to 2, "bg_color_r" to 10, "bg_color_g" to 20, "bg_color_b" to 40
+ ))
+ )
+
+ val chipGroup = findViewById(R.id.preset_chip_group)
+ chipGroup.removeAllViews()
+ val activePreset = prefs.getString("active_preset", null)
+
+ val primaryContainer = com.google.android.material.color.MaterialColors.getColor(
+ chipGroup, com.google.android.material.R.attr.colorPrimaryContainer
+ )
+ val surfaceContainer = com.google.android.material.color.MaterialColors.getColor(
+ chipGroup, com.google.android.material.R.attr.colorSurfaceContainerHighest
+ )
+ val onPrimaryContainer = com.google.android.material.color.MaterialColors.getColor(
+ chipGroup, com.google.android.material.R.attr.colorOnPrimaryContainer
+ )
+ val onSurfaceVariant = com.google.android.material.color.MaterialColors.getColor(
+ chipGroup, com.google.android.material.R.attr.colorOnSurfaceVariant
+ )
+
+ val chipBgStateList = android.content.res.ColorStateList(
+ arrayOf(
+ intArrayOf(android.R.attr.state_checked),
+ intArrayOf(-android.R.attr.state_checked)
+ ),
+ intArrayOf(
+ primaryContainer,
+ surfaceContainer
+ )
+ )
+
+ val chipTextStateList = android.content.res.ColorStateList(
+ arrayOf(
+ intArrayOf(android.R.attr.state_checked),
+ intArrayOf(-android.R.attr.state_checked)
+ ),
+ intArrayOf(
+ onPrimaryContainer,
+ onSurfaceVariant
+ )
+ )
+
+ val density = resources.displayMetrics.density
+
+ for (preset in presets) {
+ val chip = com.google.android.material.chip.Chip(this).apply {
+ text = preset.label
+ isCheckable = true
+ isChecked = (preset.key == activePreset)
+ isCheckedIconVisible = false
+ shapeAppearanceModel = shapeAppearanceModel.toBuilder().setAllCornerSizes(14f * density).build()
+ chipBackgroundColor = chipBgStateList
+ setTextColor(chipTextStateList)
+ chipStrokeWidth = 0f
+ setEnsureMinTouchTargetSize(false)
+ textSize = 13f
+ typeface = android.graphics.Typeface.DEFAULT_BOLD
+ setOnClickListener {
+ val editor = prefs.edit()
+ for ((k, v) in preset.prefs) {
+ when (v) {
+ is Boolean -> editor.putBoolean(k, v)
+ is Float -> editor.putFloat(k, v)
+ is Int -> editor.putInt(k, v)
+ is String -> editor.putString(k, v)
+ }
+ }
+ editor.putString("active_preset", preset.key)
+ editor.apply()
+ updateWidget()
+ recreate()
+ }
+ }
+ chipGroup.addView(chip)
+ }
+}
+
+internal fun MainActivity.applyTheme() {
+ updateWidget()
+}
diff --git a/app/src/main/java/com/leanbitlab/lwidget/SettingsBinders.kt b/app/src/main/java/com/leanbitlab/lwidget/SettingsBinders.kt
new file mode 100644
index 0000000..a224017
--- /dev/null
+++ b/app/src/main/java/com/leanbitlab/lwidget/SettingsBinders.kt
@@ -0,0 +1,259 @@
+/*
+ * Copyright (C) 2026 LeanBitLab
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+
+
+package com.leanbitlab.lwidget
+
+import android.view.View
+import android.widget.AutoCompleteTextView
+import android.widget.TextView
+import android.view.ViewGroup
+import com.google.android.material.card.MaterialCardView
+import com.google.android.material.slider.Slider
+import com.google.android.material.switchmaterial.SwitchMaterial
+import androidx.transition.AutoTransition
+import androidx.transition.TransitionManager
+
+internal fun MainActivity.bindToggle(
+ viewId: Int, title: String, prefShowKey: String, defShow: Boolean,
+ isContent: Boolean = false,
+ onChanged: ((Boolean) -> Unit)? = null
+) {
+ val row = findViewById(viewId)
+ val tvTitle = row.findViewById(R.id.row_label)
+ val switch = row.findViewById(R.id.row_switch)
+
+ tvTitle.text = title
+ switch.tag = prefShowKey
+ if (isContent) contentSwitches.add(switch)
+
+ val isShown = prefs.getBoolean(prefShowKey, defShow)
+ switch.isChecked = isShown
+ onChanged?.invoke(isShown)
+
+ switch.setOnCheckedChangeListener { buttonView, isChecked ->
+ 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()
+ if (isContent) updateToggleAvailability()
+ }
+}
+
+internal fun MainActivity.bindSlider(
+ viewId: Int, title: String, prefKey: String, defValue: Float,
+ minValue: Float, maxValue: Float, suffix: String = "%"
+) {
+ val row = findViewById(viewId)
+ val tvTitle = row.findViewById(R.id.row_label)
+ val slider = row.findViewById(R.id.row_slider)
+ val tvValue = row.findViewById(R.id.row_value)
+
+ tvTitle.text = title
+
+ val currentValue = prefs.getFloat(prefKey, defValue)
+ slider.valueFrom = minValue
+ slider.valueTo = maxValue
+ slider.value = currentValue.coerceIn(minValue, maxValue)
+ tvValue.text = "${currentValue.toInt()}$suffix"
+
+ slider.addOnChangeListener { _, value, fromUser ->
+ if (fromUser) {
+ tvValue.text = "${value.toInt()}$suffix"
+ prefs.edit().putFloat(prefKey, value).apply()
+ scheduleWidgetUpdate()
+ }
+ }
+}
+
+internal fun MainActivity.bindSelector(
+ viewId: Int, title: String, prefKey: String, options: List,
+ defaultIdx: Int, onSelectionChanged: ((Int) -> Unit)? = null
+) {
+ val row = findViewById(viewId)
+ val tvTitle = row.findViewById(R.id.row_label)
+ val autoCompleteTextView = row.findViewById(R.id.row_value)
+
+ tvTitle.text = title
+
+ 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") {
+ val appPackages = if (prefKey == "clock_app_package") clockAppPackages else calendarAppPackages
+ val currentVal = prefs.getString(prefKey, "default") ?: "default"
+ val currentIdx = appPackages.indexOf(currentVal).coerceAtLeast(0)
+ autoCompleteTextView.setText(options.getOrElse(currentIdx) { options[0] }, false)
+ autoCompleteTextView.setOnItemClickListener { _, _, position, _ ->
+ val selected = appPackages.getOrElse(position) { "default" }
+ prefs.edit().putString(prefKey, selected).apply()
+ updateWidget()
+ onSelectionChanged?.invoke(position)
+ row.requestFocus()
+ autoCompleteTextView.clearFocus()
+ }
+ } else {
+ val currentIdx = prefs.getInt(prefKey, defaultIdx)
+ autoCompleteTextView.setText(options.getOrElse(currentIdx) { options[defaultIdx] }, false)
+ autoCompleteTextView.setOnItemClickListener { _, _, position, _ ->
+ prefs.edit().putInt(prefKey, position).apply()
+ updateWidget()
+ onSelectionChanged?.invoke(position)
+ row.requestFocus()
+ autoCompleteTextView.clearFocus()
+ }
+ }
+}
+
+internal fun MainActivity.bindColorSliders(viewId: Int, prefPrefix: String): View {
+ val row = findViewById(viewId)
+ val sliderRed = row.findViewById(R.id.slider_red)
+ val sliderGreen = row.findViewById(R.id.slider_green)
+ val sliderBlue = row.findViewById(R.id.slider_blue)
+ val valRed = row.findViewById(R.id.val_red)
+ val valGreen = row.findViewById(R.id.val_green)
+ val valBlue = row.findViewById(R.id.val_blue)
+ val preview = row.findViewById(R.id.color_preview)
+
+ val r = prefs.getInt("${prefPrefix}_r", 255)
+ val g = prefs.getInt("${prefPrefix}_g", 255)
+ val b = prefs.getInt("${prefPrefix}_b", 255)
+
+ fun updatePreview() {
+ val color = android.graphics.Color.rgb(sliderRed.value.toInt(), sliderGreen.value.toInt(), sliderBlue.value.toInt())
+ preview.backgroundTintList = android.content.res.ColorStateList.valueOf(color)
+ valRed.text = sliderRed.value.toInt().toString()
+ valGreen.text = sliderGreen.value.toInt().toString()
+ valBlue.text = sliderBlue.value.toInt().toString()
+ }
+
+ sliderRed.value = r.toFloat()
+ sliderGreen.value = g.toFloat()
+ sliderBlue.value = b.toFloat()
+ updatePreview()
+
+ val listener = Slider.OnChangeListener { _, _, fromUser ->
+ if (fromUser) {
+ updatePreview()
+ prefs.edit()
+ .putInt("${prefPrefix}_r", sliderRed.value.toInt())
+ .putInt("${prefPrefix}_g", sliderGreen.value.toInt())
+ .putInt("${prefPrefix}_b", sliderBlue.value.toInt())
+ .apply()
+ scheduleWidgetUpdate()
+ }
+ }
+
+ sliderRed.addOnChangeListener(listener)
+ sliderGreen.addOnChangeListener(listener)
+ sliderBlue.addOnChangeListener(listener)
+
+ return row
+}
+
+internal fun MainActivity.updateColorVisibility(useDynamicColors: Boolean) {
+ val manualColorIds = listOf(
+ R.id.row_bg_color, R.id.row_bg_color_custom,
+ R.id.row_text_color_primary, R.id.row_text_color_primary_custom,
+ R.id.row_text_color_secondary, R.id.row_text_color_secondary_custom,
+ R.id.row_date_color, R.id.row_date_color_custom,
+ R.id.row_outline_color, R.id.row_outline_color_custom
+ )
+ manualColorIds.forEach { id ->
+ findViewById(id).visibility = if (useDynamicColors) View.GONE else View.VISIBLE
+ }
+}
+
+internal fun MainActivity.updateToggleCardStyle(card: MaterialCardView?, enabled: Boolean) {
+ if (card == null) return
+ if (enabled) {
+ card.setCardBackgroundColor(android.graphics.Color.TRANSPARENT)
+ card.strokeWidth = (1f * resources.displayMetrics.density).toInt()
+ card.setStrokeColor(android.content.res.ColorStateList.valueOf(
+ com.google.android.material.color.MaterialColors.getColor(card, com.google.android.material.R.attr.colorPrimary)
+ ))
+ } else {
+ card.setCardBackgroundColor(
+ com.google.android.material.color.MaterialColors.getColor(card, com.google.android.material.R.attr.colorSurfaceContainerLow)
+ )
+ card.setStrokeColor(android.content.res.ColorStateList.valueOf(
+ com.google.android.material.color.MaterialColors.getColor(card, com.google.android.material.R.attr.colorOutlineVariant)
+ ))
+ }
+}
+
+// Helper for callers who override the toggle listener to update row visibility
+internal fun MainActivity.updateFeatureRowVisibility(switch: SwitchMaterial, isChecked: Boolean, vararg rowIds: Int) {
+ val toggleRow = switch.parent as? View
+ val toggleCard = toggleRow?.findViewById(R.id.toggle_row_card)
+ updateToggleCardStyle(toggleCard, isChecked)
+
+ val parentViewGroup = (toggleRow?.parent as? ViewGroup)
+ if (parentViewGroup != null) {
+ TransitionManager.beginDelayedTransition(
+ parentViewGroup,
+ AutoTransition().apply {
+ duration = 180L
+ }
+ )
+ }
+
+ rowIds.forEach { id ->
+ findViewById(id)?.visibility = if (isChecked) View.VISIBLE else View.GONE
+ }
+}
+
+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
+ for (switch in contentSwitches) {
+ switch.isEnabled = true
+ switch.alpha = 1.0f
+ }
+}
diff --git a/app/src/main/java/com/leanbitlab/lwidget/SettingsDisplaySections.kt b/app/src/main/java/com/leanbitlab/lwidget/SettingsDisplaySections.kt
new file mode 100644
index 0000000..ab2df3f
--- /dev/null
+++ b/app/src/main/java/com/leanbitlab/lwidget/SettingsDisplaySections.kt
@@ -0,0 +1,229 @@
+/*
+ * Copyright (C) 2026 LeanBitLab
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+
+
+package com.leanbitlab.lwidget
+
+import android.util.Log
+import android.content.Intent
+import androidx.browser.customtabs.CustomTabsIntent
+import android.content.pm.PackageManager
+import android.view.View
+import androidx.core.app.ActivityCompat
+import androidx.core.content.ContextCompat
+
+internal fun MainActivity.getInstalledClockApps(): Pair, List> {
+ val labels = mutableListOf(getString(R.string.font_default))
+ val packages = mutableListOf("default")
+
+ val knownPackages = listOf(
+ "com.android.deskclock",
+ "com.google.android.deskclock",
+ "com.simplemobiletools.clock",
+ "org.fossify.clock",
+ "com.sec.android.app.clockpackage",
+ "com.huawei.deskclock",
+ "com.coloros.alarmclock",
+ "com.oneplus.deskclock",
+ "com.htc.sec.android.app.clockpackage"
+ )
+
+ val pm = packageManager
+
+ val alarmIntent = Intent(android.provider.AlarmClock.ACTION_SHOW_ALARMS)
+ val resolveInfos = pm.queryIntentActivities(alarmIntent, PackageManager.MATCH_DEFAULT_ONLY)
+
+ val foundPackages = mutableSetOf()
+ for (info in resolveInfos) {
+ val pkg = info.activityInfo.packageName
+ foundPackages.add(pkg)
+ }
+
+ for (pkg in knownPackages) {
+ if (isAppInstalled(pkg)) {
+ foundPackages.add(pkg)
+ }
+ }
+
+ for (pkg in foundPackages) {
+ try {
+ val appInfo = pm.getApplicationInfo(pkg, 0)
+ val label = pm.getApplicationLabel(appInfo).toString()
+ labels.add(label)
+ packages.add(pkg)
+ } catch (e: Exception) {
+ // ignore
+ }
+ }
+
+ return Pair(labels, packages)
+}
+
+internal fun MainActivity.setupTimeSection(timeFormatOptions: List) {
+ val (labels, packages) = getInstalledClockApps()
+ clockAppPackages = packages
+
+ val clockAppRow = findViewById(R.id.row_time_clock_app)
+
+ // Time
+ bindFoldedSection(
+ R.id.header_time, R.drawable.ic_time, getString(R.string.section_time),
+ R.id.content_time, R.id.row_time_toggle,
+ "show_time", true,
+ sizeRowId = R.id.row_time_size, prefSizeKey = "size_time", defSize = 56f, minSize = 12f, maxSize = 120f,
+ selectorRowId = R.id.row_time_format, selectorOptions = timeFormatOptions, prefSelectorKey = "time_format_idx", defSelectorIdx = 0,
+ isContent = true,
+ onChanged = { isShown ->
+ clockAppRow?.visibility = if (isShown) View.VISIBLE else View.GONE
+ }
+ )
+
+ bindSelector(
+ R.id.row_time_clock_app,
+ getString(R.string.section_time_clock_app),
+ "clock_app_package",
+ labels,
+ 0
+ )
+}
+
+internal fun MainActivity.setupNextAlarmSection() {
+ // Next Alarm
+ bindFoldedSection(
+ R.id.header_next_alarm, R.drawable.ic_alarm, getString(R.string.section_next_alarm),
+ R.id.content_next_alarm, R.id.row_next_alarm_toggle,
+ "show_next_alarm", true,
+ sizeRowId = R.id.row_next_alarm_size, prefSizeKey = "size_next_alarm", defSize = 14f, minSize = 10f, maxSize = 24f,
+ isContent = true
+ )
+}
+
+internal fun MainActivity.setupWorldClockSection(zoneIds: List) {
+ // World Clock
+ bindFoldedSection(
+ R.id.header_world_clock, R.drawable.ic_world, getString(R.string.section_world_clock),
+ R.id.content_world_clock, R.id.row_world_clock_toggle,
+ "show_world_clock", false,
+ sizeRowId = R.id.row_world_clock_size, prefSizeKey = "size_world_clock", defSize = 18f, minSize = 10f, maxSize = 32f,
+ isContent = true
+ )
+ bindTimezoneSearch(R.id.row_world_clock_zone, zoneIds, "world_clock_zone_str", "UTC")
+}
+
+internal fun MainActivity.setupDateSection(dateFormatOptions: List) {
+ // Date
+ bindFoldedSection(
+ R.id.header_date, R.drawable.ic_date, getString(R.string.section_date),
+ R.id.content_date, R.id.row_date_toggle,
+ "show_date", true,
+ sizeRowId = R.id.row_date_size, prefSizeKey = "size_date", defSize = 16f, minSize = 10f, maxSize = 24f,
+ selectorRowId = R.id.row_date_format, selectorOptions = dateFormatOptions, prefSelectorKey = "date_format_idx", defSelectorIdx = 0,
+ isContent = true
+ )
+}
+
+internal fun MainActivity.setupBatterySection() {
+ // Battery
+ bindFoldedSection(
+ R.id.header_battery, R.drawable.ic_battery, getString(R.string.section_battery),
+ R.id.content_battery, R.id.row_battery_toggle,
+ "show_battery", true,
+ sizeRowId = R.id.row_battery_size, prefSizeKey = "size_battery", defSize = 32f, minSize = 10f, maxSize = 74f,
+ boldRowId = R.id.row_battery_bold,
+ isContent = true
+ ).also { it.tag = "battery" }
+ bindToggle(R.id.row_battery_bold, getString(R.string.row_bold_text), "bold_battery", true)
+}
+
+internal fun MainActivity.setupTempSection() {
+ // Temp
+ val tempUnitOptions = listOf("Celsius (°C)", "Fahrenheit (°F)")
+ bindFoldedSection(
+ R.id.header_temp, R.drawable.ic_temp, getString(R.string.section_temp),
+ R.id.content_temp, R.id.row_temp_toggle,
+ "show_temp", false,
+ sizeRowId = R.id.row_temp_size, prefSizeKey = "size_temp", defSize = 18f, minSize = 10f, maxSize = 74f,
+ selectorRowId = R.id.row_temp_unit, selectorOptions = tempUnitOptions, prefSelectorKey = "temp_unit_idx", defSelectorIdx = 0,
+ boldRowId = R.id.row_temp_bold,
+ isContent = true
+ ).also { it.tag = "temp" }
+ bindToggle(R.id.row_temp_bold, getString(R.string.row_bold_text), "bold_temp", false)
+}
+
+internal fun MainActivity.setupWeatherSection() {
+ // Weather
+ val weatherSwitch = bindFoldedSection(
+ R.id.header_weather, R.drawable.ic_weather, getString(R.string.section_weather_condition),
+ R.id.content_weather, R.id.row_weather_toggle,
+ "show_weather_condition", false,
+ sizeRowId = R.id.row_weather_size, prefSizeKey = "size_weather", defSize = 18f, minSize = 10f, maxSize = 74f,
+ boldRowId = R.id.row_weather_bold,
+ isContent = true
+ ).also { it.tag = "weather_condition" }
+ bindToggle(R.id.row_weather_bold, getString(R.string.row_bold_text), "bold_weather", false)
+
+ // Override weather listener for Breezy Weather check
+ weatherSwitch.setOnCheckedChangeListener { _, isChecked ->
+ if (isChecked) {
+ if (!isAppInstalled("org.breezyweather")) {
+ weatherSwitch.isChecked = false
+ com.google.android.material.snackbar.Snackbar.make(
+ findViewById(R.id.fab_update),
+ getString(R.string.msg_breezy_required),
+ com.google.android.material.snackbar.Snackbar.LENGTH_LONG
+ ).setAction(getString(R.string.action_install)) {
+ try {
+ CustomTabsIntent.Builder().build().launchUrl(this@setupWeatherSection, android.net.Uri.parse("https://github.com/breezy-weather/breezy-weather/releases"))
+ } catch (e: Exception) { android.util.Log.e("MainActivity", "Exception caught", e) }
+ }.show()
+ return@setOnCheckedChangeListener
+ }
+ if (ContextCompat.checkSelfPermission(this, "org.breezyweather.READ_PROVIDER") != PackageManager.PERMISSION_GRANTED) {
+ weatherSwitch.isChecked = false
+ com.google.android.material.dialog.MaterialAlertDialogBuilder(this)
+ .setTitle(getString(R.string.dialog_weather_permission_title))
+ .setMessage(getString(R.string.dialog_weather_permission_message))
+ .setPositiveButton(getString(R.string.dialog_continue)) { _, _ ->
+ ActivityCompat.requestPermissions(this, arrayOf("org.breezyweather.READ_PROVIDER"), 103)
+ }
+ .setNegativeButton(getString(R.string.dialog_cancel), null)
+ .show()
+ return@setOnCheckedChangeListener
+ }
+ if (!checkLimit()) {
+ weatherSwitch.isChecked = false
+ return@setOnCheckedChangeListener
+ }
+ }
+ prefs.edit().putBoolean("show_weather_condition", isChecked).apply()
+ updateFeatureRowVisibility(weatherSwitch, isChecked, R.id.row_weather_size, R.id.row_weather_bold)
+ updateWidget()
+ updateToggleAvailability()
+ if (isChecked) {
+ showWeatherSetupHint()
+ }
+ }
+}
+
+/** Reminder shown after the Breezy Weather permission is granted (shared by both entry points). */
+internal fun MainActivity.showWeatherSetupHint() {
+ com.google.android.material.dialog.MaterialAlertDialogBuilder(this)
+ .setTitle(getString(R.string.dialog_weather_setup_title))
+ .setMessage(getString(R.string.dialog_weather_setup_message))
+ .setPositiveButton(getString(R.string.dialog_got_it), null)
+ .show()
+}
diff --git a/app/src/main/java/com/leanbitlab/lwidget/SettingsEventsSections.kt b/app/src/main/java/com/leanbitlab/lwidget/SettingsEventsSections.kt
new file mode 100644
index 0000000..e562d87
--- /dev/null
+++ b/app/src/main/java/com/leanbitlab/lwidget/SettingsEventsSections.kt
@@ -0,0 +1,176 @@
+/*
+ * Copyright (C) 2026 LeanBitLab
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+
+
+package com.leanbitlab.lwidget
+
+import android.Manifest
+import android.content.Intent
+import androidx.browser.customtabs.CustomTabsIntent
+import android.content.pm.PackageManager
+import android.view.View
+import androidx.core.app.ActivityCompat
+import androidx.core.content.ContextCompat
+
+internal fun MainActivity.getInstalledCalendarApps(): Pair, List> {
+ val labels = mutableListOf(getString(R.string.font_default))
+ val packages = mutableListOf("default")
+
+ val knownPackages = listOf(
+ "org.fossify.calendar",
+ "com.simplemobiletools.calendar",
+ "com.google.android.calendar",
+ "com.android.calendar",
+ "com.samsung.android.calendar",
+ "com.bbk.calendar",
+ "com.miui.calendar",
+ "com.huawei.calendar"
+ )
+
+ val pm = packageManager
+ val calIntent = Intent(Intent.ACTION_VIEW).apply {
+ data = android.net.Uri.parse("content://com.android.calendar/time")
+ }
+ val resolveInfos = pm.queryIntentActivities(calIntent, PackageManager.MATCH_DEFAULT_ONLY)
+
+ val foundPackages = mutableSetOf()
+ for (info in resolveInfos) {
+ val pkg = info.activityInfo.packageName
+ foundPackages.add(pkg)
+ }
+
+ for (pkg in knownPackages) {
+ if (isAppInstalled(pkg)) {
+ foundPackages.add(pkg)
+ }
+ }
+
+ for (pkg in foundPackages) {
+ try {
+ val appInfo = pm.getApplicationInfo(pkg, 0)
+ val label = pm.getApplicationLabel(appInfo).toString()
+ labels.add(label)
+ packages.add(pkg)
+ } catch (e: Exception) {
+ // ignore
+ }
+ }
+
+ return Pair(labels, packages)
+}
+
+internal fun MainActivity.setupEventsAndTasksSections() {
+ val (calLabels, calPackages) = getInstalledCalendarApps()
+ calendarAppPackages = calPackages
+
+ val calAppRow = findViewById(R.id.row_events_calendar_app)
+
+ // Events
+ val eventsSwitch = bindFoldedSection(
+ R.id.header_events, R.drawable.ic_events, getString(R.string.section_events),
+ R.id.content_events, R.id.row_events_toggle,
+ "show_events", false,
+ sizeRowId = R.id.row_events_size, prefSizeKey = "size_events", defSize = 14f, minSize = 10f, maxSize = 18f,
+ isContent = true,
+ onChanged = { isShown ->
+ calAppRow?.visibility = if (isShown) View.VISIBLE else View.GONE
+ }
+ )
+
+ bindSelector(
+ R.id.row_events_calendar_app,
+ getString(R.string.section_events_calendar_app),
+ "calendar_app_package",
+ calLabels,
+ 0
+ )
+
+ // Show day abbreviation in events (from issue #71)
+ bindToggle(R.id.row_events_day_abbr, getString(R.string.row_show_day_abbr), "show_day_abbr_in_events", true)
+
+ // Tasks
+ val tasksSwitch = bindFoldedSection(
+ R.id.header_tasks, R.drawable.ic_tasks, getString(R.string.section_tasks),
+ R.id.content_tasks, R.id.row_tasks_toggle,
+ "show_tasks", false,
+ sizeRowId = R.id.row_tasks_size, prefSizeKey = "size_tasks", defSize = 14f, minSize = 10f, maxSize = 18f,
+ isContent = true
+ )
+
+ // Mutual Exclusion: Events vs Tasks
+ eventsSwitch.setOnCheckedChangeListener { _, isChecked ->
+ if (isChecked) {
+ if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
+ ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_CALENDAR), 100)
+ eventsSwitch.isChecked = false
+ return@setOnCheckedChangeListener
+ }
+ if (checkLimit()) {
+ tasksSwitch.isChecked = false
+ prefs.edit().putBoolean("show_events", true).putBoolean("show_tasks", false).apply()
+ updateFeatureRowVisibility(eventsSwitch, true, R.id.row_events_size, R.id.row_events_day_abbr, R.id.row_events_calendar_app)
+ updateFeatureRowVisibility(tasksSwitch, false, R.id.row_tasks_size)
+ updateWidget()
+ updateToggleAvailability()
+ checkAllPermissions()
+ } else { eventsSwitch.isChecked = false }
+ } else {
+ prefs.edit().putBoolean("show_events", false).apply()
+ updateFeatureRowVisibility(eventsSwitch, false, R.id.row_events_size, R.id.row_events_day_abbr, R.id.row_events_calendar_app)
+ updateWidget()
+ updateToggleAvailability()
+ checkAllPermissions()
+ }
+ }
+ tasksSwitch.setOnCheckedChangeListener { _, isChecked ->
+ if (isChecked) {
+ if (!isAppInstalled("org.tasks")) {
+ tasksSwitch.isChecked = false
+ com.google.android.material.snackbar.Snackbar.make(
+ findViewById(R.id.fab_update),
+ getString(R.string.msg_tasks_required),
+ com.google.android.material.snackbar.Snackbar.LENGTH_LONG
+ ).setAction(getString(R.string.action_install)) {
+ try {
+ startActivity(Intent(Intent.ACTION_VIEW, android.net.Uri.parse("market://details?id=org.tasks")))
+ } catch (e: Exception) {
+ CustomTabsIntent.Builder().build().launchUrl(this@setupEventsAndTasksSections, android.net.Uri.parse("https://play.google.com/store/apps/details?id=org.tasks"))
+ }
+ }.show()
+ return@setOnCheckedChangeListener
+ }
+ if (ContextCompat.checkSelfPermission(this, AwidgetProvider.PERMISSION_READ_TASKS_ORG) != PackageManager.PERMISSION_GRANTED) {
+ ActivityCompat.requestPermissions(this, arrayOf(AwidgetProvider.PERMISSION_READ_TASKS_ORG), 101)
+ }
+ if (checkLimit()) {
+ eventsSwitch.isChecked = false
+ prefs.edit().putBoolean("show_tasks", true).putBoolean("show_events", false).apply()
+ updateFeatureRowVisibility(tasksSwitch, true, R.id.row_tasks_size)
+ updateFeatureRowVisibility(eventsSwitch, false, R.id.row_events_size, R.id.row_events_day_abbr, R.id.row_events_calendar_app)
+ updateWidget()
+ updateToggleAvailability()
+ checkAllPermissions()
+ } else { tasksSwitch.isChecked = false }
+ } else {
+ prefs.edit().putBoolean("show_tasks", false).apply()
+ updateFeatureRowVisibility(tasksSwitch, false, R.id.row_tasks_size)
+ updateWidget()
+ updateToggleAvailability()
+ checkAllPermissions()
+ }
+ }
+}
diff --git a/app/src/main/java/com/leanbitlab/lwidget/SettingsLayout.kt b/app/src/main/java/com/leanbitlab/lwidget/SettingsLayout.kt
new file mode 100644
index 0000000..b7e1734
--- /dev/null
+++ b/app/src/main/java/com/leanbitlab/lwidget/SettingsLayout.kt
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2026 LeanBitLab
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+
+package com.leanbitlab.lwidget
+
+import androidx.core.view.doOnLayout
+import androidx.core.widget.NestedScrollView
+
+/** Settings content stops growing past this width so tablets/landscape stay readable. */
+internal const val MAX_SETTINGS_CONTENT_WIDTH_DP = 640
+
+/** Extra side inset (per side) needed to center content of at most [maxContentPx] in [availablePx]. */
+internal fun contentHorizontalInset(availablePx: Int, maxContentPx: Int): Int =
+ if (availablePx > maxContentPx) (availablePx - maxContentPx) / 2 else 0
+
+/** Centers the settings column on wide screens by widening the scroll view's side padding. */
+internal fun MainActivity.constrainContentWidth() {
+ val scroll = findViewById(R.id.nested_scroll_view) ?: return
+ val maxPx = (MAX_SETTINGS_CONTENT_WIDTH_DP * resources.displayMetrics.density).toInt()
+ val baseStart = scroll.paddingStart
+ val baseEnd = scroll.paddingEnd
+ scroll.doOnLayout { view ->
+ val inset = contentHorizontalInset(view.width - baseStart - baseEnd, maxPx)
+ if (inset > 0) {
+ view.setPaddingRelative(baseStart + inset, view.paddingTop, baseEnd + inset, view.paddingBottom)
+ }
+ }
+}
diff --git a/app/src/main/java/com/leanbitlab/lwidget/SettingsPermissions.kt b/app/src/main/java/com/leanbitlab/lwidget/SettingsPermissions.kt
new file mode 100644
index 0000000..e120183
--- /dev/null
+++ b/app/src/main/java/com/leanbitlab/lwidget/SettingsPermissions.kt
@@ -0,0 +1,258 @@
+/*
+ * Copyright (C) 2026 LeanBitLab
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see .
+ */
+
+
+package com.leanbitlab.lwidget
+
+import android.Manifest
+import android.util.Log
+import android.content.Context
+import android.content.Intent
+import androidx.browser.customtabs.CustomTabsIntent
+import android.content.pm.PackageManager
+import android.view.View
+import android.widget.TextView
+import androidx.core.app.ActivityCompat
+import androidx.core.content.ContextCompat
+import com.google.android.material.switchmaterial.SwitchMaterial
+
+internal fun MainActivity.checkAllPermissions() {
+ var widgetNeedsUpdate = false
+
+ // Check Calendar
+ val calMissing = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED
+ if (prefs.getBoolean("show_events", false) && calMissing) {
+ prefs.edit().putBoolean("show_events", false).apply()
+ findViewById(R.id.row_events_toggle).findViewById(R.id.row_switch).isChecked = false
+ findViewById(R.id.row_events_size).visibility = View.GONE
+ widgetNeedsUpdate = true
+ }
+
+ // Check Tasks
+ val tasksMissing = ContextCompat.checkSelfPermission(this, AwidgetProvider.PERMISSION_READ_TASKS_ORG) != PackageManager.PERMISSION_GRANTED
+ if (prefs.getBoolean("show_tasks", false) && tasksMissing) {
+ prefs.edit().putBoolean("show_tasks", false).apply()
+ findViewById(R.id.row_tasks_toggle).findViewById(R.id.row_switch).isChecked = false
+ findViewById(R.id.row_tasks_size).visibility = View.GONE
+ widgetNeedsUpdate = true
+ }
+
+ // Check Steps
+ var stepMissing = false
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q && ContextCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) != PackageManager.PERMISSION_GRANTED) {
+ stepMissing = true
+ }
+ if (prefs.getBoolean("show_steps", false) && stepMissing) {
+ prefs.edit().putBoolean("show_steps", false).apply()
+ findViewById(R.id.row_steps_toggle).findViewById(R.id.row_switch).isChecked = false
+ findViewById(R.id.row_steps_size).visibility = View.GONE
+ widgetNeedsUpdate = true
+ }
+
+ // Check Screen Time
+ val usageMissing = !hasUsageStatsPermission()
+ if (prefs.getBoolean("show_screen_time", false) && usageMissing) {
+ prefs.edit().putBoolean("show_screen_time", false).apply()
+ findViewById