build(messages): default SMS app: receive, send multipart with status, threads, chat, notifications with reply, search, archive
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
id("com.google.devtools.ksp")
|
||||
id("io.github.takahirom.roborazzi")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "app.messages"
|
||||
compileSdk = 36
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "app.messages"
|
||||
minSdk = 29
|
||||
targetSdk = 36
|
||||
versionCode = 1
|
||||
versionName = "0.1.0"
|
||||
}
|
||||
|
||||
// Release key lives outside the repo; without it, release builds fall back to the debug key (local only).
|
||||
val keyProps = Properties().apply {
|
||||
val f = file(System.getProperty("user.home") + "/.android/nogoogleapps-release.properties")
|
||||
if (f.exists()) f.inputStream().use { load(it) }
|
||||
}
|
||||
signingConfigs {
|
||||
if (keyProps.isNotEmpty()) create("release") {
|
||||
storeFile = file(keyProps.getProperty("storeFile"))
|
||||
storePassword = keyProps.getProperty("storePassword")
|
||||
keyAlias = keyProps.getProperty("keyAlias")
|
||||
keyPassword = keyProps.getProperty("keyPassword")
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
debug {
|
||||
// installs next to the release app from Obtainium
|
||||
applicationIdSuffix = ".debug"
|
||||
resValue("string", "app_name", "Messages (Debug)")
|
||||
}
|
||||
release {
|
||||
resValue("string", "app_name", "Messages")
|
||||
isMinifyEnabled = true
|
||||
isShrinkResources = true
|
||||
signingConfig = signingConfigs.findByName("release") ?: signingConfigs.getByName("debug")
|
||||
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
buildFeatures { compose = true }
|
||||
testOptions { unitTests { isIncludeAndroidResources = true } }
|
||||
}
|
||||
|
||||
kotlin { compilerOptions { jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17) } }
|
||||
|
||||
ksp { arg("room.schemaLocation", "$projectDir/schemas") }
|
||||
|
||||
dependencies {
|
||||
val composeBom = platform("androidx.compose:compose-bom:2025.10.01")
|
||||
implementation(composeBom)
|
||||
implementation("androidx.compose.ui:ui")
|
||||
implementation("androidx.compose.ui:ui-tooling-preview")
|
||||
implementation("androidx.compose.foundation:foundation")
|
||||
implementation("androidx.compose.material3:material3")
|
||||
implementation("androidx.compose.material:material-icons-extended")
|
||||
debugImplementation("androidx.compose.ui:ui-tooling")
|
||||
|
||||
implementation("androidx.activity:activity-compose:1.11.0")
|
||||
implementation("androidx.core:core-ktx:1.17.0")
|
||||
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.9.4")
|
||||
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.9.4")
|
||||
|
||||
implementation("androidx.room:room-runtime:2.7.0")
|
||||
implementation("androidx.room:room-ktx:2.7.0")
|
||||
ksp("androidx.room:room-compiler:2.7.0")
|
||||
implementation("androidx.datastore:datastore-preferences:1.1.7")
|
||||
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
testImplementation("org.robolectric:robolectric:4.15.1")
|
||||
testImplementation("androidx.compose.ui:ui-test-junit4")
|
||||
debugImplementation("androidx.compose.ui:ui-test-manifest")
|
||||
testImplementation("io.github.takahirom.roborazzi:roborazzi:1.46.1")
|
||||
testImplementation("io.github.takahirom.roborazzi:roborazzi-compose:1.46.1")
|
||||
}
|
||||
|
||||
roborazzi { outputDir.set(rootProject.file("../replica/messages/clone-screens")) }
|
||||
Vendored
@@ -0,0 +1,57 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<!-- no INTERNET: SMS travel over the mobile network through the system, not through this app -->
|
||||
<uses-permission android:name="android.permission.READ_SMS" />
|
||||
<uses-permission android:name="android.permission.SEND_SMS" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_SMS" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_MMS" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_WAP_PUSH" />
|
||||
<uses-permission android:name="android.permission.READ_CONTACTS" />
|
||||
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-feature android:name="android.hardware.telephony" android:required="false" />
|
||||
|
||||
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name" android:supportsRtl="true" android:theme="@android:style/Theme.Material.NoActionBar">
|
||||
|
||||
<activity android:name=".MainActivity" android:exported="true" android:launchMode="singleTask" android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
<category android:name="android.intent.category.APP_MESSAGING" />
|
||||
</intent-filter>
|
||||
<!-- required for the default SMS app role -->
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.SENDTO" />
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:scheme="sms" /><data android:scheme="smsto" /><data android:scheme="mms" /><data android:scheme="mmsto" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.SEND" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<data android:mimeType="text/plain" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<receiver android:name=".sms.SmsDeliverReceiver" android:exported="true" android:permission="android.permission.BROADCAST_SMS">
|
||||
<intent-filter><action android:name="android.provider.Telephony.SMS_DELIVER" /></intent-filter>
|
||||
</receiver>
|
||||
<receiver android:name=".sms.MmsDeliverReceiver" android:exported="true" android:permission="android.permission.BROADCAST_WAP_PUSH">
|
||||
<intent-filter>
|
||||
<action android:name="android.provider.Telephony.WAP_PUSH_DELIVER" />
|
||||
<data android:mimeType="application/vnd.wap.mms-message" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
<service android:name=".sms.RespondViaMessageService" android:exported="true" android:permission="android.permission.SEND_RESPOND_VIA_MESSAGE">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.RESPOND_VIA_MESSAGE" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<data android:scheme="sms" /><data android:scheme="smsto" /><data android:scheme="mms" /><data android:scheme="mmsto" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
<receiver android:name=".sms.SmsStatusReceiver" android:exported="false" />
|
||||
<receiver android:name=".sms.NotificationActionReceiver" android:exported="false" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,243 @@
|
||||
package app.messages
|
||||
|
||||
import android.Manifest
|
||||
import android.app.role.RoleManager
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.provider.ContactsContract
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.rounded.ArrowBack
|
||||
import androidx.compose.material.icons.outlined.Archive
|
||||
import androidx.compose.material.icons.outlined.Call
|
||||
import androidx.compose.material.icons.outlined.Chat
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material.icons.outlined.Unarchive
|
||||
import androidx.compose.material.icons.rounded.MoreVert
|
||||
import androidx.compose.material.icons.rounded.Search
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.ExtendedFloatingActionButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import app.messages.data.Message
|
||||
import app.messages.data.Sms
|
||||
import app.messages.sms.Notifier
|
||||
import app.messages.sms.Sender
|
||||
import app.messages.ui.Conversation
|
||||
import app.messages.ui.ConversationList
|
||||
import app.messages.ui.NewChat
|
||||
import app.messages.ui.SearchResults
|
||||
import app.messages.ui.components.Avatar
|
||||
import app.messages.ui.theme.MsgTheme
|
||||
import app.messages.ui.theme.WType
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/** Also the target of sms:/smsto: links (required for the default SMS app role). */
|
||||
class MainActivity : ComponentActivity() {
|
||||
private val open = mutableStateOf<Pair<String, String>?>(null) // address to draft
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
enableEdgeToEdge()
|
||||
Notifier.channel(this)
|
||||
handle(intent)
|
||||
setContent { MsgTheme { App(open.value) { open.value = null } } }
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) { super.onNewIntent(intent); handle(intent) }
|
||||
|
||||
private fun handle(i: Intent?) {
|
||||
i ?: return
|
||||
val address = when (i.action) {
|
||||
Intent.ACTION_SENDTO, Intent.ACTION_VIEW -> i.data?.schemeSpecificPart?.substringBefore('?')?.takeIf { i.data?.scheme in setOf("sms", "smsto", "mms", "mmsto") }
|
||||
Intent.ACTION_SEND -> ""
|
||||
else -> i.getStringExtra(Notifier.EXTRA_ADDRESS)
|
||||
} ?: return
|
||||
val body = i.getStringExtra("sms_body") ?: i.getStringExtra(Intent.EXTRA_TEXT) ?: ""
|
||||
open.value = Uri.decode(address) to body
|
||||
}
|
||||
}
|
||||
|
||||
private sealed interface Route {
|
||||
data class Chat(val address: String, val draft: String = "") : Route
|
||||
data object New : Route
|
||||
data object Search : Route
|
||||
data object Archive : Route
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun App(request: Pair<String, String>?, onHandled: () -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
val role = ctx.getSystemService(RoleManager::class.java)
|
||||
var isDefault by remember { mutableStateOf(role.isRoleHeld(RoleManager.ROLE_SMS)) }
|
||||
var granted by remember { mutableStateOf(has(ctx, Manifest.permission.READ_SMS)) }
|
||||
val perms = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { granted = has(ctx, Manifest.permission.READ_SMS) }
|
||||
val roleLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
|
||||
isDefault = role.isRoleHeld(RoleManager.ROLE_SMS); granted = has(ctx, Manifest.permission.READ_SMS)
|
||||
if (!has(ctx, Manifest.permission.READ_CONTACTS)) perms.launch(arrayOf(Manifest.permission.READ_CONTACTS, Manifest.permission.POST_NOTIFICATIONS))
|
||||
}
|
||||
var asked by rememberSaveable { mutableStateOf(false) }
|
||||
LaunchedEffect(Unit) {
|
||||
if (!isDefault && !asked && role.isRoleAvailable(RoleManager.ROLE_SMS)) { asked = true; roleLauncher.launch(role.createRequestRoleIntent(RoleManager.ROLE_SMS)) }
|
||||
else if (!granted) perms.launch(arrayOf(Manifest.permission.READ_SMS, Manifest.permission.READ_CONTACTS, Manifest.permission.POST_NOTIFICATIONS))
|
||||
}
|
||||
|
||||
var route by remember { mutableStateOf<Route?>(null) }
|
||||
LaunchedEffect(request) { request?.let { (a, b) -> route = if (a.isBlank()) Route.New else Route.Chat(a, b); onHandled() } }
|
||||
val threads by remember(granted, isDefault) { Sms.threads(ctx) }.collectAsState(initial = emptyList())
|
||||
var selected by remember { mutableStateOf(setOf<Long>()) }
|
||||
var confirmDelete by remember { mutableStateOf(false) }
|
||||
|
||||
val back: () -> Unit = { route = if (route is Route.Chat || route is Route.Search) null else null }
|
||||
if (route != null) BackHandler(onBack = back)
|
||||
if (selected.isNotEmpty()) BackHandler { selected = emptySet() }
|
||||
|
||||
when (val r = route) {
|
||||
is Route.Chat -> ChatScreen(r.address, r.draft, isDefault, onBack = back) { roleLauncher.launch(role.createRequestRoleIntent(RoleManager.ROLE_SMS)) }
|
||||
Route.New -> Scaffold(topBar = { TopAppBar({ Text(stringResource(R.string.new_chat)) }, navigationIcon = { BackBtn(back) }) }) { pad ->
|
||||
val contacts by produceState(emptyList<Pair<String, String>>()) { value = withContext(Dispatchers.IO) { contacts(ctx) } }
|
||||
NewChat(pad, contacts) { route = Route.Chat(it) }
|
||||
}
|
||||
Route.Search -> Scaffold(topBar = { TopAppBar({ Text(stringResource(R.string.search)) }, navigationIcon = { BackBtn(back) }) }) { pad ->
|
||||
SearchResults(pad, { Sms.search(ctx, it) }, { Sms.contact(ctx, it)?.first ?: it }) { m -> route = Route.Chat(m.address) }
|
||||
}
|
||||
Route.Archive, null -> {
|
||||
val archive = r == Route.Archive
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
Scaffold(
|
||||
topBar = {
|
||||
if (selected.isNotEmpty()) TopAppBar({ Text("${selected.size}") }, navigationIcon = { IconButton({ selected = emptySet() }) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, null) } },
|
||||
actions = {
|
||||
IconButton({ selected.forEach { Sms.setArchived(ctx, it, !archive) }; selected = emptySet() }) { Icon(if (archive) Icons.Outlined.Unarchive else Icons.Outlined.Archive, stringResource(R.string.archive)) }
|
||||
IconButton({ confirmDelete = true }) { Icon(Icons.Outlined.Delete, stringResource(R.string.delete)) }
|
||||
})
|
||||
else TopAppBar({ Text(stringResource(if (archive) R.string.archived else R.string.app_title)) },
|
||||
navigationIcon = { if (archive) BackBtn { route = null } },
|
||||
actions = {
|
||||
IconButton({ route = Route.Search }) { Icon(Icons.Rounded.Search, stringResource(R.string.search)) }
|
||||
IconButton({ menu = true }) { Icon(Icons.Rounded.MoreVert, null) }
|
||||
DropdownMenu(menu, { menu = false }) {
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.archived)) }, onClick = { menu = false; route = Route.Archive })
|
||||
}
|
||||
})
|
||||
},
|
||||
floatingActionButton = {
|
||||
if (!archive) ExtendedFloatingActionButton(onClick = { route = Route.New }, icon = { Icon(Icons.Outlined.Chat, null) }, text = { Text(stringResource(R.string.start_chat)) },
|
||||
containerColor = MaterialTheme.colorScheme.primaryContainer)
|
||||
},
|
||||
) { pad ->
|
||||
Column {
|
||||
if (!isDefault && !archive) Column(
|
||||
Modifier.padding(start = 16.dp, end = 16.dp, top = pad.calculateTopPadding() + 8.dp).clip(RoundedCornerShape(24.dp)).background(MaterialTheme.colorScheme.primaryContainer)
|
||||
.clickable { roleLauncher.launch(role.createRequestRoleIntent(RoleManager.ROLE_SMS)) }.padding(16.dp),
|
||||
) {
|
||||
Text(stringResource(R.string.default_title), style = WType.body, color = MaterialTheme.colorScheme.onPrimaryContainer)
|
||||
Text(stringResource(R.string.default_text), style = WType.bodySm, color = MaterialTheme.colorScheme.onPrimaryContainer)
|
||||
}
|
||||
ConversationList(threads.filter { it.archived == archive }, if (!isDefault && !archive) PaddingValues(bottom = pad.calculateBottomPadding()) else pad,
|
||||
onOpen = { t -> if (selected.isNotEmpty()) selected = selected.toggle(t.id) else route = Route.Chat(t.address) },
|
||||
onLongPress = { selected = selected.toggle(it.id) }, selected = selected)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (confirmDelete) AlertDialog({ confirmDelete = false }, title = { Text(stringResource(R.string.delete_confirm, selected.size)) },
|
||||
confirmButton = { TextButton({ selected.forEach { Sms.deleteThread(ctx, it) }; selected = emptySet(); confirmDelete = false }) { Text(stringResource(R.string.delete)) } },
|
||||
dismissButton = { TextButton({ confirmDelete = false }) { Text(stringResource(android.R.string.cancel)) } })
|
||||
}
|
||||
|
||||
private fun Set<Long>.toggle(id: Long) = if (id in this) this - id else this + id
|
||||
|
||||
@Composable private fun BackBtn(onClick: () -> Unit) = IconButton(onClick) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) }
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun ChatScreen(address: String, draft: String, isDefault: Boolean, onBack: () -> Unit, onMakeDefault: () -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
val threadId = remember(address) { runCatching { Sms.threadIdFor(ctx, address) }.getOrDefault(-1L) }
|
||||
val messages by remember(threadId) { Sms.messages(ctx, threadId) }.collectAsState(initial = emptyList())
|
||||
LaunchedEffect(threadId, messages.size) { if (isDefault) { Sms.markRead(ctx, threadId); Notifier.cancel(ctx, threadId) } }
|
||||
val who = remember(address) { Sms.contact(ctx, address) }
|
||||
var menuFor by remember { mutableStateOf<Message?>(null) }
|
||||
var needRole by remember { mutableStateOf(false) }
|
||||
Scaffold(topBar = {
|
||||
TopAppBar(title = {
|
||||
androidx.compose.foundation.layout.Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) {
|
||||
Avatar(who?.first ?: address, who?.second, 36.dp)
|
||||
Text(" " + (who?.first ?: address), style = WType.title.copy(fontSize = WType.body.fontSize * 1.15f))
|
||||
}
|
||||
}, navigationIcon = { BackBtn(onBack) }, actions = {
|
||||
if (address.any(Char::isDigit)) IconButton({ ctx.startActivity(Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", address, null))) }) { Icon(Icons.Outlined.Call, stringResource(R.string.call)) }
|
||||
})
|
||||
}) { pad ->
|
||||
Conversation(messages, pad, onSend = { text -> if (isDefault) Sender.send(ctx, address, text) else needRole = true },
|
||||
onRetry = { m -> if (isDefault) { Sms.deleteMessage(ctx, m.id); Sender.send(ctx, address, m.body) } }, onLong = { menuFor = it }, draft = draft)
|
||||
}
|
||||
menuFor?.let { m ->
|
||||
AlertDialog({ menuFor = null }, text = {
|
||||
Column {
|
||||
TextButton({ ctx.getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText("SMS", m.body)); menuFor = null }) { Text(stringResource(R.string.copy)) }
|
||||
TextButton({ Sms.deleteMessage(ctx, m.id); menuFor = null }) { Text(stringResource(R.string.delete)) }
|
||||
}
|
||||
}, confirmButton = {})
|
||||
}
|
||||
if (needRole) AlertDialog({ needRole = false }, title = { Text(stringResource(R.string.default_title)) }, text = { Text(stringResource(R.string.need_role_send)) },
|
||||
confirmButton = { TextButton({ needRole = false; onMakeDefault() }) { Text(stringResource(R.string.make_default)) } },
|
||||
dismissButton = { TextButton({ needRole = false }) { Text(stringResource(android.R.string.cancel)) } })
|
||||
}
|
||||
|
||||
private fun has(ctx: Context, p: String) = ContextCompat.checkSelfPermission(ctx, p) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
private fun contacts(ctx: Context): List<Pair<String, String>> {
|
||||
if (!has(ctx, Manifest.permission.READ_CONTACTS)) return emptyList()
|
||||
val out = mutableListOf<Pair<String, String>>()
|
||||
runCatching {
|
||||
ctx.contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
|
||||
arrayOf(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER), null, null,
|
||||
"${ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME} COLLATE LOCALIZED ASC")?.use { c -> while (c.moveToNext()) out += c.getString(0).orEmpty() to c.getString(1).orEmpty() }
|
||||
}
|
||||
return out.distinctBy { it.second.filter(Char::isDigit) }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package app.messages.data
|
||||
|
||||
import android.Manifest
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.database.ContentObserver
|
||||
import android.net.Uri
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.provider.ContactsContract
|
||||
import android.provider.Telephony
|
||||
import androidx.core.content.ContextCompat
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.channels.awaitClose
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.callbackFlow
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
|
||||
enum class Box { INBOX, SENT, OUTBOX, FAILED, QUEUED, DRAFT }
|
||||
|
||||
data class Message(val id: Long, val threadId: Long, val address: String, val body: String, val date: Long, val box: Box, val read: Boolean, val status: Int)
|
||||
|
||||
data class Thread(val id: Long, val address: String, val name: String?, val photo: Uri?, val snippet: String, val date: Long, val unread: Int, val lastFromMe: Boolean, val archived: Boolean)
|
||||
|
||||
private fun Context.has(p: String) = ContextCompat.checkSelfPermission(this, p) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
private fun <T> Context.observe(uri: Uri, load: () -> T): Flow<T> = callbackFlow {
|
||||
val obs = object : ContentObserver(Handler(Looper.getMainLooper())) { override fun onChange(selfChange: Boolean) { trySend(load()) } }
|
||||
contentResolver.registerContentObserver(uri, true, obs)
|
||||
trySend(load())
|
||||
awaitClose { contentResolver.unregisterContentObserver(obs) }
|
||||
}.flowOn(Dispatchers.IO)
|
||||
|
||||
/** All SMS data lives in Android's own provider; this app only reads and (as default SMS app) writes it. */
|
||||
object Sms {
|
||||
private val nameCache = mutableMapOf<String, Pair<String, Uri?>?>()
|
||||
|
||||
fun contact(context: Context, number: String): Pair<String, Uri?>? = nameCache.getOrPut(number) {
|
||||
if (number.isBlank() || !context.has(Manifest.permission.READ_CONTACTS)) return@getOrPut null
|
||||
runCatching {
|
||||
context.contentResolver.query(Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number)),
|
||||
arrayOf(ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup.PHOTO_URI), null, null, null)?.use { c ->
|
||||
if (c.moveToFirst()) c.getString(0) to c.getString(1)?.let(Uri::parse) else null
|
||||
}
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
private fun box(t: Int) = when (t) {
|
||||
Telephony.Sms.MESSAGE_TYPE_SENT -> Box.SENT; Telephony.Sms.MESSAGE_TYPE_OUTBOX -> Box.OUTBOX; Telephony.Sms.MESSAGE_TYPE_FAILED -> Box.FAILED
|
||||
Telephony.Sms.MESSAGE_TYPE_QUEUED -> Box.QUEUED; Telephony.Sms.MESSAGE_TYPE_DRAFT -> Box.DRAFT; else -> Box.INBOX
|
||||
}
|
||||
|
||||
/** One row per thread, newest first: built from the SMS table (works on every Android build). */
|
||||
fun threads(context: Context): Flow<List<Thread>> = context.observe(Telephony.Sms.CONTENT_URI) { loadThreads(context) }
|
||||
|
||||
private fun loadThreads(context: Context): List<Thread> {
|
||||
if (!context.has(Manifest.permission.READ_SMS)) return emptyList()
|
||||
val archived = archivedIds(context)
|
||||
val latest = linkedMapOf<Long, Thread>()
|
||||
val unread = mutableMapOf<Long, Int>()
|
||||
runCatching {
|
||||
context.contentResolver.query(Telephony.Sms.CONTENT_URI,
|
||||
arrayOf(Telephony.Sms.THREAD_ID, Telephony.Sms.ADDRESS, Telephony.Sms.BODY, Telephony.Sms.DATE, Telephony.Sms.TYPE, Telephony.Sms.READ),
|
||||
null, null, "${Telephony.Sms.DATE} DESC")?.use { c ->
|
||||
while (c.moveToNext()) {
|
||||
val tid = c.getLong(0)
|
||||
if (c.getInt(5) == 0 && box(c.getInt(4)) == Box.INBOX) unread[tid] = (unread[tid] ?: 0) + 1
|
||||
if (tid in latest) continue
|
||||
val address = c.getString(1).orEmpty()
|
||||
val who = contact(context, address)
|
||||
latest[tid] = Thread(tid, address, who?.first, who?.second, c.getString(2).orEmpty(), c.getLong(3), 0, box(c.getInt(4)) != Box.INBOX, tid in archived)
|
||||
}
|
||||
}
|
||||
}
|
||||
return latest.values.map { it.copy(unread = unread[it.id] ?: 0) }
|
||||
}
|
||||
|
||||
fun messages(context: Context, threadId: Long): Flow<List<Message>> = context.observe(Telephony.Sms.CONTENT_URI) {
|
||||
val out = mutableListOf<Message>()
|
||||
runCatching {
|
||||
context.contentResolver.query(Telephony.Sms.CONTENT_URI,
|
||||
arrayOf(Telephony.Sms._ID, Telephony.Sms.THREAD_ID, Telephony.Sms.ADDRESS, Telephony.Sms.BODY, Telephony.Sms.DATE, Telephony.Sms.TYPE, Telephony.Sms.READ, Telephony.Sms.STATUS),
|
||||
"${Telephony.Sms.THREAD_ID} = ?", arrayOf(threadId.toString()), "${Telephony.Sms.DATE} ASC")?.use { c ->
|
||||
while (c.moveToNext()) out += Message(c.getLong(0), c.getLong(1), c.getString(2).orEmpty(), c.getString(3).orEmpty(), c.getLong(4), box(c.getInt(5)), c.getInt(6) == 1, c.getInt(7))
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fun search(context: Context, q: String): List<Message> {
|
||||
if (q.length < 2) return emptyList()
|
||||
val out = mutableListOf<Message>()
|
||||
runCatching {
|
||||
context.contentResolver.query(Telephony.Sms.CONTENT_URI,
|
||||
arrayOf(Telephony.Sms._ID, Telephony.Sms.THREAD_ID, Telephony.Sms.ADDRESS, Telephony.Sms.BODY, Telephony.Sms.DATE, Telephony.Sms.TYPE, Telephony.Sms.READ, Telephony.Sms.STATUS),
|
||||
"${Telephony.Sms.BODY} LIKE ?", arrayOf("%$q%"), "${Telephony.Sms.DATE} DESC LIMIT 100")?.use { c ->
|
||||
while (c.moveToNext()) out += Message(c.getLong(0), c.getLong(1), c.getString(2).orEmpty(), c.getString(3).orEmpty(), c.getLong(4), box(c.getInt(5)), c.getInt(6) == 1, c.getInt(7))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
fun threadIdFor(context: Context, address: String): Long = Telephony.Threads.getOrCreateThreadId(context, address)
|
||||
|
||||
fun insertIncoming(context: Context, address: String, body: String, sentAt: Long, subId: Int): Uri? = context.contentResolver.insert(
|
||||
Telephony.Sms.Inbox.CONTENT_URI,
|
||||
ContentValues().apply {
|
||||
put(Telephony.Sms.ADDRESS, address); put(Telephony.Sms.BODY, body); put(Telephony.Sms.DATE, System.currentTimeMillis())
|
||||
put(Telephony.Sms.DATE_SENT, sentAt); put(Telephony.Sms.READ, 0); put(Telephony.Sms.SEEN, 0); put(Telephony.Sms.SUBSCRIPTION_ID, subId)
|
||||
},
|
||||
)
|
||||
|
||||
fun insertOutgoing(context: Context, address: String, body: String, subId: Int): Uri? = context.contentResolver.insert(
|
||||
Telephony.Sms.Outbox.CONTENT_URI,
|
||||
ContentValues().apply {
|
||||
put(Telephony.Sms.ADDRESS, address); put(Telephony.Sms.BODY, body); put(Telephony.Sms.DATE, System.currentTimeMillis())
|
||||
put(Telephony.Sms.READ, 1); put(Telephony.Sms.SUBSCRIPTION_ID, subId)
|
||||
},
|
||||
)
|
||||
|
||||
fun setBox(context: Context, uri: Uri, type: Int) = runCatching {
|
||||
context.contentResolver.update(uri, ContentValues().apply { put(Telephony.Sms.TYPE, type) }, null, null)
|
||||
}
|
||||
|
||||
fun setDelivered(context: Context, uri: Uri, ok: Boolean) = runCatching {
|
||||
context.contentResolver.update(uri, ContentValues().apply { put(Telephony.Sms.STATUS, if (ok) Telephony.Sms.STATUS_COMPLETE else Telephony.Sms.STATUS_FAILED) }, null, null)
|
||||
}
|
||||
|
||||
fun markRead(context: Context, threadId: Long) = runCatching {
|
||||
context.contentResolver.update(Telephony.Sms.CONTENT_URI, ContentValues().apply { put(Telephony.Sms.READ, 1); put(Telephony.Sms.SEEN, 1) },
|
||||
"${Telephony.Sms.THREAD_ID} = ? AND ${Telephony.Sms.READ} = 0", arrayOf(threadId.toString()))
|
||||
}
|
||||
|
||||
fun deleteThread(context: Context, threadId: Long) = runCatching {
|
||||
context.contentResolver.delete(Telephony.Sms.CONTENT_URI, "${Telephony.Sms.THREAD_ID} = ?", arrayOf(threadId.toString()))
|
||||
}
|
||||
|
||||
fun deleteMessage(context: Context, id: Long) = runCatching {
|
||||
context.contentResolver.delete(Uri.withAppendedPath(Telephony.Sms.CONTENT_URI, id.toString()), null, null)
|
||||
}
|
||||
|
||||
// Archive: kept in our own preferences (the provider column is not writable on every build)
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("archive", Context.MODE_PRIVATE)
|
||||
fun archivedIds(context: Context): Set<Long> = prefs(context).getStringSet("ids", emptySet())!!.mapNotNull { it.toLongOrNull() }.toSet()
|
||||
fun setArchived(context: Context, threadId: Long, on: Boolean) {
|
||||
val s = archivedIds(context).map { it.toString() }.toMutableSet()
|
||||
if (on) s += threadId.toString() else s -= threadId.toString()
|
||||
prefs(context).edit().putStringSet("ids", s).apply()
|
||||
context.contentResolver.notifyChange(Telephony.Sms.CONTENT_URI, null)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package app.messages.sms
|
||||
|
||||
import android.Manifest
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.Person
|
||||
import androidx.core.app.RemoteInput
|
||||
import androidx.core.content.ContextCompat
|
||||
import app.messages.MainActivity
|
||||
import app.messages.R
|
||||
import app.messages.data.Sms
|
||||
|
||||
object Notifier {
|
||||
const val CH = "messages"
|
||||
const val ACTION_REPLY = "app.messages.REPLY"
|
||||
const val ACTION_READ = "app.messages.READ"
|
||||
const val KEY_REPLY = "reply"
|
||||
const val EXTRA_THREAD = "thread"
|
||||
const val EXTRA_ADDRESS = "address"
|
||||
|
||||
fun channel(context: Context) = context.getSystemService(NotificationManager::class.java)
|
||||
.createNotificationChannel(NotificationChannel(CH, context.getString(R.string.ch_messages), NotificationManager.IMPORTANCE_HIGH))
|
||||
|
||||
fun incoming(context: Context, threadId: Long, address: String, body: String) {
|
||||
if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) return
|
||||
channel(context)
|
||||
val name = Sms.contact(context, address)?.first ?: address
|
||||
val sender = Person.Builder().setName(name).setKey(address).build()
|
||||
val me = Person.Builder().setName(context.getString(R.string.me)).build()
|
||||
val open = PendingIntent.getActivity(context, threadId.toInt(),
|
||||
Intent(context, MainActivity::class.java).putExtra(EXTRA_THREAD, threadId).putExtra(EXTRA_ADDRESS, address).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
fun action(a: String, mutable: Boolean) = PendingIntent.getBroadcast(context, (a + threadId).hashCode(),
|
||||
Intent(context, NotificationActionReceiver::class.java).setAction(a).putExtra(EXTRA_THREAD, threadId).putExtra(EXTRA_ADDRESS, address),
|
||||
if (mutable) PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT else PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
val reply = NotificationCompat.Action.Builder(0, context.getString(R.string.reply), action(ACTION_REPLY, true))
|
||||
.addRemoteInput(RemoteInput.Builder(KEY_REPLY).setLabel(context.getString(R.string.reply_hint)).build())
|
||||
.setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY).setShowsUserInterface(false).build()
|
||||
val read = NotificationCompat.Action.Builder(0, context.getString(R.string.mark_read), action(ACTION_READ, false))
|
||||
.setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ).setShowsUserInterface(false).build()
|
||||
val n = NotificationCompat.Builder(context, CH).setSmallIcon(R.drawable.ic_stat_message)
|
||||
.setStyle(NotificationCompat.MessagingStyle(me).addMessage(body, System.currentTimeMillis(), sender))
|
||||
.setContentIntent(open).setAutoCancel(true).setCategory(NotificationCompat.CATEGORY_MESSAGE)
|
||||
.addAction(reply).addAction(read).setShortcutId(null).build()
|
||||
context.getSystemService(NotificationManager::class.java).notify(threadId.toInt(), n)
|
||||
}
|
||||
|
||||
fun cancel(context: Context, threadId: Long) = context.getSystemService(NotificationManager::class.java).cancel(threadId.toInt())
|
||||
|
||||
fun mmsUnsupported(context: Context) {
|
||||
if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) return
|
||||
channel(context)
|
||||
context.getSystemService(NotificationManager::class.java).notify(1,
|
||||
NotificationCompat.Builder(context, CH).setSmallIcon(R.drawable.ic_stat_message)
|
||||
.setContentTitle(context.getString(R.string.mms_title)).setContentText(context.getString(R.string.mms_text)).setAutoCancel(true).build())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package app.messages.sms
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Service
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.IBinder
|
||||
import android.provider.Telephony
|
||||
import android.telephony.SmsManager
|
||||
import android.telephony.SubscriptionManager
|
||||
import androidx.core.app.RemoteInput
|
||||
import app.messages.data.Sms
|
||||
|
||||
/** SMS_DELIVER: only the default SMS app gets this, and must store the message itself. */
|
||||
class SmsDeliverReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val parts = Telephony.Sms.Intents.getMessagesFromIntent(intent) ?: return
|
||||
if (parts.isEmpty()) return
|
||||
val address = parts[0].displayOriginatingAddress.orEmpty()
|
||||
val body = parts.joinToString("") { it.displayMessageBody.orEmpty() }
|
||||
val subId = intent.getIntExtra("subscription", SubscriptionManager.getDefaultSmsSubscriptionId())
|
||||
val uri = Sms.insertIncoming(context, address, body, parts[0].timestampMillis, subId)
|
||||
val threadId = Sms.threadIdFor(context, address)
|
||||
Notifier.incoming(context, threadId, address, body)
|
||||
android.util.Log.i("Messages", "stored incoming sms $uri")
|
||||
}
|
||||
}
|
||||
|
||||
/** MMS push: accepted so the role is valid; MMS download is not supported yet. */
|
||||
class MmsDeliverReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) = Notifier.mmsUnsupported(context)
|
||||
}
|
||||
|
||||
object Sender {
|
||||
const val ACTION_SENT = "app.messages.SENT"
|
||||
const val ACTION_DELIVERED = "app.messages.DELIVERED"
|
||||
|
||||
/** Writes to the outbox first, so a message never disappears; the receivers move it to sent or failed. */
|
||||
fun send(context: Context, address: String, text: String, subId: Int = SubscriptionManager.getDefaultSmsSubscriptionId()) {
|
||||
if (text.isBlank() || address.isBlank()) return
|
||||
val uri = Sms.insertOutgoing(context, address, text, subId) ?: return
|
||||
val sm = (if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) context.getSystemService(SmsManager::class.java).createForSubscriptionId(subId)
|
||||
else context.getSystemService(SmsManager::class.java))
|
||||
val parts = sm.divideMessage(text)
|
||||
fun pi(action: String, i: Int) = android.app.PendingIntent.getBroadcast(
|
||||
context, (uri.toString() + action + i).hashCode(),
|
||||
Intent(context, SmsStatusReceiver::class.java).setAction(action).setData(uri).putExtra("last", i == parts.lastIndex),
|
||||
android.app.PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
val sent = ArrayList(parts.indices.map { pi(ACTION_SENT, it) })
|
||||
val delivered = ArrayList(parts.indices.map { pi(ACTION_DELIVERED, it) })
|
||||
runCatching { sm.sendMultipartTextMessage(address, null, parts, sent, delivered) }
|
||||
.onFailure { Sms.setBox(context, uri, Telephony.Sms.MESSAGE_TYPE_FAILED) }
|
||||
}
|
||||
}
|
||||
|
||||
class SmsStatusReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val uri: Uri = intent.data ?: return
|
||||
when (intent.action) {
|
||||
Sender.ACTION_SENT -> {
|
||||
val ok = resultCode == Activity.RESULT_OK
|
||||
// any failed part fails the message; the last part's success marks it sent
|
||||
if (!ok) Sms.setBox(context, uri, Telephony.Sms.MESSAGE_TYPE_FAILED)
|
||||
else if (intent.getBooleanExtra("last", true)) Sms.setBox(context, uri, Telephony.Sms.MESSAGE_TYPE_SENT)
|
||||
}
|
||||
Sender.ACTION_DELIVERED -> if (intent.getBooleanExtra("last", true)) Sms.setDelivered(context, uri, resultCode == Activity.RESULT_OK)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Direct reply and "mark as read" from the notification. */
|
||||
class NotificationActionReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val threadId = intent.getLongExtra(Notifier.EXTRA_THREAD, -1)
|
||||
val address = intent.getStringExtra(Notifier.EXTRA_ADDRESS).orEmpty()
|
||||
when (intent.action) {
|
||||
Notifier.ACTION_REPLY -> {
|
||||
val text = RemoteInput.getResultsFromIntent(intent)?.getCharSequence(Notifier.KEY_REPLY)?.toString().orEmpty()
|
||||
Sender.send(context, address, text)
|
||||
Sms.markRead(context, threadId)
|
||||
Notifier.cancel(context, threadId)
|
||||
}
|
||||
Notifier.ACTION_READ -> { Sms.markRead(context, threadId); Notifier.cancel(context, threadId) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** "Decline with message" from the phone app; required for the SMS role. */
|
||||
class RespondViaMessageService : Service() {
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
val to = intent?.data?.schemeSpecificPart?.substringBefore('?').orEmpty()
|
||||
val text = intent?.getStringExtra(Intent.EXTRA_TEXT).orEmpty()
|
||||
if (to.isNotBlank() && text.isNotBlank()) Sender.send(this, to, text)
|
||||
stopSelf(startId)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package app.messages.ui
|
||||
|
||||
import android.text.format.DateUtils
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.rounded.Send
|
||||
import androidx.compose.material.icons.rounded.ErrorOutline
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextField
|
||||
import androidx.compose.material3.TextFieldDefaults
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.text.withStyle
|
||||
import androidx.compose.ui.unit.dp
|
||||
import app.messages.R
|
||||
import app.messages.data.Box as MBox
|
||||
import app.messages.data.Message
|
||||
import app.messages.data.Thread
|
||||
import app.messages.ui.components.Avatar
|
||||
import app.messages.ui.theme.WType
|
||||
import java.time.Instant
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.time.format.FormatStyle
|
||||
|
||||
fun shortTime(at: Long): String {
|
||||
val d = Instant.ofEpochMilli(at).atZone(ZoneId.systemDefault())
|
||||
return when {
|
||||
d.toLocalDate() == LocalDate.now() -> d.toLocalTime().format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT))
|
||||
d.toLocalDate().isAfter(LocalDate.now().minusDays(7)) -> d.format(DateTimeFormatter.ofPattern("EEE"))
|
||||
else -> d.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT))
|
||||
}
|
||||
}
|
||||
|
||||
/** S01 */
|
||||
@Composable
|
||||
fun ConversationList(threads: List<Thread>, pad: PaddingValues, onOpen: (Thread) -> Unit, onLongPress: (Thread) -> Unit, selected: Set<Long>) {
|
||||
if (threads.isEmpty()) {
|
||||
Box(Modifier.fillMaxSize().padding(pad), contentAlignment = Alignment.Center) {
|
||||
Text(stringResource(R.string.no_threads), style = WType.body, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
return
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(top = pad.calculateTopPadding(), bottom = pad.calculateBottomPadding() + 96.dp)) {
|
||||
items(threads, key = { it.id }) { t ->
|
||||
val unread = t.unread > 0
|
||||
val sel = t.id in selected
|
||||
Row(
|
||||
Modifier.fillMaxWidth().background(if (sel) MaterialTheme.colorScheme.secondaryContainer else Color.Transparent)
|
||||
.combinedClickable(onClick = { onOpen(t) }, onLongClick = { onLongPress(t) }).padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Avatar(t.name ?: t.address, t.photo, 48.dp)
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(t.name ?: t.address, style = WType.body.copy(fontWeight = if (unread) FontWeight.Bold else FontWeight.Normal), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
(if (t.lastFromMe) stringResource(R.string.you_prefix) else "") + t.snippet.replace('\n', ' '),
|
||||
style = WType.bodySm.copy(fontWeight = if (unread) FontWeight.SemiBold else FontWeight.Normal),
|
||||
color = if (unread) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Column(horizontalAlignment = Alignment.End) {
|
||||
Text(shortTime(t.date), style = WType.label, color = if (unread) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
if (unread) Box(Modifier.padding(top = 6.dp).size(10.dp).clip(CircleShape).background(MaterialTheme.colorScheme.primary))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** S02 */
|
||||
@Composable
|
||||
fun Conversation(messages: List<Message>, pad: PaddingValues, onSend: (String) -> Unit, onRetry: (Message) -> Unit, onLong: (Message) -> Unit, draft: String = "") {
|
||||
var text by rememberSaveable { mutableStateOf(draft) }
|
||||
val list = rememberLazyListState()
|
||||
LaunchedEffect(messages.size) { if (messages.isNotEmpty()) list.scrollToItem(messages.size * 2) }
|
||||
Column(Modifier.fillMaxSize().padding(top = pad.calculateTopPadding()).imePadding().navigationBarsPadding()) {
|
||||
LazyColumn(Modifier.weight(1f).fillMaxWidth(), state = list, contentPadding = PaddingValues(12.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
var lastDay: LocalDate? = null
|
||||
messages.forEachIndexed { i, m ->
|
||||
val day = Instant.ofEpochMilli(m.date).atZone(ZoneId.systemDefault()).toLocalDate()
|
||||
if (day != lastDay) {
|
||||
lastDay = day
|
||||
item(key = "d${m.id}") {
|
||||
Text(DateUtils.getRelativeTimeSpanString(m.date, System.currentTimeMillis(), DateUtils.DAY_IN_MILLIS).toString(),
|
||||
style = WType.label, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.fillMaxWidth().padding(vertical = 12.dp),
|
||||
textAlign = androidx.compose.ui.text.style.TextAlign.Center)
|
||||
}
|
||||
}
|
||||
val mine = m.box != MBox.INBOX
|
||||
val prevSame = messages.getOrNull(i - 1)?.let { (it.box != MBox.INBOX) == mine } == true
|
||||
val nextSame = messages.getOrNull(i + 1)?.let { (it.box != MBox.INBOX) == mine } == true
|
||||
item(key = m.id) { Bubble(m, mine, prevSame, nextSame, isLast = !nextSame, onRetry, onLong) }
|
||||
}
|
||||
}
|
||||
Row(Modifier.padding(8.dp), verticalAlignment = Alignment.Bottom) {
|
||||
TextField(
|
||||
text, { text = it }, Modifier.weight(1f).heightIn(min = 52.dp).clip(RoundedCornerShape(26.dp)),
|
||||
placeholder = { Text(stringResource(R.string.compose_hint)) }, maxLines = 6,
|
||||
colors = TextFieldDefaults.colors(focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent,
|
||||
focusedContainerColor = MaterialTheme.colorScheme.surfaceContainer, unfocusedContainerColor = MaterialTheme.colorScheme.surfaceContainer),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
val can = text.isNotBlank()
|
||||
Box(Modifier.size(52.dp).clip(CircleShape).background(if (can) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surfaceContainer)
|
||||
.clickable(enabled = can) { onSend(text.trim()); text = "" }, contentAlignment = Alignment.Center) {
|
||||
Icon(Icons.AutoMirrored.Rounded.Send, stringResource(R.string.send), tint = if (can) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Bubble(m: Message, mine: Boolean, prevSame: Boolean, nextSame: Boolean, isLast: Boolean, onRetry: (Message) -> Unit, onLong: (Message) -> Unit) {
|
||||
val s = MaterialTheme.colorScheme
|
||||
val big = 20.dp; val small = 6.dp
|
||||
val shape = if (mine) RoundedCornerShape(big, if (prevSame) small else big, if (nextSame) small else big, big)
|
||||
else RoundedCornerShape(if (prevSame) small else big, big, big, if (nextSame) small else big)
|
||||
val failed = m.box == MBox.FAILED
|
||||
Column(Modifier.fillMaxWidth().padding(top = if (prevSame) 0.dp else 6.dp), horizontalAlignment = if (mine) Alignment.End else Alignment.Start) {
|
||||
Box(
|
||||
Modifier.widthIn(max = 300.dp).clip(shape).background(if (mine) s.primary else s.surfaceContainerHigh)
|
||||
.combinedClickable(onClick = { if (failed) onRetry(m) }, onLongClick = { onLong(m) }).padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
) { Text(m.body, style = WType.body, color = if (mine) s.onPrimary else s.onSurface) }
|
||||
if (isLast || failed) {
|
||||
val status = when {
|
||||
failed -> stringResource(R.string.failed_retry)
|
||||
m.box == MBox.OUTBOX || m.box == MBox.QUEUED -> stringResource(R.string.sending)
|
||||
mine && m.status == android.provider.Telephony.Sms.STATUS_COMPLETE -> stringResource(R.string.delivered) + " · " + shortTime(m.date)
|
||||
else -> shortTime(m.date)
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp)) {
|
||||
if (failed) Icon(Icons.Rounded.ErrorOutline, null, Modifier.size(14.dp), tint = s.error)
|
||||
Text(" $status", style = WType.label, color = if (failed) s.error else s.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** S03 */
|
||||
@Composable
|
||||
fun NewChat(pad: PaddingValues, contacts: List<Pair<String, String>>, onPick: (String) -> Unit) {
|
||||
var q by rememberSaveable { mutableStateOf("") }
|
||||
val hits = remember(q, contacts) { contacts.filter { (n, num) -> q.isBlank() || n.contains(q, true) || num.filter(Char::isDigit).contains(q.filter(Char::isDigit).ifEmpty { "§" }) }.take(60) }
|
||||
Column(Modifier.fillMaxSize().padding(pad)) {
|
||||
TextField(q, { q = it }, Modifier.fillMaxWidth().padding(16.dp).clip(RoundedCornerShape(28.dp)), singleLine = true,
|
||||
prefix = { Text(stringResource(R.string.to) + " ") }, placeholder = { Text(stringResource(R.string.to_hint)) },
|
||||
colors = TextFieldDefaults.colors(focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent))
|
||||
LazyColumn {
|
||||
if (q.count(Char::isDigit) >= 3) item {
|
||||
Text(stringResource(R.string.send_to, q), style = WType.body, modifier = Modifier.fillMaxWidth().clickable { onPick(q) }.padding(horizontal = 24.dp, vertical = 14.dp))
|
||||
}
|
||||
items(hits) { (name, number) ->
|
||||
Row(Modifier.fillMaxWidth().clickable { onPick(number) }.padding(horizontal = 16.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Avatar(name, null, 40.dp); Spacer(Modifier.width(16.dp))
|
||||
Column { Text(name, style = WType.body); Text(number, style = WType.bodySm, color = MaterialTheme.colorScheme.onSurfaceVariant) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** S04 */
|
||||
@Composable
|
||||
fun SearchResults(pad: PaddingValues, search: (String) -> List<Message>, nameOf: (String) -> String, onOpen: (Message) -> Unit) {
|
||||
var q by rememberSaveable { mutableStateOf("") }
|
||||
val hits = remember(q) { search(q) }
|
||||
Column(Modifier.fillMaxSize().padding(pad)) {
|
||||
TextField(q, { q = it }, Modifier.fillMaxWidth().padding(16.dp).clip(RoundedCornerShape(28.dp)), singleLine = true, placeholder = { Text(stringResource(R.string.search_hint)) },
|
||||
colors = TextFieldDefaults.colors(focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent))
|
||||
LazyColumn {
|
||||
itemsIndexed(hits) { _, m ->
|
||||
Column(Modifier.fillMaxWidth().clickable { onOpen(m) }.padding(horizontal = 24.dp, vertical = 10.dp)) {
|
||||
Row { Text(nameOf(m.address), style = WType.body, modifier = Modifier.weight(1f)); Text(shortTime(m.date), style = WType.label) }
|
||||
val i = m.body.indexOf(q, ignoreCase = true)
|
||||
Text(buildAnnotatedString {
|
||||
if (i < 0) append(m.body) else {
|
||||
append(m.body.substring(0, i))
|
||||
withStyle(SpanStyle(fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary)) { append(m.body.substring(i, i + q.length)) }
|
||||
append(m.body.substring(i + q.length))
|
||||
}
|
||||
}, style = WType.bodySm, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package app.messages.ui.components
|
||||
|
||||
import android.graphics.BitmapFactory
|
||||
import android.net.Uri
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Person
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.Outline
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.Density
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.LayoutDirection
|
||||
import androidx.compose.ui.unit.sp
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
|
||||
/** 12-wave scalloped circle for the call screens. */
|
||||
object CookieShape : Shape {
|
||||
override fun createOutline(size: Size, layoutDirection: LayoutDirection, density: Density): Outline {
|
||||
val c = Offset(size.width / 2, size.height / 2); val r = size.minDimension / 2 * .94f
|
||||
val p = Path()
|
||||
for (i in 0..180) {
|
||||
val a = 2 * PI * i / 180
|
||||
val rr = r * (1 + .05f * cos(12 * a).toFloat())
|
||||
val x = c.x + rr * cos(a).toFloat(); val y = c.y + rr * sin(a).toFloat()
|
||||
if (i == 0) p.moveTo(x, y) else p.lineTo(x, y)
|
||||
}
|
||||
p.close()
|
||||
return Outline.Generic(p)
|
||||
}
|
||||
}
|
||||
|
||||
private val palette = listOf(0xFFD3E3FD, 0xFFC4EED0, 0xFFFFDAD6, 0xFFE9DDFF, 0xFFFFE08B, 0xFFC2E7FF).map { Color(it) }
|
||||
private val onPalette = listOf(0xFF041E49, 0xFF072711, 0xFF410002, 0xFF21005D, 0xFF241A00, 0xFF001E2F).map { Color(it) }
|
||||
|
||||
@Composable
|
||||
fun Avatar(name: String?, photo: Uri?, size: Dp, cookie: Boolean = false, modifier: Modifier = Modifier) {
|
||||
val ctx = LocalContext.current
|
||||
val bmp = produceState<ImageBitmap?>(null, photo) {
|
||||
value = photo?.let { u -> withContext(Dispatchers.IO) { runCatching { ctx.contentResolver.openInputStream(u)?.use { BitmapFactory.decodeStream(it)?.asImageBitmap() } }.getOrNull() } }
|
||||
}.value
|
||||
val shape = if (cookie) CookieShape else CircleShape
|
||||
val i = abs((name ?: "").hashCode()) % palette.size
|
||||
Box(modifier.size(size).clip(shape).background(palette[i]), contentAlignment = Alignment.Center) {
|
||||
when {
|
||||
bmp != null -> Image(bmp, null, Modifier.size(size), contentScale = ContentScale.Crop)
|
||||
!name.isNullOrBlank() && name.first().isLetter() -> Text(name.first().uppercase(), color = onPalette[i], fontSize = (size.value * .42f).sp)
|
||||
else -> Icon(Icons.Rounded.Person, null, tint = onPalette[i], modifier = Modifier.size(size * .55f))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package app.messages.ui.theme
|
||||
|
||||
import android.os.Build
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.material3.dynamicDarkColorScheme
|
||||
import androidx.compose.material3.dynamicLightColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
|
||||
@Composable
|
||||
fun MsgTheme(dynamic: Boolean = true, forceDark: Boolean? = null, content: @Composable () -> Unit) {
|
||||
val dark = forceDark ?: isSystemInDarkTheme()
|
||||
val ctx = LocalContext.current
|
||||
val scheme = when {
|
||||
dynamic && Build.VERSION.SDK_INT >= 31 -> if (dark) dynamicDarkColorScheme(ctx) else dynamicLightColorScheme(ctx)
|
||||
dark -> darkColorScheme(primary = WColor.darkBubbleOut, onPrimary = WColor.darkOnBubbleOut, background = WColor.darkBg, surface = WColor.darkBg,
|
||||
surfaceContainerLowest = WColor.darkRow, surfaceContainerHigh = WColor.darkBubbleIn, surfaceContainer = WColor.darkComposer,
|
||||
primaryContainer = WColor.darkFab, onPrimaryContainer = WColor.darkOnFab, onSurface = WColor.darkText, onSurfaceVariant = WColor.darkTextMuted, error = WColor.darkError)
|
||||
else -> lightColorScheme(primary = WColor.bubbleOut, onPrimary = WColor.onBubbleOut, background = WColor.bg, surface = WColor.bg,
|
||||
surfaceContainerLowest = WColor.row, surfaceContainerHigh = WColor.bubbleIn, surfaceContainer = WColor.composer,
|
||||
primaryContainer = WColor.fab, onPrimaryContainer = WColor.onFab, onSurface = WColor.text, onSurfaceVariant = WColor.textMuted, error = WColor.error)
|
||||
}
|
||||
MaterialTheme(colorScheme = scheme, content = content)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// Generated from tokens.json by gen_theme.py. Do not edit by hand.
|
||||
package app.messages.ui.theme
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
object WColor {
|
||||
val bg = Color(0xFFF8F9FF)
|
||||
val row = Color(0xFFFFFFFF)
|
||||
val text = Color(0xFF191C20)
|
||||
val textMuted = Color(0xFF44474E)
|
||||
val bubbleIn = Color(0xFFE8EAF1)
|
||||
val onBubbleIn = Color(0xFF191C20)
|
||||
val bubbleOut = Color(0xFF2B5EA7)
|
||||
val onBubbleOut = Color(0xFFFFFFFF)
|
||||
val unread = Color(0xFF2B5EA7)
|
||||
val error = Color(0xFFBA1A1A)
|
||||
val fab = Color(0xFFD6E3FF)
|
||||
val onFab = Color(0xFF001B3E)
|
||||
val composer = Color(0xFFECEEF4)
|
||||
val onComposer = Color(0xFF191C20)
|
||||
val darkBg = Color(0xFF111318)
|
||||
val darkRow = Color(0xFF1D2024)
|
||||
val darkText = Color(0xFFE2E2E9)
|
||||
val darkTextMuted = Color(0xFFC4C6D0)
|
||||
val darkBubbleIn = Color(0xFF2B2F36)
|
||||
val darkOnBubbleIn = Color(0xFFE2E2E9)
|
||||
val darkBubbleOut = Color(0xFFA8C7FA)
|
||||
val darkOnBubbleOut = Color(0xFF062E6F)
|
||||
val darkUnread = Color(0xFFA8C7FA)
|
||||
val darkError = Color(0xFFFFB4AB)
|
||||
val darkFab = Color(0xFF284777)
|
||||
val darkOnFab = Color(0xFFD6E3FF)
|
||||
val darkComposer = Color(0xFF2B2F36)
|
||||
val darkOnComposer = Color(0xFFE2E2E9)
|
||||
}
|
||||
|
||||
object WType {
|
||||
val label = TextStyle(fontSize = 12.sp, lineHeight = 16.sp, fontWeight = FontWeight.W500)
|
||||
val bodySm = TextStyle(fontSize = 14.sp, lineHeight = 20.sp, fontWeight = FontWeight.W400)
|
||||
val body = TextStyle(fontSize = 16.sp, lineHeight = 22.sp, fontWeight = FontWeight.W400)
|
||||
val title = TextStyle(fontSize = 22.sp, lineHeight = 28.sp, fontWeight = FontWeight.W400)
|
||||
}
|
||||
|
||||
object WSpace {
|
||||
val s0 = 0.dp
|
||||
val s2 = 2.dp
|
||||
val s4 = 4.dp
|
||||
val s8 = 8.dp
|
||||
val s12 = 12.dp
|
||||
val s16 = 16.dp
|
||||
val s24 = 24.dp
|
||||
}
|
||||
|
||||
object WRadius {
|
||||
val bubble = 20.dp
|
||||
val bubbleTight = 6.dp
|
||||
val pill = 999.dp
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108"><path android:fillColor="#FF0E4F8A" android:pathData="M0,0h108v108h-108z"/></vector>
|
||||
@@ -0,0 +1 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108"><path android:fillColor="#FFCFE5FF" android:pathData="M36,32h36a8,8 0 0 1 8,8v22a8,8 0 0 1 -8,8h-20l-12,10v-10h-4a8,8 0 0 1 -8,-8v-22a8,8 0 0 1 8,-8z"/><path android:fillColor="#FF0E4F8A" android:pathData="M44,51m-3.2,0a3.2,3.2 0 1,0 6.4,0a3.2,3.2 0 1,0 -6.4,0"/><path android:fillColor="#FF0E4F8A" android:pathData="M54,51m-3.2,0a3.2,3.2 0 1,0 6.4,0a3.2,3.2 0 1,0 -6.4,0"/><path android:fillColor="#FF0E4F8A" android:pathData="M64,51m-3.2,0a3.2,3.2 0 1,0 6.4,0a3.2,3.2 0 1,0 -6.4,0"/></vector>
|
||||
@@ -0,0 +1 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108"><path android:fillColor="#FF000000" android:pathData="M36,32h36a8,8 0 0 1 8,8v22a8,8 0 0 1 -8,8h-20l-12,10v-10h-4a8,8 0 0 1 -8,-8v-22a8,8 0 0 1 8,-8z"/><path android:fillColor="#FFFFFFFF" android:pathData="M44,51m-3.2,0a3.2,3.2 0 1,0 6.4,0a3.2,3.2 0 1,0 -6.4,0"/><path android:fillColor="#FFFFFFFF" android:pathData="M54,51m-3.2,0a3.2,3.2 0 1,0 6.4,0a3.2,3.2 0 1,0 -6.4,0"/><path android:fillColor="#FFFFFFFF" android:pathData="M64,51m-3.2,0a3.2,3.2 0 1,0 6.4,0a3.2,3.2 0 1,0 -6.4,0"/></vector>
|
||||
@@ -0,0 +1 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24"><path android:fillColor="#FFFFFFFF" android:pathData="M4,4h16a2,2 0 0 1 2,2v10a2,2 0 0 1 -2,2H8l-4,4V6a2,2 0 0 1 2,-2z"/></vector>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background"/>
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
|
||||
<monochrome android:drawable="@drawable/ic_launcher_monochrome"/>
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,36 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_title">Nachrichten</string>
|
||||
<string name="search">Suchen</string>
|
||||
<string name="search_hint">Nachrichten durchsuchen</string>
|
||||
<string name="back">Zurück</string>
|
||||
<string name="archived">Archiviert</string>
|
||||
<string name="archive">Archivieren</string>
|
||||
<string name="delete">Löschen</string>
|
||||
<string name="delete_confirm">%1$d Unterhaltungen löschen?</string>
|
||||
<string name="copy">Text kopieren</string>
|
||||
<string name="call">Anrufen</string>
|
||||
<string name="start_chat">Chat starten</string>
|
||||
<string name="new_chat">Neuer Chat</string>
|
||||
<string name="to">An:</string>
|
||||
<string name="to_hint">Name oder Nummer</string>
|
||||
<string name="send_to">An %1$s senden</string>
|
||||
<string name="no_threads">Noch keine Unterhaltungen</string>
|
||||
<string name="you_prefix">"Du: "</string>
|
||||
<string name="compose_hint">SMS schreiben</string>
|
||||
<string name="send">Senden</string>
|
||||
<string name="sending">Wird gesendet …</string>
|
||||
<string name="delivered">Zugestellt</string>
|
||||
<string name="failed_retry">Nicht gesendet, tippen zum Wiederholen</string>
|
||||
<string name="default_title">Als Standard-SMS-App festlegen</string>
|
||||
<string name="default_text">Nur die Standard-SMS-App darf Nachrichten empfangen und senden. Du kannst das jederzeit in den Android-Einstellungen ändern.</string>
|
||||
<string name="need_role_send">Zum Senden muss diese App deine Standard-SMS-App sein.</string>
|
||||
<string name="make_default">Als Standard festlegen</string>
|
||||
<string name="ch_messages">Nachrichten</string>
|
||||
<string name="me">Ich</string>
|
||||
<string name="reply">Antworten</string>
|
||||
<string name="reply_hint">Nachricht</string>
|
||||
<string name="mark_read">Als gelesen markieren</string>
|
||||
<string name="mms_title">MMS empfangen</string>
|
||||
<string name="mms_text">Bilder und Gruppennachrichten (MMS) werden noch nicht unterstützt.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,49 @@
|
||||
package app.messages
|
||||
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.test.junit4.createComposeRule
|
||||
import androidx.compose.ui.test.onRoot
|
||||
import app.messages.data.Box
|
||||
import app.messages.data.Message
|
||||
import app.messages.data.Thread
|
||||
import app.messages.ui.Conversation
|
||||
import app.messages.ui.ConversationList
|
||||
import app.messages.ui.theme.MsgTheme
|
||||
import com.github.takahirom.roborazzi.captureRoboImage
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
|
||||
/** Made-up people and texts. */
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(sdk = [35], qualifiers = "de-rDE-w412dp-h915dp-xxhdpi", application = android.app.Application::class)
|
||||
class ScreenshotTest {
|
||||
@get:Rule val compose = createComposeRule()
|
||||
private val now = System.currentTimeMillis()
|
||||
private val threads = listOf(
|
||||
Thread(1, "+4930555012", "Clara Wu", null, "Sehen wir uns morgen am Bahnhof?", now - 120_000, 2, false, false),
|
||||
Thread(2, "+4930555013", "Ben Okafor", null, "Alles klar, bis später!", now - 3_600_000, 0, true, false),
|
||||
Thread(3, "+4930555077", "Fahrradladen", null, "Ihr Rad ist abholbereit.", now - 90_000_000, 0, false, false),
|
||||
Thread(4, "88888", null, null, "Ihr Bestätigungscode lautet 482913", now - 200_000_000, 0, false, false),
|
||||
)
|
||||
private val msgs = listOf(
|
||||
Message(1, 1, "+4930555012", "Hey! Hast du am Wochenende Zeit?", now - 7_200_000, Box.INBOX, true, -1),
|
||||
Message(2, 1, "+4930555012", "Wir wollten wandern gehen 🥾", now - 7_100_000, Box.INBOX, true, -1),
|
||||
Message(3, 1, "", "Klingt super, ich bin dabei!", now - 7_000_000, Box.SENT, true, 0),
|
||||
Message(4, 1, "", "Wann geht es los?", now - 6_900_000, Box.SENT, true, 0),
|
||||
Message(5, 1, "+4930555012", "Sehen wir uns morgen am Bahnhof?", now - 120_000, Box.INBOX, false, -1),
|
||||
Message(6, 1, "", "Ja, um 9 Uhr am Gleis 3", now - 60_000, Box.FAILED, true, -1),
|
||||
)
|
||||
private fun shot(name: String, dark: Boolean, c: @Composable () -> Unit) {
|
||||
compose.setContent { MsgTheme(dynamic = false, forceDark = dark) { c() } }
|
||||
compose.onRoot().captureRoboImage("../../replica/messages/clone-screens/$name.png")
|
||||
}
|
||||
@Test fun s01_list() = shot("S01-list-light", false) { ConversationList(threads, PaddingValues(), {}, {}, emptySet()) }
|
||||
@Test fun s02_chat_dark() = shot("S02-chat-dark", true) { Conversation(msgs, PaddingValues(), {}, {}, {}) }
|
||||
@Test fun s02_chat_light() = shot("S02-chat-light", false) { Conversation(msgs, PaddingValues(), {}, {}, {}) }
|
||||
}
|
||||
Reference in New Issue
Block a user