Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -985,7 +985,8 @@ things to preserve:
- **The hypnogram draws the counted gaps** (`hypnogramBlocks`), display-only. Never feed those
blocks to `awakeMinutes`, which counts the gaps itself.
- **An hour-plus gap inside the wearer's Bedtime window stays one night** (`SleepGapBridge`). Off
unless quiet hours are on; Bedtime windows decide when the night has any, else the clock window.
unless the schedule or Bedtime tracking is on — the two are independent since #126; Bedtime
windows decide when the night has any, else the clock window if the schedule is on.
The sync's reconcile and `SleepRecordDeletion`'s restate must segment with the same bridge, or a
record delete would split a night the next sync merges back.

Expand Down
11 changes: 7 additions & 4 deletions app/src/main/assets/i18n/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@
"A screening questionnaire, not a diagnosis.": "Um questionário de rastreamento, não um diagnóstico.",
"A solid active day so far.": "Um dia ativo e consistente até agora.",
"A steady week. Keep it up.": "Uma semana estável. Continue assim.",
"A still wrist reads as sleep, so an evening on the sofa can run the night high. Trimmed minutes are never imported — changing these later won't bring them back.": "Um pulso parado parece sono, então uma noite no sofá pode inflar a noite. Minutos cortados nunca são importados — mudar isso depois não os traz de volta.",
"A typical daytime stress score.": "Um nível de estresse diurno típico.",
"A typical resting heart rate for adults.": "Uma frequência cardíaca em repouso típica para adultos.",
"A typical skin-temperature range from the ring.": "Uma faixa típica de temperatura da pele medida pelo anel.",
Expand Down Expand Up @@ -231,7 +232,6 @@
"Authorize in your browser — you'll return to PulseLoop automatically.": "Autorize no navegador — você voltará ao PulseLoop automaticamente.",
"Auto Upload": "Envio automático",
"Automatic backups": "Backups automáticos",
"Automatically align quiet hours with Android's Bedtime or Do Not Disturb mode.": "Alinhar automaticamente o horário de silêncio com o modo Hora de dormir ou Não perturbe do Android.",
"Average": "Média",
"Average difference {0}; 95 % of differences between {1} and {2}": "Diferença média {0}; 95 % das diferenças entre {1} e {2}",
"Averaging {0} against a need of {1}": "Média de {0} contra uma necessidade de {1}",
Expand Down Expand Up @@ -492,6 +492,7 @@
"Daily goals": "Metas diárias",
"Daily guidance": "Orientação diária",
"Daily or almost daily": "Diariamente ou quase",
"Daily schedule for nights without Bedtime/DND.": "Horário diário para noites sem Hora de dormir/Não perturbe.",
"Daily targets": "Metas diárias",
"Dance": "Dança",
"Data & privacy": "Dados e privacidade",
Expand Down Expand Up @@ -687,7 +688,6 @@
"Factory reset ring": "Restaurar anel de fábrica",
"Factory reset ring?": "Restaurar anel de fábrica?",
"Fair": "Razoável",
"Fallback schedule (used when no Bedtime/DND mode was active):": "Horário alternativo (usado quando nenhum modo Hora de dormir/Não perturbe estava ativo):",
"Fastest and cheapest": "O mais rápido e barato",
"Fasting 100–125 is above the typical range.": "Em jejum, 100–125 está acima da faixa típica.",
"Fasting normal is up to 99 mg/dL.": "Em jejum, o normal é até 99 mg/dL.",
Expand Down Expand Up @@ -890,6 +890,8 @@
"Keep going": "Continue",
"Keep it always on?": "Deixar sempre ligado?",
"Keep it on": "Deixar ligado",
"Keep only sleep inside Android's Bedtime or Do Not Disturb.": "Manter só o sono dentro do modo Hora de dormir ou Não perturbe do Android.",
"Keep only sleep inside a daily schedule. Naps outside it are skipped.": "Manter só o sono dentro de um horário diário. Cochilos fora dele são ignorados.",
"Keep recording": "Continuar gravando",
"Keep still — measuring blood oxygen…": "Fique parado — medindo o oxigênio no sangue…",
"Keep still — measuring blood pressure, SpO₂, stress, fatigue & blood sugar…": "Fique parado — medindo pressão arterial, SpO₂, estresse, fadiga e glicose…",
Expand Down Expand Up @@ -1109,6 +1111,8 @@
"Nightly sleep: latest {0}, range {1}–{2}, {3} of {4} nights tracked": "Sono por noite: última {0}, faixa {1}–{2}, {3} de {4} noites registradas",
"Nightly sleep: no nights tracked in this range": "Sono por noite: nenhuma noite registrada neste período",
"Nights in your baseline": "Noites na sua linha de base",
"Nights without it are kept whole.": "Noites sem ele ficam inteiras.",
"Nights without it use the schedule.": "Noites sem ele usam o horário.",
"No HR samples yet — sync your ring to start your trend.": "Ainda não há amostras de HR — sincronize seu anel para começar sua tendência.",
"No HRV data yet — HRV builds up over a few hours of wear.": "Ainda não há dados de HRV — a HRV se forma após algumas horas de uso.",
"No Health Connect permissions granted — nothing to export.": "Nenhuma permissão do Health Connect concedida — nada para exportar.",
Expand Down Expand Up @@ -1357,7 +1361,6 @@
"Pão francês com queijo minas": "Pão francês com queijo minas",
"Quick Access": "Acesso rápido",
"Quiet from": "Silêncio a partir de",
"Quiet hours schedule:": "Horário de silêncio:",
"Quiet until": "Silêncio até",
"READINGS": "LEITURAS",
"RECORDS": "RECORDES",
Expand Down Expand Up @@ -1589,6 +1592,7 @@
"Sleep stages: {0}": "Estágios do sono: {0}",
"Sleep synced": "Sono sincronizado",
"Sleep tracking": "Monitoramento do sono",
"Sleep trimming": "Corte do sono",
"Sleep {0} a night": "Dormir {0} por noite",
"Sleep, steps, heart and more, from a week to a year": "Sono, passos, coração e mais, de uma semana a um ano",
"Sleeping less this week": "Dormindo menos nesta semana",
Expand Down Expand Up @@ -1940,7 +1944,6 @@
"When": "Quando",
"When did it end?": "Quando terminou?",
"When did it start?": "Quando começou?",
"When on, sleep the ring records outside the window is trimmed off on import — a still wrist reads as sleep, so an evening on the sofa can log a phantom session and run the night high. Set the start to when you actually go to bed. Naps outside the window are skipped too. Already-imported nights are never touched, and what the gate skips while it is narrower stays skipped.": "Quando ativado, o sono que o anel registra fora da janela é cortado na importação — um pulso parado parece sono, então uma noite no sofá pode registrar uma sessão fantasma e inflar a noite. Defina o início para quando você realmente vai para a cama. Cochilos fora da janela também são ignorados. Noites já importadas nunca são alteradas, e o que o filtro ignora enquanto está mais estreito continua ignorado.",
"When the ring is at 30% or less a couple of hours before your usual bedtime.": "Quando o anel estiver com 30% ou menos algumas horas antes do seu horário habitual de dormir.",
"When the ring says… what {0} says (minutes)": "Quando o anel diz… o que {0} diz (minutos)",
"When two or more of last night's signals are outside your usual range.": "Quando dois ou mais sinais da última noite estiverem fora da sua faixa habitual.",
Expand Down
3 changes: 3 additions & 0 deletions app/src/main/java/com/pulseloop/PulseLoopApplication.kt
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ class PulseLoopApplication : Application() {
override fun onCreate() {
super.onCreate()
CrashLogger.install(this)
// Before any sync can read them: Bedtime tracking no longer needs the schedule (issue #126),
// so a Bedtime flag left on under a switched-off schedule is cleared rather than reread.
com.pulseloop.settings.QuietHoursPrefs.migrateIndependentBedtime(this)
com.pulseloop.service.DrinkPrefs.init(this)
com.pulseloop.service.Postpartum.init(this)
com.pulseloop.service.LabPrefs.init(this)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -606,13 +606,12 @@ class EventPersistenceSubscriber(
// judged by its start, because the ring often runs the sofa hour and the real night as one
// record. Already-imported nights are untouched (this never deletes), and the gate is read
// per record so a settings change takes effect on the next packet, not the next launch.
val quiet = QuietHoursPrefs(context)
if (quiet.enabled) {
val kept = quiet.keptMinutesForRecord(effectiveTs, effectiveStages.size, context)
?: return
effectiveTs = effectiveTs + kept.first * 60_000L
effectiveStages = effectiveStages.subList(kept.first, kept.last + 1)
}
// The schedule and Bedtime tracking are independent (issue #126); with neither on this
// keeps the whole record.
val kept = QuietHoursPrefs(context).keptMinutesForRecord(effectiveTs, effectiveStages.size, context)
?: return
effectiveTs = effectiveTs + kept.first * 60_000L
effectiveStages = effectiveStages.subList(kept.first, kept.last + 1)

// Sleep record deletion gate: drop if the user deleted this entire record (issue #78, #82)
val dayStart = com.pulseloop.util.TimeUtil.wakingDayLocal(effectiveTs)
Expand Down
48 changes: 18 additions & 30 deletions app/src/main/java/com/pulseloop/service/SleepGapBridge.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@ package com.pulseloop.service
import android.content.Context
import com.pulseloop.data.entity.SleepStageBlockEntity
import com.pulseloop.settings.QuietHoursPrefs
import com.pulseloop.settings.ZenModeListener
import com.pulseloop.settings.ZenModeTracker
import com.pulseloop.settings.ZenWindow
import com.pulseloop.util.TimeUtil
import java.time.ZoneId

/**
Expand Down Expand Up @@ -38,52 +35,43 @@ fun interface SleepGapBridge {
/** The bridge for the user's current quiet-hours settings. Reads them once. */
fun fromSettings(context: Context): SleepGapBridge {
val prefs = QuietHoursPrefs(context)
val zenWindows = if (prefs.gateByZenMode && ZenModeListener.isAccessGranted(context)) {
ZenModeTracker.getWindows(context)
} else {
null
}
return forWindows(prefs.enabled, zenWindows, prefs.startMinutes, prefs.endMinutes)
return forWindows(
prefs.enabled,
QuietHoursPrefs.activeBedtimeWindows(prefs, context),
prefs.startMinutes,
prefs.endMinutes,
)
}

/**
* The same source order as the import gate ([QuietHoursPrefs.keptMinutesForRecord]): off
* unless quiet hours are on; the recorded Bedtime/DND windows when that gating is on and the
* night has any; otherwise the clock window. A night that has Bedtime windows is judged by
* them alone, so a gap after Bedtime ended is not bridged by a wider clock schedule.
* The same source order as the import gate ([QuietHoursPrefs.resolveKeptMinutes]): the
* recorded Bedtime/DND windows when that tracking is on and the night has any; otherwise
* the clock window if the schedule is on; otherwise nothing is bridged. A night that has
* Bedtime windows is judged by them alone, so a gap after Bedtime ended is not bridged by a
* wider clock schedule. Bedtime tracking bridges with the schedule off (issue #126), as
* the import gate trims with it off.
*
* [zenWindows] is null when Bedtime gating is off.
* [zenWindows] is null when Bedtime tracking is off.
*/
fun forWindows(
enabled: Boolean,
scheduleEnabled: Boolean,
zenWindows: List<ZenWindow>?,
startMinutes: Int,
endMinutes: Int,
zone: ZoneId = ZoneId.systemDefault(),
): SleepGapBridge {
if (!enabled) return NONE
if (!scheduleEnabled && zenWindows == null) return NONE
return SleepGapBridge { gapStart, gapEnd ->
if (gapEnd <= gapStart) return@SleepGapBridge false
val night = zenWindows?.let { nightWindows(it, gapStart, zone) }.orEmpty()
val night = zenWindows?.let { QuietHoursPrefs.nightWindows(it, gapStart, zone) }.orEmpty()
if (night.isNotEmpty()) {
night.any { w -> w.start <= gapStart && gapEnd <= effectiveEnd(w) }
night.any { w -> w.start <= gapStart && gapEnd <= QuietHoursPrefs.effectiveEnd(w) }
} else {
clockCovers(gapStart, gapEnd, startMinutes, endMinutes, zone)
scheduleEnabled && clockCovers(gapStart, gapEnd, startMinutes, endMinutes, zone)
}
}
}

/** The windows of the waking day [ts] falls in — the span the import gate reads too. */
private fun nightWindows(windows: List<ZenWindow>, ts: Long, zone: ZoneId): List<ZenWindow> {
val wakingDay = TimeUtil.wakingDayLocal(ts, zone)
val dayStart = wakingDay - 12 * 3_600_000L
val dayEnd = wakingDay + 36 * 3_600_000L
return windows.filter { w -> effectiveEnd(w) > dayStart && w.start < dayEnd }
}

private fun effectiveEnd(w: ZenWindow): Long =
w.end ?: (w.start + ZenModeTracker.MAX_WINDOW_DURATION_MS)

/**
* Every minute of the gap inside the daily clock window. A gap of a day or more never is, and
* neither is anything under a window whose start equals its end: for the import gate that
Expand Down
Loading
Loading