Skip to content

CircleToSearch with multi search engine support for all android

Kotlin

QR code detection issue

AKS Labs2760bd73389e
diff --git a/CircleToSearchScreen_auto.kt b/CircleToSearchScreen_auto.kt
new file mode 100644
index 0000000..6061f74
Binary files /dev/null and b/CircleToSearchScreen_auto.kt differ
diff --git a/CircleToSearchScreen_auto_utf8.kt b/CircleToSearchScreen_auto_utf8.kt
new file mode 100644
index 0000000..b95619f
--- /dev/null
+++ b/CircleToSearchScreen_auto_utf8.kt
@@ -0,0 +1,1779 @@
+/*
+ *
+ * * Copyright (C) 2025 AKS-Labs (original author)
+ * *
+ * * This program is free software: you can redistribute it and/or modify
+ * * it under the terms of the GNU General Public License as published by
+ * * the Free Software Foundation, either version 3 of the License, or
+ * * (at your option) any later version.
+ * *
+ * * This program is distributed in the hope that it will be useful,
+ * * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * * GNU General Public License for more details.
+ * *
+ * * You should have received a copy of the GNU General Public License
+ * * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+package com.akslabs.circletosearch.ui
+
+import android.graphics.Bitmap
+import android.graphics.Rect
+import android.util.Base64
+import android.view.ViewGroup
+import android.webkit.WebSettings
+import android.webkit.WebView
+import android.webkit.WebViewClient
+import android.widget.FrameLayout
+import androidx.activity.compose.BackHandler
+import androidx.compose.animation.core.Spring
+import androidx.compose.animation.core.animateFloat
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.animation.core.spring
+import androidx.compose.animation.core.tween
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.slideInVertically
+import androidx.compose.animation.slideOutVertically
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.Image
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.gestures.detectDragGestures
+import androidx.compose.foundation.gestures.detectTapGestures
+import androidx.compose.foundation.interaction.MutableInteractionSource
+import androidx.compose.foundation.interaction.collectIsPressedAsState
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxWithConstraints
+import androidx.compose.foundation.layout.Column
+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.height
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.layout.wrapContentSize
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.BorderOuter
+import androidx.compose.material.icons.filled.Close
+import androidx.compose.material.icons.filled.Code
+import androidx.compose.material.icons.filled.ContentCopy
+import androidx.compose.material.icons.filled.DarkMode
+import androidx.compose.material.icons.filled.DesktopWindows
+import androidx.compose.material.icons.filled.Favorite
+import androidx.compose.material.icons.filled.Fullscreen
+import androidx.compose.material.icons.filled.LightMode
+import androidx.compose.material.icons.filled.Mic
+import androidx.compose.material.icons.filled.MoreVert
+import androidx.compose.material.icons.filled.MusicNote
+import androidx.compose.material.icons.filled.OpenInNew
+import androidx.compose.material.icons.filled.QrCode
+import androidx.compose.material.icons.filled.Refresh
+import androidx.compose.material.icons.filled.Search
+import androidx.compose.material.icons.filled.Send
+import androidx.compose.material.icons.filled.Settings
+import androidx.compose.material.icons.filled.Smartphone
+import androidx.compose.material.icons.filled.TextFields
+import androidx.compose.material.icons.filled.Translate
+import androidx.compose.material3.BottomSheetDefaults
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
+import androidx.compose.material3.FilledTonalIconButton
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.IconButtonDefaults
+import androidx.compose.material3.LoadingIndicator
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.ModalBottomSheet
+import androidx.compose.material3.ScrollableTabRow
+import androidx.compose.material3.SheetValue
+import androidx.compose.material3.Tab
+import androidx.compose.material3.Text
+import androidx.compose.material3.VerticalDivider
+import androidx.compose.material3.rememberModalBottomSheetState
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateListOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.runtime.snapshots.SnapshotStateList
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.draw.shadow
+import androidx.compose.ui.geometry.CornerRadius
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.Path
+import androidx.compose.ui.graphics.StrokeCap
+import androidx.compose.ui.graphics.StrokeJoin
+import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.graphics.drawscope.Stroke
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.painterResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.viewinterop.AndroidView
+import androidx.compose.ui.zIndex
+import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
+import androidx.webkit.WebSettingsCompat
+import com.akslabs.circletosearch.data.SearchEngine
+import com.akslabs.circletosearch.ui.components.FriendlyMessageBubble
+import com.akslabs.circletosearch.ui.components.searchWithGoogleLens
+import com.akslabs.circletosearch.ui.theme.OverlayGradientColors
+import com.akslabs.circletosearch.utils.FriendlyMessageManager
+import com.akslabs.circletosearch.utils.ImageSearchUploader
+import com.akslabs.circletosearch.utils.ImageUtils
+import com.akslabs.circletosearch.utils.QrResultWithBounds
+import com.akslabs.circletosearch.utils.QrScanner
+import com.akslabs.circletosearch.utils.UIPreferences
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import java.io.ByteArrayOutputStream
+import androidx.webkit.WebViewFeature
+import com.akslabs.circletosearch.data.isDirectUpload
+import kotlin.math.max
+import kotlin.math.min
+import androidx.compose.foundation.isSystemInDarkTheme
+import androidx.compose.material3.dynamicDarkColorScheme
+import androidx.compose.material3.dynamicLightColorScheme
+import android.os.Build
+import androidx.compose.material3.Surface
+
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun CircleToSearchScreen(
+ screenshot: Bitmap?,
+ onClose: () -> Unit,
+ copyTextManager: com.akslabs.circletosearch.ui.components.CopyTextOverlayManager? = null,
+ onCopyText: () -> Unit = {},
+ onExitCopyMode: () -> Unit = {}
+) {
+ val context = LocalContext.current
+ val scope = rememberCoroutineScope()
+
+ // Initialize preferences
+ val uiPreferences = remember { UIPreferences(context) }
+
+ // Support Sheet State
+ var showSupportSheet by remember { mutableStateOf(false) }
+ val supportSheetState = rememberModalBottomSheetState()
+
+ // Material You logic for colors
+ val isDark = isSystemInDarkTheme()
+ val dynamicColor = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
+ val colorScheme = when {
+ dynamicColor && isDark -> dynamicDarkColorScheme(context)
+ dynamicColor && !isDark -> dynamicLightColorScheme(context)
+ else -> MaterialTheme.colorScheme // Fallback standard
+ }
+ //Colors for dark theme
+ val barBgColor = if (isDark) Color(0xFF0D0D0D) else colorScheme.surface
+ val bubbleColor = if (isDark) Color(0xFF1F1F1F) else colorScheme.secondaryContainer.copy(alpha = 0.9f)
+ val contentColor = if (isDark) Color.White else colorScheme.onSecondaryContainer
+
+ //Haptic feedback
+ val haptic = androidx.compose.ui.platform.LocalHapticFeedback.current
+
+ //Slide-in animation
+ var isUIVisible by remember { mutableStateOf(false) }
+ LaunchedEffect(Unit) {
+ isUIVisible = true // Déclenche l'animation à l'ouverture
+ }
+
+ // Search Engines Order Logic
+ val preferredOrder = remember(uiPreferences.getSearchEngineOrder()) {
+ val allEngines = SearchEngine.values()
+ val orderString = uiPreferences.getSearchEngineOrder()
+ if (orderString == null) allEngines
+ else {
+ val preferredNames = orderString.split(",")
+ val ordered = mutableListOf<SearchEngine>()
+ preferredNames.forEach { name ->
+ allEngines.find { it.name == name }?.let { ordered.add(it) }
+ }
+ allEngines.forEach { if (!ordered.contains(it)) ordered.add(it) }
+ ordered
+ }
+ }
+ val searchEngines = preferredOrder
+
+ // Copy Mode internal state
+ var isCopyMode by remember { mutableStateOf(false) }
+
+
+ // Support Settings Sheet
+ var showSettingsScreen by remember { mutableStateOf(false) }
+
+ // Friendly Message State
+ var friendlyMessage by remember { mutableStateOf("") }
+ var isMessageVisible by remember { mutableStateOf(false) }
+ var isCopyTextTriggered by remember { mutableStateOf(false) }
+
+ // Resizing state
+ var isResizing by remember { mutableStateOf(false) }
+ var activeHandle by remember { mutableStateOf<String?>(null) } // "tl", "tr", "bl", "br"
+
+ // QR Scanner state
+ var showQrSheet by remember { mutableStateOf(false) }
+ var qrScanBitmap by remember { mutableStateOf<android.graphics.Bitmap?>(null) }
+ var detectedQrCodes by remember { mutableStateOf<List<QrResultWithBounds>>(emptyList()) }
+ var selectedQrResult by remember { mutableStateOf<QrResultWithBounds?>(null) }
+
+ LaunchedEffect(Unit) {
+ if (uiPreferences.isShowFriendlyMessages()) {
+ val manager = FriendlyMessageManager(context)
+ friendlyMessage = manager.getNextMessage()
+ delay(500) // Small delay for smooth entrance
+ isMessageVisible = true
+ delay(4000) // Show for 4 seconds
+ isMessageVisible = false
+ }
+ }
+
+ // Search State
+ var selectedEngine by remember(searchEngines) { mutableStateOf<SearchEngine>(searchEngines.first()) }
+ var searchUrl by remember { mutableStateOf<String?>(null) }
+ var hostedImageUrl by remember { mutableStateOf<String?>(null) }
+ var isLoading by remember { mutableStateOf(false) }
+
+ // Auto-scan entire screenshot for QR codes when it arrives
+ LaunchedEffect(screenshot) {
+ if (screenshot != null) {
+ val found = withContext(Dispatchers.Default) {
+ QrScanner.scanBitmapAll(screenshot!!)
+ }
+ detectedQrCodes = found
+ }
+ }
+ // Desktop Mode - Per Tab
+ // We use a set to track which engines are in desktop mode
+ val initialDesktopMode = uiPreferences.isDesktopMode() // Global default
+ var desktopModeEngines by remember { mutableStateOf<Set<SearchEngine>>(if(initialDesktopMode) searchEngines.toSet() else emptySet()) }
+
+ var isDarkMode by remember { mutableStateOf(uiPreferences.isDarkMode()) }
+ var showGradientBorder by remember { mutableStateOf(uiPreferences.isShowGradientBorder()) }
+
+ // Back gesture handler for QR sheet
+ BackHandler(enabled = showQrSheet) {
+ showQrSheet = false
+ }
+
+ // Track initialized engines for Smart Loading
+ val initializedEngines = remember { mutableStateListOf<SearchEngine>() }
+
+ // Save global preference if user toggles it for the MAIN engine (Google) - Optional choice,
+ // or we just keep it per session. Let's keep it simple: no auto-save of per-tab state to verify complex persistence yet.
+ // simpler: If user toggles, we just update the state.
+
+ // Helper to check desktop mode
+ fun isDesktop(engine: SearchEngine) = desktopModeEngines.contains(engine)
+
+ // Removed auto-save of isDesktopMode for now as it is complex with per-tab
+ // We could save "If ALL are desktop" or just the active one?
+ // User requested "depending on opened tab", so per-session state is safer.
+
+ LaunchedEffect(isDarkMode) {
+ uiPreferences.setDarkMode(isDarkMode)
+ }
+
+ LaunchedEffect(showGradientBorder) {
+ uiPreferences.setShowGradientBorder(showGradientBorder)
+ }
+
+ // Cache for preloaded URLs to avoid re-uploading/re-generating
+ val preloadedUrls = remember { mutableMapOf<SearchEngine, String>() }
+
+ // WebView Cache
+ val webViews = remember { mutableMapOf<SearchEngine, WebView>() }
+
+ // Update User Agent dynamically when desktop mode changes for a specific engine
+ // This is now handled in the AndroidView update block or individual engine effects
+ // BUT we need to force reload if the state changes.
+ LaunchedEffect(desktopModeEngines) {
+ webViews.forEach { (engine, wv) ->
+ val isDesktop = desktopModeEngines.contains(engine)
+ val newUserAgent = if (isDesktop) {
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
+ } else {
+ "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"
+ }
+
+ if (wv.settings.userAgentString != newUserAgent) {
+ wv.settings.userAgentString = newUserAgent
+ wv.reload()
+ android.util.Log.d("CircleToSearch", "Desktop mode changed for $engine - Reloaded")
+ }
+ }
+ }
+
+ // Update WebViews when dark mode changes
+ LaunchedEffect(isDarkMode) {
+ webViews.values.forEach { wv ->
+ try {
+ // Update WebViewClient for dark mode
+ if (isDarkMode) {
+ wv.webViewClient = object : android.webkit.WebViewClient() {
+ override fun onPageFinished(view: android.webkit.WebView?, url: String?) {
+ super.onPageFinished(view, url)
+ val darkModeCSS = """
+ javascript:(function() {
+ var style = document.createElement('style');
+ style.innerHTML = `
+ html { filter: invert(1) hue-rotate(180deg) !important; background: #000 !important; }
+ img, video, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; }
+ `;
+ document.head.appendChild(style);
+ })()
+ """.trimIndent()
+ view?.loadUrl(darkModeCSS)
+ }
+ }
+ } else {
+ wv.webViewClient = android.webkit.WebViewClient()
+ }
+ wv.reload()
+ android.util.Log.d("CircleToSearch", "Dark mode changed to: $isDarkMode - Reloaded WebViews")
+ } catch (e: Exception) {
+ android.util.Log.e("CircleToSearch", "Error updating dark mode", e)
+ }
+ }
+ }
+
+ // Bottom Sheet State
+ val scaffoldState = androidx.compose.material3.rememberBottomSheetScaffoldState(
+ bottomSheetState = androidx.compose.material3.rememberStandardBottomSheetState(
+ initialValue = androidx.compose.material3.SheetValue.Hidden,
+ skipHiddenState = false
+ )
+ )
+
+ // Drawing State
+ val currentPathPoints = remember { mutableStateListOf<Offset>() }
+
+ // Selection State
+ var selectedBitmap by remember { mutableStateOf<Bitmap?>(null) }
+ var isSearching by remember { mutableStateOf(false) }
+ var selectionRect by remember { mutableStateOf<Rect?>(null) }
+ val selectionAnim = remember { androidx.compose.animation.core.Animatable(0f) }
+
+ // Lifecycle reset: When screenshot changes, reset selection and modes
+ LaunchedEffect(screenshot) {
+ if (screenshot != null) {
+ isCopyMode = false
+ selectionRect = null
+ selectedBitmap = null
+ isSearching = false
+ currentPathPoints.clear()
+ selectionAnim.snapTo(0f)
+ }
+ }
+
+ // searchEngines moved to top
+ // val searchEngines = SearchEngine.values()
+
+ // Gradient Animation
+ val alphaAnim by animateFloatAsState(
+ targetValue = if (screenshot != null) 1f else 0f,
+ animationSpec = tween(1000), label = "alpha"
+ )
+
+ // Helper to create and configure WebView
+ fun createWebView(ctx: android.content.Context, engine: SearchEngine): WebView {
+ return WebView(ctx).apply {
+ layoutParams = ViewGroup.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT,
+ ViewGroup.LayoutParams.MATCH_PARENT
+ )
+
+ // Caching & Performance - must be set on WebView directly
+ setLayerType(android.view.View.LAYER_TYPE_HARDWARE, null)
+
+ settings.apply {
+ javaScriptEnabled = true
+ domStorageEnabled = true
+ databaseEnabled = true
+ allowFileAccess = true
+ allowContentAccess = true
+ allowFileAccessFromFileURLs = true
+ allowUniversalAccessFromFileURLs = true
+ mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
+
+ // Performance & UI
+ setRenderPriority(WebSettings.RenderPriority.HIGH)
+
+ // Caching for Speed
+ cacheMode = WebSettings.LOAD_DEFAULT // Was LOAD_CACHE_ELSE_NETWORK - caused refresh issues
+
+ // Zoom support
+ setSupportZoom(true)
+ builtInZoomControls = true
+ displayZoomControls = false
+
+ useWideViewPort = true
+ loadWithOverviewMode = true
+
+ userAgentString = if (isDesktop(engine)) {
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
+ } else {
+ "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"
+ }
+
+ // Dark Mode - Use CSS injection for universal compatibility
+ // Algorithmic darkening alone doesn't work on many websites
+ android.util.Log.d("CircleToSearch", "Dark mode enabled: $isDarkMode")
+ }
+
+ // UI Tweaks
+ isVerticalScrollBarEnabled = false
+ isHorizontalScrollBarEnabled = false
+
+ // Enable Third-Party Cookies
+ android.webkit.CookieManager.getInstance().setAcceptThirdPartyCookies(this, true)
+
+ webViewClient = object : WebViewClient() {
+
+ override fun onPageFinished(view: WebView?, url: String?) {
+ super.onPageFinished(view, url)
+ // Inject dark mode CSS if enabled
+ if (isDarkMode) {
+ val darkModeCSS = """
+ javascript:(function() {
+ var style = document.createElement('style');
+ style.innerHTML = `
+ html { filter: invert(1) hue-rotate(180deg) !important; background: #000 !important; }
+ img, video, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; }
+ `;
+ document.head.appendChild(style);
+ })()
+ """.trimIndent()
+ view?.loadUrl(darkModeCSS)
+ android.util.Log.d("CircleToSearch", "Dark mode CSS injected for: $url")
+ }
+ }
+ }
+ isNestedScrollingEnabled = true
+ setOnTouchListener { v, event ->
+ when (event.action) {
+ android.view.MotionEvent.ACTION_DOWN -> {
+ v.parent.requestDisallowInterceptTouchEvent(true)
+ }
+ android.view.MotionEvent.ACTION_UP, android.view.MotionEvent.ACTION_CANCEL -> {
+ v.parent.requestDisallowInterceptTouchEvent(false)
+ }
+ }
+ false
+ }
+ }
+ }
+
+ // Back Handler Logic
+ BackHandler(enabled = true) {
+ if (isCopyMode) {
+ isCopyMode = false
+ onExitCopyMode()
+ return@BackHandler
+ }
+ val currentWebView = webViews[selectedEngine]
+ if (currentWebView != null && currentWebView.canGoBack()) {
+ currentWebView.goBack()
+ } else if (scaffoldState.bottomSheetState.currentValue == androidx.compose.material3.SheetValue.Expanded) {
+ scope.launch { scaffoldState.bottomSheetState.partialExpand() }
+ } else if (scaffoldState.bottomSheetState.currentValue == androidx.compose.material3.SheetValue.PartiallyExpanded) {
+ scope.launch { scaffoldState.bottomSheetState.hide() }
+ } else {
+ onClose()
+ }
+ }
+
+ Surface(
+ color = Color.Transparent,
+ tonalElevation = 0.dp
+ ) {
+ androidx.compose.material3.BottomSheetScaffold(
+ scaffoldState = scaffoldState,
+ sheetPeekHeight = (androidx.compose.ui.platform.LocalConfiguration.current.screenHeightDp.dp * 0.55f), // Dynamic 55% peek
+ containerColor = Color.Transparent,
+ sheetContainerColor = Color.Transparent,
+ sheetContentColor = MaterialTheme.colorScheme.onSurface,
+ sheetDragHandle = { BottomSheetDefaults.DragHandle() },
+ sheetSwipeEnabled = true,
+ sheetContent = {
+ // Bottom Sheet Content (Results)
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(800.dp)
+ .background(MaterialTheme.colorScheme.surface, RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp))
+ ) {
+ Spacer(modifier = Modifier.height(16.dp))
+
+ // Tabs - Polished UI
+ ScrollableTabRow(
+ selectedTabIndex = searchEngines.indexOf(selectedEngine),
+ edgePadding = 16.dp,
+ containerColor = Color.Transparent,
+ contentColor = MaterialTheme.colorScheme.onSurface,
+ divider = {},
+ indicator = {}
+ ) {
+ searchEngines.forEach { engine ->
+ val selected = selectedEngine == engine
+ val transition = androidx.compose.animation.core.updateTransition(targetState = selected, label = "TabSelect")
+ val scale by transition.animateFloat(label = "Scale") { if (it) 1.05f else 1f }
+ val alpha by transition.animateFloat(label = "Alpha") { if (it) 1f else 0.7f }
+
+ Tab(
+ selected = selected,
+ onClick = { selectedEngine = engine },
+ modifier = Modifier.graphicsLayer {
+ scaleX = scale
+ scaleY = scale
+ this.alpha = alpha
+ },
+ text = {
+ Text(
+ engine.name,
+ style = MaterialTheme.typography.labelLarge.copy(
+ fontWeight = if (selected) FontWeight.Bold else FontWeight.Medium
+ ),
+ modifier = Modifier
+ .background(
+ if (selected) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.surfaceVariant.copy(alpha=0.5f),
+ RoundedCornerShape(16.dp)
+ )
+ .border(
+ width = 1.dp,
+ color = if(selected) MaterialTheme.colorScheme.primary.copy(alpha=0.5f) else Color.Transparent,
+ shape = RoundedCornerShape(16.dp)
+ )
+ .padding(horizontal = 16.dp, vertical = 8.dp),
+ color = if (selected) MaterialTheme.colorScheme.onSecondaryContainer else MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ )
+ }
+ }
+
+ // Reset everything when bitmap changes (new area selected)
+ LaunchedEffect(selectedBitmap) {
+ hostedImageUrl = null
+ searchUrl = null
+ preloadedUrls.clear()
+ initializedEngines.clear() // Reset smart loading
+ // Do NOT destroy webviews here to keep them cached if possible?
+ // PROBABLY safer to destroy to avoid stale state from previous searches.
+ webViews.values.forEach { it.destroy() }
+ webViews.clear()
+ }
+
+ LaunchedEffect(selectedBitmap, hostedImageUrl) {
+ if (selectedBitmap != null) {
+ isLoading = true
+
+ // 1. Google Lens Only Mode Check
+ if (uiPreferences.isUseGoogleLensOnly()) {
+ // Save to cache and launch Lens
+ val path = ImageUtils.saveBitmap(context, selectedBitmap!!)
+ val uri = android.net.Uri.fromFile(java.io.File(path))
+
+ // Prepare content URI for Lens (using existing FileProvider logic in helper)
+ val success = searchWithGoogleLens(uri, context)
+
+ if (success) {
+ // Close the overlay since Lens is taking over
+ onClose()
+ return@LaunchedEffect
+ } else {
+ // Fallback to multi-search if Lens failed
+ android.util.Log.e("CircleToSearch", "Google Lens launch failed, falling back to multi-search")
+ }
+ }
+
+ // 2. Multi-Search Mode (Expanded UI)
+ scope.launch { scaffoldState.bottomSheetState.expand() }
+
+ // 3. Upload to host if needed (Multi-Search Mode)
+ if (hostedImageUrl == null) {
+ val url = ImageSearchUploader.uploadToImageHost(selectedBitmap!!)
+ if (url != null) {
+ hostedImageUrl = url
+ } else {
+ isLoading = false
+ return@LaunchedEffect
+ }
+ }
+
+ // 2. Generate URLs for ALL engines (lightweight string op)
+ searchEngines.forEach { engine ->
+ if (!preloadedUrls.containsKey(engine)) {
+ val url = if (engine.isDirectUpload) {
+ when (engine) {
+ SearchEngine.Perplexity -> ImageSearchUploader.getPerplexityUrl(hostedImageUrl!!)
+ SearchEngine.ChatGPT -> ImageSearchUploader.getChatGPTUrl(hostedImageUrl!!)
+ else -> null
+ }
+ } else {
+ when (engine) {
+ SearchEngine.Google -> ImageSearchUploader.getGoogleLensUrl(hostedImageUrl!!)
+ SearchEngine.Bing -> ImageSearchUploader.getBingUrl(hostedImageUrl!!)
+ SearchEngine.Yandex -> ImageSearchUploader.getYandexUrl(hostedImageUrl!!)
+ SearchEngine.TinEye -> ImageSearchUploader.getTinEyeUrl(hostedImageUrl!!)
+ else -> null
+ }
+ }
+ if (url != null) preloadedUrls[engine] = url
+ }
+ }
+
+ // 3. Set initial URL
+ if (preloadedUrls.containsKey(selectedEngine)) {
+ searchUrl = preloadedUrls[selectedEngine]
+ }
+
+ // 4. SMART LOADING SEQUENCE
+ // First, ensure selected engine is initialized
+ if (!initializedEngines.contains(selectedEngine)) {
+ initializedEngines.add(selectedEngine)
+ }
+
+ isLoading = false
+
+ // Then, load others sequentially
+ scope.launch {
+ searchEngines.forEach { engine ->
+ if (engine != selectedEngine) {
+ delay(300) // Reduced from 800ms for faster loading
+ if (!initializedEngines.contains(engine)) {
+ initializedEngines.add(engine)
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Update searchUrl when engine changes
+ LaunchedEffect(selectedEngine, preloadedUrls) {
+ if (preloadedUrls.containsKey(selectedEngine)) {
+ searchUrl = preloadedUrls[selectedEngine]
+ }
+ }
+
+ // Memory Optimization: REMOVED Aggressive Cleanup
+ // User Requirement: "dont refresh tabs when user switch tabs keep them in background"
+ // We keep them alive.
+ /*
+ LaunchedEffect(selectedEngine) {
+ // ... (Cleanup logic removed)
+ }
+ */
+
+ Box(modifier = Modifier.fillMaxSize()) {
+ // Show loading only if the SELECTED engine isn't ready or just starting
+ if (isLoading || (preloadedUrls.containsKey(selectedEngine) && !webViews.containsKey(selectedEngine))) {
+ // We delay showing the loader slightly to avoid flicker if WebView attaches instantly
+ var showLoader by remember { mutableStateOf(false) }
+ LaunchedEffect(Unit) {
+ kotlinx.coroutines.delay(100)
+ showLoader = true
+ }
+
+ if (showLoader || isLoading) {
+ Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ ContainedLoadingIndicatorSample()
+ }
+ }
+ }
+
+ // Dynamic Settings Update (User Agent etc) - Now handled at top level
+ // Cleanup on Dispose
+ DisposableEffect(Unit) {
+ onDispose {
+ webViews.values.forEach { it.destroy() }
+ webViews.clear()
+ }
+ }
+
+ // Render WebViews
+ searchEngines.forEach { engine ->
+ // Logic: Render if it's in the initialized set (Smart Loading)
+ // This ensures we don't load everything at once, but once loaded, we keep it.
+ if (initializedEngines.contains(engine) && preloadedUrls.containsKey(engine)) {
+ val url = preloadedUrls[engine]!!
+ val isSelected = (engine == selectedEngine)
+
+ androidx.compose.runtime.key(engine) {
+ AndroidView(
+ factory = { ctx ->
+ if (webViews.containsKey(engine)) {
+ // Should not happen with key(), but safety check
+ val v = webViews[engine]!!
+ (v.parent as? ViewGroup)?.removeView(v)
+
+ val swipeRefresh = SwipeRefreshLayout(ctx).apply {
+ layoutParams = ViewGroup.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT,
+ ViewGroup.LayoutParams.MATCH_PARENT
+ )
+ }
+ swipeRefresh.addView(v)
+ swipeRefresh.setOnRefreshListener {
+ v.reload()
+ swipeRefresh.isRefreshing = false
+ }
+ swipeRefresh
+ } else {
+ val swipeRefresh = SwipeRefreshLayout(ctx).apply {
+ layoutParams = ViewGroup.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT,
+ ViewGroup.LayoutParams.MATCH_PARENT
+ )
+ }
+ val webView = createWebView(ctx, engine)
+ // Apply current settings
+ if (isDesktop(engine)) {
+ webView.settings.userAgentString = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
+ }
+
+ webViews[engine] = webView
+ webView.loadUrl(url)
+
+ swipeRefresh.addView(webView)
+ swipeRefresh.setOnRefreshListener {
+ webView.reload()
+ swipeRefresh.isRefreshing = false
+ }
+ swipeRefresh
+ }
+ },
+ update = { swipeRefresh ->
+ var webView: WebView? = null
+ for (i in 0 until swipeRefresh.childCount) {
+ val child = swipeRefresh.getChildAt(i)
+ if (child is WebView) {
+ webView = child
+ break
+ }
+ }
+
+ if (webView != null) {
+ if (webView.url != url && url != webView.originalUrl) {
+ webView.loadUrl(url)
+ }
+ }
+ },
+ modifier = Modifier
+ .fillMaxSize()
+ .zIndex(if (isSelected) 1f else 0f)
+ .graphicsLayer {
+ alpha = if (isSelected) 1f else 0f
+ }
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+ ) { _ ->
+ // Root Box
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(Color.Transparent) // Changed from Black to Transparent
+ ) {
+ // Close button for Copy Mode (Top Left)
+
+ // Friendly Message Overlay (Top Center)
+ if (!isCopyMode) {
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .offset(y = 100.dp) // Offset to not cover potential top icons
+ .zIndex(100f), // Ensure on top
+ contentAlignment = Alignment.TopCenter
+ ) {
+ FriendlyMessageBubble(
+ message = friendlyMessage,
+ visible = isMessageVisible
+ )
+ }
+ }
+
+ // 1. Screenshot Layer
+ if (screenshot != null && !isCopyMode) {
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .graphicsLayer {
+ // Required for BlendMode.Clear to work in child Canvas
+ compositingStrategy = androidx.compose.ui.graphics.CompositingStrategy.Offscreen
+ }
+ ) {
+ Image(
+ bitmap = screenshot.asImageBitmap(),
+ contentDescription = "Screenshot",
+ contentScale = ContentScale.FillBounds,
+ modifier = Modifier.fillMaxSize()
+ )
+
+ // QR Overlay Chips
+ BoxWithConstraints(modifier = Modifier.fillMaxSize()) {
+ val screenWidth = maxWidth
+ val screenHeight = maxHeight
+ val bitmapWidth = screenshot.width.toFloat()
+ val bitmapHeight = screenshot.height.toFloat()
+
+ detectedQrCodes.forEach { qr ->
+ qr.bounds?.let { bounds ->
+ val chipX = (bounds.centerX() / bitmapWidth) * screenWidth.value
+ val chipY = (bounds.centerY() / bitmapHeight) * screenHeight.value
+
+ Box(
+ modifier = Modifier
+ .offset(
+ x = chipX.dp - 24.dp,
+ y = chipY.dp - 24.dp
+ )
+ .size(48.dp)
+ .background(MaterialTheme.colorScheme.primary.copy(alpha = 0.8f), CircleShape)
+ .border(2.dp, Color.White, CircleShape)
+ .clickable {
+ selectedQrResult = qr
+ qrScanBitmap = null // Use results directly
+ showQrSheet = true
+ }
+ .zIndex(200f),
+ contentAlignment = Alignment.Center
+ ) {
+ Icon(
+ Icons.Default.QrCode,
+ contentDescription = "QR Found",
+ tint = Color.White,
+ modifier = Modifier.size(24.dp)
+ )
+ }
+
+ // Mini label
+ val label = com.akslabs.circletosearch.ui.qrResultShortLabel(qr.result)
+ if (label.isNotEmpty()) {
+ Surface(
+ modifier = Modifier
+ .offset(
+ x = chipX.dp + 28.dp,
+ y = chipY.dp - 12.dp
+ )
+ .zIndex(199f),
+ shape = RoundedCornerShape(8.dp),
+ color = MaterialTheme.colorScheme.surfaceContainerHighest.copy(alpha = 0.9f),
+ tonalElevation = 4.dp
+ ) {
+ Text(
+ text = label,
+ style = MaterialTheme.typography.labelSmall,
+ modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+ }
+ }
+ }
+
+ // Tint Overlay (Punch-out style)
+ Canvas(modifier = Modifier.fillMaxSize()) {
+ val strokeWidth = 0f
+ val dimAlpha = 0.15f
+
+ // 1. Draw global dim
+ drawRect(Color.Black.copy(alpha = dimAlpha))
+ drawRect(
+ brush = Brush.verticalGradient(
+ colors = OverlayGradientColors.map { it.copy(alpha = dimAlpha) }
+ )
+ )
+
+ // 2. Clear selection area if it exists
+ if (selectionRect != null && selectionAnim.value > 0f) {
+ val rect = selectionRect!!
+ val progress = selectionAnim.value
+ val holeRect = androidx.compose.ui.geometry.Rect(
+ rect.left.toFloat(),
+ rect.top.toFloat(),
+ rect.right.toFloat(),
+ rect.bottom.toFloat()
+ )
+
+ // Punch the hole
+ drawRoundRect(
+ color = Color.Transparent,
+ topLeft = holeRect.topLeft,
+ size = holeRect.size,
+ cornerRadius = CornerRadius(48f),
+ blendMode = androidx.compose.ui.graphics.BlendMode.Clear
+ )
+ }
+ }
+ }
+ }
+
+ // 2. Gradient Border Layer (Overlaying screenshot, clipped to rounded corners)
+ if (showGradientBorder && !isCopyMode) {
+ androidx.compose.animation.AnimatedVisibility(
+ visible = isUIVisible,
+ enter = androidx.compose.animation.fadeIn(animationSpec = tween(700))
+ ) {
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .border(
+ width = 8.dp,
+ brush = Brush.verticalGradient(
+ colors = OverlayGradientColors.map { it.copy(alpha = 0.5f) }
+ ),
+ shape = RoundedCornerShape(24.dp) // Rounded corners for device
+ )
+ .clip(RoundedCornerShape(24.dp))
+ )
+ }
+ }
+
+ // 3. Drawing Canvas (Interactive Layer)
+ if (!isCopyMode) { Canvas(
+ modifier = Modifier
+ .fillMaxSize()
+ .pointerInput(Unit) {
+ detectDragGestures(
+ onDragStart = { offset ->
+ val rect = selectionRect
+ if (rect != null && selectionAnim.value == 1f) {
+ val handleSize = 64f // px for hit testing
+ val tl = Offset(rect.left.toFloat(), rect.top.toFloat())
+ val tr = Offset(rect.right.toFloat(), rect.top.toFloat())
+ val bl = Offset(rect.left.toFloat(), rect.bottom.toFloat())
+ val br = Offset(rect.right.toFloat(), rect.bottom.toFloat())
+
+ when {
+ (offset - tl).getDistance() < handleSize -> { isResizing = true; activeHandle = "tl" }
+ (offset - tr).getDistance() < handleSize -> { isResizing = true; activeHandle = "tr" }
+ (offset - bl).getDistance() < handleSize -> { isResizing = true; activeHandle = "bl" }
+ (offset - br).getDistance() < handleSize -> { isResizing = true; activeHandle = "br" }
+ else -> { isResizing = false; activeHandle = null }
+ }
+
+ if (isResizing) return@detectDragGestures
+ }
+
+ // Clear previous state if starting new draw
+ currentPathPoints.clear()
+ currentPathPoints.add(offset)
+ selectionRect = null
+ scope.launch { selectionAnim.snapTo(0f) }
+ },
+ onDrag = { change, _ ->
+ if (isResizing && activeHandle != null) {
+ val rect = selectionRect ?: return@detectDragGestures
+ val pos = change.position
+ val newRect = android.graphics.Rect(rect)
+ when (activeHandle) {
+ "tl" -> { newRect.left = pos.x.toInt(); newRect.top = pos.y.toInt() }
+ "tr" -> { newRect.right = pos.x.toInt(); newRect.top = pos.y.toInt() }
+ "bl" -> { newRect.left = pos.x.toInt(); newRect.bottom = pos.y.toInt() }
+ "br" -> { newRect.right = pos.x.toInt(); newRect.bottom = pos.y.toInt() }
+ }
+ // Basic validation (min size)
+ if (newRect.width() > 20 && newRect.height() > 20) {
+ selectionRect = newRect
+ }
+ } else {
+ currentPathPoints.add(change.position)
+ }
+ },
+ onDragEnd = {
+ if (isResizing) {
+ isResizing = false
+ activeHandle = null
+ // Update cropped bitmap after resize
+ if (screenshot != null && selectionRect != null) {
+ selectedBitmap = ImageUtils.cropBitmap(screenshot, selectionRect!!)
+ }
+ } else if (currentPathPoints.isNotEmpty()) {
+ var minX = Float.MAX_VALUE
+ var minY = Float.MAX_VALUE
+ var maxX = Float.MIN_VALUE
+ var maxY = Float.MIN_VALUE
+ currentPathPoints.forEach { p ->
+ minX = kotlin.math.min(minX, p.x)
+ minY = kotlin.math.min(minY, p.y)
+ maxX = kotlin.math.max(maxX, p.x)
+ maxY = kotlin.math.max(maxY, p.y)
+ }
+
+ val border = 20
+ val rect = android.graphics.Rect(
+ (minX - border).toInt().coerceAtLeast(0),
+ (minY - border).toInt().coerceAtLeast(0),
+ (maxX + border).toInt().coerceAtMost(screenshot?.width ?: 0),
+ (maxY + border).toInt().coerceAtMost(screenshot?.height ?: 0)
+ )
+
+ if (rect.width() > 10 && rect.height() > 10) {
+ selectionRect = rect
+ currentPathPoints.clear() // Hide the drawn circle
+ if (screenshot != null) {
+ selectedBitmap = ImageUtils.cropBitmap(screenshot!!, rect)
+ }
+ scope.launch {
+ selectionAnim.animateTo(1f, tween(600))
+ isSearching = true
+ }
+ }
+ }
+ }
+ )
+ }
+ ) {
+ // Draw current path (Real-time)
+ if (currentPathPoints.size > 1) {
+ val path = Path().apply {
+ moveTo(currentPathPoints.first().x, currentPathPoints.first().y)
+ for (i in 1 until currentPathPoints.size) {
+ lineTo(currentPathPoints[i].x, currentPathPoints[i].y)
+ }
+ }
+
+ // Glow
+ drawPath(
+ path = path,
+ brush = Brush.linearGradient(OverlayGradientColors),
+ style = Stroke(width = 30f, cap = StrokeCap.Round, join = StrokeJoin.Round),
+ alpha = 0.6f
+ )
+ // Core
+ drawPath(
+ path = path,
+ color = Color.White,
+ style = Stroke(width = 12f, cap = StrokeCap.Round, join = StrokeJoin.Round)
+ )
+ }
+
+ // Draw Lens Animation (Rounded Corner Brackets)
+ if (selectionRect != null && selectionAnim.value > 0f) {
+ val rect = selectionRect!!
+ val progress = selectionAnim.value
+ val left = rect.left.toFloat()
+ val top = rect.top.toFloat()
+ val right = rect.right.toFloat()
+ val bottom = rect.bottom.toFloat()
+
+ val width = right - left
+ val height = bottom - top
+ val cornerRadius = 48f // Slightly smaller radius
+ val armLength = min(width, height) * 0.15f // Slightly shorter arms
+
+ // Top Left
+ val tlPath = Path().apply {
+ moveTo(left, top + armLength)
+ lineTo(left, top + cornerRadius)
+ arcTo(
+ rect = androidx.compose.ui.geometry.Rect(left, top, left + 2 * cornerRadius, top + 2 * cornerRadius),
+ startAngleDegrees = 180f,
+ sweepAngleDegrees = 90f,
+ forceMoveTo = false
+ )
+ lineTo(left + armLength, top)
+ }
+ // Top Right
+ val trPath = Path().apply {
+ moveTo(right - armLength, top)
+ lineTo(right - cornerRadius, top)
+ arcTo(
+ rect = androidx.compose.ui.geometry.Rect(right - 2 * cornerRadius, top, right, top + 2 * cornerRadius),
+ startAngleDegrees = 270f,
+ sweepAngleDegrees = 90f,
+ forceMoveTo = false
+ )
+ lineTo(right, top + armLength)
+ }
+ // Bottom Right
+ val brPath = Path().apply {
+ moveTo(right, bottom - armLength)
+ lineTo(right, bottom - cornerRadius)
+ arcTo(
+ rect = androidx.compose.ui.geometry.Rect(right - 2 * cornerRadius, bottom - 2 * cornerRadius, right, bottom),
+ startAngleDegrees = 0f,
+ sweepAngleDegrees = 90f,
+ forceMoveTo = false
+ )
+ lineTo(right - armLength, bottom)
+ }
+ // Bottom Left
+ val blPath = Path().apply {
+ moveTo(left + armLength, bottom)
+ lineTo(left + cornerRadius, bottom)
+ arcTo(
+ rect = androidx.compose.ui.geometry.Rect(left, bottom - 2 * cornerRadius, left + 2 * cornerRadius, bottom),
+ startAngleDegrees = 90f,
+ sweepAngleDegrees = 90f,
+ forceMoveTo = false
+ )
+ lineTo(left, bottom - armLength)
+ }
+
+ val bracketAlpha = progress
+ val bracketStroke = Stroke(width = 12f, cap = StrokeCap.Round, join = StrokeJoin.Round)
+
+ // Draw Brackets (Solid White)
+ listOf(tlPath, trPath, brPath, blPath).forEach { p ->
+ drawPath(p, Color.White, style = bracketStroke, alpha = bracketAlpha)
+ }
+
+ // Optional: Flash effect inside
+ drawRoundRect(
+ color = Color.White,
+ topLeft = Offset(left, top),
+ size = Size(width, height),
+ cornerRadius = CornerRadius(48f),
+ style = Stroke(width = 4f),
+ alpha = (1f - progress) * 0.5f
+ )
+ }
+ }
+
+ }
+
+ // 4. Header (Top)
+ androidx.compose.animation.AnimatedVisibility(
+ visible = isUIVisible && !isCopyMode,
+ enter = androidx.compose.animation.slideInVertically(
+ initialOffsetY = { -it }, // Commence au-dessus de l'écran (-100%)
+ animationSpec = tween(500, easing = androidx.compose.animation.core.FastOutSlowInEasing)
+ ),
+ modifier = Modifier.align(Alignment.TopCenter)
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .statusBarsPadding()
+ .padding(top = 16.dp, start = 16.dp, end = 16.dp)
+ .align(Alignment.TopCenter),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ IconButton(
+ onClick =
+ {
+ haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
+ onClose()
+ },
+ modifier = Modifier
+ .background(Color.Gray.copy(alpha = 0.5f), CircleShape)
+ .size(40.dp)
+ ) {
+ Icon(Icons.Default.Close, contentDescription = "Close", tint = Color.White)
+ }
+ Spacer(modifier = Modifier.weight(1f))
+ if (selectedEngine.name == "Google") {
+ // Si c'est Google, on affiche ta belle typo officielle
+ Image(
+ painter = painterResource(id = com.akslabs.circletosearch.R.drawable.googletypo),
+ contentDescription = "Google Search",
+ modifier = Modifier.height(50.dp), // Hauteur ajustable selon ton PNG
+ colorFilter = androidx.compose.ui.graphics.ColorFilter.tint(Color.White)
+ )
+ } else {
+ // Si c'est Bing, Yandex, etc., on garde le texte stylé d'origine
+ Text(
+ text = selectedEngine.name,
+ style = MaterialTheme.typography.headlineMedium.copy(
+ fontWeight = FontWeight.Bold,
+ color = Color.White
+ )
+ )
+ }
+ Spacer(modifier = Modifier.weight(1f))
+
+ // Action Button (Menu)
+ Box(
+ modifier = Modifier
+ .background(Color.Gray.copy(alpha = 0.5f), CircleShape)
+ .size(40.dp),
+ contentAlignment = Alignment.Center
+ ) {
+ var showMenu by remember { mutableStateOf(false) }
+ IconButton(onClick = {
+ haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
+ showMenu = true
+ }) {
+ Icon(
+ Icons.Default.MoreVert,
+ contentDescription = "Menu",
+ tint = Color.White
+ )
+ }
+
+ androidx.compose.material3.DropdownMenu(
+ expanded = showMenu,
+ onDismissRequest = { showMenu = false }
+ ) {
+ val isDesktop = isDesktop(selectedEngine)
+ androidx.compose.material3.DropdownMenuItem(
+ text = { Text(if (isDesktop) "Mobile Mode" else "Desktop Mode") },
+ leadingIcon = {
+ Icon(
+ if (isDesktop) Icons.Default.Smartphone else Icons.Default.DesktopWindows,
+ contentDescription = null
+ )
+ },
+ onClick = {
+ val newSet = desktopModeEngines.toMutableSet()
+ if (newSet.contains(selectedEngine)) {
+ newSet.remove(selectedEngine)
+ } else {
+ newSet.add(selectedEngine)
+ }
+ desktopModeEngines = newSet
+ showMenu = false
+ }
+ )
+ androidx.compose.material3.DropdownMenuItem(
+ text = { Text(if (isDarkMode) "Light Mode" else "Dark Mode") },
+ leadingIcon = {
+ Icon(
+ if (isDarkMode) Icons.Default.LightMode else Icons.Default.DarkMode,
+ contentDescription = null
+ )
+ },
+ onClick = {
+ isDarkMode = !isDarkMode
+ showMenu = false
+ }
+ )
+ androidx.compose.material3.DropdownMenuItem(
+ text = { Text(if (showGradientBorder) "Hide Border" else "Show Border") },
+ leadingIcon = {
+ Icon(Icons.Default.BorderOuter, contentDescription = null)
+ },
+ onClick = {
+ showGradientBorder = !showGradientBorder
+ showMenu = false
+ }
+ )
+ androidx.compose.material3.DropdownMenuItem(
+ text = { Text("Refresh") },
+ leadingIcon = {
+ Icon(Icons.Default.Refresh, contentDescription = null)
+ },
+ onClick = {
+ webViews[selectedEngine]?.reload()
+ showMenu = false
+ }
+ )
+ androidx.compose.material3.DropdownMenuItem(
+ text = { Text("Copy URL") },
+ leadingIcon = {
+ Icon(Icons.Default.ContentCopy, contentDescription = null)
+ },
+ onClick = {
+ if (searchUrl != null) {
+ val clipboard =
+ context.getSystemService(android.content.Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
+ val clip = android.content.ClipData.newPlainText(
+ "Search URL",
+ searchUrl
+ )
+ clipboard.setPrimaryClip(clip)
+ }
+ showMenu = false
+ }
+ )
+ androidx.compose.material3.DropdownMenuItem(
+ text = { Text("Open in Browser") },
+ leadingIcon = {
+ Icon(Icons.Default.OpenInNew, contentDescription = null)
+ },
+ onClick = {
+ val currentUrl = webViews[selectedEngine]?.url ?: searchUrl
+ if (currentUrl != null) {
+ try {
+ val intent = android.content.Intent(
+ android.content.Intent.ACTION_VIEW,
+ android.net.Uri.parse(currentUrl)
+ )
+ context.startActivity(intent)
+ } catch (e: Exception) {
+ android.util.Log.e(
+ "CircleToSearch",
+ "Failed to open browser",
+ e
+ )
+ }
+ }
+ showMenu = false
+ }
+ )
+ androidx.compose.material3.DropdownMenuItem(
+ text = { Text("Settings") },
+ leadingIcon = {
+ Icon(Icons.Default.Settings, contentDescription = null)
+ },
+ onClick = {
+ showSettingsScreen = true
+ showMenu = false
+ }
+ )
+ }
+ }
+ }
+ }
+ // 5. Bottom Bar ΓÇö Material 3 Expressive two-row card
+ // State for Copy Text mode
+ var isCopyTextTriggered by remember { mutableStateOf(false) }
+
+ androidx.compose.animation.AnimatedVisibility(
+ visible = isUIVisible && !isCopyMode,
+ enter = slideInVertically(
+ initialOffsetY = { it }, // slides up from below
+ animationSpec = tween(300, easing = androidx.compose.animation.core.CubicBezierEasing(0f, 0f, 0.2f, 1f))
+ ) + fadeIn(animationSpec = tween(300)),
+ exit = slideOutVertically(
+ targetOffsetY = { it }, // slides back down
+ animationSpec = tween(200, easing = androidx.compose.animation.core.CubicBezierEasing(0.4f, 0f, 1f, 1f))
+ ) + fadeOut(animationSpec = tween(200)),
+ modifier = Modifier.align(Alignment.BottomCenter)
+ ) {
+ // ΓöÇΓöÇ Outer card container ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+ androidx.compose.material3.Surface(
+ modifier = Modifier
+ .align(Alignment.BottomCenter)
+ .navigationBarsPadding()
+ .fillMaxWidth()
+ .padding(horizontal = 12.dp, vertical = 16.dp),
+ shape = RoundedCornerShape(28.dp),
+ color = MaterialTheme.colorScheme.surfaceContainerHigh,
+ shadowElevation = 8.dp,
+ tonalElevation = 4.dp
+ ) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 12.dp, vertical = 10.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ // ΓöÇΓöÇ ROW 1: Search Pill + Instant Actions (Song, Translate) ΓöÇΓöÇ
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ // Main Search Pill
+ androidx.compose.material3.Surface(
+ modifier = Modifier
+ .weight(1f)
+ .height(60.dp),
+ shape = CircleShape,
+ color = MaterialTheme.colorScheme.surfaceContainer,
+ tonalElevation = 2.dp
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(horizontal = 14.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ // App logo
+ Image(
+ painter = painterResource(id = com.akslabs.circletosearch.R.drawable.circletosearch),
+ contentDescription = "Logo",
+ modifier = Modifier
+ .size(44.dp)
+ .clickable {
+ haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
+ scope.launch { scaffoldState.bottomSheetState.expand() }
+ }
+ )
+
+ Spacer(modifier = Modifier.weight(1f))
+
+ // Mic Button
+ IconButton(
+ onClick = {
+ haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
+ try {
+ val intent = android.content.Intent(android.speech.RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
+ putExtra(android.speech.RecognizerIntent.EXTRA_LANGUAGE_MODEL, android.speech.RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
+ addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
+ }
+ context.startActivity(intent)
+ } catch (e: Exception) {}
+ },
+ modifier = Modifier.size(44.dp)
+ ) {
+ Icon(Icons.Default.Mic, contentDescription = "Voice Search")
+ }
+
+ Spacer(modifier = Modifier.width(4.dp))
+
+ // Lens Button
+ IconButton(
+ onClick = {
+ haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
+ uiPreferences.setUseGoogleLensOnly(true)
+ if (screenshot != null) {
+ selectedBitmap = screenshot
+ }
+ },
+ modifier = Modifier.size(44.dp)
+ ) {
+ Icon(painterResource(id = com.akslabs.circletosearch.R.drawable.circletosearch), contentDescription = "Lens", tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(26.dp))
+ }
+ }
+ }
+
+ // Circular Button: Song
+ IconButton(
+ onClick = {
+ haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
+ try {
+ val shazamIntent = context.packageManager.getLaunchIntentForPackage("com.shazam.android")
+ val soundHoundIntent = context.packageManager.getLaunchIntentForPackage("com.melodis.midomiMusicIdentifier.freemium")
+ val launchIntent = (shazamIntent ?: soundHoundIntent)?.apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) }
+ if (launchIntent != null) context.startActivity(launchIntent)
+ else context.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse("https://play.google.com/store/search?q=shazam&c=apps")).apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) })
+ } catch (e: Exception) {}
+ },
+ modifier = Modifier
+ .size(60.dp)
+ .background(MaterialTheme.colorScheme.surfaceContainer, CircleShape),
+ ) {
+ Icon(Icons.Default.MusicNote, contentDescription = "Song Search")
+ }
+
+ // Circular Button: Translate
+ IconButton(
+ onClick = {
+ haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
+ try {
+ val intent = context.packageManager.getLaunchIntentForPackage("com.google.android.apps.translate")?.apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) }
+ if (intent != null) context.startActivity(intent)
+ else context.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse("https://translate.google.com")).apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) })
+ } catch (e: Exception) {}
+ },
+ modifier = Modifier
+ .size(60.dp)
+ .background(MaterialTheme.colorScheme.surfaceContainer, CircleShape),
+ ) {
+ Icon(Icons.Default.Translate, contentDescription = "Translate")
+ }
+ }
+
+ // ΓöÇΓöÇ ROW 2: Action buttons ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceEvenly,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ @Composable
+ fun BottomBarButton(label: String, icon: @Composable () -> Unit, onClick: () -> Unit) {
+ Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ FilledTonalIconButton(
+ onClick = { haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress); onClick() },
+ modifier = Modifier.size(52.dp),
+ colors = IconButtonDefaults.filledTonalIconButtonColors(
+ containerColor = MaterialTheme.colorScheme.surfaceContainer,
+ contentColor = MaterialTheme.colorScheme.onSurface
+ )
+ ) { icon() }
+ Text(text = label, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center, maxLines = 1, softWrap = false)
+ }
+ }
+
+ // Share
+ BottomBarButton("Share", { Icon(Icons.Default.Send, null) }) {
+ if (screenshot != null) {
+ scope.launch {
+ try {
+ val fileName = "share_${java.util.UUID.randomUUID()}.png"
+ val path = ImageUtils.saveBitmap(context, selectedBitmap ?: screenshot, fileName)
+ val file = java.io.File(path)
+ val uri = androidx.core.content.FileProvider.getUriForFile(context, "com.akslabs.circletosearch.fileprovider", file)
+ val shareIntent = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
+ type = "image/png"
+ putExtra(android.content.Intent.EXTRA_STREAM, uri)
+ clipData = android.content.ClipData.newRawUri("Selection", uri)
+ addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
+ }
+ context.startActivity(android.content.Intent.createChooser(shareIntent, "Share Image").apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) })
+ } catch (e: Exception) {}
+ }
+ }
+ }
+
+ // GitHub
+ BottomBarButton("GitHub", { Icon(painterResource(id = com.akslabs.circletosearch.R.drawable.github), null, modifier = Modifier.size(22.dp)) }) {
+ context.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse("https://github.com/aks-labs")).apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) })
+ }
+
+ // Telegram
+ BottomBarButton("Telegram", { Icon(painterResource(id = com.akslabs.circletosearch.R.drawable.telegram), null, modifier = Modifier.size(22.dp)) }) {
+ context.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse("https://t.me/akslabs")).apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) })
+ }
+
+ // Donate
+ BottomBarButton("Donate", { Icon(painterResource(id = com.akslabs.circletosearch.R.drawable.donation), null, modifier = Modifier.size(22.dp)) }) {
+ showSupportSheet = true
+ }
+
+ // Copy Text
+ BottomBarButton("Copy Text", { Icon(Icons.Default.TextFields, null) }) {
+ isCopyMode = true
+ isCopyTextTriggered = true
+ }
+
+ // QR Scan
+ BottomBarButton("Scan QR", { Icon(Icons.Default.QrCode, null) }) {
+ qrScanBitmap = selectedBitmap ?: screenshot
+ showQrSheet = true
+ }
+
+ // Fullscreen
+ BottomBarButton("Fullscreen", { Icon(Icons.Default.Fullscreen, null) }) {
+ if (screenshot != null) {
+ selectionRect = Rect(0, 0, screenshot.width, screenshot.height)
+ currentPathPoints.clear()
+ scope.launch { selectionAnim.snapTo(0f); selectionAnim.animateTo(1f, tween(600)); selectedBitmap = screenshot; isSearching = true }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Copy Text overlay integration (Activity-based)
+ if (isCopyMode && copyTextManager != null) {
+ AndroidView(
+ factory = { ctx ->
+ copyTextManager.getOverlayView(onDismiss = {
+ isCopyMode = false
+ onExitCopyMode()
+ })
+ },
+ modifier = Modifier
+ .fillMaxSize()
+ .zIndex(150f)
+ )
+ }
+
+ // 4. Selection Actions (Share) ΓÇö Positioned at the very end for absolute top-layer rendering
+ if (selectionRect != null && selectionAnim.value == 1f && !isCopyMode) {
+ val rect = selectionRect!!
+ val density = androidx.compose.ui.platform.LocalDensity.current
+ val leftPx = rect.left.toFloat()
+ val topPx = rect.top.toFloat()
+ val rightPx = rect.right.toFloat()
+ val bottomPx = rect.bottom.toFloat()
+
+ val leftDp = with(density) { leftPx.toDp() }
+ val topDp = with(density) { topPx.toDp() }
+ val rightDp = with(density) { rightPx.toDp() }
+ val bottomDp = with(density) { bottomPx.toDp() }
+ val widthDp = rightDp - leftDp
+
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .zIndex(2000f) // Highest Z-index
+ ) {
+ Box(
+ modifier = Modifier
+ .offset(
+ x = leftDp,
+ y = if (topPx > 200f) topDp - 64.dp else bottomDp + 16.dp
+ )
+ .width(widthDp),
+ contentAlignment = Alignment.Center
+ ) {
+ // Wrapped in Surface to match Bottom Bar tonal environment
+ androidx.compose.material3.Surface(
+ color = MaterialTheme.colorScheme.surfaceContainerHigh,
+ shape = CircleShape,
+ tonalElevation = 4.dp,
+ shadowElevation = 8.dp
+ ) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ // 1. SHARE BUTTON
+ androidx.compose.material3.FilledTonalButton(
+ onClick = {
+ if (selectedBitmap != null) {
+ scope.launch {
+ try {
+ val fileName = "selection_${java.util.UUID.randomUUID()}.png"
+ val path = ImageUtils.saveBitmap(context, selectedBitmap!!, fileName)
+ val file = java.io.File(path)
+ val uri = androidx.core.content.FileProvider.getUriForFile(context, "com.akslabs.circletosearch.fileprovider", file)
+ val shareIntent = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
+ type = "image/png"
+ putExtra(android.content.Intent.EXTRA_STREAM, uri)
+ clipData = android.content.ClipData.newRawUri("Selection", uri)
+ addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
+ }
+ context.startActivity(android.content.Intent.createChooser(shareIntent, "Share Selection").apply {
+ addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
+ })
+ } catch (e: Exception) {
+ android.util.Log.e("CircleToSearch", "Failed to share selection", e)
+ }
+ }
+ }
+ },
+ modifier = Modifier.height(48.dp),
+ shape = CircleShape,
+ colors = androidx.compose.material3.ButtonDefaults.filledTonalButtonColors(
+ containerColor = Color.Transparent, // Parent surface handles color
+ contentColor = MaterialTheme.colorScheme.onSurface
+ ),
+ elevation = null,
+ contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 20.dp)
+ ) {
+ Text(
+ "Share",
+ style = MaterialTheme.typography.labelLarge.copy(
+ fontWeight = androidx.compose.ui.text.font.FontWeight.Normal
+ )
+ )
+ }
+
+ // Separator
+ androidx.compose.material3.VerticalDivider(
+ modifier = Modifier.height(24.dp).padding(horizontal = 2.dp),
+ color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
+ )
+
+ // 2. SAVE BUTTON
+ androidx.compose.material3.FilledTonalButton(
+ onClick = {
+ if (selectedBitmap != null) {
+ val success = ImageUtils.saveToGallery(context, selectedBitmap!!)
+ if (success) {
+ haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
+ android.widget.Toast.makeText(context, "Saved to Gallery", android.widget.Toast.LENGTH_SHORT).show()
+ } else {
+ android.widget.Toast.makeText(context, "Failed to save", android.widget.Toast.LENGTH_SHORT).show()
+ }
+ }
+ },
+ modifier = Modifier.height(48.dp),
+ shape = CircleShape,
+ colors = androidx.compose.material3.ButtonDefaults.filledTonalButtonColors(
+ containerColor = Color.Transparent,
+ contentColor = MaterialTheme.colorScheme.onSurface
+ ),
+ elevation = null,
+ contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 20.dp)
+ ) {
+ Text(
+ "Save",
+ style = MaterialTheme.typography.labelLarge.copy(
+ fontWeight = androidx.compose.ui.text.font.FontWeight.Normal
+ )
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // QR Code Result Sheet
+ if (showQrSheet) {
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .align(Alignment.BottomCenter)
+ .navigationBarsPadding()
+ .padding(bottom = 16.dp)
+ .zIndex(3000f),
+ contentAlignment = Alignment.BottomCenter
+ ) {
+ Column {
+ QrCodeResultSheet(
+ context = context,
+ bitmap = qrScanBitmap,
+ onDismiss = {
+ showQrSheet = false
+ selectedQrResult = null
+ },
+ preScanned = if (selectedQrResult != null) listOf(selectedQrResult!!) else detectedQrCodes
+ )
+ // Dismiss tap area
+ androidx.compose.foundation.layout.Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(8.dp)
+ .clickable { showQrSheet = false }
+ )
+ }
+ }
+ }
+
+ if (showSupportSheet) {
+ com.akslabs.circletosearch.SupportSheet(
+ sheetState = supportSheetState,
+ onDismissRequest = {
+ scope.launch {
+ supportSheetState.hide()
+ }.invokeOnCompletion {
+ if (!supportSheetState.isVisible) {
+ showSupportSheet = false
+ }
+ }
+ }
+ )
+ }
+
+ if (showSettingsScreen) {
+ SettingsScreen(
+ uiPreferences = uiPreferences,
+ onDismissRequest = { showSettingsScreen = false }
+ )
+ }
+ }
+}
+}
+}
+
+@OptIn(ExperimentalMaterial3ExpressiveApi::class)
+fun ContainedLoadingIndicatorSample() {
+ Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ androidx.compose.material3.ContainedLoadingIndicator()
+ }
+}
diff --git a/CircleToSearchScreen_good.kt b/CircleToSearchScreen_good.kt
new file mode 100644
index 0000000..f492daa
Binary files /dev/null and b/CircleToSearchScreen_good.kt differ
diff --git a/CircleToSearchScreen_good_utf8.kt b/CircleToSearchScreen_good_utf8.kt
new file mode 100644
index 0000000..5963ddc
--- /dev/null
+++ b/CircleToSearchScreen_good_utf8.kt
@@ -0,0 +1,1809 @@
+/*
+ *
+ * * Copyright (C) 2025 AKS-Labs (original author)
+ * *
+ * * This program is free software: you can redistribute it and/or modify
+ * * it under the terms of the GNU General Public License as published by
+ * * the Free Software Foundation, either version 3 of the License, or
+ * * (at your option) any later version.
+ * *
+ * * This program is distributed in the hope that it will be useful,
+ * * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * * GNU General Public License for more details.
+ * *
+ * * You should have received a copy of the GNU General Public License
+ * * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+package com.akslabs.circletosearch.ui
+
+import android.graphics.Bitmap
+import android.graphics.Rect
+import android.util.Base64
+import android.view.ViewGroup
+import android.webkit.WebSettings
+import android.webkit.WebView
+import android.webkit.WebViewClient
+import android.widget.FrameLayout
+import androidx.activity.compose.BackHandler
+import androidx.compose.animation.core.Spring
+import androidx.compose.animation.core.animateFloat
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.animation.core.spring
+import androidx.compose.animation.core.tween
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.slideInVertically
+import androidx.compose.animation.slideOutVertically
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.Image
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.gestures.detectDragGestures
+import androidx.compose.foundation.gestures.detectTapGestures
+import androidx.compose.foundation.interaction.MutableInteractionSource
+import androidx.compose.foundation.interaction.collectIsPressedAsState
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxWithConstraints
+import androidx.compose.foundation.layout.Column
+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.height
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.layout.wrapContentSize
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.BorderOuter
+import androidx.compose.material.icons.filled.Close
+import androidx.compose.material.icons.filled.Code
+import androidx.compose.material.icons.filled.ContentCopy
+import androidx.compose.material.icons.filled.DarkMode
+import androidx.compose.material.icons.filled.DesktopWindows
+import androidx.compose.material.icons.filled.Favorite
+import androidx.compose.material.icons.filled.Fullscreen
+import androidx.compose.material.icons.filled.LightMode
+import androidx.compose.material.icons.filled.Mic
+import androidx.compose.material.icons.filled.MoreVert
+import androidx.compose.material.icons.filled.MusicNote
+import androidx.compose.material.icons.filled.OpenInNew
+import androidx.compose.material.icons.filled.QrCode
+import androidx.compose.material.icons.filled.Refresh
+import androidx.compose.material.icons.filled.Search
+import androidx.compose.material.icons.filled.Send
+import androidx.compose.material.icons.filled.Settings
+import androidx.compose.material.icons.filled.Smartphone
+import androidx.compose.material.icons.filled.TextFields
+import androidx.compose.material.icons.filled.Translate
+import androidx.compose.material3.BottomSheetDefaults
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
+import androidx.compose.material3.FilledTonalIconButton
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.IconButtonDefaults
+import androidx.compose.material3.LoadingIndicator
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.ModalBottomSheet
+import androidx.compose.material3.ScrollableTabRow
+import androidx.compose.material3.SheetValue
+import androidx.compose.material3.Tab
+import androidx.compose.material3.Text
+import androidx.compose.material3.VerticalDivider
+import androidx.compose.material3.rememberModalBottomSheetState
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateListOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.runtime.snapshots.SnapshotStateList
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.draw.shadow
+import androidx.compose.ui.geometry.CornerRadius
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.Path
+import androidx.compose.ui.graphics.StrokeCap
+import androidx.compose.ui.graphics.StrokeJoin
+import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.graphics.drawscope.Stroke
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.painterResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.viewinterop.AndroidView
+import androidx.compose.ui.zIndex
+import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
+import androidx.webkit.WebSettingsCompat
+import com.akslabs.circletosearch.data.SearchEngine
+import com.akslabs.circletosearch.ui.components.FriendlyMessageBubble
+import com.akslabs.circletosearch.ui.components.searchWithGoogleLens
+import com.akslabs.circletosearch.ui.theme.OverlayGradientColors
+import com.akslabs.circletosearch.utils.FriendlyMessageManager
+import com.akslabs.circletosearch.utils.ImageSearchUploader
+import com.akslabs.circletosearch.utils.ImageUtils
+import com.akslabs.circletosearch.utils.QrResult
+import com.akslabs.circletosearch.utils.QrResultWithBounds
+import com.akslabs.circletosearch.utils.QrScanner
+import com.akslabs.circletosearch.ui.qrResultShortLabel
+import com.akslabs.circletosearch.utils.UIPreferences
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import java.io.ByteArrayOutputStream
+import androidx.webkit.WebViewFeature
+import com.akslabs.circletosearch.data.isDirectUpload
+import kotlin.math.max
+import kotlin.math.min
+import androidx.compose.foundation.isSystemInDarkTheme
+import androidx.compose.material3.dynamicDarkColorScheme
+import androidx.compose.material3.dynamicLightColorScheme
+import android.os.Build
+import androidx.compose.material3.Surface
+
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun CircleToSearchScreen(
+ screenshot: Bitmap?,
+ onClose: () -> Unit,
+ copyTextManager: com.akslabs.circletosearch.ui.components.CopyTextOverlayManager? = null,
+ onCopyText: () -> Unit = {},
+ onExitCopyMode: () -> Unit = {}
+) {
+ val context = LocalContext.current
+ val scope = rememberCoroutineScope()
+
+ // Initialize preferences
+ val uiPreferences = remember { UIPreferences(context) }
+
+ // Support Sheet State
+ var showSupportSheet by remember { mutableStateOf(false) }
+ val supportSheetState = rememberModalBottomSheetState()
+
+ // Material You logic for colors
+ val isDark = isSystemInDarkTheme()
+ val dynamicColor = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
+ val colorScheme = when {
+ dynamicColor && isDark -> dynamicDarkColorScheme(context)
+ dynamicColor && !isDark -> dynamicLightColorScheme(context)
+ else -> MaterialTheme.colorScheme // Fallback standard
+ }
+ //Colors for dark theme
+ val barBgColor = if (isDark) Color(0xFF0D0D0D) else colorScheme.surface
+ val bubbleColor = if (isDark) Color(0xFF1F1F1F) else colorScheme.secondaryContainer.copy(alpha = 0.9f)
+ val contentColor = if (isDark) Color.White else colorScheme.onSecondaryContainer
+
+ //Haptic feedback
+ val haptic = androidx.compose.ui.platform.LocalHapticFeedback.current
+
+ //Slide-in animation
+ var isUIVisible by remember { mutableStateOf(false) }
+ LaunchedEffect(Unit) {
+ isUIVisible = true // Déclenche l'animation à l'ouverture
+ }
+
+ // Search Engines Order Logic
+ val preferredOrder = remember(uiPreferences.getSearchEngineOrder()) {
+ val allEngines = SearchEngine.values()
+ val orderString = uiPreferences.getSearchEngineOrder()
+ if (orderString == null) allEngines
+ else {
+ val preferredNames = orderString.split(",")
+ val ordered = mutableListOf<SearchEngine>()
+ preferredNames.forEach { name ->
+ allEngines.find { it.name == name }?.let { ordered.add(it) }
+ }
+ allEngines.forEach { if (!ordered.contains(it)) ordered.add(it) }
+ ordered
+ }
+ }
+ val searchEngines = preferredOrder
+
+ // Copy Mode internal state
+ var isCopyMode by remember { mutableStateOf(false) }
+
+
+ // Support Settings Sheet
+ var showSettingsScreen by remember { mutableStateOf(false) }
+
+ // Friendly Message State
+ var friendlyMessage by remember { mutableStateOf("") }
+ var isMessageVisible by remember { mutableStateOf(false) }
+ var isCopyTextTriggered by remember { mutableStateOf(false) }
+
+ // Resizing state
+ var isResizing by remember { mutableStateOf(false) }
+ var activeHandle by remember { mutableStateOf<String?>(null) } // "tl", "tr", "bl", "br"
+
+ // QR Scanner state
+ var showQrSheet by remember { mutableStateOf(false) }
+ var qrScanBitmap by remember { mutableStateOf<android.graphics.Bitmap?>(null) }
+ var detectedQrCodes by remember { mutableStateOf<List<QrResultWithBounds>>(emptyList()) }
+ var selectedQrResult by remember { mutableStateOf<QrResultWithBounds?>(null) }
+
+ LaunchedEffect(Unit) {
+ if (uiPreferences.isShowFriendlyMessages()) {
+ val manager = FriendlyMessageManager(context)
+ friendlyMessage = manager.getNextMessage()
+ delay(500) // Small delay for smooth entrance
+ isMessageVisible = true
+ delay(4000) // Show for 4 seconds
+ isMessageVisible = false
+ }
+ }
+
+ // Search State
+ var selectedEngine by remember(searchEngines) { mutableStateOf<SearchEngine>(searchEngines.first()) }
+ var searchUrl by remember { mutableStateOf<String?>(null) }
+ var hostedImageUrl by remember { mutableStateOf<String?>(null) }
+ var isLoading by remember { mutableStateOf(false) }
+
+ // Auto-scan entire screenshot for QR codes when it arrives
+ LaunchedEffect(screenshot) {
+ if (screenshot != null) {
+ val found = withContext(Dispatchers.Default) {
+ QrScanner.scanBitmapAll(screenshot!!)
+ }
+ detectedQrCodes = found
+ }
+ }
+ // Desktop Mode - Per Tab
+ // We use a set to track which engines are in desktop mode
+ val initialDesktopMode = uiPreferences.isDesktopMode() // Global default
+ var desktopModeEngines by remember { mutableStateOf<Set<SearchEngine>>(if(initialDesktopMode) searchEngines.toSet() else emptySet()) }
+
+ var isDarkMode by remember { mutableStateOf(uiPreferences.isDarkMode()) }
+ var showGradientBorder by remember { mutableStateOf(uiPreferences.isShowGradientBorder()) }
+
+ // Back gesture handler for QR sheet
+ // We use a high-priority check or ensure it's at the very top of the hierarchy
+ BackHandler(enabled = showQrSheet) {
+ showQrSheet = false
+ selectedQrResult = null
+ }
+
+ // Track initialized engines for Smart Loading
+ val initializedEngines = remember { mutableStateListOf<SearchEngine>() }
+
+ // Save global preference if user toggles it for the MAIN engine (Google) - Optional choice,
+ // or we just keep it per session. Let's keep it simple: no auto-save of per-tab state to verify complex persistence yet.
+ // simpler: If user toggles, we just update the state.
+
+ // Helper to check desktop mode
+ fun isDesktop(engine: SearchEngine) = desktopModeEngines.contains(engine)
+
+ // Removed auto-save of isDesktopMode for now as it is complex with per-tab
+ // We could save "If ALL are desktop" or just the active one?
+ // User requested "depending on opened tab", so per-session state is safer.
+
+ LaunchedEffect(isDarkMode) {
+ uiPreferences.setDarkMode(isDarkMode)
+ }
+
+ LaunchedEffect(showGradientBorder) {
+ uiPreferences.setShowGradientBorder(showGradientBorder)
+ }
+
+ // Cache for preloaded URLs to avoid re-uploading/re-generating
+ val preloadedUrls = remember { mutableMapOf<SearchEngine, String>() }
+
+ // WebView Cache
+ val webViews = remember { mutableMapOf<SearchEngine, WebView>() }
+
+ // Update User Agent dynamically when desktop mode changes for a specific engine
+ // This is now handled in the AndroidView update block or individual engine effects
+ // BUT we need to force reload if the state changes.
+ LaunchedEffect(desktopModeEngines) {
+ webViews.forEach { (engine, wv) ->
+ val isDesktop = desktopModeEngines.contains(engine)
+ val newUserAgent = if (isDesktop) {
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
+ } else {
+ "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"
+ }
+
+ if (wv.settings.userAgentString != newUserAgent) {
+ wv.settings.userAgentString = newUserAgent
+ wv.reload()
+ android.util.Log.d("CircleToSearch", "Desktop mode changed for $engine - Reloaded")
+ }
+ }
+ }
+
+ // Update WebViews when dark mode changes
+ LaunchedEffect(isDarkMode) {
+ webViews.values.forEach { wv ->
+ try {
+ // Update WebViewClient for dark mode
+ if (isDarkMode) {
+ wv.webViewClient = object : android.webkit.WebViewClient() {
+ override fun onPageFinished(view: android.webkit.WebView?, url: String?) {
+ super.onPageFinished(view, url)
+ val darkModeCSS = """
+ javascript:(function() {
+ var style = document.createElement('style');
+ style.innerHTML = `
+ html { filter: invert(1) hue-rotate(180deg) !important; background: #000 !important; }
+ img, video, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; }
+ `;
+ document.head.appendChild(style);
+ })()
+ """.trimIndent()
+ view?.loadUrl(darkModeCSS)
+ }
+ }
+ } else {
+ wv.webViewClient = android.webkit.WebViewClient()
+ }
+ wv.reload()
+ android.util.Log.d("CircleToSearch", "Dark mode changed to: $isDarkMode - Reloaded WebViews")
+ } catch (e: Exception) {
+ android.util.Log.e("CircleToSearch", "Error updating dark mode", e)
+ }
+ }
+ }
+
+ // Bottom Sheet State
+ val scaffoldState = androidx.compose.material3.rememberBottomSheetScaffoldState(
+ bottomSheetState = androidx.compose.material3.rememberStandardBottomSheetState(
+ initialValue = androidx.compose.material3.SheetValue.Hidden,
+ skipHiddenState = false
+ )
+ )
+
+ // Drawing State
+ val currentPathPoints = remember { mutableStateListOf<Offset>() }
+
+ // Selection State
+ var selectedBitmap by remember { mutableStateOf<Bitmap?>(null) }
+ var isSearching by remember { mutableStateOf(false) }
+ var selectionRect by remember { mutableStateOf<Rect?>(null) }
+ val selectionAnim = remember { androidx.compose.animation.core.Animatable(0f) }
+
+ // Lifecycle reset: When screenshot changes, reset selection and modes
+ LaunchedEffect(screenshot) {
+ if (screenshot != null) {
+ isCopyMode = false
+ selectionRect = null
+ selectedBitmap = null
+ isSearching = false
+ currentPathPoints.clear()
+ selectionAnim.snapTo(0f)
+ }
+ }
+
+ // searchEngines moved to top
+ // val searchEngines = SearchEngine.values()
+
+ // Gradient Animation
+ val alphaAnim by animateFloatAsState(
+ targetValue = if (screenshot != null) 1f else 0f,
+ animationSpec = tween(1000), label = "alpha"
+ )
+
+ // Helper to create and configure WebView
+ fun createWebView(ctx: android.content.Context, engine: SearchEngine): WebView {
+ return WebView(ctx).apply {
+ layoutParams = ViewGroup.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT,
+ ViewGroup.LayoutParams.MATCH_PARENT
+ )
+
+ // Caching & Performance - must be set on WebView directly
+ setLayerType(android.view.View.LAYER_TYPE_HARDWARE, null)
+
+ settings.apply {
+ javaScriptEnabled = true
+ domStorageEnabled = true
+ databaseEnabled = true
+ allowFileAccess = true
+ allowContentAccess = true
+ allowFileAccessFromFileURLs = true
+ allowUniversalAccessFromFileURLs = true
+ mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
+
+ // Performance & UI
+ setRenderPriority(WebSettings.RenderPriority.HIGH)
+
+ // Caching for Speed
+ cacheMode = WebSettings.LOAD_DEFAULT // Was LOAD_CACHE_ELSE_NETWORK - caused refresh issues
+
+ // Zoom support
+ setSupportZoom(true)
+ builtInZoomControls = true
+ displayZoomControls = false
+
+ useWideViewPort = true
+ loadWithOverviewMode = true
+
+ userAgentString = if (isDesktop(engine)) {
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
+ } else {
+ "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"
+ }
+
+ // Dark Mode - Use CSS injection for universal compatibility
+ // Algorithmic darkening alone doesn't work on many websites
+ android.util.Log.d("CircleToSearch", "Dark mode enabled: $isDarkMode")
+ }
+
+ // UI Tweaks
+ isVerticalScrollBarEnabled = false
+ isHorizontalScrollBarEnabled = false
+
+ // Enable Third-Party Cookies
+ android.webkit.CookieManager.getInstance().setAcceptThirdPartyCookies(this, true)
+
+ webViewClient = object : WebViewClient() {
+
+ override fun onPageFinished(view: WebView?, url: String?) {
+ super.onPageFinished(view, url)
+ // Inject dark mode CSS if enabled
+ if (isDarkMode) {
+ val darkModeCSS = """
+ javascript:(function() {
+ var style = document.createElement('style');
+ style.innerHTML = `
+ html { filter: invert(1) hue-rotate(180deg) !important; background: #000 !important; }
+ img, video, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; }
+ `;
+ document.head.appendChild(style);
+ })()
+ """.trimIndent()
+ view?.loadUrl(darkModeCSS)
+ android.util.Log.d("CircleToSearch", "Dark mode CSS injected for: $url")
+ }
+ }
+ }
+ isNestedScrollingEnabled = true
+ setOnTouchListener { v, event ->
+ when (event.action) {
+ android.view.MotionEvent.ACTION_DOWN -> {
+ v.parent.requestDisallowInterceptTouchEvent(true)
+ }
+ android.view.MotionEvent.ACTION_UP, android.view.MotionEvent.ACTION_CANCEL -> {
+ v.parent.requestDisallowInterceptTouchEvent(false)
+ }
+ }
+ false
+ }
+ }
+ }
+
+ // Back Handler Logic
+ BackHandler(enabled = true) {
+ if (isCopyMode) {
+ isCopyMode = false
+ onExitCopyMode()
+ return@BackHandler
+ }
+ val currentWebView = webViews[selectedEngine]
+ if (currentWebView != null && currentWebView.canGoBack()) {
+ currentWebView.goBack()
+ } else if (scaffoldState.bottomSheetState.currentValue == androidx.compose.material3.SheetValue.Expanded) {
+ scope.launch { scaffoldState.bottomSheetState.partialExpand() }
+ } else if (scaffoldState.bottomSheetState.currentValue == androidx.compose.material3.SheetValue.PartiallyExpanded) {
+ scope.launch { scaffoldState.bottomSheetState.hide() }
+ } else {
+ onClose()
+ }
+ }
+
+ Surface(
+ color = Color.Transparent,
+ tonalElevation = 0.dp
+ ) {
+ androidx.compose.material3.BottomSheetScaffold(
+ scaffoldState = scaffoldState,
+ sheetPeekHeight = (androidx.compose.ui.platform.LocalConfiguration.current.screenHeightDp.dp * 0.55f), // Dynamic 55% peek
+ containerColor = Color.Transparent,
+ sheetContainerColor = Color.Transparent,
+ sheetContentColor = MaterialTheme.colorScheme.onSurface,
+ sheetDragHandle = { BottomSheetDefaults.DragHandle() },
+ sheetSwipeEnabled = true,
+ sheetContent = {
+ // Bottom Sheet Content (Results)
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(800.dp)
+ .background(MaterialTheme.colorScheme.surface, RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp))
+ ) {
+ Spacer(modifier = Modifier.height(16.dp))
+
+ // Tabs - Polished UI
+ ScrollableTabRow(
+ selectedTabIndex = searchEngines.indexOf(selectedEngine),
+ edgePadding = 16.dp,
+ containerColor = Color.Transparent,
+ contentColor = MaterialTheme.colorScheme.onSurface,
+ divider = {},
+ indicator = {}
+ ) {
+ searchEngines.forEach { engine ->
+ val selected = selectedEngine == engine
+ val transition = androidx.compose.animation.core.updateTransition(targetState = selected, label = "TabSelect")
+ val scale by transition.animateFloat(label = "Scale") { if (it) 1.05f else 1f }
+ val alpha by transition.animateFloat(label = "Alpha") { if (it) 1f else 0.7f }
+
+ Tab(
+ selected = selected,
+ onClick = { selectedEngine = engine },
+ modifier = Modifier.graphicsLayer {
+ scaleX = scale
+ scaleY = scale
+ this.alpha = alpha
+ },
+ text = {
+ Text(
+ engine.name,
+ style = MaterialTheme.typography.labelLarge.copy(
+ fontWeight = if (selected) FontWeight.Bold else FontWeight.Medium
+ ),
+ modifier = Modifier
+ .background(
+ if (selected) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.surfaceVariant.copy(alpha=0.5f),
+ RoundedCornerShape(16.dp)
+ )
+ .border(
+ width = 1.dp,
+ color = if(selected) MaterialTheme.colorScheme.primary.copy(alpha=0.5f) else Color.Transparent,
+ shape = RoundedCornerShape(16.dp)
+ )
+ .padding(horizontal = 16.dp, vertical = 8.dp),
+ color = if (selected) MaterialTheme.colorScheme.onSecondaryContainer else MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ )
+ }
+ }
+
+ // Reset everything when bitmap changes (new area selected)
+ LaunchedEffect(selectedBitmap) {
+ hostedImageUrl = null
+ searchUrl = null
+ preloadedUrls.clear()
+ initializedEngines.clear() // Reset smart loading
+ // Do NOT destroy webviews here to keep them cached if possible?
+ // PROBABLY safer to destroy to avoid stale state from previous searches.
+ webViews.values.forEach { it.destroy() }
+ webViews.clear()
+ }
+
+ LaunchedEffect(selectedBitmap, hostedImageUrl) {
+ if (selectedBitmap != null) {
+ isLoading = true
+
+ // 1. Google Lens Only Mode Check
+ if (uiPreferences.isUseGoogleLensOnly()) {
+ // Save to cache and launch Lens
+ val path = ImageUtils.saveBitmap(context, selectedBitmap!!)
+ val uri = android.net.Uri.fromFile(java.io.File(path))
+
+ // Prepare content URI for Lens (using existing FileProvider logic in helper)
+ val success = searchWithGoogleLens(uri, context)
+
+ if (success) {
+ // Close the overlay since Lens is taking over
+ onClose()
+ return@LaunchedEffect
+ } else {
+ // Fallback to multi-search if Lens failed
+ android.util.Log.e("CircleToSearch", "Google Lens launch failed, falling back to multi-search")
+ }
+ }
+
+ // 2. Multi-Search Mode (Expanded UI)
+ scope.launch { scaffoldState.bottomSheetState.expand() }
+
+ // 3. Upload to host if needed (Multi-Search Mode)
+ if (hostedImageUrl == null) {
+ val url = ImageSearchUploader.uploadToImageHost(selectedBitmap!!)
+ if (url != null) {
+ hostedImageUrl = url
+ } else {
+ isLoading = false
+ return@LaunchedEffect
+ }
+ }
+
+ // 2. Generate URLs for ALL engines (lightweight string op)
+ searchEngines.forEach { engine ->
+ if (!preloadedUrls.containsKey(engine)) {
+ val url = if (engine.isDirectUpload) {
+ when (engine) {
+ SearchEngine.Perplexity -> ImageSearchUploader.getPerplexityUrl(hostedImageUrl!!)
+ SearchEngine.ChatGPT -> ImageSearchUploader.getChatGPTUrl(hostedImageUrl!!)
+ else -> null
+ }
+ } else {
+ when (engine) {
+ SearchEngine.Google -> ImageSearchUploader.getGoogleLensUrl(hostedImageUrl!!)
+ SearchEngine.Bing -> ImageSearchUploader.getBingUrl(hostedImageUrl!!)
+ SearchEngine.Yandex -> ImageSearchUploader.getYandexUrl(hostedImageUrl!!)
+ SearchEngine.TinEye -> ImageSearchUploader.getTinEyeUrl(hostedImageUrl!!)
+ else -> null
+ }
+ }
+ if (url != null) preloadedUrls[engine] = url
+ }
+ }
+
+ // 3. Set initial URL
+ if (preloadedUrls.containsKey(selectedEngine)) {
+ searchUrl = preloadedUrls[selectedEngine]
+ }
+
+ // 4. SMART LOADING SEQUENCE
+ // First, ensure selected engine is initialized
+ if (!initializedEngines.contains(selectedEngine)) {
+ initializedEngines.add(selectedEngine)
+ }
+
+ isLoading = false
+
+ // Then, load others sequentially
+ scope.launch {
+ searchEngines.forEach { engine ->
+ if (engine != selectedEngine) {
+ delay(300) // Reduced from 800ms for faster loading
+ if (!initializedEngines.contains(engine)) {
+ initializedEngines.add(engine)
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Update searchUrl when engine changes
+ LaunchedEffect(selectedEngine, preloadedUrls) {
+ if (preloadedUrls.containsKey(selectedEngine)) {
+ searchUrl = preloadedUrls[selectedEngine]
+ }
+ }
+
+ // Memory Optimization: REMOVED Aggressive Cleanup
+ // User Requirement: "dont refresh tabs when user switch tabs keep them in background"
+ // We keep them alive.
+ /*
+ LaunchedEffect(selectedEngine) {
+ // ... (Cleanup logic removed)
+ }
+ */
+
+ Box(modifier = Modifier.fillMaxSize()) {
+ // Show loading only if the SELECTED engine isn't ready or just starting
+ if (isLoading || (preloadedUrls.containsKey(selectedEngine) && !webViews.containsKey(selectedEngine))) {
+ // We delay showing the loader slightly to avoid flicker if WebView attaches instantly
+ var showLoader by remember { mutableStateOf(false) }
+ LaunchedEffect(Unit) {
+ kotlinx.coroutines.delay(100)
+ showLoader = true
+ }
+
+ if (showLoader || isLoading) {
+ Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ ContainedLoadingIndicatorSample()
+ }
+ }
+ }
+
+ // Dynamic Settings Update (User Agent etc) - Now handled at top level
+ // Cleanup on Dispose
+ DisposableEffect(Unit) {
+ onDispose {
+ webViews.values.forEach { it.destroy() }
+ webViews.clear()
+ }
+ }
+
+ // Render WebViews
+ searchEngines.forEach { engine ->
+ // Logic: Render if it's in the initialized set (Smart Loading)
+ // This ensures we don't load everything at once, but once loaded, we keep it.
+ if (initializedEngines.contains(engine) && preloadedUrls.containsKey(engine)) {
+ val url = preloadedUrls[engine]!!
+ val isSelected = (engine == selectedEngine)
+
+ androidx.compose.runtime.key(engine) {
+ AndroidView(
+ factory = { ctx ->
+ if (webViews.containsKey(engine)) {
+ // Should not happen with key(), but safety check
+ val v = webViews[engine]!!
+ (v.parent as? ViewGroup)?.removeView(v)
+
+ val swipeRefresh = SwipeRefreshLayout(ctx).apply {
+ layoutParams = ViewGroup.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT,
+ ViewGroup.LayoutParams.MATCH_PARENT
+ )
+ }
+ swipeRefresh.addView(v)
+ swipeRefresh.setOnRefreshListener {
+ v.reload()
+ swipeRefresh.isRefreshing = false
+ }
+ swipeRefresh
+ } else {
+ val swipeRefresh = SwipeRefreshLayout(ctx).apply {
+ layoutParams = ViewGroup.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT,
+ ViewGroup.LayoutParams.MATCH_PARENT
+ )
+ }
+ val webView = createWebView(ctx, engine)
+ // Apply current settings
+ if (isDesktop(engine)) {
+ webView.settings.userAgentString = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
+ }
+
+ webViews[engine] = webView
+ webView.loadUrl(url)
+
+ swipeRefresh.addView(webView)
+ swipeRefresh.setOnRefreshListener {
+ webView.reload()
+ swipeRefresh.isRefreshing = false
+ }
+ swipeRefresh
+ }
+ },
+ update = { swipeRefresh ->
+ var webView: WebView? = null
+ for (i in 0 until swipeRefresh.childCount) {
+ val child = swipeRefresh.getChildAt(i)
+ if (child is WebView) {
+ webView = child
+ break
+ }
+ }
+
+ if (webView != null) {
+ if (webView.url != url && url != webView.originalUrl) {
+ webView.loadUrl(url)
+ }
+ }
+ },
+ modifier = Modifier
+ .fillMaxSize()
+ .zIndex(if (isSelected) 1f else 0f)
+ .graphicsLayer {
+ alpha = if (isSelected) 1f else 0f
+ }
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+ ) { _ ->
+ // Root Box
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(Color.Transparent) // Changed from Black to Transparent
+ ) {
+ // Close button for Copy Mode (Top Left)
+
+ // Friendly Message Overlay (Top Center)
+ if (!isCopyMode) {
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .offset(y = 100.dp) // Offset to not cover potential top icons
+ .zIndex(100f), // Ensure on top
+ contentAlignment = Alignment.TopCenter
+ ) {
+ FriendlyMessageBubble(
+ message = friendlyMessage,
+ visible = isMessageVisible
+ )
+ }
+ }
+
+ // 1. Screenshot Layer
+ if (screenshot != null && !isCopyMode) {
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .graphicsLayer {
+ // Required for BlendMode.Clear to work in child Canvas
+ compositingStrategy = androidx.compose.ui.graphics.CompositingStrategy.Offscreen
+ }
+ ) {
+ Image(
+ bitmap = screenshot.asImageBitmap(),
+ contentDescription = "Screenshot",
+ contentScale = ContentScale.FillBounds,
+ modifier = Modifier.fillMaxSize()
+ )
+
+
+ // Tint Overlay (Punch-out style)
+ Canvas(modifier = Modifier.fillMaxSize()) {
+ val strokeWidth = 0f
+ val dimAlpha = 0.15f
+
+ // 1. Draw global dim
+ drawRect(Color.Black.copy(alpha = dimAlpha))
+ drawRect(
+ brush = Brush.verticalGradient(
+ colors = OverlayGradientColors.map { it.copy(alpha = dimAlpha) }
+ )
+ )
+
+ // 2. Clear selection area if it exists
+ if (selectionRect != null && selectionAnim.value > 0f) {
+ val rect = selectionRect!!
+ val progress = selectionAnim.value
+ val holeRect = androidx.compose.ui.geometry.Rect(
+ rect.left.toFloat(),
+ rect.top.toFloat(),
+ rect.right.toFloat(),
+ rect.bottom.toFloat()
+ )
+
+ // Punch the hole
+ drawRoundRect(
+ color = Color.Transparent,
+ topLeft = holeRect.topLeft,
+ size = holeRect.size,
+ cornerRadius = CornerRadius(48f),
+ blendMode = androidx.compose.ui.graphics.BlendMode.Clear
+ )
+ }
+ }
+ }
+ }
+
+ // 2. Gradient Border Layer (Overlaying screenshot, clipped to rounded corners)
+ if (showGradientBorder && !isCopyMode) {
+ androidx.compose.animation.AnimatedVisibility(
+ visible = isUIVisible,
+ enter = androidx.compose.animation.fadeIn(animationSpec = tween(700))
+ ) {
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .border(
+ width = 8.dp,
+ brush = Brush.verticalGradient(
+ colors = OverlayGradientColors.map { it.copy(alpha = 0.5f) }
+ ),
+ shape = RoundedCornerShape(24.dp) // Rounded corners for device
+ )
+ .clip(RoundedCornerShape(24.dp))
+ )
+ }
+ }
+
+ // 3. Drawing Canvas (Interactive Layer)
+ if (!isCopyMode) { Canvas(
+ modifier = Modifier
+ .fillMaxSize()
+ .pointerInput(Unit) {
+ detectDragGestures(
+ onDragStart = { offset ->
+ val rect = selectionRect
+ if (rect != null && selectionAnim.value == 1f) {
+ val handleSize = 64f // px for hit testing
+ val tl = Offset(rect.left.toFloat(), rect.top.toFloat())
+ val tr = Offset(rect.right.toFloat(), rect.top.toFloat())
+ val bl = Offset(rect.left.toFloat(), rect.bottom.toFloat())
+ val br = Offset(rect.right.toFloat(), rect.bottom.toFloat())
+
+ when {
+ (offset - tl).getDistance() < handleSize -> { isResizing = true; activeHandle = "tl" }
+ (offset - tr).getDistance() < handleSize -> { isResizing = true; activeHandle = "tr" }
+ (offset - bl).getDistance() < handleSize -> { isResizing = true; activeHandle = "bl" }
+ (offset - br).getDistance() < handleSize -> { isResizing = true; activeHandle = "br" }
+ else -> { isResizing = false; activeHandle = null }
+ }
+
+ if (isResizing) return@detectDragGestures
+ }
+
+ // Clear previous state if starting new draw
+ currentPathPoints.clear()
+ currentPathPoints.add(offset)
+ selectionRect = null
+ scope.launch { selectionAnim.snapTo(0f) }
+ },
+ onDrag = { change, _ ->
+ if (isResizing && activeHandle != null) {
+ val rect = selectionRect ?: return@detectDragGestures
+ val pos = change.position
+ val newRect = android.graphics.Rect(rect)
+ when (activeHandle) {
+ "tl" -> { newRect.left = pos.x.toInt(); newRect.top = pos.y.toInt() }
+ "tr" -> { newRect.right = pos.x.toInt(); newRect.top = pos.y.toInt() }
+ "bl" -> { newRect.left = pos.x.toInt(); newRect.bottom = pos.y.toInt() }
+ "br" -> { newRect.right = pos.x.toInt(); newRect.bottom = pos.y.toInt() }
+ }
+ // Basic validation (min size)
+ if (newRect.width() > 20 && newRect.height() > 20) {
+ selectionRect = newRect
+ }
+ } else {
+ currentPathPoints.add(change.position)
+ }
+ },
+ onDragEnd = {
+ if (isResizing) {
+ isResizing = false
+ activeHandle = null
+ // Update cropped bitmap after resize
+ if (screenshot != null && selectionRect != null) {
+ selectedBitmap = ImageUtils.cropBitmap(screenshot, selectionRect!!)
+ }
+ } else if (currentPathPoints.isNotEmpty()) {
+ var minX = Float.MAX_VALUE
+ var minY = Float.MAX_VALUE
+ var maxX = Float.MIN_VALUE
+ var maxY = Float.MIN_VALUE
+ currentPathPoints.forEach { p ->
+ minX = kotlin.math.min(minX, p.x)
+ minY = kotlin.math.min(minY, p.y)
+ maxX = kotlin.math.max(maxX, p.x)
+ maxY = kotlin.math.max(maxY, p.y)
+ }
+
+ val border = 20
+ val rect = android.graphics.Rect(
+ (minX - border).toInt().coerceAtLeast(0),
+ (minY - border).toInt().coerceAtLeast(0),
+ (maxX + border).toInt().coerceAtMost(screenshot?.width ?: 0),
+ (maxY + border).toInt().coerceAtMost(screenshot?.height ?: 0)
+ )
+
+ if (rect.width() > 10 && rect.height() > 10) {
+ selectionRect = rect
+ currentPathPoints.clear() // Hide the drawn circle
+ if (screenshot != null) {
+ selectedBitmap = ImageUtils.cropBitmap(screenshot!!, rect)
+ }
+ scope.launch {
+ selectionAnim.animateTo(1f, tween(600))
+ isSearching = true
+ }
+ }
+ }
+ }
+ )
+ }
+ ) {
+ // Draw current path (Real-time)
+ if (currentPathPoints.size > 1) {
+ val path = Path().apply {
+ moveTo(currentPathPoints.first().x, currentPathPoints.first().y)
+ for (i in 1 until currentPathPoints.size) {
+ lineTo(currentPathPoints[i].x, currentPathPoints[i].y)
+ }
+ }
+
+ // Glow
+ drawPath(
+ path = path,
+ brush = Brush.linearGradient(OverlayGradientColors),
+ style = Stroke(width = 30f, cap = StrokeCap.Round, join = StrokeJoin.Round),
+ alpha = 0.6f
+ )
+ // Core
+ drawPath(
+ path = path,
+ color = Color.White,
+ style = Stroke(width = 12f, cap = StrokeCap.Round, join = StrokeJoin.Round)
+ )
+ }
+
+ // Draw Lens Animation (Rounded Corner Brackets)
+ if (selectionRect != null && selectionAnim.value > 0f) {
+ val rect = selectionRect!!
+ val progress = selectionAnim.value
+ val left = rect.left.toFloat()
+ val top = rect.top.toFloat()
+ val right = rect.right.toFloat()
+ val bottom = rect.bottom.toFloat()
+
+ val width = right - left
+ val height = bottom - top
+ val cornerRadius = 48f // Slightly smaller radius
+ val armLength = min(width, height) * 0.15f // Slightly shorter arms
+
+ // Top Left
+ val tlPath = Path().apply {
+ moveTo(left, top + armLength)
+ lineTo(left, top + cornerRadius)
+ arcTo(
+ rect = androidx.compose.ui.geometry.Rect(left, top, left + 2 * cornerRadius, top + 2 * cornerRadius),
+ startAngleDegrees = 180f,
+ sweepAngleDegrees = 90f,
+ forceMoveTo = false
+ )
+ lineTo(left + armLength, top)
+ }
+ // Top Right
+ val trPath = Path().apply {
+ moveTo(right - armLength, top)
+ lineTo(right - cornerRadius, top)
+ arcTo(
+ rect = androidx.compose.ui.geometry.Rect(right - 2 * cornerRadius, top, right, top + 2 * cornerRadius),
+ startAngleDegrees = 270f,
+ sweepAngleDegrees = 90f,
+ forceMoveTo = false
+ )
+ lineTo(right, top + armLength)
+ }
+ // Bottom Right
+ val brPath = Path().apply {
+ moveTo(right, bottom - armLength)
+ lineTo(right, bottom - cornerRadius)
+ arcTo(
+ rect = androidx.compose.ui.geometry.Rect(right - 2 * cornerRadius, bottom - 2 * cornerRadius, right, bottom),
+ startAngleDegrees = 0f,
+ sweepAngleDegrees = 90f,
+ forceMoveTo = false
+ )
+ lineTo(right - armLength, bottom)
+ }
+ // Bottom Left
+ val blPath = Path().apply {
+ moveTo(left + armLength, bottom)
+ lineTo(left + cornerRadius, bottom)
+ arcTo(
+ rect = androidx.compose.ui.geometry.Rect(left, bottom - 2 * cornerRadius, left + 2 * cornerRadius, bottom),
+ startAngleDegrees = 90f,
+ sweepAngleDegrees = 90f,
+ forceMoveTo = false
+ )
+ lineTo(left, bottom - armLength)
+ }
+
+ val bracketAlpha = progress
+ val bracketStroke = Stroke(width = 12f, cap = StrokeCap.Round, join = StrokeJoin.Round)
+
+ // Draw Brackets (Solid White)
+ listOf(tlPath, trPath, brPath, blPath).forEach { p ->
+ drawPath(p, Color.White, style = bracketStroke, alpha = bracketAlpha)
+ }
+
+ // Optional: Flash effect inside
+ drawRoundRect(
+ color = Color.White,
+ topLeft = Offset(left, top),
+ size = Size(width, height),
+ cornerRadius = CornerRadius(48f),
+ style = Stroke(width = 4f),
+ alpha = (1f - progress) * 0.5f
+ )
+ }
+ }
+
+ }
+
+ // 4. Header (Top)
+ androidx.compose.animation.AnimatedVisibility(
+ visible = isUIVisible && !isCopyMode,
+ enter = androidx.compose.animation.slideInVertically(
+ initialOffsetY = { -it }, // Commence au-dessus de l'écran (-100%)
+ animationSpec = tween(500, easing = androidx.compose.animation.core.FastOutSlowInEasing)
+ ),
+ modifier = Modifier.align(Alignment.TopCenter).zIndex(2000f)
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .statusBarsPadding()
+ .padding(top = 16.dp, start = 16.dp, end = 16.dp)
+ .align(Alignment.TopCenter),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ IconButton(
+ onClick =
+ {
+ haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
+ onClose()
+ },
+ modifier = Modifier
+ .background(Color.Gray.copy(alpha = 0.5f), CircleShape)
+ .size(40.dp)
+ ) {
+ Icon(Icons.Default.Close, contentDescription = "Close", tint = Color.White)
+ }
+ Spacer(modifier = Modifier.weight(1f))
+ if (selectedEngine.name == "Google") {
+ // Si c'est Google, on affiche ta belle typo officielle
+ Image(
+ painter = painterResource(id = com.akslabs.circletosearch.R.drawable.googletypo),
+ contentDescription = "Google Search",
+ modifier = Modifier.height(50.dp), // Hauteur ajustable selon ton PNG
+ colorFilter = androidx.compose.ui.graphics.ColorFilter.tint(Color.White)
+ )
+ } else {
+ // Si c'est Bing, Yandex, etc., on garde le texte stylé d'origine
+ Text(
+ text = selectedEngine.name,
+ style = MaterialTheme.typography.headlineMedium.copy(
+ fontWeight = FontWeight.Bold,
+ color = Color.White
+ )
+ )
+ }
+ Spacer(modifier = Modifier.weight(1f))
+
+ // Action Button (Menu)
+ Box(
+ modifier = Modifier
+ .background(Color.Gray.copy(alpha = 0.5f), CircleShape)
+ .size(40.dp),
+ contentAlignment = Alignment.Center
+ ) {
+ var showMenu by remember { mutableStateOf(false) }
+ IconButton(onClick = {
+ haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
+ showMenu = true
+ }) {
+ Icon(
+ Icons.Default.MoreVert,
+ contentDescription = "Menu",
+ tint = Color.White
+ )
+ }
+
+ androidx.compose.material3.DropdownMenu(
+ expanded = showMenu,
+ onDismissRequest = { showMenu = false }
+ ) {
+ val isDesktop = isDesktop(selectedEngine)
+ androidx.compose.material3.DropdownMenuItem(
+ text = { Text(if (isDesktop) "Mobile Mode" else "Desktop Mode") },
+ leadingIcon = {
+ Icon(
+ if (isDesktop) Icons.Default.Smartphone else Icons.Default.DesktopWindows,
+ contentDescription = null
+ )
+ },
+ onClick = {
+ val newSet = desktopModeEngines.toMutableSet()
+ if (newSet.contains(selectedEngine)) {
+ newSet.remove(selectedEngine)
+ } else {
+ newSet.add(selectedEngine)
+ }
+ desktopModeEngines = newSet
+ showMenu = false
+ }
+ )
+ androidx.compose.material3.DropdownMenuItem(
+ text = { Text(if (isDarkMode) "Light Mode" else "Dark Mode") },
+ leadingIcon = {
+ Icon(
+ if (isDarkMode) Icons.Default.LightMode else Icons.Default.DarkMode,
+ contentDescription = null
+ )
+ },
+ onClick = {
+ isDarkMode = !isDarkMode
+ showMenu = false
+ }
+ )
+ androidx.compose.material3.DropdownMenuItem(
+ text = { Text(if (showGradientBorder) "Hide Border" else "Show Border") },
+ leadingIcon = {
+ Icon(Icons.Default.BorderOuter, contentDescription = null)
+ },
+ onClick = {
+ showGradientBorder = !showGradientBorder
+ showMenu = false
+ }
+ )
+ androidx.compose.material3.DropdownMenuItem(
+ text = { Text("Refresh") },
+ leadingIcon = {
+ Icon(Icons.Default.Refresh, contentDescription = null)
+ },
+ onClick = {
+ webViews[selectedEngine]?.reload()
+ showMenu = false
+ }
+ )
+ androidx.compose.material3.DropdownMenuItem(
+ text = { Text("Copy URL") },
+ leadingIcon = {
+ Icon(Icons.Default.ContentCopy, contentDescription = null)
+ },
+ onClick = {
+ if (searchUrl != null) {
+ val clipboard =
+ context.getSystemService(android.content.Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
+ val clip = android.content.ClipData.newPlainText(
+ "Search URL",
+ searchUrl
+ )
+ clipboard.setPrimaryClip(clip)
+ }
+ showMenu = false
+ }
+ )
+ androidx.compose.material3.DropdownMenuItem(
+ text = { Text("Open in Browser") },
+ leadingIcon = {
+ Icon(Icons.Default.OpenInNew, contentDescription = null)
+ },
+ onClick = {
+ val currentUrl = webViews[selectedEngine]?.url ?: searchUrl
+ if (currentUrl != null) {
+ try {
+ val intent = android.content.Intent(
+ android.content.Intent.ACTION_VIEW,
+ android.net.Uri.parse(currentUrl)
+ )
+ context.startActivity(intent)
+ } catch (e: Exception) {
+ android.util.Log.e(
+ "CircleToSearch",
+ "Failed to open browser",
+ e
+ )
+ }
+ }
+ showMenu = false
+ }
+ )
+ androidx.compose.material3.DropdownMenuItem(
+ text = { Text("Settings") },
+ leadingIcon = {
+ Icon(Icons.Default.Settings, contentDescription = null)
+ },
+ onClick = {
+ showSettingsScreen = true
+ showMenu = false
+ }
+ )
+ }
+ }
+ }
+ }
+ // 5. Bottom Bar ΓÇö Material 3 Expressive two-row card
+ // State for Copy Text mode
+ var isCopyTextTriggered by remember { mutableStateOf(false) }
+
+ androidx.compose.animation.AnimatedVisibility(
+ visible = isUIVisible && !isCopyMode,
+ enter = slideInVertically(
+ initialOffsetY = { it }, // slides up from below
+ animationSpec = tween(300, easing = androidx.compose.animation.core.CubicBezierEasing(0f, 0f, 0.2f, 1f))
+ ) + fadeIn(animationSpec = tween(300)),
+ exit = slideOutVertically(
+ targetOffsetY = { it }, // slides back down
+ animationSpec = tween(200, easing = androidx.compose.animation.core.CubicBezierEasing(0.4f, 0f, 1f, 1f))
+ ) + fadeOut(animationSpec = tween(200)),
+ modifier = Modifier.align(Alignment.BottomCenter).zIndex(2000f)
+ ) {
+ // ΓöÇΓöÇ Outer card container ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+ androidx.compose.material3.Surface(
+ modifier = Modifier
+ .align(Alignment.BottomCenter)
+ .navigationBarsPadding()
+ .fillMaxWidth()
+ .padding(horizontal = 12.dp, vertical = 16.dp),
+ shape = RoundedCornerShape(28.dp),
+ color = MaterialTheme.colorScheme.surfaceContainerHigh,
+ shadowElevation = 8.dp,
+ tonalElevation = 4.dp
+ ) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 12.dp, vertical = 10.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ // ΓöÇΓöÇ ROW 1: Search Pill + Instant Actions (Song, Translate) ΓöÇΓöÇ
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ // Main Search Pill
+ androidx.compose.material3.Surface(
+ modifier = Modifier
+ .weight(1f)
+ .height(60.dp),
+ shape = CircleShape,
+ color = MaterialTheme.colorScheme.surfaceContainer,
+ tonalElevation = 2.dp
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(horizontal = 14.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ // App logo
+ Image(
+ painter = painterResource(id = com.akslabs.circletosearch.R.drawable.circletosearch),
+ contentDescription = "Logo",
+ modifier = Modifier
+ .size(44.dp)
+ .clickable {
+ haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
+ scope.launch { scaffoldState.bottomSheetState.expand() }
+ }
+ )
+
+ Spacer(modifier = Modifier.weight(1f))
+
+ // Mic Button
+ IconButton(
+ onClick = {
+ haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
+ try {
+ val intent = android.content.Intent(android.speech.RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
+ putExtra(android.speech.RecognizerIntent.EXTRA_LANGUAGE_MODEL, android.speech.RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
+ addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
+ }
+ context.startActivity(intent)
+ } catch (e: Exception) {}
+ },
+ modifier = Modifier.size(44.dp)
+ ) {
+ Icon(Icons.Default.Mic, contentDescription = "Voice Search")
+ }
+
+ Spacer(modifier = Modifier.width(4.dp))
+
+ // Lens Button
+ IconButton(
+ onClick = {
+ haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
+ uiPreferences.setUseGoogleLensOnly(true)
+ if (screenshot != null) {
+ selectedBitmap = screenshot
+ }
+ },
+ modifier = Modifier.size(44.dp)
+ ) {
+ Icon(painterResource(id = com.akslabs.circletosearch.R.drawable.circletosearch), contentDescription = "Lens", tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(26.dp))
+ }
+ }
+ }
+
+ // Circular Button: Song
+ IconButton(
+ onClick = {
+ haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
+ try {
+ val shazamIntent = context.packageManager.getLaunchIntentForPackage("com.shazam.android")
+ val soundHoundIntent = context.packageManager.getLaunchIntentForPackage("com.melodis.midomiMusicIdentifier.freemium")
+ val launchIntent = (shazamIntent ?: soundHoundIntent)?.apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) }
+ if (launchIntent != null) context.startActivity(launchIntent)
+ else context.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse("https://play.google.com/store/search?q=shazam&c=apps")).apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) })
+ } catch (e: Exception) {}
+ },
+ modifier = Modifier
+ .size(60.dp)
+ .background(MaterialTheme.colorScheme.surfaceContainer, CircleShape),
+ ) {
+ Icon(Icons.Default.MusicNote, contentDescription = "Song Search")
+ }
+
+ // Circular Button: Translate
+ IconButton(
+ onClick = {
+ haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
+ try {
+ val intent = context.packageManager.getLaunchIntentForPackage("com.google.android.apps.translate")?.apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) }
+ if (intent != null) context.startActivity(intent)
+ else context.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse("https://translate.google.com")).apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) })
+ } catch (e: Exception) {}
+ },
+ modifier = Modifier
+ .size(60.dp)
+ .background(MaterialTheme.colorScheme.surfaceContainer, CircleShape),
+ ) {
+ Icon(Icons.Default.Translate, contentDescription = "Translate")
+ }
+ }
+
+ // ΓöÇΓöÇ ROW 2: Action buttons ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceEvenly,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ @Composable
+ fun BottomBarButton(label: String, icon: @Composable () -> Unit, onClick: () -> Unit) {
+ Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ FilledTonalIconButton(
+ onClick = { haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress); onClick() },
+ modifier = Modifier.size(52.dp),
+ colors = IconButtonDefaults.filledTonalIconButtonColors(
+ containerColor = MaterialTheme.colorScheme.surfaceContainer,
+ contentColor = MaterialTheme.colorScheme.onSurface
+ )
+ ) { icon() }
+ Text(text = label, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center, maxLines = 1, softWrap = false)
+ }
+ }
+
+ // Share
+ BottomBarButton("Share", { Icon(Icons.Default.Send, null) }) {
+ if (screenshot != null) {
+ scope.launch {
+ try {
+ val fileName = "share_${java.util.UUID.randomUUID()}.png"
+ val path = ImageUtils.saveBitmap(context, selectedBitmap ?: screenshot, fileName)
+ val file = java.io.File(path)
+ val uri = androidx.core.content.FileProvider.getUriForFile(context, "com.akslabs.circletosearch.fileprovider", file)
+ val shareIntent = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
+ type = "image/png"
+ putExtra(android.content.Intent.EXTRA_STREAM, uri)
+ clipData = android.content.ClipData.newRawUri("Selection", uri)
+ addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
+ }
+ context.startActivity(android.content.Intent.createChooser(shareIntent, "Share Image").apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) })
+ } catch (e: Exception) {}
+ }
+ }
+ }
+
+ // GitHub
+ BottomBarButton("GitHub", { Icon(painterResource(id = com.akslabs.circletosearch.R.drawable.github), null, modifier = Modifier.size(22.dp)) }) {
+ context.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse("https://github.com/aks-labs")).apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) })
+ }
+
+ // Telegram
+ BottomBarButton("Telegram", { Icon(painterResource(id = com.akslabs.circletosearch.R.drawable.telegram), null, modifier = Modifier.size(22.dp)) }) {
+ context.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse("https://t.me/akslabs")).apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) })
+ }
+
+ // Donate
+ BottomBarButton("Donate", { Icon(painterResource(id = com.akslabs.circletosearch.R.drawable.donation), null, modifier = Modifier.size(22.dp)) }) {
+ showSupportSheet = true
+ }
+
+ // Copy Text
+ BottomBarButton("Copy Text", { Icon(Icons.Default.TextFields, null) }) {
+ isCopyMode = true
+ isCopyTextTriggered = true
+ }
+
+ // QR Scan
+ BottomBarButton("Scan QR", { Icon(Icons.Default.QrCode, null) }) {
+ qrScanBitmap = selectedBitmap ?: screenshot
+ showQrSheet = true
+ }
+
+ // Fullscreen
+ BottomBarButton("Fullscreen", { Icon(Icons.Default.Fullscreen, null) }) {
+ if (screenshot != null) {
+ selectionRect = Rect(0, 0, screenshot.width, screenshot.height)
+ currentPathPoints.clear()
+ scope.launch { selectionAnim.snapTo(0f); selectionAnim.animateTo(1f, tween(600)); selectedBitmap = screenshot; isSearching = true }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Copy Text overlay integration (Activity-based)
+ if (isCopyMode && copyTextManager != null) {
+ AndroidView(
+ factory = { ctx ->
+ copyTextManager.getOverlayView(onDismiss = {
+ isCopyMode = false
+ onExitCopyMode()
+ })
+ },
+ modifier = Modifier
+ .fillMaxSize()
+ .zIndex(150f)
+ )
+ }
+
+ // 4. Selection Actions (Share) ΓÇö Positioned at the very end for absolute top-layer rendering
+ if (selectionRect != null && selectionAnim.value == 1f && !isCopyMode) {
+ val rect = selectionRect!!
+ val density = androidx.compose.ui.platform.LocalDensity.current
+ val leftPx = rect.left.toFloat()
+ val topPx = rect.top.toFloat()
+ val rightPx = rect.right.toFloat()
+ val bottomPx = rect.bottom.toFloat()
+
+ val leftDp = with(density) { leftPx.toDp() }
+ val topDp = with(density) { topPx.toDp() }
+ val rightDp = with(density) { rightPx.toDp() }
+ val bottomDp = with(density) { bottomPx.toDp() }
+ val widthDp = rightDp - leftDp
+
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .zIndex(2000f) // Highest Z-index
+ ) {
+ val screenWidth = androidx.compose.ui.platform.LocalConfiguration.current.screenWidthDp.dp
+ val screenHeight = androidx.compose.ui.platform.LocalConfiguration.current.screenHeightDp.dp
+ Box(
+ modifier = Modifier
+ .offset(
+ x = ((leftDp + rightDp) / 2 - 90.dp).coerceIn(16.dp, screenWidth - 196.dp),
+ y = if (topPx > 200f) (topDp - 72.dp).coerceAtLeast(16.dp) else (bottomDp + 16.dp).coerceAtMost(screenHeight - 80.dp)
+ )
+ .wrapContentSize(),
+ contentAlignment = Alignment.Center
+ ) {
+ // Wrapped in Surface to match Bottom Bar tonal environment
+ androidx.compose.material3.Surface(
+ color = MaterialTheme.colorScheme.surfaceContainerHigh,
+ shape = CircleShape,
+ tonalElevation = 4.dp,
+ shadowElevation = 8.dp
+ ) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ // 1. SHARE BUTTON
+ androidx.compose.material3.FilledTonalButton(
+ onClick = {
+ if (selectedBitmap != null) {
+ scope.launch {
+ try {
+ val fileName = "selection_${java.util.UUID.randomUUID()}.png"
+ val path = ImageUtils.saveBitmap(context, selectedBitmap!!, fileName)
+ val file = java.io.File(path)
+ val uri = androidx.core.content.FileProvider.getUriForFile(context, "com.akslabs.circletosearch.fileprovider", file)
+ val shareIntent = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
+ type = "image/png"
+ putExtra(android.content.Intent.EXTRA_STREAM, uri)
+ clipData = android.content.ClipData.newRawUri("Selection", uri)
+ addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
+ }
+ context.startActivity(android.content.Intent.createChooser(shareIntent, "Share Selection").apply {
+ addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
+ })
+ } catch (e: Exception) {
+ android.util.Log.e("CircleToSearch", "Failed to share selection", e)
+ }
+ }
+ }
+ },
+ modifier = Modifier.height(48.dp),
+ shape = CircleShape,
+ colors = androidx.compose.material3.ButtonDefaults.filledTonalButtonColors(
+ containerColor = Color.Transparent, // Parent surface handles color
+ contentColor = MaterialTheme.colorScheme.onSurface
+ ),
+ elevation = null,
+ contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 20.dp)
+ ) {
+ Text(
+ "Share",
+ style = MaterialTheme.typography.labelLarge.copy(
+ fontWeight = androidx.compose.ui.text.font.FontWeight.Normal
+ )
+ )
+ }
+
+ // Separator
+ androidx.compose.material3.VerticalDivider(
+ modifier = Modifier.height(24.dp).padding(horizontal = 2.dp),
+ color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
+ )
+
+ // 2. SAVE BUTTON
+ androidx.compose.material3.FilledTonalButton(
+ onClick = {
+ if (selectedBitmap != null) {
+ val success = ImageUtils.saveToGallery(context, selectedBitmap!!)
+ if (success) {
+ haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
+ android.widget.Toast.makeText(context, "Saved to Gallery", android.widget.Toast.LENGTH_SHORT).show()
+ } else {
+ android.widget.Toast.makeText(context, "Failed to save", android.widget.Toast.LENGTH_SHORT).show()
+ }
+ }
+ },
+ modifier = Modifier.height(48.dp),
+ shape = CircleShape,
+ colors = androidx.compose.material3.ButtonDefaults.filledTonalButtonColors(
+ containerColor = Color.Transparent,
+ contentColor = MaterialTheme.colorScheme.onSurface
+ ),
+ elevation = null,
+ contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 20.dp)
+ ) {
+ Text(
+ "Save",
+ style = MaterialTheme.typography.labelLarge.copy(
+ fontWeight = androidx.compose.ui.text.font.FontWeight.Normal
+ )
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // --- NEW: QR Overlay Chips (High Layer) ---
+ if (screenshot != null && !isCopyMode) {
+ BoxWithConstraints(modifier = Modifier.fillMaxSize().zIndex(2000f)) {
+ val screenWidth = maxWidth
+ val screenHeight = maxHeight
+ val bitmapWidth = screenshot.width.toFloat()
+ val bitmapHeight = screenshot.height.toFloat()
+
+ detectedQrCodes.forEach { qr ->
+ qr.bounds?.let { bounds ->
+ val chipX = (bounds.centerX() / bitmapWidth) * screenWidth.value
+ val chipY = (bounds.centerY() / bitmapHeight) * screenHeight.value
+ val isUrl = qr.result is QrResult.Url
+
+ // Using a Box with pointerInput to consume taps and prevent circling
+ Box(
+ modifier = Modifier
+ .offset(x = chipX.dp - 24.dp, y = chipY.dp - 24.dp)
+ .size(48.dp)
+ .shadow(6.dp, CircleShape)
+ .background(Color.White, CircleShape)
+ .border(1.5.dp, if(isUrl) Color(0xFF1A73E8) else MaterialTheme.colorScheme.primary.copy(alpha = 0.5f), CircleShape)
+ .pointerInput(qr) {
+ detectTapGestures {
+ selectedQrResult = qr
+ qrScanBitmap = null
+ showQrSheet = true
+ }
+ },
+ contentAlignment = Alignment.Center
+ ) {
+ Icon(
+ Icons.Default.QrCode,
+ null,
+ tint = if(isUrl) Color(0xFF1A73E8) else MaterialTheme.colorScheme.primary,
+ modifier = Modifier.size(24.dp)
+ )
+ }
+
+ val label = qrResultShortLabel(qr.result)
+ if (label.isNotEmpty()) {
+ Surface(
+ modifier = Modifier
+ .offset(x = chipX.dp + 28.dp, y = chipY.dp - 12.dp)
+ .pointerInput(qr) {
+ detectTapGestures {
+ selectedQrResult = qr
+ qrScanBitmap = null
+ showQrSheet = true
+ }
+ },
+ shape = RoundedCornerShape(12.dp),
+ color = Color.White.copy(alpha = 0.95f),
+ tonalElevation = 4.dp,
+ shadowElevation = 4.dp,
+ border = if(isUrl) androidx.compose.foundation.BorderStroke(1.dp, Color(0xFF1A73E8).copy(alpha = 0.3f)) else null
+ ) {
+ Text(
+ text = label,
+ style = MaterialTheme.typography.labelSmall.copy(
+ color = if(isUrl) Color(0xFF1A73E8) else MaterialTheme.colorScheme.onSurface,
+ fontWeight = if(isUrl) FontWeight.Bold else FontWeight.Medium
+ ),
+ modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // QR Code Result Sheet
+ if (showQrSheet) {
+ // Full-screen invisible overlay to catch "click outside"
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .zIndex(2500f)
+ .background(Color.Black.copy(alpha = 0.01f)) // Almost invisible but catches taps
+ .clickable(
+ interactionSource = remember { MutableInteractionSource() },
+ indication = null
+ ) {
+ showQrSheet = false
+ selectedQrResult = null
+ }
+ )
+
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .align(Alignment.BottomCenter)
+ .navigationBarsPadding()
+ .padding(bottom = 16.dp)
+ .zIndex(3000f),
+ contentAlignment = Alignment.BottomCenter
+ ) {
+ // Ensure BackHandler is active when sheet is shown
+ androidx.activity.compose.BackHandler {
+ showQrSheet = false
+ selectedQrResult = null
+ }
+
+ QrCodeResultSheet(
+ context = context,
+ bitmap = qrScanBitmap,
+ onDismiss = {
+ showQrSheet = false
+ selectedQrResult = null
+ },
+ initialResults = detectedQrCodes,
+ initialPage = if (selectedQrResult != null) detectedQrCodes.indexOf(selectedQrResult!!) else 0
+ )
+ }
+ }
+
+ if (showSupportSheet) {
+ com.akslabs.circletosearch.SupportSheet(
+ sheetState = supportSheetState,
+ onDismissRequest = {
+ scope.launch {
+ supportSheetState.hide()
+ }.invokeOnCompletion {
+ if (!supportSheetState.isVisible) {
+ showSupportSheet = false
+ }
+ }
+ }
+ )
+ }
+
+ if (showSettingsScreen) {
+ SettingsScreen(
+ uiPreferences = uiPreferences,
+ onDismissRequest = { showSettingsScreen = false }
+ )
+ }
+ }
+}
+}
+}
+
+@OptIn(ExperimentalMaterial3ExpressiveApi::class)
+fun ContainedLoadingIndicatorSample() {
+ Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ androidx.compose.material3.ContainedLoadingIndicator()
+ }
+}
diff --git a/QrScanner_good.kt b/QrScanner_good.kt
new file mode 100644
index 0000000..b5d1f87
Binary files /dev/null and b/QrScanner_good.kt differ
diff --git a/QrScanner_good_utf8.txt b/QrScanner_good_utf8.txt
new file mode 100644
index 0000000..a54ff80
--- /dev/null
+++ b/QrScanner_good_utf8.txt
@@ -0,0 +1,130 @@
+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 {
+ data class Url(val url: String, val displayUrl: String) : QrResult()
+ data class WiFi(val ssid: String, val password: String?, val security: String) : QrResult()
+ data class Phone(val number: String) : QrResult()
+ data class Product(val barcode: String) : QrResult()
+ data class VCard(val name: String?, val phone: String?, val email: String?, val raw: String) : QrResult()
+ data class GeoPoint(val lat: Double, val lng: Double) : 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 {
+
+ 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
+ val pixels = IntArray(width * height)
+ bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
+
+ val source = RGBLuminanceSource(width, height, pixels)
+ val binaryBitmap = BinaryBitmap(HybridBinarizer(source))
+
+ val multiReader = GenericMultipleBarcodeReader(MultiFormatReader())
+ val rawResults: Array<Result> = try {
+ multiReader.decodeMultiple(binaryBitmap, HINTS)
+ } catch (e: NotFoundException) {
+ emptyArray()
+ }
+
+ rawResults.mapNotNull { raw ->
+ try {
+ val bounds = computeBounds(raw.resultPoints)
+ QrResultWithBounds(parseResult(raw.text), raw.text, bounds)
+ } catch (e: Exception) { null }
+ }
+ } catch (e: Exception) {
+ emptyList()
+ }
+ }
+
+ /** 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 {
+ text.startsWith("http://", ignoreCase = true) || text.startsWith("https://", ignoreCase = true) -> {
+ val display = text.removePrefix("http://").removePrefix("https://").trimEnd('/')
+ QrResult.Url(text, display)
+ }
+ text.startsWith("WIFI:", ignoreCase = true) -> parseWifi(text)
+ text.startsWith("tel:", ignoreCase = true) -> QrResult.Phone(text.removePrefix("tel:").trim())
+ text.startsWith("BEGIN:VCARD", ignoreCase = true) -> parseVCard(text)
+ text.startsWith("geo:", ignoreCase = true) -> parseGeo(text)
+ text.matches(Regex("\\d{8,14}")) -> QrResult.Product(text)
+ else -> QrResult.PlainText(text)
+ }
+ }
+
+ private fun parseWifi(text: String): QrResult {
+ val ssid = Regex("S:([^;]*)").find(text)?.groupValues?.get(1) ?: ""
+ val pass = Regex("P:([^;]*)").find(text)?.groupValues?.get(1)
+ val sec = Regex("T:([^;]*)").find(text)?.groupValues?.get(1) ?: "WPA"
+ return QrResult.WiFi(ssid, pass, sec)
+ }
+
+ private fun parseVCard(text: String): QrResult {
+ val name = Regex("FN:([^\r\n]+)").find(text)?.groupValues?.get(1)
+ val phone = Regex("TEL[^:]*:([^\r\n]+)").find(text)?.groupValues?.get(1)
+ val email = Regex("EMAIL[^:]*:([^\r\n]+)").find(text)?.groupValues?.get(1)
+ return QrResult.VCard(name, phone, email, text)
+ }
+
+ private fun parseGeo(text: String): QrResult {
+ return try {
+ val coords = text.removePrefix("geo:").split(",")
+ QrResult.GeoPoint(coords[0].toDouble(), coords[1].split("?")[0].toDouble())
+ } catch (e: Exception) { QrResult.PlainText(text) }
+ }
+}
diff --git a/app/src/main/java/com/akslabs/circletosearch/ui/CircleToSearchScreen.kt b/app/src/main/java/com/akslabs/circletosearch/ui/CircleToSearchScreen.kt
index 5b0c665..3488c5b 100644
--- a/app/src/main/java/com/akslabs/circletosearch/ui/CircleToSearchScreen.kt
+++ b/app/src/main/java/com/akslabs/circletosearch/ui/CircleToSearchScreen.kt
@@ -263,15 +263,6 @@ fun CircleToSearchScreen(
var hostedImageUrl by remember { mutableStateOf<String?>(null) }
var isLoading by remember { mutableStateOf(false) }
- // Auto-scan entire screenshot for QR codes when it arrives
- LaunchedEffect(screenshot) {
- if (screenshot != null) {
- val found = withContext(Dispatchers.Default) {
- QrScanner.scanBitmapAll(screenshot!!)
- }
- detectedQrCodes = found
- }
- }
// Desktop Mode - Per Tab
// We use a set to track which engines are in desktop mode
val initialDesktopMode = uiPreferences.isDesktopMode() // Global default
@@ -397,6 +388,7 @@ fun CircleToSearchScreen(
}
}
+
// searchEngines moved to top
// val searchEngines = SearchEngine.values()
@@ -406,6 +398,22 @@ fun CircleToSearchScreen(
animationSpec = tween(1000), label = "alpha"
)
+ // Auto-scan entire screenshot for QR codes when it arrives
+ LaunchedEffect(screenshot) {
+ android.util.Log.d("CircleToSearch", "Auto-scan Effect: screenshot=${screenshot != null}")
+ if (screenshot != null) {
+ val found = withContext(Dispatchers.Default) {
+ android.util.Log.d("CircleToSearch", "Auto-scan starting...")
+ val res = QrScanner.scanBitmapAll(screenshot!!)
+ android.util.Log.d("CircleToSearch", "Auto-scan finished: found ${res.size} codes")
+ res
+ }
+ detectedQrCodes = found
+ } else {
+ detectedQrCodes = emptyList()
+ }
+ }
+
// Helper to create and configure WebView
fun createWebView(ctx: android.content.Context, engine: SearchEngine): WebView {
return WebView(ctx).apply {
@@ -1553,13 +1561,14 @@ fun CircleToSearchScreen(
) {
val screenWidth = androidx.compose.ui.platform.LocalConfiguration.current.screenWidthDp.dp
val screenHeight = androidx.compose.ui.platform.LocalConfiguration.current.screenHeightDp.dp
+ val centerX = (leftDp + rightDp) / 2
Box(
modifier = Modifier
.offset(
- x = ((leftDp + rightDp) / 2 - 90.dp).coerceIn(16.dp, screenWidth - 196.dp),
+ x = (centerX - 125.dp).coerceIn(0.dp, screenWidth - 250.dp),
y = if (topPx > 200f) (topDp - 72.dp).coerceAtLeast(16.dp) else (bottomDp + 16.dp).coerceAtMost(screenHeight - 80.dp)
)
- .wrapContentSize(),
+ .width(250.dp),
contentAlignment = Alignment.Center
) {
// Wrapped in Surface to match Bottom Bar tonal environment
@@ -1656,12 +1665,13 @@ fun CircleToSearchScreen(
// --- NEW: QR Overlay Chips (High Layer) ---
if (screenshot != null && !isCopyMode) {
- BoxWithConstraints(modifier = Modifier.fillMaxSize().zIndex(2000f)) {
+ BoxWithConstraints(modifier = Modifier.fillMaxSize().zIndex(2500f)) {
val screenWidth = maxWidth
val screenHeight = maxHeight
val bitmapWidth = screenshot.width.toFloat()
val bitmapHeight = screenshot.height.toFloat()
+ android.util.Log.d("CircleToSearch", "Rendering QR Chips: count=${detectedQrCodes.size}")
detectedQrCodes.forEach { qr ->
qr.bounds?.let { bounds ->
val chipX = (bounds.centerX() / bitmapWidth) * screenWidth.value
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 514d36a..e5b29fe 100644
--- a/app/src/main/java/com/akslabs/circletosearch/ui/QrCodeResultSheet.kt
+++ b/app/src/main/java/com/akslabs/circletosearch/ui/QrCodeResultSheet.kt
@@ -159,7 +159,7 @@ fun QrCodeResultSheet(
color = MaterialTheme.colorScheme.surfaceContainerHigh,
tonalElevation = 6.dp, shadowElevation = 12.dp
) {
- Column(modifier = Modifier.padding(20.dp), horizontalAlignment = Alignment.CenterHorizontally) {
+ Column(modifier = Modifier.padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally) {
// Header Row
Row(modifier = Modifier.padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
Icon(Icons.Default.QrCode, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp))
@@ -182,7 +182,7 @@ fun QrCodeResultSheet(
}
}
- Spacer(Modifier.height(16.dp))
+ Spacer(Modifier.height(20.dp))
if (isScanning) {
ScanningIndicator(scanlineY)
@@ -200,7 +200,7 @@ fun QrCodeResultSheet(
}
if (results.size > 1) {
- Spacer(Modifier.height(16.dp))
+ Spacer(Modifier.height(20.dp))
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
@@ -253,7 +253,7 @@ fun NotFoundContent() {
@Composable
fun QrResultContent(context: Context, result: QrResult) {
- Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
+ Box(modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) {
when (result) {
is QrResult.Url -> UrlResult(context, result)
is QrResult.WiFi -> WifiResult(context, result)
@@ -282,7 +282,7 @@ private fun UrlResult(context: Context, result: QrResult.Url) {
overflow = TextOverflow.Ellipsis,
modifier = Modifier.clickable { openUrl(context, result.url) }.padding(2.dp)
)
- Spacer(Modifier.height(16.dp))
+ Spacer(Modifier.height(20.dp))
ActionRow { PrimaryAction("Open Link") { openUrl(context, result.url) }; SecondaryAction("Copy") { copyToClipboard(context, "URL", result.url) } }
}
}
@@ -294,7 +294,7 @@ private fun WifiResult(context: Context, result: QrResult.WiFi) {
Spacer(Modifier.height(6.dp))
Text(result.ssid, style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold))
Text("${result.security}${if (result.password != null) " · ${result.password}" else ""}", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
- Spacer(Modifier.height(16.dp))
+ Spacer(Modifier.height(20.dp))
ActionRow { if (result.password != null) PrimaryAction("Copy Pass") { copyToClipboard(context, "WiFi Password", result.password) } }
}
}
@@ -305,7 +305,7 @@ private fun PhoneResult(context: Context, result: QrResult.Phone) {
Icon(Icons.Default.Phone, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(40.dp))
Spacer(Modifier.height(6.dp))
Text(result.number, style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold))
- Spacer(Modifier.height(16.dp))
+ Spacer(Modifier.height(20.dp))
ActionRow {
PrimaryAction("Call") { openUrl(context, "tel:${result.number}") }
SecondaryAction("SMS") { openUrl(context, "sms:${result.number}") }
@@ -320,7 +320,7 @@ private fun ProductResult(context: Context, result: QrResult.Product) {
Icon(Icons.Default.ShoppingBag, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(40.dp))
Spacer(Modifier.height(6.dp))
Text(result.barcode, style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold))
- Spacer(Modifier.height(16.dp))
+ Spacer(Modifier.height(20.dp))
ActionRow {
PrimaryAction("Amazon") { openUrl(context, "https://www.amazon.com/s?k=${result.barcode}") }
SecondaryAction("Google") { openUrl(context, "https://www.google.com/search?q=${result.barcode}") }
@@ -336,7 +336,7 @@ private fun VCardResult(context: Context, result: QrResult.VCard) {
if (result.name != null) Text(result.name, style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold))
val sub = listOfNotNull(result.phone, result.email).joinToString(" · ")
if (sub.isNotEmpty()) Text(sub, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
- Spacer(Modifier.height(16.dp))
+ Spacer(Modifier.height(20.dp))
ActionRow {
PrimaryAction("Save") {
context.startActivity(Intent(Intent.ACTION_INSERT).apply {
@@ -359,7 +359,7 @@ private fun GeoResult(context: Context, result: QrResult.GeoPoint) {
Icon(Icons.Default.LocationOn, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(40.dp))
Spacer(Modifier.height(6.dp))
Text(coord, style = MaterialTheme.typography.labelMedium.copy(fontWeight = FontWeight.Bold))
- Spacer(Modifier.height(16.dp))
+ Spacer(Modifier.height(20.dp))
ActionRow {
PrimaryAction("Maps") { openUrl(context, "geo:${result.lat},${result.lng}?q=${result.lat},${result.lng}") }
SecondaryAction("Copy") { copyToClipboard(context, "Coordinates", coord) }
@@ -379,7 +379,7 @@ private fun PlainTextResult(context: Context, result: QrResult.PlainText) {
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(horizontal = 8.dp)
)
- Spacer(Modifier.height(16.dp))
+ Spacer(Modifier.height(20.dp))
ActionRow {
PrimaryAction("Search") { openUrl(context, "https://www.google.com/search?q=${Uri.encode(result.text)}") }
SecondaryAction("Copy") { copyToClipboard(context, "Text", result.text) }
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 2d7c7cd..32fa4a8 100644
--- a/app/src/main/java/com/akslabs/circletosearch/utils/QrScanner.kt
+++ b/app/src/main/java/com/akslabs/circletosearch/utils/QrScanner.kt
@@ -60,11 +60,23 @@ object QrScanner {
val binaryBitmap = BinaryBitmap(HybridBinarizer(source))
val multiReader = GenericMultipleBarcodeReader(MultiFormatReader())
- val rawResults: Array<Result> = try {
+ android.util.Log.d("CircleToSearch", "QrScanner: Starting decodeMultiple (HybridBinarizer)...")
+ var rawResults: Array<Result> = try {
multiReader.decodeMultiple(binaryBitmap, HINTS)
} catch (e: NotFoundException) {
+ android.util.Log.d("CircleToSearch", "QrScanner: HybridBinarizer found nothing, trying GlobalHistogramBinarizer...")
+ try {
+ val globalBitmap = BinaryBitmap(com.google.zxing.common.GlobalHistogramBinarizer(source))
+ multiReader.decodeMultiple(globalBitmap, HINTS)
+ } catch (e2: NotFoundException) {
+ android.util.Log.d("CircleToSearch", "QrScanner: GlobalHistogramBinarizer also found nothing")
+ emptyArray()
+ }
+ } catch (e: Exception) {
+ android.util.Log.e("CircleToSearch", "QrScanner: Error during decode", e)
emptyArray()
}
+ android.util.Log.d("CircleToSearch", "QrScanner: Processed ${rawResults.size} raw results")
rawResults.mapNotNull { raw ->
try {
diff --git a/build_errors_52.txt b/build_errors_52.txt
new file mode 100644
index 0000000..b3649fe
Binary files /dev/null and b/build_errors_52.txt differ
diff --git a/build_errors_53.txt b/build_errors_53.txt
new file mode 100644
index 0000000..a704bc2
Binary files /dev/null and b/build_errors_53.txt differ
diff --git a/build_errors_54.txt b/build_errors_54.txt
new file mode 100644
index 0000000..e4e6935
Binary files /dev/null and b/build_errors_54.txt differ
diff --git a/build_errors_54_utf8.txt b/build_errors_54_utf8.txt
new file mode 100644
index 0000000..c959de9
--- /dev/null
+++ b/build_errors_54_utf8.txt
@@ -0,0 +1,84 @@
+
+> Configure project :app
+WARNING: BuildType 'debug' is both debuggable and has 'isMinifyEnabled' set to true.
+All code optimizations and obfuscation are disabled for debuggable builds.
+
+> Task :app:checkKotlinGradlePluginConfigurationErrors SKIPPED
+> Task :app:preBuild UP-TO-DATE
+> Task :app:preDebugBuild UP-TO-DATE
+> Task :app:checkDebugAarMetadata UP-TO-DATE
+> Task :app:processDebugNavigationResources UP-TO-DATE
+> Task :app:compileDebugNavigationResources UP-TO-DATE
+> Task :app:generateDebugResValues UP-TO-DATE
+> Task :app:mapDebugSourceSetPaths UP-TO-DATE
+> Task :app:generateDebugResources UP-TO-DATE
+> Task :app:mergeDebugResources UP-TO-DATE
+> Task :app:packageDebugResources UP-TO-DATE
+> Task :app:parseDebugLocalResources UP-TO-DATE
+> Task :app:createDebugCompatibleScreenManifests
+> Task :app:extractDeepLinksDebug UP-TO-DATE
+
+> Task :app:processDebugMainManifest
+C:\Users\ashin\AndroidStudioProjects\CircleToSearch\app\src\main\AndroidManifest.xml:43:9-41 Warning:
+ android:extractNativeLibs should not be specified in this source AndroidManifest.xml file. See https://d.android.com/guide/topics/manifest/application-element#extractNativeLibs for more information.
+The AGP Upgrade Assistant can remove the attribute from the AndroidManifest.xml file and update the build file accordingly. See https://d.android.com/studio/build/agp-upgrade-assistant for more information.
+
+> Task :app:processDebugManifest
+> Task :app:processDebugManifestForPackage
+> Task :app:processDebugResources
+> Task :app:compileDebugKotlin
+.\gradlew.bat : e: file:///C:/Users/ashin/Androi
+dStudioProjects/CircleToSearch/app/src/main/java
+/com/akslabs/circletosearch/ui/CircleToSearchScr
+een.kt:273:13 Unresolved reference
+'selectionRect'.
+At line:1 char:1
++ .\gradlew.bat :app:compileDebugKotlin
+--console=plain > build_errors_ ...
++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~~~~~~~
+ + CategoryInfo : NotSpecified: (e:
+ file:///C:/U...selectionRect'.:String) [],
+ RemoteException
+ + FullyQualifiedErrorId : NativeCommandErro
+ r
+
+e: file:///C:/Users/ashin/AndroidStudioProjects/
+CircleToSearch/app/src/main/java/com/akslabs/cir
+cletosearch/ui/CircleToSearchScreen.kt:274:13
+Unresolved reference 'selectedBitmap'.
+e: file:///C:/Users/ashin/AndroidStudioProjects/
+CircleToSearch/app/src/main/java/com/akslabs/cir
+cletosearch/ui/CircleToSearchScreen.kt:275:13
+Unresolved reference 'isSearching'.
+e: file:///C:/Users/ashin/AndroidStudioProjects/
+CircleToSearch/app/src/main/java/com/akslabs/cir
+cletosearch/ui/CircleToSearchScreen.kt:276:13
+Unresolved reference 'currentPathPoints'.
+e: file:///C:/Users/ashin/AndroidStudioProjects/
+CircleToSearch/app/src/main/java/com/akslabs/cir
+cletosearch/ui/CircleToSearchScreen.kt:277:13
+Unresolved reference 'selectionAnim'.
+
+> Task :app:compileDebugKotlin FAILED
+
+FAILURE: Build failed with an exception.
+
+* What went wrong:
+Execution failed for task
+':app:compileDebugKotlin'.
+> A failure occurred while executing org.jetbrai
+ns.kotlin.compilerRunner.GradleCompilerRunnerWit
+hWorkers$GradleKotlinCompilerWorkAction
+ > Compilation error. See log for more details
+
+* Try:
+> Run with --stacktrace option to get the stack
+trace.
+> Run with --info or --debug option to get more
+log output.
+> Run with --scan to get full insights.
+> Get more help at https://help.gradle.org.
+
+BUILD FAILED in 1m 4s
+16 actionable tasks: 6 executed, 10 up-to-date
diff --git a/build_errors_55.txt b/build_errors_55.txt
new file mode 100644
index 0000000..6f494f7
Binary files /dev/null and b/build_errors_55.txt differ
diff --git a/builderors.md b/builderors.md
index 8b13789..344cc30 100644
--- a/builderors.md
+++ b/builderors.md
@@ -1 +1,120 @@
+--------- beginning of main
+03-23 01:08:50.094 1450 1450 W main : type=1400 audit(0.0:316629): avc: denied { search } for name="app" dev="mmcblk0p61" ino=1343489 scontext=u:r:zygote:s0 tcontext=u:object_r:apk_data_file:s0 tclass=dir permissive=0 app=com.akslabs.circletosearch
+03-23 01:08:50.094 1450 1450 W main : type=1400 audit(0.0:316630): avc: denied { search } for name="app" dev="mmcblk0p61" ino=1343489 scontext=u:r:zygote:s0 tcontext=u:object_r:apk_data_file:s0 tclass=dir permissive=0 app=com.akslabs.circletosearch
+03-23 01:08:50.094 1450 1450 W main : type=1400 audit(0.0:316631): avc: denied { search } for name="app" dev="mmcblk0p61" ino=1343489 scontext=u:r:zygote:s0 tcontext=u:object_r:apk_data_file:s0 tclass=dir permissive=0 app=com.akslabs.circletosearch
+03-23 01:08:50.094 1450 1450 W main : type=1400 audit(0.0:316632): avc: denied { search } for name="app" dev="mmcblk0p61" ino=1343489 scontext=u:r:zygote:s0 tcontext=u:object_r:apk_data_file:s0 tclass=dir permissive=0 app=com.akslabs.circletosearch
+03-23 01:08:50.114 1450 1450 I .circletosearch: Late-enabling -Xcheck:jni
+03-23 01:08:50.211 1450 1450 I .circletosearch: Using CollectorTypeCC GC.
+03-23 01:08:50.305 1450 1450 D nativeloader: Load libframework-connectivity-tiramisu-jni.so using APEX ns com_android_tethering for caller /apex/com.android.tethering/javalib/framework-connectivity-t.jar: ok
+03-23 01:08:50.394 1450 1450 W re-initialized>: type=1400 audit(0.0:316633): avc: granted { execute } for path="/data/data/com.akslabs.circletosearch/code_cache/startup_agents/6097f3dc-agent.so" dev="mmcblk0p61" ino=417800 scontext=u:r:untrusted_app:s0:c167,c259,c512,c768 tcontext=u:object_r:app_data_file:s0:c167,c259,c512,c768 tclass=file app=com.akslabs.circletosearch
+03-23 01:08:50.429 1450 1450 D nativeloader: Load /data/user/0/com.akslabs.circletosearch/code_cache/startup_agents/6097f3dc-agent.so using system ns (caller=<unknown>): ok
+03-23 01:08:50.429 1450 1450 V studio.deploy: Startup agent attached to VM
+03-23 01:08:50.435 1450 1450 V studio.deploy: No existing instrumentation found. Loading instrumentation from instruments-6a1a1143.jar
+03-23 01:08:50.491 1450 1450 W .circletosearch: DexFile /data/data/com.akslabs.circletosearch/code_cache/.studio/instruments-6a1a1143.jar is in boot class path but is not in a known location
+03-23 01:08:50.689 1450 1450 V studio.deploy: Applying transforms with cached classes
+03-23 01:08:50.865 1450 1450 W .circletosearch: Redefining intrinsic method java.lang.Thread java.lang.Thread.currentThread(). This may cause the unexpected use of the original definition of java.lang.Thread java.lang.Thread.currentThread()in methods that have already been compiled.
+03-23 01:08:50.865 1450 1450 W .circletosearch: Redefining intrinsic method boolean java.lang.Thread.interrupted(). This may cause the unexpected use of the original definition of boolean java.lang.Thread.interrupted()in methods that have already been compiled.
+03-23 01:08:50.868 1450 1450 I studio.deploy: Registering DispatchJNI
+03-23 01:08:50.868 1450 1450 I studio.deploy: Found com/android/tools/deploy/interpreter/JNI
+03-23 01:08:51.025 1450 1450 W ziparchive: Unable to open '/data/data/com.akslabs.circletosearch/code_cache/.overlay/base.apk/classes.dm': No such file or directory
+03-23 01:08:51.192 1450 1450 W .circletosearch: ClassLoaderContext classpath size mismatch. expected=0, found=1 (PCL[] | PCL[/data/data/com.akslabs.circletosearch/code_cache/.overlay/base.apk/classes.dex*4268598632])
+03-23 01:08:51.198 1450 1450 D nativeloader: Configuring clns-7 for other apk /data/app/~~UXQwZLMrccRuoxuIEEn2ZA==/com.akslabs.circletosearch-yRdMISAYBcNVWRam0Tii2Q==/base.apk. target_sdk_version=36, uses_libraries=, library_path=/data/app/~~UXQwZLMrccRuoxuIEEn2ZA==/com.akslabs.circletosearch-yRdMISAYBcNVWRam0Tii2Q==/lib/arm64:/data/app/~~UXQwZLMrccRuoxuIEEn2ZA==/com.akslabs.circletosearch-yRdMISAYBcNVWRam0Tii2Q==/base.apk!/lib/arm64-v8a, permitted_path=/data:/mnt/expand:/data/user/0/com.akslabs.circletosearch
+03-23 01:08:51.206 1450 1450 I .circletosearch: AssetManager2(0x7318c278f8) locale list changing from [] to [en-IN]
+03-23 01:08:51.212 1450 1450 I .circletosearch: AssetManager2(0x7318c21818) locale list changing from [] to [en-IN]
+03-23 01:08:51.228 1450 1450 V GraphicsEnvironment: Currently set values for:
+03-23 01:08:51.228 1450 1450 V GraphicsEnvironment: angle_gl_driver_selection_pkgs=[com.android.angle, com.linecorp.b612.android, com.campmobile.snow, com.google.android.apps.tachyon]
+03-23 01:08:51.228 1450 1450 V GraphicsEnvironment: angle_gl_driver_selection_values=[angle, native, native, native]
+03-23 01:08:51.228 1450 1450 V GraphicsEnvironment: com.akslabs.circletosearch is not listed in per-application setting
+03-23 01:08:51.228 1450 1450 V GraphicsEnvironment: Neither updatable production driver nor prerelease driver is supported.
+03-23 01:08:51.343 1450 1450 I .circletosearch: AssetManager2(0x7318c1d358) locale list changing from [] to [en-IN]
+03-23 01:08:51.450 1450 1450 D DesktopModeFlagsUtil: Toggle override initialized to: OVERRIDE_UNSET
+03-23 01:08:51.975 1450 1450 W .circletosearch: Accessing hidden method Landroid/os/SystemProperties;->addChangeCallback(Ljava/lang/Runnable;)V (unsupported, reflection, allowed)
+03-23 01:08:52.470 1450 1450 W HWUI : Image decoding logging dropped!
+03-23 01:08:52.804 1450 1536 I AdrenoGLES-0: QUALCOMM build : 95db91f, Ifbc588260a
+03-23 01:08:52.804 1450 1536 I AdrenoGLES-0: Build Date : 09/24/20
+03-23 01:08:52.804 1450 1536 I AdrenoGLES-0: OpenGL ES Shader Compiler Version: EV031.32.02.01
+03-23 01:08:52.804 1450 1536 I AdrenoGLES-0: Local Branch : mybrancheafe5b6d-fb5b-f1b0-b904-5cb90179c3e0
+03-23 01:08:52.804 1450 1536 I AdrenoGLES-0: Remote Branch : quic/gfx-adreno.lnx.1.0.r114-rel
+03-23 01:08:52.804 1450 1536 I AdrenoGLES-0: Remote Branch : NONE
+03-23 01:08:52.804 1450 1536 I AdrenoGLES-0: Reconstruct Branch : NOTHING
+03-23 01:08:52.804 1450 1536 I AdrenoGLES-0: Build Config : S P 10.0.7 AArch64
+03-23 01:08:52.804 1450 1536 I AdrenoGLES-0: Driver Path : /vendor/lib64/egl/libGLESv2_adreno.so
+03-23 01:08:52.821 1450 1536 I AdrenoGLES-0: PFP: 0x016ee190, ME: 0x00000000
+03-23 01:08:52.930 1450 1559 I Gralloc4: mapper 4.x is not supported
+03-23 01:08:52.930 1450 1559 W Gralloc3: mapper 3.x is not supported
+03-23 01:08:52.939 1450 1559 I Gralloc2: Adding additional valid usage bits: 0x8202000
+03-23 01:08:53.026 1450 1469 I HWUI : Davey! duration=1697ms; Flags=1, FrameTimelineVsyncId=96236844, IntendedVsync=122869838241344, Vsync=122870121580361, InputEventId=0, HandleInputStart=122870134057033, AnimationStart=122870134068439, PerformTraversalsStart=122870134269064, DrawStart=122871435255522, FrameDeadline=122869859574676, FrameInterval=122870133683752, FrameStartTime=16667001, SyncQueued=122871489577241, SyncStart=122871489711043, IssueDrawCommandsStart=122871490430783, SwapBuffers=122871532341668, FrameCompleted=122871536251303, DequeueBufferDuration=14687, QueueBufferDuration=654480, GpuCompleted=122871536251303, SwapBuffersCompleted=122871534357866, DisplayPresentTime=0, CommandSubmissionCompleted=122871532341668,
+03-23 01:08:53.114 1450 1450 I Choreographer: Skipped 83 frames! The application may be doing too much work on its main thread.
+03-23 01:08:53.130 1450 1469 I HWUI : Davey! duration=1399ms; Flags=0, FrameTimelineVsyncId=96237256, IntendedVsync=122870257575722, Vsync=122871640984696, InputEventId=0, HandleInputStart=122871649082658, AnimationStart=122871649086147, PerformTraversalsStart=122871649087085, DrawStart=122871650298074, FrameDeadline=122871554942112, FrameInterval=122871648320210, FrameStartTime=16667578, SyncQueued=122871650961147, SyncStart=122871651172814, IssueDrawCommandsStart=122871651266251, SwapBuffers=122871653528960, FrameCompleted=122871657284220, DequeueBufferDuration=15573, QueueBufferDuration=259583, GpuCompleted=122871657284220, SwapBuffersCompleted=122871654519845, DisplayPresentTime=0, CommandSubmissionCompleted=122871653528960,
+03-23 01:08:53.306 1450 1466 I HWUI : Davey! duration=1563ms; Flags=1, FrameTimelineVsyncId=96237256, IntendedVsync=122870257575722, Vsync=122871640984696, InputEventId=0, HandleInputStart=122871649082658, AnimationStart=122871649086147, PerformTraversalsStart=122871649087085, DrawStart=122871801525105, FrameDeadline=122870274242388, FrameInterval=122871648320210, FrameStartTime=16667578, SyncQueued=122871812772553, SyncStart=122871812914949, IssueDrawCommandsStart=122871813002137, SwapBuffers=122871819126043, FrameCompleted=122871821033230, DequeueBufferDuration=12969, QueueBufferDuration=250677, GpuCompleted=122871821033230, SwapBuffersCompleted=122871819915574, DisplayPresentTime=0, CommandSubmissionCompleted=122871819126043,
+03-23 01:08:53.387 1450 1450 D InsetsController: hide(ime(), fromIme=false)
+03-23 01:08:53.387 1450 1450 I ImeTracker: com.akslabs.circletosearch:47e3d2e0: onCancelled at PHASE_CLIENT_ALREADY_HIDDEN
+03-23 01:08:54.659 1450 1450 W WindowOnBackDispatcher: sendCancelIfRunning: isInProgress=false callback=androidx.navigationevent.OnBackInvokedInput$createOnBackAnimationCallback$1@baca4b6
+03-23 01:08:54.683 1450 1536 D HWUI : endAllActiveAnimators on 0x7218c6d7c0 (UnprojectedRipple) with handle 0x72c8cad250
+03-23 01:08:54.733 1450 1450 D InsetsController: hide(ime(), fromIme=false)
+03-23 01:08:54.733 1450 1450 I ImeTracker: com.akslabs.circletosearch:8ea12879: onCancelled at PHASE_CLIENT_ALREADY_HIDDEN
+03-23 01:08:56.873 1450 1802 D ProfileInstaller: Installing profile for com.akslabs.circletosearch
+03-23 01:08:58.751 1450 1450 D VRI[MainActivity]: visibilityChanged oldVisibility=true newVisibility=false
+03-23 01:09:04.409 1450 1461 W .circletosearch: Cleared Reference was only reachable from finalizer (only reported once)
+03-23 01:09:04.429 1450 1461 I .circletosearch: Background concurrent copying GC freed 10056KB AllocSpace bytes, 7(140KB) LOS objects, 49% free, 5103KB/10206KB, paused 65us,22us total 102.452ms
+03-23 01:09:06.498 1450 1450 D CircleToSearch: performCapture called. hasWindowManager=true
+03-23 01:09:06.612 1450 2402 D CircleToSearchAccess: AccessibilityService launching OverlayActivity
+03-23 01:09:06.820 1450 1450 D CircleToSearch: OverlayActivity onCreate
+03-23 01:09:06.820 1450 1450 D CircleToSearch: Bitmap loaded from Repository. Size: 1080x2340
+03-23 01:09:07.889 1450 1571 I HWUI : Davey! duration=1033ms; Flags=1, FrameTimelineVsyncId=96256380, IntendedVsync=122885358073707, Vsync=122885391407653, InputEventId=0, HandleInputStart=122885399394579, AnimationStart=122885399396819, PerformTraversalsStart=122885399397757, DrawStart=122886312984319, FrameDeadline=122885374740373, FrameInterval=122885399385413, FrameStartTime=16666973, SyncQueued=122886331237444, SyncStart=122886331530360, IssueDrawCommandsStart=122886331688017, SwapBuffers=122886381614944, FrameCompleted=122886392183381, DequeueBufferDuration=13333, QueueBufferDuration=701823, GpuCompleted=122886392183381, SwapBuffersCompleted=122886383234944, DisplayPresentTime=122871839892814, CommandSubmissionCompleted=122886381614944,
+03-23 01:09:07.906 1450 1450 D CircleToSearch: QR Scan starting - Bitmap: 1080x2340
+03-23 01:09:07.932 1450 1450 I Choreographer: Skipped 63 frames! The application may be doing too much work on its main thread.
+03-23 01:09:08.012 1450 1450 W HWUI : Image decoding logging dropped!
+03-23 01:09:08.093 1450 1450 W HWUI : Image decoding logging dropped!
+03-23 01:09:08.479 1450 2429 I HWUI : Davey! duration=1596ms; Flags=0, FrameTimelineVsyncId=96256491, IntendedVsync=122885408072041, Vsync=122886458088631, InputEventId=0, HandleInputStart=122886466590152, AnimationStart=122886466593798, PerformTraversalsStart=122886799270204, DrawStart=122886939968121, FrameDeadline=122886424759672, FrameInterval=122886466186871, FrameStartTime=16666930, SyncQueued=122886990125620, SyncStart=122886990507860, IssueDrawCommandsStart=122886990867391, SwapBuffers=122886993833381, FrameCompleted=122887004494110, DequeueBufferDuration=23958, QueueBufferDuration=509531, GpuCompleted=122887004494110, SwapBuffersCompleted=122886995426193, DisplayPresentTime=122871906560626, CommandSubmissionCompleted=122886993833381,
+03-23 01:09:08.647 1450 1450 D InsetsController: hide(ime(), fromIme=false)
+03-23 01:09:08.647 1450 1450 I ImeTracker: com.akslabs.circletosearch:8121a967: onCancelled at PHASE_CLIENT_ALREADY_HIDDEN
+03-23 01:09:10.444 1450 1450 D CircleToSearch: QR Scan finished - Found: 0 codes
+03-23 01:09:19.411 1450 1450 D VRI[OverlayActivity]: visibilityChanged oldVisibility=true newVisibility=false
+03-23 01:09:19.439 1450 1450 W WindowOnBackDispatcher: sendCancelIfRunning: isInProgress=false callback=androidx.navigationevent.OnBackInvokedInput$createOnBackAnimationCallback$1@f22adfc
+03-23 01:09:19.561 1450 1450 W WindowOnBackDispatcher: sendCancelIfRunning: isInProgress=false callback=android.app.Activity$$ExternalSyntheticLambda0@56af219
+03-23 01:09:19.566 1450 1450 D ViewRootImpl: Skipping stats log for color mode
+03-23 01:09:50.001 1450 1450 D CircleToSearch: performCapture called. hasWindowManager=true
+03-23 01:09:50.059 1450 2402 D CircleToSearchAccess: AccessibilityService launching OverlayActivity
+03-23 01:09:50.226 1450 1450 D CircleToSearch: OverlayActivity onCreate
+03-23 01:09:50.226 1450 1450 D CircleToSearch: Bitmap loaded from Repository. Size: 1080x2340
+03-23 01:09:50.852 1450 1450 D CircleToSearch: QR Scan starting - Bitmap: 1080x2340
+03-23 01:09:50.865 1450 1450 I Choreographer: Skipped 35 frames! The application may be doing too much work on its main thread.
+03-23 01:09:50.913 1450 1450 W HWUI : Image decoding logging dropped!
+03-23 01:09:50.941 1450 1450 W HWUI : Image decoding logging dropped!
+03-23 01:09:51.245 1450 1466 I HWUI : Davey! duration=956ms; Flags=0, FrameTimelineVsyncId=96308265, IntendedVsync=122928808061365, Vsync=122929391387325, InputEventId=0, HandleInputStart=122929399749615, AnimationStart=122929399753208, PerformTraversalsStart=122929597769719, DrawStart=122929712644146, FrameDeadline=122929391378856, FrameInterval=122929399224615, FrameStartTime=16666456, SyncQueued=122929752165865, SyncStart=122929752234979, IssueDrawCommandsStart=122929752406125, SwapBuffers=122929753767063, FrameCompleted=122929764206542, DequeueBufferDuration=15730, QueueBufferDuration=532657, GpuCompleted=122929764206542, SwapBuffersCompleted=122929755043156, DisplayPresentTime=-69972189863528145, CommandSubmissionCompleted=122929753767063,
+03-23 01:09:51.266 1450 1450 D InsetsController: hide(ime(), fromIme=false)
+03-23 01:09:51.266 1450 1450 I ImeTracker: com.akslabs.circletosearch:89ad9691: onCancelled at PHASE_CLIENT_ALREADY_HIDDEN
+03-23 01:09:51.705 1450 1450 D CircleToSearch: QR Scan finished - Found: 0 codes
+03-23 01:10:07.779 1450 1450 D VRI[OverlayActivity]: visibilityChanged oldVisibility=true newVisibility=false
+03-23 01:10:07.812 1450 1450 W WindowOnBackDispatcher: sendCancelIfRunning: isInProgress=false callback=androidx.navigationevent.OnBackInvokedInput$createOnBackAnimationCallback$1@2665684
+03-23 01:10:07.945 1450 1450 W WindowOnBackDispatcher: sendCancelIfRunning: isInProgress=false callback=android.app.Activity$$ExternalSyntheticLambda0@78f1e62
+03-23 01:10:07.949 1450 1450 D ViewRootImpl: Skipping stats log for color mode
+03-23 01:10:10.795 1450 1450 D CircleToSearch: performCapture called. hasWindowManager=true
+03-23 01:10:10.864 1450 2402 D CircleToSearchAccess: AccessibilityService launching OverlayActivity
+03-23 01:10:11.105 1450 1450 D CircleToSearch: OverlayActivity onCreate
+03-23 01:10:11.105 1450 1450 D CircleToSearch: Bitmap loaded from Repository. Size: 1080x2340
+03-23 01:10:11.383 1450 1457 I .circletosearch: Compiler allocated 5163KB to compile void com.akslabs.circletosearch.ui.CircleToSearchScreenKt$CircleToSearchScreen$13$2.invoke(androidx.compose.foundation.layout.PaddingValues, androidx.compose.runtime.Composer, int)
+03-23 01:10:11.598 1450 1450 D CircleToSearch: QR Scan starting - Bitmap: 1080x2340
+03-23 01:10:11.688 1450 1450 W HWUI : Image decoding logging dropped!
+03-23 01:10:11.724 1450 1450 W HWUI : Image decoding logging dropped!
+03-23 01:10:11.785 1450 1535 I .circletosearch: Waiting for a blocking GC ProfileSaver
+03-23 01:10:11.803 1450 1461 I .circletosearch: Background concurrent copying GC freed 3776KB AllocSpace bytes, 13(31MB) LOS objects, 50% free, 19MB/39MB, paused 106us,49us total 199.866ms
+03-23 01:10:11.804 1450 1535 I .circletosearch: WaitForGcToComplete blocked ProfileSaver on Background for 18.859ms
+03-23 01:10:12.002 1450 1467 I HWUI : Davey! duration=850ms; Flags=0, FrameTimelineVsyncId=96334223, IntendedVsync=122949674733337, Vsync=122950158067028, InputEventId=0, HandleInputStart=122950172554451, AnimationStart=122950172558096, PerformTraversalsStart=122950375630492, DrawStart=122950469565128, FrameDeadline=122950108060013, FrameInterval=122950172148617, FrameStartTime=16666679, SyncQueued=122950512905648, SyncStart=122950512985596, IssueDrawCommandsStart=122950513161430, SwapBuffers=122950514883669, FrameCompleted=122950525548617, DequeueBufferDuration=15729, QueueBufferDuration=1063177, GpuCompleted=122950525548617, SwapBuffersCompleted=122950516516742, DisplayPresentTime=0, CommandSubmissionCompleted=122950514883669,
+03-23 01:10:12.028 1450 1450 D InsetsController: hide(ime(), fromIme=false)
+03-23 01:10:12.028 1450 1450 I ImeTracker: com.akslabs.circletosearch:b7697256: onCancelled at PHASE_CLIENT_ALREADY_HIDDEN
+03-23 01:10:12.421 1450 1450 D CircleToSearch: QR Scan finished - Found: 0 codes
+03-23 01:10:21.749 1450 2425 D TesseractEngine: Initializing Tesseract with dataPath=/data/user/0/com.akslabs.circletosearch/files
+03-23 01:10:21.764 1450 2425 D nativeloader: Load /data/app/~~UXQwZLMrccRuoxuIEEn2ZA==/com.akslabs.circletosearch-yRdMISAYBcNVWRam0Tii2Q==/lib/arm64/libjpeg.so using class loader ns clns-7 (caller=/data/data/com.akslabs.circletosearch/code_cache/.overlay/base.apk/classes.dex): ok
+03-23 01:10:21.770 1450 2425 D nativeloader: Load /data/app/~~UXQwZLMrccRuoxuIEEn2ZA==/com.akslabs.circletosearch-yRdMISAYBcNVWRam0Tii2Q==/lib/arm64/libpngx.so using class loader ns clns-7 (caller=/data/data/com.akslabs.circletosearch/code_cache/.overlay/base.apk/classes.dex): ok
+03-23 01:10:21.782 1450 2425 D nativeloader: Load /data/app/~~UXQwZLMrccRuoxuIEEn2ZA==/com.akslabs.circletosearch-yRdMISAYBcNVWRam0Tii2Q==/lib/arm64/libleptonica.so using class loader ns clns-7 (caller=/data/data/com.akslabs.circletosearch/code_cache/.overlay/base.apk/classes.dex): ok
+03-23 01:10:21.835 1450 2425 D nativeloader: Load /data/app/~~UXQwZLMrccRuoxuIEEn2ZA==/com.akslabs.circletosearch-yRdMISAYBcNVWRam0Tii2Q==/lib/arm64/libtesseract.so using class loader ns clns-7 (caller=/data/data/com.akslabs.circletosearch/code_cache/.overlay/base.apk/classes.dex): ok
+03-23 01:10:22.254 1450 2425 I Tesseract(native): Initialized Tesseract API with language=eng
+03-23 01:10:22.258 1450 2425 W .circletosearch: Accessing hidden field Landroid/graphics/Bitmap;->mNativePtr:J (unsupported, JNI, allowed)
+03-23 01:10:24.934 1450 2425 D TesseractEngine: Tesseract recognition complete. Full text length: 1070
+03-23 01:10:25.017 1450 2425 D TesseractEngine: Tesseract successfully extracted 59 text nodes.
+03-23 01:10:25.022 1450 1450 D CopyTextOverlay: OCR complete: 59 nodes, 255 words
+03-23 01:10:27.089 1450 1450 W HWUI : Image decoding logging dropped!
+03-23 01:10:27.105 1450 1450 W HWUI : Image decoding logging dropped!
diff --git a/changes_since_last_good.diff b/changes_since_last_good.diff
new file mode 100644
index 0000000..820a891
Binary files /dev/null and b/changes_since_last_good.diff differ
diff --git a/changes_since_last_good_utf8.diff b/changes_since_last_good_utf8.diff
new file mode 100644
index 0000000..9277f0a
--- /dev/null
+++ b/changes_since_last_good_utf8.diff
@@ -0,0 +1,372 @@
+diff --git a/app/src/main/java/com/akslabs/circletosearch/ui/CircleToSearchScreen.kt b/app/src/main/java/com/akslabs/circletosearch/ui/CircleToSearchScreen.kt
+index 5b0c665..689c694 100644
+--- a/app/src/main/java/com/akslabs/circletosearch/ui/CircleToSearchScreen.kt
++++ b/app/src/main/java/com/akslabs/circletosearch/ui/CircleToSearchScreen.kt
+@@ -263,15 +263,6 @@ fun CircleToSearchScreen(
+ var hostedImageUrl by remember { mutableStateOf<String?>(null) }
+ var isLoading by remember { mutableStateOf(false) }
+
+- // Auto-scan entire screenshot for QR codes when it arrives
+- LaunchedEffect(screenshot) {
+- if (screenshot != null) {
+- val found = withContext(Dispatchers.Default) {
+- QrScanner.scanBitmapAll(screenshot!!)
+- }
+- detectedQrCodes = found
+- }
+- }
+ // Desktop Mode - Per Tab
+ // We use a set to track which engines are in desktop mode
+ val initialDesktopMode = uiPreferences.isDesktopMode() // Global default
+@@ -385,26 +376,40 @@ fun CircleToSearchScreen(
+ var selectionRect by remember { mutableStateOf<Rect?>(null) }
+ val selectionAnim = remember { androidx.compose.animation.core.Animatable(0f) }
+
+- // Lifecycle reset: When screenshot changes, reset selection and modes
++
++ // searchEngines moved to top
++ // val searchEngines = SearchEngine.values()
++
++ // Gradient Animation
++ val alphaAnim by animateFloatAsState(
++ targetValue = if (screenshot != null) 1f else 0f,
++ animationSpec = tween(1000), label = "alpha"
++ )
++
++ // Lifecycle & QR Scan: When screenshot changes, reset state and scan for codes
+ LaunchedEffect(screenshot) {
+ if (screenshot != null) {
++ android.util.Log.d("CircleToSearch", "New Session - Screenshot: ${screenshot.width}x${screenshot.height}, Config: ${screenshot.config}")
++
++ // 1. Reset selection state
+ isCopyMode = false
+ selectionRect = null
+ selectedBitmap = null
+ isSearching = false
+ currentPathPoints.clear()
+ selectionAnim.snapTo(0f)
++
++ // 2. Perform QR scan in background
++ val found = withContext(Dispatchers.Default) {
++ QrScanner.scanBitmapAll(screenshot!!)
++ }
++ android.util.Log.d("CircleToSearch", "QR Scan finished - Found: ${found.size} codes")
++ detectedQrCodes = found
++ } else {
++ android.util.Log.d("CircleToSearch", "Session ended - Screenshot is null")
++ detectedQrCodes = emptyList()
+ }
+ }
+-
+- // searchEngines moved to top
+- // val searchEngines = SearchEngine.values()
+-
+- // Gradient Animation
+- val alphaAnim by animateFloatAsState(
+- targetValue = if (screenshot != null) 1f else 0f,
+- animationSpec = tween(1000), label = "alpha"
+- )
+
+ // Helper to create and configure WebView
+ fun createWebView(ctx: android.content.Context, engine: SearchEngine): WebView {
+@@ -1553,13 +1558,14 @@ fun CircleToSearchScreen(
+ ) {
+ val screenWidth = androidx.compose.ui.platform.LocalConfiguration.current.screenWidthDp.dp
+ val screenHeight = androidx.compose.ui.platform.LocalConfiguration.current.screenHeightDp.dp
++ val centerX = (leftDp + rightDp) / 2
+ Box(
+ modifier = Modifier
+ .offset(
+- x = ((leftDp + rightDp) / 2 - 90.dp).coerceIn(16.dp, screenWidth - 196.dp),
++ x = (centerX - 125.dp).coerceIn(0.dp, screenWidth - 250.dp),
+ y = if (topPx > 200f) (topDp - 72.dp).coerceAtLeast(16.dp) else (bottomDp + 16.dp).coerceAtMost(screenHeight - 80.dp)
+ )
+- .wrapContentSize(),
++ .width(250.dp),
+ contentAlignment = Alignment.Center
+ ) {
+ // Wrapped in Surface to match Bottom Bar tonal environment
+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 514d36a..e5b29fe 100644
+--- a/app/src/main/java/com/akslabs/circletosearch/ui/QrCodeResultSheet.kt
++++ b/app/src/main/java/com/akslabs/circletosearch/ui/QrCodeResultSheet.kt
+@@ -159,7 +159,7 @@ fun QrCodeResultSheet(
+ color = MaterialTheme.colorScheme.surfaceContainerHigh,
+ tonalElevation = 6.dp, shadowElevation = 12.dp
+ ) {
+- Column(modifier = Modifier.padding(20.dp), horizontalAlignment = Alignment.CenterHorizontally) {
++ Column(modifier = Modifier.padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally) {
+ // Header Row
+ Row(modifier = Modifier.padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
+ Icon(Icons.Default.QrCode, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp))
+@@ -182,7 +182,7 @@ fun QrCodeResultSheet(
+ }
+ }
+
+- Spacer(Modifier.height(16.dp))
++ Spacer(Modifier.height(20.dp))
+
+ if (isScanning) {
+ ScanningIndicator(scanlineY)
+@@ -200,7 +200,7 @@ fun QrCodeResultSheet(
+ }
+
+ if (results.size > 1) {
+- Spacer(Modifier.height(16.dp))
++ Spacer(Modifier.height(20.dp))
+ Row(
+ Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.Center,
+@@ -253,7 +253,7 @@ fun NotFoundContent() {
+
+ @Composable
+ fun QrResultContent(context: Context, result: QrResult) {
+- Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
++ Box(modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) {
+ when (result) {
+ is QrResult.Url -> UrlResult(context, result)
+ is QrResult.WiFi -> WifiResult(context, result)
+@@ -282,7 +282,7 @@ private fun UrlResult(context: Context, result: QrResult.Url) {
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.clickable { openUrl(context, result.url) }.padding(2.dp)
+ )
+- Spacer(Modifier.height(16.dp))
++ Spacer(Modifier.height(20.dp))
+ ActionRow { PrimaryAction("Open Link") { openUrl(context, result.url) }; SecondaryAction("Copy") { copyToClipboard(context, "URL", result.url) } }
+ }
+ }
+@@ -294,7 +294,7 @@ private fun WifiResult(context: Context, result: QrResult.WiFi) {
+ Spacer(Modifier.height(6.dp))
+ Text(result.ssid, style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold))
+ Text("${result.security}${if (result.password != null) " ┬╖ ${result.password}" else ""}", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
+- Spacer(Modifier.height(16.dp))
++ Spacer(Modifier.height(20.dp))
+ ActionRow { if (result.password != null) PrimaryAction("Copy Pass") { copyToClipboard(context, "WiFi Password", result.password) } }
+ }
+ }
+@@ -305,7 +305,7 @@ private fun PhoneResult(context: Context, result: QrResult.Phone) {
+ Icon(Icons.Default.Phone, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(40.dp))
+ Spacer(Modifier.height(6.dp))
+ Text(result.number, style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold))
+- Spacer(Modifier.height(16.dp))
++ Spacer(Modifier.height(20.dp))
+ ActionRow {
+ PrimaryAction("Call") { openUrl(context, "tel:${result.number}") }
+ SecondaryAction("SMS") { openUrl(context, "sms:${result.number}") }
+@@ -320,7 +320,7 @@ private fun ProductResult(context: Context, result: QrResult.Product) {
+ Icon(Icons.Default.ShoppingBag, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(40.dp))
+ Spacer(Modifier.height(6.dp))
+ Text(result.barcode, style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold))
+- Spacer(Modifier.height(16.dp))
++ Spacer(Modifier.height(20.dp))
+ ActionRow {
+ PrimaryAction("Amazon") { openUrl(context, "https://www.amazon.com/s?k=${result.barcode}") }
+ SecondaryAction("Google") { openUrl(context, "https://www.google.com/search?q=${result.barcode}") }
+@@ -336,7 +336,7 @@ private fun VCardResult(context: Context, result: QrResult.VCard) {
+ if (result.name != null) Text(result.name, style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold))
+ val sub = listOfNotNull(result.phone, result.email).joinToString(" ┬╖ ")
+ if (sub.isNotEmpty()) Text(sub, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
+- Spacer(Modifier.height(16.dp))
++ Spacer(Modifier.height(20.dp))
+ ActionRow {
+ PrimaryAction("Save") {
+ context.startActivity(Intent(Intent.ACTION_INSERT).apply {
+@@ -359,7 +359,7 @@ private fun GeoResult(context: Context, result: QrResult.GeoPoint) {
+ Icon(Icons.Default.LocationOn, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(40.dp))
+ Spacer(Modifier.height(6.dp))
+ Text(coord, style = MaterialTheme.typography.labelMedium.copy(fontWeight = FontWeight.Bold))
+- Spacer(Modifier.height(16.dp))
++ Spacer(Modifier.height(20.dp))
+ ActionRow {
+ PrimaryAction("Maps") { openUrl(context, "geo:${result.lat},${result.lng}?q=${result.lat},${result.lng}") }
+ SecondaryAction("Copy") { copyToClipboard(context, "Coordinates", coord) }
+@@ -379,7 +379,7 @@ private fun PlainTextResult(context: Context, result: QrResult.PlainText) {
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.padding(horizontal = 8.dp)
+ )
+- Spacer(Modifier.height(16.dp))
++ Spacer(Modifier.height(20.dp))
+ ActionRow {
+ PrimaryAction("Search") { openUrl(context, "https://www.google.com/search?q=${Uri.encode(result.text)}") }
+ SecondaryAction("Copy") { copyToClipboard(context, "Text", result.text) }
+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 2d7c7cd..194d060 100644
+--- a/app/src/main/java/com/akslabs/circletosearch/utils/QrScanner.kt
++++ b/app/src/main/java/com/akslabs/circletosearch/utils/QrScanner.kt
+@@ -53,18 +53,34 @@ object QrScanner {
+ return try {
+ val width = bitmap.width
+ val height = bitmap.height
++
++ android.util.Log.d("CircleToSearch", "Scanning bitmap: ${width}x${height}, config=${bitmap.config}")
++
+ val pixels = IntArray(width * height)
+ bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
++
++ // Debug: Check first 10 pixels
++ val first10 = pixels.take(10).joinToString { it.toUInt().toString(16) }
++ android.util.Log.d("CircleToSearch", "First 10 pixels: $first10")
+
+ val source = RGBLuminanceSource(width, height, pixels)
+- val binaryBitmap = BinaryBitmap(HybridBinarizer(source))
+-
+ val multiReader = GenericMultipleBarcodeReader(MultiFormatReader())
+- val rawResults: Array<Result> = try {
+- multiReader.decodeMultiple(binaryBitmap, HINTS)
+- } catch (e: NotFoundException) {
++
++ // Try 1: HybridBinarizer (Best for varying lighting)
++ var rawResults: Array<Result> = try {
++ multiReader.decodeMultiple(BinaryBitmap(HybridBinarizer(source)), HINTS)
++ } catch (e: Exception) {
+ emptyArray()
+ }
++
++ // Try 2: GlobalHistogramBinarizer (Fallback for low contrast or uniform background)
++ if (rawResults.isEmpty()) {
++ rawResults = try {
++ multiReader.decodeMultiple(BinaryBitmap(com.google.zxing.common.GlobalHistogramBinarizer(source)), HINTS)
++ } catch (e: Exception) {
++ emptyArray()
++ }
++ }
+
+ rawResults.mapNotNull { raw ->
+ try {
+@@ -73,6 +89,7 @@ object QrScanner {
+ } catch (e: Exception) { null }
+ }
+ } catch (e: Exception) {
++ android.util.Log.e("CircleToSearch", "QrScanner error", e)
+ emptyList()
+ }
+ }
+diff --git a/build_errors_52.txt b/build_errors_52.txt
+new file mode 100644
+index 0000000..b3649fe
+Binary files /dev/null and b/build_errors_52.txt differ
+diff --git a/builderors.md b/builderors.md
+index 8b13789..344cc30 100644
+--- a/builderors.md
++++ b/builderors.md
+@@ -1 +1,120 @@
+
++--------- beginning of main
++03-23 01:08:50.094 1450 1450 W main : type=1400 audit(0.0:316629): avc: denied { search } for name="app" dev="mmcblk0p61" ino=1343489 scontext=u:r:zygote:s0 tcontext=u:object_r:apk_data_file:s0 tclass=dir permissive=0 app=com.akslabs.circletosearch
++03-23 01:08:50.094 1450 1450 W main : type=1400 audit(0.0:316630): avc: denied { search } for name="app" dev="mmcblk0p61" ino=1343489 scontext=u:r:zygote:s0 tcontext=u:object_r:apk_data_file:s0 tclass=dir permissive=0 app=com.akslabs.circletosearch
++03-23 01:08:50.094 1450 1450 W main : type=1400 audit(0.0:316631): avc: denied { search } for name="app" dev="mmcblk0p61" ino=1343489 scontext=u:r:zygote:s0 tcontext=u:object_r:apk_data_file:s0 tclass=dir permissive=0 app=com.akslabs.circletosearch
++03-23 01:08:50.094 1450 1450 W main : type=1400 audit(0.0:316632): avc: denied { search } for name="app" dev="mmcblk0p61" ino=1343489 scontext=u:r:zygote:s0 tcontext=u:object_r:apk_data_file:s0 tclass=dir permissive=0 app=com.akslabs.circletosearch
++03-23 01:08:50.114 1450 1450 I .circletosearch: Late-enabling -Xcheck:jni
++03-23 01:08:50.211 1450 1450 I .circletosearch: Using CollectorTypeCC GC.
++03-23 01:08:50.305 1450 1450 D nativeloader: Load libframework-connectivity-tiramisu-jni.so using APEX ns com_android_tethering for caller /apex/com.android.tethering/javalib/framework-connectivity-t.jar: ok
++03-23 01:08:50.394 1450 1450 W re-initialized>: type=1400 audit(0.0:316633): avc: granted { execute } for path="/data/data/com.akslabs.circletosearch/code_cache/startup_agents/6097f3dc-agent.so" dev="mmcblk0p61" ino=417800 scontext=u:r:untrusted_app:s0:c167,c259,c512,c768 tcontext=u:object_r:app_data_file:s0:c167,c259,c512,c768 tclass=file app=com.akslabs.circletosearch
++03-23 01:08:50.429 1450 1450 D nativeloader: Load /data/user/0/com.akslabs.circletosearch/code_cache/startup_agents/6097f3dc-agent.so using system ns (caller=<unknown>): ok
++03-23 01:08:50.429 1450 1450 V studio.deploy: Startup agent attached to VM
++03-23 01:08:50.435 1450 1450 V studio.deploy: No existing instrumentation found. Loading instrumentation from instruments-6a1a1143.jar
++03-23 01:08:50.491 1450 1450 W .circletosearch: DexFile /data/data/com.akslabs.circletosearch/code_cache/.studio/instruments-6a1a1143.jar is in boot class path but is not in a known location
++03-23 01:08:50.689 1450 1450 V studio.deploy: Applying transforms with cached classes
++03-23 01:08:50.865 1450 1450 W .circletosearch: Redefining intrinsic method java.lang.Thread java.lang.Thread.currentThread(). This may cause the unexpected use of the original definition of java.lang.Thread java.lang.Thread.currentThread()in methods that have already been compiled.
++03-23 01:08:50.865 1450 1450 W .circletosearch: Redefining intrinsic method boolean java.lang.Thread.interrupted(). This may cause the unexpected use of the original definition of boolean java.lang.Thread.interrupted()in methods that have already been compiled.
++03-23 01:08:50.868 1450 1450 I studio.deploy: Registering DispatchJNI
++03-23 01:08:50.868 1450 1450 I studio.deploy: Found com/android/tools/deploy/interpreter/JNI
++03-23 01:08:51.025 1450 1450 W ziparchive: Unable to open '/data/data/com.akslabs.circletosearch/code_cache/.overlay/base.apk/classes.dm': No such file or directory
++03-23 01:08:51.192 1450 1450 W .circletosearch: ClassLoaderContext classpath size mismatch. expected=0, found=1 (PCL[] | PCL[/data/data/com.akslabs.circletosearch/code_cache/.overlay/base.apk/classes.dex*4268598632])
++03-23 01:08:51.198 1450 1450 D nativeloader: Configuring clns-7 for other apk /data/app/~~UXQwZLMrccRuoxuIEEn2ZA==/com.akslabs.circletosearch-yRdMISAYBcNVWRam0Tii2Q==/base.apk. target_sdk_version=36, uses_libraries=, library_path=/data/app/~~UXQwZLMrccRuoxuIEEn2ZA==/com.akslabs.circletosearch-yRdMISAYBcNVWRam0Tii2Q==/lib/arm64:/data/app/~~UXQwZLMrccRuoxuIEEn2ZA==/com.akslabs.circletosearch-yRdMISAYBcNVWRam0Tii2Q==/base.apk!/lib/arm64-v8a, permitted_path=/data:/mnt/expand:/data/user/0/com.akslabs.circletosearch
++03-23 01:08:51.206 1450 1450 I .circletosearch: AssetManager2(0x7318c278f8) locale list changing from [] to [en-IN]
++03-23 01:08:51.212 1450 1450 I .circletosearch: AssetManager2(0x7318c21818) locale list changing from [] to [en-IN]
++03-23 01:08:51.228 1450 1450 V GraphicsEnvironment: Currently set values for:
++03-23 01:08:51.228 1450 1450 V GraphicsEnvironment: angle_gl_driver_selection_pkgs=[com.android.angle, com.linecorp.b612.android, com.campmobile.snow, com.google.android.apps.tachyon]
++03-23 01:08:51.228 1450 1450 V GraphicsEnvironment: angle_gl_driver_selection_values=[angle, native, native, native]
++03-23 01:08:51.228 1450 1450 V GraphicsEnvironment: com.akslabs.circletosearch is not listed in per-application setting
++03-23 01:08:51.228 1450 1450 V GraphicsEnvironment: Neither updatable production driver nor prerelease driver is supported.
++03-23 01:08:51.343 1450 1450 I .circletosearch: AssetManager2(0x7318c1d358) locale list changing from [] to [en-IN]
++03-23 01:08:51.450 1450 1450 D DesktopModeFlagsUtil: Toggle override initialized to: OVERRIDE_UNSET
++03-23 01:08:51.975 1450 1450 W .circletosearch: Accessing hidden method Landroid/os/SystemProperties;->addChangeCallback(Ljava/lang/Runnable;)V (unsupported, reflection, allowed)
++03-23 01:08:52.470 1450 1450 W HWUI : Image decoding logging dropped!
++03-23 01:08:52.804 1450 1536 I AdrenoGLES-0: QUALCOMM build : 95db91f, Ifbc588260a
++03-23 01:08:52.804 1450 1536 I AdrenoGLES-0: Build Date : 09/24/20
++03-23 01:08:52.804 1450 1536 I AdrenoGLES-0: OpenGL ES Shader Compiler Version: EV031.32.02.01
++03-23 01:08:52.804 1450 1536 I AdrenoGLES-0: Local Branch : mybrancheafe5b6d-fb5b-f1b0-b904-5cb90179c3e0
++03-23 01:08:52.804 1450 1536 I AdrenoGLES-0: Remote Branch : quic/gfx-adreno.lnx.1.0.r114-rel
++03-23 01:08:52.804 1450 1536 I AdrenoGLES-0: Remote Branch : NONE
++03-23 01:08:52.804 1450 1536 I AdrenoGLES-0: Reconstruct Branch : NOTHING
++03-23 01:08:52.804 1450 1536 I AdrenoGLES-0: Build Config : S P 10.0.7 AArch64
++03-23 01:08:52.804 1450 1536 I AdrenoGLES-0: Driver Path : /vendor/lib64/egl/libGLESv2_adreno.so
++03-23 01:08:52.821 1450 1536 I AdrenoGLES-0: PFP: 0x016ee190, ME: 0x00000000
++03-23 01:08:52.930 1450 1559 I Gralloc4: mapper 4.x is not supported
++03-23 01:08:52.930 1450 1559 W Gralloc3: mapper 3.x is not supported
++03-23 01:08:52.939 1450 1559 I Gralloc2: Adding additional valid usage bits: 0x8202000
++03-23 01:08:53.026 1450 1469 I HWUI : Davey! duration=1697ms; Flags=1, FrameTimelineVsyncId=96236844, IntendedVsync=122869838241344, Vsync=122870121580361, InputEventId=0, HandleInputStart=122870134057033, AnimationStart=122870134068439, PerformTraversalsStart=122870134269064, DrawStart=122871435255522, FrameDeadline=122869859574676, FrameInterval=122870133683752, FrameStartTime=16667001, SyncQueued=122871489577241, SyncStart=122871489711043, IssueDrawCommandsStart=122871490430783, SwapBuffers=122871532341668, FrameCompleted=122871536251303, DequeueBufferDuration=14687, QueueBufferDuration=654480, GpuCompleted=122871536251303, SwapBuffersCompleted=122871534357866, DisplayPresentTime=0, CommandSubmissionCompleted=122871532341668,
++03-23 01:08:53.114 1450 1450 I Choreographer: Skipped 83 frames! The application may be doing too much work on its main thread.
++03-23 01:08:53.130 1450 1469 I HWUI : Davey! duration=1399ms; Flags=0, FrameTimelineVsyncId=96237256, IntendedVsync=122870257575722, Vsync=122871640984696, InputEventId=0, HandleInputStart=122871649082658, AnimationStart=122871649086147, PerformTraversalsStart=122871649087085, DrawStart=122871650298074, FrameDeadline=122871554942112, FrameInterval=122871648320210, FrameStartTime=16667578, SyncQueued=122871650961147, SyncStart=122871651172814, IssueDrawCommandsStart=122871651266251, SwapBuffers=122871653528960, FrameCompleted=122871657284220, DequeueBufferDuration=15573, QueueBufferDuration=259583, GpuCompleted=122871657284220, SwapBuffersCompleted=122871654519845, DisplayPresentTime=0, CommandSubmissionCompleted=122871653528960,
++03-23 01:08:53.306 1450 1466 I HWUI : Davey! duration=1563ms; Flags=1, FrameTimelineVsyncId=96237256, IntendedVsync=122870257575722, Vsync=122871640984696, InputEventId=0, HandleInputStart=122871649082658, AnimationStart=122871649086147, PerformTraversalsStart=122871649087085, DrawStart=122871801525105, FrameDeadline=122870274242388, FrameInterval=122871648320210, FrameStartTime=16667578, SyncQueued=122871812772553, SyncStart=122871812914949, IssueDrawCommandsStart=122871813002137, SwapBuffers=122871819126043, FrameCompleted=122871821033230, DequeueBufferDuration=12969, QueueBufferDuration=250677, GpuCompleted=122871821033230, SwapBuffersCompleted=122871819915574, DisplayPresentTime=0, CommandSubmissionCompleted=122871819126043,
++03-23 01:08:53.387 1450 1450 D InsetsController: hide(ime(), fromIme=false)
++03-23 01:08:53.387 1450 1450 I ImeTracker: com.akslabs.circletosearch:47e3d2e0: onCancelled at PHASE_CLIENT_ALREADY_HIDDEN
++03-23 01:08:54.659 1450 1450 W WindowOnBackDispatcher: sendCancelIfRunning: isInProgress=false callback=androidx.navigationevent.OnBackInvokedInput$createOnBackAnimationCallback$1@baca4b6
++03-23 01:08:54.683 1450 1536 D HWUI : endAllActiveAnimators on 0x7218c6d7c0 (UnprojectedRipple) with handle 0x72c8cad250
++03-23 01:08:54.733 1450 1450 D InsetsController: hide(ime(), fromIme=false)
++03-23 01:08:54.733 1450 1450 I ImeTracker: com.akslabs.circletosearch:8ea12879: onCancelled at PHASE_CLIENT_ALREADY_HIDDEN
++03-23 01:08:56.873 1450 1802 D ProfileInstaller: Installing profile for com.akslabs.circletosearch
++03-23 01:08:58.751 1450 1450 D VRI[MainActivity]: visibilityChanged oldVisibility=true newVisibility=false
++03-23 01:09:04.409 1450 1461 W .circletosearch: Cleared Reference was only reachable from finalizer (only reported once)
++03-23 01:09:04.429 1450 1461 I .circletosearch: Background concurrent copying GC freed 10056KB AllocSpace bytes, 7(140KB) LOS objects, 49% free, 5103KB/10206KB, paused 65us,22us total 102.452ms
++03-23 01:09:06.498 1450 1450 D CircleToSearch: performCapture called. hasWindowManager=true
++03-23 01:09:06.612 1450 2402 D CircleToSearchAccess: AccessibilityService launching OverlayActivity
++03-23 01:09:06.820 1450 1450 D CircleToSearch: OverlayActivity onCreate
++03-23 01:09:06.820 1450 1450 D CircleToSearch: Bitmap loaded from Repository. Size: 1080x2340
++03-23 01:09:07.889 1450 1571 I HWUI : Davey! duration=1033ms; Flags=1, FrameTimelineVsyncId=96256380, IntendedVsync=122885358073707, Vsync=122885391407653, InputEventId=0, HandleInputStart=122885399394579, AnimationStart=122885399396819, PerformTraversalsStart=122885399397757, DrawStart=122886312984319, FrameDeadline=122885374740373, FrameInterval=122885399385413, FrameStartTime=16666973, SyncQueued=122886331237444, SyncStart=122886331530360, IssueDrawCommandsStart=122886331688017, SwapBuffers=122886381614944, FrameCompleted=122886392183381, DequeueBufferDuration=13333, QueueBufferDuration=701823, GpuCompleted=122886392183381, SwapBuffersCompleted=122886383234944, DisplayPresentTime=122871839892814, CommandSubmissionCompleted=122886381614944,
++03-23 01:09:07.906 1450 1450 D CircleToSearch: QR Scan starting - Bitmap: 1080x2340
++03-23 01:09:07.932 1450 1450 I Choreographer: Skipped 63 frames! The application may be doing too much work on its main thread.
++03-23 01:09:08.012 1450 1450 W HWUI : Image decoding logging dropped!
++03-23 01:09:08.093 1450 1450 W HWUI : Image decoding logging dropped!
++03-23 01:09:08.479 1450 2429 I HWUI : Davey! duration=1596ms; Flags=0, FrameTimelineVsyncId=96256491, IntendedVsync=122885408072041, Vsync=122886458088631, InputEventId=0, HandleInputStart=122886466590152, AnimationStart=122886466593798, PerformTraversalsStart=122886799270204, DrawStart=122886939968121, FrameDeadline=122886424759672, FrameInterval=122886466186871, FrameStartTime=16666930, SyncQueued=122886990125620, SyncStart=122886990507860, IssueDrawCommandsStart=122886990867391, SwapBuffers=122886993833381, FrameCompleted=122887004494110, DequeueBufferDuration=23958, QueueBufferDuration=509531, GpuCompleted=122887004494110, SwapBuffersCompleted=122886995426193, DisplayPresentTime=122871906560626, CommandSubmissionCompleted=122886993833381,
++03-23 01:09:08.647 1450 1450 D InsetsController: hide(ime(), fromIme=false)
++03-23 01:09:08.647 1450 1450 I ImeTracker: com.akslabs.circletosearch:8121a967: onCancelled at PHASE_CLIENT_ALREADY_HIDDEN
++03-23 01:09:10.444 1450 1450 D CircleToSearch: QR Scan finished - Found: 0 codes
++03-23 01:09:19.411 1450 1450 D VRI[OverlayActivity]: visibilityChanged oldVisibility=true newVisibility=false
++03-23 01:09:19.439 1450 1450 W WindowOnBackDispatcher: sendCancelIfRunning: isInProgress=false callback=androidx.navigationevent.OnBackInvokedInput$createOnBackAnimationCallback$1@f22adfc
++03-23 01:09:19.561 1450 1450 W WindowOnBackDispatcher: sendCancelIfRunning: isInProgress=false callback=android.app.Activity$$ExternalSyntheticLambda0@56af219
++03-23 01:09:19.566 1450 1450 D ViewRootImpl: Skipping stats log for color mode
++03-23 01:09:50.001 1450 1450 D CircleToSearch: performCapture called. hasWindowManager=true
++03-23 01:09:50.059 1450 2402 D CircleToSearchAccess: AccessibilityService launching OverlayActivity
++03-23 01:09:50.226 1450 1450 D CircleToSearch: OverlayActivity onCreate
++03-23 01:09:50.226 1450 1450 D CircleToSearch: Bitmap loaded from Repository. Size: 1080x2340
++03-23 01:09:50.852 1450 1450 D CircleToSearch: QR Scan starting - Bitmap: 1080x2340
++03-23 01:09:50.865 1450 1450 I Choreographer: Skipped 35 frames! The application may be doing too much work on its main thread.
++03-23 01:09:50.913 1450 1450 W HWUI : Image decoding logging dropped!
++03-23 01:09:50.941 1450 1450 W HWUI : Image decoding logging dropped!
++03-23 01:09:51.245 1450 1466 I HWUI : Davey! duration=956ms; Flags=0, FrameTimelineVsyncId=96308265, IntendedVsync=122928808061365, Vsync=122929391387325, InputEventId=0, HandleInputStart=122929399749615, AnimationStart=122929399753208, PerformTraversalsStart=122929597769719, DrawStart=122929712644146, FrameDeadline=122929391378856, FrameInterval=122929399224615, FrameStartTime=16666456, SyncQueued=122929752165865, SyncStart=122929752234979, IssueDrawCommandsStart=122929752406125, SwapBuffers=122929753767063, FrameCompleted=122929764206542, DequeueBufferDuration=15730, QueueBufferDuration=532657, GpuCompleted=122929764206542, SwapBuffersCompleted=122929755043156, DisplayPresentTime=-69972189863528145, CommandSubmissionCompleted=122929753767063,
++03-23 01:09:51.266 1450 1450 D InsetsController: hide(ime(), fromIme=false)
++03-23 01:09:51.266 1450 1450 I ImeTracker: com.akslabs.circletosearch:89ad9691: onCancelled at PHASE_CLIENT_ALREADY_HIDDEN
++03-23 01:09:51.705 1450 1450 D CircleToSearch: QR Scan finished - Found: 0 codes
++03-23 01:10:07.779 1450 1450 D VRI[OverlayActivity]: visibilityChanged oldVisibility=true newVisibility=false
++03-23 01:10:07.812 1450 1450 W WindowOnBackDispatcher: sendCancelIfRunning: isInProgress=false callback=androidx.navigationevent.OnBackInvokedInput$createOnBackAnimationCallback$1@2665684
++03-23 01:10:07.945 1450 1450 W WindowOnBackDispatcher: sendCancelIfRunning: isInProgress=false callback=android.app.Activity$$ExternalSyntheticLambda0@78f1e62
++03-23 01:10:07.949 1450 1450 D ViewRootImpl: Skipping stats log for color mode
++03-23 01:10:10.795 1450 1450 D CircleToSearch: performCapture called. hasWindowManager=true
++03-23 01:10:10.864 1450 2402 D CircleToSearchAccess: AccessibilityService launching OverlayActivity
++03-23 01:10:11.105 1450 1450 D CircleToSearch: OverlayActivity onCreate
++03-23 01:10:11.105 1450 1450 D CircleToSearch: Bitmap loaded from Repository. Size: 1080x2340
++03-23 01:10:11.383 1450 1457 I .circletosearch: Compiler allocated 5163KB to compile void com.akslabs.circletosearch.ui.CircleToSearchScreenKt$CircleToSearchScreen$13$2.invoke(androidx.compose.foundation.layout.PaddingValues, androidx.compose.runtime.Composer, int)
++03-23 01:10:11.598 1450 1450 D CircleToSearch: QR Scan starting - Bitmap: 1080x2340
++03-23 01:10:11.688 1450 1450 W HWUI : Image decoding logging dropped!
++03-23 01:10:11.724 1450 1450 W HWUI : Image decoding logging dropped!
++03-23 01:10:11.785 1450 1535 I .circletosearch: Waiting for a blocking GC ProfileSaver
++03-23 01:10:11.803 1450 1461 I .circletosearch: Background concurrent copying GC freed 3776KB AllocSpace bytes, 13(31MB) LOS objects, 50% free, 19MB/39MB, paused 106us,49us total 199.866ms
++03-23 01:10:11.804 1450 1535 I .circletosearch: WaitForGcToComplete blocked ProfileSaver on Background for 18.859ms
++03-23 01:10:12.002 1450 1467 I HWUI : Davey! duration=850ms; Flags=0, FrameTimelineVsyncId=96334223, IntendedVsync=122949674733337, Vsync=122950158067028, InputEventId=0, HandleInputStart=122950172554451, AnimationStart=122950172558096, PerformTraversalsStart=122950375630492, DrawStart=122950469565128, FrameDeadline=122950108060013, FrameInterval=122950172148617, FrameStartTime=16666679, SyncQueued=122950512905648, SyncStart=122950512985596, IssueDrawCommandsStart=122950513161430, SwapBuffers=122950514883669, FrameCompleted=122950525548617, DequeueBufferDuration=15729, QueueBufferDuration=1063177, GpuCompleted=122950525548617, SwapBuffersCompleted=122950516516742, DisplayPresentTime=0, CommandSubmissionCompleted=122950514883669,
++03-23 01:10:12.028 1450 1450 D InsetsController: hide(ime(), fromIme=false)
++03-23 01:10:12.028 1450 1450 I ImeTracker: com.akslabs.circletosearch:b7697256: onCancelled at PHASE_CLIENT_ALREADY_HIDDEN
++03-23 01:10:12.421 1450 1450 D CircleToSearch: QR Scan finished - Found: 0 codes
++03-23 01:10:21.749 1450 2425 D TesseractEngine: Initializing Tesseract with dataPath=/data/user/0/com.akslabs.circletosearch/files
++03-23 01:10:21.764 1450 2425 D nativeloader: Load /data/app/~~UXQwZLMrccRuoxuIEEn2ZA==/com.akslabs.circletosearch-yRdMISAYBcNVWRam0Tii2Q==/lib/arm64/libjpeg.so using class loader ns clns-7 (caller=/data/data/com.akslabs.circletosearch/code_cache/.overlay/base.apk/classes.dex): ok
++03-23 01:10:21.770 1450 2425 D nativeloader: Load /data/app/~~UXQwZLMrccRuoxuIEEn2ZA==/com.akslabs.circletosearch-yRdMISAYBcNVWRam0Tii2Q==/lib/arm64/libpngx.so using class loader ns clns-7 (caller=/data/data/com.akslabs.circletosearch/code_cache/.overlay/base.apk/classes.dex): ok
++03-23 01:10:21.782 1450 2425 D nativeloader: Load /data/app/~~UXQwZLMrccRuoxuIEEn2ZA==/com.akslabs.circletosearch-yRdMISAYBcNVWRam0Tii2Q==/lib/arm64/libleptonica.so using class loader ns clns-7 (caller=/data/data/com.akslabs.circletosearch/code_cache/.overlay/base.apk/classes.dex): ok
++03-23 01:10:21.835 1450 2425 D nativeloader: Load /data/app/~~UXQwZLMrccRuoxuIEEn2ZA==/com.akslabs.circletosearch-yRdMISAYBcNVWRam0Tii2Q==/lib/arm64/libtesseract.so using class loader ns clns-7 (caller=/data/data/com.akslabs.circletosearch/code_cache/.overlay/base.apk/classes.dex): ok
++03-23 01:10:22.254 1450 2425 I Tesseract(native): Initialized Tesseract API with language=eng
++03-23 01:10:22.258 1450 2425 W .circletosearch: Accessing hidden field Landroid/graphics/Bitmap;->mNativePtr:J (unsupported, JNI, allowed)
++03-23 01:10:24.934 1450 2425 D TesseractEngine: Tesseract recognition complete. Full text length: 1070
++03-23 01:10:25.017 1450 2425 D TesseractEngine: Tesseract successfully extracted 59 text nodes.
++03-23 01:10:25.022 1450 1450 D CopyTextOverlay: OCR complete: 59 nodes, 255 words
++03-23 01:10:27.089 1450 1450 W HWUI : Image decoding logging dropped!
++03-23 01:10:27.105 1450 1450 W HWUI : Image decoding logging dropped!