diff --git a/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt b/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt index 3efe6947..42f4159f 100644 --- a/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt +++ b/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt @@ -8,6 +8,7 @@ import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.Image 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 @@ -43,6 +44,8 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember @@ -60,6 +63,7 @@ import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.liveRegion @@ -89,6 +93,7 @@ import com.android.polybazaar.chat.viewmodel.PendingPhotoStatus import com.android.polybazaar.error.model.AppError import com.android.polybazaar.error.ui.message import com.android.polybazaar.listing.ui.CameraPermissionDialog +import com.android.polybazaar.listing.ui.decodePhotoPreview import com.android.polybazaar.listing.ui.loadPhotoPreview import com.android.polybazaar.listing.ui.rememberPhotoCamera import java.time.Instant @@ -126,6 +131,12 @@ object ConversationScreenTags { /** Tag of the bubble of the other participant's message with [id]. */ fun theirMessage(id: String) = "conversation_their_message_$id" + /** Tag of the photo of the message with [id], or of its placeholder while it loads. */ + fun messagePhoto(id: String) = "conversation_message_photo_$id" + + /** Tag of the placeholder of the message with [id] whose photo failed to load; tap to retry. */ + fun photoLoadError(id: String) = "conversation_photo_load_error_$id" + /** Tag of the bubble of the photo being sent, or that failed, with message ID [id]. */ fun pendingPhoto(id: String) = "conversation_pending_photo_$id" @@ -170,6 +181,12 @@ private val MaxBubbleWidth = 300.dp */ private val BubblePhotoHeight = 200.dp +/** Longest side, in pixels, a message photo is decoded at: sharp across a bubble. */ +private const val BUBBLE_PHOTO_MAX_SIZE = 1024 + +/** Download errors a retry can't fix: the photo is gone, or the rules refuse it. */ +private val PermanentPhotoErrors = setOf(AppError.NOT_FOUND, AppError.PERMISSION_DENIED) + private val TimeFormat = DateTimeFormatter.ofPattern("HH:mm") /** @@ -213,6 +230,7 @@ fun ConversationScreen(viewModel: ConversationViewModel, onBack: () -> Unit) { ) }, onRemoveAttachedPhoto = viewModel::removeAttachedPhoto, + onLoadPhoto = viewModel::loadPhoto, onRetryPhoto = viewModel::retryPhoto, onDiscardPhoto = viewModel::discardPhoto, ) @@ -237,6 +255,9 @@ fun ConversationScreen(viewModel: ConversationViewModel, onBack: () -> Unit) { * @param onTakePhoto called when the user picks "Take photo" in the photo menu. * @param onChoosePhoto called when the user picks "Choose from gallery" in the photo menu. * @param onRemoveAttachedPhoto called when the user taps ✕ on the attached photo. + * @param onLoadPhoto called with a message's imagePath when its bubble shows and the photo is + * neither pending, downloaded nor failed, when a pending photo is marked uploaded, and when the + * user taps a photo that failed to load. * @param onRetryPhoto called with the message ID of a failed photo when the user taps Retry. * @param onDiscardPhoto called with the message ID of a failed photo when the user taps Remove. * @param zone time zone of the message times. @@ -252,6 +273,7 @@ fun ConversationContent( onTakePhoto: () -> Unit = {}, onChoosePhoto: () -> Unit = {}, onRemoveAttachedPhoto: () -> Unit = {}, + onLoadPhoto: (String) -> Unit = {}, onRetryPhoto: (String) -> Unit = {}, onDiscardPhoto: (String) -> Unit = {}, zone: ZoneId = ZoneId.systemDefault(), @@ -292,7 +314,7 @@ fun ConversationContent( uiState = uiState, zone = zone, onRetry = onRetry, - photoActions = PhotoActions(onRetryPhoto, onDiscardPhoto), + photoActions = PhotoActions(onLoadPhoto, onRetryPhoto, onDiscardPhoto), ) } } @@ -504,8 +526,9 @@ private fun EmptyState( } } -/** What the user can do with the photos being sent. */ +/** What the user can do with the photos in the conversation. */ private class PhotoActions( + val load: (path: String) -> Unit, val retry: (messageId: String) -> Unit, val discard: (messageId: String) -> Unit, ) @@ -524,6 +547,8 @@ private fun MessageList( val messages = uiState.shownMessages val pendingPhotos = uiState.pendingPhotos val listState = rememberLazyListState() + // Decoded above the list: a bubble that scrolls out of view and back shows its photo at once. + val decodedPhotos = rememberDecodedPhotos(uiState.messagePhotos) // The list keeps its place by key, so a new message or photo would arrive below the view without // this. LaunchedEffect(messages.lastOrNull()?.id, pendingPhotos.lastOrNull()?.messageId) { @@ -554,6 +579,16 @@ private fun MessageList( isMine = message.senderUid == uiState.myUid, otherUsername = uiState.otherUser?.username, zone = zone, + photo = + message.imagePath?.let { path -> + MessagePhoto( + downloaded = path in uiState.messagePhotos, + decoded = decodedPhotos[path] ?: DecodedPhoto.Loading, + loadError = uiState.photoLoadErrors[path], + pending = message.photoPending, + load = { photoActions.load(path) }, + ) + }, ) } } @@ -592,8 +627,22 @@ private fun LoadErrorRow(text: String, onRetry: () -> Unit) { } /** - * One message: the user's own at the end of the row, the other participant's at the start. The - * footer says who sent it and when, or only when while the other participant's profile is unknown. + * The photo of a message: [downloaded] once its bytes arrived, [decoded] from them above the list + * ([DecodedPhoto.Loading] until then); [loadError] why the download failed; [pending] while its + * sender is still uploading it, so it can't be downloaded yet. [load] asks for it. + */ +private class MessagePhoto( + val downloaded: Boolean, + val decoded: DecodedPhoto, + val loadError: AppError?, + val pending: Boolean, + val load: () -> Unit, +) + +/** + * One message: the user's own at the end of the row, the other participant's at the start. A photo + * message shows its photo, then its caption if any. The footer says who sent it and when, or only + * when while the other participant's profile is unknown. */ @Composable private fun MessageBubble( @@ -601,6 +650,7 @@ private fun MessageBubble( isMine: Boolean, otherUsername: String?, zone: ZoneId, + photo: MessagePhoto?, ) { val time = message.sentAt.atZone(zone).format(TimeFormat) val footer = @@ -615,14 +665,19 @@ private fun MessageBubble( tag = if (isMine) ConversationScreenTags.myMessage(message.id) else ConversationScreenTags.theirMessage(message.id), - fixedWidth = false, + // A photo bubble takes its full width at once, so it does not grow when the photo arrives. + fixedWidth = photo != null, ) { - Text( - text = message.text, - color = AuthColors.TextPrimary, - fontSize = 14.sp, - lineHeight = 19.sp, - ) + photo?.let { BubblePhoto(messageId = message.id, photo = it) } + // A photo alone has no text. + if (message.text.isNotEmpty()) { + Text( + text = message.text, + color = AuthColors.TextPrimary, + fontSize = 14.sp, + lineHeight = 19.sp, + ) + } BubbleFooter(text = footer) } } @@ -676,6 +731,132 @@ private fun ColumnScope.BubbleFooter(text: String) { ) } +/** + * [photos] decoded off the main thread, by path: each one once, and again only if its bytes change. + * A photo still decoding is absent. + */ +@Composable +private fun rememberDecodedPhotos(photos: Map): Map { + val decoded = remember { mutableStateMapOf() } + photos.forEach { (path, bytes) -> + // One effect per photo: a photo that finishes downloading starts its own decode, without + // restarting the ones already running. + key(path) { + LaunchedEffect(bytes) { + decoded[path] = + decodePhotoPreview(bytes, maxSize = BUBBLE_PHOTO_MAX_SIZE)?.let { + DecodedPhoto.Shown(it) + } ?: DecodedPhoto.Failed + } + } + } + return decoded +} + +/** A message photo after it is decoded, or why it is not shown. */ +private sealed interface DecodedPhoto { + data object Loading : DecodedPhoto + + data object Failed : DecodedPhoto + + class Shown(val bitmap: ImageBitmap) : DecodedPhoto +} + +/** + * The photo of a message, asked for when the bubble first shows, or once its sender has uploaded + * it: a placeholder of the same size while it uploads, downloads and decodes, and one that says it + * could not be loaded, offering to try again when that may help. + */ +@Composable +private fun BubblePhoto(messageId: String, photo: MessagePhoto) { + // Not asked again on its own after a failure: only when the user taps to retry. + LaunchedEffect(messageId, photo.pending) { + if (!photo.pending && !photo.downloaded && photo.loadError == null) photo.load() + } + val description = stringResource(R.string.conversation_photo) + // Not the same as the photo's, so TalkBack users can tell it is not there yet. + val loadingDescription = stringResource(R.string.conversation_photo_loading) + val shape = RoundedCornerShape(10.dp) + val current = photo.decoded + val loadError = photo.loadError + val downloadFailed = loadError != null && current !is DecodedPhoto.Shown + // One tag per state: of two test tags on a node, only the first counts. + val tag = + if (downloadFailed) ConversationScreenTags.photoLoadError(messageId) + else ConversationScreenTags.messagePhoto(messageId) + val modifier = Modifier.fillMaxWidth().height(BubblePhotoHeight).clip(shape).testTag(tag) + when { + current is DecodedPhoto.Shown -> + Image( + bitmap = current.bitmap, + contentDescription = description, + contentScale = ContentScale.Crop, + modifier = modifier, + ) + // Undecodable bytes, or a photo missing or refused, would fail again: only another failed + // download offers to retry. + loadError != null || current is DecodedPhoto.Failed -> + PhotoLoadError( + onRetry = photo.load.takeIf { loadError != null && loadError !in PermanentPhotoErrors }, + modifier = modifier, + ) + else -> + Box( + modifier = + modifier.background(AuthColors.Outline).semantics { + contentDescription = loadingDescription + }, + contentAlignment = Alignment.Center, + ) { + CircularProgressIndicator( + color = AuthColors.TextSecondary, + strokeWidth = 2.dp, + modifier = Modifier.size(20.dp), + ) + } + } +} + +/** A photo that could not be loaded, with "tap to retry" when [onRetry] is given. */ +@Composable +private fun PhotoLoadError(onRetry: (() -> Unit)?, modifier: Modifier) { + Column( + modifier = + modifier + .background(AuthColors.Outline) + .then( + if (onRetry != null) + Modifier.clickable( + role = Role.Button, + onClickLabel = stringResource(R.string.conversation_retry), + onClick = onRetry, + ) + else Modifier + ) + .padding(12.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterVertically), + ) { + // Decorative: the text under it says what happened. + Icon( + painter = painterResource(R.drawable.ic_image), + contentDescription = null, + tint = AuthColors.TextSecondary, + modifier = Modifier.size(20.dp), + ) + Text( + text = + stringResource( + if (onRetry != null) R.string.conversation_photo_load_failed_retry + else R.string.conversation_photo_load_failed + ), + color = AuthColors.TextSecondary, + fontSize = 11.sp, + textAlign = TextAlign.Center, + ) + } +} + /** * A photo the user sent that is not in the conversation yet, as their own bubble: faded with a * spinner while it uploads; faded with why it failed, Retry and Remove once it failed. @@ -1078,3 +1259,51 @@ internal fun ConversationContentPreview() { zone = ZoneOffset.UTC, ) } + +/** A photo from the other participant still loading, and one of mine that failed to send. */ +@Preview(showBackground = true, widthDp = 412, heightDp = 917) +@Composable +internal fun ConversationPhotosPreview() { + val start = Instant.parse("2026-05-04T09:12:00Z") + ConversationContent( + uiState = + ConversationUiState( + myUid = "renter", + messages = + listOf( + ChatMessage("1", "renter", "Could you send a photo of the drill?", start), + ChatMessage( + "2", + "lender", + "Here it is, with both batteries.", + start.plusSeconds(120), + imagePath = "conversations/drill_renter/2.jpg", + ), + ), + conversation = + Conversation( + listingId = "drill", + listingTitle = "Bosch drill set", + renterUid = "renter", + lenderUid = "lender", + lastMessageAt = start.plusSeconds(120), + ), + listingTitle = "Bosch drill set", + listingStatus = ConversationListingStatus.ACTIVE, + otherUser = User(uid = "lender", email = "", username = "james"), + canAttachPhoto = true, + pendingPhotos = + listOf( + PendingPhoto( + messageId = "3", + photo = Uri.parse("file:///preview/photo_3.jpg"), + caption = "And the shelf I mean", + status = PendingPhotoStatus.FAILED, + error = AppError.NETWORK, + ) + ), + isLoading = false, + ), + zone = ZoneOffset.UTC, + ) +} diff --git a/app/src/main/java/com/android/polybazaar/chat/ui/InboxScreen.kt b/app/src/main/java/com/android/polybazaar/chat/ui/InboxScreen.kt index 8a659be2..c74abe61 100644 --- a/app/src/main/java/com/android/polybazaar/chat/ui/InboxScreen.kt +++ b/app/src/main/java/com/android/polybazaar/chat/ui/InboxScreen.kt @@ -415,16 +415,34 @@ private fun LastMessagePreview( isUnread: Boolean, conversationId: String, ) { - Text( - text = if (isMine) stringResource(R.string.inbox_last_message_mine, text) else text, - color = if (isUnread) AuthColors.TextPrimary else AuthColors.TextSecondary, - fontSize = 13.sp, - lineHeight = 18.sp, - fontWeight = if (isUnread) FontWeight.SemiBold else FontWeight.Normal, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.testTag(InboxScreenTags.preview(conversationId)), - ) + // A photo sent alone previews as an empty text. + val isPhoto = text.isEmpty() + val shown = if (isPhoto) stringResource(R.string.inbox_last_message_photo) else text + val color = if (isUnread) AuthColors.TextPrimary else AuthColors.TextSecondary + Row( + horizontalArrangement = Arrangement.spacedBy(4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + if (isPhoto) { + // Decorative: the text says "Photo". + Icon( + painter = painterResource(R.drawable.ic_image), + contentDescription = null, + tint = color, + modifier = Modifier.size(14.dp), + ) + } + Text( + text = if (isMine) stringResource(R.string.inbox_last_message_mine, shown) else shown, + color = color, + fontSize = 13.sp, + lineHeight = 18.sp, + fontWeight = if (isUnread) FontWeight.SemiBold else FontWeight.Normal, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.testTag(InboxScreenTags.preview(conversationId)), + ) + } } /** diff --git a/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt b/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt index 211d8019..5b6e0341 100644 --- a/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt +++ b/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt @@ -81,6 +81,9 @@ data class PendingPhoto( * conversation loads and after it failed to load, when whether it exists is unknown. * @property pendingPhotos the photos sent that are still uploading or failed, oldest first. Their * message may already be in [messages], since it is written before the photo is uploaded. + * @property messagePhotos the photos of [messages] downloaded so far, by [ChatMessage.imagePath]. + * @property photoLoadErrors why the photo at each path could not be downloaded; + * [ConversationViewModel.loadPhoto] tries again. * @property isLoading true until the listing, the conversation and the messages have each been * loaded or failed, and again while a retry reloads any of them. * @property loadError why the conversation could not be loaded; the screen offers Retry. What is @@ -100,6 +103,8 @@ data class ConversationUiState( val canSend: Boolean = false, val firstMessageBlockedByPause: Boolean = false, val pendingPhotos: List = emptyList(), + val messagePhotos: Map = emptyMap(), + val photoLoadErrors: Map = emptyMap(), val isLoading: Boolean = true, val loadError: AppError? = null, val sendError: AppError? = null, @@ -184,6 +189,8 @@ class ConversationViewModel( // Photos taken with the camera and not deleted yet, so gallery photos are never deleted. private val takenPhotos = mutableSetOf() + // The message photos being downloaded, so that no photo is downloaded twice at once. + private val photosDownloading = mutableSetOf() init { observeListing() @@ -388,6 +395,32 @@ class ConversationViewModel( abandon(failed) } + /** + * Downloads the photo of a message at [path], its [ChatMessage.imagePath], unless it is already + * downloaded or downloading. A message's photo never changes, so it is downloaded once. Ignored + * while the message's photo is still pending ([ChatMessage.photoPending]): it is not in Storage + * yet, so call it again once the message says it is uploaded. After a failure, calling it again + * clears the error and tries again. + */ + fun loadPhoto(path: String) { + val state = _uiState.value + if (state.messages.any { it.imagePath == path && it.photoPending }) return + if (path in state.messagePhotos || !photosDownloading.add(path)) return + _uiState.update { it.copy(photoLoadErrors = it.photoLoadErrors - path) } + viewModelScope.launch { + try { + val photo = chatRepository.loadMessagePhoto(path) + _uiState.update { it.copy(messagePhotos = it.messagePhotos + (path to photo)) } + } catch (exception: Exception) { + if (exception is CancellationException) throw exception + val error = exception.toAppError() + _uiState.update { it.copy(photoLoadErrors = it.photoLoadErrors + (path to error)) } + } finally { + photosDownloading.remove(path) + } + } + } + fun dismissSendError() { _uiState.update { it.copy(sendError = null) } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index d62ee84e..15afa6c4 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -99,6 +99,9 @@ Attached photo Remove photo Photo + Photo, loading + Couldn’t load the photo · Tap to retry + Couldn’t load the photo Sending… Not sent. %1$s Remove @@ -176,6 +179,7 @@ Found something you like?\nOpen a listing and message its owner.\nYour conversations will appear here. Browse listings You: %1$s + Photo Unread diff --git a/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt b/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt index 62dfbec5..415dafe6 100644 --- a/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt @@ -17,12 +17,16 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toPixelMap import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.SemanticsActions import androidx.compose.ui.semantics.SemanticsProperties import androidx.compose.ui.test.SemanticsMatcher import androidx.compose.ui.test.SemanticsNodeInteraction import androidx.compose.ui.test.assert import androidx.compose.ui.test.assertContentDescriptionEquals import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.assertHasNoClickAction +import androidx.compose.ui.test.assertHeightIsEqualTo import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsEnabled import androidx.compose.ui.test.assertIsNotDisplayed @@ -33,6 +37,7 @@ import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.getBoundsInRoot import androidx.compose.ui.test.hasAnyAncestor import androidx.compose.ui.test.hasTestTag +import androidx.compose.ui.test.hasText import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText @@ -134,6 +139,7 @@ class ConversationScreenTest { onTakePhoto: () -> Unit = {}, onChoosePhoto: () -> Unit = {}, onRemoveAttachedPhoto: () -> Unit = {}, + onLoadPhoto: (String) -> Unit = {}, onRetryPhoto: (String) -> Unit = {}, onDiscardPhoto: (String) -> Unit = {}, ) { @@ -148,6 +154,7 @@ class ConversationScreenTest { onTakePhoto = onTakePhoto, onChoosePhoto = onChoosePhoto, onRemoveAttachedPhoto = onRemoveAttachedPhoto, + onLoadPhoto = onLoadPhoto, onRetryPhoto = onRetryPhoto, onDiscardPhoto = onDiscardPhoto, zone = ZoneOffset.UTC, @@ -743,6 +750,17 @@ class ConversationScreenTest { node(ConversationScreenTags.theirMessage("2")).assertIsDisplayed() } + @Test + fun photosPreview_showsTheirPhotoLoadingAndMyFailedPhoto() { + composeTestRule.setContent { ConversationPhotosPreview() } + + composeTestRule + .onNodeWithTag(ConversationScreenTags.messagePhoto("2"), useUnmergedTree = true) + .assertExists() + node(ConversationScreenTags.pendingPhoto("3")).assertExists() + node(ConversationScreenTags.retryPhoto("3")).assertExists() + } + @Test fun conversationBody_prefersTheMessages_thenTheError_thenLoading_elseEmpty() { fun body(messages: Boolean, error: Boolean, loading: Boolean) = @@ -1004,7 +1022,7 @@ class ConversationScreenTest { assertEquals(1, sends) } - // Photos being sent + // Photo bubbles private val photoTime = Instant.parse("2026-11-11T09:16:00Z") @@ -1012,9 +1030,212 @@ class ConversationScreenTest { private fun photoMessage(id: String, senderUid: String, caption: String = "") = ChatMessage(id, senderUid, caption, photoTime, imagePath = "conversations/drill_renter/$id") + private val myPhoto = photoMessage("m3", "renter", caption = "Here it is") + private val theirPhoto = photoMessage("m4", james.uid) + private fun pending(status: PendingPhotoStatus, error: AppError? = null) = PendingPhoto("m5", galleryPhoto, "And the shelf", status, error) + /** Waits until the photo of message [id] is drawn: [redPhoto] decoded, not the placeholder. */ + private fun waitForRedPhoto(id: String) { + composeTestRule.waitUntil(5_000) { + val image = + composeTestRule + .onNodeWithTag(ConversationScreenTags.messagePhoto(id), useUnmergedTree = true) + .captureToImage() + image.toPixelMap()[image.width / 2, image.height / 2] == Color.Red + } + } + + private fun photoNode(id: String) = + composeTestRule.onNodeWithTag(ConversationScreenTags.messagePhoto(id), useUnmergedTree = true) + + @Test + fun myPhotoWithACaption_isOneTalkBackItem_photoThenCaptionThenFooter() { + setContent(loaded.copy(messages = listOf(myPhoto))) + + node(ConversationScreenTags.myMessage("m3")) + .assertContentDescriptionEquals(string(R.string.conversation_photo_loading)) + .assertTextEquals("Here it is", "You · 09:16") + val photo = photoNode("m3").getBoundsInRoot() + val caption = text("Here it is").getBoundsInRoot() + assertTrue(photo.bottom <= caption.top) + } + + @Test + fun theirPhotoWithoutACaption_showsOnlyThePhotoAndTheFooter() { + setContent(loaded.copy(messages = listOf(theirPhoto))) + + node(ConversationScreenTags.theirMessage("m4")) + .assertContentDescriptionEquals(string(R.string.conversation_photo_loading)) + .assertTextEquals("james · 09:16") + photoNode("m4").assertIsDisplayed() + } + + @Test + fun photoNotDownloaded_isAskedForOnce_withAFixedSizePlaceholder() { + val loads = mutableListOf() + setContent(loaded.copy(messages = listOf(myPhoto, theirPhoto)), onLoadPhoto = { loads += it }) + + composeTestRule.waitForIdle() + assertEquals(listOf(theirPhoto.imagePath, myPhoto.imagePath), loads) + photoNode("m3").assertHeightIsEqualTo(200.dp) + node(ConversationScreenTags.photoLoadError("m3")).assertDoesNotExist() + } + + @Test + fun pendingPhoto_showsTheLoadingPlaceholder_withoutBeingAskedFor() { + val loads = mutableListOf() + val uploading = theirPhoto.copy(photoPending = true) + setContent(loaded.copy(messages = listOf(uploading)), onLoadPhoto = { loads += it }) + + composeTestRule.waitForIdle() + assertEquals(emptyList(), loads) + photoNode("m4").assertHeightIsEqualTo(200.dp) + node(ConversationScreenTags.photoLoadError("m4")).assertDoesNotExist() + } + + @Test + fun pendingPhoto_isAskedForOnceMarkedUploaded() { + val loads = mutableListOf() + var state by + mutableStateOf(loaded.copy(messages = listOf(theirPhoto.copy(photoPending = true)))) + composeTestRule.setContent { + ConversationContent(uiState = state, onLoadPhoto = { loads += it }, zone = ZoneOffset.UTC) + } + composeTestRule.waitForIdle() + + state = state.copy(messages = listOf(theirPhoto)) + composeTestRule.waitForIdle() + + assertEquals(listOf(theirPhoto.imagePath), loads) + } + + @Test + @GraphicsMode(GraphicsMode.Mode.NATIVE) // Real decoding and drawing. + fun downloadedPhoto_isShownAtTheSameSize_withoutAskingAgain() { + val loads = mutableListOf() + setContent( + loaded.copy( + messages = listOf(theirPhoto), + messagePhotos = mapOf(theirPhoto.imagePath!! to redPhoto()), + ), + onLoadPhoto = { loads += it }, + ) + + waitForRedPhoto("m4") + photoNode("m4").assertHeightIsEqualTo(200.dp) + // Loaded: no longer "loading" for TalkBack. + node(ConversationScreenTags.theirMessage("m4")) + .assertContentDescriptionEquals(string(R.string.conversation_photo)) + assertEquals(emptyList(), loads) + } + + @Test + @GraphicsMode(GraphicsMode.Mode.NATIVE) // Real decoding and drawing. + fun decodedPhoto_scrolledOutOfViewAndBack_isShownAtOnce() { + val later = + List(30) { ChatMessage("t$it", "renter", "Message $it", photoTime.plusSeconds(60L + it)) } + setContent( + loaded.copy( + messages = listOf(theirPhoto) + later, + messagePhotos = mapOf(theirPhoto.imagePath!! to redPhoto()), + ) + ) + val list = node(ConversationScreenTags.MESSAGE_LIST) + // Newest first: the photo is last. + list.performScrollToIndex(later.size) + waitForRedPhoto("m4") + + list.performScrollToIndex(0) + photoNode("m4").assertDoesNotExist() + // Frozen clock: a photo decoded again would still show the placeholder. + composeTestRule.mainClock.autoAdvance = false + list.performScrollToIndex(later.size) + + // Not decoded again: drawn in the first frame, without the placeholder. + val image = photoNode("m4").captureToImage() + assertEquals(Color.Red, image.toPixelMap()[image.width / 2, image.height / 2]) + } + + @Test + @GraphicsMode(GraphicsMode.Mode.NATIVE) // The legacy BitmapFactory "decodes" any bytes. + fun undecodablePhoto_saysItCouldNotLoad_withoutOfferingARetry() { + setContent( + loaded.copy( + messages = listOf(theirPhoto), + messagePhotos = mapOf(theirPhoto.imagePath!! to byteArrayOf(1, 2, 3)), + ) + ) + + composeTestRule.waitUntil(5_000) { + composeTestRule + .onAllNodes( + hasText(string(R.string.conversation_photo_load_failed)), + useUnmergedTree = true, + ) + .fetchSemanticsNodes() + .isNotEmpty() + } + node(ConversationScreenTags.photoLoadError("m4")).assertDoesNotExist() + } + + @Test + fun photoThatFailedToDownload_offersARetry_andTappingAsksForItAgain() { + val loads = mutableListOf() + setContent( + loaded.copy( + messages = listOf(theirPhoto), + photoLoadErrors = mapOf(theirPhoto.imagePath!! to AppError.NETWORK), + ), + onLoadPhoto = { loads += it }, + ) + composeTestRule.waitForIdle() + assertEquals(emptyList(), loads) + + composeTestRule + .onNodeWithTag(ConversationScreenTags.photoLoadError("m4"), useUnmergedTree = true) + .assertHeightIsEqualTo(200.dp) + // Announced by TalkBack as a button that retries. + .assert(SemanticsMatcher.expectValue(SemanticsProperties.Role, Role.Button)) + .assert( + SemanticsMatcher("retries on click") { + it.config[SemanticsActions.OnClick].label == string(R.string.conversation_retry) + } + ) + .performClick() + + text(string(R.string.conversation_photo_load_failed_retry)).assertIsDisplayed() + assertEquals(listOf(theirPhoto.imagePath), loads) + } + + @Test + fun photoMissingOrRefused_saysItCouldNotLoad_withoutOfferingARetry() { + val loads = mutableListOf() + var error by mutableStateOf(AppError.NOT_FOUND) + composeTestRule.setContent { + ConversationContent( + uiState = + loaded.copy( + messages = listOf(theirPhoto), + photoLoadErrors = mapOf(theirPhoto.imagePath!! to error), + ), + zone = ZoneOffset.UTC, + onLoadPhoto = { loads += it }, + ) + } + + for (permanent in listOf(AppError.NOT_FOUND, AppError.PERMISSION_DENIED)) { + error = permanent + composeTestRule + .onNodeWithTag(ConversationScreenTags.photoLoadError("m4"), useUnmergedTree = true) + .assertHasNoClickAction() + text(string(R.string.conversation_photo_load_failed)).assertIsDisplayed() + text(string(R.string.conversation_photo_load_failed_retry)).assertDoesNotExist() + } + assertEquals(emptyList(), loads) + } + @Test fun pendingPhoto_whoseMessageArrived_showsOnce() { setContent( diff --git a/app/src/test/java/com/android/polybazaar/chat/ui/InboxScreenTest.kt b/app/src/test/java/com/android/polybazaar/chat/ui/InboxScreenTest.kt index cbfea4d4..7105ff03 100644 --- a/app/src/test/java/com/android/polybazaar/chat/ui/InboxScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/chat/ui/InboxScreenTest.kt @@ -233,6 +233,54 @@ class InboxScreenTest { .assertTextEquals(context.getString(R.string.inbox_last_message_mine, "See you at 6")) } + @Test + fun rowPreview_ofAPhotoAlone_saysPhoto() { + val photo = context.getString(R.string.inbox_last_message_photo) + val drill = conversation("drill").copy(lastMessageText = "") + setContent(loaded(row(drill))) + + node(InboxScreenTags.preview(drill.id)).assertTextEquals(photo) + // Read once in the row: the icon next to it is decorative. + rowOf(drill).assert(hasText(photo)) + composeTestRule + .onAllNodes( + hasContentDescription(photo) and + hasAnyAncestor(hasTestTag(InboxScreenTags.row(drill.id))), + useUnmergedTree = true, + ) + .assertCountEquals(0) + } + + @Test + fun rowPreview_ofAPhotoWithACaption_showsTheCaption_notPhoto() { + // A photo's caption is its message text, so it is the preview. + val drill = conversation("drill").copy(lastMessageText = "Both batteries are in") + setContent(loaded(row(drill))) + + node(InboxScreenTags.preview(drill.id)).assertTextEquals("Both batteries are in") + composeTestRule + .onAllNodes( + hasText(context.getString(R.string.inbox_last_message_photo)) and + hasAnyAncestor(hasTestTag(InboxScreenTags.row(drill.id))), + useUnmergedTree = true, + ) + .assertCountEquals(0) + } + + @Test + fun rowPreview_ofMyOwnPhoto_startsWithYou() { + val drill = conversation("drill").copy(lastMessageText = "") + setContent(loaded(row(drill, isLastMessageMine = true))) + + node(InboxScreenTags.preview(drill.id)) + .assertTextEquals( + context.getString( + R.string.inbox_last_message_mine, + context.getString(R.string.inbox_last_message_photo), + ) + ) + } + @Test fun rowWithoutLastMessageText_showsNoPreview() { val drill = conversation("drill") diff --git a/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt b/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt index cb21bac2..d8633a40 100644 --- a/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt +++ b/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt @@ -10,6 +10,7 @@ import androidx.lifecycle.viewmodel.viewModelFactory import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.polybazaar.auth.model.User import com.android.polybazaar.chat.model.ChatMessage +import com.android.polybazaar.chat.model.ChatRepository import com.android.polybazaar.chat.model.ChatRules import com.android.polybazaar.chat.model.Conversation import com.android.polybazaar.chat.model.FakeChatRepository @@ -33,6 +34,7 @@ import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.After +import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull @@ -53,6 +55,7 @@ class ConversationViewModelTest { private lateinit var profiles: FakeProfileRepository private lateinit var listings: FakeListingRepository private lateinit var photoStorage: FakePhotoStorage + private lateinit var downloads: CountingDownloads private val lender = User(uid = "lender", email = "", username = "Lena") private val renter = User(uid = "renter", email = "", username = "Remi") @@ -108,7 +111,7 @@ class ConversationViewModelTest { listing.listingId!!, renter.uid, myUid, - chat, + CountingDownloads(chat).also { downloads = it }, profiles, listings, photoStorage, @@ -1753,6 +1756,141 @@ class ConversationViewModelTest { assertEquals(listOf(conversation.id to "m1"), chat.deletedPhotoMessages) } + private val photoPath = "chats/drill_renter/m1.jpg" + private val photoBytes = byteArrayOf(1, 2, 3) + private val missing = AppException(AppError.NOT_FOUND) + + /** Remi's photo message "m1", the id the fake gives the next photo sent. */ + private val photoMessage = + ChatMessage("m1", renter.uid, "", Instant.ofEpochSecond(300), imagePath = photoPath) + + /** Runs what is due now without moving the virtual clock. */ + private fun runCurrent() = testDispatcher.scheduler.runCurrent() + + /** The photo is in Storage now. */ + private fun uploaded() { + chat.photoLoadFailure = null + chat.photos[photoPath] = photoBytes + } + + @Test + fun loadPhoto_putsTheBytesInMessagePhotos() { + uploaded() + val viewModel = inConversation() + + viewModel.loadPhoto(photoPath) + advance() + + assertArrayEquals(photoBytes, viewModel.uiState.value.messagePhotos[photoPath]) + assertEquals(emptyMap(), viewModel.uiState.value.photoLoadErrors) + } + + @Test + fun loadPhoto_twiceWhileDownloading_downloadsOnce() { + uploaded() + val viewModel = inConversation() + + viewModel.loadPhoto(photoPath) + viewModel.loadPhoto(photoPath) + advance() + + assertEquals(listOf(photoPath), downloads.loads) + } + + @Test + fun loadPhoto_onceDownloaded_doesNotDownloadAgain() { + uploaded() + val viewModel = inConversation() + viewModel.loadPhoto(photoPath) + advance() + + viewModel.loadPhoto(photoPath) + advance() + + assertEquals(listOf(photoPath), downloads.loads) + } + + @Test + fun loadPhoto_failing_recordsTheErrorAtOnce_withoutWaiting() { + chat.photoLoadFailure = firestoreError(FirebaseFirestoreException.Code.UNAVAILABLE) + val viewModel = inConversation() + + viewModel.loadPhoto(photoPath) + runCurrent() + + assertEquals(mapOf(photoPath to AppError.NETWORK), viewModel.uiState.value.photoLoadErrors) + assertEquals(1, downloads.loads.size) + } + + @Test + fun loadPhoto_afterAFailure_clearsTheErrorAndDownloadsAgain() { + chat.photoLoadFailure = firestoreError(FirebaseFirestoreException.Code.UNAVAILABLE) + val viewModel = inConversation() + viewModel.loadPhoto(photoPath) + advance() + uploaded() + + viewModel.loadPhoto(photoPath) + assertEquals(emptyMap(), viewModel.uiState.value.photoLoadErrors) + advance() + + assertArrayEquals(photoBytes, viewModel.uiState.value.messagePhotos[photoPath]) + } + + @Test + fun loadPhoto_notFound_recordsTheErrorAtOnce() { + // Not pending, so it was uploaded: a missing photo will not arrive later. + chat.photoLoadFailure = missing + val viewModel = inConversation() + + viewModel.loadPhoto(photoPath) + runCurrent() + + assertEquals(mapOf(photoPath to AppError.NOT_FOUND), viewModel.uiState.value.photoLoadErrors) + assertEquals(1, downloads.loads.size) + } + + @Test + fun loadPhoto_whileThePhotoIsPending_downloadsNothing() { + givenConversation(messages = arrayOf(photoMessage.copy(photoPending = true))) + uploaded() + val viewModel = loadedViewModel() + + viewModel.loadPhoto(photoPath) + advance() + + assertEquals(emptyList(), downloads.loads) + assertEquals(emptyMap(), viewModel.uiState.value.messagePhotos) + assertEquals(emptyMap(), viewModel.uiState.value.photoLoadErrors) + } + + @Test + fun loadPhoto_onceThePhotoIsMarkedUploaded_downloadsIt() { + givenConversation(messages = arrayOf(photoMessage.copy(photoPending = true))) + uploaded() + val viewModel = loadedViewModel() + viewModel.loadPhoto(photoPath) + advance() + + chat.messages.value = mapOf(conversation.id to listOf(photoMessage)) + advance() + viewModel.loadPhoto(photoPath) + advance() + + assertEquals(listOf(photoPath), downloads.loads) + assertArrayEquals(photoBytes, viewModel.uiState.value.messagePhotos[photoPath]) + } + + /** Delegates to [FakeChatRepository] and records each photo download, by path, in [loads]. */ + private class CountingDownloads(private val fake: FakeChatRepository) : ChatRepository by fake { + val loads = mutableListOf() + + override suspend fun loadMessagePhoto(imagePath: String): ByteArray { + loads += imagePath + return fake.loadMessagePhoto(imagePath) + } + } + /** * Creates photos like the camera folder: "taken_0", "taken_1", … in [taken], or none while * [full]. Records the photos deleted.