diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 05bb280..4de1cbf 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -24,8 +24,8 @@ android { applicationId = "space.gitwall.app" minSdk = 26 targetSdk = 35 - versionCode = 1 - versionName = "1.0.0" + versionCode = 2 + versionName = "1.1.0" } signingConfigs { diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro index 3a65f81..8662fb9 100644 --- a/android/app/proguard-rules.pro +++ b/android/app/proguard-rules.pro @@ -1,2 +1,4 @@ # WorkManager instantiates workers reflectively by class name. -keep class space.gitwall.app.RefreshWorker { *; } +-keep class space.gitwall.app.AlarmReceiver { *; } +-keep class space.gitwall.app.BootReceiver { *; } diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 336b6c9..d47055e 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -3,6 +3,15 @@ + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/java/space/gitwall/app/DailyAlarm.kt b/android/app/src/main/java/space/gitwall/app/DailyAlarm.kt new file mode 100644 index 0000000..18ca94d --- /dev/null +++ b/android/app/src/main/java/space/gitwall/app/DailyAlarm.kt @@ -0,0 +1,86 @@ +package space.gitwall.app + +import android.app.AlarmManager +import android.app.PendingIntent +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.os.Build +import java.util.Calendar + +/** + * One exact alarm per day at the user's chosen time. Exact alarms fire within + * a minute even while the phone sleeps, unlike WorkManager's batched jobs that + * Android may hold back for hours overnight. The alarm only enqueues the + * worker; the download itself runs under WorkManager with its retries. + */ +object DailyAlarm { + private const val REQUEST_CODE = 1001 + + fun arm(context: Context, hour: Int, minute: Int) { + val at = System.currentTimeMillis() + millisUntil(hour, minute) + val alarms = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager + val pending = pendingIntent(context) + val exact = Build.VERSION.SDK_INT < Build.VERSION_CODES.S || alarms.canScheduleExactAlarms() + if (exact) { + alarms.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pending) + } else { + // Exact alarms were revoked by the user; land as close as Android allows. + alarms.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pending) + } + SettingsStore(context).saveNextRun(at) + } + + fun cancel(context: Context) { + val alarms = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager + alarms.cancel(pendingIntent(context)) + SettingsStore(context).saveNextRun(0L) + } + + fun millisUntil(hour: Int, minute: Int): Long { + val now = Calendar.getInstance() + val next = (now.clone() as Calendar).apply { + set(Calendar.HOUR_OF_DAY, hour) + set(Calendar.MINUTE, minute) + set(Calendar.SECOND, 0) + set(Calendar.MILLISECOND, 0) + if (!after(now)) add(Calendar.DAY_OF_YEAR, 1) + } + return next.timeInMillis - now.timeInMillis + } + + private fun pendingIntent(context: Context): PendingIntent = + PendingIntent.getBroadcast( + context, + REQUEST_CODE, + Intent(context, AlarmReceiver::class.java), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) +} + +class AlarmReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + val settings = SettingsStore(context).read() + if (settings.url.isBlank()) return + // Re-arm first so a crash in the refresh can never lose tomorrow's alarm. + DailyAlarm.arm(context, settings.refreshHour, settings.refreshMinute) + Scheduler.runNow(context, RefreshWorker.SOURCE_ALARM) + } +} + +/** Alarms are cleared on reboot and can drift on clock or zone changes; re-arm and catch up. */ +class BootReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + when (intent.action) { + Intent.ACTION_BOOT_COMPLETED, + Intent.ACTION_MY_PACKAGE_REPLACED, + Intent.ACTION_TIME_CHANGED, + Intent.ACTION_TIMEZONE_CHANGED -> { + val settings = SettingsStore(context).read() + if (settings.url.isBlank()) return + DailyAlarm.arm(context, settings.refreshHour, settings.refreshMinute) + Scheduler.ensureHealthy(context) + } + } + } +} diff --git a/android/app/src/main/java/space/gitwall/app/MainActivity.kt b/android/app/src/main/java/space/gitwall/app/MainActivity.kt index 981ce8c..9d01a81 100644 --- a/android/app/src/main/java/space/gitwall/app/MainActivity.kt +++ b/android/app/src/main/java/space/gitwall/app/MainActivity.kt @@ -1,36 +1,50 @@ package space.gitwall.app import android.app.TimePickerDialog +import android.content.Context import android.content.Intent +import android.net.Uri import android.os.Bundle +import android.os.PowerManager +import android.provider.Settings as AndroidSettings import android.text.format.DateFormat import android.text.format.DateUtils import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.Surface import androidx.compose.material3.Text -import androidx.compose.material3.TextButton import androidx.compose.material3.darkColorScheme import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue @@ -39,24 +53,42 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.work.WorkInfo import androidx.work.WorkManager import kotlinx.coroutines.flow.map import java.util.Calendar +// Palette mirrors the website: near-black canvas, GitHub green accent. private val Green = Color(0xFF39D353) private val Ink = Color(0xFF0A0A0A) -private val Panel = Color(0xFF141414) -private val Line = Color(0xFF2A2A2A) -private val Muted = Color(0xFF8B8B8B) +private val Panel = Color(0xFF121212) +private val PanelRaised = Color(0xFF181818) +private val Line = Color(0xFF262626) +private val TextPrimary = Color(0xFFF2F2F2) +private val TextMuted = Color(0xFF8A8A8A) +private val TextDim = Color(0xFF5A5A5A) private val Danger = Color(0xFFF87171) +private val Amber = Color(0xFFF5C451) + +private enum class RunState { IDLE, WAITING_NETWORK, RUNNING } class MainActivity : ComponentActivity() { private val incomingUrl = mutableStateOf(null) @@ -83,35 +115,62 @@ class MainActivity : ComponentActivity() { extractWallpaperUrl(intent?.data, intent?.getStringExtra(Intent.EXTRA_TEXT)) } +private fun isBatteryUnrestricted(context: Context): Boolean { + val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager + return pm.isIgnoringBatteryOptimizations(context.packageName) +} + @Composable private fun Screen(incomingUrl: String?, onIncomingConsumed: () -> Unit) { val context = LocalContext.current val store = remember { SettingsStore(context) } val settings by store.flow().collectAsStateWithLifecycle(initialValue = store.read()) - val running by remember { - WorkManager.getInstance(context).getWorkInfosForUniqueWorkFlow("gitwall-now") - .map { list -> list.any { it.state == WorkInfo.State.RUNNING || it.state == WorkInfo.State.ENQUEUED } } - }.collectAsState(initial = false) + val runState by remember { + WorkManager.getInstance(context).getWorkInfosForUniqueWorkFlow("gitwall-now").map { list -> + when { + list.any { it.state == WorkInfo.State.RUNNING } -> RunState.RUNNING + // Enqueued but not running means the network constraint is unmet. + list.any { it.state == WorkInfo.State.ENQUEUED } -> RunState.WAITING_NETWORK + else -> RunState.IDLE + } + } + }.collectAsState(initial = RunState.IDLE) var url by remember { mutableStateOf(settings.url) } - var validation by remember { mutableStateOf(null) } + var message by remember { mutableStateOf(null) } + var batteryOk by remember { mutableStateOf(isBatteryUnrestricted(context)) } val clipboard = LocalClipboardManager.current val size = remember { screenSize(context) } + val hasUnsavedUrl = settings.url.isNotBlank() && url.trim() != settings.url + + // On every return to the screen: re-read the battery setting (the user may + // have just changed it in Settings) and catch up on a missed refresh. + val lifecycleOwner = LocalLifecycleOwner.current + DisposableEffect(lifecycleOwner) { + val observer = LifecycleEventObserver { _, event -> + if (event == Lifecycle.Event.ON_RESUME) { + batteryOk = isBatteryUnrestricted(context) + Scheduler.ensureHealthy(context) + } + } + lifecycleOwner.lifecycle.addObserver(observer) + onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } + } // A URL handed over by the website replaces whatever is in the field. LaunchedEffect(incomingUrl) { if (incomingUrl != null) { url = incomingUrl - validation = null + message = null onIncomingConsumed() } } fun apply() { when (val check = prepareWallpaperUrl(url, size)) { - is UrlCheck.Invalid -> validation = check.reason + is UrlCheck.Invalid -> message = check.reason is UrlCheck.Ok -> { - validation = null + message = null store.saveUrl(url) Scheduler.scheduleDaily(context, settings.refreshHour, settings.refreshMinute) Scheduler.runNow(context) @@ -119,12 +178,21 @@ private fun Screen(incomingUrl: String?, onIncomingConsumed: () -> Unit) { } } + fun paste() { + val text = clipboard.getText()?.text?.trim() + if (text.isNullOrEmpty()) { + message = "Clipboard is empty. Copy the URL from gitwall.space first." + } else { + url = text + message = null + } + } + fun pickTime() { TimePickerDialog( context, { _, hour, minute -> store.saveRefreshTime(hour, minute) - // Only re-anchor the schedule when a wallpaper is already set up. if (settings.url.isNotBlank()) Scheduler.scheduleDaily(context, hour, minute) }, settings.refreshHour, @@ -133,88 +201,245 @@ private fun Screen(incomingUrl: String?, onIncomingConsumed: () -> Unit) { ).show() } + fun requestUnrestrictedBattery() { + val direct = Intent(AndroidSettings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, Uri.parse("package:${context.packageName}")) + runCatching { context.startActivity(direct) } + .onFailure { runCatching { context.startActivity(Intent(AndroidSettings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)) } } + } + Column( Modifier .fillMaxSize() .statusBarsPadding() + .navigationBarsPadding() + .imePadding() .verticalScroll(rememberScrollState()) - .padding(horizontal = 24.dp, vertical = 32.dp), + .padding(horizontal = 20.dp) + .padding(top = 28.dp, bottom = 32.dp), ) { - Text("GitWall", color = Color.White, fontSize = 28.sp, fontWeight = FontWeight.ExtraBold, letterSpacing = (-0.5).sp) - Spacer(Modifier.height(6.dp)) - Text( - "Paste the wallpaper URL from gitwall.space. The app sets it as your lock screen now and refreshes it every day.", - color = Muted, fontSize = 14.sp, lineHeight = 20.sp, - ) + Header() Spacer(Modifier.height(28.dp)) - Text("WALLPAPER URL", color = Muted, fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp) - Spacer(Modifier.height(8.dp)) - OutlinedTextField( - value = url, - onValueChange = { url = it; validation = null }, - modifier = Modifier.fillMaxWidth(), - placeholder = { Text("https://gitwall.space/api/wallpaper?user=...", color = Color(0xFF555555)) }, - singleLine = false, - minLines = 2, - isError = validation != null, - supportingText = validation?.let { { Text(it, color = Danger) } }, - colors = OutlinedTextFieldDefaults.colors( - focusedContainerColor = Panel, unfocusedContainerColor = Panel, - focusedBorderColor = Color(0xFF4A4A4A), unfocusedBorderColor = Line, - focusedTextColor = Color.White, unfocusedTextColor = Color.White, - cursorColor = Green, - ), - ) - TextButton(onClick = { clipboard.getText()?.text?.let { url = it.trim(); validation = null } }) { - Text("Paste from clipboard", color = Green, fontSize = 13.sp) + Card { + Label("Wallpaper URL") + Spacer(Modifier.height(10.dp)) + UrlField(url, onChange = { url = it; message = null }) + Spacer(Modifier.height(10.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + LinkButton("Paste from clipboard", onClick = ::paste) + if (hasUnsavedUrl) { + Spacer(Modifier.width(12.dp)) + Text("New URL not applied yet", color = Amber, fontSize = 12.sp) + } + } + message?.let { + Spacer(Modifier.height(8.dp)) + Text(it, color = Danger, fontSize = 13.sp, lineHeight = 18.sp) + } } - Spacer(Modifier.height(20.dp)) + Spacer(Modifier.height(14.dp)) Button( onClick = ::apply, - enabled = !running, - modifier = Modifier.fillMaxWidth().height(52.dp), - colors = ButtonDefaults.buttonColors(containerColor = Color.White, contentColor = Ink, disabledContainerColor = Color(0xFF333333)), + modifier = Modifier.fillMaxWidth().height(54.dp), + shape = RoundedCornerShape(14.dp), + colors = ButtonDefaults.buttonColors(containerColor = Color.White, contentColor = Ink), ) { - if (running) CircularProgressIndicator(Modifier.height(18.dp), color = Ink, strokeWidth = 2.dp) - else Text("Set lock screen wallpaper", fontWeight = FontWeight.Bold, fontSize = 15.sp) + when (runState) { + RunState.RUNNING -> { + CircularProgressIndicator(Modifier.size(18.dp), color = Ink, strokeWidth = 2.dp) + Spacer(Modifier.width(10.dp)) + Text("Setting wallpaper", fontWeight = FontWeight.Bold, fontSize = 15.sp) + } + RunState.WAITING_NETWORK -> Text("Waiting for internet", fontWeight = FontWeight.Bold, fontSize = 15.sp) + RunState.IDLE -> Text( + if (settings.lastSuccessAt > 0L) "Update lock screen now" else "Set lock screen wallpaper", + fontWeight = FontWeight.Bold, fontSize = 15.sp, + ) + } } - Spacer(Modifier.height(16.dp)) - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text("Refresh every day at", color = Muted, fontSize = 13.sp) - TextButton(onClick = ::pickTime, contentPadding = PaddingValues(horizontal = 12.dp, vertical = 4.dp)) { - Text(formatTime(context, settings.refreshHour, settings.refreshMinute), color = Color.White, fontSize = 15.sp, fontWeight = FontWeight.SemiBold) + Spacer(Modifier.height(14.dp)) + Card { + Label("Schedule") + Spacer(Modifier.height(6.dp)) + Row( + Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp)).clickable(onClick = ::pickTime).padding(vertical = 8.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Text("Refresh every day at", color = TextPrimary, fontSize = 14.sp) + Text( + formatTime(context, settings.refreshHour, settings.refreshMinute), + color = Green, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, + ) + } + Divider() + Row( + Modifier.fillMaxWidth().padding(vertical = 8.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text("Background refresh", color = TextPrimary, fontSize = 14.sp) + Text( + if (batteryOk) "Allowed. The refresh can run while the phone sleeps." + else "Restricted. Android may delay the refresh for hours.", + color = if (batteryOk) TextMuted else Amber, fontSize = 12.sp, lineHeight = 16.sp, + ) + } + Spacer(Modifier.width(12.dp)) + if (batteryOk) Dot(Green) else LinkButton("Allow", onClick = ::requestUnrestrictedBattery, color = Amber) } } - Spacer(Modifier.height(16.dp)) - Status(settings, size) + Spacer(Modifier.height(14.dp)) + StatusCard(settings, runState, size) } } -private fun formatTime(context: android.content.Context, hour: Int, minute: Int): String { - val cal = Calendar.getInstance().apply { - set(Calendar.HOUR_OF_DAY, hour) - set(Calendar.MINUTE, minute) +@Composable +private fun Header() { + Row(verticalAlignment = Alignment.CenterVertically) { + Mark() + Spacer(Modifier.width(12.dp)) + Column { + Text("GitWall", color = TextPrimary, fontSize = 24.sp, fontWeight = FontWeight.ExtraBold, letterSpacing = (-0.5).sp) + Text("Your contribution graph, on your lock screen.", color = TextMuted, fontSize = 13.sp) + } + } +} + +/** The four-cell GitWall mark, laid out like the website favicon. */ +@Composable +private fun Mark() { + Canvas(Modifier.size(40.dp).background(Color(0xFF0D1117), RoundedCornerShape(10.dp))) { + val gap = size.width * 0.07f + val cell = (size.width - gap * 3) / 2 + val r = CornerRadius(cell * 0.18f) + val dark = Color(0xFF1F2630) + fun cellAt(col: Int, row: Int, color: Color) = drawRoundRect( + color, Offset(gap + col * (cell + gap), gap + row * (cell + gap)), Size(cell, cell), r, + ) + cellAt(0, 0, dark); cellAt(1, 0, Green); cellAt(0, 1, Green); cellAt(1, 1, dark) } - return DateFormat.getTimeFormat(context).format(cal.time) } @Composable -private fun Status(settings: Settings, size: ScreenSize) { +private fun Card(content: @Composable () -> Unit) { + Column( + Modifier + .fillMaxWidth() + .background(Panel, RoundedCornerShape(16.dp)) + .border(1.dp, Line, RoundedCornerShape(16.dp)) + .padding(16.dp), + ) { content() } +} + +@Composable +private fun Label(text: String) { + Text(text.uppercase(), color = TextDim, fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.4.sp) +} + +@Composable +private fun Divider() { + Box(Modifier.fillMaxWidth().height(1.dp).background(Line)) +} + +@Composable +private fun Dot(color: Color) { + Box(Modifier.size(10.dp).clip(CircleShape).background(color)) +} + +@Composable +private fun LinkButton(text: String, onClick: () -> Unit, color: Color = Green) { + Text( + text, + color = color, + fontSize = 13.sp, + fontWeight = FontWeight.SemiBold, + modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(onClick = onClick).padding(horizontal = 4.dp, vertical = 4.dp), + ) +} + +@Composable +private fun UrlField(value: String, onChange: (String) -> Unit) { + Box( + Modifier + .fillMaxWidth() + .background(PanelRaised, RoundedCornerShape(12.dp)) + .border(1.dp, Line, RoundedCornerShape(12.dp)) + .padding(horizontal = 14.dp, vertical = 12.dp), + ) { + if (value.isEmpty()) { + Text("https://gitwall.space/api/wallpaper?user=…", color = TextDim, fontSize = 13.sp, fontFamily = FontFamily.Monospace) + } + BasicTextField( + value = value, + onValueChange = onChange, + textStyle = TextStyle(color = Green, fontSize = 13.sp, fontFamily = FontFamily.Monospace, lineHeight = 19.sp), + cursorBrush = SolidColor(Green), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri), + minLines = 2, + modifier = Modifier.fillMaxWidth(), + ) + } +} + +@Composable +private fun StatusCard(settings: Settings, runState: RunState, size: ScreenSize) { val context = LocalContext.current - Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { - when { - settings.lastError != null -> Text(settings.lastError, color = Danger, fontSize = 13.sp, lineHeight = 18.sp) - settings.lastSuccessAt > 0L -> Text( - "Lock screen updated " + DateUtils.getRelativeTimeSpanString(settings.lastSuccessAt).toString().lowercase() + - ". Next refresh around " + formatTime(context, settings.refreshHour, settings.refreshMinute) + ".", - color = Green, fontSize = 13.sp, lineHeight = 18.sp, + val (tone, headline) = when { + runState == RunState.RUNNING -> Green to "Setting your lock screen…" + runState == RunState.WAITING_NETWORK -> Amber to "Waiting for an internet connection." + settings.lastError != null -> Danger to "Last attempt failed" + settings.lastSuccessAt > 0L -> Green to "Lock screen updated " + relative(settings.lastSuccessAt) + else -> TextMuted to "Not set yet" + } + Card { + Label("Status") + Spacer(Modifier.height(10.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + Dot(tone) + Spacer(Modifier.width(10.dp)) + Text(headline, color = TextPrimary, fontSize = 14.sp, fontWeight = FontWeight.Medium) + } + if (settings.lastError != null && runState == RunState.IDLE) { + Spacer(Modifier.height(6.dp)) + Text( + relative(settings.lastAttemptAt).replaceFirstChar { it.uppercase() } + ": " + settings.lastError, + color = Danger, fontSize = 13.sp, lineHeight = 18.sp, modifier = Modifier.padding(start = 20.dp), ) - else -> Text("Not set yet.", color = Muted, fontSize = 13.sp) } - Text("This phone renders at ${size.width} x ${size.height}.", color = Color(0xFF555555), fontSize = 12.sp) + Spacer(Modifier.height(12.dp)) + Divider() + Spacer(Modifier.height(10.dp)) + InfoRow("Next refresh", if (settings.nextRunAt > 0L) formatWhen(context, settings.nextRunAt) else "Not scheduled") + Spacer(Modifier.height(6.dp)) + InfoRow("Screen size", "${size.width} × ${size.height}") + } +} + +@Composable +private fun InfoRow(key: String, value: String) { + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { + Text(key, color = TextMuted, fontSize = 13.sp) + Text(value, color = TextPrimary, fontSize = 13.sp) } } + +private fun relative(at: Long): String { + if (System.currentTimeMillis() - at < DateUtils.MINUTE_IN_MILLIS) return "just now" + return DateUtils.getRelativeTimeSpanString(at).toString().lowercase() +} + +private fun formatTime(context: Context, hour: Int, minute: Int): String { + val cal = Calendar.getInstance().apply { + set(Calendar.HOUR_OF_DAY, hour) + set(Calendar.MINUTE, minute) + } + return DateFormat.getTimeFormat(context).format(cal.time) +} + +private fun formatWhen(context: Context, at: Long): String = + DateUtils.formatDateTime(context, at, DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_ABBREV_ALL) diff --git a/android/app/src/main/java/space/gitwall/app/RefreshWorker.kt b/android/app/src/main/java/space/gitwall/app/RefreshWorker.kt index f4231d0..e8727a9 100644 --- a/android/app/src/main/java/space/gitwall/app/RefreshWorker.kt +++ b/android/app/src/main/java/space/gitwall/app/RefreshWorker.kt @@ -11,15 +11,28 @@ import androidx.work.OutOfQuotaPolicy import androidx.work.PeriodicWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkerParameters +import androidx.work.workDataOf import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext -import java.util.Calendar import java.util.concurrent.TimeUnit +/** + * Downloads the wallpaper and sets the lock screen. Three things enqueue it: + * the exact daily alarm, the user tapping the button, and the periodic + * safety net. The periodic run steps aside when the alarm already did the job. + */ class RefreshWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) { override suspend fun doWork(): Result = withContext(Dispatchers.IO) { val store = SettingsStore(applicationContext) - val prepared = prepareWallpaperUrl(store.read().url, screenSize(applicationContext)) + val settings = store.read() + val source = inputData.getString(KEY_SOURCE) ?: SOURCE_MANUAL + + if (source == SOURCE_BACKUP) { + val fresh = System.currentTimeMillis() - settings.lastSuccessAt < BACKUP_SKIP_WINDOW_MS + if (fresh) return@withContext Result.success() + } + + val prepared = prepareWallpaperUrl(settings.url, screenSize(applicationContext)) if (prepared !is UrlCheck.Ok) { store.recordFailure("No valid wallpaper URL saved.") return@withContext Result.failure() @@ -30,60 +43,80 @@ class RefreshWorker(context: Context, params: WorkerParameters) : CoroutineWorke Result.success() } catch (e: WallpaperException) { store.recordFailure(e.message ?: "Unknown error") - // Network trouble is worth a retry with backoff; a bad URL is not. - if (runAttemptCount < 3 && e.message?.startsWith("Could not reach") == true) Result.retry() else Result.failure() + // Network trouble is worth a few retries with backoff; a bad URL is not. + val transient = e.message?.startsWith("Could not reach") == true || e.message?.contains("HTTP 5") == true + if (transient && runAttemptCount < 5) Result.retry() else Result.failure() } catch (e: Exception) { store.recordFailure(e.message ?: e.javaClass.simpleName) Result.failure() } } + + companion object { + const val KEY_SOURCE = "source" + const val SOURCE_MANUAL = "manual" + const val SOURCE_ALARM = "alarm" + const val SOURCE_BACKUP = "backup" + const val SOURCE_CATCHUP = "catchup" + private val BACKUP_SKIP_WINDOW_MS = TimeUnit.HOURS.toMillis(20) + } } object Scheduler { - private const val DAILY = "gitwall-daily" - private const val NOW = "gitwall-now" + private const val DAILY_BACKUP = "gitwall-daily" + private const val RUN = "gitwall-now" + private val STALE_MS = TimeUnit.HOURS.toMillis(26) private val network = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() /** - * WorkManager cannot promise an exact minute. Anchoring the first run at - * the chosen time and repeating every 24h lands within the flex window on - * every device and survives reboots without a boot receiver. Re-enqueueing - * resets the anchor, which is what a changed time needs. + * Arms everything that keeps the wallpaper fresh: + * 1. An exact alarm at the chosen time, which fires on the minute even in + * Doze and re-arms itself for the next day (see [AlarmReceiver]). + * 2. A 24h periodic job as a safety net in case the alarm is lost, which + * skips itself when the alarm already refreshed within 20 hours. */ fun scheduleDaily(context: Context, hour: Int, minute: Int) { - val request = PeriodicWorkRequestBuilder(24, TimeUnit.HOURS, 30, TimeUnit.MINUTES) + DailyAlarm.arm(context, hour, minute) + + val backup = PeriodicWorkRequestBuilder(24, TimeUnit.HOURS, 2, TimeUnit.HOURS) .setConstraints(network) - .setInitialDelay(millisUntil(hour, minute), TimeUnit.MILLISECONDS) + .setInitialDelay(DailyAlarm.millisUntil(hour, minute) + TimeUnit.HOURS.toMillis(2), TimeUnit.MILLISECONDS) + .setInputData(workDataOf(RefreshWorker.KEY_SOURCE to RefreshWorker.SOURCE_BACKUP)) .build() WorkManager.getInstance(context) - .enqueueUniquePeriodicWork(DAILY, ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, request) + .enqueueUniquePeriodicWork(DAILY_BACKUP, ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, backup) } fun cancelDaily(context: Context) { - WorkManager.getInstance(context).cancelUniqueWork(DAILY) + DailyAlarm.cancel(context) + WorkManager.getInstance(context).cancelUniqueWork(DAILY_BACKUP) } - /** Applies the wallpaper right away, in the background, using the saved URL. */ - fun runNow(context: Context) { + /** Applies the wallpaper right away in the background using the saved URL. */ + fun runNow(context: Context, source: String = RefreshWorker.SOURCE_MANUAL) { val request = OneTimeWorkRequestBuilder() .setConstraints(network) .setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST) + .setInputData(workDataOf(RefreshWorker.KEY_SOURCE to source)) .build() - WorkManager.getInstance(context).enqueueUniqueWork(NOW, ExistingWorkPolicy.REPLACE, request) + WorkManager.getInstance(context).enqueueUniqueWork(RUN, ExistingWorkPolicy.REPLACE, request) } - private fun millisUntil(hour: Int, minute: Int): Long { - val now = Calendar.getInstance() - val next = (now.clone() as Calendar).apply { - set(Calendar.HOUR_OF_DAY, hour) - set(Calendar.MINUTE, minute) - set(Calendar.SECOND, 0) - set(Calendar.MILLISECOND, 0) - if (!after(now)) add(Calendar.DAY_OF_YEAR, 1) + /** + * Called when the app opens or the phone boots. Always re-arms the alarm, + * because a reboot or a force-stop silently drops it and arming is + * idempotent. If a refresh was missed (phone off, no network, aggressive + * battery saver) it catches up now. + */ + fun ensureHealthy(context: Context) { + val settings = SettingsStore(context).read() + if (settings.url.isBlank()) return + DailyAlarm.arm(context, settings.refreshHour, settings.refreshMinute) + if (System.currentTimeMillis() - settings.lastSuccessAt > STALE_MS) { + runNow(context, RefreshWorker.SOURCE_CATCHUP) } - return next.timeInMillis - now.timeInMillis } } diff --git a/android/app/src/main/java/space/gitwall/app/Settings.kt b/android/app/src/main/java/space/gitwall/app/Settings.kt index 4b70cc6..d40870d 100644 --- a/android/app/src/main/java/space/gitwall/app/Settings.kt +++ b/android/app/src/main/java/space/gitwall/app/Settings.kt @@ -12,7 +12,10 @@ data class Settings( val refreshHour: Int = 6, val refreshMinute: Int = 0, val lastSuccessAt: Long = 0L, + val lastAttemptAt: Long = 0L, val lastError: String? = null, + /** Epoch millis of the next scheduled exact alarm, 0 when none is set. */ + val nextRunAt: Long = 0L, ) /** One small SharedPreferences file; a listener-backed Flow keeps the UI in sync with the worker. */ @@ -25,7 +28,9 @@ class SettingsStore(context: Context) { refreshHour = prefs.getInt(KEY_HOUR, 6), refreshMinute = prefs.getInt(KEY_MINUTE, 0), lastSuccessAt = prefs.getLong(KEY_LAST_SUCCESS, 0L), + lastAttemptAt = prefs.getLong(KEY_LAST_ATTEMPT, 0L), lastError = prefs.getString(KEY_LAST_ERROR, null), + nextRunAt = prefs.getLong(KEY_NEXT_RUN, 0L), ) fun flow(): Flow = callbackFlow { @@ -43,12 +48,17 @@ class SettingsStore(context: Context) { prefs.edit().putInt(KEY_HOUR, hour.coerceIn(0, 23)).putInt(KEY_MINUTE, minute.coerceIn(0, 59)).apply() } + fun saveNextRun(at: Long) { + prefs.edit().putLong(KEY_NEXT_RUN, at).apply() + } + fun recordSuccess() { - prefs.edit().putLong(KEY_LAST_SUCCESS, System.currentTimeMillis()).remove(KEY_LAST_ERROR).apply() + val now = System.currentTimeMillis() + prefs.edit().putLong(KEY_LAST_SUCCESS, now).putLong(KEY_LAST_ATTEMPT, now).remove(KEY_LAST_ERROR).apply() } fun recordFailure(message: String) { - prefs.edit().putString(KEY_LAST_ERROR, message).apply() + prefs.edit().putLong(KEY_LAST_ATTEMPT, System.currentTimeMillis()).putString(KEY_LAST_ERROR, message).apply() } private companion object { @@ -56,6 +66,8 @@ class SettingsStore(context: Context) { const val KEY_HOUR = "refresh_hour" const val KEY_MINUTE = "refresh_minute" const val KEY_LAST_SUCCESS = "last_success" + const val KEY_LAST_ATTEMPT = "last_attempt" const val KEY_LAST_ERROR = "last_error" + const val KEY_NEXT_RUN = "next_run" } } diff --git a/android/app/src/main/res/drawable/ic_launcher_foreground.xml b/android/app/src/main/res/drawable/ic_launcher_foreground.xml index cf71fa7..9c55e0f 100644 --- a/android/app/src/main/res/drawable/ic_launcher_foreground.xml +++ b/android/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -1,13 +1,13 @@ - + - - - - + + + + diff --git a/android/app/src/main/res/drawable/ic_launcher_monochrome.xml b/android/app/src/main/res/drawable/ic_launcher_monochrome.xml index 5cefe7c..8841466 100644 --- a/android/app/src/main/res/drawable/ic_launcher_monochrome.xml +++ b/android/app/src/main/res/drawable/ic_launcher_monochrome.xml @@ -4,6 +4,6 @@ android:height="108dp" android:viewportWidth="108" android:viewportHeight="108"> - - + + diff --git a/public/gitwall.apk b/public/gitwall.apk index 661b5c7..401171a 100644 Binary files a/public/gitwall.apk and b/public/gitwall.apk differ diff --git a/src/app/api/themes/route.ts b/src/app/api/themes/route.ts index c51a656..a89496d 100644 --- a/src/app/api/themes/route.ts +++ b/src/app/api/themes/route.ts @@ -7,6 +7,7 @@ export async function GET() { name: t.name, colors: t.levels, background: t.background, + text: t.text, })); return NextResponse.json(themes); } diff --git a/src/app/page.tsx b/src/app/page.tsx index b53429d..d9b4539 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -56,6 +56,7 @@ const FALLBACK_THEMES: Theme[] = Object.entries(THEMES).map(([id, t]) => ({ name: t.name, colors: t.levels, background: t.background, + text: t.text, })); const FALLBACK_DEVICES: Device[] = Object.entries(DEVICES) @@ -118,18 +119,25 @@ function ImportantNote({ children }: { children: ReactNode }) { ); } -function UrlBox({ - url, - copied, - onCopy, -}: { - url: string | null; - copied: boolean; - onCopy: () => void; -}) { +function UrlBox({ url }: { url: string | null }) { + const inputRef = useRef(null); + const [copied, setCopied] = useState(false); + const copy = useCallback(async () => { + if (!url) return; + try { + await navigator.clipboard.writeText(url); + setCopied(true); + setTimeout(() => setCopied(false), 2000); + } catch { + // Clipboard API needs a secure context; select the text so a long-press + // or Cmd/Ctrl+C still works. + inputRef.current?.select(); + } + }, [url]); return (
+ ); +} + export default function Home() { const [platform, setPlatform] = useState<"iphone" | "android">("iphone"); const [username, setUsername] = useState(""); @@ -165,8 +235,8 @@ export default function Home() { const [generatedKey, setGeneratedKey] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); - const [copied, setCopied] = useState(false); const [autoDetected, setAutoDetected] = useState(false); + const [isAndroidVisitor, setIsAndroidVisitor] = useState(false); const [themes, setThemes] = useState(FALLBACK_THEMES); const [devices, setDevices] = useState(FALLBACK_DEVICES); // Monotonic id so an out-of-order preview fetch can't overwrite a newer one. @@ -196,6 +266,7 @@ export default function Home() { const ua = navigator.userAgent; if (/Android/.test(ua)) { setPlatform("android"); + setIsAndroidVisitor(true); const dpr = window.devicePixelRatio || 1; setAndroidScreen({ width: Math.round(Math.min(screen.width, screen.height) * dpr), @@ -309,20 +380,6 @@ export default function Home() { } }, [username, selectedTheme, iphoneDevice, platform, showStats, shape]); - const handleCopy = useCallback(async () => { - if (!wallpaperUrl) return; - try { - await navigator.clipboard.writeText(wallpaperUrl); - } catch { - // Clipboard API needs a secure context; fall back to selecting the field. - const input = document.querySelector("input[readonly][value^='http']"); - input?.select(); - return; - } - setCopied(true); - setTimeout(() => setCopied(false), 2000); - }, [wallpaperUrl]); - // Direct download for Android uses the browser-reported screen size so the // PNG matches the phone even without the app. const downloadUrl = (() => { @@ -398,6 +455,23 @@ export default function Home() { const ironmanSelected = isIronmanId(selectedTheme); const ironmanGroup = ironmanThemes.find((t) => t.id === IRONMAN_DEFAULT) ?? ironmanThemes[0]; + // Tiles in the Special row. Groups open their variant picker below; single + // themes select directly. Missing themes (API drift) simply do not render. + const specialGroups = ( + [ + { id: "minecraft", label: "Minecraft", theme: minecraftGroup, selected: minecraftSelected, defaultId: MINECRAFT_DEFAULT }, + { id: "onepiece", label: "One Piece", theme: onepieceGroup, selected: onepieceSelected, defaultId: ONEPIECE_DEFAULT }, + { id: "aot", label: "Attack on Titan", theme: aotGroup, selected: aotSelected, defaultId: AOT_DEFAULT }, + { id: "got", label: "Game of Thrones", theme: gotGroup, selected: gotSelected, defaultId: GOT_DEFAULT }, + { id: "spiderman", label: "Spider-Man", theme: spidermanGroup, selected: spidermanSelected, defaultId: SPIDERMAN_DEFAULT }, + { id: "ironman", label: "Iron Man", theme: ironmanGroup, selected: ironmanSelected, defaultId: IRONMAN_DEFAULT }, + { id: "pointblank", label: "Point Blank", theme: pointblankTheme, selected: pointblankSelected, defaultId: POINTBLANK_ID }, + { id: "breakingbad", label: "Breaking Bad", theme: breakingbadTheme, selected: breakingbadSelected, defaultId: BREAKINGBAD_ID }, + { id: "bettercallsaul", label: "Better Call Saul", theme: bettercallsaulTheme, selected: bettercallsaulSelected, defaultId: BETTERCALLSAUL_ID }, + { id: "pokemon", label: "Pokémon", theme: pokemonGroup, selected: pokemonSelected, defaultId: POKEMON_DEFAULT }, + ] as const + ).filter((g): g is typeof g & { theme: Theme } => g.theme !== undefined); + const iphoneGuide = (
@@ -413,7 +487,7 @@ export default function Home() {

Add these actions

“Get Contents of URL” → paste your wallpaper URL:

- +

“Set Wallpaper Photo” → choose Lock Screen.

@@ -434,7 +508,7 @@ export default function Home() {

Enter your GitHub username, choose a theme above, then tap Generate. No phone model needed: the app measures your screen.

-

A small app that does one thing: fetches your wallpaper and sets it as the lock screen, then repeats every morning.

+

A small app that does one thing: fetches your wallpaper and sets it as the lock screen, then repeats every day at a time you choose.

-

Tap the button below on your phone. The app opens with the URL filled in. Or copy the URL and paste it into the app.

- {wallpaperUrl ? ( +

On your phone, tap the button below and the app opens with the URL filled in. Or copy the URL and paste it into the app.

+ {!wallpaperUrl ? ( +

Complete step 1 to enable this button.

+ ) : !isAndroidVisitor ? ( +

You are not on an Android phone. Open gitwall.space on your phone to use this button, or copy the URL below into the app.

+ ) : (
Open in GitWall app - ) : ( -

Complete step 1 to enable this button.

)} - + -

In the app tap Set lock screen wallpaper. Your lock screen updates right away and refreshes every day at the time you choose in the app (6:00 by default).

+

In the app tap Set lock screen wallpaper. Your lock screen updates right away and refreshes every day at the time you choose (6:00 by default).

+

Tap Allow next to Background refresh so Android lets the app fetch while the phone sleeps.

If your phone has a rotating lock screen feature such as Samsung Dynamic Lock screen or Xiaomi Wallpaper Carousel, turn it off or it will replace GitWall. @@ -475,7 +552,17 @@ export default function Home() {
{/* Hero */} -
+
+ {/* Brand row: the same four-cell mark as the favicon and the Android app icon */} +
+ + GitWall +

GitHub contributions as your wallpaper.

@@ -617,30 +704,7 @@ export default function Home() {

{gridThemes.map((t) => ( - + setSelectedTheme(t.id)} /> ))}
@@ -678,245 +742,16 @@ export default function Home() { Special

- {/* Minecraft group — opens the block-style sub-options below */} - {minecraftGroup && ( - - )} - - {/* One Piece group */} - {onepieceGroup && ( - - )} - - {/* Attack on Titan group */} - {aotGroup && ( - - )} - - {/* Game of Thrones group */} - {gotGroup && ( - - )} - - {/* Spider-Man group */} - {spidermanGroup && ( - - )} - - {/* Iron Man group */} - {ironmanGroup && ( - - )} - - {/* Point Blank — a single full-scene theme (no variants) */} - {pointblankTheme && ( - - )} - - {/* Breaking Bad */} - {breakingbadTheme && ( - - )} - - {/* Better Call Saul */} - {bettercallsaulTheme && ( - - )} - - {/* Pokémon group */} - {pokemonGroup && ( - - )} + {specialGroups.map((g) => ( + { if (!g.selected) setSelectedTheme(g.defaultId); }} + /> + ))}
{/* Minecraft block variants */}