calendar: add compact week layouts with a variable hour scale
- Commit
c1fb44e9e4210cac634bb82e74b4a70bf5708b30- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-05 19:25 UTC (4 months ago)
- Parents
bd3eca7
Diff
calendar/src/main/java/com/vayunmathur/calendar/ui/CalendarScreen.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/ui/CalendarScreen.kt b/calendar/src/main/java/com/vayunmathur/calendar/ui/CalendarScreen.ktindex 60ebba40dd..df69dfe831 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/ui/CalendarScreen.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/ui/CalendarScreen.kt@@ -54,11 +54,9 @@ import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.graphics.Color-import androidx.compose.ui.layout.onGloballyPositioned-import androidx.compose.ui.layout.positionInParent import androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp@@ -83,6 +81,7 @@ import kotlinx.datetime.TimeZone import kotlinx.datetime.atStartOfDayIn import com.vayunmathur.library.util.localizedMonthNames import com.vayunmathur.library.util.localizedDayOfWeekNames+import com.vayunmathur.library.util.localeFirstDayOfWeek import kotlinx.datetime.isoDayNumber import kotlinx.datetime.minus import kotlinx.datetime.number@@ -90,27 +89,13 @@ import kotlinx.datetime.plus import kotlinx.datetime.toLocalDateTime import kotlinx.datetime.format import kotlinx.datetime.todayIn-import androidx.core.text.util.LocalePreferences import java.util.Locale import kotlin.time.Clock import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant -private fun getFirstDayOfWeekValue(locale: Locale): Int {- return when (LocalePreferences.getFirstDayOfWeek(locale)) {- LocalePreferences.FirstDayOfWeek.MONDAY -> 1- LocalePreferences.FirstDayOfWeek.TUESDAY -> 2- LocalePreferences.FirstDayOfWeek.WEDNESDAY -> 3- LocalePreferences.FirstDayOfWeek.THURSDAY -> 4- LocalePreferences.FirstDayOfWeek.FRIDAY -> 5- LocalePreferences.FirstDayOfWeek.SATURDAY -> 6- LocalePreferences.FirstDayOfWeek.SUNDAY -> 7- else -> 7- }-}- private fun firstDayOfWeekOffset(date: LocalDate, locale: Locale): Int {- val firstDayOfWeek = getFirstDayOfWeekValue(locale)+ val firstDayOfWeek = localeFirstDayOfWeek(locale) return (date.dayOfWeek.isoDayNumber - firstDayOfWeek + 7) % 7 } @@ -281,11 +266,15 @@ fun CalendarPagerView( ) { val daysToShow = when (currentLayout) { CalendarViewModel.CalendarLayout.Day -> 1- CalendarViewModel.CalendarLayout.WorkWeek, CalendarViewModel.CalendarLayout.WorkWeekSummary -> 5+ CalendarViewModel.CalendarLayout.WorkWeek,+ CalendarViewModel.CalendarLayout.WorkWeekSummary,+ CalendarViewModel.CalendarLayout.WorkWeekCompact -> 5 else -> 7 } val isSummary = currentLayout == CalendarViewModel.CalendarLayout.WorkWeekSummary || currentLayout == CalendarViewModel.CalendarLayout.FullWeekSummary+ val isCompact = currentLayout == CalendarViewModel.CalendarLayout.WorkWeekCompact ||+ currentLayout == CalendarViewModel.CalendarLayout.FullWeekCompact val pagerState = rememberPagerState(initialPage = 5000) { 10000 } // Track whether the pager is being programmatically scrolled to avoid feedback loops@@ -318,101 +307,63 @@ fun CalendarPagerView( } } - Row(Modifier.fillMaxSize()) {- var yOffset by remember { mutableStateOf(0.dp) }- val density = LocalDensity.current-- if (!isSummary) {- // Static Hour labels column- Column {- Spacer(Modifier.height(yOffset))- Column(- Modifier- .verticalScroll(verticalState)- .padding(bottom = 16.dp)- ) {- for (hour in 0..23) {- Box(modifier = Modifier- .height(56.dp)- .width(56.dp)) {- val hourString = if(DateFormat.is24HourFormat(context)) {- "%02d:00".format(hour)- } else when {- hour == 0 -> context.getString(R.string.twelve_am)- hour < 12 -> context.getString(R.string.hour_am, hour)- hour == 12 -> context.getString(R.string.twelve_pm)- else -> context.getString(R.string.hour_pm, hour - 12)- }- Text(- text = hourString,- modifier = Modifier.padding(start = 8.dp),- style = MaterialTheme.typography.labelSmall- )- }- }- }+ HorizontalPager(+ state = pagerState,+ modifier = Modifier.fillMaxSize(),+ beyondViewportPageCount = 1+ ) { page ->+ val delta = page - 5000+ val pageStartDate = if (daysToShow == 1) {+ anchorDate.plus(DatePeriod(days = delta))+ } else {+ anchorDate.plus(DatePeriod(days = delta * 7))+ }+ + val startDay = when (currentLayout) {+ CalendarViewModel.CalendarLayout.Day -> pageStartDate+ CalendarViewModel.CalendarLayout.WorkWeek,+ CalendarViewModel.CalendarLayout.WorkWeekSummary,+ CalendarViewModel.CalendarLayout.WorkWeekCompact ->+ pageStartDate.minus(DatePeriod(days = (pageStartDate.dayOfWeek.isoDayNumber - 1) % 7))+ else -> {+ val locale = context.resources.configuration.locales[0]+ pageStartDate.minus(DatePeriod(days = firstDayOfWeekOffset(pageStartDate, locale))) } }+ + val weekDays = (0 until daysToShow).map { startDay.plus(DatePeriod(days = it)) }+ val vEventsByID = remember(events) { events.associateBy { it.id!! } } - HorizontalPager(- state = pagerState,- modifier = Modifier.weight(1f),- beyondViewportPageCount = 1- ) { page ->- val delta = page - 5000- val pageStartDate = if (daysToShow == 1) {- anchorDate.plus(DatePeriod(days = delta))- } else {- anchorDate.plus(DatePeriod(days = delta * 7))- }+ val weekInstances by produceState(emptyList<Instance>(), events, calendarVisibility, startDay, daysToShow) {+ value = loadInstances(+ weekDays.first().atStartOfDayIn(TimeZone.currentSystemDefault()),+ weekDays.last().atEndOfDayIn(TimeZone.currentSystemDefault())+ )+ }++ Column(Modifier.fillMaxSize()) {+ WeekHeader(weekDays, leadingGutter = !isSummary) - val startDay = when (currentLayout) {- CalendarViewModel.CalendarLayout.Day -> pageStartDate- CalendarViewModel.CalendarLayout.WorkWeek, CalendarViewModel.CalendarLayout.WorkWeekSummary -> - pageStartDate.minus(DatePeriod(days = (pageStartDate.dayOfWeek.isoDayNumber - 1) % 7))- else -> {- val locale = context.resources.configuration.locales[0]- pageStartDate.minus(DatePeriod(days = firstDayOfWeekOffset(pageStartDate, locale)))+ if (isSummary) {+ SummaryGrid(context, weekInstances, vEventsByID, calendars, weekDays, onEventClick)+ } else {+ val (allDay, notAllDay) = weekInstances.partition { it.allDay }+ val allDayByDate = weekDays.associateWith { d -> allDay.filter { d in it.spanDays } }+ val timedByDateHour = weekDays.associateWith { d ->+ notAllDay.filter { d in it.spanDays }.groupBy { it.startDateTime.hour } }- }- - val weekDays = (0 until daysToShow).map { startDay.plus(DatePeriod(days = it)) }- val vEventsByID = remember(events) { events.associateBy { it.id!! } } - val weekInstances by produceState(emptyList<Instance>(), events, calendarVisibility, startDay, daysToShow) {- value = loadInstances(- weekDays.first().atStartOfDayIn(TimeZone.currentSystemDefault()),- weekDays.last().atEndOfDayIn(TimeZone.currentSystemDefault())+ AllDayRow(allDayByDate, vEventsByID, calendars, weekDays, onEventClick)+ HourlyGrid(+ context,+ timedByDateHour,+ weekDays,+ verticalState,+ shrinkEmptyHours = isCompact,+ onEventClick = onEventClick,+ innerPadding = PaddingValues(0.dp) ) }-- Column(Modifier.fillMaxSize()) {- WeekHeader(weekDays)- - if (isSummary) {- SummaryGrid(context, weekInstances, vEventsByID, calendars, weekDays, onEventClick)- } else {- val (allDay, notAllDay) = weekInstances.partition { it.allDay }- val allDayByDate = weekDays.associateWith { d -> allDay.filter { d in it.spanDays } }- val timedByDateHour = weekDays.associateWith { d ->- notAllDay.filter { d in it.spanDays }.groupBy { it.startDateTime.hour }- }-- AllDayRow(allDayByDate, vEventsByID, calendars, weekDays, onEventClick)- Spacer(Modifier.onGloballyPositioned {- if (page == pagerState.currentPage) {- yOffset = with(density) { it.positionInParent().y.toDp() }- }- })- HourlyGrid(- timedByDateHour,- weekDays,- verticalState,- onEventClick,- PaddingValues(0.dp)- )- }- } } } }@@ -543,7 +494,7 @@ fun MonthView( val lastOfMonth = firstOfMonth.plus(DatePeriod(months = 1)).minus(DatePeriod(days = 1)) val locale = context.resources.configuration.locales[0]- val firstDayOfWeek = getFirstDayOfWeekValue(locale)+ val firstDayOfWeek = localeFirstDayOfWeek(locale) val lastDayOfWeek = if (firstDayOfWeek == 1) 7 else firstDayOfWeek - 1 val startDay = firstOfMonth.minus(DatePeriod(days = firstDayOfWeekOffset(firstOfMonth, locale)))@@ -732,10 +683,14 @@ fun LocalDate.atEndOfDayIn(currentSystemDefault: TimeZone): Instant { return this.plus(DatePeriod(days = 1)).atStartOfDayIn(currentSystemDefault) } +/** Width of the hour-label gutter down the left of the day/week grid. */+private val HourGutterWidth = 56.dp+ @Composable-private fun WeekHeader(weekDays: List<LocalDate>) {+private fun WeekHeader(weekDays: List<LocalDate>, leadingGutter: Boolean) { val today = remember { Clock.System.todayIn(TimeZone.currentSystemDefault()) } Row(modifier = Modifier.fillMaxWidth(), Arrangement.spacedBy(4.dp)) {+ if (leadingGutter) Spacer(Modifier.width(HourGutterWidth)) weekDays.forEach { d -> val isToday = d == today Column(@@ -774,6 +729,7 @@ private fun AllDayRow( onEventClick: (Instance) -> Unit ) { Row(Modifier.fillMaxWidth(), Arrangement.spacedBy(4.dp)) {+ Spacer(Modifier.width(HourGutterWidth)) weekDays.forEach { d -> val instances = allDayByDate[d].orEmpty() Column(Modifier.weight(1f)) {@@ -813,14 +769,14 @@ private fun AllDayRow( @Composable private fun HourlyGrid(+ context: android.content.Context, timedByDateHour: Map<LocalDate, Map<Int, List<Instance>>>, weekDays: List<LocalDate>, verticalState: ScrollState,+ shrinkEmptyHours: Boolean, onEventClick: (Instance) -> Unit, innerPadding: PaddingValues ) {- // Each hour row height- val hourRowHeight = 56.dp val minEventHeight = 18.dp val minEventWidth = 56.dp @@ -834,91 +790,103 @@ private fun HourlyGrid( } } - Row(- Modifier- .fillMaxSize()- .verticalScroll(verticalState)- .padding(bottom = innerPadding.calculateBottomPadding()).padding(bottom = 4.dp), Arrangement.spacedBy(4.dp)- ) {- // create 7 equal columns with weight so all 7 fit on screen- for (d in weekDays) {- val isToday = d == today- // collect unique timed events for this day (timedByDateHour groups by hour)- val eventsForDay = timedByDateHour[d]?.values?.flatten().orEmpty().distinctBy { it.id }+ val eventsByDay = weekDays.associateWith { d ->+ timedByDateHour[d]?.values?.flatten().orEmpty().distinctBy { it.id }+ }+ val positionedByDay = eventsByDay.mapValues { (d, events) -> computePositionedEventsForDay(events, d) }++ BoxWithConstraints(Modifier.fillMaxSize()) {+ val bottomPadding = innerPadding.calculateBottomPadding() + 4.dp+ // One scale for the whole page: the columns share the hour gutter, so a shrunk hour has to+ // be shrunk on every day at once.+ val scale = if (shrinkEmptyHours) {+ HourScale.collapsingEmptyHours(busyHours(positionedByDay.values.flatten()), maxHeight - bottomPadding)+ } else {+ HourScale.uniform()+ } - Box(Modifier.weight(1f).clip(RoundedCornerShape(16.dp)).background(if (isToday) MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.15f) else MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.25f))) {- // background hourly grid — fixed 24 rows with faint hour separators- Column {- for (hour in 0..23) {- Box(- Modifier- .height(hourRowHeight)- .fillMaxWidth()- ) {- if (hour != 0) {- HorizontalDivider(- Modifier.align(Alignment.TopStart),- color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)- )+ Row(+ Modifier+ .fillMaxSize()+ .verticalScroll(verticalState)+ .padding(bottom = bottomPadding), Arrangement.spacedBy(4.dp)+ ) {+ HourLabelColumn(context, scale)++ // create 7 equal columns with weight so all 7 fit on screen+ for (d in weekDays) {+ val isToday = d == today++ Box(Modifier.weight(1f).clip(RoundedCornerShape(16.dp)).background(if (isToday) MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.15f) else MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.25f))) {+ // background hourly grid — fixed 24 rows with faint hour separators+ Column {+ for (hour in 0..23) {+ Box(+ Modifier+ .height(scale.heightOf(hour))+ .fillMaxWidth()+ ) {+ if (hour != 0) {+ HorizontalDivider(+ Modifier.align(Alignment.TopStart),+ color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)+ )+ } } } }- }-- if (isToday) {- val minutesPassed = now.hour * 60 + now.minute- val yOffset = hourRowHeight * (minutesPassed.toFloat() / 60f)- Box(- Modifier- .offset(y = yOffset - 1.dp)- .fillMaxWidth()- .height(2.dp)- .background(Color.Red)- .zIndex(10f)- )- } - // compute positioned events using the helper that assigns columns for overlaps- val positioned = computePositionedEventsForDay(eventsForDay, d)- val instancesById = remember(eventsForDay) { eventsForDay.associateBy { it.id } }+ if (isToday) {+ val yOffset = scale.offsetOf(now.hour * 60 + now.minute)+ Box(+ Modifier+ .offset(y = yOffset - 1.dp)+ .fillMaxWidth()+ .height(2.dp)+ .background(Color.Red)+ .zIndex(10f)+ )+ } - // overlay event segments positioned by their time within the day and column- BoxWithConstraints(Modifier.fillMaxWidth()) {- val columnWidth = this.maxWidth+ val positioned = positionedByDay.getValue(d)+ val eventsForDay = eventsByDay.getValue(d)+ val instancesById = remember(eventsForDay) { eventsForDay.associateBy { it.id } } - positioned.forEach { ev ->- val instance = instancesById.getValue(ev.instanceID)- // compute vertical position and height- val startHours = ev.startMinutes.toFloat() / 60f- val lengthHours = (ev.endMinutes - ev.startMinutes).toFloat() / 60f+ // overlay event segments positioned by their time within the day and column+ BoxWithConstraints(Modifier.fillMaxWidth()) {+ val columnWidth = this.maxWidth - val yOffset = hourRowHeight * startHours- var heightDp = hourRowHeight * lengthHours- if (heightDp < minEventHeight) heightDp = minEventHeight+ positioned.forEach { ev ->+ val instance = instancesById.getValue(ev.instanceID)+ // compute vertical position and height+ val yOffset = scale.offsetOf(ev.startMinutes)+ var heightDp = scale.offsetOf(ev.endMinutes) - yOffset+ if (heightDp < minEventHeight) heightDp = minEventHeight - // compute horizontal position and size- val widthFraction = 1f / ev.totalColumns.toFloat()- val xFraction = ev.columnIndex * widthFraction- val xOffsetDp = columnWidth * xFraction- val widthDp = (columnWidth * widthFraction).coerceAtLeast(minEventWidth)+ // compute horizontal position and size+ val widthFraction = 1f / ev.totalColumns.toFloat()+ val xFraction = ev.columnIndex * widthFraction+ val xOffsetDp = columnWidth * xFraction+ val widthDp = (columnWidth * widthFraction).coerceAtLeast(minEventWidth) - Box(- Modifier- .offset(xOffsetDp, yOffset)- .size(widthDp, heightDp)- .padding(2.dp)- .zIndex(1f + ev.columnIndex * 0.01f)- .clip(RoundedCornerShape(10.dp))- .background(Color(ev.color))- .clickable { onEventClick(instance) }- ) {- Text(- ev.title.ifEmpty { stringResource(R.string.no_title) },- Modifier.padding(6.dp),- Color.White,- maxLines = 2,- fontSize = 12.sp- )+ Box(+ Modifier+ .offset(xOffsetDp, yOffset)+ .size(widthDp, heightDp)+ .padding(2.dp)+ .zIndex(1f + ev.columnIndex * 0.01f)+ .clip(RoundedCornerShape(10.dp))+ .background(Color(ev.color))+ .clickable { onEventClick(instance) }+ ) {+ Text(+ ev.title.ifEmpty { stringResource(R.string.no_title) },+ Modifier.padding(6.dp),+ Color.White,+ maxLines = 2,+ fontSize = 12.sp+ )+ } } } }@@ -926,3 +894,35 @@ private fun HourlyGrid( } } }++/**+ * The hour gutter. It lives inside the grid's scroll container so it stays pinned to the rows+ * it labels even when [scale] gives them different heights.+ */+@Composable+private fun HourLabelColumn(context: android.content.Context, scale: HourScale) {+ Column {+ for (hour in 0..23) {+ Box(+ Modifier+ .height(scale.heightOf(hour))+ .width(HourGutterWidth)+ .clipToBounds()+ ) {+ val hourString = if (DateFormat.is24HourFormat(context)) {+ "%02d:00".format(hour)+ } else when {+ hour == 0 -> context.getString(R.string.twelve_am)+ hour < 12 -> context.getString(R.string.hour_am, hour)+ hour == 12 -> context.getString(R.string.twelve_pm)+ else -> context.getString(R.string.hour_pm, hour - 12)+ }+ Text(+ text = hourString,+ modifier = Modifier.padding(start = 8.dp),+ style = MaterialTheme.typography.labelSmall+ )+ }+ }+ }+}
calendar/src/main/java/com/vayunmathur/calendar/ui/HourScale.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/ui/HourScale.kt b/calendar/src/main/java/com/vayunmathur/calendar/ui/HourScale.ktnew file mode 100644index 0000000000..57c4e4c493--- /dev/null+++ b/calendar/src/main/java/com/vayunmathur/calendar/ui/HourScale.kt@@ -0,0 +1,62 @@+package com.vayunmathur.calendar.ui++import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp++private val FULL_HOUR_HEIGHT = 56.dp+private val MIN_FULL_HOUR_HEIGHT = 28.dp+private val COLLAPSED_HOUR_HEIGHT = 18.dp++/**+ * The vertical axis of the day/week grid: how tall each of the 24 hour rows is, and where any+ * minute of the day lands on it. Rows are not necessarily equal — the compact week view keeps+ * hours that contain events readable and squeezes the rest — so callers must map times through+ * [offsetOf] rather than multiplying by a single hour height.+ */+data class HourScale(val rowHeights: List<Dp>) {+ private val offsets: List<Dp> = buildList(25) {+ var acc = 0.dp+ add(acc)+ for (height in rowHeights) {+ acc += height+ add(acc)+ }+ }++ fun heightOf(hour: Int): Dp = rowHeights[hour]++ /** Where [minuteOfDay] (0..1440) sits, measured from the top of the grid. */+ fun offsetOf(minuteOfDay: Int): Dp {+ val minute = minuteOfDay.coerceIn(0, 24 * 60)+ val hour = minute / 60+ if (hour == 24) return offsets[24]+ return offsets[hour] + rowHeights[hour] * ((minute % 60) / 60f)+ }++ companion object {+ fun uniform(): HourScale = HourScale(List(24) { FULL_HOUR_HEIGHT })++ /**+ * Hours in [busyHours] stay as tall as [available] allows; the rest shrink to a thin+ * strip, so a whole day fits on screen unless it is packed edge to edge.+ */+ fun collapsingEmptyHours(busyHours: Set<Int>, available: Dp): HourScale {+ val slack = available - COLLAPSED_HOUR_HEIGHT * (24 - busyHours.size)+ val fullHeight = if (busyHours.isEmpty()) FULL_HOUR_HEIGHT+ else (slack / busyHours.size).coerceIn(MIN_FULL_HOUR_HEIGHT, FULL_HOUR_HEIGHT)+ return HourScale(List(24) { if (it in busyHours) fullHeight else COLLAPSED_HOUR_HEIGHT })+ }+ }+}++/**+ * Every hour any of [events] overlaps — not just the hour each one starts in, so a 09:30–11:30+ * meeting keeps 10:00 at full height too.+ */+fun busyHours(events: List<PositionedEvent>): Set<Int> = buildSet {+ for (event in events) {+ // An event ending exactly on the hour does not occupy that hour.+ val last = ((event.endMinutes - 1) / 60).coerceAtMost(23)+ for (hour in (event.startMinutes / 60)..last) add(hour)+ }+}
calendar/src/main/java/com/vayunmathur/calendar/util/CalendarViewModel.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/util/CalendarViewModel.kt b/calendar/src/main/java/com/vayunmathur/calendar/util/CalendarViewModel.ktindex d2bd35e963..97958ff3fd 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/util/CalendarViewModel.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/util/CalendarViewModel.kt@@ -57,7 +57,9 @@ class CalendarViewModel(application: Application) : FullWeek(R.string.layout_short_full_week, R.string.layout_full_week), Month(R.string.layout_short_month, R.string.layout_month), WorkWeekSummary(R.string.layout_short_work_week_summary, R.string.layout_work_week_summary),- FullWeekSummary(R.string.layout_short_full_week_summary, R.string.layout_full_week_summary)+ FullWeekSummary(R.string.layout_short_full_week_summary, R.string.layout_full_week_summary),+ WorkWeekCompact(R.string.layout_short_work_week_compact, R.string.layout_work_week_compact),+ FullWeekCompact(R.string.layout_short_full_week_compact, R.string.layout_full_week_compact) } private val _currentLayout = MutableStateFlow(
calendar/src/main/res/values/strings.xml
diff --git a/calendar/src/main/res/values/strings.xml b/calendar/src/main/res/values/strings.xmlindex dafd5bcc82..f8c9f24fe2 100644--- a/calendar/src/main/res/values/strings.xml+++ b/calendar/src/main/res/values/strings.xml@@ -17,6 +17,10 @@ <string name="layout_work_week_summary">Work Week Summary</string> <!-- Main calendar: Summary of full week events --> <string name="layout_full_week_summary">Full Week Summary</string>+ <!-- Main calendar: Work week hourly grid where hours with no events are shrunk so the whole day fits without scrolling -->+ <string name="layout_work_week_compact">Work Week Compact</string>+ <!-- Main calendar: Full week hourly grid where hours with no events are shrunk so the whole day fits without scrolling -->+ <string name="layout_full_week_compact">Full Week Compact</string> <!-- Layout picker: short single-letter abbreviation for Agenda (keep very short) --> <string name="layout_short_agenda">A</string> <!-- Layout picker: short abbreviation for Day -->@@ -31,6 +35,10 @@ <string name="layout_short_work_week_summary">W5S</string> <!-- Layout picker: short abbreviation for Full Week Summary (7-day summary) --> <string name="layout_short_full_week_summary">W7S</string>+ <!-- Layout picker: short abbreviation for Work Week Compact (5-day compact) -->+ <string name="layout_short_work_week_compact">W5C</string>+ <!-- Layout picker: short abbreviation for Full Week Compact (7-day compact) -->+ <string name="layout_short_full_week_compact">W7C</string> <!-- Theme settings: ThemeMode enum labels --> <!-- Settings: follow system light/dark theme -->
calendar/src/test/java/com/vayunmathur/calendar/ui/HourScaleTest.kt
diff --git a/calendar/src/test/java/com/vayunmathur/calendar/ui/HourScaleTest.kt b/calendar/src/test/java/com/vayunmathur/calendar/ui/HourScaleTest.ktnew file mode 100644index 0000000000..aee4828a39--- /dev/null+++ b/calendar/src/test/java/com/vayunmathur/calendar/ui/HourScaleTest.kt@@ -0,0 +1,64 @@+package com.vayunmathur.calendar.ui++import androidx.compose.ui.unit.dp+import org.junit.Assert.assertEquals+import org.junit.Test++class HourScaleTest {+ private fun event(startMinutes: Int, endMinutes: Int) = PositionedEvent(+ instanceID = 1,+ eventID = 1,+ title = "",+ color = 0,+ startMinutes = startMinutes,+ endMinutes = endMinutes,+ columnIndex = 0,+ totalColumns = 1,+ )++ @Test+ fun `busy hours cover every hour an event spans`() {+ assertEquals(setOf(9, 10, 11), busyHours(listOf(event(9 * 60 + 30, 11 * 60 + 30))))+ }++ @Test+ fun `an event ending on the hour does not claim that hour`() {+ assertEquals(setOf(9), busyHours(listOf(event(9 * 60, 10 * 60))))+ }++ @Test+ fun `uniform scale places a time at its proportional offset`() {+ val scale = HourScale.uniform()+ assertEquals(56.dp * 9.5f, scale.offsetOf(9 * 60 + 30))+ assertEquals(56.dp * 24f, scale.offsetOf(24 * 60))+ }++ @Test+ fun `collapsed hours compress the offsets before them`() {+ // Only 09:00 is busy, so hours 0..8 are collapsed to 18dp each.+ val scale = HourScale.collapsingEmptyHours(setOf(9), available = 1000.dp)+ assertEquals(18.dp * 9f, scale.offsetOf(9 * 60))+ assertEquals(18.dp * 9f + scale.heightOf(9) / 2f, scale.offsetOf(9 * 60 + 30))+ }++ @Test+ fun `a full hour never grows past its natural height`() {+ val scale = HourScale.collapsingEmptyHours(setOf(9), available = 10_000.dp)+ assertEquals(56.dp, scale.heightOf(9))+ }++ @Test+ fun `full hours shrink to fit the available height`() {+ val busy = (0..11).toSet()+ // 12 collapsed hours take 216dp, leaving 480dp to split across the 12 busy ones.+ val scale = HourScale.collapsingEmptyHours(busy, available = 696.dp)+ assertEquals(40.dp, scale.heightOf(0))+ assertEquals(696.dp, scale.offsetOf(24 * 60))+ }++ @Test+ fun `full hours stop shrinking once they would be unreadable`() {+ val scale = HourScale.collapsingEmptyHours((0..11).toSet(), available = 300.dp)+ assertEquals(28.dp, scale.heightOf(0))+ }+}
games/voxels/src/main/rust/src/container.rs
diff --git a/games/voxels/src/main/rust/src/container.rs b/games/voxels/src/main/rust/src/container.rsindex 30c08c2663..af20133a53 100644--- a/games/voxels/src/main/rust/src/container.rs+++ b/games/voxels/src/main/rust/src/container.rs@@ -95,7 +95,7 @@ impl Containers { } fn container_file(base: &str) -> PathBuf {- Path::new(base).join("voxels").join("worlds").join("default").join("containers.json")+ Path::new(base).join("containers.json") } // Deterministic loot for a world-generated chest, from its position. The End's chests hold the
games/voxels/src/main/rust/src/engine.rs
diff --git a/games/voxels/src/main/rust/src/engine.rs b/games/voxels/src/main/rust/src/engine.rsindex 20efe65cfc..12725bdc76 100644--- a/games/voxels/src/main/rust/src/engine.rs+++ b/games/voxels/src/main/rust/src/engine.rs@@ -220,16 +220,13 @@ pub fn init_engine(files_dir: String, seed: u32) -> bool { let mut dim_visited = [false; 3]; for (i, v) in progress.dim_visited.iter().enumerate().take(3) { dim_visited[i] = *v; } dim_visited[dim as usize] = true;- // Crafted recipes, unpacked from the saved bitmask. Saves written before the tech tree existed- // carry only the old ingredient-based "discovered" set; seed from that so a returning player- // keeps the access they had rather than being sent back to the roots.+ // Crafted recipes, unpacked from the saved bitmask. let mut crafted_recipes = vec![false; crate::inventory::RECIPES.len()];- let bit = |bits: &[u8], i: usize| bits.get(i / 8).is_some_and(|b| b & (1 << (i % 8)) != 0); for (i, c) in crafted_recipes.iter_mut().enumerate() {- *c = bit(&progress.crafted_recipes, i) || bit(&progress.known_recipes, i);+ *c = progress.crafted_recipes.get(i / 8).is_some_and(|b| b & (1 << (i % 8)) != 0); } - // Trade counts are stored as a Vec so old saves load; a short or long one is padded/truncated.+ // A Vec rather than a fixed array so adding a profession doesn't invalidate a save mid-development. let mut trades_done = [0u32; crate::villager::ALL.len()]; for (i, n) in progress.trades_done.iter().enumerate().take(trades_done.len()) { trades_done[i] = *n; } @@ -353,7 +350,6 @@ pub fn destroy_engine() { } bits },- known_recipes: Vec::new(), }, }; let _ = crate::world::save::save_player(&state.save_dir, &ps);
games/voxels/src/main/rust/src/raycast.rs
diff --git a/games/voxels/src/main/rust/src/raycast.rs b/games/voxels/src/main/rust/src/raycast.rsindex ae5f6e9c5c..b77be4d6ad 100644--- a/games/voxels/src/main/rust/src/raycast.rs+++ b/games/voxels/src/main/rust/src/raycast.rs@@ -1,5 +1,5 @@ use glam::Vec3;-use crate::world::{ChunkMap, block::{Aabb, Block, Shape}};+use crate::world::{ChunkMap, block::{Block, Shape}}; #[derive(Debug, Clone, Copy)] pub struct HitResult { pub pos: (i32,i32,i32), pub prev: (i32,i32,i32), pub normal: (i32,i32,i32), pub dist: f32 }
games/voxels/src/main/rust/src/villager.rs
diff --git a/games/voxels/src/main/rust/src/villager.rs b/games/voxels/src/main/rust/src/villager.rsindex 18db06ce07..461f02c472 100644--- a/games/voxels/src/main/rust/src/villager.rs+++ b/games/voxels/src/main/rust/src/villager.rs@@ -256,7 +256,7 @@ pub fn give_count(offer: &Offer) -> i32 { #[cfg(test)] mod tests { use super::*;- use crate::world::block::{is_real_id, MAX_LOW_BLOCK_ID};+ use crate::world::block::is_real_id; // A typo in a trade table is invisible until a player taps it and receives Air, so every id in // every tier of every profession gets checked.
games/voxels/src/main/rust/src/world/chunk_map.rs
diff --git a/games/voxels/src/main/rust/src/world/chunk_map.rs b/games/voxels/src/main/rust/src/world/chunk_map.rsindex a8b9f46fa9..e5197f968a 100644--- a/games/voxels/src/main/rust/src/world/chunk_map.rs+++ b/games/voxels/src/main/rust/src/world/chunk_map.rs@@ -56,7 +56,7 @@ impl ChunkMap { if !loaded { self.gen.fill_chunk(&mut chunk); }- // Water below sea level, for freshly generated AND older saved chunks (idempotent).+ // Water below sea level, for freshly generated and loaded chunks alike (idempotent). self.gen.ensure_water(&mut chunk); self.chunks.insert(pos, chunk); }
games/voxels/src/main/rust/src/world/save.rs
diff --git a/games/voxels/src/main/rust/src/world/save.rs b/games/voxels/src/main/rust/src/world/save.rsindex 720d89caf4..188dab7b0f 100644--- a/games/voxels/src/main/rust/src/world/save.rs+++ b/games/voxels/src/main/rust/src/world/save.rs@@ -2,8 +2,10 @@ use super::chunk::{Chunk, ChunkPos, SECTIONS_PER_CHUNK}; use std::fs; use std::path::{Path, PathBuf}; +// `base` is already the world's own directory (MainActivity passes it in), so everything below sits+// directly inside it. fn region_dir(base: &str) -> PathBuf {- Path::new(base).join("voxels").join("worlds").join("default").join("regions")+ Path::new(base).join("regions") } fn chunk_file(base: &str, pos: ChunkPos) -> PathBuf { region_dir(base).join(format!("c_{}_{}.dat", pos.0, pos.1))@@ -40,47 +42,34 @@ pub fn load_chunk(base: &str, _pos: ChunkPos, chunk: &mut Chunk) -> std::io::Res let path = chunk_file(base, chunk.pos); decode_chunk(&fs::read(&path)?, chunk) }-// Reads VOX1, VOX2 and VOX3. Older chunks upgrade losslessly: a VOX1 chunk holds only full cubes,-// which is exactly what meta 0 means, and narrow block bytes widen into the same numbers. Rejecting-// an old file instead would make `load_or_gen` treat the chunk as ungenerated and regenerate it from-// the seed, erasing the player's build.+// Reads the one format there is. A decode error makes `load_or_gen` treat the chunk as ungenerated+// and regenerate it from the seed, erasing whatever the player built there, so `Err` has to mean the+// bytes genuinely are not a chunk. fn decode_chunk(bytes: &[u8], chunk: &mut Chunk) -> std::io::Result<()> { let bad = |m: &'static str| std::io::Error::new(std::io::ErrorKind::InvalidData, m); if bytes.len() < 5 { return Err(bad("too small")); }- let (wide_ids, has_meta_flags) = match &bytes[0..4] {- b"VOX1" => (false, false),- b"VOX2" => (false, true),- b"VOX3" => (true, true),- _ => return Err(bad("bad magic")),- };- let block_bytes = if wide_ids { 8192 } else { 4096 };+ if &bytes[0..4] != b"VOX3" { return Err(bad("bad magic")); } let sec_count = bytes[4] as usize; let mut off = 5usize; for sec_idx in 0..sec_count.min(SECTIONS_PER_CHUNK) { if off >= bytes.len() { break; } let flag = bytes[off]; off+=1; if flag != 1 { continue; }- if off + block_bytes > bytes.len() { return Err(bad("section overflow")); }+ if off + 8192 > bytes.len() { return Err(bad("section overflow")); } let mut blocks = [0 as crate::world::block::Id; 4096];- if wide_ids {- for (i, cell) in blocks.iter_mut().enumerate() {- *cell = u16::from_le_bytes([bytes[off + i*2], bytes[off + i*2 + 1]]);- }- } else {- for (i, cell) in blocks.iter_mut().enumerate() { *cell = bytes[off + i] as u16; }+ for (i, cell) in blocks.iter_mut().enumerate() {+ *cell = u16::from_le_bytes([bytes[off + i*2], bytes[off + i*2 + 1]]); }- off+=block_bytes;+ off += 8192; let mut meta = None;- if has_meta_flags {- if off >= bytes.len() { return Err(bad("missing meta flag")); }- let has_meta = bytes[off]; off+=1;- if has_meta == 1 {- if off + 4096 > bytes.len() { return Err(bad("meta overflow")); }- let mut m = Box::new([0u8; 4096]);- m.copy_from_slice(&bytes[off..off+4096]);- off+=4096;- meta = Some(m);- }+ if off >= bytes.len() { return Err(bad("missing meta flag")); }+ let has_meta = bytes[off]; off+=1;+ if has_meta == 1 {+ if off + 4096 > bytes.len() { return Err(bad("meta overflow")); }+ let mut m = Box::new([0u8; 4096]);+ m.copy_from_slice(&bytes[off..off+4096]);+ off+=4096;+ meta = Some(m); } let non_air = blocks.iter().filter(|&&b| b!=0).count(); if non_air>0 { chunk.sections[sec_idx] = Some(super::chunk::BlockSection{ blocks, meta, non_air }); }@@ -93,10 +82,9 @@ fn decode_chunk(bytes: &[u8], chunk: &mut Chunk) -> std::io::Result<()> { pub struct PlayerSave { pub x: f32, pub y: f32, pub z: f32, pub yaw: f32, pub pitch: f32, pub inventory: InventorySave, pub stats: StatsSave,- // Everything below was added after the first save format; `default` keeps old saves loadable. #[serde(default)] pub progress: ProgressSave, }-// Progression that used to reset on every quit: equipped armor, earned max health, which dimension+// Progression that survives a quit: equipped armor, earned max health, which dimension // the player is standing in (and where they were in the others), and one-time boss kills. #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] pub struct ProgressSave {@@ -120,9 +108,6 @@ pub struct ProgressSave { #[serde(default)] pub weather_cd: f32, /// Bitmask over RECIPES of recipes crafted at least once — the crafting tech tree's state. #[serde(default)] pub crafted_recipes: Vec<u8>,- /// Retired: the old ingredient-based "discovered" set. Still read on load to seed- /// `crafted_recipes` for saves written before the tech tree existed, and written empty.- #[serde(default)] pub known_recipes: Vec<u8>, } fn default_max_health() -> f32 { 20.0 } fn default_deepest() -> i32 { 128 }@@ -135,7 +120,7 @@ impl Default for ProgressSave { best_beacon: 0, deepest_y: default_deepest(), blessings: crate::blessing::Attunement::default(), trades_done: Vec::new(),- weather: 0, weather_cd: 0.0, crafted_recipes: Vec::new(), known_recipes: Vec::new(),+ weather: 0, weather_cd: 0.0, crafted_recipes: Vec::new(), } } }@@ -147,7 +132,7 @@ pub struct InvSlotSave { pub id: crate::world::block::Id, pub count: i32 } pub struct StatsSave { pub placed: i32, pub broken: i32, pub walked: i32, pub night_seen: bool } pub fn player_file(base: &str) -> PathBuf {- Path::new(base).join("voxels").join("worlds").join("default").join("player.json")+ Path::new(base).join("player.json") } pub fn save_player(base: &str, save: &PlayerSave) -> std::io::Result<()> { let path = player_file(base);@@ -167,88 +152,7 @@ pub fn load_player(base: &str) -> Option<PlayerSave> { #[cfg(test)] mod tests { use super::*;- use super::super::chunk::{BlockSection, CHUNK_HEIGHT, SECTIONS_PER_CHUNK};-- // Build a chunk file in the retired VOX1 layout: magic, section count, then per section a- // present-flag followed by 4096 raw block bytes and nothing else.- fn encode_vox1(chunk: &Chunk) -> Vec<u8> {- let mut data = vec![];- data.extend_from_slice(b"VOX1");- data.push(SECTIONS_PER_CHUNK as u8);- for sec in chunk.sections.iter() {- match sec {- Some(s) => { data.push(1); data.extend(s.blocks.iter().map(|&b| b as u8)); }- None => data.push(0),- }- }- data- }-- // Build a chunk file in the retired VOX2 layout: VOX1 plus a has-meta flag and optional meta- // array per section.- fn encode_vox2(chunk: &Chunk) -> Vec<u8> {- let mut data = vec![];- data.extend_from_slice(b"VOX2");- data.push(SECTIONS_PER_CHUNK as u8);- for sec in chunk.sections.iter() {- match sec {- Some(s) => {- data.push(1);- data.extend(s.blocks.iter().map(|&b| b as u8));- match s.meta.as_ref() {- Some(m) => { data.push(1); data.extend_from_slice(&m[..]); }- None => data.push(0),- }- }- None => data.push(0),- }- }- data- }-- // The load path treats a decode failure as "not generated", which makes ChunkMap regenerate the- // chunk from the seed and silently destroy whatever the player built there. A VOX1 file must- // therefore keep loading, byte-for-byte, with meta defaulting to plain cubes.- #[test]- fn legacy_vox1_chunks_still_load() {- let mut original = Chunk::new(ChunkPos(3, -4));- original.set_block(1, 5, 2, 42);- original.set_block(15, 200, 15, 7);- let bytes = encode_vox1(&original);-- let mut loaded = Chunk::new(ChunkPos(3, -4));- decode_chunk(&bytes, &mut loaded).expect("a VOX1 chunk must still decode");-- assert!(loaded.generated, "a decoded chunk must count as generated or it gets regenerated");- assert_eq!(loaded.get_block(1, 5, 2), 42);- assert_eq!(loaded.get_block(15, 200, 15), 7);- assert_eq!(loaded.get_meta(1, 5, 2), 0, "legacy blocks are all full cubes");- for (a, b) in original.sections.iter().zip(loaded.sections.iter()) {- match (a, b) {- (Some(a), Some(b)) => assert_eq!(a.blocks, b.blocks, "block bytes must survive verbatim"),- (None, None) => {}- _ => panic!("section presence changed across a VOX1 load"),- }- }- }-- #[test]- fn legacy_vox2_chunks_still_load() {- let mut original = Chunk::new(ChunkPos(-9, 12));- original.set_block(2, 30, 4, 55);- original.set_block_meta(3, 30, 4, 103, 0b110);- original.set_block(15, 250, 15, 1);- let bytes = encode_vox2(&original);-- let mut loaded = Chunk::new(ChunkPos(-9, 12));- decode_chunk(&bytes, &mut loaded).expect("a VOX2 chunk must still decode");-- assert!(loaded.generated);- assert_eq!(loaded.get_block(2, 30, 4), 55);- assert_eq!(loaded.get_block(3, 30, 4), 103);- assert_eq!(loaded.get_meta(3, 30, 4), 0b110, "stair facing must survive the upgrade");- assert_eq!(loaded.get_block(15, 250, 15), 1);- }+ use super::super::chunk::{BlockSection, SECTIONS_PER_CHUNK}; #[test] fn vox3_round_trips_blocks_and_meta() {@@ -280,31 +184,6 @@ mod tests { } } - // The upgrade is the dangerous moment: a world saved by the old build gets read as VOX2 and- // rewritten as VOX3 the first time it's touched. Not one cell may shift in the process.- #[test]- fn a_vox2_chunk_upgrades_without_losing_a_block() {- let mut original = Chunk::new(ChunkPos(1, -1));- // A spread of ids and metas across several sections, including the extremes.- for i in 0..64 {- let x = i % 16; let z = (i / 16) % 16;- original.set_block(x, i, z, (i as crate::world::block::Id % 123) + 1);- }- original.set_block_meta(4, 100, 4, 103, 2);- original.set_block_meta(5, 100, 4, 102, 0b100);- original.set_block(0, 255, 0, 123);-- let mut once = Chunk::new(ChunkPos(1, -1));- decode_chunk(&encode_vox2(&original), &mut once).expect("VOX2 decodes");- let mut twice = Chunk::new(ChunkPos(1, -1));- decode_chunk(&encode_chunk(&once), &mut twice).expect("the VOX3 rewrite decodes");-- for y in 0..CHUNK_HEIGHT { for x in 0..16 { for z in 0..16 {- assert_eq!(original.get_block(x, y, z), twice.get_block(x, y, z), "block at {x},{y},{z} changed");- assert_eq!(original.get_meta(x, y, z), twice.get_meta(x, y, z), "meta at {x},{y},{z} changed");- }}}- }- // A decode error makes ChunkMap regenerate the chunk from the seed, so `Err` has to mean "this // really is not a chunk file" and nothing weaker. #[test]@@ -321,32 +200,28 @@ mod tests { // A file whose header promises more sections than it carries stops early rather than // failing: the sections it did carry are real data worth keeping.- let mut short = good.clone();- short[4] = SECTIONS_PER_CHUNK as u8; let mut partial = Chunk::new(ChunkPos(0, 0));- assert!(decode_chunk(&short[..6 + 8192 + 1], &mut partial).is_ok());+ assert!(decode_chunk(&good[..6 + 8192 + 1], &mut partial).is_ok()); assert_eq!(partial.get_block(1, 1, 1), 5); } - // The whole point of keeping VOX1 and VOX2 readable: `ChunkMap::load_or_gen` treats a decode- // failure as "never generated" and rebuilds the chunk from the seed, so a rejected file silently- // erases whatever the player built. This drives the real load path against a real file to prove- // an old-format world survives the upgrade.+ // `ChunkMap::load_or_gen` treats a decode failure as "never generated" and rebuilds the chunk+ // from the seed, so a file it can't read silently erases whatever the player built. This drives+ // the real load path against a real file on disk rather than just the codec. #[test]- fn a_world_saved_by_the_old_build_still_loads_through_chunk_map() {+ fn a_saved_world_reloads_instead_of_regenerating() { use super::super::ChunkMap;- let dir = std::env::temp_dir().join("voxels_vox2_world_test");+ let dir = std::env::temp_dir().join("voxels_reload_test"); let _ = fs::remove_dir_all(&dir); let base = dir.to_string_lossy().into_owned(); - // Hand-build a chunk the way the previous build wrote it, well above sea level so the water- // pass can't touch it, and drop it exactly where the loader looks.+ // Build a chunk well above sea level so the water pass can't touch it, and save it exactly+ // the way the engine does. let pos = ChunkPos(5, -3); let mut original = Chunk::new(pos); original.set_block(2, 200, 3, 42); original.set_block_meta(4, 200, 3, 103, 0b110);- fs::create_dir_all(region_dir(&base)).unwrap();- fs::write(chunk_file(&base, pos), encode_vox2(&original)).unwrap();+ save_chunk(&base, &original).unwrap(); let mut map = ChunkMap::new(0xB10CCA, base.clone()); map.load_or_gen(pos);@@ -369,7 +244,7 @@ mod tests { original.set_block(5, 64, 0, 1); // a plain cube alongside let mut loaded = Chunk::new(ChunkPos(0, 0));- decode_chunk(&encode_chunk(&original), &mut loaded).expect("VOX2 must decode");+ decode_chunk(&encode_chunk(&original), &mut loaded).expect("the chunk must decode"); assert_eq!(loaded.get_meta(0, 64, 0), 0b100); assert_eq!(loaded.get_meta(1, 64, 0), 0);@@ -407,21 +282,6 @@ mod tests { assert_eq!(s.get_meta(1, 2, 3), 0, "a fresh block starts with default meta"); } - // A player.json written before ProgressSave existed must still load, defaulting to a fresh- // progression rather than failing and wiping the world.- #[test]- fn legacy_player_json_still_loads() {- let legacy = r#"{"x":1.0,"y":80.0,"z":-3.0,"yaw":0.5,"pitch":0.0,- "inventory":{"selected":2,"slots":[{"id":3,"count":64}]},- "stats":{"placed":7,"broken":9,"walked":42,"night_seen":true}}"#;- let ps: PlayerSave = serde_json::from_str(legacy).expect("legacy save must parse");- assert_eq!(ps.inventory.selected, 2);- assert_eq!(ps.stats.placed, 7);- assert_eq!(ps.progress.max_health, 20.0);- assert_eq!(ps.progress.dim, 0);- assert!(!ps.progress.end_dragon_dead);- }- #[test] fn progress_round_trips() { let mut ps = PlayerSave::default();