1package com.peachpasswords.ui.pairing23import com.peachpasswords.BuildConfig4import androidx.compose.foundation.background5import androidx.compose.foundation.clickable6import androidx.compose.foundation.shape.RoundedCornerShape7import androidx.compose.ui.draw.clip8import androidx.compose.ui.graphics.Color9import androidx.compose.foundation.layout.Arrangement10import androidx.compose.foundation.layout.Box11import androidx.compose.foundation.layout.Column12import androidx.compose.foundation.layout.Spacer13import androidx.compose.foundation.layout.fillMaxSize14import androidx.compose.foundation.layout.fillMaxWidth15import androidx.compose.foundation.layout.height16import androidx.compose.foundation.layout.padding17import androidx.compose.foundation.layout.systemBarsPadding18import androidx.compose.foundation.Canvas19import androidx.compose.material3.Text20import androidx.compose.runtime.Composable21import androidx.compose.runtime.LaunchedEffect22import androidx.compose.runtime.mutableStateOf23import androidx.compose.runtime.remember24import androidx.compose.runtime.setValue25import androidx.compose.runtime.getValue26import androidx.compose.ui.platform.LocalContext27import androidx.compose.ui.Alignment28import androidx.compose.ui.Modifier29import androidx.compose.ui.semantics.Role30import androidx.compose.ui.text.font.FontStyle31import androidx.compose.ui.text.style.TextAlign32import androidx.compose.ui.unit.dp33import androidx.compose.ui.unit.sp34import androidx.compose.ui.geometry.Offset35import androidx.compose.ui.geometry.Size36import androidx.hilt.navigation.compose.hiltViewModel37import androidx.lifecycle.compose.collectAsStateWithLifecycle38import com.peachpasswords.ui.components.BirdAnimation39import com.peachpasswords.ui.components.PairingAnimState40import com.peachpasswords.ui.theme.LocalPeachAccent41import com.peachpasswords.ui.theme.PeachSpacing42import com.peachpasswords.ui.theme.PeachType43import com.peachpasswords.ui.theme.ShellBackground44import com.peachpasswords.ui.theme.peachColors45import com.google.zxing.BarcodeFormat46import com.google.zxing.qrcode.QRCodeWriter4748495051525354@Composable55fun CodePairScreen(56 onBack: () -> Unit,57 onOpenPro: () -> Unit = onBack,58 vm: CodePairViewModel = hiltViewModel(),59) {60 val state by vm.state.collectAsStateWithLifecycle()61 val syncMode by vm.syncMode.collectAsStateWithLifecycle()62 val privateRelayUrl by vm.privateRelayUrl.collectAsStateWithLifecycle()63 val context = LocalContext.current6465 var showBackgroundSyncPrompt by remember { mutableStateOf(false) }66 var relayExpanded by remember { mutableStateOf(false) }6768 LaunchedEffect(Unit) { vm.start() }6970 LaunchedEffect(state) {71 if (shouldPromptForBackgroundSync(state is CodePairUiState.Paired)) showBackgroundSyncPrompt = true72 }7374 if (showBackgroundSyncPrompt) {75 BackgroundSyncDialog { enabled ->76 showBackgroundSyncPrompt = false77 vm.setBackgroundSync(enabled)78 if (enabled) {79 80 81 82 val intent = vm.batteryExemptionIntent(userConfirmed = true)83 if (intent != null) runCatching { context.startActivity(intent) }84 else vm.syncOnce()85 }86 }87 }8889 val animState = when (state) {90 is CodePairUiState.Paired -> PairingAnimState.CONNECTED91 is CodePairUiState.AwaitingPeerConfirmation -> PairingAnimState.LISTENING92 else -> PairingAnimState.WAITING93 }9495 ShellBackground {96 Column(97 modifier = Modifier98 .fillMaxSize()99 .systemBarsPadding()100 .padding(horizontal = PeachSpacing.lg, vertical = PeachSpacing.md),101 ) {102 if (state !is CodePairUiState.Failed ||103 (state as? CodePairUiState.Failed)?.reason != "ADOPT_PRO_REQUIRED"104 ) {105 Box(Modifier.fillMaxWidth().weight(1f), contentAlignment = Alignment.Center) {106 BirdAnimation(animState, Modifier.fillMaxWidth().height(220.dp))107 }108 }109110 when (val s = state) {111 is CodePairUiState.Starting -> Headline("Starting…", "Opening a secure relay pairing room.")112113 is CodePairUiState.ShowingInvitation -> {114 Headline(115 "Pair a device",116 "Scan this QR on the empty device. Peach will send this vault only after the 8-digit code matches.",117 )118 Spacer(Modifier.height(PeachSpacing.md))119 PairingRelayChoice(120 mode = syncMode,121 configuredPrivateUrl = privateRelayUrl,122 expanded = relayExpanded,123 onExpandedChange = { relayExpanded = it },124 onSelectMode = vm::selectRelayMode,125 onSavePrivateUrl = vm::savePrivateRelayUrl,126 )127 if (!relayExpanded) {128 PairingQrCode(129 value = s.invitation,130 modifier = Modifier131 .fillMaxWidth()132 .height(260.dp),133 )134 }135 }136137 is CodePairUiState.AwaitingPeerConfirmation -> {138 Headline(139 "Confirm on the scanning device",140 "If this code matches there, tap “They match” on that device. " +141 "Peach finishes only after both sides save the pairing.",142 )143 Spacer(Modifier.height(PeachSpacing.lg))144 Text(145 text = s.sas,146 color = LocalPeachAccent.current,147 fontFamily = PeachType.Mono,148 fontSize = 38.sp,149 letterSpacing = 6.sp,150 textAlign = TextAlign.Center,151 modifier = Modifier.fillMaxWidth(),152 )153 }154155 is CodePairUiState.Paired -> {156 Headline("Paired", "${s.deviceName} will now sync through the relay.")157 Spacer(Modifier.height(PeachSpacing.lg))158 PillButton("Done", LocalPeachAccent.current, filled = true, onClick = onBack)159 }160161 is CodePairUiState.Expired -> {162 Headline(163 "That code expired",164 "Codes are good for five minutes so one doesn't stay live on a phone in your pocket. Nothing was lost.",165 )166 Spacer(Modifier.height(PeachSpacing.lg))167 PillButton("Show a new code", LocalPeachAccent.current, filled = true) { vm.restart() }168 }169170 is CodePairUiState.Failed -> {171 if (s.reason == "ADOPT_PRO_REQUIRED") {172 PairingProRequired(173 onRetry = vm::restart,174 onOpenPro = onOpenPro,175 )176 } else {177 Headline("Couldn't pair", failureCopy(s.reason))178 Spacer(Modifier.height(PeachSpacing.md))179 if (s.reason == "sync_disabled" || s.reason == "private_relay_unset") {180 PairingRelayChoice(181 mode = syncMode,182 configuredPrivateUrl = privateRelayUrl,183 expanded = true,184 collapsible = false,185 onExpandedChange = { relayExpanded = it },186 onSelectMode = vm::selectRelayMode,187 onSavePrivateUrl = vm::savePrivateRelayUrl,188 )189 Spacer(Modifier.height(PeachSpacing.md))190 }191 PillButton("Back", LocalPeachAccent.current, filled = true, onClick = onBack)192 }193 }194 }195 Spacer(Modifier.height(PeachSpacing.md))196 }197 }198}199200@Composable201private fun PairingQrCode(value: String, modifier: Modifier = Modifier) {202 val matrix = remember(value) {203 QRCodeWriter().encode(value, BarcodeFormat.QR_CODE, 0, 0)204 }205 Canvas(modifier = modifier) {206 val side = minOf(size.width, size.height)207 val module = side / matrix.width208 val qrSize = module * matrix.width209 val origin = Offset((size.width - qrSize) / 2f, (size.height - qrSize) / 2f)210 drawRect(Color.White, topLeft = origin, size = Size(qrSize, qrSize))211 for (y in 0 until matrix.height) {212 for (x in 0 until matrix.width) {213 if (matrix[x, y]) {214 drawRect(215 Color.Black,216 topLeft = Offset(origin.x + x * module, origin.y + y * module),217 size = Size(module + 0.5f, module + 0.5f),218 )219 }220 }221 }222 }223}224225226@Composable227internal fun PillButton(228 label: String,229 color: Color,230 filled: Boolean,231 enabled: Boolean = true,232 onClick: () -> Unit,233) {234 val accent = LocalPeachAccent.current235 val buttonColor = if (filled) accent else color236 Box(237 modifier = Modifier238 .fillMaxWidth()239 .clip(RoundedCornerShape(14.dp))240 .background(241 if (filled) {242 accent.copy(alpha = if (enabled) 0.14f else 0.05f)243 } else {244 Color.Transparent245 },246 )247 .clickable(enabled = enabled, role = Role.Button, onClick = onClick)248 .padding(vertical = PeachSpacing.md),249 contentAlignment = Alignment.Center,250 ) {251 Text(252 label,253 color = buttonColor.copy(alpha = if (enabled) 1f else 0.38f),254 fontFamily = PeachType.Mono,255 fontSize = 13.sp,256 )257 }258}259260private fun failureCopy(reason: String): String = when (reason) {261 "ADOPT_PRO_REQUIRED" -> "Peach Pro is required on at least one paired device."262 "vault_locked" -> "Unlock your vault first — pairing shares the key that protects it."263 "no_local_network" -> "This phone isn't on a Wi-Fi network, so there's no address to hand out."264 "sas_mismatch" -> "The codes didn't match, so nothing was saved. That's the right outcome if you didn't expect a connection."265 "sync_disabled" -> "Sync is switched off for this vault. Turn it on in Settings → Sync first."266 267 268 "private_relay_unset" -> "Private relay chosen but no address set. Enter your relay URL in Settings → Sync first."269 270 271 272 273 else -> "Something interrupted the connection. Try again."274 .let { if (BuildConfig.DEBUG) "$it\n\n[$reason]" else it }275}276277@Composable278private fun Headline(title: String, body: String) {279 Column(280 modifier = Modifier.fillMaxWidth(),281 horizontalAlignment = Alignment.CenterHorizontally,282 verticalArrangement = Arrangement.Center,283 ) {284 Text(285 title,286 color = peachColors.T0,287 fontFamily = PeachType.Display,288 fontStyle = FontStyle.Italic,289 fontSize = 22.sp,290 textAlign = TextAlign.Center,291 )292 Spacer(Modifier.height(PeachSpacing.xs))293 Text(294 body,295 color = peachColors.T2,296 fontFamily = PeachType.Body,297 fontSize = 13.sp,298 textAlign = TextAlign.Center,299 )300 }301}