Feat/settings #39

Merged
robin merged 2 commits from feat/settings into main 2026-10-30 12:35:54 +00:00
8 changed files with 410 additions and 30 deletions

No files matched your search

+4
View File
@@ -1,5 +1,9 @@
# Changelog # Changelog
## [1.4.0] - 2026-10-30
### New
* settings
## [1.3.0] - 2026-10-30 ## [1.3.0] - 2026-10-30
### New ### New
* auto update * auto update
@@ -5,6 +5,7 @@ import android.os.Bundle
import androidx.activity.ComponentActivity import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.* import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.Home
@@ -21,7 +22,10 @@ import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import de.schanbro.weekfocus.ui.theme.WeekFocusTheme import de.schanbro.weekfocus.ui.theme.WeekFocusTheme
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import de.schanbro.weekfocus.screens.SettingsScreen
import de.schanbro.weekfocus.screens.WordListScreen import de.schanbro.weekfocus.screens.WordListScreen
import de.schanbro.weekfocus.settings.SettingsRepository
import de.schanbro.weekfocus.settings.ThemeMode
import de.schanbro.weekfocus.update.NetworkPermissionGate import de.schanbro.weekfocus.update.NetworkPermissionGate
import de.schanbro.weekfocus.update.UpdateHandler import de.schanbro.weekfocus.update.UpdateHandler
@@ -31,7 +35,14 @@ class MainActivity : ComponentActivity() {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
enableEdgeToEdge() enableEdgeToEdge()
setContent { setContent {
WeekFocusTheme { val settings = remember { SettingsRepository.get(applicationContext) }
val darkTheme = when (settings.themeMode) {
ThemeMode.SYSTEM -> isSystemInDarkTheme()
ThemeMode.LIGHT -> false
ThemeMode.DARK -> true
}
WeekFocusTheme(darkTheme = darkTheme) {
MainScreen() MainScreen()
NetworkPermissionGate { NetworkPermissionGate {
UpdateHandler() UpdateHandler()
@@ -124,7 +135,7 @@ fun MainScreen() {
when (selectedTab) { when (selectedTab) {
0 -> PlaceholderScreen(title = stringResource(R.string.title_weekly_focus)) 0 -> PlaceholderScreen(title = stringResource(R.string.title_weekly_focus))
1 -> WordListScreen() 1 -> WordListScreen()
2 -> PlaceholderScreen(title = stringResource(R.string.title_settings)) 2 -> SettingsScreen()
} }
} }
} }
@@ -0,0 +1,236 @@
package de.schanbro.weekfocus.screens
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import de.schanbro.weekfocus.R
import de.schanbro.weekfocus.settings.SettingsRepository
import de.schanbro.weekfocus.settings.ThemeMode
import de.schanbro.weekfocus.update.ReleaseInfo
import de.schanbro.weekfocus.update.UpdateChecker
import de.schanbro.weekfocus.update.UpdateDialog
import kotlinx.coroutines.launch
private const val REPO_URL = "https://git.schamagusa.de/robin/WeekFocus"
private enum class CheckStatus { IDLE, CHECKING, UP_TO_DATE, FAILED, AVAILABLE }
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(modifier: Modifier = Modifier) {
val context = LocalContext.current
val settings = remember { SettingsRepository.get(context) }
val haptic = LocalHapticFeedback.current
val uriHandler = LocalUriHandler.current
val scope = rememberCoroutineScope()
val currentVersion = remember { UpdateChecker.currentVersion(context) }
var status by remember { mutableStateOf(CheckStatus.IDLE) }
var availableRelease by remember { mutableStateOf<ReleaseInfo?>(null) }
fun checkNow() {
if (status == CheckStatus.CHECKING) return
status = CheckStatus.CHECKING
scope.launch {
val latest = UpdateChecker.fetchLatestRelease(settings.includePrereleases)
status = when {
latest == null -> CheckStatus.FAILED
UpdateChecker.isNewer(latest.version, currentVersion) -> {
availableRelease = latest
CheckStatus.AVAILABLE
}
else -> CheckStatus.UP_TO_DATE
}
}
}
Column(
modifier = modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
) {
// ---------- Updates ----------
SectionTitle(stringResource(R.string.settings_section_updates))
SwitchRow(
title = stringResource(R.string.settings_auto_update_title),
summary = stringResource(R.string.settings_auto_update_summary),
checked = settings.autoCheckUpdates,
onCheckedChange = {
haptic.performHapticFeedback(
if (it) HapticFeedbackType.ToggleOn else HapticFeedbackType.ToggleOff
)
settings.updateAutoCheckUpdates(it)
}
)
SwitchRow(
title = stringResource(R.string.settings_prerelease_title),
summary = stringResource(R.string.settings_prerelease_summary),
checked = settings.includePrereleases,
onCheckedChange = {
haptic.performHapticFeedback(
if (it) HapticFeedbackType.ToggleOn else HapticFeedbackType.ToggleOff
)
settings.updateIncludePrereleases(it)
}
)
ClickRow(
title = stringResource(R.string.settings_check_now_title),
summary = when (status) {
CheckStatus.IDLE -> stringResource(R.string.settings_check_idle, currentVersion)
CheckStatus.CHECKING -> stringResource(R.string.settings_check_checking)
CheckStatus.UP_TO_DATE -> stringResource(R.string.settings_check_up_to_date)
CheckStatus.FAILED -> stringResource(R.string.settings_check_failed)
CheckStatus.AVAILABLE -> stringResource(R.string.settings_check_available)
},
onClick = { checkNow() },
trailing = {
if (status == CheckStatus.CHECKING) {
CircularProgressIndicator(
modifier = Modifier.size(24.dp),
strokeWidth = 3.dp
)
}
}
)
HorizontalDivider(Modifier.padding(vertical = 8.dp))
// ---------- Darstellung ----------
SectionTitle(stringResource(R.string.settings_section_appearance))
ListItem(headlineContent = { Text(stringResource(R.string.settings_theme_title)) })
val modes = listOf(
ThemeMode.SYSTEM to R.string.settings_theme_system,
ThemeMode.LIGHT to R.string.settings_theme_light,
ThemeMode.DARK to R.string.settings_theme_dark
)
SingleChoiceSegmentedButtonRow(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
) {
modes.forEachIndexed { index, (mode, labelRes) ->
SegmentedButton(
selected = settings.themeMode == mode,
onClick = {
if (settings.themeMode != mode) {
haptic.performHapticFeedback(HapticFeedbackType.ToggleOn)
settings.updateThemeMode(mode)
}
},
shape = SegmentedButtonDefaults.itemShape(index, modes.size)
) {
Text(stringResource(labelRes))
}
}
}
// Pro-App-Sprache gibt es erst ab Android 13
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
ClickRow(
title = stringResource(R.string.settings_language_title),
summary = stringResource(R.string.settings_language_summary),
onClick = {
try {
context.startActivity(
Intent(
Settings.ACTION_APP_LOCALE_SETTINGS,
Uri.fromParts("package", context.packageName, null)
)
)
} catch (_: Exception) {
// Gerät ohne diese Einstellungsseite: nichts tun
}
}
)
}
HorizontalDivider(Modifier.padding(vertical = 8.dp))
// ---------- Info ----------
SectionTitle(stringResource(R.string.settings_section_about))
ListItem(
headlineContent = { Text(stringResource(R.string.settings_version_title)) },
supportingContent = { Text(currentVersion) }
)
ClickRow(
title = stringResource(R.string.settings_source_title),
summary = stringResource(R.string.settings_source_summary),
onClick = { uriHandler.openUri(REPO_URL) }
)
Spacer(Modifier.height(16.dp))
}
// Dialog, wenn "Jetzt nach Updates suchen" etwas gefunden hat
availableRelease?.let { info ->
UpdateDialog(info = info, onDismiss = { availableRelease = null })
}
}
@Composable
private fun SectionTitle(text: String) {
Text(
text = text,
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 4.dp)
)
}
@Composable
private fun SwitchRow(
title: String,
summary: String,
checked: Boolean,
onCheckedChange: (Boolean) -> Unit
) {
ListItem(
headlineContent = { Text(title) },
supportingContent = { Text(summary) },
trailingContent = { Switch(checked = checked, onCheckedChange = null) },
// Die ganze Zeile ist klickbar, der Switch selbst nur Anzeige (gut für TalkBack)
modifier = Modifier.toggleable(
value = checked,
role = Role.Switch,
onValueChange = onCheckedChange
)
)
}
@Composable
private fun ClickRow(
title: String,
summary: String,
onClick: () -> Unit,
trailing: (@Composable () -> Unit)? = null
) {
ListItem(
headlineContent = { Text(title) },
supportingContent = { Text(summary) },
trailingContent = trailing,
modifier = Modifier.clickable(onClick = onClick)
)
}
@@ -0,0 +1,54 @@
package de.schanbro.weekfocus.settings
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
enum class ThemeMode { SYSTEM, LIGHT, DARK }
class SettingsRepository private constructor(context: Context) {
private val prefs = context.getSharedPreferences("WeekFocusPrefs", Context.MODE_PRIVATE)
var themeMode by mutableStateOf(
runCatching { ThemeMode.valueOf(prefs.getString(KEY_THEME, "") ?: "") }
.getOrDefault(ThemeMode.SYSTEM)
)
private set
var autoCheckUpdates by mutableStateOf(prefs.getBoolean(KEY_AUTO_UPDATE, true))
private set
var includePrereleases by mutableStateOf(prefs.getBoolean(KEY_PRERELEASE, false))
private set
fun updateThemeMode(mode: ThemeMode) {
themeMode = mode
prefs.edit().putString(KEY_THEME, mode.name).apply()
}
fun updateAutoCheckUpdates(value: Boolean) {
autoCheckUpdates = value
prefs.edit().putBoolean(KEY_AUTO_UPDATE, value).apply()
}
fun updateIncludePrereleases(value: Boolean) {
includePrereleases = value
prefs.edit().putBoolean(KEY_PRERELEASE, value).apply()
}
companion object {
private const val KEY_THEME = "theme_mode"
private const val KEY_AUTO_UPDATE = "auto_check_updates"
private const val KEY_PRERELEASE = "include_prereleases"
@Volatile
private var instance: SettingsRepository? = null
fun get(context: Context): SettingsRepository =
instance ?: synchronized(this) {
instance ?: SettingsRepository(context.applicationContext).also { instance = it }
}
}
}
@@ -6,6 +6,7 @@ import kotlinx.coroutines.withContext
import org.json.JSONObject import org.json.JSONObject
import java.net.HttpURLConnection import java.net.HttpURLConnection
import java.net.URL import java.net.URL
import org.json.JSONArray
data class ReleaseInfo( data class ReleaseInfo(
val version: String, val version: String,
@@ -15,37 +16,53 @@ data class ReleaseInfo(
object UpdateChecker { object UpdateChecker {
private const val LATEST_RELEASE_URL = private const val RELEASES_URL =
"https://git.schamagusa.de/api/v1/repos/robin/WeekFocus/releases/latest" "https://git.schamagusa.de/api/v1/repos/robin/WeekFocus/releases"
/** Liefert das neueste stabile Release oder null (bei Fehler / ohne APK). */ suspend fun fetchLatestRelease(includePrereleases: Boolean = false): ReleaseInfo? =
suspend fun fetchLatestRelease(): ReleaseInfo? = withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
try { try {
val conn = URL(LATEST_RELEASE_URL).openConnection() as HttpURLConnection if (includePrereleases) {
val body = httpGet("$RELEASES_URL?limit=10") ?: return@withContext null
val array = JSONArray(body)
(0 until array.length())
.map { array.getJSONObject(it) }
.firstNotNullOfOrNull { toRelease(it) }
} else {
val body = httpGet("$RELEASES_URL/latest") ?: return@withContext null
toRelease(JSONObject(body))
}
} catch (e: Exception) {
null
}
}
private fun httpGet(url: String): String? {
val conn = URL(url).openConnection() as HttpURLConnection
conn.connectTimeout = 10_000 conn.connectTimeout = 10_000
conn.readTimeout = 10_000 conn.readTimeout = 10_000
conn.setRequestProperty("Accept", "application/json") conn.setRequestProperty("Accept", "application/json")
try { return try {
if (conn.responseCode != HttpURLConnection.HTTP_OK) return@withContext null if (conn.responseCode == HttpURLConnection.HTTP_OK) {
conn.inputStream.bufferedReader().use { it.readText() }
} else null
} finally {
conn.disconnect()
}
}
val json = JSONObject(conn.inputStream.bufferedReader().use { it.readText() }) private fun toRelease(json: JSONObject): ReleaseInfo? {
if (json.optBoolean("draft", false)) return null
val assets = json.getJSONArray("assets") val assets = json.getJSONArray("assets")
val apk = (0 until assets.length()) val apk = (0 until assets.length())
.map { assets.getJSONObject(it) } .map { assets.getJSONObject(it) }
.firstOrNull { it.getString("name").endsWith(".apk", ignoreCase = true) } .firstOrNull { it.getString("name").endsWith(".apk", ignoreCase = true) }
?: return@withContext null ?: return null
return ReleaseInfo(
ReleaseInfo(
version = json.getString("tag_name"), version = json.getString("tag_name"),
notes = json.optString("body", ""), notes = json.optString("body", ""),
apkUrl = apk.getString("browser_download_url") apkUrl = apk.getString("browser_download_url")
) )
} finally {
conn.disconnect()
}
} catch (e: Exception) {
null // Netzwerk- oder Parse-Fehler: still ignorieren
}
} }
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
@@ -12,6 +12,7 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import de.schanbro.weekfocus.R import de.schanbro.weekfocus.R
import de.schanbro.weekfocus.settings.SettingsRepository
import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
@@ -21,21 +22,20 @@ private const val CHECK_INTERVAL_MS = 24L * 60 * 60 * 1000
@Composable @Composable
fun UpdateHandler() { fun UpdateHandler() {
val context = LocalContext.current val context = LocalContext.current
val scope = rememberCoroutineScope() val settings = remember { SettingsRepository.get(context) }
val prefs = remember { val prefs = remember {
context.getSharedPreferences("WeekFocusPrefs", Context.MODE_PRIVATE) context.getSharedPreferences("WeekFocusPrefs", Context.MODE_PRIVATE)
} }
var release by remember { mutableStateOf<ReleaseInfo?>(null) } var release by remember { mutableStateOf<ReleaseInfo?>(null) }
var progress by remember { mutableStateOf<Float?>(null) } // null = kein Download
var downloadJob by remember { mutableStateOf<Job?>(null) }
// Einmal pro Start, höchstens alle 24 Stunden
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
if (!settings.autoCheckUpdates) return@LaunchedEffect
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
if (now - prefs.getLong("last_update_check", 0L) < CHECK_INTERVAL_MS) return@LaunchedEffect if (now - prefs.getLong("last_update_check", 0L) < CHECK_INTERVAL_MS) return@LaunchedEffect
val latest = UpdateChecker.fetchLatestRelease() ?: return@LaunchedEffect val latest = UpdateChecker.fetchLatestRelease(settings.includePrereleases)
?: return@LaunchedEffect
prefs.edit().putLong("last_update_check", now).apply() prefs.edit().putLong("last_update_check", now).apply()
if (UpdateChecker.isNewer(latest.version, UpdateChecker.currentVersion(context))) { if (UpdateChecker.isNewer(latest.version, UpdateChecker.currentVersion(context))) {
@@ -43,11 +43,19 @@ fun UpdateHandler() {
} }
} }
release?.let { info -> release?.let { UpdateDialog(info = it, onDismiss = { release = null }) }
}
@Composable
fun UpdateDialog(info: ReleaseInfo, onDismiss: () -> Unit) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
var progress by remember { mutableStateOf<Float?>(null) } // null = kein Download
var downloadJob by remember { mutableStateOf<Job?>(null) }
val downloading = progress != null val downloading = progress != null
AlertDialog( AlertDialog(
onDismissRequest = { if (!downloading) release = null }, onDismissRequest = { if (!downloading) onDismiss() },
title = { Text(stringResource(R.string.update_title)) }, title = { Text(stringResource(R.string.update_title)) },
text = { text = {
Column(Modifier.verticalScroll(rememberScrollState())) { Column(Modifier.verticalScroll(rememberScrollState())) {
@@ -86,7 +94,7 @@ fun UpdateHandler() {
progress = it progress = it
} }
progress = null progress = null
release = null onDismiss()
ApkInstaller.install(context, apk) ApkInstaller.install(context, apk)
} catch (e: CancellationException) { } catch (e: CancellationException) {
throw e throw e
@@ -106,7 +114,7 @@ fun UpdateHandler() {
onClick = { onClick = {
downloadJob?.cancel() downloadJob?.cancel()
progress = null progress = null
release = null onDismiss()
} }
) { ) {
Text( Text(
@@ -118,4 +126,3 @@ fun UpdateHandler() {
} }
) )
} }
}
+25
View File
@@ -28,4 +28,29 @@
<string name="permission_network_message">WeekFocus needs network access to check for updates. Without it the app keeps working, but won’t look for new versions.</string> <string name="permission_network_message">WeekFocus needs network access to check for updates. Without it the app keeps working, but won’t look for new versions.</string>
<string name="permission_allow">Allow</string> <string name="permission_allow">Allow</string>
<string name="permission_not_now">Not now</string> <string name="permission_not_now">Not now</string>
<string name="settings_section_updates">Updates</string>
<string name="settings_auto_update_title">Check for updates automatically</string>
<string name="settings_auto_update_summary">On app start, at most once a day</string>
<string name="settings_prerelease_title">Include beta versions</string>
<string name="settings_prerelease_summary">Also offer pre-releases. These may contain bugs.</string>
<string name="settings_check_now_title">Check for updates now</string>
<string name="settings_check_idle">Installed version: %1$s</string>
<string name="settings_check_checking">Checking …</string>
<string name="settings_check_up_to_date">The app is up to date</string>
<string name="settings_check_failed">Check failed. Please check your network connection.</string>
<string name="settings_check_available">Update available</string>
<string name="settings_section_appearance">Appearance</string>
<string name="settings_theme_title">Theme</string>
<string name="settings_theme_system">System</string>
<string name="settings_theme_light">Light</string>
<string name="settings_theme_dark">Dark</string>
<string name="settings_language_title">Language</string>
<string name="settings_language_summary">Change in system settings</string>
<string name="settings_section_about">About</string>
<string name="settings_version_title">Version</string>
<string name="settings_source_title">Source code</string>
<string name="settings_source_summary">Open repository on Gitea</string>
</resources> </resources>
+26
View File
@@ -33,4 +33,30 @@
<string name="permission_network_message">WeekFocus braucht Netzwerkzugriff, um nach Updates zu suchen. Ohne Zugriff funktioniert die App weiterhin, sucht aber nicht nach neuen Versionen.</string> <string name="permission_network_message">WeekFocus braucht Netzwerkzugriff, um nach Updates zu suchen. Ohne Zugriff funktioniert die App weiterhin, sucht aber nicht nach neuen Versionen.</string>
<string name="permission_allow">Erlauben</string> <string name="permission_allow">Erlauben</string>
<string name="permission_not_now">Nicht jetzt</string> <string name="permission_not_now">Nicht jetzt</string>
<!-- Einstellungen -->
<string name="settings_section_updates">Updates</string>
<string name="settings_auto_update_title">Automatisch nach Updates suchen</string>
<string name="settings_auto_update_summary">Beim Start der App, höchstens einmal täglich</string>
<string name="settings_prerelease_title">Beta-Versionen einbeziehen</string>
<string name="settings_prerelease_summary">Auch Vorabversionen anbieten. Diese können Fehler enthalten.</string>
<string name="settings_check_now_title">Jetzt nach Updates suchen</string>
<string name="settings_check_idle">Installierte Version: %1$s</string>
<string name="settings_check_checking">Suche läuft …</string>
<string name="settings_check_up_to_date">Die App ist auf dem neuesten Stand</string>
<string name="settings_check_failed">Suche fehlgeschlagen. Bitte Netzwerkverbindung prüfen.</string>
<string name="settings_check_available">Update verfügbar</string>
<string name="settings_section_appearance">Darstellung</string>
<string name="settings_theme_title">Design</string>
<string name="settings_theme_system">System</string>
<string name="settings_theme_light">Hell</string>
<string name="settings_theme_dark">Dunkel</string>
<string name="settings_language_title">Sprache</string>
<string name="settings_language_summary">In den Systemeinstellungen ändern</string>
<string name="settings_section_about">Über die App</string>
<string name="settings_version_title">Version</string>
<string name="settings_source_title">Quellcode</string>
<string name="settings_source_summary">Repository auf Gitea öffnen</string>
</resources> </resources>