Compare commits

...
50 Commits
Author SHA1 Message Date
robin c87f51017f CHANGELOG update
Build & Release Android App / build (push) Successful in 11m32s
2026-10-30 20:25:23 +01:00
robin a876465894 Merge pull request 'Feat/home screen' (#45) from feat/home-screen into main
Build & Release Android App / build (push) Canceled after 16s
Reviewed-on: #45
2026-10-30 19:23:47 +00:00
robin 761ee25642 refactor: use functions from WordOfWeek.kt in SimpleWidget.kt 2026-10-30 20:23:20 +01:00
robin c56ff94a47 feat: add home screen
refactor: change navigation method
2026-10-30 20:06:03 +01:00
robin 792047eae4 README.md aktualisiert 2026-10-30 18:00:29 +00:00
robin 78fd859889 CHANGELOG update
Build & Release Android App / build (push) Successful in 17m52s
2026-10-30 18:52:26 +01:00
robin b93d23f31c feat: beta may take release notes from stable 2026-10-30 18:51:37 +01:00
robin 648da0fb37 Merge pull request 'feat: show changelog after update' (#41) from feat/changelog-after-update into main
Build & Release Android App / build (push) Successful in 11m15s
Reviewed-on: robin/WeekFocus#41
2026-10-30 17:34:31 +00:00
robin d8bb6f1671 feat: show changelog after update 2026-10-30 18:34:08 +01:00
robin 168c3eeedc README.md aktualisiert 2026-10-30 13:32:15 +00:00
robin 1f0f556e82 Merge pull request 'Feat/about screen' (#40) from feat/about-screen into main
Build & Release Android App / build (push) Successful in 9m30s
Reviewed-on: robin/WeekFocus#40
2026-10-30 13:25:02 +00:00
robin 2a4b5f54a8 CHANGELOG update 2026-10-30 14:24:38 +01:00
robin 31a1f5158f feat: about screen 2026-10-30 14:24:03 +01:00
robin 3aedc51b97 Merge pull request 'Feat/settings' (#39) from feat/settings into main
Build & Release Android App / build (push) Successful in 11m1s
Reviewed-on: robin/WeekFocus#39
2026-10-30 12:35:53 +00:00
robin 8e88e9601a CHANGELOG update 2026-10-30 13:35:25 +01:00
robin 8f65bb05b7 feat: settings 2026-10-30 13:34:34 +01:00
robin 6be81093e0 fix CHANGELOG typo 2026-10-30 13:18:07 +01:00
robin 1b90010bbc README.md aktualisiert 2026-10-30 12:06:00 +00:00
robin ade61c0850 README.md aktualisiert 2026-10-30 12:04:13 +00:00
robin e97498a148 CHANGELOG update
Build & Release Android App / build (push) Successful in 12m17s
2026-10-30 12:57:30 +01:00
robin 584ec246d1 Merge pull request 'Feat/auto update' (#36) from feat/auto-update into main
Reviewed-on: robin/WeekFocus#36
2026-10-30 11:56:19 +00:00
robin 200b834d1c Merge branch 'main' into feat/auto-update 2026-10-30 11:56:09 +00:00
robin 0fcc9ba514 refactor: move update code to folder update 2026-10-30 12:55:37 +01:00
robin 8d38c319a2 feat: ask for network permission before checking for updates 2026-10-30 12:50:15 +01:00
robin 90ce637846 feat: auto update 2026-10-30 12:42:29 +01:00
robin f77080f6f2 CHANGELOG update 2026-10-30 12:33:22 +01:00
robin f161db3345 Merge pull request 'fix: show app icon' (#35) from fix/splashscreen-light into main
Reviewed-on: robin/WeekFocus#35
2026-10-30 11:26:47 +00:00
robin 32ae274da3 fix: show app icon 2026-10-30 12:26:14 +01:00
robin 431f61e683 CHANGELOG update
Build & Release Android App / build (push) Successful in 14m33s
2026-10-29 18:11:33 +01:00
robin 2cadfa8972 Merge pull request 'style: dark mode support on splash screen' (#33) from style/splash-screen into main
Reviewed-on: robin/WeekFocus#33
2026-10-29 17:10:17 +00:00
robin 77bcaddc55 style: dark mode support on splash screen 2026-10-29 18:09:55 +01:00
robin a2d049e280 Merge pull request 'chore(l10n): add translations' (#31) from chore(l10n)/translation into main
Build & Release Android App / build (push) Successful in 8m24s
Reviewed-on: robin/WeekFocus#31
2026-10-29 16:41:08 +00:00
robin a393624d03 chore(l10n): add translations 2026-10-29 17:40:35 +01:00
robin 27d1a4b6ea Merge pull request 'Feat/edit words' (#30) from feat/edit-words into main
Build & Release Android App / build (push) Successful in 20m22s
Reviewed-on: robin/WeekFocus#30
2026-10-29 16:23:20 +00:00
robin 5ae35c4cac CHANGELOG update 2026-10-29 17:22:42 +01:00
robin 75c4a43d57 feat: ability to edit words 2026-10-29 17:19:15 +01:00
robin 0c75afab4e CHANGELOG update
Build & Release Android App / build (push) Successful in 16m15s
2026-10-08 15:20:25 +02:00
robin 0c2ec3f20c chore: add proguard-rules.pro
Build & Release Android App / build (push) Successful in 18m51s
2026-10-08 14:55:36 +02:00
robin daf16f0e67 chore: adjust workflow
Build & Release Android App / build (push) Failing after 18m42s
2026-10-08 14:35:15 +02:00
robin 8ccd4430da Merge pull request 'refactor: implement better choosing of the word' (#23) from test/widget-automation into main
Build & Release Android App / build (push) Failing after 54s
Reviewed-on: #23
2026-10-08 11:45:25 +00:00
robin 98ffa47fa4 Merge branch 'main' into test/widget-automation 2026-10-08 11:45:17 +00:00
robin dfd0b75521 Merge pull request 'Chore/reduce apk size' (#29) from chore/reduce-apk-size into main
Reviewed-on: #29
2026-10-07 14:50:17 +00:00
robin d9c1942f2a Merge branch 'main' into chore/reduce-apk-size 2026-10-07 14:50:08 +00:00
robin bc6edc4a04 chore: adjust workflow 2026-10-07 16:49:40 +02:00
robin d03f9eee67 chore: enable R8 (Code-Shrinking) 2026-10-07 16:48:13 +02:00
robin 7eff7300d0 chore: disable abi (apk-split) 2026-10-07 16:45:22 +02:00
robin 8458f0fce5 Merge pull request 'Chore/smaller apk' (#28) from chore/smaller-apk into main
Build & Release Android App / build (push) Successful in 19m5s
Reviewed-on: #28
2026-10-07 14:08:54 +00:00
robin e444abecae Merge branch 'main' into chore/smaller-apk 2026-10-07 14:08:43 +00:00
robin 107f1c3955 Merge pull request 'chore: fix workflow 2' (#26) from chore/smaller-apk into main
Build & Release Android App / build (push) Failing after 1m16s
Reviewed-on: #26
2026-10-07 13:57:30 +00:00
robin 7cc3245b97 refactor: implement better choosing of the word 2026-10-06 17:06:13 +02:00
30 changed files with 2049 additions and 227 deletions

No files matched your search

+59 -55
View File
@@ -64,7 +64,52 @@ jobs:
echo "$KEYSTORE_BASE64" | base64 -d > "$RUNNER_TEMP/release.keystore"
echo "KEYSTORE_PATH=$RUNNER_TEMP/release.keystore" >> $GITHUB_ENV
- name: Android Release APKs bauen
- name: Release-Notes aus CHANGELOG.md extrahieren
run: |
VERSION="${GITHUB_REF_NAME#v}"
NOTES_FILE="$RUNNER_TEMP/release_notes.md"
extract_notes() {
awk -v ver="$1" '
/^##[[:space:]]/ {
if (found) exit
line = $0
sub(/^##[[:space:]]+/, "", line)
sub(/^\[?v?/, "", line)
if (substr(line, 1, length(ver)) == ver) {
rest = substr(line, length(ver) + 1)
if (rest ~ /^([^0-9.]|$)/) { found = 1 }
}
next
}
found { print }
' CHANGELOG.md
}
if [ -f CHANGELOG.md ]; then
extract_notes "$VERSION" > "$NOTES_FILE"
# Kein eigener Eintrag für die Beta? Dann den der Basisversion nehmen.
BASE="${VERSION%%-*}"
if ! grep -q '[^[:space:]]' "$NOTES_FILE" && [ "$BASE" != "$VERSION" ]; then
extract_notes "$BASE" > "$NOTES_FILE"
fi
else
: > "$NOTES_FILE"
fi
# In die APK einbetten, aber nur, wenn es echte Notes gibt
mkdir -p app/src/main/assets
if grep -q '[^[:space:]]' "$NOTES_FILE"; then
cp "$NOTES_FILE" app/src/main/assets/release_notes.md
else
echo "Keine Release-Notes für Version $VERSION vorhanden." > "$NOTES_FILE"
fi
echo "Release-Notes:"
cat "$NOTES_FILE"
- name: Android Release APK bauen
run: |
set -euo pipefail
@@ -79,70 +124,29 @@ jobs:
APK_DIR="app/build/outputs/apk/release"
echo "Gefundene Original-APKs in $APK_DIR:"
echo "Gefundene APKs in $APK_DIR:"
ls -lh "$APK_DIR"
for APK in "$APK_DIR"/*.apk; do
[ -e "$APK" ] || continue
SRC="$APK_DIR/app-release.apk"
if [ ! -f "$SRC" ]; then
echo "app-release.apk nicht gefunden (evtl. unsigniert oder anderer Name)"
exit 1
fi
if [[ "$APK" == *"unsigned"* || "$APK" == *"WeekFocus-"* ]]; then
continue
fi
TARGET_PATH="$APK_DIR/WeekFocus-${VERSION}.apk"
mv "$SRC" "$TARGET_PATH"
FILENAME=$(basename "$APK")
VARIANT=$(echo "$FILENAME" | sed -E 's/^app-(.*)-release\.apk$/\1/')
if [ "$VARIANT" = "$FILENAME" ]; then
VARIANT="release"
fi
echo "Signatur prüfen für $(basename "$TARGET_PATH")..."
"$ANDROID_HOME/build-tools/35.0.0/apksigner" verify --verbose "$TARGET_PATH"
TARGET_NAME="WeekFocus-${VERSION}-${VARIANT}.apk"
TARGET_PATH="$APK_DIR/$TARGET_NAME"
mv "$APK" "$TARGET_PATH"
echo "Signatur prüfen für $TARGET_NAME..."
"$ANDROID_HOME/build-tools/35.0.0/apksigner" verify --verbose "$TARGET_PATH"
done
echo "Finale Release-APKs:"
ls -lh "$APK_DIR"/WeekFocus-*.apk
echo "Finale Release-APK:"
ls -lh "$TARGET_PATH"
env:
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}
- name: Release-Notes aus CHANGELOG.md extrahieren
run: |
VERSION="${GITHUB_REF_NAME#v}"
NOTES_FILE="$RUNNER_TEMP/release_notes.md"
if [ -f CHANGELOG.md ]; then
awk -v ver="$VERSION" '
/^##[[:space:]]/ {
if (found) exit
line = $0
sub(/^##[[:space:]]+/, "", line)
sub(/^\[?v?/, "", line)
if (substr(line, 1, length(ver)) == ver) {
rest = substr(line, length(ver) + 1)
if (rest ~ /^([^0-9.]|$)/) { found = 1 }
}
next
}
found { print }
' CHANGELOG.md > "$NOTES_FILE"
else
: > "$NOTES_FILE"
fi
if ! grep -q '[^[:space:]]' "$NOTES_FILE"; then
echo "Keine Release-Notes für Version $VERSION vorhanden." > "$NOTES_FILE"
fi
echo "Release-Notes:"
cat "$NOTES_FILE"
- name: Release in Gitea erstellen und APKs hochladen
- name: Release in Gitea erstellen und APK hochladen
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
+1
View File
@@ -15,3 +15,4 @@
.externalNativeBuild
.cxx
local.properties
app/src/main/assets/release_notes.md
+1 -1
View File
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" project-jdk-name="17" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
+39 -1
View File
@@ -1,5 +1,43 @@
# Changelog
## [1.4.4] - 2026-10-30
### New
* home screen
## [1.4.2] - 2026-10-30
### New
* show changelog after update
## [1.4.1] - 2026-10-30
### New
* about screen
## [1.4.0] - 2026-10-30
### New
* settings
## [1.3.0] - 2026-10-30
### New
* auto update
### Fixed
* show app icon on splash screen
## [1.2.12] - 2026-10-29
### New
* dark mode support on the splash screen
## [1.2.11] - 2026-10-29
### New
* ability to edit words (with swiping to the left)
### Changed
* delete words with swiping to the right (instead of pressing the button)
## [1.2.10] - 2026-10-08
### Changed
* implemented a better choosing of the focus word.
* reduced apk file size from 44MB to 2.2MB
## [1.2.0] - 2026-10-04
### New
* navigation
@@ -8,7 +46,7 @@
## [1.1.3] - 2026-10-03
### Changed
- chore: refactor: switch from release github action to bash
- chore: refactor: switch from release GitHub Action to bash
## [1.1.1] - 2026-10-03
### Changed
+11 -10
View File
@@ -7,7 +7,7 @@
**One word. One week. One quality to grow.**
<a href="https://apps.obtainium.imranr.dev/redirect?r=obtainium://app/%7B%22id%22%3A%22de.schanbro.weekfocus%22%2C%22url%22%3A%22https%3A%2F%2Fgit.schamagusa.de%2FSchanbro%2FWeekFocus%22%2C%22author%22%3A%22Schanbro%22%2C%22name%22%3A%22WeekFocus%22%2C%22overrideSource%22%3A%22Codeberg%22%7D">
<a href="https://apps.obtainium.imranr.dev/redirect?r=obtainium://app/%7B%22id%22%3A%22de.schanbro.weekfocus%22%2C%22url%22%3A%22https%3A%2F%2Fgit.schamagusa.de%Schanbro%2FWeekFocus%22%2C%22author%22%3A%Schanbro%22%2C%22name%22%3A%22WeekFocus%22%2C%22overrideSource%22%3A%22Codeberg%22%7D">
<img src="https://raw.githubusercontent.com/ImranR98/Obtainium/main/assets/graphics/badge_obtainium.png" alt="Get it on Obtainium" height="64">
</a>
@@ -58,11 +58,11 @@ No streaks, no pressure, no clutter. Just a gentle daily reminder of what you wa
## Features
- 🧩 Home screen widget showing your current quality of the week
- 🔄 Automatic weekly rotation to a new quality
- 🌙 Light and dark theme support
- 🔒 No ads, no tracking, no unnecessary permissions
- ⚡ Lightweight and battery-friendly
- Home screen widget showing your current quality of the week
- Automatic weekly rotation to a new quality
- Light and dark theme support, Material You
- No ads, no tracking, no unnecessary permissions
- Lightweight and battery-friendly
## Installation
@@ -124,7 +124,7 @@ You can follow the build under **Actions** in the repository. When it finishes,
The workflow takes the notes from the section of `CHANGELOG.md` whose heading starts with the version number:
```markdown
## 1.1.3
## [1.1.3] - 2026-10-03
- Added Weblate translations
- Fixed widget update at the start of a new week
@@ -152,7 +152,8 @@ You are free to use, modify and redistribute this software under the terms of th
## Translations
WeekFocus is translated via [Weblate](https://weblate.schamagusa.de/engage/weekfocus/).
Help translate the app into your language!
~~WeekFocus is translated via [Weblate](https://weblate.schamagusa.de/engage/weekfocus/).
Help translate the app into your language!~~
<!--[![Translation status](https://weblate.schamagusa.de/widgets/weekfocus/-/multi-auto.svg)](https://weblate.schamagusa.de/engage/weekfocus/)-->
[![Translation status](https://weblate.schamagusa.de/widgets/weekfocus/-/multi-auto.svg)](https://weblate.schamagusa.de/engage/weekfocus/)
If you want to contribute with translation you would have to fork this repository, translate into the files directly and make an pull request back to this repository.
+13 -3
View File
@@ -27,14 +27,15 @@ android {
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
splits {
// not necessary
/*splits {
abi {
isEnable = true
reset()
include("arm64-v8a", "armeabi-v7a", "x86", "x86_64")
isUniversalApk = true
}
}
}*/
signingConfigs {
create("release") {
@@ -56,8 +57,13 @@ android {
release {
signingConfig = signingConfigs.getByName("release")
optimization {
enable = false
enable = true
}
isShrinkResources = true
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
@@ -72,6 +78,7 @@ android {
dependencies {
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.activity.compose)
implementation(libs.androidx.compose.animation)
implementation(libs.androidx.compose.material3)
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.ui.graphics)
@@ -86,4 +93,7 @@ dependencies {
debugImplementation(libs.androidx.compose.ui.test.manifest)
debugImplementation(libs.androidx.compose.ui.tooling)
implementation(libs.androidx.material.icons.extended)
implementation("androidx.core:core-splashscreen:1.0.1")
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.7")
implementation("androidx.navigation:navigation-compose:2.8.5")
}
+6
View File
@@ -0,0 +1,6 @@
# Project-specific R8/ProGuard rules for WeekFocus.
# Default Android and Compose rules are applied automatically via consumer rules.
# Keep line numbers for readable stack traces
-keepattributes SourceFile,LineNumberTable
-renamesourcefileattribute SourceFile
+22 -3
View File
@@ -1,6 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
<!-- Nötig, damit der Wochenwechsel-Alarm nach einem Neustart neu geplant wird -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!-- used for auto-update -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<application
android:allowBackup="true"
@@ -15,7 +21,7 @@
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.WeekFocus"
android:theme="@style/Theme.WeekFocus.Splash"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
@@ -28,11 +34,24 @@
android:exported="true">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.DATE_CHANGED" />
<action android:name="android.intent.action.TIME_SET" />
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/widget_info" />
</receiver>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
</manifest>
@@ -1,63 +1,151 @@
package de.schanbro.weekfocus
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.List
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.outlined.Home
import androidx.compose.material.icons.outlined.List
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import de.schanbro.weekfocus.ui.theme.WeekFocusTheme
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import de.schanbro.weekfocus.screens.AboutScreen
import de.schanbro.weekfocus.screens.HomeScreen
import de.schanbro.weekfocus.screens.SettingsScreen
import de.schanbro.weekfocus.screens.WordListScreen
import de.schanbro.weekfocus.settings.SettingsRepository
import de.schanbro.weekfocus.settings.ThemeMode
import de.schanbro.weekfocus.ui.theme.WeekFocusTheme
import de.schanbro.weekfocus.update.NetworkPermissionGate
import de.schanbro.weekfocus.update.UpdateHandler
import de.schanbro.weekfocus.update.WhatsNewHandler
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.automirrored.filled.List
import androidx.compose.material.icons.automirrored.outlined.List
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LargeTopAppBar
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.ui.input.nestedscroll.nestedScroll
private object Routes {
const val HOME = "home"
const val WORDS = "words"
const val SETTINGS = "settings"
const val ABOUT = "about"
}
private data class Tab(
val route: String,
val labelRes: Int,
val iconSelected: ImageVector,
val iconUnselected: ImageVector
)
private val tabs = listOf(
Tab(Routes.HOME, R.string.title_home, Icons.Filled.Home, Icons.Outlined.Home),
Tab(
Routes.WORDS, R.string.title_words,
Icons.AutoMirrored.Filled.List, Icons.AutoMirrored.Outlined.List
),
Tab(Routes.SETTINGS, R.string.title_settings, Icons.Filled.Settings, Icons.Outlined.Settings)
)
/** Titel im Header je Route. Hier bei Bedarf anpassen. */
private fun titleFor(route: String?): Int = when (route) {
Routes.HOME -> R.string.title_weekly_focus
Routes.WORDS -> R.string.title_words
Routes.SETTINGS -> R.string.title_settings
Routes.ABOUT -> R.string.title_about
else -> R.string.app_name
}
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen()
super.onCreate(savedInstanceState)
enableEdgeToEdge()
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()
WhatsNewHandler()
NetworkPermissionGate {
UpdateHandler()
}
}
}
}
override fun onResume() {
super.onResume()
updateWidget(this)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainScreen() {
var selectedTab by remember { mutableIntStateOf(0) }
val navController = rememberNavController()
val backStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = backStackEntry?.destination?.route
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
fun navigateToTab(route: String) {
navController.navigate(route) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
}
Scaffold(
modifier = Modifier
.fillMaxSize()
.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
LargeTopAppBar(
title = {
Text(
when (selectedTab) {
0 -> stringResource(R.string.title_home)
1 -> stringResource(R.string.title_words)
2 -> stringResource(R.string.title_settings)
else -> stringResource(R.string.app_name)
title = { Text(stringResource(titleFor(currentRoute))) },
navigationIcon = {
if (currentRoute == Routes.ABOUT) {
IconButton(onClick = { navController.popBackStack() }) {
Icon(
Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(R.string.action_back)
)
}
)
}
},
scrollBehavior = scrollBehavior,
colors = TopAppBarDefaults.largeTopAppBarColors(
@@ -67,78 +155,43 @@ fun MainScreen() {
)
},
bottomBar = {
NavigationBar {
NavigationBarItem(
selected = selectedTab == 0,
onClick = { selectedTab = 0 },
icon = {
Icon(
imageVector = if (selectedTab == 0) Icons.Filled.Home else Icons.Outlined.Home,
contentDescription = stringResource(R.string.title_home)
if (tabs.any { it.route == currentRoute }) {
NavigationBar {
tabs.forEach { tab ->
val selected = currentRoute == tab.route
NavigationBarItem(
selected = selected,
onClick = { navigateToTab(tab.route) },
icon = {
Icon(
imageVector = if (selected) tab.iconSelected else tab.iconUnselected,
contentDescription = null
)
},
label = { Text(stringResource(tab.labelRes)) }
)
},
label = { Text(stringResource(R.string.title_home)) }
)
NavigationBarItem(
selected = selectedTab == 1,
onClick = { selectedTab = 1 },
icon = {
Icon(
imageVector = if (selectedTab == 1) Icons.Filled.List else Icons.Outlined.List,
contentDescription = stringResource(R.string.title_words)
)
},
label = { Text(stringResource(R.string.title_words)) }
)
NavigationBarItem(
selected = selectedTab == 2,
onClick = { selectedTab = 2 },
icon = {
Icon(
imageVector = if (selectedTab == 2) Icons.Filled.Settings else Icons.Outlined.Settings,
contentDescription = stringResource(R.string.title_settings)
)
},
label = { Text(stringResource(R.string.title_settings)) }
)
}
}
}
}
) { innerPadding ->
Surface(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding),
color = MaterialTheme.colorScheme.background
) { padding ->
NavHost(
navController = navController,
startDestination = Routes.HOME,
modifier = Modifier.padding(padding)
) {
when (selectedTab) {
0 -> PlaceholderScreen(title = stringResource(R.string.title_weekly_focus))
1 -> WordListScreen()
2 -> PlaceholderScreen(title = stringResource(R.string.title_settings))
composable(Routes.HOME) {
HomeScreen(onOpenWords = { navigateToTab(Routes.WORDS) })
}
composable(Routes.WORDS) { WordListScreen() }
composable(Routes.SETTINGS) {
SettingsScreen(onOpenAbout = { navController.navigate(Routes.ABOUT) })
}
composable(Routes.ABOUT) { AboutScreen() }
}
}
}
@Composable
fun PlaceholderScreen(title: String) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
text = title,
style = MaterialTheme.typography.headlineMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
fun updateWidget(context: Context) {
val appWidgetManager = AppWidgetManager.getInstance(context)
val componentName = ComponentName(context, SimpleWidget::class.java)
val appWidgetIds = appWidgetManager.getAppWidgetIds(componentName)
for (appWidgetId in appWidgetIds) {
SimpleWidget.updateAppWidget(context, appWidgetManager, appWidgetId)
}
}
SimpleWidget.updateAllWidgets(context)
}
@@ -1,15 +1,32 @@
package de.schanbro.weekfocus
import android.app.AlarmManager
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.widget.RemoteViews
import androidx.compose.ui.res.stringResource
import java.util.Calendar
import java.util.Random
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.ZoneId
import java.time.temporal.TemporalAdjusters
class SimpleWidget : AppWidgetProvider() {
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)
when (intent.action) {
ACTION_WEEK_CHANGED,
Intent.ACTION_BOOT_COMPLETED,
Intent.ACTION_DATE_CHANGED,
Intent.ACTION_TIME_CHANGED,
Intent.ACTION_TIMEZONE_CHANGED -> updateAllWidgets(context)
}
}
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
@@ -18,40 +35,124 @@ class SimpleWidget : AppWidgetProvider() {
for (appWidgetId in appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId)
}
scheduleNextWeekChange(context)
}
override fun onEnabled(context: Context) {
scheduleNextWeekChange(context)
}
override fun onDisabled(context: Context) {
cancelWeekChange(context)
}
companion object {
const val ACTION_WEEK_CHANGED = "de.schanbro.weekfocus.ACTION_WEEK_CHANGED"
private const val PREFS_NAME = "WeekFocusPrefs"
private const val KEY_WEEK = "current_week_key"
private const val KEY_WORD = "current_word"
/**
* Aktualisiert alle Widget-Instanzen und plant den nächsten Wochenwechsel.
*/
fun updateAllWidgets(context: Context) {
val appWidgetManager = AppWidgetManager.getInstance(context)
val componentName = ComponentName(context, SimpleWidget::class.java)
val appWidgetIds = appWidgetManager.getAppWidgetIds(componentName)
if (appWidgetIds.isEmpty()) return
for (appWidgetId in appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId)
}
scheduleNextWeekChange(context)
}
fun updateAppWidget(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetId: Int
) {
// 1. SharedPreferences auslesen
val sharedPrefs = context.getSharedPreferences("WeekFocusPrefs", Context.MODE_PRIVATE)
val savedSet = sharedPrefs.getStringSet("words_key", emptySet()) ?: emptySet()
val wordList = savedSet.toList()
val displayText = resolveWordOfWeek(context)
?: context.getString(R.string.msg_no_words)
// 2. Aktuelle Kalenderwoche & Jahr bestimmen
val calendar = Calendar.getInstance()
val weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR)
val year = calendar.get(Calendar.YEAR)
// 3. Wort für die aktuelle Kalenderwoche auswählen
val displayText = if (wordList.isNotEmpty()) {
// Kombinierter Seed aus Jahr und Kalenderwoche
val seed = (year * 100 + weekOfYear).toLong()
val random = Random(seed)
val randomIndex = random.nextInt(wordList.size)
wordList[randomIndex]
} else {
context.getString(R.string.msg_no_words)
}
// 4. RemoteViews aktualisieren
val views = RemoteViews(context.packageName, R.layout.widget_main)
views.setTextViewText(R.id.appwidget_text, displayText)
appWidgetManager.updateAppWidget(appWidgetId, views)
}
/**
* Holt das Wort für die aktuelle Woche unter Verwendung von WordOfWeek
* und speichert es persistent ab, solange sich die Woche nicht ändert.
*/
private fun resolveWordOfWeek(context: Context): String? {
// Wörter sortiert laden, damit die Reihenfolge deterministisch bleibt
val words = WordOfWeek.loadWords(context).sorted()
if (words.isEmpty()) {
context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
.edit().remove(KEY_WEEK).remove(KEY_WORD).apply()
return null
}
val currentWeek = WordOfWeek.weekOf(0)
val weekKey = currentWeek.weekYear * 100 + currentWeek.weekNumber
val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
val storedWord = prefs.getString(KEY_WORD, null)
// Wenn die gespeicherte Woche passt und das gespeicherte Wort noch in der Liste existiert: behalten
if (prefs.getInt(KEY_WEEK, -1) == weekKey && storedWord != null && storedWord in words) {
return storedWord
}
// Ansonsten neu über WordOfWeek bestimmen
val newWord = WordOfWeek.wordFor(words, currentWeek) ?: return null
// Speichern für den Rest der Woche
prefs.edit()
.putInt(KEY_WEEK, weekKey)
.putString(KEY_WORD, newWord)
.apply()
return newWord
}
/**
* Plant einen Alarm für den nächsten Montag, 00:00 Uhr (lokale Zeit).
*/
private fun scheduleNextWeekChange(context: Context) {
val alarmManager = context.getSystemService(AlarmManager::class.java) ?: return
val triggerAtMillis = LocalDate.now()
.with(TemporalAdjusters.next(DayOfWeek.MONDAY))
.atStartOfDay(ZoneId.systemDefault())
.toInstant()
.toEpochMilli()
alarmManager.setAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
triggerAtMillis,
weekChangePendingIntent(context)
)
}
private fun cancelWeekChange(context: Context) {
val alarmManager = context.getSystemService(AlarmManager::class.java) ?: return
alarmManager.cancel(weekChangePendingIntent(context))
}
private fun weekChangePendingIntent(context: Context): PendingIntent {
val intent = Intent(context, SimpleWidget::class.java).apply {
action = ACTION_WEEK_CHANGED
}
return PendingIntent.getBroadcast(
context,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
}
}
}
@@ -0,0 +1,32 @@
package de.schanbro.weekfocus
import android.content.Context
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.temporal.IsoFields
import java.util.Random
data class WeekInfo(val monday: LocalDate) {
val sunday: LocalDate get() = monday.plusDays(6)
val weekNumber: Int get() = monday.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR)
val weekYear: Int get() = monday.get(IsoFields.WEEK_BASED_YEAR)
}
object WordOfWeek {
fun loadWords(context: Context): List<String> =
context.getSharedPreferences("WeekFocusPrefs", Context.MODE_PRIVATE)
.getStringSet("words_key", emptySet())
?.toList()
.orEmpty()
/** offset 0 = diese Woche, -1 = letzte, 1 = nächste ... */
fun weekOf(offset: Int = 0, today: LocalDate = LocalDate.now()): WeekInfo =
WeekInfo(today.with(DayOfWeek.MONDAY).plusWeeks(offset.toLong()))
fun wordFor(words: List<String>, week: WeekInfo): String? {
if (words.isEmpty()) return null
val seed = (week.weekYear * 100 + week.weekNumber).toLong()
return words[Random(seed).nextInt(words.size)]
}
}
@@ -0,0 +1,58 @@
package de.schanbro.weekfocus.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.selection.toggleable
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
@Composable
internal 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
internal 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
internal 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,111 @@
package de.schanbro.weekfocus.screens
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import de.schanbro.weekfocus.R
import de.schanbro.weekfocus.components.ClickRow
import de.schanbro.weekfocus.components.SectionTitle
import de.schanbro.weekfocus.update.ReleaseNotes
import de.schanbro.weekfocus.update.UpdateChecker
import de.schanbro.weekfocus.update.WhatsNewDialog
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
private const val REPO_URL = "https://git.schamagusa.de/robin/WeekFocus"
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AboutScreen(
modifier: Modifier = Modifier
) {
val context = LocalContext.current
val uriHandler = LocalUriHandler.current
val version = remember { UpdateChecker.currentVersion(context) }
Column(modifier = modifier.fillMaxSize()) {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 24.dp, vertical = 32.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = stringResource(R.string.app_name),
style = MaterialTheme.typography.headlineMedium
)
Spacer(Modifier.height(4.dp))
Text(
text = stringResource(R.string.about_version, version),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(Modifier.height(16.dp))
Text(
text = stringResource(R.string.about_description),
style = MaterialTheme.typography.bodyLarge,
textAlign = TextAlign.Center
)
}
HorizontalDivider()
SectionTitle(stringResource(R.string.about_section_links))
ClickRow(
title = stringResource(R.string.settings_source_title),
summary = stringResource(R.string.settings_source_summary),
onClick = { uriHandler.openUri(REPO_URL) }
)
ClickRow(
title = stringResource(R.string.about_issues_title),
summary = stringResource(R.string.about_issues_summary),
onClick = { uriHandler.openUri("$REPO_URL/issues") }
)
ClickRow(
title = stringResource(R.string.about_releases_title),
summary = stringResource(R.string.about_releases_summary),
onClick = { uriHandler.openUri("$REPO_URL/releases") }
)
HorizontalDivider()
SectionTitle(stringResource(R.string.about_whats_new_section_title))
var showNotes by remember { mutableStateOf(false) }
val notes = remember { ReleaseNotes.load(context) }
if (notes != null) {
ClickRow(
title = stringResource(R.string.about_whats_new_title),
summary = stringResource(R.string.about_whats_new_summary),
onClick = { showNotes = true }
)
}
if (showNotes && notes != null) {
WhatsNewDialog(version = version, notes = notes, onDismiss = { showNotes = false })
}
Spacer(Modifier.height(16.dp))
}
}
}
@@ -0,0 +1,328 @@
package de.schanbro.weekfocus.screens
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import android.text.format.DateUtils
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowLeft
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import de.schanbro.weekfocus.R
import de.schanbro.weekfocus.SimpleWidget
import de.schanbro.weekfocus.WeekInfo
import de.schanbro.weekfocus.WordOfWeek
import java.time.LocalDate
import java.time.ZoneId
@Composable
fun HomeScreen(
onOpenWords: () -> Unit,
modifier: Modifier = Modifier
) {
val context = LocalContext.current
val haptic = LocalHapticFeedback.current
var words by remember { mutableStateOf(WordOfWeek.loadWords(context)) }
var widgetPlaced by remember { mutableStateOf(true) } // true = kein Flackern beim Start
var weekOffset by rememberSaveable { mutableIntStateOf(0) }
val canPinWidget = remember {
AppWidgetManager.getInstance(context).isRequestPinAppWidgetSupported
}
// Beim Zurückkehren (Wörter-Tab, Launcher, Widget) neu laden
LifecycleEventEffect(Lifecycle.Event.ON_RESUME) {
words = WordOfWeek.loadWords(context)
widgetPlaced = isWidgetPlaced(context)
}
fun changeOffset(new: Int) {
haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
weekOffset = new
}
Column(
modifier = modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(horizontal = 16.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
if (words.isEmpty()) {
EmptyCard(onOpenWords)
} else {
WordHeroCard(words, weekOffset, ::changeOffset)
WeeksCard(words, weekOffset, ::changeOffset)
}
if (!widgetPlaced && canPinWidget) {
WidgetCard(
onAdd = {
AppWidgetManager.getInstance(context).requestPinAppWidget(
ComponentName(context, SimpleWidget::class.java), null, null
)
}
)
}
Spacer(Modifier.height(8.dp))
}
}
@Composable
private fun WordHeroCard(
words: List<String>,
weekOffset: Int,
onOffsetChange: (Int) -> Unit
) {
val context = LocalContext.current
val week = WordOfWeek.weekOf(weekOffset)
val onColor = MaterialTheme.colorScheme.onPrimaryContainer
Card(
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.extraLarge,
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
contentColor = onColor
)
) {
Column(
modifier = Modifier.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
IconButton(onClick = { onOffsetChange(weekOffset - 1) }) {
Icon(
Icons.AutoMirrored.Filled.KeyboardArrowLeft,
contentDescription = stringResource(R.string.home_cd_previous)
)
}
Column(
modifier = Modifier.weight(1f),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = weekLabel(weekOffset, week),
style = MaterialTheme.typography.labelLarge
)
Text(
text = stringResource(
R.string.home_week_range,
week.weekNumber,
formatRange(context, week)
),
style = MaterialTheme.typography.bodySmall
)
}
IconButton(onClick = { onOffsetChange(weekOffset + 1) }) {
Icon(
Icons.AutoMirrored.Filled.KeyboardArrowRight,
contentDescription = stringResource(R.string.home_cd_next)
)
}
}
AnimatedContent(
targetState = weekOffset,
transitionSpec = {
val dir = if (targetState > initialState) 1 else -1
(slideInHorizontally { width -> width * dir } + fadeIn()) togetherWith
(slideOutHorizontally { width -> -width * dir } + fadeOut())
},
label = "word"
) { offset ->
Text(
text = WordOfWeek.wordFor(words, WordOfWeek.weekOf(offset)).orEmpty(),
style = MaterialTheme.typography.displaySmall,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 32.dp, horizontal = 8.dp)
)
}
if (weekOffset == 0) {
val day = remember { LocalDate.now().dayOfWeek.value } // 1 = Mo ... 7 = So
LinearProgressIndicator(
progress = { day / 7f },
modifier = Modifier.fillMaxWidth(),
color = onColor,
trackColor = onColor.copy(alpha = 0.15f)
)
Spacer(Modifier.height(8.dp))
Text(
text = stringResource(R.string.home_day_progress, day),
style = MaterialTheme.typography.bodySmall
)
} else {
FilledTonalButton(onClick = { onOffsetChange(0) }) {
Text(stringResource(R.string.home_back_to_current))
}
}
}
}
}
@Composable
private fun WeeksCard(
words: List<String>,
selectedOffset: Int,
onOffsetChange: (Int) -> Unit
) {
val context = LocalContext.current
Column {
Text(
text = stringResource(R.string.home_more_weeks),
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.padding(start = 4.dp, bottom = 8.dp)
)
Card(
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.large,
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceContainerLow
)
) {
listOf(-2, -1, 0, 1, 2, 3).forEach { offset ->
val week = WordOfWeek.weekOf(offset)
ListItem(
overlineContent = {
Text(
stringResource(
R.string.home_week_range,
week.weekNumber,
formatRange(context, week)
)
)
},
headlineContent = {
Text(WordOfWeek.wordFor(words, week).orEmpty())
},
trailingContent = {
if (offset == selectedOffset) {
Icon(Icons.Default.Check, contentDescription = null)
}
},
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
modifier = Modifier.clickable { onOffsetChange(offset) }
)
}
}
Text(
text = stringResource(R.string.home_preview_hint),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(start = 4.dp, top = 8.dp)
)
}
}
@Composable
private fun EmptyCard(onOpenWords: () -> Unit) {
Card(
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.extraLarge,
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceContainerLow
)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
Text(
text = stringResource(R.string.msg_no_words_yet),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Button(onClick = onOpenWords) {
Text(stringResource(R.string.hint_add_word))
}
}
}
}
@Composable
private fun WidgetCard(onAdd: () -> Unit) {
Card(
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.large,
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer,
contentColor = MaterialTheme.colorScheme.onSecondaryContainer
)
) {
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(
text = stringResource(R.string.home_widget_title),
style = MaterialTheme.typography.titleMedium
)
Text(
text = stringResource(R.string.home_widget_message),
style = MaterialTheme.typography.bodyMedium
)
Spacer(Modifier.height(8.dp))
FilledTonalButton(onClick = onAdd) {
Text(stringResource(R.string.home_widget_action))
}
}
}
}
@Composable
private fun weekLabel(offset: Int, week: WeekInfo): String = when (offset) {
0 -> stringResource(R.string.home_this_week)
1 -> stringResource(R.string.home_next_week)
-1 -> stringResource(R.string.home_last_week)
else -> stringResource(R.string.home_calendar_week, week.weekNumber)
}
private fun formatRange(context: Context, week: WeekInfo): String {
val zone = ZoneId.systemDefault()
val start = week.monday.atStartOfDay(zone).toInstant().toEpochMilli()
val end = week.sunday.atStartOfDay(zone).toInstant().toEpochMilli()
return DateUtils.formatDateRange(
context, start, end,
DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_ABBREV_MONTH or DateUtils.FORMAT_NO_YEAR
)
}
private fun isWidgetPlaced(context: Context): Boolean =
AppWidgetManager.getInstance(context)
.getAppWidgetIds(ComponentName(context, SimpleWidget::class.java))
.isNotEmpty()
@@ -0,0 +1,192 @@
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
import de.schanbro.weekfocus.components.SectionTitle
import de.schanbro.weekfocus.components.ClickRow
import de.schanbro.weekfocus.components.SwitchRow
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,
onOpenAbout: () -> Unit
) {
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))
ClickRow(
title = stringResource(R.string.title_about),
summary = stringResource(R.string.settings_about_summary),
onClick = onOpenAbout
)
Spacer(Modifier.height(16.dp))
}
// Dialog, wenn "Jetzt nach Updates suchen" etwas gefunden hat
availableRelease?.let { info ->
UpdateDialog(info = info, onDismiss = { availableRelease = null })
}
}
@@ -2,29 +2,177 @@ package de.schanbro.weekfocus.screens
import android.content.Context
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import de.schanbro.weekfocus.R
import de.schanbro.weekfocus.updateWidget
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.graphics.Color
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SwipeableWordItem(
word: String,
onDeleteRequest: () -> Unit,
onEditRequest: () -> Unit,
modifier: Modifier = Modifier
) {
val haptic = LocalHapticFeedback.current
val dismissState = rememberSwipeToDismissBoxState(
confirmValueChange = { value ->
when (value) {
SwipeToDismissBoxValue.StartToEnd -> onDeleteRequest() // nach rechts
SwipeToDismissBoxValue.EndToStart -> onEditRequest() // nach links
SwipeToDismissBoxValue.Settled -> Unit
}
false // Karte springt immer zurück, Dialog übernimmt
},
positionalThreshold = { totalDistance -> totalDistance * 0.4f }
)
// Haptisches Feedback, sobald die Schwelle überschritten wird
LaunchedEffect(dismissState.targetValue) {
if (dismissState.targetValue != SwipeToDismissBoxValue.Settled) {
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
}
}
SwipeToDismissBox(
state = dismissState,
modifier = modifier,
backgroundContent = {
val direction = dismissState.dismissDirection
val isDelete = direction == SwipeToDismissBoxValue.StartToEnd
val isEdit = direction == SwipeToDismissBoxValue.EndToStart
val color by animateColorAsState(
targetValue = when {
isDelete -> MaterialTheme.colorScheme.errorContainer
isEdit -> MaterialTheme.colorScheme.secondaryContainer
else -> Color.Transparent
},
label = "swipeBackground"
)
Box(
modifier = Modifier
.fillMaxSize()
.clip(MaterialTheme.shapes.medium)
.background(color)
.padding(horizontal = 20.dp),
contentAlignment = if (isDelete) Alignment.CenterStart else Alignment.CenterEnd
) {
when {
isDelete -> Icon(
Icons.Default.Delete,
contentDescription = null,
tint = MaterialTheme.colorScheme.onErrorContainer
)
isEdit -> Icon(
Icons.Default.Edit,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSecondaryContainer
)
}
}
}
) {
ElevatedCard(
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.medium,
colors = CardDefaults.elevatedCardColors(
containerColor = MaterialTheme.colorScheme.surfaceContainerLow
)
) {
Text(
text = word,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 16.dp)
)
}
}
}
@Composable
fun DeleteWordDialog(
word: String,
onConfirm: () -> Unit,
onDismiss: () -> Unit
) {
AlertDialog(
onDismissRequest = onDismiss,
icon = { Icon(Icons.Default.Delete, contentDescription = null) },
title = { Text(stringResource(R.string.dialog_delete_title)) },
text = { Text(stringResource(R.string.dialog_delete_message, word)) },
confirmButton = {
TextButton(onClick = onConfirm) { Text(stringResource(R.string.action_delete)) }
},
dismissButton = {
TextButton(onClick = onDismiss) { Text(stringResource(R.string.action_cancel)) }
}
)
}
@Composable
fun EditWordDialog(
word: String,
onSave: (String) -> Unit,
onDismiss: () -> Unit
) {
var text by remember(word) { mutableStateOf(word) }
AlertDialog(
onDismissRequest = onDismiss,
icon = { Icon(Icons.Default.Edit, contentDescription = null) },
title = { Text(stringResource(R.string.dialog_edit_title)) },
text = {
OutlinedTextField(
value = text,
onValueChange = { text = it },
singleLine = true,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = { onSave(text) })
)
},
confirmButton = {
TextButton(
onClick = { onSave(text) },
enabled = text.isNotBlank()
) { Text(stringResource(R.string.action_save)) }
},
dismissButton = {
TextButton(onClick = onDismiss) { Text(stringResource(R.string.action_cancel)) }
}
)
}
@Composable
fun WordListScreen(modifier: Modifier = Modifier) {
@@ -43,25 +191,40 @@ fun WordListScreen(modifier: Modifier = Modifier) {
}
}
val haptic = LocalHapticFeedback.current
var wordToDelete by remember { mutableStateOf<String?>(null) }
var wordToEdit by remember { mutableStateOf<String?>(null) }
fun saveWords() {
sharedPrefs.edit().putStringSet("words_key", wordList.toSet()).apply()
}
fun addCurrentWord() {
val trimmed = textInput.trim()
if (trimmed.isNotEmpty()) {
if (trimmed.isNotEmpty() && trimmed !in wordList) {
wordList.add(0, trimmed)
saveWords()
updateWidget(context)
textInput = ""
focusManager.clearFocus() // Fokus aufheben & Tastatur schließen
focusManager.clearFocus()
}
}
fun updateWord(old: String, new: String) {
val trimmed = new.trim()
val index = wordList.indexOf(old)
// Duplikate vermeiden, da das Set ohnehin keine doppelten Einträge speichert
if (index >= 0 && trimmed.isNotEmpty() && (trimmed == old || trimmed !in wordList)) {
wordList[index] = trimmed
saveWords()
updateWidget(context)
}
}
Column(
modifier = modifier
.fillMaxSize()
// Auf Klicks im leeren Bereich reagieren -> Fokus aufheben
// Auf Klicks im leeren Bereich reagieren → Fokus aufheben
.pointerInput(Unit) {
detectTapGestures(onTap = {
focusManager.clearFocus()
@@ -127,43 +290,39 @@ fun WordListScreen(modifier: Modifier = Modifier) {
verticalArrangement = Arrangement.spacedBy(8.dp),
contentPadding = PaddingValues(bottom = 16.dp)
) {
itemsIndexed(wordList) { index, word ->
ElevatedCard(
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.medium,
colors = CardDefaults.elevatedCardColors(
containerColor = MaterialTheme.colorScheme.surfaceContainerLow
)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = word,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.weight(1f)
)
IconButton(
onClick = {
wordList.removeAt(index)
saveWords()
updateWidget(context)
}
) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = "Entfernen",
tint = MaterialTheme.colorScheme.error
)
}
}
}
items(items = wordList, key = { it }) { word ->
SwipeableWordItem(
word = word,
onDeleteRequest = { wordToDelete = word },
onEditRequest = { wordToEdit = word },
modifier = Modifier.animateItem() // ältere Compose-Versionen: animateItemPlacement()
)
}
}
wordToDelete?.let { word ->
DeleteWordDialog(
word = word,
onConfirm = {
wordList.remove(word)
saveWords()
updateWidget(context)
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
wordToDelete = null
},
onDismiss = { wordToDelete = null }
)
}
wordToEdit?.let { word ->
EditWordDialog(
word = word,
onSave = { new ->
updateWord(word, new)
wordToEdit = null
},
onDismiss = { wordToEdit = null }
)
}
}
}
@@ -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 }
}
}
}
@@ -0,0 +1,77 @@
package de.schanbro.weekfocus.update
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import androidx.core.content.FileProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
import java.io.File
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
object ApkInstaller {
fun canInstall(context: Context): Boolean =
context.packageManager.canRequestPackageInstalls()
fun openInstallPermissionSettings(context: Context) {
val intent = Intent(
Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
Uri.parse("package:${context.packageName}")
).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
suspend fun download(
context: Context,
url: String,
onProgress: (Float) -> Unit
): File = withContext(Dispatchers.IO) {
val dir = File(context.cacheDir, "updates").apply {
mkdirs()
listFiles()?.forEach { it.delete() } // alte Downloads aufräumen
}
val file = File(dir, "update.apk")
val conn = URL(url).openConnection() as HttpURLConnection
conn.connectTimeout = 15_000
conn.readTimeout = 15_000
try {
if (conn.responseCode != HttpURLConnection.HTTP_OK) {
throw IOException("HTTP ${conn.responseCode}")
}
val total = conn.contentLengthLong
conn.inputStream.use { input ->
file.outputStream().use { output ->
val buffer = ByteArray(16 * 1024)
var done = 0L
var read: Int
while (input.read(buffer).also { read = it } != -1) {
ensureActive() // macht den Abbruch möglich
output.write(buffer, 0, read)
done += read
if (total > 0) onProgress(done.toFloat() / total)
}
}
}
file
} finally {
conn.disconnect()
}
}
fun install(context: Context, apk: File) {
val uri = FileProvider.getUriForFile(
context, "${context.packageName}.fileprovider", apk
)
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, "application/vnd.android.package-archive")
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK)
}
context.startActivity(intent)
}
}
@@ -0,0 +1,82 @@
package de.schanbro.weekfocus.update
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import de.schanbro.weekfocus.R
private const val KEY_HINT_DISMISSED = "network_hint_dismissed"
/** Zeigt [content] nur, wenn die App Netzwerkzugriff hat. Fragt sonst einmal danach. */
@Composable
fun NetworkPermissionGate(content: @Composable () -> Unit) {
val context = LocalContext.current
val prefs = remember {
context.getSharedPreferences("WeekFocusPrefs", Context.MODE_PRIVATE)
}
fun isGranted() = ContextCompat.checkSelfPermission(
context, Manifest.permission.INTERNET
) == PackageManager.PERMISSION_GRANTED
var granted by remember { mutableStateOf(isGranted()) }
var showDialog by remember {
mutableStateOf(!isGranted() && !prefs.getBoolean(KEY_HINT_DISMISSED, false))
}
val launcher = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission()
) { result ->
granted = result || isGranted()
if (!granted) openAppSettings(context) // kein System-Dialog möglich → Einstellungen
}
// Nach Rückkehr aus den Einstellungen neu prüfen
LifecycleEventEffect(Lifecycle.Event.ON_RESUME) {
granted = isGranted()
}
if (granted) {
content()
} else if (showDialog) {
AlertDialog(
onDismissRequest = {},
title = { Text(stringResource(R.string.permission_network_title)) },
text = { Text(stringResource(R.string.permission_network_message)) },
confirmButton = {
TextButton(onClick = {
showDialog = false
launcher.launch(Manifest.permission.INTERNET)
}) { Text(stringResource(R.string.permission_allow)) }
},
dismissButton = {
TextButton(onClick = {
prefs.edit().putBoolean(KEY_HINT_DISMISSED, true).apply()
showDialog = false
}) { Text(stringResource(R.string.permission_not_now)) }
}
)
}
}
private fun openAppSettings(context: Context) {
val intent = Intent(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", context.packageName, null)
).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
@@ -0,0 +1,29 @@
package de.schanbro.weekfocus.update
import android.content.Context
import java.io.IOException
object ReleaseNotes {
/** Liefert die eingebetteten Notes oder null (z. B. bei lokalen Builds). */
fun load(context: Context): String? = try {
context.assets.open("release_notes.md")
.bufferedReader().use { it.readText() }
.trim()
.ifEmpty { null }
} catch (e: IOException) {
null
}
/** Einfache Markdown-Bereinigung für die Anzeige als Text. */
fun format(markdown: String): String =
markdown.lines()
.joinToString("\n") { line ->
line.trimEnd()
.replace(Regex("^#{1,6}\\s*"), "")
.replace(Regex("^\\s*[-*]\\s+"), "• ")
.replace("**", "")
}
.replace(Regex("\n{3,}"), "\n\n")
.trim()
}
@@ -0,0 +1,88 @@
package de.schanbro.weekfocus.update
import android.content.Context
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
import org.json.JSONArray
data class ReleaseInfo(
val version: String,
val notes: String,
val apkUrl: String
)
object UpdateChecker {
private const val RELEASES_URL =
"https://git.schamagusa.de/api/v1/repos/robin/WeekFocus/releases"
suspend fun fetchLatestRelease(includePrereleases: Boolean = false): ReleaseInfo? =
withContext(Dispatchers.IO) {
try {
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.readTimeout = 10_000
conn.setRequestProperty("Accept", "application/json")
return try {
if (conn.responseCode == HttpURLConnection.HTTP_OK) {
conn.inputStream.bufferedReader().use { it.readText() }
} else null
} finally {
conn.disconnect()
}
}
private fun toRelease(json: JSONObject): ReleaseInfo? {
if (json.optBoolean("draft", false)) return null
val assets = json.getJSONArray("assets")
val apk = (0 until assets.length())
.map { assets.getJSONObject(it) }
.firstOrNull { it.getString("name").endsWith(".apk", ignoreCase = true) }
?: return null
return ReleaseInfo(
version = json.getString("tag_name"),
notes = json.optString("body", ""),
apkUrl = apk.getString("browser_download_url")
)
}
@Suppress("DEPRECATION")
fun currentVersion(context: Context): String =
context.packageManager.getPackageInfo(context.packageName, 0).versionName ?: "0"
/** Numerischer Vergleich pro Segment, damit 1.2.11 > 1.2.9 gilt. */
fun isNewer(remote: String, local: String): Boolean {
val r = parse(remote)
val l = parse(local)
for (i in 0 until maxOf(r.size, l.size)) {
val a = r.getOrElse(i) { 0 }
val b = l.getOrElse(i) { 0 }
if (a != b) return a > b
}
// Gleiche Nummer: stabiles Release ist neuer als eine installierte Beta
return local.contains("-") && !remote.contains("-")
}
private fun parse(version: String): List<Int> =
version.trim().removePrefix("v").substringBefore("-")
.split(".").map { it.toIntOrNull() ?: 0 }
}
@@ -0,0 +1,128 @@
package de.schanbro.weekfocus.update
import android.content.Context
import android.widget.Toast
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import de.schanbro.weekfocus.R
import de.schanbro.weekfocus.settings.SettingsRepository
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
private const val CHECK_INTERVAL_MS = 24L * 60 * 60 * 1000
@Composable
fun UpdateHandler() {
val context = LocalContext.current
val settings = remember { SettingsRepository.get(context) }
val prefs = remember {
context.getSharedPreferences("WeekFocusPrefs", Context.MODE_PRIVATE)
}
var release by remember { mutableStateOf<ReleaseInfo?>(null) }
LaunchedEffect(Unit) {
if (!settings.autoCheckUpdates) return@LaunchedEffect
val now = System.currentTimeMillis()
if (now - prefs.getLong("last_update_check", 0L) < CHECK_INTERVAL_MS) return@LaunchedEffect
val latest = UpdateChecker.fetchLatestRelease(settings.includePrereleases)
?: return@LaunchedEffect
prefs.edit().putLong("last_update_check", now).apply()
if (UpdateChecker.isNewer(latest.version, UpdateChecker.currentVersion(context))) {
release = latest
}
}
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
AlertDialog(
onDismissRequest = { if (!downloading) onDismiss() },
title = { Text(stringResource(R.string.update_title)) },
text = {
Column(Modifier.verticalScroll(rememberScrollState())) {
Text(stringResource(R.string.update_message, info.version.removePrefix("v")))
if (info.notes.isNotBlank()) {
Spacer(Modifier.height(12.dp))
Text(
text = info.notes,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
progress?.let { p ->
Spacer(Modifier.height(16.dp))
LinearProgressIndicator(
progress = { p },
modifier = Modifier.fillMaxWidth()
)
}
}
},
confirmButton = {
TextButton(
enabled = !downloading,
onClick = {
if (!ApkInstaller.canInstall(context)) {
Toast.makeText(
context, R.string.update_permission_hint, Toast.LENGTH_LONG
).show()
ApkInstaller.openInstallPermissionSettings(context)
} else {
downloadJob = scope.launch {
progress = 0f
try {
val apk = ApkInstaller.download(context, info.apkUrl) {
progress = it
}
progress = null
onDismiss()
ApkInstaller.install(context, apk)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
progress = null
Toast.makeText(
context, R.string.update_failed, Toast.LENGTH_LONG
).show()
}
}
}
}
) { Text(stringResource(R.string.update_action)) }
},
dismissButton = {
TextButton(
onClick = {
downloadJob?.cancel()
progress = null
onDismiss()
}
) {
Text(
stringResource(
if (downloading) R.string.action_cancel else R.string.update_later
)
)
}
}
)
}
@@ -0,0 +1,75 @@
package de.schanbro.weekfocus.update
import android.content.Context
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import de.schanbro.weekfocus.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
private const val KEY_LAST_SEEN = "last_seen_version"
@Composable
fun WhatsNewHandler() {
val context = LocalContext.current
val prefs = remember {
context.getSharedPreferences("WeekFocusPrefs", Context.MODE_PRIVATE)
}
val current = remember { UpdateChecker.currentVersion(context) }
var notes by remember { mutableStateOf<String?>(null) }
fun markSeen() = prefs.edit().putString(KEY_LAST_SEEN, current).apply()
LaunchedEffect(Unit) {
val lastSeen = prefs.getString(KEY_LAST_SEEN, null)
// Erster Start nach Neuinstallation: nichts anzeigen, nur merken
if (lastSeen == null) {
markSeen()
return@LaunchedEffect
}
if (UpdateChecker.isNewer(current, lastSeen)) {
val loaded = withContext(Dispatchers.IO) { ReleaseNotes.load(context) }
if (loaded != null) notes = loaded else markSeen()
}
}
notes?.let {
WhatsNewDialog(
version = current,
notes = it,
onDismiss = {
markSeen()
notes = null
}
)
}
}
@Composable
fun WhatsNewDialog(version: String, notes: String, onDismiss: () -> Unit) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.whats_new_title, version)) },
text = {
Column(Modifier.verticalScroll(rememberScrollState())) {
Text(
text = ReleaseNotes.format(notes),
style = MaterialTheme.typography.bodyMedium
)
}
},
confirmButton = {
TextButton(onClick = onDismiss) {
Text(stringResource(R.string.whats_new_close))
}
}
)
}
+80 -3
View File
@@ -1,11 +1,88 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hint_new_word">Enter new Word</string>
<string name="hint_new_word">Enter new word</string>
<string name="hint_add_word">Add word</string>
<string name="msg_no_words_yet">No words yet.</string>
<string name="msg_no_words">No words</string>
<string name="title_weekly_focus">Weekly Focus</string>
<string name="title_weekly_focus">Weekly focus</string>
<string name="title_settings">Settings</string>
<string name="title_words">Words</string>
<string name="title_home">Home</string>
</resources>
<string name="action_delete">Delete</string>
<string name="action_cancel">Cancel</string>
<string name="action_save">Save</string>
<string name="dialog_delete_title">Delete word?</string>
<string name="dialog_delete_message">“%1$s” will be permanently removed.</string>
<string name="dialog_edit_title">Edit word</string>
<string name="update_title">Update available</string>
<string name="update_message">Version %1$s is available. Download and install now?</string>
<string name="update_action">Update</string>
<string name="update_later">Later</string>
<string name="update_failed">Update failed. Please try again later.</string>
<string name="update_permission_hint">Please allow installs from this source, then tap “Update” again.</string>
<string name="permission_network_title">Network access needed</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_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>
<string name="action_back">Back</string>
<string name="settings_about_summary">Version, source code and more</string>
<string name="about_version">Version %1$s</string>
<string name="about_description">Keep your words of the week in view, right on your home screen.</string>
<string name="about_section_links">Links</string>
<string name="about_issues_title">Report a problem</string>
<string name="about_issues_summary">Bugs and requests in the issue tracker</string>
<string name="about_releases_title">Releases</string>
<string name="about_releases_summary">See all releases and changes</string>
<string name="whats_new_title">What’s new in version %1$s</string>
<string name="whats_new_close">Got it</string>
<string name="about_whats_new_title">What’s new</string>
<string name="about_whats_new_summary">See the changes in this version</string>
<string name="about_whats_new_section_title">Changes</string>
<string name="home_this_week">This week</string>
<string name="home_next_week">Next week</string>
<string name="home_last_week">Last week</string>
<string name="home_calendar_week">Week %1$d</string>
<string name="home_week_range">Week %1$d · %2$s</string>
<string name="home_cd_previous">Previous week</string>
<string name="home_cd_next">Show next week</string>
<string name="home_back_to_current">Back to this week</string>
<string name="home_day_progress">Day %1$d of 7</string>
<string name="home_more_weeks">More weeks</string>
<string name="home_preview_hint">The preview is based on your current word list and changes whenever you add, edit or remove words.</string>
<string name="home_widget_title">Add widget</string>
<string name="home_widget_message">Show your word of the week right on your home screen.</string>
<string name="home_widget_action">Add</string>
</resources>
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="splash_background">#121212</color>
</resources>
+1
View File
@@ -7,4 +7,5 @@
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
<color name="splash_background">#FFFFFF</color>
</resources>
+85 -1
View File
@@ -9,4 +9,88 @@
<string name="title_settings">Einstellungen</string>
<string name="title_words">Wörter</string>
<string name="title_home">Start</string>
</resources>
<string name="title_about">Über</string>
<!-- Aktionen -->
<string name="action_delete">Löschen</string>
<string name="action_cancel">Abbrechen</string>
<string name="action_save">Speichern</string>
<!-- Dialoge -->
<string name="dialog_delete_title">Wort löschen?</string>
<string name="dialog_delete_message">„%1$s“ wird dauerhaft entfernt.</string>
<string name="dialog_edit_title">Wort bearbeiten</string>
<!-- Auto-Update -->
<string name="update_title">Update verfügbar</string>
<string name="update_message">Version %1$s ist verfügbar. Jetzt herunterladen und installieren?</string>
<string name="update_action">Aktualisieren</string>
<string name="update_later">Später</string>
<string name="update_failed">Update fehlgeschlagen. Bitte später erneut versuchen.</string>
<string name="update_permission_hint">Bitte die Installation aus dieser Quelle erlauben und danach erneut auf „Aktualisieren“ tippen.</string>
<!-- Berechntigungen -->
<string name="permission_network_title">Netzwerkzugriff benötigt</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_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>
<string name="action_back">Zurück</string>
<string name="settings_about_summary">Version, Quellcode und mehr</string>
<string name="about_version">Version %1$s</string>
<string name="about_description">Behalte deine Wörter der Woche im Blick, direkt auf dem Startbildschirm.</string>
<string name="about_section_links">Links</string>
<string name="about_issues_title">Fehler melden</string>
<string name="about_issues_summary">Probleme und Wünsche im Issue-Tracker</string>
<string name="about_releases_title">Versionen</string>
<string name="about_releases_summary">Alle Releases und Änderungen ansehen</string>
<string name="whats_new_title">Neu in Version %1$s</string>
<string name="whats_new_close">Alles klar</string>
<string name="about_whats_new_title">Was ist neu</string>
<string name="about_whats_new_summary">Änderungen dieser Version ansehen</string>
<string name="about_whats_new_section_title">Änderungen</string>
<!-- Home Screen-->
<string name="home_this_week">Diese Woche</string>
<string name="home_next_week">Nächste Woche</string>
<string name="home_last_week">Letzte Woche</string>
<string name="home_calendar_week">Kalenderwoche %1$d</string>
<string name="home_week_range">KW %1$d · %2$s</string>
<string name="home_cd_previous">Vorherige Woche</string>
<string name="home_cd_next">Nächste Woche anzeigen</string>
<string name="home_back_to_current">Zur aktuellen Woche</string>
<string name="home_day_progress">Tag %1$d von 7</string>
<string name="home_more_weeks">Weitere Wochen</string>
<string name="home_preview_hint">Die Vorschau richtet sich nach deiner aktuellen Wortliste und ändert sich, sobald du Wörter hinzufügst, bearbeitest oder entfernst.</string>
<string name="home_widget_title">Widget hinzufügen</string>
<string name="home_widget_message">Zeige dein Wort der Woche direkt auf dem Startbildschirm.</string>
<string name="home_widget_action">Hinzufügen</string>
</resources>
+5 -1
View File
@@ -1,5 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.WeekFocus" parent="android:Theme.Material.Light.NoActionBar" />
<style name="Theme.WeekFocus.Splash" parent="Theme.SplashScreen">
<item name="windowSplashScreenBackground">@color/splash_background</item>
<item name="windowSplashScreenAnimatedIcon">@mipmap/ic_launcher</item>
<item name="postSplashScreenTheme">@style/Theme.WeekFocus</item>
</style>
</resources>
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<paths>
<cache-path name="updates" path="updates/" />
</paths>
+2
View File
@@ -8,6 +8,7 @@ lifecycleRuntimeKtx = "2.11.0"
activityCompose = "1.13.0"
kotlin = "2.4.20"
composeBom = "2026.09.00"
animation = "1.12.1"
[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
@@ -25,6 +26,7 @@ androidx-compose-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-
androidx-compose-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" }
androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }
androidx-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended" }
androidx-compose-animation = { group = "androidx.compose.animation", name = "animation", version.ref = "animation" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }