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 - - - - + + + + - - - - + + + +
Screenshot 1Screenshot 2Screenshot 3Screenshot 4Screenshot 1Screenshot 2Screenshot 3Screenshot 4
Screenshot 5Screenshot 6Screenshot 7Screenshot 8Screenshot 5Screenshot 6Screenshot 7Screenshot 8
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(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, getString(R.string.section_events), !calMissing) { + if (calMissing) ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_CALENDAR), 100) + else openAppSettings() + } + updatePermissionToggle(R.id.row_perm_tasks, getString(R.string.section_tasks), !tasksMissing) { + if (tasksMissing) ActivityCompat.requestPermissions(this, arrayOf(AwidgetProvider.PERMISSION_READ_TASKS_ORG), 101) + else openAppSettings() + } + updatePermissionToggle(R.id.row_perm_steps, getString(R.string.section_steps), !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, getString(R.string.section_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, getString(R.string.section_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, getString(R.string.section_weather_condition), !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@checkAllPermissions, 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() + } +} + +internal fun MainActivity.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() + } + } +} + +internal fun MainActivity.openAppSettings() { + val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS) + intent.data = android.net.Uri.parse("package:" + packageName) + startActivity(intent) +} + +// Check usage stats permission +internal fun MainActivity.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 +} + +internal fun MainActivity.isAppInstalled(packageName: String): Boolean { + return try { + packageManager.getPackageInfo(packageName, 0) + true + } catch (e: PackageManager.NameNotFoundException) { + false + } +} + +internal fun MainActivity.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) + } + } + } +} + +internal fun MainActivity.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() +} + +internal fun MainActivity.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() + } + } + } + } + } +} diff --git a/app/src/main/java/com/leanbitlab/lwidget/SettingsReorder.kt b/app/src/main/java/com/leanbitlab/lwidget/SettingsReorder.kt new file mode 100644 index 0000000..b75580f --- /dev/null +++ b/app/src/main/java/com/leanbitlab/lwidget/SettingsReorder.kt @@ -0,0 +1,142 @@ +/* + * 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 java.util.Locale +import androidx.recyclerview.widget.ItemTouchHelper +import androidx.recyclerview.widget.RecyclerView + +internal fun MainActivity.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 + + fun persistOrder() { + val orderStr = items.joinToString(",") { it.key } + prefs.edit().putString("widget_right_column_order", orderStr).apply() + updateWidget() + updateLivePreview() + } + + val adapter = ReorderAdapter( + items, + onStartDrag = { viewHolder -> + itemTouchHelper?.startDrag(viewHolder) + }, + onOrderChanged = { persistOrder() } + ) + 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 + persistOrder() + } + } + + 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) + } +} diff --git a/app/src/main/java/com/leanbitlab/lwidget/SettingsSearch.kt b/app/src/main/java/com/leanbitlab/lwidget/SettingsSearch.kt new file mode 100644 index 0000000..defd349 --- /dev/null +++ b/app/src/main/java/com/leanbitlab/lwidget/SettingsSearch.kt @@ -0,0 +1,161 @@ +/* + * 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 com.google.android.material.tabs.TabLayout +import com.google.android.material.appbar.AppBarLayout + +internal fun MainActivity.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 + } + } + } + }) +} diff --git a/app/src/main/java/com/leanbitlab/lwidget/SettingsSystemSections.kt b/app/src/main/java/com/leanbitlab/lwidget/SettingsSystemSections.kt new file mode 100644 index 0000000..607ebd2 --- /dev/null +++ b/app/src/main/java/com/leanbitlab/lwidget/SettingsSystemSections.kt @@ -0,0 +1,196 @@ +/* + * 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 android.content.pm.PackageManager +import androidx.core.app.ActivityCompat +import androidx.core.content.ContextCompat + +internal fun MainActivity.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() + } +} + +internal fun MainActivity.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) +} + +internal fun MainActivity.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) +} + +internal fun MainActivity.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() + } +} + +internal fun MainActivity.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() + } +} diff --git a/app/src/main/java/com/leanbitlab/lwidget/SetupActivity.kt b/app/src/main/java/com/leanbitlab/lwidget/SetupActivity.kt index 6572e33..f9e01c4 100644 --- a/app/src/main/java/com/leanbitlab/lwidget/SetupActivity.kt +++ b/app/src/main/java/com/leanbitlab/lwidget/SetupActivity.kt @@ -132,7 +132,7 @@ class SetupActivity : AppCompatActivity() { } else { com.google.android.material.snackbar.Snackbar.make( findViewById(R.id.setup_view_flipper), - "Breezy Weather app is required.", + getString(R.string.msg_breezy_required_short), com.google.android.material.snackbar.Snackbar.LENGTH_LONG ).show() } @@ -166,7 +166,7 @@ class SetupActivity : AppCompatActivity() { val btnWeather = findViewById(R.id.btn_grant_weather) if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) == PackageManager.PERMISSION_GRANTED) { - btnCalendar.text = "Granted" + btnCalendar.setText(R.string.perm_granted) btnCalendar.isEnabled = false prefs.edit().putBoolean("show_events", true).apply() } @@ -174,35 +174,35 @@ class SetupActivity : AppCompatActivity() { val hasTasksPerm = ContextCompat.checkSelfPermission(this, "org.tasks.permission.READ_TASKS") == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, "com.todoroo.astrid.READ") == PackageManager.PERMISSION_GRANTED if (hasTasksPerm) { - btnTasks.text = "Granted" + btnTasks.setText(R.string.perm_granted) btnTasks.isEnabled = false prefs.edit().putBoolean("show_tasks", true).apply() } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_GRANTED) { - btnSteps.text = "Granted" + btnSteps.setText(R.string.perm_granted) btnSteps.isEnabled = false prefs.edit().putBoolean("show_steps", true).apply() } } else { - btnSteps.text = "Granted" + btnSteps.setText(R.string.perm_granted) btnSteps.isEnabled = false prefs.edit().putBoolean("show_steps", true).apply() } if (hasUsageStatsPermission()) { - btnDataUsage.text = "Granted" + btnDataUsage.setText(R.string.perm_granted) btnDataUsage.isEnabled = false prefs.edit().putBoolean("show_data_usage", true).apply() - btnScreenTime.text = "Granted" + btnScreenTime.setText(R.string.perm_granted) btnScreenTime.isEnabled = false prefs.edit().putBoolean("show_screen_time", true).apply() } if (ContextCompat.checkSelfPermission(this, "org.breezyweather.READ_PROVIDER") == PackageManager.PERMISSION_GRANTED) { - btnWeather.text = "Granted" + btnWeather.setText(R.string.perm_granted) btnWeather.isEnabled = false prefs.edit().putBoolean("show_weather_condition", true).apply() } diff --git a/app/src/main/java/com/leanbitlab/lwidget/StepCounterService.kt b/app/src/main/java/com/leanbitlab/lwidget/StepCounterService.kt index 64a6faa..8548cb9 100644 --- a/app/src/main/java/com/leanbitlab/lwidget/StepCounterService.kt +++ b/app/src/main/java/com/leanbitlab/lwidget/StepCounterService.kt @@ -337,17 +337,17 @@ class StepCounterService : Service(), SensorEventListener { val showSteps = isStepsVisibleAnywhere(this) - val title = if (showSteps) "Lwidget Step Counter" else "Lwidget Keep Alive" + val title = getString(if (showSteps) R.string.notif_title_steps else R.string.notif_title_keepalive) val text = if (showSteps) { val stepsToday = (lastTotalSteps - baselineSteps).toInt().coerceAtLeast(0) if (stepsToday > 0) { val formatted = java.text.NumberFormat.getIntegerInstance().format(stepsToday) - "$formatted steps today" + getString(R.string.notif_text_steps_today, formatted) } else { - "Counting steps in the background" + getString(R.string.notif_text_counting) } } else { - "Keeping widget updated" + getString(R.string.notif_text_keepalive) } val iconRes = if (showSteps) R.drawable.ic_steps else R.drawable.ic_shield @@ -368,10 +368,10 @@ class StepCounterService : Service(), SensorEventListener { private fun createNotificationChannel() { val channel = NotificationChannel( CHANNEL_ID, - "Step Counter Service", + getString(R.string.notif_channel_name), NotificationManager.IMPORTANCE_MIN ).apply { - description = "Keeps the step counter running in the background." + description = getString(R.string.notif_channel_desc) setShowBadge(false) } val manager = getSystemService(NotificationManager::class.java) diff --git a/app/src/main/java/com/leanbitlab/lwidget/stats/SystemStatsFetcher.kt b/app/src/main/java/com/leanbitlab/lwidget/stats/SystemStatsFetcher.kt index 96db37f..9263e7e 100644 --- a/app/src/main/java/com/leanbitlab/lwidget/stats/SystemStatsFetcher.kt +++ b/app/src/main/java/com/leanbitlab/lwidget/stats/SystemStatsFetcher.kt @@ -113,7 +113,7 @@ object SystemStatsFetcher { if (isFahrenheit) { tempVal = (tempVal * 9f / 5f) + 32f } - val tempStr = String.format("%.1f", tempVal) + val tempStr = String.format(java.util.Locale.getDefault(), "%.1f", tempVal) val tempText = "$tempStr$unitStr" val tempSpan = SpannableString(tempText) val cIdx = tempText.indexOf(unitStr) @@ -201,12 +201,12 @@ object SystemStatsFetcher { val gb = mb / 1024f val text: CharSequence = if (gb >= 1.0f) { - val gbStr = String.format("%.2f", gb) + val gbStr = String.format(java.util.Locale.getDefault(), "%.2f", gb) val span = SpannableString("$gbStr GB") span.setSpan(RelativeSizeSpan(0.5f), gbStr.length, gbStr.length + 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) span } else { - val mbStr = String.format("%.1f", mb) + val mbStr = String.format(java.util.Locale.getDefault(), "%.1f", mb) val span = SpannableString("$mbStr MB") span.setSpan(RelativeSizeSpan(0.5f), mbStr.length, mbStr.length + 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) span @@ -235,7 +235,7 @@ object SystemStatsFetcher { val gb = freeBytes / (1024f * 1024f * 1024f) - val gbStr = String.format("%.0f", gb) + val gbStr = String.format(java.util.Locale.getDefault(), "%.0f", gb) val span = SpannableString("$gbStr GB") span.setSpan(RelativeSizeSpan(0.5f), gbStr.length, gbStr.length + 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) @@ -259,7 +259,7 @@ object SystemStatsFetcher { val percentage = if (totalBytes > 0) (freeBytes.toFloat() / totalBytes.toFloat() * 100) else 0f - val pctStr = String.format("%.0f", percentage) + val pctStr = String.format(java.util.Locale.getDefault(), "%.0f", percentage) val span = SpannableString("$pctStr%") span.setSpan(RelativeSizeSpan(0.5f), pctStr.length, pctStr.length + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) diff --git a/app/src/main/res/layout/activity_setup.xml b/app/src/main/res/layout/activity_setup.xml index f794f01..86e5e46 100644 --- a/app/src/main/res/layout/activity_setup.xml +++ b/app/src/main/res/layout/activity_setup.xml @@ -86,6 +86,7 @@ android:padding="24dp"> تطبيق التقويم البحث في الإعدادات… ما الجديد في v2.9 + + + توضيح الإذن + لعرض الطقس، يحتاج Lwidget إلى قراءة البيانات من Breezy Weather.\n\nسيطلب Android الآن إذن «الموقع». يرجى الملاحظة: لا يصل Lwidget إلى موقعك ولا يملك إذنًا للوصول إلى الإنترنت. هذه ببساطة طريقة تصنيف Android لإذن مشاركة بيانات Breezy Weather. + خطوة مهمة + إذا لم يظهر الطقس في الودجت قريبًا:\n\nافتح Breezy Weather ← الإعدادات ← الوحدات الخارجية ← فعّل «Send Gadgetbridge Data» ثم فعّل «Lwidget». + متابعة + إلغاء + حسنًا + تثبيت + تطبيق Breezy Weather (مع تفعيل DataBridge) مطلوب. + تطبيق Breezy Weather مطلوب. + تطبيق Tasks.org مطلوب لهذه الميزة. + الإعدادات الافتراضية + الإعدادات الافتراضية ▾ + Lwidget #%1$d + الودجت #%1$d ▾ + الودجت #%1$d (المعرّف: %2$d) + اختر الودجت المراد إعداده + تم المنح + تفعيل + الحجم + عدّاد خطوات Lwidget + إبقاء Lwidget نشطًا + %1$s خطوة اليوم + جارٍ عدّ الخطوات في الخلفية + الحفاظ على تحديث الودجت + خدمة عدّاد الخطوات + يُبقي عدّاد الخطوات يعمل في الخلفية. + غير معروف + نقل لأعلى + نقل لأسفل diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 3b2cf6f..d5a9214 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -114,4 +114,36 @@ Kalender-App Einstellungen durchsuchen… Was gibt\'s Neues in v2.9 + + + Berechtigung erklärt + Um das Wetter anzuzeigen, muss Lwidget Daten von Breezy Weather lesen.\n\nAndroid fragt jetzt nach dem Zugriff auf den „Standort“. Hinweis: Lwidget greift NICHT auf Ihren Standort zu und hat auch keine Berechtigung für den Internetzugriff. So stuft Android lediglich die Berechtigung zur Datenfreigabe von Breezy Weather ein. + Wichtiger Schritt + Falls das Wetter bald nicht in Ihrem Widget erscheint:\n\nÖffnen Sie Breezy Weather → Einstellungen → Externe Module → Aktivieren Sie „Send Gadgetbridge Data“ und schalten Sie „Lwidget“ ein. + Weiter + Abbrechen + Verstanden + Installieren + Die App Breezy Weather (mit aktivierter DataBridge) ist erforderlich. + Die App Breezy Weather ist erforderlich. + Für diese Funktion ist die App Tasks.org erforderlich. + Standardeinstellungen + Standardeinstellungen ▾ + Lwidget #%1$d + Widget #%1$d ▾ + Widget #%1$d (ID: %2$d) + Widget zum Konfigurieren auswählen + Erteilt + Aktivieren + Größe + Lwidget Schrittzähler + Lwidget bleibt aktiv + %1$s Schritte heute + Zählt Schritte im Hintergrund + Hält das Widget aktuell + Schrittzähler-Dienst + Hält den Schrittzähler im Hintergrund aktiv. + Unbekannt + Nach oben + Nach unten diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 17d42d3..fda9129 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -114,4 +114,36 @@ Aplicación de calendario Buscar ajustes… Novedades de la versión 2.9 + + + Aclaración del permiso + Para mostrar el tiempo, Lwidget necesita leer datos de Breezy Weather.\n\nAndroid pedirá ahora acceso a la «Ubicación». Importante: Lwidget NO accede a tu ubicación ni tiene permiso para acceder a internet. Así es como Android clasifica el permiso de uso compartido de datos de Breezy Weather. + Paso importante + Si el tiempo no aparece pronto en tu widget:\n\nAbre Breezy Weather → Ajustes → Módulos externos → Activa «Send Gadgetbridge Data» y activa «Lwidget». + Continuar + Cancelar + Entendido + Instalar + Se requiere la app Breezy Weather (con DataBridge activado). + Se requiere la app Breezy Weather. + Esta función requiere la app Tasks.org. + Ajustes predeterminados + Ajustes predeterminados ▾ + Lwidget #%1$d + Widget #%1$d ▾ + Widget #%1$d (ID: %2$d) + Selecciona el widget a configurar + Concedido + Activar + Tamaño + Contador de pasos de Lwidget + Lwidget en segundo plano + %1$s pasos hoy + Contando pasos en segundo plano + Manteniendo el widget actualizado + Servicio del contador de pasos + Mantiene el contador de pasos en segundo plano. + Desconocida + Subir + Bajar diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 0db55bc..664aa58 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -114,4 +114,36 @@ Application Calendrier Rechercher dans les paramètres… Nouveautés de la v2.9 + + + Précision sur l\'autorisation + Pour afficher la météo, Lwidget doit lire les données de Breezy Weather.\n\nAndroid va maintenant demander l\'accès à la « Position ». Remarque : Lwidget n\'accède PAS à votre position et n\'a pas non plus l\'autorisation d\'accéder à Internet. C\'est simplement la façon dont Android classe l\'autorisation de partage de données de Breezy Weather. + Étape importante + Si la météo n\'apparaît pas bientôt sur votre widget :\n\nOuvrez Breezy Weather → Paramètres → Modules externes → Activez « Send Gadgetbridge Data » et activez « Lwidget ». + Continuer + Annuler + Compris + Installer + L\'application Breezy Weather (avec DataBridge activé) est requise. + L\'application Breezy Weather est requise. + L\'application Tasks.org est requise pour cette fonctionnalité. + Paramètres par défaut + Paramètres par défaut ▾ + Lwidget #%1$d + Widget #%1$d ▾ + Widget #%1$d (ID : %2$d) + Sélectionnez le widget à configurer + Accordé + Activer + Taille + Compteur de pas Lwidget + Lwidget maintien actif + %1$s pas aujourd\'hui + Comptage des pas en arrière-plan + Maintien du widget à jour + Service du compteur de pas + Maintient le compteur de pas actif en arrière-plan. + Inconnue + Monter + Descendre diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index cd7af58..7172e31 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -114,4 +114,36 @@ कैलेंडर ऐप सेटिंग्स खोजें… v2.9 में नया क्या है + + + अनुमति की जानकारी + मौसम दिखाने के लिए Lwidget को Breezy Weather से डेटा पढ़ना होगा।\n\nAndroid अब \'स्थान\' की अनुमति मांगेगा। कृपया ध्यान दें: Lwidget आपके स्थान तक नहीं पहुँचता और न ही उसे इंटरनेट की अनुमति है। Android बस इसी तरह Breezy Weather की डेटा साझा करने की अनुमति को वर्गीकृत करता है। + ज़रूरी चरण + अगर मौसम जल्द ही आपके विजेट पर न दिखे:\n\nBreezy Weather खोलें → सेटिंग्स → बाहरी मॉड्यूल → \'Send Gadgetbridge Data\' चालू करें और \'Lwidget\' को ऑन करें। + जारी रखें + रद्द करें + समझ गया + इंस्टॉल करें + Breezy Weather ऐप (DataBridge चालू के साथ) आवश्यक है। + Breezy Weather ऐप आवश्यक है। + इस सुविधा के लिए Tasks.org ऐप आवश्यक है। + डिफ़ॉल्ट सेटिंग्स + डिफ़ॉल्ट सेटिंग्स ▾ + Lwidget #%1$d + विजेट #%1$d ▾ + विजेट #%1$d (ID: %2$d) + कॉन्फ़िगर करने के लिए विजेट चुनें + दी गई + चालू करें + आकार + Lwidget स्टेप काउंटर + Lwidget सक्रिय रखें + आज %1$s कदम + बैकग्राउंड में कदम गिने जा रहे हैं + विजेट को अपडेट रखा जा रहा है + स्टेप काउंटर सेवा + स्टेप काउंटर को बैकग्राउंड में चालू रखता है। + अज्ञात + ऊपर ले जाएँ + नीचे ले जाएँ diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 0ba69ba..9eda87e 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -114,4 +114,36 @@ カレンダーアプリ 設定を検索… v2.9 の新機能 + + + 権限についての説明 + 天気を表示するには、Lwidget が Breezy Weather のデータを読み取る必要があります。\n\nこれから Android が「位置情報」へのアクセスを求めます。Lwidget があなたの位置情報にアクセスすることはなく、インターネットへのアクセス権限もありません。これは Android が Breezy Weather のデータ共有権限をこのように分類しているためです。 + 重要な手順 + 天気がすぐにウィジェットに表示されない場合:\n\nBreezy Weather を開く → 設定 → 外部モジュール → 「Send Gadgetbridge Data」を有効にし、「Lwidget」をオンにしてください。 + 続ける + キャンセル + 了解 + インストール + Breezy Weather アプリ(DataBridge を有効にしたもの)が必要です。 + Breezy Weather アプリが必要です。 + この機能には Tasks.org アプリが必要です。 + デフォルト設定 + デフォルト設定 ▾ + Lwidget #%1$d + ウィジェット #%1$d ▾ + ウィジェット #%1$d (ID: %2$d) + 設定するウィジェットを選択 + 許可済み + 有効にする + サイズ + Lwidget 歩数計 + Lwidget バックグラウンド維持 + 今日は %1$s 歩 + バックグラウンドで歩数を計測中 + ウィジェットを最新の状態に保っています + 歩数計サービス + 歩数計をバックグラウンドで動作させ続けます。 + 不明 + 上へ移動 + 下へ移動 diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 6757cdc..d409c18 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -114,4 +114,36 @@ Aplicativo de calendário Pesquisar configurações… Novidades da v2.9 + + + Esclarecimento da permissão + Para exibir o clima, o Lwidget precisa ler dados do Breezy Weather.\n\nO Android agora pedirá acesso à «Localização». Observação: o Lwidget NÃO acessa sua localização, nem tem permissão para acessar a internet. É apenas assim que o Android classifica a permissão de compartilhamento de dados do Breezy Weather. + Etapa importante + Se o clima não aparecer em breve no seu widget:\n\nAbra o Breezy Weather → Configurações → Módulos externos → Ative «Send Gadgetbridge Data» e ative «Lwidget». + Continuar + Cancelar + Entendi + Instalar + O app Breezy Weather (com DataBridge ativado) é necessário. + O app Breezy Weather é necessário. + O app Tasks.org é necessário para este recurso. + Configurações padrão + Configurações padrão ▾ + Lwidget #%1$d + Widget #%1$d ▾ + Widget #%1$d (ID: %2$d) + Selecione o widget para configurar + Concedido + Ativar + Tamanho + Contador de passos do Lwidget + Lwidget mantido ativo + %1$s passos hoje + Contando passos em segundo plano + Mantendo o widget atualizado + Serviço do contador de passos + Mantém o contador de passos em execução em segundo plano. + Desconhecida + Mover para cima + Mover para baixo diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 161ed06..f8c7bc4 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -114,4 +114,36 @@ Приложение Календарь Поиск настроек… Что нового в v2.9 + + + Пояснение к разрешению + Чтобы показывать погоду, Lwidget должен читать данные из Breezy Weather.\n\nСейчас Android запросит доступ к «Местоположению». Обратите внимание: Lwidget НЕ получает доступ к вашему местоположению и не имеет разрешения на доступ в интернет. Так Android просто классифицирует разрешение на обмен данными Breezy Weather. + Важный шаг + Если погода скоро не появится на виджете:\n\nОткройте Breezy Weather → Настройки → Внешние модули → Включите «Send Gadgetbridge Data» и включите «Lwidget». + Продолжить + Отмена + Понятно + Установить + Требуется приложение Breezy Weather (с включённым DataBridge). + Требуется приложение Breezy Weather. + Для этой функции требуется приложение Tasks.org. + Настройки по умолчанию + Настройки по умолчанию ▾ + Lwidget #%1$d + Виджет #%1$d ▾ + Виджет #%1$d (ID: %2$d) + Выберите виджет для настройки + Предоставлено + Включить + Размер + Шагомер Lwidget + Lwidget в фоне + %1$s шагов сегодня + Подсчёт шагов в фоновом режиме + Поддержание актуальности виджета + Служба шагомера + Поддерживает работу шагомера в фоновом режиме. + Неизвестно + Переместить вверх + Переместить вниз diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 88e80dd..a1f2b78 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -114,4 +114,36 @@ Takvim Uygulaması Ayarları ara… v2.9\'daki Yenilikler + + + İzin Açıklaması + Hava durumunu göstermek için Lwidget\'ın Breezy Weather\'dan veri okuması gerekir.\n\nAndroid şimdi \'Konum\' erişimi isteyecek. Lütfen unutmayın: Lwidget konumunuza ERİŞMEZ ve internete erişim izni de yoktur. Android, Breezy Weather\'ın veri paylaşım iznini yalnızca bu şekilde sınıflandırır. + Önemli Adım + Hava durumu kısa süre içinde widget\'ınızda görünmezse:\n\nBreezy Weather → Ayarlar → Harici Modüller → \'Send Gadgetbridge Data\' seçeneğini etkinleştirin ve \'Lwidget\'ı açın. + Devam + İptal + Anladım + Yükle + Breezy Weather uygulaması (DataBridge etkin) gereklidir. + Breezy Weather uygulaması gereklidir. + Bu özellik için Tasks.org uygulaması gereklidir. + Varsayılan Ayarlar + Varsayılan Ayarlar ▾ + Lwidget #%1$d + Widget #%1$d ▾ + Widget #%1$d (ID: %2$d) + Yapılandırılacak widget\'ı seçin + Verildi + Etkinleştir + Boyut + Lwidget Adım Sayar + Lwidget Arka Planda Tut + Bugün %1$s adım + Adımlar arka planda sayılıyor + Widget güncel tutuluyor + Adım Sayar Hizmeti + Adım sayarın arka planda çalışmasını sağlar. + Bilinmiyor + Yukarı taşı + Aşağı taşı diff --git a/app/src/main/res/values-zh/strings.xml b/app/src/main/res/values-zh/strings.xml index 20a5618..4bec02e 100644 --- a/app/src/main/res/values-zh/strings.xml +++ b/app/src/main/res/values-zh/strings.xml @@ -114,4 +114,36 @@ 日历应用 搜索设置… v2.9 新特性 + + + 权限说明 + 要显示天气,Lwidget 需要读取 Breezy Weather 的数据。\n\nAndroid 接下来会请求“位置信息”权限。请注意:Lwidget 不会访问您的位置信息,也没有访问互联网的权限。这只是 Android 对 Breezy Weather 数据共享权限的分类方式。 + 重要步骤 + 如果天气很快没有显示在小部件上:\n\n打开 Breezy Weather → 设置 → 外部模块 → 启用“Send Gadgetbridge Data”并打开“Lwidget”。 + 继续 + 取消 + 知道了 + 安装 + 需要 Breezy Weather 应用(并启用 DataBridge)。 + 需要 Breezy Weather 应用。 + 此功能需要 Tasks.org 应用。 + 默认设置 + 默认设置 ▾ + Lwidget #%1$d + 小部件 #%1$d ▾ + 小部件 #%1$d(ID:%2$d) + 选择要配置的小部件 + 已授权 + 启用 + 大小 + Lwidget 计步器 + Lwidget 后台保活 + 今天 %1$s 步 + 正在后台统计步数 + 正在保持小部件更新 + 计步服务 + 让计步器在后台持续运行。 + 未知 + 上移 + 下移 diff --git a/app/src/main/res/values/ids.xml b/app/src/main/res/values/ids.xml new file mode 100644 index 0000000..5575a5f --- /dev/null +++ b/app/src/main/res/values/ids.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index d97cfd4..acf7fa9 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -114,4 +114,36 @@ Skip Finish Grant + + + Permission Clarification + 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. + Important Step + 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\'. + Continue + Cancel + Got it + Install + Breezy Weather app (with DataBridge enabled) is required. + Breezy Weather app is required. + Tasks.org app is required for this feature. + Default Settings + Default Settings ▾ + Lwidget #%1$d + Widget #%1$d ▾ + Widget #%1$d (ID: %2$d) + Select Widget to Configure + Granted + Enable + Size + Lwidget Step Counter + Lwidget Keep Alive + %1$s steps today + Counting steps in the background + Keeping widget updated + Step Counter Service + Keeps the step counter running in the background. + Unknown + Move up + Move down diff --git a/app/src/test/java/com/leanbitlab/lwidget/AwidgetProviderScheduleTest.kt b/app/src/test/java/com/leanbitlab/lwidget/AwidgetProviderScheduleTest.kt new file mode 100644 index 0000000..84a3246 --- /dev/null +++ b/app/src/test/java/com/leanbitlab/lwidget/AwidgetProviderScheduleTest.kt @@ -0,0 +1,71 @@ +package com.leanbitlab.lwidget + +import android.app.AlarmManager +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf + +@RunWith(RobolectricTestRunner::class) +class AwidgetProviderScheduleTest { + + private lateinit var context: Context + private lateinit var alarmManager: AlarmManager + + @Before + fun setUp() { + context = ApplicationProvider.getApplicationContext() + alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager + context.getSharedPreferences("com.leanbitlab.lwidget.PREFS", Context.MODE_PRIVATE) + .edit().clear().commit() + } + + private fun setIntervalMinutes(minutes: Float) { + context.getSharedPreferences("com.leanbitlab.lwidget.PREFS", Context.MODE_PRIVATE) + .edit().putFloat("update_interval", minutes).commit() + } + + @Test + fun onEnabledSchedulesDefaultFifteenMinuteInterval() { + AwidgetProvider().onEnabled(context) + + val alarm = shadowOf(alarmManager).nextScheduledAlarm + assertNotNull(alarm) + assertEquals(15 * 60 * 1000L, alarm!!.interval) + } + + @Test + fun intervalUsesConfiguredValue() { + setIntervalMinutes(30f) + + AwidgetProvider().onEnabled(context) + + assertEquals(30 * 60 * 1000L, shadowOf(alarmManager).nextScheduledAlarm!!.interval) + } + + @Test + fun intervalIsNeverBelowOneMinute() { + setIntervalMinutes(0.1f) + + AwidgetProvider().onEnabled(context) + + assertEquals(60_000L, shadowOf(alarmManager).nextScheduledAlarm!!.interval) + } + + @Test + fun onDisabledCancelsTheAlarm() { + val provider = AwidgetProvider() + provider.onEnabled(context) + assertNotNull(shadowOf(alarmManager).nextScheduledAlarm) + + provider.onDisabled(context) + + assertNull(shadowOf(alarmManager).nextScheduledAlarm) + } +} diff --git a/app/src/test/java/com/leanbitlab/lwidget/FallbackPreferencesTest.kt b/app/src/test/java/com/leanbitlab/lwidget/FallbackPreferencesTest.kt new file mode 100644 index 0000000..6d1b51e --- /dev/null +++ b/app/src/test/java/com/leanbitlab/lwidget/FallbackPreferencesTest.kt @@ -0,0 +1,95 @@ +package com.leanbitlab.lwidget + +import android.content.Context +import android.content.SharedPreferences +import androidx.test.core.app.ApplicationProvider +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) +class FallbackPreferencesTest { + + private lateinit var global: SharedPreferences + private lateinit var widget: SharedPreferences + private lateinit var prefs: FallbackPreferences + + @Before + fun setUp() { + val context = ApplicationProvider.getApplicationContext() + global = context.getSharedPreferences("test_global", Context.MODE_PRIVATE) + widget = context.getSharedPreferences("test_widget", Context.MODE_PRIVATE) + global.edit().clear().commit() + widget.edit().clear().commit() + prefs = FallbackPreferences(widget, global) + } + + @Test + fun readsFromGlobalWhenWidgetHasNoValue() { + global.edit().putBoolean("show_battery", true).putInt("size", 14).commit() + + assertTrue(prefs.getBoolean("show_battery", false)) + assertEquals(14, prefs.getInt("size", 0)) + } + + @Test + fun widgetValueOverridesGlobal() { + global.edit().putString("date_format", "global").putFloat("update_interval", 15f).commit() + widget.edit().putString("date_format", "widget").putFloat("update_interval", 5f).commit() + + assertEquals("widget", prefs.getString("date_format", null)) + assertEquals(5f, prefs.getFloat("update_interval", 0f), 0f) + } + + @Test + fun widgetFalseOverridesGlobalTrue() { + global.edit().putBoolean("show_steps", true).commit() + widget.edit().putBoolean("show_steps", false).commit() + + assertFalse(prefs.getBoolean("show_steps", true)) + } + + @Test + fun returnsDefaultWhenNowhere() { + assertEquals("def", prefs.getString("missing", "def")) + assertEquals(7L, prefs.getLong("missing", 7L)) + assertFalse(prefs.contains("missing")) + } + + @Test + fun writesGoOnlyToWidgetPrefs() { + global.edit().putInt("size", 14).commit() + + prefs.edit().putInt("size", 20).commit() + + assertEquals(20, widget.getInt("size", 0)) + assertEquals(14, global.getInt("size", 0)) + assertEquals(20, prefs.getInt("size", 0)) + } + + @Test + fun removingWidgetValueFallsBackToGlobal() { + global.edit().putInt("size", 14).commit() + prefs.edit().putInt("size", 20).commit() + + prefs.edit().remove("size").commit() + + assertEquals(14, prefs.getInt("size", 0)) + } + + @Test + fun getAllMergesWithWidgetWinning() { + global.edit().putString("a", "g").putString("b", "g").commit() + widget.edit().putString("b", "w").putString("c", "w").commit() + + val all = prefs.all + assertEquals("g", all["a"]) + assertEquals("w", all["b"]) + assertEquals("w", all["c"]) + assertTrue(prefs.contains("a") && prefs.contains("c")) + } +} diff --git a/app/src/test/java/com/leanbitlab/lwidget/MainActivitySmokeTest.kt b/app/src/test/java/com/leanbitlab/lwidget/MainActivitySmokeTest.kt new file mode 100644 index 0000000..c4dc5ad --- /dev/null +++ b/app/src/test/java/com/leanbitlab/lwidget/MainActivitySmokeTest.kt @@ -0,0 +1,71 @@ +package com.leanbitlab.lwidget + +import android.content.Context +import android.view.View +import androidx.test.core.app.ApplicationProvider +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * Safety net for MainActivity refactors: the settings screen must inflate and bind every + * section without throwing, and the key controls must still exist afterwards. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class MainActivitySmokeTest { + + private lateinit var context: Context + + @Before + fun setUp() { + context = ApplicationProvider.getApplicationContext() + context.getSharedPreferences("com.leanbitlab.lwidget.PREFS", Context.MODE_PRIVATE) + .edit().clear().putBoolean("is_first_launch", false).commit() + } + + @Test + fun launchesAndBindsAllSections() { + val activity = Robolectric.buildActivity(MainActivity::class.java).setup().get() + + assertTrue("activity should not have finished", !activity.isFinishing) + listOf( + R.id.row_update_interval, + R.id.fab_update, + R.id.nested_scroll_view, + R.id.tv_changelog_version, + ).forEach { id -> assertNotNull("missing view $id", activity.findViewById(id)) } + } + + @Test + fun firstLaunchRedirectsToSetup() { + context.getSharedPreferences("com.leanbitlab.lwidget.PREFS", Context.MODE_PRIVATE) + .edit().putBoolean("is_first_launch", true).commit() + + val activity = Robolectric.buildActivity(MainActivity::class.java).setup().get() + + assertTrue(activity.isFinishing) + } + + @Test + fun survivesRecreate() { + val controller = Robolectric.buildActivity(MainActivity::class.java).setup() + controller.recreate() + + assertTrue(!controller.get().isFinishing) + } + + @Test + @Config(sdk = [33], qualifiers = "w900dp-h600dp") + fun launchesOnWideScreen() { + val activity = Robolectric.buildActivity(MainActivity::class.java).setup().get() + + assertTrue(!activity.isFinishing) + assertNotNull(activity.findViewById(R.id.nested_scroll_view)) + } +} diff --git a/app/src/test/java/com/leanbitlab/lwidget/ReorderAdapterTest.kt b/app/src/test/java/com/leanbitlab/lwidget/ReorderAdapterTest.kt new file mode 100644 index 0000000..0ba8758 --- /dev/null +++ b/app/src/test/java/com/leanbitlab/lwidget/ReorderAdapterTest.kt @@ -0,0 +1,93 @@ +package com.leanbitlab.lwidget + +import android.content.Context +import android.view.ContextThemeWrapper +import android.view.View +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import androidx.test.core.app.ApplicationProvider +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) +class ReorderAdapterTest { + + private fun items() = mutableListOf( + ReorderItem("show_battery", "Battery", true), + ReorderItem("show_steps", "Steps", true), + ReorderItem("show_ram", "RAM", false), + ) + + @Test + fun moveItemReordersForward() { + val list = items() + ReorderAdapter(list, {}).moveItem(0, 2) + + assertEquals(listOf("show_steps", "show_ram", "show_battery"), list.map { it.key }) + } + + @Test + fun moveItemReordersBackward() { + val list = items() + ReorderAdapter(list, {}).moveItem(2, 0) + + assertEquals(listOf("show_ram", "show_battery", "show_steps"), list.map { it.key }) + } + + @Test + fun moveItemToSameIndexIsNoOp() { + val list = items() + ReorderAdapter(list, {}).moveItem(1, 1) + + assertEquals(listOf("show_battery", "show_steps", "show_ram"), list.map { it.key }) + } + + @Test + fun itemCountMatchesList() { + assertEquals(3, ReorderAdapter(items(), {}).itemCount) + } + + private fun attach(list: MutableList, onChanged: () -> Unit): RecyclerView { + val base = ApplicationProvider.getApplicationContext() + val ctx = ContextThemeWrapper(base, R.style.Theme_Lwidget) + return RecyclerView(ctx).apply { + layoutManager = LinearLayoutManager(ctx) + adapter = ReorderAdapter(list, {}, onChanged) + measure( + View.MeasureSpec.makeMeasureSpec(1000, View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec(2000, View.MeasureSpec.EXACTLY) + ) + layout(0, 0, 1000, 2000) + } + } + + @Test + fun accessibilityMoveDownReordersAndNotifies() { + val list = items() + var changed = 0 + val rv = attach(list) { changed++ } + + val handled = rv.getChildAt(0).performAccessibilityAction(R.id.a11y_action_move_down, null) + + assertTrue(handled) + assertEquals(listOf("show_steps", "show_battery", "show_ram"), list.map { it.key }) + assertEquals(1, changed) + } + + @Test + fun accessibilityMoveUpOnFirstItemIsRejected() { + val list = items() + var changed = 0 + val rv = attach(list) { changed++ } + + val handled = rv.getChildAt(0).performAccessibilityAction(R.id.a11y_action_move_up, null) + + assertFalse(handled) + assertEquals(listOf("show_battery", "show_steps", "show_ram"), list.map { it.key }) + assertEquals(0, changed) + } +} diff --git a/app/src/test/java/com/leanbitlab/lwidget/SettingsLayoutTest.kt b/app/src/test/java/com/leanbitlab/lwidget/SettingsLayoutTest.kt new file mode 100644 index 0000000..aa79c05 --- /dev/null +++ b/app/src/test/java/com/leanbitlab/lwidget/SettingsLayoutTest.kt @@ -0,0 +1,24 @@ +package com.leanbitlab.lwidget + +import org.junit.Assert.assertEquals +import org.junit.Test + +class SettingsLayoutTest { + + @Test + fun noInsetWhenContentFits() { + assertEquals(0, contentHorizontalInset(availablePx = 1080, maxContentPx = 1800)) + assertEquals(0, contentHorizontalInset(availablePx = 1800, maxContentPx = 1800)) + } + + @Test + fun insetCentersContentWhenWider() { + // 2400 wide, 1800 max -> 300px each side + assertEquals(300, contentHorizontalInset(availablePx = 2400, maxContentPx = 1800)) + } + + @Test + fun oddRemainderIsFloored() { + assertEquals(150, contentHorizontalInset(availablePx = 2101, maxContentPx = 1800)) + } +} diff --git a/app/src/test/java/com/leanbitlab/lwidget/WidgetUpdateDebounceTest.kt b/app/src/test/java/com/leanbitlab/lwidget/WidgetUpdateDebounceTest.kt new file mode 100644 index 0000000..fac4e8f --- /dev/null +++ b/app/src/test/java/com/leanbitlab/lwidget/WidgetUpdateDebounceTest.kt @@ -0,0 +1,56 @@ +package com.leanbitlab.lwidget + +import android.appwidget.AppWidgetManager +import android.content.Context +import android.os.Looper +import androidx.test.core.app.ApplicationProvider +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import java.time.Duration + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class WidgetUpdateDebounceTest { + + @Before + fun setUp() { + ApplicationProvider.getApplicationContext() + .getSharedPreferences("com.leanbitlab.lwidget.PREFS", Context.MODE_PRIVATE) + .edit().clear().putBoolean("is_first_launch", false).commit() + } + + private fun updateBroadcasts(): Int = + shadowOf(ApplicationProvider.getApplicationContext()) + .broadcastIntents.count { it.action == AppWidgetManager.ACTION_APPWIDGET_UPDATE } + + @Test + fun rapidSliderChangesProduceOneWidgetUpdate() { + val activity = Robolectric.buildActivity(MainActivity::class.java).setup().get() + shadowOf(Looper.getMainLooper()).idle() + val before = updateBroadcasts() + + repeat(20) { activity.scheduleWidgetUpdate() } + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1)) + + assertEquals(1, updateBroadcasts() - before) + } + + @Test + fun pendingUpdateIsCancelledOnDestroy() { + val controller = Robolectric.buildActivity(MainActivity::class.java).setup() + shadowOf(Looper.getMainLooper()).idle() + val before = updateBroadcasts() + + controller.get().scheduleWidgetUpdate() + controller.pause().stop().destroy() + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1)) + + assertEquals(0, updateBroadcasts() - before) + } +} diff --git a/app/src/test/resources/robolectric.properties b/app/src/test/resources/robolectric.properties new file mode 100644 index 0000000..efe7f6b --- /dev/null +++ b/app/src/test/resources/robolectric.properties @@ -0,0 +1,3 @@ +# Robolectric 4.11.1 supports up to SDK 34; the app targets 36. Pin the simulated SDK for all tests. +# Revisit when Robolectric is upgraded. +sdk=34 diff --git a/docs/images/1.png b/docs/images/1.png deleted file mode 100644 index 7883589..0000000 Binary files a/docs/images/1.png and /dev/null differ diff --git a/docs/images/2.png b/docs/images/2.png deleted file mode 100644 index 8512d81..0000000 Binary files a/docs/images/2.png and /dev/null differ diff --git a/docs/images/3.png b/docs/images/3.png deleted file mode 100644 index 2245c63..0000000 Binary files a/docs/images/3.png and /dev/null differ diff --git a/docs/images/4.png b/docs/images/4.png deleted file mode 100644 index 2ff46ee..0000000 Binary files a/docs/images/4.png and /dev/null differ diff --git a/docs/images/5.png b/docs/images/5.png deleted file mode 100644 index 2314e3f..0000000 Binary files a/docs/images/5.png and /dev/null differ diff --git a/docs/images/6.png b/docs/images/6.png deleted file mode 100644 index 005a2b0..0000000 Binary files a/docs/images/6.png and /dev/null differ diff --git a/docs/images/7.png b/docs/images/7.png deleted file mode 100644 index 562b4cb..0000000 Binary files a/docs/images/7.png and /dev/null differ diff --git a/docs/images/8.png b/docs/images/8.png deleted file mode 100644 index 000da9a..0000000 Binary files a/docs/images/8.png and /dev/null differ diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml deleted file mode 100644 index 73410ed..0000000 --- a/gradle/libs.versions.toml +++ /dev/null @@ -1,43 +0,0 @@ -[versions] -#jetbrains -geocoderVersion = "3.20" -kotlin = "2.2.21" -kotlinxSerializationJson = "1.9.0" -#Detekt -detekt = "1.23.8" -detektCompose = "0.4.28" -#Eventbus -eventbus = "3.3.1" -#Fossify -commons = "5.11.0" -#Gradle -gradlePlugins-agp = "8.11.1" -#Other -indicatorFastScroll = "c7873f7168" -autofitTextView = "0.2.1" -libphonenumberVersion = "9.0.20" -#build -app-build-compileSDKVersion = "36" -app-build-targetSDK = "36" -app-build-minimumSDK = "26" -app-build-javaVersion = "VERSION_17" -app-build-kotlinJVMTarget = "17" -[libraries] -#Compose -compose-detekt = { module = "io.nlopez.compose.rules:detekt", version.ref = "detektCompose" } -#Fossify -fossify-commons = { module = "org.fossify:commons", version.ref = "commons" } -#EventBus -eventbus = { module = "org.greenrobot:eventbus", version.ref = "eventbus" } -#Kotlin -geocoder = { module = "com.googlecode.libphonenumber:geocoder", version.ref = "geocoderVersion" } -kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinxSerializationJson" } -#Other -indicator-fast-scroll = { module = "org.fossify:IndicatorFastScroll", version.ref = "indicatorFastScroll" } -autofit-text-view = { module = "me.grantland:autofittextview", version.ref = "autofitTextView" } -libphonenumber = { module = "com.googlecode.libphonenumber:libphonenumber", version.ref = "libphonenumberVersion" } -[plugins] -android = { id = "com.android.application", version.ref = "gradlePlugins-agp" } -kotlinAndroid = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } -kotlinSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } -detekt = { id = "io.gitlab.arturbosch.detekt", version.ref = "detekt" } diff --git a/scripts/check_strings.py b/scripts/check_strings.py new file mode 100644 index 0000000..485cd81 --- /dev/null +++ b/scripts/check_strings.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Verify every localized strings.xml matches the base values/strings.xml. + +Checks, per locale: + - missing keys (present in base, absent in locale) + - extra keys (present in locale, absent in base) + - format placeholder mismatch (%s, %d, %1$s, ...) +Entries with translatable="false" in the base file are ignored. + +Usage: python3 scripts/check_strings.py [res_dir] +Exit code 1 if any problem is found. +""" +import re +import sys +import xml.etree.ElementTree as ET +from pathlib import Path + +RES = Path(sys.argv[1] if len(sys.argv) > 1 else "app/src/main/res") +PLACEHOLDER = re.compile(r"%(?:\d+\$)?[sdfxXc%n]") + + +def load(path): + """Return {name: text} for , , ; skip non-translatable.""" + out = {} + for el in ET.parse(path).getroot(): + name = el.get("name") + if not name or el.get("translatable") == "false": + continue + out[name] = "".join(el.itertext()) + return out + + +def placeholders(text): + return sorted(p for p in PLACEHOLDER.findall(text) if p != "%%") + + +def main(): + base_file = RES / "values" / "strings.xml" + base = load(base_file) + problems = [] + for loc_file in sorted(RES.glob("values-*/strings.xml")): + loc = load(loc_file) + name = loc_file.parent.name + for key in sorted(base.keys() - loc.keys()): + problems.append(f"{name}: missing '{key}'") + for key in sorted(loc.keys() - base.keys()): + problems.append(f"{name}: extra '{key}' (not in base)") + for key in sorted(base.keys() & loc.keys()): + if placeholders(base[key]) != placeholders(loc[key]): + problems.append( + f"{name}: placeholder mismatch in '{key}': " + f"{placeholders(base[key])} vs {placeholders(loc[key])}" + ) + if problems: + print("String resource problems:") + for p in problems: + print(" " + p) + return 1 + print(f"OK: {len(base)} base strings consistent across all locales") + return 0 + + +if __name__ == "__main__": + sys.exit(main())