Skip to content

CircleToSearch with multi search engine support for all android

Kotlin

multi QR codes detection

AKS Labs4fe89b0f9b93
diff --git a/app/src/main/java/com/akslabs/circletosearch/ui/QrCodeResultSheet.kt b/app/src/main/java/com/akslabs/circletosearch/ui/QrCodeResultSheet.kt
index fb73469..5f30cac 100644
--- a/app/src/main/java/com/akslabs/circletosearch/ui/QrCodeResultSheet.kt
+++ b/app/src/main/java/com/akslabs/circletosearch/ui/QrCodeResultSheet.kt
@@ -9,7 +9,6 @@ import android.provider.ContactsContract
import android.widget.Toast
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
-import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
@@ -22,6 +21,7 @@ import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -36,40 +36,40 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.ChevronLeft
+import androidx.compose.material.icons.filled.ChevronRight
import androidx.compose.material.icons.filled.ContentCopy
-import androidx.compose.material.icons.filled.Language
import androidx.compose.material.icons.filled.LocationOn
import androidx.compose.material.icons.filled.Phone
import androidx.compose.material.icons.filled.QrCode
-import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.ShoppingBag
-import androidx.compose.material.icons.filled.Sms
import androidx.compose.material.icons.filled.Wifi
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
-import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
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.Brush
import androidx.compose.ui.graphics.Color
-import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.akslabs.circletosearch.utils.QrResult
+import com.akslabs.circletosearch.utils.QrResultWithBounds
+import com.akslabs.circletosearch.utils.QrScanner
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -86,94 +86,90 @@ private fun openUrl(context: Context, url: String) {
})
}
+fun qrResultShortLabel(result: QrResult): String = when (result) {
+ is QrResult.Url -> result.displayUrl.take(30)
+ is QrResult.WiFi -> result.ssid
+ is QrResult.Phone -> result.number
+ is QrResult.Product -> result.barcode
+ is QrResult.VCard -> result.name ?: "Contact"
+ is QrResult.GeoPoint -> "%.4f, %.4f".format(result.lat, result.lng)
+ is QrResult.PlainText -> result.text.take(30)
+}
+
@Composable
fun QrCodeResultSheet(
context: Context,
bitmap: android.graphics.Bitmap?,
- onDismiss: () -> Unit
+ onDismiss: () -> Unit,
+ // Supply pre-scanned results to avoid re-scanning; null = scan now
+ preScanned: List<QrResultWithBounds>? = null
) {
val scope = rememberCoroutineScope()
- var qrResult by remember { mutableStateOf<QrResult?>(null) }
- var isScanning by remember { mutableStateOf(true) }
+ var results by remember { mutableStateOf<List<QrResultWithBounds>>(preScanned ?: emptyList()) }
+ var isScanning by remember { mutableStateOf(preScanned == null) }
var notFound by remember { mutableStateOf(false) }
+ var currentIndex by remember { mutableIntStateOf(0) }
- // Animate scanline
val infiniteTransition = rememberInfiniteTransition(label = "scanline")
val scanlineY by infiniteTransition.animateFloat(
- initialValue = 0f,
- targetValue = 1f,
- animationSpec = infiniteRepeatable(
- animation = tween(1500, easing = LinearEasing),
- repeatMode = RepeatMode.Reverse
- ),
+ initialValue = 0f, targetValue = 1f,
+ animationSpec = infiniteRepeatable(tween(1500, easing = LinearEasing), RepeatMode.Reverse),
label = "scanlineY"
)
LaunchedEffect(bitmap) {
+ if (preScanned != null) return@LaunchedEffect
if (bitmap == null) { isScanning = false; notFound = true; return@LaunchedEffect }
- isScanning = true
- notFound = false
- qrResult = null
- val result = withContext(Dispatchers.Default) {
- com.akslabs.circletosearch.utils.QrScanner.scanBitmap(bitmap)
- }
+ isScanning = true; notFound = false
+ val found = withContext(Dispatchers.Default) { QrScanner.scanBitmapAll(bitmap) }
isScanning = false
- if (result == null) notFound = true else qrResult = result
+ if (found.isEmpty()) notFound = true else { results = found; currentIndex = 0 }
}
- // Overall container
- val slideIn = slideInVertically(tween(400, easing = FastOutSlowInEasing)) { it / 2 }
- val fadeIn = fadeIn(tween(400))
-
- AnimatedVisibility(
- visible = true,
- enter = slideIn + fadeIn
+ Surface(
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
+ shape = RoundedCornerShape(24.dp),
+ color = MaterialTheme.colorScheme.surfaceContainerHigh,
+ tonalElevation = 6.dp, shadowElevation = 12.dp
) {
- Surface(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = 16.dp, vertical = 8.dp),
- shape = RoundedCornerShape(24.dp),
- color = MaterialTheme.colorScheme.surfaceContainerHigh,
- tonalElevation = 6.dp,
- shadowElevation = 12.dp
- ) {
- Column(
- modifier = Modifier.padding(20.dp),
- horizontalAlignment = Alignment.CenterHorizontally
- ) {
- // Header
- Row(verticalAlignment = Alignment.CenterVertically) {
- Icon(
- Icons.Default.QrCode,
- contentDescription = null,
- tint = MaterialTheme.colorScheme.primary,
- modifier = Modifier.size(20.dp)
- )
- Spacer(Modifier.width(8.dp))
- Text(
- "QR / Barcode",
- style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold)
- )
+ Column(modifier = Modifier.padding(20.dp), horizontalAlignment = Alignment.CenterHorizontally) {
+ // Header row
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Icon(Icons.Default.QrCode, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp))
+ Spacer(Modifier.width(8.dp))
+ val titleText = when {
+ isScanning -> "Scanning…"
+ notFound -> "No QR Found"
+ results.size > 1 -> "QR ${currentIndex + 1} of ${results.size}"
+ else -> "QR / Barcode"
}
+ Text(titleText, style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold), modifier = Modifier.weight(1f))
+ // Multi-result navigation
+ if (results.size > 1) {
+ IconButton(onClick = { currentIndex = (currentIndex - 1 + results.size) % results.size }, modifier = Modifier.size(32.dp)) {
+ Icon(Icons.Default.ChevronLeft, null)
+ }
+ IconButton(onClick = { currentIndex = (currentIndex + 1) % results.size }, modifier = Modifier.size(32.dp)) {
+ Icon(Icons.Default.ChevronRight, null)
+ }
+ }
+ }
- Spacer(Modifier.height(16.dp))
+ Spacer(Modifier.height(16.dp))
- // Content area
- AnimatedContent(
- targetState = when {
- isScanning -> "scanning"
- notFound -> "notfound"
- else -> "result"
- },
- transitionSpec = { fadeIn(tween(300)) togetherWith fadeOut(tween(200)) },
- label = "qrContent"
- ) { state ->
- when (state) {
- "scanning" -> ScanningIndicator(scanlineY)
- "notfound" -> NotFoundContent()
- else -> qrResult?.let { QrResultContent(context, it) }
- }
+ AnimatedContent(
+ targetState = when {
+ isScanning -> "scanning"
+ notFound -> "notfound"
+ else -> "result_${currentIndex}"
+ },
+ transitionSpec = { fadeIn(tween(300)) togetherWith fadeOut(tween(200)) },
+ label = "qrState"
+ ) { state ->
+ when {
+ state == "scanning" -> ScanningIndicator(scanlineY)
+ state == "notfound" -> NotFoundContent()
+ results.isNotEmpty() -> QrResultContent(context, results[currentIndex].result)
}
}
}
@@ -181,79 +177,57 @@ fun QrCodeResultSheet(
}
@Composable
-private fun ScanningIndicator(scanlineY: Float) {
+fun ScanningIndicator(scanlineY: Float) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Box(
- modifier = Modifier
- .size(80.dp)
- .clip(RoundedCornerShape(16.dp))
- .background(MaterialTheme.colorScheme.surfaceContainerHighest),
+ modifier = Modifier.size(80.dp).background(MaterialTheme.colorScheme.surfaceContainerHighest, RoundedCornerShape(16.dp)),
contentAlignment = Alignment.Center
) {
- CircularProgressIndicator(
- modifier = Modifier.size(40.dp),
- strokeWidth = 3.dp,
- color = MaterialTheme.colorScheme.primary
- )
- // Scanline effect
- Box(
- modifier = Modifier
- .fillMaxWidth()
- .height(2.dp)
- .offset(y = (80.dp * scanlineY) - 40.dp)
- .background(
- Brush.horizontalGradient(
- listOf(Color.Transparent, MaterialTheme.colorScheme.primary, Color.Transparent)
- )
- )
+ CircularProgressIndicator(modifier = Modifier.size(40.dp), strokeWidth = 3.dp, color = MaterialTheme.colorScheme.primary)
+ Box(modifier = Modifier.fillMaxWidth().height(2.dp)
+ .offset(y = (80.dp * scanlineY) - 40.dp)
+ .background(Brush.horizontalGradient(listOf(Color.Transparent, MaterialTheme.colorScheme.primary, Color.Transparent)))
)
}
Spacer(Modifier.height(12.dp))
- Text("Scanning for QR codes…", style = MaterialTheme.typography.bodyMedium,
- color = MaterialTheme.colorScheme.onSurfaceVariant)
+ Text("Scanning for QR codes…", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
@Composable
-private fun NotFoundContent() {
+fun NotFoundContent() {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text("🔍", style = MaterialTheme.typography.headlineLarge)
Spacer(Modifier.height(8.dp))
- Text("No QR code found", style = MaterialTheme.typography.bodyLarge,
- color = MaterialTheme.colorScheme.onSurfaceVariant)
- Text("Try circling the QR code more precisely",
- style = MaterialTheme.typography.bodySmall,
- color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f))
+ Text("No QR code found", style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ Text("Try circling the QR code more precisely", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f))
}
}
@Composable
-private fun QrResultContent(context: Context, result: QrResult) {
- val slideIn = slideInVertically(tween(350, delayMillis = 50)) { it / 3 } + fadeIn(tween(300))
- AnimatedVisibility(visible = true, enter = slideIn) {
+fun QrResultContent(context: Context, result: QrResult) {
+ AnimatedVisibility(visible = true, enter = slideInVertically(tween(350)) { it / 3 } + fadeIn(tween(300))) {
when (result) {
- is QrResult.Url -> UrlResult(context, result)
- is QrResult.WiFi -> WifiResult(context, result)
- is QrResult.Phone -> PhoneResult(context, result)
- is QrResult.Product -> ProductResult(context, result)
- is QrResult.VCard -> VCardResult(context, result)
- is QrResult.GeoPoint -> GeoResult(context, result)
+ is QrResult.Url -> UrlResult(context, result)
+ is QrResult.WiFi -> WifiResult(context, result)
+ is QrResult.Phone -> PhoneResult(context, result)
+ is QrResult.Product -> ProductResult(context, result)
+ is QrResult.VCard -> VCardResult(context, result)
+ is QrResult.GeoPoint -> GeoResult(context, result)
is QrResult.PlainText -> PlainTextResult(context, result)
}
}
}
-// ── Result types ────────────────────────────────────────────────────────────
-
@Composable
private fun UrlResult(context: Context, result: QrResult.Url) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
- ResultHeader("🔗", result.displayUrl.substringBefore("/"), result.displayUrl)
+ Text("🔗", style = MaterialTheme.typography.headlineLarge)
+ Spacer(Modifier.height(4.dp))
+ Text(result.displayUrl.substringBefore("/"), style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.Bold), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(result.displayUrl, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 2)
Spacer(Modifier.height(16.dp))
- ActionRow {
- PrimaryAction("Open in Browser") { openUrl(context, result.url) }
- SecondaryAction("Copy Link") { copyToClipboard(context, "URL", result.url) }
- }
+ ActionRow { PrimaryAction("Open in Browser") { openUrl(context, result.url) }; SecondaryAction("Copy Link") { copyToClipboard(context, "URL", result.url) } }
}
}
@@ -261,16 +235,10 @@ private fun UrlResult(context: Context, result: QrResult.Url) {
private fun WifiResult(context: Context, result: QrResult.WiFi) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Icon(Icons.Default.Wifi, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(32.dp))
- Spacer(Modifier.height(4.dp))
Text(result.ssid, style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.Bold))
- Text("${result.security} · Password: ${result.password ?: "None"}",
- style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ Text("${result.security}${if (result.password != null) " · Password: ${result.password}" else ""}", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
Spacer(Modifier.height(16.dp))
- ActionRow {
- if (result.password != null) {
- SecondaryAction("Copy Password") { copyToClipboard(context, "WiFi Password", result.password) }
- }
- }
+ ActionRow { if (result.password != null) SecondaryAction("Copy Password") { copyToClipboard(context, "WiFi Password", result.password) } }
}
}
@@ -278,12 +246,11 @@ private fun WifiResult(context: Context, result: QrResult.WiFi) {
private fun PhoneResult(context: Context, result: QrResult.Phone) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Icon(Icons.Default.Phone, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(32.dp))
- Spacer(Modifier.height(4.dp))
Text(result.number, style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.Bold))
Spacer(Modifier.height(16.dp))
ActionRow {
PrimaryAction("Call") { openUrl(context, "tel:${result.number}") }
- SecondaryAction("Send SMS") { openUrl(context, "sms:${result.number}") }
+ SecondaryAction("SMS") { openUrl(context, "sms:${result.number}") }
SecondaryAction("Copy") { copyToClipboard(context, "Phone", result.number) }
}
}
@@ -293,16 +260,11 @@ private fun PhoneResult(context: Context, result: QrResult.Phone) {
private fun ProductResult(context: Context, result: QrResult.Product) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Icon(Icons.Default.ShoppingBag, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(32.dp))
- Spacer(Modifier.height(4.dp))
Text(result.barcode, style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.Bold))
Spacer(Modifier.height(16.dp))
ActionRow {
- PrimaryAction("Search Amazon") {
- openUrl(context, "https://www.amazon.com/s?k=${result.barcode}")
- }
- SecondaryAction("Google") {
- openUrl(context, "https://www.google.com/search?q=${result.barcode}")
- }
+ PrimaryAction("Amazon") { openUrl(context, "https://www.amazon.com/s?k=${result.barcode}") }
+ SecondaryAction("Google") { openUrl(context, "https://www.google.com/search?q=${result.barcode}") }
SecondaryAction("Copy") { copyToClipboard(context, "Barcode", result.barcode) }
}
}
@@ -318,14 +280,13 @@ private fun VCardResult(context: Context, result: QrResult.VCard) {
Spacer(Modifier.height(16.dp))
ActionRow {
PrimaryAction("Save Contact") {
- val i = Intent(Intent.ACTION_INSERT).apply {
+ context.startActivity(Intent(Intent.ACTION_INSERT).apply {
type = ContactsContract.RawContacts.CONTENT_TYPE
result.name?.let { putExtra(ContactsContract.Intents.Insert.NAME, it) }
result.phone?.let { putExtra(ContactsContract.Intents.Insert.PHONE, it) }
result.email?.let { putExtra(ContactsContract.Intents.Insert.EMAIL, it) }
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
- }
- context.startActivity(i)
+ })
}
SecondaryAction("Copy") { copyToClipboard(context, "Contact", result.raw) }
}
@@ -334,17 +295,14 @@ private fun VCardResult(context: Context, result: QrResult.VCard) {
@Composable
private fun GeoResult(context: Context, result: QrResult.GeoPoint) {
- val coordStr = "%.4f° N, %.4f° E".format(result.lat, result.lng)
+ val coord = "%.4f° N, %.4f° E".format(result.lat, result.lng)
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Icon(Icons.Default.LocationOn, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(32.dp))
- Spacer(Modifier.height(4.dp))
- Text(coordStr, style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold))
+ Text(coord, style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold))
Spacer(Modifier.height(16.dp))
ActionRow {
- PrimaryAction("Open in Maps") {
- openUrl(context, "geo:${result.lat},${result.lng}?q=${result.lat},${result.lng}")
- }
- SecondaryAction("Copy") { copyToClipboard(context, "Coordinates", coordStr) }
+ PrimaryAction("Open Maps") { openUrl(context, "geo:${result.lat},${result.lng}?q=${result.lat},${result.lng}") }
+ SecondaryAction("Copy") { copyToClipboard(context, "Coordinates", coord) }
}
}
}
@@ -354,62 +312,27 @@ private fun PlainTextResult(context: Context, result: QrResult.PlainText) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text("📋", style = MaterialTheme.typography.headlineLarge)
Spacer(Modifier.height(4.dp))
- Text(
- "\"${result.text}\"",
- style = MaterialTheme.typography.bodyLarge,
- maxLines = 4,
- overflow = TextOverflow.Ellipsis,
- color = MaterialTheme.colorScheme.onSurface
- )
+ Text("\"${result.text}\"", style = MaterialTheme.typography.bodyLarge, maxLines = 4, overflow = TextOverflow.Ellipsis)
Spacer(Modifier.height(16.dp))
ActionRow {
SecondaryAction("Copy") { copyToClipboard(context, "Text", result.text) }
- SecondaryAction("Search") {
- openUrl(context, "https://www.google.com/search?q=${Uri.encode(result.text)}")
- }
- SecondaryAction("Translate") {
- openUrl(context, "https://translate.google.com/?text=${Uri.encode(result.text)}")
- }
+ SecondaryAction("Search") { openUrl(context, "https://www.google.com/search?q=${Uri.encode(result.text)}") }
+ SecondaryAction("Translate") { openUrl(context, "https://translate.google.com/?text=${Uri.encode(result.text)}") }
}
}
}
-// ── Shared UI helpers ───────────────────────────────────────────────────────
-
-@Composable
-private fun ResultHeader(emoji: String, title: String, subtitle: String) {
- Column(horizontalAlignment = Alignment.CenterHorizontally) {
- Text(emoji, style = MaterialTheme.typography.headlineLarge)
- Spacer(Modifier.height(4.dp))
- Text(title, style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.Bold),
- maxLines = 1, overflow = TextOverflow.Ellipsis)
- Text(subtitle, style = MaterialTheme.typography.bodyMedium,
- color = MaterialTheme.colorScheme.onSurfaceVariant,
- maxLines = 2, overflow = TextOverflow.Ellipsis)
- }
-}
-
@Composable
private fun ActionRow(content: @Composable () -> Unit) {
- Row(
- modifier = Modifier.fillMaxWidth(),
- horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
- verticalAlignment = Alignment.CenterVertically
- ) {
- content()
- }
+ Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally), verticalAlignment = Alignment.CenterVertically) { content() }
}
@Composable
private fun PrimaryAction(label: String, onClick: () -> Unit) {
- Button(onClick = onClick, shape = RoundedCornerShape(12.dp)) {
- Text(label, style = MaterialTheme.typography.labelMedium)
- }
+ Button(onClick = onClick, shape = RoundedCornerShape(12.dp)) { Text(label, style = MaterialTheme.typography.labelMedium) }
}
@Composable
private fun SecondaryAction(label: String, onClick: () -> Unit) {
- FilledTonalButton(onClick = onClick, shape = RoundedCornerShape(12.dp)) {
- Text(label, style = MaterialTheme.typography.labelMedium)
- }
+ FilledTonalButton(onClick = onClick, shape = RoundedCornerShape(12.dp)) { Text(label, style = MaterialTheme.typography.labelMedium) }
}
diff --git a/app/src/main/java/com/akslabs/circletosearch/utils/QrScanner.kt b/app/src/main/java/com/akslabs/circletosearch/utils/QrScanner.kt
index 1df4a2c..2d7c7cd 100644
--- a/app/src/main/java/com/akslabs/circletosearch/utils/QrScanner.kt
+++ b/app/src/main/java/com/akslabs/circletosearch/utils/QrScanner.kt
@@ -1,13 +1,17 @@
package com.akslabs.circletosearch.utils
import android.graphics.Bitmap
+import android.graphics.RectF
import com.google.zxing.BarcodeFormat
import com.google.zxing.BinaryBitmap
import com.google.zxing.DecodeHintType
import com.google.zxing.MultiFormatReader
+import com.google.zxing.NotFoundException
import com.google.zxing.RGBLuminanceSource
import com.google.zxing.Result
+import com.google.zxing.ResultPoint
import com.google.zxing.common.HybridBinarizer
+import com.google.zxing.multi.GenericMultipleBarcodeReader
// Sealed class representing all supported QR / barcode result types
sealed class QrResult {
@@ -20,9 +24,32 @@ sealed class QrResult {
data class PlainText(val text: String) : QrResult()
}
+/** Wraps a parsed QR result with its bounding box in bitmap-pixel coordinates */
+data class QrResultWithBounds(
+ val result: QrResult,
+ val rawText: String,
+ /** Bounds in bitmap pixel coords (may be null if position unavailable) */
+ val bounds: RectF?
+)
+
object QrScanner {
- fun scanBitmap(bitmap: Bitmap): QrResult? {
+ private val HINTS = mapOf(
+ DecodeHintType.TRY_HARDER to true,
+ DecodeHintType.POSSIBLE_FORMATS to listOf(
+ BarcodeFormat.QR_CODE,
+ BarcodeFormat.EAN_13,
+ BarcodeFormat.EAN_8,
+ BarcodeFormat.UPC_A,
+ BarcodeFormat.DATA_MATRIX,
+ BarcodeFormat.PDF_417,
+ BarcodeFormat.CODE_128,
+ BarcodeFormat.CODE_39
+ )
+ )
+
+ /** Scan for all barcodes / QR codes in the given bitmap. Returns empty list when none found. */
+ fun scanBitmapAll(bitmap: Bitmap): List<QrResultWithBounds> {
return try {
val width = bitmap.width
val height = bitmap.height
@@ -32,46 +59,50 @@ object QrScanner {
val source = RGBLuminanceSource(width, height, pixels)
val binaryBitmap = BinaryBitmap(HybridBinarizer(source))
- val hints = mapOf(
- DecodeHintType.TRY_HARDER to true,
- DecodeHintType.POSSIBLE_FORMATS to listOf(
- BarcodeFormat.QR_CODE,
- BarcodeFormat.EAN_13,
- BarcodeFormat.EAN_8,
- BarcodeFormat.UPC_A,
- BarcodeFormat.DATA_MATRIX,
- BarcodeFormat.PDF_417
- )
- )
+ val multiReader = GenericMultipleBarcodeReader(MultiFormatReader())
+ val rawResults: Array<Result> = try {
+ multiReader.decodeMultiple(binaryBitmap, HINTS)
+ } catch (e: NotFoundException) {
+ emptyArray()
+ }
- val reader = MultiFormatReader()
- val result: Result = reader.decode(binaryBitmap, hints)
- parseResult(result.text)
+ rawResults.mapNotNull { raw ->
+ try {
+ val bounds = computeBounds(raw.resultPoints)
+ QrResultWithBounds(parseResult(raw.text), raw.text, bounds)
+ } catch (e: Exception) { null }
+ }
} catch (e: Exception) {
- null
+ emptyList()
}
}
- private fun parseResult(text: String): QrResult {
+ /** Compatibility single-result scan (kept for backward compat). */
+ fun scanBitmap(bitmap: Bitmap): QrResult? = scanBitmapAll(bitmap).firstOrNull()?.result
+
+ private fun computeBounds(points: Array<ResultPoint>?): RectF? {
+ if (points.isNullOrEmpty()) return null
+ var minX = Float.MAX_VALUE; var minY = Float.MAX_VALUE
+ var maxX = Float.MIN_VALUE; var maxY = Float.MIN_VALUE
+ for (p in points) {
+ if (p == null) continue
+ if (p.x < minX) minX = p.x; if (p.x > maxX) maxX = p.x
+ if (p.y < minY) minY = p.y; if (p.y > maxY) maxY = p.y
+ }
+ return if (minX == Float.MAX_VALUE) null else RectF(minX - 20f, minY - 20f, maxX + 20f, maxY + 20f)
+ }
+
+ fun parseResult(text: String): QrResult {
return when {
- // URL
text.startsWith("http://", ignoreCase = true) || text.startsWith("https://", ignoreCase = true) -> {
val display = text.removePrefix("http://").removePrefix("https://").trimEnd('/')
QrResult.Url(text, display)
}
- // WiFi: WIFI:S:SSID;T:WPA;P:password;;
text.startsWith("WIFI:", ignoreCase = true) -> parseWifi(text)
- // Tel
- text.startsWith("tel:", ignoreCase = true) -> {
- QrResult.Phone(text.removePrefix("tel:").trim())
- }
- // vCard
+ text.startsWith("tel:", ignoreCase = true) -> QrResult.Phone(text.removePrefix("tel:").trim())
text.startsWith("BEGIN:VCARD", ignoreCase = true) -> parseVCard(text)
- // Geo
text.startsWith("geo:", ignoreCase = true) -> parseGeo(text)
- // Barcode-only (all digits, length 8-14)
text.matches(Regex("\\d{8,14}")) -> QrResult.Product(text)
- // Plain text fallback
else -> QrResult.PlainText(text)
}
}
@@ -93,11 +124,7 @@ object QrScanner {
private fun parseGeo(text: String): QrResult {
return try {
val coords = text.removePrefix("geo:").split(",")
- val lat = coords[0].toDouble()
- val lng = coords[1].split("?")[0].toDouble()
- QrResult.GeoPoint(lat, lng)
- } catch (e: Exception) {
- QrResult.PlainText(text)
- }
+ QrResult.GeoPoint(coords[0].toDouble(), coords[1].split("?")[0].toDouble())
+ } catch (e: Exception) { QrResult.PlainText(text) }
}
}